]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
simplify index (string drunkness corrected)
[lyx.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>, 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 from parser_tools import get_value, check_token, find_token
20 import os.path
21 import gzip
22 import sys
23 import re
24 import string
25
26 ##
27 # file format version
28 #
29 version = "1.4.0cvs"
30 default_debug_level = 2
31 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
32 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
33 original_version = re.compile(r"\#LyX (\S*)")
34 lst_ft = [210, 215, 216, 217, 218, 220, 221, 223, 224, 225, 226, 227, 228, 229, 
35           230, 231, 232, 233, 234, 235, 236]
36
37 format_relation = [("0_10",  [210], ["0.10.7","0.10"]),
38                    ("0_12",  [215], ["0.12","0.12.1","0.12"]),
39                    ("1_0_0", [215], ["1.0.0","1.0"]),
40                    ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
41                    ("1_1_4", [215], ["1.1.4","1.1"]),
42                    ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
43                    ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
44                    ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
45                    ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
46                    ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3"]),
47                    ("1_4", [223,224,225,226,227,228,229,230,231,232,233,234,235, 236], ["1.4.0cvs","1.4"])]
48
49
50 def get_end_format():
51     return format_relation[-1][1][-1]
52
53
54 def get_backend(textclass):
55     if textclass == "linuxdoc" or textclass == "manpage":
56         return "linuxdoc"
57     if textclass[:7] == "docbook":
58         return "docbook"
59     return "latex"
60
61
62 ##
63 # Class
64 #
65 class FileInfo:
66     """This class carries all the information of the LyX file."""
67     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level):
68         if input:
69             self.input = self.open(input)
70         else:
71             self.input = sys.stdin
72         if output:
73             self.output = open(output, "w")
74         else:
75             self.output = sys.stdout
76
77         if error:
78             self.err = open(error, "w")
79         else:
80             self.err = sys.stderr
81
82         self.debug = debug
83
84         if end_format:
85             self.end_format = self.lyxformat(end_format)
86         else:
87             self.end_format = get_end_format()
88
89         self.backend = "latex"
90         self.textclass = "article"
91         self.header = []
92         self.body = []
93         self.read()
94
95     def warning(self, message, debug_level= default_debug_level):
96         if debug_level <= self.debug:
97             self.err.write(message + "\n")
98
99     def error(self, message):
100         self.warning(message)
101         self.warning("Quiting.")
102         sys.exit(1)
103
104     def read(self):
105         """Reads a file into the self.header and self.body parts"""
106         preamble = 0
107
108         while 1:
109             line = self.input.readline()
110             if not line:
111                 self.error("Invalid LyX file.")
112
113             line = line[:-1]
114             # remove '\r' from line's end, if present
115             if line[-1:] == '\r':
116                 line = line[:-1]
117
118             if check_token(line, '\\begin_preamble'):
119                 preamble = 1
120             if check_token(line, '\\end_preamble'):
121                 preamble = 0
122
123             if not preamble:
124                 line = string.strip(line)
125
126             if not line and not preamble:
127                 break
128
129             self.header.append(line)
130
131         while 1:
132             line = self.input.readline()
133             if not line:
134                 break
135             # remove '\r' from line's end, if present
136             if line[-2:-1] == '\r':
137                 self.body.append(line[:-2])
138             else:
139                 self.body.append(line[:-1])
140
141         self.textclass = get_value(self.header, "\\textclass", 0)
142         self.backend = get_backend(self.textclass)
143         self.format  = self.read_format()
144         self.language = get_value(self.header, "\\language", 0)
145         if self.language == "":
146             self.language = "english"
147         self.initial_version = self.read_version()
148
149     def write(self):
150         self.set_version()
151         self.set_format()
152
153         for line in self.header:
154             self.output.write(line+"\n")
155         self.output.write("\n")
156         for line in self.body:
157             self.output.write(line+"\n")
158
159
160     def open(self, file):
161         """Transparently deals with compressed files."""
162
163         self.dir = os.path.dirname(os.path.abspath(file))
164         try:
165             gzip.open(file).readline()
166             self.output = gzip.GzipFile("","wb",6,self.output)
167             return gzip.open(file)
168         except:
169             return open(file)
170
171     def lyxformat(self, format):
172         result = format_re.match(format)
173         if result:
174             format = int(result.group(1) + result.group(2))
175         else:
176             self.error(str(format) + ": " + "Invalid LyX file.")
177
178         if format in lst_ft:
179             return format
180
181         self.error(str(format) + ": " + "Format not supported.")
182         return None
183
184     def read_version(self):
185         for line in self.header:
186             if line[0] != "#":
187                 return None
188
189             result = original_version.match(line)
190             if result:
191                 return result.group(1)
192         return None
193
194     def set_version(self):
195         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version
196         if self.header[1][0] == '#':
197             del self.header[1]
198
199     def read_format(self):
200         for line in self.header:
201             result = fileformat.match(line)
202             if result:
203                 return self.lyxformat(result.group(1))
204         else:
205             self.error("Invalid LyX File.")
206         return None
207
208
209     def set_format(self):
210         if int(self.format) <= 217:
211             format = str(float(format)/100)
212         else:
213             format = self.format
214         i = find_token(self.header, "\\lyxformat", 0)
215         self.header[i] = "\\lyxformat %s" % format
216
217
218     def chain(self):
219         """ This is where all the decisions related with the convertion are taken"""
220
221         self.start =  self.format
222         format = self.format
223         correct_version = 0
224
225         for rel in format_relation:
226             if self.initial_version in rel[2]:
227                 if format in rel[1]:
228                     initial_step = rel[0]
229                     correct_version = 1
230                     break
231
232         if not correct_version:
233             if format <= 215:
234                 self.warning("Version does not match file format, discarding it.")
235             for rel in format_relation:
236                 if format in rel[1]:
237                     initial_step = rel[0]
238                     break
239             else:
240                 # This should not happen, really.
241                 self.error("Format not supported.")
242
243         # Find the final step
244         for rel in format_relation:
245             if self.end_format in rel[1]:
246                 final_step = rel[0]
247                 break
248         else:
249             self.error("Format not supported.")
250
251         # Convertion mode, back or forth
252         steps = []
253         if (initial_step, self.start) < (final_step, self.end_format):
254             mode = "convert"
255             first_step = 1
256             for step in format_relation:
257                 if  initial_step <= step[0] <= final_step:
258                     if first_step and len(step[1]) == 1:
259                         first_step = 0
260                         continue
261                     steps.append(step[0])
262         else:
263             mode = "revert"
264             relation_format = format_relation
265             relation_format.reverse()
266             last_step = None
267
268             for step in relation_format:
269                 if  final_step <= step[0] <= initial_step:
270                     steps.append(step[0])
271                     last_step = step
272
273             if last_step[1][-1] == self.end_format:
274                 steps.pop()
275
276         return mode, steps