]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
Fix typo (thanks to Salvatore Falco for the fix).
[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, find_tokens,
24                           find_end_of, find_complete_lines)
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(b".*?LyX ([\\d.]*)")
75 original_tex2lyx_version = re.compile(b".*?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:1] != b"#":
523                 return None
524
525             line = line.replace(b"fix",b".")
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(b"reLyX") != -1 or line.find(b"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.decode('ascii') if not PY2 else 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       " Append module to the modules list."
599       i = find_token(self.header, "\\begin_modules", 0)
600       if i == -1:
601         #No modules yet included
602         i = find_token(self.header, "\\textclass", 0)
603         if i == -1:
604           self.warning("Malformed LyX document: No \\textclass!!")
605           return
606         modinfo = ["\\begin_modules", module, "\\end_modules"]
607         self.header[i + 1: i + 1] = modinfo
608         return
609       j = find_token(self.header, "\\end_modules", i)
610       if j == -1:
611         self.warning("(add_module)Malformed LyX document: No \\end_modules.")
612         return
613       k = find_token(self.header, module, i)
614       if k != -1 and k < j:
615         return
616       self.header.insert(j, module)
617
618
619     def del_module(self, module):
620         " Delete `module` from module list, return success."
621         modlist = self.get_module_list()
622         if module not in modlist:
623             return False
624         self.set_module_list([line for line in modlist if line != module])
625         return True
626
627     def get_module_list(self):
628       " Return list of modules."
629       i = find_token(self.header, "\\begin_modules", 0)
630       if (i == -1):
631         return []
632       j = find_token(self.header, "\\end_modules", i)
633       return self.header[i + 1 : j]
634
635
636     def set_module_list(self, mlist):
637       i = find_token(self.header, "\\begin_modules", 0)
638       if (i == -1):
639         #No modules yet included
640         tclass = find_token(self.header, "\\textclass", 0)
641         if tclass == -1:
642           self.warning("Malformed LyX document: No \\textclass!!")
643           return
644         i = j = tclass + 1
645       else:
646         j = find_token(self.header, "\\end_modules", i)
647         if j == -1:
648             self.warning("(set_module_list) Malformed LyX document: No \\end_modules.")
649             return
650         j += 1
651       if mlist:
652           mlist = ['\\begin_modules'] + mlist + ['\\end_modules']
653       self.header[i:j] = mlist
654
655
656     def set_parameter(self, param, value):
657         " Set the value of the header parameter."
658         i = find_token(self.header, '\\' + param, 0)
659         if i == -1:
660             self.warning('Parameter not found in the header: %s' % param, 3)
661             return
662         self.header[i] = '\\%s %s' % (param, str(value))
663
664
665     def is_default_layout(self, layout):
666         " Check whether a layout is the default layout of this class."
667         # FIXME: Check against the real text class default layout
668         if layout == 'Standard' or layout == self.default_layout:
669             return 1
670         return 0
671
672
673     def convert(self):
674         "Convert from current (self.format) to self.end_format."
675         if self.format == self.end_format:
676             self.warning("No conversion needed: Target format %s "
677                 "same as current format!" % self.format, default_debug__)
678             return
679
680         mode, conversion_chain = self.chain()
681         self.warning("conversion chain: " + str(conversion_chain), 3)
682
683         for step in conversion_chain:
684             steps = getattr(__import__("lyx_" + step), mode)
685
686             self.warning("Convertion step: %s - %s" % (step, mode),
687                          default_debug__ + 1)
688             if not steps:
689                 self.error("The conversion to an older "
690                 "format (%s) is not implemented." % self.format)
691
692             multi_conv = len(steps) != 1
693             for version, table in steps:
694                 if multi_conv and \
695                    (self.format >= version and mode == "convert") or\
696                    (self.format <= version and mode == "revert"):
697                     continue
698
699                 for conv in table:
700                     init_t = time.time()
701                     try:
702                         conv(self)
703                     except:
704                         self.warning("An error ocurred in %s, %s" %
705                                      (version, str(conv)),
706                                      default_debug__)
707                         if not self.try_hard:
708                             raise
709                         self.status = 2
710                     else:
711                         self.warning("%lf: Elapsed time on %s" %
712                                      (time.time() - init_t,
713                                       str(conv)), default_debug__ +
714                                      1)
715                 self.format = version
716                 if self.end_format == self.format:
717                     return
718
719
720     def chain(self):
721         """ This is where all the decisions related with the
722         conversion are taken.  It returns a list of modules needed to
723         convert the LyX file from self.format to self.end_format"""
724
725         format = self.format
726         correct_version = 0
727
728         for rel in format_relation:
729             if self.initial_version in rel[2]:
730                 if format in rel[1]:
731                     initial_step = rel[0]
732                     correct_version = 1
733                     break
734
735         if not correct_version:
736             if format <= 215:
737                 self.warning("Version does not match file format, "
738                              "discarding it. (Version %s, format %d)" %
739                              (self.initial_version, self.format))
740             for rel in format_relation:
741                 if format in rel[1]:
742                     initial_step = rel[0]
743                     break
744             else:
745                 # This should not happen, really.
746                 self.error("Format not supported.")
747
748         # Find the final step
749         for rel in format_relation:
750             if self.end_format in rel[1]:
751                 final_step = rel[0]
752                 break
753         else:
754             self.error("Format not supported.")
755
756         # Convertion mode, back or forth
757         steps = []
758         if (initial_step, self.initial_format) < (final_step, self.end_format):
759             mode = "convert"
760             full_steps = []
761             for step in format_relation:
762                 if  initial_step <= step[0] <= final_step and step[2][0] <= self.final_version:
763                     full_steps.append(step)
764             if full_steps[0][1][-1] == self.format:
765                 full_steps = full_steps[1:]
766             for step in full_steps:
767                 steps.append(step[0])
768         else:
769             mode = "revert"
770             relation_format = format_relation[:]
771             relation_format.reverse()
772             last_step = None
773
774             for step in relation_format:
775                 if  final_step <= step[0] <= initial_step:
776                     steps.append(step[0])
777                     last_step = step
778
779             if last_step[1][-1] == self.end_format:
780                 steps.pop()
781
782         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
783         return mode, steps
784
785
786     def append_local_layout(self, new_layout):
787         " Append `new_layout` to the local layouts."
788         # new_layout may be a string or a list of strings (lines)
789         try:
790             new_layout = new_layout.splitlines()
791         except AttributeError:
792             pass
793         i = find_token(self.header, "\\begin_local_layout", 0)
794         if i == -1:
795             k = find_token(self.header, "\\language", 0)
796             if k == -1:
797                 # this should not happen
798                 self.warning("Malformed LyX document! No \\language header found!")
799                 return
800             self.header[k : k] = ["\\begin_local_layout", "\\end_local_layout"]
801             i = k
802
803         j = find_end_of(self.header, i, "\\begin_local_layout", "\\end_local_layout")
804         if j == -1:
805             # this should not happen
806             self.warning("Malformed LyX document: Can't find end of local layout!")
807             return
808
809         self.header[i+1 : i+1] = new_layout
810
811     def del_local_layout(self, layout_def):
812         " Delete `layout_def` from local layouts, return success."
813         i = find_complete_lines(self.header, layout_def)
814         if i == -1:
815             return False
816         j = i+len(layout_def)
817         if (self.header[i-1] == "\\begin_local_layout" and
818             self.header[j] == "\\end_local_layout"):
819             i -=1
820             j +=1
821         self.header[i:j] = []
822         return True
823
824     def del_from_header(self, lines):
825         " Delete `lines` from the document header, return success."
826         i = find_complete_lines(self.header, lines)
827         if i == -1:
828             return False
829         j = i + len(lines)
830         self.header[i:j] = []
831         return True
832
833 # Part of an unfinished attempt to make lyx2lyx gave a more
834 # structured view of the document.
835 #    def get_toc(self, depth = 4):
836 #        " Returns the TOC of this LyX document."
837 #        paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
838 #                             'Subsection' : 3, 'Subsubsection': 4}
839 #        allowed_insets = ['Quotes']
840 #        allowed_parameters = ('\\paragraph_spacing', '\\noindent',
841 #                              '\\align', '\\labelwidthstring',
842 #                              "\\start_of_appendix", "\\leftindent")
843 #        sections = []
844 #        for section in paragraphs_filter.keys():
845 #            sections.append('\\begin_layout %s' % section)
846
847 #        toc_par = []
848 #        i = 0
849 #        while True:
850 #            i = find_tokens(self.body, sections, i)
851 #            if i == -1:
852 #                break
853
854 #            j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
855 #            if j == -1:
856 #                self.warning('Incomplete file.', 0)
857 #                break
858
859 #            section = self.body[i].split()[1]
860 #            if section[-1] == '*':
861 #                section = section[:-1]
862
863 #            par = []
864
865 #            k = i + 1
866 #            # skip paragraph parameters
867 #            while not self.body[k].strip() or self.body[k].split()[0] \
868 #                      in allowed_parameters:
869 #                k += 1
870
871 #            while k < j:
872 #                if check_token(self.body[k], '\\begin_inset'):
873 #                    inset = self.body[k].split()[1]
874 #                    end = find_end_of_inset(self.body, k)
875 #                    if end == -1 or end > j:
876 #                        self.warning('Malformed file.', 0)
877
878 #                    if inset in allowed_insets:
879 #                        par.extend(self.body[k: end+1])
880 #                    k = end + 1
881 #                else:
882 #                    par.append(self.body[k])
883 #                    k += 1
884
885 #            # trim empty lines in the end.
886 #            while par and par[-1].strip() == '':
887 #                par.pop()
888
889 #            toc_par.append(Paragraph(section, par))
890
891 #            i = j + 1
892
893 #        return toc_par
894
895
896 class File(LyX_base):
897     " This class reads existing LyX files."
898
899     def __init__(self, end_format = 0, input = u'', output = u'', error = u'',
900                  debug = default_debug__, try_hard = 0, cjk_encoding = u'',
901                  final_version = u'', systemlyxdir = u''):
902         LyX_base.__init__(self, end_format, input, output, error,
903                           debug, try_hard, cjk_encoding, final_version,
904                           systemlyxdir)
905         self.read()
906
907
908 # FIXME: header settings are completely outdated, don't use like this
909 #class NewFile(LyX_base):
910 #    " This class is to create new LyX files."
911 #    def set_header(self, **params):
912 #        # set default values
913 #        self.header.extend([
914 #            "#LyX xxxx created this file."
915 #            "For more info see http://www.lyx.org/",
916 #            "\\lyxformat xxx",
917 #            "\\begin_document",
918 #            "\\begin_header",
919 #            "\\textclass article",
920 #            "\\language english",
921 #            "\\inputencoding auto",
922 #            "\\font_roman default",
923 #            "\\font_sans default",
924 #            "\\font_typewriter default",
925 #            "\\font_default_family default",
926 #            "\\font_sc false",
927 #            "\\font_osf false",
928 #            "\\font_sf_scale 100",
929 #            "\\font_tt_scale 100",
930 #            "\\graphics default",
931 #            "\\paperfontsize default",
932 #            "\\papersize default",
933 #            "\\use_geometry false",
934 #            "\\use_amsmath 1",
935 #            "\\cite_engine basic",
936 #            "\\use_bibtopic false",
937 #            "\\use_indices false",
938 #            "\\paperorientation portrait",
939 #            "\\secnumdepth 3",
940 #            "\\tocdepth 3",
941 #            "\\paragraph_separation indent",
942 #            "\\defskip medskip",
943 #            "\\quotes_language english",
944 #            "\\papercolumns 1",
945 #            "\\papersides 1",
946 #            "\\paperpagestyle default",
947 #            "\\tracking_changes false",
948 #            "\\end_header"])
949
950 #        self.format = get_end_format()
951 #        for param in params:
952 #            self.set_parameter(param, params[param])
953
954
955 #    def set_body(self, paragraphs):
956 #        self.body.extend(['\\begin_body',''])
957
958 #        for par in paragraphs:
959 #            self.body.extend(par.asLines())
960
961 #        self.body.extend(['','\\end_body', '\\end_document'])
962
963
964 # Part of an unfinished attempt to make lyx2lyx gave a more
965 # structured view of the document.
966 #class Paragraph:
967 #    # unfinished implementation, it is missing the Text and Insets
968 #    # representation.
969 #    " This class represents the LyX paragraphs."
970 #    def __init__(self, name, body=[], settings = [], child = []):
971 #        """ Parameters:
972 #        name: paragraph name.
973 #        body: list of lines of body text.
974 #        child: list of paragraphs that descend from this paragraph.
975 #        """
976 #        self.name = name
977 #        self.body = body
978 #        self.settings = settings
979 #        self.child = child
980
981 #    def asLines(self):
982 #        """ Converts the paragraph to a list of strings, representing
983 #        it in the LyX file."""
984
985 #        result = ['','\\begin_layout %s' % self.name]
986 #        result.extend(self.settings)
987 #        result.append('')
988 #        result.extend(self.body)
989 #        result.append('\\end_layout')
990
991 #        if not self.child:
992 #            return result
993
994 #        result.append('\\begin_deeper')
995 #        for node in self.child:
996 #            result.extend(node.asLines())
997 #        result.append('\\end_deeper')
998
999 #        return result