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
50 program_version = '@TOPLEVEL_VERSION@'
51 program_name = os.path.basename (sys.argv[0])
53 original_dir = os.getcwd ()
57 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
61 lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
62 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
63 lilypond-book --process='lilypond -I include' %(BOOK)s
64 ''' % {'BOOK': _ ("BOOK")})
66 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
67 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
69 ################################################################
71 if global_options.verbose:
72 raise Exception (_ ('Exiting (%d)...') % i)
77 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
79 progress = ly.progress
82 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
85 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
87 def ps_page_count (ps_name):
88 header = file (ps_name).read (1024)
89 m = re.search ('\n%%Pages: ([0-9]+)', header)
91 return int (m.group (1))
96 ly.encoded_write (sys.stdout, '''
103 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
105 _ ("Distributed under terms of the GNU General Public License."),
106 _ ("It comes with NO WARRANTY.")))
108 def get_option_parser ():
109 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
110 description=help_summary,
111 add_help_option=False)
113 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
116 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
119 p.add_option ('-f', '--format',
120 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
123 p.add_option("-h", "--help",
125 help=_ ("show this help and exit"))
127 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
129 action='append', dest='include_path',
130 default=[os.path.abspath (os.getcwd ())])
132 p.add_option ('--info-images-dir',
133 help=_ ("format Texinfo output so that Info will "
134 "look for images of music in DIR"),
136 action='store', dest='info_images_dir',
139 p.add_option ('--latex-program',
140 help=_ ("run executable PROG instead of latex"),
142 action='store', dest='latex_program',
145 p.add_option ('--left-padding',
148 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
152 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
154 action='store', dest='output_dir',
157 p.add_option ('--skip-lily-check',
158 help=_ ("do not fail if no lilypond output is found."),
160 action='store_true', dest='skip_lilypond_run',
163 p.add_option ('--skip-png-check',
164 help=_ ("do not fail if no PNG images are found for EPS files"),
166 action='store_true', dest='skip_png_check',
169 p.add_option ('--lily-output-dir',
170 help=_ ("write lily-XXX files to DIR, link into --output dir."),
172 action='store', dest='lily_output_dir',
175 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
176 help = _ ("process ly_files using COMMAND FILE..."),
178 dest='process_cmd', default='')
180 p.add_option ('--pdf',
183 help=_ ("create PDF files for use with PDFTeX"),
186 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
191 p.version = "@TOPLEVEL_VERSION@"
192 p.add_option("--version",
194 help=_ ("show version number and exit"))
196 p.add_option ('-w', '--warranty',
197 help=_ ("show warranty and copyright"),
199 p.add_option_group (ly.display_encode (_ ('Bugs')),
201 _ ("Report bugs via")
202 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
205 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
207 # Only use installed binary when we are installed too.
208 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
209 lilypond_binary = 'lilypond'
211 global_options = None
214 default_ly_options = { 'alt': "[image of music]" }
216 document_language = ''
219 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
221 ADDVERSION = 'addversion'
225 EXAMPLEINDENT = 'exampleindent'
227 FRAGMENT = 'fragment'
233 LINE_WIDTH = 'line-width'
234 LILYQUOTE = 'lilyquote'
235 NOFRAGMENT = 'nofragment'
236 NOINDENT = 'noindent'
241 OUTPUTIMAGE = 'outputimage'
244 PREAMBLE = 'preamble'
245 PRINTFILENAME = 'printfilename'
247 RAGGED_RIGHT = 'ragged-right'
248 RELATIVE = 'relative'
249 STAFFSIZE = 'staffsize'
250 DOCTITLE = 'doctitle'
253 VERBATIM = 'verbatim'
254 FONTLOAD = 'fontload'
255 FILENAME = 'filename'
259 # NOTIME has no opposite so it isn't part of this dictionary.
260 # NOQUOTE is used internally only.
262 NOFRAGMENT: FRAGMENT,
267 # Recognize special sequences in the input.
269 # (?P<name>regex) -- Assign result of REGEX to NAME.
270 # *? -- Match non-greedily.
271 # (?m) -- Multiline regex: Make ^ and $ match at each line.
272 # (?s) -- Make the dot match all characters including newline.
273 # (?x) -- Ignore whitespace in patterns.
284 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
289 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
294 <(?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>)''',
300 (?P<code><!--\s.*?!-->)
303 'singleline_comment':
322 (\s*(?P<options>.*?)\s*:)?\s*
330 \s*(?P<options>.*?)\s*
339 \s*(?P<options>.*?)\s*
341 \s*(?P<filename>.*?)\s*
348 (?P<code><!--\s.*?!-->)
351 'singleline_comment':
357 (?P<code><pre>.*?</pre>))''',
363 (?P<code><pre>\s.*?</pre>\s))''',
382 \s*(?P<options>.*?)\s*
393 \s*(?P<options>.*?)\s*
397 \\end\s*{lilypond})''',
405 \s*(?P<options>.*?)\s*
413 'singleline_comment':
436 \\end\s*{verbatim}))''',
445 (?P<filename>\S+))''',
449 ^[^\n]*?(?!@c\s+)[^\n]*?
453 \s*(?P<options>.*?)\s*
463 \s*(?P<options>.*?)\s*
466 ^@end\s+lilypond)\s''',
473 \s*(?P<options>.*?)\s*
484 @end\s+ignore))\s''',
486 'singleline_comment':
491 @c([ \t][^\n]*|)\n))''',
493 # Don't do this: It interferes with @code{@{}.
494 # 'verb': r'''(?P<code>@code{.*?})''',
502 @end\s+example\s))''',
511 'intertext': r',?\s*intertext=\".*?\"',
515 'intertext': r',?\s*intertext=\".*?\"',
520 'intertext': r',?\s*intertext=\".*?\"',
521 'option_sep': '\s*,\s*',
525 'intertext': r',?\s*intertext=\".*?\"',
526 'option_sep': '\s*,\s*',
530 # Options without a pattern in ly_options.
550 RELATIVE: r'''\relative c%(relative_quotes)s''',
555 INDENT: r'''indent = %(indent)s''',
557 LINE_WIDTH: r'''line-width = %(line-width)s''',
559 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
561 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
563 RAGGED_RIGHT: r'''ragged-right = ##t''',
565 PACKED: r'''packed = ##t''',
577 \remove Time_signature_engraver
583 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
590 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
593 <imageobject role="latex">
594 <imagedata fileref="%(base)s.pdf" format="PDF"/>
596 <imageobject role="html">
597 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
599 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
601 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
605 FILTER: r'''<lilypond %(options)s>
615 <a href="%(base)s.ly">''',
619 border="0" src="%(image)s" alt="%(alt)s">''',
621 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
623 QUOTE: r'''<blockquote>
636 \ifx\preLilyPondExample \undefined%%
639 \preLilyPondExample%%
641 \def\lilypondbook{}%%
642 \input %(base)s-systems.tex%%
643 \ifx\postLilyPondExample \undefined%%
646 \postLilyPondExample%%
650 PRINTFILENAME: '''\\texttt{%(filename)s}
653 QUOTE: r'''\begin{quotation}%(str)s
656 VERBATIM: r'''\noindent
657 \begin{verbatim}%(verb)s\end{verbatim}''',
659 FILTER: r'''\begin{lilypond}[%(options)s]
666 FILTER: r'''@lilypond[%(options)s]
672 @include %(base)s-systems.texi
676 OUTPUTIMAGE: r'''@noindent
678 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
682 <a href="%(base)s.ly">
684 border="0" src="%(image)s" alt="%(alt)s">
692 <a href="%(base)s.ly">
700 QUOTE: r'''@quotation
701 %(str)s@end quotation
708 VERBATIM: r'''@exampleindent 0
710 %(verb)s@end verbatim
713 ADDVERSION: r'''@example
714 \version @w{"@version{}"}
721 # Maintain line numbers.
726 for f in [HTML, LATEX]:
727 for s in (QUOTE, VERBATIM):
728 output[f][s] = output[f][s].replace("\n"," ")
731 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
732 %%%% Options: [%(option_string)s]
733 \\include "lilypond-book-preamble.ly"
736 %% ****************************************************************
737 %% Start cut-&-pastable-section
738 %% ****************************************************************
743 #(define dump-extents #t)
744 %(font_dump_setting)s
746 force-assignment = #""
747 line-width = #(- line-width (* mm %(padding_mm)f))
760 %% ****************************************************************
761 %% ly snippet contents follows:
762 %% ****************************************************************
766 %% ****************************************************************
768 %% ****************************************************************
775 %% ****************************************************************
777 %% ****************************************************************
781 %% ****************************************************************
783 %% ****************************************************************
786 texinfo_line_widths = {
787 '@afourpaper': '160\\mm',
788 '@afourwide': '6.5\\in',
789 '@afourlatex': '150\\mm',
790 '@smallbook': '5\\in',
791 '@letterpaper': '6\\in',
794 def classic_lilypond_book_compatibility (key, value):
795 if key == 'singleline' and value == None:
796 return (RAGGED_RIGHT, None)
798 m = re.search ('relative\s*([-0-9])', key)
800 return ('relative', m.group (1))
802 m = re.match ('([0-9]+)pt', key)
804 return ('staffsize', m.group (1))
806 if key == 'indent' or key == 'line-width':
807 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
809 f = float (m.group (1))
810 return (key, '%f\\%s' % (f, m.group (2)))
814 def find_file (name, raise_error=True):
815 for i in global_options.include_path:
816 full = os.path.join (i, name)
817 if os.path.exists (full):
821 error (_ ("file not found: %s") % name + '\n')
825 def verbatim_html (s):
826 return re.sub ('>', '>',
828 re.sub ('&', '&', s)))
830 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
831 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
833 def ly_comment_gettext (t, m):
834 return m.group (1) + t (m.group (2))
836 def verb_ly_gettext (s):
837 if not document_language:
840 t = langdefs.translation[document_language]
844 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
846 for v in ly_var_def_re.findall (s):
847 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
848 "\\1" + t (v) + "\\2",
852 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
853 def set_default_options (source, default_ly_options, format):
854 global document_language
855 if LINE_WIDTH not in default_ly_options:
857 textwidth = get_latex_textwidth (source)
858 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
859 elif format == TEXINFO:
860 m = texinfo_lang_re.search (source)
861 if m and not m.group (1).startswith ('en'):
862 document_language = m.group (1)
864 document_language = ''
865 for regex in texinfo_line_widths:
866 # FIXME: @layout is usually not in
869 # \input texinfo @c -*-texinfo-*-
871 # Bluntly search first K items of
873 # s = chunks[0].replacement_text ()
874 if re.search (regex, source[:1024]):
875 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
879 def replacement_text (self):
882 def filter_text (self):
883 return self.replacement_text ()
888 class Substring (Chunk):
889 """A string that does not require extra memory."""
890 def __init__ (self, source, start, end, line_number):
894 self.line_number = line_number
895 self.override_text = None
900 def replacement_text (self):
901 if self.override_text:
902 return self.override_text
904 return self.source[self.start:self.end]
906 class Snippet (Chunk):
907 def __init__ (self, type, match, format, line_number):
911 self.option_dict = {}
913 self.line_number = line_number
915 def replacement_text (self):
916 return self.match.group ('match')
918 def substring (self, s):
919 return self.match.group (s)
922 return `self.__class__` + ' type = ' + self.type
924 class IncludeSnippet (Snippet):
925 def processed_filename (self):
926 f = self.substring ('filename')
927 return os.path.splitext (f)[0] + format2ext[self.format]
929 def replacement_text (self):
930 s = self.match.group ('match')
931 f = self.substring ('filename')
933 return re.sub (f, self.processed_filename (), s)
935 class LilypondSnippet (Snippet):
936 def __init__ (self, type, match, format, line_number):
937 Snippet.__init__ (self, type, match, format, line_number)
938 os = match.group ('options')
939 self.do_options (os, self.type)
942 return verb_ly_gettext (self.substring ('code'))
945 contents = self.substring ('code')
946 return ('\\sourcefileline %d\n%s'
947 % (self.line_number - 1, contents))
952 return self.compose_ly (s)
955 def split_options (self, option_string):
957 if self.format == HTML:
958 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
960 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
964 return re.split (format_res[self.format]['option_sep'],
968 def do_options (self, option_string, type):
969 self.option_dict = {}
971 options = self.split_options (option_string)
973 for option in options:
975 (key, value) = re.split ('\s*=\s*', option)
976 self.option_dict[key] = value
978 if option in no_options:
979 if no_options[option] in self.option_dict:
980 del self.option_dict[no_options[option]]
982 self.option_dict[option] = None
984 has_line_width = self.option_dict.has_key (LINE_WIDTH)
985 no_line_width_value = 0
987 # If LINE_WIDTH is used without parameter, set it to default.
988 if has_line_width and self.option_dict[LINE_WIDTH] == None:
989 no_line_width_value = 1
990 del self.option_dict[LINE_WIDTH]
992 for k in default_ly_options:
993 if k not in self.option_dict:
994 self.option_dict[k] = default_ly_options[k]
996 # RELATIVE does not work without FRAGMENT;
997 # make RELATIVE imply FRAGMENT
998 has_relative = self.option_dict.has_key (RELATIVE)
999 if has_relative and not self.option_dict.has_key (FRAGMENT):
1000 self.option_dict[FRAGMENT] = None
1002 if not has_line_width:
1003 if type == 'lilypond' or FRAGMENT in self.option_dict:
1004 self.option_dict[RAGGED_RIGHT] = None
1006 if type == 'lilypond':
1007 if LINE_WIDTH in self.option_dict:
1008 del self.option_dict[LINE_WIDTH]
1010 if RAGGED_RIGHT in self.option_dict:
1011 if LINE_WIDTH in self.option_dict:
1012 del self.option_dict[LINE_WIDTH]
1014 if QUOTE in self.option_dict or type == 'lilypond':
1015 if LINE_WIDTH in self.option_dict:
1016 del self.option_dict[LINE_WIDTH]
1018 if not INDENT in self.option_dict:
1019 self.option_dict[INDENT] = '0\\mm'
1021 # The QUOTE pattern from ly_options only emits the `line-width'
1023 if has_line_width and QUOTE in self.option_dict:
1024 if no_line_width_value:
1025 del self.option_dict[LINE_WIDTH]
1027 del self.option_dict[QUOTE]
1029 def compose_ly (self, code):
1030 if FRAGMENT in self.option_dict:
1038 # The original concept of the `exampleindent' option is broken.
1039 # It is not possible to get a sane value for @exampleindent at all
1040 # without processing the document itself. Saying
1048 # causes ugly results with the DVI backend of texinfo since the
1049 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1050 # value). Executing the above code changes the environment
1051 # indentation to an unknown value because we don't know the amount
1052 # of 1em in advance since it is font-dependent. Modifying
1053 # @exampleindent in the middle of a document is simply not
1054 # supported within texinfo.
1056 # As a consequence, the only function of @exampleindent is now to
1057 # specify the amount of indentation for the `quote' option.
1059 # To set @exampleindent locally to zero, we use the @format
1060 # environment for non-quoted snippets.
1061 override[EXAMPLEINDENT] = r'0.4\in'
1062 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1063 override.update (default_ly_options)
1066 for (key, value) in self.option_dict.items ():
1068 option_list.append (key)
1070 option_list.append (key + '=' + value)
1071 option_string = ','.join (option_list)
1074 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1075 for a in compose_types:
1076 compose_dict[a] = []
1078 for (key, value) in self.option_dict.items ():
1079 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1083 _ ("deprecated ly-option used: %s=%s") % (key, value))
1085 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1088 _ ("deprecated ly-option used: %s") % key)
1090 _ ("compatibility mode translation: %s") % c_key)
1092 (key, value) = (c_key, c_value)
1095 override[key] = value
1097 if not override.has_key (key):
1098 override[key] = None
1101 for type in compose_types:
1102 if ly_options[type].has_key (key):
1103 compose_dict[type].append (ly_options[type][key])
1107 if not found and key not in simple_options:
1108 warning (_ ("ignoring unknown ly option: %s") % key)
1111 if RELATIVE in override and override[RELATIVE]:
1112 relative = int (override[RELATIVE])
1114 relative_quotes = ''
1118 relative_quotes += ',' * (- relative)
1120 relative_quotes += "'" * relative
1122 paper_string = '\n '.join (compose_dict[PAPER]) % override
1123 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1124 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1125 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1126 padding_mm = global_options.padding_mm
1127 font_dump_setting = ''
1128 if FONTLOAD in self.option_dict:
1129 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1131 d = globals().copy()
1133 return (PREAMBLE_LY + body) % d
1135 def get_checksum (self):
1136 if not self.checksum:
1137 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1139 ## let's not create too long names.
1140 self.checksum = hash.hexdigest ()[:10]
1142 return self.checksum
1144 def basename (self):
1145 cs = self.get_checksum ()
1146 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1149 def write_ly (self):
1150 base = self.basename ()
1151 path = os.path.join (global_options.lily_output_dir, base)
1152 directory = os.path.split(path)[0]
1153 if not os.path.isdir (directory):
1154 os.makedirs (directory)
1155 out = file (path + '.ly', 'w')
1156 out.write (self.full_ly ())
1157 file (path + '.txt', 'w').write ('image of music')
1159 def relevant_contents (self, ly):
1160 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1162 def link_all_output_files (self, output_dir, output_dir_files, destination):
1163 existing, missing = self.all_output_files (output_dir, output_dir_files)
1165 print '\nMissing', missing
1166 raise CompileError(self.basename())
1167 for name in existing:
1169 os.unlink (os.path.join (destination, name))
1173 src = os.path.join (output_dir, name)
1174 dst = os.path.join (destination, name)
1175 dst_path = os.path.split(dst)[0]
1176 if not os.path.isdir (dst_path):
1177 os.makedirs (dst_path)
1181 def all_output_files (self, output_dir, output_dir_files):
1182 """Return all files generated in lily_output_dir, a set.
1184 output_dir_files is the list of files in the output directory.
1188 base = self.basename()
1189 full = os.path.join (output_dir, base)
1190 def consider_file (name):
1191 if name in output_dir_files:
1194 def require_file (name):
1195 if name in output_dir_files:
1200 # UGH - junk global_options
1201 skip_lily = global_options.skip_lilypond_run
1202 for required in [base + '.ly',
1204 require_file (required)
1206 require_file (base + '-systems.count')
1208 map (consider_file, [base + '.tex',
1212 base + '.signature',
1213 base + '-systems.texi',
1214 base + '-systems.tex',
1215 base + '-systems.pdftexi'])
1216 if document_language:
1218 [base + '.texidoc' + document_language,
1219 base + '.doctitle' + document_language])
1221 # UGH - junk global_options
1222 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1223 and not global_options.skip_png_check):
1224 page_count = ps_page_count (full + '.eps')
1226 require_file (base + '.png')
1228 for page in range (1, page_count + 1):
1229 require_file (base + '-page%d.png' % page)
1232 if not skip_lily and not missing:
1233 system_count = int(file (full + '-systems.count').read())
1234 for number in range(1, system_count + 1):
1235 systemfile = '%s-%d' % (base, number)
1236 require_file (systemfile + '.eps')
1237 consider_file (systemfile + '.pdf')
1239 return (result, missing)
1241 def is_outdated (self, output_dir, current_files):
1242 found, missing = self.all_output_files (output_dir, current_files)
1245 def filter_text (self):
1246 """Run snippet bodies through a command (say: convert-ly).
1248 This functionality is rarely used, and this code must have bitrot.
1250 code = self.substring ('code')
1251 s = filter_pipe (code, global_options.filter_cmd)
1254 'options': self.match.group ('options')
1257 return output[self.format][FILTER] % d
1259 def replacement_text (self):
1260 func = LilypondSnippet.__dict__['output_' + self.format]
1263 def get_images (self):
1264 base = self.basename ()
1266 single = '%(base)s.png' % vars ()
1267 multiple = '%(base)s-page1.png' % vars ()
1269 if (os.path.exists (multiple)
1270 and (not os.path.exists (single)
1271 or (os.stat (multiple)[stat.ST_MTIME]
1272 > os.stat (single)[stat.ST_MTIME]))):
1273 count = ps_page_count ('%(base)s.eps' % vars ())
1274 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1275 images = tuple (images)
1279 def output_docbook (self):
1281 base = self.basename ()
1282 for image in self.get_images ():
1283 (base, ext) = os.path.splitext (image)
1284 str += output[DOCBOOK][OUTPUT] % vars ()
1285 str += self.output_print_filename (DOCBOOK)
1286 if (self.substring('inline') == 'inline'):
1287 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1289 str = '<mediaobject>' + str + '</mediaobject>'
1290 if VERBATIM in self.option_dict:
1291 verb = verbatim_html (self.verb_ly ())
1292 str = output[DOCBOOK][VERBATIM] % vars () + str
1295 def output_html (self):
1297 base = self.basename ()
1298 if self.format == HTML:
1299 str += self.output_print_filename (HTML)
1300 if VERBATIM in self.option_dict:
1301 verb = verbatim_html (self.verb_ly ())
1302 str += output[HTML][VERBATIM] % vars ()
1303 if QUOTE in self.option_dict:
1304 str = output[HTML][QUOTE] % vars ()
1306 str += output[HTML][BEFORE] % vars ()
1307 for image in self.get_images ():
1308 (base, ext) = os.path.splitext (image)
1309 alt = self.option_dict[ALT]
1310 str += output[HTML][OUTPUT] % vars ()
1311 str += output[HTML][AFTER] % vars ()
1314 def output_info (self):
1316 for image in self.get_images ():
1317 (base, ext) = os.path.splitext (image)
1319 # URG, makeinfo implicitly prepends dot to extension.
1320 # Specifying no extension is most robust.
1322 alt = self.option_dict[ALT]
1323 info_image_path = os.path.join (global_options.info_images_dir, base)
1324 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1326 base = self.basename ()
1327 str += output[self.format][OUTPUT] % vars ()
1330 def output_latex (self):
1332 base = self.basename ()
1333 if self.format == LATEX:
1334 str += self.output_print_filename (LATEX)
1335 if VERBATIM in self.option_dict:
1336 verb = self.verb_ly ()
1337 str += (output[LATEX][VERBATIM] % vars ())
1339 str += (output[LATEX][OUTPUT] % vars ())
1341 ## todo: maintain breaks
1343 breaks = self.ly ().count ("\n")
1344 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1346 if QUOTE in self.option_dict:
1347 str = output[LATEX][QUOTE] % vars ()
1350 def output_print_filename (self, format):
1352 if PRINTFILENAME in self.option_dict:
1353 base = self.basename ()
1354 filename = os.path.basename (self.substring ('filename'))
1355 str = output[format][PRINTFILENAME] % vars ()
1359 def output_texinfo (self):
1360 str = self.output_print_filename (TEXINFO)
1361 base = self.basename ()
1362 if DOCTITLE in self.option_dict:
1363 doctitle = base + '.doctitle'
1364 translated_doctitle = doctitle + document_language
1365 if os.path.exists (translated_doctitle):
1366 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1367 elif os.path.exists (doctitle):
1368 str += '@lydoctitle %s\n' % open (doctitle).read ()
1369 if TEXIDOC in self.option_dict:
1370 texidoc = base + '.texidoc'
1371 translated_texidoc = texidoc + document_language
1372 if os.path.exists (translated_texidoc):
1373 str += '@include %(translated_texidoc)s\n\n' % vars ()
1374 elif os.path.exists (texidoc):
1375 str += '@include %(texidoc)s\n\n' % vars ()
1378 if VERBATIM in self.option_dict:
1380 if ADDVERSION in self.option_dict:
1381 version = output[TEXINFO][ADDVERSION]
1382 verb = self.verb_ly ()
1383 substr = output[TEXINFO][VERBATIM] % vars ()
1384 substr += self.output_info ()
1385 if LILYQUOTE in self.option_dict:
1386 substr = output[TEXINFO][QUOTE] % {'str':substr}
1389 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1390 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1391 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1393 if QUOTE in self.option_dict:
1394 str = output[TEXINFO][QUOTE] % vars ()
1396 # need par after image
1401 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1402 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1404 class LilypondFileSnippet (LilypondSnippet):
1405 def __init__ (self, type, match, format, line_number):
1406 LilypondSnippet.__init__ (self, type, match, format, line_number)
1407 self.contents = file (find_file (self.substring ('filename'))).read ()
1411 s = re_begin_verbatim.split (s)[-1]
1412 s = re_end_verbatim.split (s)[0]
1413 return verb_ly_gettext (s)
1416 name = self.substring ('filename')
1417 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1418 % (name, self.contents))
1421 snippet_type_to_class = {
1422 'lilypond_file': LilypondFileSnippet,
1423 'lilypond_block': LilypondSnippet,
1424 'lilypond': LilypondSnippet,
1425 'include': IncludeSnippet,
1428 def find_linestarts (s):
1433 i = s.find ('\n', start)
1441 nls.append (len (s))
1444 def find_toplevel_snippets (input_string, format, types):
1447 res[t] = re.compile (snippet_res[format][t])
1451 found = dict ([(t, None) for t in types])
1453 line_starts = find_linestarts (input_string)
1455 # We want to search for multiple regexes, without searching
1456 # the string multiple times for one regex.
1457 # Hence, we use earlier results to limit the string portion
1459 # Since every part of the string is traversed at most once for
1460 # every type of snippet, this is linear.
1466 if not found[type] or found[type][0] < index:
1469 m = res[type].search (input_string[index:endex])
1474 if type in snippet_type_to_class:
1475 klass = snippet_type_to_class[type]
1477 start = index + m.start ('match')
1478 line_number = line_start_idx
1479 while (line_starts[line_number] < start):
1483 snip = klass (type, m, format, line_number)
1485 found[type] = (start, snip)
1489 or found[type][0] < found[first][0])):
1494 # Limiting the search space is a cute
1495 # idea, but this *requires* to search
1496 # for possible containing blocks
1497 # first, at least as long as we do not
1498 # search for the start of blocks, but
1499 # always/directly for the entire
1500 # @block ... @end block.
1502 endex = found[first][0]
1505 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1508 while (start > line_starts[line_start_idx+1]):
1511 (start, snip) = found[first]
1512 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1513 snippets.append (snip)
1515 index = start + len (snip.match.group ('match'))
1519 def filter_pipe (input, cmd):
1520 """Pass input through cmd, and return the result."""
1522 if global_options.verbose:
1523 progress (_ ("Opening filter `%s'") % cmd)
1525 (stdin, stdout, stderr) = os.popen3 (cmd)
1527 status = stdin.close ()
1531 output = stdout.read ()
1532 status = stdout.close ()
1533 error = stderr.read ()
1537 signal = 0x0f & status
1538 if status or (not output and error):
1539 exit_status = status >> 8
1540 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1541 error (_ ("The error log is as follows:"))
1542 ly.stderr_write (error)
1543 ly.stderr_write (stderr.read ())
1546 if global_options.verbose:
1551 def system_in_directory (cmd, directory):
1552 """Execute a command in a different directory.
1554 Because of win32 compatibility, we can't simply use subprocess.
1557 current = os.getcwd()
1558 os.chdir (directory)
1559 ly.system(cmd, be_verbose=global_options.verbose,
1564 def process_snippets (cmd, snippets,
1565 format, lily_output_dir):
1566 """Run cmd on all of the .ly files from snippets."""
1571 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1572 cmd += ' --formats=png '
1573 elif format in (DOCBOOK) and '--formats' not in cmd:
1574 cmd += ' --formats=png,pdf '
1576 checksum = snippet_list_checksum (snippets)
1577 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1578 + [snip.basename() + '.ly' for snip in snippets])
1579 name = os.path.join (lily_output_dir,
1580 'snippet-names-%d.ly' % checksum)
1581 file (name, 'wb').write (contents)
1583 system_in_directory (' '.join ([cmd, name]),
1588 # Retrieve dimensions from LaTeX
1589 LATEX_INSPECTION_DOCUMENT = r'''
1593 \typeout{textwidth=\the\textwidth}
1594 \typeout{columnsep=\the\columnsep}
1595 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1599 # Do we need anything else besides `textwidth'?
1600 def get_latex_textwidth (source):
1601 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1603 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1605 ## what's a sensible default?
1608 preamble = source[:m.start (0)]
1609 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1611 (handle, tmpfile) = tempfile.mkstemp('.tex')
1612 logfile = os.path.splitext (tmpfile)[0] + '.log'
1613 logfile = os.path.split (logfile)[1]
1615 tmp_handle = os.fdopen (handle,'w')
1616 tmp_handle.write (latex_document)
1619 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1620 be_verbose=global_options.verbose)
1621 parameter_string = file (logfile).read()
1627 m = re.search ('columns=([0-9.]*)', parameter_string)
1629 columns = int (m.group (1))
1632 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1634 columnsep = float (m.group (1))
1637 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1639 textwidth = float (m.group (1))
1641 textwidth = (textwidth - columnsep) / columns
1645 def modify_preamble (chunk):
1646 str = chunk.replacement_text ()
1647 if (re.search (r"\\begin *{document}", str)
1648 and not re.search ("{graphic[sx]", str)):
1649 str = re.sub (r"\\begin{document}",
1650 r"\\usepackage{graphics}" + '\n'
1651 + r"\\begin{document}",
1653 chunk.override_text = str
1658 # TEXINFO: '.texinfo',
1664 class CompileError(Exception):
1667 def snippet_list_checksum (snippets):
1668 return hash (' '.join([l.basename() for l in snippets]))
1670 def write_file_map (lys, name):
1671 snippet_map = file (os.path.join (
1672 global_options.lily_output_dir,
1673 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1675 snippet_map.write ("""
1676 #(define version-seen #t)
1677 #(define output-empty-score-list #f)
1678 #(ly:add-file-name-alist '(%s
1680 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1683 def split_output_files(directory):
1684 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1686 Return value is a set of strings.
1689 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1690 base_subdir = os.path.split (subdir)[1]
1691 sub_files = [os.path.join (base_subdir, name)
1692 for name in os.listdir (subdir)]
1696 def do_process_cmd (chunks, input_name, options):
1697 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1699 output_files = split_output_files (options.lily_output_dir)
1700 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1702 write_file_map (outdated, input_name)
1703 progress (_ ("Writing snippets..."))
1704 for snippet in outdated:
1709 progress (_ ("Processing..."))
1711 process_snippets (options.process_cmd, outdated,
1712 options.format, options.lily_output_dir)
1715 progress (_ ("All snippets are up to date..."))
1717 if options.lily_output_dir != options.output_dir:
1718 output_files = split_output_files (options.lily_output_dir)
1719 for snippet in snippets:
1720 snippet.link_all_output_files (options.lily_output_dir,
1728 # Format guessing data
1737 '.texinfo': TEXINFO,
1742 def guess_format (input_filename):
1744 e = os.path.splitext (input_filename)[1]
1747 format = ext2format[e]
1749 error (_ ("cannot determine format for: %s"
1754 def write_if_updated (file_name, lines):
1756 f = file (file_name)
1758 new_str = ''.join (lines)
1759 if oldstr == new_str:
1760 progress (_ ("%s is up to date.") % file_name)
1763 # this prevents make from always rerunning lilypond-book:
1764 # output file must be touched in order to be up to date
1765 os.utime (file_name, None)
1770 output_dir = os.path.dirname (file_name)
1771 if not os.path.exists (output_dir):
1772 os.makedirs (output_dir)
1774 progress (_ ("Writing `%s'...") % file_name)
1775 file (file_name, 'w').writelines (lines)
1779 def note_input_file (name, inputs=[]):
1780 ## hack: inputs is mutable!
1781 inputs.append (name)
1784 def samefile (f1, f2):
1786 return os.path.samefile (f1, f2)
1787 except AttributeError: # Windoze
1788 f1 = re.sub ("//*", "/", f1)
1789 f2 = re.sub ("//*", "/", f2)
1792 def do_file (input_filename, included=False):
1794 if not input_filename or input_filename == '-':
1795 in_handle = sys.stdin
1796 input_fullname = '<stdin>'
1798 if os.path.exists (input_filename):
1799 input_fullname = input_filename
1800 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1801 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1803 input_fullname = find_file (input_filename)
1805 note_input_file (input_fullname)
1806 in_handle = file (input_fullname)
1808 if input_filename == '-':
1809 input_base = 'stdin'
1811 input_base = os.path.splitext (input_filename)[0]
1813 input_base = os.path.basename (
1814 os.path.splitext (input_filename)[0])
1816 # don't complain when global_options.output_dir is existing
1817 if not global_options.output_dir:
1818 global_options.output_dir = os.getcwd()
1820 global_options.output_dir = os.path.abspath(global_options.output_dir)
1822 if not os.path.isdir (global_options.output_dir):
1823 os.mkdir (global_options.output_dir, 0777)
1824 os.chdir (global_options.output_dir)
1826 output_filename = os.path.join(global_options.output_dir,
1827 input_base + format2ext[global_options.format])
1828 if (os.path.exists (input_filename)
1829 and os.path.exists (output_filename)
1830 and samefile (output_filename, input_fullname)):
1832 _ ("Output would overwrite input file; use --output."))
1836 progress (_ ("Reading %s...") % input_fullname)
1837 source = in_handle.read ()
1840 set_default_options (source, default_ly_options, global_options.format)
1843 # FIXME: Containing blocks must be first, see
1844 # find_toplevel_snippets.
1846 'multiline_comment',
1850 'singleline_comment',
1855 progress (_ ("Dissecting..."))
1856 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1858 if global_options.format == LATEX:
1860 if (c.is_plain () and
1861 re.search (r"\\begin *{document}", c.replacement_text())):
1866 if global_options.filter_cmd:
1867 write_if_updated (output_filename,
1868 [c.filter_text () for c in chunks])
1869 elif global_options.process_cmd:
1870 do_process_cmd (chunks, input_fullname, global_options)
1871 progress (_ ("Compiling %s...") % output_filename)
1873 write_if_updated (output_filename,
1874 [s.replacement_text ()
1877 def process_include (snippet):
1878 os.chdir (original_dir)
1879 name = snippet.substring ('filename')
1880 progress (_ ("Processing include: %s") % name)
1882 return do_file (name, included=True)
1884 include_chunks = map (process_include,
1885 filter (lambda x: isinstance (x, IncludeSnippet),
1888 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1890 except CompileError:
1891 os.chdir (original_dir)
1892 progress (_ ("Removing `%s'") % output_filename)
1897 global global_options
1899 opt_parser = get_option_parser()
1900 (global_options, args) = opt_parser.parse_args ()
1901 if global_options.format in ('texi-html', 'texi'):
1902 global_options.format = TEXINFO
1904 global_options.include_path = map (os.path.abspath, global_options.include_path)
1906 if global_options.warranty:
1909 if not args or len (args) > 1:
1910 opt_parser.print_help ()
1916 # FIXME: 85 lines of `main' macramee??
1917 files = do_options ()
1919 basename = os.path.splitext (files[0])[0]
1920 basename = os.path.split (basename)[1]
1922 if not global_options.format:
1923 global_options.format = guess_format (files[0])
1926 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1929 if global_options.process_cmd == '':
1930 global_options.process_cmd = (lilypond_binary
1931 + ' --formats=%s -dbackend=eps ' % formats)
1933 if global_options.process_cmd:
1934 includes = global_options.include_path
1935 if global_options.lily_output_dir:
1936 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1937 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1940 if global_options.format in (TEXINFO, LATEX):
1941 ## prevent PDF from being switched on by default.
1942 global_options.process_cmd += ' --formats=eps '
1943 if global_options.create_pdf:
1944 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1946 if global_options.verbose:
1947 global_options.process_cmd += " --verbose "
1949 if global_options.padding_mm:
1950 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1952 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1954 if global_options.lily_output_dir:
1955 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1956 if not os.path.isdir (global_options.lily_output_dir):
1957 os.makedirs (global_options.lily_output_dir)
1959 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1964 chunks = do_file (files[0])
1965 except CompileError:
1968 inputs = note_input_file ('')
1971 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1972 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1973 final_output_file = os.path.join (global_options.output_dir,
1975 + '.%s' % global_options.format)
1977 os.chdir (original_dir)
1978 file (dep_file, 'w').write ('%s: %s'
1979 % (final_output_file, ' '.join (inputs)))
1981 if __name__ == '__main__':