7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
44 for d in ['@lilypond_datadir@',
46 sys.path.insert (0, os.path.join (d, 'python'))
48 # dynamic relocation, for GUB binaries.
49 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
50 for p in ['share', 'lib']:
51 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
52 sys.path.insert (0, datadir)
61 program_version = '@TOPLEVEL_VERSION@'
62 program_name = os.path.basename (sys.argv[0])
64 original_dir = os.getcwd ()
68 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
72 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
73 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
74 lilypond-book --process='lilypond -I include' BOOK
77 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
78 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
81 ################################################################
83 if global_options.verbose:
84 raise _ ('Exiting (%d)...') % i
89 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
95 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
98 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
100 def ps_page_count (ps_name):
101 header = open (ps_name).read (1024)
102 m = re.search ('\n%%Pages: ([0-9]+)', header)
104 return string.atoi (m.group (1))
109 sys.stdout.write ('''
116 ''' % ( _('Copyright (c) %s by') % '2001--2006',
118 _('Distributed under terms of the GNU General Public License.'),
119 _('It comes with NO WARRANTY.')))
122 def get_option_parser ():
123 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
124 version="@TOPLEVEL_VERSION@",
125 description=help_summary)
127 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
130 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
132 p.add_option ('-f', '--format',
133 help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
135 p.add_option ("-I", '--include', help=_('add DIR to include path'),
137 action='append', dest='include_path',
138 default=[os.path.abspath (os.getcwd ())])
140 p.add_option ("-o", '--output', help=_('write output to DIR'),
142 action='store', dest='output_name',
144 p.add_option ('-P', '--process', metavar=_("COMMAND"),
145 help = _ ("process ly_files using COMMAND FILE..."),
147 dest='process_cmd', default='lilypond -b eps')
149 p.add_option ('--pdf',
152 help="Create PDF files for use with PDFTeX",
155 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
156 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
157 '''must use this with dvips -h INPUT.psfonts'''),
159 p.add_option ('-V', '--verbose', help=_("be verbose"),
164 p.add_option ('-w', '--warranty',
165 help=_("show warranty and copyright"),
169 p.add_option_group ('bugs',
170 description='''Report bugs via http://post.gmane.org/post.php'''
171 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
175 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
177 # Only use installed binary when we are installed too.
178 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
179 lilypond_binary = 'lilypond'
181 global_options = None
184 default_ly_options = { 'alt': "[image of music]" }
187 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
191 EXAMPLEINDENT = 'exampleindent'
193 FRAGMENT = 'fragment'
198 LINE_WIDTH = 'line-width'
199 NOFRAGMENT = 'nofragment'
200 NOINDENT = 'noindent'
205 OUTPUTIMAGE = 'outputimage'
208 PREAMBLE = 'preamble'
209 PRINTFILENAME = 'printfilename'
211 RAGGED_RIGHT = 'ragged-right'
212 RELATIVE = 'relative'
213 STAFFSIZE = 'staffsize'
216 VERBATIM = 'verbatim'
217 FONTLOAD = 'fontload'
218 FILENAME = 'filename'
222 # NOTIME has no opposite so it isn't part of this dictionary.
223 # NOQUOTE is used internally only.
225 NOFRAGMENT: FRAGMENT,
230 # Recognize special sequences in the input.
232 # (?P<name>regex) -- Assign result of REGEX to NAME.
233 # *? -- Match non-greedily.
234 # (?m) -- Multiline regex: Make ^ and $ match at each line.
235 # (?s) -- Make the dot match all characters including newline.
236 # (?x) -- Ignore whitespace in patterns.
248 (\s*(?P<options>.*?)\s*:)?\s*
256 \s*(?P<options>.*?)\s*
265 \s*(?P<options>.*?)\s*
267 \s*(?P<filename>.*?)\s*
274 (?P<code><!--\s.*?!-->)
277 'singleline_comment':
283 (?P<code><pre>.*?</pre>))''',
289 (?P<code><pre>\s.*?</pre>\s))''',
308 \s*(?P<options>.*?)\s*
319 \s*(?P<options>.*?)\s*
323 \\end\s*{lilypond})''',
331 \s*(?P<options>.*?)\s*
339 'singleline_comment':
362 \\end\s*{verbatim}))''',
371 (?P<filename>\S+))''',
375 ^[^\n]*?(?!@c\s+)[^\n]*?
379 \s*(?P<options>.*?)\s*
389 \s*(?P<options>.*?)\s*
392 ^@end\s+lilypond)\s''',
399 \s*(?P<options>.*?)\s*
410 @end\s+ignore))\s''',
412 'singleline_comment':
417 @c([ \t][^\n]*|)\n))''',
419 # Don't do this: It interferes with @code{@{}.
420 # 'verb': r'''(?P<code>@code{.*?})''',
428 @end\s+example\s))''',
437 'intertext': r',?\s*intertext=\".*?\"',
442 'intertext': r',?\s*intertext=\".*?\"',
443 'option_sep': '\s*,\s*',
447 'intertext': r',?\s*intertext=\".*?\"',
448 'option_sep': '\s*,\s*',
452 # Options without a pattern in ly_options.
469 RELATIVE: r'''\relative c%(relative_quotes)s''',
474 INDENT: r'''indent = %(indent)s''',
476 LINE_WIDTH: r'''line-width = %(line-width)s''',
478 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
480 RAGGED_RIGHT: r'''ragged-right = ##t''',
482 PACKED: r'''packed = ##t''',
494 \remove Time_signature_engraver
500 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
507 FILTER: r'''<lilypond %(options)s>
517 <a href="%(base)s.ly">''',
520 <img align="center" valign="center"
521 border="0" src="%(image)s" alt="%(alt)s">''',
523 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
525 QUOTE: r'''<blockquote>
539 \ifx\preLilyPondExample \undefined%%
542 \preLilyPondExample%%
544 \def\lilypondbook{}%%
545 \input %(base)s-systems.tex%%
546 \ifx\postLilyPondExample \undefined%%
549 \postLilyPondExample%%
553 PRINTFILENAME: '''\\texttt{%(filename)s}
556 QUOTE: r'''\begin{quotation}%(str)s
559 VERBATIM: r'''\noindent
560 \begin{verbatim}%(verb)s\end{verbatim}''',
562 FILTER: r'''\begin{lilypond}[%(options)s]
569 FILTER: r'''@lilypond[%(options)s]
575 @include %(base)s-systems.texi
579 OUTPUTIMAGE: r'''@noindent
581 @image{%(base)s,,,%(alt)s,%(ext)s}
585 <a href="%(base)s.ly">
586 <img align="center" valign="center"
587 border="0" src="%(image)s" alt="%(alt)s">
595 <a href="%(base)s.ly">
603 QUOTE: r'''@quotation
604 %(str)s@end quotation
611 VERBATIM: r'''@exampleindent 0
613 %(verb)s@end verbatim
619 # Maintain line numbers.
624 for f in [HTML, LATEX]:
625 for s in (QUOTE, VERBATIM):
626 output[f][s] = output[f][s].replace("\n"," ")
629 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
630 %%%% Options: [%(option_string)s]
631 \\include "lilypond-book-preamble.ly"
639 %% ****************************************************************
640 %% Start cut-&-pastable-section
641 %% ****************************************************************
644 #(define dump-extents #t)
645 %(font_dump_setting)s
659 %% ****************************************************************
660 %% ly snippet contents follows:
661 %% ****************************************************************
665 %% ****************************************************************
667 %% ****************************************************************
674 %% ****************************************************************
676 %% ****************************************************************
680 %% ****************************************************************
682 %% ****************************************************************
685 texinfo_line_widths = {
686 '@afourpaper': '160\\mm',
687 '@afourwide': '6.5\\in',
688 '@afourlatex': '150\\mm',
689 '@smallbook': '5\\in',
690 '@letterpaper': '6\\in',
693 def classic_lilypond_book_compatibility (key, value):
694 if key == 'singleline' and value == None:
695 return (RAGGED_RIGHT, None)
697 m = re.search ('relative\s*([-0-9])', key)
699 return ('relative', m.group (1))
701 m = re.match ('([0-9]+)pt', key)
703 return ('staffsize', m.group (1))
705 if key == 'indent' or key == 'line-width':
706 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
708 f = float (m.group (1))
709 return (key, '%f\\%s' % (f, m.group (2)))
713 def find_file (name):
714 for i in global_options.include_path:
715 full = os.path.join (i, name)
716 if os.path.exists (full):
719 error (_ ("file not found: %s") % name + '\n')
723 def verbatim_html (s):
724 return re.sub ('>', '>',
726 re.sub ('&', '&', s)))
728 def split_options (option_string):
730 if global_options.format == HTML:
731 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
732 for i in range(len(options)):
733 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
736 return re.split (format_res[global_options.format]['option_sep'],
740 def set_default_options (source):
741 global default_ly_options
742 if not default_ly_options.has_key (LINE_WIDTH):
743 if global_options.format == LATEX:
744 textwidth = get_latex_textwidth (source)
745 default_ly_options[LINE_WIDTH] = \
746 '''%.0f\\pt''' % textwidth
747 elif global_options.format == TEXINFO:
748 for (k, v) in texinfo_line_widths.items ():
749 # FIXME: @layout is usually not in
752 # \input texinfo @c -*-texinfo-*-
754 # Bluntly search first K items of
756 # s = chunks[0].replacement_text ()
757 if re.search (k, source[:1024]):
758 default_ly_options[LINE_WIDTH] = v
762 def replacement_text (self):
765 def filter_text (self):
766 return self.replacement_text ()
768 def ly_is_outdated (self):
771 def png_is_outdated (self):
777 class Substring (Chunk):
778 def __init__ (self, source, start, end, line_number):
782 self.line_number = line_number
783 self.override_text = None
788 def replacement_text (self):
789 if self.override_text:
790 return self.override_text
792 return self.source[self.start:self.end]
794 class Snippet (Chunk):
795 def __init__ (self, type, match, format, line_number):
799 self.option_dict = {}
801 self.line_number = line_number
803 def replacement_text (self):
804 return self.match.group ('match')
806 def substring (self, s):
807 return self.match.group (s)
810 return `self.__class__` + ' type = ' + self.type
812 class Include_snippet (Snippet):
813 def processed_filename (self):
814 f = self.substring ('filename')
815 return os.path.splitext (f)[0] + format2ext[global_options.format]
817 def replacement_text (self):
818 s = self.match.group ('match')
819 f = self.substring ('filename')
821 return re.sub (f, self.processed_filename (), s)
823 class Lilypond_snippet (Snippet):
824 def __init__ (self, type, match, format, line_number):
825 Snippet.__init__ (self, type, match, format, line_number)
826 os = match.group ('options')
827 self.do_options (os, self.type)
830 return self.substring ('code')
835 return self.compose_ly (s)
838 def do_options (self, option_string, type):
839 self.option_dict = {}
841 options = split_options (option_string)
844 if string.find (i, '=') > 0:
845 (key, value) = re.split ('\s*=\s*', i)
846 self.option_dict[key] = value
848 if i in no_options.keys ():
849 if no_options[i] in self.option_dict.keys ():
850 del self.option_dict[no_options[i]]
852 self.option_dict[i] = None
854 has_line_width = self.option_dict.has_key (LINE_WIDTH)
855 no_line_width_value = 0
857 # If LINE_WIDTH is used without parameter, set it to default.
858 if has_line_width and self.option_dict[LINE_WIDTH] == None:
859 no_line_width_value = 1
860 del self.option_dict[LINE_WIDTH]
862 for i in default_ly_options.keys ():
863 if i not in self.option_dict.keys ():
864 self.option_dict[i] = default_ly_options[i]
866 if not has_line_width:
867 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
868 self.option_dict[RAGGED_RIGHT] = None
870 if type == 'lilypond':
871 if LINE_WIDTH in self.option_dict.keys ():
872 del self.option_dict[LINE_WIDTH]
874 if RAGGED_RIGHT in self.option_dict.keys ():
875 if LINE_WIDTH in self.option_dict.keys ():
876 del self.option_dict[LINE_WIDTH]
878 if QUOTE in self.option_dict.keys () or type == 'lilypond':
879 if LINE_WIDTH in self.option_dict.keys ():
880 del self.option_dict[LINE_WIDTH]
882 if not INDENT in self.option_dict.keys ():
883 self.option_dict[INDENT] = '0\\mm'
885 # The QUOTE pattern from ly_options only emits the `line-width'
887 if has_line_width and QUOTE in self.option_dict.keys ():
888 if no_line_width_value:
889 del self.option_dict[LINE_WIDTH]
891 del self.option_dict[QUOTE]
893 def compose_ly (self, code):
894 if FRAGMENT in self.option_dict.keys ():
902 # The original concept of the `exampleindent' option is broken.
903 # It is not possible to get a sane value for @exampleindent at all
904 # without processing the document itself. Saying
912 # causes ugly results with the DVI backend of texinfo since the
913 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
914 # value). Executing the above code changes the environment
915 # indentation to an unknown value because we don't know the amount
916 # of 1em in advance since it is font-dependent. Modifying
917 # @exampleindent in the middle of a document is simply not
918 # supported within texinfo.
920 # As a consequence, the only function of @exampleindent is now to
921 # specify the amount of indentation for the `quote' option.
923 # To set @exampleindent locally to zero, we use the @format
924 # environment for non-quoted snippets.
925 override[EXAMPLEINDENT] = r'0.4\in'
926 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
927 override.update (default_ly_options)
930 for (key, value) in self.option_dict.items ():
932 option_list.append (key)
934 option_list.append (key + '=' + value)
935 option_string = string.join (option_list, ',')
938 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
939 for a in compose_types:
942 for (key, value) in self.option_dict.items ():
944 classic_lilypond_book_compatibility (key, value)
948 (_ ("deprecated ly-option used: %s=%s" \
951 (_ ("compatibility mode translation: %s=%s" \
955 (_ ("deprecated ly-option used: %s" \
958 (_ ("compatibility mode translation: %s" \
961 (key, value) = (c_key, c_value)
964 override[key] = value
966 if not override.has_key (key):
970 for type in compose_types:
971 if ly_options[type].has_key (key):
972 compose_dict[type].append (ly_options[type][key])
976 if not found and key not in simple_options:
977 warning (_ ("ignoring unknown ly option: %s") % key)
980 if RELATIVE in override.keys () and override[RELATIVE]:
981 relative = int (override[RELATIVE])
987 relative_quotes += ',' * (- relative)
989 relative_quotes += "'" * relative
991 paper_string = string.join (compose_dict[PAPER],
993 layout_string = string.join (compose_dict[LAYOUT],
995 notes_string = string.join (compose_dict[NOTES],
997 preamble_string = string.join (compose_dict[PREAMBLE],
1000 font_dump_setting = ''
1001 if FONTLOAD in self.option_dict:
1002 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1004 d = globals().copy()
1006 return (PREAMBLE_LY + body) % d
1009 def get_hash (self):
1011 self.hash = abs (hash (self.full_ly ()))
1014 def basename (self):
1015 if FILENAME in self.option_dict:
1016 return self.option_dict[FILENAME]
1017 if global_options.use_hash:
1018 return 'lily-%d' % self.get_hash ()
1021 def write_ly (self):
1022 outf = open (self.basename () + '.ly', 'w')
1023 outf.write (self.full_ly ())
1025 open (self.basename () + '.txt', 'w').write ('image of music')
1027 def ly_is_outdated (self):
1028 base = self.basename ()
1030 tex_file = '%s.tex' % base
1031 eps_file = '%s.eps' % base
1032 system_file = '%s-systems.tex' % base
1033 ly_file = '%s.ly' % base
1034 ok = os.path.exists (ly_file) \
1035 and os.path.exists (system_file)\
1036 and os.stat (system_file)[stat.ST_SIZE] \
1037 and re.match ('% eof', open (system_file).readlines ()[-1])
1038 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1039 ok = (self.full_ly () == open (ly_file).read ())
1041 # TODO: Do something smart with target formats
1042 # (ps, png) and m/ctimes.
1046 def png_is_outdated (self):
1047 base = self.basename ()
1048 ok = not self.ly_is_outdated ()
1049 if global_options.format in (HTML, TEXINFO):
1050 ok = ok and os.path.exists (base + '.eps')
1054 page_count = ps_page_count (base + '.eps')
1057 ok = ok and os.path.exists (base + '.png')
1059 elif page_count > 1:
1060 for a in range (1, page_count + 1):
1061 ok = ok and os.path.exists (base + '-page%d.png' % a)
1065 def texstr_is_outdated (self):
1069 base = self.basename ()
1070 ok = self.ly_is_outdated ()
1071 ok = ok and (os.path.exists (base + '.texstr'))
1074 def filter_text (self):
1075 code = self.substring ('code')
1076 s = run_filter (code)
1079 'options': self.match.group ('options')
1082 return output[self.format][FILTER] % d
1084 def replacement_text (self):
1085 func = Lilypond_snippet.__dict__['output_' + self.format]
1088 def get_images (self):
1089 base = self.basename ()
1091 single = '%(base)s.png' % vars ()
1092 multiple = '%(base)s-page1.png' % vars ()
1094 if os.path.exists (multiple) \
1095 and (not os.path.exists (single) \
1096 or (os.stat (multiple)[stat.ST_MTIME] \
1097 > os.stat (single)[stat.ST_MTIME])):
1098 count = ps_page_count ('%(base)s.eps' % vars ())
1099 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1100 images = tuple (images)
1103 def output_html (self):
1105 base = self.basename ()
1106 if global_options.format == HTML:
1107 str += self.output_print_filename (HTML)
1108 if VERBATIM in self.option_dict:
1109 verb = verbatim_html (self.substring ('code'))
1110 str += output[HTML][VERBATIM] % vars ()
1111 if QUOTE in self.option_dict:
1112 str = output[HTML][QUOTE] % vars ()
1114 str += output[HTML][BEFORE] % vars ()
1115 for image in self.get_images ():
1116 (base, ext) = os.path.splitext (image)
1117 alt = self.option_dict[ALT]
1118 str += output[HTML][OUTPUT] % vars ()
1119 str += output[HTML][AFTER] % vars ()
1122 def output_info (self):
1124 for image in self.get_images ():
1125 (base, ext) = os.path.splitext (image)
1127 # URG, makeinfo implicitly prepends dot to extension.
1128 # Specifying no extension is most robust.
1130 alt = self.option_dict[ALT]
1131 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1133 base = self.basename ()
1134 str += output[global_options.format][OUTPUT] % vars ()
1137 def output_latex (self):
1139 base = self.basename ()
1140 if global_options.format == LATEX:
1141 str += self.output_print_filename (LATEX)
1142 if VERBATIM in self.option_dict:
1143 verb = self.substring ('code')
1144 str += (output[LATEX][VERBATIM] % vars ())
1146 str += (output[LATEX][OUTPUT] % vars ())
1148 ## todo: maintain breaks
1150 breaks = self.ly ().count ("\n")
1151 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1153 if QUOTE in self.option_dict:
1154 str = output[LATEX][QUOTE] % vars ()
1157 def output_print_filename (self, format):
1159 if PRINTFILENAME in self.option_dict:
1160 base = self.basename ()
1161 filename = self.substring ('filename')
1162 str = output[global_options.format][PRINTFILENAME] % vars ()
1166 def output_texinfo (self):
1168 if self.output_print_filename (TEXINFO):
1170 + self.output_print_filename (HTML)
1173 + self.output_print_filename (LATEX)
1175 base = self.basename ()
1176 if TEXIDOC in self.option_dict:
1177 texidoc = base + '.texidoc'
1178 if os.path.exists (texidoc):
1179 str += '@include %(texidoc)s\n\n' % vars ()
1181 if VERBATIM in self.option_dict:
1182 verb = self.substring ('code')
1183 str += (output[TEXINFO][VERBATIM] % vars ())
1184 if not QUOTE in self.option_dict:
1185 str = output[TEXINFO][NOQUOTE] % vars ()
1187 str += self.output_info ()
1189 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1190 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1191 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1193 if QUOTE in self.option_dict:
1194 str = output[TEXINFO][QUOTE] % vars ()
1196 # need par after image
1201 class Lilypond_file_snippet (Lilypond_snippet):
1203 name = self.substring ('filename')
1204 contents = open (find_file (name)).read ()
1206 ## strip version string to make automated regtest comparisons
1207 ## across versions easier.
1208 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1210 return ('\\sourcefilename \"%s\"\n%s'
1213 snippet_type_to_class = {
1214 'lilypond_file': Lilypond_file_snippet,
1215 'lilypond_block': Lilypond_snippet,
1216 'lilypond': Lilypond_snippet,
1217 'include': Include_snippet,
1220 def find_linestarts (s):
1225 i = s.find ('\n', start)
1233 nls.append (len (s))
1236 def find_toplevel_snippets (s, types):
1239 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1243 found = dict ([(t, None) for t in types])
1245 line_starts = find_linestarts (s)
1247 # We want to search for multiple regexes, without searching
1248 # the string multiple times for one regex.
1249 # Hence, we use earlier results to limit the string portion
1251 # Since every part of the string is traversed at most once for
1252 # every type of snippet, this is linear.
1258 if not found[type] or found[type][0] < index:
1261 m = res[type].search (s[index:endex])
1266 if snippet_type_to_class.has_key (type):
1267 cl = snippet_type_to_class[type]
1270 start = index + m.start ('match')
1271 line_number = line_start_idx
1272 while (line_starts[line_number] < start):
1276 snip = cl (type, m, global_options.format, line_number)
1278 found[type] = (start, snip)
1282 or found[type][0] < found[first][0]):
1287 # Limiting the search space is a cute
1288 # idea, but this *requires* to search
1289 # for possible containing blocks
1290 # first, at least as long as we do not
1291 # search for the start of blocks, but
1292 # always/directly for the entire
1293 # @block ... @end block.
1295 endex = found[first][0]
1298 snippets.append (Substring (s, index, len (s), line_start_idx))
1301 while (start > line_starts[line_start_idx+1]):
1304 (start, snip) = found[first]
1305 snippets.append (Substring (s, index, start, line_start_idx + 1))
1306 snippets.append (snip)
1308 index = start + len (snip.match.group ('match'))
1312 def filter_pipe (input, cmd):
1313 if global_options.verbose:
1314 progress (_ ("Opening filter `%s'") % cmd)
1316 (stdin, stdout, stderr) = os.popen3 (cmd)
1318 status = stdin.close ()
1322 output = stdout.read ()
1323 status = stdout.close ()
1324 error = stderr.read ()
1328 signal = 0x0f & status
1329 if status or (not output and error):
1330 exit_status = status >> 8
1331 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1332 error (_ ("The error log is as follows:"))
1333 sys.stderr.write (error)
1334 sys.stderr.write (stderr.read ())
1337 if global_options.verbose:
1343 return filter_pipe (s, global_options.filter_cmd)
1345 def is_derived_class (cl, baseclass):
1348 for b in cl.__bases__:
1349 if is_derived_class (b, baseclass):
1353 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1354 ly_names = filter (lambda x: x,
1355 map (Lilypond_snippet.basename, ly_snippets))
1356 texstr_names = filter (lambda x: x,
1357 map (Lilypond_snippet.basename, texstr_snippets))
1359 png_names = filter (lambda x: x,
1360 map (Lilypond_snippet.basename, png_snippets))
1363 def my_system (cmd):
1364 status = ly.system (cmd,
1365 be_verbose=global_options.verbose,
1368 if global_options.format in (HTML, TEXINFO):
1369 cmd += ' --formats=png '
1372 # the --process=CMD switch is a bad idea
1373 # it is too generic for lilypond-book.
1375 my_system (string.join ([cmd, '--backend texstr',
1376 'snippet-map.ly'] + texstr_names))
1377 for l in texstr_names:
1378 my_system ('latex %s.texstr' % l)
1381 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1383 LATEX_INSPECTION_DOCUMENT = r'''
1387 \typeout{textwidth=\the\textwidth}
1388 \typeout{columnsep=\the\columnsep}
1389 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1393 # Do we need anything else besides `textwidth'?
1394 def get_latex_textwidth (source):
1395 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1397 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1399 ## what's a sensible default?
1402 preamble = source[:m.start (0)]
1403 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1405 (handle, tmpfile) = tempfile.mkstemp('.tex')
1406 logfile = os.path.splitext (tmpfile)[0] + '.log'
1407 logfile = os.path.split (logfile)[1]
1409 tmp_handle = os.fdopen (handle,'w')
1410 tmp_handle.write (latex_document)
1413 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1414 parameter_string = open (logfile).read()
1420 m = re.search ('columns=([0-9.]*)', parameter_string)
1422 columns = int (m.group (1))
1425 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1427 columnsep = float (m.group (1))
1430 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1432 textwidth = float (m.group (1))
1434 textwidth = (textwidth - columnsep) / columns
1438 def modify_preamble (chunk):
1439 str = chunk.replacement_text ()
1440 if (re.search (r"\\begin *{document}", str)
1441 and not re.search ("{graphic[sx]", str)):
1442 str = re.sub (r"\\begin{document}",
1443 r"\\usepackage{graphics}" + '\n'
1444 + r"\\begin{document}",
1446 chunk.override_text = str
1458 '.texinfo': TEXINFO,
1464 # TEXINFO: '.texinfo',
1469 class Compile_error:
1472 def write_file_map (lys, name):
1473 snippet_map = open ('snippet-map.ly', 'w')
1474 snippet_map.write ("""
1475 #(define version-seen #t)
1476 #(ly:add-file-name-alist '(
1479 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1485 snippet_map.write ('))\n')
1487 def do_process_cmd (chunks, input_name):
1488 all_lys = filter (lambda x: is_derived_class (x.__class__,
1492 write_file_map (all_lys, input_name)
1493 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1495 and x.ly_is_outdated (), chunks)
1496 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1498 and x.texstr_is_outdated (),
1500 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1502 and x.png_is_outdated (),
1505 outdated = png_outdated + texstr_outdated + ly_outdated
1507 progress (_ ("Writing snippets..."))
1508 map (Lilypond_snippet.write_ly, ly_outdated)
1512 progress (_ ("Processing..."))
1514 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1516 progress (_ ("All snippets are up to date..."))
1519 def guess_format (input_filename):
1521 e = os.path.splitext (input_filename)[1]
1522 if e in ext2format.keys ():
1524 format = ext2format[e]
1526 error (_ ("can't determine format for: %s" \
1531 def write_if_updated (file_name, lines):
1533 f = open (file_name)
1535 new_str = string.join (lines, '')
1536 if oldstr == new_str:
1537 progress (_ ("%s is up to date.") % file_name)
1543 progress (_ ("Writing `%s'...") % file_name)
1544 open (file_name, 'w').writelines (lines)
1547 def note_input_file (name, inputs=[]):
1548 ## hack: inputs is mutable!
1549 inputs.append (name)
1552 def samefile (f1, f2):
1554 return os.path.samefile (f1, f2)
1555 except AttributeError: # Windoze
1556 f1 = re.sub ("//*", "/", f1)
1557 f2 = re.sub ("//*", "/", f2)
1560 def do_file (input_filename):
1562 if not input_filename or input_filename == '-':
1563 in_handle = sys.stdin
1564 input_fullname = '<stdin>'
1566 if os.path.exists (input_filename):
1567 input_fullname = input_filename
1568 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1569 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1571 input_fullname = find_file (input_filename)
1573 note_input_file (input_fullname)
1574 in_handle = open (input_fullname)
1576 if input_filename == '-':
1577 input_base = 'stdin'
1579 input_base = os.path.basename \
1580 (os.path.splitext (input_filename)[0])
1582 # Only default to stdout when filtering.
1583 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1584 output_filename = '-'
1585 output_file = sys.stdout
1587 # don't complain when global_options.output_name is existing
1588 output_filename = input_base + format2ext[global_options.format]
1589 if global_options.output_name:
1590 if not os.path.isdir (global_options.output_name):
1591 os.mkdir (global_options.output_name, 0777)
1592 os.chdir (global_options.output_name)
1594 if (os.path.exists (input_filename)
1595 and os.path.exists (output_filename)
1596 and samefile (output_filename, input_fullname)):
1598 _ ("Output would overwrite input file; use --output."))
1602 progress (_ ("Reading %s...") % input_fullname)
1603 source = in_handle.read ()
1606 set_default_options (source)
1609 # FIXME: Containing blocks must be first, see
1610 # find_toplevel_snippets.
1612 'multiline_comment',
1616 'singleline_comment',
1621 progress (_ ("Dissecting..."))
1622 chunks = find_toplevel_snippets (source, snippet_types)
1624 if global_options.format == LATEX:
1626 if (c.is_plain () and
1627 re.search (r"\\begin *{document}", c.replacement_text())):
1632 if global_options.filter_cmd:
1633 write_if_updated (output_filename,
1634 [c.filter_text () for c in chunks])
1635 elif global_options.process_cmd:
1636 do_process_cmd (chunks, input_fullname)
1637 progress (_ ("Compiling %s...") % output_filename)
1639 write_if_updated (output_filename,
1640 [s.replacement_text ()
1643 def process_include (snippet):
1644 os.chdir (original_dir)
1645 name = snippet.substring ('filename')
1646 progress (_ ("Processing include: %s") % name)
1648 return do_file (name)
1650 include_chunks = map (process_include,
1651 filter (lambda x: is_derived_class (x.__class__,
1656 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1658 except Compile_error:
1659 os.chdir (original_dir)
1660 progress (_ ("Removing `%s'") % output_filename)
1666 global global_options
1668 opt_parser = get_option_parser()
1669 (global_options, args) = opt_parser.parse_args ()
1671 if global_options.format in ('texi-html', 'texi'):
1672 global_options.format = TEXINFO
1673 global_options.use_hash = True
1675 global_options.include_path = map (os.path.abspath, global_options.include_path)
1677 if global_options.warranty:
1680 if not args or len (args) > 1:
1681 opt_parser.print_help ()
1687 files = do_options ()
1691 basename = os.path.splitext (file)[0]
1692 basename = os.path.split (basename)[1]
1694 if not global_options.format:
1695 global_options.format = guess_format (files[0])
1698 if global_options.format in (TEXINFO, HTML):
1702 if global_options.process_cmd == '':
1703 global_options.process_cmd = (lilypond_binary
1704 + ' --formats=%s --backend eps ' % formats)
1706 if global_options.process_cmd:
1707 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1708 for p in global_options.include_path])
1710 if (global_options.format in (TEXINFO, LATEX)
1711 and global_options.create_pdf):
1712 global_options.process_cmd += "--pdf -deps-font-include -dgs-font-load "
1714 if global_options.verbose:
1715 global_options.process_cmd += " --verbose "
1719 chunks = do_file (file)
1720 if global_options.psfonts:
1721 fontextract.verbose = global_options.verbose
1722 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1726 psfonts_file = basename + '.psfonts'
1727 if not global_options.verbose:
1728 progress (_ ("Writing fonts to %s...") % psfonts_file)
1729 fontextract.extract_fonts (psfonts_file,
1730 [x.basename() + '.eps'
1731 for x in snippet_chunks])
1732 if not global_options.verbose:
1735 except Compile_error:
1738 if global_options.format in (TEXINFO, LATEX):
1739 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1740 output = os.path.join (global_options.output_name, basename + '.dvi' )
1742 if not global_options.psfonts and not global_options.create_pdf:
1743 warning (_ ("option --psfonts not used"))
1744 warning (_ ("processing with dvips will have no fonts"))
1747 progress (_ ("DVIPS usage:"))
1749 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1752 inputs = note_input_file ('')
1755 base_file_name = os.path.splitext (os.path.basename (file))[0]
1756 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1757 final_output_file = os.path.join (global_options.output_name,
1759 + '.%s' % global_options.format)
1761 os.chdir (original_dir)
1762 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1764 if __name__ == '__main__':