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
48 ly.require_python_version ()
51 program_version = '@TOPLEVEL_VERSION@'
52 program_name = os.path.basename (sys.argv[0])
54 # Check if program_version contains @ characters. This will be the case if
55 # the .py file is called directly while building the lilypond documentation.
56 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
57 # makefiles and use its value.
58 at_re = re.compile (r'@')
59 if at_re.match (program_version):
60 if os.environ.has_key('LILYPOND_VERSION'):
61 program_version = os.environ['LILYPOND_VERSION']
63 program_version = "unknown"
65 original_dir = os.getcwd ()
69 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
73 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
74 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
75 $ lilypond-book --process='lilypond -I include' %(BOOK)s
76 ''' % {'BOOK': _ ("BOOK")})
78 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
79 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
81 ################################################################
83 if global_options.verbose:
84 raise Exception (_ ('Exiting (%d)...') % i)
89 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
91 progress = ly.progress
94 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
97 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
99 def ps_page_count (ps_name):
100 header = file (ps_name).read (1024)
101 m = re.search ('\n%%Pages: ([0-9]+)', header)
103 return int (m.group (1))
108 ly.encoded_write (sys.stdout, '''
115 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
116 '\n '.join (authors),
117 _ ("Distributed under terms of the GNU General Public License."),
118 _ ("It comes with NO WARRANTY.")))
120 def get_option_parser ():
121 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
122 description=help_summary,
123 add_help_option=False)
125 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
128 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
131 p.add_option ('-f', '--format',
132 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
133 metavar=_ ("FORMAT"),
136 p.add_option("-h", "--help",
138 help=_ ("show this help and exit"))
140 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
142 action='append', dest='include_path',
143 default=[os.path.abspath (os.getcwd ())])
145 p.add_option ('--info-images-dir',
146 help=_ ("format Texinfo output so that Info will "
147 "look for images of music in DIR"),
149 action='store', dest='info_images_dir',
152 p.add_option ('--latex-program',
153 help=_ ("run executable PROG instead of latex"),
155 action='store', dest='latex_program',
158 p.add_option ('--left-padding',
161 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
165 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
167 action='store', dest='output_dir',
170 p.add_option ('--skip-lily-check',
171 help=_ ("do not fail if no lilypond output is found"),
173 action='store_true', dest='skip_lilypond_run',
176 p.add_option ('--skip-png-check',
177 help=_ ("do not fail if no PNG images are found for EPS files"),
179 action='store_true', dest='skip_png_check',
182 p.add_option ('--lily-output-dir',
183 help=_ ("write lily-XXX files to DIR, link into --output dir"),
185 action='store', dest='lily_output_dir',
188 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
189 help = _ ("process ly_files using COMMAND FILE..."),
191 dest='process_cmd', default='')
193 p.add_option ('--pdf',
196 help=_ ("create PDF files for use with PDFTeX"),
199 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
204 p.version = "@TOPLEVEL_VERSION@"
205 p.add_option("--version",
207 help=_ ("show version number and exit"))
209 p.add_option ('-w', '--warranty',
210 help=_ ("show warranty and copyright"),
212 p.add_option_group ('',
214 _ ("Report bugs via %s")
215 % ' http://post.gmane.org/post.php'
216 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
219 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
221 # If we are called with full path, try to use lilypond binary
222 # installed in the same path; this is needed in GUB binaries, where
223 # @bindir is always different from the installed binary path.
224 if 'bindir' in globals () and bindir:
225 lilypond_binary = os.path.join (bindir, 'lilypond')
227 # Only use installed binary when we are installed too.
228 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
229 lilypond_binary = 'lilypond'
231 global_options = None
234 default_ly_options = { 'alt': "[image of music]" }
236 document_language = ''
239 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
241 ADDVERSION = 'addversion'
245 EXAMPLEINDENT = 'exampleindent'
247 FRAGMENT = 'fragment'
253 LINE_WIDTH = 'line-width'
254 LILYQUOTE = 'lilyquote'
255 NOFRAGMENT = 'nofragment'
256 NOGETTEXT = 'nogettext'
257 NOINDENT = 'noindent'
259 NORAGGED_RIGHT = 'noragged-right'
263 OUTPUTIMAGE = 'outputimage'
265 PREAMBLE = 'preamble'
266 PRINTFILENAME = 'printfilename'
268 RAGGED_RIGHT = 'ragged-right'
269 RELATIVE = 'relative'
270 STAFFSIZE = 'staffsize'
271 DOCTITLE = 'doctitle'
274 VERBATIM = 'verbatim'
275 VERSION = 'lilypondversion'
276 FONTLOAD = 'fontload'
277 FILENAME = 'filename'
281 # NOTIME has no opposite so it isn't part of this dictionary.
282 # NOQUOTE is used internally only.
284 NOFRAGMENT: FRAGMENT,
289 # Recognize special sequences in the input.
291 # (?P<name>regex) -- Assign result of REGEX to NAME.
292 # *? -- Match non-greedily.
293 # (?!...) -- Match if `...' doesn't match next (without consuming
296 # (?m) -- Multiline regex: Make ^ and $ match at each line.
297 # (?s) -- Make the dot match all characters including newline.
298 # (?x) -- Ignore whitespace in patterns.
309 <(?P<inline>(inline)?)mediaobject>\s*
311 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
313 </programlisting\s*>\s*
315 </(inline)?mediaobject>)''',
320 <(?P<inline>(inline)?)mediaobject>\s*
322 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
324 </programlisting\s*>\s*
326 </(inline)?mediaobject>)''',
331 <(?P<inline>(inline)?)mediaobject>\s*
334 fileref="(?P<filename>.*?\.ly)"\s*
335 (role="(?P<options>.*?)")?\s*
336 (/>|>\s*</imagedata>)\s*
338 </(inline)?mediaobject>)''',
344 (?P<code><!--\s.*?!-->)
347 'singleline_comment':
368 (\s*(?P<options>.*?)\s*:)?\s*
376 \s*(?P<options>.*?)\s*
385 \s*(?P<options>.*?)\s*
387 \s*(?P<filename>.*?)\s*
394 (?P<code><!--\s.*?!-->)
397 'singleline_comment':
403 (?P<code><pre>.*?</pre>))''',
409 (?P<code><pre>\s.*?</pre>\s))''',
414 <lilypondversion\s*/>)''',
433 \s*(?P<options>.*?)\s*
444 \s*(?P<options>.*?)\s*
448 \\end\s*{lilypond})''',
456 \s*(?P<options>.*?)\s*
464 'singleline_comment':
487 \\end\s*{verbatim}))''',
492 \\lilypondversion)[^a-zA-Z]''',
502 (?P<filename>\S+))''',
506 ^[^\n]*?(?!@c\s+)[^\n]*?
510 \s*(?P<options>.*?)\s*
520 \s*(?P<options>.*?)\s*
523 ^@end\s+lilypond)\s''',
530 \s*(?P<options>.*?)\s*
541 @end\s+ignore))\s''',
543 'singleline_comment':
548 @c([ \t][^\n]*|)\n))''',
550 # Don't do this: It interferes with @code{@{}.
551 # 'verb': r'''(?P<code>@code{.*?})''',
559 @end\s+example\s))''',
564 @lilypondversion)[^a-zA-Z]''',
572 'intertext': r',?\s*intertext=\".*?\"',
576 'intertext': r',?\s*intertext=\".*?\"',
581 'intertext': r',?\s*intertext=\".*?\"',
582 'option_sep': '\s*,\s*',
586 'intertext': r',?\s*intertext=\".*?\"',
587 'option_sep': '\s*,\s*',
592 # Options without a pattern in ly_options.
613 RELATIVE: r'''\relative c%(relative_quotes)s''',
618 INDENT: r'''indent = %(indent)s''',
620 LINE_WIDTH: r'''line-width = %(line-width)s''',
622 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
624 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
626 RAGGED_RIGHT: r'''ragged-right = ##t''',
628 NORAGGED_RIGHT: r'''ragged-right = ##f''',
640 \remove "Time_signature_engraver"
646 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
653 FILTER: r'''<mediaobject>
655 <programlisting language="lilypond"
662 OUTPUT: r'''<imageobject role="latex">
663 <imagedata fileref="%(base)s.pdf" format="PDF"/>
665 <imageobject role="html">
666 <imagedata fileref="%(base)s.png" format="PNG"/>
669 VERBATIM: r'''<programlisting>
670 %(verb)s</programlisting>''',
672 VERSION: program_version,
674 PRINTFILENAME: r'''<textobject>
676 <ulink url="%(base)s.ly">
686 FILTER: r'''<lilypond %(options)s>
696 <a href="%(base)s.ly">''',
704 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
706 QUOTE: r'''<blockquote>
714 VERSION: program_version,
721 \ifx\preLilyPondExample \undefined
723 \expandafter\preLilyPondExample
725 \def\lilypondbook{}%%
726 \input %(base)s-systems.tex
727 \ifx\postLilyPondExample \undefined
729 \expandafter\postLilyPondExample
733 PRINTFILENAME: '''\\texttt{%(filename)s}
736 QUOTE: r'''\begin{quotation}
740 VERBATIM: r'''\noindent
741 \begin{verbatim}%(verb)s\end{verbatim}
744 VERSION: program_version,
746 FILTER: r'''\begin{lilypond}[%(options)s]
753 FILTER: r'''@lilypond[%(options)s]
759 @include %(base)s-systems.texi
763 OUTPUTIMAGE: r'''@noindent
765 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
769 <a href="%(base)s.ly">
781 <a href="%(base)s.ly">
789 QUOTE: r'''@quotation
790 %(str)s@end quotation
797 VERBATIM: r'''@exampleindent 0
799 %(verb)s@end verbatim
802 VERSION: program_version,
804 ADDVERSION: r'''@example
805 \version @w{"@version{}"}
812 # Maintain line numbers.
817 for f in [HTML, LATEX]:
818 for s in (QUOTE, VERBATIM):
819 output[f][s] = output[f][s].replace("\n"," ")
822 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
823 %%%% Options: [%(option_string)s]
824 \\include "lilypond-book-preamble.ly"
827 %% ****************************************************************
828 %% Start cut-&-pastable-section
829 %% ****************************************************************
834 #(define dump-extents #t)
835 %(font_dump_setting)s
837 force-assignment = #""
838 line-width = #(- line-width (* mm %(padding_mm)f))
851 %% ****************************************************************
852 %% ly snippet contents follows:
853 %% ****************************************************************
857 %% ****************************************************************
859 %% ****************************************************************
866 %% ****************************************************************
868 %% ****************************************************************
872 %% ****************************************************************
874 %% ****************************************************************
877 texinfo_line_widths = {
878 '@afourpaper': '160\\mm',
879 '@afourwide': '6.5\\in',
880 '@afourlatex': '150\\mm',
881 '@smallbook': '5\\in',
882 '@letterpaper': '6\\in',
885 def classic_lilypond_book_compatibility (key, value):
886 if key == 'singleline' and value == None:
887 return (RAGGED_RIGHT, None)
889 m = re.search ('relative\s*([-0-9])', key)
891 return ('relative', m.group (1))
893 m = re.match ('([0-9]+)pt', key)
895 return ('staffsize', m.group (1))
897 if key == 'indent' or key == 'line-width':
898 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
900 f = float (m.group (1))
901 return (key, '%f\\%s' % (f, m.group (2)))
905 def find_file (name, raise_error=True):
906 for i in global_options.include_path:
907 full = os.path.join (i, name)
908 if os.path.exists (full):
912 error (_ ("file not found: %s") % name + '\n')
916 def verbatim_html (s):
917 return re.sub ('>', '>',
919 re.sub ('&', '&', s)))
921 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
922 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
923 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
924 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
926 def ly_comment_gettext (t, m):
927 return m.group (1) + t (m.group (2))
929 def verb_ly_gettext (s):
930 if not document_language:
933 t = langdefs.translation[document_language]
937 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
939 for v in ly_var_def_re.findall (s):
940 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
941 "\\1" + t (v) + "\\2",
943 for id in ly_context_id_re.findall (s):
944 s = re.sub (r'(\s+|")%s(\s+|")' % id,
945 "\\1" + t (id) + "\\2",
949 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
950 def set_default_options (source, default_ly_options, format):
951 global document_language
952 if LINE_WIDTH not in default_ly_options:
954 textwidth = get_latex_textwidth (source)
955 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
956 elif format == TEXINFO:
957 m = texinfo_lang_re.search (source)
958 if m and not m.group (1).startswith ('en'):
959 document_language = m.group (1)
961 document_language = ''
962 for regex in texinfo_line_widths:
963 # FIXME: @layout is usually not in
966 # \input texinfo @c -*-texinfo-*-
968 # Bluntly search first K items of
970 # s = chunks[0].replacement_text ()
971 if re.search (regex, source[:1024]):
972 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
976 def replacement_text (self):
979 def filter_text (self):
980 return self.replacement_text ()
985 class Substring (Chunk):
986 """A string that does not require extra memory."""
987 def __init__ (self, source, start, end, line_number):
991 self.line_number = line_number
992 self.override_text = None
997 def replacement_text (self):
998 if self.override_text:
999 return self.override_text
1001 return self.source[self.start:self.end]
1003 class Snippet (Chunk):
1004 def __init__ (self, type, match, format, line_number):
1008 self.option_dict = {}
1009 self.format = format
1010 self.line_number = line_number
1012 def replacement_text (self):
1013 return self.match.group ('match')
1015 def substring (self, s):
1016 return self.match.group (s)
1018 def __repr__ (self):
1019 return `self.__class__` + ' type = ' + self.type
1021 class IncludeSnippet (Snippet):
1022 def processed_filename (self):
1023 f = self.substring ('filename')
1024 return os.path.splitext (f)[0] + format2ext[self.format]
1026 def replacement_text (self):
1027 s = self.match.group ('match')
1028 f = self.substring ('filename')
1030 return re.sub (f, self.processed_filename (), s)
1032 class LilypondSnippet (Snippet):
1033 def __init__ (self, type, match, format, line_number):
1034 Snippet.__init__ (self, type, match, format, line_number)
1035 os = match.group ('options')
1036 self.do_options (os, self.type)
1039 if NOGETTEXT in self.option_dict:
1040 return self.substring ('code')
1042 return verb_ly_gettext (self.substring ('code'))
1045 contents = self.substring ('code')
1046 return ('\\sourcefileline %d\n%s'
1047 % (self.line_number - 1, contents))
1052 return self.compose_ly (s)
1055 def split_options (self, option_string):
1057 if self.format == HTML:
1058 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1060 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1064 return re.split (format_res[self.format]['option_sep'],
1068 def do_options (self, option_string, type):
1069 self.option_dict = {}
1071 options = self.split_options (option_string)
1073 for option in options:
1075 (key, value) = re.split ('\s*=\s*', option)
1076 self.option_dict[key] = value
1078 if option in no_options:
1079 if no_options[option] in self.option_dict:
1080 del self.option_dict[no_options[option]]
1082 self.option_dict[option] = None
1084 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1085 no_line_width_value = 0
1087 # If LINE_WIDTH is used without parameter, set it to default.
1088 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1089 no_line_width_value = 1
1090 del self.option_dict[LINE_WIDTH]
1092 for k in default_ly_options:
1093 if k not in self.option_dict:
1094 self.option_dict[k] = default_ly_options[k]
1096 # RELATIVE does not work without FRAGMENT;
1097 # make RELATIVE imply FRAGMENT
1098 has_relative = self.option_dict.has_key (RELATIVE)
1099 if has_relative and not self.option_dict.has_key (FRAGMENT):
1100 self.option_dict[FRAGMENT] = None
1102 if not has_line_width:
1103 if type == 'lilypond' or FRAGMENT in self.option_dict:
1104 self.option_dict[RAGGED_RIGHT] = None
1106 if type == 'lilypond':
1107 if LINE_WIDTH in self.option_dict:
1108 del self.option_dict[LINE_WIDTH]
1110 if RAGGED_RIGHT in self.option_dict:
1111 if LINE_WIDTH in self.option_dict:
1112 del self.option_dict[LINE_WIDTH]
1114 if QUOTE in self.option_dict or type == 'lilypond':
1115 if LINE_WIDTH in self.option_dict:
1116 del self.option_dict[LINE_WIDTH]
1118 if not INDENT in self.option_dict:
1119 self.option_dict[INDENT] = '0\\mm'
1121 # The QUOTE pattern from ly_options only emits the `line-width'
1123 if has_line_width and QUOTE in self.option_dict:
1124 if no_line_width_value:
1125 del self.option_dict[LINE_WIDTH]
1127 del self.option_dict[QUOTE]
1129 def compose_ly (self, code):
1130 if FRAGMENT in self.option_dict:
1138 # The original concept of the `exampleindent' option is broken.
1139 # It is not possible to get a sane value for @exampleindent at all
1140 # without processing the document itself. Saying
1148 # causes ugly results with the DVI backend of texinfo since the
1149 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1150 # value). Executing the above code changes the environment
1151 # indentation to an unknown value because we don't know the amount
1152 # of 1em in advance since it is font-dependent. Modifying
1153 # @exampleindent in the middle of a document is simply not
1154 # supported within texinfo.
1156 # As a consequence, the only function of @exampleindent is now to
1157 # specify the amount of indentation for the `quote' option.
1159 # To set @exampleindent locally to zero, we use the @format
1160 # environment for non-quoted snippets.
1161 override[EXAMPLEINDENT] = r'0.4\in'
1162 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1163 override.update (default_ly_options)
1166 for (key, value) in self.option_dict.items ():
1168 option_list.append (key)
1170 option_list.append (key + '=' + value)
1171 option_string = ','.join (option_list)
1174 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1175 for a in compose_types:
1176 compose_dict[a] = []
1178 for (key, value) in self.option_dict.items ():
1179 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1183 _ ("deprecated ly-option used: %s=%s") % (key, value))
1185 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1188 _ ("deprecated ly-option used: %s") % key)
1190 _ ("compatibility mode translation: %s") % c_key)
1192 (key, value) = (c_key, c_value)
1195 override[key] = value
1197 if not override.has_key (key):
1198 override[key] = None
1201 for type in compose_types:
1202 if ly_options[type].has_key (key):
1203 compose_dict[type].append (ly_options[type][key])
1207 if not found and key not in simple_options:
1208 warning (_ ("ignoring unknown ly option: %s") % key)
1211 if RELATIVE in override and override[RELATIVE]:
1212 relative = int (override[RELATIVE])
1214 relative_quotes = ''
1218 relative_quotes += ',' * (- relative)
1220 relative_quotes += "'" * relative
1222 paper_string = '\n '.join (compose_dict[PAPER]) % override
1223 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1224 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1225 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1226 padding_mm = global_options.padding_mm
1227 font_dump_setting = ''
1228 if FONTLOAD in self.option_dict:
1229 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1231 d = globals().copy()
1233 return (PREAMBLE_LY + body) % d
1235 def get_checksum (self):
1236 if not self.checksum:
1237 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1239 ## let's not create too long names.
1240 self.checksum = hash.hexdigest ()[:10]
1242 return self.checksum
1244 def basename (self):
1245 cs = self.get_checksum ()
1246 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1249 def write_ly (self):
1250 base = self.basename ()
1251 path = os.path.join (global_options.lily_output_dir, base)
1252 directory = os.path.split(path)[0]
1253 if not os.path.isdir (directory):
1254 os.makedirs (directory)
1255 out = file (path + '.ly', 'w')
1256 out.write (self.full_ly ())
1257 file (path + '.txt', 'w').write ('image of music')
1259 def relevant_contents (self, ly):
1260 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n|' +
1261 NOGETTEXT + '[,\]]', '', ly)
1263 def link_all_output_files (self, output_dir, output_dir_files, destination):
1264 existing, missing = self.all_output_files (output_dir, output_dir_files)
1266 print '\nMissing', missing
1267 raise CompileError(self.basename())
1268 for name in existing:
1270 os.unlink (os.path.join (destination, name))
1274 src = os.path.join (output_dir, name)
1275 dst = os.path.join (destination, name)
1276 dst_path = os.path.split(dst)[0]
1277 if not os.path.isdir (dst_path):
1278 os.makedirs (dst_path)
1282 def all_output_files (self, output_dir, output_dir_files):
1283 """Return all files generated in lily_output_dir, a set.
1285 output_dir_files is the list of files in the output directory.
1289 base = self.basename()
1290 full = os.path.join (output_dir, base)
1291 def consider_file (name):
1292 if name in output_dir_files:
1295 def require_file (name):
1296 if name in output_dir_files:
1301 # UGH - junk global_options
1302 skip_lily = global_options.skip_lilypond_run
1303 for required in [base + '.ly',
1305 require_file (required)
1307 require_file (base + '-systems.count')
1309 if 'ddump-profile' in global_options.process_cmd:
1310 require_file (base + '.profile')
1311 if 'dseparate-log-file' in global_options.process_cmd:
1312 require_file (base + '.log')
1314 map (consider_file, [base + '.tex',
1318 base + '-systems.texi',
1319 base + '-systems.tex',
1320 base + '-systems.pdftexi'])
1321 if document_language:
1323 [base + '.texidoc' + document_language,
1324 base + '.doctitle' + document_language])
1326 # UGH - junk global_options
1327 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1328 and not global_options.skip_png_check):
1329 page_count = ps_page_count (full + '.eps')
1331 require_file (base + '.png')
1333 for page in range (1, page_count + 1):
1334 require_file (base + '-page%d.png' % page)
1337 if not skip_lily and not missing:
1338 system_count = int(file (full + '-systems.count').read())
1340 for number in range(1, system_count + 1):
1341 systemfile = '%s-%d' % (base, number)
1342 require_file (systemfile + '.eps')
1343 consider_file (systemfile + '.pdf')
1345 # We can't require signatures, since books and toplevel
1346 # markups do not output a signature.
1347 if 'ddump-signature' in global_options.process_cmd:
1348 consider_file (systemfile + '.signature')
1351 return (result, missing)
1353 def is_outdated (self, output_dir, current_files):
1354 found, missing = self.all_output_files (output_dir, current_files)
1357 def filter_text (self):
1358 """Run snippet bodies through a command (say: convert-ly).
1360 This functionality is rarely used, and this code must have bitrot.
1362 code = self.substring ('code')
1363 s = filter_pipe (code, global_options.filter_cmd)
1366 'options': self.match.group ('options')
1369 return output[self.format][FILTER] % d
1371 def replacement_text (self):
1372 func = LilypondSnippet.__dict__['output_' + self.format]
1375 def get_images (self):
1376 base = self.basename ()
1378 single = '%(base)s.png' % vars ()
1379 multiple = '%(base)s-page1.png' % vars ()
1381 if (os.path.exists (multiple)
1382 and (not os.path.exists (single)
1383 or (os.stat (multiple)[stat.ST_MTIME]
1384 > os.stat (single)[stat.ST_MTIME]))):
1385 count = ps_page_count ('%(base)s.eps' % vars ())
1386 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1387 images = tuple (images)
1391 def output_docbook (self):
1393 base = self.basename ()
1394 for image in self.get_images ():
1395 (base, ext) = os.path.splitext (image)
1396 str += output[DOCBOOK][OUTPUT] % vars ()
1397 str += self.output_print_filename (DOCBOOK)
1398 if (self.substring('inline') == 'inline'):
1399 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1401 str = '<mediaobject>' + str + '</mediaobject>'
1402 if VERBATIM in self.option_dict:
1403 verb = verbatim_html (self.verb_ly ())
1404 str = output[DOCBOOK][VERBATIM] % vars () + str
1407 def output_html (self):
1409 base = self.basename ()
1410 if self.format == HTML:
1411 str += self.output_print_filename (HTML)
1412 if VERBATIM in self.option_dict:
1413 verb = verbatim_html (self.verb_ly ())
1414 str += output[HTML][VERBATIM] % vars ()
1415 if QUOTE in self.option_dict:
1416 str = output[HTML][QUOTE] % vars ()
1418 str += output[HTML][BEFORE] % vars ()
1419 for image in self.get_images ():
1420 (base, ext) = os.path.splitext (image)
1421 alt = self.option_dict[ALT]
1422 str += output[HTML][OUTPUT] % vars ()
1423 str += output[HTML][AFTER] % vars ()
1426 def output_info (self):
1428 for image in self.get_images ():
1429 (base, ext) = os.path.splitext (image)
1431 # URG, makeinfo implicitly prepends dot to extension.
1432 # Specifying no extension is most robust.
1434 alt = self.option_dict[ALT]
1435 info_image_path = os.path.join (global_options.info_images_dir, base)
1436 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1438 base = self.basename ()
1439 str += output[self.format][OUTPUT] % vars ()
1442 def output_latex (self):
1444 base = self.basename ()
1445 if self.format == LATEX:
1446 str += self.output_print_filename (LATEX)
1447 if VERBATIM in self.option_dict:
1448 verb = self.verb_ly ()
1449 str += (output[LATEX][VERBATIM] % vars ())
1451 str += (output[LATEX][OUTPUT] % vars ())
1453 ## todo: maintain breaks
1455 breaks = self.ly ().count ("\n")
1456 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1458 if QUOTE in self.option_dict:
1459 str = output[LATEX][QUOTE] % vars ()
1462 def output_print_filename (self, format):
1464 if PRINTFILENAME in self.option_dict:
1465 base = self.basename ()
1466 filename = os.path.basename (self.substring ('filename'))
1467 str = output[format][PRINTFILENAME] % vars ()
1471 def output_texinfo (self):
1472 str = self.output_print_filename (TEXINFO)
1473 base = self.basename ()
1474 if DOCTITLE in self.option_dict:
1475 doctitle = base + '.doctitle'
1476 translated_doctitle = doctitle + document_language
1477 if os.path.exists (translated_doctitle):
1478 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1479 elif os.path.exists (doctitle):
1480 str += '@lydoctitle %s\n' % open (doctitle).read ()
1481 if TEXIDOC in self.option_dict:
1482 texidoc = base + '.texidoc'
1483 translated_texidoc = texidoc + document_language
1484 if os.path.exists (translated_texidoc):
1485 str += '@include %(translated_texidoc)s\n\n' % vars ()
1486 elif os.path.exists (texidoc):
1487 str += '@include %(texidoc)s\n\n' % vars ()
1490 if VERBATIM in self.option_dict:
1492 if ADDVERSION in self.option_dict:
1493 version = output[TEXINFO][ADDVERSION]
1494 verb = self.verb_ly ()
1495 substr = output[TEXINFO][VERBATIM] % vars ()
1496 substr += self.output_info ()
1497 if LILYQUOTE in self.option_dict:
1498 substr = output[TEXINFO][QUOTE] % {'str':substr}
1501 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1502 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1503 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1505 if QUOTE in self.option_dict:
1506 str = output[TEXINFO][QUOTE] % vars ()
1508 # need par after image
1513 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1514 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1516 class LilypondFileSnippet (LilypondSnippet):
1517 def __init__ (self, type, match, format, line_number):
1518 LilypondSnippet.__init__ (self, type, match, format, line_number)
1519 self.contents = file (find_file (self.substring ('filename'))).read ()
1523 s = re_begin_verbatim.split (s)[-1]
1524 s = re_end_verbatim.split (s)[0]
1525 return verb_ly_gettext (s)
1528 name = self.substring ('filename')
1529 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1530 % (name, self.contents))
1533 class LilyPondVersionString (Snippet):
1534 """A string that does not require extra memory."""
1535 def __init__ (self, type, match, format, line_number):
1536 Snippet.__init__ (self, type, match, format, line_number)
1538 def replacement_text (self):
1539 return output[self.format][self.type]
1542 snippet_type_to_class = {
1543 'lilypond_file': LilypondFileSnippet,
1544 'lilypond_block': LilypondSnippet,
1545 'lilypond': LilypondSnippet,
1546 'include': IncludeSnippet,
1547 'lilypondversion': LilyPondVersionString,
1550 def find_linestarts (s):
1555 i = s.find ('\n', start)
1563 nls.append (len (s))
1566 def find_toplevel_snippets (input_string, format, types):
1569 res[t] = re.compile (snippet_res[format][t])
1573 found = dict ([(t, None) for t in types])
1575 line_starts = find_linestarts (input_string)
1577 # We want to search for multiple regexes, without searching
1578 # the string multiple times for one regex.
1579 # Hence, we use earlier results to limit the string portion
1581 # Since every part of the string is traversed at most once for
1582 # every type of snippet, this is linear.
1588 if not found[type] or found[type][0] < index:
1591 m = res[type].search (input_string[index:endex])
1596 if type in snippet_type_to_class:
1597 klass = snippet_type_to_class[type]
1599 start = index + m.start ('match')
1600 line_number = line_start_idx
1601 while (line_starts[line_number] < start):
1605 snip = klass (type, m, format, line_number)
1607 found[type] = (start, snip)
1611 or found[type][0] < found[first][0])):
1616 # Limiting the search space is a cute
1617 # idea, but this *requires* to search
1618 # for possible containing blocks
1619 # first, at least as long as we do not
1620 # search for the start of blocks, but
1621 # always/directly for the entire
1622 # @block ... @end block.
1624 endex = found[first][0]
1627 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1630 while (start > line_starts[line_start_idx+1]):
1633 (start, snip) = found[first]
1634 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1635 snippets.append (snip)
1637 index = start + len (snip.match.group ('match'))
1641 def filter_pipe (input, cmd):
1642 """Pass input through cmd, and return the result."""
1644 if global_options.verbose:
1645 progress (_ ("Opening filter `%s'") % cmd)
1647 (stdin, stdout, stderr) = os.popen3 (cmd)
1649 status = stdin.close ()
1653 output = stdout.read ()
1654 status = stdout.close ()
1655 error = stderr.read ()
1659 signal = 0x0f & status
1660 if status or (not output and error):
1661 exit_status = status >> 8
1662 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1663 error (_ ("The error log is as follows:"))
1664 ly.stderr_write (error)
1665 ly.stderr_write (stderr.read ())
1668 if global_options.verbose:
1673 def system_in_directory (cmd, directory):
1674 """Execute a command in a different directory.
1676 Because of win32 compatibility, we can't simply use subprocess.
1679 current = os.getcwd()
1680 os.chdir (directory)
1681 ly.system(cmd, be_verbose=global_options.verbose,
1686 def process_snippets (cmd, snippets,
1687 format, lily_output_dir):
1688 """Run cmd on all of the .ly files from snippets."""
1693 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1694 cmd += ' --formats=png '
1695 elif format in (DOCBOOK) and '--formats' not in cmd:
1696 cmd += ' --formats=png,pdf '
1698 checksum = snippet_list_checksum (snippets)
1699 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1700 + [snip.basename() + '.ly' for snip in snippets])
1701 name = os.path.join (lily_output_dir,
1702 'snippet-names-%d.ly' % checksum)
1703 file (name, 'wb').write (contents)
1705 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1710 # Retrieve dimensions from LaTeX
1711 LATEX_INSPECTION_DOCUMENT = r'''
1715 \typeout{textwidth=\the\textwidth}
1716 \typeout{columnsep=\the\columnsep}
1717 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1721 # Do we need anything else besides `textwidth'?
1722 def get_latex_textwidth (source):
1723 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1725 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1727 ## what's a sensible default?
1730 preamble = source[:m.start (0)]
1731 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1733 (handle, tmpfile) = tempfile.mkstemp('.tex')
1734 logfile = os.path.splitext (tmpfile)[0] + '.log'
1735 logfile = os.path.split (logfile)[1]
1737 tmp_handle = os.fdopen (handle,'w')
1738 tmp_handle.write (latex_document)
1741 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1742 be_verbose=global_options.verbose)
1743 parameter_string = file (logfile).read()
1749 m = re.search ('columns=([0-9.]*)', parameter_string)
1751 columns = int (m.group (1))
1754 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1756 columnsep = float (m.group (1))
1759 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1761 textwidth = float (m.group (1))
1763 textwidth = (textwidth - columnsep) / columns
1767 def modify_preamble (chunk):
1768 str = chunk.replacement_text ()
1769 if (re.search (r"\\begin *{document}", str)
1770 and not re.search ("{graphic[sx]", str)):
1771 str = re.sub (r"\\begin{document}",
1772 r"\\usepackage{graphics}" + '\n'
1773 + r"\\begin{document}",
1775 chunk.override_text = str
1780 # TEXINFO: '.texinfo',
1786 class CompileError(Exception):
1789 def snippet_list_checksum (snippets):
1790 return hash (' '.join([l.basename() for l in snippets]))
1792 def write_file_map (lys, name):
1793 snippet_map = file (os.path.join (
1794 global_options.lily_output_dir,
1795 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1797 snippet_map.write ("""
1798 #(define version-seen #t)
1799 #(define output-empty-score-list #f)
1800 #(ly:add-file-name-alist '(%s
1802 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1805 def split_output_files(directory):
1806 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1808 Return value is a set of strings.
1811 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1812 base_subdir = os.path.split (subdir)[1]
1813 sub_files = [os.path.join (base_subdir, name)
1814 for name in os.listdir (subdir)]
1818 def do_process_cmd (chunks, input_name, options):
1819 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1821 output_files = split_output_files (options.lily_output_dir)
1822 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1824 write_file_map (outdated, input_name)
1825 progress (_ ("Writing snippets..."))
1826 for snippet in outdated:
1831 progress (_ ("Processing..."))
1833 process_snippets (options.process_cmd, outdated,
1834 options.format, options.lily_output_dir)
1837 progress (_ ("All snippets are up to date..."))
1839 if options.lily_output_dir != options.output_dir:
1840 output_files = split_output_files (options.lily_output_dir)
1841 for snippet in snippets:
1842 snippet.link_all_output_files (options.lily_output_dir,
1850 # Format guessing data
1859 '.texinfo': TEXINFO,
1864 def guess_format (input_filename):
1866 e = os.path.splitext (input_filename)[1]
1869 format = ext2format[e]
1871 error (_ ("cannot determine format for: %s"
1876 def write_if_updated (file_name, lines):
1878 f = file (file_name)
1880 new_str = ''.join (lines)
1881 if oldstr == new_str:
1882 progress (_ ("%s is up to date.") % file_name)
1885 # this prevents make from always rerunning lilypond-book:
1886 # output file must be touched in order to be up to date
1887 os.utime (file_name, None)
1892 output_dir = os.path.dirname (file_name)
1893 if not os.path.exists (output_dir):
1894 os.makedirs (output_dir)
1896 progress (_ ("Writing `%s'...") % file_name)
1897 file (file_name, 'w').writelines (lines)
1901 def note_input_file (name, inputs=[]):
1902 ## hack: inputs is mutable!
1903 inputs.append (name)
1906 def samefile (f1, f2):
1908 return os.path.samefile (f1, f2)
1909 except AttributeError: # Windoze
1910 f1 = re.sub ("//*", "/", f1)
1911 f2 = re.sub ("//*", "/", f2)
1914 def do_file (input_filename, included=False):
1916 if not input_filename or input_filename == '-':
1917 in_handle = sys.stdin
1918 input_fullname = '<stdin>'
1920 if os.path.exists (input_filename):
1921 input_fullname = input_filename
1922 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1923 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1925 input_fullname = find_file (input_filename)
1927 note_input_file (input_fullname)
1928 in_handle = file (input_fullname)
1930 if input_filename == '-':
1931 input_base = 'stdin'
1933 input_base = os.path.splitext (input_filename)[0]
1935 input_base = os.path.basename (
1936 os.path.splitext (input_filename)[0])
1938 # don't complain when global_options.output_dir is existing
1939 if not global_options.output_dir:
1940 global_options.output_dir = os.getcwd()
1942 global_options.output_dir = os.path.abspath(global_options.output_dir)
1944 if not os.path.isdir (global_options.output_dir):
1945 os.mkdir (global_options.output_dir, 0777)
1946 os.chdir (global_options.output_dir)
1948 output_filename = os.path.join(global_options.output_dir,
1949 input_base + format2ext[global_options.format])
1950 if (os.path.exists (input_filename)
1951 and os.path.exists (output_filename)
1952 and samefile (output_filename, input_fullname)):
1954 _ ("Output would overwrite input file; use --output."))
1958 progress (_ ("Reading %s...") % input_fullname)
1959 source = in_handle.read ()
1962 set_default_options (source, default_ly_options, global_options.format)
1965 # FIXME: Containing blocks must be first, see
1966 # find_toplevel_snippets.
1968 'multiline_comment',
1972 'singleline_comment',
1978 progress (_ ("Dissecting..."))
1979 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1981 if global_options.format == LATEX:
1983 if (c.is_plain () and
1984 re.search (r"\\begin *{document}", c.replacement_text())):
1989 if global_options.filter_cmd:
1990 write_if_updated (output_filename,
1991 [c.filter_text () for c in chunks])
1992 elif global_options.process_cmd:
1993 do_process_cmd (chunks, input_fullname, global_options)
1994 progress (_ ("Compiling %s...") % output_filename)
1996 write_if_updated (output_filename,
1997 [s.replacement_text ()
2000 def process_include (snippet):
2001 os.chdir (original_dir)
2002 name = snippet.substring ('filename')
2003 progress (_ ("Processing include: %s") % name)
2005 return do_file (name, included=True)
2007 include_chunks = map (process_include,
2008 filter (lambda x: isinstance (x, IncludeSnippet),
2011 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2013 except CompileError:
2014 os.chdir (original_dir)
2015 progress (_ ("Removing `%s'") % output_filename)
2020 global global_options
2022 opt_parser = get_option_parser()
2023 (global_options, args) = opt_parser.parse_args ()
2024 if global_options.format in ('texi-html', 'texi'):
2025 global_options.format = TEXINFO
2027 global_options.include_path = map (os.path.abspath, global_options.include_path)
2029 if global_options.warranty:
2032 if not args or len (args) > 1:
2033 opt_parser.print_help ()
2039 # FIXME: 85 lines of `main' macramee??
2040 files = do_options ()
2042 basename = os.path.splitext (files[0])[0]
2043 basename = os.path.split (basename)[1]
2045 if not global_options.format:
2046 global_options.format = guess_format (files[0])
2049 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2052 if global_options.process_cmd == '':
2053 global_options.process_cmd = (lilypond_binary
2054 + ' --formats=%s -dbackend=eps ' % formats)
2056 if global_options.process_cmd:
2057 includes = global_options.include_path
2058 if global_options.lily_output_dir:
2059 # This must be first, so lilypond prefers to read .ly
2060 # files in the other lybookdb dir.
2061 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2062 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2065 if global_options.format in (TEXINFO, LATEX):
2066 ## prevent PDF from being switched on by default.
2067 global_options.process_cmd += ' --formats=eps '
2068 if global_options.create_pdf:
2069 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2071 if global_options.verbose:
2072 global_options.process_cmd += " --verbose "
2074 if global_options.padding_mm:
2075 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2077 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2079 if global_options.lily_output_dir:
2080 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2081 if not os.path.isdir (global_options.lily_output_dir):
2082 os.makedirs (global_options.lily_output_dir)
2084 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2089 chunks = do_file (files[0])
2090 except CompileError:
2093 inputs = note_input_file ('')
2096 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2097 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2098 final_output_file = os.path.join (global_options.output_dir,
2100 + '.%s' % global_options.format)
2102 os.chdir (original_dir)
2103 file (dep_file, 'w').write ('%s: %s'
2104 % (final_output_file, ' '.join (inputs)))
2106 if __name__ == '__main__':