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 -F "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 [default: `convert-ly -n -']"),
119 p.add_option ('-f', '--format',
120 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
121 metavar=_ ("FORMAT"),
124 p.add_option("-h", "--help",
126 help=_ ("show this help and exit"))
128 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
130 action='append', dest='include_path',
131 default=[os.path.abspath (os.getcwd ())])
133 p.add_option ('--info-images-dir',
134 help=_ ("format Texinfo output so that Info will "
135 "look for images of music in DIR"),
137 action='store', dest='info_images_dir',
140 p.add_option ('--latex-program',
141 help=_ ("run executable PROG instead of latex"),
143 action='store', dest='latex_program',
146 p.add_option ('--left-padding',
149 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
153 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
155 action='store', dest='output_dir',
158 p.add_option ('--skip-lily-check',
159 help=_ ("do not fail if no lilypond output is found"),
161 action='store_true', dest='skip_lilypond_run',
164 p.add_option ('--skip-png-check',
165 help=_ ("do not fail if no PNG images are found for EPS files"),
167 action='store_true', dest='skip_png_check',
170 p.add_option ('--lily-output-dir',
171 help=_ ("write lily-XXX files to DIR, link into --output dir"),
173 action='store', dest='lily_output_dir',
176 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
177 help = _ ("process ly_files using COMMAND FILE..."),
179 dest='process_cmd', default='')
181 p.add_option ('--pdf',
184 help=_ ("create PDF files for use with PDFTeX"),
187 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
192 p.version = "@TOPLEVEL_VERSION@"
193 p.add_option("--version",
195 help=_ ("show version number and exit"))
197 p.add_option ('-w', '--warranty',
198 help=_ ("show warranty and copyright"),
200 p.add_option_group ('',
202 _ ("Report bugs via")
203 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
206 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
208 # Only use installed binary when we are installed too.
209 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
210 lilypond_binary = 'lilypond'
212 global_options = None
215 default_ly_options = { 'alt': "[image of music]" }
217 document_language = ''
220 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
222 ADDVERSION = 'addversion'
226 EXAMPLEINDENT = 'exampleindent'
228 FRAGMENT = 'fragment'
234 LINE_WIDTH = 'line-width'
235 LILYQUOTE = 'lilyquote'
236 NOFRAGMENT = 'nofragment'
237 NOINDENT = 'noindent'
239 NORAGGED_RIGHT = 'noragged-right'
243 OUTPUTIMAGE = 'outputimage'
246 PREAMBLE = 'preamble'
247 PRINTFILENAME = 'printfilename'
249 RAGGED_RIGHT = 'ragged-right'
250 RELATIVE = 'relative'
251 STAFFSIZE = 'staffsize'
252 DOCTITLE = 'doctitle'
255 VERBATIM = 'verbatim'
256 FONTLOAD = 'fontload'
257 FILENAME = 'filename'
261 # NOTIME has no opposite so it isn't part of this dictionary.
262 # NOQUOTE is used internally only.
264 NOFRAGMENT: FRAGMENT,
269 # Recognize special sequences in the input.
271 # (?P<name>regex) -- Assign result of REGEX to NAME.
272 # *? -- Match non-greedily.
273 # (?m) -- Multiline regex: Make ^ and $ match at each line.
274 # (?s) -- Make the dot match all characters including newline.
275 # (?x) -- Ignore whitespace in patterns.
286 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
291 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
296 <(?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>)''',
302 (?P<code><!--\s.*?!-->)
305 'singleline_comment':
324 (\s*(?P<options>.*?)\s*:)?\s*
332 \s*(?P<options>.*?)\s*
341 \s*(?P<options>.*?)\s*
343 \s*(?P<filename>.*?)\s*
350 (?P<code><!--\s.*?!-->)
353 'singleline_comment':
359 (?P<code><pre>.*?</pre>))''',
365 (?P<code><pre>\s.*?</pre>\s))''',
384 \s*(?P<options>.*?)\s*
395 \s*(?P<options>.*?)\s*
399 \\end\s*{lilypond})''',
407 \s*(?P<options>.*?)\s*
415 'singleline_comment':
438 \\end\s*{verbatim}))''',
447 (?P<filename>\S+))''',
451 ^[^\n]*?(?!@c\s+)[^\n]*?
455 \s*(?P<options>.*?)\s*
465 \s*(?P<options>.*?)\s*
468 ^@end\s+lilypond)\s''',
475 \s*(?P<options>.*?)\s*
486 @end\s+ignore))\s''',
488 'singleline_comment':
493 @c([ \t][^\n]*|)\n))''',
495 # Don't do this: It interferes with @code{@{}.
496 # 'verb': r'''(?P<code>@code{.*?})''',
504 @end\s+example\s))''',
513 'intertext': r',?\s*intertext=\".*?\"',
517 'intertext': r',?\s*intertext=\".*?\"',
522 'intertext': r',?\s*intertext=\".*?\"',
523 'option_sep': '\s*,\s*',
527 'intertext': r',?\s*intertext=\".*?\"',
528 'option_sep': '\s*,\s*',
532 # Options without a pattern in ly_options.
552 RELATIVE: r'''\relative c%(relative_quotes)s''',
557 INDENT: r'''indent = %(indent)s''',
559 LINE_WIDTH: r'''line-width = %(line-width)s''',
561 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
563 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
565 RAGGED_RIGHT: r'''ragged-right = ##t''',
567 NORAGGED_RIGHT: r'''ragged-right = ##f''',
569 PACKED: r'''packed = ##t''',
581 \remove "Time_signature_engraver"
587 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
594 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
597 <imageobject role="latex">
598 <imagedata fileref="%(base)s.pdf" format="PDF"/>
600 <imageobject role="html">
601 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
603 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
605 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
609 FILTER: r'''<lilypond %(options)s>
619 <a href="%(base)s.ly">''',
623 border="0" src="%(image)s" alt="%(alt)s">''',
625 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
627 QUOTE: r'''<blockquote>
640 \ifx\preLilyPondExample \undefined%%
643 \preLilyPondExample%%
645 \def\lilypondbook{}%%
646 \input %(base)s-systems.tex%%
647 \ifx\postLilyPondExample \undefined%%
650 \postLilyPondExample%%
654 PRINTFILENAME: '''\\texttt{%(filename)s}
657 QUOTE: r'''\begin{quotation}%(str)s
660 VERBATIM: r'''\noindent
661 \begin{verbatim}%(verb)s\end{verbatim}''',
663 FILTER: r'''\begin{lilypond}[%(options)s]
670 FILTER: r'''@lilypond[%(options)s]
676 @include %(base)s-systems.texi
680 OUTPUTIMAGE: r'''@noindent
682 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
686 <a href="%(base)s.ly">
688 border="0" src="%(image)s" alt="%(alt)s">
696 <a href="%(base)s.ly">
704 QUOTE: r'''@quotation
705 %(str)s@end quotation
712 VERBATIM: r'''@exampleindent 0
714 %(verb)s@end verbatim
717 ADDVERSION: r'''@example
718 \version @w{"@version{}"}
725 # Maintain line numbers.
730 for f in [HTML, LATEX]:
731 for s in (QUOTE, VERBATIM):
732 output[f][s] = output[f][s].replace("\n"," ")
735 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
736 %%%% Options: [%(option_string)s]
737 \\include "lilypond-book-preamble.ly"
740 %% ****************************************************************
741 %% Start cut-&-pastable-section
742 %% ****************************************************************
747 #(define dump-extents #t)
748 %(font_dump_setting)s
750 force-assignment = #""
751 line-width = #(- line-width (* mm %(padding_mm)f))
764 %% ****************************************************************
765 %% ly snippet contents follows:
766 %% ****************************************************************
770 %% ****************************************************************
772 %% ****************************************************************
779 %% ****************************************************************
781 %% ****************************************************************
785 %% ****************************************************************
787 %% ****************************************************************
790 texinfo_line_widths = {
791 '@afourpaper': '160\\mm',
792 '@afourwide': '6.5\\in',
793 '@afourlatex': '150\\mm',
794 '@smallbook': '5\\in',
795 '@letterpaper': '6\\in',
798 def classic_lilypond_book_compatibility (key, value):
799 if key == 'singleline' and value == None:
800 return (RAGGED_RIGHT, None)
802 m = re.search ('relative\s*([-0-9])', key)
804 return ('relative', m.group (1))
806 m = re.match ('([0-9]+)pt', key)
808 return ('staffsize', m.group (1))
810 if key == 'indent' or key == 'line-width':
811 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
813 f = float (m.group (1))
814 return (key, '%f\\%s' % (f, m.group (2)))
818 def find_file (name, raise_error=True):
819 for i in global_options.include_path:
820 full = os.path.join (i, name)
821 if os.path.exists (full):
825 error (_ ("file not found: %s") % name + '\n')
829 def verbatim_html (s):
830 return re.sub ('>', '>',
832 re.sub ('&', '&', s)))
834 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
835 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
837 def ly_comment_gettext (t, m):
838 return m.group (1) + t (m.group (2))
840 def verb_ly_gettext (s):
841 if not document_language:
844 t = langdefs.translation[document_language]
848 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
850 for v in ly_var_def_re.findall (s):
851 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
852 "\\1" + t (v) + "\\2",
856 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
857 def set_default_options (source, default_ly_options, format):
858 global document_language
859 if LINE_WIDTH not in default_ly_options:
861 textwidth = get_latex_textwidth (source)
862 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
863 elif format == TEXINFO:
864 m = texinfo_lang_re.search (source)
865 if m and not m.group (1).startswith ('en'):
866 document_language = m.group (1)
868 document_language = ''
869 for regex in texinfo_line_widths:
870 # FIXME: @layout is usually not in
873 # \input texinfo @c -*-texinfo-*-
875 # Bluntly search first K items of
877 # s = chunks[0].replacement_text ()
878 if re.search (regex, source[:1024]):
879 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
883 def replacement_text (self):
886 def filter_text (self):
887 return self.replacement_text ()
892 class Substring (Chunk):
893 """A string that does not require extra memory."""
894 def __init__ (self, source, start, end, line_number):
898 self.line_number = line_number
899 self.override_text = None
904 def replacement_text (self):
905 if self.override_text:
906 return self.override_text
908 return self.source[self.start:self.end]
910 class Snippet (Chunk):
911 def __init__ (self, type, match, format, line_number):
915 self.option_dict = {}
917 self.line_number = line_number
919 def replacement_text (self):
920 return self.match.group ('match')
922 def substring (self, s):
923 return self.match.group (s)
926 return `self.__class__` + ' type = ' + self.type
928 class IncludeSnippet (Snippet):
929 def processed_filename (self):
930 f = self.substring ('filename')
931 return os.path.splitext (f)[0] + format2ext[self.format]
933 def replacement_text (self):
934 s = self.match.group ('match')
935 f = self.substring ('filename')
937 return re.sub (f, self.processed_filename (), s)
939 class LilypondSnippet (Snippet):
940 def __init__ (self, type, match, format, line_number):
941 Snippet.__init__ (self, type, match, format, line_number)
942 os = match.group ('options')
943 self.do_options (os, self.type)
946 return verb_ly_gettext (self.substring ('code'))
949 contents = self.substring ('code')
950 return ('\\sourcefileline %d\n%s'
951 % (self.line_number - 1, contents))
956 return self.compose_ly (s)
959 def split_options (self, option_string):
961 if self.format == HTML:
962 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
964 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
968 return re.split (format_res[self.format]['option_sep'],
972 def do_options (self, option_string, type):
973 self.option_dict = {}
975 options = self.split_options (option_string)
977 for option in options:
979 (key, value) = re.split ('\s*=\s*', option)
980 self.option_dict[key] = value
982 if option in no_options:
983 if no_options[option] in self.option_dict:
984 del self.option_dict[no_options[option]]
986 self.option_dict[option] = None
988 has_line_width = self.option_dict.has_key (LINE_WIDTH)
989 no_line_width_value = 0
991 # If LINE_WIDTH is used without parameter, set it to default.
992 if has_line_width and self.option_dict[LINE_WIDTH] == None:
993 no_line_width_value = 1
994 del self.option_dict[LINE_WIDTH]
996 for k in default_ly_options:
997 if k not in self.option_dict:
998 self.option_dict[k] = default_ly_options[k]
1000 # RELATIVE does not work without FRAGMENT;
1001 # make RELATIVE imply FRAGMENT
1002 has_relative = self.option_dict.has_key (RELATIVE)
1003 if has_relative and not self.option_dict.has_key (FRAGMENT):
1004 self.option_dict[FRAGMENT] = None
1006 if not has_line_width:
1007 if type == 'lilypond' or FRAGMENT in self.option_dict:
1008 self.option_dict[RAGGED_RIGHT] = None
1010 if type == 'lilypond':
1011 if LINE_WIDTH in self.option_dict:
1012 del self.option_dict[LINE_WIDTH]
1014 if RAGGED_RIGHT in self.option_dict:
1015 if LINE_WIDTH in self.option_dict:
1016 del self.option_dict[LINE_WIDTH]
1018 if QUOTE in self.option_dict or type == 'lilypond':
1019 if LINE_WIDTH in self.option_dict:
1020 del self.option_dict[LINE_WIDTH]
1022 if not INDENT in self.option_dict:
1023 self.option_dict[INDENT] = '0\\mm'
1025 # The QUOTE pattern from ly_options only emits the `line-width'
1027 if has_line_width and QUOTE in self.option_dict:
1028 if no_line_width_value:
1029 del self.option_dict[LINE_WIDTH]
1031 del self.option_dict[QUOTE]
1033 def compose_ly (self, code):
1034 if FRAGMENT in self.option_dict:
1042 # The original concept of the `exampleindent' option is broken.
1043 # It is not possible to get a sane value for @exampleindent at all
1044 # without processing the document itself. Saying
1052 # causes ugly results with the DVI backend of texinfo since the
1053 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1054 # value). Executing the above code changes the environment
1055 # indentation to an unknown value because we don't know the amount
1056 # of 1em in advance since it is font-dependent. Modifying
1057 # @exampleindent in the middle of a document is simply not
1058 # supported within texinfo.
1060 # As a consequence, the only function of @exampleindent is now to
1061 # specify the amount of indentation for the `quote' option.
1063 # To set @exampleindent locally to zero, we use the @format
1064 # environment for non-quoted snippets.
1065 override[EXAMPLEINDENT] = r'0.4\in'
1066 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1067 override.update (default_ly_options)
1070 for (key, value) in self.option_dict.items ():
1072 option_list.append (key)
1074 option_list.append (key + '=' + value)
1075 option_string = ','.join (option_list)
1078 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1079 for a in compose_types:
1080 compose_dict[a] = []
1082 for (key, value) in self.option_dict.items ():
1083 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1087 _ ("deprecated ly-option used: %s=%s") % (key, value))
1089 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1092 _ ("deprecated ly-option used: %s") % key)
1094 _ ("compatibility mode translation: %s") % c_key)
1096 (key, value) = (c_key, c_value)
1099 override[key] = value
1101 if not override.has_key (key):
1102 override[key] = None
1105 for type in compose_types:
1106 if ly_options[type].has_key (key):
1107 compose_dict[type].append (ly_options[type][key])
1111 if not found and key not in simple_options:
1112 warning (_ ("ignoring unknown ly option: %s") % key)
1115 if RELATIVE in override and override[RELATIVE]:
1116 relative = int (override[RELATIVE])
1118 relative_quotes = ''
1122 relative_quotes += ',' * (- relative)
1124 relative_quotes += "'" * relative
1126 paper_string = '\n '.join (compose_dict[PAPER]) % override
1127 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1128 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1129 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1130 padding_mm = global_options.padding_mm
1131 font_dump_setting = ''
1132 if FONTLOAD in self.option_dict:
1133 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1135 d = globals().copy()
1137 return (PREAMBLE_LY + body) % d
1139 def get_checksum (self):
1140 if not self.checksum:
1141 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1143 ## let's not create too long names.
1144 self.checksum = hash.hexdigest ()[:10]
1146 return self.checksum
1148 def basename (self):
1149 cs = self.get_checksum ()
1150 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1153 def write_ly (self):
1154 base = self.basename ()
1155 path = os.path.join (global_options.lily_output_dir, base)
1156 directory = os.path.split(path)[0]
1157 if not os.path.isdir (directory):
1158 os.makedirs (directory)
1159 out = file (path + '.ly', 'w')
1160 out.write (self.full_ly ())
1161 file (path + '.txt', 'w').write ('image of music')
1163 def relevant_contents (self, ly):
1164 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1166 def link_all_output_files (self, output_dir, output_dir_files, destination):
1167 existing, missing = self.all_output_files (output_dir, output_dir_files)
1169 print '\nMissing', missing
1170 raise CompileError(self.basename())
1171 for name in existing:
1173 os.unlink (os.path.join (destination, name))
1177 src = os.path.join (output_dir, name)
1178 dst = os.path.join (destination, name)
1179 dst_path = os.path.split(dst)[0]
1180 if not os.path.isdir (dst_path):
1181 os.makedirs (dst_path)
1185 def all_output_files (self, output_dir, output_dir_files):
1186 """Return all files generated in lily_output_dir, a set.
1188 output_dir_files is the list of files in the output directory.
1192 base = self.basename()
1193 full = os.path.join (output_dir, base)
1194 def consider_file (name):
1195 if name in output_dir_files:
1198 def require_file (name):
1199 if name in output_dir_files:
1204 # UGH - junk global_options
1205 skip_lily = global_options.skip_lilypond_run
1206 for required in [base + '.ly',
1208 require_file (required)
1210 require_file (base + '-systems.count')
1212 if 'ddump-profile' in global_options.process_cmd:
1213 require_file (base + '.profile')
1214 if 'dseparate-log-file' in global_options.process_cmd:
1215 require_file (base + '.log')
1217 map (consider_file, [base + '.tex',
1221 base + '-systems.texi',
1222 base + '-systems.tex',
1223 base + '-systems.pdftexi'])
1224 if document_language:
1226 [base + '.texidoc' + document_language,
1227 base + '.doctitle' + document_language])
1229 # UGH - junk global_options
1230 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1231 and not global_options.skip_png_check):
1232 page_count = ps_page_count (full + '.eps')
1234 require_file (base + '.png')
1236 for page in range (1, page_count + 1):
1237 require_file (base + '-page%d.png' % page)
1240 if not skip_lily and not missing:
1241 system_count = int(file (full + '-systems.count').read())
1243 for number in range(1, system_count + 1):
1244 systemfile = '%s-%d' % (base, number)
1245 require_file (systemfile + '.eps')
1246 consider_file (systemfile + '.pdf')
1248 # We can't require signatures, since books and toplevel
1249 # markups do not output a signature.
1250 if 'ddump-signature' in global_options.process_cmd:
1251 consider_file (systemfile + '.signature')
1254 return (result, missing)
1256 def is_outdated (self, output_dir, current_files):
1257 found, missing = self.all_output_files (output_dir, current_files)
1260 def filter_text (self):
1261 """Run snippet bodies through a command (say: convert-ly).
1263 This functionality is rarely used, and this code must have bitrot.
1265 code = self.substring ('code')
1266 s = filter_pipe (code, global_options.filter_cmd)
1269 'options': self.match.group ('options')
1272 return output[self.format][FILTER] % d
1274 def replacement_text (self):
1275 func = LilypondSnippet.__dict__['output_' + self.format]
1278 def get_images (self):
1279 base = self.basename ()
1281 single = '%(base)s.png' % vars ()
1282 multiple = '%(base)s-page1.png' % vars ()
1284 if (os.path.exists (multiple)
1285 and (not os.path.exists (single)
1286 or (os.stat (multiple)[stat.ST_MTIME]
1287 > os.stat (single)[stat.ST_MTIME]))):
1288 count = ps_page_count ('%(base)s.eps' % vars ())
1289 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1290 images = tuple (images)
1294 def output_docbook (self):
1296 base = self.basename ()
1297 for image in self.get_images ():
1298 (base, ext) = os.path.splitext (image)
1299 str += output[DOCBOOK][OUTPUT] % vars ()
1300 str += self.output_print_filename (DOCBOOK)
1301 if (self.substring('inline') == 'inline'):
1302 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1304 str = '<mediaobject>' + str + '</mediaobject>'
1305 if VERBATIM in self.option_dict:
1306 verb = verbatim_html (self.verb_ly ())
1307 str = output[DOCBOOK][VERBATIM] % vars () + str
1310 def output_html (self):
1312 base = self.basename ()
1313 if self.format == HTML:
1314 str += self.output_print_filename (HTML)
1315 if VERBATIM in self.option_dict:
1316 verb = verbatim_html (self.verb_ly ())
1317 str += output[HTML][VERBATIM] % vars ()
1318 if QUOTE in self.option_dict:
1319 str = output[HTML][QUOTE] % vars ()
1321 str += output[HTML][BEFORE] % vars ()
1322 for image in self.get_images ():
1323 (base, ext) = os.path.splitext (image)
1324 alt = self.option_dict[ALT]
1325 str += output[HTML][OUTPUT] % vars ()
1326 str += output[HTML][AFTER] % vars ()
1329 def output_info (self):
1331 for image in self.get_images ():
1332 (base, ext) = os.path.splitext (image)
1334 # URG, makeinfo implicitly prepends dot to extension.
1335 # Specifying no extension is most robust.
1337 alt = self.option_dict[ALT]
1338 info_image_path = os.path.join (global_options.info_images_dir, base)
1339 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1341 base = self.basename ()
1342 str += output[self.format][OUTPUT] % vars ()
1345 def output_latex (self):
1347 base = self.basename ()
1348 if self.format == LATEX:
1349 str += self.output_print_filename (LATEX)
1350 if VERBATIM in self.option_dict:
1351 verb = self.verb_ly ()
1352 str += (output[LATEX][VERBATIM] % vars ())
1354 str += (output[LATEX][OUTPUT] % vars ())
1356 ## todo: maintain breaks
1358 breaks = self.ly ().count ("\n")
1359 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1361 if QUOTE in self.option_dict:
1362 str = output[LATEX][QUOTE] % vars ()
1365 def output_print_filename (self, format):
1367 if PRINTFILENAME in self.option_dict:
1368 base = self.basename ()
1369 filename = os.path.basename (self.substring ('filename'))
1370 str = output[format][PRINTFILENAME] % vars ()
1374 def output_texinfo (self):
1375 str = self.output_print_filename (TEXINFO)
1376 base = self.basename ()
1377 if DOCTITLE in self.option_dict:
1378 doctitle = base + '.doctitle'
1379 translated_doctitle = doctitle + document_language
1380 if os.path.exists (translated_doctitle):
1381 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1382 elif os.path.exists (doctitle):
1383 str += '@lydoctitle %s\n' % open (doctitle).read ()
1384 if TEXIDOC in self.option_dict:
1385 texidoc = base + '.texidoc'
1386 translated_texidoc = texidoc + document_language
1387 if os.path.exists (translated_texidoc):
1388 str += '@include %(translated_texidoc)s\n\n' % vars ()
1389 elif os.path.exists (texidoc):
1390 str += '@include %(texidoc)s\n\n' % vars ()
1393 if VERBATIM in self.option_dict:
1395 if ADDVERSION in self.option_dict:
1396 version = output[TEXINFO][ADDVERSION]
1397 verb = self.verb_ly ()
1398 substr = output[TEXINFO][VERBATIM] % vars ()
1399 substr += self.output_info ()
1400 if LILYQUOTE in self.option_dict:
1401 substr = output[TEXINFO][QUOTE] % {'str':substr}
1404 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1405 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1406 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1408 if QUOTE in self.option_dict:
1409 str = output[TEXINFO][QUOTE] % vars ()
1411 # need par after image
1416 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1417 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1419 class LilypondFileSnippet (LilypondSnippet):
1420 def __init__ (self, type, match, format, line_number):
1421 LilypondSnippet.__init__ (self, type, match, format, line_number)
1422 self.contents = file (find_file (self.substring ('filename'))).read ()
1426 s = re_begin_verbatim.split (s)[-1]
1427 s = re_end_verbatim.split (s)[0]
1428 return verb_ly_gettext (s)
1431 name = self.substring ('filename')
1432 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1433 % (name, self.contents))
1436 snippet_type_to_class = {
1437 'lilypond_file': LilypondFileSnippet,
1438 'lilypond_block': LilypondSnippet,
1439 'lilypond': LilypondSnippet,
1440 'include': IncludeSnippet,
1443 def find_linestarts (s):
1448 i = s.find ('\n', start)
1456 nls.append (len (s))
1459 def find_toplevel_snippets (input_string, format, types):
1462 res[t] = re.compile (snippet_res[format][t])
1466 found = dict ([(t, None) for t in types])
1468 line_starts = find_linestarts (input_string)
1470 # We want to search for multiple regexes, without searching
1471 # the string multiple times for one regex.
1472 # Hence, we use earlier results to limit the string portion
1474 # Since every part of the string is traversed at most once for
1475 # every type of snippet, this is linear.
1481 if not found[type] or found[type][0] < index:
1484 m = res[type].search (input_string[index:endex])
1489 if type in snippet_type_to_class:
1490 klass = snippet_type_to_class[type]
1492 start = index + m.start ('match')
1493 line_number = line_start_idx
1494 while (line_starts[line_number] < start):
1498 snip = klass (type, m, format, line_number)
1500 found[type] = (start, snip)
1504 or found[type][0] < found[first][0])):
1509 # Limiting the search space is a cute
1510 # idea, but this *requires* to search
1511 # for possible containing blocks
1512 # first, at least as long as we do not
1513 # search for the start of blocks, but
1514 # always/directly for the entire
1515 # @block ... @end block.
1517 endex = found[first][0]
1520 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1523 while (start > line_starts[line_start_idx+1]):
1526 (start, snip) = found[first]
1527 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1528 snippets.append (snip)
1530 index = start + len (snip.match.group ('match'))
1534 def filter_pipe (input, cmd):
1535 """Pass input through cmd, and return the result."""
1537 if global_options.verbose:
1538 progress (_ ("Opening filter `%s'") % cmd)
1540 (stdin, stdout, stderr) = os.popen3 (cmd)
1542 status = stdin.close ()
1546 output = stdout.read ()
1547 status = stdout.close ()
1548 error = stderr.read ()
1552 signal = 0x0f & status
1553 if status or (not output and error):
1554 exit_status = status >> 8
1555 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1556 error (_ ("The error log is as follows:"))
1557 ly.stderr_write (error)
1558 ly.stderr_write (stderr.read ())
1561 if global_options.verbose:
1566 def system_in_directory (cmd, directory):
1567 """Execute a command in a different directory.
1569 Because of win32 compatibility, we can't simply use subprocess.
1572 current = os.getcwd()
1573 os.chdir (directory)
1574 ly.system(cmd, be_verbose=global_options.verbose,
1579 def process_snippets (cmd, snippets,
1580 format, lily_output_dir):
1581 """Run cmd on all of the .ly files from snippets."""
1586 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1587 cmd += ' --formats=png '
1588 elif format in (DOCBOOK) and '--formats' not in cmd:
1589 cmd += ' --formats=png,pdf '
1591 checksum = snippet_list_checksum (snippets)
1592 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1593 + [snip.basename() + '.ly' for snip in snippets])
1594 name = os.path.join (lily_output_dir,
1595 'snippet-names-%d.ly' % checksum)
1596 file (name, 'wb').write (contents)
1598 system_in_directory (' '.join ([cmd, name]),
1603 # Retrieve dimensions from LaTeX
1604 LATEX_INSPECTION_DOCUMENT = r'''
1608 \typeout{textwidth=\the\textwidth}
1609 \typeout{columnsep=\the\columnsep}
1610 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1614 # Do we need anything else besides `textwidth'?
1615 def get_latex_textwidth (source):
1616 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1618 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1620 ## what's a sensible default?
1623 preamble = source[:m.start (0)]
1624 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1626 (handle, tmpfile) = tempfile.mkstemp('.tex')
1627 logfile = os.path.splitext (tmpfile)[0] + '.log'
1628 logfile = os.path.split (logfile)[1]
1630 tmp_handle = os.fdopen (handle,'w')
1631 tmp_handle.write (latex_document)
1634 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1635 be_verbose=global_options.verbose)
1636 parameter_string = file (logfile).read()
1642 m = re.search ('columns=([0-9.]*)', parameter_string)
1644 columns = int (m.group (1))
1647 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1649 columnsep = float (m.group (1))
1652 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1654 textwidth = float (m.group (1))
1656 textwidth = (textwidth - columnsep) / columns
1660 def modify_preamble (chunk):
1661 str = chunk.replacement_text ()
1662 if (re.search (r"\\begin *{document}", str)
1663 and not re.search ("{graphic[sx]", str)):
1664 str = re.sub (r"\\begin{document}",
1665 r"\\usepackage{graphics}" + '\n'
1666 + r"\\begin{document}",
1668 chunk.override_text = str
1673 # TEXINFO: '.texinfo',
1679 class CompileError(Exception):
1682 def snippet_list_checksum (snippets):
1683 return hash (' '.join([l.basename() for l in snippets]))
1685 def write_file_map (lys, name):
1686 snippet_map = file (os.path.join (
1687 global_options.lily_output_dir,
1688 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1690 snippet_map.write ("""
1691 #(define version-seen #t)
1692 #(define output-empty-score-list #f)
1693 #(ly:add-file-name-alist '(%s
1695 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1698 def split_output_files(directory):
1699 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1701 Return value is a set of strings.
1704 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1705 base_subdir = os.path.split (subdir)[1]
1706 sub_files = [os.path.join (base_subdir, name)
1707 for name in os.listdir (subdir)]
1711 def do_process_cmd (chunks, input_name, options):
1712 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1714 output_files = split_output_files (options.lily_output_dir)
1715 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1717 write_file_map (outdated, input_name)
1718 progress (_ ("Writing snippets..."))
1719 for snippet in outdated:
1724 progress (_ ("Processing..."))
1726 process_snippets (options.process_cmd, outdated,
1727 options.format, options.lily_output_dir)
1730 progress (_ ("All snippets are up to date..."))
1732 if options.lily_output_dir != options.output_dir:
1733 output_files = split_output_files (options.lily_output_dir)
1734 for snippet in snippets:
1735 snippet.link_all_output_files (options.lily_output_dir,
1743 # Format guessing data
1752 '.texinfo': TEXINFO,
1757 def guess_format (input_filename):
1759 e = os.path.splitext (input_filename)[1]
1762 format = ext2format[e]
1764 error (_ ("cannot determine format for: %s"
1769 def write_if_updated (file_name, lines):
1771 f = file (file_name)
1773 new_str = ''.join (lines)
1774 if oldstr == new_str:
1775 progress (_ ("%s is up to date.") % file_name)
1778 # this prevents make from always rerunning lilypond-book:
1779 # output file must be touched in order to be up to date
1780 os.utime (file_name, None)
1785 output_dir = os.path.dirname (file_name)
1786 if not os.path.exists (output_dir):
1787 os.makedirs (output_dir)
1789 progress (_ ("Writing `%s'...") % file_name)
1790 file (file_name, 'w').writelines (lines)
1794 def note_input_file (name, inputs=[]):
1795 ## hack: inputs is mutable!
1796 inputs.append (name)
1799 def samefile (f1, f2):
1801 return os.path.samefile (f1, f2)
1802 except AttributeError: # Windoze
1803 f1 = re.sub ("//*", "/", f1)
1804 f2 = re.sub ("//*", "/", f2)
1807 def do_file (input_filename, included=False):
1809 if not input_filename or input_filename == '-':
1810 in_handle = sys.stdin
1811 input_fullname = '<stdin>'
1813 if os.path.exists (input_filename):
1814 input_fullname = input_filename
1815 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1816 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1818 input_fullname = find_file (input_filename)
1820 note_input_file (input_fullname)
1821 in_handle = file (input_fullname)
1823 if input_filename == '-':
1824 input_base = 'stdin'
1826 input_base = os.path.splitext (input_filename)[0]
1828 input_base = os.path.basename (
1829 os.path.splitext (input_filename)[0])
1831 # don't complain when global_options.output_dir is existing
1832 if not global_options.output_dir:
1833 global_options.output_dir = os.getcwd()
1835 global_options.output_dir = os.path.abspath(global_options.output_dir)
1837 if not os.path.isdir (global_options.output_dir):
1838 os.mkdir (global_options.output_dir, 0777)
1839 os.chdir (global_options.output_dir)
1841 output_filename = os.path.join(global_options.output_dir,
1842 input_base + format2ext[global_options.format])
1843 if (os.path.exists (input_filename)
1844 and os.path.exists (output_filename)
1845 and samefile (output_filename, input_fullname)):
1847 _ ("Output would overwrite input file; use --output."))
1851 progress (_ ("Reading %s...") % input_fullname)
1852 source = in_handle.read ()
1855 set_default_options (source, default_ly_options, global_options.format)
1858 # FIXME: Containing blocks must be first, see
1859 # find_toplevel_snippets.
1861 'multiline_comment',
1865 'singleline_comment',
1870 progress (_ ("Dissecting..."))
1871 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1873 if global_options.format == LATEX:
1875 if (c.is_plain () and
1876 re.search (r"\\begin *{document}", c.replacement_text())):
1881 if global_options.filter_cmd:
1882 write_if_updated (output_filename,
1883 [c.filter_text () for c in chunks])
1884 elif global_options.process_cmd:
1885 do_process_cmd (chunks, input_fullname, global_options)
1886 progress (_ ("Compiling %s...") % output_filename)
1888 write_if_updated (output_filename,
1889 [s.replacement_text ()
1892 def process_include (snippet):
1893 os.chdir (original_dir)
1894 name = snippet.substring ('filename')
1895 progress (_ ("Processing include: %s") % name)
1897 return do_file (name, included=True)
1899 include_chunks = map (process_include,
1900 filter (lambda x: isinstance (x, IncludeSnippet),
1903 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1905 except CompileError:
1906 os.chdir (original_dir)
1907 progress (_ ("Removing `%s'") % output_filename)
1912 global global_options
1914 opt_parser = get_option_parser()
1915 (global_options, args) = opt_parser.parse_args ()
1916 if global_options.format in ('texi-html', 'texi'):
1917 global_options.format = TEXINFO
1919 global_options.include_path = map (os.path.abspath, global_options.include_path)
1921 if global_options.warranty:
1924 if not args or len (args) > 1:
1925 opt_parser.print_help ()
1931 # FIXME: 85 lines of `main' macramee??
1932 files = do_options ()
1934 basename = os.path.splitext (files[0])[0]
1935 basename = os.path.split (basename)[1]
1937 if not global_options.format:
1938 global_options.format = guess_format (files[0])
1941 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1944 if global_options.process_cmd == '':
1945 global_options.process_cmd = (lilypond_binary
1946 + ' --formats=%s -dbackend=eps ' % formats)
1948 if global_options.process_cmd:
1949 includes = global_options.include_path
1950 if global_options.lily_output_dir:
1951 # This must be first, so lilypond prefers to read .ly
1952 # files in the other lybookdb dir.
1953 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1954 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1957 if global_options.format in (TEXINFO, LATEX):
1958 ## prevent PDF from being switched on by default.
1959 global_options.process_cmd += ' --formats=eps '
1960 if global_options.create_pdf:
1961 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1963 if global_options.verbose:
1964 global_options.process_cmd += " --verbose "
1966 if global_options.padding_mm:
1967 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1969 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1971 if global_options.lily_output_dir:
1972 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1973 if not os.path.isdir (global_options.lily_output_dir):
1974 os.makedirs (global_options.lily_output_dir)
1976 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1981 chunks = do_file (files[0])
1982 except CompileError:
1985 inputs = note_input_file ('')
1988 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1989 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1990 final_output_file = os.path.join (global_options.output_dir,
1992 + '.%s' % global_options.format)
1994 os.chdir (original_dir)
1995 file (dep_file, 'w').write ('%s: %s'
1996 % (final_output_file, ' '.join (inputs)))
1998 if __name__ == '__main__':