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'
122 default_ly_options = { 'alt': "[image of music]" }
125 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
129 EXAMPLEINDENT = 'exampleindent'
131 FRAGMENT = 'fragment'
136 LINEWIDTH = 'linewidth'
137 NOFRAGMENT = 'nofragment'
138 NOINDENT = 'noindent'
143 OUTPUTIMAGE = 'outputimage'
146 PREAMBLE = 'preamble'
147 PRINTFILENAME = 'printfilename'
149 RAGGEDRIGHT = 'raggedright'
150 RELATIVE = 'relative'
151 STAFFSIZE = 'staffsize'
154 VERBATIM = 'verbatim'
155 FONTLOAD = 'fontload'
156 FILENAME = 'filename'
160 # NOTIME has no opposite so it isn't part of this dictionary.
161 # NOQUOTE is used internally only.
163 NOFRAGMENT: FRAGMENT,
168 # Recognize special sequences in the input.
170 # (?P<name>regex) -- Assign result of REGEX to NAME.
171 # *? -- Match non-greedily.
172 # (?m) -- Multiline regex: Make ^ and $ match at each line.
173 # (?s) -- Make the dot match all characters including newline.
174 # (?x) -- Ignore whitespace in patterns.
186 (\s*(?P<options>.*?)\s*:)?\s*
194 \s*(?P<options>.*?)\s*
203 \s*(?P<options>.*?)\s*
205 \s*(?P<filename>.*?)\s*
212 (?P<code><!--\s.*?!-->)
215 'singleline_comment':
221 (?P<code><pre>.*?</pre>))''',
227 (?P<code><pre>\s.*?</pre>\s))''',
246 \s*(?P<options>.*?)\s*
257 \s*(?P<options>.*?)\s*
261 \\end\s*{lilypond})''',
269 \s*(?P<options>.*?)\s*
277 'singleline_comment':
300 \\end\s*{verbatim}))''',
309 (?P<filename>\S+))''',
313 ^[^\n]*?(?!@c\s+)[^\n]*?
317 \s*(?P<options>.*?)\s*
327 \s*(?P<options>.*?)\s*
330 ^@end\s+lilypond)\s''',
337 \s*(?P<options>.*?)\s*
348 @end\s+ignore))\s''',
350 'singleline_comment':
355 @c([ \t][^\n]*|)\n))''',
357 # Don't do this: It interferes with @code{@{}.
358 # 'verb': r'''(?P<code>@code{.*?})''',
366 @end\s+example\s))''',
372 'intertext': r',?\s*intertext=\".*?\"',
377 'intertext': r',?\s*intertext=\".*?\"',
378 'option_sep': '\s*,\s*',
382 'intertext': r',?\s*intertext=\".*?\"',
383 'option_sep': '\s*,\s*',
387 # Options without a pattern in ly_options.
404 RELATIVE: r'''\relative c%(relative_quotes)s''',
409 INDENT: r'''indent = %(indent)s''',
411 LINEWIDTH: r'''linewidth = %(linewidth)s''',
413 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
415 RAGGEDRIGHT: r'''raggedright = ##t''',
417 PACKED: r'''packed = ##t''',
429 \remove Time_signature_engraver
435 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
442 FILTER: r'''<lilypond %(options)s>
452 <a href="%(base)s.ly">''',
455 <img align="center" valign="center"
456 border="0" src="%(image)s" alt="%(alt)s">''',
458 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
460 QUOTE: r'''<blockquote>
474 \ifx\preLilyPondExample \undefined
479 \def\lilypondbook{}%%
480 \input %(base)s-systems.tex
481 \ifx\postLilyPondExample \undefined
488 PRINTFILENAME: '''\\texttt{%(filename)s}
491 QUOTE: r'''\begin{quotation}
496 VERBATIM: r'''\noindent
498 %(verb)s\end{verbatim}
501 FILTER: r'''\begin{lilypond}[%(options)s]
508 FILTER: r'''@lilypond[%(options)s]
514 @include %(base)s-systems.texi
518 OUTPUTIMAGE: r'''@noindent
520 @image{%(base)s,,,%(alt)s,%(ext)s}
524 <a href="%(base)s.ly">
525 <img align="center" valign="center"
526 border="0" src="%(image)s" alt="%(alt)s">
532 PRINTFILENAME: '''@file{%(filename)s}
535 QUOTE: r'''@quotation
536 %(str)s@end quotation
543 VERBATIM: r'''@exampleindent 0
550 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
551 %%%% Options: [%(option_string)s]
553 #(set! toplevel-score-handler print-score-with-defaults)
554 #(set! toplevel-music-handler (lambda (p m)
555 (print-score-with-defaults
556 p (scorify-music m p))))
558 #(ly:set-option (quote no-point-and-click))
559 #(define inside-lilypond-book #t)
560 #(define version-seen? #t)
568 %% ****************************************************************
569 %% Start cut-&-pastable-section
570 %% ****************************************************************
573 #(define dump-extents #t)
574 %(font_dump_setting)s
588 %% ****************************************************************
589 %% ly snippet contents follows:
590 %% ****************************************************************
594 %% ****************************************************************
596 %% ****************************************************************
603 %% ****************************************************************
605 %% ****************************************************************
609 %% ****************************************************************
611 %% ****************************************************************
614 texinfo_linewidths = {
615 '@afourpaper': '160\\mm',
616 '@afourwide': '6.5\\in',
617 '@afourlatex': '150\\mm',
618 '@smallbook': '5\\in',
619 '@letterpaper': '6\\in',
622 def classic_lilypond_book_compatibility (key, value):
623 if key == 'singleline' and value == None:
624 return (RAGGEDRIGHT, None)
626 m = re.search ('relative\s*([-0-9])', key)
628 return ('relative', m.group (1))
630 m = re.match ('([0-9]+)pt', key)
632 return ('staffsize', m.group (1))
634 if key == 'indent' or key == 'linewidth':
635 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
637 f = float (m.group (1))
638 return (key, '%f\\%s' % (f, m.group (2)))
642 def find_file (name):
643 for i in include_path:
644 full = os.path.join (i, name)
645 if os.path.exists (full):
647 ly.error (_ ("file not found: %s") % name + '\n')
651 def verbatim_html (s):
652 return re.sub ('>', '>',
654 re.sub ('&', '&', s)))
656 def verbatim_texinfo (s):
657 return re.sub ('{', '@{',
659 re.sub ('@', '@@', s)))
661 def split_options (option_string):
664 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
665 for i in range(len(options)):
666 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
669 return re.split (format_res[format]['option_sep'],
673 def invokes_lilypond ():
674 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
676 def set_default_options (source):
677 global default_ly_options
678 if not default_ly_options.has_key (LINEWIDTH):
680 textwidth = get_latex_textwidth (source)
681 default_ly_options[LINEWIDTH] = \
682 '''%.0f\\pt''' % textwidth
683 elif format == TEXINFO:
684 for (k, v) in texinfo_linewidths.items ():
685 # FIXME: @layout is usually not in
688 # \input texinfo @c -*-texinfo-*-
690 # Bluntly search first K items of
692 # s = chunks[0].replacement_text ()
693 if re.search (k, source[:1024]):
694 default_ly_options[LINEWIDTH] = v
698 def replacement_text (self):
701 def filter_text (self):
702 return self.replacement_text ()
704 def ly_is_outdated (self):
707 def png_is_outdated (self):
710 class Substring (Chunk):
711 def __init__ (self, source, start, end, line_number):
715 self.line_number = line_number
716 self.override_text = None
718 def replacement_text (self):
719 if self.override_text:
720 return self.override_text
722 return self.source[self.start:self.end]
724 class Snippet (Chunk):
725 def __init__ (self, type, match, format, line_number):
729 self.option_dict = {}
731 self.line_number = line_number
733 def replacement_text (self):
734 return self.match.group ('match')
736 def substring (self, s):
737 return self.match.group (s)
740 return `self.__class__` + ' type = ' + self.type
742 class Include_snippet (Snippet):
743 def processed_filename (self):
744 f = self.substring ('filename')
745 return os.path.splitext (f)[0] + format2ext[format]
747 def replacement_text (self):
748 s = self.match.group ('match')
749 f = self.substring ('filename')
751 return re.sub (f, self.processed_filename (), s)
753 class Lilypond_snippet (Snippet):
754 def __init__ (self, type, match, format, line_number):
755 Snippet.__init__ (self, type, match, format, line_number)
756 os = match.group ('options')
757 self.do_options (os, self.type)
760 return self.substring ('code')
765 return self.compose_ly (s)
768 def do_options (self, option_string, type):
769 self.option_dict = {}
771 options = split_options (option_string)
774 if string.find (i, '=') > 0:
775 (key, value) = re.split ('\s*=\s*', i)
776 self.option_dict[key] = value
778 if i in no_options.keys ():
779 if no_options[i] in self.option_dict.keys ():
780 del self.option_dict[no_options[i]]
782 self.option_dict[i] = None
784 has_linewidth = self.option_dict.has_key (LINEWIDTH)
785 no_linewidth_value = 0
787 # If LINEWIDTH is used without parameter, set it to default.
788 if has_linewidth and self.option_dict[LINEWIDTH] == None:
789 no_linewidth_value = 1
790 del self.option_dict[LINEWIDTH]
792 for i in default_ly_options.keys ():
793 if i not in self.option_dict.keys ():
794 self.option_dict[i] = default_ly_options[i]
796 if not has_linewidth:
797 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
798 self.option_dict[RAGGEDRIGHT] = None
800 if type == 'lilypond':
801 if LINEWIDTH in self.option_dict.keys ():
802 del self.option_dict[LINEWIDTH]
804 if RAGGEDRIGHT in self.option_dict.keys ():
805 if LINEWIDTH in self.option_dict.keys ():
806 del self.option_dict[LINEWIDTH]
808 if QUOTE in self.option_dict.keys () or type == 'lilypond':
809 if LINEWIDTH in self.option_dict.keys ():
810 del self.option_dict[LINEWIDTH]
812 if not INDENT in self.option_dict.keys ():
813 self.option_dict[INDENT] = '0\\mm'
815 # The QUOTE pattern from ly_options only emits the `linewidth'
817 if has_linewidth and QUOTE in self.option_dict.keys ():
818 if no_linewidth_value:
819 del self.option_dict[LINEWIDTH]
821 del self.option_dict[QUOTE]
823 def compose_ly (self, code):
824 if FRAGMENT in self.option_dict.keys ():
832 # The original concept of the `exampleindent' option is broken.
833 # It is not possible to get a sane value for @exampleindent at all
834 # without processing the document itself. Saying
842 # causes ugly results with the DVI backend of texinfo since the
843 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
844 # value). Executing the above code changes the environment
845 # indentation to an unknown value because we don't know the amount
846 # of 1em in advance since it is font-dependent. Modifying
847 # @exampleindent in the middle of a document is simply not
848 # supported within texinfo.
850 # As a consequence, the only function of @exampleindent is now to
851 # specify the amount of indentation for the `quote' option.
853 # To set @exampleindent locally to zero, we use the @format
854 # environment for non-quoted snippets.
855 override[EXAMPLEINDENT] = r'0.4\in'
856 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
857 override.update (default_ly_options)
860 for (key, value) in self.option_dict.items ():
862 option_list.append (key)
864 option_list.append (key + '=' + value)
865 option_string = string.join (option_list, ',')
868 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
869 for a in compose_types:
872 for (key, value) in self.option_dict.items ():
874 classic_lilypond_book_compatibility (key, value)
878 (_ ("deprecated ly-option used: %s=%s" \
881 (_ ("compatibility mode translation: %s=%s" \
885 (_ ("deprecated ly-option used: %s" \
888 (_ ("compatibility mode translation: %s" \
891 (key, value) = (c_key, c_value)
894 override[key] = value
896 if not override.has_key (key):
900 for type in compose_types:
901 if ly_options[type].has_key (key):
902 compose_dict[type].append (ly_options[type][key])
906 if not found and key not in simple_options:
907 ly.warning (_ ("ignoring unknown ly option: %s") % key)
910 if RELATIVE in override.keys () and override[RELATIVE]:
911 relative = string.atoi (override[RELATIVE])
917 relative_quotes += ',' * (- relative)
919 relative_quotes += "'" * relative
921 program_name = __main__.program_name
923 paper_string = string.join (compose_dict[PAPER],
925 layout_string = string.join (compose_dict[LAYOUT],
927 notes_string = string.join (compose_dict[NOTES],
929 preamble_string = string.join (compose_dict[PREAMBLE],
932 font_dump_setting = ''
933 if FONTLOAD in self.option_dict:
934 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
936 return (PREAMBLE_LY + body) % vars ()
941 self.hash = abs (hash (self.full_ly ()))
945 if FILENAME in self.option_dict:
946 return self.option_dict[FILENAME]
948 return 'lily-%d' % self.get_hash ()
952 outf = open (self.basename () + '.ly', 'w')
953 outf.write (self.full_ly ())
955 open (self.basename () + '.txt', 'w').write ('image of music')
957 def ly_is_outdated (self):
958 base = self.basename ()
960 tex_file = '%s.tex' % base
961 eps_file = '%s.eps' % base
962 system_file = '%s-systems.tex' % base
963 ly_file = '%s.ly' % base
964 ok = os.path.exists (ly_file) \
965 and os.path.exists (system_file)\
966 and os.stat (system_file)[stat.ST_SIZE] \
967 and re.match ('% eof', open (system_file).readlines ()[-1])
968 if ok and (not use_hash_p or FILENAME in self.option_dict):
969 ok = (self.full_ly () == open (ly_file).read ())
971 # TODO: Do something smart with target formats
972 # (ps, png) and m/ctimes.
976 def png_is_outdated (self):
977 base = self.basename ()
978 ok = self.ly_is_outdated ()
979 if format == HTML or format == TEXINFO:
980 ok = ok and os.path.exists (base + '.eps')
984 page_count = ly.ps_page_count (base + '.eps')
987 ok = ok and os.path.exists (base + '.png')
989 for a in range (1, page_count + 1):
990 ok = ok and os.path.exists (base + '-page%d.png' % a)
994 def texstr_is_outdated (self):
998 base = self.basename ()
999 ok = self.ly_is_outdated ()
1000 ok = ok and (os.path.exists (base + '.texstr'))
1003 def filter_text (self):
1004 code = self.substring ('code')
1005 s = run_filter (code)
1008 'options': self.match.group ('options')
1011 return output[self.format][FILTER] % d
1013 def replacement_text (self):
1014 func = Lilypond_snippet.__dict__['output_' + self.format]
1017 def get_images (self):
1018 base = self.basename ()
1020 single = '%(base)s.png' % vars ()
1021 multiple = '%(base)s-page1.png' % vars ()
1023 if os.path.exists (multiple) \
1024 and (not os.path.exists (single) \
1025 or (os.stat (multiple)[stat.ST_MTIME] \
1026 > os.stat (single)[stat.ST_MTIME])):
1027 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1028 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1029 images = tuple (images)
1032 def output_html (self):
1034 base = self.basename ()
1036 str += self.output_print_filename (HTML)
1037 if VERBATIM in self.option_dict:
1038 verb = verbatim_html (self.substring ('code'))
1039 str += write (output[HTML][VERBATIM] % vars ())
1040 if QUOTE in self.option_dict:
1041 str = output[HTML][QUOTE] % vars ()
1043 str += output[HTML][BEFORE] % vars ()
1044 for image in self.get_images ():
1045 (base, ext) = os.path.splitext (image)
1046 alt = self.option_dict[ALT]
1047 str += output[HTML][OUTPUT] % vars ()
1048 str += output[HTML][AFTER] % vars ()
1051 def output_info (self):
1053 for image in self.get_images ():
1054 (base, ext) = os.path.splitext (image)
1056 # URG, makeinfo implicitly prepends dot to extension.
1057 # Specifying no extension is most robust.
1059 alt = self.option_dict[ALT]
1060 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1062 base = self.basename ()
1063 str += output[format][OUTPUT] % vars ()
1066 def output_latex (self):
1068 base = self.basename ()
1070 str += self.output_print_filename (LATEX)
1071 if VERBATIM in self.option_dict:
1072 verb = self.substring ('code')
1073 str += (output[LATEX][VERBATIM] % vars ())
1075 str += (output[LATEX][OUTPUT] % vars ())
1076 if QUOTE in self.option_dict:
1077 str = output[LATEX][QUOTE] % vars ()
1080 def output_print_filename (self, format):
1082 if PRINTFILENAME in self.option_dict:
1083 base = self.basename ()
1084 filename = self.substring ('filename')
1085 str = output[format][PRINTFILENAME] % vars ()
1089 def output_texinfo (self):
1091 if self.output_print_filename (TEXINFO):
1093 + self.output_print_filename (HTML)
1096 + self.output_print_filename (LATEX)
1098 base = self.basename ()
1099 if TEXIDOC in self.option_dict:
1100 texidoc = base + '.texidoc'
1101 if os.path.exists (texidoc):
1102 str += '@include %(texidoc)s\n\n' % vars ()
1104 if VERBATIM in self.option_dict:
1105 verb = verbatim_texinfo (self.substring ('code'))
1106 str += (output[TEXINFO][VERBATIM] % vars ())
1107 if not QUOTE in self.option_dict:
1108 str = output[TEXINFO][NOQUOTE] % vars ()
1110 str += self.output_info ()
1112 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1113 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1114 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1116 if QUOTE in self.option_dict:
1117 str = output[TEXINFO][QUOTE] % vars ()
1119 # need par after image
1124 class Lilypond_file_snippet (Lilypond_snippet):
1126 name = self.substring ('filename')
1127 return '\\renameinput \"%s\"\n%s' \
1128 % (name, open (find_file (name)).read ())
1130 snippet_type_to_class = {
1131 'lilypond_file': Lilypond_file_snippet,
1132 'lilypond_block': Lilypond_snippet,
1133 'lilypond': Lilypond_snippet,
1134 'include': Include_snippet,
1137 def find_linestarts (s):
1142 i = s.find ('\n', start)
1150 nls.append (len (s))
1153 def find_toplevel_snippets (s, types):
1156 res[i] = ly.re.compile (snippet_res[format][i])
1160 ## found = dict (map (lambda x: (x, None),
1164 map (lambda x, f = found: f.setdefault (x, None),
1167 line_starts = find_linestarts (s)
1169 # We want to search for multiple regexes, without searching
1170 # the string multiple times for one regex.
1171 # Hence, we use earlier results to limit the string portion
1173 # Since every part of the string is traversed at most once for
1174 # every type of snippet, this is linear.
1180 if not found[type] or found[type][0] < index:
1182 m = res[type].search (s[index:endex])
1187 if snippet_type_to_class.has_key (type):
1188 cl = snippet_type_to_class[type]
1191 start = index + m.start ('match')
1192 line_number = line_start_idx
1193 while (line_starts[line_number] < start):
1197 snip = cl (type, m, format, line_number)
1198 found[type] = (start, snip)
1202 or found[type][0] < found[first][0]):
1207 # Limiting the search space is a cute
1208 # idea, but this *requires* to search
1209 # for possible containing blocks
1210 # first, at least as long as we do not
1211 # search for the start of blocks, but
1212 # always/directly for the entire
1213 # @block ... @end block.
1215 endex = found[first][0]
1218 snippets.append (Substring (s, index, len (s), line_start_idx))
1221 while (start > line_starts[line_start_idx+1]):
1224 (start, snip) = found[first]
1225 snippets.append (Substring (s, index, start, line_start_idx + 1))
1226 snippets.append (snip)
1228 index = start + len (snip.match.group ('match'))
1232 def filter_pipe (input, cmd):
1234 ly.progress (_ ("Opening filter `%s'") % cmd)
1236 (stdin, stdout, stderr) = os.popen3 (cmd)
1238 status = stdin.close ()
1242 output = stdout.read ()
1243 status = stdout.close ()
1244 error = stderr.read ()
1248 signal = 0x0f & status
1249 if status or (not output and error):
1250 exit_status = status >> 8
1251 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1252 ly.error (_ ("The error log is as follows:"))
1253 sys.stderr.write (error)
1254 sys.stderr.write (stderr.read ())
1263 return filter_pipe (s, filter_cmd)
1265 def is_derived_class (cl, baseclass):
1268 for b in cl.__bases__:
1269 if is_derived_class (b, baseclass):
1273 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1274 ly_names = filter (lambda x: x,
1275 map (Lilypond_snippet.basename, ly_snippets))
1276 texstr_names = filter (lambda x: x,
1277 map (Lilypond_snippet.basename, texstr_snippets))
1278 png_names = filter (lambda x: x,
1279 map (Lilypond_snippet.basename, png_snippets))
1282 def my_system (cmd):
1283 status = ly.system (cmd,
1284 ignore_error = 1, progress_p = 1)
1287 ly.error ('Process %s exited unsuccessfully.' % cmd)
1291 # the --process=CMD switch is a bad idea
1292 # it is too generic for lilypond-book.
1293 if texstr_names and invokes_lilypond:
1294 my_system (string.join ([cmd, '--backend texstr',
1295 'snippet-map.ly'] + texstr_names))
1296 for l in texstr_names:
1297 my_system ('latex %s.texstr' % l)
1300 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1302 LATEX_INSPECTION_DOCUMENT = r'''
1306 \typeout{textwidth=\the\textwidth}
1307 \typeout{columnsep=\the\columnsep}
1308 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1312 # Do we need anything else besides `textwidth'?
1313 def get_latex_textwidth (source):
1314 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1315 preamble = source[:m.start (0)]
1316 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1317 # Workaround problems with unusable $TMP on Cygwin:
1318 tempfile.tempdir = ''
1319 tmpfile = tempfile.mktemp('.tex')
1320 logfile = os.path.splitext (tmpfile)[0] + '.log'
1321 open (tmpfile,'w').write (latex_document)
1322 ly.system ('latex %s' % tmpfile)
1323 parameter_string = open (logfile).read()
1328 m = re.search ('columns=([0-9.]*)', parameter_string)
1330 columns = string.atoi (m.group (1))
1333 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1335 columnsep = string.atof (m.group (1))
1338 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1340 textwidth = string.atof (m.group (1))
1342 textwidth = (textwidth - columnsep) / columns
1346 def modify_preamble (chunk):
1347 str = chunk.replacement_text ()
1348 if (re.search (r"\\begin{document}", str)
1349 and not re.search ("{graphic[sx]", str)):
1350 str = re.sub (r"\\begin{document}",
1351 r"\\RequirePackage{graphics}" + '\n'
1352 + r"\\begin{document}",
1354 chunk.override_text = str
1366 '.texinfo': TEXINFO,
1372 # TEXINFO: '.texinfo',
1377 class Compile_error:
1380 def write_file_map (lys, name):
1381 snippet_map = open ('snippet-map.ly', 'w')
1382 snippet_map.write ("""
1383 #(define version-seen? #t)
1384 #(ly:add-file-name-alist '(
1387 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1393 snippet_map.write ('))\n')
1395 def do_process_cmd (chunks, input_name):
1396 all_lys = filter (lambda x: is_derived_class (x.__class__,
1400 write_file_map (all_lys, input_name)
1402 filter (lambda x: is_derived_class (x.__class__,
1404 and x.ly_is_outdated (),
1407 filter (lambda x: is_derived_class (x.__class__,
1409 and x.texstr_is_outdated (),
1412 filter (lambda x: is_derived_class (x.__class__,
1414 and x.png_is_outdated (),
1417 ly.progress (_ ("Writing snippets..."))
1418 map (Lilypond_snippet.write_ly, ly_outdated)
1422 ly.progress (_ ("Processing..."))
1424 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1426 ly.progress (_ ("All snippets are up to date..."))
1429 def guess_format (input_filename):
1431 e = os.path.splitext (input_filename)[1]
1432 if e in ext2format.keys ():
1434 format = ext2format[e]
1436 ly.error (_ ("can't determine format for: %s" \
1441 def write_if_updated (file_name, lines):
1443 f = open (file_name)
1445 new_str = string.join (lines, '')
1446 if oldstr == new_str:
1447 ly.progress (_ ("%s is up to date.") % file_name)
1453 ly.progress (_ ("Writing `%s'...") % file_name)
1454 open (file_name, 'w').writelines (lines)
1457 def do_file (input_filename):
1459 if not input_filename or input_filename == '-':
1460 in_handle = sys.stdin
1461 input_fullname = '<stdin>'
1463 if os.path.exists (input_filename):
1464 input_fullname = input_filename
1465 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1466 # urg python interface to libkpathsea?
1467 input_fullname = ly.read_pipe ('kpsewhich '
1468 + input_filename)[:-1]
1470 input_fullname = find_file (input_filename)
1471 in_handle = open (input_fullname)
1473 if input_filename == '-':
1474 input_base = 'stdin'
1476 input_base = os.path.basename \
1477 (os.path.splitext (input_filename)[0])
1479 # Only default to stdout when filtering.
1480 if output_name == '-' or (not output_name and filter_cmd):
1481 output_filename = '-'
1482 output_file = sys.stdout
1484 # don't complain when output_name is existing
1485 output_filename = input_base + format2ext[format]
1487 if not os.path.isdir (output_name):
1488 os.mkdir (output_name, 0777)
1489 os.chdir (output_name)
1491 if os.path.exists (input_filename) \
1492 and os.path.exists (output_filename) \
1493 and os.path.samefile (output_filename, input_fullname):
1495 _ ("Output would overwrite input file; use --output."))
1499 ly.progress (_ ("Reading %s...") % input_fullname)
1500 source = in_handle.read ()
1503 set_default_options (source)
1506 # FIXME: Containing blocks must be first, see
1507 # find_toplevel_snippets.
1509 'multiline_comment',
1513 'singleline_comment',
1518 ly.progress (_ ("Dissecting..."))
1519 chunks = find_toplevel_snippets (source, snippet_types)
1522 modify_preamble (chunks[0])
1528 write_if_updated (output_filename,
1529 [c.filter_text () for c in chunks])
1531 do_process_cmd (chunks, input_fullname)
1532 ly.progress (_ ("Compiling %s...") % output_filename)
1534 write_if_updated (output_filename,
1535 [s.replacement_text ()
1538 def process_include (snippet):
1539 os.chdir (original_dir)
1540 name = snippet.substring ('filename')
1541 ly.progress (_ ("Processing include: %s") % name)
1543 return do_file (name)
1545 include_chunks = map (process_include,
1546 filter (lambda x: is_derived_class (x.__class__,
1551 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1553 except Compile_error:
1554 os.chdir (original_dir)
1555 ly.progress (_ ("Removing `%s'") % output_filename)
1560 global format, output_name, psfonts_p
1561 global filter_cmd, process_cmd, verbose_p
1563 (sh, long) = ly.getopt_args (option_definitions)
1565 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1566 except getopt.error, s:
1567 sys.stderr.write ('\n')
1568 ly.error (_ ("getopt says: `%s'" % s))
1569 sys.stderr.write ('\n')
1579 elif o == '--filter' or o == '-F':
1582 elif o == '--format' or o == '-f':
1584 if a == 'texi-html' or a == 'texi':
1586 elif o == '--tex-backend ':
1588 elif o == '--help' or o == '-h':
1591 elif o == '--include' or o == '-I':
1592 include_path.append (os.path.join (original_dir,
1593 os.path.abspath (a)))
1594 elif o == '--output' or o == '-o':
1596 elif o == '--process' or o == '-P':
1599 elif o == '--version' or o == '-v':
1600 ly.identify (sys.stdout)
1602 elif o == '--verbose' or o == '-V':
1604 elif o == '--psfonts':
1606 elif o == '--warranty' or o == '-w':
1613 files = do_options ()
1614 if not files or len (files) > 1:
1620 basename = os.path.splitext (file)[0]
1621 basename = os.path.split (basename)[1]
1623 global process_cmd, format
1625 format = guess_format (files[0])
1628 if format == TEXINFO or format == HTML:
1630 if process_cmd == '':
1631 process_cmd = lilypond_binary \
1632 + ' --formats=%s --backend eps ' % formats
1635 process_cmd += string.join ([(' -I %s' % p)
1636 for p in include_path])
1638 ly.identify (sys.stderr)
1641 chunks = do_file (file)
1642 if psfonts_p and invokes_lilypond ():
1643 fontextract.verbose = verbose_p
1644 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1648 psfonts_file = basename + '.psfonts'
1650 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1651 fontextract.extract_fonts (psfonts_file,
1652 [x.basename() + '.eps'
1653 for x in snippet_chunks])
1657 except Compile_error:
1660 if format == TEXINFO or format == LATEX:
1662 ly.warning (_ ("option --psfonts not used"))
1663 ly.warning (_ ("processing with dvips will have no fonts"))
1665 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1666 output = os.path.join (output_name, basename + '.dvi' )
1669 ly.progress (_ ("DVIPS usage:"))
1671 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1674 if __name__ == '__main__':