]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
allow to use glue lengths in the HSpace dialog; file format change
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008 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 """ Convert files to the file format generated by lyx 2.0"""
20
21 import re, string
22 import unicodedata
23 import sys, os
24
25 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
26
27 ####################################################################
28 # Private helper functions
29
30 def find_end_of_inset(lines, i):
31     " Find end of inset, where lines[i] is included."
32     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
33
34
35 def add_to_preamble(document, text):
36     """ Add text to the preamble if it is not already there.
37     Only the first line is checked!"""
38
39     if find_token(document.preamble, text[0], 0) != -1:
40         return
41
42     document.preamble.extend(text)
43
44
45 def insert_to_preamble(index, document, text):
46     """ Insert text to the preamble at a given line"""
47
48     document.preamble.insert(index, text)
49
50
51 def read_unicodesymbols():
52     " Read the unicodesymbols list of unicode characters and corresponding commands."
53     pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
54     fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
55     spec_chars = []
56     # Two backslashes, followed by some non-word character, and then a character
57     # in brackets. The idea is to check for constructs like: \"{u}, which is how
58     # they are written in the unicodesymbols file; but they can also be written
59     # as: \"u or even \" u.
60     r = re.compile(r'\\\\(\W)\{(\w)\}')
61     for line in fp.readlines():
62         if line[0] != '#' and line.strip() != "":
63             line=line.replace(' "',' ') # remove all quotation marks with spaces before
64             line=line.replace('" ',' ') # remove all quotation marks with spaces after
65             line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
66             try:
67                 [ucs4,command,dead] = line.split(None,2)
68                 if command[0:1] != "\\":
69                     continue
70                 spec_chars.append([command, unichr(eval(ucs4))])
71             except:
72                 continue
73             m = r.match(command)
74             if m != None:
75                 command = "\\\\"
76                 # If the character is a double-quote, then we need to escape it, too,
77                 # since it is done that way in the LyX file.
78                 if m.group(1) == "\"":
79                     command += "\\"
80                 commandbl = command
81                 command += m.group(1) + m.group(2)
82                 commandbl += m.group(1) + ' ' + m.group(2)
83                 spec_chars.append([command, unichr(eval(ucs4))])
84                 spec_chars.append([commandbl, unichr(eval(ucs4))])
85     fp.close()
86     return spec_chars
87
88
89 unicode_reps = read_unicodesymbols()
90
91
92 def put_cmd_in_ert(string):
93     for rep in unicode_reps:
94         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
95     string = string.replace('\\', "\\backslash\n")
96     string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
97       + string + "\n\\end_layout\n\\end_inset"
98     return string
99
100
101 def lyx2latex(document, lines):
102     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
103     # clean up multiline stuff
104     content = ""
105     ert_end = 0
106
107     for curline in range(len(lines)):
108       line = lines[curline]
109       if line.startswith("\\begin_inset ERT"):
110           # We don't want to replace things inside ERT, so figure out
111           # where the end of the inset is.
112           ert_end = find_end_of_inset(lines, curline + 1)
113           continue
114       elif line.startswith("\\begin_inset Formula"):
115           line = line[20:]
116       elif line.startswith("\\begin_inset Quotes"):
117           # For now, we do a very basic reversion. Someone who understands
118           # quotes is welcome to fix it up.
119           qtype = line[20:].strip()
120           # lang = qtype[0]
121           side = qtype[1]
122           dbls = qtype[2]
123           if side == "l":
124               if dbls == "d":
125                   line = "``"
126               else:
127                   line = "`"
128           else:
129               if dbls == "d":
130                   line = "''"
131               else:
132                   line = "'"
133       elif line.isspace() or \
134             line.startswith("\\begin_layout") or \
135             line.startswith("\\end_layout") or \
136             line.startswith("\\begin_inset") or \
137             line.startswith("\\end_inset") or \
138             line.startswith("\\lang") or \
139             line.strip() == "status collapsed" or \
140             line.strip() == "status open":
141           #skip all that stuff
142           continue
143
144       # this needs to be added to the preamble because of cases like
145       # \textmu, \textbackslash, etc.
146       add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
147                                  '\\@ifundefined{textmu}',
148                                  ' {\\usepackage{textcomp}}{}'])
149       # a lossless reversion is not possible
150       # try at least to handle some common insets and settings
151       if ert_end >= curline:
152           line = line.replace(r'\backslash', r'\\')
153       else:
154           line = line.replace('&', '\\&{}')
155           line = line.replace('#', '\\#{}')
156           line = line.replace('^', '\\^{}')
157           line = line.replace('%', '\\%{}')
158           line = line.replace('_', '\\_{}')
159           line = line.replace('$', '\\${}')
160
161           # Do the LyX text --> LaTeX conversion
162           for rep in unicode_reps:
163             line = line.replace(rep[1], rep[0] + "{}")
164           line = line.replace(r'\backslash', r'\textbackslash{}')
165           line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
166           line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
167           line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
168           line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
169           line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
170           line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
171           line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
172           line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
173           line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
174       content += line
175     return content
176
177
178 def latex_length(string):
179     'Convert lengths to their LaTeX representation.'
180     i = 0
181     percent = False
182     i = string.find("text%")
183     if i > -1:
184         percent = True
185         minus = string.rfind("-", 0, i)
186         plus = string.rfind("+", 0, i)
187         if plus == -1 and minus == -1:
188             value = string[:i]
189             value = str(float(value)/100)
190             end = string[i+5:]
191             string = value + "\\textwidth" + end
192         if plus > minus:
193             value = string[plus+1:i]
194             value = str(float(value)/100)
195             begin = string[:plus+1]
196             end = string[i+5:]
197             string = begin + value + "\\textwidth" + end
198         if plus < minus:
199             value = string[minus+1:i]
200             value = str(float(value)/100)
201             begin = string[:minus+1]
202             string = begin + value + "\\textwidth"
203     i = string.find("col%")
204     if i > -1:
205         percent = True
206         minus = string.rfind("-", 0, i)
207         plus = string.rfind("+", 0, i)
208         if plus == -1 and minus == -1:
209             value = string[:i]
210             value = str(float(value)/100)
211             end = string[i+4:]
212             string = value + "\\columnwidth" + end
213         if plus > minus:
214             value = string[plus+1:i]
215             value = str(float(value)/100)
216             begin = string[:plus+1]
217             end = string[i+4:]
218             string = begin + value + "\\columnwidth" + end
219         if plus < minus:
220             value = string[minus+1:i]
221             value = str(float(value)/100)
222             begin = string[:minus+1]
223             string = begin + value + "\\columnwidth"
224     i = string.find("page%")
225     if i > -1:
226         percent = True
227         minus = string.rfind("-", 0, i)
228         plus = string.rfind("+", 0, i)
229         if plus == -1 and minus == -1:
230             value = string[:i]
231             value = str(float(value)/100)
232             end = string[i+5:]
233             string = value + "\\paperwidth" + end
234         if plus > minus:
235             value = string[plus+1:i]
236             value = str(float(value)/100)
237             begin = string[:plus+1]
238             end = string[i+5:]
239             string = begin + value + "\\paperwidth" + end
240         if plus < minus:
241             value = string[minus+1:i]
242             value = str(float(value)/100)
243             begin = string[:minus+1]
244             string = begin + value + "\\paperwidth"
245     i = string.find("line%")
246     if i > -1:
247         percent = True
248         minus = string.rfind("-", 0, i)
249         plus = string.rfind("+", 0, i)
250         if plus == -1 and minus == -1:
251             value = string[:i]
252             value = str(float(value)/100)
253             end = string[i+5:]
254             string = value + "\\linewidth" + end
255         if plus > minus:
256             value = string[plus+1:i]
257             value = str(float(value)/100)
258             begin = string[:plus+1]
259             end = string[i+5:]
260             string = begin + value + "\\linewidth" + end
261         if plus < minus:
262             value = string[minus+1:i]
263             value = str(float(value)/100)
264             begin = string[:minus+1]
265             string = begin + value + "\\linewidth"
266     i = string.find("theight%")
267     if i > -1:
268         percent = True
269         minus = string.rfind("-", 0, i)
270         plus = string.rfind("+", 0, i)
271         if plus == -1 and minus == -1:
272             value = string[:i]
273             value = str(float(value)/100)
274             end = string[i+8:]
275             string = value + "\\textheight" + end
276         if plus > minus:
277             value = string[plus+1:i]
278             value = str(float(value)/100)
279             begin = string[:plus+1]
280             end = string[i+8:]
281             string = begin + value + "\\textheight" + end
282         if plus < minus:
283             value = string[minus+1:i]
284             value = str(float(value)/100)
285             begin = string[:minus+1]
286             string = begin + value + "\\textheight"
287     i = string.find("pheight%")
288     if i > -1:
289         percent = True
290         minus = string.rfind("-", 0, i)
291         plus = string.rfind("+", 0, i)
292         if plus == -1 and minus == -1:
293             value = string[:i]
294             value = str(float(value)/100)
295             end = string[i+8:]
296             string = value + "\\paperheight" + end
297         if plus > minus:
298             value = string[plus+1:i]
299             value = str(float(value)/100)
300             begin = string[:plus+1]
301             end = string[i+8:]
302             string = begin + value + "\\paperheight" + end
303         if plus < minus:
304             value = string[minus+1:i]
305             value = str(float(value)/100)
306             begin = string[:minus+1]
307             string = begin + value + "\\paperheight"
308     if percent ==  False:
309         return "False," + string
310     else:
311         string = string.replace("+", " plus ")
312         string = string.replace("-", " minus ")
313         return "True," + string
314         
315
316 ####################################################################
317
318
319 def revert_swiss(document):
320     " Set language german-ch to ngerman "
321     i = 0
322     if document.language == "german-ch":
323         document.language = "ngerman"
324         i = find_token(document.header, "\\language", 0)
325         if i != -1:
326             document.header[i] = "\\language ngerman"
327     j = 0
328     while True:
329         j = find_token(document.body, "\\lang german-ch", j)
330         if j == -1:
331             return
332         document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
333         j = j + 1
334
335
336 def revert_tabularvalign(document):
337    " Revert the tabular valign option "
338    i = 0
339    while True:
340        i = find_token(document.body, "\\begin_inset Tabular", i)
341        if i == -1:
342            return
343        j = find_end_of_inset(document.body, i)
344        if j == -1:
345            document.warning("Malformed LyX document: Could not find end of tabular.")
346            i = j
347            continue
348        # don't set a box for longtables, only delete tabularvalignment
349        # the alignment is 2 lines below \\begin_inset Tabular
350        p = document.body[i+2].find("islongtable")
351        if p > -1:
352            q = document.body[i+2].find("tabularvalignment")
353            if q > -1:
354                document.body[i+2] = document.body[i+2][:q-1]
355                document.body[i+2] = document.body[i+2] + '>'
356            i = i + 1
357
358        # when no longtable
359        if p == -1:
360          tabularvalignment = 'c'
361          # which valignment is specified?
362          m = document.body[i+2].find('tabularvalignment="top"')
363          if m > -1:
364              tabularvalignment = 't'
365          m = document.body[i+2].find('tabularvalignment="bottom"')
366          if m > -1:
367              tabularvalignment = 'b'
368          # delete tabularvalignment
369          q = document.body[i+2].find("tabularvalignment")
370          if q > -1:
371              document.body[i+2] = document.body[i+2][:q-1]
372              document.body[i+2] = document.body[i+2] + '>'
373
374          # don't add a box when centered
375          if tabularvalignment == 'c':
376              i = j
377              continue
378          subst = ['\\end_layout', '\\end_inset']
379          document.body[j+1:j+1] = subst # just inserts those lines
380          subst = ['\\begin_inset Box Frameless',
381              'position "' + tabularvalignment +'"',
382              'hor_pos "c"',
383              'has_inner_box 1',
384              'inner_pos "c"',
385              'use_parbox 0',
386              # we don't know the width, assume 50%
387              'width "50col%"',
388              'special "none"',
389              'height "1in"',
390              'height_special "totalheight"',
391              'status open',
392              '',
393              '\\begin_layout Plain Layout']
394          document.body[i:i] = subst # this just inserts the array at i
395          i += len(subst) + 2 # adjust i to save a few cycles
396
397
398 def revert_phantom(document):
399     " Reverts phantom to ERT "
400     i = 0
401     j = 0
402     while True:
403       i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
404       if i == -1:
405           return
406       substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
407                 '\\begin_inset ERT\nstatus collapsed\n\n' \
408                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
409                 'phantom{\n\\end_layout\n\n\\end_inset\n')
410       substi = substi.split('\n')
411       document.body[i : i+4] = substi
412       i += len(substi)
413       j = find_token(document.body, "\\end_layout", i)
414       if j == -1:
415           document.warning("Malformed LyX document: Could not find end of Phantom inset.")
416           return
417       substj = document.body[j].replace('\\end_layout', \
418                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
419                 '\\begin_layout Plain Layout\n\n' \
420                 '}\n\\end_layout\n\n\\end_inset\n')
421       substj = substj.split('\n')
422       document.body[j : j+4] = substj
423       i += len(substj)
424
425
426 def revert_hphantom(document):
427     " Reverts hphantom to ERT "
428     i = 0
429     j = 0
430     while True:
431       i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
432       if i == -1:
433           return
434       substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
435                 '\\begin_inset ERT\nstatus collapsed\n\n' \
436                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
437                 'hphantom{\n\\end_layout\n\n\\end_inset\n')
438       substi = substi.split('\n')
439       document.body[i : i+4] = substi
440       i += len(substi)
441       j = find_token(document.body, "\\end_layout", i)
442       if j == -1:
443           document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
444           return
445       substj = document.body[j].replace('\\end_layout', \
446                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
447                 '\\begin_layout Plain Layout\n\n' \
448                 '}\n\\end_layout\n\n\\end_inset\n')
449       substj = substj.split('\n')
450       document.body[j : j+4] = substj
451       i += len(substj)
452
453
454 def revert_vphantom(document):
455     " Reverts vphantom to ERT "
456     i = 0
457     j = 0
458     while True:
459       i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
460       if i == -1:
461           return
462       substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
463                 '\\begin_inset ERT\nstatus collapsed\n\n' \
464                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
465                 'vphantom{\n\\end_layout\n\n\\end_inset\n')
466       substi = substi.split('\n')
467       document.body[i : i+4] = substi
468       i += len(substi)
469       j = find_token(document.body, "\\end_layout", i)
470       if j == -1:
471           document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
472           return
473       substj = document.body[j].replace('\\end_layout', \
474                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
475                 '\\begin_layout Plain Layout\n\n' \
476                 '}\n\\end_layout\n\n\\end_inset\n')
477       substj = substj.split('\n')
478       document.body[j : j+4] = substj
479       i += len(substj)
480
481
482 def revert_xetex(document):
483     " Reverts documents that use XeTeX "
484     i = find_token(document.header, '\\use_xetex', 0)
485     if i == -1:
486         document.warning("Malformed LyX document: Missing \\use_xetex.")
487         return
488     if get_value(document.header, "\\use_xetex", i) == 'false':
489         del document.header[i]
490         return
491     del document.header[i]
492     # 1.) set doc encoding to utf8-plain
493     i = find_token(document.header, "\\inputencoding", 0)
494     if i == -1:
495         document.warning("Malformed LyX document: Missing \\inputencoding.")
496     document.header[i] = "\\inputencoding utf8-plain"
497     # 2.) check font settings
498     l = find_token(document.header, "\\font_roman", 0)
499     if l == -1:
500         document.warning("Malformed LyX document: Missing \\font_roman.")
501     line = document.header[l]
502     l = re.compile(r'\\font_roman (.*)$')
503     m = l.match(line)
504     roman = m.group(1)
505     l = find_token(document.header, "\\font_sans", 0)
506     if l == -1:
507         document.warning("Malformed LyX document: Missing \\font_sans.")
508     line = document.header[l]
509     l = re.compile(r'\\font_sans (.*)$')
510     m = l.match(line)
511     sans = m.group(1)
512     l = find_token(document.header, "\\font_typewriter", 0)
513     if l == -1:
514         document.warning("Malformed LyX document: Missing \\font_typewriter.")
515     line = document.header[l]
516     l = re.compile(r'\\font_typewriter (.*)$')
517     m = l.match(line)
518     typewriter = m.group(1)
519     osf = get_value(document.header, '\\font_osf', 0) == "true"
520     sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
521     tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
522     # 3.) set preamble stuff
523     pretext = '%% This document must be processed with xelatex!\n'
524     pretext += '\\usepackage{fontspec}\n'
525     if roman != "default":
526         pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
527     if sans != "default":
528         pretext += '\\setsansfont['
529         if sf_scale != 100:
530             pretext += 'Scale=' + str(sf_scale / 100) + ','
531         pretext += 'Mapping=tex-text]{' + sans + '}\n'
532     if typewriter != "default":
533         pretext += '\\setmonofont'
534         if tt_scale != 100:
535             pretext += '[Scale=' + str(tt_scale / 100) + ']'
536         pretext += '{' + typewriter + '}\n'
537     if osf:
538         pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
539     pretext += '\usepackage{xunicode}\n'
540     pretext += '\usepackage{xltxtra}\n'
541     insert_to_preamble(0, document, pretext)
542     # 4.) reset font settings
543     i = find_token(document.header, "\\font_roman", 0)
544     if i == -1:
545         document.warning("Malformed LyX document: Missing \\font_roman.")
546     document.header[i] = "\\font_roman default"
547     i = find_token(document.header, "\\font_sans", 0)
548     if i == -1:
549         document.warning("Malformed LyX document: Missing \\font_sans.")
550     document.header[i] = "\\font_sans default"
551     i = find_token(document.header, "\\font_typewriter", 0)
552     if i == -1:
553         document.warning("Malformed LyX document: Missing \\font_typewriter.")
554     document.header[i] = "\\font_typewriter default"
555     i = find_token(document.header, "\\font_osf", 0)
556     if i == -1:
557         document.warning("Malformed LyX document: Missing \\font_osf.")
558     document.header[i] = "\\font_osf false"
559     i = find_token(document.header, "\\font_sc", 0)
560     if i == -1:
561         document.warning("Malformed LyX document: Missing \\font_sc.")
562     document.header[i] = "\\font_sc false"
563     i = find_token(document.header, "\\font_sf_scale", 0)
564     if i == -1:
565         document.warning("Malformed LyX document: Missing \\font_sf_scale.")
566     document.header[i] = "\\font_sf_scale 100"
567     i = find_token(document.header, "\\font_tt_scale", 0)
568     if i == -1:
569         document.warning("Malformed LyX document: Missing \\font_tt_scale.")
570     document.header[i] = "\\font_tt_scale 100"
571
572
573 def revert_outputformat(document):
574     " Remove default output format param "
575     i = find_token(document.header, '\\default_output_format', 0)
576     if i == -1:
577         document.warning("Malformed LyX document: Missing \\default_output_format.")
578         return
579     del document.header[i]
580
581
582 def revert_backgroundcolor(document):
583     " Reverts background color to preamble code "
584     i = 0
585     colorcode = ""
586     while True:
587       i = find_token(document.header, "\\backgroundcolor", i)
588       if i == -1:
589           return
590       colorcode = get_value(document.header, '\\backgroundcolor', 0)
591       del document.header[i]
592       # don't clutter the preamble if backgroundcolor is not set
593       if colorcode == "#ffffff":
594           continue
595       # the color code is in the form #rrggbb where every character denotes a hex number
596       # convert the string to an int
597       red = string.atoi(colorcode[1:3],16)
598       # we want the output "0.5" for the value "127" therefore add here
599       if red != 0:
600           red = red + 1
601       redout = float(red) / 256
602       green = string.atoi(colorcode[3:5],16)
603       if green != 0:
604           green = green + 1
605       greenout = float(green) / 256
606       blue = string.atoi(colorcode[5:7],16)
607       if blue != 0:
608           blue = blue + 1
609       blueout = float(blue) / 256
610       # write the preamble
611       insert_to_preamble(0, document,
612                            '% Commands inserted by lyx2lyx to set the background color\n'
613                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
614                            + '\\definecolor{page_backgroundcolor}{rgb}{'
615                            + str(redout) + ', ' + str(greenout)
616                            + ', ' + str(blueout) + '}\n'
617                            + '\\pagecolor{page_backgroundcolor}\n')
618
619
620 def revert_splitindex(document):
621     " Reverts splitindex-aware documents "
622     i = find_token(document.header, '\\use_indices', 0)
623     if i == -1:
624         document.warning("Malformed LyX document: Missing \\use_indices.")
625         return
626     indices = get_value(document.header, "\\use_indices", i)
627     preamble = ""
628     if indices == "true":
629          preamble += "\\usepackage{splitidx}\n"
630     del document.header[i]
631     i = 0
632     while True:
633         i = find_token(document.header, "\\index", i)
634         if i == -1:
635             break
636         k = find_token(document.header, "\\end_index", i)
637         if k == -1:
638             document.warning("Malformed LyX document: Missing \\end_index.")
639             return
640         line = document.header[i]
641         l = re.compile(r'\\index (.*)$')
642         m = l.match(line)
643         iname = m.group(1)
644         ishortcut = get_value(document.header, '\\shortcut', i, k)
645         if ishortcut != "" and indices == "true":
646             preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
647         del document.header[i:k+1]
648         i = 0
649     if preamble != "":
650         insert_to_preamble(0, document, preamble)
651     i = 0
652     while True:
653         i = find_token(document.body, "\\begin_inset Index", i)
654         if i == -1:
655             break
656         line = document.body[i]
657         l = re.compile(r'\\begin_inset Index (.*)$')
658         m = l.match(line)
659         itype = m.group(1)
660         if itype == "idx" or indices == "false":
661             document.body[i] = "\\begin_inset Index"
662         else:
663             k = find_end_of_inset(document.body, i)
664             if k == -1:
665                  return
666             content = lyx2latex(document, document.body[i:k])
667             # escape quotes
668             content = content.replace('"', r'\"')
669             subst = [put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
670             document.body[i:k+1] = subst
671         i = i + 1
672     i = 0
673     while True:
674         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
675         if i == -1:
676             return
677         k = find_end_of_inset(document.body, i)
678         ptype = get_value(document.body, 'type', i, k).strip('"')
679         if ptype == "idx":
680             j = find_token(document.body, "type", i, k)
681             del document.body[j]
682         elif indices == "false":
683             del document.body[i:k+1]
684         else:
685             subst = [put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
686             document.body[i:k+1] = subst
687         i = i + 1
688
689
690 def convert_splitindex(document):
691     " Converts index and printindex insets to splitindex-aware format "
692     i = 0
693     while True:
694         i = find_token(document.body, "\\begin_inset Index", i)
695         if i == -1:
696             break
697         document.body[i] = document.body[i].replace("\\begin_inset Index",
698             "\\begin_inset Index idx")
699         i = i + 1
700     i = 0
701     while True:
702         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
703         if i == -1:
704             return
705         if document.body[i + 1].find('LatexCommand printindex') == -1:
706             document.warning("Malformed LyX document: Incomplete printindex inset.")
707             return
708         subst = ["LatexCommand printindex", 
709             "type \"idx\""]
710         document.body[i + 1:i + 2] = subst
711         i = i + 1
712
713
714 def revert_subindex(document):
715     " Reverts \\printsubindex CommandInset types "
716     i = find_token(document.header, '\\use_indices', 0)
717     if i == -1:
718         document.warning("Malformed LyX document: Missing \\use_indices.")
719         return
720     indices = get_value(document.header, "\\use_indices", i)
721     i = 0
722     while True:
723         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
724         if i == -1:
725             return
726         k = find_end_of_inset(document.body, i)
727         ctype = get_value(document.body, 'LatexCommand', i, k)
728         if ctype != "printsubindex":
729             i = i + 1
730             continue
731         ptype = get_value(document.body, 'type', i, k).strip('"')
732         if indices == "false":
733             del document.body[i:k+1]
734         else:
735             subst = [put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
736             document.body[i:k+1] = subst
737         i = i + 1
738
739
740 def revert_printindexall(document):
741     " Reverts \\print[sub]index* CommandInset types "
742     i = find_token(document.header, '\\use_indices', 0)
743     if i == -1:
744         document.warning("Malformed LyX document: Missing \\use_indices.")
745         return
746     indices = get_value(document.header, "\\use_indices", i)
747     i = 0
748     while True:
749         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
750         if i == -1:
751             return
752         k = find_end_of_inset(document.body, i)
753         ctype = get_value(document.body, 'LatexCommand', i, k)
754         if ctype != "printindex*" and ctype != "printsubindex*":
755             i = i + 1
756             continue
757         if indices == "false":
758             del document.body[i:k+1]
759         else:
760             subst = [put_cmd_in_ert("\\" + ctype + "{}")]
761             document.body[i:k+1] = subst
762         i = i + 1
763
764
765 def revert_strikeout(document):
766     " Reverts \\strikeout character style "
767     while True:
768         i = find_token(document.body, '\\strikeout', 0)
769         if i == -1:
770             return
771         del document.body[i]
772
773
774 def revert_uulinewave(document):
775     " Reverts \\uuline, and \\uwave character styles "
776     while True:
777         i = find_token(document.body, '\\uuline', 0)
778         if i == -1:
779             break
780         del document.body[i]
781     while True:
782         i = find_token(document.body, '\\uwave', 0)
783         if i == -1:
784             return
785         del document.body[i]
786
787
788 def revert_ulinelatex(document):
789     " Reverts \\uline character style "
790     i = find_token(document.body, '\\bar under', 0)
791     if i == -1:
792         return
793     insert_to_preamble(0, document,
794             '% Commands inserted by lyx2lyx for proper underlining\n'
795             + '\\PassOptionsToPackage{normalem}{ulem}\n'
796             + '\\usepackage{ulem}\n'
797             + '\\let\\cite@rig\\cite\n'
798             + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
799             + '  \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
800             + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
801
802
803 def revert_custom_processors(document):
804     " Remove bibtex_command and index_command params "
805     i = find_token(document.header, '\\bibtex_command', 0)
806     if i == -1:
807         document.warning("Malformed LyX document: Missing \\bibtex_command.")
808         return
809     del document.header[i]
810     i = find_token(document.header, '\\index_command', 0)
811     if i == -1:
812         document.warning("Malformed LyX document: Missing \\index_command.")
813         return
814     del document.header[i]
815
816
817 def convert_nomencl_width(document):
818     " Add set_width param to nomencl_print "
819     i = 0
820     while True:
821       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
822       if i == -1:
823         break
824       document.body.insert(i + 2, "set_width \"none\"")
825       i = i + 1
826
827
828 def revert_nomencl_width(document):
829     " Remove set_width param from nomencl_print "
830     i = 0
831     while True:
832       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
833       if i == -1:
834         break
835       j = find_end_of_inset(document.body, i)
836       l = find_token(document.body, "set_width", i, j)
837       if l == -1:
838             document.warning("Can't find set_width option for nomencl_print!")
839             i = j
840             continue
841       del document.body[l]
842       i = i + 1
843
844
845 def revert_nomencl_cwidth(document):
846     " Remove width param from nomencl_print "
847     i = 0
848     while True:
849       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
850       if i == -1:
851         break
852       j = find_end_of_inset(document.body, i)
853       l = find_token(document.body, "width", i, j)
854       if l == -1:
855             document.warning("Can't find width option for nomencl_print!")
856             i = j
857             continue
858       width = get_value(document.body, "width", i, j).strip('"')
859       del document.body[l]
860       add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
861       i = i + 1
862
863
864 def revert_applemac(document):
865     " Revert applemac encoding to auto "
866     i = 0
867     if document.encoding == "applemac":
868         document.encoding = "auto"
869         i = find_token(document.header, "\\encoding", 0)
870         if i != -1:
871             document.header[i] = "\\encoding auto"
872
873
874 def revert_longtable_align(document):
875     " Remove longtable alignment setting "
876     i = 0
877     j = 0
878     while True:
879       i = find_token(document.body, "\\begin_inset Tabular", i)
880       if i == -1:
881           break
882       # the alignment is 2 lines below \\begin_inset Tabular
883       j = document.body[i+2].find("longtabularalignment")
884       if j == -1:
885           break
886       document.body[i+2] = document.body[i+2][:j-1]
887       document.body[i+2] = document.body[i+2] + '>'
888       i = i + 1
889
890
891 def revert_branch_filename(document):
892     " Remove \\filename_suffix parameter from branches "
893     i = 0
894     while True:
895         i = find_token(document.header, "\\filename_suffix", i)
896         if i == -1:
897             return
898         del document.header[i]
899
900
901 def revert_paragraph_indentation(document):
902     " Revert custom paragraph indentation to preamble code "
903     i = 0
904     while True:
905       i = find_token(document.header, "\\paragraph_indentation", i)
906       if i == -1:
907           break
908       # only remove the preamble line when default
909       # otherwise also write the value to the preamble  
910       j = document.header[i].find("default")
911       if j > -1:
912           del document.header[i]
913           break
914       else:
915           # search for the beginning of the value via the space
916           j = document.header[i].find(" ")
917           length = document.header[i][j+1:]
918           # handle percent lengths
919           length = latex_length(length)
920           # latex_length returns "bool,length"
921           k = length.find(",")
922           length = length[k+1:]
923           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
924           add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
925           del document.header[i]
926       i = i + 1
927
928
929 def revert_percent_skip_lengths(document):
930     " Revert relative lengths for paragraph skip separation to preamble code "
931     i = 0
932     while True:
933       i = find_token(document.header, "\\defskip", i)
934       if i == -1:
935           break
936       # only revert when a custom length was set and when
937       # it used a percent length
938       j = document.header[i].find("smallskip")
939       k = document.header[i].find("medskip")
940       l = document.header[i].find("bigskip")
941       if (j > -1) or (k > -1) or (l > -1):
942           break
943       else:
944           # search for the beginning of the value via the space
945           j = document.header[i].find(" ")
946           length = document.header[i][j+1:]
947           # handle percent lengths
948           length = latex_length(length)
949           # latex_length returns "bool,length"
950           l = length.find(",")
951           percent = length[:l]
952           length = length[l+1:]
953           if percent == "True":
954               add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
955               add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
956               # set defskip to medskip as default
957               document.header[i] = "\\defskip medskip"
958       i = i + 1
959
960
961 def revert_percent_vspace_lengths(document):
962     " Revert relative VSpace lengths to ERT "
963     i = 0
964     while True:
965       i = find_token(document.body, "\\begin_inset VSpace", i)
966       if i == -1:
967           break
968       # only revert when a custom length was set and when
969       # it used a percent length
970       j = document.body[i].find("defskip")
971       k = document.body[i].find("smallskip")
972       l = document.body[i].find("medskip")
973       m = document.body[i].find("bigskip")
974       n = document.body[i].find("vfill")
975       if (j > -1) or (k > -1) or (l > -1) or (m > -1) or (n > -1):
976           break
977       else:
978           # search for the beginning of the value via the last space
979           o = document.body[i].rfind(" ")
980           length = document.body[i][o+1:]
981           # check if the space has a star (protected space)
982           p = document.body[i].rfind("*")
983           if p > -1:
984               length = length[:-1]
985           # handle percent lengths
986           length = latex_length(length)
987           # latex_length returns "bool,length"
988           q = length.find(",")
989           percent = length[:q]
990           length = length[q+1:]
991           # revert the VSpace inset to ERT
992           if percent == "True":
993               if p > -1:
994                   subst = [put_cmd_in_ert("\\vspace*{" + length + "}")]
995               else:
996                   subst = [put_cmd_in_ert("\\vspace{" + length + "}")]
997               document.body[i:i+2] = subst
998       i = i + 1
999
1000
1001 def revert_percent_hspace_lengths(document):
1002     " Revert relative HSpace lengths to ERT "
1003     i = 0
1004     j = 0
1005     while True:
1006       i = find_token(document.body, "\\begin_inset space \hspace{}", i)
1007       if i == -1:
1008           j = find_token(document.body, "\\begin_inset space \hspace*{}", j)
1009           if j == -1:
1010               break
1011           else:
1012               star = True
1013               i = j
1014       else:
1015           star = False
1016       # only revert when a custom length was set and when
1017       # it used a percent length
1018       o = document.body[i+1].find("\\length")
1019       if o == -1:
1020           document.warning("Error: Cannot find lenght for \\hspace!")
1021           break
1022       # search for the beginning of the value via the space
1023       k = document.body[i+1].find(" ")
1024       length = document.body[i+1][k+1:]
1025       # handle percent lengths
1026       length = latex_length(length)
1027       # latex_length returns "bool,length"
1028       m = length.find(",")
1029       percent = length[:m]
1030       length = length[m+1:]
1031       # revert the HSpace inset to ERT
1032       if percent == "True":
1033           if star == True:
1034               subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
1035           else:
1036               subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
1037           document.body[i:i+3] = subst
1038       i = i + 2
1039       j = i
1040
1041
1042 def revert_hspace_glue_lengths(document):
1043     " Revert HSpace glue lengths to ERT "
1044     i = 0
1045     j = 0
1046     while True:
1047       i = find_token(document.body, "\\begin_inset space \hspace{}", i)
1048       if i == -1:
1049           j = find_token(document.body, "\\begin_inset space \hspace*{}", j)
1050           if j == -1:
1051               break
1052           else:
1053               star = True
1054               i = j
1055       else:
1056           star = False
1057       # only revert when a custom length was set and when
1058       # it used a percent length
1059       o = document.body[i+1].find("\\length")
1060       if o == -1:
1061           document.warning("Error: Cannot find lenght for \\hspace!")
1062           break
1063       # search for the beginning of the value via the space
1064       k = document.body[i+1].find(" ")
1065       length = document.body[i+1][k+1:]
1066       # check if the length contains a plus or minus
1067       l = length.find("+")
1068       if l == -1:
1069           l = length.find("-")
1070           if l == -1:
1071               break
1072       # handle percent lengths
1073       length = latex_length(length)
1074       # latex_length returns "bool,length"
1075       m = length.find(",")
1076       percent = length[:m]
1077       length = length[m+1:]
1078       # revert the HSpace inset to ERT
1079       if percent == "True":
1080           if star == True:
1081               subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
1082           else:
1083               subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
1084           document.body[i:i+3] = subst
1085       i = i + 2
1086       j = i
1087
1088
1089 ##
1090 # Conversion hub
1091 #
1092
1093 supported_versions = ["2.0.0","2.0"]
1094 convert = [[346, []],
1095            [347, []],
1096            [348, []],
1097            [349, []],
1098            [350, []],
1099            [351, []],
1100            [352, [convert_splitindex]],
1101            [353, []],
1102            [354, []],
1103            [355, []],
1104            [356, []],
1105            [357, []],
1106            [358, []],
1107            [359, [convert_nomencl_width]],
1108            [360, []],
1109            [361, []],
1110            [362, []],
1111            [363, []],
1112            [364, []],
1113            [365, []],
1114            [366, []],
1115            [367, []],
1116            [368, []]
1117           ]
1118
1119 revert =  [[367, [revert_hspace_glue_lengths]],
1120            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1121            [365, [revert_percent_skip_lengths]],
1122            [364, [revert_paragraph_indentation]],
1123            [363, [revert_branch_filename]],
1124            [362, [revert_longtable_align]],
1125            [361, [revert_applemac]],
1126            [360, []],
1127            [359, [revert_nomencl_cwidth]],
1128            [358, [revert_nomencl_width]],
1129            [357, [revert_custom_processors]],
1130            [356, [revert_ulinelatex]],
1131            [355, [revert_uulinewave]],
1132            [354, [revert_strikeout]],
1133            [353, [revert_printindexall]],
1134            [352, [revert_subindex]],
1135            [351, [revert_splitindex]],
1136            [350, [revert_backgroundcolor]],
1137            [349, [revert_outputformat]],
1138            [348, [revert_xetex]],
1139            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1140            [346, [revert_tabularvalign]],
1141            [345, [revert_swiss]]
1142           ]
1143
1144
1145 if __name__ == "__main__":
1146     pass