]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
Improve readability of the lyx2lyx help output.
[lyx.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2018 The LyX Team
4 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
5 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License
9 # as published by the Free Software Foundation; either version 2
10 # of the License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20
21 " The LyX module has all the rules related with different lyx file formats."
22
23 from parser_tools import get_value, check_token, find_token, \
24      find_tokens, find_end_of
25 import os.path
26 import gzip
27 import locale
28 import sys
29 import re
30 import time
31 import io
32 import codecs
33
34 try:
35     import lyx2lyx_version
36     version__ = lyx2lyx_version.version
37     stable_version = True
38 except: # we are running from build directory so assume the last version
39     version__ = '2.4'
40     stable_version = False
41
42 default_debug__ = 2
43
44 # Provide support for both python 2 and 3
45 PY2 = sys.version_info[0] == 2
46 # End of code to support for both python 2 and 3
47
48 ####################################################################
49 # Private helper functions
50
51 def find_end_of_inset(lines, i):
52     " Find beginning of inset, where lines[i] is included."
53     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
54
55 def minor_versions(major, last_minor_version):
56     """ Generate minor versions, using major as prefix and minor
57     versions from 0 until last_minor_version, plus the generic version.
58
59     Example:
60
61       minor_versions("1.2", 4) ->
62       [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
63     """
64     return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
65
66
67 # End of helper functions
68 ####################################################################
69
70
71 # Regular expressions used
72 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
73 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
74 original_version = re.compile(r".*?LyX ([\d.]*)")
75 original_tex2lyx_version = re.compile(r".*?tex2lyx ([\d.]*)")
76
77 ##
78 # file format information:
79 #  file, supported formats, stable release versions
80 format_relation = [("0_06",    [200], minor_versions("0.6" , 4)),
81                    ("0_08",    [210], minor_versions("0.8" , 6) + ["0.7"]),
82                    ("0_10",    [210], minor_versions("0.10", 7) + ["0.9"]),
83                    ("0_12",    [215], minor_versions("0.12", 1) + ["0.11"]),
84                    ("1_0",     [215], minor_versions("1.0" , 4)),
85                    ("1_1",     [215], minor_versions("1.1" , 4)),
86                    ("1_1_5",   [216], ["1.1", "1.1.5","1.1.5.1","1.1.5.2"]),
87                    ("1_1_6_0", [217], ["1.1", "1.1.6","1.1.6.1","1.1.6.2"]),
88                    ("1_1_6_3", [218], ["1.1", "1.1.6.3","1.1.6.4"]),
89                    ("1_2",     [220], minor_versions("1.2" , 4)),
90                    ("1_3",     [221], minor_versions("1.3" , 7)),
91                    # Note that range(i,j) is up to j *excluded*.
92                    ("1_4", list(range(222,246)), minor_versions("1.4" , 5)),
93                    ("1_5", list(range(246,277)), minor_versions("1.5" , 7)),
94                    ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
95                    ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
96                    ("2_1", list(range(414,475)), minor_versions("2.1" , 5)),
97                    ("2_2", list(range(475,509)), minor_versions("2.2" , 4)),
98                    ("2_3", list(range(509,545)), minor_versions("2.3" , 0)),
99                    ("2_4", (), minor_versions("2.4" , 0))
100                   ]
101
102 ####################################################################
103 # This is useful just for development versions                     #
104 # if the list of supported formats is empty get it from last step  #
105 if not format_relation[-1][1]:
106     step, mode = format_relation[-1][0], "convert"
107     convert = getattr(__import__("lyx_" + step), mode)
108     format_relation[-1] = (step,
109                            [conv[0] for conv in convert],
110                            format_relation[-1][2])
111 #                                                                  #
112 ####################################################################
113
114 def formats_list():
115     " Returns a list with supported file formats."
116     formats = []
117     for version in format_relation:
118         for format in version[1]:
119             if format not in formats:
120                 formats.append(format)
121     return formats
122
123
124 def format_info():
125     " Returns a list with the supported file formats."
126     template = """
127 %s\tstable format:       %s
128   \tstable versions:     %s
129   \tdevelopment formats: %s
130 """
131
132     out = "version: formats and versions"
133     for version in format_relation:
134         major = str(version[2][0])
135         versions = str(version[2][1:])
136         if len(version[1]) == 1:
137             formats = str(version[1][0])
138             stable_format = str(version[1][0])
139         elif not stable_version and major == version__:
140             stable_format = "-- not yet --"
141             versions = "-- not yet --"
142             formats = "%s - %s" % (version[1][0], version[1][-1])
143         else:
144             formats = "%s - %s" % (version[1][0], version[1][-2])
145             stable_format = str(version[1][-1])
146
147         out += template % (major, stable_format, versions, formats)
148     return out + '\n'
149
150
151 def get_end_format():
152     " Returns the more recent file format available."
153     # this check will fail only when we have a new version
154     # and there is no format change yet.
155     if format_relation[-1][1]:
156       return format_relation[-1][1][-1]
157     return format_relation[-2][1][-1]
158
159
160 def get_backend(textclass):
161     " For _textclass_ returns its backend."
162     if textclass == "linuxdoc" or textclass == "manpage":
163         return "linuxdoc"
164     if textclass.startswith("docbook") or textclass.startswith("agu-"):
165         return "docbook"
166     return "latex"
167
168
169 def trim_eol(line):
170     " Remove end of line char(s)."
171     if line[-1] != '\n' and line[-1] != '\r':
172         # May happen for the last line of a document
173         return line
174     if line[-2:-1] == '\r':
175         return line[:-2]
176     else:
177         return line[:-1]
178
179
180 def trim_eol_binary(line):
181     " Remove end of line char(s)."
182     if line[-1] != 10 and line[-1] != 13:
183         # May happen for the last line of a document
184         return line
185     if line[-2:-1] == 13:
186         return line[:-2]
187     else:
188         return line[:-1]
189
190
191 def get_encoding(language, inputencoding, format, cjk_encoding):
192     " Returns enconding of the lyx file"
193     if format > 248:
194         return "utf8"
195     # CJK-LyX encodes files using the current locale encoding.
196     # This means that files created by CJK-LyX can only be converted using
197     # the correct locale settings unless the encoding is given as commandline
198     # argument.
199     if cjk_encoding == 'auto':
200         return locale.getpreferredencoding()
201     elif cjk_encoding:
202         return cjk_encoding
203     from lyx2lyx_lang import lang
204     if inputencoding == "auto" or inputencoding == "default":
205         return lang[language][3]
206     if inputencoding == "":
207         return "latin1"
208     if inputencoding == "utf8x":
209         return "utf8"
210     # python does not know the alias latin9
211     if inputencoding == "latin9":
212         return "iso-8859-15"
213     return inputencoding
214
215 ##
216 # Class
217 #
218 class LyX_base:
219     """This class carries all the information of the LyX file."""
220
221     def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
222                  debug = default_debug__, try_hard = 0, cjk_encoding = u'',
223                  final_version = u'', systemlyxdir = u'', language = u'english',
224                  encoding = u'auto'):
225
226         """Arguments:
227         end_format: final format that the file should be converted. (integer)
228         input: the name of the input source, if empty resort to standard input.
229         output: the name of the output file, if empty use the standard output.
230         error: the name of the error file, if empty use the standard error.
231         debug: debug level, O means no debug, as its value increases be more verbose.
232         """
233         self.choose_input(input)
234         self.output = output
235
236         if error:
237             self.err = open(error, "w")
238         else:
239             self.err = sys.stderr
240
241         self.debug = debug
242         self.try_hard = try_hard
243         self.cjk_encoding = cjk_encoding
244
245         if end_format:
246             self.end_format = self.lyxformat(end_format)
247
248             # In case the target version and format are both specified
249             # verify that they are compatible. If not send a warning
250             # and ignore the version.
251             if final_version:
252                 message = "Incompatible version %s for specified format %d" % (
253                     final_version, self.end_format)
254                 for version in format_relation:
255                     if self.end_format in version[1]:
256                         if final_version not in version[2]:
257                             self.warning(message)
258                             final_version = ""
259         elif final_version:
260             for version in format_relation:
261                 if final_version in version[2]:
262                     # set the last format for that version
263                     self.end_format = version[1][-1]
264                     break
265             else:
266                 final_version = ""
267         else:
268             self.end_format = get_end_format()
269
270         if not final_version:
271             for step in format_relation:
272                 if self.end_format in step[1]:
273                     final_version = step[2][1]
274         self.final_version = final_version
275         self.warning("Final version: %s" % self.final_version, 10)
276         self.warning("Final format: %d" % self.end_format, 10)
277
278         self.backend = "latex"
279         self.textclass = "article"
280         # This is a hack: We use '' since we don't know the default
281         # layout of the text class. LyX will parse it as default layout.
282         # FIXME: Read the layout file and use the real default layout
283         self.default_layout = ''
284         self.header = []
285         self.preamble = []
286         self.body = []
287         self.status = 0
288         self.encoding = encoding
289         self.language = language
290         self.systemlyxdir = systemlyxdir
291
292
293     def warning(self, message, debug_level= default_debug__):
294         """ Emits warning to self.error, if the debug_level is less
295         than the self.debug."""
296         if debug_level <= self.debug:
297             self.err.write("Warning: " + message + "\n")
298
299
300     def error(self, message):
301         " Emits a warning and exits if not in try_hard mode."
302         self.warning(message)
303         if not self.try_hard:
304             self.warning("Quitting.")
305             sys.exit(1)
306
307         self.status = 2
308
309
310     def read(self):
311         """Reads a file into the self.header and
312         self.body parts, from self.input."""
313
314         # First pass: Read header to determine file encoding
315         # If we are running under python3 then all strings are binary in this
316         # pass. In some cases we need to convert binary to unicode in order to
317         # use our parser tools. Since we do not know the true encoding yet we
318         # use latin1. This works since a) the parts we are interested in are
319         # pure ASCII (subset of latin1) and b) in contrast to pure ascii or
320         # utf8, one can decode any 8byte string using latin1.
321         first_line = True
322         while True:
323             line = self.input.readline()
324             if not line:
325                 # eof found before end of header
326                 self.error("Invalid LyX file: Missing body.")
327
328             if first_line:
329                 # Remove UTF8 BOM marker if present
330                 if line.startswith(codecs.BOM_UTF8):
331                     line = line[len(codecs.BOM_UTF8):]
332
333                 first_line = False
334
335             if PY2:
336                 line = trim_eol(line)
337                 decoded = line
338             else:
339                 line = trim_eol_binary(line)
340                 decoded = line.decode('latin1')
341             if check_token(decoded, '\\begin_preamble'):
342                 while True:
343                     line = self.input.readline()
344                     if not line:
345                         # eof found before end of header
346                         self.error("Invalid LyX file: Missing body.")
347
348                     if PY2:
349                         line = trim_eol(line)
350                         decoded = line
351                     else:
352                         line = trim_eol_binary(line)
353                         decoded = line.decode('latin1')
354                     if check_token(decoded, '\\end_preamble'):
355                         break
356
357                     if decoded.split()[:0] in ("\\layout",
358                                             "\\begin_layout", "\\begin_body"):
359
360                         self.warning("Malformed LyX file:"
361                                      "Missing '\\end_preamble'."
362                                      "\nAdding it now and hoping"
363                                      "for the best.")
364
365                     self.preamble.append(line)
366
367             if check_token(decoded, '\\end_preamble'):
368                 continue
369
370             line = line.rstrip()
371             if not line:
372                 continue
373
374             if decoded.split()[0] in ("\\layout", "\\begin_layout",
375                                    "\\begin_body", "\\begin_deeper"):
376                 self.body.append(line)
377                 break
378
379             self.header.append(line)
380
381         if PY2:
382             i = find_token(self.header, '\\textclass', 0)
383         else:
384             i = find_token(self.header, b'\\textclass', 0)
385         if i == -1:
386             self.warning("Malformed LyX file: Missing '\\textclass'.")
387             if PY2:
388                 i = find_token(self.header, '\\lyxformat', 0) + 1
389                 self.header[i:i] = ['\\textclass article']
390             else:
391                 i = find_token(self.header, b'\\lyxformat', 0) + 1
392                 self.header[i:i] = [b'\\textclass article']
393
394         if PY2:
395             self.textclass = get_value(self.header, "\\textclass", 0,
396                                        default = "")
397             self.language = get_value(self.header, "\\language", 0,
398                                       default = "english")
399             self.inputencoding = get_value(self.header, "\\inputencoding", 0,
400                                            default = "auto")
401         else:
402             self.textclass = get_value(self.header, b"\\textclass", 0,
403                                        default = b"")
404             self.language = get_value(self.header, b"\\language", 0,
405                                       default = b"english").decode('ascii')
406             self.inputencoding = get_value(self.header, b"\\inputencoding", 0,
407                                            default = b"auto").decode('ascii')
408         self.format = self.read_format()
409         self.initial_format = self.format
410         self.encoding = get_encoding(self.language,
411                                      self.inputencoding, self.format,
412                                      self.cjk_encoding)
413         self.initial_version = self.read_version()
414
415         # Second pass over header and preamble, now we know the file encoding
416         # Do not forget the textclass (Debian bug #700828)
417         self.textclass = self.textclass.decode(self.encoding)
418         self.backend = get_backend(self.textclass)
419         for i in range(len(self.header)):
420             self.header[i] = self.header[i].decode(self.encoding)
421         for i in range(len(self.preamble)):
422             self.preamble[i] = self.preamble[i].decode(self.encoding)
423         for i in range(len(self.body)):
424             self.body[i] = self.body[i].decode(self.encoding)
425
426         # Read document body
427         while True:
428             line = self.input.readline().decode(self.encoding)
429             if not line:
430                 break
431             self.body.append(trim_eol(line))
432
433
434     def write(self):
435         " Writes the LyX file to self.output."
436         self.choose_output(self.output)
437         self.set_version()
438         self.set_format()
439         self.set_textclass()
440         if self.encoding == "auto":
441             self.encoding = get_encoding(self.language, self.encoding,
442                                          self.format, self.cjk_encoding)
443         if self.preamble:
444             i = find_token(self.header, '\\textclass', 0) + 1
445             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
446             header = self.header[:i] + preamble + self.header[i:]
447         else:
448             header = self.header
449
450         for line in header + [u''] + self.body:
451             self.output.write(line+u'\n')
452
453
454     def choose_output(self, output):
455         """Choose output streams dealing transparently with
456         compressed files."""
457
458         # This is a bit complicated, because we need to be compatible both with
459         # python 2 and python 3. Therefore we handle the encoding here and not
460         # when writing individual lines and may need up to 3 layered file like
461         # interfaces.
462         if self.compressed:
463             if output:
464                 outputfileobj = open(output, 'wb')
465             else:
466                 # We cannot not use stdout directly since it needs text, not bytes in python 3
467                 outputfileobj = os.fdopen(sys.stdout.fileno(), 'wb')
468             # We cannot not use gzip.open() since it is not supported by python 2
469             zipbuffer = gzip.GzipFile(mode='wb', fileobj=outputfileobj)
470             # We do not want to use different newlines on different OSes inside zipped files
471             self.output = io.TextIOWrapper(zipbuffer, encoding=self.encoding, newline='\n')
472         else:
473             if output:
474                 self.output = io.open(output, 'w', encoding=self.encoding)
475             else:
476                 self.output = io.open(sys.stdout.fileno(), 'w', encoding=self.encoding)
477
478
479     def choose_input(self, input):
480         """Choose input stream, dealing transparently with
481         compressed files."""
482
483         # Since we do not know the encoding yet we need to read the input as
484         # bytes in binary mode, and convert later to unicode.
485         if input and input != u'-':
486             self.dir = os.path.dirname(os.path.abspath(input))
487             try:
488                 gzip.open(input).readline()
489                 self.input = gzip.open(input)
490                 self.compressed = True
491             except:
492                 self.input = open(input, 'rb')
493                 self.compressed = False
494         else:
495             self.dir = u''
496             self.input = os.fdopen(sys.stdin.fileno(), 'rb')
497             self.compressed = False
498
499
500     def lyxformat(self, format):
501         " Returns the file format representation, an integer."
502         result = format_re.match(format)
503         if result:
504             format = int(result.group(1) + result.group(2))
505         elif format == '2':
506             format = 200
507         else:
508             self.error(str(format) + ": " + "Invalid LyX file.")
509
510         if format in formats_list():
511             return format
512
513         self.error(str(format) + ": " + "Format not supported.")
514         return None
515
516
517     def read_version(self):
518         """ Searchs for clues of the LyX version used to write the
519         file, returns the most likely value, or None otherwise."""
520
521         for line in self.header:
522             if line[0] != "#":
523                 return None
524
525             line = line.replace("fix",".")
526             # need to test original_tex2lyx_version first because tex2lyx
527             # writes "#LyX file created by tex2lyx 2.2"
528             result = original_tex2lyx_version.match(line)
529             if not result:
530                 result = original_version.match(line)
531                 if result:
532                     # Special know cases: reLyX and KLyX
533                     if line.find("reLyX") != -1 or line.find("KLyX") != -1:
534                         return "0.12"
535             if result:
536                 res = result.group(1)
537                 if not res:
538                     self.warning(line)
539                 #self.warning("Version %s" % result.group(1))
540                 return res
541         self.warning(str(self.header[:2]))
542         return None
543
544
545     def set_version(self):
546         " Set the header with the version used."
547
548         initial_comment = " ".join(["#LyX %s created this file." % version__,
549                                     "For more info see https://www.lyx.org/"])
550
551         # Simple heuristic to determine the comment that always starts
552         # a lyx file
553         if self.header[0].startswith("#"):
554             self.header[0] = initial_comment
555         else:
556             self.header.insert(0, initial_comment)
557
558         # Old lyx files had a two lines comment header:
559         # 1) the first line had the user who had created it
560         # 2) the second line had the lyx version used
561         # later we decided that 1) was a privacy risk for no gain
562         # here we remove the second line effectively erasing 1)
563         if self.header[1][0] == '#':
564             del self.header[1]
565
566
567     def read_format(self):
568         " Read from the header the fileformat of the present LyX file."
569         for line in self.header:
570             if PY2:
571                 result = fileformat.match(line)
572             else:
573                 result = fileformat.match(line.decode('ascii'))
574             if result:
575                 return self.lyxformat(result.group(1))
576         else:
577             self.error("Invalid LyX File: Missing format.")
578         return None
579
580
581     def set_format(self):
582         " Set the file format of the file, in the header."
583         if self.format <= 217:
584             format = str(float(self.format)/100)
585         else:
586             format = str(self.format)
587         i = find_token(self.header, "\\lyxformat", 0)
588         self.header[i] = "\\lyxformat %s" % format
589
590
591     def set_textclass(self):
592         i = find_token(self.header, "\\textclass", 0)
593         self.header[i] = "\\textclass %s" % self.textclass
594
595
596     #Note that the module will be added at the END of the extant ones
597     def add_module(self, module):
598       i = find_token(self.header, "\\begin_modules", 0)
599       if i == -1:
600         #No modules yet included
601         i = find_token(self.header, "\\textclass", 0)
602         if i == -1:
603           self.warning("Malformed LyX document: No \\textclass!!")
604           return
605         modinfo = ["\\begin_modules", module, "\\end_modules"]
606         self.header[i + 1: i + 1] = modinfo
607         return
608       j = find_token(self.header, "\\end_modules", i)
609       if j == -1:
610         self.warning("(add_module)Malformed LyX document: No \\end_modules.")
611         return
612       k = find_token(self.header, module, i)
613       if k != -1 and k < j:
614         return
615       self.header.insert(j, module)
616
617
618     def get_module_list(self):
619       i = find_token(self.header, "\\begin_modules", 0)
620       if (i == -1):
621         return []
622       j = find_token(self.header, "\\end_modules", i)
623       return self.header[i + 1 : j]
624
625
626     def set_module_list(self, mlist):
627       modbegin = find_token(self.header, "\\begin_modules", 0)
628       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
629       if (modbegin == -1):
630         #No modules yet included
631         tclass = find_token(self.header, "\\textclass", 0)
632         if tclass == -1:
633           self.warning("Malformed LyX document: No \\textclass!!")
634           return
635         modbegin = tclass + 1
636         self.header[modbegin:modbegin] = newmodlist
637         return
638       modend = find_token(self.header, "\\end_modules", modbegin)
639       if modend == -1:
640         self.warning("(set_module_list)Malformed LyX document: No \\end_modules.")
641         return
642       newmodlist = ['\\begin_modules'] + mlist + ['\\end_modules']
643       self.header[modbegin:modend + 1] = newmodlist
644
645
646     def set_parameter(self, param, value):
647         " Set the value of the header parameter."
648         i = find_token(self.header, '\\' + param, 0)
649         if i == -1:
650             self.warning('Parameter not found in the header: %s' % param, 3)
651             return
652         self.header[i] = '\\%s %s' % (param, str(value))
653
654
655     def is_default_layout(self, layout):
656         " Check whether a layout is the default layout of this class."
657         # FIXME: Check against the real text class default layout
658         if layout == 'Standard' or layout == self.default_layout:
659             return 1
660         return 0
661
662
663     def convert(self):
664         "Convert from current (self.format) to self.end_format."
665         if self.format == self.end_format:
666             self.warning("No conversion needed: Target format %s "
667                 "same as current format!" % self.format, default_debug__)
668             return
669
670         mode, conversion_chain = self.chain()
671         self.warning("conversion chain: " + str(conversion_chain), 3)
672
673         for step in conversion_chain:
674             steps = getattr(__import__("lyx_" + step), mode)
675
676             self.warning("Convertion step: %s - %s" % (step, mode),
677                          default_debug__ + 1)
678             if not steps:
679                 self.error("The conversion to an older "
680                 "format (%s) is not implemented." % self.format)
681
682             multi_conv = len(steps) != 1
683             for version, table in steps:
684                 if multi_conv and \
685                    (self.format >= version and mode == "convert") or\
686                    (self.format <= version and mode == "revert"):
687                     continue
688
689                 for conv in table:
690                     init_t = time.time()
691                     try:
692                         conv(self)
693                     except:
694                         self.warning("An error ocurred in %s, %s" %
695                                      (version, str(conv)),
696                                      default_debug__)
697                         if not self.try_hard:
698                             raise
699                         self.status = 2
700                     else:
701                         self.warning("%lf: Elapsed time on %s" %
702                                      (time.time() - init_t,
703                                       str(conv)), default_debug__ +
704                                      1)
705                 self.format = version
706                 if self.end_format == self.format:
707                     return
708
709
710     def chain(self):
711         """ This is where all the decisions related with the
712         conversion are taken.  It returns a list of modules needed to
713         convert the LyX file from self.format to self.end_format"""
714
715         format = self.format
716         correct_version = 0
717
718         for rel in format_relation:
719             if self.initial_version in rel[2]:
720                 if format in rel[1]:
721                     initial_step = rel[0]
722                     correct_version = 1
723                     break
724
725         if not correct_version:
726             if format <= 215:
727                 self.warning("Version does not match file format, "
728                              "discarding it. (Version %s, format %d)" %
729                              (self.initial_version, self.format))
730             for rel in format_relation:
731                 if format in rel[1]:
732                     initial_step = rel[0]
733                     break
734             else:
735                 # This should not happen, really.
736                 self.error("Format not supported.")
737
738         # Find the final step
739         for rel in format_relation:
740             if self.end_format in rel[1]:
741                 final_step = rel[0]
742                 break
743         else:
744             self.error("Format not supported.")
745
746         # Convertion mode, back or forth
747         steps = []
748         if (initial_step, self.initial_format) < (final_step, self.end_format):
749             mode = "convert"
750             full_steps = []
751             for step in format_relation:
752                 if  initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
753                     full_steps.append(step)
754             if full_steps[0][1][-1] == self.format:
755                 full_steps = full_steps[1:]
756             for step in full_steps:
757                 steps.append(step[0])
758         else:
759             mode = "revert"
760             relation_format = format_relation[:]
761             relation_format.reverse()
762             last_step = None
763
764             for step in relation_format:
765                 if  final_step <= step[0] <= initial_step:
766                     steps.append(step[0])
767                     last_step = step
768
769             if last_step[1][-1] == self.end_format:
770                 steps.pop()
771
772         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
773         return mode, steps
774
775
776 # Part of an unfinished attempt to make lyx2lyx gave a more
777 # structured view of the document.
778 #    def get_toc(self, depth = 4):
779 #        " Returns the TOC of this LyX document."
780 #        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
781 #                             'Subsection' : 3, 'Subsubsection': 4}
782 #        allowed_insets = ['Quotes']
783 #        allowed_parameters = ('\\paragraph_spacing', '\\noindent',
784 #                              '\\align', '\\labelwidthstring',
785 #                              "\\start_of_appendix", "\\leftindent")
786 #        sections = []
787 #        for section in paragraphs_filter.keys():
788 #            sections.append('\\begin_layout %s' % section)
789
790 #        toc_par = []
791 #        i = 0
792 #        while True:
793 #            i = find_tokens(self.body, sections, i)
794 #            if i == -1:
795 #                break
796
797 #            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
798 #            if j == -1:
799 #                self.warning('Incomplete file.', 0)
800 #                break
801
802 #            section = self.body[i].split()[1]
803 #            if section[-1] == '*':
804 #                section = section[:-1]
805
806 #            par = []
807
808 #            k = i + 1
809 #            # skip paragraph parameters
810 #            while not self.body[k].strip() or self.body[k].split()[0] \
811 #                      in allowed_parameters:
812 #                k += 1
813
814 #            while k < j:
815 #                if check_token(self.body[k], '\\begin_inset'):
816 #                    inset = self.body[k].split()[1]
817 #                    end = find_end_of_inset(self.body, k)
818 #                    if end == -1 or end > j:
819 #                        self.warning('Malformed file.', 0)
820
821 #                    if inset in allowed_insets:
822 #                        par.extend(self.body[k: end+1])
823 #                    k = end + 1
824 #                else:
825 #                    par.append(self.body[k])
826 #                    k += 1
827
828 #            # trim empty lines in the end.
829 #            while par and par[-1].strip() == '':
830 #                par.pop()
831
832 #            toc_par.append(Paragraph(section, par))
833
834 #            i = j + 1
835
836 #        return toc_par
837
838
839 class File(LyX_base):
840     " This class reads existing LyX files."
841
842     def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
843                  debug = default_debug__, try_hard = 0, cjk_encoding = u'',
844                  final_version = u'', systemlyxdir = u''):
845         LyX_base.__init__(self, end_format, input, output, error,
846                           debug, try_hard, cjk_encoding, final_version,
847                           systemlyxdir)
848         self.read()
849
850
851 # FIXME: header settings are completely outdated, don't use like this
852 #class NewFile(LyX_base):
853 #    " This class is to create new LyX files."
854 #    def set_header(self, **params):
855 #        # set default values
856 #        self.header.extend([
857 #            "#LyX xxxx created this file."
858 #            "For more info see http://www.lyx.org/",
859 #            "\\lyxformat xxx",
860 #            "\\begin_document",
861 #            "\\begin_header",
862 #            "\\textclass article",
863 #            "\\language english",
864 #            "\\inputencoding auto",
865 #            "\\font_roman default",
866 #            "\\font_sans default",
867 #            "\\font_typewriter default",
868 #            "\\font_default_family default",
869 #            "\\font_sc false",
870 #            "\\font_osf false",
871 #            "\\font_sf_scale 100",
872 #            "\\font_tt_scale 100",
873 #            "\\graphics default",
874 #            "\\paperfontsize default",
875 #            "\\papersize default",
876 #            "\\use_geometry false",
877 #            "\\use_amsmath 1",
878 #            "\\cite_engine basic",
879 #            "\\use_bibtopic false",
880 #            "\\use_indices false",
881 #            "\\paperorientation portrait",
882 #            "\\secnumdepth 3",
883 #            "\\tocdepth 3",
884 #            "\\paragraph_separation indent",
885 #            "\\defskip medskip",
886 #            "\\quotes_language english",
887 #            "\\papercolumns 1",
888 #            "\\papersides 1",
889 #            "\\paperpagestyle default",
890 #            "\\tracking_changes false",
891 #            "\\end_header"])
892
893 #        self.format = get_end_format()
894 #        for param in params:
895 #            self.set_parameter(param, params[param])
896
897
898 #    def set_body(self, paragraphs):
899 #        self.body.extend(['\\begin_body',''])
900
901 #        for par in paragraphs:
902 #            self.body.extend(par.asLines())
903
904 #        self.body.extend(['','\\end_body', '\\end_document'])
905
906
907 # Part of an unfinished attempt to make lyx2lyx gave a more
908 # structured view of the document.
909 #class Paragraph:
910 #    # unfinished implementation, it is missing the Text and Insets
911 #    # representation.
912 #    " This class represents the LyX paragraphs."
913 #    def __init__(self, name, body=[], settings = [], child = []):
914 #        """ Parameters:
915 #        name: paragraph name.
916 #        body: list of lines of body text.
917 #        child: list of paragraphs that descend from this paragraph.
918 #        """
919 #        self.name = name
920 #        self.body = body
921 #        self.settings = settings
922 #        self.child = child
923
924 #    def asLines(self):
925 #        """ Converts the paragraph to a list of strings, representing
926 #        it in the LyX file."""
927
928 #        result = ['','\\begin_layout %s' % self.name]
929 #        result.extend(self.settings)
930 #        result.append('')
931 #        result.extend(self.body)
932 #        result.append('\\end_layout')
933
934 #        if not self.child:
935 #            return result
936
937 #        result.append('\\begin_deeper')
938 #        for node in self.child:
939 #            result.extend(node.asLines())
940 #        result.append('\\end_deeper')
941
942 #        return result