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 # If we are called with full path, try to use lilypond binary
209 # installed in the same path; this is needed in GUB binaries, where
210 # @bindir is always different from the installed binary path.
211 if 'bindir' in globals () and bindir:
212 lilypond_binary = os.path.join (bindir, 'lilypond')
214 # Only use installed binary when we are installed too.
215 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
216 lilypond_binary = 'lilypond'
218 global_options = None
221 default_ly_options = { 'alt': "[image of music]" }
223 document_language = ''
226 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
228 ADDVERSION = 'addversion'
232 EXAMPLEINDENT = 'exampleindent'
234 FRAGMENT = 'fragment'
240 LINE_WIDTH = 'line-width'
241 LILYQUOTE = 'lilyquote'
242 NOFRAGMENT = 'nofragment'
243 NOINDENT = 'noindent'
245 NORAGGED_RIGHT = 'noragged-right'
249 OUTPUTIMAGE = 'outputimage'
252 PREAMBLE = 'preamble'
253 PRINTFILENAME = 'printfilename'
255 RAGGED_RIGHT = 'ragged-right'
256 RELATIVE = 'relative'
257 STAFFSIZE = 'staffsize'
258 DOCTITLE = 'doctitle'
261 VERBATIM = 'verbatim'
262 FONTLOAD = 'fontload'
263 FILENAME = 'filename'
267 # NOTIME has no opposite so it isn't part of this dictionary.
268 # NOQUOTE is used internally only.
270 NOFRAGMENT: FRAGMENT,
275 # Recognize special sequences in the input.
277 # (?P<name>regex) -- Assign result of REGEX to NAME.
278 # *? -- Match non-greedily.
279 # (?m) -- Multiline regex: Make ^ and $ match at each line.
280 # (?s) -- Make the dot match all characters including newline.
281 # (?x) -- Ignore whitespace in patterns.
292 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
297 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
302 <(?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>)''',
308 (?P<code><!--\s.*?!-->)
311 'singleline_comment':
330 (\s*(?P<options>.*?)\s*:)?\s*
338 \s*(?P<options>.*?)\s*
347 \s*(?P<options>.*?)\s*
349 \s*(?P<filename>.*?)\s*
356 (?P<code><!--\s.*?!-->)
359 'singleline_comment':
365 (?P<code><pre>.*?</pre>))''',
371 (?P<code><pre>\s.*?</pre>\s))''',
390 \s*(?P<options>.*?)\s*
401 \s*(?P<options>.*?)\s*
405 \\end\s*{lilypond})''',
413 \s*(?P<options>.*?)\s*
421 'singleline_comment':
444 \\end\s*{verbatim}))''',
453 (?P<filename>\S+))''',
457 ^[^\n]*?(?!@c\s+)[^\n]*?
461 \s*(?P<options>.*?)\s*
471 \s*(?P<options>.*?)\s*
474 ^@end\s+lilypond)\s''',
481 \s*(?P<options>.*?)\s*
492 @end\s+ignore))\s''',
494 'singleline_comment':
499 @c([ \t][^\n]*|)\n))''',
501 # Don't do this: It interferes with @code{@{}.
502 # 'verb': r'''(?P<code>@code{.*?})''',
510 @end\s+example\s))''',
519 'intertext': r',?\s*intertext=\".*?\"',
523 'intertext': r',?\s*intertext=\".*?\"',
528 'intertext': r',?\s*intertext=\".*?\"',
529 'option_sep': '\s*,\s*',
533 'intertext': r',?\s*intertext=\".*?\"',
534 'option_sep': '\s*,\s*',
538 # Options without a pattern in ly_options.
558 RELATIVE: r'''\relative c%(relative_quotes)s''',
563 INDENT: r'''indent = %(indent)s''',
565 LINE_WIDTH: r'''line-width = %(line-width)s''',
567 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
569 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
571 RAGGED_RIGHT: r'''ragged-right = ##t''',
573 NORAGGED_RIGHT: r'''ragged-right = ##f''',
575 PACKED: r'''packed = ##t''',
587 \remove "Time_signature_engraver"
593 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
600 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
603 <imageobject role="latex">
604 <imagedata fileref="%(base)s.pdf" format="PDF"/>
606 <imageobject role="html">
607 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
609 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
611 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
615 FILTER: r'''<lilypond %(options)s>
625 <a href="%(base)s.ly">''',
629 border="0" src="%(image)s" alt="%(alt)s">''',
631 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
633 QUOTE: r'''<blockquote>
646 \ifx\preLilyPondExample \undefined%%
649 \preLilyPondExample%%
651 \def\lilypondbook{}%%
652 \input %(base)s-systems.tex%%
653 \ifx\postLilyPondExample \undefined%%
656 \postLilyPondExample%%
660 PRINTFILENAME: '''\\texttt{%(filename)s}
663 QUOTE: r'''\begin{quotation}%(str)s
666 VERBATIM: r'''\noindent
667 \begin{verbatim}%(verb)s\end{verbatim}''',
669 FILTER: r'''\begin{lilypond}[%(options)s]
676 FILTER: r'''@lilypond[%(options)s]
682 @include %(base)s-systems.texi
686 OUTPUTIMAGE: r'''@noindent
688 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
692 <a href="%(base)s.ly">
694 border="0" src="%(image)s" alt="%(alt)s">
702 <a href="%(base)s.ly">
710 QUOTE: r'''@quotation
711 %(str)s@end quotation
718 VERBATIM: r'''@exampleindent 0
720 %(verb)s@end verbatim
723 ADDVERSION: r'''@example
724 \version @w{"@version{}"}
731 # Maintain line numbers.
736 for f in [HTML, LATEX]:
737 for s in (QUOTE, VERBATIM):
738 output[f][s] = output[f][s].replace("\n"," ")
741 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
742 %%%% Options: [%(option_string)s]
743 \\include "lilypond-book-preamble.ly"
746 %% ****************************************************************
747 %% Start cut-&-pastable-section
748 %% ****************************************************************
753 #(define dump-extents #t)
754 %(font_dump_setting)s
756 force-assignment = #""
757 line-width = #(- line-width (* mm %(padding_mm)f))
770 %% ****************************************************************
771 %% ly snippet contents follows:
772 %% ****************************************************************
776 %% ****************************************************************
778 %% ****************************************************************
785 %% ****************************************************************
787 %% ****************************************************************
791 %% ****************************************************************
793 %% ****************************************************************
796 texinfo_line_widths = {
797 '@afourpaper': '160\\mm',
798 '@afourwide': '6.5\\in',
799 '@afourlatex': '150\\mm',
800 '@smallbook': '5\\in',
801 '@letterpaper': '6\\in',
804 def classic_lilypond_book_compatibility (key, value):
805 if key == 'singleline' and value == None:
806 return (RAGGED_RIGHT, None)
808 m = re.search ('relative\s*([-0-9])', key)
810 return ('relative', m.group (1))
812 m = re.match ('([0-9]+)pt', key)
814 return ('staffsize', m.group (1))
816 if key == 'indent' or key == 'line-width':
817 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
819 f = float (m.group (1))
820 return (key, '%f\\%s' % (f, m.group (2)))
824 def find_file (name, raise_error=True):
825 for i in global_options.include_path:
826 full = os.path.join (i, name)
827 if os.path.exists (full):
831 error (_ ("file not found: %s") % name + '\n')
835 def verbatim_html (s):
836 return re.sub ('>', '>',
838 re.sub ('&', '&', s)))
840 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
841 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
843 def ly_comment_gettext (t, m):
844 return m.group (1) + t (m.group (2))
846 def verb_ly_gettext (s):
847 if not document_language:
850 t = langdefs.translation[document_language]
854 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
856 for v in ly_var_def_re.findall (s):
857 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
858 "\\1" + t (v) + "\\2",
862 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
863 def set_default_options (source, default_ly_options, format):
864 global document_language
865 if LINE_WIDTH not in default_ly_options:
867 textwidth = get_latex_textwidth (source)
868 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
869 elif format == TEXINFO:
870 m = texinfo_lang_re.search (source)
871 if m and not m.group (1).startswith ('en'):
872 document_language = m.group (1)
874 document_language = ''
875 for regex in texinfo_line_widths:
876 # FIXME: @layout is usually not in
879 # \input texinfo @c -*-texinfo-*-
881 # Bluntly search first K items of
883 # s = chunks[0].replacement_text ()
884 if re.search (regex, source[:1024]):
885 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
889 def replacement_text (self):
892 def filter_text (self):
893 return self.replacement_text ()
898 class Substring (Chunk):
899 """A string that does not require extra memory."""
900 def __init__ (self, source, start, end, line_number):
904 self.line_number = line_number
905 self.override_text = None
910 def replacement_text (self):
911 if self.override_text:
912 return self.override_text
914 return self.source[self.start:self.end]
916 class Snippet (Chunk):
917 def __init__ (self, type, match, format, line_number):
921 self.option_dict = {}
923 self.line_number = line_number
925 def replacement_text (self):
926 return self.match.group ('match')
928 def substring (self, s):
929 return self.match.group (s)
932 return `self.__class__` + ' type = ' + self.type
934 class IncludeSnippet (Snippet):
935 def processed_filename (self):
936 f = self.substring ('filename')
937 return os.path.splitext (f)[0] + format2ext[self.format]
939 def replacement_text (self):
940 s = self.match.group ('match')
941 f = self.substring ('filename')
943 return re.sub (f, self.processed_filename (), s)
945 class LilypondSnippet (Snippet):
946 def __init__ (self, type, match, format, line_number):
947 Snippet.__init__ (self, type, match, format, line_number)
948 os = match.group ('options')
949 self.do_options (os, self.type)
952 return verb_ly_gettext (self.substring ('code'))
955 contents = self.substring ('code')
956 return ('\\sourcefileline %d\n%s'
957 % (self.line_number - 1, contents))
962 return self.compose_ly (s)
965 def split_options (self, option_string):
967 if self.format == HTML:
968 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
970 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
974 return re.split (format_res[self.format]['option_sep'],
978 def do_options (self, option_string, type):
979 self.option_dict = {}
981 options = self.split_options (option_string)
983 for option in options:
985 (key, value) = re.split ('\s*=\s*', option)
986 self.option_dict[key] = value
988 if option in no_options:
989 if no_options[option] in self.option_dict:
990 del self.option_dict[no_options[option]]
992 self.option_dict[option] = None
994 has_line_width = self.option_dict.has_key (LINE_WIDTH)
995 no_line_width_value = 0
997 # If LINE_WIDTH is used without parameter, set it to default.
998 if has_line_width and self.option_dict[LINE_WIDTH] == None:
999 no_line_width_value = 1
1000 del self.option_dict[LINE_WIDTH]
1002 for k in default_ly_options:
1003 if k not in self.option_dict:
1004 self.option_dict[k] = default_ly_options[k]
1006 # RELATIVE does not work without FRAGMENT;
1007 # make RELATIVE imply FRAGMENT
1008 has_relative = self.option_dict.has_key (RELATIVE)
1009 if has_relative and not self.option_dict.has_key (FRAGMENT):
1010 self.option_dict[FRAGMENT] = None
1012 if not has_line_width:
1013 if type == 'lilypond' or FRAGMENT in self.option_dict:
1014 self.option_dict[RAGGED_RIGHT] = None
1016 if type == 'lilypond':
1017 if LINE_WIDTH in self.option_dict:
1018 del self.option_dict[LINE_WIDTH]
1020 if RAGGED_RIGHT in self.option_dict:
1021 if LINE_WIDTH in self.option_dict:
1022 del self.option_dict[LINE_WIDTH]
1024 if QUOTE in self.option_dict or type == 'lilypond':
1025 if LINE_WIDTH in self.option_dict:
1026 del self.option_dict[LINE_WIDTH]
1028 if not INDENT in self.option_dict:
1029 self.option_dict[INDENT] = '0\\mm'
1031 # The QUOTE pattern from ly_options only emits the `line-width'
1033 if has_line_width and QUOTE in self.option_dict:
1034 if no_line_width_value:
1035 del self.option_dict[LINE_WIDTH]
1037 del self.option_dict[QUOTE]
1039 def compose_ly (self, code):
1040 if FRAGMENT in self.option_dict:
1048 # The original concept of the `exampleindent' option is broken.
1049 # It is not possible to get a sane value for @exampleindent at all
1050 # without processing the document itself. Saying
1058 # causes ugly results with the DVI backend of texinfo since the
1059 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1060 # value). Executing the above code changes the environment
1061 # indentation to an unknown value because we don't know the amount
1062 # of 1em in advance since it is font-dependent. Modifying
1063 # @exampleindent in the middle of a document is simply not
1064 # supported within texinfo.
1066 # As a consequence, the only function of @exampleindent is now to
1067 # specify the amount of indentation for the `quote' option.
1069 # To set @exampleindent locally to zero, we use the @format
1070 # environment for non-quoted snippets.
1071 override[EXAMPLEINDENT] = r'0.4\in'
1072 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1073 override.update (default_ly_options)
1076 for (key, value) in self.option_dict.items ():
1078 option_list.append (key)
1080 option_list.append (key + '=' + value)
1081 option_string = ','.join (option_list)
1084 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1085 for a in compose_types:
1086 compose_dict[a] = []
1088 for (key, value) in self.option_dict.items ():
1089 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1093 _ ("deprecated ly-option used: %s=%s") % (key, value))
1095 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1098 _ ("deprecated ly-option used: %s") % key)
1100 _ ("compatibility mode translation: %s") % c_key)
1102 (key, value) = (c_key, c_value)
1105 override[key] = value
1107 if not override.has_key (key):
1108 override[key] = None
1111 for type in compose_types:
1112 if ly_options[type].has_key (key):
1113 compose_dict[type].append (ly_options[type][key])
1117 if not found and key not in simple_options:
1118 warning (_ ("ignoring unknown ly option: %s") % key)
1121 if RELATIVE in override and override[RELATIVE]:
1122 relative = int (override[RELATIVE])
1124 relative_quotes = ''
1128 relative_quotes += ',' * (- relative)
1130 relative_quotes += "'" * relative
1132 paper_string = '\n '.join (compose_dict[PAPER]) % override
1133 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1134 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1135 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1136 padding_mm = global_options.padding_mm
1137 font_dump_setting = ''
1138 if FONTLOAD in self.option_dict:
1139 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1141 d = globals().copy()
1143 return (PREAMBLE_LY + body) % d
1145 def get_checksum (self):
1146 if not self.checksum:
1147 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1149 ## let's not create too long names.
1150 self.checksum = hash.hexdigest ()[:10]
1152 return self.checksum
1154 def basename (self):
1155 cs = self.get_checksum ()
1156 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1159 def write_ly (self):
1160 base = self.basename ()
1161 path = os.path.join (global_options.lily_output_dir, base)
1162 directory = os.path.split(path)[0]
1163 if not os.path.isdir (directory):
1164 os.makedirs (directory)
1165 out = file (path + '.ly', 'w')
1166 out.write (self.full_ly ())
1167 file (path + '.txt', 'w').write ('image of music')
1169 def relevant_contents (self, ly):
1170 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1172 def link_all_output_files (self, output_dir, output_dir_files, destination):
1173 existing, missing = self.all_output_files (output_dir, output_dir_files)
1175 print '\nMissing', missing
1176 raise CompileError(self.basename())
1177 for name in existing:
1179 os.unlink (os.path.join (destination, name))
1183 src = os.path.join (output_dir, name)
1184 dst = os.path.join (destination, name)
1185 dst_path = os.path.split(dst)[0]
1186 if not os.path.isdir (dst_path):
1187 os.makedirs (dst_path)
1191 def all_output_files (self, output_dir, output_dir_files):
1192 """Return all files generated in lily_output_dir, a set.
1194 output_dir_files is the list of files in the output directory.
1198 base = self.basename()
1199 full = os.path.join (output_dir, base)
1200 def consider_file (name):
1201 if name in output_dir_files:
1204 def require_file (name):
1205 if name in output_dir_files:
1210 # UGH - junk global_options
1211 skip_lily = global_options.skip_lilypond_run
1212 for required in [base + '.ly',
1214 require_file (required)
1216 require_file (base + '-systems.count')
1218 if 'ddump-profile' in global_options.process_cmd:
1219 require_file (base + '.profile')
1220 if 'dseparate-log-file' in global_options.process_cmd:
1221 require_file (base + '.log')
1223 map (consider_file, [base + '.tex',
1227 base + '-systems.texi',
1228 base + '-systems.tex',
1229 base + '-systems.pdftexi'])
1230 if document_language:
1232 [base + '.texidoc' + document_language,
1233 base + '.doctitle' + document_language])
1235 # UGH - junk global_options
1236 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1237 and not global_options.skip_png_check):
1238 page_count = ps_page_count (full + '.eps')
1240 require_file (base + '.png')
1242 for page in range (1, page_count + 1):
1243 require_file (base + '-page%d.png' % page)
1246 if not skip_lily and not missing:
1247 system_count = int(file (full + '-systems.count').read())
1249 for number in range(1, system_count + 1):
1250 systemfile = '%s-%d' % (base, number)
1251 require_file (systemfile + '.eps')
1252 consider_file (systemfile + '.pdf')
1254 # We can't require signatures, since books and toplevel
1255 # markups do not output a signature.
1256 if 'ddump-signature' in global_options.process_cmd:
1257 consider_file (systemfile + '.signature')
1260 return (result, missing)
1262 def is_outdated (self, output_dir, current_files):
1263 found, missing = self.all_output_files (output_dir, current_files)
1266 def filter_text (self):
1267 """Run snippet bodies through a command (say: convert-ly).
1269 This functionality is rarely used, and this code must have bitrot.
1271 code = self.substring ('code')
1272 s = filter_pipe (code, global_options.filter_cmd)
1275 'options': self.match.group ('options')
1278 return output[self.format][FILTER] % d
1280 def replacement_text (self):
1281 func = LilypondSnippet.__dict__['output_' + self.format]
1284 def get_images (self):
1285 base = self.basename ()
1287 single = '%(base)s.png' % vars ()
1288 multiple = '%(base)s-page1.png' % vars ()
1290 if (os.path.exists (multiple)
1291 and (not os.path.exists (single)
1292 or (os.stat (multiple)[stat.ST_MTIME]
1293 > os.stat (single)[stat.ST_MTIME]))):
1294 count = ps_page_count ('%(base)s.eps' % vars ())
1295 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1296 images = tuple (images)
1300 def output_docbook (self):
1302 base = self.basename ()
1303 for image in self.get_images ():
1304 (base, ext) = os.path.splitext (image)
1305 str += output[DOCBOOK][OUTPUT] % vars ()
1306 str += self.output_print_filename (DOCBOOK)
1307 if (self.substring('inline') == 'inline'):
1308 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1310 str = '<mediaobject>' + str + '</mediaobject>'
1311 if VERBATIM in self.option_dict:
1312 verb = verbatim_html (self.verb_ly ())
1313 str = output[DOCBOOK][VERBATIM] % vars () + str
1316 def output_html (self):
1318 base = self.basename ()
1319 if self.format == HTML:
1320 str += self.output_print_filename (HTML)
1321 if VERBATIM in self.option_dict:
1322 verb = verbatim_html (self.verb_ly ())
1323 str += output[HTML][VERBATIM] % vars ()
1324 if QUOTE in self.option_dict:
1325 str = output[HTML][QUOTE] % vars ()
1327 str += output[HTML][BEFORE] % vars ()
1328 for image in self.get_images ():
1329 (base, ext) = os.path.splitext (image)
1330 alt = self.option_dict[ALT]
1331 str += output[HTML][OUTPUT] % vars ()
1332 str += output[HTML][AFTER] % vars ()
1335 def output_info (self):
1337 for image in self.get_images ():
1338 (base, ext) = os.path.splitext (image)
1340 # URG, makeinfo implicitly prepends dot to extension.
1341 # Specifying no extension is most robust.
1343 alt = self.option_dict[ALT]
1344 info_image_path = os.path.join (global_options.info_images_dir, base)
1345 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1347 base = self.basename ()
1348 str += output[self.format][OUTPUT] % vars ()
1351 def output_latex (self):
1353 base = self.basename ()
1354 if self.format == LATEX:
1355 str += self.output_print_filename (LATEX)
1356 if VERBATIM in self.option_dict:
1357 verb = self.verb_ly ()
1358 str += (output[LATEX][VERBATIM] % vars ())
1360 str += (output[LATEX][OUTPUT] % vars ())
1362 ## todo: maintain breaks
1364 breaks = self.ly ().count ("\n")
1365 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1367 if QUOTE in self.option_dict:
1368 str = output[LATEX][QUOTE] % vars ()
1371 def output_print_filename (self, format):
1373 if PRINTFILENAME in self.option_dict:
1374 base = self.basename ()
1375 filename = os.path.basename (self.substring ('filename'))
1376 str = output[format][PRINTFILENAME] % vars ()
1380 def output_texinfo (self):
1381 str = self.output_print_filename (TEXINFO)
1382 base = self.basename ()
1383 if DOCTITLE in self.option_dict:
1384 doctitle = base + '.doctitle'
1385 translated_doctitle = doctitle + document_language
1386 if os.path.exists (translated_doctitle):
1387 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1388 elif os.path.exists (doctitle):
1389 str += '@lydoctitle %s\n' % open (doctitle).read ()
1390 if TEXIDOC in self.option_dict:
1391 texidoc = base + '.texidoc'
1392 translated_texidoc = texidoc + document_language
1393 if os.path.exists (translated_texidoc):
1394 str += '@include %(translated_texidoc)s\n\n' % vars ()
1395 elif os.path.exists (texidoc):
1396 str += '@include %(texidoc)s\n\n' % vars ()
1399 if VERBATIM in self.option_dict:
1401 if ADDVERSION in self.option_dict:
1402 version = output[TEXINFO][ADDVERSION]
1403 verb = self.verb_ly ()
1404 substr = output[TEXINFO][VERBATIM] % vars ()
1405 substr += self.output_info ()
1406 if LILYQUOTE in self.option_dict:
1407 substr = output[TEXINFO][QUOTE] % {'str':substr}
1410 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1411 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1412 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1414 if QUOTE in self.option_dict:
1415 str = output[TEXINFO][QUOTE] % vars ()
1417 # need par after image
1422 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1423 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1425 class LilypondFileSnippet (LilypondSnippet):
1426 def __init__ (self, type, match, format, line_number):
1427 LilypondSnippet.__init__ (self, type, match, format, line_number)
1428 self.contents = file (find_file (self.substring ('filename'))).read ()
1432 s = re_begin_verbatim.split (s)[-1]
1433 s = re_end_verbatim.split (s)[0]
1434 return verb_ly_gettext (s)
1437 name = self.substring ('filename')
1438 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1439 % (name, self.contents))
1442 snippet_type_to_class = {
1443 'lilypond_file': LilypondFileSnippet,
1444 'lilypond_block': LilypondSnippet,
1445 'lilypond': LilypondSnippet,
1446 'include': IncludeSnippet,
1449 def find_linestarts (s):
1454 i = s.find ('\n', start)
1462 nls.append (len (s))
1465 def find_toplevel_snippets (input_string, format, types):
1468 res[t] = re.compile (snippet_res[format][t])
1472 found = dict ([(t, None) for t in types])
1474 line_starts = find_linestarts (input_string)
1476 # We want to search for multiple regexes, without searching
1477 # the string multiple times for one regex.
1478 # Hence, we use earlier results to limit the string portion
1480 # Since every part of the string is traversed at most once for
1481 # every type of snippet, this is linear.
1487 if not found[type] or found[type][0] < index:
1490 m = res[type].search (input_string[index:endex])
1495 if type in snippet_type_to_class:
1496 klass = snippet_type_to_class[type]
1498 start = index + m.start ('match')
1499 line_number = line_start_idx
1500 while (line_starts[line_number] < start):
1504 snip = klass (type, m, format, line_number)
1506 found[type] = (start, snip)
1510 or found[type][0] < found[first][0])):
1515 # Limiting the search space is a cute
1516 # idea, but this *requires* to search
1517 # for possible containing blocks
1518 # first, at least as long as we do not
1519 # search for the start of blocks, but
1520 # always/directly for the entire
1521 # @block ... @end block.
1523 endex = found[first][0]
1526 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1529 while (start > line_starts[line_start_idx+1]):
1532 (start, snip) = found[first]
1533 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1534 snippets.append (snip)
1536 index = start + len (snip.match.group ('match'))
1540 def filter_pipe (input, cmd):
1541 """Pass input through cmd, and return the result."""
1543 if global_options.verbose:
1544 progress (_ ("Opening filter `%s'") % cmd)
1546 (stdin, stdout, stderr) = os.popen3 (cmd)
1548 status = stdin.close ()
1552 output = stdout.read ()
1553 status = stdout.close ()
1554 error = stderr.read ()
1558 signal = 0x0f & status
1559 if status or (not output and error):
1560 exit_status = status >> 8
1561 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1562 error (_ ("The error log is as follows:"))
1563 ly.stderr_write (error)
1564 ly.stderr_write (stderr.read ())
1567 if global_options.verbose:
1572 def system_in_directory (cmd, directory):
1573 """Execute a command in a different directory.
1575 Because of win32 compatibility, we can't simply use subprocess.
1578 current = os.getcwd()
1579 os.chdir (directory)
1580 ly.system(cmd, be_verbose=global_options.verbose,
1585 def process_snippets (cmd, snippets,
1586 format, lily_output_dir):
1587 """Run cmd on all of the .ly files from snippets."""
1592 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1593 cmd += ' --formats=png '
1594 elif format in (DOCBOOK) and '--formats' not in cmd:
1595 cmd += ' --formats=png,pdf '
1597 checksum = snippet_list_checksum (snippets)
1598 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1599 + [snip.basename() + '.ly' for snip in snippets])
1600 name = os.path.join (lily_output_dir,
1601 'snippet-names-%d.ly' % checksum)
1602 file (name, 'wb').write (contents)
1604 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1609 # Retrieve dimensions from LaTeX
1610 LATEX_INSPECTION_DOCUMENT = r'''
1614 \typeout{textwidth=\the\textwidth}
1615 \typeout{columnsep=\the\columnsep}
1616 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1620 # Do we need anything else besides `textwidth'?
1621 def get_latex_textwidth (source):
1622 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1624 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1626 ## what's a sensible default?
1629 preamble = source[:m.start (0)]
1630 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1632 (handle, tmpfile) = tempfile.mkstemp('.tex')
1633 logfile = os.path.splitext (tmpfile)[0] + '.log'
1634 logfile = os.path.split (logfile)[1]
1636 tmp_handle = os.fdopen (handle,'w')
1637 tmp_handle.write (latex_document)
1640 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1641 be_verbose=global_options.verbose)
1642 parameter_string = file (logfile).read()
1648 m = re.search ('columns=([0-9.]*)', parameter_string)
1650 columns = int (m.group (1))
1653 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1655 columnsep = float (m.group (1))
1658 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1660 textwidth = float (m.group (1))
1662 textwidth = (textwidth - columnsep) / columns
1666 def modify_preamble (chunk):
1667 str = chunk.replacement_text ()
1668 if (re.search (r"\\begin *{document}", str)
1669 and not re.search ("{graphic[sx]", str)):
1670 str = re.sub (r"\\begin{document}",
1671 r"\\usepackage{graphics}" + '\n'
1672 + r"\\begin{document}",
1674 chunk.override_text = str
1679 # TEXINFO: '.texinfo',
1685 class CompileError(Exception):
1688 def snippet_list_checksum (snippets):
1689 return hash (' '.join([l.basename() for l in snippets]))
1691 def write_file_map (lys, name):
1692 snippet_map = file (os.path.join (
1693 global_options.lily_output_dir,
1694 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1696 snippet_map.write ("""
1697 #(define version-seen #t)
1698 #(define output-empty-score-list #f)
1699 #(ly:add-file-name-alist '(%s
1701 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1704 def split_output_files(directory):
1705 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1707 Return value is a set of strings.
1710 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1711 base_subdir = os.path.split (subdir)[1]
1712 sub_files = [os.path.join (base_subdir, name)
1713 for name in os.listdir (subdir)]
1717 def do_process_cmd (chunks, input_name, options):
1718 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1720 output_files = split_output_files (options.lily_output_dir)
1721 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1723 write_file_map (outdated, input_name)
1724 progress (_ ("Writing snippets..."))
1725 for snippet in outdated:
1730 progress (_ ("Processing..."))
1732 process_snippets (options.process_cmd, outdated,
1733 options.format, options.lily_output_dir)
1736 progress (_ ("All snippets are up to date..."))
1738 if options.lily_output_dir != options.output_dir:
1739 output_files = split_output_files (options.lily_output_dir)
1740 for snippet in snippets:
1741 snippet.link_all_output_files (options.lily_output_dir,
1749 # Format guessing data
1758 '.texinfo': TEXINFO,
1763 def guess_format (input_filename):
1765 e = os.path.splitext (input_filename)[1]
1768 format = ext2format[e]
1770 error (_ ("cannot determine format for: %s"
1775 def write_if_updated (file_name, lines):
1777 f = file (file_name)
1779 new_str = ''.join (lines)
1780 if oldstr == new_str:
1781 progress (_ ("%s is up to date.") % file_name)
1784 # this prevents make from always rerunning lilypond-book:
1785 # output file must be touched in order to be up to date
1786 os.utime (file_name, None)
1791 output_dir = os.path.dirname (file_name)
1792 if not os.path.exists (output_dir):
1793 os.makedirs (output_dir)
1795 progress (_ ("Writing `%s'...") % file_name)
1796 file (file_name, 'w').writelines (lines)
1800 def note_input_file (name, inputs=[]):
1801 ## hack: inputs is mutable!
1802 inputs.append (name)
1805 def samefile (f1, f2):
1807 return os.path.samefile (f1, f2)
1808 except AttributeError: # Windoze
1809 f1 = re.sub ("//*", "/", f1)
1810 f2 = re.sub ("//*", "/", f2)
1813 def do_file (input_filename, included=False):
1815 if not input_filename or input_filename == '-':
1816 in_handle = sys.stdin
1817 input_fullname = '<stdin>'
1819 if os.path.exists (input_filename):
1820 input_fullname = input_filename
1821 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1822 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1824 input_fullname = find_file (input_filename)
1826 note_input_file (input_fullname)
1827 in_handle = file (input_fullname)
1829 if input_filename == '-':
1830 input_base = 'stdin'
1832 input_base = os.path.splitext (input_filename)[0]
1834 input_base = os.path.basename (
1835 os.path.splitext (input_filename)[0])
1837 # don't complain when global_options.output_dir is existing
1838 if not global_options.output_dir:
1839 global_options.output_dir = os.getcwd()
1841 global_options.output_dir = os.path.abspath(global_options.output_dir)
1843 if not os.path.isdir (global_options.output_dir):
1844 os.mkdir (global_options.output_dir, 0777)
1845 os.chdir (global_options.output_dir)
1847 output_filename = os.path.join(global_options.output_dir,
1848 input_base + format2ext[global_options.format])
1849 if (os.path.exists (input_filename)
1850 and os.path.exists (output_filename)
1851 and samefile (output_filename, input_fullname)):
1853 _ ("Output would overwrite input file; use --output."))
1857 progress (_ ("Reading %s...") % input_fullname)
1858 source = in_handle.read ()
1861 set_default_options (source, default_ly_options, global_options.format)
1864 # FIXME: Containing blocks must be first, see
1865 # find_toplevel_snippets.
1867 'multiline_comment',
1871 'singleline_comment',
1876 progress (_ ("Dissecting..."))
1877 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1879 if global_options.format == LATEX:
1881 if (c.is_plain () and
1882 re.search (r"\\begin *{document}", c.replacement_text())):
1887 if global_options.filter_cmd:
1888 write_if_updated (output_filename,
1889 [c.filter_text () for c in chunks])
1890 elif global_options.process_cmd:
1891 do_process_cmd (chunks, input_fullname, global_options)
1892 progress (_ ("Compiling %s...") % output_filename)
1894 write_if_updated (output_filename,
1895 [s.replacement_text ()
1898 def process_include (snippet):
1899 os.chdir (original_dir)
1900 name = snippet.substring ('filename')
1901 progress (_ ("Processing include: %s") % name)
1903 return do_file (name, included=True)
1905 include_chunks = map (process_include,
1906 filter (lambda x: isinstance (x, IncludeSnippet),
1909 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1911 except CompileError:
1912 os.chdir (original_dir)
1913 progress (_ ("Removing `%s'") % output_filename)
1918 global global_options
1920 opt_parser = get_option_parser()
1921 (global_options, args) = opt_parser.parse_args ()
1922 if global_options.format in ('texi-html', 'texi'):
1923 global_options.format = TEXINFO
1925 global_options.include_path = map (os.path.abspath, global_options.include_path)
1927 if global_options.warranty:
1930 if not args or len (args) > 1:
1931 opt_parser.print_help ()
1937 # FIXME: 85 lines of `main' macramee??
1938 files = do_options ()
1940 basename = os.path.splitext (files[0])[0]
1941 basename = os.path.split (basename)[1]
1943 if not global_options.format:
1944 global_options.format = guess_format (files[0])
1947 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1950 if global_options.process_cmd == '':
1951 global_options.process_cmd = (lilypond_binary
1952 + ' --formats=%s -dbackend=eps ' % formats)
1954 if global_options.process_cmd:
1955 includes = global_options.include_path
1956 if global_options.lily_output_dir:
1957 # This must be first, so lilypond prefers to read .ly
1958 # files in the other lybookdb dir.
1959 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1960 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1963 if global_options.format in (TEXINFO, LATEX):
1964 ## prevent PDF from being switched on by default.
1965 global_options.process_cmd += ' --formats=eps '
1966 if global_options.create_pdf:
1967 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1969 if global_options.verbose:
1970 global_options.process_cmd += " --verbose "
1972 if global_options.padding_mm:
1973 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1975 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1977 if global_options.lily_output_dir:
1978 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1979 if not os.path.isdir (global_options.lily_output_dir):
1980 os.makedirs (global_options.lily_output_dir)
1982 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1987 chunks = do_file (files[0])
1988 except CompileError:
1991 inputs = note_input_file ('')
1994 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1995 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1996 final_output_file = os.path.join (global_options.output_dir,
1998 + '.%s' % global_options.format)
2000 os.chdir (original_dir)
2001 file (dep_file, 'w').write ('%s: %s'
2002 % (final_output_file, ' '.join (inputs)))
2004 if __name__ == '__main__':