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