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 + '.eps')
961 page_count = ly.ps_page_count (base + '.eps')
964 ok = ok and os.path.exists (base + '.png')
966 for a in range (1, page_count + 1):
967 ok = ok and os.path.exists (base + '-page%d.png' % a)
971 def texstr_is_outdated (self):
975 base = self.basename ()
976 ok = self.ly_is_outdated ()
977 ok = ok and (os.path.exists (base + '.texstr'))
980 def filter_text (self):
981 code = self.substring ('code')
982 s = run_filter (code)
985 'options': self.match.group ('options')
988 return output[self.format][FILTER] % d
990 def replacement_text (self):
991 func = Lilypond_snippet.__dict__['output_' + self.format]
994 def get_images (self):
995 base = self.basename ()
997 single = '%(base)s.png' % vars ()
998 multiple = '%(base)s-page1.png' % vars ()
1000 if os.path.exists (multiple) \
1001 and (not os.path.exists (single) \
1002 or (os.stat (multiple)[stat.ST_MTIME] \
1003 > os.stat (single)[stat.ST_MTIME])):
1004 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1005 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1006 images = tuple (images)
1009 def output_html (self):
1011 base = self.basename ()
1013 str += self.output_print_filename (HTML)
1014 if VERBATIM in self.option_dict:
1015 verb = verbatim_html (self.substring ('code'))
1016 str += write (output[HTML][VERBATIM] % vars ())
1017 if QUOTE in self.option_dict:
1018 str = output[HTML][QUOTE] % vars ()
1020 str += output[HTML][BEFORE] % vars ()
1021 for image in self.get_images ():
1022 (base, ext) = os.path.splitext (image)
1023 alt = self.option_dict[ALT]
1024 str += output[HTML][OUTPUT] % vars ()
1025 str += output[HTML][AFTER] % vars ()
1028 def output_info (self):
1030 for image in self.get_images ():
1031 (base, ext) = os.path.splitext (image)
1033 # URG, makeinfo implicitly prepends dot to extension.
1034 # Specifying no extension is most robust.
1036 alt = self.option_dict[ALT]
1037 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1039 base = self.basename ()
1040 str += output[format][OUTPUT] % vars ()
1043 def output_latex (self):
1045 base = self.basename ()
1047 str += self.output_print_filename (LATEX)
1048 if VERBATIM in self.option_dict:
1049 verb = self.substring ('code')
1050 str += (output[LATEX][VERBATIM] % vars ())
1051 if QUOTE in self.option_dict:
1052 str = output[LATEX][QUOTE] % vars ()
1054 str += (output[LATEX][OUTPUT] % vars ())
1057 def output_print_filename (self, format):
1059 if PRINTFILENAME in self.option_dict:
1060 base = self.basename ()
1061 filename = self.substring ('filename')
1062 str = output[format][PRINTFILENAME] % vars ()
1066 def output_texinfo (self):
1068 if self.output_print_filename (TEXINFO):
1070 + self.output_print_filename (HTML)
1073 + self.output_print_filename (LATEX)
1075 base = self.basename ()
1076 if TEXIDOC in self.option_dict:
1077 texidoc = base + '.texidoc'
1078 if os.path.exists (texidoc):
1079 str += '@include %(texidoc)s\n\n' % vars ()
1081 if VERBATIM in self.option_dict:
1082 verb = verbatim_texinfo (self.substring ('code'))
1083 str += (output[TEXINFO][VERBATIM] % vars ())
1084 if not QUOTE in self.option_dict:
1085 str = output[TEXINFO][NOQUOTE] % vars ()
1087 str += self.output_info ()
1089 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1090 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1091 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1093 if QUOTE in self.option_dict:
1094 str = output[TEXINFO][QUOTE] % vars ()
1096 # need par after image
1101 class Lilypond_file_snippet (Lilypond_snippet):
1103 name = self.substring ('filename')
1104 return '\\renameinput \"%s\"\n%s' \
1105 % (name, open (find_file (name)).read ())
1107 snippet_type_to_class = {
1108 'lilypond_file': Lilypond_file_snippet,
1109 'lilypond_block': Lilypond_snippet,
1110 'lilypond': Lilypond_snippet,
1111 'include': Include_snippet,
1114 def find_linestarts (s):
1119 i = s.find ('\n', start)
1127 nls.append (len (s))
1130 def find_toplevel_snippets (s, types):
1133 res[i] = ly.re.compile (snippet_res[format][i])
1137 ## found = dict (map (lambda x: (x, None),
1141 map (lambda x, f = found: f.setdefault (x, None),
1144 line_starts = find_linestarts (s)
1146 # We want to search for multiple regexes, without searching
1147 # the string multiple times for one regex.
1148 # Hence, we use earlier results to limit the string portion
1150 # Since every part of the string is traversed at most once for
1151 # every type of snippet, this is linear.
1157 if not found[type] or found[type][0] < index:
1159 m = res[type].search (s[index:endex])
1164 if snippet_type_to_class.has_key (type):
1165 cl = snippet_type_to_class[type]
1168 start = index + m.start ('match')
1169 line_number = line_start_idx
1170 while (line_starts[line_number] < start):
1174 snip = cl (type, m, format, line_number)
1175 found[type] = (start, snip)
1179 or found[type][0] < found[first][0]):
1184 # Limiting the search space is a cute
1185 # idea, but this *requires* to search
1186 # for possible containing blocks
1187 # first, at least as long as we do not
1188 # search for the start of blocks, but
1189 # always/directly for the entire
1190 # @block ... @end block.
1192 endex = found[first][0]
1195 snippets.append (Substring (s, index, len (s), line_start_idx))
1198 while (start > line_starts[line_start_idx+1]):
1201 (start, snip) = found[first]
1202 snippets.append (Substring (s, index, start, line_start_idx + 1))
1203 snippets.append (snip)
1205 index = start + len (snip.match.group ('match'))
1209 def filter_pipe (input, cmd):
1211 ly.progress (_ ("Opening filter `%s'") % cmd)
1213 (stdin, stdout, stderr) = os.popen3 (cmd)
1215 status = stdin.close ()
1219 output = stdout.read ()
1220 status = stdout.close ()
1221 error = stderr.read ()
1225 signal = 0x0f & status
1226 if status or (not output and error):
1227 exit_status = status >> 8
1228 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1229 ly.error (_ ("The error log is as follows:"))
1230 sys.stderr.write (error)
1231 sys.stderr.write (stderr.read ())
1240 return filter_pipe (s, filter_cmd)
1242 def is_derived_class (cl, baseclass):
1245 for b in cl.__bases__:
1246 if is_derived_class (b, baseclass):
1250 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1251 ly_names = filter (lambda x: x,
1252 map (Lilypond_snippet.basename, ly_snippets))
1253 texstr_names = filter (lambda x: x,
1254 map (Lilypond_snippet.basename, texstr_snippets))
1255 png_names = filter (lambda x: x,
1256 map (Lilypond_snippet.basename, png_snippets))
1259 def my_system (cmd):
1260 status = ly.system (cmd,
1261 ignore_error = 1, progress_p = 1)
1264 ly.error ('Process %s exited unsuccessfully.' % cmd)
1268 # the --process=CMD switch is a bad idea
1269 # it is too generic for lilypond-book.
1270 if texstr_names and invokes_lilypond:
1271 my_system (string.join ([cmd, '--backend texstr',
1272 'snippet-map.ly'] + texstr_names))
1273 for l in texstr_names:
1274 my_system ('latex %s.texstr' % l)
1277 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1279 LATEX_DOCUMENT = r'''
1282 \typeout{textwidth=\the\textwidth}
1283 \typeout{columnsep=\the\columnsep}
1284 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1288 # Do we need anything else besides `textwidth'?
1289 def get_latex_textwidth (source):
1290 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1291 preamble = source[:m.start (0)]
1292 latex_document = LATEX_DOCUMENT % vars ()
1293 # Workaround problems with unusable $TMP on Cygwin:
1294 tempfile.tempdir = ''
1295 tmpfile = tempfile.mktemp('.tex')
1296 cmd = latex_filter_cmd % vars ()
1297 parameter_string = filter_pipe (latex_document, cmd)
1300 m = re.search ('columns=([0-9.]*)', parameter_string)
1302 columns = string.atoi (m.group (1))
1305 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1307 columnsep = string.atof (m.group (1))
1310 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1312 textwidth = string.atof (m.group (1))
1314 textwidth = (textwidth - columnsep) / columns
1326 '.texinfo': TEXINFO,
1332 # TEXINFO: '.texinfo',
1337 class Compile_error:
1340 def write_file_map (lys, name):
1341 snippet_map = open ('snippet-map.ly', 'w')
1342 snippet_map.write ("""
1343 #(define version-seen? #t)
1344 #(ly:add-file-name-alist '(
1347 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1353 snippet_map.write ('))\n')
1355 def do_process_cmd (chunks, input_name):
1356 all_lys = filter (lambda x: is_derived_class (x.__class__,
1360 write_file_map (all_lys, input_name)
1362 filter (lambda x: is_derived_class (x.__class__,
1364 and x.ly_is_outdated (),
1367 filter (lambda x: is_derived_class (x.__class__,
1369 and x.texstr_is_outdated (),
1372 filter (lambda x: is_derived_class (x.__class__,
1374 and x.png_is_outdated (),
1377 ly.progress (_ ("Writing snippets..."))
1378 map (Lilypond_snippet.write_ly, ly_outdated)
1382 ly.progress (_ ("Processing..."))
1384 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1386 ly.progress (_ ("All snippets are up to date..."))
1389 def guess_format (input_filename):
1391 e = os.path.splitext (input_filename)[1]
1392 if e in ext2format.keys ():
1394 format = ext2format[e]
1396 ly.error (_ ("can't determine format for: %s" \
1401 def write_if_updated (file_name, lines):
1403 f = open (file_name)
1405 new_str = string.join (lines, '')
1406 if oldstr == new_str:
1407 ly.progress (_ ("%s is up to date.") % file_name)
1413 ly.progress (_ ("Writing `%s'...") % file_name)
1414 open (file_name, 'w').writelines (lines)
1417 def do_file (input_filename):
1419 if not input_filename or input_filename == '-':
1420 in_handle = sys.stdin
1421 input_fullname = '<stdin>'
1423 if os.path.exists (input_filename):
1424 input_fullname = input_filename
1425 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1426 # urg python interface to libkpathsea?
1427 input_fullname = ly.read_pipe ('kpsewhich '
1428 + input_filename)[:-1]
1430 input_fullname = find_file (input_filename)
1431 in_handle = open (input_fullname)
1433 if input_filename == '-':
1434 input_base = 'stdin'
1436 input_base = os.path.basename \
1437 (os.path.splitext (input_filename)[0])
1439 # Only default to stdout when filtering.
1440 if output_name == '-' or (not output_name and filter_cmd):
1441 output_filename = '-'
1442 output_file = sys.stdout
1444 # don't complain when output_name is existing
1445 output_filename = input_base + format2ext[format]
1447 if not os.path.isdir (output_name):
1448 os.mkdir (output_name, 0777)
1449 os.chdir (output_name)
1451 if os.path.exists (input_filename) \
1452 and os.path.exists (output_filename) \
1453 and os.path.samefile (output_filename, input_fullname):
1455 _ ("Output would overwrite input file; use --output."))
1459 ly.progress (_ ("Reading %s...") % input_fullname)
1460 source = in_handle.read ()
1463 set_default_options (source)
1466 # FIXME: Containing blocks must be first, see
1467 # find_toplevel_snippets.
1469 'multiline_comment',
1473 'singleline_comment',
1478 ly.progress (_ ("Dissecting..."))
1479 chunks = find_toplevel_snippets (source, snippet_types)
1483 write_if_updated (output_filename,
1484 [c.filter_text () for c in chunks])
1486 do_process_cmd (chunks, input_fullname)
1487 ly.progress (_ ("Compiling %s...") % output_filename)
1489 write_if_updated (output_filename,
1490 [s.replacement_text ()
1493 def process_include (snippet):
1494 os.chdir (original_dir)
1495 name = snippet.substring ('filename')
1496 ly.progress (_ ("Processing include: %s") % name)
1498 return do_file (name)
1500 include_chunks = map (process_include,
1501 filter (lambda x: is_derived_class (x.__class__,
1506 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1508 except Compile_error:
1509 os.chdir (original_dir)
1510 ly.progress (_ ("Removing `%s'") % output_filename)
1515 global format, output_name, psfonts_p
1516 global filter_cmd, process_cmd, verbose_p
1518 (sh, long) = ly.getopt_args (option_definitions)
1520 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1521 except getopt.error, s:
1522 sys.stderr.write ('\n')
1523 ly.error (_ ("getopt says: `%s'" % s))
1524 sys.stderr.write ('\n')
1534 elif o == '--filter' or o == '-F':
1537 elif o == '--format' or o == '-f':
1539 if a == 'texi-html' or a == 'texi':
1541 elif o == '--tex-backend ':
1543 elif o == '--help' or o == '-h':
1546 elif o == '--include' or o == '-I':
1547 include_path.append (os.path.join (original_dir,
1548 os.path.abspath (a)))
1549 elif o == '--output' or o == '-o':
1551 elif o == '--process' or o == '-P':
1554 elif o == '--version' or o == '-v':
1555 ly.identify (sys.stdout)
1557 elif o == '--verbose' or o == '-V':
1559 elif o == '--psfonts':
1561 elif o == '--warranty' or o == '-w':
1568 files = do_options ()
1569 if not files or len (files) > 1:
1575 basename = os.path.splitext (file)[0]
1576 basename = os.path.split (basename)[1]
1578 global process_cmd, format
1580 format = guess_format (files[0])
1583 if format == TEXINFO or format == HTML:
1585 if process_cmd == '':
1586 process_cmd = lilypond_binary \
1587 + ' --formats=%s --backend eps ' % formats
1590 process_cmd += string.join ([(' -I %s' % p)
1591 for p in include_path])
1593 ly.identify (sys.stderr)
1596 chunks = do_file (file)
1597 if psfonts_p and invokes_lilypond ():
1598 fontextract.verbose = verbose_p
1599 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1603 psfonts_file = basename + '.psfonts'
1605 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1606 fontextract.extract_fonts (psfonts_file,
1607 [x.basename() + '.eps'
1608 for x in snippet_chunks])
1612 except Compile_error:
1615 if format == TEXINFO or format == LATEX:
1617 ly.warning (_ ("option --psfonts not used"))
1618 ly.warning (_ ("processing with dvips will have no fonts"))
1620 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1621 output = os.path.join (output_name, basename + '.dvi' )
1624 ly.progress (_ ("DVIPS usage:"))
1626 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1629 if __name__ == '__main__':