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