1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 from parser_tools import get_value, check_token, find_token,\
21 find_tokens, find_end_of
30 import lyx2lyx_version
31 version_lyx2lyx = lyx2lyx_version.version
32 except: # we are running from build directory so assume the last version
33 version_lyx2lyx = '1.6.0svn'
35 default_debug_level = 2
37 ####################################################################
38 # Private helper functions
40 def find_end_of_inset(lines, i):
41 " Find beginning of inset, where lines[i] is included."
42 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
44 def generate_minor_versions(major, last_minor_version):
45 """ Generate minor versions, using major as prefix and minor
46 versions from 0 until last_minor_version, plus the generic version.
50 generate_minor_versions("1.2", 4) ->
51 [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
53 return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
56 # End of helper functions
57 ####################################################################
60 # Regular expressions used
61 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
62 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
63 original_version = re.compile(r".*?LyX ([\d.]*)")
66 # file format information:
67 # file, supported formats, stable release versions
68 format_relation = [("0_06", [200], generate_minor_versions("0.6" , 4)),
69 ("0_08", [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
70 ("0_10", [210], generate_minor_versions("0.10", 7) + ["0.9"]),
71 ("0_12", [215], generate_minor_versions("0.12", 1) + ["0.11"]),
72 ("1_0", [215], generate_minor_versions("1.0" , 4)),
73 ("1_1", [215], generate_minor_versions("1.1" , 4)),
74 ("1_1_5", [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
75 ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
76 ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
77 ("1_2", [220], generate_minor_versions("1.2" , 4)),
78 ("1_3", [221], generate_minor_versions("1.3" , 7)),
79 ("1_4", range(222,246), generate_minor_versions("1.4" , 5)),
80 ("1_5", range(246,277), generate_minor_versions("1.5" , 1)),
81 ("1_6", range(277,283), generate_minor_versions("1.6" , 0))]
85 " Returns a list with supported file formats."
87 for version in format_relation:
88 for format in version[1]:
89 if format not in formats:
90 formats.append(format)
95 " Returns the more recent file format available."
96 return format_relation[-1][1][-1]
99 def get_backend(textclass):
100 " For _textclass_ returns its backend."
101 if textclass == "linuxdoc" or textclass == "manpage":
103 if textclass[:7] == "docbook":
109 " Remove end of line char(s)."
110 if line[-2:-1] == '\r':
116 def get_encoding(language, inputencoding, format, cjk_encoding):
119 # CJK-LyX encodes files using the current locale encoding.
120 # This means that files created by CJK-LyX can only be converted using
121 # the correct locale settings unless the encoding is given as commandline
123 if cjk_encoding == 'auto':
124 return locale.getpreferredencoding()
125 elif cjk_encoding != '':
127 from lyx2lyx_lang import lang
128 if inputencoding == "auto" or inputencoding == "default":
129 return lang[language][3]
130 if inputencoding == "":
132 # python does not know the alias latin9
133 if inputencoding == "latin9":
141 """This class carries all the information of the LyX file."""
143 def __init__(self, end_format = 0, input = "", output = "", error
144 = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
145 language = "english", encoding = "auto"):
148 end_format: final format that the file should be converted. (integer)
149 input: the name of the input source, if empty resort to standard input.
150 output: the name of the output file, if empty use the standard output.
151 error: the name of the error file, if empty use the standard error.
152 debug: debug level, O means no debug, as its value increases be more verbose.
154 self.choose_io(input, output)
157 self.err = open(error, "w")
159 self.err = sys.stderr
162 self.try_hard = try_hard
163 self.cjk_encoding = cjk_encoding
166 self.end_format = self.lyxformat(end_format)
168 self.end_format = get_end_format()
170 self.backend = "latex"
171 self.textclass = "article"
172 # This is a hack: We use '' since we don't know the default
173 # layout of the text class. LyX will parse it as default layout.
174 # FIXME: Read the layout file and use the real default layout
175 self.default_layout = ''
180 self.encoding = encoding
181 self.language = language
184 def warning(self, message, debug_level= default_debug_level):
185 " Emits warning to self.error, if the debug_level is less than the self.debug."
186 if debug_level <= self.debug:
187 self.err.write("Warning: " + message + "\n")
190 def error(self, message):
191 " Emits a warning and exits if not in try_hard mode."
192 self.warning(message)
193 if not self.try_hard:
194 self.warning("Quiting.")
201 """Reads a file into the self.header and self.body parts, from self.input."""
204 line = self.input.readline()
206 self.error("Invalid LyX file.")
208 line = trim_eol(line)
209 if check_token(line, '\\begin_preamble'):
211 line = self.input.readline()
213 self.error("Invalid LyX file.")
215 line = trim_eol(line)
216 if check_token(line, '\\end_preamble'):
219 if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
220 self.warning("Malformed LyX file: Missing '\\end_preamble'.")
221 self.warning("Adding it now and hoping for the best.")
223 self.preamble.append(line)
225 if check_token(line, '\\end_preamble'):
232 if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body", "\\begin_deeper"):
233 self.body.append(line)
236 self.header.append(line)
238 self.textclass = get_value(self.header, "\\textclass", 0)
239 self.backend = get_backend(self.textclass)
240 self.format = self.read_format()
241 self.language = get_value(self.header, "\\language", 0, default = "english")
242 self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
243 self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
244 self.initial_version = self.read_version()
246 # Second pass over header and preamble, now we know the file encoding
247 for i in range(len(self.header)):
248 self.header[i] = self.header[i].decode(self.encoding)
249 for i in range(len(self.preamble)):
250 self.preamble[i] = self.preamble[i].decode(self.encoding)
254 line = self.input.readline().decode(self.encoding)
257 self.body.append(trim_eol(line))
261 " Writes the LyX file to self.output."
265 if self.encoding == "auto":
266 self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
269 i = find_token(self.header, '\\textclass', 0) + 1
270 preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
272 self.error("Malformed LyX file: Missing '\\textclass'.")
274 header = self.header[:i] + preamble + self.header[i:]
278 for line in header + [''] + self.body:
279 self.output.write(line.encode(self.encoding)+"\n")
282 def choose_io(self, input, output):
283 """Choose input and output streams, dealing transparently with
287 self.output = open(output, "wb")
289 self.output = sys.stdout
291 if input and input != '-':
292 self.dir = os.path.dirname(os.path.abspath(input))
294 gzip.open(input).readline()
295 self.input = gzip.open(input)
296 self.output = gzip.GzipFile(mode="wb", fileobj=self.output)
298 self.input = open(input)
301 self.input = sys.stdin
304 def lyxformat(self, format):
305 " Returns the file format representation, an integer."
306 result = format_re.match(format)
308 format = int(result.group(1) + result.group(2))
312 self.error(str(format) + ": " + "Invalid LyX file.")
314 if format in formats_list():
317 self.error(str(format) + ": " + "Format not supported.")
321 def read_version(self):
322 """ Searchs for clues of the LyX version used to write the file, returns the
323 most likely value, or None otherwise."""
324 for line in self.header:
328 line = line.replace("fix",".")
329 result = original_version.match(line)
331 # Special know cases: reLyX and KLyX
332 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
335 res = result.group(1)
338 #self.warning("Version %s" % result.group(1))
340 self.warning(str(self.header[:2]))
344 def set_version(self):
345 " Set the header with the version used."
346 self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
347 if self.header[1][0] == '#':
351 def read_format(self):
352 " Read from the header the fileformat of the present LyX file."
353 for line in self.header:
354 result = fileformat.match(line)
356 return self.lyxformat(result.group(1))
358 self.error("Invalid LyX File.")
362 def set_format(self):
363 " Set the file format of the file, in the header."
364 if self.format <= 217:
365 format = str(float(self.format)/100)
367 format = str(self.format)
368 i = find_token(self.header, "\\lyxformat", 0)
369 self.header[i] = "\\lyxformat %s" % format
372 def set_textclass(self):
373 i = find_token(self.header, "\\textclass", 0)
374 self.header[i] = "\\textclass %s" % self.textclass
377 def set_parameter(self, param, value):
378 " Set the value of the header parameter."
379 i = find_token(self.header, '\\' + param, 0)
381 self.warning('Parameter not found in the header: %s' % param, 3)
383 self.header[i] = '\\%s %s' % (param, str(value))
386 def is_default_layout(self, layout):
387 " Check whether a layout is the default layout of this class."
388 # FIXME: Check against the real text class default layout
389 if layout == 'Standard' or layout == self.default_layout:
395 "Convert from current (self.format) to self.end_format."
396 mode, convertion_chain = self.chain()
397 self.warning("convertion chain: " + str(convertion_chain), 3)
399 for step in convertion_chain:
400 steps = getattr(__import__("lyx_" + step), mode)
402 self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
404 self.error("The convertion to an older format (%s) is not implemented." % self.format)
406 multi_conv = len(steps) != 1
407 for version, table in steps:
409 (self.format >= version and mode == "convert") or\
410 (self.format <= version and mode == "revert"):
418 self.warning("An error ocurred in %s, %s" % (version, str(conv)),
420 if not self.try_hard:
424 self.warning("%lf: Elapsed time on %s" % (time.time() - init_t, str(conv)),
425 default_debug_level + 1)
427 self.format = version
428 if self.end_format == self.format:
433 """ This is where all the decisions related with the convertion are taken.
434 It returns a list of modules needed to convert the LyX file from
435 self.format to self.end_format"""
437 self.start = self.format
441 for rel in format_relation:
442 if self.initial_version in rel[2]:
444 initial_step = rel[0]
448 if not correct_version:
450 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
451 for rel in format_relation:
453 initial_step = rel[0]
456 # This should not happen, really.
457 self.error("Format not supported.")
459 # Find the final step
460 for rel in format_relation:
461 if self.end_format in rel[1]:
465 self.error("Format not supported.")
467 # Convertion mode, back or forth
469 if (initial_step, self.start) < (final_step, self.end_format):
472 for step in format_relation:
473 if initial_step <= step[0] <= final_step:
474 if first_step and len(step[1]) == 1:
477 steps.append(step[0])
480 relation_format = format_relation[:]
481 relation_format.reverse()
484 for step in relation_format:
485 if final_step <= step[0] <= initial_step:
486 steps.append(step[0])
489 if last_step[1][-1] == self.end_format:
492 self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
496 def get_toc(self, depth = 4):
497 " Returns the TOC of this LyX document."
498 paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
499 allowed_insets = ['Quotes']
500 allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
503 for section in paragraphs_filter.keys():
504 sections.append('\\begin_layout %s' % section)
509 i = find_tokens(self.body, sections, i)
513 j = find_end_of(self.body, i + 1, '\\begin_layout', '\\end_layout')
515 self.warning('Incomplete file.', 0)
518 section = self.body[i].split()[1]
519 if section[-1] == '*':
520 section = section[:-1]
525 # skip paragraph parameters
526 while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
530 if check_token(self.body[k], '\\begin_inset'):
531 inset = self.body[k].split()[1]
532 end = find_end_of_inset(self.body, k)
533 if end == -1 or end > j:
534 self.warning('Malformed file.', 0)
536 if inset in allowed_insets:
537 par.extend(self.body[k: end+1])
540 par.append(self.body[k])
543 # trim empty lines in the end.
544 while par[-1].strip() == '' and par:
547 toc_par.append(Paragraph(section, par))
554 class File(LyX_Base):
555 " This class reads existing LyX files."
556 def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
557 LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
561 class NewFile(LyX_Base):
562 " This class is to create new LyX files."
563 def set_header(self, **params):
566 "#LyX xxxx created this file. For more info see http://www.lyx.org/",
570 "\\textclass article",
571 "\\language english",
572 "\\inputencoding auto",
573 "\\font_roman default",
574 "\\font_sans default",
575 "\\font_typewriter default",
576 "\\font_default_family default",
579 "\\font_sf_scale 100",
580 "\\font_tt_scale 100",
581 "\\graphics default",
582 "\\paperfontsize default",
583 "\\papersize default",
584 "\\use_geometry false",
586 "\\cite_engine basic",
587 "\\use_bibtopic false",
588 "\\paperorientation portrait",
591 "\\paragraph_separation indent",
593 "\\quotes_language english",
596 "\\paperpagestyle default",
597 "\\tracking_changes false",
600 self.format = get_end_format()
602 self.set_parameter(param, params[param])
605 def set_body(self, paragraphs):
606 self.body.extend(['\\begin_body',''])
608 for par in paragraphs:
609 self.body.extend(par.asLines())
611 self.body.extend(['','\\end_body', '\\end_document'])
615 # unfinished implementation, it is missing the Text and Insets representation.
616 " This class represents the LyX paragraphs."
617 def __init__(self, name, body=[], settings = [], child = []):
619 name: paragraph name.
620 body: list of lines of body text.
621 child: list of paragraphs that descend from this paragraph.
625 self.settings = settings
629 " Converts the paragraph to a list of strings, representing it in the LyX file."
630 result = ['','\\begin_layout %s' % self.name]
631 result.extend(self.settings)
633 result.extend(self.body)
634 result.append('\\end_layout')
639 result.append('\\begin_deeper')
640 for node in self.child:
641 result.extend(node.asLines())
642 result.append('\\end_deeper')
648 " This class represents the LyX insets."
653 " This class represents simple chuncks of text."