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 = 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 PS snippet fonts into FILE')),
101 _ ("print version information")),
102 ('', 'w', 'warranty',
103 _ ("show warranty and copyright")),
106 include_path = [ly.abspath (os.getcwd ())]
107 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
109 # Only use installed binary when we are installed too.
110 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
111 lilypond_binary = 'lilypond'
117 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
120 default_ly_options = {}
123 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
127 EXAMPLEINDENT = 'exampleindent'
129 FRAGMENT = 'fragment'
134 LINEWIDTH = 'linewidth'
135 NOFRAGMENT = 'nofragment'
136 NOINDENT = 'noindent'
141 OUTPUTIMAGE = 'outputimage'
144 PREAMBLE = 'preamble'
145 PRINTFILENAME = 'printfilename'
147 RAGGEDRIGHT = 'raggedright'
148 RELATIVE = 'relative'
149 STAFFSIZE = 'staffsize'
152 VERBATIM = 'verbatim'
153 FONTLOAD = 'fontload'
156 # NOTIME has no opposite so it isn't part of this dictionary.
157 # NOQUOTE is used internally only.
159 NOFRAGMENT: FRAGMENT,
164 # Recognize special sequences in the input.
166 # (?P<name>regex) -- Assign result of REGEX to NAME.
167 # *? -- Match non-greedily.
168 # (?m) -- Multiline regex: Make ^ and $ match at each line.
169 # (?s) -- Make the dot match all characters including newline.
170 # (?x) -- Ignore whitespace in patterns.
182 (\s*(?P<options>.*?)\s*:)?\s*
190 \s*(?P<options>.*?)\s*
199 \s*(?P<options>.*?)\s*
201 \s*(?P<filename>.*?)\s*
208 (?P<code><!--\s.*?!-->)
211 'singleline_comment':
217 (?P<code><pre>.*?</pre>))''',
223 (?P<code><pre>\s.*?</pre>\s))''',
242 \s*(?P<options>.*?)\s*
253 \s*(?P<options>.*?)\s*
257 \\end\s*{lilypond})''',
265 \s*(?P<options>.*?)\s*
273 'singleline_comment':
296 \\end\s*{verbatim}))''',
305 (?P<filename>\S+))''',
309 ^[^\n]*?(?!@c\s+)[^\n]*?
313 \s*(?P<options>.*?)\s*
323 \s*(?P<options>.*?)\s*
326 ^@end\s+lilypond)\s''',
333 \s*(?P<options>.*?)\s*
344 @end\s+ignore))\s''',
346 'singleline_comment':
351 @c([ \t][^\n]*|)\n))''',
353 # Don't do this: It interferes with @code{@{}.
354 # 'verb': r'''(?P<code>@code{.*?})''',
362 @end\s+example\s))''',
368 'intertext': r',?\s*intertext=\".*?\"',
373 'intertext': r',?\s*intertext=\".*?\"',
374 'option_sep': '\s*,\s*',
378 'intertext': r',?\s*intertext=\".*?\"',
379 'option_sep': '\s*,\s*',
383 # Options without a pattern in ly_options.
398 RELATIVE: r'''\relative c%(relative_quotes)s''',
403 INDENT: r'''indent = %(indent)s''',
405 LINEWIDTH: r'''linewidth = %(linewidth)s''',
407 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
409 RAGGEDRIGHT: r'''raggedright = ##t''',
411 PACKED: r'''packed = ##t''',
416 NOTIME: r'''\context {
418 \remove Time_signature_engraver
424 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
431 FILTER: r'''<lilypond %(options)s>
441 <a href="%(base)s.ly">''',
444 <img align="center" valign="center"
445 border="0" src="%(image)s" alt="[image of music]">''',
447 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
449 QUOTE: r'''<blockquote>
463 \ifx\preLilyPondExample \undefined
468 \def\lilypondbook{}%%
469 \input %(base)s-systems.tex
470 \ifx\postLilyPondExample \undefined
477 PRINTFILENAME: '''\\texttt{%(filename)s}
480 QUOTE: r'''\begin{quotation}
485 VERBATIM: r'''\noindent
487 %(verb)s\end{verbatim}
490 FILTER: r'''\begin{lilypond}[%(options)s]
497 FILTER: r'''@lilypond[%(options)s]
503 @include %(base)s-systems.texi
507 OUTPUTIMAGE: r'''@noindent
509 @image{%(base)s,,,[image of music],%(ext)s}
513 <a href="%(base)s.ly">
514 <img align="center" valign="center"
515 border="0" src="%(image)s" alt="[image of music]">
521 PRINTFILENAME: '''@file{%(filename)s}
524 QUOTE: r'''@quotation
525 %(str)s@end quotation
532 VERBATIM: r'''@exampleindent 0
539 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
540 %%%% Options: [%(option_string)s]
542 #(set! toplevel-score-handler ly:parser-print-score)
543 #(set! toplevel-music-handler (lambda (p m)
544 (ly:parser-print-score
545 p (ly:music-scorify m p))))
547 #(define version-seen? #t)
551 #(define dump-extents #t)
552 %(font_dump_setting)s
564 %% ly snippet contents follows:
576 texinfo_linewidths = {
577 '@afourpaper': '160\\mm',
578 '@afourwide': '6.5\\in',
579 '@afourlatex': '150\\mm',
580 '@smallbook': '5\\in',
581 '@letterpaper': '6\\in',
584 def classic_lilypond_book_compatibility (key, value):
585 if key == 'singleline' and value == None:
586 return (RAGGEDRIGHT, None)
588 m = re.search ('relative\s*([-0-9])', key)
590 return ('relative', m.group (1))
592 m = re.match ('([0-9]+)pt', key)
594 return ('staffsize', m.group (1))
596 if key == 'indent' or key == 'linewidth':
597 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
599 f = float (m.group (1))
600 return (key, '%f\\%s' % (f, m.group (2)))
604 def find_file (name):
605 for i in include_path:
606 full = os.path.join (i, name)
607 if os.path.exists (full):
609 ly.error (_ ("file not found: %s") % name + '\n')
613 def verbatim_html (s):
614 return re.sub ('>', '>',
616 re.sub ('&', '&', s)))
618 def verbatim_texinfo (s):
619 return re.sub ('{', '@{',
621 re.sub ('@', '@@', s)))
623 def split_options (option_string):
625 return re.split (format_res[format]['option_sep'],
630 def replacement_text (self):
633 def filter_text (self):
634 return self.replacement_text ()
636 def ly_is_outdated (self):
639 def png_is_outdated (self):
642 class Substring (Chunk):
643 def __init__ (self, source, start, end, line_number):
647 self.line_number = line_number
649 def replacement_text (self):
650 return self.source[self.start:self.end]
652 class Snippet (Chunk):
653 def __init__ (self, type, match, format, line_number):
657 self.option_dict = {}
659 self.line_number = line_number
661 def replacement_text (self):
662 return self.match.group ('match')
664 def substring (self, s):
665 return self.match.group (s)
668 return `self.__class__` + ' type = ' + self.type
670 class Include_snippet (Snippet):
671 def processed_filename (self):
672 f = self.substring ('filename')
673 return os.path.splitext (f)[0] + format2ext[format]
675 def replacement_text (self):
676 s = self.match.group ('match')
677 f = self.substring ('filename')
679 return re.sub (f, self.processed_filename (), s)
681 class Lilypond_snippet (Snippet):
682 def __init__ (self, type, match, format, line_number):
683 Snippet.__init__ (self, type, match, format, line_number)
684 os = match.group ('options')
686 self.do_options (os, self.type)
689 return self.substring ('code')
694 return self.compose_ly (s)
697 def do_options (self, option_string, type):
698 self.option_dict = {}
700 options = split_options (option_string)
703 if string.find (i, '=') > 0:
704 (key, value) = re.split ('\s*=\s*', i)
705 self.option_dict[key] = value
707 if i in no_options.keys ():
708 if no_options[i] in self.option_dict.keys ():
709 del self.option_dict[no_options[i]]
711 self.option_dict[i] = None
713 has_linewidth = self.option_dict.has_key (LINEWIDTH)
714 no_linewidth_value = 0
716 # If LINEWIDTH is used without parameter, set it to default.
717 if has_linewidth and self.option_dict[LINEWIDTH] == None:
718 no_linewidth_value = 1
719 del self.option_dict[LINEWIDTH]
721 for i in default_ly_options.keys ():
722 if i not in self.option_dict.keys ():
723 self.option_dict[i] = default_ly_options[i]
725 if not has_linewidth:
726 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
727 self.option_dict[RAGGEDRIGHT] = None
729 if type == 'lilypond':
730 if LINEWIDTH in self.option_dict.keys ():
731 del self.option_dict[LINEWIDTH]
733 if RAGGEDRIGHT in self.option_dict.keys ():
734 if LINEWIDTH in self.option_dict.keys ():
735 del self.option_dict[LINEWIDTH]
737 if QUOTE in self.option_dict.keys () or type == 'lilypond':
738 if LINEWIDTH in self.option_dict.keys ():
739 del self.option_dict[LINEWIDTH]
741 if not INDENT in self.option_dict.keys ():
742 self.option_dict[INDENT] = '0\\mm'
744 # The QUOTE pattern from ly_options only emits the `linewidth'
746 if has_linewidth and QUOTE in self.option_dict.keys ():
747 if no_linewidth_value:
748 del self.option_dict[LINEWIDTH]
750 del self.option_dict[QUOTE]
752 def compose_ly (self, code):
753 if FRAGMENT in self.option_dict.keys ():
761 # The original concept of the `exampleindent' option is broken.
762 # It is not possible to get a sane value for @exampleindent at all
763 # without processing the document itself. Saying
771 # causes ugly results with the DVI backend of texinfo since the
772 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
773 # value). Executing the above code changes the environment
774 # indentation to an unknown value because we don't know the amount
775 # of 1em in advance since it is font-dependent. Modifying
776 # @exampleindent in the middle of a document is simply not
777 # supported within texinfo.
779 # As a consequence, the only function of @exampleindent is now to
780 # specify the amount of indentation for the `quote' option.
782 # To set @exampleindent locally to zero, we use the @format
783 # environment for non-quoted snippets.
784 override[EXAMPLEINDENT] = r'0.4\in'
785 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
786 override.update (default_ly_options)
789 for (key, value) in self.option_dict.items ():
791 option_list.append (key)
793 option_list.append (key + '=' + value)
794 option_string = string.join (option_list, ',')
797 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
798 for a in compose_types:
801 for (key, value) in self.option_dict.items ():
803 classic_lilypond_book_compatibility (key, value)
807 (_ ("deprecated ly-option used: %s=%s" \
810 (_ ("compatibility mode translation: %s=%s" \
814 (_ ("deprecated ly-option used: %s" \
817 (_ ("compatibility mode translation: %s" \
820 (key, value) = (c_key, c_value)
823 override[key] = value
825 if not override.has_key (key):
829 for type in compose_types:
830 if ly_options[type].has_key (key):
831 compose_dict[type].append (ly_options[type][key])
835 if not found and key not in simple_options:
836 ly.warning (_ ("ignoring unknown ly option: %s") % key)
839 if RELATIVE in override.keys () and override[RELATIVE]:
840 relative = string.atoi (override[RELATIVE])
846 relative_quotes += ',' * (- relative)
848 relative_quotes += "'" * relative
850 program_name = __main__.program_name
852 paper_string = string.join (compose_dict[PAPER],
854 layout_string = string.join (compose_dict[LAYOUT],
856 notes_string = string.join (compose_dict[NOTES],
858 preamble_string = string.join (compose_dict[PREAMBLE],
861 font_dump_setting = ''
862 if FONTLOAD in self.option_dict:
863 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
865 return (PREAMBLE_LY + body) % vars ()
870 self.hash = abs (hash (self.full_ly ()))
875 return 'lily-%d' % self.get_hash ()
879 outf = open (self.basename () + '.ly', 'w')
880 outf.write (self.full_ly ())
882 open (self.basename () + '.txt', 'w').write ('image of music')
884 def ly_is_outdated (self):
885 base = self.basename ()
887 tex_file = '%s.tex' % base
888 eps_file = '%s.eps' % base
889 system_file = '%s-systems.tex' % base
890 ly_file = '%s.ly' % base
891 ok = os.path.exists (ly_file) \
892 and os.path.exists (system_file)\
893 and os.stat (system_file)[stat.ST_SIZE] \
894 and re.match ('% eof', open (system_file).readlines ()[-1])
895 if ok and (use_hash_p \
896 or self.ly () == open (ly_file).read ()):
897 # TODO: Do something smart with target formats
898 # (ps, png) and m/ctimes.
902 def png_is_outdated (self):
903 base = self.basename ()
904 ok = self.ly_is_outdated ()
905 if format == HTML or format == TEXINFO:
906 ok = ok and (os.path.exists (base + '.png')
907 or glob.glob (base + '-page*.png'))
909 def texstr_is_outdated (self):
913 base = self.basename ()
914 ok = self.ly_is_outdated ()
915 ok = ok and (os.path.exists (base + '.texstr'))
918 def filter_text (self):
919 code = self.substring ('code')
920 s = run_filter (code)
923 'options': self.match.group ('options')
926 return output[self.format][FILTER] % d
928 def replacement_text (self):
929 func = Lilypond_snippet.__dict__['output_' + self.format]
932 def get_images (self):
933 base = self.basename ()
935 single = '%(base)s.png' % vars ()
936 multiple = '%(base)s-page1.png' % vars ()
938 if os.path.exists (multiple) \
939 and (not os.path.exists (single) \
940 or (os.stat (multiple)[stat.ST_MTIME] \
941 > os.stat (single)[stat.ST_MTIME])):
942 images = glob.glob ('%(base)s-page*.png' % vars ())
945 def output_html (self):
947 base = self.basename ()
949 str += self.output_print_filename (HTML)
950 if VERBATIM in self.option_dict:
951 verb = verbatim_html (self.substring ('code'))
952 str += write (output[HTML][VERBATIM] % vars ())
953 if QUOTE in self.option_dict:
954 str = output[HTML][QUOTE] % vars ()
956 str += output[HTML][BEFORE] % vars ()
957 for image in self.get_images ():
958 (base, ext) = os.path.splitext (image)
959 str += output[HTML][OUTPUT] % vars ()
960 str += output[HTML][AFTER] % vars ()
963 def output_info (self):
965 for image in self.get_images ():
966 (base, ext) = os.path.splitext (image)
968 # URG, makeinfo implicitly prepends dot to extension.
969 # Specifying no extension is most robust.
971 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
973 base = self.basename ()
974 str += output[format][OUTPUT] % vars ()
977 def output_latex (self):
979 base = self.basename ()
981 str += self.output_print_filename (LATEX)
982 if VERBATIM in self.option_dict:
983 verb = self.substring ('code')
984 str += (output[LATEX][VERBATIM] % vars ())
985 if QUOTE in self.option_dict:
986 str = output[LATEX][QUOTE] % vars ()
988 str += (output[LATEX][OUTPUT] % vars ())
991 def output_print_filename (self, format):
993 if PRINTFILENAME in self.option_dict:
994 base = self.basename ()
995 filename = self.substring ('filename')
996 str = output[format][PRINTFILENAME] % vars ()
1000 def output_texinfo (self):
1002 if self.output_print_filename (TEXINFO):
1004 + self.output_print_filename (HTML)
1007 + self.output_print_filename (LATEX)
1009 base = self.basename ()
1010 if TEXIDOC in self.option_dict:
1011 texidoc = base + '.texidoc'
1012 if os.path.exists (texidoc):
1013 str += '@include %(texidoc)s\n\n' % vars ()
1015 if VERBATIM in self.option_dict:
1016 verb = verbatim_texinfo (self.substring ('code'))
1017 str += (output[TEXINFO][VERBATIM] % vars ())
1018 if not QUOTE in self.option_dict:
1019 str = output[TEXINFO][NOQUOTE] % vars ()
1021 str += self.output_info ()
1023 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1024 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1025 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1027 if QUOTE in self.option_dict:
1028 str = output[TEXINFO][QUOTE] % vars ()
1030 # need par after image
1035 class Lilypond_file_snippet (Lilypond_snippet):
1037 name = self.substring ('filename')
1038 return '\\renameinput \"%s\"\n%s' \
1039 % (name, open (find_file (name)).read ())
1041 snippet_type_to_class = {
1042 'lilypond_file': Lilypond_file_snippet,
1043 'lilypond_block': Lilypond_snippet,
1044 'lilypond': Lilypond_snippet,
1045 'include': Include_snippet,
1048 def find_linestarts (s):
1053 i = s.find ('\n', start)
1061 nls.append (len (s))
1064 def find_toplevel_snippets (s, types):
1067 res[i] = ly.re.compile (snippet_res[format][i])
1071 ## found = dict (map (lambda x: (x, None),
1075 map (lambda x, f = found: f.setdefault (x, None),
1078 line_starts = find_linestarts (s)
1080 # We want to search for multiple regexes, without searching
1081 # the string multiple times for one regex.
1082 # Hence, we use earlier results to limit the string portion
1084 # Since every part of the string is traversed at most once for
1085 # every type of snippet, this is linear.
1091 if not found[type] or found[type][0] < index:
1093 m = res[type].search (s[index:endex])
1098 if snippet_type_to_class.has_key (type):
1099 cl = snippet_type_to_class[type]
1102 start = index + m.start ('match')
1103 line_number = line_start_idx
1104 while (line_starts[line_number] < start):
1108 snip = cl (type, m, format, line_number)
1109 found[type] = (start, snip)
1113 or found[type][0] < found[first][0]):
1118 # Limiting the search space is a cute
1119 # idea, but this *requires* to search
1120 # for possible containing blocks
1121 # first, at least as long as we do not
1122 # search for the start of blocks, but
1123 # always/directly for the entire
1124 # @block ... @end block.
1126 endex = found[first][0]
1129 snippets.append (Substring (s, index, len (s), line_start_idx))
1132 while (start > line_starts[line_start_idx+1]):
1135 (start, snip) = found[first]
1136 snippets.append (Substring (s, index, start, line_start_idx + 1))
1137 snippets.append (snip)
1139 index = start + len (snip.match.group ('match'))
1143 def filter_pipe (input, cmd):
1145 ly.progress (_ ("Opening filter `%s'") % cmd)
1147 (stdin, stdout, stderr) = os.popen3 (cmd)
1149 status = stdin.close ()
1153 output = stdout.read ()
1154 status = stdout.close ()
1155 error = stderr.read ()
1159 signal = 0x0f & status
1160 if status or (not output and error):
1161 exit_status = status >> 8
1162 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1163 ly.error (_ ("The error log is as follows:"))
1164 sys.stderr.write (error)
1165 sys.stderr.write (stderr.read ())
1174 return filter_pipe (s, filter_cmd)
1176 def is_derived_class (cl, baseclass):
1179 for b in cl.__bases__:
1180 if is_derived_class (b, baseclass):
1184 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1185 ly_names = filter (lambda x: x,
1186 map (Lilypond_snippet.basename, ly_snippets))
1187 texstr_names = filter (lambda x: x,
1188 map (Lilypond_snippet.basename, texstr_snippets))
1189 png_names = filter (lambda x: x,
1190 map (Lilypond_snippet.basename, png_snippets))
1193 def my_system (cmd):
1194 status = ly.system (cmd,
1195 ignore_error = 1, progress_p = 1)
1198 ly.error ('Process %s exited unsuccessfully.' % cmd)
1202 # the --process=CMD switch is a bad idea
1203 # it is too generic for lilypond-book.
1204 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1206 my_system (string.join ([cmd, '--backend texstr',
1207 'snippet-map.ly'] + texstr_names))
1208 for l in texstr_names:
1209 my_system ('latex %s.texstr' % l)
1212 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1214 LATEX_DOCUMENT = r'''
1217 \typeout{textwidth=\the\textwidth}
1218 \typeout{columnsep=\the\columnsep}
1219 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1223 # Do we need anything else besides `textwidth'?
1224 def get_latex_textwidth (source):
1225 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1226 preamble = source[:m.start (0)]
1227 latex_document = LATEX_DOCUMENT % vars ()
1228 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1231 m = re.search ('columns=([0-9.]*)', parameter_string)
1233 columns = string.atoi (m.group (1))
1236 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1238 columnsep = string.atof (m.group (1))
1241 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1243 textwidth = string.atof (m.group (1))
1245 textwidth = (textwidth - columnsep) / columns
1257 '.texinfo': TEXINFO,
1263 # TEXINFO: '.texinfo',
1268 class Compile_error:
1271 def write_file_map (lys, name):
1272 snippet_map = open ('snippet-map.ly', 'w')
1273 snippet_map.write ("""
1274 #(define version-seen? #t)
1275 #(ly:add-file-name-alist '(
1278 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1284 snippet_map.write ('))\n')
1286 def do_process_cmd (chunks, input_name):
1287 all_lys = filter (lambda x: is_derived_class (x.__class__,
1291 write_file_map (all_lys, input_name)
1293 filter (lambda x: is_derived_class (x.__class__,
1295 and x.ly_is_outdated (),
1298 filter (lambda x: is_derived_class (x.__class__,
1300 and x.texstr_is_outdated (),
1303 filter (lambda x: is_derived_class (x.__class__,
1305 and x.png_is_outdated (),
1308 ly.progress (_ ("Writing snippets..."))
1309 map (Lilypond_snippet.write_ly, ly_outdated)
1313 ly.progress (_ ("Processing..."))
1315 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1317 ly.progress (_ ("All snippets are up to date..."))
1320 def guess_format (input_filename):
1322 e = os.path.splitext (input_filename)[1]
1323 if e in ext2format.keys ():
1325 format = ext2format[e]
1327 ly.error (_ ("can't determine format for: %s" \
1332 def write_if_updated (file_name, lines):
1334 f = open (file_name)
1336 new_str = string.join (lines, '')
1338 ly.progress (_ ("Output file is up to date."))
1343 ly.progress (_ ("Writing output file."))
1344 open (file_name, 'w').writelines (lines)
1346 def do_file (input_filename):
1348 if not input_filename or input_filename == '-':
1349 in_handle = sys.stdin
1350 input_fullname = '<stdin>'
1352 if os.path.exists (input_filename):
1353 input_fullname = input_filename
1354 elif format == LATEX:
1355 # urg python interface to libkpathsea?
1356 input_fullname = ly.read_pipe ('kpsewhich '
1357 + input_filename)[:-1]
1359 input_fullname = find_file (input_filename)
1360 in_handle = open (input_fullname)
1362 if input_filename == '-':
1363 input_base = 'stdin'
1365 input_base = os.path.basename \
1366 (os.path.splitext (input_filename)[0])
1368 # Only default to stdout when filtering.
1369 if output_name == '-' or (not output_name and filter_cmd):
1370 output_filename = '-'
1371 output_file = sys.stdout
1374 if not os.path.isdir (output_name):
1375 os.mkdir (output_name, 0777)
1376 os.chdir (output_name)
1378 output_filename = input_base + format2ext[format]
1379 if os.path.exists (input_filename) \
1380 and os.path.exists (output_filename) \
1381 and os.path.samefile (output_filename, input_fullname):
1383 _ ("Output would overwrite input file; use --output."))
1387 ly.progress (_ ("Reading %s...") % input_fullname)
1388 source = in_handle.read ()
1391 # FIXME: Containing blocks must be first, see
1392 # find_toplevel_snippets.
1394 'multiline_comment',
1398 'singleline_comment',
1403 ly.progress (_ ("Dissecting..."))
1404 chunks = find_toplevel_snippets (source, snippet_types)
1407 global default_ly_options
1409 if not default_ly_options.has_key (LINEWIDTH):
1411 textwidth = get_latex_textwidth (source)
1412 default_ly_options[LINEWIDTH] = \
1413 '''%.0f\\pt''' % textwidth
1414 elif format == TEXINFO:
1415 for (k, v) in texinfo_linewidths.items ():
1416 # FIXME: @layout is usually not in
1419 # \input texinfo @c -*-texinfo-*-
1421 # Bluntly search first K items of
1423 # s = chunks[0].replacement_text ()
1424 if re.search (k, source[:1024]):
1425 default_ly_options[LINEWIDTH] = v
1429 write_if_updated (output_filename,
1430 [c.filter_text () for c in chunks])
1432 do_process_cmd (chunks, input_fullname)
1433 ly.progress (_ ("Compiling %s...") % output_filename)
1434 write_if_updated (output_filename,
1435 [s.replacement_text ()
1441 def process_include (snippet):
1442 os.chdir (original_dir)
1443 name = snippet.substring ('filename')
1444 ly.progress (_ ("Processing include: %s") % name)
1446 return do_file (name)
1448 include_chunks = map (process_include,
1449 filter (lambda x: is_derived_class (x.__class__,
1454 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1456 except Compile_error:
1457 os.chdir (original_dir)
1458 ly.progress (_ ("Removing `%s'") % output_filename)
1463 global format, output_name, psfonts_file
1464 global filter_cmd, process_cmd, verbose_p
1466 (sh, long) = ly.getopt_args (option_definitions)
1468 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1469 except getopt.error, s:
1470 sys.stderr.write ('\n')
1471 ly.error (_ ("getopt says: `%s'" % s))
1472 sys.stderr.write ('\n')
1482 elif o == '--filter' or o == '-F':
1485 elif o == '--format' or o == '-f':
1487 if a == 'texi-html' or a == 'texi':
1489 elif o == '--tex-backend ':
1491 elif o == '--help' or o == '-h':
1494 elif o == '--include' or o == '-I':
1495 include_path.append (os.path.join (original_dir,
1497 elif o == '--output' or o == '-o':
1499 elif o == '--outdir':
1501 elif o == '--process' or o == '-P':
1504 elif o == '--version' or o == '-v':
1505 ly.identify (sys.stdout)
1507 elif o == '--verbose' or o == '-V':
1509 elif o == '--psfonts':
1511 elif o == '--warranty' or o == '-w':
1518 files = do_options ()
1520 ly.warning ("Need to have command line option")
1524 global process_cmd, format
1526 format = guess_format (files[0])
1529 if format == TEXINFO or format == HTML:
1531 if process_cmd == '':
1532 process_cmd = lilypond_binary \
1533 + ' --formats=%s --backend eps ' % formats
1536 process_cmd += string.join ([(' -I %s' % p)
1537 for p in include_path])
1539 ly.identify (sys.stderr)
1540 ly.setup_environment ()
1543 chunks = do_file (file)
1545 fontextract.verbose = verbose_p
1546 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1549 fontextract.extract_fonts (psfonts_file,
1550 [x.basename() + '.eps'
1551 for x in snippet_chunks])
1553 except Compile_error:
1557 if __name__ == '__main__':