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