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 # * use --png --ps --pdf for making images?
38 ################################################################
39 # Users of python modules should include this snippet
40 # and customize variables below.
42 # We'll suffer this path init stuff as long as we don't install our
43 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
44 # it as we do with teTeX on Red Hat Linux: set some environment var
45 # (PYTHONPATH) in profile)
47 # If set, LILYPONDPREFIX must take prevalence
48 # if datadir is not set, we're doing a build and LILYPONDPREFIX
49 import getopt, os, sys
50 datadir = '@local_lilypond_datadir@'
51 if not os.path.isdir (datadir):
52 datadir = '@lilypond_datadir@'
53 if os.environ.has_key ('LILYPONDPREFIX'):
54 datadir = os.environ['LILYPONDPREFIX']
55 while datadir[-1] == os.sep:
58 sys.path.insert (0, os.path.join (datadir, 'python'))
61 #if __name__ == '__main__':
68 program_version = '@TOPLEVEL_VERSION@'
69 program_name = sys.argv[0]
72 original_dir = os.getcwd ()
74 help_summary = _ ('''Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.
77 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
78 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
79 lilypond-book --process='lilypond -I include' BOOK
83 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
84 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
86 option_definitions = [
87 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
88 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
89 ('', 'h', 'help', _ ("print this help")),
90 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
91 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
92 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
93 ('', 'V', 'verbose', _ ("be verbose")),
94 ('', 'v', 'version', _ ("print version information")),
95 ('', 'w', 'warranty', _ ("show warranty and copyright")),
98 include_path = [ly.abspath (os.getcwd ())]
99 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
101 # only use installed binary when we're installed too.
102 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
103 lilypond_binary = 'lilypond'
108 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
111 default_ly_options = {}
114 # is this pythonic? Personally, I find this rather #define-nesque. --hwn
118 EXAMPLEINDENT = 'exampleindent'
120 FRAGMENT = 'fragment'
125 LINEWIDTH = 'linewidth'
126 NOFRAGMENT = 'nofragment'
127 NOINDENT = 'noindent'
132 PREAMBLE = 'preamble'
133 PRINTFILENAME = 'printfilename'
135 RAGGEDRIGHT = 'raggedright'
136 RELATIVE = 'relative'
137 STAFFSIZE = 'staffsize'
140 VERBATIM = 'verbatim'
142 # NOTIME has no opposite so it isn't part of this dictionary
144 NOFRAGMENT: FRAGMENT,
148 # Recognize special sequences in the input;
150 # (?P<name>regex) -- assign result of REGEX to NAME
151 # *? -- match non-greedily.
152 # (?m) -- multiline regex: make ^ and $ match at each line
153 # (?s) -- make the dot match all characters including newline
154 # (?x) -- ignore whitespace in patterns
166 (\s*(?P<options>.*?)\s*:)?\s*
174 \s*(?P<options>.*?)\s*
183 \s*(?P<options>.*?)\s*
185 \s*(?P<filename>.*?)\s*
192 (?P<code><!--\s.*?!-->)
195 'singleline_comment':
201 (?P<code><pre>.*?</pre>))''',
207 (?P<code><pre>\s.*?</pre>\s))''',
226 \s*(?P<options>.*?)\s*
237 \s*(?P<options>.*?)\s*
241 \\end\s*{lilypond})''',
249 \s*(?P<options>.*?)\s*
257 'singleline_comment':
280 \\end\s*{verbatim}))''',
289 (?P<filename>\S+))''',
293 ^[^\n]*?(?!@c\s+)[^\n]*?
297 \s*(?P<options>.*?)\s*
307 \s*(?P<options>.*?)\s*
310 ^@end\s+lilypond)\s''',
317 \s*(?P<options>.*?)\s*
328 @end\s+ignore))\s''',
330 'singleline_comment':
335 @c([ \t][^\n]*|)\n))''',
337 # don't do this: fucks up with @code{@{}
338 # 'verb': r'''(?P<code>@code{.*?})''',
346 @end\s+example\s))''',
352 'intertext': r',?\s*intertext=\".*?\"',
357 'intertext': r',?\s*intertext=\".*?\"',
358 'option_sep': '\s*,\s*',
362 'intertext': r',?\s*intertext=\".*?\"',
363 'option_sep': '\s*,\s*',
367 # options without a pattern in ly_options
381 RELATIVE: r'''\relative c%(relative_quotes)s''',
386 INDENT: r'''indent = %(indent)s''',
388 LINEWIDTH: r'''linewidth = %(linewidth)s''',
390 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
392 RAGGEDRIGHT: r'''raggedright = ##t''',
397 NOTIME: r'''\context {
399 \remove Time_signature_engraver
405 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
412 FILTER: r'''<lilypond %(options)s>
422 <a href="%(base)s.ly">''',
425 <img align="center" valign="center"
426 border="0" src="%(image)s" alt="[image of music]">''',
428 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
430 QUOTE: r'''<blockquote>
447 \ifx\preLilyPondExample \undefined
452 \def\lilypondbook{}%%
454 \ifx\postLilyPondExample \undefined
461 PRINTFILENAME: '''\\texttt{%(filename)s}
464 QUOTE: r'''\begin{quotation}
469 VERBATIM: r'''\noindent
471 %(verb)s\end{verbatim}
474 FILTER: r'''\begin{lilypond}[%(options)s]
481 FILTER: r'''@lilypond[%(options)s]
489 OUTPUT: r'''@noindent
490 @image{%(base)s,,,[image of music],%(ext)s}''',
492 PRINTFILENAME: '''@file{%(filename)s}
495 QUOTE: r'''@quotation
500 # FIXME: @exampleindent 5 is the default...
501 VERBATIM: r'''@exampleindent 0
509 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
510 %%%% Options: [%(option_string)s]
512 #(set! toplevel-score-handler ly:parser-print-score)
513 #(set! toplevel-music-handler (lambda (p m)
514 (ly:parser-print-score
515 p (ly:music-scorify m p))))
520 #(define dump-extents #t)
532 %% ly snippet contents follows:
544 texinfo_linewidths = {
545 '@afourpaper': '160\\mm',
546 '@afourwide': '6.5\\in',
547 '@afourlatex': '150\\mm',
548 '@smallbook': '5\\in',
549 '@letterpaper': '6\\in',
552 def classic_lilypond_book_compatibility (key, value):
553 if key == 'singleline' and value == None:
554 return (RAGGEDRIGHT, None)
556 m = re.search ('relative\s*([-0-9])', key)
558 return ('relative', m.group (1))
560 m = re.match ('([0-9]+)pt', key)
562 return ('staffsize', m.group (1))
564 if key == 'indent' or key == 'linewidth':
565 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
567 f = float (m.group (1))
568 return (key, '%f\\%s' % (f, m.group (2)))
572 def compose_ly (code, options, type):
576 if string.find (i, '=') > 0:
577 (key, value) = re.split ('\s*=\s*', i)
578 option_dict[key] = value
580 if i in no_options.keys ():
581 if no_options[i] in option_dict.keys ():
582 del option_dict[no_options[i]]
584 option_dict[i] = None
586 has_linewidth = option_dict.has_key (LINEWIDTH)
587 no_linewidth_value = 0
589 # if LINEWIDTH is used without parameter, set it to default
590 if has_linewidth and option_dict[LINEWIDTH] == None:
591 no_linewidth_value = 1
592 del option_dict[LINEWIDTH]
594 for i in default_ly_options.keys ():
595 if i not in option_dict.keys ():
596 option_dict[i] = default_ly_options[i]
598 if not has_linewidth:
599 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
600 option_dict[RAGGEDRIGHT] = None
602 if type == 'lilypond':
603 if LINEWIDTH in option_dict.keys ():
604 del option_dict[LINEWIDTH]
606 if RAGGEDRIGHT in option_dict.keys ():
607 if LINEWIDTH in option_dict.keys ():
608 del option_dict[LINEWIDTH]
610 if QUOTE in option_dict.keys () or type == 'lilypond':
611 if LINEWIDTH in option_dict.keys ():
612 del option_dict[LINEWIDTH]
614 if not INDENT in option_dict.keys ():
615 option_dict[INDENT] = '0\\mm'
617 # the QUOTE pattern from ly_options only emits the `linewidth' keyword
618 if has_linewidth and QUOTE in option_dict.keys ():
619 if no_linewidth_value:
620 del option_dict[LINEWIDTH]
622 del option_dict[QUOTE]
624 if FRAGMENT in option_dict.keys ():
632 # FIXME: Where to get sane value for exampleindent?
633 # In texinfo.tex, its maximum value is 0.4in, so we use that.
634 override[EXAMPLEINDENT] = r'0.4\in'
635 override[LINEWIDTH] = None
636 override.update (default_ly_options)
639 for (key, value) in option_dict.items ():
641 option_list.append (key)
643 option_list.append (key + '=' + value)
644 option_string = string.join (option_list, ',')
647 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
648 for a in compose_types:
651 for (key, value) in option_dict.items():
653 classic_lilypond_book_compatibility (key, value)
657 (_ ("deprecated ly-option used: %s=%s" \
660 (_ ("compatibility mode translation: %s=%s" \
664 (_ ("deprecated ly-option used: %s" \
667 (_ ("compatibility mode translation: %s" \
670 (key, value) = (c_key, c_value)
673 override[key] = value
675 if not override.has_key (key):
679 for type in compose_types:
680 if ly_options[type].has_key (key):
681 compose_dict[type].append (ly_options[type][key])
685 if not found and key not in simple_options:
686 ly.warning (_ ("ignoring unknown ly option: %s") % i)
689 if RELATIVE in override.keys () and override[RELATIVE]:
690 relative = string.atoi (override[RELATIVE])
696 relative_quotes += ',' * (- relative)
698 relative_quotes += "'" * relative
700 program_name = __main__.program_name
703 string.join (compose_dict[PAPER], '\n ') % override
705 string.join (compose_dict[LAYOUT], '\n ') % override
707 string.join (compose_dict[NOTES], '\n ') % vars ()
709 string.join (compose_dict[PREAMBLE], '\n ') % override
711 return (PREAMBLE_LY + body) % vars ()
714 # use lilypond for latex (.lytex) books,
715 # and lilypond --preview for html, texinfo books?
717 cmd = r'latex "\nonstopmode \input %s"' % file
718 # Ugh. (La)TeX writes progress and error messages on stdout
720 cmd = '(( %s >&2 ) >&- )' % cmd
722 ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
725 # check if it really is EPS.
726 # Otherwise music glyphs disappear from 2nd and following pages.
728 # TODO: should run dvips -pp -E per page, then we get proper
731 f = open ('%s.eps' % file)
732 for x in range (0, 10):
733 if re.search ("^%%Pages: ", f.readline ()):
735 ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
739 def find_file (name):
740 for i in include_path:
741 full = os.path.join (i, name)
742 if os.path.exists (full):
744 ly.error (_ ("file not found: %s") % name + '\n')
748 def verbatim_html (s):
749 return re.sub ('>', '>',
751 re.sub ('&', '&', s)))
753 def verbatim_texinfo (s):
754 return re.sub ('{', '@{',
756 re.sub ('@', '@@', s)))
758 def split_options (option_string):
759 return re.split (format_res[format]['option_sep'], option_string)
762 def replacement_text (self):
765 def filter_text (self):
766 return self.replacement_text ()
768 def ly_is_outdated (self):
771 def png_is_outdated (self):
774 class Substring (Chunk):
775 def __init__ (self, source, start, end):
780 def replacement_text (self):
781 return self.source [self.start:self.end]
783 class Snippet (Chunk):
784 def __init__ (self, type, match, format):
791 def replacement_text (self):
792 return self.match.group ('match')
794 def substring (self, s):
795 return self.match.group (s)
798 return `self.__class__` + " type = " + self.type
800 class Include_snippet (Snippet):
801 def processed_filename (self):
802 f = self.substring ('filename')
803 return os.path.splitext (f)[0] + format2ext[format]
805 def replacement_text (self):
806 s = self.match.group ('match')
807 f = self.substring ('filename')
809 return re.sub (f, self.processed_filename (), s)
811 class Lilypond_snippet (Snippet):
812 def __init__ (self, type, match, format):
813 Snippet.__init__ (self, type, match, format)
814 os = match.group ('options')
816 self.options = split_options (os)
819 return self.substring ('code')
824 return compose_ly (s, self.options, self.type)
830 self.hash = abs (hash (self.full_ly ()))
835 return 'lily-%d' % self.get_hash ()
839 outf = open (self.basename () + '.ly', 'w')
840 outf.write (self.full_ly ())
842 open (self.basename () + '.txt', 'w').write ("image of music")
844 def ly_is_outdated (self):
845 base = self.basename ()
847 tex_file = '%s.tex' % base
848 ly_file = '%s.ly' % base
849 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
850 and os.stat (tex_file)[stat.ST_SIZE] \
851 and open (tex_file).readlines ()[-1][1:-1] \
854 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
855 # TODO: something smart with target formats
856 # (ps, png) and m/ctimes
860 def png_is_outdated (self):
861 base = self.basename ()
862 ok = self.ly_is_outdated ()
863 if format == HTML or format == TEXINFO:
864 ok = ok and (os.path.exists (base + '.png')
865 or glob.glob (base + '-page*.png'))
868 def filter_text (self):
869 code = self.substring ('code')
870 s = run_filter (code)
873 'options': self.match.group ('options')
876 return output[self.format][FILTER] % d
878 def replacement_text (self):
879 func = Lilypond_snippet.__dict__ ['output_' + self.format]
882 def get_images (self):
883 base = self.basename ()
885 single = '%(base)s.png' % vars ()
886 multiple = '%(base)s-page1.png' % vars ()
888 if os.path.exists (multiple) \
889 and (not os.path.exists (single) \
890 or (os.stat (multiple)[stat.ST_MTIME] \
891 > os.stat (single)[stat.ST_MTIME])):
892 images = glob.glob ('%(base)s-page*.png' % vars ())
895 def output_html (self):
897 base = self.basename ()
899 str += self.output_print_filename (HTML)
900 if VERBATIM in self.options:
901 verb = verbatim_html (self.substring ('code'))
902 str += write (output[HTML][VERBATIM] % vars ())
903 if QUOTE in self.options:
904 str = output[HTML][QUOTE] % vars ()
906 str += output[HTML][BEFORE] % vars ()
907 for image in self.get_images ():
908 (base, ext) = os.path.splitext (image)
909 str += output[HTML][OUTPUT] % vars ()
910 str += output[HTML][AFTER] % vars ()
913 def output_info (self):
914 str = self.output_print_filename (HTML)
915 str = output[TEXINFO][BEFORE] % vars ()
916 for image in self.get_images ():
917 (base, ext) = os.path.splitext (image)
919 # URG, makeinfo implicitely prepends dot to ext
920 # specifying no extension is most robust
922 str += output[TEXINFO][OUTPUT] % vars ()
923 str += output[TEXINFO][AFTER] % vars ()
926 def output_latex (self):
928 base = self.basename ()
930 str += self.output_print_filename (LATEX)
931 if VERBATIM in self.options:
932 verb = self.substring ('code')
933 str += (output[LATEX][VERBATIM] % vars ())
934 if QUOTE in self.options:
935 str = output[LATEX][QUOTE] % vars ()
937 str += (output[LATEX][BEFORE]
938 + (output[LATEX][OUTPUT] % vars ())
939 + output[LATEX][AFTER])
942 def output_print_filename (self,format):
944 if PRINTFILENAME in self.options:
945 base = self.basename ()
946 filename = self.substring ('filename')
947 str = output[format][PRINTFILENAME] % vars ()
950 def output_texinfo (self):
952 if self.output_print_filename (TEXINFO):
953 str += ('@html\n' + self.output_print_filename (HTML)
955 str += ('@tex\n' + self.output_print_filename (LATEX)
957 base = self.basename ()
958 if TEXIDOC in self.options:
959 texidoc = base + '.texidoc'
960 if os.path.exists (texidoc):
961 str += '@include %(texidoc)s\n\n' % vars ()
963 if VERBATIM in self.options:
964 verb = verbatim_texinfo (self.substring ('code'))
965 str += (output[TEXINFO][VERBATIM] % vars ())
967 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
968 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
969 str += ('@html\n' + self.output_html () + '\n@end html\n')
971 if QUOTE in self.options:
972 str = output[TEXINFO][QUOTE] % vars ()
974 # need par after image
979 class Lilypond_file_snippet (Lilypond_snippet):
981 name = self.substring ('filename')
982 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
984 snippet_type_to_class = {
985 'lilypond_file': Lilypond_file_snippet,
986 'lilypond_block': Lilypond_snippet,
987 'lilypond': Lilypond_snippet,
988 'include': Include_snippet,
991 def find_toplevel_snippets (s, types):
994 res[i] = ly.re.compile (snippet_res[format][i])
998 ## found = dict (map (lambda x: (x, None), types))
1001 map (lambda x, f = found: f.setdefault (x, None), types)
1003 # We want to search for multiple regexes, without searching
1004 # the string multiple times for one regex.
1005 # Hence, we use earlier results to limit the string portion
1007 # Since every part of the string is traversed at most once for
1008 # every type of snippet, this is linear.
1014 if not found[type] or found[type][0] < index:
1016 m = res[type].search (s[index:endex])
1021 if snippet_type_to_class.has_key (type):
1022 cl = snippet_type_to_class[type]
1023 snip = cl (type, m, format)
1024 start = index + m.start ('match')
1025 found[type] = (start, snip)
1028 and (not first or found[type][0] < found[first][0]):
1033 # Limiting the search space is a cute
1034 # idea, but this *requires* to search
1035 # for possible containing blocks
1036 # first, at least as long as we do not
1037 # search for the start of blocks, but
1038 # always/directly for the entire
1039 # @block ... @end block.
1041 endex = found[first][0]
1044 snippets.append (Substring (s, index, len (s)))
1047 (start, snip) = found[first]
1048 snippets.append (Substring (s, index, start))
1049 snippets.append (snip)
1051 index = start + len (snip.match.group ('match'))
1055 def filter_pipe (input, cmd):
1057 ly.progress (_ ("Opening filter `%s'") % cmd)
1059 (stdin, stdout, stderr) = os.popen3 (cmd)
1061 status = stdin.close ()
1065 output = stdout.read ()
1066 status = stdout.close ()
1067 error = stderr.read ()
1071 signal = 0x0f & status
1072 if status or (not output and error):
1073 exit_status = status >> 8
1074 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1075 ly.error (_ ("The error log is as follows:"))
1076 sys.stderr.write (error)
1077 sys.stderr.write (stderr.read ())
1086 return filter_pipe (s, filter_cmd)
1088 def is_derived_class (cl, baseclass):
1091 for b in cl.__bases__:
1092 if is_derived_class (b, baseclass):
1096 def process_snippets (cmd, ly_snippets, png_snippets):
1097 ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
1098 png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
1102 status = ly.system (string.join ([cmd] + ly_names),
1103 ignore_error = 1, progress_p = 1)
1106 ly.error ('Process %s exited unsuccessfully.' % cmd)
1109 if format == HTML or format == TEXINFO:
1111 if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
1113 ly.make_ps_images (i + '.eps', resolution = 110)
1115 # elif os.path.exists (i + '.ps'):
1116 # ly.make_ps_images (i + '.ps', resolution = 110)
1118 LATEX_DOCUMENT = r'''
1121 \typeout{textwidth=\the\textwidth}
1122 \typeout{columnsep=\the\columnsep}
1123 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1126 # need anything else besides textwidth?
1127 def get_latex_textwidth (source):
1128 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1129 preamble = source[:m.start (0)]
1130 latex_document = LATEX_DOCUMENT % vars ()
1131 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1134 m = re.search ('columns=([0-9.]*)', parameter_string)
1136 columns = string.atoi (m.group (1))
1139 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1141 columnsep = string.atof (m.group (1))
1144 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1146 textwidth = string.atof (m.group (1))
1148 textwidth = (textwidth - columnsep) / columns
1160 '.texinfo': TEXINFO,
1166 # TEXINFO: '.texinfo',
1171 class Compile_error:
1174 def do_process_cmd (chunks):
1175 ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1176 and x.ly_is_outdated (), chunks)
1177 png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1178 and x.png_is_outdated (), chunks)
1180 ly.progress (_ ("Writing snippets..."))
1181 map (Lilypond_snippet.write_ly, ly_outdated)
1185 ly.progress (_ ("Processing...\n"))
1186 process_snippets (process_cmd, ly_outdated, png_outdated)
1188 ly.progress (_ ("All snippets are up to date..."))
1191 def do_file (input_filename):
1195 e = os.path.splitext (input_filename)[1]
1196 if e in ext2format.keys ():
1198 format = ext2format[e]
1200 ly.error (_ ("cannot determine format for: %s" \
1204 if not input_filename or input_filename == '-':
1205 in_handle = sys.stdin
1206 input_fullname = '<stdin>'
1208 if os.path.exists (input_filename):
1209 input_fullname = input_filename
1210 elif format == LATEX:
1211 # urg python interface to libkpathsea?
1212 input_fullname = ly.read_pipe ('kpsewhich '
1213 + input_filename)[:-1]
1215 input_fullname = find_file (input_filename)
1216 in_handle = open (input_fullname)
1218 if input_filename == '-':
1219 input_base = 'stdin'
1221 input_base = os.path.basename \
1222 (os.path.splitext (input_filename)[0])
1224 # only default to stdout when filtering
1225 if output_name == '-' or (not output_name and filter_cmd):
1226 output_filename = '-'
1227 output_file = sys.stdout
1230 output_filename = input_base + format2ext[format]
1232 if not os.path.isdir (output_name):
1233 os.mkdir (output_name, 0777)
1234 output_filename = (output_name
1236 + format2ext[format])
1238 if (os.path.exists (input_filename) and
1239 os.path.exists (output_filename) and
1240 os.path.samefile (output_filename, input_fullname)):
1241 ly.error (_ ("Output would overwrite input file; use --output."))
1244 output_file = open (output_filename, 'w')
1246 os.chdir (output_name)
1248 ly.progress (_ ("Reading %s...") % input_fullname)
1249 source = in_handle.read ()
1252 # FIXME: containing blocks must be first, see
1253 # find_toplevel_snippets
1255 'multiline_comment',
1259 'singleline_comment',
1263 ly.progress (_ ("Dissecting..."))
1264 chunks = find_toplevel_snippets (source, snippet_types)
1267 global default_ly_options
1269 if not default_ly_options.has_key (LINEWIDTH):
1271 textwidth = get_latex_textwidth (source)
1272 default_ly_options[LINEWIDTH] = \
1273 '''%.0f\\pt''' % textwidth
1274 elif format == TEXINFO:
1275 for (k, v) in texinfo_linewidths.items ():
1276 # FIXME: @layout is usually not in chunk #0:
1277 # \input texinfo @c -*-texinfo-*-
1278 # bluntly search first K of source
1279 # s = chunks[0].replacement_text ()
1280 if re.search (k, source[:1024]):
1281 default_ly_options[LINEWIDTH] = v
1285 output_file.writelines ([c.filter_text () for c in chunks])
1288 do_process_cmd (chunks)
1289 ly.progress (_ ("Compiling %s...") % output_filename)
1290 output_file.writelines ([s.replacement_text () \
1294 def process_include (snippet):
1295 os.chdir (original_dir)
1296 name = snippet.substring ('filename')
1297 ly.progress (_ ("Processing include: %s") % name)
1301 map (process_include,
1302 filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1303 except Compile_error:
1304 os.chdir (original_dir)
1305 ly.progress (_ ("Removing `%s'") % output_filename)
1308 os.unlink (output_filename)
1312 global format, output_name
1313 global filter_cmd, process_cmd, verbose_p
1315 (sh, long) = ly.getopt_args (option_definitions)
1317 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1318 except getopt.error, s:
1319 sys.stderr.write ('\n')
1320 ly.error (_ ("getopt says: `%s'" % s))
1321 sys.stderr.write ('\n')
1331 elif o == '--filter' or o == '-F':
1334 elif o == '--format' or o == '-f':
1336 if a == 'texi-html' or a == 'texi':
1338 elif o == '--help' or o == '-h':
1341 elif o == '--include' or o == '-I':
1342 include_path.append (os.path.join (original_dir,
1344 elif o == '--output' or o == '-o':
1346 elif o == '--outdir':
1348 elif o == '--process' or o == '-P':
1351 elif o == '--version' or o == '-v':
1352 ly.identify (sys.stdout)
1354 elif o == '--verbose' or o == '-V':
1356 elif o == '--warranty' or o == '-w':
1363 files = do_options ()
1365 if process_cmd == '':
1366 process_cmd = lilypond_binary + " -f tex"
1369 process_cmd += string.join ([(' -I %s' % p)
1370 for p in include_path])
1372 ly.identify (sys.stderr)
1373 ly.setup_environment ()
1377 except Compile_error:
1380 if __name__ == '__main__':