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 if not has_line_width:
995 if type == 'lilypond' or FRAGMENT in self.option_dict:
996 self.option_dict[RAGGED_RIGHT] = None
998 if type == 'lilypond':
999 if LINE_WIDTH in self.option_dict:
1000 del self.option_dict[LINE_WIDTH]
1002 if RAGGED_RIGHT in self.option_dict:
1003 if LINE_WIDTH in self.option_dict:
1004 del self.option_dict[LINE_WIDTH]
1006 if QUOTE in self.option_dict or type == 'lilypond':
1007 if LINE_WIDTH in self.option_dict:
1008 del self.option_dict[LINE_WIDTH]
1010 if not INDENT in self.option_dict:
1011 self.option_dict[INDENT] = '0\\mm'
1013 # The QUOTE pattern from ly_options only emits the `line-width'
1015 if has_line_width and QUOTE in self.option_dict:
1016 if no_line_width_value:
1017 del self.option_dict[LINE_WIDTH]
1019 del self.option_dict[QUOTE]
1021 def compose_ly (self, code):
1022 if FRAGMENT in self.option_dict:
1030 # The original concept of the `exampleindent' option is broken.
1031 # It is not possible to get a sane value for @exampleindent at all
1032 # without processing the document itself. Saying
1040 # causes ugly results with the DVI backend of texinfo since the
1041 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1042 # value). Executing the above code changes the environment
1043 # indentation to an unknown value because we don't know the amount
1044 # of 1em in advance since it is font-dependent. Modifying
1045 # @exampleindent in the middle of a document is simply not
1046 # supported within texinfo.
1048 # As a consequence, the only function of @exampleindent is now to
1049 # specify the amount of indentation for the `quote' option.
1051 # To set @exampleindent locally to zero, we use the @format
1052 # environment for non-quoted snippets.
1053 override[EXAMPLEINDENT] = r'0.4\in'
1054 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1055 override.update (default_ly_options)
1058 for (key, value) in self.option_dict.items ():
1060 option_list.append (key)
1062 option_list.append (key + '=' + value)
1063 option_string = ','.join (option_list)
1066 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1067 for a in compose_types:
1068 compose_dict[a] = []
1070 for (key, value) in self.option_dict.items ():
1071 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1075 _ ("deprecated ly-option used: %s=%s") % (key, value))
1077 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1080 _ ("deprecated ly-option used: %s") % key)
1082 _ ("compatibility mode translation: %s") % c_key)
1084 (key, value) = (c_key, c_value)
1087 override[key] = value
1089 if not override.has_key (key):
1090 override[key] = None
1093 for type in compose_types:
1094 if ly_options[type].has_key (key):
1095 compose_dict[type].append (ly_options[type][key])
1099 if not found and key not in simple_options:
1100 warning (_ ("ignoring unknown ly option: %s") % key)
1103 if RELATIVE in override and override[RELATIVE]:
1104 relative = int (override[RELATIVE])
1106 relative_quotes = ''
1110 relative_quotes += ',' * (- relative)
1112 relative_quotes += "'" * relative
1114 paper_string = '\n '.join (compose_dict[PAPER]) % override
1115 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1116 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1117 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1118 padding_mm = global_options.padding_mm
1119 font_dump_setting = ''
1120 if FONTLOAD in self.option_dict:
1121 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1123 d = globals().copy()
1125 return (PREAMBLE_LY + body) % d
1127 def get_checksum (self):
1128 if not self.checksum:
1129 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1131 ## let's not create too long names.
1132 self.checksum = hash.hexdigest ()[:10]
1134 return self.checksum
1136 def basename (self):
1137 cs = self.get_checksum ()
1138 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1141 def write_ly (self):
1142 base = self.basename ()
1143 path = os.path.join (global_options.lily_output_dir, base)
1144 directory = os.path.split(path)[0]
1145 if not os.path.isdir (directory):
1146 os.makedirs (directory)
1147 out = file (path + '.ly', 'w')
1148 out.write (self.full_ly ())
1149 file (path + '.txt', 'w').write ('image of music')
1151 def relevant_contents (self, ly):
1152 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1154 def link_all_output_files (self, output_dir, output_dir_files, destination):
1155 existing, missing = self.all_output_files (output_dir, output_dir_files)
1157 print '\nMissing', missing
1158 raise CompileError(self.basename())
1159 for name in existing:
1161 os.unlink (os.path.join (destination, name))
1165 src = os.path.join (output_dir, name)
1166 dst = os.path.join (destination, name)
1167 dst_path = os.path.split(dst)[0]
1168 if not os.path.isdir (dst_path):
1169 os.makedirs (dst_path)
1173 def all_output_files (self, output_dir, output_dir_files):
1174 """Return all files generated in lily_output_dir, a set.
1176 output_dir_files is the list of files in the output directory.
1180 base = self.basename()
1181 full = os.path.join (output_dir, base)
1182 def consider_file (name):
1183 if name in output_dir_files:
1186 def require_file (name):
1187 if name in output_dir_files:
1192 # UGH - junk global_options
1193 skip_lily = global_options.skip_lilypond_run
1194 for required in [base + '.ly',
1196 require_file (required)
1198 require_file (base + '-systems.count')
1200 map (consider_file, [base + '.tex',
1203 base + '.texidoc' + document_language,
1204 base + '-systems.texi',
1205 base + '-systems.tex',
1206 base + '-systems.pdftexi'])
1208 # UGH - junk global_options
1209 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1210 and not global_options.skip_png_check):
1211 page_count = ps_page_count (full + '.eps')
1213 require_file (base + '.png')
1215 for page in range (1, page_count + 1):
1216 require_file (base + '-page%d.png' % page)
1219 if not skip_lily and not missing:
1220 system_count = int(file (full + '-systems.count').read())
1221 for number in range(1, system_count + 1):
1222 systemfile = '%s-%d' % (base, number)
1223 require_file (systemfile + '.eps')
1224 consider_file (systemfile + '.pdf')
1226 return (result, missing)
1228 def is_outdated (self, output_dir, current_files):
1229 found, missing = self.all_output_files (output_dir, current_files)
1232 def filter_text (self):
1233 """Run snippet bodies through a command (say: convert-ly).
1235 This functionality is rarely used, and this code must have bitrot.
1237 code = self.substring ('code')
1238 s = filter_pipe (code, global_options.filter_cmd)
1241 'options': self.match.group ('options')
1244 return output[self.format][FILTER] % d
1246 def replacement_text (self):
1247 func = LilypondSnippet.__dict__['output_' + self.format]
1250 def get_images (self):
1251 base = self.basename ()
1253 single = '%(base)s.png' % vars ()
1254 multiple = '%(base)s-page1.png' % vars ()
1256 if (os.path.exists (multiple)
1257 and (not os.path.exists (single)
1258 or (os.stat (multiple)[stat.ST_MTIME]
1259 > os.stat (single)[stat.ST_MTIME]))):
1260 count = ps_page_count ('%(base)s.eps' % vars ())
1261 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1262 images = tuple (images)
1266 def output_docbook (self):
1268 base = self.basename ()
1269 for image in self.get_images ():
1270 (base, ext) = os.path.splitext (image)
1271 str += output[DOCBOOK][OUTPUT] % vars ()
1272 str += self.output_print_filename (DOCBOOK)
1273 if (self.substring('inline') == 'inline'):
1274 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1276 str = '<mediaobject>' + str + '</mediaobject>'
1277 if VERBATIM in self.option_dict:
1278 verb = verbatim_html (self.verb_ly ())
1279 str = output[DOCBOOK][VERBATIM] % vars () + str
1282 def output_html (self):
1284 base = self.basename ()
1285 if self.format == HTML:
1286 str += self.output_print_filename (HTML)
1287 if VERBATIM in self.option_dict:
1288 verb = verbatim_html (self.verb_ly ())
1289 str += output[HTML][VERBATIM] % vars ()
1290 if QUOTE in self.option_dict:
1291 str = output[HTML][QUOTE] % vars ()
1293 str += output[HTML][BEFORE] % vars ()
1294 for image in self.get_images ():
1295 (base, ext) = os.path.splitext (image)
1296 alt = self.option_dict[ALT]
1297 str += output[HTML][OUTPUT] % vars ()
1298 str += output[HTML][AFTER] % vars ()
1301 def output_info (self):
1303 for image in self.get_images ():
1304 (base, ext) = os.path.splitext (image)
1306 # URG, makeinfo implicitly prepends dot to extension.
1307 # Specifying no extension is most robust.
1309 alt = self.option_dict[ALT]
1310 info_image_path = os.path.join (global_options.info_images_dir, base)
1311 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1313 base = self.basename ()
1314 str += output[self.format][OUTPUT] % vars ()
1317 def output_latex (self):
1319 base = self.basename ()
1320 if self.format == LATEX:
1321 str += self.output_print_filename (LATEX)
1322 if VERBATIM in self.option_dict:
1323 verb = self.verb_ly ()
1324 str += (output[LATEX][VERBATIM] % vars ())
1326 str += (output[LATEX][OUTPUT] % vars ())
1328 ## todo: maintain breaks
1330 breaks = self.ly ().count ("\n")
1331 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1333 if QUOTE in self.option_dict:
1334 str = output[LATEX][QUOTE] % vars ()
1337 def output_print_filename (self, format):
1339 if PRINTFILENAME in self.option_dict:
1340 base = self.basename ()
1341 filename = os.path.basename (self.substring ('filename'))
1342 str = output[format][PRINTFILENAME] % vars ()
1346 def output_texinfo (self):
1347 str = self.output_print_filename (TEXINFO)
1348 base = self.basename ()
1349 if TEXIDOC in self.option_dict:
1350 texidoc = base + '.texidoc'
1351 translated_texidoc = texidoc + document_language
1352 if os.path.exists (translated_texidoc):
1353 str += '@include %(translated_texidoc)s\n\n' % vars ()
1354 elif os.path.exists (texidoc):
1355 str += '@include %(texidoc)s\n\n' % vars ()
1358 if VERBATIM in self.option_dict:
1360 if ADDVERSION in self.option_dict:
1361 version = output[TEXINFO][ADDVERSION]
1362 verb = self.verb_ly ()
1363 substr = output[TEXINFO][VERBATIM] % vars ()
1364 substr += self.output_info ()
1365 if LILYQUOTE in self.option_dict:
1366 substr = output[TEXINFO][QUOTE] % {'str':substr}
1369 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1370 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1371 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1373 if QUOTE in self.option_dict:
1374 str = output[TEXINFO][QUOTE] % vars ()
1376 # need par after image
1381 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1382 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1384 class LilypondFileSnippet (LilypondSnippet):
1385 def __init__ (self, type, match, format, line_number):
1386 LilypondSnippet.__init__ (self, type, match, format, line_number)
1387 self.contents = file (find_file (self.substring ('filename'))).read ()
1391 s = re_begin_verbatim.split (s)[-1]
1392 s = re_end_verbatim.split (s)[0]
1393 return verb_ly_gettext (s)
1396 name = self.substring ('filename')
1397 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1398 % (name, self.contents))
1401 snippet_type_to_class = {
1402 'lilypond_file': LilypondFileSnippet,
1403 'lilypond_block': LilypondSnippet,
1404 'lilypond': LilypondSnippet,
1405 'include': IncludeSnippet,
1408 def find_linestarts (s):
1413 i = s.find ('\n', start)
1421 nls.append (len (s))
1424 def find_toplevel_snippets (input_string, format, types):
1427 res[t] = re.compile (snippet_res[format][t])
1431 found = dict ([(t, None) for t in types])
1433 line_starts = find_linestarts (input_string)
1435 # We want to search for multiple regexes, without searching
1436 # the string multiple times for one regex.
1437 # Hence, we use earlier results to limit the string portion
1439 # Since every part of the string is traversed at most once for
1440 # every type of snippet, this is linear.
1446 if not found[type] or found[type][0] < index:
1449 m = res[type].search (input_string[index:endex])
1454 if type in snippet_type_to_class:
1455 klass = snippet_type_to_class[type]
1457 start = index + m.start ('match')
1458 line_number = line_start_idx
1459 while (line_starts[line_number] < start):
1463 snip = klass (type, m, format, line_number)
1465 found[type] = (start, snip)
1469 or found[type][0] < found[first][0])):
1474 # Limiting the search space is a cute
1475 # idea, but this *requires* to search
1476 # for possible containing blocks
1477 # first, at least as long as we do not
1478 # search for the start of blocks, but
1479 # always/directly for the entire
1480 # @block ... @end block.
1482 endex = found[first][0]
1485 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1488 while (start > line_starts[line_start_idx+1]):
1491 (start, snip) = found[first]
1492 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1493 snippets.append (snip)
1495 index = start + len (snip.match.group ('match'))
1499 def filter_pipe (input, cmd):
1500 """Pass input through cmd, and return the result."""
1502 if global_options.verbose:
1503 progress (_ ("Opening filter `%s'") % cmd)
1505 (stdin, stdout, stderr) = os.popen3 (cmd)
1507 status = stdin.close ()
1511 output = stdout.read ()
1512 status = stdout.close ()
1513 error = stderr.read ()
1517 signal = 0x0f & status
1518 if status or (not output and error):
1519 exit_status = status >> 8
1520 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1521 error (_ ("The error log is as follows:"))
1522 ly.stderr_write (error)
1523 ly.stderr_write (stderr.read ())
1526 if global_options.verbose:
1531 def system_in_directory (cmd, directory):
1532 """Execute a command in a different directory.
1534 Because of win32 compatibility, we can't simply use subprocess.
1537 current = os.getcwd()
1538 os.chdir (directory)
1539 ly.system(cmd, be_verbose=global_options.verbose,
1544 def process_snippets (cmd, snippets,
1545 format, lily_output_dir):
1546 """Run cmd on all of the .ly files from snippets."""
1551 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1552 cmd += ' --formats=png '
1553 elif format in (DOCBOOK) and '--formats' not in cmd:
1554 cmd += ' --formats=png,pdf '
1556 checksum = snippet_list_checksum (snippets)
1557 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1558 + [snip.basename() + '.ly' for snip in snippets])
1559 name = os.path.join (lily_output_dir,
1560 'snippet-names-%d.ly' % checksum)
1561 file (name, 'wb').write (contents)
1563 system_in_directory (' '.join ([cmd, name]),
1568 # Retrieve dimensions from LaTeX
1569 LATEX_INSPECTION_DOCUMENT = r'''
1573 \typeout{textwidth=\the\textwidth}
1574 \typeout{columnsep=\the\columnsep}
1575 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1579 # Do we need anything else besides `textwidth'?
1580 def get_latex_textwidth (source):
1581 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1583 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1585 ## what's a sensible default?
1588 preamble = source[:m.start (0)]
1589 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1591 (handle, tmpfile) = tempfile.mkstemp('.tex')
1592 logfile = os.path.splitext (tmpfile)[0] + '.log'
1593 logfile = os.path.split (logfile)[1]
1595 tmp_handle = os.fdopen (handle,'w')
1596 tmp_handle.write (latex_document)
1599 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1600 be_verbose=global_options.verbose)
1601 parameter_string = file (logfile).read()
1607 m = re.search ('columns=([0-9.]*)', parameter_string)
1609 columns = int (m.group (1))
1612 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1614 columnsep = float (m.group (1))
1617 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1619 textwidth = float (m.group (1))
1621 textwidth = (textwidth - columnsep) / columns
1625 def modify_preamble (chunk):
1626 str = chunk.replacement_text ()
1627 if (re.search (r"\\begin *{document}", str)
1628 and not re.search ("{graphic[sx]", str)):
1629 str = re.sub (r"\\begin{document}",
1630 r"\\usepackage{graphics}" + '\n'
1631 + r"\\begin{document}",
1633 chunk.override_text = str
1638 # TEXINFO: '.texinfo',
1644 class CompileError(Exception):
1647 def snippet_list_checksum (snippets):
1648 return hash (' '.join([l.basename() for l in snippets]))
1650 def write_file_map (lys, name):
1651 snippet_map = file (os.path.join (
1652 global_options.lily_output_dir,
1653 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1655 snippet_map.write ("""
1656 #(define version-seen #t)
1657 #(define output-empty-score-list #f)
1658 #(ly:add-file-name-alist '(%s
1660 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1663 def split_output_files(directory):
1664 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1666 Return value is a set of strings.
1669 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1670 base_subdir = os.path.split (subdir)[1]
1671 sub_files = [os.path.join (base_subdir, name)
1672 for name in os.listdir (subdir)]
1676 def do_process_cmd (chunks, input_name, options):
1677 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1679 output_files = split_output_files (options.lily_output_dir)
1680 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1682 write_file_map (outdated, input_name)
1683 progress (_ ("Writing snippets..."))
1684 for snippet in outdated:
1689 progress (_ ("Processing..."))
1691 process_snippets (options.process_cmd, outdated,
1692 options.format, options.lily_output_dir)
1695 progress (_ ("All snippets are up to date..."))
1697 if options.lily_output_dir != options.output_dir:
1698 output_files = split_output_files (options.lily_output_dir)
1699 for snippet in snippets:
1700 snippet.link_all_output_files (options.lily_output_dir,
1708 # Format guessing data
1717 '.texinfo': TEXINFO,
1722 def guess_format (input_filename):
1724 e = os.path.splitext (input_filename)[1]
1727 format = ext2format[e]
1729 error (_ ("cannot determine format for: %s"
1734 def write_if_updated (file_name, lines):
1736 f = file (file_name)
1738 new_str = ''.join (lines)
1739 if oldstr == new_str:
1740 progress (_ ("%s is up to date.") % file_name)
1743 # this prevents make from always rerunning lilypond-book:
1744 # output file must be touched in order to be up to date
1745 os.utime (file_name, None)
1750 output_dir = os.path.dirname (file_name)
1751 if not os.path.exists (output_dir):
1752 os.makedirs (output_dir)
1754 progress (_ ("Writing `%s'...") % file_name)
1755 file (file_name, 'w').writelines (lines)
1759 def note_input_file (name, inputs=[]):
1760 ## hack: inputs is mutable!
1761 inputs.append (name)
1764 def samefile (f1, f2):
1766 return os.path.samefile (f1, f2)
1767 except AttributeError: # Windoze
1768 f1 = re.sub ("//*", "/", f1)
1769 f2 = re.sub ("//*", "/", f2)
1772 def do_file (input_filename, included=False):
1774 if not input_filename or input_filename == '-':
1775 in_handle = sys.stdin
1776 input_fullname = '<stdin>'
1778 if os.path.exists (input_filename):
1779 input_fullname = input_filename
1780 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1781 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1783 input_fullname = find_file (input_filename)
1785 note_input_file (input_fullname)
1786 in_handle = file (input_fullname)
1788 if input_filename == '-':
1789 input_base = 'stdin'
1791 input_base = os.path.splitext (input_filename)[0]
1793 input_base = os.path.basename (
1794 os.path.splitext (input_filename)[0])
1796 # don't complain when global_options.output_dir is existing
1797 if not global_options.output_dir:
1798 global_options.output_dir = os.getcwd()
1800 global_options.output_dir = os.path.abspath(global_options.output_dir)
1802 if not os.path.isdir (global_options.output_dir):
1803 os.mkdir (global_options.output_dir, 0777)
1804 os.chdir (global_options.output_dir)
1806 output_filename = os.path.join(global_options.output_dir,
1807 input_base + format2ext[global_options.format])
1808 if (os.path.exists (input_filename)
1809 and os.path.exists (output_filename)
1810 and samefile (output_filename, input_fullname)):
1812 _ ("Output would overwrite input file; use --output."))
1816 progress (_ ("Reading %s...") % input_fullname)
1817 source = in_handle.read ()
1820 set_default_options (source, default_ly_options, global_options.format)
1823 # FIXME: Containing blocks must be first, see
1824 # find_toplevel_snippets.
1826 'multiline_comment',
1830 'singleline_comment',
1835 progress (_ ("Dissecting..."))
1836 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1838 if global_options.format == LATEX:
1840 if (c.is_plain () and
1841 re.search (r"\\begin *{document}", c.replacement_text())):
1846 if global_options.filter_cmd:
1847 write_if_updated (output_filename,
1848 [c.filter_text () for c in chunks])
1849 elif global_options.process_cmd:
1850 do_process_cmd (chunks, input_fullname, global_options)
1851 progress (_ ("Compiling %s...") % output_filename)
1853 write_if_updated (output_filename,
1854 [s.replacement_text ()
1857 def process_include (snippet):
1858 os.chdir (original_dir)
1859 name = snippet.substring ('filename')
1860 progress (_ ("Processing include: %s") % name)
1862 return do_file (name, included=True)
1864 include_chunks = map (process_include,
1865 filter (lambda x: isinstance (x, IncludeSnippet),
1868 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1870 except CompileError:
1871 os.chdir (original_dir)
1872 progress (_ ("Removing `%s'") % output_filename)
1877 global global_options
1879 opt_parser = get_option_parser()
1880 (global_options, args) = opt_parser.parse_args ()
1881 if global_options.format in ('texi-html', 'texi'):
1882 global_options.format = TEXINFO
1884 global_options.include_path = map (os.path.abspath, global_options.include_path)
1886 if global_options.warranty:
1889 if not args or len (args) > 1:
1890 opt_parser.print_help ()
1896 # FIXME: 85 lines of `main' macramee??
1897 files = do_options ()
1899 basename = os.path.splitext (files[0])[0]
1900 basename = os.path.split (basename)[1]
1902 if not global_options.format:
1903 global_options.format = guess_format (files[0])
1906 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1909 if global_options.process_cmd == '':
1910 global_options.process_cmd = (lilypond_binary
1911 + ' --formats=%s -dbackend=eps ' % formats)
1913 if global_options.process_cmd:
1914 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1915 for p in global_options.include_path])
1917 if global_options.format in (TEXINFO, LATEX):
1918 ## prevent PDF from being switched on by default.
1919 global_options.process_cmd += ' --formats=eps '
1920 if global_options.create_pdf:
1921 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1923 if global_options.verbose:
1924 global_options.process_cmd += " --verbose "
1926 if global_options.padding_mm:
1927 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1929 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1931 if global_options.lily_output_dir:
1932 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1933 if not os.path.isdir (global_options.lily_output_dir):
1934 os.makedirs (global_options.lily_output_dir)
1936 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1941 chunks = do_file (files[0])
1942 except CompileError:
1945 inputs = note_input_file ('')
1948 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1949 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1950 final_output_file = os.path.join (global_options.output_dir,
1952 + '.%s' % global_options.format)
1954 os.chdir (original_dir)
1955 file (dep_file, 'w').write ('%s: %s'
1956 % (final_output_file, ' '.join (inputs)))
1958 if __name__ == '__main__':