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
47 ly.require_python_version ()
50 program_version = '@TOPLEVEL_VERSION@'
51 program_name = os.path.basename (sys.argv[0])
53 # Check if program_version contains @ characters. This will be the case if
54 # the .py file is called directly while building the lilypond documentation.
55 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
56 # makefiles and use its value.
57 at_re = re.compile (r'@')
58 if at_re.match (program_version):
59 if os.environ.has_key('LILYPOND_VERSION'):
60 program_version = os.environ['LILYPOND_VERSION']
62 program_version = "unknown"
64 original_dir = os.getcwd ()
68 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
72 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
73 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
74 $ lilypond-book --process='lilypond -I include' %(BOOK)s
75 ''' % {'BOOK': _ ("BOOK")})
77 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
78 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
80 ################################################################
82 if global_options.verbose:
83 raise Exception (_ ('Exiting (%d)...') % i)
88 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
90 progress = ly.progress
93 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
96 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
98 def ps_page_count (ps_name):
99 header = file (ps_name).read (1024)
100 m = re.search ('\n%%Pages: ([0-9]+)', header)
102 return int (m.group (1))
107 ly.encoded_write (sys.stdout, '''
114 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
115 '\n '.join (authors),
116 _ ("Distributed under terms of the GNU General Public License."),
117 _ ("It comes with NO WARRANTY.")))
119 def get_option_parser ():
120 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
121 description=help_summary,
122 add_help_option=False)
124 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
127 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
130 p.add_option ('-f', '--format',
131 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
132 metavar=_ ("FORMAT"),
135 p.add_option("-h", "--help",
137 help=_ ("show this help and exit"))
139 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
141 action='append', dest='include_path',
142 default=[os.path.abspath (os.getcwd ())])
144 p.add_option ('--info-images-dir',
145 help=_ ("format Texinfo output so that Info will "
146 "look for images of music in DIR"),
148 action='store', dest='info_images_dir',
151 p.add_option ('--latex-program',
152 help=_ ("run executable PROG instead of latex"),
154 action='store', dest='latex_program',
157 p.add_option ('--left-padding',
160 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
164 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
166 action='store', dest='output_dir',
169 p.add_option ('--skip-lily-check',
170 help=_ ("do not fail if no lilypond output is found"),
172 action='store_true', dest='skip_lilypond_run',
175 p.add_option ('--skip-png-check',
176 help=_ ("do not fail if no PNG images are found for EPS files"),
178 action='store_true', dest='skip_png_check',
181 p.add_option ('--lily-output-dir',
182 help=_ ("write lily-XXX files to DIR, link into --output dir"),
184 action='store', dest='lily_output_dir',
187 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
188 help = _ ("process ly_files using COMMAND FILE..."),
190 dest='process_cmd', default='')
192 p.add_option ('--pdf',
195 help=_ ("create PDF files for use with PDFTeX"),
198 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
203 p.version = "@TOPLEVEL_VERSION@"
204 p.add_option("--version",
206 help=_ ("show version number and exit"))
208 p.add_option ('-w', '--warranty',
209 help=_ ("show warranty and copyright"),
211 p.add_option_group ('',
213 _ ("Report bugs via %s")
214 % ' http://post.gmane.org/post.php'
215 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
218 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
220 # If we are called with full path, try to use lilypond binary
221 # installed in the same path; this is needed in GUB binaries, where
222 # @bindir is always different from the installed binary path.
223 if 'bindir' in globals () and bindir:
224 lilypond_binary = os.path.join (bindir, 'lilypond')
226 # Only use installed binary when we are installed too.
227 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
228 lilypond_binary = 'lilypond'
230 global_options = None
233 default_ly_options = { 'alt': "[image of music]" }
235 document_language = ''
238 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
240 ADDVERSION = 'addversion'
244 EXAMPLEINDENT = 'exampleindent'
246 FRAGMENT = 'fragment'
252 LINE_WIDTH = 'line-width'
253 LILYQUOTE = 'lilyquote'
254 NOFRAGMENT = 'nofragment'
255 NOGETTEXT = 'nogettext'
256 NOINDENT = 'noindent'
258 NORAGGED_RIGHT = 'noragged-right'
262 OUTPUTIMAGE = 'outputimage'
264 PREAMBLE = 'preamble'
265 PRINTFILENAME = 'printfilename'
267 RAGGED_RIGHT = 'ragged-right'
268 RELATIVE = 'relative'
269 STAFFSIZE = 'staffsize'
270 DOCTITLE = 'doctitle'
273 VERBATIM = 'verbatim'
274 VERSION = 'lilypondversion'
275 FONTLOAD = 'fontload'
276 FILENAME = 'filename'
280 # NOTIME has no opposite so it isn't part of this dictionary.
281 # NOQUOTE is used internally only.
283 NOFRAGMENT: FRAGMENT,
288 # Recognize special sequences in the input.
290 # (?P<name>regex) -- Assign result of REGEX to NAME.
291 # *? -- Match non-greedily.
292 # (?!...) -- Match if `...' doesn't match next (without consuming
295 # (?m) -- Multiline regex: Make ^ and $ match at each line.
296 # (?s) -- Make the dot match all characters including newline.
297 # (?x) -- Ignore whitespace in patterns.
308 <(?P<inline>(inline)?)mediaobject>\s*
310 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
312 </programlisting\s*>\s*
314 </(inline)?mediaobject>)''',
319 <(?P<inline>(inline)?)mediaobject>\s*
321 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
323 </programlisting\s*>\s*
325 </(inline)?mediaobject>)''',
330 <(?P<inline>(inline)?)mediaobject>\s*
333 fileref="(?P<filename>.*?\.ly)"\s*
334 (role="(?P<options>.*?)")?\s*
335 (/>|>\s*</imagedata>)\s*
337 </(inline)?mediaobject>)''',
343 (?P<code><!--\s.*?!-->)
346 'singleline_comment':
367 (\s*(?P<options>.*?)\s*:)?\s*
375 \s*(?P<options>.*?)\s*
384 \s*(?P<options>.*?)\s*
386 \s*(?P<filename>.*?)\s*
393 (?P<code><!--\s.*?!-->)
396 'singleline_comment':
402 (?P<code><pre>.*?</pre>))''',
408 (?P<code><pre>\s.*?</pre>\s))''',
413 <lilypondversion\s*/>)''',
432 \s*(?P<options>.*?)\s*
443 \s*(?P<options>.*?)\s*
447 \\end\s*{lilypond})''',
455 \s*(?P<options>.*?)\s*
463 'singleline_comment':
486 \\end\s*{verbatim}))''',
491 \\lilypondversion)[^a-zA-Z]''',
501 (?P<filename>\S+))''',
505 ^[^\n]*?(?!@c\s+)[^\n]*?
509 \s*(?P<options>.*?)\s*
519 \s*(?P<options>.*?)\s*
522 ^@end\s+lilypond)\s''',
529 \s*(?P<options>.*?)\s*
540 @end\s+ignore))\s''',
542 'singleline_comment':
547 @c([ \t][^\n]*|)\n))''',
549 # Don't do this: It interferes with @code{@{}.
550 # 'verb': r'''(?P<code>@code{.*?})''',
558 @end\s+example\s))''',
563 @lilypondversion)[^a-zA-Z]''',
571 'intertext': r',?\s*intertext=\".*?\"',
575 'intertext': r',?\s*intertext=\".*?\"',
580 'intertext': r',?\s*intertext=\".*?\"',
581 'option_sep': '\s*,\s*',
585 'intertext': r',?\s*intertext=\".*?\"',
586 'option_sep': '\s*,\s*',
591 # Options without a pattern in ly_options.
612 RELATIVE: r'''\relative c%(relative_quotes)s''',
617 INDENT: r'''indent = %(indent)s''',
619 LINE_WIDTH: r'''line-width = %(line-width)s''',
621 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
623 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
625 RAGGED_RIGHT: r'''ragged-right = ##t''',
627 NORAGGED_RIGHT: r'''ragged-right = ##f''',
639 \remove "Time_signature_engraver"
645 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
652 FILTER: r'''<mediaobject>
654 <programlisting language="lilypond"
661 OUTPUT: r'''<imageobject role="latex">
662 <imagedata fileref="%(base)s.pdf" format="PDF"/>
664 <imageobject role="html">
665 <imagedata fileref="%(base)s.png" format="PNG"/>
668 VERBATIM: r'''<programlisting>
669 %(verb)s</programlisting>''',
671 VERSION: program_version,
673 PRINTFILENAME: r'''<textobject>
675 <ulink url="%(base)s.ly">
685 FILTER: r'''<lilypond %(options)s>
695 <a href="%(base)s.ly">''',
703 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
705 QUOTE: r'''<blockquote>
713 VERSION: program_version,
720 \ifx\preLilyPondExample \undefined
722 \expandafter\preLilyPondExample
724 \def\lilypondbook{}%%
725 \input %(base)s-systems.tex
726 \ifx\postLilyPondExample \undefined
728 \expandafter\postLilyPondExample
732 PRINTFILENAME: '''\\texttt{%(filename)s}
735 QUOTE: r'''\begin{quotation}
739 VERBATIM: r'''\noindent
740 \begin{verbatim}%(verb)s\end{verbatim}
743 VERSION: program_version,
745 FILTER: r'''\begin{lilypond}[%(options)s]
752 FILTER: r'''@lilypond[%(options)s]
758 @include %(base)s-systems.texi
762 OUTPUTIMAGE: r'''@noindent
764 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
768 <a href="%(base)s.ly">
780 <a href="%(base)s.ly">
788 QUOTE: r'''@quotation
789 %(str)s@end quotation
796 VERBATIM: r'''@exampleindent 0
798 %(verb)s@end verbatim
801 VERSION: program_version,
803 ADDVERSION: r'''@example
804 \version @w{"@version{}"}
811 # Maintain line numbers.
816 for f in [HTML, LATEX]:
817 for s in (QUOTE, VERBATIM):
818 output[f][s] = output[f][s].replace("\n"," ")
821 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
822 %%%% Options: [%(option_string)s]
823 \\include "lilypond-book-preamble.ly"
826 %% ****************************************************************
827 %% Start cut-&-pastable-section
828 %% ****************************************************************
833 #(define dump-extents #t)
834 %(font_dump_setting)s
836 force-assignment = #""
837 line-width = #(- line-width (* mm %(padding_mm)f))
850 %% ****************************************************************
851 %% ly snippet contents follows:
852 %% ****************************************************************
856 %% ****************************************************************
858 %% ****************************************************************
865 %% ****************************************************************
867 %% ****************************************************************
871 %% ****************************************************************
873 %% ****************************************************************
876 texinfo_line_widths = {
877 '@afourpaper': '160\\mm',
878 '@afourwide': '6.5\\in',
879 '@afourlatex': '150\\mm',
880 '@smallbook': '5\\in',
881 '@letterpaper': '6\\in',
884 def classic_lilypond_book_compatibility (key, value):
885 if key == 'singleline' and value == None:
886 return (RAGGED_RIGHT, None)
888 m = re.search ('relative\s*([-0-9])', key)
890 return ('relative', m.group (1))
892 m = re.match ('([0-9]+)pt', key)
894 return ('staffsize', m.group (1))
896 if key == 'indent' or key == 'line-width':
897 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
899 f = float (m.group (1))
900 return (key, '%f\\%s' % (f, m.group (2)))
904 def find_file (name, raise_error=True):
905 for i in global_options.include_path:
906 full = os.path.join (i, name)
907 if os.path.exists (full):
911 error (_ ("file not found: %s") % name + '\n')
915 def verbatim_html (s):
916 return re.sub ('>', '>',
918 re.sub ('&', '&', s)))
920 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
921 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
922 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
923 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
925 def ly_comment_gettext (t, m):
926 return m.group (1) + t (m.group (2))
928 def verb_ly_gettext (s):
929 if not document_language:
932 t = langdefs.translation[document_language]
936 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
938 if langdefs.LANGDICT[document_language].enable_ly_identifier_l10n:
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 verb_text = self.substring ('code')
1040 if not NOGETTEXT in self.option_dict:
1041 verb_text = verb_ly_gettext (verb_text)
1042 if not verb_text.endswith ('\n'):
1047 contents = self.substring ('code')
1048 return ('\\sourcefileline %d\n%s'
1049 % (self.line_number - 1, contents))
1054 return self.compose_ly (s)
1057 def split_options (self, option_string):
1059 if self.format == HTML:
1060 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1062 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1066 return re.split (format_res[self.format]['option_sep'],
1070 def do_options (self, option_string, type):
1071 self.option_dict = {}
1073 options = self.split_options (option_string)
1075 for option in options:
1077 (key, value) = re.split ('\s*=\s*', option)
1078 self.option_dict[key] = value
1080 if option in no_options:
1081 if no_options[option] in self.option_dict:
1082 del self.option_dict[no_options[option]]
1084 self.option_dict[option] = None
1086 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1087 no_line_width_value = 0
1089 # If LINE_WIDTH is used without parameter, set it to default.
1090 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1091 no_line_width_value = 1
1092 del self.option_dict[LINE_WIDTH]
1094 for k in default_ly_options:
1095 if k not in self.option_dict:
1096 self.option_dict[k] = default_ly_options[k]
1098 # RELATIVE does not work without FRAGMENT;
1099 # make RELATIVE imply FRAGMENT
1100 has_relative = self.option_dict.has_key (RELATIVE)
1101 if has_relative and not self.option_dict.has_key (FRAGMENT):
1102 self.option_dict[FRAGMENT] = None
1104 if not has_line_width:
1105 if type == 'lilypond' or FRAGMENT in self.option_dict:
1106 self.option_dict[RAGGED_RIGHT] = None
1108 if type == 'lilypond':
1109 if LINE_WIDTH in self.option_dict:
1110 del self.option_dict[LINE_WIDTH]
1112 if RAGGED_RIGHT in self.option_dict:
1113 if LINE_WIDTH in self.option_dict:
1114 del self.option_dict[LINE_WIDTH]
1116 if QUOTE in self.option_dict or type == 'lilypond':
1117 if LINE_WIDTH in self.option_dict:
1118 del self.option_dict[LINE_WIDTH]
1120 if not INDENT in self.option_dict:
1121 self.option_dict[INDENT] = '0\\mm'
1123 # The QUOTE pattern from ly_options only emits the `line-width'
1125 if has_line_width and QUOTE in self.option_dict:
1126 if no_line_width_value:
1127 del self.option_dict[LINE_WIDTH]
1129 del self.option_dict[QUOTE]
1131 def compose_ly (self, code):
1132 if FRAGMENT in self.option_dict:
1140 # The original concept of the `exampleindent' option is broken.
1141 # It is not possible to get a sane value for @exampleindent at all
1142 # without processing the document itself. Saying
1150 # causes ugly results with the DVI backend of texinfo since the
1151 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1152 # value). Executing the above code changes the environment
1153 # indentation to an unknown value because we don't know the amount
1154 # of 1em in advance since it is font-dependent. Modifying
1155 # @exampleindent in the middle of a document is simply not
1156 # supported within texinfo.
1158 # As a consequence, the only function of @exampleindent is now to
1159 # specify the amount of indentation for the `quote' option.
1161 # To set @exampleindent locally to zero, we use the @format
1162 # environment for non-quoted snippets.
1163 override[EXAMPLEINDENT] = r'0.4\in'
1164 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1165 override.update (default_ly_options)
1168 for (key, value) in self.option_dict.items ():
1170 option_list.append (key)
1172 option_list.append (key + '=' + value)
1173 option_string = ','.join (option_list)
1176 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1177 for a in compose_types:
1178 compose_dict[a] = []
1180 for (key, value) in self.option_dict.items ():
1181 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1185 _ ("deprecated ly-option used: %s=%s") % (key, value))
1187 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1190 _ ("deprecated ly-option used: %s") % key)
1192 _ ("compatibility mode translation: %s") % c_key)
1194 (key, value) = (c_key, c_value)
1197 override[key] = value
1199 if not override.has_key (key):
1200 override[key] = None
1203 for type in compose_types:
1204 if ly_options[type].has_key (key):
1205 compose_dict[type].append (ly_options[type][key])
1209 if not found and key not in simple_options:
1210 warning (_ ("ignoring unknown ly option: %s") % key)
1213 if RELATIVE in override and override[RELATIVE]:
1214 relative = int (override[RELATIVE])
1216 relative_quotes = ''
1220 relative_quotes += ',' * (- relative)
1222 relative_quotes += "'" * relative
1224 paper_string = '\n '.join (compose_dict[PAPER]) % override
1225 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1226 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1227 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1228 padding_mm = global_options.padding_mm
1229 font_dump_setting = ''
1230 if FONTLOAD in self.option_dict:
1231 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1233 d = globals().copy()
1235 return (PREAMBLE_LY + body) % d
1237 def get_checksum (self):
1238 if not self.checksum:
1239 # Work-around for md5 module deprecation warning in python 2.5+:
1241 from hashlib import md5
1245 hash = md5 (self.relevant_contents (self.full_ly ()))
1247 ## let's not create too long names.
1248 self.checksum = hash.hexdigest ()[:10]
1250 return self.checksum
1252 def basename (self):
1253 cs = self.get_checksum ()
1254 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1257 def write_ly (self):
1258 base = self.basename ()
1259 path = os.path.join (global_options.lily_output_dir, base)
1260 directory = os.path.split(path)[0]
1261 if not os.path.isdir (directory):
1262 os.makedirs (directory)
1263 out = file (path + '.ly', 'w')
1264 out.write (self.full_ly ())
1265 file (path + '.txt', 'w').write ('image of music')
1267 def relevant_contents (self, ly):
1268 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n|' +
1269 NOGETTEXT + '[,\]]', '', ly)
1271 def link_all_output_files (self, output_dir, output_dir_files, destination):
1272 existing, missing = self.all_output_files (output_dir, output_dir_files)
1274 print '\nMissing', missing
1275 raise CompileError(self.basename())
1276 for name in existing:
1278 os.unlink (os.path.join (destination, name))
1282 src = os.path.join (output_dir, name)
1283 dst = os.path.join (destination, name)
1284 dst_path = os.path.split(dst)[0]
1285 if not os.path.isdir (dst_path):
1286 os.makedirs (dst_path)
1290 def all_output_files (self, output_dir, output_dir_files):
1291 """Return all files generated in lily_output_dir, a set.
1293 output_dir_files is the list of files in the output directory.
1297 base = self.basename()
1298 full = os.path.join (output_dir, base)
1299 def consider_file (name):
1300 if name in output_dir_files:
1303 def require_file (name):
1304 if name in output_dir_files:
1309 # UGH - junk global_options
1310 skip_lily = global_options.skip_lilypond_run
1311 for required in [base + '.ly',
1313 require_file (required)
1315 require_file (base + '-systems.count')
1317 if 'ddump-profile' in global_options.process_cmd:
1318 require_file (base + '.profile')
1319 if 'dseparate-log-file' in global_options.process_cmd:
1320 require_file (base + '.log')
1322 map (consider_file, [base + '.tex',
1326 base + '-systems.texi',
1327 base + '-systems.tex',
1328 base + '-systems.pdftexi'])
1329 if document_language:
1331 [base + '.texidoc' + document_language,
1332 base + '.doctitle' + document_language])
1334 # UGH - junk global_options
1335 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1336 and not global_options.skip_png_check):
1337 page_count = ps_page_count (full + '.eps')
1339 require_file (base + '.png')
1341 for page in range (1, page_count + 1):
1342 require_file (base + '-page%d.png' % page)
1345 if not skip_lily and not missing:
1346 system_count = int(file (full + '-systems.count').read())
1348 for number in range(1, system_count + 1):
1349 systemfile = '%s-%d' % (base, number)
1350 require_file (systemfile + '.eps')
1351 consider_file (systemfile + '.pdf')
1353 # We can't require signatures, since books and toplevel
1354 # markups do not output a signature.
1355 if 'ddump-signature' in global_options.process_cmd:
1356 consider_file (systemfile + '.signature')
1359 return (result, missing)
1361 def is_outdated (self, output_dir, current_files):
1362 found, missing = self.all_output_files (output_dir, current_files)
1365 def filter_text (self):
1366 """Run snippet bodies through a command (say: convert-ly).
1368 This functionality is rarely used, and this code must have bitrot.
1370 code = self.substring ('code')
1371 s = filter_pipe (code, global_options.filter_cmd)
1374 'options': self.match.group ('options')
1377 return output[self.format][FILTER] % d
1379 def replacement_text (self):
1380 func = LilypondSnippet.__dict__['output_' + self.format]
1383 def get_images (self):
1384 base = self.basename ()
1386 single = '%(base)s.png' % vars ()
1387 multiple = '%(base)s-page1.png' % vars ()
1389 if (os.path.exists (multiple)
1390 and (not os.path.exists (single)
1391 or (os.stat (multiple)[stat.ST_MTIME]
1392 > os.stat (single)[stat.ST_MTIME]))):
1393 count = ps_page_count ('%(base)s.eps' % vars ())
1394 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1395 images = tuple (images)
1399 def output_docbook (self):
1401 base = self.basename ()
1402 for image in self.get_images ():
1403 (base, ext) = os.path.splitext (image)
1404 str += output[DOCBOOK][OUTPUT] % vars ()
1405 str += self.output_print_filename (DOCBOOK)
1406 if (self.substring('inline') == 'inline'):
1407 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1409 str = '<mediaobject>' + str + '</mediaobject>'
1410 if VERBATIM in self.option_dict:
1411 verb = verbatim_html (self.verb_ly ())
1412 str = output[DOCBOOK][VERBATIM] % vars () + str
1415 def output_html (self):
1417 base = self.basename ()
1418 if self.format == HTML:
1419 str += self.output_print_filename (HTML)
1420 if VERBATIM in self.option_dict:
1421 verb = verbatim_html (self.verb_ly ())
1422 str += output[HTML][VERBATIM] % vars ()
1423 if QUOTE in self.option_dict:
1424 str = output[HTML][QUOTE] % vars ()
1426 str += output[HTML][BEFORE] % vars ()
1427 for image in self.get_images ():
1428 (base, ext) = os.path.splitext (image)
1429 alt = self.option_dict[ALT]
1430 str += output[HTML][OUTPUT] % vars ()
1431 str += output[HTML][AFTER] % vars ()
1434 def output_info (self):
1436 for image in self.get_images ():
1437 (base, ext) = os.path.splitext (image)
1439 # URG, makeinfo implicitly prepends dot to extension.
1440 # Specifying no extension is most robust.
1442 alt = self.option_dict[ALT]
1443 info_image_path = os.path.join (global_options.info_images_dir, base)
1444 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1446 base = self.basename ()
1447 str += output[self.format][OUTPUT] % vars ()
1450 def output_latex (self):
1452 base = self.basename ()
1453 if self.format == LATEX:
1454 str += self.output_print_filename (LATEX)
1455 if VERBATIM in self.option_dict:
1456 verb = self.verb_ly ()
1457 str += (output[LATEX][VERBATIM] % vars ())
1459 str += (output[LATEX][OUTPUT] % vars ())
1461 ## todo: maintain breaks
1463 breaks = self.ly ().count ("\n")
1464 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1466 if QUOTE in self.option_dict:
1467 str = output[LATEX][QUOTE] % vars ()
1470 def output_print_filename (self, format):
1472 if PRINTFILENAME in self.option_dict:
1473 base = self.basename ()
1474 filename = os.path.basename (self.substring ('filename'))
1475 str = output[format][PRINTFILENAME] % vars ()
1479 def output_texinfo (self):
1480 str = self.output_print_filename (TEXINFO)
1481 base = self.basename ()
1482 if DOCTITLE in self.option_dict:
1483 doctitle = base + '.doctitle'
1484 translated_doctitle = doctitle + document_language
1485 if os.path.exists (translated_doctitle):
1486 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
1487 elif os.path.exists (doctitle):
1488 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
1489 if TEXIDOC in self.option_dict:
1490 texidoc = base + '.texidoc'
1491 translated_texidoc = texidoc + document_language
1492 if os.path.exists (translated_texidoc):
1493 str += '@include %(translated_texidoc)s\n\n' % vars ()
1494 elif os.path.exists (texidoc):
1495 str += '@include %(texidoc)s\n\n' % vars ()
1498 if VERBATIM in self.option_dict:
1500 if ADDVERSION in self.option_dict:
1501 version = output[TEXINFO][ADDVERSION]
1502 verb = self.verb_ly ()
1503 substr = output[TEXINFO][VERBATIM] % vars ()
1504 substr += self.output_info ()
1505 if LILYQUOTE in self.option_dict:
1506 substr = output[TEXINFO][QUOTE] % {'str':substr}
1509 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1510 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1511 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1513 if QUOTE in self.option_dict:
1514 str = output[TEXINFO][QUOTE] % vars ()
1516 # need par after image
1521 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1522 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1524 class LilypondFileSnippet (LilypondSnippet):
1525 def __init__ (self, type, match, format, line_number):
1526 LilypondSnippet.__init__ (self, type, match, format, line_number)
1527 self.contents = file (find_file (self.substring ('filename'))).read ()
1531 s = re_begin_verbatim.split (s)[-1]
1532 s = re_end_verbatim.split (s)[0]
1533 if not NOGETTEXT in self.option_dict:
1534 s = verb_ly_gettext (s)
1535 if not s.endswith ('\n'):
1540 name = self.substring ('filename')
1541 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1542 % (name, self.contents))
1545 class LilyPondVersionString (Snippet):
1546 """A string that does not require extra memory."""
1547 def __init__ (self, type, match, format, line_number):
1548 Snippet.__init__ (self, type, match, format, line_number)
1550 def replacement_text (self):
1551 return output[self.format][self.type]
1554 snippet_type_to_class = {
1555 'lilypond_file': LilypondFileSnippet,
1556 'lilypond_block': LilypondSnippet,
1557 'lilypond': LilypondSnippet,
1558 'include': IncludeSnippet,
1559 'lilypondversion': LilyPondVersionString,
1562 def find_linestarts (s):
1567 i = s.find ('\n', start)
1575 nls.append (len (s))
1578 def find_toplevel_snippets (input_string, format, types):
1581 res[t] = re.compile (snippet_res[format][t])
1585 found = dict ([(t, None) for t in types])
1587 line_starts = find_linestarts (input_string)
1589 # We want to search for multiple regexes, without searching
1590 # the string multiple times for one regex.
1591 # Hence, we use earlier results to limit the string portion
1593 # Since every part of the string is traversed at most once for
1594 # every type of snippet, this is linear.
1600 if not found[type] or found[type][0] < index:
1603 m = res[type].search (input_string[index:endex])
1608 if type in snippet_type_to_class:
1609 klass = snippet_type_to_class[type]
1611 start = index + m.start ('match')
1612 line_number = line_start_idx
1613 while (line_starts[line_number] < start):
1617 snip = klass (type, m, format, line_number)
1619 found[type] = (start, snip)
1623 or found[type][0] < found[first][0])):
1628 # Limiting the search space is a cute
1629 # idea, but this *requires* to search
1630 # for possible containing blocks
1631 # first, at least as long as we do not
1632 # search for the start of blocks, but
1633 # always/directly for the entire
1634 # @block ... @end block.
1636 endex = found[first][0]
1639 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1642 while (start > line_starts[line_start_idx+1]):
1645 (start, snip) = found[first]
1646 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1647 snippets.append (snip)
1649 index = start + len (snip.match.group ('match'))
1653 def filter_pipe (input, cmd):
1654 """Pass input through cmd, and return the result."""
1656 if global_options.verbose:
1657 progress (_ ("Opening filter `%s'") % cmd)
1659 (stdin, stdout, stderr) = os.popen3 (cmd)
1661 status = stdin.close ()
1665 output = stdout.read ()
1666 status = stdout.close ()
1667 error = stderr.read ()
1671 signal = 0x0f & status
1672 if status or (not output and error):
1673 exit_status = status >> 8
1674 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1675 error (_ ("The error log is as follows:"))
1676 ly.stderr_write (error)
1677 ly.stderr_write (stderr.read ())
1680 if global_options.verbose:
1685 def system_in_directory (cmd, directory):
1686 """Execute a command in a different directory.
1688 Because of win32 compatibility, we can't simply use subprocess.
1691 current = os.getcwd()
1692 os.chdir (directory)
1693 ly.system(cmd, be_verbose=global_options.verbose,
1698 def process_snippets (cmd, snippets,
1699 format, lily_output_dir):
1700 """Run cmd on all of the .ly files from snippets."""
1705 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1706 cmd += ' --formats=png '
1707 elif format in (DOCBOOK) and '--formats' not in cmd:
1708 cmd += ' --formats=png,pdf '
1710 checksum = snippet_list_checksum (snippets)
1711 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1712 + [snip.basename() + '.ly' for snip in snippets])
1713 name = os.path.join (lily_output_dir,
1714 'snippet-names-%d.ly' % checksum)
1715 file (name, 'wb').write (contents)
1717 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1722 # Retrieve dimensions from LaTeX
1723 LATEX_INSPECTION_DOCUMENT = r'''
1727 \typeout{textwidth=\the\textwidth}
1728 \typeout{columnsep=\the\columnsep}
1729 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1733 # Do we need anything else besides `textwidth'?
1734 def get_latex_textwidth (source):
1735 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1737 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1739 ## what's a sensible default?
1742 preamble = source[:m.start (0)]
1743 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1745 (handle, tmpfile) = tempfile.mkstemp('.tex')
1746 logfile = os.path.splitext (tmpfile)[0] + '.log'
1747 logfile = os.path.split (logfile)[1]
1749 tmp_handle = os.fdopen (handle,'w')
1750 tmp_handle.write (latex_document)
1753 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1754 be_verbose=global_options.verbose)
1755 parameter_string = file (logfile).read()
1761 m = re.search ('columns=([0-9.]*)', parameter_string)
1763 columns = int (m.group (1))
1766 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1768 columnsep = float (m.group (1))
1771 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1773 textwidth = float (m.group (1))
1775 textwidth = (textwidth - columnsep) / columns
1779 def modify_preamble (chunk):
1780 str = chunk.replacement_text ()
1781 if (re.search (r"\\begin *{document}", str)
1782 and not re.search ("{graphic[sx]", str)):
1783 str = re.sub (r"\\begin{document}",
1784 r"\\usepackage{graphics}" + '\n'
1785 + r"\\begin{document}",
1787 chunk.override_text = str
1792 # TEXINFO: '.texinfo',
1798 class CompileError(Exception):
1801 def snippet_list_checksum (snippets):
1802 return hash (' '.join([l.basename() for l in snippets]))
1804 def write_file_map (lys, name):
1805 snippet_map = file (os.path.join (
1806 global_options.lily_output_dir,
1807 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1809 snippet_map.write ("""
1810 #(define version-seen #t)
1811 #(define output-empty-score-list #f)
1812 #(ly:add-file-name-alist '(%s
1814 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1817 def split_output_files(directory):
1818 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1820 Return value is a set of strings.
1823 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1824 base_subdir = os.path.split (subdir)[1]
1825 sub_files = [os.path.join (base_subdir, name)
1826 for name in os.listdir (subdir)]
1830 def do_process_cmd (chunks, input_name, options):
1831 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1833 output_files = split_output_files (options.lily_output_dir)
1834 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1836 write_file_map (outdated, input_name)
1837 progress (_ ("Writing snippets..."))
1838 for snippet in outdated:
1843 progress (_ ("Processing..."))
1845 process_snippets (options.process_cmd, outdated,
1846 options.format, options.lily_output_dir)
1849 progress (_ ("All snippets are up to date..."))
1851 if options.lily_output_dir != options.output_dir:
1852 output_files = split_output_files (options.lily_output_dir)
1853 for snippet in snippets:
1854 snippet.link_all_output_files (options.lily_output_dir,
1862 # Format guessing data
1871 '.texinfo': TEXINFO,
1876 def guess_format (input_filename):
1878 e = os.path.splitext (input_filename)[1]
1881 format = ext2format[e]
1883 error (_ ("cannot determine format for: %s"
1888 def write_if_updated (file_name, lines):
1890 f = file (file_name)
1892 new_str = ''.join (lines)
1893 if oldstr == new_str:
1894 progress (_ ("%s is up to date.") % file_name)
1897 # this prevents make from always rerunning lilypond-book:
1898 # output file must be touched in order to be up to date
1899 os.utime (file_name, None)
1904 output_dir = os.path.dirname (file_name)
1905 if not os.path.exists (output_dir):
1906 os.makedirs (output_dir)
1908 progress (_ ("Writing `%s'...") % file_name)
1909 file (file_name, 'w').writelines (lines)
1913 def note_input_file (name, inputs=[]):
1914 ## hack: inputs is mutable!
1915 inputs.append (name)
1918 def samefile (f1, f2):
1920 return os.path.samefile (f1, f2)
1921 except AttributeError: # Windoze
1922 f1 = re.sub ("//*", "/", f1)
1923 f2 = re.sub ("//*", "/", f2)
1926 def do_file (input_filename, included=False):
1928 if not input_filename or input_filename == '-':
1929 in_handle = sys.stdin
1930 input_fullname = '<stdin>'
1932 if os.path.exists (input_filename):
1933 input_fullname = input_filename
1934 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1935 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1937 input_fullname = find_file (input_filename)
1939 note_input_file (input_fullname)
1940 in_handle = file (input_fullname)
1942 if input_filename == '-':
1943 input_base = 'stdin'
1945 input_base = os.path.splitext (input_filename)[0]
1947 input_base = os.path.basename (
1948 os.path.splitext (input_filename)[0])
1950 # don't complain when global_options.output_dir is existing
1951 if not global_options.output_dir:
1952 global_options.output_dir = os.getcwd()
1954 global_options.output_dir = os.path.abspath(global_options.output_dir)
1956 if not os.path.isdir (global_options.output_dir):
1957 os.mkdir (global_options.output_dir, 0777)
1958 os.chdir (global_options.output_dir)
1960 output_filename = os.path.join(global_options.output_dir,
1961 input_base + format2ext[global_options.format])
1962 if (os.path.exists (input_filename)
1963 and os.path.exists (output_filename)
1964 and samefile (output_filename, input_fullname)):
1966 _ ("Output would overwrite input file; use --output."))
1970 progress (_ ("Reading %s...") % input_fullname)
1971 source = in_handle.read ()
1974 set_default_options (source, default_ly_options, global_options.format)
1977 # FIXME: Containing blocks must be first, see
1978 # find_toplevel_snippets.
1980 'multiline_comment',
1984 'singleline_comment',
1990 progress (_ ("Dissecting..."))
1991 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1993 if global_options.format == LATEX:
1995 if (c.is_plain () and
1996 re.search (r"\\begin *{document}", c.replacement_text())):
2001 if global_options.filter_cmd:
2002 write_if_updated (output_filename,
2003 [c.filter_text () for c in chunks])
2004 elif global_options.process_cmd:
2005 do_process_cmd (chunks, input_fullname, global_options)
2006 progress (_ ("Compiling %s...") % output_filename)
2008 write_if_updated (output_filename,
2009 [s.replacement_text ()
2012 def process_include (snippet):
2013 os.chdir (original_dir)
2014 name = snippet.substring ('filename')
2015 progress (_ ("Processing include: %s") % name)
2017 return do_file (name, included=True)
2019 include_chunks = map (process_include,
2020 filter (lambda x: isinstance (x, IncludeSnippet),
2023 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2025 except CompileError:
2026 os.chdir (original_dir)
2027 progress (_ ("Removing `%s'") % output_filename)
2032 global global_options
2034 opt_parser = get_option_parser()
2035 (global_options, args) = opt_parser.parse_args ()
2036 if global_options.format in ('texi-html', 'texi'):
2037 global_options.format = TEXINFO
2039 global_options.include_path = map (os.path.abspath, global_options.include_path)
2041 if global_options.warranty:
2044 if not args or len (args) > 1:
2045 opt_parser.print_help ()
2051 # FIXME: 85 lines of `main' macramee??
2052 files = do_options ()
2054 basename = os.path.splitext (files[0])[0]
2055 basename = os.path.split (basename)[1]
2057 if not global_options.format:
2058 global_options.format = guess_format (files[0])
2061 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2064 if global_options.process_cmd == '':
2065 global_options.process_cmd = (lilypond_binary
2066 + ' --formats=%s -dbackend=eps ' % formats)
2068 if global_options.process_cmd:
2069 includes = global_options.include_path
2070 if global_options.lily_output_dir:
2071 # This must be first, so lilypond prefers to read .ly
2072 # files in the other lybookdb dir.
2073 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2074 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2077 if global_options.format in (TEXINFO, LATEX):
2078 ## prevent PDF from being switched on by default.
2079 global_options.process_cmd += ' --formats=eps '
2080 if global_options.create_pdf:
2081 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2083 if global_options.verbose:
2084 global_options.process_cmd += " --verbose "
2086 if global_options.padding_mm:
2087 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2089 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2091 if global_options.lily_output_dir:
2092 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2093 if not os.path.isdir (global_options.lily_output_dir):
2094 os.makedirs (global_options.lily_output_dir)
2096 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2101 chunks = do_file (files[0])
2102 except CompileError:
2105 inputs = note_input_file ('')
2108 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2109 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2110 final_output_file = os.path.join (global_options.output_dir,
2112 + '.%s' % global_options.format)
2114 os.chdir (original_dir)
2115 file (dep_file, 'w').write ('%s: %s'
2116 % (final_output_file, ' '.join (inputs)))
2118 if __name__ == '__main__':