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
45 for d in ['@lilypond_datadir@',
47 sys.path.insert (0, os.path.join (d, 'python'))
49 # dynamic relocation, for GUB binaries.
50 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
52 os.environ['PATH'] = bindir + os.pathsep + os.environ['PATH']
53 for p in ['share', 'lib']:
54 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
55 sys.path.insert (0, datadir)
64 program_version = '@TOPLEVEL_VERSION@'
65 program_name = os.path.basename (sys.argv[0])
67 original_dir = os.getcwd ()
71 '''Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.
75 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
76 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
77 lilypond-book --process='lilypond -I include' BOOK
80 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
81 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
84 ################################################################
86 if global_options.verbose:
87 raise _ ('Exiting (%d)...') % i
92 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
98 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
101 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
103 def ps_page_count (ps_name):
104 header = open (ps_name).read (1024)
105 m = re.search ('\n%%Pages: ([0-9]+)', header)
107 return string.atoi (m.group (1))
112 sys.stdout.write ('''
119 ''' % ( _('Copyright (c) %s by') % '2001--2006',
121 _('Distributed under terms of the GNU General Public License.'),
122 _('It comes with NO WARRANTY.')))
125 def get_option_parser ():
126 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
127 version="@TOPLEVEL_VERSION@",
128 description=help_summary)
130 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
133 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
135 p.add_option ('-f', '--format',
136 help=_('''use output format FORMAT (texi [default], texi-html, latex, html, docbook)'''),
139 p.add_option ("-I", '--include', help=_('add DIR to include path'),
141 action='append', dest='include_path',
142 default=[os.path.abspath (os.getcwd ())])
144 p.add_option ("-o", '--output', help=_('write output to DIR'),
146 action='store', dest='output_name',
148 p.add_option ('-P', '--process', metavar=_("COMMAND"),
149 help = _ ("process ly_files using COMMAND FILE..."),
151 dest='process_cmd', default='lilypond -b eps')
153 p.add_option ('--pdf',
156 help="Create PDF files for use with PDFTeX",
159 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
160 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
161 must use this with dvips -h INPUT.psfonts'''),
163 p.add_option ('-V', '--verbose', help=_("be verbose"),
168 p.add_option ('-w', '--warranty',
169 help=_("show warranty and copyright"),
173 p.add_option_group ('bugs',
174 description='''Report bugs via http://post.gmane.org/post.php'''
175 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
179 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
181 # Only use installed binary when we are installed too.
182 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
183 lilypond_binary = 'lilypond'
185 global_options = None
188 default_ly_options = { 'alt': "[image of music]" }
191 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
196 EXAMPLEINDENT = 'exampleindent'
198 FRAGMENT = 'fragment'
203 LINE_WIDTH = 'line-width'
204 NOFRAGMENT = 'nofragment'
205 NOINDENT = 'noindent'
210 OUTPUTIMAGE = 'outputimage'
213 PREAMBLE = 'preamble'
214 PRINTFILENAME = 'printfilename'
216 RAGGED_RIGHT = 'ragged-right'
217 RELATIVE = 'relative'
218 STAFFSIZE = 'staffsize'
221 VERBATIM = 'verbatim'
222 FONTLOAD = 'fontload'
223 FILENAME = 'filename'
227 # NOTIME has no opposite so it isn't part of this dictionary.
228 # NOQUOTE is used internally only.
230 NOFRAGMENT: FRAGMENT,
235 # Recognize special sequences in the input.
237 # (?P<name>regex) -- Assign result of REGEX to NAME.
238 # *? -- Match non-greedily.
239 # (?m) -- Multiline regex: Make ^ and $ match at each line.
240 # (?s) -- Make the dot match all characters including newline.
241 # (?x) -- Ignore whitespace in patterns.
252 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
257 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
262 <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
268 (?P<code><!--\s.*?!-->)
271 'singleline_comment':
290 (\s*(?P<options>.*?)\s*:)?\s*
298 \s*(?P<options>.*?)\s*
307 \s*(?P<options>.*?)\s*
309 \s*(?P<filename>.*?)\s*
316 (?P<code><!--\s.*?!-->)
319 'singleline_comment':
325 (?P<code><pre>.*?</pre>))''',
331 (?P<code><pre>\s.*?</pre>\s))''',
350 \s*(?P<options>.*?)\s*
361 \s*(?P<options>.*?)\s*
365 \\end\s*{lilypond})''',
373 \s*(?P<options>.*?)\s*
381 'singleline_comment':
404 \\end\s*{verbatim}))''',
413 (?P<filename>\S+))''',
417 ^[^\n]*?(?!@c\s+)[^\n]*?
421 \s*(?P<options>.*?)\s*
431 \s*(?P<options>.*?)\s*
434 ^@end\s+lilypond)\s''',
441 \s*(?P<options>.*?)\s*
452 @end\s+ignore))\s''',
454 'singleline_comment':
459 @c([ \t][^\n]*|)\n))''',
461 # Don't do this: It interferes with @code{@{}.
462 # 'verb': r'''(?P<code>@code{.*?})''',
470 @end\s+example\s))''',
479 'intertext': r',?\s*intertext=\".*?\"',
483 'intertext': r',?\s*intertext=\".*?\"',
488 'intertext': r',?\s*intertext=\".*?\"',
489 'option_sep': '\s*,\s*',
493 'intertext': r',?\s*intertext=\".*?\"',
494 'option_sep': '\s*,\s*',
498 # Options without a pattern in ly_options.
515 RELATIVE: r'''\relative c%(relative_quotes)s''',
520 INDENT: r'''indent = %(indent)s''',
522 LINE_WIDTH: r'''line-width = %(line-width)s''',
524 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
526 RAGGED_RIGHT: r'''ragged-right = ##t''',
528 PACKED: r'''packed = ##t''',
540 \remove Time_signature_engraver
546 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
553 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
556 <imageobject role="latex">
557 <imagedata fileref="%(base)s.pdf" format="PDF"/>
559 <imageobject role="html">
560 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
562 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
564 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
568 FILTER: r'''<lilypond %(options)s>
578 <a href="%(base)s.ly">''',
581 <img align="center" valign="center"
582 border="0" src="%(image)s" alt="%(alt)s">''',
584 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
586 QUOTE: r'''<blockquote>
599 \ifx\preLilyPondExample \undefined%%
602 \preLilyPondExample%%
604 \def\lilypondbook{}%%
605 \input %(base)s-systems.tex%%
606 \ifx\postLilyPondExample \undefined%%
609 \postLilyPondExample%%
613 PRINTFILENAME: '''\\texttt{%(filename)s}
616 QUOTE: r'''\begin{quotation}%(str)s
619 VERBATIM: r'''\noindent
620 \begin{verbatim}%(verb)s\end{verbatim}''',
622 FILTER: r'''\begin{lilypond}[%(options)s]
629 FILTER: r'''@lilypond[%(options)s]
635 @include %(base)s-systems.texi
639 OUTPUTIMAGE: r'''@noindent
641 @image{%(base)s,,,%(alt)s,%(ext)s}
645 <a href="%(base)s.ly">
646 <img align="center" valign="center"
647 border="0" src="%(image)s" alt="%(alt)s">
655 <a href="%(base)s.ly">
663 QUOTE: r'''@quotation
664 %(str)s@end quotation
671 VERBATIM: r'''@exampleindent 0
673 %(verb)s@end verbatim
679 # Maintain line numbers.
684 for f in [HTML, LATEX]:
685 for s in (QUOTE, VERBATIM):
686 output[f][s] = output[f][s].replace("\n"," ")
689 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
690 %%%% Options: [%(option_string)s]
691 \\include "lilypond-book-preamble.ly"
699 %% ****************************************************************
700 %% Start cut-&-pastable-section
701 %% ****************************************************************
704 #(define dump-extents #t)
705 %(font_dump_setting)s
719 %% ****************************************************************
720 %% ly snippet contents follows:
721 %% ****************************************************************
725 %% ****************************************************************
727 %% ****************************************************************
734 %% ****************************************************************
736 %% ****************************************************************
740 %% ****************************************************************
742 %% ****************************************************************
745 texinfo_line_widths = {
746 '@afourpaper': '160\\mm',
747 '@afourwide': '6.5\\in',
748 '@afourlatex': '150\\mm',
749 '@smallbook': '5\\in',
750 '@letterpaper': '6\\in',
753 def classic_lilypond_book_compatibility (key, value):
754 if key == 'singleline' and value == None:
755 return (RAGGED_RIGHT, None)
757 m = re.search ('relative\s*([-0-9])', key)
759 return ('relative', m.group (1))
761 m = re.match ('([0-9]+)pt', key)
763 return ('staffsize', m.group (1))
765 if key == 'indent' or key == 'line-width':
766 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
768 f = float (m.group (1))
769 return (key, '%f\\%s' % (f, m.group (2)))
773 def find_file (name):
774 for i in global_options.include_path:
775 full = os.path.join (i, name)
776 if os.path.exists (full):
779 error (_ ("file not found: %s") % name + '\n')
783 def verbatim_html (s):
784 return re.sub ('>', '>',
786 re.sub ('&', '&', s)))
788 def split_options (option_string):
790 if global_options.format == HTML:
791 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
792 for i in range(len(options)):
793 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
796 return re.split (format_res[global_options.format]['option_sep'],
800 def set_default_options (source):
801 global default_ly_options
802 if not default_ly_options.has_key (LINE_WIDTH):
803 if global_options.format == LATEX:
804 textwidth = get_latex_textwidth (source)
805 default_ly_options[LINE_WIDTH] = \
806 '''%.0f\\pt''' % textwidth
807 elif global_options.format == TEXINFO:
808 for (k, v) in texinfo_line_widths.items ():
809 # FIXME: @layout is usually not in
812 # \input texinfo @c -*-texinfo-*-
814 # Bluntly search first K items of
816 # s = chunks[0].replacement_text ()
817 if re.search (k, source[:1024]):
818 default_ly_options[LINE_WIDTH] = v
822 def replacement_text (self):
825 def filter_text (self):
826 return self.replacement_text ()
828 def ly_is_outdated (self):
831 def png_is_outdated (self):
837 class Substring (Chunk):
838 def __init__ (self, source, start, end, line_number):
842 self.line_number = line_number
843 self.override_text = None
848 def replacement_text (self):
849 if self.override_text:
850 return self.override_text
852 return self.source[self.start:self.end]
854 class Snippet (Chunk):
855 def __init__ (self, type, match, format, line_number):
859 self.option_dict = {}
861 self.line_number = line_number
863 def replacement_text (self):
864 return self.match.group ('match')
866 def substring (self, s):
867 return self.match.group (s)
870 return `self.__class__` + ' type = ' + self.type
872 class Include_snippet (Snippet):
873 def processed_filename (self):
874 f = self.substring ('filename')
875 return os.path.splitext (f)[0] + format2ext[global_options.format]
877 def replacement_text (self):
878 s = self.match.group ('match')
879 f = self.substring ('filename')
881 return re.sub (f, self.processed_filename (), s)
883 class Lilypond_snippet (Snippet):
884 def __init__ (self, type, match, format, line_number):
885 Snippet.__init__ (self, type, match, format, line_number)
886 os = match.group ('options')
887 self.do_options (os, self.type)
890 contents = self.substring ('code')
891 return ('\\sourcefileline %d\n%s'
892 % (self.line_number - 1, contents))
897 return self.compose_ly (s)
900 def do_options (self, option_string, type):
901 self.option_dict = {}
903 options = split_options (option_string)
907 (key, value) = re.split ('\s*=\s*', i)
908 self.option_dict[key] = value
910 if i in no_options.keys ():
911 if no_options[i] in self.option_dict.keys ():
912 del self.option_dict[no_options[i]]
914 self.option_dict[i] = None
916 has_line_width = self.option_dict.has_key (LINE_WIDTH)
917 no_line_width_value = 0
919 # If LINE_WIDTH is used without parameter, set it to default.
920 if has_line_width and self.option_dict[LINE_WIDTH] == None:
921 no_line_width_value = 1
922 del self.option_dict[LINE_WIDTH]
924 for i in default_ly_options.keys ():
925 if i not in self.option_dict.keys ():
926 self.option_dict[i] = default_ly_options[i]
928 if not has_line_width:
929 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
930 self.option_dict[RAGGED_RIGHT] = None
932 if type == 'lilypond':
933 if LINE_WIDTH in self.option_dict.keys ():
934 del self.option_dict[LINE_WIDTH]
936 if RAGGED_RIGHT in self.option_dict.keys ():
937 if LINE_WIDTH in self.option_dict.keys ():
938 del self.option_dict[LINE_WIDTH]
940 if QUOTE in self.option_dict.keys () or type == 'lilypond':
941 if LINE_WIDTH in self.option_dict.keys ():
942 del self.option_dict[LINE_WIDTH]
944 if not INDENT in self.option_dict.keys ():
945 self.option_dict[INDENT] = '0\\mm'
947 # The QUOTE pattern from ly_options only emits the `line-width'
949 if has_line_width and QUOTE in self.option_dict.keys ():
950 if no_line_width_value:
951 del self.option_dict[LINE_WIDTH]
953 del self.option_dict[QUOTE]
955 def compose_ly (self, code):
956 if FRAGMENT in self.option_dict.keys ():
964 # The original concept of the `exampleindent' option is broken.
965 # It is not possible to get a sane value for @exampleindent at all
966 # without processing the document itself. Saying
974 # causes ugly results with the DVI backend of texinfo since the
975 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
976 # value). Executing the above code changes the environment
977 # indentation to an unknown value because we don't know the amount
978 # of 1em in advance since it is font-dependent. Modifying
979 # @exampleindent in the middle of a document is simply not
980 # supported within texinfo.
982 # As a consequence, the only function of @exampleindent is now to
983 # specify the amount of indentation for the `quote' option.
985 # To set @exampleindent locally to zero, we use the @format
986 # environment for non-quoted snippets.
987 override[EXAMPLEINDENT] = r'0.4\in'
988 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
989 override.update (default_ly_options)
992 for (key, value) in self.option_dict.items ():
994 option_list.append (key)
996 option_list.append (key + '=' + value)
997 option_string = string.join (option_list, ',')
1000 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1001 for a in compose_types:
1002 compose_dict[a] = []
1004 for (key, value) in self.option_dict.items ():
1005 (c_key, c_value) = \
1006 classic_lilypond_book_compatibility (key, value)
1010 (_ ("deprecated ly-option used: %s=%s" \
1013 (_ ("compatibility mode translation: %s=%s" \
1014 % (c_key, c_value)))
1017 (_ ("deprecated ly-option used: %s" \
1020 (_ ("compatibility mode translation: %s" \
1023 (key, value) = (c_key, c_value)
1026 override[key] = value
1028 if not override.has_key (key):
1029 override[key] = None
1032 for type in compose_types:
1033 if ly_options[type].has_key (key):
1034 compose_dict[type].append (ly_options[type][key])
1038 if not found and key not in simple_options:
1039 warning (_ ("ignoring unknown ly option: %s") % key)
1042 if RELATIVE in override.keys () and override[RELATIVE]:
1043 relative = int (override[RELATIVE])
1045 relative_quotes = ''
1049 relative_quotes += ',' * (- relative)
1051 relative_quotes += "'" * relative
1053 paper_string = string.join (compose_dict[PAPER],
1055 layout_string = string.join (compose_dict[LAYOUT],
1057 notes_string = string.join (compose_dict[NOTES],
1059 preamble_string = string.join (compose_dict[PREAMBLE],
1062 font_dump_setting = ''
1063 if FONTLOAD in self.option_dict:
1064 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1066 d = globals().copy()
1068 return (PREAMBLE_LY + body) % d
1070 def get_hash (self):
1072 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1074 ## let's not create too long names.
1075 self.hash = hash.hexdigest ()[:10]
1079 def basename (self):
1080 if FILENAME in self.option_dict:
1081 return self.option_dict[FILENAME]
1082 if global_options.use_hash:
1083 return 'lily-%s' % self.get_hash ()
1086 def write_ly (self):
1087 outf = open (self.basename () + '.ly', 'w')
1088 outf.write (self.full_ly ())
1089 open (self.basename () + '.txt', 'w').write ('image of music')
1091 def relevant_contents (self, ly):
1092 return re.sub (r'\\(version|sourcefileline)[^\n]*\n', '', ly)
1094 def ly_is_outdated (self):
1095 base = self.basename ()
1096 ly_file = base + '.ly'
1097 tex_file = base + '.tex'
1098 eps_file = base + '.eps'
1099 systems_file = base + '-systems.tex'
1101 if (os.path.exists (ly_file)
1102 and os.path.exists (systems_file)
1103 and os.stat (systems_file)[stat.ST_SIZE]
1104 and re.match ('% eof', open (systems_file).readlines ()[-1])
1105 and (global_options.use_hash or FILENAME in self.option_dict)
1106 and (self.relevant_contents (self.full_ly ())
1107 == self.relevant_contents (open (ly_file).read ()))):
1109 if global_options.verbose:
1110 print 'OUT OF DATE: ', ly_file
1113 def png_is_outdated (self):
1114 base = self.basename ()
1115 # FIXME: refactor stupid OK stuff
1116 ok = not self.ly_is_outdated ()
1117 if global_options.format in (HTML, TEXINFO):
1118 ok = ok and os.path.exists (base + '.eps')
1122 page_count = ps_page_count (base + '.eps')
1125 ok = ok and os.path.exists (base + '.png')
1127 elif page_count > 1:
1128 for a in range (1, page_count + 1):
1129 ok = ok and os.path.exists (base + '-page%d.png' % a)
1133 def texstr_is_outdated (self):
1137 # FIXME: refactor stupid OK stuff
1138 base = self.basename ()
1139 ok = self.ly_is_outdated ()
1140 ok = ok and (os.path.exists (base + '.texstr'))
1143 def filter_text (self):
1144 code = self.substring ('code')
1145 s = run_filter (code)
1148 'options': self.match.group ('options')
1151 return output[self.format][FILTER] % d
1153 def replacement_text (self):
1154 func = Lilypond_snippet.__dict__['output_' + self.format]
1157 def get_images (self):
1158 base = self.basename ()
1160 single = '%(base)s.png' % vars ()
1161 multiple = '%(base)s-page1.png' % vars ()
1163 if os.path.exists (multiple) \
1164 and (not os.path.exists (single) \
1165 or (os.stat (multiple)[stat.ST_MTIME] \
1166 > os.stat (single)[stat.ST_MTIME])):
1167 count = ps_page_count ('%(base)s.eps' % vars ())
1168 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1169 images = tuple (images)
1172 def output_docbook (self):
1174 base = self.basename ()
1175 for image in self.get_images ():
1176 (base, ext) = os.path.splitext (image)
1177 str += output[DOCBOOK][OUTPUT] % vars ()
1178 str += self.output_print_filename (DOCBOOK)
1179 if (self.substring('inline') == 'inline'):
1180 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1182 str = '<mediaobject>' + str + '</mediaobject>'
1183 if VERBATIM in self.option_dict:
1184 verb = verbatim_html (self.substring ('code'))
1185 str = output[DOCBOOK][VERBATIM] % vars () + str
1188 def output_html (self):
1190 base = self.basename ()
1191 if global_options.format == HTML:
1192 str += self.output_print_filename (HTML)
1193 if VERBATIM in self.option_dict:
1194 verb = verbatim_html (self.substring ('code'))
1195 str += output[HTML][VERBATIM] % vars ()
1196 if QUOTE in self.option_dict:
1197 str = output[HTML][QUOTE] % vars ()
1199 str += output[HTML][BEFORE] % vars ()
1200 for image in self.get_images ():
1201 (base, ext) = os.path.splitext (image)
1202 alt = self.option_dict[ALT]
1203 str += output[HTML][OUTPUT] % vars ()
1204 str += output[HTML][AFTER] % vars ()
1207 def output_info (self):
1209 for image in self.get_images ():
1210 (base, ext) = os.path.splitext (image)
1212 # URG, makeinfo implicitly prepends dot to extension.
1213 # Specifying no extension is most robust.
1215 alt = self.option_dict[ALT]
1216 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1218 base = self.basename ()
1219 str += output[global_options.format][OUTPUT] % vars ()
1222 def output_latex (self):
1224 base = self.basename ()
1225 if global_options.format == LATEX:
1226 str += self.output_print_filename (LATEX)
1227 if VERBATIM in self.option_dict:
1228 verb = self.substring ('code')
1229 str += (output[LATEX][VERBATIM] % vars ())
1231 str += (output[LATEX][OUTPUT] % vars ())
1233 ## todo: maintain breaks
1235 breaks = self.ly ().count ("\n")
1236 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1238 if QUOTE in self.option_dict:
1239 str = output[LATEX][QUOTE] % vars ()
1242 def output_print_filename (self, format):
1244 if PRINTFILENAME in self.option_dict:
1245 base = self.basename ()
1246 filename = self.substring ('filename')
1247 str = output[global_options.format][PRINTFILENAME] % vars ()
1251 def output_texinfo (self):
1253 if self.output_print_filename (TEXINFO):
1255 + self.output_print_filename (HTML)
1258 + self.output_print_filename (LATEX)
1260 base = self.basename ()
1261 if TEXIDOC in self.option_dict:
1262 texidoc = base + '.texidoc'
1263 if os.path.exists (texidoc):
1264 str += '@include %(texidoc)s\n\n' % vars ()
1266 if VERBATIM in self.option_dict:
1267 verb = self.substring ('code')
1268 str += (output[TEXINFO][VERBATIM] % vars ())
1269 if not QUOTE in self.option_dict:
1270 str = output[TEXINFO][NOQUOTE] % vars ()
1272 str += self.output_info ()
1274 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1275 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1276 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1278 if QUOTE in self.option_dict:
1279 str = output[TEXINFO][QUOTE] % vars ()
1281 # need par after image
1286 class Lilypond_file_snippet (Lilypond_snippet):
1288 name = self.substring ('filename')
1289 contents = open (find_file (name)).read ()
1290 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1293 snippet_type_to_class = {
1294 'lilypond_file': Lilypond_file_snippet,
1295 'lilypond_block': Lilypond_snippet,
1296 'lilypond': Lilypond_snippet,
1297 'include': Include_snippet,
1300 def find_linestarts (s):
1305 i = s.find ('\n', start)
1313 nls.append (len (s))
1316 def find_toplevel_snippets (s, types):
1319 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1323 found = dict ([(t, None) for t in types])
1325 line_starts = find_linestarts (s)
1327 # We want to search for multiple regexes, without searching
1328 # the string multiple times for one regex.
1329 # Hence, we use earlier results to limit the string portion
1331 # Since every part of the string is traversed at most once for
1332 # every type of snippet, this is linear.
1338 if not found[type] or found[type][0] < index:
1341 m = res[type].search (s[index:endex])
1346 if snippet_type_to_class.has_key (type):
1347 cl = snippet_type_to_class[type]
1350 start = index + m.start ('match')
1351 line_number = line_start_idx
1352 while (line_starts[line_number] < start):
1356 snip = cl (type, m, global_options.format, line_number)
1358 found[type] = (start, snip)
1362 or found[type][0] < found[first][0]):
1367 # Limiting the search space is a cute
1368 # idea, but this *requires* to search
1369 # for possible containing blocks
1370 # first, at least as long as we do not
1371 # search for the start of blocks, but
1372 # always/directly for the entire
1373 # @block ... @end block.
1375 endex = found[first][0]
1378 snippets.append (Substring (s, index, len (s), line_start_idx))
1381 while (start > line_starts[line_start_idx+1]):
1384 (start, snip) = found[first]
1385 snippets.append (Substring (s, index, start, line_start_idx + 1))
1386 snippets.append (snip)
1388 index = start + len (snip.match.group ('match'))
1392 def filter_pipe (input, cmd):
1393 if global_options.verbose:
1394 progress (_ ("Opening filter `%s'") % cmd)
1396 (stdin, stdout, stderr) = os.popen3 (cmd)
1398 status = stdin.close ()
1402 output = stdout.read ()
1403 status = stdout.close ()
1404 error = stderr.read ()
1408 signal = 0x0f & status
1409 if status or (not output and error):
1410 exit_status = status >> 8
1411 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1412 error (_ ("The error log is as follows:"))
1413 sys.stderr.write (error)
1414 sys.stderr.write (stderr.read ())
1417 if global_options.verbose:
1423 return filter_pipe (s, global_options.filter_cmd)
1425 def is_derived_class (cl, baseclass):
1428 for b in cl.__bases__:
1429 if is_derived_class (b, baseclass):
1433 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1434 ly_names = filter (lambda x: x,
1435 map (Lilypond_snippet.basename, ly_snippets))
1436 texstr_names = filter (lambda x: x,
1437 map (Lilypond_snippet.basename, texstr_snippets))
1439 png_names = filter (lambda x: x,
1440 map (Lilypond_snippet.basename, png_snippets))
1443 def my_system (cmd):
1444 status = ly.system (cmd,
1445 be_verbose=global_options.verbose,
1448 if global_options.format in (HTML, TEXINFO):
1449 cmd += ' --formats=png '
1450 if global_options.format in (DOCBOOK):
1451 cmd += ' --formats=png,pdf '
1453 # the --process=CMD switch is a bad idea
1454 # it is too generic for lilypond-book.
1456 my_system (string.join ([cmd, '--backend texstr',
1457 'snippet-map.ly'] + texstr_names))
1458 for l in texstr_names:
1459 my_system ('latex %s.texstr' % l)
1462 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1465 my_system (string.join ([cmd, 'snippet-names']))
1468 LATEX_INSPECTION_DOCUMENT = r'''
1472 \typeout{textwidth=\the\textwidth}
1473 \typeout{columnsep=\the\columnsep}
1474 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1478 # Do we need anything else besides `textwidth'?
1479 def get_latex_textwidth (source):
1480 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1482 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1484 ## what's a sensible default?
1487 preamble = source[:m.start (0)]
1488 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1490 (handle, tmpfile) = tempfile.mkstemp('.tex')
1491 logfile = os.path.splitext (tmpfile)[0] + '.log'
1492 logfile = os.path.split (logfile)[1]
1494 tmp_handle = os.fdopen (handle,'w')
1495 tmp_handle.write (latex_document)
1498 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1499 parameter_string = open (logfile).read()
1505 m = re.search ('columns=([0-9.]*)', parameter_string)
1507 columns = int (m.group (1))
1510 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1512 columnsep = float (m.group (1))
1515 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1517 textwidth = float (m.group (1))
1519 textwidth = (textwidth - columnsep) / columns
1523 def modify_preamble (chunk):
1524 str = chunk.replacement_text ()
1525 if (re.search (r"\\begin *{document}", str)
1526 and not re.search ("{graphic[sx]", str)):
1527 str = re.sub (r"\\begin{document}",
1528 r"\\usepackage{graphics}" + '\n'
1529 + r"\\begin{document}",
1531 chunk.override_text = str
1543 '.texinfo': TEXINFO,
1550 # TEXINFO: '.texinfo',
1556 class Compile_error:
1559 def write_file_map (lys, name):
1560 snippet_map = open ('snippet-map.ly', 'w')
1561 snippet_map.write ("""
1562 #(define version-seen #t)
1563 #(ly:add-file-name-alist '(
1566 snippet_map.write ('("%s.ly" . "%s")\n'
1570 snippet_map.write ('))\n')
1572 def do_process_cmd (chunks, input_name):
1573 all_lys = filter (lambda x: is_derived_class (x.__class__,
1577 write_file_map (all_lys, input_name)
1578 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1580 and x.ly_is_outdated (), chunks)
1581 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1583 and x.texstr_is_outdated (),
1585 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1587 and x.png_is_outdated (),
1590 outdated = png_outdated + texstr_outdated + ly_outdated
1592 progress (_ ("Writing snippets..."))
1593 map (Lilypond_snippet.write_ly, ly_outdated)
1597 progress (_ ("Processing..."))
1599 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1601 progress (_ ("All snippets are up to date..."))
1604 def guess_format (input_filename):
1606 e = os.path.splitext (input_filename)[1]
1607 if e in ext2format.keys ():
1609 format = ext2format[e]
1611 error (_ ("can't determine format for: %s" \
1616 def write_if_updated (file_name, lines):
1618 f = open (file_name)
1620 new_str = string.join (lines, '')
1621 if oldstr == new_str:
1622 progress (_ ("%s is up to date.") % file_name)
1628 progress (_ ("Writing `%s'...") % file_name)
1629 open (file_name, 'w').writelines (lines)
1632 def note_input_file (name, inputs=[]):
1633 ## hack: inputs is mutable!
1634 inputs.append (name)
1637 def samefile (f1, f2):
1639 return os.path.samefile (f1, f2)
1640 except AttributeError: # Windoze
1641 f1 = re.sub ("//*", "/", f1)
1642 f2 = re.sub ("//*", "/", f2)
1645 def do_file (input_filename):
1647 if not input_filename or input_filename == '-':
1648 in_handle = sys.stdin
1649 input_fullname = '<stdin>'
1651 if os.path.exists (input_filename):
1652 input_fullname = input_filename
1653 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1654 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1656 input_fullname = find_file (input_filename)
1658 note_input_file (input_fullname)
1659 in_handle = open (input_fullname)
1661 if input_filename == '-':
1662 input_base = 'stdin'
1664 input_base = os.path.basename \
1665 (os.path.splitext (input_filename)[0])
1667 # Only default to stdout when filtering.
1668 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1669 output_filename = '-'
1670 output_file = sys.stdout
1672 # don't complain when global_options.output_name is existing
1673 output_filename = input_base + format2ext[global_options.format]
1674 if global_options.output_name:
1675 if not os.path.isdir (global_options.output_name):
1676 os.mkdir (global_options.output_name, 0777)
1677 os.chdir (global_options.output_name)
1679 if (os.path.exists (input_filename)
1680 and os.path.exists (output_filename)
1681 and samefile (output_filename, input_fullname)):
1683 _ ("Output would overwrite input file; use --output."))
1687 progress (_ ("Reading %s...") % input_fullname)
1688 source = in_handle.read ()
1691 set_default_options (source)
1694 # FIXME: Containing blocks must be first, see
1695 # find_toplevel_snippets.
1697 'multiline_comment',
1701 'singleline_comment',
1706 progress (_ ("Dissecting..."))
1707 chunks = find_toplevel_snippets (source, snippet_types)
1709 if global_options.format == LATEX:
1711 if (c.is_plain () and
1712 re.search (r"\\begin *{document}", c.replacement_text())):
1717 if global_options.filter_cmd:
1718 write_if_updated (output_filename,
1719 [c.filter_text () for c in chunks])
1720 elif global_options.process_cmd:
1721 do_process_cmd (chunks, input_fullname)
1722 progress (_ ("Compiling %s...") % output_filename)
1724 write_if_updated (output_filename,
1725 [s.replacement_text ()
1728 def process_include (snippet):
1729 os.chdir (original_dir)
1730 name = snippet.substring ('filename')
1731 progress (_ ("Processing include: %s") % name)
1733 return do_file (name)
1735 include_chunks = map (process_include,
1736 filter (lambda x: is_derived_class (x.__class__,
1741 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1743 except Compile_error:
1744 os.chdir (original_dir)
1745 progress (_ ("Removing `%s'") % output_filename)
1751 global global_options
1753 opt_parser = get_option_parser()
1754 (global_options, args) = opt_parser.parse_args ()
1756 if global_options.format in ('texi-html', 'texi'):
1757 global_options.format = TEXINFO
1758 global_options.use_hash = True
1760 global_options.include_path = map (os.path.abspath, global_options.include_path)
1762 if global_options.warranty:
1765 if not args or len (args) > 1:
1766 opt_parser.print_help ()
1772 # FIXME: 85 lines of `main' macramee??
1773 files = do_options ()
1777 basename = os.path.splitext (file)[0]
1778 basename = os.path.split (basename)[1]
1780 if not global_options.format:
1781 global_options.format = guess_format (files[0])
1784 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1788 if global_options.process_cmd == '':
1789 global_options.process_cmd = (lilypond_binary
1790 + ' --formats=%s --backend eps ' % formats)
1792 if global_options.process_cmd:
1793 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1794 for p in global_options.include_path])
1796 if global_options.format in (TEXINFO, LATEX):
1797 ## prevent PDF from being switched on by default.
1798 global_options.process_cmd += ' --formats=eps '
1800 if (global_options.format in (TEXINFO, LATEX)
1801 and global_options.create_pdf):
1802 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1806 if global_options.verbose:
1807 global_options.process_cmd += " --verbose "
1809 global_options.process_cmd += " -dread-file-list -deps-box-padding=-3 "
1814 chunks = do_file (file)
1815 if global_options.psfonts:
1816 fontextract.verbose = global_options.verbose
1817 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1821 psfonts_file = basename + '.psfonts'
1822 if not global_options.verbose:
1823 progress (_ ("Writing fonts to %s...") % psfonts_file)
1824 fontextract.extract_fonts (psfonts_file,
1825 [x.basename() + '.eps'
1826 for x in snippet_chunks])
1827 if not global_options.verbose:
1830 except Compile_error:
1833 if global_options.format in (TEXINFO, LATEX):
1834 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1835 output = os.path.join (global_options.output_name, basename + '.dvi' )
1837 if not global_options.psfonts and not global_options.create_pdf:
1838 warning (_ ("option --psfonts not used"))
1839 warning (_ ("processing with dvips will have no fonts"))
1842 progress (_ ("DVIPS usage:"))
1844 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1847 inputs = note_input_file ('')
1850 base_file_name = os.path.splitext (os.path.basename (file))[0]
1851 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1852 final_output_file = os.path.join (global_options.output_name,
1854 + '.%s' % global_options.format)
1856 os.chdir (original_dir)
1857 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1859 if __name__ == '__main__':