]> git.donarmstrong.com Git - lilypond.git/blobdiff - scripts/ly2dvi.py
patch::: 1.3.140.jcn3
[lilypond.git] / scripts / ly2dvi.py
index 42cf6cb29e153ea4a507e4f7ca8bb5ff87787f0c..1c93f63ceded422e4f1612bf2c1426fc0910511e 100644 (file)
@@ -1,9 +1,27 @@
 #!@PYTHON@
 # run lily, setup LaTeX input.
 
-""" TODO: --dependencies
+# Note: gettext work best if we use ' for docstrings and "
+# for gettextable strings
 
-"""
+'''
+TODO:
+
+  * check --dependencies
+
+  * move versatile taglines, 
+  
+     \header {
+        beginfooter=\mutopiaPD
+        endfooter=\tagline  -> 'lily was here <version>'
+     }
+
+  * head/header tagline/endfooter
+
+  * dvi from lilypond .tex output?  This is hairy, because we create dvi
+    from lilypond .tex *and* header output.
+
+'''
 
 
 import os
@@ -16,6 +34,12 @@ import __main__
 import operator
 import tempfile
 
+sys.path.append ('@datadir@/python')
+import gettext
+gettext.bindtextdomain ('lilypond', '@localedir@')
+gettext.textdomain('lilypond')
+_ = gettext.gettext
+
 
 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
          'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
