3 # This file is part of LilyPond, the GNU music typesetter.
5 # LilyPond is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # LilyPond is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
22 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
25 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
27 classic lilypond-book:
28 lilypond-book --process="lilypond" BOOK.tely
32 * this script is too complex. Modularize.
34 * ly-options: intertext?
36 * eps in latex / eps by lilypond -b ps?
37 * check latex parameters, twocolumn, multicolumn?
38 * use --png --ps --pdf for making images?
40 * Converting from lilypond-book source, substitute:
41 @mbinclude foo.itely -> @include foo.itely
62 ly
.require_python_version ()
65 program_version
= '@TOPLEVEL_VERSION@'
66 program_name
= os
.path
.basename (sys
.argv
[0])
68 # Check if program_version contains @ characters. This will be the case if
69 # the .py file is called directly while building the lilypond documentation.
70 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
71 # makefiles and use its value.
72 at_re
= re
.compile (r
'@')
73 if at_re
.match (program_version
):
74 if os
.environ
.has_key('LILYPOND_VERSION'):
75 program_version
= os
.environ
['LILYPOND_VERSION']
77 program_version
= "unknown"
79 original_dir
= os
.getcwd ()
83 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
87 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
88 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
89 $ lilypond-book --process='lilypond -I include' %(BOOK)s
90 ''' % {'BOOK': _ ("BOOK")})
92 authors
= ('Jan Nieuwenhuizen <janneke@gnu.org>',
93 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
95 ################################################################
97 if global_options
.verbose
:
98 raise Exception (_ ('Exiting (%d)...') % i
)
103 ly
.encoded_write (sys
.stdout
, '%s (GNU LilyPond) %s\n' % (program_name
, program_version
))
105 progress
= ly
.progress
108 ly
.stderr_write (program_name
+ ": " + _ ("warning: %s") % s
+ '\n')
111 ly
.stderr_write (program_name
+ ": " + _ ("error: %s") % s
+ '\n')
113 def ps_page_count (ps_name
):
114 header
= file (ps_name
).read (1024)
115 m
= re
.search ('\n%%Pages: ([0-9]+)', header
)
117 return int (m
.group (1))
122 ly
.encoded_write (sys
.stdout
, '''
129 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
130 '\n '.join (authors
),
131 _ ("Distributed under terms of the GNU General Public License."),
132 _ ("It comes with NO WARRANTY.")))
134 def get_option_parser ():
135 p
= ly
.get_option_parser (usage
=_ ("%s [OPTION]... FILE") % 'lilypond-book',
136 description
=help_summary
,
137 add_help_option
=False)
139 p
.add_option ('-F', '--filter', metavar
=_ ("FILTER"),
142 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
145 p
.add_option ('-f', '--format',
146 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
147 metavar
=_ ("FORMAT"),
150 p
.add_option("-h", "--help",
152 help=_ ("show this help and exit"))
154 p
.add_option ("-I", '--include', help=_ ("add DIR to include path"),
156 action
='append', dest
='include_path',
157 default
=[os
.path
.abspath (os
.getcwd ())])
159 p
.add_option ('--info-images-dir',
160 help=_ ("format Texinfo output so that Info will "
161 "look for images of music in DIR"),
163 action
='store', dest
='info_images_dir',
166 p
.add_option ('--latex-program',
167 help=_ ("run executable PROG instead of latex"),
169 action
='store', dest
='latex_program',
172 p
.add_option ('--left-padding',
175 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
179 p
.add_option ('--lily-output-dir',
180 help=_ ("write lily-XXX files to DIR, link into --output dir"),
182 action
='store', dest
='lily_output_dir',
185 p
.add_option ("-o", '--output', help=_ ("write output to DIR"),
187 action
='store', dest
='output_dir',
190 p
.add_option ('--pdf',
193 help=_ ("create PDF files for use with PDFTeX"),
196 p
.add_option ('-P', '--process', metavar
=_ ("COMMAND"),
197 help = _ ("process ly_files using COMMAND FILE..."),
199 dest
='process_cmd', default
='')
201 p
.add_option ('--skip-lily-check',
202 help=_ ("do not fail if no lilypond output is found"),
204 action
='store_true', dest
='skip_lilypond_run',
207 p
.add_option ('--skip-png-check',
208 help=_ ("do not fail if no PNG images are found for EPS files"),
210 action
='store_true', dest
='skip_png_check',
213 p
.add_option ('--use-source-file-names',
214 help=_ ("write snippet output files with the same base name as their source file"),
215 action
='store_true', dest
='use_source_file_names',
218 p
.add_option ('-V', '--verbose', help=_ ("be verbose"),
223 p
.version
= "@TOPLEVEL_VERSION@"
224 p
.add_option("--version",
226 help=_ ("show version number and exit"))
228 p
.add_option ('-w', '--warranty',
229 help=_ ("show warranty and copyright"),
231 p
.add_option_group ('',
233 _ ("Report bugs via %s")
234 % ' http://post.gmane.org/post.php'
235 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
238 lilypond_binary
= os
.path
.join ('@bindir@', 'lilypond')
240 # If we are called with full path, try to use lilypond binary
241 # installed in the same path; this is needed in GUB binaries, where
242 # @bindir is always different from the installed binary path.
243 if 'bindir' in globals () and bindir
:
244 lilypond_binary
= os
.path
.join (bindir
, 'lilypond')
246 # Only use installed binary when we are installed too.
247 if '@bindir@' == ('@' + 'bindir@') or not os
.path
.exists (lilypond_binary
):
248 lilypond_binary
= 'lilypond'
250 global_options
= None
253 default_ly_options
= { 'alt': "[image of music]" }
255 document_language
= ''
258 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
260 ADDVERSION
= 'addversion'
264 EXAMPLEINDENT
= 'exampleindent'
266 FRAGMENT
= 'fragment'
272 LINE_WIDTH
= 'line-width'
273 LILYQUOTE
= 'lilyquote'
274 NOFRAGMENT
= 'nofragment'
275 NOGETTEXT
= 'nogettext'
276 NOINDENT
= 'noindent'
278 NORAGGED_RIGHT
= 'noragged-right'
282 OUTPUTIMAGE
= 'outputimage'
284 PREAMBLE
= 'preamble'
285 PRINTFILENAME
= 'printfilename'
287 RAGGED_RIGHT
= 'ragged-right'
288 RELATIVE
= 'relative'
289 STAFFSIZE
= 'staffsize'
290 DOCTITLE
= 'doctitle'
293 VERBATIM
= 'verbatim'
294 VERSION
= 'lilypondversion'
295 FILENAME
= 'filename'
299 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
301 # NOQUOTE is used internally only.
303 NOFRAGMENT
: FRAGMENT
,
307 # Options that have no impact on processing by lilypond (or --process
309 PROCESSING_INDEPENDENT_OPTIONS
= (
310 ALT
, NOGETTEXT
, VERBATIM
, ADDVERSION
,
311 TEXIDOC
, DOCTITLE
, VERSION
, PRINTFILENAME
)
313 # Recognize special sequences in the input.
315 # (?P<name>regex) -- Assign result of REGEX to NAME.
316 # *? -- Match non-greedily.
317 # (?!...) -- Match if `...' doesn't match next (without consuming
320 # (?m) -- Multiline regex: Make ^ and $ match at each line.
321 # (?s) -- Make the dot match all characters including newline.
322 # (?x) -- Ignore whitespace in patterns.
333 <(?P<inline>(inline)?)mediaobject>\s*
335 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
337 </programlisting\s*>\s*
339 </(inline)?mediaobject>)''',
344 <(?P<inline>(inline)?)mediaobject>\s*
346 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
348 </programlisting\s*>\s*
350 </(inline)?mediaobject>)''',
355 <(?P<inline>(inline)?)mediaobject>\s*
358 fileref="(?P<filename>.*?\.ly)"\s*
359 (role="(?P<options>.*?)")?\s*
360 (/>|>\s*</imagedata>)\s*
362 </(inline)?mediaobject>)''',
368 (?P<code><!--\s.*?!-->)
371 'singleline_comment':
392 (\s*(?P<options>.*?)\s*:)?\s*
400 \s*(?P<options>.*?)\s*
409 \s*(?P<options>.*?)\s*
411 \s*(?P<filename>.*?)\s*
418 (?P<code><!--\s.*?!-->)
421 'singleline_comment':
427 (?P<code><pre>.*?</pre>))''',
433 (?P<code><pre>\s.*?</pre>\s))''',
438 <lilypondversion\s*/>)''',
457 \s*(?P<options>.*?)\s*
468 \s*(?P<options>.*?)\s*
472 \\end\s*{lilypond})''',
480 \s*(?P<options>.*?)\s*
488 'singleline_comment':
511 \\end\s*{verbatim}))''',
516 \\lilypondversion)[^a-zA-Z]''',
526 (?P<filename>\S+))''',
530 ^[^\n]*?(?!@c\s+)[^\n]*?
534 \s*(?P<options>.*?)\s*
544 \s*(?P<options>.*?)\s*
547 ^@end\s+lilypond)\s''',
554 \s*(?P<options>.*?)\s*
565 @end\s+ignore))\s''',
567 'singleline_comment':
572 @c([ \t][^\n]*|)\n))''',
574 # Don't do this: It interferes with @code{@{}.
575 # 'verb': r'''(?P<code>@code{.*?})''',
583 @end\s+example\s))''',
588 @lilypondversion)[^a-zA-Z]''',
596 'intertext': r
',?\s*intertext=\".*?\"',
600 'intertext': r
',?\s*intertext=\".*?\"',
605 'intertext': r
',?\s*intertext=\".*?\"',
606 'option_sep': '\s*,\s*',
610 'intertext': r
',?\s*intertext=\".*?\"',
611 'option_sep': '\s*,\s*',
616 # Options without a pattern in ly_options.
636 RELATIVE
: r
'''\relative c%(relative_quotes)s''',
641 INDENT
: r
'''indent = %(indent)s''',
643 LINE_WIDTH
: r
'''line-width = %(line-width)s''',
645 QUOTE
: r
'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
647 LILYQUOTE
: r
'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
649 RAGGED_RIGHT
: r
'''ragged-right = ##t''',
651 NORAGGED_RIGHT
: r
'''ragged-right = ##f''',
663 \remove "Time_signature_engraver"
669 STAFFSIZE
: r
'''#(set-global-staff-size %(staffsize)s)''',
676 FILTER
: r
'''<mediaobject>
678 <programlisting language="lilypond"
685 OUTPUT
: r
'''<imageobject role="latex">
686 <imagedata fileref="%(base)s.pdf" format="PDF"/>
688 <imageobject role="html">
689 <imagedata fileref="%(base)s.png" format="PNG"/>
692 VERBATIM
: r
'''<programlisting>
693 %(verb)s</programlisting>''',
695 VERSION
: program_version
,
697 PRINTFILENAME
: r
'''<textobject>
699 <ulink url="%(base)s.ly">
709 FILTER
: r
'''<lilypond %(options)s>
719 <a href="%(base)s.ly">''',
727 PRINTFILENAME
: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
729 QUOTE
: r
'''<blockquote>
737 VERSION
: program_version
,
744 \ifx\preLilyPondExample \undefined
746 \expandafter\preLilyPondExample
748 \def\lilypondbook{}%%
749 \input %(base)s-systems.tex
750 \ifx\postLilyPondExample \undefined
752 \expandafter\postLilyPondExample
756 PRINTFILENAME
: '''\\texttt{%(filename)s}
759 QUOTE
: r
'''\begin{quotation}
763 VERBATIM
: r
'''\noindent
764 \begin{verbatim}%(verb)s\end{verbatim}
767 VERSION
: program_version
,
769 FILTER
: r
'''\begin{lilypond}[%(options)s]
776 FILTER
: r
'''@lilypond[%(options)s]
782 @include %(base)s-systems.texi
786 OUTPUTIMAGE
: r
'''@noindent
788 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
792 <a href="%(base)s.ly">
804 <a href="%(base)s.ly">
812 QUOTE
: r
'''@quotation
813 %(str)s@end quotation
820 VERBATIM
: r
'''@exampleindent 0
822 %(verb)s@end verbatim
825 VERSION
: program_version
,
827 ADDVERSION
: r
'''@example
828 \version @w{"@version{}"}
835 # Maintain line numbers.
840 for f
in [HTML
, LATEX
]:
841 for s
in (QUOTE
, VERBATIM
):
842 output
[f
][s
] = output
[f
][s
].replace("\n"," ")
845 PREAMBLE_LY
= '''%%%% Generated by %(program_name)s
846 %%%% Options: [%(option_string)s]
847 \\include "lilypond-book-preamble.ly"
850 %% ****************************************************************
851 %% Start cut-&-pastable-section
852 %% ****************************************************************
858 force-assignment = #""
859 line-width = #(- line-width (* mm %(padding_mm)f))
872 %% ****************************************************************
873 %% ly snippet contents follows:
874 %% ****************************************************************
878 %% ****************************************************************
880 %% ****************************************************************
887 %% ****************************************************************
889 %% ****************************************************************
893 %% ****************************************************************
895 %% ****************************************************************
898 texinfo_line_widths
= {
899 '@afourpaper': '160\\mm',
900 '@afourwide': '6.5\\in',
901 '@afourlatex': '150\\mm',
902 '@smallbook': '5\\in',
903 '@letterpaper': '6\\in',
906 def classic_lilypond_book_compatibility (key
, value
):
907 if key
== 'singleline' and value
== None:
908 return (RAGGED_RIGHT
, None)
910 m
= re
.search ('relative\s*([-0-9])', key
)
912 return ('relative', m
.group (1))
914 m
= re
.match ('([0-9]+)pt', key
)
916 return ('staffsize', m
.group (1))
918 if key
== 'indent' or key
== 'line-width':
919 m
= re
.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value
)
921 f
= float (m
.group (1))
922 return (key
, '%f\\%s' % (f
, m
.group (2)))
926 def find_file (name
, raise_error
=True):
927 for i
in global_options
.include_path
:
928 full
= os
.path
.join (i
, name
)
929 if os
.path
.exists (full
):
933 error (_ ("file not found: %s") % name
+ '\n')
937 def verbatim_html (s
):
938 return re
.sub ('>', '>',
940 re
.sub ('&', '&', s
)))
942 ly_var_def_re
= re
.compile (r
'^([a-zA-Z]+)[\t ]*=', re
.M
)
943 ly_comment_re
= re
.compile (r
'(%+[\t ]*)(.*)$', re
.M
)
944 ly_context_id_re
= re
.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
945 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
947 def ly_comment_gettext (t
, m
):
948 return m
.group (1) + t (m
.group (2))
950 def verb_ly_gettext (s
):
951 if not document_language
:
954 t
= langdefs
.translation
[document_language
]
958 s
= ly_comment_re
.sub (lambda m
: ly_comment_gettext (t
, m
), s
)
960 if langdefs
.LANGDICT
[document_language
].enable_ly_identifier_l10n
:
961 for v
in ly_var_def_re
.findall (s
):
962 s
= re
.sub (r
"(?m)(^|[' \\#])%s([^a-zA-Z])" % v
,
963 "\\1" + t (v
) + "\\2",
965 for id in ly_context_id_re
.findall (s
):
966 s
= re
.sub (r
'(\s+|")%s(\s+|")' % id,
967 "\\1" + t (id) + "\\2",
971 texinfo_lang_re
= re
.compile ('(?m)^@documentlanguage (.*?)( |$)')
972 def set_default_options (source
, default_ly_options
, format
):
973 global document_language
974 if LINE_WIDTH
not in default_ly_options
:
976 textwidth
= get_latex_textwidth (source
)
977 default_ly_options
[LINE_WIDTH
] = '%.0f\\pt' % textwidth
978 elif format
== TEXINFO
:
979 m
= texinfo_lang_re
.search (source
)
980 if m
and not m
.group (1).startswith ('en'):
981 document_language
= m
.group (1)
983 document_language
= ''
984 for regex
in texinfo_line_widths
:
985 # FIXME: @layout is usually not in
988 # \input texinfo @c -*-texinfo-*-
990 # Bluntly search first K items of
992 # s = chunks[0].replacement_text ()
993 if re
.search (regex
, source
[:1024]):
994 default_ly_options
[LINE_WIDTH
] = texinfo_line_widths
[regex
]
998 def replacement_text (self
):
1001 def filter_text (self
):
1002 return self
.replacement_text ()
1004 def is_plain (self
):
1007 class Substring (Chunk
):
1008 """A string that does not require extra memory."""
1009 def __init__ (self
, source
, start
, end
, line_number
):
1010 self
.source
= source
1013 self
.line_number
= line_number
1014 self
.override_text
= None
1016 def is_plain (self
):
1019 def replacement_text (self
):
1020 if self
.override_text
:
1021 return self
.override_text
1023 return self
.source
[self
.start
:self
.end
]
1025 class Snippet (Chunk
):
1026 def __init__ (self
, type, match
, format
, line_number
):
1030 self
.option_dict
= {}
1031 self
.format
= format
1032 self
.line_number
= line_number
1034 def replacement_text (self
):
1035 return self
.match
.group ('match')
1037 def substring (self
, s
):
1038 return self
.match
.group (s
)
1040 def __repr__ (self
):
1041 return `self
.__class
__`
+ ' type = ' + self
.type
1043 class IncludeSnippet (Snippet
):
1044 def processed_filename (self
):
1045 f
= self
.substring ('filename')
1046 return os
.path
.splitext (f
)[0] + format2ext
[self
.format
]
1048 def replacement_text (self
):
1049 s
= self
.match
.group ('match')
1050 f
= self
.substring ('filename')
1052 return re
.sub (f
, self
.processed_filename (), s
)
1054 class LilypondSnippet (Snippet
):
1055 def __init__ (self
, type, match
, format
, line_number
):
1056 Snippet
.__init
__ (self
, type, match
, format
, line_number
)
1057 os
= match
.group ('options')
1058 self
.do_options (os
, self
.type)
1061 verb_text
= self
.substring ('code')
1062 if not NOGETTEXT
in self
.option_dict
:
1063 verb_text
= verb_ly_gettext (verb_text
)
1064 if not verb_text
.endswith ('\n'):
1069 contents
= self
.substring ('code')
1070 return ('\\sourcefileline %d\n%s'
1071 % (self
.line_number
- 1, contents
))
1076 return self
.compose_ly (s
)
1079 def split_options (self
, option_string
):
1081 if self
.format
== HTML
:
1082 options
= re
.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1084 options
= [re
.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt
)
1088 return re
.split (format_res
[self
.format
]['option_sep'],
1092 def do_options (self
, option_string
, type):
1093 self
.option_dict
= {}
1095 options
= self
.split_options (option_string
)
1097 for option
in options
:
1099 (key
, value
) = re
.split ('\s*=\s*', option
)
1100 self
.option_dict
[key
] = value
1102 if option
in no_options
:
1103 if no_options
[option
] in self
.option_dict
:
1104 del self
.option_dict
[no_options
[option
]]
1106 self
.option_dict
[option
] = None
1108 has_line_width
= self
.option_dict
.has_key (LINE_WIDTH
)
1109 no_line_width_value
= 0
1111 # If LINE_WIDTH is used without parameter, set it to default.
1112 if has_line_width
and self
.option_dict
[LINE_WIDTH
] == None:
1113 no_line_width_value
= 1
1114 del self
.option_dict
[LINE_WIDTH
]
1116 for k
in default_ly_options
:
1117 if k
not in self
.option_dict
:
1118 self
.option_dict
[k
] = default_ly_options
[k
]
1120 # RELATIVE does not work without FRAGMENT;
1121 # make RELATIVE imply FRAGMENT
1122 has_relative
= self
.option_dict
.has_key (RELATIVE
)
1123 if has_relative
and not self
.option_dict
.has_key (FRAGMENT
):
1124 self
.option_dict
[FRAGMENT
] = None
1126 if not has_line_width
:
1127 if type == 'lilypond' or FRAGMENT
in self
.option_dict
:
1128 self
.option_dict
[RAGGED_RIGHT
] = None
1130 if type == 'lilypond':
1131 if LINE_WIDTH
in self
.option_dict
:
1132 del self
.option_dict
[LINE_WIDTH
]
1134 if RAGGED_RIGHT
in self
.option_dict
:
1135 if LINE_WIDTH
in self
.option_dict
:
1136 del self
.option_dict
[LINE_WIDTH
]
1138 if QUOTE
in self
.option_dict
or type == 'lilypond':
1139 if LINE_WIDTH
in self
.option_dict
:
1140 del self
.option_dict
[LINE_WIDTH
]
1142 if not INDENT
in self
.option_dict
:
1143 self
.option_dict
[INDENT
] = '0\\mm'
1145 # Set a default line-width if there is none. We need this, because
1146 # lilypond-book has set left-padding by default and therefore does
1147 # #(define line-width (- line-width (* 3 mm)))
1148 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
1149 # all settings before writing them in the \paper block.
1150 if not LINE_WIDTH
in self
.option_dict
:
1151 if not QUOTE
in self
.option_dict
:
1152 if not LILYQUOTE
in self
.option_dict
:
1153 self
.option_dict
[LINE_WIDTH
] = "#(- paper-width \
1154 left-margin-default right-margin-default)"
1156 def get_option_list (self
):
1157 if not 'option_list' in self
.__dict
__:
1159 for (key
, value
) in self
.option_dict
.items ():
1161 option_list
.append (key
)
1163 option_list
.append (key
+ '=' + value
)
1165 self
.option_list
= option_list
1166 return self
.option_list
1168 def compose_ly (self
, code
):
1169 if FRAGMENT
in self
.option_dict
:
1177 # The original concept of the `exampleindent' option is broken.
1178 # It is not possible to get a sane value for @exampleindent at all
1179 # without processing the document itself. Saying
1187 # causes ugly results with the DVI backend of texinfo since the
1188 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1189 # value). Executing the above code changes the environment
1190 # indentation to an unknown value because we don't know the amount
1191 # of 1em in advance since it is font-dependent. Modifying
1192 # @exampleindent in the middle of a document is simply not
1193 # supported within texinfo.
1195 # As a consequence, the only function of @exampleindent is now to
1196 # specify the amount of indentation for the `quote' option.
1198 # To set @exampleindent locally to zero, we use the @format
1199 # environment for non-quoted snippets.
1200 override
[EXAMPLEINDENT
] = r
'0.4\in'
1201 override
[LINE_WIDTH
] = texinfo_line_widths
['@smallbook']
1202 override
.update (default_ly_options
)
1205 for option
in self
.get_option_list ():
1206 for name
in PROCESSING_INDEPENDENT_OPTIONS
:
1207 if not option
.startswith (name
):
1208 option_list
.append (option
)
1209 option_string
= ','.join (option_list
)
1212 compose_types
= [NOTES
, PREAMBLE
, LAYOUT
, PAPER
]
1213 for a
in compose_types
:
1214 compose_dict
[a
] = []
1216 option_names
= self
.option_dict
.keys ()
1217 option_names
.sort ()
1218 for key
in option_names
:
1219 value
= self
.option_dict
[key
]
1220 (c_key
, c_value
) = classic_lilypond_book_compatibility (key
, value
)
1224 _ ("deprecated ly-option used: %s=%s") % (key
, value
))
1226 _ ("compatibility mode translation: %s=%s") % (c_key
, c_value
))
1229 _ ("deprecated ly-option used: %s") % key
)
1231 _ ("compatibility mode translation: %s") % c_key
)
1233 (key
, value
) = (c_key
, c_value
)
1236 override
[key
] = value
1238 if not override
.has_key (key
):
1239 override
[key
] = None
1242 for type in compose_types
:
1243 if ly_options
[type].has_key (key
):
1244 compose_dict
[type].append (ly_options
[type][key
])
1248 if not found
and key
not in simple_options
:
1249 warning (_ ("ignoring unknown ly option: %s") % key
)
1252 if RELATIVE
in override
and override
[RELATIVE
]:
1253 relative
= int (override
[RELATIVE
])
1255 relative_quotes
= ''
1259 relative_quotes
+= ',' * (- relative
)
1261 relative_quotes
+= "'" * relative
1263 paper_string
= '\n '.join (compose_dict
[PAPER
]) % override
1264 layout_string
= '\n '.join (compose_dict
[LAYOUT
]) % override
1265 notes_string
= '\n '.join (compose_dict
[NOTES
]) % vars ()
1266 preamble_string
= '\n '.join (compose_dict
[PREAMBLE
]) % override
1267 padding_mm
= global_options
.padding_mm
1269 d
= globals().copy()
1271 return (PREAMBLE_LY
+ body
) % d
1273 def get_checksum (self
):
1274 if not self
.checksum
:
1275 # Work-around for md5 module deprecation warning in python 2.5+:
1277 from hashlib
import md5
1281 # We only want to calculate the hash based on the snippet
1282 # code plus fragment options relevant to processing by
1283 # lilypond, not the snippet + preamble
1284 hash = md5 (self
.relevant_contents (self
.ly ()))
1285 for option
in self
.get_option_list ():
1286 for name
in PROCESSING_INDEPENDENT_OPTIONS
:
1287 if not option
.startswith (name
):
1288 hash.update (option
)
1290 ## let's not create too long names.
1291 self
.checksum
= hash.hexdigest ()[:10]
1293 return self
.checksum
1295 def basename (self
):
1296 cs
= self
.get_checksum ()
1297 name
= '%s/lily-%s' % (cs
[:2], cs
[2:])
1300 final_basename
= basename
1302 def write_ly (self
):
1303 base
= self
.basename ()
1304 path
= os
.path
.join (global_options
.lily_output_dir
, base
)
1305 directory
= os
.path
.split(path
)[0]
1306 if not os
.path
.isdir (directory
):
1307 os
.makedirs (directory
)
1308 filename
= path
+ '.ly'
1309 if os
.path
.exists (filename
):
1310 diff_against_existing
= filter_pipe (self
.full_ly (), 'diff -u %s -' % filename
)
1311 if diff_against_existing
:
1312 warning ("%s: duplicate filename but different contents of orginal file,\n\
1313 printing diff against existing file." % filename
)
1314 ly
.stderr_write (diff_against_existing
)
1316 out
= file (filename
, 'w')
1317 out
.write (self
.full_ly ())
1318 file (path
+ '.txt', 'w').write ('image of music')
1320 def relevant_contents (self
, ly
):
1321 return re
.sub (r
'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly
)
1323 def link_all_output_files (self
, output_dir
, output_dir_files
, destination
):
1324 existing
, missing
= self
.all_output_files (output_dir
, output_dir_files
)
1326 print '\nMissing', missing
1327 raise CompileError(self
.basename())
1328 for name
in existing
:
1329 if (global_options
.use_source_file_names
1330 and isinstance (self
, LilypondFileSnippet
)):
1331 base
, ext
= os
.path
.splitext (name
)
1332 components
= base
.split ('-')
1333 # ugh, assume filenames with prefix with one dash (lily-xxxx)
1334 if len (components
) > 2:
1335 base_suffix
= '-' + components
[-1]
1338 final_name
= self
.final_basename () + base_suffix
+ ext
1342 os
.unlink (os
.path
.join (destination
, final_name
))
1346 src
= os
.path
.join (output_dir
, name
)
1347 dst
= os
.path
.join (destination
, final_name
)
1348 dst_path
= os
.path
.split(dst
)[0]
1349 if not os
.path
.isdir (dst_path
):
1350 os
.makedirs (dst_path
)
1354 def all_output_files (self
, output_dir
, output_dir_files
):
1355 """Return all files generated in lily_output_dir, a set.
1357 output_dir_files is the list of files in the output directory.
1361 base
= self
.basename()
1362 full
= os
.path
.join (output_dir
, base
)
1363 def consider_file (name
):
1364 if name
in output_dir_files
:
1367 def require_file (name
):
1368 if name
in output_dir_files
:
1373 # UGH - junk global_options
1374 skip_lily
= global_options
.skip_lilypond_run
1375 for required
in [base
+ '.ly',
1377 require_file (required
)
1379 require_file (base
+ '-systems.count')
1381 if 'ddump-profile' in global_options
.process_cmd
:
1382 require_file (base
+ '.profile')
1383 if 'dseparate-log-file' in global_options
.process_cmd
:
1384 require_file (base
+ '.log')
1386 map (consider_file
, [base
+ '.tex',
1390 base
+ '-systems.texi',
1391 base
+ '-systems.tex',
1392 base
+ '-systems.pdftexi'])
1393 if document_language
:
1395 [base
+ '.texidoc' + document_language
,
1396 base
+ '.doctitle' + document_language
])
1398 # UGH - junk global_options
1399 if (base
+ '.eps' in result
and self
.format
in (HTML
, TEXINFO
)
1400 and not global_options
.skip_png_check
):
1401 page_count
= ps_page_count (full
+ '.eps')
1403 require_file (base
+ '.png')
1405 for page
in range (1, page_count
+ 1):
1406 require_file (base
+ '-page%d.png' % page
)
1409 if not skip_lily
and not missing
:
1410 system_count
= int(file (full
+ '-systems.count').read())
1412 for number
in range(1, system_count
+ 1):
1413 systemfile
= '%s-%d' % (base
, number
)
1414 require_file (systemfile
+ '.eps')
1415 consider_file (systemfile
+ '.pdf')
1417 # We can't require signatures, since books and toplevel
1418 # markups do not output a signature.
1419 if 'ddump-signature' in global_options
.process_cmd
:
1420 consider_file (systemfile
+ '.signature')
1423 return (result
, missing
)
1425 def is_outdated (self
, output_dir
, current_files
):
1426 found
, missing
= self
.all_output_files (output_dir
, current_files
)
1429 def filter_text (self
):
1430 """Run snippet bodies through a command (say: convert-ly).
1432 This functionality is rarely used, and this code must have bitrot.
1434 code
= self
.substring ('code')
1435 s
= filter_pipe (code
, global_options
.filter_cmd
)
1438 'options': self
.match
.group ('options')
1441 return output
[self
.format
][FILTER
] % d
1443 def replacement_text (self
):
1444 func
= LilypondSnippet
.__dict
__['output_' + self
.format
]
1447 def get_images (self
):
1448 base
= self
.final_basename ()
1450 single
= '%(base)s.png' % vars ()
1451 multiple
= '%(base)s-page1.png' % vars ()
1453 if (os
.path
.exists (multiple
)
1454 and (not os
.path
.exists (single
)
1455 or (os
.stat (multiple
)[stat
.ST_MTIME
]
1456 > os
.stat (single
)[stat
.ST_MTIME
]))):
1457 count
= ps_page_count ('%(base)s.eps' % vars ())
1458 images
= ['%s-page%d.png' % (base
, page
) for page
in range (1, count
+1)]
1459 images
= tuple (images
)
1463 def output_docbook (self
):
1465 base
= self
.final_basename ()
1466 for image
in self
.get_images ():
1467 (base
, ext
) = os
.path
.splitext (image
)
1468 str += output
[DOCBOOK
][OUTPUT
] % vars ()
1469 str += self
.output_print_filename (DOCBOOK
)
1470 if (self
.substring('inline') == 'inline'):
1471 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1473 str = '<mediaobject>' + str + '</mediaobject>'
1474 if VERBATIM
in self
.option_dict
:
1475 verb
= verbatim_html (self
.verb_ly ())
1476 str = output
[DOCBOOK
][VERBATIM
] % vars () + str
1479 def output_html (self
):
1481 base
= self
.final_basename ()
1482 if self
.format
== HTML
:
1483 str += self
.output_print_filename (HTML
)
1484 if VERBATIM
in self
.option_dict
:
1485 verb
= verbatim_html (self
.verb_ly ())
1486 str += output
[HTML
][VERBATIM
] % vars ()
1487 if QUOTE
in self
.option_dict
:
1488 str = output
[HTML
][QUOTE
] % vars ()
1490 str += output
[HTML
][BEFORE
] % vars ()
1491 for image
in self
.get_images ():
1492 (base
, ext
) = os
.path
.splitext (image
)
1493 alt
= self
.option_dict
[ALT
]
1494 str += output
[HTML
][OUTPUT
] % vars ()
1495 str += output
[HTML
][AFTER
] % vars ()
1498 def output_info (self
):
1500 for image
in self
.get_images ():
1501 (base
, ext
) = os
.path
.splitext (image
)
1503 # URG, makeinfo implicitly prepends dot to extension.
1504 # Specifying no extension is most robust.
1506 alt
= self
.option_dict
[ALT
]
1507 info_image_path
= os
.path
.join (global_options
.info_images_dir
, base
)
1508 str += output
[TEXINFO
][OUTPUTIMAGE
] % vars ()
1510 base
= self
.final_basename ()
1511 str += output
[self
.format
][OUTPUT
] % vars ()
1514 def output_latex (self
):
1516 base
= self
.final_basename ()
1517 if self
.format
== LATEX
:
1518 str += self
.output_print_filename (LATEX
)
1519 if VERBATIM
in self
.option_dict
:
1520 verb
= self
.verb_ly ()
1521 str += (output
[LATEX
][VERBATIM
] % vars ())
1523 str += (output
[LATEX
][OUTPUT
] % vars ())
1525 ## todo: maintain breaks
1527 breaks
= self
.ly ().count ("\n")
1528 str += "".ljust (breaks
, "\n").replace ("\n","%\n")
1530 if QUOTE
in self
.option_dict
:
1531 str = output
[LATEX
][QUOTE
] % vars ()
1534 def output_print_filename (self
, format
):
1536 if PRINTFILENAME
in self
.option_dict
:
1537 base
= self
.final_basename ()
1538 filename
= os
.path
.basename (self
.substring ('filename'))
1539 str = output
[format
][PRINTFILENAME
] % vars ()
1543 def output_texinfo (self
):
1544 str = self
.output_print_filename (TEXINFO
)
1545 base
= self
.final_basename ()
1546 if DOCTITLE
in self
.option_dict
:
1547 doctitle
= base
+ '.doctitle'
1548 translated_doctitle
= doctitle
+ document_language
1549 if os
.path
.exists (translated_doctitle
):
1550 str += '@lydoctitle %s\n\n' % open (translated_doctitle
).read ()
1551 elif os
.path
.exists (doctitle
):
1552 str += '@lydoctitle %s\n\n' % open (doctitle
).read ()
1553 if TEXIDOC
in self
.option_dict
:
1554 texidoc
= base
+ '.texidoc'
1555 translated_texidoc
= texidoc
+ document_language
1556 if os
.path
.exists (translated_texidoc
):
1557 str += '@include %(translated_texidoc)s\n\n' % vars ()
1558 elif os
.path
.exists (texidoc
):
1559 str += '@include %(texidoc)s\n\n' % vars ()
1562 if VERBATIM
in self
.option_dict
:
1564 if ADDVERSION
in self
.option_dict
:
1565 version
= output
[TEXINFO
][ADDVERSION
]
1566 verb
= self
.verb_ly ()
1567 substr
= output
[TEXINFO
][VERBATIM
] % vars ()
1568 substr
+= self
.output_info ()
1569 if LILYQUOTE
in self
.option_dict
:
1570 substr
= output
[TEXINFO
][QUOTE
] % {'str':substr
}
1573 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1574 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1575 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1577 if QUOTE
in self
.option_dict
:
1578 str = output
[TEXINFO
][QUOTE
] % vars ()
1580 # need par after image
1585 re_begin_verbatim
= re
.compile (r
'\s+%.*?begin verbatim.*\n*', re
.M
)
1586 re_end_verbatim
= re
.compile (r
'\s+%.*?end verbatim.*$', re
.M
)
1588 class LilypondFileSnippet (LilypondSnippet
):
1589 def __init__ (self
, type, match
, format
, line_number
):
1590 LilypondSnippet
.__init
__ (self
, type, match
, format
, line_number
)
1591 self
.contents
= file (find_file (self
.substring ('filename'))).read ()
1595 s
= re_begin_verbatim
.split (s
)[-1]
1596 s
= re_end_verbatim
.split (s
)[0]
1597 if not NOGETTEXT
in self
.option_dict
:
1598 s
= verb_ly_gettext (s
)
1599 if not s
.endswith ('\n'):
1604 name
= self
.substring ('filename')
1605 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1606 % (name
, self
.contents
))
1608 def final_basename (self
):
1609 if global_options
.use_source_file_names
:
1610 base
= os
.path
.splitext (os
.path
.basename (self
.substring ('filename')))[0]
1613 return self
.basename ()
1616 class LilyPondVersionString (Snippet
):
1617 """A string that does not require extra memory."""
1618 def __init__ (self
, type, match
, format
, line_number
):
1619 Snippet
.__init
__ (self
, type, match
, format
, line_number
)
1621 def replacement_text (self
):
1622 return output
[self
.format
][self
.type]
1625 snippet_type_to_class
= {
1626 'lilypond_file': LilypondFileSnippet
,
1627 'lilypond_block': LilypondSnippet
,
1628 'lilypond': LilypondSnippet
,
1629 'include': IncludeSnippet
,
1630 'lilypondversion': LilyPondVersionString
,
1633 def find_linestarts (s
):
1638 i
= s
.find ('\n', start
)
1646 nls
.append (len (s
))
1649 def find_toplevel_snippets (input_string
, format
, types
):
1652 res
[t
] = re
.compile (snippet_res
[format
][t
])
1656 found
= dict ([(t
, None) for t
in types
])
1658 line_starts
= find_linestarts (input_string
)
1660 # We want to search for multiple regexes, without searching
1661 # the string multiple times for one regex.
1662 # Hence, we use earlier results to limit the string portion
1664 # Since every part of the string is traversed at most once for
1665 # every type of snippet, this is linear.
1671 if not found
[type] or found
[type][0] < index
:
1674 m
= res
[type].search (input_string
[index
:endex
])
1679 if type in snippet_type_to_class
:
1680 klass
= snippet_type_to_class
[type]
1682 start
= index
+ m
.start ('match')
1683 line_number
= line_start_idx
1684 while (line_starts
[line_number
] < start
):
1688 snip
= klass (type, m
, format
, line_number
)
1690 found
[type] = (start
, snip
)
1694 or found
[type][0] < found
[first
][0])):
1699 # Limiting the search space is a cute
1700 # idea, but this *requires* to search
1701 # for possible containing blocks
1702 # first, at least as long as we do not
1703 # search for the start of blocks, but
1704 # always/directly for the entire
1705 # @block ... @end block.
1707 endex
= found
[first
][0]
1710 snippets
.append (Substring (input_string
, index
, len (input_string
), line_start_idx
))
1713 while (start
> line_starts
[line_start_idx
+1]):
1716 (start
, snip
) = found
[first
]
1717 snippets
.append (Substring (input_string
, index
, start
, line_start_idx
+ 1))
1718 snippets
.append (snip
)
1720 index
= start
+ len (snip
.match
.group ('match'))
1724 def filter_pipe (input, cmd
):
1725 """Pass input through cmd, and return the result."""
1727 if global_options
.verbose
:
1728 progress (_ ("Opening filter `%s'") % cmd
)
1730 (stdin
, stdout
, stderr
) = os
.popen3 (cmd
)
1732 status
= stdin
.close ()
1736 output
= stdout
.read ()
1737 status
= stdout
.close ()
1738 error
= stderr
.read ()
1742 signal
= 0x0f & status
1743 if status
or (not output
and error
):
1744 exit_status
= status
>> 8
1745 error (_ ("`%s' failed (%d)") % (cmd
, exit_status
))
1746 error (_ ("The error log is as follows:"))
1747 ly
.stderr_write (error
)
1748 ly
.stderr_write (stderr
.read ())
1751 if global_options
.verbose
:
1756 def system_in_directory (cmd
, directory
):
1757 """Execute a command in a different directory.
1759 Because of win32 compatibility, we can't simply use subprocess.
1762 current
= os
.getcwd()
1763 os
.chdir (directory
)
1764 ly
.system(cmd
, be_verbose
=global_options
.verbose
,
1769 def process_snippets (cmd
, snippets
,
1770 format
, lily_output_dir
):
1771 """Run cmd on all of the .ly files from snippets."""
1776 if format
in (HTML
, TEXINFO
) and '--formats' not in cmd
:
1777 cmd
+= ' --formats=png '
1778 elif format
in (DOCBOOK
) and '--formats' not in cmd
:
1779 cmd
+= ' --formats=png,pdf '
1781 checksum
= snippet_list_checksum (snippets
)
1782 contents
= '\n'.join (['snippet-map-%d.ly' % checksum
]
1783 + list (set ([snip
.basename() + '.ly' for snip
in snippets
])))
1784 name
= os
.path
.join (lily_output_dir
,
1785 'snippet-names-%d.ly' % checksum
)
1786 file (name
, 'wb').write (contents
)
1788 system_in_directory (' '.join ([cmd
, ly
.mkarg (name
)]),
1793 # Retrieve dimensions from LaTeX
1794 LATEX_INSPECTION_DOCUMENT
= r
'''
1798 \typeout{textwidth=\the\textwidth}
1799 \typeout{columnsep=\the\columnsep}
1800 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1804 # Do we need anything else besides `textwidth'?
1805 def get_latex_textwidth (source
):
1806 m
= re
.search (r
'''(?P<preamble>\\begin\s*{document})''', source
)
1808 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1810 ## what's a sensible default?
1813 preamble
= source
[:m
.start (0)]
1814 latex_document
= LATEX_INSPECTION_DOCUMENT
% vars ()
1816 (handle
, tmpfile
) = tempfile
.mkstemp('.tex')
1817 logfile
= os
.path
.splitext (tmpfile
)[0] + '.log'
1818 logfile
= os
.path
.split (logfile
)[1]
1820 tmp_handle
= os
.fdopen (handle
,'w')
1821 tmp_handle
.write (latex_document
)
1824 ly
.system ('%s %s' % (global_options
.latex_program
, tmpfile
),
1825 be_verbose
=global_options
.verbose
)
1826 parameter_string
= file (logfile
).read()
1832 m
= re
.search ('columns=([0-9.]+)', parameter_string
)
1834 columns
= int (m
.group (1))
1837 m
= re
.search ('columnsep=([0-9.]+)pt', parameter_string
)
1839 columnsep
= float (m
.group (1))
1842 m
= re
.search ('textwidth=([0-9.]+)pt', parameter_string
)
1844 textwidth
= float (m
.group (1))
1846 textwidth
= (textwidth
- columnsep
) / columns
1850 def modify_preamble (chunk
):
1851 str = chunk
.replacement_text ()
1852 if (re
.search (r
"\\begin *{document}", str)
1853 and not re
.search ("{graphic[sx]", str)):
1854 str = re
.sub (r
"\\begin{document}",
1855 r
"\\usepackage{graphics}" + '\n'
1856 + r
"\\begin{document}",
1858 chunk
.override_text
= str
1863 # TEXINFO: '.texinfo',
1869 class CompileError(Exception):
1872 def snippet_list_checksum (snippets
):
1873 return hash (' '.join([l
.basename() for l
in snippets
]))
1875 def write_file_map (lys
, name
):
1876 snippet_map
= file (os
.path
.join (
1877 global_options
.lily_output_dir
,
1878 'snippet-map-%d.ly' % snippet_list_checksum (lys
)), 'w')
1880 snippet_map
.write ("""
1881 #(define version-seen #t)
1882 #(define output-empty-score-list #f)
1883 #(ly:add-file-name-alist '(%s
1885 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly
.basename (), name
)
1888 def split_output_files(directory
):
1889 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1891 Return value is a set of strings.
1894 for subdir
in glob
.glob (os
.path
.join (directory
, '[a-f0-9][a-f0-9]')):
1895 base_subdir
= os
.path
.split (subdir
)[1]
1896 sub_files
= [os
.path
.join (base_subdir
, name
)
1897 for name
in os
.listdir (subdir
)]
1901 def do_process_cmd (chunks
, input_name
, options
):
1902 snippets
= [c
for c
in chunks
if isinstance (c
, LilypondSnippet
)]
1904 output_files
= split_output_files (options
.lily_output_dir
)
1905 outdated
= [c
for c
in snippets
if c
.is_outdated (options
.lily_output_dir
, output_files
)]
1907 write_file_map (outdated
, input_name
)
1908 progress (_ ("Writing snippets..."))
1909 for snippet
in outdated
:
1914 progress (_ ("Processing..."))
1916 process_snippets (options
.process_cmd
, outdated
,
1917 options
.format
, options
.lily_output_dir
)
1920 progress (_ ("All snippets are up to date..."))
1922 if options
.lily_output_dir
!= options
.output_dir
:
1923 output_files
= split_output_files (options
.lily_output_dir
)
1924 for snippet
in snippets
:
1925 snippet
.link_all_output_files (options
.lily_output_dir
,
1933 # Format guessing data
1942 '.texinfo': TEXINFO
,
1947 def guess_format (input_filename
):
1949 e
= os
.path
.splitext (input_filename
)[1]
1952 format
= ext2format
[e
]
1954 error (_ ("cannot determine format for: %s"
1959 def write_if_updated (file_name
, lines
):
1961 f
= file (file_name
)
1963 new_str
= ''.join (lines
)
1964 if oldstr
== new_str
:
1965 progress (_ ("%s is up to date.") % file_name
)
1968 # this prevents make from always rerunning lilypond-book:
1969 # output file must be touched in order to be up to date
1970 os
.utime (file_name
, None)
1975 output_dir
= os
.path
.dirname (file_name
)
1976 if not os
.path
.exists (output_dir
):
1977 os
.makedirs (output_dir
)
1979 progress (_ ("Writing `%s'...") % file_name
)
1980 file (file_name
, 'w').writelines (lines
)
1984 def note_input_file (name
, inputs
=[]):
1985 ## hack: inputs is mutable!
1986 inputs
.append (name
)
1989 def samefile (f1
, f2
):
1991 return os
.path
.samefile (f1
, f2
)
1992 except AttributeError: # Windoze
1993 f1
= re
.sub ("//*", "/", f1
)
1994 f2
= re
.sub ("//*", "/", f2
)
1997 def do_file (input_filename
, included
=False):
1999 if not input_filename
or input_filename
== '-':
2000 in_handle
= sys
.stdin
2001 input_fullname
= '<stdin>'
2003 if os
.path
.exists (input_filename
):
2004 input_fullname
= input_filename
2005 elif global_options
.format
== LATEX
and ly
.search_exe_path ('kpsewhich'):
2006 input_fullname
= os
.popen ('kpsewhich ' + input_filename
).read()[:-1]
2008 input_fullname
= find_file (input_filename
)
2010 note_input_file (input_fullname
)
2011 in_handle
= file (input_fullname
)
2013 if input_filename
== '-':
2014 input_base
= 'stdin'
2016 input_base
= os
.path
.splitext (input_filename
)[0]
2018 input_base
= os
.path
.basename (
2019 os
.path
.splitext (input_filename
)[0])
2021 # don't complain when global_options.output_dir is existing
2022 if not global_options
.output_dir
:
2023 global_options
.output_dir
= os
.getcwd()
2025 global_options
.output_dir
= os
.path
.abspath(global_options
.output_dir
)
2027 if not os
.path
.isdir (global_options
.output_dir
):
2028 os
.mkdir (global_options
.output_dir
, 0777)
2029 os
.chdir (global_options
.output_dir
)
2031 output_filename
= os
.path
.join(global_options
.output_dir
,
2032 input_base
+ format2ext
[global_options
.format
])
2033 if (os
.path
.exists (input_filename
)
2034 and os
.path
.exists (output_filename
)
2035 and samefile (output_filename
, input_fullname
)):
2037 _ ("Output would overwrite input file; use --output."))
2041 progress (_ ("Reading %s...") % input_fullname
)
2042 source
= in_handle
.read ()
2045 set_default_options (source
, default_ly_options
, global_options
.format
)
2048 # FIXME: Containing blocks must be first, see
2049 # find_toplevel_snippets.
2051 'multiline_comment',
2055 'singleline_comment',
2061 progress (_ ("Dissecting..."))
2062 chunks
= find_toplevel_snippets (source
, global_options
.format
, snippet_types
)
2064 if global_options
.format
== LATEX
:
2066 if (c
.is_plain () and
2067 re
.search (r
"\\begin *{document}", c
.replacement_text())):
2072 if global_options
.filter_cmd
:
2073 write_if_updated (output_filename
,
2074 [c
.filter_text () for c
in chunks
])
2075 elif global_options
.process_cmd
:
2076 do_process_cmd (chunks
, input_fullname
, global_options
)
2077 progress (_ ("Compiling %s...") % output_filename
)
2079 write_if_updated (output_filename
,
2080 [s
.replacement_text ()
2083 def process_include (snippet
):
2084 os
.chdir (original_dir
)
2085 name
= snippet
.substring ('filename')
2086 progress (_ ("Processing include: %s") % name
)
2088 return do_file (name
, included
=True)
2090 include_chunks
= map (process_include
,
2091 filter (lambda x
: isinstance (x
, IncludeSnippet
),
2094 return chunks
+ reduce (lambda x
, y
: x
+ y
, include_chunks
, [])
2096 except CompileError
:
2097 os
.chdir (original_dir
)
2098 progress (_ ("Removing `%s'") % output_filename
)
2103 global global_options
2105 opt_parser
= get_option_parser()
2106 (global_options
, args
) = opt_parser
.parse_args ()
2107 if global_options
.format
in ('texi-html', 'texi'):
2108 global_options
.format
= TEXINFO
2110 global_options
.include_path
= map (os
.path
.abspath
, global_options
.include_path
)
2112 if global_options
.warranty
:
2115 if not args
or len (args
) > 1:
2116 opt_parser
.print_help ()
2122 # FIXME: 85 lines of `main' macramee??
2123 files
= do_options ()
2125 basename
= os
.path
.splitext (files
[0])[0]
2126 basename
= os
.path
.split (basename
)[1]
2128 if not global_options
.format
:
2129 global_options
.format
= guess_format (files
[0])
2132 if global_options
.format
in (TEXINFO
, HTML
, DOCBOOK
):
2135 if global_options
.process_cmd
== '':
2136 global_options
.process_cmd
= (lilypond_binary
2137 + ' --formats=%s -dbackend=eps ' % formats
)
2139 if global_options
.process_cmd
:
2140 includes
= global_options
.include_path
2141 if global_options
.lily_output_dir
:
2142 # This must be first, so lilypond prefers to read .ly
2143 # files in the other lybookdb dir.
2144 includes
= [os
.path
.abspath(global_options
.lily_output_dir
)] + includes
2145 global_options
.process_cmd
+= ' '.join ([' -I %s' % ly
.mkarg (p
)
2148 if global_options
.format
in (TEXINFO
, LATEX
):
2149 ## prevent PDF from being switched on by default.
2150 global_options
.process_cmd
+= ' --formats=eps '
2151 if global_options
.create_pdf
:
2152 global_options
.process_cmd
+= "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2154 if global_options
.verbose
:
2155 global_options
.process_cmd
+= " --verbose "
2157 if global_options
.padding_mm
:
2158 global_options
.process_cmd
+= " -deps-box-padding=%f " % global_options
.padding_mm
2160 global_options
.process_cmd
+= " -dread-file-list -dno-strip-output-dir"
2162 if global_options
.lily_output_dir
:
2163 global_options
.lily_output_dir
= os
.path
.abspath(global_options
.lily_output_dir
)
2164 if not os
.path
.isdir (global_options
.lily_output_dir
):
2165 os
.makedirs (global_options
.lily_output_dir
)
2167 global_options
.lily_output_dir
= os
.path
.abspath(global_options
.output_dir
)
2172 chunks
= do_file (files
[0])
2173 except CompileError
:
2176 inputs
= note_input_file ('')
2179 base_file_name
= os
.path
.splitext (os
.path
.basename (files
[0]))[0]
2180 dep_file
= os
.path
.join (global_options
.output_dir
, base_file_name
+ '.dep')
2181 final_output_file
= os
.path
.join (global_options
.output_dir
,
2183 + '.%s' % global_options
.format
)
2185 os
.chdir (original_dir
)
2186 file (dep_file
, 'w').write ('%s: %s'
2187 % (final_output_file
, ' '.join (inputs
)))
2189 if __name__
== '__main__':