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