@@ -27,8 +51,8 @@ extra_init = {
        'language' : [],
        'latexheaders' : [],
        'latexpackages' :  ['geometry'],
-       'papersizename' : [],
-       'pagenumber' : [],
+       'papersize' : [],
+       'pagenumber' : [1],
        'textheight' : [], 
        'linewidth' : [],
        'orientation' : []
@@ -56,42 +80,54 @@ if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
 postscript_p = 0
 
 option_definitions = [
-       ('', 'h', 'help', 'print help'),
-       ('KEY=VAL', 's', 'set', 'change global setting KEY to VAL'),    
-       ('', 'P', 'postscript', 'Generate PostScript output'),
-       ('', 'k', 'keep', 'Keep all output, and name the directory ly2dvi.dir'),
-       ('', '', 'no-lily', 'Don\'t run lilypond'),
-       ('', 'v', 'version', "Print version and copyright info"),
-       ('DIR', '', 'outdir', 'Dump all final output into DIR'),
-       ('', 'd', 'dependencies', 'Dump all final output into DIR'),
+       ('', 'h', 'help', _ ("this help")),
+       ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
+       ('', 'P', 'postscript', _ ("generate PostScript output")),
+       ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
+       ('', '', 'no-lily', _ ("don't run LilyPond")),
+       ('', 'v', 'version', _ ("print version number")),
+       ('', 'w', 'warranty', _ ("show warranty and copyright")),
+       ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
+       ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
        ]
 
-
-
-def identify():
+def identify ():
        sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
 
-def print_version ():
-       identify()
-       sys.stdout.write (r"""Copyright 1998--1999
+def warranty ():
+       identify ()
+       sys.stdout.write ('\n')
+       sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
+       sys.stdout.write ('\n')
+       sys.stdout.write ('  Han-Wen Nienhuys')
+       sys.stdout.write ('\n')
+       sys.stdout.write (_ (r'''
 Distributed under terms of the GNU General Public License. It comes with
-NO WARRANTY.""")
+NO WARRANTY.'''))
+       sys.stdout.write ('\n')
 
 
 
 def progress (s):
-       """Make the progress messages stand out between lilypond stuff"""
+       '''Make the progress messages stand out between lilypond stuff'''
+       # Why should they have to stand out?  Blend in would be nice too.
        sys.stderr.write ('*** ' + s+ '\n')
+
+def warning (s):
+       sys.stderr.write (_ ("warning: ") + s)
+       sys.stderr.write ('\n')
        
+               
 def error (s):
-       sys.stderr.write (s)
-       raise 'Exiting ... '
+       sys.stderr.write (_ ("error: ") + s)
+       sys.stderr.write ('\n')
+       raise _ ("Exiting ... ")
 
 
 def find_file (name):
-       """
+       '''
        Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
-       """
+       '''
        
        f = None
        nm = ''
@@ -104,17 +140,19 @@ def find_file (name):
                except IOError:
                        pass
        if f:
-               sys.stderr.write ("Reading `%s'\n" % nm)
+               sys.stderr.write (_ ("Reading `%s'") % nm)
+               sys.stderr.write ('\n');
                return (f.read (), nm)
        else:
-               error ("File not found `%s'\n" % name)
+               error (_ ("can't open file: `%s'" % name))
+               sys.stderr.write ('\n');
                return ('', '')
 
 
 
 
 def getopt_args (opts):
-       "Construct arguments (LONG, SHORT) for getopt from  list of options."
+       '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
        short = ''
        long = []
        for o in opts:
@@ -130,7 +168,7 @@ def getopt_args (opts):
        return (short, long)
 
 def option_help_str (o):
-       "Transform one option description (4-tuple ) into neatly formatted string"
+       '''Transform one option description (4-tuple ) into neatly formatted string'''
        sh = '  '       
        if o[1]:
                sh = '-%s' % o[1]
@@ -152,7 +190,7 @@ def option_help_str (o):
 
 
 def options_help_str (opts):
-       "Convert a list of options into a neatly formatted string"
+       '''Convert a list of options into a neatly formatted string'''
        w = 0
        strs =[]
        helps = []
@@ -168,22 +206,19 @@ def options_help_str (opts):
                str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
        return str
 
-def help():
-       sys.stdout.write("""Usage: lyvi [options] FILE\n
-Generate .dvi with LaTeX for lilypond
-Options:
-""")
+def help ():
+       sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
+       sys.stdout.write ('\n\n')
+       sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
+       sys.stdout.write ('\n\n')
+       sys.stdout.write (_ ("Options:"))
+       sys.stdout.write ('\n')
        sys.stdout.write (options_help_str (option_definitions))
-       sys.stdout.write (r"""Warning all output is written in the CURRENT directory
-
-
-
-Report bugs to bug-gnu-music@gnu.org.
-
-Written by
-Han-Wen Nienhuys <hanwen@cs.uu.nl>
-""")
-
+       sys.stdout.write ('\n\n')
+       warning (_ ("all output is written in the CURRENT directory"))
+       sys.stdout.write ('\n')
+       sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
+       sys.stdout.write ('\n')
        sys.exit (0)
 
 
@@ -194,7 +229,7 @@ def setup_temp ():
                temp_dir = tempfile.mktemp ('ly2dvi')
                
        try:
-               os.mkdir (temp_dir)
+               os.mkdir (temp_dir, 0777)
        except OSError:
                pass
                
@@ -210,16 +245,17 @@ def setup_temp ():
        os.environ['TFMFONTS'] =  original_dir + fp
 
        os.chdir (temp_dir)
-       progress ('Temp directory is `%s\'\n' % temp_dir) 
+       progress (_ ('Temp directory is `%s\'\n') % temp_dir) 
 
        
 def system (cmd, ignore_error = 0):
-       sys.stderr.write ("invoking `%s\'\n" % cmd)
+       sys.stderr.write (_ ("Invoking `%s\'") % cmd)
+       sys.stderr.write ('\n')
        st = os.system (cmd)
        if st:
-               msg =  ('Error command exited with value %d' % st)
+               msg =  ( _ ("error: ") + _ ("command exited with value %d") % st)
                if ignore_error:
-                       sys.stderr.write (msg + ' (ignored)\n')
+                       sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
                else:
                        error (msg)
 
@@ -227,7 +263,7 @@ def system (cmd, ignore_error = 0):
 
 def cleanup_temp ():
        if not keep_temp_dir:
-               progress ('Cleaning up `%s\'' % temp_dir)
+               progress (_ ('Cleaning up `%s\'') % temp_dir)
                system ('rm -rf %s' % temp_dir)
        
 
@@ -248,24 +284,26 @@ def set_setting (dict, key, val):
        try:
                val = string.atof (val)
        except ValueError:
+               #warning (_ ("invalid value: %s") % `val`)
                pass
 
        try:
                dict[key].append (val)
        except KeyError:
+               warning (_ ("no such setting: %s") % `key`)
                dict[key] = [val]
        
 
 def analyse_lilypond_output (filename, extra):
-       """Grep FILENAME for interesting stuff, and
-       put relevant info into EXTRA."""
+       '''Grep FILENAME for interesting stuff, and
+       put relevant info into EXTRA.'''
        filename = filename+'.tex'
-       progress ("Analyzing `%s'" % filename)
+       progress (_ ("Analyzing `%s'") % filename)
        s = open (filename).read ()
 
        # search only the first 10k
        s = s[:10240]
-       for x in ('textheight', 'linewidth', 'papersizename', 'orientation'):
+       for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
                m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
                if m:
                        set_setting (extra, x, m.group (1))
@@ -292,7 +330,7 @@ def find_tex_files (files, extra):
                x = 0
                while 1:
                        fname = os.path.basename (f)
-                       fname = os.path.splitext (fname)[0]
+                       fname = strip_ly_suffix (fname)
                        if x:
                                fname = fname + '-%d' % x
 
@@ -302,13 +340,20 @@ def find_tex_files (files, extra):
                        else:
                                break
 
-                       x = x +1 
+                       x = x + 1
+       if not x:
+               warning (_ ("no lilypond output found for %s") % `files`)
        return tfiles
 
 def one_latex_definition (defn, first):
-       s = ''
+       s = '\n'
        for (k,v) in defn[1].items ():
-               s = r"""\def\the%s{%s}""" % (k,open (v).read ())
+               val = open (v).read ()
+               if (string.strip (val)):
+                       s = s + r'''\def\lilypond%s{%s}''' % (k, val)
+               else:
+                       s = s + r'''\let\lilypond%s\relax''' % k
+               s = s + '\n'
 
        if first:
                s = s + '\\def\\mustmakelilypondtitle{}\n'
@@ -321,13 +366,13 @@ def one_latex_definition (defn, first):
 
 ly_paper_to_latexpaper =  {
        'a4' : 'a4paper',
-       
+       'letter' : 'letterpaper', 
 }
 
 def global_latex_definition (tfiles, extra):
-       """construct preamble from EXTRA,
+       '''construct preamble from EXTRA,
        dump lily output files after that, and return result.
-       """
+       '''
 
 
        s = ""
@@ -335,8 +380,13 @@ def global_latex_definition (tfiles, extra):
 
        paper = ''
 
-       if extra['papersizename']:
-               paper = '[%s]' % ly_paper_to_latexpaper[extra['papersizename'][0]]
+       if extra['papersize']:
+               try:
+                       paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
+               except:
+                       warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
+                       pass
+       
        s = s + '\\documentclass%s{article}\n' % paper
 
        if extra['language']:
@@ -355,37 +405,50 @@ def global_latex_definition (tfiles, extra):
        orientation = 'portrait'
        if extra['orientation']:
                orientation = extra['orientation'][0]
-       s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (extra['linewidth'][0], textheight, orientation)
 
-       s= s + r"""
-\usepackage[latin1]{inputenc} 
+       # set sane geometry width (a4-width) for linewidth = -1.
+       linewidth = extra['linewidth'][0]
+       if linewidth < 0:
+               linewidth = 597
+       s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
+
+       s = s + r'''
+\usepackage[latin1]{inputenc}
 \input{titledefs}
 \makeatletter
-\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
-"""
-       if extra['pagenumber'] and  extra['pagenumber'][-1]:
-               s = s + r"""
-               \renewcommand{\@oddhead}{\parbox{\textwidth}%%
-               {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%"""
+\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
+'''
+       
+       if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
+               s = s + r'''
+\renewcommand{\@oddhead}{\parbox{\textwidth}%
+    {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
+'''
        else:
-               s = s + '\\pagestyle{empty}'
-               
-       s = s + '\\begin{document}'
+               s = s + '\\pagestyle{empty}\n'
+
+       s = s + '\\makeatother\n'
+       s = s + '\\begin{document}\n'
+
 
        first = 1
        for t in tfiles:
                s = s + one_latex_definition (t, first)
                first = 0
-               
+
+       s = s + r'''
+\makeatletter
+\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
+\makeatother
+'''
        s = s + '\\end{document}'
 
        return s
 
 def do_files (fs, extra):
 
-       """process the list of filenames in FS, using standard settings in EXTRA.
-       """
+       '''process the list of filenames in FS, using standard settings in EXTRA.
+       '''
        if not no_lily:
                run_lilypond (fs)
 
@@ -402,11 +465,11 @@ def do_files (fs, extra):
        return latex_file + '.dvi'
 
 def generate_postscript (dvi_name, extra):
-       """Run dvips on DVI_NAME, optionally doing -t landscape"""
+       '''Run dvips on DVI_NAME, optionally doing -t landscape'''
 
        opts = ''
-       if extra['papersizename']:
-               opts = opts + ' -t %s' % extra['papersizename'][0]
+       if extra['papersize']:
+               opts = opts + ' -t %s' % extra['papersize'][0]
 
        if extra['orientation'] and extra['orientation'][0] == 'landscape':
                opts = opts + ' -t landscape'
@@ -436,7 +499,12 @@ def generate_dependency_file (depfile, outname):
        df.close ();
 
 (sh, long) = getopt_args (__main__.option_definitions)
-(options, files) = getopt.getopt(sys.argv[1:], sh, long)
+try:
+       (options, files) = getopt.getopt(sys.argv[1:], sh, long)
+except:
+       help ()
+       sys.exit (2)
+       
 for opt in options:    
        o = opt[0]
        a = opt[1]
@@ -462,6 +530,10 @@ for opt in options:
                track_dependencies_p = 1
        elif o == '--version' or o == '-v':
                identify ()
+               sys.exit (0)
+       elif o == '--warranty' or o == '-w':
+               warranty ()
+               sys.exit (0)
                
                
 include_path = map (os.path.abspath, include_path)
@@ -502,6 +574,8 @@ if files:
                type = 'DVI'
 
        dest = os.path.join (outdir, dest)
+       if outdir != '.':
+               system ('mkdir -p %s' % outdir)
        system ('cp \"%s\" \"%s\"' % (srcname, dest ))
        system ('cp *.midi %s' % outdir, ignore_error = 1)
 
@@ -510,11 +584,12 @@ if files:
        if track_dependencies_p:
                generate_dependency_file (depfile, dest)
 
+       os.chdir (original_dir)
        cleanup_temp ()
 
        # most insteresting info last
-       progress ("Dependency file left in `%s'" % depfile)
-       progress ("%s file left in `%s'" % (type, dest))
+       progress (_ ("dependencies output to %s...") % depfile)
+       progress (_ ("%s file left in `%s'") % (type, dest))