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 %% ********************************
562 %% Start cut-&-pastable-section
563 %% ********************************
566 #(define dump-extents #t)
567 %(font_dump_setting)s
579 %% ly snippet contents follows:
591 texinfo_linewidths = {
592 '@afourpaper': '160\\mm',
593 '@afourwide': '6.5\\in',
594 '@afourlatex': '150\\mm',
595 '@smallbook': '5\\in',
596 '@letterpaper': '6\\in',
599 def classic_lilypond_book_compatibility (key, value):
600 if key == 'singleline' and value == None:
601 return (RAGGEDRIGHT, None)
603 m = re.search ('relative\s*([-0-9])', key)
605 return ('relative', m.group (1))
607 m = re.match ('([0-9]+)pt', key)
609 return ('staffsize', m.group (1))
611 if key == 'indent' or key == 'linewidth':
612 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
614 f = float (m.group (1))
615 return (key, '%f\\%s' % (f, m.group (2)))
619 def find_file (name):
620 for i in include_path:
621 full = os.path.join (i, name)
622 if os.path.exists (full):
624 ly.error (_ ("file not found: %s") % name + '\n')
628 def verbatim_html (s):
629 return re.sub ('>', '>',
631 re.sub ('&', '&', s)))
633 def verbatim_texinfo (s):
634 return re.sub ('{', '@{',
636 re.sub ('@', '@@', s)))
638 def split_options (option_string):
641 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
642 for i in range(len(options)):
643 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
646 return re.split (format_res[format]['option_sep'],
650 def invokes_lilypond ():
651 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
654 def replacement_text (self):
657 def filter_text (self):
658 return self.replacement_text ()
660 def ly_is_outdated (self):
663 def png_is_outdated (self):
666 class Substring (Chunk):
667 def __init__ (self, source, start, end, line_number):
671 self.line_number = line_number
673 def replacement_text (self):
674 return self.source[self.start:self.end]
676 class Snippet (Chunk):
677 def __init__ (self, type, match, format, line_number):
681 self.option_dict = {}
683 self.line_number = line_number
685 def replacement_text (self):
686 return self.match.group ('match')
688 def substring (self, s):
689 return self.match.group (s)
692 return `self.__class__` + ' type = ' + self.type
694 class Include_snippet (Snippet):
695 def processed_filename (self):
696 f = self.substring ('filename')
697 return os.path.splitext (f)[0] + format2ext[format]
699 def replacement_text (self):
700 s = self.match.group ('match')
701 f = self.substring ('filename')
703 return re.sub (f, self.processed_filename (), s)
705 class Lilypond_snippet (Snippet):
706 def __init__ (self, type, match, format, line_number):
707 Snippet.__init__ (self, type, match, format, line_number)
708 os = match.group ('options')
709 self.do_options (os, self.type)
712 return self.substring ('code')
717 return self.compose_ly (s)
720 def do_options (self, option_string, type):
721 self.option_dict = {}
723 options = split_options (option_string)
726 if string.find (i, '=') > 0:
727 (key, value) = re.split ('\s*=\s*', i)
728 self.option_dict[key] = value
730 if i in no_options.keys ():
731 if no_options[i] in self.option_dict.keys ():
732 del self.option_dict[no_options[i]]
734 self.option_dict[i] = None
736 has_linewidth = self.option_dict.has_key (LINEWIDTH)
737 no_linewidth_value = 0
739 # If LINEWIDTH is used without parameter, set it to default.
740 if has_linewidth and self.option_dict[LINEWIDTH] == None:
741 no_linewidth_value = 1
742 del self.option_dict[LINEWIDTH]
744 for i in default_ly_options.keys ():
745 if i not in self.option_dict.keys ():
746 self.option_dict[i] = default_ly_options[i]
748 if not has_linewidth:
749 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
750 self.option_dict[RAGGEDRIGHT] = None
752 if type == 'lilypond':
753 if LINEWIDTH in self.option_dict.keys ():
754 del self.option_dict[LINEWIDTH]
756 if RAGGEDRIGHT in self.option_dict.keys ():
757 if LINEWIDTH in self.option_dict.keys ():
758 del self.option_dict[LINEWIDTH]
760 if QUOTE in self.option_dict.keys () or type == 'lilypond':
761 if LINEWIDTH in self.option_dict.keys ():
762 del self.option_dict[LINEWIDTH]
764 if not INDENT in self.option_dict.keys ():
765 self.option_dict[INDENT] = '0\\mm'
767 # The QUOTE pattern from ly_options only emits the `linewidth'
769 if has_linewidth and QUOTE in self.option_dict.keys ():
770 if no_linewidth_value:
771 del self.option_dict[LINEWIDTH]
773 del self.option_dict[QUOTE]
775 def compose_ly (self, code):
776 if FRAGMENT in self.option_dict.keys ():
784 # The original concept of the `exampleindent' option is broken.
785 # It is not possible to get a sane value for @exampleindent at all
786 # without processing the document itself. Saying
794 # causes ugly results with the DVI backend of texinfo since the
795 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
796 # value). Executing the above code changes the environment
797 # indentation to an unknown value because we don't know the amount
798 # of 1em in advance since it is font-dependent. Modifying
799 # @exampleindent in the middle of a document is simply not
800 # supported within texinfo.
802 # As a consequence, the only function of @exampleindent is now to
803 # specify the amount of indentation for the `quote' option.
805 # To set @exampleindent locally to zero, we use the @format
806 # environment for non-quoted snippets.
807 override[EXAMPLEINDENT] = r'0.4\in'
808 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
809 override.update (default_ly_options)
812 for (key, value) in self.option_dict.items ():
814 option_list.append (key)
816 option_list.append (key + '=' + value)
817 option_string = string.join (option_list, ',')
820 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
821 for a in compose_types:
824 for (key, value) in self.option_dict.items ():
826 classic_lilypond_book_compatibility (key, value)
830 (_ ("deprecated ly-option used: %s=%s" \
833 (_ ("compatibility mode translation: %s=%s" \
837 (_ ("deprecated ly-option used: %s" \
840 (_ ("compatibility mode translation: %s" \
843 (key, value) = (c_key, c_value)
846 override[key] = value
848 if not override.has_key (key):
852 for type in compose_types:
853 if ly_options[type].has_key (key):
854 compose_dict[type].append (ly_options[type][key])
858 if not found and key not in simple_options:
859 ly.warning (_ ("ignoring unknown ly option: %s") % key)
862 if RELATIVE in override.keys () and override[RELATIVE]:
863 relative = string.atoi (override[RELATIVE])
869 relative_quotes += ',' * (- relative)
871 relative_quotes += "'" * relative
873 program_name = __main__.program_name
875 paper_string = string.join (compose_dict[PAPER],
877 layout_string = string.join (compose_dict[LAYOUT],
879 notes_string = string.join (compose_dict[NOTES],
881 preamble_string = string.join (compose_dict[PREAMBLE],
884 font_dump_setting = ''
885 if FONTLOAD in self.option_dict:
886 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
888 return (PREAMBLE_LY + body) % vars ()
893 self.hash = abs (hash (self.full_ly ()))
897 if FILENAME in self.option_dict:
898 return self.option_dict[FILENAME]
900 return 'lily-%d' % self.get_hash ()
904 outf = open (self.basename () + '.ly', 'w')
905 outf.write (self.full_ly ())
907 open (self.basename () + '.txt', 'w').write ('image of music')
909 def ly_is_outdated (self):
910 base = self.basename ()
912 tex_file = '%s.tex' % base
913 eps_file = '%s.eps' % base
914 system_file = '%s-systems.tex' % base
915 ly_file = '%s.ly' % base
916 ok = os.path.exists (ly_file) \
917 and os.path.exists (system_file)\
918 and os.stat (system_file)[stat.ST_SIZE] \
919 and re.match ('% eof', open (system_file).readlines ()[-1])
920 if ok and (not use_hash_p or FILENAME in self.option_dict):
921 ok = (self.full_ly () == open (ly_file).read ())
923 # TODO: Do something smart with target formats
924 # (ps, png) and m/ctimes.
928 def png_is_outdated (self):
929 base = self.basename ()
930 ok = self.ly_is_outdated ()
931 if format == HTML or format == TEXINFO:
932 ok = ok and (os.path.exists (base + '.png')
933 or glob.glob (base + '-page*.png'))
935 def texstr_is_outdated (self):
939 base = self.basename ()
940 ok = self.ly_is_outdated ()
941 ok = ok and (os.path.exists (base + '.texstr'))
944 def filter_text (self):
945 code = self.substring ('code')
946 s = run_filter (code)
949 'options': self.match.group ('options')
952 return output[self.format][FILTER] % d
954 def replacement_text (self):
955 func = Lilypond_snippet.__dict__['output_' + self.format]
958 def get_images (self):
959 base = self.basename ()
961 single = '%(base)s.png' % vars ()
962 multiple = '%(base)s-page1.png' % vars ()
964 if os.path.exists (multiple) \
965 and (not os.path.exists (single) \
966 or (os.stat (multiple)[stat.ST_MTIME] \
967 > os.stat (single)[stat.ST_MTIME])):
968 images = glob.glob ('%(base)s-page*.png' % vars ())
971 def output_html (self):
973 base = self.basename ()
975 str += self.output_print_filename (HTML)
976 if VERBATIM in self.option_dict:
977 verb = verbatim_html (self.substring ('code'))
978 str += write (output[HTML][VERBATIM] % vars ())
979 if QUOTE in self.option_dict:
980 str = output[HTML][QUOTE] % vars ()
982 str += output[HTML][BEFORE] % vars ()
983 for image in self.get_images ():
984 (base, ext) = os.path.splitext (image)
985 alt = self.option_dict[ALT]
986 str += output[HTML][OUTPUT] % vars ()
987 str += output[HTML][AFTER] % vars ()
990 def output_info (self):
992 for image in self.get_images ():
993 (base, ext) = os.path.splitext (image)
995 # URG, makeinfo implicitly prepends dot to extension.
996 # Specifying no extension is most robust.
998 alt = self.option_dict[ALT]
999 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1001 base = self.basename ()
1002 str += output[format][OUTPUT] % vars ()
1005 def output_latex (self):
1007 base = self.basename ()
1009 str += self.output_print_filename (LATEX)
1010 if VERBATIM in self.option_dict:
1011 verb = self.substring ('code')
1012 str += (output[LATEX][VERBATIM] % vars ())
1013 if QUOTE in self.option_dict:
1014 str = output[LATEX][QUOTE] % vars ()
1016 str += (output[LATEX][OUTPUT] % vars ())
1019 def output_print_filename (self, format):
1021 if PRINTFILENAME in self.option_dict:
1022 base = self.basename ()
1023 filename = self.substring ('filename')
1024 str = output[format][PRINTFILENAME] % vars ()
1028 def output_texinfo (self):
1030 if self.output_print_filename (TEXINFO):
1032 + self.output_print_filename (HTML)
1035 + self.output_print_filename (LATEX)
1037 base = self.basename ()
1038 if TEXIDOC in self.option_dict:
1039 texidoc = base + '.texidoc'
1040 if os.path.exists (texidoc):
1041 str += '@include %(texidoc)s\n\n' % vars ()
1043 if VERBATIM in self.option_dict:
1044 verb = verbatim_texinfo (self.substring ('code'))
1045 str += (output[TEXINFO][VERBATIM] % vars ())
1046 if not QUOTE in self.option_dict:
1047 str = output[TEXINFO][NOQUOTE] % vars ()
1049 str += self.output_info ()
1051 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1052 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1053 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1055 if QUOTE in self.option_dict:
1056 str = output[TEXINFO][QUOTE] % vars ()
1058 # need par after image
1063 class Lilypond_file_snippet (Lilypond_snippet):
1065 name = self.substring ('filename')
1066 return '\\renameinput \"%s\"\n%s' \
1067 % (name, open (find_file (name)).read ())
1069 snippet_type_to_class = {
1070 'lilypond_file': Lilypond_file_snippet,
1071 'lilypond_block': Lilypond_snippet,
1072 'lilypond': Lilypond_snippet,
1073 'include': Include_snippet,
1076 def find_linestarts (s):
1081 i = s.find ('\n', start)
1089 nls.append (len (s))
1092 def find_toplevel_snippets (s, types):
1095 res[i] = ly.re.compile (snippet_res[format][i])
1099 ## found = dict (map (lambda x: (x, None),
1103 map (lambda x, f = found: f.setdefault (x, None),
1106 line_starts = find_linestarts (s)
1108 # We want to search for multiple regexes, without searching
1109 # the string multiple times for one regex.
1110 # Hence, we use earlier results to limit the string portion
1112 # Since every part of the string is traversed at most once for
1113 # every type of snippet, this is linear.
1119 if not found[type] or found[type][0] < index:
1121 m = res[type].search (s[index:endex])
1126 if snippet_type_to_class.has_key (type):
1127 cl = snippet_type_to_class[type]
1130 start = index + m.start ('match')
1131 line_number = line_start_idx
1132 while (line_starts[line_number] < start):
1136 snip = cl (type, m, format, line_number)
1137 found[type] = (start, snip)
1141 or found[type][0] < found[first][0]):
1146 # Limiting the search space is a cute
1147 # idea, but this *requires* to search
1148 # for possible containing blocks
1149 # first, at least as long as we do not
1150 # search for the start of blocks, but
1151 # always/directly for the entire
1152 # @block ... @end block.
1154 endex = found[first][0]
1157 snippets.append (Substring (s, index, len (s), line_start_idx))
1160 while (start > line_starts[line_start_idx+1]):
1163 (start, snip) = found[first]
1164 snippets.append (Substring (s, index, start, line_start_idx + 1))
1165 snippets.append (snip)
1167 index = start + len (snip.match.group ('match'))
1171 def filter_pipe (input, cmd):
1173 ly.progress (_ ("Opening filter `%s'") % cmd)
1175 (stdin, stdout, stderr) = os.popen3 (cmd)
1177 status = stdin.close ()
1181 output = stdout.read ()
1182 status = stdout.close ()
1183 error = stderr.read ()
1187 signal = 0x0f & status
1188 if status or (not output and error):
1189 exit_status = status >> 8
1190 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1191 ly.error (_ ("The error log is as follows:"))
1192 sys.stderr.write (error)
1193 sys.stderr.write (stderr.read ())
1202 return filter_pipe (s, filter_cmd)
1204 def is_derived_class (cl, baseclass):
1207 for b in cl.__bases__:
1208 if is_derived_class (b, baseclass):
1212 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1213 ly_names = filter (lambda x: x,
1214 map (Lilypond_snippet.basename, ly_snippets))
1215 texstr_names = filter (lambda x: x,
1216 map (Lilypond_snippet.basename, texstr_snippets))
1217 png_names = filter (lambda x: x,
1218 map (Lilypond_snippet.basename, png_snippets))
1221 def my_system (cmd):
1222 status = ly.system (cmd,
1223 ignore_error = 1, progress_p = 1)
1226 ly.error ('Process %s exited unsuccessfully.' % cmd)
1230 # the --process=CMD switch is a bad idea
1231 # it is too generic for lilypond-book.
1232 if texstr_names and invokes_lilypond:
1233 my_system (string.join ([cmd, '--backend texstr',
1234 'snippet-map.ly'] + texstr_names))
1235 for l in texstr_names:
1236 my_system ('latex %s.texstr' % l)
1239 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1241 LATEX_DOCUMENT = r'''
1244 \typeout{textwidth=\the\textwidth}
1245 \typeout{columnsep=\the\columnsep}
1246 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1250 # Do we need anything else besides `textwidth'?
1251 def get_latex_textwidth (source):
1252 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1253 preamble = source[:m.start (0)]
1254 latex_document = LATEX_DOCUMENT % vars ()
1255 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1258 m = re.search ('columns=([0-9.]*)', parameter_string)
1260 columns = string.atoi (m.group (1))
1263 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1265 columnsep = string.atof (m.group (1))
1268 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1270 textwidth = string.atof (m.group (1))
1272 textwidth = (textwidth - columnsep) / columns
1284 '.texinfo': TEXINFO,
1290 # TEXINFO: '.texinfo',
1295 class Compile_error:
1298 def write_file_map (lys, name):
1299 snippet_map = open ('snippet-map.ly', 'w')
1300 snippet_map.write ("""
1301 #(define version-seen? #t)
1302 #(ly:add-file-name-alist '(
1305 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1311 snippet_map.write ('))\n')
1313 def do_process_cmd (chunks, input_name):
1314 all_lys = filter (lambda x: is_derived_class (x.__class__,
1318 write_file_map (all_lys, input_name)
1320 filter (lambda x: is_derived_class (x.__class__,
1322 and x.ly_is_outdated (),
1325 filter (lambda x: is_derived_class (x.__class__,
1327 and x.texstr_is_outdated (),
1330 filter (lambda x: is_derived_class (x.__class__,
1332 and x.png_is_outdated (),
1335 ly.progress (_ ("Writing snippets..."))
1336 map (Lilypond_snippet.write_ly, ly_outdated)
1340 ly.progress (_ ("Processing..."))
1342 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1344 ly.progress (_ ("All snippets are up to date..."))
1347 def guess_format (input_filename):
1349 e = os.path.splitext (input_filename)[1]
1350 if e in ext2format.keys ():
1352 format = ext2format[e]
1354 ly.error (_ ("can't determine format for: %s" \
1359 def write_if_updated (file_name, lines):
1361 f = open (file_name)
1363 new_str = string.join (lines, '')
1364 if oldstr == new_str:
1365 ly.progress (_ ("%s is up to date.") % file_name)
1371 ly.progress (_ ("Writing `%s'...") % file_name)
1372 open (file_name, 'w').writelines (lines)
1375 def do_file (input_filename):
1377 if not input_filename or input_filename == '-':
1378 in_handle = sys.stdin
1379 input_fullname = '<stdin>'
1381 if os.path.exists (input_filename):
1382 input_fullname = input_filename
1383 elif format == LATEX:
1384 # urg python interface to libkpathsea?
1385 input_fullname = ly.read_pipe ('kpsewhich '
1386 + input_filename)[:-1]
1388 input_fullname = find_file (input_filename)
1389 in_handle = open (input_fullname)
1391 if input_filename == '-':
1392 input_base = 'stdin'
1394 input_base = os.path.basename \
1395 (os.path.splitext (input_filename)[0])
1397 # Only default to stdout when filtering.
1398 if output_name == '-' or (not output_name and filter_cmd):
1399 output_filename = '-'
1400 output_file = sys.stdout
1403 if not os.path.isdir (output_name):
1404 os.mkdir (output_name, 0777)
1405 os.chdir (output_name)
1407 output_filename = input_base + format2ext[format]
1408 if os.path.exists (input_filename) \
1409 and os.path.exists (output_filename) \
1410 and os.path.samefile (output_filename, input_fullname):
1412 _ ("Output would overwrite input file; use --output."))
1416 ly.progress (_ ("Reading %s...") % input_fullname)
1417 source = in_handle.read ()
1420 # FIXME: Containing blocks must be first, see
1421 # find_toplevel_snippets.
1423 'multiline_comment',
1427 'singleline_comment',
1432 ly.progress (_ ("Dissecting..."))
1433 chunks = find_toplevel_snippets (source, snippet_types)
1436 global default_ly_options
1438 if not default_ly_options.has_key (LINEWIDTH):
1440 textwidth = get_latex_textwidth (source)
1441 default_ly_options[LINEWIDTH] = \
1442 '''%.0f\\pt''' % textwidth
1443 elif format == TEXINFO:
1444 for (k, v) in texinfo_linewidths.items ():
1445 # FIXME: @layout is usually not in
1448 # \input texinfo @c -*-texinfo-*-
1450 # Bluntly search first K items of
1452 # s = chunks[0].replacement_text ()
1453 if re.search (k, source[:1024]):
1454 default_ly_options[LINEWIDTH] = v
1458 write_if_updated (output_filename,
1459 [c.filter_text () for c in chunks])
1461 do_process_cmd (chunks, input_fullname)
1462 ly.progress (_ ("Compiling %s...") % output_filename)
1464 write_if_updated (output_filename,
1465 [s.replacement_text ()
1468 def process_include (snippet):
1469 os.chdir (original_dir)
1470 name = snippet.substring ('filename')
1471 ly.progress (_ ("Processing include: %s") % name)
1473 return do_file (name)
1475 include_chunks = map (process_include,
1476 filter (lambda x: is_derived_class (x.__class__,
1481 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1483 except Compile_error:
1484 os.chdir (original_dir)
1485 ly.progress (_ ("Removing `%s'") % output_filename)
1490 global format, output_name, psfonts_file
1491 global filter_cmd, process_cmd, verbose_p
1493 (sh, long) = ly.getopt_args (option_definitions)
1495 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1496 except getopt.error, s:
1497 sys.stderr.write ('\n')
1498 ly.error (_ ("getopt says: `%s'" % s))
1499 sys.stderr.write ('\n')
1509 elif o == '--filter' or o == '-F':
1512 elif o == '--format' or o == '-f':
1514 if a == 'texi-html' or a == 'texi':
1516 elif o == '--tex-backend ':
1518 elif o == '--help' or o == '-h':
1521 elif o == '--include' or o == '-I':
1522 include_path.append (os.path.join (original_dir,
1524 elif o == '--output' or o == '-o':
1526 elif o == '--process' or o == '-P':
1529 elif o == '--version' or o == '-v':
1530 ly.identify (sys.stdout)
1532 elif o == '--verbose' or o == '-V':
1534 elif o == '--psfonts':
1536 elif o == '--warranty' or o == '-w':
1543 files = do_options ()
1544 if not files or len (files) > 1:
1549 global process_cmd, format
1551 format = guess_format (files[0])
1554 if format == TEXINFO or format == HTML:
1556 if process_cmd == '':
1557 process_cmd = lilypond_binary \
1558 + ' --formats=%s --backend eps ' % formats
1561 process_cmd += string.join ([(' -I %s' % p)
1562 for p in include_path])
1564 ly.identify (sys.stderr)
1565 ly.setup_environment ()
1568 chunks = do_file (file)
1569 if psfonts_file and invokes_lilypond ():
1570 fontextract.verbose = verbose_p
1571 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1575 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1576 fontextract.extract_fonts (psfonts_file,
1577 [x.basename() + '.eps'
1578 for x in snippet_chunks])
1582 except Compile_error:
1585 if format == TEXINFO or format == LATEX:
1586 psfonts = os.path.join (output_name, psfonts_file)
1587 output = os.path.join (output_name,
1588 os.path.splitext (os.path.basename
1589 (file))[0]) + '.dvi'
1591 ly.warning (_ ("option --psfonts=FILE not used"))
1592 ly.warning (_ ("processing with dvips will have no fonts"))
1593 psfonts = 'PSFONTS-FILE'
1595 ly.progress (_ ("DVIPS usage:"))
1597 ly.progress (" dvips -h %(psfonts)s %(output)s" % vars ())
1600 if __name__ == '__main__':