7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
16 * ly-options: intertext ?
18 * eps in latex / eps by lilypond -fps ?
19 * check latex parameters, twocolumn, multicolumn?
21 * Converting from lilypond-book source, substitute:
22 @mbinclude foo.itely -> @include foo.itely
35 # * should have a sane default --process setting
37 # * use --png --ps --pdf for making images?
40 ################################################################
41 # Users of python modules should include this snippet
42 # and customize variables below.
44 # We'll suffer this path init stuff as long as we don't install our
45 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
46 # it as we do with teTeX on Red Hat Linux: set some environment var
47 # (PYTHONPATH) in profile)
49 # If set, LILYPONDPREFIX must take prevalence
50 # if datadir is not set, we're doing a build and LILYPONDPREFIX
51 import getopt
, os
, sys
52 datadir
= '@local_lilypond_datadir@'
53 if not os
.path
.isdir (datadir
):
54 datadir
= '@lilypond_datadir@'
55 if os
.environ
.has_key ('LILYPONDPREFIX') :
56 datadir
= os
.environ
['LILYPONDPREFIX']
57 while datadir
[-1] == os
.sep
:
60 sys
.path
.insert (0, os
.path
.join (datadir
, 'python'))
63 #if __name__ == '__main__':
71 program_version
= '@TOPLEVEL_VERSION@'
72 program_name
= 'lilypond-book'
75 original_dir
= os
.getcwd ()
78 help_summary
= _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.
81 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
82 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
83 lilypond-book --process='lilypond -I include' BOOK
87 copyright
= ('Jan Nieuwenhuizen <janneke@gnu.org>',
88 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
90 option_definitions
= [
91 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
92 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
93 ('', 'h', 'help', _ ("print this help")),
94 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
95 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
96 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
97 ('', 'V', 'verbose', _ ("be verbose")),
98 ('', 'v', 'version', _ ("print version information")),
99 ('', 'w', 'warranty', _ ("show warranty and copyright")),
102 include_path
= [ly
.abspath (os
.getcwd ())]
103 lilypond_binary
= os
.path
.join ('@bindir@', 'lilypond')
105 # only use installed binary when we're installed too.
106 if '@bindir@' == ('@' + 'bindir@') or not os
.path
.exists (lilypond_binary
):
107 lilypond_binary
= 'lilypond'
113 latex_filter_cmd
= 'latex "\\nonstopmode \input /dev/stdin"'
115 process_cmd
= lilypond_binary
116 default_ly_options
= {}
119 # is this pythonic? Personally, I find this rather #define-nesque. --hwn
123 BOOKPAPER
= 'bookpaper'
124 EXAMPLEINDENT
= 'exampleindent'
126 FRAGMENT
= 'fragment'
130 LINEWIDTH
= 'linewidth'
131 NOFRAGMENT
= 'nofragment'
132 NOINDENT
= 'noindent'
137 PREAMBLE
= 'preamble'
138 PRINTFILENAME
= 'printfilename'
140 RAGGEDRIGHT
= 'raggedright'
141 RELATIVE
= 'relative'
142 STAFFSIZE
= 'staffsize'
145 VERBATIM
= 'verbatim'
147 # Recognize special sequences in the input
149 # (?P<name>regex) -- assign result of REGEX to NAME
150 # *? -- match non-greedily.
151 # (?m) -- multiline regex: make ^ and $ match at each line
152 # (?s) -- make the dot match all characters including newline
157 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
158 'lilypond_block': r
'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
159 'lilypond_file': r
'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
160 'multiline_comment': r
"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
161 'singleline_comment': no_match
,
162 'verb': r
'''(?P<code><pre>.*?</pre>)''',
163 'verbatim': r
'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
167 'include': r
'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
168 'lilypond' : r
'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
169 'lilypond_block': r
"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
170 'lilypond_file': r
'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
171 'multiline_comment': no_match
,
172 'singleline_comment': r
"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
173 'verb': r
"(?P<code>\\verb(?P<del>.).*?(?P=del))",
174 'verbatim': r
"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
178 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S+))',
179 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
180 'lilypond_block': r
'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
181 'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
182 'multiline_comment': r
'(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end\s+ignore)\s',
183 'singleline_comment': r
'(?m)^.*(?P<match>(?P<code>@c([ \t][^\n]*|)\n))',
185 # don't do this: fucks up with @code{@{}
186 # 'verb': r'''(?P<code>@code{.*?})''',
187 'verbatim': r
'''(?s)(?P<code>@example\s.*?@end\s+example\s)''',
193 'option-sep' : '\s*',
194 'intertext': r
',?\s*intertext=\".*?\"',
197 'intertext': r
',?\s*intertext=\".*?\"',
198 'option-sep' : ',\s*',
201 'intertext': r
',?\s*intertext=\".*?\"',
202 'option-sep' : ',\s*',
208 RELATIVE
: r
'''\relative c%(relative_quotes)s''',
212 indent = %(indent)s''',
214 linewidth = %(linewidth)s''',
218 linewidth = %(linewidth)s - 2.0 * %(exampleindent)s
222 raggedright = ##t''',
232 \remove Time_signature_engraver
239 #(set-global-staff-size %(staffsize)s)''',
245 FILTER
: r
'''<lilypond %(options)s>
255 <a href="%(base)s.ly">''',
257 <img align="center" valign="center"
258 border="0" src="%(image)s" alt="[image of music]">''',
259 PRINTFILENAME
:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
260 QUOTE
: r
'''<blockquote>
271 OUTPUT
: r
'''{\parindent 0pt
273 \ifx\preLilyPondExample\undefined\relax\else\preLilyPondExample\fi
276 \ifx\postLilyPondExample\undefined\relax\else\postLilyPondExample\fi
278 PRINTFILENAME
: '''\\texttt{%(filename)s}
281 QUOTE
: r
'''\begin{quotation}
285 VERBATIM
: r
'''\noindent
287 %(verb)s\end{verbatim}
289 FILTER
: r
'''\begin{lilypond}[%(options)s]
295 FILTER
: r
'''@lilypond[%(options)s]
300 OUTPUT
: r
'''@noindent
301 @image{%(base)s,,,[image of music],%(ext)s}
303 PRINTFILENAME
: '''@file{%(filename)s}
306 QUOTE
: r
'''@quotation
310 # FIXME: @exampleindent 5 is the default...
311 VERBATIM
: r
'''@exampleindent 0
319 PREAMBLE_LY
= r
'''%%%% Generated by %(program_name)s
320 %%%% Options: [%(option_string)s]
321 #(set! toplevel-score-handler ly:parser-print-score)
322 #(set! toplevel-music-handler (lambda (p m)
323 (ly:parser-print-score
324 p (ly:music-scorify m))
327 \bookpaper {%(bookpaper_string)s
329 \paper { %(paper_string)s
340 texinfo_linewidths
= {
341 '@afourpaper': '160 \\mm',
342 '@afourwide': '6.5 \\in',
343 '@afourlatex': '150 \\mm',
344 '@smallbook': '5 \\in' ,
345 '@letterpaper': '6\\in',
348 def classic_lilypond_book_compatibility (o
):
349 if o
== 'singleline':
351 m
= re
.search ('relative\s*([-0-9])', o
)
353 return 'relative=%s' % m
.group (1)
354 m
= re
.match ('([0-9]+)pt', o
)
356 return 'staffsize=%s' % m
.group (1)
357 m
= re
.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o
)
359 f
= float (m
.group (1))
360 return 'indent=%f\\%s' % (f
, m
.group (2))
361 m
= re
.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o
)
363 f
= float (m
.group (1))
364 return 'linewidth=%f\\%s' % (f
, m
.group (2))
367 def compose_ly (code
, options
):
369 for i
in default_ly_options
.keys ():
374 if QUOTE
in options
and LINEWIDTH
in options
:
375 options
.remove (LINEWIDTH
)
377 if FRAGMENT
in options
:
378 if RAGGEDRIGHT
not in options
:
379 options
.append (RAGGEDRIGHT
)
388 override
.update (default_ly_options
)
389 #FIXME: where to get sane value for exampleindent?
390 override
[EXAMPLEINDENT
] = r
'9.0 \mm'
392 option_string
= string
.join (options
, ',')
395 option_types
= [NOTES
, PREAMBLE
, PAPER
, BOOKPAPER
]
396 for a
in option_types
:
400 c
= classic_lilypond_book_compatibility (i
)
402 ly
.warning (_ ("deprecated ly-option used: %s" % i
))
403 ly
.warning (_ ("compatibility mode translation: %s" \
407 if string
.find (i
, '=') > 0:
408 key
, value
= string
.split (i
, '=')
409 override
[key
] = value
412 if not override
.has_key (i
):
416 for type in option_types
:
417 if ly_options
[type].has_key (key
):
419 options_dict
[type].append (ly_options
[type][key
])
423 if not found
and key
not in (FRAGMENT
, NOFRAGMENT
, PRINTFILENAME
,
424 RELATIVE
, VERBATIM
, TEXIDOC
):
425 ly
.warning (_("ignoring unknown ly option: %s") % i
)
428 if RELATIVE
in override
.keys () and override
[RELATIVE
]:
429 relative
= string
.atoi (override
[RELATIVE
])
435 relative_quotes
+= ',' * (- relative
)
437 relative_quotes
+= "'" * relative
439 program_name
= __main__
.program_name
441 paper_string
= string
.join (options_dict
[PAPER
], '\n ') % override
442 bookpaper_string
= string
.join (options_dict
[BOOKPAPER
], '\n ') % override
443 notes_string
= string
.join (options_dict
[NOTES
], '\n ') % vars ()
444 preamble_string
= string
.join (options_dict
[PREAMBLE
], '\n ') % override
445 return (PREAMBLE_LY
+ body
) % vars ()
449 # use lilypond for latex (.lytex) books,
450 # and lilypond --preview for html, texinfo books?
452 cmd
= r
'latex "\nonstopmode \input %s"' % file
453 # Ugh. (La)TeX writes progress and error messages on stdout
455 cmd
= '(( %s >&2 ) >&- )' % cmd
457 ly
.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
461 # check if it really is EPS.
462 # Otherwise music glyphs disappear from 2nd and following pages.
464 # TODO: should run dvips -pp -E per page, then we get proper
467 f
= open ('%s.eps' % file)
468 for x
in range(0,10) :
469 if re
.search ("^%%Pages: ", f
.readline ()):
472 ly
.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
477 def find_file (name
):
478 for i
in include_path
:
479 full
= os
.path
.join (i
, name
)
480 if os
.path
.exists (full
):
482 ly
.error (_ ('file not found: %s') % name
+ '\n')
486 def verbatim_html (s
):
487 return re
.sub ('>', '>',
489 re
.sub ('&', '&', s
)))
491 def verbatim_texinfo (s
):
492 return re
.sub ('{', '@{',
494 re
.sub ('@', '@@', s
)))
496 def split_options (option_string
):
497 return re
.split (format_res
[format
]['option-sep'], option_string
)
501 def replacement_text (self
):
504 def filter_text (self
):
505 return self
.replacement_text ()
508 def is_outdated (self
):
511 class Substring (Chunk
):
512 def __init__ (self
, source
, start
, end
):
517 def replacement_text (self
):
518 return self
.source
[self
.start
:self
.end
]
520 class Snippet (Chunk
):
521 def __init__ (self
, type, match
, format
):
528 def replacement_text (self
):
529 return self
.match
.group (0)
531 def substring (self
, s
):
532 return self
.match
.group (s
)
535 return `self
.__class
__`
+ " type = " + self
.type
537 class Include_snippet (Snippet
):
538 def processed_filename (self
):
539 f
= self
.substring ('filename')
540 return os
.path
.splitext (f
)[0] + format2ext
[format
]
542 def replacement_text (self
):
543 s
= self
.match
.group (0)
544 f
= self
.substring ('filename')
546 return re
.sub (f
, self
.processed_filename (), s
)
548 class Lilypond_snippet (Snippet
):
549 def __init__ (self
, type, match
, format
):
550 Snippet
.__init
__ (self
, type, match
, format
)
551 os
= match
.group ('options')
553 self
.options
= split_options (os
)
556 return self
.substring ('code')
561 return compose_ly (s
, self
.options
)
567 self
.hash = abs (hash (self
.full_ly ()))
572 return 'lily-%d' % self
.get_hash ()
576 outf
= open (self
.basename () + '.ly', 'w')
577 outf
.write (self
.full_ly ())
579 open (self
.basename() + '.txt', 'w').write("image of music")
582 def is_outdated (self
):
583 base
= self
.basename ()
585 tex_file
= '%s.tex' % base
586 ly_file
= '%s.ly' % base
587 ok
= os
.path
.exists (ly_file
) and os
.path
.exists (tex_file
)\
588 and os
.stat (tex_file
)[stat
.ST_SIZE
] \
589 and open (tex_file
).readlines ()[-1][1:-1] \
592 if format
== HTML
or format
== TEXINFO
:
593 ok
= ok
and (os
.path
.exists (base
+ '.png')
594 or glob
.glob (base
+ '-page*.png'))
596 if ok
and (use_hash_p
or self
.ly () == open (ly_file
).read ()):
597 # TODO: something smart with target formats
598 # (ps, png) and m/ctimes
602 def filter_text (self
):
603 code
= self
.substring ('code')
604 s
= run_filter (code
)
606 'options': self
.match
.group ('options')
609 return output
[self
.format
][FILTER
] % d
611 def replacement_text (self
):
612 func
= Lilypond_snippet
.__dict
__ ['output_' + self
.format
]
615 def get_images (self
):
616 base
= self
.basename ()
618 single
= '%(base)s.png' % vars ()
619 multiple
= '%(base)s-page1.png' % vars ()
621 if os
.path
.exists (multiple
) \
622 and (not os
.path
.exists (single
)\
623 or (os
.stat (multiple
)[stat
.ST_MTIME
] \
624 > os
.stat (single
)[stat
.ST_MTIME
])):
625 images
= glob
.glob ('%(base)s-page*.png' % vars ())
628 def output_html (self
):
630 base
= self
.basename ()
632 str += self
.output_print_filename (HTML
)
633 if VERBATIM
in self
.options
:
634 verb
= verbatim_html (self
.substring ('code'))
635 str += write (output
[HTML
][VERBATIM
] % vars ())
636 if QUOTE
in self
.options
:
637 str = output
[HTML
][QUOTE
] % vars ()
639 str += output
[HTML
][BEFORE
] % vars ()
640 for image
in self
.get_images ():
641 base
, ext
= os
.path
.splitext (image
)
642 str += output
[HTML
][OUTPUT
] % vars ()
643 str += output
[HTML
][AFTER
] % vars ()
646 def output_info (self
):
647 str = self
.output_print_filename (HTML
)
648 str = output
[TEXINFO
][BEFORE
] % vars ()
649 for image
in self
.get_images ():
650 base
, ext
= os
.path
.splitext (image
)
652 # URG, makeinfo implicitely prepends dot to ext
653 # specifying no extension is most robust
655 str += output
[TEXINFO
][OUTPUT
] % vars ()
656 str += output
[TEXINFO
][AFTER
] % vars ()
659 def output_latex (self
):
661 base
= self
.basename ()
663 str += self
.output_print_filename (LATEX
)
664 if VERBATIM
in self
.options
:
665 verb
= self
.substring ('code')
666 str += (output
[LATEX
][VERBATIM
] % vars ())
667 if QUOTE
in self
.options
:
668 str = output
[LATEX
][QUOTE
] % vars ()
670 str += (output
[LATEX
][BEFORE
]
671 + (output
[LATEX
][OUTPUT
] % vars ())
672 + output
[LATEX
][AFTER
])
675 def output_print_filename (self
,format
):
677 if PRINTFILENAME
in self
.options
:
678 base
= self
.basename ()
679 filename
= self
.substring ('filename')
680 str = output
[format
][PRINTFILENAME
] % vars ()
683 def output_texinfo (self
):
685 # self.output_print_filename (TEXINFO)
686 str += ('@html\n' + self
.output_print_filename (HTML
)
688 str += ('@tex\n' + self
.output_print_filename (LATEX
)
690 base
= self
.basename ()
691 if TEXIDOC
in self
.options
:
692 texidoc
= base
+ '.texidoc'
693 if os
.path
.exists (texidoc
):
694 str += '@include %(texidoc)s\n\n' % vars ()
696 if VERBATIM
in self
.options
:
697 verb
= verbatim_texinfo (self
.substring ('code'))
698 str += (output
[TEXINFO
][VERBATIM
] % vars ())
700 str += ('@ifinfo\n' + self
.output_info () + '\n@end ifinfo\n')
701 str += ('@tex\n' + self
.output_latex () + '\n@end tex\n')
702 str += ('@html\n' + self
.output_html () + '\n@end html\n')
704 if QUOTE
in self
.options
:
705 str = output
[TEXINFO
][QUOTE
] % vars ()
707 # need par after image
712 class Lilypond_file_snippet (Lilypond_snippet
):
714 name
= self
.substring ('filename')
715 contents
= open (find_file (name
)).read ()
716 checksum
= abs (hash (contents
))
717 width
= default_ly_options
[LINEWIDTH
]
719 %% hash of included file: %(checksum)d
726 snippet_type_to_class
= {
727 'lilypond_file' : Lilypond_file_snippet
,
728 'lilypond_block' : Lilypond_snippet
,
729 'lilypond' : Lilypond_snippet
,
730 'include' : Include_snippet
,
733 def find_toplevel_snippets (s
, types
):
736 res
[i
] = ly
.re
.compile (snippet_res
[format
][i
])
740 ## found = dict (map (lambda x: (x, None), types))
743 map (lambda x
, f
=found
: f
.setdefault (x
, None), types
)
745 # We want to search for multiple regexes, without searching
746 # the string multiple times for one regex.
747 # Hence, we use earlier results to limit the string portion
749 # Since every part of the string is traversed at most once for
750 # every type of snippet, this is linear.
756 if not found
[type] or found
[type][0] < index
:
758 m
= res
[type].search (s
[index
:endex
])
763 if snippet_type_to_class
.has_key (type):
764 cl
= snippet_type_to_class
[type]
765 snip
= cl (type, m
, format
)
766 start
= index
+ m
.start (0)
767 found
[type] = (start
, snip
)
770 and (not first
or found
[type][0] < found
[first
][0]):
775 # Limiting the search space is a cute
776 # idea, but this *requires* to search
777 # for possible containing blocks
778 # first, at least long as we do not
779 # search for the start of blocks, but
780 # always/directly for the entire
781 # @block ... @end block.
783 endex
= found
[first
][0]
786 snippets
.append (Substring (s
, index
, len (s
)))
789 (start
, snip
) = found
[first
]
790 snippets
.append (Substring (s
, index
, start
))
791 snippets
.append (snip
)
793 index
= start
+ len (snip
.match
.group (0))
797 def filter_pipe (input, cmd
):
799 ly
.progress (_ ("Opening filter `%s\'") % cmd
)
801 stdin
, stdout
, stderr
= os
.popen3 (cmd
)
803 status
= stdin
.close ()
807 output
= stdout
.read ()
808 status
= stdout
.close ()
809 error
= stderr
.read ()
813 signal
= 0x0f & status
814 if status
or (not output
and error
):
815 exit_status
= status
>> 8
816 ly
.error (_ ("`%s\' failed (%d)") % (cmd
, exit_status
))
817 ly
.error (_ ("The error log is as follows:"))
818 sys
.stderr
.write (error
)
819 sys
.stderr
.write (stderr
.read ())
828 return filter_pipe (s
, filter_cmd
)
830 def is_derived_class (cl
, baseclass
):
833 for b
in cl
.__bases
__:
834 if is_derived_class (b
, baseclass
):
839 def process_snippets (cmd
, snippets
):
840 names
= filter (lambda x
: x
, map (Lilypond_snippet
.basename
, snippets
))
842 ly
.system (string
.join ([cmd
] + names
))
844 if format
== HTML
or format
== TEXINFO
:
846 if not os
.path
.exists (i
+ '.eps') and os
.path
.exists (i
+ '.tex'):
848 ly
.make_ps_images (i
+ '.eps', resolution
=110)
850 # elif os.path.exists (i + '.ps'):
851 # ly.make_ps_images (i + '.ps', resolution=110)
854 LATEX_DOCUMENT
= r
'''
857 \typeout{textwidth=\the\textwidth}
858 \typeout{columnsep=\the\columnsep}
859 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
862 #need anything else besides textwidth?
863 def get_latex_textwidth (source
):
864 m
= re
.search (r
'''(?P<preamble>\\begin\s*{document})''', source
)
865 preamble
= source
[:m
.start (0)]
866 latex_document
= LATEX_DOCUMENT
% vars ()
867 parameter_string
= filter_pipe (latex_document
, latex_filter_cmd
)
870 m
= re
.search ('columns=([0-9.]*)', parameter_string
)
872 columns
= string
.atoi (m
.group (1))
875 m
= re
.search ('columnsep=([0-9.]*)pt', parameter_string
)
877 columnsep
= string
.atof (m
.group (1))
880 m
= re
.search('textwidth=([0-9.]*)pt', parameter_string
)
882 textwidth
= string
.atof (m
.group (1))
884 textwidth
= (textwidth
- columnsep
) / columns
895 '.texinfo' : TEXINFO
,
901 #TEXINFO: '.texinfo',
906 def do_file (input_filename
):
910 e
= os
.path
.splitext (input_filename
)[1]
911 if e
in ext2format
.keys ():
913 format
= ext2format
[e
]
915 ly
.error (_ ("cannot determine format for: %s" \
918 if not input_filename
or input_filename
== '-':
919 in_handle
= sys
.stdin
920 input_fullname
= '<stdin>'
922 if os
.path
.exists (input_filename
):
923 input_fullname
= input_filename
924 elif format
== LATEX
:
925 # urg python interface to libkpathsea?
926 input_fullname
= ly
.read_pipe ('kpsewhich '
927 + input_filename
)[:-1]
929 input_fullname
= find_file (input_filename
)
930 in_handle
= open (input_fullname
)
932 if input_filename
== '-':
935 input_base
= os
.path
.basename \
936 (os
.path
.splitext (input_filename
)[0])
938 # only default to stdout when filtering
939 if output_name
== '-' or (not output_name
and filter_cmd
):
940 output_filename
= '-'
941 output_file
= sys
.stdout
944 output_filename
= input_base
+ format2ext
[format
]
946 if not os
.path
.isdir (output_name
):
947 os
.mkdir (output_name
, 0777)
948 output_filename
= (output_name
950 + format2ext
[format
])
953 if (os
.path
.exists (input_filename
) and
954 os
.path
.exists (output_filename
) and
955 os
.path
.samefile (output_filename
, input_fullname
)):
956 ly
.error (_("Output would overwrite input file; use --output."))
959 output_file
= open (output_filename
, 'w')
961 os
.chdir (output_name
)
963 ly
.progress (_ ("Reading %s...") % input_fullname
)
964 source
= in_handle
.read ()
967 # FIXME: containing blocks must be first, see find_toplevel_snippets
973 'singleline_comment',
977 ly
.progress (_ ("Dissecting..."))
978 chunks
= find_toplevel_snippets (source
, snippet_types
)
981 global default_ly_options
983 if not default_ly_options
.has_key (LINEWIDTH
):
985 textwidth
= get_latex_textwidth (source
)
986 default_ly_options
[LINEWIDTH
] = '''%.0f\\pt''' \
988 elif format
== TEXINFO
:
989 for (k
, v
) in texinfo_linewidths
.items ():
990 # FIXME: @paper is usually not in chunk #0:
991 # \input texinfo @c -*-texinfo-*-
992 # bluntly search first K of source
993 # s = chunks[0].replacement_text ()
994 if re
.search (k
, source
[:1024]):
995 default_ly_options
[LINEWIDTH
] = v
999 output_file
.writelines ([c
.filter_text () for c
in chunks
])
1003 outdated
= filter (lambda x
: is_derived_class (x
.__class
__, Lilypond_snippet
) \
1004 and x
.is_outdated (), chunks
)
1005 ly
.progress (_ ("Writing snippets..."))
1006 map (Lilypond_snippet
.write_ly
, outdated
)
1010 ly
.progress (_ ("Processing..."))
1011 process_snippets (process_cmd
, outdated
)
1013 ly
.progress (_ ("All snippets are up to date..."))
1016 ly
.progress (_ ("Compiling %s...") % output_filename
)
1017 output_file
.writelines ([s
.replacement_text () \
1021 def process_include (snippet
):
1022 os
.chdir (original_dir
)
1023 name
= snippet
.substring ('filename')
1024 ly
.progress (_ ('Processing include: %s') % name
)
1028 map (process_include
,
1029 filter (lambda x
: is_derived_class (x
.__class
__, Include_snippet
), chunks
))
1032 global format
, output_name
1033 global filter_cmd
, process_cmd
, verbose_p
1035 (sh
, long) = ly
.getopt_args (option_definitions
)
1037 (options
, files
) = getopt
.getopt (sys
.argv
[1:], sh
, long)
1038 except getopt
.error
, s
:
1039 sys
.stderr
.write ('\n')
1040 ly
.error (_ ("getopt says: `%s\'" % s
))
1041 sys
.stderr
.write ('\n')
1051 elif o
== '--filter' or o
== '-F':
1054 elif o
== '--format' or o
== '-f':
1056 if a
== 'texi-html' or a
== 'texi':
1058 elif o
== '--help' or o
== '-h':
1061 elif o
== '--include' or o
== '-I':
1062 include_path
.append (os
.path
.join (original_dir
,
1064 elif o
== '--output' or o
== '-o':
1066 elif o
== '--outdir':
1068 elif o
== '--process' or o
== '-P':
1071 elif o
== '--version' or o
== '-v':
1072 ly
.identify (sys
.stdout
)
1074 elif o
== '--verbose' or o
== '-V':
1076 elif o
== '--warranty' or o
== '-w':
1083 files
= do_options ()
1086 process_cmd
+= string
.join ([(' -I %s' % p
)
1087 for p
in include_path
])
1089 ly
.identify (sys
.stderr
)
1090 ly
.setup_environment ()
1094 if __name__
== '__main__':