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 = {}
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'
157 # NOTIME has no opposite so it isn't part of this dictionary.
158 # NOQUOTE is used internally only.
160 NOFRAGMENT: FRAGMENT,
165 # Recognize special sequences in the input.
167 # (?P<name>regex) -- Assign result of REGEX to NAME.
168 # *? -- Match non-greedily.
169 # (?m) -- Multiline regex: Make ^ and $ match at each line.
170 # (?s) -- Make the dot match all characters including newline.
171 # (?x) -- Ignore whitespace in patterns.
183 (\s*(?P<options>.*?)\s*:)?\s*
191 \s*(?P<options>.*?)\s*
200 \s*(?P<options>.*?)\s*
202 \s*(?P<filename>.*?)\s*
209 (?P<code><!--\s.*?!-->)
212 'singleline_comment':
218 (?P<code><pre>.*?</pre>))''',
224 (?P<code><pre>\s.*?</pre>\s))''',
243 \s*(?P<options>.*?)\s*
254 \s*(?P<options>.*?)\s*
258 \\end\s*{lilypond})''',
266 \s*(?P<options>.*?)\s*
274 'singleline_comment':
297 \\end\s*{verbatim}))''',
306 (?P<filename>\S+))''',
310 ^[^\n]*?(?!@c\s+)[^\n]*?
314 \s*(?P<options>.*?)\s*
324 \s*(?P<options>.*?)\s*
327 ^@end\s+lilypond)\s''',
334 \s*(?P<options>.*?)\s*
345 @end\s+ignore))\s''',
347 'singleline_comment':
352 @c([ \t][^\n]*|)\n))''',
354 # Don't do this: It interferes with @code{@{}.
355 # 'verb': r'''(?P<code>@code{.*?})''',
363 @end\s+example\s))''',
369 'intertext': r',?\s*intertext=\".*?\"',
374 'intertext': r',?\s*intertext=\".*?\"',
375 'option_sep': '\s*,\s*',
379 'intertext': r',?\s*intertext=\".*?\"',
380 'option_sep': '\s*,\s*',
384 # Options without a pattern in ly_options.
399 RELATIVE: r'''\relative c%(relative_quotes)s''',
404 INDENT: r'''indent = %(indent)s''',
406 LINEWIDTH: r'''linewidth = %(linewidth)s''',
408 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
410 RAGGEDRIGHT: r'''raggedright = ##t''',
412 PACKED: r'''packed = ##t''',
417 NOTIME: r'''\context {
419 \remove Time_signature_engraver
425 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
432 FILTER: r'''<lilypond %(options)s>
442 <a href="%(base)s.ly">''',
445 <img align="center" valign="center"
446 border="0" src="%(image)s" alt="[image of music]">''',
448 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
450 QUOTE: r'''<blockquote>
464 \ifx\preLilyPondExample \undefined
469 \def\lilypondbook{}%%
470 \input %(base)s-systems.tex
471 \ifx\postLilyPondExample \undefined
478 PRINTFILENAME: '''\\texttt{%(filename)s}
481 QUOTE: r'''\begin{quotation}
486 VERBATIM: r'''\noindent
488 %(verb)s\end{verbatim}
491 FILTER: r'''\begin{lilypond}[%(options)s]
498 FILTER: r'''@lilypond[%(options)s]
504 @include %(base)s-systems.texi
508 OUTPUTIMAGE: r'''@noindent
510 @image{%(base)s,,,[image of music],%(ext)s}
514 <a href="%(base)s.ly">
515 <img align="center" valign="center"
516 border="0" src="%(image)s" alt="[image of music]">
522 PRINTFILENAME: '''@file{%(filename)s}
525 QUOTE: r'''@quotation
526 %(str)s@end quotation
533 VERBATIM: r'''@exampleindent 0
540 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
541 %%%% Options: [%(option_string)s]
543 #(set! toplevel-score-handler ly:parser-print-score)
544 #(set! toplevel-music-handler (lambda (p m)
545 (ly:parser-print-score
546 p (ly:music-scorify m p))))
548 #(define version-seen? #t)
552 #(define dump-extents #t)
553 %(font_dump_setting)s
565 %% ly snippet contents follows:
577 texinfo_linewidths = {
578 '@afourpaper': '160\\mm',
579 '@afourwide': '6.5\\in',
580 '@afourlatex': '150\\mm',
581 '@smallbook': '5\\in',
582 '@letterpaper': '6\\in',
585 def classic_lilypond_book_compatibility (key, value):
586 if key == 'singleline' and value == None:
587 return (RAGGEDRIGHT, None)
589 m = re.search ('relative\s*([-0-9])', key)
591 return ('relative', m.group (1))
593 m = re.match ('([0-9]+)pt', key)
595 return ('staffsize', m.group (1))
597 if key == 'indent' or key == 'linewidth':
598 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
600 f = float (m.group (1))
601 return (key, '%f\\%s' % (f, m.group (2)))
605 def find_file (name):
606 for i in include_path:
607 full = os.path.join (i, name)
608 if os.path.exists (full):
610 ly.error (_ ("file not found: %s") % name + '\n')
614 def verbatim_html (s):
615 return re.sub ('>', '>',
617 re.sub ('&', '&', s)))
619 def verbatim_texinfo (s):
620 return re.sub ('{', '@{',
622 re.sub ('@', '@@', s)))
624 def split_options (option_string):
626 return re.split (format_res[format]['option_sep'],
631 def replacement_text (self):
634 def filter_text (self):
635 return self.replacement_text ()
637 def ly_is_outdated (self):
640 def png_is_outdated (self):
643 class Substring (Chunk):
644 def __init__ (self, source, start, end, line_number):
648 self.line_number = line_number
650 def replacement_text (self):
651 return self.source[self.start:self.end]
653 class Snippet (Chunk):
654 def __init__ (self, type, match, format, line_number):
658 self.option_dict = {}
660 self.line_number = line_number
662 def replacement_text (self):
663 return self.match.group ('match')
665 def substring (self, s):
666 return self.match.group (s)
669 return `self.__class__` + ' type = ' + self.type
671 class Include_snippet (Snippet):
672 def processed_filename (self):
673 f = self.substring ('filename')
674 return os.path.splitext (f)[0] + format2ext[format]
676 def replacement_text (self):
677 s = self.match.group ('match')
678 f = self.substring ('filename')
680 return re.sub (f, self.processed_filename (), s)
682 class Lilypond_snippet (Snippet):
683 def __init__ (self, type, match, format, line_number):
684 Snippet.__init__ (self, type, match, format, line_number)
685 os = match.group ('options')
687 self.do_options (os, self.type)
690 return self.substring ('code')
695 return self.compose_ly (s)
698 def do_options (self, option_string, type):
699 self.option_dict = {}
701 options = split_options (option_string)
704 if string.find (i, '=') > 0:
705 (key, value) = re.split ('\s*=\s*', i)
706 self.option_dict[key] = value
708 if i in no_options.keys ():
709 if no_options[i] in self.option_dict.keys ():
710 del self.option_dict[no_options[i]]
712 self.option_dict[i] = None
714 has_linewidth = self.option_dict.has_key (LINEWIDTH)
715 no_linewidth_value = 0
717 # If LINEWIDTH is used without parameter, set it to default.
718 if has_linewidth and self.option_dict[LINEWIDTH] == None:
719 no_linewidth_value = 1
720 del self.option_dict[LINEWIDTH]
722 for i in default_ly_options.keys ():
723 if i not in self.option_dict.keys ():
724 self.option_dict[i] = default_ly_options[i]
726 if not has_linewidth:
727 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
728 self.option_dict[RAGGEDRIGHT] = None
730 if type == 'lilypond':
731 if LINEWIDTH in self.option_dict.keys ():
732 del self.option_dict[LINEWIDTH]
734 if RAGGEDRIGHT in self.option_dict.keys ():
735 if LINEWIDTH in self.option_dict.keys ():
736 del self.option_dict[LINEWIDTH]
738 if QUOTE in self.option_dict.keys () or type == 'lilypond':
739 if LINEWIDTH in self.option_dict.keys ():
740 del self.option_dict[LINEWIDTH]
742 if not INDENT in self.option_dict.keys ():
743 self.option_dict[INDENT] = '0\\mm'
745 # The QUOTE pattern from ly_options only emits the `linewidth'
747 if has_linewidth and QUOTE in self.option_dict.keys ():
748 if no_linewidth_value:
749 del self.option_dict[LINEWIDTH]
751 del self.option_dict[QUOTE]
753 def compose_ly (self, code):
754 if FRAGMENT in self.option_dict.keys ():
762 # The original concept of the `exampleindent' option is broken.
763 # It is not possible to get a sane value for @exampleindent at all
764 # without processing the document itself. Saying
772 # causes ugly results with the DVI backend of texinfo since the
773 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
774 # value). Executing the above code changes the environment
775 # indentation to an unknown value because we don't know the amount
776 # of 1em in advance since it is font-dependent. Modifying
777 # @exampleindent in the middle of a document is simply not
778 # supported within texinfo.
780 # As a consequence, the only function of @exampleindent is now to
781 # specify the amount of indentation for the `quote' option.
783 # To set @exampleindent locally to zero, we use the @format
784 # environment for non-quoted snippets.
785 override[EXAMPLEINDENT] = r'0.4\in'
786 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
787 override.update (default_ly_options)
790 for (key, value) in self.option_dict.items ():
792 option_list.append (key)
794 option_list.append (key + '=' + value)
795 option_string = string.join (option_list, ',')
798 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
799 for a in compose_types:
802 for (key, value) in self.option_dict.items ():
804 classic_lilypond_book_compatibility (key, value)
808 (_ ("deprecated ly-option used: %s=%s" \
811 (_ ("compatibility mode translation: %s=%s" \
815 (_ ("deprecated ly-option used: %s" \
818 (_ ("compatibility mode translation: %s" \
821 (key, value) = (c_key, c_value)
824 override[key] = value
826 if not override.has_key (key):
830 for type in compose_types:
831 if ly_options[type].has_key (key):
832 compose_dict[type].append (ly_options[type][key])
836 if not found and key not in simple_options:
837 ly.warning (_ ("ignoring unknown ly option: %s") % key)
840 if RELATIVE in override.keys () and override[RELATIVE]:
841 relative = string.atoi (override[RELATIVE])
847 relative_quotes += ',' * (- relative)
849 relative_quotes += "'" * relative
851 program_name = __main__.program_name
853 paper_string = string.join (compose_dict[PAPER],
855 layout_string = string.join (compose_dict[LAYOUT],
857 notes_string = string.join (compose_dict[NOTES],
859 preamble_string = string.join (compose_dict[PREAMBLE],
862 font_dump_setting = ''
863 if FONTLOAD in self.option_dict:
864 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
866 return (PREAMBLE_LY + body) % vars ()
871 self.hash = abs (hash (self.full_ly ()))
876 return 'lily-%d' % self.get_hash ()
880 outf = open (self.basename () + '.ly', 'w')
881 outf.write (self.full_ly ())
883 open (self.basename () + '.txt', 'w').write ('image of music')
885 def ly_is_outdated (self):
886 base = self.basename ()
888 tex_file = '%s.tex' % base
889 eps_file = '%s.eps' % base
890 system_file = '%s-systems.tex' % base
891 ly_file = '%s.ly' % base
892 ok = os.path.exists (ly_file) \
893 and os.path.exists (system_file)\
894 and os.stat (system_file)[stat.ST_SIZE] \
895 and re.match ('% eof', open (system_file).readlines ()[-1])
896 if ok and (use_hash_p \
897 or self.ly () == open (ly_file).read ()):
898 # TODO: Do something smart with target formats
899 # (ps, png) and m/ctimes.
903 def png_is_outdated (self):
904 base = self.basename ()
905 ok = self.ly_is_outdated ()
906 if format == HTML or format == TEXINFO:
907 ok = ok and (os.path.exists (base + '.png')
908 or glob.glob (base + '-page*.png'))
910 def texstr_is_outdated (self):
914 base = self.basename ()
915 ok = self.ly_is_outdated ()
916 ok = ok and (os.path.exists (base + '.texstr'))
919 def filter_text (self):
920 code = self.substring ('code')
921 s = run_filter (code)
924 'options': self.match.group ('options')
927 return output[self.format][FILTER] % d
929 def replacement_text (self):
930 func = Lilypond_snippet.__dict__['output_' + self.format]
933 def get_images (self):
934 base = self.basename ()
936 single = '%(base)s.png' % vars ()
937 multiple = '%(base)s-page1.png' % vars ()
939 if os.path.exists (multiple) \
940 and (not os.path.exists (single) \
941 or (os.stat (multiple)[stat.ST_MTIME] \
942 > os.stat (single)[stat.ST_MTIME])):
943 images = glob.glob ('%(base)s-page*.png' % vars ())
946 def output_html (self):
948 base = self.basename ()
950 str += self.output_print_filename (HTML)
951 if VERBATIM in self.option_dict:
952 verb = verbatim_html (self.substring ('code'))
953 str += write (output[HTML][VERBATIM] % vars ())
954 if QUOTE in self.option_dict:
955 str = output[HTML][QUOTE] % vars ()
957 str += output[HTML][BEFORE] % vars ()
958 for image in self.get_images ():
959 (base, ext) = os.path.splitext (image)
960 str += output[HTML][OUTPUT] % vars ()
961 str += output[HTML][AFTER] % vars ()
964 def output_info (self):
966 for image in self.get_images ():
967 (base, ext) = os.path.splitext (image)
969 # URG, makeinfo implicitly prepends dot to extension.
970 # Specifying no extension is most robust.
972 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
974 base = self.basename ()
975 str += output[format][OUTPUT] % vars ()
978 def output_latex (self):
980 base = self.basename ()
982 str += self.output_print_filename (LATEX)
983 if VERBATIM in self.option_dict:
984 verb = self.substring ('code')
985 str += (output[LATEX][VERBATIM] % vars ())
986 if QUOTE in self.option_dict:
987 str = output[LATEX][QUOTE] % vars ()
989 str += (output[LATEX][OUTPUT] % vars ())
992 def output_print_filename (self, format):
994 if PRINTFILENAME in self.option_dict:
995 base = self.basename ()
996 filename = self.substring ('filename')
997 str = output[format][PRINTFILENAME] % vars ()
1001 def output_texinfo (self):
1003 if self.output_print_filename (TEXINFO):
1005 + self.output_print_filename (HTML)
1008 + self.output_print_filename (LATEX)
1010 base = self.basename ()
1011 if TEXIDOC in self.option_dict:
1012 texidoc = base + '.texidoc'
1013 if os.path.exists (texidoc):
1014 str += '@include %(texidoc)s\n\n' % vars ()
1016 if VERBATIM in self.option_dict:
1017 verb = verbatim_texinfo (self.substring ('code'))
1018 str += (output[TEXINFO][VERBATIM] % vars ())
1019 if not QUOTE in self.option_dict:
1020 str = output[TEXINFO][NOQUOTE] % vars ()
1022 str += self.output_info ()
1024 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1025 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1026 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1028 if QUOTE in self.option_dict:
1029 str = output[TEXINFO][QUOTE] % vars ()
1031 # need par after image
1036 class Lilypond_file_snippet (Lilypond_snippet):
1038 name = self.substring ('filename')
1039 return '\\renameinput \"%s\"\n%s' \
1040 % (name, open (find_file (name)).read ())
1042 snippet_type_to_class = {
1043 'lilypond_file': Lilypond_file_snippet,
1044 'lilypond_block': Lilypond_snippet,
1045 'lilypond': Lilypond_snippet,
1046 'include': Include_snippet,
1049 def find_linestarts (s):
1054 i = s.find ('\n', start)
1062 nls.append (len (s))
1065 def find_toplevel_snippets (s, types):
1068 res[i] = ly.re.compile (snippet_res[format][i])
1072 ## found = dict (map (lambda x: (x, None),
1076 map (lambda x, f = found: f.setdefault (x, None),
1079 line_starts = find_linestarts (s)
1081 # We want to search for multiple regexes, without searching
1082 # the string multiple times for one regex.
1083 # Hence, we use earlier results to limit the string portion
1085 # Since every part of the string is traversed at most once for
1086 # every type of snippet, this is linear.
1092 if not found[type] or found[type][0] < index:
1094 m = res[type].search (s[index:endex])
1099 if snippet_type_to_class.has_key (type):
1100 cl = snippet_type_to_class[type]
1103 start = index + m.start ('match')
1104 line_number = line_start_idx
1105 while (line_starts[line_number] < start):
1109 snip = cl (type, m, format, line_number)
1110 found[type] = (start, snip)
1114 or found[type][0] < found[first][0]):
1119 # Limiting the search space is a cute
1120 # idea, but this *requires* to search
1121 # for possible containing blocks
1122 # first, at least as long as we do not
1123 # search for the start of blocks, but
1124 # always/directly for the entire
1125 # @block ... @end block.
1127 endex = found[first][0]
1130 snippets.append (Substring (s, index, len (s), line_start_idx))
1133 while (start > line_starts[line_start_idx+1]):
1136 (start, snip) = found[first]
1137 snippets.append (Substring (s, index, start, line_start_idx + 1))
1138 snippets.append (snip)
1140 index = start + len (snip.match.group ('match'))
1144 def filter_pipe (input, cmd):
1146 ly.progress (_ ("Opening filter `%s'") % cmd)
1148 (stdin, stdout, stderr) = os.popen3 (cmd)
1150 status = stdin.close ()
1154 output = stdout.read ()
1155 status = stdout.close ()
1156 error = stderr.read ()
1160 signal = 0x0f & status
1161 if status or (not output and error):
1162 exit_status = status >> 8
1163 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1164 ly.error (_ ("The error log is as follows:"))
1165 sys.stderr.write (error)
1166 sys.stderr.write (stderr.read ())
1175 return filter_pipe (s, filter_cmd)
1177 def is_derived_class (cl, baseclass):
1180 for b in cl.__bases__:
1181 if is_derived_class (b, baseclass):
1185 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1186 ly_names = filter (lambda x: x,
1187 map (Lilypond_snippet.basename, ly_snippets))
1188 texstr_names = filter (lambda x: x,
1189 map (Lilypond_snippet.basename, texstr_snippets))
1190 png_names = filter (lambda x: x,
1191 map (Lilypond_snippet.basename, png_snippets))
1194 def my_system (cmd):
1195 status = ly.system (cmd,
1196 ignore_error = 1, progress_p = 1)
1199 ly.error ('Process %s exited unsuccessfully.' % cmd)
1203 # the --process=CMD switch is a bad idea
1204 # it is too generic for lilypond-book.
1205 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1207 my_system (string.join ([cmd, '--backend texstr',
1208 'snippet-map.ly'] + texstr_names))
1209 for l in texstr_names:
1210 my_system ('latex %s.texstr' % l)
1213 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1215 LATEX_DOCUMENT = r'''
1218 \typeout{textwidth=\the\textwidth}
1219 \typeout{columnsep=\the\columnsep}
1220 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1224 # Do we need anything else besides `textwidth'?
1225 def get_latex_textwidth (source):
1226 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1227 preamble = source[:m.start (0)]
1228 latex_document = LATEX_DOCUMENT % vars ()
1229 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1232 m = re.search ('columns=([0-9.]*)', parameter_string)
1234 columns = string.atoi (m.group (1))
1237 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1239 columnsep = string.atof (m.group (1))
1242 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1244 textwidth = string.atof (m.group (1))
1246 textwidth = (textwidth - columnsep) / columns
1258 '.texinfo': TEXINFO,
1264 # TEXINFO: '.texinfo',
1269 class Compile_error:
1272 def write_file_map (lys, name):
1273 snippet_map = open ('snippet-map.ly', 'w')
1274 snippet_map.write ("""
1275 #(define version-seen? #t)
1276 #(ly:add-file-name-alist '(
1279 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1285 snippet_map.write ('))\n')
1287 def do_process_cmd (chunks, input_name):
1288 all_lys = filter (lambda x: is_derived_class (x.__class__,
1292 write_file_map (all_lys, input_name)
1294 filter (lambda x: is_derived_class (x.__class__,
1296 and x.ly_is_outdated (),
1299 filter (lambda x: is_derived_class (x.__class__,
1301 and x.texstr_is_outdated (),
1304 filter (lambda x: is_derived_class (x.__class__,
1306 and x.png_is_outdated (),
1309 ly.progress (_ ("Writing snippets..."))
1310 map (Lilypond_snippet.write_ly, ly_outdated)
1314 ly.progress (_ ("Processing..."))
1316 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1318 ly.progress (_ ("All snippets are up to date..."))
1321 def guess_format (input_filename):
1323 e = os.path.splitext (input_filename)[1]
1324 if e in ext2format.keys ():
1326 format = ext2format[e]
1328 ly.error (_ ("can't determine format for: %s" \
1333 def write_if_updated (file_name, lines):
1335 f = open (file_name)
1337 new_str = string.join (lines, '')
1338 if oldstr == new_str:
1339 ly.progress (_ ("%s is up to date."))
1345 ly.progress (_ ("Writing `%s'...") % file_name)
1346 open (file_name, 'w').writelines (lines)
1349 def do_file (input_filename):
1351 if not input_filename or input_filename == '-':
1352 in_handle = sys.stdin
1353 input_fullname = '<stdin>'
1355 if os.path.exists (input_filename):
1356 input_fullname = input_filename
1357 elif format == LATEX:
1358 # urg python interface to libkpathsea?
1359 input_fullname = ly.read_pipe ('kpsewhich '
1360 + input_filename)[:-1]
1362 input_fullname = find_file (input_filename)
1363 in_handle = open (input_fullname)
1365 if input_filename == '-':
1366 input_base = 'stdin'
1368 input_base = os.path.basename \
1369 (os.path.splitext (input_filename)[0])
1371 # Only default to stdout when filtering.
1372 if output_name == '-' or (not output_name and filter_cmd):
1373 output_filename = '-'
1374 output_file = sys.stdout
1377 if not os.path.isdir (output_name):
1378 os.mkdir (output_name, 0777)
1379 os.chdir (output_name)
1381 output_filename = input_base + format2ext[format]
1382 if os.path.exists (input_filename) \
1383 and os.path.exists (output_filename) \
1384 and os.path.samefile (output_filename, input_fullname):
1386 _ ("Output would overwrite input file; use --output."))
1390 ly.progress (_ ("Reading %s...") % input_fullname)
1391 source = in_handle.read ()
1394 # FIXME: Containing blocks must be first, see
1395 # find_toplevel_snippets.
1397 'multiline_comment',
1401 'singleline_comment',
1406 ly.progress (_ ("Dissecting..."))
1407 chunks = find_toplevel_snippets (source, snippet_types)
1410 global default_ly_options
1412 if not default_ly_options.has_key (LINEWIDTH):
1414 textwidth = get_latex_textwidth (source)
1415 default_ly_options[LINEWIDTH] = \
1416 '''%.0f\\pt''' % textwidth
1417 elif format == TEXINFO:
1418 for (k, v) in texinfo_linewidths.items ():
1419 # FIXME: @layout is usually not in
1422 # \input texinfo @c -*-texinfo-*-
1424 # Bluntly search first K items of
1426 # s = chunks[0].replacement_text ()
1427 if re.search (k, source[:1024]):
1428 default_ly_options[LINEWIDTH] = v
1432 write_if_updated (output_filename,
1433 [c.filter_text () for c in chunks])
1435 do_process_cmd (chunks, input_fullname)
1436 ly.progress (_ ("Compiling %s...") % output_filename)
1438 write_if_updated (output_filename,
1439 [s.replacement_text ()
1442 def process_include (snippet):
1443 os.chdir (original_dir)
1444 name = snippet.substring ('filename')
1445 ly.progress (_ ("Processing include: %s") % name)
1447 return do_file (name)
1449 include_chunks = map (process_include,
1450 filter (lambda x: is_derived_class (x.__class__,
1455 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1457 except Compile_error:
1458 os.chdir (original_dir)
1459 ly.progress (_ ("Removing `%s'") % output_filename)
1464 global format, output_name, psfonts_file
1465 global filter_cmd, process_cmd, verbose_p
1467 (sh, long) = ly.getopt_args (option_definitions)
1469 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1470 except getopt.error, s:
1471 sys.stderr.write ('\n')
1472 ly.error (_ ("getopt says: `%s'" % s))
1473 sys.stderr.write ('\n')
1483 elif o == '--filter' or o == '-F':
1486 elif o == '--format' or o == '-f':
1488 if a == 'texi-html' or a == 'texi':
1490 elif o == '--tex-backend ':
1492 elif o == '--help' or o == '-h':
1495 elif o == '--include' or o == '-I':
1496 include_path.append (os.path.join (original_dir,
1498 elif o == '--output' or o == '-o':
1500 elif o == '--process' or o == '-P':
1503 elif o == '--version' or o == '-v':
1504 ly.identify (sys.stdout)
1506 elif o == '--verbose' or o == '-V':
1508 elif o == '--psfonts':
1510 elif o == '--warranty' or o == '-w':
1517 files = do_options ()
1518 if not files or len (files) > 1:
1523 global process_cmd, format
1525 format = guess_format (files[0])
1528 if format == TEXINFO or format == HTML:
1530 if process_cmd == '':
1531 process_cmd = lilypond_binary \
1532 + ' --formats=%s --backend eps ' % formats
1535 process_cmd += string.join ([(' -I %s' % p)
1536 for p in include_path])
1538 ly.identify (sys.stderr)
1539 ly.setup_environment ()
1542 chunks = do_file (file)
1544 fontextract.verbose = verbose_p
1545 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1549 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1550 fontextract.extract_fonts (psfonts_file,
1551 [x.basename() + '.eps'
1552 for x in snippet_chunks])
1556 except Compile_error:
1559 if format == TEXINFO or format == LATEX:
1560 psfonts = os.path.join (output_name, psfonts_file)
1561 output = os.path.join (output_name,
1562 os.path.splitext (os.path.basename
1563 (file))[0]) + '.dvi'
1565 ly.warning (_ ("option --psfonts=FILE not used"))
1566 ly.warning (_ ("processing with dvips will have no fonts"))
1567 psfonts = 'PSFONTS-FILE'
1569 ly.progress (_ ("DVIPS usage:"))
1571 ly.progress (" dvips -h %(psfonts)s %(output)s" % vars ())
1574 if __name__ == '__main__':