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
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
37 # Users of python modules should include this snippet
38 # and customize variables below.
40 # We'll suffer this path initialization stuff as long as we don't install
41 # our python packages in <prefix>/lib/pythonX.Y
43 # If set, LILYPONDPREFIX must take prevalence.
44 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
45 import getopt, os, sys
46 datadir = '@local_lilypond_datadir@'
47 if not os.path.isdir (datadir):
48 datadir = '@lilypond_datadir@'
49 if os.environ.has_key ('LILYPONDPREFIX'):
50 datadir = os.environ['LILYPONDPREFIX']
51 while datadir[-1] == os.sep:
54 sys.path.insert (0, os.path.join (datadir, 'python'))
57 #if __name__ == '__main__':
65 program_version = '@TOPLEVEL_VERSION@'
66 program_name = os.path.basename (sys.argv[0])
69 original_dir = os.getcwd ()
73 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
76 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
77 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
78 lilypond-book --process='lilypond -I include' BOOK
81 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
82 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
84 option_definitions = [
85 (_ ("FMT"), 'f', 'format',
86 _ ('''use output format FMT (texi [default], texi-html,
88 (_ ("FILTER"), 'F', 'filter',
89 _ ("pipe snippets through FILTER [convert-ly -n -]")),
91 _ ("print this help")),
92 (_ ("DIR"), 'I', 'include',
93 _ ("add DIR to include path")),
94 (_ ("DIR"), 'o', 'output',
95 _ ("write output to DIR")),
96 (_ ("COMMAND"), 'P', 'process',
97 _ ("process ly_files using COMMAND FILE...")),
99 _ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
100 must use this with dvips -h INPUT.psfonts''')),
104 _ ("print version information")),
105 ('', 'w', 'warranty',
106 _ ("show warranty and copyright")),
109 include_path = [os.path.abspath (os.getcwd ())]
110 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
112 # Only use installed binary when we are installed too.
113 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
114 lilypond_binary = 'lilypond'
120 latex_filter_cmd = 'cat > %(tmpfile)s && latex "\\nonstopmode \input %(tmpfile)s" && rm %(tmpfile)s'
123 default_ly_options = { 'alt': "[image of music]" }
126 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
130 EXAMPLEINDENT = 'exampleindent'
132 FRAGMENT = 'fragment'
137 LINEWIDTH = 'linewidth'
138 NOFRAGMENT = 'nofragment'
139 NOINDENT = 'noindent'
144 OUTPUTIMAGE = 'outputimage'
147 PREAMBLE = 'preamble'
148 PRINTFILENAME = 'printfilename'
150 RAGGEDRIGHT = 'raggedright'
151 RELATIVE = 'relative'
152 STAFFSIZE = 'staffsize'
155 VERBATIM = 'verbatim'
156 FONTLOAD = 'fontload'
157 FILENAME = 'filename'
161 # NOTIME has no opposite so it isn't part of this dictionary.
162 # NOQUOTE is used internally only.
164 NOFRAGMENT: FRAGMENT,
169 # Recognize special sequences in the input.
171 # (?P<name>regex) -- Assign result of REGEX to NAME.
172 # *? -- Match non-greedily.
173 # (?m) -- Multiline regex: Make ^ and $ match at each line.
174 # (?s) -- Make the dot match all characters including newline.
175 # (?x) -- Ignore whitespace in patterns.
187 (\s*(?P<options>.*?)\s*:)?\s*
195 \s*(?P<options>.*?)\s*
204 \s*(?P<options>.*?)\s*
206 \s*(?P<filename>.*?)\s*
213 (?P<code><!--\s.*?!-->)
216 'singleline_comment':
222 (?P<code><pre>.*?</pre>))''',
228 (?P<code><pre>\s.*?</pre>\s))''',
247 \s*(?P<options>.*?)\s*
258 \s*(?P<options>.*?)\s*
262 \\end\s*{lilypond})''',
270 \s*(?P<options>.*?)\s*
278 'singleline_comment':
301 \\end\s*{verbatim}))''',
310 (?P<filename>\S+))''',
314 ^[^\n]*?(?!@c\s+)[^\n]*?
318 \s*(?P<options>.*?)\s*
328 \s*(?P<options>.*?)\s*
331 ^@end\s+lilypond)\s''',
338 \s*(?P<options>.*?)\s*
349 @end\s+ignore))\s''',
351 'singleline_comment':
356 @c([ \t][^\n]*|)\n))''',
358 # Don't do this: It interferes with @code{@{}.
359 # 'verb': r'''(?P<code>@code{.*?})''',
367 @end\s+example\s))''',
373 'intertext': r',?\s*intertext=\".*?\"',
378 'intertext': r',?\s*intertext=\".*?\"',
379 'option_sep': '\s*,\s*',
383 'intertext': r',?\s*intertext=\".*?\"',
384 'option_sep': '\s*,\s*',
388 # Options without a pattern in ly_options.
405 RELATIVE: r'''\relative c%(relative_quotes)s''',
410 INDENT: r'''indent = %(indent)s''',
412 LINEWIDTH: r'''linewidth = %(linewidth)s''',
414 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
416 RAGGEDRIGHT: r'''raggedright = ##t''',
418 PACKED: r'''packed = ##t''',
430 \remove Time_signature_engraver
436 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
443 FILTER: r'''<lilypond %(options)s>
453 <a href="%(base)s.ly">''',
456 <img align="center" valign="center"
457 border="0" src="%(image)s" alt="%(alt)s">''',
459 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
461 QUOTE: r'''<blockquote>
475 \ifx\preLilyPondExample \undefined
480 \def\lilypondbook{}%%
481 \input %(base)s-systems.tex
482 \ifx\postLilyPondExample \undefined
489 PRINTFILENAME: '''\\texttt{%(filename)s}
492 QUOTE: r'''\begin{quotation}
497 VERBATIM: r'''\noindent
499 %(verb)s\end{verbatim}
502 FILTER: r'''\begin{lilypond}[%(options)s]
509 FILTER: r'''@lilypond[%(options)s]
515 @include %(base)s-systems.texi
519 OUTPUTIMAGE: r'''@noindent
521 @image{%(base)s,,,%(alt)s,%(ext)s}
525 <a href="%(base)s.ly">
526 <img align="center" valign="center"
527 border="0" src="%(image)s" alt="%(alt)s">
533 PRINTFILENAME: '''@file{%(filename)s}
536 QUOTE: r'''@quotation
537 %(str)s@end quotation
544 VERBATIM: r'''@exampleindent 0
551 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
552 %%%% Options: [%(option_string)s]
554 #(set! toplevel-score-handler print-score-with-defaults)
555 #(set! toplevel-music-handler (lambda (p m)
556 (print-score-with-defaults
557 p (scorify-music m p))))
559 #(ly:set-option (quote no-point-and-click))
561 #(define version-seen? #t)
565 %% ********************************
566 %% Start cut-&-pastable-section
567 %% ********************************
570 #(define dump-extents #t)
571 %(font_dump_setting)s
583 %% ly snippet contents follows:
595 texinfo_linewidths = {
596 '@afourpaper': '160\\mm',
597 '@afourwide': '6.5\\in',
598 '@afourlatex': '150\\mm',
599 '@smallbook': '5\\in',
600 '@letterpaper': '6\\in',
603 def classic_lilypond_book_compatibility (key, value):
604 if key == 'singleline' and value == None:
605 return (RAGGEDRIGHT, None)
607 m = re.search ('relative\s*([-0-9])', key)
609 return ('relative', m.group (1))
611 m = re.match ('([0-9]+)pt', key)
613 return ('staffsize', m.group (1))
615 if key == 'indent' or key == 'linewidth':
616 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
618 f = float (m.group (1))
619 return (key, '%f\\%s' % (f, m.group (2)))
623 def find_file (name):
624 for i in include_path:
625 full = os.path.join (i, name)
626 if os.path.exists (full):
628 ly.error (_ ("file not found: %s") % name + '\n')
632 def verbatim_html (s):
633 return re.sub ('>', '>',
635 re.sub ('&', '&', s)))
637 def verbatim_texinfo (s):
638 return re.sub ('{', '@{',
640 re.sub ('@', '@@', s)))
642 def split_options (option_string):
645 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
646 for i in range(len(options)):
647 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
650 return re.split (format_res[format]['option_sep'],
654 def invokes_lilypond ():
655 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
657 def set_default_options (source):
658 global default_ly_options
659 if not default_ly_options.has_key (LINEWIDTH):
661 textwidth = get_latex_textwidth (source)
662 default_ly_options[LINEWIDTH] = \
663 '''%.0f\\pt''' % textwidth
664 elif format == TEXINFO:
665 for (k, v) in texinfo_linewidths.items ():
666 # FIXME: @layout is usually not in
669 # \input texinfo @c -*-texinfo-*-
671 # Bluntly search first K items of
673 # s = chunks[0].replacement_text ()
674 if re.search (k, source[:1024]):
675 default_ly_options[LINEWIDTH] = v
679 def replacement_text (self):
682 def filter_text (self):
683 return self.replacement_text ()
685 def ly_is_outdated (self):
688 def png_is_outdated (self):
691 class Substring (Chunk):
692 def __init__ (self, source, start, end, line_number):
696 self.line_number = line_number
698 def replacement_text (self):
699 return self.source[self.start:self.end]
701 class Snippet (Chunk):
702 def __init__ (self, type, match, format, line_number):
706 self.option_dict = {}
708 self.line_number = line_number
710 def replacement_text (self):
711 return self.match.group ('match')
713 def substring (self, s):
714 return self.match.group (s)
717 return `self.__class__` + ' type = ' + self.type
719 class Include_snippet (Snippet):
720 def processed_filename (self):
721 f = self.substring ('filename')
722 return os.path.splitext (f)[0] + format2ext[format]
724 def replacement_text (self):
725 s = self.match.group ('match')
726 f = self.substring ('filename')
728 return re.sub (f, self.processed_filename (), s)
730 class Lilypond_snippet (Snippet):
731 def __init__ (self, type, match, format, line_number):
732 Snippet.__init__ (self, type, match, format, line_number)
733 os = match.group ('options')
734 self.do_options (os, self.type)
737 return self.substring ('code')
742 return self.compose_ly (s)
745 def do_options (self, option_string, type):
746 self.option_dict = {}
748 options = split_options (option_string)
751 if string.find (i, '=') > 0:
752 (key, value) = re.split ('\s*=\s*', i)
753 self.option_dict[key] = value
755 if i in no_options.keys ():
756 if no_options[i] in self.option_dict.keys ():
757 del self.option_dict[no_options[i]]
759 self.option_dict[i] = None
761 has_linewidth = self.option_dict.has_key (LINEWIDTH)
762 no_linewidth_value = 0
764 # If LINEWIDTH is used without parameter, set it to default.
765 if has_linewidth and self.option_dict[LINEWIDTH] == None:
766 no_linewidth_value = 1
767 del self.option_dict[LINEWIDTH]
769 for i in default_ly_options.keys ():
770 if i not in self.option_dict.keys ():
771 self.option_dict[i] = default_ly_options[i]
773 if not has_linewidth:
774 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
775 self.option_dict[RAGGEDRIGHT] = None
777 if type == 'lilypond':
778 if LINEWIDTH in self.option_dict.keys ():
779 del self.option_dict[LINEWIDTH]
781 if RAGGEDRIGHT in self.option_dict.keys ():
782 if LINEWIDTH in self.option_dict.keys ():
783 del self.option_dict[LINEWIDTH]
785 if QUOTE in self.option_dict.keys () or type == 'lilypond':
786 if LINEWIDTH in self.option_dict.keys ():
787 del self.option_dict[LINEWIDTH]
789 if not INDENT in self.option_dict.keys ():
790 self.option_dict[INDENT] = '0\\mm'
792 # The QUOTE pattern from ly_options only emits the `linewidth'
794 if has_linewidth and QUOTE in self.option_dict.keys ():
795 if no_linewidth_value:
796 del self.option_dict[LINEWIDTH]
798 del self.option_dict[QUOTE]
800 def compose_ly (self, code):
801 if FRAGMENT in self.option_dict.keys ():
809 # The original concept of the `exampleindent' option is broken.
810 # It is not possible to get a sane value for @exampleindent at all
811 # without processing the document itself. Saying
819 # causes ugly results with the DVI backend of texinfo since the
820 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
821 # value). Executing the above code changes the environment
822 # indentation to an unknown value because we don't know the amount
823 # of 1em in advance since it is font-dependent. Modifying
824 # @exampleindent in the middle of a document is simply not
825 # supported within texinfo.
827 # As a consequence, the only function of @exampleindent is now to
828 # specify the amount of indentation for the `quote' option.
830 # To set @exampleindent locally to zero, we use the @format
831 # environment for non-quoted snippets.
832 override[EXAMPLEINDENT] = r'0.4\in'
833 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
834 override.update (default_ly_options)
837 for (key, value) in self.option_dict.items ():
839 option_list.append (key)
841 option_list.append (key + '=' + value)
842 option_string = string.join (option_list, ',')
845 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
846 for a in compose_types:
849 for (key, value) in self.option_dict.items ():
851 classic_lilypond_book_compatibility (key, value)
855 (_ ("deprecated ly-option used: %s=%s" \
858 (_ ("compatibility mode translation: %s=%s" \
862 (_ ("deprecated ly-option used: %s" \
865 (_ ("compatibility mode translation: %s" \
868 (key, value) = (c_key, c_value)
871 override[key] = value
873 if not override.has_key (key):
877 for type in compose_types:
878 if ly_options[type].has_key (key):
879 compose_dict[type].append (ly_options[type][key])
883 if not found and key not in simple_options:
884 ly.warning (_ ("ignoring unknown ly option: %s") % key)
887 if RELATIVE in override.keys () and override[RELATIVE]:
888 relative = string.atoi (override[RELATIVE])
894 relative_quotes += ',' * (- relative)
896 relative_quotes += "'" * relative
898 program_name = __main__.program_name
900 paper_string = string.join (compose_dict[PAPER],
902 layout_string = string.join (compose_dict[LAYOUT],
904 notes_string = string.join (compose_dict[NOTES],
906 preamble_string = string.join (compose_dict[PREAMBLE],
909 font_dump_setting = ''
910 if FONTLOAD in self.option_dict:
911 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
913 return (PREAMBLE_LY + body) % vars ()
918 self.hash = abs (hash (self.full_ly ()))
922 if FILENAME in self.option_dict:
923 return self.option_dict[FILENAME]
925 return 'lily-%d' % self.get_hash ()
929 outf = open (self.basename () + '.ly', 'w')
930 outf.write (self.full_ly ())
932 open (self.basename () + '.txt', 'w').write ('image of music')
934 def ly_is_outdated (self):
935 base = self.basename ()
937 tex_file = '%s.tex' % base
938 eps_file = '%s.eps' % base
939 system_file = '%s-systems.tex' % base
940 ly_file = '%s.ly' % base
941 ok = os.path.exists (ly_file) \
942 and os.path.exists (system_file)\
943 and os.stat (system_file)[stat.ST_SIZE] \
944 and re.match ('% eof', open (system_file).readlines ()[-1])
945 if ok and (not use_hash_p or FILENAME in self.option_dict):
946 ok = (self.full_ly () == open (ly_file).read ())
948 # TODO: Do something smart with target formats
949 # (ps, png) and m/ctimes.
953 def png_is_outdated (self):
954 base = self.basename ()
955 ok = self.ly_is_outdated ()
956 if format == HTML or format == TEXINFO:
957 ok = ok and (os.path.exists (base + '.png')
958 or glob.glob (base + '-page*.png'))
960 def texstr_is_outdated (self):
964 base = self.basename ()
965 ok = self.ly_is_outdated ()
966 ok = ok and (os.path.exists (base + '.texstr'))
969 def filter_text (self):
970 code = self.substring ('code')
971 s = run_filter (code)
974 'options': self.match.group ('options')
977 return output[self.format][FILTER] % d
979 def replacement_text (self):
980 func = Lilypond_snippet.__dict__['output_' + self.format]
983 def get_images (self):
984 base = self.basename ()
986 single = '%(base)s.png' % vars ()
987 multiple = '%(base)s-page1.png' % vars ()
989 if os.path.exists (multiple) \
990 and (not os.path.exists (single) \
991 or (os.stat (multiple)[stat.ST_MTIME] \
992 > os.stat (single)[stat.ST_MTIME])):
993 images = glob.glob ('%(base)s-page*.png' % vars ())
996 def output_html (self):
998 base = self.basename ()
1000 str += self.output_print_filename (HTML)
1001 if VERBATIM in self.option_dict:
1002 verb = verbatim_html (self.substring ('code'))
1003 str += write (output[HTML][VERBATIM] % vars ())
1004 if QUOTE in self.option_dict:
1005 str = output[HTML][QUOTE] % vars ()
1007 str += output[HTML][BEFORE] % vars ()
1008 for image in self.get_images ():
1009 (base, ext) = os.path.splitext (image)
1010 alt = self.option_dict[ALT]
1011 str += output[HTML][OUTPUT] % vars ()
1012 str += output[HTML][AFTER] % vars ()
1015 def output_info (self):
1017 for image in self.get_images ():
1018 (base, ext) = os.path.splitext (image)
1020 # URG, makeinfo implicitly prepends dot to extension.
1021 # Specifying no extension is most robust.
1023 alt = self.option_dict[ALT]
1024 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1026 base = self.basename ()
1027 str += output[format][OUTPUT] % vars ()
1030 def output_latex (self):
1032 base = self.basename ()
1034 str += self.output_print_filename (LATEX)
1035 if VERBATIM in self.option_dict:
1036 verb = self.substring ('code')
1037 str += (output[LATEX][VERBATIM] % vars ())
1038 if QUOTE in self.option_dict:
1039 str = output[LATEX][QUOTE] % vars ()
1041 str += (output[LATEX][OUTPUT] % vars ())
1044 def output_print_filename (self, format):
1046 if PRINTFILENAME in self.option_dict:
1047 base = self.basename ()
1048 filename = self.substring ('filename')
1049 str = output[format][PRINTFILENAME] % vars ()
1053 def output_texinfo (self):
1055 if self.output_print_filename (TEXINFO):
1057 + self.output_print_filename (HTML)
1060 + self.output_print_filename (LATEX)
1062 base = self.basename ()
1063 if TEXIDOC in self.option_dict:
1064 texidoc = base + '.texidoc'
1065 if os.path.exists (texidoc):
1066 str += '@include %(texidoc)s\n\n' % vars ()
1068 if VERBATIM in self.option_dict:
1069 verb = verbatim_texinfo (self.substring ('code'))
1070 str += (output[TEXINFO][VERBATIM] % vars ())
1071 if not QUOTE in self.option_dict:
1072 str = output[TEXINFO][NOQUOTE] % vars ()
1074 str += self.output_info ()
1076 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1077 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1078 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1080 if QUOTE in self.option_dict:
1081 str = output[TEXINFO][QUOTE] % vars ()
1083 # need par after image
1088 class Lilypond_file_snippet (Lilypond_snippet):
1090 name = self.substring ('filename')
1091 return '\\renameinput \"%s\"\n%s' \
1092 % (name, open (find_file (name)).read ())
1094 snippet_type_to_class = {
1095 'lilypond_file': Lilypond_file_snippet,
1096 'lilypond_block': Lilypond_snippet,
1097 'lilypond': Lilypond_snippet,
1098 'include': Include_snippet,
1101 def find_linestarts (s):
1106 i = s.find ('\n', start)
1114 nls.append (len (s))
1117 def find_toplevel_snippets (s, types):
1120 res[i] = ly.re.compile (snippet_res[format][i])
1124 ## found = dict (map (lambda x: (x, None),
1128 map (lambda x, f = found: f.setdefault (x, None),
1131 line_starts = find_linestarts (s)
1133 # We want to search for multiple regexes, without searching
1134 # the string multiple times for one regex.
1135 # Hence, we use earlier results to limit the string portion
1137 # Since every part of the string is traversed at most once for
1138 # every type of snippet, this is linear.
1144 if not found[type] or found[type][0] < index:
1146 m = res[type].search (s[index:endex])
1151 if snippet_type_to_class.has_key (type):
1152 cl = snippet_type_to_class[type]
1155 start = index + m.start ('match')
1156 line_number = line_start_idx
1157 while (line_starts[line_number] < start):
1161 snip = cl (type, m, format, line_number)
1162 found[type] = (start, snip)
1166 or found[type][0] < found[first][0]):
1171 # Limiting the search space is a cute
1172 # idea, but this *requires* to search
1173 # for possible containing blocks
1174 # first, at least as long as we do not
1175 # search for the start of blocks, but
1176 # always/directly for the entire
1177 # @block ... @end block.
1179 endex = found[first][0]
1182 snippets.append (Substring (s, index, len (s), line_start_idx))
1185 while (start > line_starts[line_start_idx+1]):
1188 (start, snip) = found[first]
1189 snippets.append (Substring (s, index, start, line_start_idx + 1))
1190 snippets.append (snip)
1192 index = start + len (snip.match.group ('match'))
1196 def filter_pipe (input, cmd):
1198 ly.progress (_ ("Opening filter `%s'") % cmd)
1200 (stdin, stdout, stderr) = os.popen3 (cmd)
1202 status = stdin.close ()
1206 output = stdout.read ()
1207 status = stdout.close ()
1208 error = stderr.read ()
1212 signal = 0x0f & status
1213 if status or (not output and error):
1214 exit_status = status >> 8
1215 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1216 ly.error (_ ("The error log is as follows:"))
1217 sys.stderr.write (error)
1218 sys.stderr.write (stderr.read ())
1227 return filter_pipe (s, filter_cmd)
1229 def is_derived_class (cl, baseclass):
1232 for b in cl.__bases__:
1233 if is_derived_class (b, baseclass):
1237 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1238 ly_names = filter (lambda x: x,
1239 map (Lilypond_snippet.basename, ly_snippets))
1240 texstr_names = filter (lambda x: x,
1241 map (Lilypond_snippet.basename, texstr_snippets))
1242 png_names = filter (lambda x: x,
1243 map (Lilypond_snippet.basename, png_snippets))
1246 def my_system (cmd):
1247 status = ly.system (cmd,
1248 ignore_error = 1, progress_p = 1)
1251 ly.error ('Process %s exited unsuccessfully.' % cmd)
1255 # the --process=CMD switch is a bad idea
1256 # it is too generic for lilypond-book.
1257 if texstr_names and invokes_lilypond:
1258 my_system (string.join ([cmd, '--backend texstr',
1259 'snippet-map.ly'] + texstr_names))
1260 for l in texstr_names:
1261 my_system ('latex %s.texstr' % l)
1264 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1266 LATEX_DOCUMENT = r'''
1269 \typeout{textwidth=\the\textwidth}
1270 \typeout{columnsep=\the\columnsep}
1271 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1275 # Do we need anything else besides `textwidth'?
1276 def get_latex_textwidth (source):
1277 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1278 preamble = source[:m.start (0)]
1279 latex_document = LATEX_DOCUMENT % vars ()
1280 # Workaround problems with unusable $TMP on Cygwin:
1281 tempfile.tempdir = ''
1282 tmpfile = tempfile.mktemp('.tex')
1283 cmd = latex_filter_cmd % vars ()
1284 parameter_string = filter_pipe (latex_document, cmd)
1287 m = re.search ('columns=([0-9.]*)', parameter_string)
1289 columns = string.atoi (m.group (1))
1292 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1294 columnsep = string.atof (m.group (1))
1297 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1299 textwidth = string.atof (m.group (1))
1301 textwidth = (textwidth - columnsep) / columns
1313 '.texinfo': TEXINFO,
1319 # TEXINFO: '.texinfo',
1324 class Compile_error:
1327 def write_file_map (lys, name):
1328 snippet_map = open ('snippet-map.ly', 'w')
1329 snippet_map.write ("""
1330 #(define version-seen? #t)
1331 #(ly:add-file-name-alist '(
1334 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1340 snippet_map.write ('))\n')
1342 def do_process_cmd (chunks, input_name):
1343 all_lys = filter (lambda x: is_derived_class (x.__class__,
1347 write_file_map (all_lys, input_name)
1349 filter (lambda x: is_derived_class (x.__class__,
1351 and x.ly_is_outdated (),
1354 filter (lambda x: is_derived_class (x.__class__,
1356 and x.texstr_is_outdated (),
1359 filter (lambda x: is_derived_class (x.__class__,
1361 and x.png_is_outdated (),
1364 ly.progress (_ ("Writing snippets..."))
1365 map (Lilypond_snippet.write_ly, ly_outdated)
1369 ly.progress (_ ("Processing..."))
1371 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1373 ly.progress (_ ("All snippets are up to date..."))
1376 def guess_format (input_filename):
1378 e = os.path.splitext (input_filename)[1]
1379 if e in ext2format.keys ():
1381 format = ext2format[e]
1383 ly.error (_ ("can't determine format for: %s" \
1388 def write_if_updated (file_name, lines):
1390 f = open (file_name)
1392 new_str = string.join (lines, '')
1393 if oldstr == new_str:
1394 ly.progress (_ ("%s is up to date.") % file_name)
1400 ly.progress (_ ("Writing `%s'...") % file_name)
1401 open (file_name, 'w').writelines (lines)
1404 def do_file (input_filename):
1406 if not input_filename or input_filename == '-':
1407 in_handle = sys.stdin
1408 input_fullname = '<stdin>'
1410 if os.path.exists (input_filename):
1411 input_fullname = input_filename
1412 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1413 # urg python interface to libkpathsea?
1414 input_fullname = ly.read_pipe ('kpsewhich '
1415 + input_filename)[:-1]
1417 input_fullname = find_file (input_filename)
1418 in_handle = open (input_fullname)
1420 if input_filename == '-':
1421 input_base = 'stdin'
1423 input_base = os.path.basename \
1424 (os.path.splitext (input_filename)[0])
1426 # Only default to stdout when filtering.
1427 if output_name == '-' or (not output_name and filter_cmd):
1428 output_filename = '-'
1429 output_file = sys.stdout
1431 # don't complain when output_name is existing
1432 output_filename = input_base + format2ext[format]
1434 if not os.path.isdir (output_name):
1435 os.mkdir (output_name, 0777)
1436 os.chdir (output_name)
1438 if os.path.exists (input_filename) \
1439 and os.path.exists (output_filename) \
1440 and os.path.samefile (output_filename, input_fullname):
1442 _ ("Output would overwrite input file; use --output."))
1446 ly.progress (_ ("Reading %s...") % input_fullname)
1447 source = in_handle.read ()
1450 set_default_options (source)
1453 # FIXME: Containing blocks must be first, see
1454 # find_toplevel_snippets.
1456 'multiline_comment',
1460 'singleline_comment',
1465 ly.progress (_ ("Dissecting..."))
1466 chunks = find_toplevel_snippets (source, snippet_types)
1470 write_if_updated (output_filename,
1471 [c.filter_text () for c in chunks])
1473 do_process_cmd (chunks, input_fullname)
1474 ly.progress (_ ("Compiling %s...") % output_filename)
1476 write_if_updated (output_filename,
1477 [s.replacement_text ()
1480 def process_include (snippet):
1481 os.chdir (original_dir)
1482 name = snippet.substring ('filename')
1483 ly.progress (_ ("Processing include: %s") % name)
1485 return do_file (name)
1487 include_chunks = map (process_include,
1488 filter (lambda x: is_derived_class (x.__class__,
1493 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1495 except Compile_error:
1496 os.chdir (original_dir)
1497 ly.progress (_ ("Removing `%s'") % output_filename)
1502 global format, output_name, psfonts_p
1503 global filter_cmd, process_cmd, verbose_p
1505 (sh, long) = ly.getopt_args (option_definitions)
1507 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1508 except getopt.error, s:
1509 sys.stderr.write ('\n')
1510 ly.error (_ ("getopt says: `%s'" % s))
1511 sys.stderr.write ('\n')
1521 elif o == '--filter' or o == '-F':
1524 elif o == '--format' or o == '-f':
1526 if a == 'texi-html' or a == 'texi':
1528 elif o == '--tex-backend ':
1530 elif o == '--help' or o == '-h':
1533 elif o == '--include' or o == '-I':
1534 include_path.append (os.path.join (original_dir,
1535 os.path.abspath (a)))
1536 elif o == '--output' or o == '-o':
1538 elif o == '--process' or o == '-P':
1541 elif o == '--version' or o == '-v':
1542 ly.identify (sys.stdout)
1544 elif o == '--verbose' or o == '-V':
1546 elif o == '--psfonts':
1548 elif o == '--warranty' or o == '-w':
1555 files = do_options ()
1556 if not files or len (files) > 1:
1562 basename = os.path.splitext (file)[0]
1563 basename = os.path.split (basename)[1]
1565 global process_cmd, format
1567 format = guess_format (files[0])
1570 if format == TEXINFO or format == HTML:
1572 if process_cmd == '':
1573 process_cmd = lilypond_binary \
1574 + ' --formats=%s --backend eps ' % formats
1577 process_cmd += string.join ([(' -I %s' % p)
1578 for p in include_path])
1580 ly.identify (sys.stderr)
1583 chunks = do_file (file)
1584 if psfonts_p and invokes_lilypond ():
1585 fontextract.verbose = verbose_p
1586 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1590 psfonts_file = basename + '.psfonts'
1592 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1593 fontextract.extract_fonts (psfonts_file,
1594 [x.basename() + '.eps'
1595 for x in snippet_chunks])
1599 except Compile_error:
1602 if format == TEXINFO or format == LATEX:
1604 ly.warning (_ ("option --psfonts not used"))
1605 ly.warning (_ ("processing with dvips will have no fonts"))
1607 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1608 output = os.path.join (output_name, basename + '.dvi' )
1611 ly.progress (_ ("DVIPS usage:"))
1613 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1616 if __name__ == '__main__':