]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_0.py
Fix the nameref reversion routine per a suggestion of Uwe's: We just
[lyx.git] / lib / lyx2lyx / lyx_2_0.py
1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2008 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 """ Convert files to the file format generated by lyx 2.0"""
21
22 import re, string
23 import unicodedata
24 import sys, os
25
26 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
27
28 ####################################################################
29 # Private helper functions
30
31 def remove_option(document, m, option):
32     l = document.body[m].find(option)
33     if l != -1:
34         val = document.body[m][l:].split('"')[1]
35         document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
36     return l
37
38 def find_end_of_inset(lines, i):
39     " Find end of inset, where lines[i] is included."
40     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
41
42
43 def add_to_preamble(document, text):
44     """ Add text to the preamble if it is not already there.
45     Only the first line is checked!"""
46
47     if not type(text) is list:
48       text = [text]
49
50     if find_token(document.preamble, text[0], 0) != -1:
51         return
52
53     document.preamble.extend(text)
54
55
56 def insert_to_preamble(index, document, text):
57     """ Insert text to the preamble at a given line"""
58
59     document.preamble.insert(index, text)
60
61
62 def read_unicodesymbols():
63     " Read the unicodesymbols list of unicode characters and corresponding commands."
64     pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
65     fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
66     spec_chars = []
67     # Two backslashes, followed by some non-word character, and then a character
68     # in brackets. The idea is to check for constructs like: \"{u}, which is how
69     # they are written in the unicodesymbols file; but they can also be written
70     # as: \"u or even \" u.
71     r = re.compile(r'\\\\(\W)\{(\w)\}')
72     for line in fp.readlines():
73         if line[0] != '#' and line.strip() != "":
74             line=line.replace(' "',' ') # remove all quotation marks with spaces before
75             line=line.replace('" ',' ') # remove all quotation marks with spaces after
76             line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
77             try:
78                 [ucs4,command,dead] = line.split(None,2)
79                 if command[0:1] != "\\":
80                     continue
81                 spec_chars.append([command, unichr(eval(ucs4))])
82             except:
83                 continue
84             m = r.match(command)
85             if m != None:
86                 command = "\\\\"
87                 # If the character is a double-quote, then we need to escape it, too,
88                 # since it is done that way in the LyX file.
89                 if m.group(1) == "\"":
90                     command += "\\"
91                 commandbl = command
92                 command += m.group(1) + m.group(2)
93                 commandbl += m.group(1) + ' ' + m.group(2)
94                 spec_chars.append([command, unichr(eval(ucs4))])
95                 spec_chars.append([commandbl, unichr(eval(ucs4))])
96     fp.close()
97     return spec_chars
98
99
100 unicode_reps = read_unicodesymbols()
101
102
103 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
104 # have been made of it with uses of put_cmd_in_ert.
105 def old_put_cmd_in_ert(string):
106     for rep in unicode_reps:
107         string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
108     string = string.replace('\\', "\\backslash\n")
109     string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
110       + string + "\n\\end_layout\n\\end_inset"
111     return string
112
113
114 # This routine wraps some content in an ERT inset. 
115 #
116 # NOTE: The function accepts either a single string or a LIST of strings as
117 # argument. But it returns a LIST of strings, split on \n, so that it does 
118 # not have embedded newlines.
119
120 # This is how lyx2lyx represents a LyX document: as a list of strings, 
121 # each representing a line of a LyX file. Embedded newlines confuse 
122 # lyx2lyx very much.
123 #
124 # A call to this routine will often go something like this:
125 #   i = find_token('\\begin_inset FunkyInset', ...)
126 #   ...
127 #   j = find_end_of_inset(document.body, i)
128 #   content = ...extract content from insets
129 #   # that could be as simple as: 
130 #   # content = lyx2latex(document[i:j + 1])
131 #   ert = put_cmd_in_ert(content)
132 #   document.body[i:j] = ert
133 # Now, before we continue, we need to reset i appropriately. Normally,
134 # this would be: 
135 #   i += len(ert)
136 # That puts us right after the ERT we just inserted.
137 #
138 def put_cmd_in_ert(arg):
139     ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
140     # Despite the warnings just given, it will be faster for us to work
141     # with a single string internally. That way, we only go through the
142     # unicode_reps loop once.
143     if type(arg) is list:
144       s = "\n".join(arg)
145     else:
146       s = arg
147     for rep in unicode_reps:
148       s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
149     s = s.replace('\\', "\\backslash\n")
150     ret += s.splitlines()
151     ret += ["\\end_layout", "\\end_inset"]
152     return ret
153
154             
155 def lyx2latex(document, lines):
156     'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
157     # clean up multiline stuff
158     content = ""
159     ert_end = 0
160     note_end = 0
161     hspace = ""
162
163     for curline in range(len(lines)):
164       line = lines[curline]
165       if line.startswith("\\begin_inset Note Note"):
166           # We want to skip LyX notes, so remember where the inset ends
167           note_end = find_end_of_inset(lines, curline + 1)
168           continue
169       elif note_end >= curline:
170           # Skip LyX notes
171           continue
172       elif line.startswith("\\begin_inset ERT"):
173           # We don't want to replace things inside ERT, so figure out
174           # where the end of the inset is.
175           ert_end = find_end_of_inset(lines, curline + 1)
176           continue
177       elif line.startswith("\\begin_inset Formula"):
178           line = line[20:]
179       elif line.startswith("\\begin_inset Quotes"):
180           # For now, we do a very basic reversion. Someone who understands
181           # quotes is welcome to fix it up.
182           qtype = line[20:].strip()
183           # lang = qtype[0]
184           side = qtype[1]
185           dbls = qtype[2]
186           if side == "l":
187               if dbls == "d":
188                   line = "``"
189               else:
190                   line = "`"
191           else:
192               if dbls == "d":
193                   line = "''"
194               else:
195                   line = "'"
196       elif line.startswith("\\begin_inset space"):
197           line = line[18:].strip()
198           if line.startswith("\\hspace"):
199               # Account for both \hspace and \hspace*
200               hspace = line[:-2]
201               continue
202           elif line == "\\space{}":
203               line = "\\ "
204           elif line == "\\thinspace{}":
205               line = "\\,"
206       elif hspace != "":
207           # The LyX length is in line[8:], after the \length keyword
208           # latex_length returns "bool,length"
209           length = latex_length(line[8:]).split(",")[1]
210           line = hspace + "{" + length + "}"
211           hspace = ""
212       elif line.isspace() or \
213             line.startswith("\\begin_layout") or \
214             line.startswith("\\end_layout") or \
215             line.startswith("\\begin_inset") or \
216             line.startswith("\\end_inset") or \
217             line.startswith("\\lang") or \
218             line.strip() == "status collapsed" or \
219             line.strip() == "status open":
220           #skip all that stuff
221           continue
222
223       # this needs to be added to the preamble because of cases like
224       # \textmu, \textbackslash, etc.
225       add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
226                                  '\\@ifundefined{textmu}',
227                                  ' {\\usepackage{textcomp}}{}'])
228       # a lossless reversion is not possible
229       # try at least to handle some common insets and settings
230       if ert_end >= curline:
231           line = line.replace(r'\backslash', '\\')
232       else:
233           # No need to add "{}" after single-nonletter macros
234           line = line.replace('&', '\\&')
235           line = line.replace('#', '\\#')
236           line = line.replace('^', '\\textasciicircum{}')
237           line = line.replace('%', '\\%')
238           line = line.replace('_', '\\_')
239           line = line.replace('$', '\\$')
240
241           # Do the LyX text --> LaTeX conversion
242           for rep in unicode_reps:
243             line = line.replace(rep[1], rep[0] + "{}")
244           line = line.replace(r'\backslash', r'\textbackslash{}')
245           line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
246           line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
247           line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
248           line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
249           line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
250           line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
251           line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
252           line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
253           line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
254       content += line
255     return content
256
257
258 def latex_length(string):
259     'Convert lengths to their LaTeX representation.'
260     i = 0
261     percent = False
262     # the string has the form
263     # ValueUnit+ValueUnit-ValueUnit or
264     # ValueUnit+-ValueUnit
265     # the + and - (glue lengths) are optional
266     # the + always precedes the -
267
268     # Convert relative lengths to LaTeX units
269     units = {"text%":"\\textwidth", "col%":"\\columnwidth",
270              "page%":"\\paperwidth", "line%":"\\linewidth",
271              "theight%":"\\textheight", "pheight%":"\\paperheight"}
272     for unit in units.keys():
273         i = string.find(unit)
274         if i != -1:
275             percent = True
276             minus = string.rfind("-", 1, i)
277             plus = string.rfind("+", 0, i)
278             latex_unit = units[unit]
279             if plus == -1 and minus == -1:
280                 value = string[:i]
281                 value = str(float(value)/100)
282                 end = string[i + len(unit):]
283                 string = value + latex_unit + end
284             if plus > minus:
285                 value = string[plus + 1:i]
286                 value = str(float(value)/100)
287                 begin = string[:plus + 1]
288                 end = string[i+len(unit):]
289                 string = begin + value + latex_unit + end
290             if plus < minus:
291                 value = string[minus + 1:i]
292                 value = str(float(value)/100)
293                 begin = string[:minus + 1]
294                 string = begin + value + latex_unit
295
296     # replace + and -, but only if the - is not the first character
297     string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
298     # handle the case where "+-1mm" was used, because LaTeX only understands
299     # "plus 1mm minus 1mm"
300     if string.find("plus  minus"):
301         lastvaluepos = string.rfind(" ")
302         lastvalue = string[lastvaluepos:]
303         string = string.replace("  ", lastvalue + " ")
304     if percent ==  False:
305         return "False," + string
306     else:
307         return "True," + string
308
309
310 def revert_flex_inset(document, name, LaTeXname, position):
311   " Convert flex insets to TeX code "
312   i = position
313   while True:
314     i = find_token(document.body, '\\begin_inset Flex ' + name, i)
315     if i == -1:
316       return
317     z = find_end_of_inset(document.body, i)
318     if z == -1:
319       document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
320       return
321     # remove the \end_inset
322     document.body[z - 2:z + 1] = put_cmd_in_ert("}")
323     # we need to reset character layouts if necessary
324     j = find_token(document.body, '\\emph on', i)
325     k = find_token(document.body, '\\noun on', i)
326     l = find_token(document.body, '\\series', i)
327     m = find_token(document.body, '\\family', i)
328     n = find_token(document.body, '\\shape', i)
329     o = find_token(document.body, '\\color', i)
330     p = find_token(document.body, '\\size', i)
331     q = find_token(document.body, '\\bar under', i)
332     r = find_token(document.body, '\\uuline on', i)
333     s = find_token(document.body, '\\uwave on', i)
334     t = find_token(document.body, '\\strikeout on', i)
335     if j != -1 and j < z:
336       document.body.insert(z - 2, "\\emph default")
337     if k != -1 and k < z:
338       document.body.insert(z - 2, "\\noun default")
339     if l != -1 and l < z:
340       document.body.insert(z - 2, "\\series default")
341     if m != -1 and m < z:
342       document.body.insert(z - 2, "\\family default")
343     if n != -1 and n < z:
344       document.body.insert(z - 2, "\\shape default")
345     if o != -1 and o < z:
346       document.body.insert(z - 2, "\\color inherit")
347     if p != -1 and p < z:
348       document.body.insert(z - 2, "\\size default")
349     if q != -1 and q < z:
350       document.body.insert(z - 2, "\\bar default")
351     if r != -1 and r < z:
352       document.body.insert(z - 2, "\\uuline default")
353     if s != -1 and s < z:
354       document.body.insert(z - 2, "\\uwave default")
355     if t != -1 and t < z:
356       document.body.insert(z - 2, "\\strikeout default")
357     document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
358     i += 1
359
360
361 def revert_charstyles(document, name, LaTeXname, changed):
362   " Reverts character styles to TeX code "
363   i = 0
364   while True:
365     i = find_token(document.body, name + ' on', i)
366     if i == -1:
367       return changed
368     j = find_token(document.body, name + ' default', i)
369     k = find_token(document.body, name + ' on', i + 1)
370     # if there is no default set, the style ends with the layout
371     # assure hereby that we found the correct layout end
372     if j != -1 and (j < k or k == -1):
373       document.body[j:j + 1] = put_cmd_in_ert("}")
374     else:
375       j = find_token(document.body, '\\end_layout', i)
376       document.body[j:j] = put_cmd_in_ert("}")
377     document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
378     changed = True
379     i += 1
380
381
382 def revert_layout_command(document, name, LaTeXname, position):
383   " Reverts a command from a layout to TeX code "
384   i = position
385   while True:
386     i = find_token(document.body, '\\begin_layout ' + name, i)
387     if i == -1:
388       return
389     k = -1
390     # find the next layout
391     j = i + 1
392     while k == -1:
393       j = find_token(document.body, '\\begin_layout', j)
394       l = len(document.body)
395       # if nothing was found it was the last layout of the document
396       if j == -1:
397         document.body[l - 4:l - 4] = put_cmd_in_ert("}")
398         k = 0
399       # exclude plain layout because this can be TeX code or another inset
400       elif document.body[j] != '\\begin_layout Plain Layout':
401         document.body[j - 2:j - 2] = put_cmd_in_ert("}")
402         k = 0
403       else:
404         j += 1
405     document.body[i] = '\\begin_layout Standard'
406     document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
407     i += 1
408
409
410 ####################################################################
411
412
413 def revert_swiss(document):
414     " Set language german-ch to ngerman "
415     i = 0
416     if document.language == "german-ch":
417         document.language = "ngerman"
418         i = find_token(document.header, "\\language", 0)
419         if i != -1:
420             document.header[i] = "\\language ngerman"
421     j = 0
422     while True:
423         j = find_token(document.body, "\\lang german-ch", j)
424         if j == -1:
425             return
426         document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
427         j = j + 1
428
429
430 def revert_tabularvalign(document):
431    " Revert the tabular valign option "
432    i = 0
433    while True:
434        i = find_token(document.body, "\\begin_inset Tabular", i)
435        if i == -1:
436            return
437        j = find_token(document.body, "</cell>", i)
438        if j == -1:
439            document.warning("Malformed LyX document: Could not find end of tabular cell.")
440            i = j
441            continue
442        # don't set a box for longtables, only delete tabularvalignment
443        # the alignment is 2 lines below \\begin_inset Tabular
444        p = document.body[i + 2].find("islongtable")
445        if p > -1:
446            q = document.body[i + 2].find("tabularvalignment")
447            if q > -1:
448                document.body[i + 2] = document.body[i + 2][:q - 1]
449                document.body[i + 2] = document.body[i + 2] + '>'
450            i = i + 1
451
452        # when no longtable
453        if p == -1:
454          tabularvalignment = 'c'
455          # which valignment is specified?
456          m = document.body[i + 2].find('tabularvalignment="top"')
457          if m > -1:
458              tabularvalignment = 't'
459          m = document.body[ i+ 2].find('tabularvalignment="bottom"')
460          if m > -1:
461              tabularvalignment = 'b'
462          # delete tabularvalignment
463          q = document.body[i + 2].find("tabularvalignment")
464          if q > -1:
465              document.body[i + 2] = document.body[i + 2][:q - 1]
466              document.body[i + 2] = document.body[i + 2] + '>'
467
468          # don't add a box when centered
469          if tabularvalignment == 'c':
470              i = j
471              continue
472          subst = ['\\end_layout', '\\end_inset']
473          document.body[j:j] = subst # just inserts those lines
474          subst = ['\\begin_inset Box Frameless',
475              'position "' + tabularvalignment +'"',
476              'hor_pos "c"',
477              'has_inner_box 1',
478              'inner_pos "c"',
479              'use_parbox 0',
480              # we don't know the width, assume 50%
481              'width "50col%"',
482              'special "none"',
483              'height "1in"',
484              'height_special "totalheight"',
485              'status open',
486              '',
487              '\\begin_layout Plain Layout']
488          document.body[i:i] = subst # this just inserts the array at i
489          i += len(subst) + 2 # adjust i to save a few cycles
490
491
492 def revert_phantom(document):
493     " Reverts phantom to ERT "
494     i = 0
495     j = 0
496     while True:
497       i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
498       if i == -1:
499           return
500       substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
501                 '\\begin_inset ERT\nstatus collapsed\n\n' \
502                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
503                 'phantom{\n\\end_layout\n\n\\end_inset\n')
504       substi = substi.split('\n')
505       document.body[i:i + 4] = substi
506       i += len(substi)
507       j = find_token(document.body, "\\end_layout", i)
508       if j == -1:
509           document.warning("Malformed LyX document: Could not find end of Phantom inset.")
510           return
511       substj = document.body[j].replace('\\end_layout', \
512                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
513                 '\\begin_layout Plain Layout\n\n' \
514                 '}\n\\end_layout\n\n\\end_inset\n')
515       substj = substj.split('\n')
516       document.body[j:j + 4] = substj
517       i += len(substj)
518
519
520 def revert_hphantom(document):
521     " Reverts hphantom to ERT "
522     i = 0
523     j = 0
524     while True:
525       i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
526       if i == -1:
527           return
528       substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
529                 '\\begin_inset ERT\nstatus collapsed\n\n' \
530                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
531                 'hphantom{\n\\end_layout\n\n\\end_inset\n')
532       substi = substi.split('\n')
533       document.body[i:i + 4] = substi
534       i += len(substi)
535       j = find_token(document.body, "\\end_layout", i)
536       if j == -1:
537           document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
538           return
539       substj = document.body[j].replace('\\end_layout', \
540                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
541                 '\\begin_layout Plain Layout\n\n' \
542                 '}\n\\end_layout\n\n\\end_inset\n')
543       substj = substj.split('\n')
544       document.body[j:j + 4] = substj
545       i += len(substj)
546
547
548 def revert_vphantom(document):
549     " Reverts vphantom to ERT "
550     i = 0
551     j = 0
552     while True:
553       i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
554       if i == -1:
555           return
556       substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
557                 '\\begin_inset ERT\nstatus collapsed\n\n' \
558                 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
559                 'vphantom{\n\\end_layout\n\n\\end_inset\n')
560       substi = substi.split('\n')
561       document.body[i:i + 4] = substi
562       i += len(substi)
563       j = find_token(document.body, "\\end_layout", i)
564       if j == -1:
565           document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
566           return
567       substj = document.body[j].replace('\\end_layout', \
568                 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
569                 '\\begin_layout Plain Layout\n\n' \
570                 '}\n\\end_layout\n\n\\end_inset\n')
571       substj = substj.split('\n')
572       document.body[j:j + 4] = substj
573       i += len(substj)
574
575
576 def revert_xetex(document):
577     " Reverts documents that use XeTeX "
578     i = find_token(document.header, '\\use_xetex', 0)
579     if i == -1:
580         document.warning("Malformed LyX document: Missing \\use_xetex.")
581         return
582     if get_value(document.header, "\\use_xetex", i) == 'false':
583         del document.header[i]
584         return
585     del document.header[i]
586     # 1.) set doc encoding to utf8-plain
587     i = find_token(document.header, "\\inputencoding", 0)
588     if i == -1:
589         document.warning("Malformed LyX document: Missing \\inputencoding.")
590     document.header[i] = "\\inputencoding utf8-plain"
591     # 2.) check font settings
592     l = find_token(document.header, "\\font_roman", 0)
593     if l == -1:
594         document.warning("Malformed LyX document: Missing \\font_roman.")
595     line = document.header[l]
596     l = re.compile(r'\\font_roman (.*)$')
597     m = l.match(line)
598     roman = m.group(1)
599     l = find_token(document.header, "\\font_sans", 0)
600     if l == -1:
601         document.warning("Malformed LyX document: Missing \\font_sans.")
602     line = document.header[l]
603     l = re.compile(r'\\font_sans (.*)$')
604     m = l.match(line)
605     sans = m.group(1)
606     l = find_token(document.header, "\\font_typewriter", 0)
607     if l == -1:
608         document.warning("Malformed LyX document: Missing \\font_typewriter.")
609     line = document.header[l]
610     l = re.compile(r'\\font_typewriter (.*)$')
611     m = l.match(line)
612     typewriter = m.group(1)
613     osf = get_value(document.header, '\\font_osf', 0) == "true"
614     sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
615     tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
616     # 3.) set preamble stuff
617     pretext = '%% This document must be processed with xelatex!\n'
618     pretext += '\\usepackage{fontspec}\n'
619     if roman != "default":
620         pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
621     if sans != "default":
622         pretext += '\\setsansfont['
623         if sf_scale != 100:
624             pretext += 'Scale=' + str(sf_scale / 100) + ','
625         pretext += 'Mapping=tex-text]{' + sans + '}\n'
626     if typewriter != "default":
627         pretext += '\\setmonofont'
628         if tt_scale != 100:
629             pretext += '[Scale=' + str(tt_scale / 100) + ']'
630         pretext += '{' + typewriter + '}\n'
631     if osf:
632         pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
633     pretext += '\usepackage{xunicode}\n'
634     pretext += '\usepackage{xltxtra}\n'
635     insert_to_preamble(0, document, pretext)
636     # 4.) reset font settings
637     i = find_token(document.header, "\\font_roman", 0)
638     if i == -1:
639         document.warning("Malformed LyX document: Missing \\font_roman.")
640     document.header[i] = "\\font_roman default"
641     i = find_token(document.header, "\\font_sans", 0)
642     if i == -1:
643         document.warning("Malformed LyX document: Missing \\font_sans.")
644     document.header[i] = "\\font_sans default"
645     i = find_token(document.header, "\\font_typewriter", 0)
646     if i == -1:
647         document.warning("Malformed LyX document: Missing \\font_typewriter.")
648     document.header[i] = "\\font_typewriter default"
649     i = find_token(document.header, "\\font_osf", 0)
650     if i == -1:
651         document.warning("Malformed LyX document: Missing \\font_osf.")
652     document.header[i] = "\\font_osf false"
653     i = find_token(document.header, "\\font_sc", 0)
654     if i == -1:
655         document.warning("Malformed LyX document: Missing \\font_sc.")
656     document.header[i] = "\\font_sc false"
657     i = find_token(document.header, "\\font_sf_scale", 0)
658     if i == -1:
659         document.warning("Malformed LyX document: Missing \\font_sf_scale.")
660     document.header[i] = "\\font_sf_scale 100"
661     i = find_token(document.header, "\\font_tt_scale", 0)
662     if i == -1:
663         document.warning("Malformed LyX document: Missing \\font_tt_scale.")
664     document.header[i] = "\\font_tt_scale 100"
665
666
667 def revert_outputformat(document):
668     " Remove default output format param "
669     i = find_token(document.header, '\\default_output_format', 0)
670     if i == -1:
671         document.warning("Malformed LyX document: Missing \\default_output_format.")
672         return
673     del document.header[i]
674
675
676 def revert_backgroundcolor(document):
677     " Reverts background color to preamble code "
678     i = 0
679     colorcode = ""
680     while True:
681       i = find_token(document.header, "\\backgroundcolor", i)
682       if i == -1:
683           return
684       colorcode = get_value(document.header, '\\backgroundcolor', 0)
685       del document.header[i]
686       # don't clutter the preamble if backgroundcolor is not set
687       if colorcode == "#ffffff":
688           continue
689       # the color code is in the form #rrggbb where every character denotes a hex number
690       # convert the string to an int
691       red = string.atoi(colorcode[1:3],16)
692       # we want the output "0.5" for the value "127" therefore add here
693       if red != 0:
694           red = red + 1
695       redout = float(red) / 256
696       green = string.atoi(colorcode[3:5],16)
697       if green != 0:
698           green = green + 1
699       greenout = float(green) / 256
700       blue = string.atoi(colorcode[5:7],16)
701       if blue != 0:
702           blue = blue + 1
703       blueout = float(blue) / 256
704       # write the preamble
705       insert_to_preamble(0, document,
706                            '% Commands inserted by lyx2lyx to set the background color\n'
707                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
708                            + '\\definecolor{page_backgroundcolor}{rgb}{'
709                            + str(redout) + ', ' + str(greenout)
710                            + ', ' + str(blueout) + '}\n'
711                            + '\\pagecolor{page_backgroundcolor}\n')
712
713
714 def revert_splitindex(document):
715     " Reverts splitindex-aware documents "
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     preamble = ""
722     if indices == "true":
723          preamble += "\\usepackage{splitidx}\n"
724     del document.header[i]
725     i = 0
726     while True:
727         i = find_token(document.header, "\\index", i)
728         if i == -1:
729             break
730         k = find_token(document.header, "\\end_index", i)
731         if k == -1:
732             document.warning("Malformed LyX document: Missing \\end_index.")
733             return
734         line = document.header[i]
735         l = re.compile(r'\\index (.*)$')
736         m = l.match(line)
737         iname = m.group(1)
738         ishortcut = get_value(document.header, '\\shortcut', i, k)
739         if ishortcut != "" and indices == "true":
740             preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
741         del document.header[i:k + 1]
742         i = 0
743     if preamble != "":
744         insert_to_preamble(0, document, preamble)
745     i = 0
746     while True:
747         i = find_token(document.body, "\\begin_inset Index", i)
748         if i == -1:
749             break
750         line = document.body[i]
751         l = re.compile(r'\\begin_inset Index (.*)$')
752         m = l.match(line)
753         itype = m.group(1)
754         if itype == "idx" or indices == "false":
755             document.body[i] = "\\begin_inset Index"
756         else:
757             k = find_end_of_inset(document.body, i)
758             if k == -1:
759                  return
760             content = lyx2latex(document, document.body[i:k])
761             # escape quotes
762             content = content.replace('"', r'\"')
763             subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
764             document.body[i:k + 1] = subst
765         i = i + 1
766     i = 0
767     while True:
768         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
769         if i == -1:
770             return
771         k = find_end_of_inset(document.body, i)
772         ptype = get_value(document.body, 'type', i, k).strip('"')
773         if ptype == "idx":
774             j = find_token(document.body, "type", i, k)
775             del document.body[j]
776         elif indices == "false":
777             del document.body[i:k + 1]
778         else:
779             subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
780             document.body[i:k + 1] = subst
781         i = i + 1
782
783
784 def convert_splitindex(document):
785     " Converts index and printindex insets to splitindex-aware format "
786     i = 0
787     while True:
788         i = find_token(document.body, "\\begin_inset Index", i)
789         if i == -1:
790             break
791         document.body[i] = document.body[i].replace("\\begin_inset Index",
792             "\\begin_inset Index idx")
793         i = i + 1
794     i = 0
795     while True:
796         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
797         if i == -1:
798             return
799         if document.body[i + 1].find('LatexCommand printindex') == -1:
800             document.warning("Malformed LyX document: Incomplete printindex inset.")
801             return
802         subst = ["LatexCommand printindex", 
803             "type \"idx\""]
804         document.body[i + 1:i + 2] = subst
805         i = i + 1
806
807
808 def revert_subindex(document):
809     " Reverts \\printsubindex CommandInset types "
810     i = find_token(document.header, '\\use_indices', 0)
811     if i == -1:
812         document.warning("Malformed LyX document: Missing \\use_indices.")
813         return
814     indices = get_value(document.header, "\\use_indices", i)
815     i = 0
816     while True:
817         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
818         if i == -1:
819             return
820         k = find_end_of_inset(document.body, i)
821         ctype = get_value(document.body, 'LatexCommand', i, k)
822         if ctype != "printsubindex":
823             i = i + 1
824             continue
825         ptype = get_value(document.body, 'type', i, k).strip('"')
826         if indices == "false":
827             del document.body[i:k + 1]
828         else:
829             subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
830             document.body[i:k + 1] = subst
831         i = i + 1
832
833
834 def revert_printindexall(document):
835     " Reverts \\print[sub]index* CommandInset types "
836     i = find_token(document.header, '\\use_indices', 0)
837     if i == -1:
838         document.warning("Malformed LyX document: Missing \\use_indices.")
839         return
840     indices = get_value(document.header, "\\use_indices", i)
841     i = 0
842     while True:
843         i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
844         if i == -1:
845             return
846         k = find_end_of_inset(document.body, i)
847         ctype = get_value(document.body, 'LatexCommand', i, k)
848         if ctype != "printindex*" and ctype != "printsubindex*":
849             i = i + 1
850             continue
851         if indices == "false":
852             del document.body[i:k + 1]
853         else:
854             subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
855             document.body[i:k + 1] = subst
856         i = i + 1
857
858
859 def revert_strikeout(document):
860   " Reverts \\strikeout character style "
861   changed = False
862   changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
863   changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
864   changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
865   if changed == True:
866     insert_to_preamble(0, document,
867         '% Commands inserted by lyx2lyx for proper underlining\n'
868         + '\\PassOptionsToPackage{normalem}{ulem}\n'
869         + '\\usepackage{ulem}\n')
870
871
872 def revert_ulinelatex(document):
873     " Reverts \\uline character style "
874     i = find_token(document.body, '\\bar under', 0)
875     if i == -1:
876         return
877     insert_to_preamble(0, document,
878             '% Commands inserted by lyx2lyx for proper underlining\n'
879             + '\\PassOptionsToPackage{normalem}{ulem}\n'
880             + '\\usepackage{ulem}\n'
881             + '\\let\\cite@rig\\cite\n'
882             + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
883             + '  \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
884             + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
885
886
887 def revert_custom_processors(document):
888     " Remove bibtex_command and index_command params "
889     i = find_token(document.header, '\\bibtex_command', 0)
890     if i == -1:
891         document.warning("Malformed LyX document: Missing \\bibtex_command.")
892         return
893     del document.header[i]
894     i = find_token(document.header, '\\index_command', 0)
895     if i == -1:
896         document.warning("Malformed LyX document: Missing \\index_command.")
897         return
898     del document.header[i]
899
900
901 def convert_nomencl_width(document):
902     " Add set_width param to nomencl_print "
903     i = 0
904     while True:
905       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
906       if i == -1:
907         break
908       document.body.insert(i + 2, "set_width \"none\"")
909       i = i + 1
910
911
912 def revert_nomencl_width(document):
913     " Remove set_width param from nomencl_print "
914     i = 0
915     while True:
916       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
917       if i == -1:
918         break
919       j = find_end_of_inset(document.body, i)
920       l = find_token(document.body, "set_width", i, j)
921       if l == -1:
922             document.warning("Can't find set_width option for nomencl_print!")
923             i = j
924             continue
925       del document.body[l]
926       i = i + 1
927
928
929 def revert_nomencl_cwidth(document):
930     " Remove width param from nomencl_print "
931     i = 0
932     while True:
933       i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
934       if i == -1:
935         break
936       j = find_end_of_inset(document.body, i)
937       l = find_token(document.body, "width", i, j)
938       if l == -1:
939             #Can't find width option for nomencl_print
940             i = j
941             continue
942       width = get_value(document.body, "width", i, j).strip('"')
943       del document.body[l]
944       add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
945       add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
946       i = i + 1
947
948
949 def revert_applemac(document):
950     " Revert applemac encoding to auto "
951     i = 0
952     if document.encoding == "applemac":
953         document.encoding = "auto"
954         i = find_token(document.header, "\\encoding", 0)
955         if i != -1:
956             document.header[i] = "\\encoding auto"
957
958
959 def revert_longtable_align(document):
960     " Remove longtable alignment setting "
961     i = 0
962     j = 0
963     while True:
964       i = find_token(document.body, "\\begin_inset Tabular", i)
965       if i == -1:
966           break
967       # the alignment is 2 lines below \\begin_inset Tabular
968       j = document.body[i + 2].find("longtabularalignment")
969       if j == -1:
970           break
971       document.body[i + 2] = document.body[i + 2][:j - 1]
972       document.body[i + 2] = document.body[i + 2] + '>'
973       i = i + 1
974
975
976 def revert_branch_filename(document):
977     " Remove \\filename_suffix parameter from branches "
978     i = 0
979     while True:
980         i = find_token(document.header, "\\filename_suffix", i)
981         if i == -1:
982             return
983         del document.header[i]
984
985
986 def revert_paragraph_indentation(document):
987     " Revert custom paragraph indentation to preamble code "
988     i = 0
989     while True:
990       i = find_token(document.header, "\\paragraph_indentation", i)
991       if i == -1:
992           break
993       # only remove the preamble line if default
994       # otherwise also write the value to the preamble
995       length = get_value(document.header, "\\paragraph_indentation", i)
996       if length == "default":
997           del document.header[i]
998           break
999       else:
1000           # handle percent lengths
1001           # latex_length returns "bool,length"
1002           length = latex_length(length).split(",")[1]
1003           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1004           add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
1005           del document.header[i]
1006       i = i + 1
1007
1008
1009 def revert_percent_skip_lengths(document):
1010     " Revert relative lengths for paragraph skip separation to preamble code "
1011     i = 0
1012     while True:
1013       i = find_token(document.header, "\\defskip", i)
1014       if i == -1:
1015           break
1016       length = get_value(document.header, "\\defskip", i)
1017       # only revert when a custom length was set and when
1018       # it used a percent length
1019       if length not in ('smallskip', 'medskip', 'bigskip'):
1020           # handle percent lengths
1021           length = latex_length(length)
1022           # latex_length returns "bool,length"
1023           percent = length.split(",")[0]
1024           length = length.split(",")[1]
1025           if percent == "True":
1026               add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1027               add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1028               # set defskip to medskip as default
1029               document.header[i] = "\\defskip medskip"
1030       i = i + 1
1031
1032
1033 def revert_percent_vspace_lengths(document):
1034     " Revert relative VSpace lengths to ERT "
1035     i = 0
1036     while True:
1037       i = find_token(document.body, "\\begin_inset VSpace", i)
1038       if i == -1:
1039           break
1040       # only revert if a custom length was set and if
1041       # it used a percent length
1042       line = document.body[i]
1043       r = re.compile(r'\\begin_inset VSpace (.*)$')
1044       m = r.match(line)
1045       length = m.group(1)
1046       if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1047           # check if the space has a star (protected space)
1048           protected = (document.body[i].rfind("*") != -1)
1049           if protected:
1050               length = length.rstrip('*')
1051           # handle percent lengths
1052           length = latex_length(length)
1053           # latex_length returns "bool,length"
1054           percent = length.split(",")[0]
1055           length = length.split(",")[1]
1056           # revert the VSpace inset to ERT
1057           if percent == "True":
1058               if protected:
1059                   subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1060               else:
1061                   subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1062               document.body[i:i + 2] = subst
1063       i = i + 1
1064
1065
1066 def revert_percent_hspace_lengths(document):
1067     " Revert relative HSpace lengths to ERT "
1068     i = 0
1069     while True:
1070       i = find_token(document.body, "\\begin_inset space \\hspace", i)
1071       if i == -1:
1072           break
1073       protected = (document.body[i].find("\\hspace*{}") != -1)
1074       # only revert if a custom length was set and if
1075       # it used a percent length
1076       length = get_value(document.body, '\\length', i + 1)
1077       if length == '':
1078           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1079           return
1080       # handle percent lengths
1081       length = latex_length(length)
1082       # latex_length returns "bool,length"
1083       percent = length.split(",")[0]
1084       length = length.split(",")[1]
1085       # revert the HSpace inset to ERT
1086       if percent == "True":
1087           if protected:
1088               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1089           else:
1090               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1091           document.body[i:i + 3] = subst
1092       i = i + 2
1093
1094
1095 def revert_hspace_glue_lengths(document):
1096     " Revert HSpace glue lengths to ERT "
1097     i = 0
1098     while True:
1099       i = find_token(document.body, "\\begin_inset space \\hspace", i)
1100       if i == -1:
1101           break
1102       protected = (document.body[i].find("\\hspace*{}") != -1)
1103       length = get_value(document.body, '\\length', i + 1)
1104       if length == '':
1105           document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1106           return
1107       # only revert if the length contains a plus or minus at pos != 0
1108       glue  = re.compile(r'.+[\+-]')
1109       if glue.search(length):
1110           # handle percent lengths
1111           # latex_length returns "bool,length"
1112           length = latex_length(length).split(",")[1]
1113           # revert the HSpace inset to ERT
1114           if protected:
1115               subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1116           else:
1117               subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1118           document.body[i:i + 3] = subst
1119       i = i + 2
1120
1121 def convert_author_id(document):
1122     " Add the author_id to the \\author definition and make sure 0 is not used"
1123     i = 0
1124     j = 1
1125     while True:
1126         i = find_token(document.header, "\\author", i)
1127         if i == -1:
1128             break
1129         
1130         r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1131         m = r.match(document.header[i])
1132         if m != None:
1133             name = m.group(2)
1134             
1135             email = ''
1136             if m.lastindex == 3:
1137                 email = m.group(3)
1138             document.header[i] = "\\author %i %s %s" % (j, name, email)
1139         j = j + 1
1140         i = i + 1
1141         
1142     k = 0
1143     while True:
1144         k = find_token(document.body, "\\change_", k)
1145         if k == -1:
1146             break
1147
1148         change = document.body[k].split(' ');
1149         if len(change) == 3:
1150             type = change[0]
1151             author_id = int(change[1])
1152             time = change[2]
1153             document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1154         k = k + 1
1155
1156 def revert_author_id(document):
1157     " Remove the author_id from the \\author definition "
1158     i = 0
1159     j = 0
1160     idmap = dict()
1161     while True:
1162         i = find_token(document.header, "\\author", i)
1163         if i == -1:
1164             break
1165         
1166         r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1167         m = r.match(document.header[i])
1168         if m != None:
1169             author_id = int(m.group(2))
1170             idmap[author_id] = j
1171             name = m.group(3)
1172             
1173             email = ''
1174             if m.lastindex == 4:
1175                 email = m.group(4)
1176             document.header[i] = "\\author %s %s" % (name, email)
1177         i = i + 1
1178         j = j + 1
1179
1180     k = 0
1181     while True:
1182         k = find_token(document.body, "\\change_", k)
1183         if k == -1:
1184             break
1185
1186         change = document.body[k].split(' ');
1187         if len(change) == 3:
1188             type = change[0]
1189             author_id = int(change[1])
1190             time = change[2]
1191             document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1192         k = k + 1
1193
1194
1195 def revert_suppress_date(document):
1196     " Revert suppressing of default document date to preamble code "
1197     i = 0
1198     while True:
1199       i = find_token(document.header, "\\suppress_date", i)
1200       if i == -1:
1201           break
1202       # remove the preamble line and write to the preamble
1203       # when suppress_date was true
1204       date = get_value(document.header, "\\suppress_date", i)
1205       if date == "true":
1206           add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1207           add_to_preamble(document, ["\\date{}"])
1208       del document.header[i]
1209       i = i + 1
1210
1211
1212 def revert_mhchem(document):
1213     "Revert mhchem loading to preamble code"
1214     i = 0
1215     j = 0
1216     k = 0
1217     mhchem = "off"
1218     i = find_token(document.header, "\\use_mhchem 1", 0)
1219     if i != -1:
1220         mhchem = "auto"
1221     else:
1222         i = find_token(document.header, "\\use_mhchem 2", 0)
1223         if i != -1:
1224             mhchem = "on"
1225     if mhchem == "auto":
1226         j = find_token(document.body, "\\cf{", 0)
1227         if j != -1:
1228             mhchem = "on"
1229         else:
1230             j = find_token(document.body, "\\ce{", 0)
1231             if j != -1:
1232                 mhchem = "on"
1233     if mhchem == "on":
1234         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1235         add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1236         add_to_preamble(document, ["\\usepackage{mhchem}"])
1237     k = find_token(document.header, "\\use_mhchem", 0)
1238     if k == -1:
1239         document.warning("Malformed LyX document: Could not find mhchem setting.")
1240         return
1241     del document.header[k]
1242
1243
1244 def revert_fontenc(document):
1245     " Remove fontencoding param "
1246     i = find_token(document.header, '\\fontencoding', 0)
1247     if i == -1:
1248         document.warning("Malformed LyX document: Missing \\fontencoding.")
1249         return
1250     del document.header[i]
1251
1252
1253 def merge_gbrief(document):
1254     " Merge g-brief-en and g-brief-de to one class "
1255
1256     if document.textclass != "g-brief-de":
1257         if document.textclass == "g-brief-en":
1258             document.textclass = "g-brief"
1259             document.set_textclass()
1260         return
1261
1262     obsoletedby = { "Brieftext":       "Letter",
1263                     "Unterschrift":    "Signature",
1264                     "Strasse":         "Street",
1265                     "Zusatz":          "Addition",
1266                     "Ort":             "Town",
1267                     "Land":            "State",
1268                     "RetourAdresse":   "ReturnAddress",
1269                     "MeinZeichen":     "MyRef",
1270                     "IhrZeichen":      "YourRef",
1271                     "IhrSchreiben":    "YourMail",
1272                     "Telefon":         "Phone",
1273                     "BLZ":             "BankCode",
1274                     "Konto":           "BankAccount",
1275                     "Postvermerk":     "PostalComment",
1276                     "Adresse":         "Address",
1277                     "Datum":           "Date",
1278                     "Betreff":         "Reference",
1279                     "Anrede":          "Opening",
1280                     "Anlagen":         "Encl.",
1281                     "Verteiler":       "cc",
1282                     "Gruss":           "Closing"}
1283     i = 0
1284     while 1:
1285         i = find_token(document.body, "\\begin_layout", i)
1286         if i == -1:
1287             break
1288
1289         layout = document.body[i][14:]
1290         if layout in obsoletedby:
1291             document.body[i] = "\\begin_layout " + obsoletedby[layout]
1292
1293         i += 1
1294         
1295     document.textclass = "g-brief"
1296     document.set_textclass()
1297
1298
1299 def revert_gbrief(document):
1300     " Revert g-brief to g-brief-en "
1301     if document.textclass == "g-brief":
1302         document.textclass = "g-brief-en"
1303         document.set_textclass()
1304
1305
1306 def revert_html_options(document):
1307     " Remove html options "
1308     i = find_token(document.header, '\\html_use_mathml', 0)
1309     if i != -1:
1310         del document.header[i]
1311     i = find_token(document.header, '\\html_be_strict', 0)
1312     if i != -1:
1313         del document.header[i]
1314
1315
1316 def revert_includeonly(document):
1317     i = 0
1318     while True:
1319         i = find_token(document.header, "\\begin_includeonly", i)
1320         if i == -1:
1321             return
1322         j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1323         if j == -1:
1324             # this should not happen
1325             break
1326         document.header[i : j + 1] = []
1327
1328
1329 def revert_includeall(document):
1330     " Remove maintain_unincluded_children param "
1331     i = find_token(document.header, '\\maintain_unincluded_children', 0)
1332     if i != -1:
1333         del document.header[i]
1334
1335
1336 def revert_multirow(document):
1337     " Revert multirow cells in tables "
1338     i = 0
1339     multirow = False
1340     while True:
1341       # cell type 3 is multirow begin cell
1342       i = find_token(document.body, '<cell multirow="3"', i)
1343       if i == -1:
1344           break
1345       # a multirow cell was found
1346       multirow = True
1347       # remove the multirow tag, set the valignment to top
1348       # and remove the bottom line
1349       document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1350       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1351       document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1352       # write ERT to create the multirow cell
1353       # use 2 rows and 2cm as default with because the multirow span
1354       # and the column width is only hardly accessible
1355       subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1356       document.body[i + 4:i + 4] = subst
1357       i = find_token(document.body, "</cell>", i)
1358       if i == -1:
1359            document.warning("Malformed LyX document: Could not find end of tabular cell.")
1360            break
1361       subst = [old_put_cmd_in_ert("}")]
1362       document.body[i - 3:i - 3] = subst
1363       # cell type 4 is multirow part cell
1364       i = find_token(document.body, '<cell multirow="4"', i)
1365       if i == -1:
1366           break
1367       # remove the multirow tag, set the valignment to top
1368       # and remove the top line
1369       document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1370       document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1371       document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1372       i = i + 1
1373     if multirow == True:
1374         add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1375         add_to_preamble(document, ["\\usepackage{multirow}"])
1376
1377
1378 def convert_math_output(document):
1379     " Convert \html_use_mathml to \html_math_output "
1380     i = find_token(document.header, "\\html_use_mathml", 0)
1381     if i == -1:
1382         return
1383     rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1384     m = rgx.match(document.header[i])
1385     if rgx:
1386         newval = "0" # MathML
1387         val = m.group(1)
1388         if val != "true":
1389             newval = "2" # Images
1390         document.header[i] = "\\html_math_output " + newval
1391
1392
1393 def revert_math_output(document):
1394     " Revert \html_math_output to \html_use_mathml "
1395     i = find_token(document.header, "\\html_math_output", 0)
1396     if i == -1:
1397         return
1398     rgx = re.compile(r'\\html_math_output\s+(\d)')
1399     m = rgx.match(document.header[i])
1400     newval = "true"
1401     if rgx:
1402         val = m.group(1)
1403         if val == "1" or val == "2":
1404             newval = "false"
1405     else:
1406         document.warning("Unable to match " + document.header[i])
1407     document.header[i] = "\\html_use_mathml " + newval
1408                 
1409
1410
1411 def revert_inset_preview(document):
1412     " Dissolves the preview inset "
1413     i = 0
1414     j = 0
1415     k = 0
1416     while True:
1417       i = find_token(document.body, "\\begin_inset Preview", i)
1418       if i == -1:
1419           return
1420       j = find_end_of_inset(document.body, i)
1421       if j == -1:
1422           document.warning("Malformed LyX document: Could not find end of Preview inset.")
1423           return
1424       #If the layout is Standard we need to remove it, otherwise there
1425       #will be paragraph breaks that shouldn't be there.
1426       k = find_token(document.body, "\\begin_layout Standard", i)
1427       if k == i + 2:
1428           del document.body[i:i + 3]
1429           del document.body[j - 5:j - 2]
1430           i -= 6
1431       else:
1432           del document.body[i]
1433           del document.body[j - 1]
1434           i -= 2
1435                 
1436
1437 def revert_equalspacing_xymatrix(document):
1438     " Revert a Formula with xymatrix@! to an ERT inset "
1439     i = 0
1440     j = 0
1441     has_preamble = False
1442     has_equal_spacing = False
1443     while True:
1444       found = -1
1445       i = find_token(document.body, "\\begin_inset Formula", i)
1446       if i == -1:
1447           break
1448       j = find_end_of_inset(document.body, i)
1449       if j == -1:
1450           document.warning("Malformed LyX document: Could not find end of Formula inset.")
1451           break
1452           
1453       for curline in range(i,j):
1454           found = document.body[curline].find("\\xymatrix@!")
1455           if found != -1:
1456               break
1457  
1458       if found != -1:
1459           has_equal_spacing = True
1460           content = [document.body[i][21:]]
1461           content += document.body[i + 1:j]
1462           subst = put_cmd_in_ert(content)
1463           document.body[i:j + 1] = subst
1464           i += len(subst)
1465       else:
1466           for curline in range(i,j):
1467               l = document.body[curline].find("\\xymatrix")
1468               if l != -1:
1469                   has_preamble = True;
1470                   break;
1471           i = j + 1
1472     if has_equal_spacing and not has_preamble:
1473         add_to_preamble(document, ['\\usepackage[all]{xy}'])
1474
1475
1476 def revert_notefontcolor(document):
1477     " Reverts greyed-out note font color to preamble code "
1478     i = 0
1479     colorcode = ""
1480     while True:
1481       i = find_token(document.header, "\\notefontcolor", i)
1482       if i == -1:
1483           return
1484       colorcode = get_value(document.header, '\\notefontcolor', 0)
1485       del document.header[i]
1486       # the color code is in the form #rrggbb where every character denotes a hex number
1487       # convert the string to an int
1488       red = string.atoi(colorcode[1:3],16)
1489       # we want the output "0.5" for the value "127" therefore increment here
1490       if red != 0:
1491           red = red + 1
1492       redout = float(red) / 256
1493       green = string.atoi(colorcode[3:5],16)
1494       if green != 0:
1495           green = green + 1
1496       greenout = float(green) / 256
1497       blue = string.atoi(colorcode[5:7],16)
1498       if blue != 0:
1499           blue = blue + 1
1500       blueout = float(blue) / 256
1501       # write the preamble
1502       insert_to_preamble(0, document,
1503                            '% Commands inserted by lyx2lyx to set the font color\n'
1504                            '% for greyed-out notes\n'
1505                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1506                            + '\\definecolor{note_fontcolor}{rgb}{'
1507                            + str(redout) + ', ' + str(greenout)
1508                            + ', ' + str(blueout) + '}\n'
1509                            + '\\renewenvironment{lyxgreyedout}\n'
1510                            + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1511
1512
1513 def revert_turkmen(document):
1514     "Set language Turkmen to English" 
1515     i = 0 
1516     if document.language == "turkmen": 
1517         document.language = "english" 
1518         i = find_token(document.header, "\\language", 0) 
1519         if i != -1: 
1520             document.header[i] = "\\language english" 
1521     j = 0 
1522     while True: 
1523         j = find_token(document.body, "\\lang turkmen", j) 
1524         if j == -1: 
1525             return 
1526         document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english") 
1527         j = j + 1 
1528
1529
1530 def revert_fontcolor(document):
1531     " Reverts font color to preamble code "
1532     i = 0
1533     colorcode = ""
1534     while True:
1535       i = find_token(document.header, "\\fontcolor", i)
1536       if i == -1:
1537           return
1538       colorcode = get_value(document.header, '\\fontcolor', 0)
1539       del document.header[i]
1540       # don't clutter the preamble if backgroundcolor is not set
1541       if colorcode == "#000000":
1542           continue
1543       # the color code is in the form #rrggbb where every character denotes a hex number
1544       # convert the string to an int
1545       red = string.atoi(colorcode[1:3],16)
1546       # we want the output "0.5" for the value "127" therefore add here
1547       if red != 0:
1548           red = red + 1
1549       redout = float(red) / 256
1550       green = string.atoi(colorcode[3:5],16)
1551       if green != 0:
1552           green = green + 1
1553       greenout = float(green) / 256
1554       blue = string.atoi(colorcode[5:7],16)
1555       if blue != 0:
1556           blue = blue + 1
1557       blueout = float(blue) / 256
1558       # write the preamble
1559       insert_to_preamble(0, document,
1560                            '% Commands inserted by lyx2lyx to set the font color\n'
1561                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1562                            + '\\definecolor{document_fontcolor}{rgb}{'
1563                            + str(redout) + ', ' + str(greenout)
1564                            + ', ' + str(blueout) + '}\n'
1565                            + '\\color{document_fontcolor}\n')
1566
1567
1568 def revert_shadedboxcolor(document):
1569     " Reverts shaded box color to preamble code "
1570     i = 0
1571     colorcode = ""
1572     while True:
1573       i = find_token(document.header, "\\boxbgcolor", i)
1574       if i == -1:
1575           return
1576       colorcode = get_value(document.header, '\\boxbgcolor', 0)
1577       del document.header[i]
1578       # the color code is in the form #rrggbb where every character denotes a hex number
1579       # convert the string to an int
1580       red = string.atoi(colorcode[1:3],16)
1581       # we want the output "0.5" for the value "127" therefore increment here
1582       if red != 0:
1583           red = red + 1
1584       redout = float(red) / 256
1585       green = string.atoi(colorcode[3:5],16)
1586       if green != 0:
1587           green = green + 1
1588       greenout = float(green) / 256
1589       blue = string.atoi(colorcode[5:7],16)
1590       if blue != 0:
1591           blue = blue + 1
1592       blueout = float(blue) / 256
1593       # write the preamble
1594       insert_to_preamble(0, document,
1595                            '% Commands inserted by lyx2lyx to set the color\n'
1596                            '% of boxes with shaded background\n'
1597                            + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1598                            + '\\definecolor{shadecolor}{rgb}{'
1599                            + str(redout) + ', ' + str(greenout)
1600                            + ', ' + str(blueout) + '}\n')
1601
1602
1603 def revert_lyx_version(document):
1604     " Reverts LyX Version information from Inset Info "
1605     version = "LyX version"
1606     try:
1607         import lyx2lyx_version
1608         version = lyx2lyx_version.version
1609     except:
1610         pass
1611
1612     i = 0
1613     while 1:
1614         i = find_token(document.body, '\\begin_inset Info', i)
1615         if i == -1:
1616             return
1617         j = find_end_of_inset(document.body, i + 1)
1618         if j == -1:
1619             # should not happen
1620             document.warning("Malformed LyX document: Could not find end of Info inset.")
1621         # We expect:
1622         # \begin_inset Info
1623         # type  "lyxinfo"
1624         # arg   "version"
1625         # \end_inset
1626         # but we shall try to be forgiving.
1627         arg = typ = ""
1628         for k in range(i, j):
1629             if document.body[k].startswith("arg"):
1630                 arg = document.body[k][3:].strip().strip('"')
1631             if document.body[k].startswith("type"):
1632                 typ = document.body[k][4:].strip().strip('"')
1633         if arg != "version" or typ != "lyxinfo":
1634             i = j + 1
1635             continue
1636
1637         # We do not actually know the version of LyX used to produce the document.
1638         # But we can use our version, since we are reverting.
1639         s = [version]
1640         # Now we want to check if the line after "\end_inset" is empty. It normally
1641         # is, so we want to remove it, too.
1642         lastline = j + 1
1643         if document.body[j + 1].strip() == "":
1644             lastline = j + 2
1645         document.body[i: lastline] = s
1646         i = i + 1
1647
1648
1649 def revert_math_scale(document):
1650   " Remove math scaling and LaTeX options "
1651   i = find_token(document.header, '\\html_math_img_scale', 0)
1652   if i != -1:
1653     del document.header[i]
1654   i = find_token(document.header, '\\html_latex_start', 0)
1655   if i != -1:
1656     del document.header[i]
1657   i = find_token(document.header, '\\html_latex_end', 0)
1658   if i != -1:
1659     del document.header[i]
1660
1661
1662 def revert_pagesizes(document):
1663   i = 0
1664   " Revert page sizes to default "
1665   i = find_token(document.header, '\\papersize', 0)
1666   if i != -1:
1667     size = document.header[i][11:]
1668     if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1669     or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1670     or size == "b2paper" or size == "b6paper" or size == "b0j" \
1671     or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1672     or size == "b5j" or size == "b6j":
1673       del document.header[i]
1674
1675
1676 def revert_DIN_C_pagesizes(document):
1677   i = 0
1678   " Revert DIN C page sizes to default "
1679   i = find_token(document.header, '\\papersize', 0)
1680   if i != -1:
1681     size = document.header[i][11:]
1682     if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1683     or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1684     or size == "c6paper":
1685       del document.header[i]
1686
1687
1688 def convert_html_quotes(document):
1689   " Remove quotes around html_latex_start and html_latex_end "
1690
1691   i = find_token(document.header, '\\html_latex_start', 0)
1692   if i != -1:
1693     line = document.header[i]
1694     l = re.compile(r'\\html_latex_start\s+"(.*)"')
1695     m = l.match(line)
1696     if m != None:
1697       document.header[i] = "\\html_latex_start " + m.group(1)
1698       
1699   i = find_token(document.header, '\\html_latex_end', 0)
1700   if i != -1:
1701     line = document.header[i]
1702     l = re.compile(r'\\html_latex_end\s+"(.*)"')
1703     m = l.match(line)
1704     if m != None:
1705       document.header[i] = "\\html_latex_end " + m.group(1)
1706       
1707
1708 def revert_html_quotes(document):
1709   " Remove quotes around html_latex_start and html_latex_end "
1710   
1711   i = find_token(document.header, '\\html_latex_start', 0)
1712   if i != -1:
1713     line = document.header[i]
1714     l = re.compile(r'\\html_latex_start\s+(.*)')
1715     m = l.match(line)
1716     document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1717       
1718   i = find_token(document.header, '\\html_latex_end', 0)
1719   if i != -1:
1720     line = document.header[i]
1721     l = re.compile(r'\\html_latex_end\s+(.*)')
1722     m = l.match(line)
1723     document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1724
1725
1726 def revert_output_sync(document):
1727   " Remove forward search options "
1728   i = find_token(document.header, '\\output_sync_macro', 0)
1729   if i != -1:
1730     del document.header[i]
1731   i = find_token(document.header, '\\output_sync', 0)
1732   if i != -1:
1733     del document.header[i]
1734
1735
1736 def convert_beamer_args(document):
1737   " Convert ERT arguments in Beamer to InsetArguments "
1738
1739   if document.textclass != "beamer" and document.textclass != "article-beamer":
1740     return
1741   
1742   layouts = ("Block", "ExampleBlock", "AlertBlock")
1743   for layout in layouts:
1744     blay = 0
1745     while True:
1746       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1747       if blay == -1:
1748         break
1749       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1750       if elay == -1:
1751         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1752         blay += 1
1753         continue
1754       bert = find_token(document.body, '\\begin_inset ERT', blay)
1755       if bert == -1:
1756         document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1757         blay = elay + 1
1758         continue
1759       eert = find_end_of_inset(document.body, bert)
1760       if eert == -1:
1761         document.warning("Malformed LyX document: Can't find end of ERT.")
1762         blay = elay + 1
1763         continue
1764       
1765       # So the ERT inset begins at line k and goes to line l. We now wrap it in 
1766       # an argument inset.
1767       # Do the end first, so as not to mess up the variables.
1768       document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1769       document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '', 
1770           '\\begin_layout Plain Layout']
1771       blay = elay + 9
1772
1773
1774 def revert_beamer_args(document):
1775   " Revert Beamer arguments to ERT "
1776   
1777   if document.textclass != "beamer" and document.textclass != "article-beamer":
1778     return
1779     
1780   layouts = ("Block", "ExampleBlock", "AlertBlock")
1781   for layout in layouts:
1782     blay = 0
1783     while True:
1784       blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1785       if blay == -1:
1786         break
1787       elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1788       if elay == -1:
1789         document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1790         blay += 1
1791         continue
1792       bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1793       if bopt == -1:
1794         # it is legal not to have one of these
1795         blay = elay + 1
1796         continue
1797       eopt = find_end_of_inset(document.body, bopt)
1798       if eopt == -1:
1799         document.warning("Malformed LyX document: Can't find end of argument.")
1800         blay = elay + 1
1801         continue
1802       bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1803       if bplay == -1:
1804         document.warning("Malformed LyX document: Can't find plain layout.")
1805         blay = elay + 1
1806         continue
1807       eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1808       if eplay == -1:
1809         document.warning("Malformed LyX document: Can't find end of plain layout.")
1810         blay = elay + 1
1811         continue
1812       # So the content of the argument inset goes from bplay + 1 to eplay - 1
1813       bcont = bplay + 1
1814       if bcont >= eplay:
1815         # Hmm.
1816         document.warning(str(bcont) + " " + str(eplay))
1817         blay = blay + 1
1818         continue
1819       # we convert the content of the argument into pure LaTeX...
1820       content = lyx2latex(document, document.body[bcont:eplay])
1821       strlist = put_cmd_in_ert(["{" + content + "}"])
1822       
1823       # now replace the optional argument with the ERT
1824       document.body[bopt:eopt + 1] = strlist
1825       blay = blay + 1
1826
1827
1828 def revert_align_decimal(document):
1829   l = 0
1830   while True:
1831     l = document.body[l].find('alignment=decimal')
1832     if l == -1:
1833         break
1834     remove_option(document, l, 'decimal_point')
1835     document.body[l].replace('decimal', 'center')
1836
1837
1838 def convert_optarg(document):
1839   " Convert \\begin_inset OptArg to \\begin_inset Argument "
1840   i = 0
1841   while 1:
1842     i = find_token(document.body, '\\begin_inset OptArg', i)
1843     if i == -1:
1844       return
1845     document.body[i] = "\\begin_inset Argument"
1846     i += 1
1847
1848
1849 def revert_argument(document):
1850   " Convert \\begin_inset Argument to \\begin_inset OptArg "
1851   i = 0
1852   while 1:
1853     i = find_token(document.body, '\\begin_inset Argument', i)
1854     if i == -1:
1855       return
1856     document.body[i] = "\\begin_inset OptArg"
1857     i += 1
1858
1859
1860 def revert_makebox(document):
1861   " Convert \\makebox to TeX code "
1862   i = 0
1863   while 1:
1864     # only revert frameless boxes without an inner box
1865     i = find_token(document.body, '\\begin_inset Box Frameless', i)
1866     if i == -1:
1867       # remove the option use_makebox
1868       revert_use_makebox(document)
1869       return
1870     z = find_end_of_inset(document.body, i)
1871     if z == -1:
1872       document.warning("Malformed LyX document: Can't find end of box inset.")
1873       return
1874     j = find_token(document.body, 'use_makebox 1', i)
1875     # assure we found the makebox of the current box
1876     if j < z and j != -1:
1877       y = find_token(document.body, "\\begin_layout", i)
1878       if y > z or y == -1:
1879         document.warning("Malformed LyX document: Can't find layout in box.")
1880         return
1881       # remove the \end_layout \end_inset pair
1882       document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1883       # determine the alignment
1884       k = find_token(document.body, 'hor_pos', j - 4)
1885       align = document.body[k][9]
1886       # determine the width
1887       l = find_token(document.body, 'width "', j + 1)
1888       length = document.body[l][7:]
1889       # remove trailing '"'
1890       length = length[:-1]
1891       # latex_length returns "bool,length"
1892       length = latex_length(length).split(",")[1]
1893       subst = "\\makebox[" + length + "][" \
1894         + align + "]{"
1895       document.body[i:y + 1] = put_cmd_in_ert(subst)
1896     i += 1
1897
1898
1899 def revert_use_makebox(document):
1900   " Deletes use_makebox option of boxes "
1901   h = 0
1902   while 1:
1903     # remove the option use_makebox
1904     h = find_token(document.body, 'use_makebox', 0)
1905     if h == -1:
1906       return
1907     del document.body[h]
1908     h += 1
1909
1910
1911 def revert_IEEEtran(document):
1912   " Convert IEEEtran layouts and styles to TeX code "
1913   if document.textclass != "IEEEtran":
1914     return
1915
1916   revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1917   revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1918
1919   layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1920              "Page headings", "Biography without photo")
1921
1922   latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1923               "After Title Text":     "\\IEEEaftertitletext",
1924               "Publication ID":       "\\IEEEpubid"}
1925
1926   obsoletedby = {"Page headings":            "MarkBoth",
1927                  "Biography without photo":  "BiographyNoPhoto"}
1928
1929   for layout in layouts:
1930     i = 0
1931     while True:
1932         i = find_token(document.body, '\\begin_layout ' + layout, i)
1933         if i == -1:
1934           break
1935         j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1936         if j == -1:
1937           document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1938           i += 1
1939           continue
1940         if layout in obsoletedby:
1941           document.body[i] = "\\begin_layout " + obsoletedby[layout]
1942           i = j
1943         else:
1944           content = lyx2latex(document, document.body[i:j + 1])
1945           add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1946           del document.body[i:j + 1]
1947
1948
1949 def revert_nameref(document):
1950   " Convert namerefs to regular references "
1951   cmds = ["Nameref", "nameref"]
1952   foundone = False
1953   rx = re.compile(r'reference "(.*)"')
1954   for cmd in cmds:
1955     i = 0
1956     oldcmd = "LatexCommand " + cmd
1957     while 1:
1958       # It seems better to look for this, as most of the reference
1959       # insets won't be ones we care about.
1960       i = find_token(document.body, oldcmd, i)
1961       if i == -1:
1962         break
1963       cmdloc = i
1964       i += 1
1965       
1966       # Make sure it is actually in an inset!
1967       # We could just check document.lines[i-1], but that relies
1968       # upon something that might easily change.
1969       # We'll look back a few lines.
1970       stins = cmdloc - 10
1971       if stins < 0:
1972         stins = 0
1973       stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
1974       if stins == -1 or stins > cmdloc:
1975         continue
1976       endins = find_end_of_inset(document.body, stins)
1977       if endins == -1:
1978         document.warning("Can't find end of inset at line " + stins + "!!")
1979         continue
1980       if endins < cmdloc:
1981         continue
1982       refline = find_token(document.body, "reference", stins)
1983       if refline == -1 or refline > endins:
1984         document.warning("Can't find reference for inset at line " + stinst + "!!")
1985         continue
1986       m = rx.match(document.body[refline])
1987       if not m:
1988         document.warning("Can't match reference line: " + document.body[ref])
1989         continue
1990       foundone = True
1991       ref = m.group(1)
1992       newcontent = ['\\begin_inset ERT', 'status collapsed', '', \
1993         '\\begin_layout Plain Layout', '', '\\backslash', \
1994         cmd + '{' + ref + '}', '\\end_layout', '', '\\end_inset']
1995       document.body[stins:endins + 1] = newcontent
1996   if foundone:
1997     add_to_preamble(document, "\usepackage{nameref}")
1998
1999
2000
2001
2002 ##
2003 # Conversion hub
2004 #
2005
2006 supported_versions = ["2.0.0","2.0"]
2007 convert = [[346, []],
2008            [347, []],
2009            [348, []],
2010            [349, []],
2011            [350, []],
2012            [351, []],
2013            [352, [convert_splitindex]],
2014            [353, []],
2015            [354, []],
2016            [355, []],
2017            [356, []],
2018            [357, []],
2019            [358, []],
2020            [359, [convert_nomencl_width]],
2021            [360, []],
2022            [361, []],
2023            [362, []],
2024            [363, []],
2025            [364, []],
2026            [365, []],
2027            [366, []],
2028            [367, []],
2029            [368, []],
2030            [369, [convert_author_id]],
2031            [370, []],
2032            [371, []],
2033            [372, []],
2034            [373, [merge_gbrief]],
2035            [374, []],
2036            [375, []],
2037            [376, []],
2038            [377, []],
2039            [378, []],
2040            [379, [convert_math_output]],
2041            [380, []],
2042            [381, []],
2043            [382, []],
2044            [383, []],
2045            [384, []],
2046            [385, []],
2047            [386, []],
2048            [387, []],
2049            [388, []],
2050            [389, [convert_html_quotes]],
2051            [390, []],
2052            [391, []],
2053            [392, [convert_beamer_args]],
2054            [393, [convert_optarg]],
2055            [394, []],
2056            [395, []],
2057            [396, []]
2058           ]
2059
2060 revert =  [[395, [revert_nameref]],
2061            [394, [revert_DIN_C_pagesizes]],
2062            [393, [revert_makebox]],
2063            [392, [revert_argument]],
2064            [391, [revert_beamer_args]],
2065            [390, [revert_align_decimal, revert_IEEEtran]],
2066            [389, [revert_output_sync]],
2067            [388, [revert_html_quotes]],
2068            [387, [revert_pagesizes]],
2069            [386, [revert_math_scale]],
2070            [385, [revert_lyx_version]],
2071            [384, [revert_shadedboxcolor]],
2072            [383, [revert_fontcolor]],
2073            [382, [revert_turkmen]],
2074            [381, [revert_notefontcolor]],
2075            [380, [revert_equalspacing_xymatrix]],
2076            [379, [revert_inset_preview]],
2077            [378, [revert_math_output]],
2078            [377, []],
2079            [376, [revert_multirow]],
2080            [375, [revert_includeall]],
2081            [374, [revert_includeonly]],
2082            [373, [revert_html_options]],
2083            [372, [revert_gbrief]],
2084            [371, [revert_fontenc]],
2085            [370, [revert_mhchem]],
2086            [369, [revert_suppress_date]],
2087            [368, [revert_author_id]],
2088            [367, [revert_hspace_glue_lengths]],
2089            [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2090            [365, [revert_percent_skip_lengths]],
2091            [364, [revert_paragraph_indentation]],
2092            [363, [revert_branch_filename]],
2093            [362, [revert_longtable_align]],
2094            [361, [revert_applemac]],
2095            [360, []],
2096            [359, [revert_nomencl_cwidth]],
2097            [358, [revert_nomencl_width]],
2098            [357, [revert_custom_processors]],
2099            [356, [revert_ulinelatex]],
2100            [355, []],
2101            [354, [revert_strikeout]],
2102            [353, [revert_printindexall]],
2103            [352, [revert_subindex]],
2104            [351, [revert_splitindex]],
2105            [350, [revert_backgroundcolor]],
2106            [349, [revert_outputformat]],
2107            [348, [revert_xetex]],
2108            [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2109            [346, [revert_tabularvalign]],
2110            [345, [revert_swiss]]
2111           ]
2112
2113
2114 if __name__ == "__main__":
2115     pass