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 -b ps?
19 * check latex parameters, twocolumn, multicolumn?
20 * use --png --ps --pdf for making images?
22 * Converting from lilypond-book source, substitute:
23 @mbinclude foo.itely -> @include foo.itely
33 # Users of python modules should include this snippet
34 # and customize variables below.
36 # We'll suffer this path initialization stuff as long as we don't install
37 # our python packages in <prefix>/lib/pythonX.Y (and don't kludge around
38 # it as we do with teTeX on Red Hat Linux: set some environment variables
39 # (PYTHONPATH) in `etc/profile').
41 # If set, LILYPONDPREFIX must take prevalence.
42 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
43 import getopt, os, sys
44 datadir = '@local_lilypond_datadir@'
45 if not os.path.isdir (datadir):
46 datadir = '@lilypond_datadir@'
47 if os.environ.has_key ('LILYPONDPREFIX'):
48 datadir = os.environ['LILYPONDPREFIX']
49 while datadir[-1] == os.sep:
52 sys.path.insert (0, os.path.join (datadir, 'python'))
55 #if __name__ == '__main__':
63 program_version = '@TOPLEVEL_VERSION@'
64 program_name = os.path.basename (sys.argv[0])
67 original_dir = os.getcwd ()
71 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
74 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
75 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
76 lilypond-book --process='lilypond -I include' BOOK
79 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
80 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
82 option_definitions = [
83 (_ ("FMT"), 'f', 'format',
84 _ ('''use output format FMT (texi [default], texi-html,
86 (_ ("FILTER"), 'F', 'filter',
87 _ ("pipe snippets through FILTER [convert-ly -n -]")),
89 _ ("print this help")),
90 (_ ("DIR"), 'I', 'include',
91 _ ("add DIR to include path")),
92 (_ ("DIR"), 'o', 'output',
93 _ ("write output to DIR")),
94 (_ ("COMMAND"), 'P', 'process',
95 _ ("process ly_files using COMMAND FILE...")),
96 (_('FILE'), '', 'psfonts',
97 _ ('''extract all PostScript fonts into FILE for LaTeX
98 must use this with dvips -h FILE''')),
102 _ ("print version information")),
103 ('', 'w', 'warranty',
104 _ ("show warranty and copyright")),
107 include_path = [ly.abspath (os.getcwd ())]
108 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
110 # Only use installed binary when we are installed too.
111 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
112 lilypond_binary = 'lilypond'
118 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
121 default_ly_options = { 'alt': "[image of music]" }
124 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
128 EXAMPLEINDENT = 'exampleindent'
130 FRAGMENT = 'fragment'
135 LINEWIDTH = 'linewidth'
136 NOFRAGMENT = 'nofragment'
137 NOINDENT = 'noindent'
142 OUTPUTIMAGE = 'outputimage'
145 PREAMBLE = 'preamble'
146 PRINTFILENAME = 'printfilename'
148 RAGGEDRIGHT = 'raggedright'
149 RELATIVE = 'relative'
150 STAFFSIZE = 'staffsize'
153 VERBATIM = 'verbatim'
154 FONTLOAD = 'fontload'
155 FILENAME = 'filename'
159 # NOTIME has no opposite so it isn't part of this dictionary.
160 # NOQUOTE is used internally only.
162 NOFRAGMENT: FRAGMENT,
167 # Recognize special sequences in the input.
169 # (?P<name>regex) -- Assign result of REGEX to NAME.
170 # *? -- Match non-greedily.
171 # (?m) -- Multiline regex: Make ^ and $ match at each line.
172 # (?s) -- Make the dot match all characters including newline.
173 # (?x) -- Ignore whitespace in patterns.
185 (\s*(?P<options>.*?)\s*:)?\s*
193 \s*(?P<options>.*?)\s*
202 \s*(?P<options>.*?)\s*
204 \s*(?P<filename>.*?)\s*
211 (?P<code><!--\s.*?!-->)
214 'singleline_comment':
220 (?P<code><pre>.*?</pre>))''',
226 (?P<code><pre>\s.*?</pre>\s))''',
245 \s*(?P<options>.*?)\s*
256 \s*(?P<options>.*?)\s*
260 \\end\s*{lilypond})''',
268 \s*(?P<options>.*?)\s*
276 'singleline_comment':
299 \\end\s*{verbatim}))''',
308 (?P<filename>\S+))''',
312 ^[^\n]*?(?!@c\s+)[^\n]*?
316 \s*(?P<options>.*?)\s*
326 \s*(?P<options>.*?)\s*
329 ^@end\s+lilypond)\s''',
336 \s*(?P<options>.*?)\s*
347 @end\s+ignore))\s''',
349 'singleline_comment':
354 @c([ \t][^\n]*|)\n))''',
356 # Don't do this: It interferes with @code{@{}.
357 # 'verb': r'''(?P<code>@code{.*?})''',
365 @end\s+example\s))''',
371 'intertext': r',?\s*intertext=\".*?\"',
376 'intertext': r',?\s*intertext=\".*?\"',
377 'option_sep': '\s*,\s*',
381 'intertext': r',?\s*intertext=\".*?\"',
382 'option_sep': '\s*,\s*',
386 # Options without a pattern in ly_options.
403 RELATIVE: r'''\relative c%(relative_quotes)s''',
408 INDENT: r'''indent = %(indent)s''',
410 LINEWIDTH: r'''linewidth = %(linewidth)s''',
412 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
414 RAGGEDRIGHT: r'''raggedright = ##t''',
416 PACKED: r'''packed = ##t''',
428 \remove Time_signature_engraver
434 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
441 FILTER: r'''<lilypond %(options)s>
451 <a href="%(base)s.ly">''',
454 <img align="center" valign="center"
455 border="0" src="%(image)s" alt="%(alt)s">''',
457 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
459 QUOTE: r'''<blockquote>
473 \ifx\preLilyPondExample \undefined
478 \def\lilypondbook{}%%
479 \input %(base)s-systems.tex
480 \ifx\postLilyPondExample \undefined
487 PRINTFILENAME: '''\\texttt{%(filename)s}
490 QUOTE: r'''\begin{quotation}
495 VERBATIM: r'''\noindent
497 %(verb)s\end{verbatim}
500 FILTER: r'''\begin{lilypond}[%(options)s]
507 FILTER: r'''@lilypond[%(options)s]
513 @include %(base)s-systems.texi
517 OUTPUTIMAGE: r'''@noindent
519 @image{%(base)s,,,%(alt)s,%(ext)s}
523 <a href="%(base)s.ly">
524 <img align="center" valign="center"
525 border="0" src="%(image)s" alt="%(alt)s">
531 PRINTFILENAME: '''@file{%(filename)s}
534 QUOTE: r'''@quotation
535 %(str)s@end quotation
542 VERBATIM: r'''@exampleindent 0
549 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
550 %%%% Options: [%(option_string)s]
552 #(set! toplevel-score-handler ly:parser-print-score)
553 #(set! toplevel-music-handler (lambda (p m)
554 (ly:parser-print-score
555 p (ly:music-scorify m p))))
557 #(define version-seen? #t)
561 #(define dump-extents #t)
562 %(font_dump_setting)s
574 %% ly snippet contents follows:
586 texinfo_linewidths = {
587 '@afourpaper': '160\\mm',
588 '@afourwide': '6.5\\in',
589 '@afourlatex': '150\\mm',
590 '@smallbook': '5\\in',
591 '@letterpaper': '6\\in',
594 def classic_lilypond_book_compatibility (key, value):
595 if key == 'singleline' and value == None:
596 return (RAGGEDRIGHT, None)
598 m = re.search ('relative\s*([-0-9])', key)
600 return ('relative', m.group (1))
602 m = re.match ('([0-9]+)pt', key)
604 return ('staffsize', m.group (1))
606 if key == 'indent' or key == 'linewidth':
607 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
609 f = float (m.group (1))
610 return (key, '%f\\%s' % (f, m.group (2)))
614 def find_file (name):
615 for i in include_path:
616 full = os.path.join (i, name)
617 if os.path.exists (full):
619 ly.error (_ ("file not found: %s") % name + '\n')
623 def verbatim_html (s):
624 return re.sub ('>', '>',
626 re.sub ('&', '&', s)))
628 def verbatim_texinfo (s):
629 return re.sub ('{', '@{',
631 re.sub ('@', '@@', s)))
633 def split_options (option_string):
636 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
637 for i in range(len(options)):
638 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
641 return re.split (format_res[format]['option_sep'],
646 def replacement_text (self):
649 def filter_text (self):
650 return self.replacement_text ()
652 def ly_is_outdated (self):
655 def png_is_outdated (self):
658 class Substring (Chunk):
659 def __init__ (self, source, start, end, line_number):
663 self.line_number = line_number
665 def replacement_text (self):
666 return self.source[self.start:self.end]
668 class Snippet (Chunk):
669 def __init__ (self, type, match, format, line_number):
673 self.option_dict = {}
675 self.line_number = line_number
677 def replacement_text (self):
678 return self.match.group ('match')
680 def substring (self, s):
681 return self.match.group (s)
684 return `self.__class__` + ' type = ' + self.type
686 class Include_snippet (Snippet):
687 def processed_filename (self):
688 f = self.substring ('filename')
689 return os.path.splitext (f)[0] + format2ext[format]
691 def replacement_text (self):
692 s = self.match.group ('match')
693 f = self.substring ('filename')
695 return re.sub (f, self.processed_filename (), s)
697 class Lilypond_snippet (Snippet):
698 def __init__ (self, type, match, format, line_number):
699 Snippet.__init__ (self, type, match, format, line_number)
700 os = match.group ('options')
701 self.do_options (os, self.type)
704 return self.substring ('code')
709 return self.compose_ly (s)
712 def do_options (self, option_string, type):
713 self.option_dict = {}
715 options = split_options (option_string)
718 if string.find (i, '=') > 0:
719 (key, value) = re.split ('\s*=\s*', i)
720 self.option_dict[key] = value
722 if i in no_options.keys ():
723 if no_options[i] in self.option_dict.keys ():
724 del self.option_dict[no_options[i]]
726 self.option_dict[i] = None
728 has_linewidth = self.option_dict.has_key (LINEWIDTH)
729 no_linewidth_value = 0
731 # If LINEWIDTH is used without parameter, set it to default.
732 if has_linewidth and self.option_dict[LINEWIDTH] == None:
733 no_linewidth_value = 1
734 del self.option_dict[LINEWIDTH]
736 for i in default_ly_options.keys ():
737 if i not in self.option_dict.keys ():
738 self.option_dict[i] = default_ly_options[i]
740 if not has_linewidth:
741 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
742 self.option_dict[RAGGEDRIGHT] = None
744 if type == 'lilypond':
745 if LINEWIDTH in self.option_dict.keys ():
746 del self.option_dict[LINEWIDTH]
748 if RAGGEDRIGHT in self.option_dict.keys ():
749 if LINEWIDTH in self.option_dict.keys ():
750 del self.option_dict[LINEWIDTH]
752 if QUOTE in self.option_dict.keys () or type == 'lilypond':
753 if LINEWIDTH in self.option_dict.keys ():
754 del self.option_dict[LINEWIDTH]
756 if not INDENT in self.option_dict.keys ():
757 self.option_dict[INDENT] = '0\\mm'
759 # The QUOTE pattern from ly_options only emits the `linewidth'
761 if has_linewidth and QUOTE in self.option_dict.keys ():
762 if no_linewidth_value:
763 del self.option_dict[LINEWIDTH]
765 del self.option_dict[QUOTE]
767 def compose_ly (self, code):
768 if FRAGMENT in self.option_dict.keys ():
776 # The original concept of the `exampleindent' option is broken.
777 # It is not possible to get a sane value for @exampleindent at all
778 # without processing the document itself. Saying
786 # causes ugly results with the DVI backend of texinfo since the
787 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
788 # value). Executing the above code changes the environment
789 # indentation to an unknown value because we don't know the amount
790 # of 1em in advance since it is font-dependent. Modifying
791 # @exampleindent in the middle of a document is simply not
792 # supported within texinfo.
794 # As a consequence, the only function of @exampleindent is now to
795 # specify the amount of indentation for the `quote' option.
797 # To set @exampleindent locally to zero, we use the @format
798 # environment for non-quoted snippets.
799 override[EXAMPLEINDENT] = r'0.4\in'
800 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
801 override.update (default_ly_options)
804 for (key, value) in self.option_dict.items ():
806 option_list.append (key)
808 option_list.append (key + '=' + value)
809 option_string = string.join (option_list, ',')
812 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
813 for a in compose_types:
816 for (key, value) in self.option_dict.items ():
818 classic_lilypond_book_compatibility (key, value)
822 (_ ("deprecated ly-option used: %s=%s" \
825 (_ ("compatibility mode translation: %s=%s" \
829 (_ ("deprecated ly-option used: %s" \
832 (_ ("compatibility mode translation: %s" \
835 (key, value) = (c_key, c_value)
838 override[key] = value
840 if not override.has_key (key):
844 for type in compose_types:
845 if ly_options[type].has_key (key):
846 compose_dict[type].append (ly_options[type][key])
850 if not found and key not in simple_options:
851 ly.warning (_ ("ignoring unknown ly option: %s") % key)
854 if RELATIVE in override.keys () and override[RELATIVE]:
855 relative = string.atoi (override[RELATIVE])
861 relative_quotes += ',' * (- relative)
863 relative_quotes += "'" * relative
865 program_name = __main__.program_name
867 paper_string = string.join (compose_dict[PAPER],
869 layout_string = string.join (compose_dict[LAYOUT],
871 notes_string = string.join (compose_dict[NOTES],
873 preamble_string = string.join (compose_dict[PREAMBLE],
876 font_dump_setting = ''
877 if FONTLOAD in self.option_dict:
878 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
880 return (PREAMBLE_LY + body) % vars ()
885 self.hash = abs (hash (self.full_ly ()))
889 if FILENAME in self.option_dict:
890 return self.option_dict[FILENAME]
892 return 'lily-%d' % self.get_hash ()
896 outf = open (self.basename () + '.ly', 'w')
897 outf.write (self.full_ly ())
899 open (self.basename () + '.txt', 'w').write ('image of music')
901 def ly_is_outdated (self):
902 base = self.basename ()
904 tex_file = '%s.tex' % base
905 eps_file = '%s.eps' % base
906 system_file = '%s-systems.tex' % base
907 ly_file = '%s.ly' % base
908 ok = os.path.exists (ly_file) \
909 and os.path.exists (system_file)\
910 and os.stat (system_file)[stat.ST_SIZE] \
911 and re.match ('% eof', open (system_file).readlines ()[-1])
912 if ok and (not use_hash_p or FILENAME in self.option_dict):
913 ok = (self.full_ly () == open (ly_file).read ())
915 # TODO: Do something smart with target formats
916 # (ps, png) and m/ctimes.
920 def png_is_outdated (self):
921 base = self.basename ()
922 ok = self.ly_is_outdated ()
923 if format == HTML or format == TEXINFO:
924 ok = ok and (os.path.exists (base + '.png')
925 or glob.glob (base + '-page*.png'))
927 def texstr_is_outdated (self):
931 base = self.basename ()
932 ok = self.ly_is_outdated ()
933 ok = ok and (os.path.exists (base + '.texstr'))
936 def filter_text (self):
937 code = self.substring ('code')
938 s = run_filter (code)
941 'options': self.match.group ('options')
944 return output[self.format][FILTER] % d
946 def replacement_text (self):
947 func = Lilypond_snippet.__dict__['output_' + self.format]
950 def get_images (self):
951 base = self.basename ()
953 single = '%(base)s.png' % vars ()
954 multiple = '%(base)s-page1.png' % vars ()
956 if os.path.exists (multiple) \
957 and (not os.path.exists (single) \
958 or (os.stat (multiple)[stat.ST_MTIME] \
959 > os.stat (single)[stat.ST_MTIME])):
960 images = glob.glob ('%(base)s-page*.png' % vars ())
963 def output_html (self):
965 base = self.basename ()
967 str += self.output_print_filename (HTML)
968 if VERBATIM in self.option_dict:
969 verb = verbatim_html (self.substring ('code'))
970 str += write (output[HTML][VERBATIM] % vars ())
971 if QUOTE in self.option_dict:
972 str = output[HTML][QUOTE] % vars ()
974 str += output[HTML][BEFORE] % vars ()
975 for image in self.get_images ():
976 (base, ext) = os.path.splitext (image)
977 alt = self.option_dict[ALT]
978 str += output[HTML][OUTPUT] % vars ()
979 str += output[HTML][AFTER] % vars ()
982 def output_info (self):
984 for image in self.get_images ():
985 (base, ext) = os.path.splitext (image)
987 # URG, makeinfo implicitly prepends dot to extension.
988 # Specifying no extension is most robust.
990 alt = self.option_dict[ALT]
991 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
993 base = self.basename ()
994 str += output[format][OUTPUT] % vars ()
997 def output_latex (self):
999 base = self.basename ()
1001 str += self.output_print_filename (LATEX)
1002 if VERBATIM in self.option_dict:
1003 verb = self.substring ('code')
1004 str += (output[LATEX][VERBATIM] % vars ())
1005 if QUOTE in self.option_dict:
1006 str = output[LATEX][QUOTE] % vars ()
1008 str += (output[LATEX][OUTPUT] % vars ())
1011 def output_print_filename (self, format):
1013 if PRINTFILENAME in self.option_dict:
1014 base = self.basename ()
1015 filename = self.substring ('filename')
1016 str = output[format][PRINTFILENAME] % vars ()
1020 def output_texinfo (self):
1022 if self.output_print_filename (TEXINFO):
1024 + self.output_print_filename (HTML)
1027 + self.output_print_filename (LATEX)
1029 base = self.basename ()
1030 if TEXIDOC in self.option_dict:
1031 texidoc = base + '.texidoc'
1032 if os.path.exists (texidoc):
1033 str += '@include %(texidoc)s\n\n' % vars ()
1035 if VERBATIM in self.option_dict:
1036 verb = verbatim_texinfo (self.substring ('code'))
1037 str += (output[TEXINFO][VERBATIM] % vars ())
1038 if not QUOTE in self.option_dict:
1039 str = output[TEXINFO][NOQUOTE] % vars ()
1041 str += self.output_info ()
1043 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1044 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1045 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1047 if QUOTE in self.option_dict:
1048 str = output[TEXINFO][QUOTE] % vars ()
1050 # need par after image
1055 class Lilypond_file_snippet (Lilypond_snippet):
1057 name = self.substring ('filename')
1058 return '\\renameinput \"%s\"\n%s' \
1059 % (name, open (find_file (name)).read ())
1061 snippet_type_to_class = {
1062 'lilypond_file': Lilypond_file_snippet,
1063 'lilypond_block': Lilypond_snippet,
1064 'lilypond': Lilypond_snippet,
1065 'include': Include_snippet,
1068 def find_linestarts (s):
1073 i = s.find ('\n', start)
1081 nls.append (len (s))
1084 def find_toplevel_snippets (s, types):
1087 res[i] = ly.re.compile (snippet_res[format][i])
1091 ## found = dict (map (lambda x: (x, None),
1095 map (lambda x, f = found: f.setdefault (x, None),
1098 line_starts = find_linestarts (s)
1100 # We want to search for multiple regexes, without searching
1101 # the string multiple times for one regex.
1102 # Hence, we use earlier results to limit the string portion
1104 # Since every part of the string is traversed at most once for
1105 # every type of snippet, this is linear.
1111 if not found[type] or found[type][0] < index:
1113 m = res[type].search (s[index:endex])
1118 if snippet_type_to_class.has_key (type):
1119 cl = snippet_type_to_class[type]
1122 start = index + m.start ('match')
1123 line_number = line_start_idx
1124 while (line_starts[line_number] < start):
1128 snip = cl (type, m, format, line_number)
1129 found[type] = (start, snip)
1133 or found[type][0] < found[first][0]):
1138 # Limiting the search space is a cute
1139 # idea, but this *requires* to search
1140 # for possible containing blocks
1141 # first, at least as long as we do not
1142 # search for the start of blocks, but
1143 # always/directly for the entire
1144 # @block ... @end block.
1146 endex = found[first][0]
1149 snippets.append (Substring (s, index, len (s), line_start_idx))
1152 while (start > line_starts[line_start_idx+1]):
1155 (start, snip) = found[first]
1156 snippets.append (Substring (s, index, start, line_start_idx + 1))
1157 snippets.append (snip)
1159 index = start + len (snip.match.group ('match'))
1163 def filter_pipe (input, cmd):
1165 ly.progress (_ ("Opening filter `%s'") % cmd)
1167 (stdin, stdout, stderr) = os.popen3 (cmd)
1169 status = stdin.close ()
1173 output = stdout.read ()
1174 status = stdout.close ()
1175 error = stderr.read ()
1179 signal = 0x0f & status
1180 if status or (not output and error):
1181 exit_status = status >> 8
1182 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1183 ly.error (_ ("The error log is as follows:"))
1184 sys.stderr.write (error)
1185 sys.stderr.write (stderr.read ())
1194 return filter_pipe (s, filter_cmd)
1196 def is_derived_class (cl, baseclass):
1199 for b in cl.__bases__:
1200 if is_derived_class (b, baseclass):
1204 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1205 ly_names = filter (lambda x: x,
1206 map (Lilypond_snippet.basename, ly_snippets))
1207 texstr_names = filter (lambda x: x,
1208 map (Lilypond_snippet.basename, texstr_snippets))
1209 png_names = filter (lambda x: x,
1210 map (Lilypond_snippet.basename, png_snippets))
1213 def my_system (cmd):
1214 status = ly.system (cmd,
1215 ignore_error = 1, progress_p = 1)
1218 ly.error ('Process %s exited unsuccessfully.' % cmd)
1222 # the --process=CMD switch is a bad idea
1223 # it is too generic for lilypond-book.
1224 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1226 my_system (string.join ([cmd, '--backend texstr',
1227 'snippet-map.ly'] + texstr_names))
1228 for l in texstr_names:
1229 my_system ('latex %s.texstr' % l)
1232 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1234 LATEX_DOCUMENT = r'''
1237 \typeout{textwidth=\the\textwidth}
1238 \typeout{columnsep=\the\columnsep}
1239 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1243 # Do we need anything else besides `textwidth'?
1244 def get_latex_textwidth (source):
1245 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1246 preamble = source[:m.start (0)]
1247 latex_document = LATEX_DOCUMENT % vars ()
1248 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1251 m = re.search ('columns=([0-9.]*)', parameter_string)
1253 columns = string.atoi (m.group (1))
1256 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1258 columnsep = string.atof (m.group (1))
1261 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1263 textwidth = string.atof (m.group (1))
1265 textwidth = (textwidth - columnsep) / columns
1277 '.texinfo': TEXINFO,
1283 # TEXINFO: '.texinfo',
1288 class Compile_error:
1291 def write_file_map (lys, name):
1292 snippet_map = open ('snippet-map.ly', 'w')
1293 snippet_map.write ("""
1294 #(define version-seen? #t)
1295 #(ly:add-file-name-alist '(
1298 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1304 snippet_map.write ('))\n')
1306 def do_process_cmd (chunks, input_name):
1307 all_lys = filter (lambda x: is_derived_class (x.__class__,
1311 write_file_map (all_lys, input_name)
1313 filter (lambda x: is_derived_class (x.__class__,
1315 and x.ly_is_outdated (),
1318 filter (lambda x: is_derived_class (x.__class__,
1320 and x.texstr_is_outdated (),
1323 filter (lambda x: is_derived_class (x.__class__,
1325 and x.png_is_outdated (),
1328 ly.progress (_ ("Writing snippets..."))
1329 map (Lilypond_snippet.write_ly, ly_outdated)
1333 ly.progress (_ ("Processing..."))
1335 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1337 ly.progress (_ ("All snippets are up to date..."))
1340 def guess_format (input_filename):
1342 e = os.path.splitext (input_filename)[1]
1343 if e in ext2format.keys ():
1345 format = ext2format[e]
1347 ly.error (_ ("can't determine format for: %s" \
1352 def write_if_updated (file_name, lines):
1354 f = open (file_name)
1356 new_str = string.join (lines, '')
1357 if oldstr == new_str:
1358 ly.progress (_ ("%s is up to date."))
1364 ly.progress (_ ("Writing `%s'...") % file_name)
1365 open (file_name, 'w').writelines (lines)
1368 def do_file (input_filename):
1370 if not input_filename or input_filename == '-':
1371 in_handle = sys.stdin
1372 input_fullname = '<stdin>'
1374 if os.path.exists (input_filename):
1375 input_fullname = input_filename
1376 elif format == LATEX:
1377 # urg python interface to libkpathsea?
1378 input_fullname = ly.read_pipe ('kpsewhich '
1379 + input_filename)[:-1]
1381 input_fullname = find_file (input_filename)
1382 in_handle = open (input_fullname)
1384 if input_filename == '-':
1385 input_base = 'stdin'
1387 input_base = os.path.basename \
1388 (os.path.splitext (input_filename)[0])
1390 # Only default to stdout when filtering.
1391 if output_name == '-' or (not output_name and filter_cmd):
1392 output_filename = '-'
1393 output_file = sys.stdout
1396 if not os.path.isdir (output_name):
1397 os.mkdir (output_name, 0777)
1398 os.chdir (output_name)
1400 output_filename = input_base + format2ext[format]
1401 if os.path.exists (input_filename) \
1402 and os.path.exists (output_filename) \
1403 and os.path.samefile (output_filename, input_fullname):
1405 _ ("Output would overwrite input file; use --output."))
1409 ly.progress (_ ("Reading %s...") % input_fullname)
1410 source = in_handle.read ()
1413 # FIXME: Containing blocks must be first, see
1414 # find_toplevel_snippets.
1416 'multiline_comment',
1420 'singleline_comment',
1425 ly.progress (_ ("Dissecting..."))
1426 chunks = find_toplevel_snippets (source, snippet_types)
1429 global default_ly_options
1431 if not default_ly_options.has_key (LINEWIDTH):
1433 textwidth = get_latex_textwidth (source)
1434 default_ly_options[LINEWIDTH] = \
1435 '''%.0f\\pt''' % textwidth
1436 elif format == TEXINFO:
1437 for (k, v) in texinfo_linewidths.items ():
1438 # FIXME: @layout is usually not in
1441 # \input texinfo @c -*-texinfo-*-
1443 # Bluntly search first K items of
1445 # s = chunks[0].replacement_text ()
1446 if re.search (k, source[:1024]):
1447 default_ly_options[LINEWIDTH] = v
1451 write_if_updated (output_filename,
1452 [c.filter_text () for c in chunks])
1454 do_process_cmd (chunks, input_fullname)
1455 ly.progress (_ ("Compiling %s...") % output_filename)
1457 write_if_updated (output_filename,
1458 [s.replacement_text ()
1461 def process_include (snippet):
1462 os.chdir (original_dir)
1463 name = snippet.substring ('filename')
1464 ly.progress (_ ("Processing include: %s") % name)
1466 return do_file (name)
1468 include_chunks = map (process_include,
1469 filter (lambda x: is_derived_class (x.__class__,
1474 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1476 except Compile_error:
1477 os.chdir (original_dir)
1478 ly.progress (_ ("Removing `%s'") % output_filename)
1483 global format, output_name, psfonts_file
1484 global filter_cmd, process_cmd, verbose_p
1486 (sh, long) = ly.getopt_args (option_definitions)
1488 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1489 except getopt.error, s:
1490 sys.stderr.write ('\n')
1491 ly.error (_ ("getopt says: `%s'" % s))
1492 sys.stderr.write ('\n')
1502 elif o == '--filter' or o == '-F':
1505 elif o == '--format' or o == '-f':
1507 if a == 'texi-html' or a == 'texi':
1509 elif o == '--tex-backend ':
1511 elif o == '--help' or o == '-h':
1514 elif o == '--include' or o == '-I':
1515 include_path.append (os.path.join (original_dir,
1517 elif o == '--output' or o == '-o':
1519 elif o == '--process' or o == '-P':
1522 elif o == '--version' or o == '-v':
1523 ly.identify (sys.stdout)
1525 elif o == '--verbose' or o == '-V':
1527 elif o == '--psfonts':
1529 elif o == '--warranty' or o == '-w':
1536 files = do_options ()
1537 if not files or len (files) > 1:
1542 global process_cmd, format
1544 format = guess_format (files[0])
1547 if format == TEXINFO or format == HTML:
1549 if process_cmd == '':
1550 process_cmd = lilypond_binary \
1551 + ' --formats=%s --backend eps ' % formats
1554 process_cmd += string.join ([(' -I %s' % p)
1555 for p in include_path])
1557 ly.identify (sys.stderr)
1558 ly.setup_environment ()
1561 chunks = do_file (file)
1563 fontextract.verbose = verbose_p
1564 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1568 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1569 fontextract.extract_fonts (psfonts_file,
1570 [x.basename() + '.eps'
1571 for x in snippet_chunks])
1575 except Compile_error:
1578 if format == TEXINFO or format == LATEX:
1579 psfonts = os.path.join (output_name, psfonts_file)
1580 output = os.path.join (output_name,
1581 os.path.splitext (os.path.basename
1582 (file))[0]) + '.dvi'
1584 ly.warning (_ ("option --psfonts=FILE not used"))
1585 ly.warning (_ ("processing with dvips will have no fonts"))
1586 psfonts = 'PSFONTS-FILE'
1588 ly.progress (_ ("DVIPS usage:"))
1590 ly.progress (" dvips -h %(psfonts)s %(output)s" % vars ())
1593 if __name__ == '__main__':