]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/LyX.py
Convert all python files to utf-8.
[features.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>, José Matos <jamatos@lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 from parser_tools import get_value, check_token, find_token,\
20      find_tokens, find_end_of
21 import os.path
22 import gzip
23 import sys
24 import re
25 import string
26 import time
27
28 import lyx2lyx_version
29 version_lyx2lyx = lyx2lyx_version.version
30
31 default_debug_level = 2
32
33 ####################################################################
34 # Private helper functions
35
36 def find_end_of_inset(lines, i):
37     " Find beginning of inset, where lines[i] is included."
38     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
39
40 # End of helper functions
41 ####################################################################
42
43
44 # Regular expressions used
45 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
46 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
47 original_version = re.compile(r"\#LyX (\S*)")
48
49 ##
50 # file format information:
51 #  file, supported formats, stable release versions
52 format_relation = [("0_08",    [210], ["0.8.%d" % i for i in range(7)] + ["0.8"]),
53                    ("0_10",    [210], ["0.10.%d" % i for i in range(8)] + ["0.10"]),
54                    ("0_12",    [215], ["0.12.0","0.12.1","0.12"]),
55                    ("1_0_0",   [215], ["1.0.0","1.0"]),
56                    ("1_0_1",   [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
57                    ("1_1_4",   [215], ["1.1.4","1.1"]),
58                    ("1_1_5",   [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
59                    ("1_1_6_0", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
60                    ("1_1_6_3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
61                    ("1_2",     [220], ["1.2.%d" % i for i in range(5)] + ["1.2"]),
62                    ("1_3",     [221], ["1.3.%d" % i for i in range(8)] + ["1.3"]),
63                    ("1_4", range(222,246), ["1.4.0", "1.4.1", "1.4.2","1.4.3svn"]),
64                    ("1_5", range(246,249), ["1.5.0svn","1.5"])]
65
66
67 def formats_list():
68     " Returns a list with supported file formats."
69     formats = []
70     for version in format_relation:
71         for format in version[1]:
72             if format not in formats:
73                 formats.append(format)
74     return formats
75
76
77 def get_end_format():
78     " Returns the more recent file format available."
79     return format_relation[-1][1][-1]
80
81
82 def get_backend(textclass):
83     " For _textclass_ returns its backend."
84     if textclass == "linuxdoc" or textclass == "manpage":
85         return "linuxdoc"
86     if textclass[:7] == "docbook":
87         return "docbook"
88     return "latex"
89
90
91 def trim_eol(line):
92     " Remove end of line char(s)."
93     if line[-2:-1] == '\r':
94         return line[:-2]
95     else:
96         return line[:-1]
97
98
99 ##
100 # Class
101 #
102 class LyX_Base:
103     """This class carries all the information of the LyX file."""
104     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
105         """Arguments:
106         end_format: final format that the file should be converted. (integer)
107         input: the name of the input source, if empty resort to standard input.
108         output: the name of the output file, if empty use the standard output.
109         error: the name of the error file, if empty use the standard error.
110         debug: debug level, O means no debug, as its value increases be more verbose.
111         """
112         self.choose_io(input, output)
113
114         if error:
115             self.err = open(error, "w")
116         else:
117             self.err = sys.stderr
118
119         self.debug = debug
120         self.try_hard = try_hard
121
122         if end_format:
123             self.end_format = self.lyxformat(end_format)
124         else:
125             self.end_format = get_end_format()
126
127         self.backend = "latex"
128         self.textclass = "article"
129         # This is a hack: We use '' since we don't know the default
130         # layout of the text class. LyX will parse it as default layout.
131         # FIXME: Read the layout file and use the real default layout
132         self.default_layout = ''
133         self.header = []
134         self.preamble = []
135         self.body = []
136         self.status = 0
137
138
139     def warning(self, message, debug_level= default_debug_level):
140         " Emits warning to self.error, if the debug_level is less than the self.debug."
141         if debug_level <= self.debug:
142             self.err.write("Warning: " + message + "\n")
143
144
145     def error(self, message):
146         " Emits a warning and exits if not in try_hard mode."
147         self.warning(message)
148         if not self.try_hard:
149             self.warning("Quiting.")
150             sys.exit(1)
151
152         self.status = 2
153
154
155     def read(self):
156         """Reads a file into the self.header and self.body parts, from self.input."""
157
158         while 1:
159             line = self.input.readline()
160             if not line:
161                 self.error("Invalid LyX file.")
162
163             line = trim_eol(line)
164             if check_token(line, '\\begin_preamble'):
165                 while 1:
166                     line = self.input.readline()
167                     if not line:
168                         self.error("Invalid LyX file.")
169
170                     line = trim_eol(line)
171                     if check_token(line, '\\end_preamble'):
172                         break
173                     
174                     if string.split(line)[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
175                         self.warning("Malformed LyX file: Missing '\\end_preamble'.")
176                         self.warning("Adding it now and hoping for the best.")
177
178                     self.preamble.append(line)
179
180             if check_token(line, '\\end_preamble'):
181                 continue
182
183             line = string.strip(line)
184             if not line:
185                 continue
186
187             if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
188                 self.body.append(line)
189                 break
190
191             self.header.append(line)
192
193         while 1:
194             line = self.input.readline()
195             if not line:
196                 break
197             self.body.append(trim_eol(line))
198
199         self.textclass = get_value(self.header, "\\textclass", 0)
200         self.backend = get_backend(self.textclass)
201         self.format  = self.read_format()
202         self.language = get_value(self.header, "\\language", 0)
203         if self.language == "":
204             self.language = "english"
205         self.initial_version = self.read_version()
206
207
208     def write(self):
209         " Writes the LyX file to self.output."
210         self.set_version()
211         self.set_format()
212
213         if self.preamble:
214             i = find_token(self.header, '\\textclass', 0) + 1
215             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
216             if i == 0:
217                 self.error("Malformed LyX file: Missing '\\textclass'.")
218             else:
219                 header = self.header[:i] + preamble + self.header[i:]
220         else:
221             header = self.header
222
223         for line in header + [''] + self.body:
224             self.output.write(line+"\n")
225
226
227     def choose_io(self, input, output):
228         """Choose input and output streams, dealing transparently with
229         compressed files."""
230
231         if output:
232             self.output = open(output, "wb")
233         else:
234             self.output = sys.stdout
235
236         if input and input != '-':
237             self.dir = os.path.dirname(os.path.abspath(input))
238             try:
239                 gzip.open(input).readline()
240                 self.input = gzip.open(input)
241                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
242             except:
243                 self.input = open(input)
244         else:
245             self.dir = ''
246             self.input = sys.stdin
247
248
249     def lyxformat(self, format):
250         " Returns the file format representation, an integer."
251         result = format_re.match(format)
252         if result:
253             format = int(result.group(1) + result.group(2))
254         else:
255             self.error(str(format) + ": " + "Invalid LyX file.")
256
257         if format in formats_list():
258             return format
259
260         self.error(str(format) + ": " + "Format not supported.")
261         return None
262
263
264     def read_version(self):
265         """ Searchs for clues of the LyX version used to write the file, returns the
266         most likely value, or None otherwise."""
267         for line in self.header:
268             if line[0] != "#":
269                 return None
270
271             result = original_version.match(line)
272             if result:
273                 return result.group(1)
274         return None
275
276
277     def set_version(self):
278         " Set the header with the version used."
279         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
280         if self.header[1][0] == '#':
281             del self.header[1]
282
283
284     def read_format(self):
285         " Read from the header the fileformat of the present LyX file."
286         for line in self.header:
287             result = fileformat.match(line)
288             if result:
289                 return self.lyxformat(result.group(1))
290         else:
291             self.error("Invalid LyX File.")
292         return None
293
294
295     def set_format(self):
296         " Set the file format of the file, in the header."
297         if self.format <= 217:
298             format = str(float(self.format)/100)
299         else:
300             format = str(self.format)
301         i = find_token(self.header, "\\lyxformat", 0)
302         self.header[i] = "\\lyxformat %s" % format
303
304
305     def set_parameter(self, param, value):
306         " Set the value of the header parameter."
307         i = find_token(self.header, '\\' + param, 0)
308         if i == -1:
309             self.warning('Parameter not found in the header: %s' % param, 3)
310             return
311         self.header[i] = '\\%s %s' % (param, str(value))
312
313
314     def is_default_layout(self, layout):
315         " Check whether a layout is the default layout of this class."
316         # FIXME: Check against the real text class default layout
317         if layout == 'Standard' or layout == self.default_layout:
318             return 1
319         return 0
320
321
322     def convert(self):
323         "Convert from current (self.format) to self.end_format."
324         mode, convertion_chain = self.chain()
325         self.warning("convertion chain: " + str(convertion_chain), 3)
326
327         for step in convertion_chain:
328             steps = getattr(__import__("lyx_" + step), mode)
329
330             self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
331             if not steps:
332                     self.error("The convertion to an older format (%s) is not implemented." % self.format)
333
334             multi_conv = len(steps) != 1
335             for version, table in steps:
336                 if multi_conv and \
337                    (self.format >= version and mode == "convert") or\
338                    (self.format <= version and mode == "revert"):
339                     continue
340
341                 for conv in table:
342                     init_t = time.time()
343                     try:
344                         conv(self)
345                     except:
346                         self.warning("An error ocurred in %s, %s" % (version, str(conv)),
347                                      default_debug_level)
348                         if not self.try_hard:
349                             raise
350                         self.status = 2
351                     else:
352                         self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
353                                      default_debug_level + 1)
354
355                 self.format = version
356                 if self.end_format == self.format:
357                     return
358
359
360     def chain(self):
361         """ This is where all the decisions related with the convertion are taken.
362         It returns a list of modules needed to convert the LyX file from
363         self.format to self.end_format"""
364
365         self.start =  self.format
366         format = self.format
367         correct_version = 0
368
369         for rel in format_relation:
370             if self.initial_version in rel[2]:
371                 if format in rel[1]:
372                     initial_step = rel[0]
373                     correct_version = 1
374                     break
375
376         if not correct_version:
377             if format <= 215:
378                 self.warning("Version does not match file format, discarding it.")
379             for rel in format_relation:
380                 if format in rel[1]:
381                     initial_step = rel[0]
382                     break
383             else:
384                 # This should not happen, really.
385                 self.error("Format not supported.")
386
387         # Find the final step
388         for rel in format_relation:
389             if self.end_format in rel[1]:
390                 final_step = rel[0]
391                 break
392         else:
393             self.error("Format not supported.")
394
395         # Convertion mode, back or forth
396         steps = []
397         if (initial_step, self.start) < (final_step, self.end_format):
398             mode = "convert"
399             first_step = 1
400             for step in format_relation:
401                 if  initial_step <= step[0] <= final_step:
402                     if first_step and len(step[1]) == 1:
403                         first_step = 0
404                         continue
405                     steps.append(step[0])
406         else:
407             mode = "revert"
408             relation_format = format_relation[:]
409             relation_format.reverse()
410             last_step = None
411
412             for step in relation_format:
413                 if  final_step <= step[0] <= initial_step:
414                     steps.append(step[0])
415                     last_step = step
416
417             if last_step[1][-1] == self.end_format:
418                 steps.pop()
419
420         return mode, steps
421
422
423     def get_toc(self, depth = 4):
424         " Returns the TOC of this LyX document."
425         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
426         allowed_insets = ['Quotes']
427         allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
428
429         sections = []
430         for section in paragraphs_filter.keys():
431             sections.append('\\begin_layout %s' % section)
432
433         toc_par = []
434         i = 0
435         while 1:
436             i = find_tokens(self.body, sections, i)
437             if i == -1:
438                 break
439
440             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
441             if j == -1:
442                 self.warning('Incomplete file.', 0)
443                 break
444
445             section = string.split(self.body[i])[1]
446             if section[-1] == '*':
447                 section = section[:-1]
448
449             par = []
450
451             k = i + 1
452             # skip paragraph parameters
453             while not string.strip(self.body[k]) or string.split(self.body[k])[0] in allowed_parameters:
454                 k = k +1
455
456             while k < j:
457                 if check_token(self.body[k], '\\begin_inset'):
458                     inset = string.split(self.body[k])[1]
459                     end = find_end_of_inset(self.body, k)
460                     if end == -1 or end > j:
461                         self.warning('Malformed file.', 0)
462
463                     if inset in allowed_insets:
464                         par.extend(self.body[k: end+1])
465                     k = end + 1
466                 else:
467                     par.append(self.body[k])
468                     k = k + 1
469
470             # trim empty lines in the end.
471             while string.strip(par[-1]) == '' and par:
472                 par.pop()
473
474             toc_par.append(Paragraph(section, par))
475
476             i = j + 1
477
478         return toc_par
479
480
481 class File(LyX_Base):
482     " This class reads existing LyX files."
483     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
484         LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard)
485         self.read()
486
487
488 class NewFile(LyX_Base):
489     " This class is to create new LyX files."
490     def set_header(self, **params):
491         # set default values
492         self.header.extend([
493             "#LyX xxxx created this file. For more info see http://www.lyx.org/",
494             "\\lyxformat xxx",
495             "\\begin_document",
496             "\\begin_header",
497             "\\textclass article",
498             "\\language english",
499             "\\inputencoding auto",
500             "\\font_roman default",
501             "\\font_sans default",
502             "\\font_typewriter default",
503             "\\font_default_family default",
504             "\\font_sc false",
505             "\\font_osf false",
506             "\\font_sf_scale 100",
507             "\\font_tt_scale 100",
508             "\\graphics default",
509             "\\paperfontsize default",
510             "\\papersize default",
511             "\\use_geometry false",
512             "\\use_amsmath 1",
513             "\\cite_engine basic",
514             "\\use_bibtopic false",
515             "\\paperorientation portrait",
516             "\\secnumdepth 3",
517             "\\tocdepth 3",
518             "\\paragraph_separation indent",
519             "\\defskip medskip",
520             "\\quotes_language english",
521             "\\papercolumns 1",
522             "\\papersides 1",
523             "\\paperpagestyle default",
524             "\\tracking_changes false",
525             "\\end_header"])
526
527         self.format = get_end_format()
528         for param in params:
529             self.set_parameter(param, params[param])
530
531
532     def set_body(self, paragraphs):
533         self.body.extend(['\\begin_body',''])
534
535         for par in paragraphs:
536             self.body.extend(par.asLines())
537
538         self.body.extend(['','\\end_body', '\\end_document'])
539
540
541 class Paragraph:
542     # unfinished implementation, it is missing the Text and Insets representation.
543     " This class represents the LyX paragraphs."
544     def __init__(self, name, body=[], settings = [], child = []):
545         """ Parameters:
546         name: paragraph name.
547         body: list of lines of body text.
548         child: list of paragraphs that descend from this paragraph.
549         """
550         self.name = name
551         self.body = body
552         self.settings = settings
553         self.child = child
554
555     def asLines(self):
556         " Converts the paragraph to a list of strings, representing it in the LyX file."
557         result = ['','\\begin_layout %s' % self.name]
558         result.extend(self.settings)
559         result.append('')
560         result.extend(self.body)
561         result.append('\\end_layout')
562
563         if not self.child:
564             return result
565
566         result.append('\\begin_deeper')
567         for node in self.child:
568             result.extend(node.asLines())
569         result.append('\\end_deeper')
570
571         return result
572
573
574 class Inset:
575     " This class represents the LyX insets."
576     pass
577
578
579 class Text:
580     " This class represents simple chuncks of text."
581     pass