]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/lyx2lyx
Declare encoding for python >= 2.3
[features.git] / lib / lyx2lyx / lyx2lyx
1 #! /usr/bin/env python
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002 José Matos <jamatos@lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program 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.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 import getopt, sys, string, re
20 from error import error, warning
21 from parser_tools import set_comment, set_format, check_token
22 import gzip
23
24 version = "1.4.0cvs"
25
26 # Allow the dummy object to be able to carry related data
27 # like a C struct
28 class struct:
29     pass
30
31 # options object, with default values
32 opt = struct()
33
34 opt.output = sys.stdout
35 opt.input = sys.stdin
36 opt.start = None
37 opt.end = None
38 opt.quiet = 0
39
40 format = re.compile(r"(\d)[\.,]?(\d\d)")
41 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
42 lst_ft = ["210", "215", "216", "217", "218", "220", "221", "223", "224", "225"]
43
44 def usage():
45     print """Usage: lyx2lyx [options] [file]
46 Convert old lyx file <file> to newer format, files can be compressed with gzip.
47 If there no file is specified then the standard input is assumed, in this case
48 gziped files are not handled.
49 Options:
50     -h, --help                  this information
51     -v, --version               output version information and exit
52     -l, --list                  list all available formats
53     -d, --debug level           level=0..2 (O_ no debug information,2_verbose)
54                                 default: level=1
55     -f, --from version          initial version (optional)
56     -t, --to version            final version (optional)
57     -o, --output name           name of the output file or else goes to stdout
58     -q, --quiet                 same as --debug=0"""
59
60
61 def parse_options(argv):
62     _options =  ["help", "version", "list", "debug=", "from=", "to=", "output=", "quiet"]
63     try:
64        opts, args = getopt.getopt(argv[1:], "d:f:hlo:qt:v", _options)
65     except getopt.error:
66         usage()
67         sys.exit(2)
68
69     for o, a in opts:
70         if o in ("-h", "--help"):
71             usage()
72             sys.exit()
73         if o in ("-v", "--version"):
74             print "lyxconvert, version %s" %(version)
75             print "Copyright (C) 2002-2003 José Matos and Dekel Tsur"
76             sys.exit()
77         if o in ("-d", "--debug"):
78             opt.debug = int(a)
79         if o in ("-q", "--quiet"):
80             opt.debug = 0
81         if o in ("-l", "--list"):
82             print lst_ft
83             sys.exit()
84         if o in ("-o", "--output"):
85             opt.output = open(a, "w")
86         if o in ("-f", "--from"):
87             opt.start = lyxformat(a)
88         if o in ("-t", "--to"):
89             opt.end = lyxformat(a)
90
91     if not opt.end:
92         opt.end = lst_ft[len(lst_ft)-1]
93
94     if opt.start and opt.start == opt.end:
95         sys.stderr.write(error.same_format)
96         sys.exit()
97
98     if opt.start > opt.end:
99         sys.stderr.write(error.newer_format)
100         sys.exit(1)
101
102     if args:
103         file = args[0]
104         try:
105             gzip.open(file).readline()
106             opt.output = gzip.GzipFile("","wb",6,opt.output)
107             opt.input = gzip.open(file)
108         except:
109             opt.input = open(file)
110
111 def lyxformat(fmt):
112     result = format.match(fmt)
113     if result:
114         fmt = result.group(1)+result.group(2)
115     else:
116         sys.stderr.write(fmt + ": " + error.invalid_format)
117         sys.exit(2)
118
119     if fmt in lst_ft:
120         return fmt
121
122     x = int(fmt)
123     if x < int(lst_ft[-1]) and x > int(lst_ft[-2]):
124         sys.stderr.write("lyx2lyx: A development version file.\n")
125         return lst_ft[-2]
126
127     sys.stderr.write(fmt + ": " + error.format_not_supported)
128     sys.exit(1)
129
130 def read_file(file, header, body):
131     """Reads a file into the header and body parts"""
132     fmt = None
133     preamble = 0
134
135     while 1:
136         line = file.readline()
137         if not line:
138             sys.stderr.write(error.invalid_file)
139             sys.exit(3)
140
141         line = line[:-1]
142         if check_token(line, '\\begin_preamble'):
143             preamble = 1
144         if check_token(line, '\\end_preamble'):
145             preamble = 0
146
147         if not preamble:
148             line = string.strip(line)
149
150         if not line and not preamble:
151             break
152
153         header.append(line)
154         result = fileformat.match(line)
155         if result:
156             fmt = lyxformat(result.group(1))
157
158     while 1:
159         line = file.readline()
160         if not line:
161             break
162         body.append(line[:-1])
163
164     if not fmt:
165         sys.stderr.write(error.invalid_file)
166         sys.exit(3)
167     return fmt
168
169 def write_file(file, header, body):
170     for line in header:
171         file.write(line+"\n")
172     file.write("\n")
173     for line in body:
174         file.write(line+"\n")
175
176 def main(argv):
177     parse_options(argv)
178
179     header, body = [], []
180     fmt =  read_file(opt.input, header, body)
181
182     if opt.start:
183         if opt.start != fmt:
184             sys.stderr.write("%s: %s %s\n" % (warning.dont_match, opt.start, fmt))
185     else:
186         opt.start = fmt
187
188     # Convertion chain
189     start = lst_ft.index(opt.start)
190     end = lst_ft.index(opt.end)
191
192     for fmt in lst_ft[start:end]:
193         __import__("lyxconvert_" + fmt).convert(header,body)
194
195     set_comment(header, version)
196     set_format(header, opt.end)
197     write_file(opt.output, header, body)
198     
199 if __name__ == "__main__":
200     main(sys.argv)