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