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'
252 VERBATIM = 'verbatim'
253 FONTLOAD = 'fontload'
254 FILENAME = 'filename'
258 # NOTIME has no opposite so it isn't part of this dictionary.
259 # NOQUOTE is used internally only.
261 NOFRAGMENT: FRAGMENT,
266 # Recognize special sequences in the input.
268 # (?P<name>regex) -- Assign result of REGEX to NAME.
269 # *? -- Match non-greedily.
270 # (?m) -- Multiline regex: Make ^ and $ match at each line.
271 # (?s) -- Make the dot match all characters including newline.
272 # (?x) -- Ignore whitespace in patterns.
283 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
288 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
293 <(?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>)''',
299 (?P<code><!--\s.*?!-->)
302 'singleline_comment':
321 (\s*(?P<options>.*?)\s*:)?\s*
329 \s*(?P<options>.*?)\s*
338 \s*(?P<options>.*?)\s*
340 \s*(?P<filename>.*?)\s*
347 (?P<code><!--\s.*?!-->)
350 'singleline_comment':
356 (?P<code><pre>.*?</pre>))''',
362 (?P<code><pre>\s.*?</pre>\s))''',
381 \s*(?P<options>.*?)\s*
392 \s*(?P<options>.*?)\s*
396 \\end\s*{lilypond})''',
404 \s*(?P<options>.*?)\s*
412 'singleline_comment':
435 \\end\s*{verbatim}))''',
444 (?P<filename>\S+))''',
448 ^[^\n]*?(?!@c\s+)[^\n]*?
452 \s*(?P<options>.*?)\s*
462 \s*(?P<options>.*?)\s*
465 ^@end\s+lilypond)\s''',
472 \s*(?P<options>.*?)\s*
483 @end\s+ignore))\s''',
485 'singleline_comment':
490 @c([ \t][^\n]*|)\n))''',
492 # Don't do this: It interferes with @code{@{}.
493 # 'verb': r'''(?P<code>@code{.*?})''',
501 @end\s+example\s))''',
510 'intertext': r',?\s*intertext=\".*?\"',
514 'intertext': r',?\s*intertext=\".*?\"',
519 'intertext': r',?\s*intertext=\".*?\"',
520 'option_sep': '\s*,\s*',
524 'intertext': r',?\s*intertext=\".*?\"',
525 'option_sep': '\s*,\s*',
529 # Options without a pattern in ly_options.
548 RELATIVE: r'''\relative c%(relative_quotes)s''',
553 INDENT: r'''indent = %(indent)s''',
555 LINE_WIDTH: r'''line-width = %(line-width)s''',
557 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
559 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
561 RAGGED_RIGHT: r'''ragged-right = ##t''',
563 PACKED: r'''packed = ##t''',
575 \remove Time_signature_engraver
581 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
588 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
591 <imageobject role="latex">
592 <imagedata fileref="%(base)s.pdf" format="PDF"/>
594 <imageobject role="html">
595 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
597 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
599 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
603 FILTER: r'''<lilypond %(options)s>
613 <a href="%(base)s.ly">''',
617 border="0" src="%(image)s" alt="%(alt)s">''',
619 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
621 QUOTE: r'''<blockquote>
634 \ifx\preLilyPondExample \undefined%%
637 \preLilyPondExample%%
639 \def\lilypondbook{}%%
640 \input %(base)s-systems.tex%%
641 \ifx\postLilyPondExample \undefined%%
644 \postLilyPondExample%%
648 PRINTFILENAME: '''\\texttt{%(filename)s}
651 QUOTE: r'''\begin{quotation}%(str)s
654 VERBATIM: r'''\noindent
655 \begin{verbatim}%(verb)s\end{verbatim}''',
657 FILTER: r'''\begin{lilypond}[%(options)s]
664 FILTER: r'''@lilypond[%(options)s]
670 @include %(base)s-systems.texi
674 OUTPUTIMAGE: r'''@noindent
676 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
680 <a href="%(base)s.ly">
682 border="0" src="%(image)s" alt="%(alt)s">
690 <a href="%(base)s.ly">
698 QUOTE: r'''@quotation
699 %(str)s@end quotation
706 VERBATIM: r'''@exampleindent 0
708 %(verb)s@end verbatim
711 ADDVERSION: r'''@example
712 \version @w{"@version{}"}
719 # Maintain line numbers.
724 for f in [HTML, LATEX]:
725 for s in (QUOTE, VERBATIM):
726 output[f][s] = output[f][s].replace("\n"," ")
729 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
730 %%%% Options: [%(option_string)s]
731 \\include "lilypond-book-preamble.ly"
734 %% ****************************************************************
735 %% Start cut-&-pastable-section
736 %% ****************************************************************
741 #(define dump-extents #t)
742 %(font_dump_setting)s
744 force-assignment = #""
745 line-width = #(- line-width (* mm %(padding_mm)f))
758 %% ****************************************************************
759 %% ly snippet contents follows:
760 %% ****************************************************************
764 %% ****************************************************************
766 %% ****************************************************************
773 %% ****************************************************************
775 %% ****************************************************************
779 %% ****************************************************************
781 %% ****************************************************************
784 texinfo_line_widths = {
785 '@afourpaper': '160\\mm',
786 '@afourwide': '6.5\\in',
787 '@afourlatex': '150\\mm',
788 '@smallbook': '5\\in',
789 '@letterpaper': '6\\in',
792 def classic_lilypond_book_compatibility (key, value):
793 if key == 'singleline' and value == None:
794 return (RAGGED_RIGHT, None)
796 m = re.search ('relative\s*([-0-9])', key)
798 return ('relative', m.group (1))
800 m = re.match ('([0-9]+)pt', key)
802 return ('staffsize', m.group (1))
804 if key == 'indent' or key == 'line-width':
805 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
807 f = float (m.group (1))
808 return (key, '%f\\%s' % (f, m.group (2)))
812 def find_file (name, raise_error=True):
813 for i in global_options.include_path:
814 full = os.path.join (i, name)
815 if os.path.exists (full):
819 error (_ ("file not found: %s") % name + '\n')
823 def verbatim_html (s):
824 return re.sub ('>', '>',
826 re.sub ('&', '&', s)))
828 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
829 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
831 def ly_comment_gettext (t, m):
832 return m.group (1) + t (m.group (2))
834 def verb_ly_gettext (s):
835 if not document_language:
838 t = langdefs.translation[document_language]
842 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
844 for v in ly_var_def_re.findall (s):
845 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
846 "\\1" + t (v) + "\\2",
850 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
851 def set_default_options (source, default_ly_options, format):
852 global document_language
853 if LINE_WIDTH not in default_ly_options:
855 textwidth = get_latex_textwidth (source)
856 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
857 elif format == TEXINFO:
858 m = texinfo_lang_re.search (source)
859 if m and not m.group (1).startswith ('en'):
860 document_language = m.group (1)
862 document_language = ''
863 for regex in texinfo_line_widths:
864 # FIXME: @layout is usually not in
867 # \input texinfo @c -*-texinfo-*-
869 # Bluntly search first K items of
871 # s = chunks[0].replacement_text ()
872 if re.search (regex, source[:1024]):
873 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
877 def replacement_text (self):
880 def filter_text (self):
881 return self.replacement_text ()
886 class Substring (Chunk):
887 """A string that does not require extra memory."""
888 def __init__ (self, source, start, end, line_number):
892 self.line_number = line_number
893 self.override_text = None
898 def replacement_text (self):
899 if self.override_text:
900 return self.override_text
902 return self.source[self.start:self.end]
904 class Snippet (Chunk):
905 def __init__ (self, type, match, format, line_number):
909 self.option_dict = {}
911 self.line_number = line_number
913 def replacement_text (self):
914 return self.match.group ('match')
916 def substring (self, s):
917 return self.match.group (s)
920 return `self.__class__` + ' type = ' + self.type
922 class IncludeSnippet (Snippet):
923 def processed_filename (self):
924 f = self.substring ('filename')
925 return os.path.splitext (f)[0] + format2ext[self.format]
927 def replacement_text (self):
928 s = self.match.group ('match')
929 f = self.substring ('filename')
931 return re.sub (f, self.processed_filename (), s)
933 class LilypondSnippet (Snippet):
934 def __init__ (self, type, match, format, line_number):
935 Snippet.__init__ (self, type, match, format, line_number)
936 os = match.group ('options')
937 self.do_options (os, self.type)
940 return verb_ly_gettext (self.substring ('code'))
943 contents = self.substring ('code')
944 return ('\\sourcefileline %d\n%s'
945 % (self.line_number - 1, contents))
950 return self.compose_ly (s)
953 def split_options (self, option_string):
955 if self.format == HTML:
956 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
958 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
962 return re.split (format_res[self.format]['option_sep'],
966 def do_options (self, option_string, type):
967 self.option_dict = {}
969 options = self.split_options (option_string)
971 for option in options:
973 (key, value) = re.split ('\s*=\s*', option)
974 self.option_dict[key] = value
976 if option in no_options:
977 if no_options[option] in self.option_dict:
978 del self.option_dict[no_options[option]]
980 self.option_dict[option] = None
982 has_line_width = self.option_dict.has_key (LINE_WIDTH)
983 no_line_width_value = 0
985 # If LINE_WIDTH is used without parameter, set it to default.
986 if has_line_width and self.option_dict[LINE_WIDTH] == None:
987 no_line_width_value = 1
988 del self.option_dict[LINE_WIDTH]
990 for k in default_ly_options:
991 if k not in self.option_dict:
992 self.option_dict[k] = default_ly_options[k]
994 # RELATIVE does not work without FRAGMENT;
995 # make RELATIVE imply FRAGMENT
996 has_relative = self.option_dict.has_key (RELATIVE)
997 if has_relative and not self.option_dict.has_key (FRAGMENT):
998 self.option_dict[FRAGMENT] = None
1000 if not has_line_width:
1001 if type == 'lilypond' or FRAGMENT in self.option_dict:
1002 self.option_dict[RAGGED_RIGHT] = None
1004 if type == 'lilypond':
1005 if LINE_WIDTH in self.option_dict:
1006 del self.option_dict[LINE_WIDTH]
1008 if RAGGED_RIGHT in self.option_dict:
1009 if LINE_WIDTH in self.option_dict:
1010 del self.option_dict[LINE_WIDTH]
1012 if QUOTE in self.option_dict or type == 'lilypond':
1013 if LINE_WIDTH in self.option_dict:
1014 del self.option_dict[LINE_WIDTH]
1016 if not INDENT in self.option_dict:
1017 self.option_dict[INDENT] = '0\\mm'
1019 # The QUOTE pattern from ly_options only emits the `line-width'
1021 if has_line_width and QUOTE in self.option_dict:
1022 if no_line_width_value:
1023 del self.option_dict[LINE_WIDTH]
1025 del self.option_dict[QUOTE]
1027 def compose_ly (self, code):
1028 if FRAGMENT in self.option_dict:
1036 # The original concept of the `exampleindent' option is broken.
1037 # It is not possible to get a sane value for @exampleindent at all
1038 # without processing the document itself. Saying
1046 # causes ugly results with the DVI backend of texinfo since the
1047 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1048 # value). Executing the above code changes the environment
1049 # indentation to an unknown value because we don't know the amount
1050 # of 1em in advance since it is font-dependent. Modifying
1051 # @exampleindent in the middle of a document is simply not
1052 # supported within texinfo.
1054 # As a consequence, the only function of @exampleindent is now to
1055 # specify the amount of indentation for the `quote' option.
1057 # To set @exampleindent locally to zero, we use the @format
1058 # environment for non-quoted snippets.
1059 override[EXAMPLEINDENT] = r'0.4\in'
1060 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1061 override.update (default_ly_options)
1064 for (key, value) in self.option_dict.items ():
1066 option_list.append (key)
1068 option_list.append (key + '=' + value)
1069 option_string = ','.join (option_list)
1072 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1073 for a in compose_types:
1074 compose_dict[a] = []
1076 for (key, value) in self.option_dict.items ():
1077 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1081 _ ("deprecated ly-option used: %s=%s") % (key, value))
1083 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1086 _ ("deprecated ly-option used: %s") % key)
1088 _ ("compatibility mode translation: %s") % c_key)
1090 (key, value) = (c_key, c_value)
1093 override[key] = value
1095 if not override.has_key (key):
1096 override[key] = None
1099 for type in compose_types:
1100 if ly_options[type].has_key (key):
1101 compose_dict[type].append (ly_options[type][key])
1105 if not found and key not in simple_options:
1106 warning (_ ("ignoring unknown ly option: %s") % key)
1109 if RELATIVE in override and override[RELATIVE]:
1110 relative = int (override[RELATIVE])
1112 relative_quotes = ''
1116 relative_quotes += ',' * (- relative)
1118 relative_quotes += "'" * relative
1120 paper_string = '\n '.join (compose_dict[PAPER]) % override
1121 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1122 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1123 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1124 padding_mm = global_options.padding_mm
1125 font_dump_setting = ''
1126 if FONTLOAD in self.option_dict:
1127 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1129 d = globals().copy()
1131 return (PREAMBLE_LY + body) % d
1133 def get_checksum (self):
1134 if not self.checksum:
1135 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1137 ## let's not create too long names.
1138 self.checksum = hash.hexdigest ()[:10]
1140 return self.checksum
1142 def basename (self):
1143 cs = self.get_checksum ()
1144 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1147 def write_ly (self):
1148 base = self.basename ()
1149 path = os.path.join (global_options.lily_output_dir, base)
1150 directory = os.path.split(path)[0]
1151 if not os.path.isdir (directory):
1152 os.makedirs (directory)
1153 out = file (path + '.ly', 'w')
1154 out.write (self.full_ly ())
1155 file (path + '.txt', 'w').write ('image of music')
1157 def relevant_contents (self, ly):
1158 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1160 def link_all_output_files (self, output_dir, output_dir_files, destination):
1161 existing, missing = self.all_output_files (output_dir, output_dir_files)
1163 print '\nMissing', missing
1164 raise CompileError(self.basename())
1165 for name in existing:
1167 os.unlink (os.path.join (destination, name))
1171 src = os.path.join (output_dir, name)
1172 dst = os.path.join (destination, name)
1173 dst_path = os.path.split(dst)[0]
1174 if not os.path.isdir (dst_path):
1175 os.makedirs (dst_path)
1179 def all_output_files (self, output_dir, output_dir_files):
1180 """Return all files generated in lily_output_dir, a set.
1182 output_dir_files is the list of files in the output directory.
1186 base = self.basename()
1187 full = os.path.join (output_dir, base)
1188 def consider_file (name):
1189 if name in output_dir_files:
1192 def require_file (name):
1193 if name in output_dir_files:
1198 # UGH - junk global_options
1199 skip_lily = global_options.skip_lilypond_run
1200 for required in [base + '.ly',
1202 require_file (required)
1204 require_file (base + '-systems.count')
1206 map (consider_file, [base + '.tex',
1209 base + '.texidoc' + document_language,
1210 base + '-systems.texi',
1211 base + '-systems.tex',
1212 base + '-systems.pdftexi'])
1214 # UGH - junk global_options
1215 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1216 and not global_options.skip_png_check):
1217 page_count = ps_page_count (full + '.eps')
1219 require_file (base + '.png')
1221 for page in range (1, page_count + 1):
1222 require_file (base + '-page%d.png' % page)
1225 if not skip_lily and not missing:
1226 system_count = int(file (full + '-systems.count').read())
1227 for number in range(1, system_count + 1):
1228 systemfile = '%s-%d' % (base, number)
1229 require_file (systemfile + '.eps')
1230 consider_file (systemfile + '.pdf')
1232 return (result, missing)
1234 def is_outdated (self, output_dir, current_files):
1235 found, missing = self.all_output_files (output_dir, current_files)
1238 def filter_text (self):
1239 """Run snippet bodies through a command (say: convert-ly).
1241 This functionality is rarely used, and this code must have bitrot.
1243 code = self.substring ('code')
1244 s = filter_pipe (code, global_options.filter_cmd)
1247 'options': self.match.group ('options')
1250 return output[self.format][FILTER] % d
1252 def replacement_text (self):
1253 func = LilypondSnippet.__dict__['output_' + self.format]
1256 def get_images (self):
1257 base = self.basename ()
1259 single = '%(base)s.png' % vars ()
1260 multiple = '%(base)s-page1.png' % vars ()
1262 if (os.path.exists (multiple)
1263 and (not os.path.exists (single)
1264 or (os.stat (multiple)[stat.ST_MTIME]
1265 > os.stat (single)[stat.ST_MTIME]))):
1266 count = ps_page_count ('%(base)s.eps' % vars ())
1267 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1268 images = tuple (images)
1272 def output_docbook (self):
1274 base = self.basename ()
1275 for image in self.get_images ():
1276 (base, ext) = os.path.splitext (image)
1277 str += output[DOCBOOK][OUTPUT] % vars ()
1278 str += self.output_print_filename (DOCBOOK)
1279 if (self.substring('inline') == 'inline'):
1280 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1282 str = '<mediaobject>' + str + '</mediaobject>'
1283 if VERBATIM in self.option_dict:
1284 verb = verbatim_html (self.verb_ly ())
1285 str = output[DOCBOOK][VERBATIM] % vars () + str
1288 def output_html (self):
1290 base = self.basename ()
1291 if self.format == HTML:
1292 str += self.output_print_filename (HTML)
1293 if VERBATIM in self.option_dict:
1294 verb = verbatim_html (self.verb_ly ())
1295 str += output[HTML][VERBATIM] % vars ()
1296 if QUOTE in self.option_dict:
1297 str = output[HTML][QUOTE] % vars ()
1299 str += output[HTML][BEFORE] % vars ()
1300 for image in self.get_images ():
1301 (base, ext) = os.path.splitext (image)
1302 alt = self.option_dict[ALT]
1303 str += output[HTML][OUTPUT] % vars ()
1304 str += output[HTML][AFTER] % vars ()
1307 def output_info (self):
1309 for image in self.get_images ():
1310 (base, ext) = os.path.splitext (image)
1312 # URG, makeinfo implicitly prepends dot to extension.
1313 # Specifying no extension is most robust.
1315 alt = self.option_dict[ALT]
1316 info_image_path = os.path.join (global_options.info_images_dir, base)
1317 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1319 base = self.basename ()
1320 str += output[self.format][OUTPUT] % vars ()
1323 def output_latex (self):
1325 base = self.basename ()
1326 if self.format == LATEX:
1327 str += self.output_print_filename (LATEX)
1328 if VERBATIM in self.option_dict:
1329 verb = self.verb_ly ()
1330 str += (output[LATEX][VERBATIM] % vars ())
1332 str += (output[LATEX][OUTPUT] % vars ())
1334 ## todo: maintain breaks
1336 breaks = self.ly ().count ("\n")
1337 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1339 if QUOTE in self.option_dict:
1340 str = output[LATEX][QUOTE] % vars ()
1343 def output_print_filename (self, format):
1345 if PRINTFILENAME in self.option_dict:
1346 base = self.basename ()
1347 filename = os.path.basename (self.substring ('filename'))
1348 str = output[format][PRINTFILENAME] % vars ()
1352 def output_texinfo (self):
1353 str = self.output_print_filename (TEXINFO)
1354 base = self.basename ()
1355 if TEXIDOC in self.option_dict:
1356 texidoc = base + '.texidoc'
1357 translated_texidoc = texidoc + document_language
1358 if os.path.exists (translated_texidoc):
1359 str += '@include %(translated_texidoc)s\n\n' % vars ()
1360 elif os.path.exists (texidoc):
1361 str += '@include %(texidoc)s\n\n' % vars ()
1364 if VERBATIM in self.option_dict:
1366 if ADDVERSION in self.option_dict:
1367 version = output[TEXINFO][ADDVERSION]
1368 verb = self.verb_ly ()
1369 substr = output[TEXINFO][VERBATIM] % vars ()
1370 substr += self.output_info ()
1371 if LILYQUOTE in self.option_dict:
1372 substr = output[TEXINFO][QUOTE] % {'str':substr}
1375 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1376 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1377 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1379 if QUOTE in self.option_dict:
1380 str = output[TEXINFO][QUOTE] % vars ()
1382 # need par after image
1387 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1388 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1390 class LilypondFileSnippet (LilypondSnippet):
1391 def __init__ (self, type, match, format, line_number):
1392 LilypondSnippet.__init__ (self, type, match, format, line_number)
1393 self.contents = file (find_file (self.substring ('filename'))).read ()
1397 s = re_begin_verbatim.split (s)[-1]
1398 s = re_end_verbatim.split (s)[0]
1399 return verb_ly_gettext (s)
1402 name = self.substring ('filename')
1403 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1404 % (name, self.contents))
1407 snippet_type_to_class = {
1408 'lilypond_file': LilypondFileSnippet,
1409 'lilypond_block': LilypondSnippet,
1410 'lilypond': LilypondSnippet,
1411 'include': IncludeSnippet,
1414 def find_linestarts (s):
1419 i = s.find ('\n', start)
1427 nls.append (len (s))
1430 def find_toplevel_snippets (input_string, format, types):
1433 res[t] = re.compile (snippet_res[format][t])
1437 found = dict ([(t, None) for t in types])
1439 line_starts = find_linestarts (input_string)
1441 # We want to search for multiple regexes, without searching
1442 # the string multiple times for one regex.
1443 # Hence, we use earlier results to limit the string portion
1445 # Since every part of the string is traversed at most once for
1446 # every type of snippet, this is linear.
1452 if not found[type] or found[type][0] < index:
1455 m = res[type].search (input_string[index:endex])
1460 if type in snippet_type_to_class:
1461 klass = snippet_type_to_class[type]
1463 start = index + m.start ('match')
1464 line_number = line_start_idx
1465 while (line_starts[line_number] < start):
1469 snip = klass (type, m, format, line_number)
1471 found[type] = (start, snip)
1475 or found[type][0] < found[first][0])):
1480 # Limiting the search space is a cute
1481 # idea, but this *requires* to search
1482 # for possible containing blocks
1483 # first, at least as long as we do not
1484 # search for the start of blocks, but
1485 # always/directly for the entire
1486 # @block ... @end block.
1488 endex = found[first][0]
1491 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1494 while (start > line_starts[line_start_idx+1]):
1497 (start, snip) = found[first]
1498 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1499 snippets.append (snip)
1501 index = start + len (snip.match.group ('match'))
1505 def filter_pipe (input, cmd):
1506 """Pass input through cmd, and return the result."""
1508 if global_options.verbose:
1509 progress (_ ("Opening filter `%s'") % cmd)
1511 (stdin, stdout, stderr) = os.popen3 (cmd)
1513 status = stdin.close ()
1517 output = stdout.read ()
1518 status = stdout.close ()
1519 error = stderr.read ()
1523 signal = 0x0f & status
1524 if status or (not output and error):
1525 exit_status = status >> 8
1526 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1527 error (_ ("The error log is as follows:"))
1528 ly.stderr_write (error)
1529 ly.stderr_write (stderr.read ())
1532 if global_options.verbose:
1537 def system_in_directory (cmd, directory):
1538 """Execute a command in a different directory.
1540 Because of win32 compatibility, we can't simply use subprocess.
1543 current = os.getcwd()
1544 os.chdir (directory)
1545 ly.system(cmd, be_verbose=global_options.verbose,
1550 def process_snippets (cmd, snippets,
1551 format, lily_output_dir):
1552 """Run cmd on all of the .ly files from snippets."""
1557 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1558 cmd += ' --formats=png '
1559 elif format in (DOCBOOK) and '--formats' not in cmd:
1560 cmd += ' --formats=png,pdf '
1562 checksum = snippet_list_checksum (snippets)
1563 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1564 + [snip.basename() + '.ly' for snip in snippets])
1565 name = os.path.join (lily_output_dir,
1566 'snippet-names-%d.ly' % checksum)
1567 file (name, 'wb').write (contents)
1569 system_in_directory (' '.join ([cmd, name]),
1574 # Retrieve dimensions from LaTeX
1575 LATEX_INSPECTION_DOCUMENT = r'''
1579 \typeout{textwidth=\the\textwidth}
1580 \typeout{columnsep=\the\columnsep}
1581 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1585 # Do we need anything else besides `textwidth'?
1586 def get_latex_textwidth (source):
1587 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1589 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1591 ## what's a sensible default?
1594 preamble = source[:m.start (0)]
1595 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1597 (handle, tmpfile) = tempfile.mkstemp('.tex')
1598 logfile = os.path.splitext (tmpfile)[0] + '.log'
1599 logfile = os.path.split (logfile)[1]
1601 tmp_handle = os.fdopen (handle,'w')
1602 tmp_handle.write (latex_document)
1605 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1606 be_verbose=global_options.verbose)
1607 parameter_string = file (logfile).read()
1613 m = re.search ('columns=([0-9.]*)', parameter_string)
1615 columns = int (m.group (1))
1618 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1620 columnsep = float (m.group (1))
1623 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1625 textwidth = float (m.group (1))
1627 textwidth = (textwidth - columnsep) / columns
1631 def modify_preamble (chunk):
1632 str = chunk.replacement_text ()
1633 if (re.search (r"\\begin *{document}", str)
1634 and not re.search ("{graphic[sx]", str)):
1635 str = re.sub (r"\\begin{document}",
1636 r"\\usepackage{graphics}" + '\n'
1637 + r"\\begin{document}",
1639 chunk.override_text = str
1644 # TEXINFO: '.texinfo',
1650 class CompileError(Exception):
1653 def snippet_list_checksum (snippets):
1654 return hash (' '.join([l.basename() for l in snippets]))
1656 def write_file_map (lys, name):
1657 snippet_map = file (os.path.join (
1658 global_options.lily_output_dir,
1659 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1661 snippet_map.write ("""
1662 #(define version-seen #t)
1663 #(define output-empty-score-list #f)
1664 #(ly:add-file-name-alist '(%s
1666 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1669 def split_output_files(directory):
1670 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1672 Return value is a set of strings.
1675 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1676 base_subdir = os.path.split (subdir)[1]
1677 sub_files = [os.path.join (base_subdir, name)
1678 for name in os.listdir (subdir)]
1682 def do_process_cmd (chunks, input_name, options):
1683 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1685 output_files = split_output_files (options.lily_output_dir)
1686 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1688 write_file_map (outdated, input_name)
1689 progress (_ ("Writing snippets..."))
1690 for snippet in outdated:
1695 progress (_ ("Processing..."))
1697 process_snippets (options.process_cmd, outdated,
1698 options.format, options.lily_output_dir)
1701 progress (_ ("All snippets are up to date..."))
1703 if options.lily_output_dir != options.output_dir:
1704 output_files = split_output_files (options.lily_output_dir)
1705 for snippet in snippets:
1706 snippet.link_all_output_files (options.lily_output_dir,
1714 # Format guessing data
1723 '.texinfo': TEXINFO,
1728 def guess_format (input_filename):
1730 e = os.path.splitext (input_filename)[1]
1733 format = ext2format[e]
1735 error (_ ("cannot determine format for: %s"
1740 def write_if_updated (file_name, lines):
1742 f = file (file_name)
1744 new_str = ''.join (lines)
1745 if oldstr == new_str:
1746 progress (_ ("%s is up to date.") % file_name)
1749 # this prevents make from always rerunning lilypond-book:
1750 # output file must be touched in order to be up to date
1751 os.utime (file_name, None)
1756 output_dir = os.path.dirname (file_name)
1757 if not os.path.exists (output_dir):
1758 os.makedirs (output_dir)
1760 progress (_ ("Writing `%s'...") % file_name)
1761 file (file_name, 'w').writelines (lines)
1765 def note_input_file (name, inputs=[]):
1766 ## hack: inputs is mutable!
1767 inputs.append (name)
1770 def samefile (f1, f2):
1772 return os.path.samefile (f1, f2)
1773 except AttributeError: # Windoze
1774 f1 = re.sub ("//*", "/", f1)
1775 f2 = re.sub ("//*", "/", f2)
1778 def do_file (input_filename, included=False):
1780 if not input_filename or input_filename == '-':
1781 in_handle = sys.stdin
1782 input_fullname = '<stdin>'
1784 if os.path.exists (input_filename):
1785 input_fullname = input_filename
1786 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1787 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1789 input_fullname = find_file (input_filename)
1791 note_input_file (input_fullname)
1792 in_handle = file (input_fullname)
1794 if input_filename == '-':
1795 input_base = 'stdin'
1797 input_base = os.path.splitext (input_filename)[0]
1799 input_base = os.path.basename (
1800 os.path.splitext (input_filename)[0])
1802 # don't complain when global_options.output_dir is existing
1803 if not global_options.output_dir:
1804 global_options.output_dir = os.getcwd()
1806 global_options.output_dir = os.path.abspath(global_options.output_dir)
1808 if not os.path.isdir (global_options.output_dir):
1809 os.mkdir (global_options.output_dir, 0777)
1810 os.chdir (global_options.output_dir)
1812 output_filename = os.path.join(global_options.output_dir,
1813 input_base + format2ext[global_options.format])
1814 if (os.path.exists (input_filename)
1815 and os.path.exists (output_filename)
1816 and samefile (output_filename, input_fullname)):
1818 _ ("Output would overwrite input file; use --output."))
1822 progress (_ ("Reading %s...") % input_fullname)
1823 source = in_handle.read ()
1826 set_default_options (source, default_ly_options, global_options.format)
1829 # FIXME: Containing blocks must be first, see
1830 # find_toplevel_snippets.
1832 'multiline_comment',
1836 'singleline_comment',
1841 progress (_ ("Dissecting..."))
1842 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1844 if global_options.format == LATEX:
1846 if (c.is_plain () and
1847 re.search (r"\\begin *{document}", c.replacement_text())):
1852 if global_options.filter_cmd:
1853 write_if_updated (output_filename,
1854 [c.filter_text () for c in chunks])
1855 elif global_options.process_cmd:
1856 do_process_cmd (chunks, input_fullname, global_options)
1857 progress (_ ("Compiling %s...") % output_filename)
1859 write_if_updated (output_filename,
1860 [s.replacement_text ()
1863 def process_include (snippet):
1864 os.chdir (original_dir)
1865 name = snippet.substring ('filename')
1866 progress (_ ("Processing include: %s") % name)
1868 return do_file (name, included=True)
1870 include_chunks = map (process_include,
1871 filter (lambda x: isinstance (x, IncludeSnippet),
1874 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1876 except CompileError:
1877 os.chdir (original_dir)
1878 progress (_ ("Removing `%s'") % output_filename)
1883 global global_options
1885 opt_parser = get_option_parser()
1886 (global_options, args) = opt_parser.parse_args ()
1887 if global_options.format in ('texi-html', 'texi'):
1888 global_options.format = TEXINFO
1890 global_options.include_path = map (os.path.abspath, global_options.include_path)
1892 if global_options.warranty:
1895 if not args or len (args) > 1:
1896 opt_parser.print_help ()
1902 # FIXME: 85 lines of `main' macramee??
1903 files = do_options ()
1905 basename = os.path.splitext (files[0])[0]
1906 basename = os.path.split (basename)[1]
1908 if not global_options.format:
1909 global_options.format = guess_format (files[0])
1912 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1915 if global_options.process_cmd == '':
1916 global_options.process_cmd = (lilypond_binary
1917 + ' --formats=%s -dbackend=eps ' % formats)
1919 if global_options.process_cmd:
1920 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1921 for p in global_options.include_path])
1923 if global_options.format in (TEXINFO, LATEX):
1924 ## prevent PDF from being switched on by default.
1925 global_options.process_cmd += ' --formats=eps '
1926 if global_options.create_pdf:
1927 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1929 if global_options.verbose:
1930 global_options.process_cmd += " --verbose "
1932 if global_options.padding_mm:
1933 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1935 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1937 if global_options.lily_output_dir:
1938 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1939 if not os.path.isdir (global_options.lily_output_dir):
1940 os.makedirs (global_options.lily_output_dir)
1942 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1947 chunks = do_file (files[0])
1948 except CompileError:
1951 inputs = note_input_file ('')
1954 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1955 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1956 final_output_file = os.path.join (global_options.output_dir,
1958 + '.%s' % global_options.format)
1960 os.chdir (original_dir)
1961 file (dep_file, 'w').write ('%s: %s'
1962 % (final_output_file, ' '.join (inputs)))
1964 if __name__ == '__main__':