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>
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.
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.
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.
19 from parser_tools import get_value, check_token, find_token,\
20 find_tokens, find_end_of, find_end_of_inset
28 version_lyx2lyx = "1.4.0cvs"
29 default_debug_level = 2
31 # Regular expressions used
32 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
33 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
34 original_version = re.compile(r"\#LyX (\S*)")
37 # file format information:
38 # file, supported formats, stable release versions
39 format_relation = [("0_10", [210], ["0.10.7","0.10"]),
40 ("0_12", [215], ["0.12","0.12.1","0.12"]),
41 ("1_0_0", [215], ["1.0.0","1.0"]),
42 ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
43 ("1_1_4", [215], ["1.1.4","1.1"]),
44 ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
45 ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
46 ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
47 ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
48 ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]),
49 ("1_4", range(223,241), ["1.4.0cvs","1.4"])]
53 " Returns a list with supported file formats."
55 for version in format_relation:
56 for format in version[1]:
57 if format not in formats:
58 formats.append(format)
63 " Returns the more recent file format available."
64 return format_relation[-1][1][-1]
67 def get_backend(textclass):
68 " For _textclass_ returns its backend."
69 if textclass == "linuxdoc" or textclass == "manpage":
71 if textclass[:7] == "docbook":
80 """This class carries all the information of the LyX file."""
81 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level):
83 end_format: final format that the file should be converted. (integer)
84 input: the name of the input source, if empty resort to standard input.
85 output: the name of the output file, if empty use the standard output.
86 error: the name of the error file, if empty use the standard error.
87 debug: debug level, O means no debug, as its value increases be more verbose.
89 if input and input != '-':
90 self.input = self.open(input)
92 self.input = sys.stdin
94 self.output = open(output, "w")
96 self.output = sys.stdout
99 self.err = open(error, "w")
101 self.err = sys.stderr
106 self.end_format = self.lyxformat(end_format)
108 self.end_format = get_end_format()
110 self.backend = "latex"
111 self.textclass = "article"
116 def warning(self, message, debug_level= default_debug_level):
117 " Emits warning to self.error, if the debug_level is less than the self.debug."
118 if debug_level <= self.debug:
119 self.err.write(message + "\n")
122 def error(self, message):
123 " Emits a warning and exist incondicionally."
124 self.warning(message)
125 self.warning("Quiting.")
130 """Reads a file into the self.header and self.body parts, from self.input."""
134 line = self.input.readline()
136 self.error("Invalid LyX file.")
139 # remove '\r' from line's end, if present
140 if line[-1:] == '\r':
143 if check_token(line, '\\begin_preamble'):
145 if check_token(line, '\\end_preamble'):
149 line = string.strip(line)
151 if not line and not preamble:
154 self.header.append(line)
157 line = self.input.readline()
160 # remove '\r' from line's end, if present
161 if line[-2:-1] == '\r':
162 self.body.append(line[:-2])
164 self.body.append(line[:-1])
166 self.textclass = get_value(self.header, "\\textclass", 0)
167 self.backend = get_backend(self.textclass)
168 self.format = self.read_format()
169 self.language = get_value(self.header, "\\language", 0)
170 if self.language == "":
171 self.language = "english"
172 self.initial_version = self.read_version()
176 " Writes the LyX file to self.output."
180 for line in self.header:
181 self.output.write(line+"\n")
182 self.output.write("\n")
183 for line in self.body:
184 self.output.write(line+"\n")
187 def open(self, file):
188 """Transparently deals with compressed files."""
190 self.dir = os.path.dirname(os.path.abspath(file))
192 gzip.open(file).readline()
193 self.output = gzip.GzipFile("","wb",6,self.output)
194 return gzip.open(file)
199 def lyxformat(self, format):
200 " Returns the file format representation, an integer."
201 result = format_re.match(format)
203 format = int(result.group(1) + result.group(2))
205 self.error(str(format) + ": " + "Invalid LyX file.")
207 if format in formats_list():
210 self.error(str(format) + ": " + "Format not supported.")
214 def read_version(self):
215 """ Searchs for clues of the LyX version used to write the file, returns the
216 most likely value, or None otherwise."""
217 for line in self.header:
221 result = original_version.match(line)
223 return result.group(1)
227 def set_version(self):
228 " Set the header with the version used."
229 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
230 if self.header[1][0] == '#':
234 def read_format(self):
235 " Read from the header the fileformat of the present LyX file."
236 for line in self.header:
237 result = fileformat.match(line)
239 return self.lyxformat(result.group(1))
241 self.error("Invalid LyX File.")
245 def set_format(self):
246 " Set the file format of the file, in the header."
247 if self.format <= 217:
248 format = str(float(self.format)/100)
250 format = str(self.format)
251 i = find_token(self.header, "\\lyxformat", 0)
252 self.header[i] = "\\lyxformat %s" % format
255 def set_parameter(self, param, value):
256 " Set the value of the header parameter."
257 i = find_token(self.header, '\\' + param, 0)
259 self.warning(3, 'Parameter not found in the header: %s' % param)
261 self.header[i] = '\\%s %s' % (param, str(value))
265 "Convert from current (self.format) to self.end_format."
266 mode, convertion_chain = self.chain()
267 self.warning("convertion chain: " + str(convertion_chain), 3)
269 for step in convertion_chain:
270 steps = getattr(__import__("lyx_" + step), mode)
272 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
274 self.error("The convertion to an older format (%s) is not implemented." % self.format)
276 multi_conv = len(steps) != 1
277 for version, table in steps:
279 (self.format >= version and mode == "convert") or\
280 (self.format <= version and mode == "revert"):
286 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
287 default_debug_level + 1)
289 self.format = version
290 if self.end_format == self.format:
295 """ This is where all the decisions related with the convertion are taken.
296 It returns a list of modules needed to convert the LyX file from
297 self.format to self.end_format"""
299 self.start = self.format
303 for rel in format_relation:
304 if self.initial_version in rel[2]:
306 initial_step = rel[0]
310 if not correct_version:
312 self.warning("Version does not match file format, discarding it.")
313 for rel in format_relation:
315 initial_step = rel[0]
318 # This should not happen, really.
319 self.error("Format not supported.")
321 # Find the final step
322 for rel in format_relation:
323 if self.end_format in rel[1]:
327 self.error("Format not supported.")
329 # Convertion mode, back or forth
331 if (initial_step, self.start) < (final_step, self.end_format):
334 for step in format_relation:
335 if initial_step <= step[0] <= final_step:
336 if first_step and len(step[1]) == 1:
339 steps.append(step[0])
342 relation_format = format_relation
343 relation_format.reverse()
346 for step in relation_format:
347 if final_step <= step[0] <= initial_step:
348 steps.append(step[0])
351 if last_step[1][-1] == self.end_format:
357 def get_toc(self, depth = 4):
358 " Returns the TOC of this LyX document."
359 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
360 allowed_insets = ['Quotes']
363 for section in paragraphs_filter.keys():
364 sections.append('\\begin_layout %s' % section)
369 i = find_tokens(self.body, sections, i)
373 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
375 self.warning('Incomplete file.', 0)
378 section = string.split(self.body[i])[1]
379 if section[-1] == '*':
380 section = section[:-1]
385 # skip paragraph parameters
386 while not self.body[k] or self.body[k][0] == '\\':
390 if check_token(self.body[k], '\\begin_inset'):
391 inset = string.split(self.body[k])[1]
392 end = find_end_of_inset(self.body, k)
393 if end == -1 or end > j:
394 self.warning('Malformed file.', 0)
396 if inset in allowed_insets:
397 par.extend(self.body[k: end+1])
400 par.append(self.body[k])
403 # trim empty lines in the end.
404 while string.strip(par[-1]) == '' and par:
407 toc_par.append(Paragraph(section, par))
414 class File(LyX_Base):
415 " This class reads existing LyX files."
416 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level):
417 LyX_Base.__init__(self, end_format, input, output, error, debug)
421 class NewFile(LyX_Base):
422 " This class is to create new LyX files."
423 def set_header(self, **params):
426 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
430 "\\textclass article",
431 "\\language english",
432 "\\inputencoding auto",
433 "\\fontscheme default",
434 "\\graphics default",
435 "\\paperfontsize default",
436 "\\papersize default",
437 "\\paperpackage none",
438 "\\use_geometry false",
440 "\\cite_engine basic",
441 "\\use_bibtopic false",
442 "\\paperorientation portrait",
445 "\\paragraph_separation indent",
447 "\\quotes_language english",
451 "\\paperpagestyle default",
452 "\\tracking_changes false",
455 self.format = get_end_format()
457 self.set_parameter(param, params[param])
460 def set_body(self, paragraphs):
461 self.body.extend(['\\begin_body',''])
463 for par in paragraphs:
464 self.body.extend(par.asLines())
466 self.body.extend(['','\\end_body', '\\end_document'])
470 # unfinished implementation, it is missing the Text and Insets representation.
471 " This class represents the LyX paragraphs."
472 def __init__(self, name, body=[], settings = [], child = []):
474 name: paragraph name.
475 body: list of lines of body text.
476 child: list of paragraphs that descend from this paragraph.
480 self.settings = settings
484 " Converts the paragraph to a list of strings, representing it in the LyX file."
485 result = ['','\\begin_layout %s' % self.name]
486 result.extend(self.settings)
488 result.extend(self.body)
489 result.append('\\end_layout')
494 result.append('\\begin_deeper')
495 for node in self.child:
496 result.extend(node.asLines())
497 result.append('\\end_deeper')
503 " This class represents the LyX insets."
508 " This class represents simple chuncks of text."