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