]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_1_6.py
ff6bb8fe023780a2ab64018b0e4c45224ccf8b95
[lyx.git] / lib / lyx2lyx / lyx_1_6.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2007-2008 The LyX Team <lyx-devel@lists.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 1.6"""
20
21 import re
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 # WARNING!
35 # DO NOT do this:
36 #   document.body[i] = wrap_insert_ert(...)
37 # wrap_into_ert may returns a multiline string, which should NOT appear
38 # in document.body. Insetad, do something like this:
39 #   subst = wrap_inset_ert(...)
40 #   subst = subst.split('\n')
41 #   document.body[i:i+1] = subst
42 #   i+= len(subst) - 1
43 # where the last statement resets the counter to accord with the added
44 # lines.
45 def wrap_into_ert(string, src, dst):
46     " Wrap a something into an ERT"
47     return string.replace(src, '\n\\begin_inset ERT\nstatus collapsed\n\\begin_layout Standard\n'
48       + dst + '\n\\end_layout\n\\end_inset\n')
49
50 def add_to_preamble(document, text):
51     """ Add text to the preamble if it is not already there.
52     Only the first line is checked!"""
53
54     if find_token(document.preamble, text[0], 0) != -1:
55         return
56
57     document.preamble.extend(text)
58
59 # Convert a LyX length into a LaTeX length
60 def convert_len(len):
61     units = {"text%":"\\backslash\ntextwidth", "col%":"\\backslash\ncolumnwidth",
62              "page%":"\\backslash\npagewidth", "line%":"\\backslash\nlinewidth",
63              "theight%":"\\backslash\ntextheight", "pheight%":"\\backslash\npageheight"}
64
65     # Convert LyX units to LaTeX units
66     for unit in units.keys():
67         if len.find(unit) != -1:
68             len = '%f' % (len2value(len) / 100)
69             len = len.strip('0') + units[unit]
70             break
71
72     return len
73
74 # Return the value of len without the unit in numerical form.
75 def len2value(len):
76     result = re.search('([+-]?[0-9.]+)', len)
77     if result:
78         return float(result.group(1))
79     # No number means 1.0
80     return 1.0
81
82 # Unfortunately, this doesn't really work, since Standard isn't always default.
83 # But it's as good as we can do right now.
84 def find_default_layout(document, start, end):
85     l = find_token(document.body, "\\begin_layout Standard", start, end)
86     if l == -1:
87         l = find_token(document.body, "\\begin_layout PlainLayout", start, end)
88     if l == -1:
89         l = find_token(document.body, "\\begin_layout Plain Layout", start, end)
90     return l
91
92 def get_option(document, m, option, default):
93     l = document.body[m].find(option)
94     val = default
95     if l != -1:
96         val = document.body[m][l:].split('"')[1]
97     return val
98
99 def remove_option(document, m, option):
100     l = document.body[m].find(option)
101     if l != -1:
102         val = document.body[m][l:].split('"')[1]
103         document.body[m] = document.body[m][:l-1] + document.body[m][l+len(option + '="' + val + '"'):]
104     return l
105
106 def set_option(document, m, option, value):
107     l = document.body[m].find(option)
108     if l != -1:
109         oldval = document.body[m][l:].split('"')[1]
110         l = l + len(option + '="')
111         document.body[m] = document.body[m][:l] + value + document.body[m][l+len(oldval):]
112     else:
113         document.body[m] = document.body[m][:-1] + ' ' + option + '="' + value + '">'
114     return l
115
116
117 ####################################################################
118
119 def convert_ltcaption(document):
120     i = 0
121     while True:
122         i = find_token(document.body, "\\begin_inset Tabular", i)
123         if i == -1:
124             return
125         j = find_end_of_inset(document.body, i + 1)
126         if j == -1:
127             document.warning("Malformed LyX document: Could not find end of tabular.")
128             continue
129
130         nrows = int(document.body[i+1].split('"')[3])
131         ncols = int(document.body[i+1].split('"')[5])
132
133         m = i + 1
134         for k in range(nrows):
135             m = find_token(document.body, "<row", m)
136             r = m
137             caption = 'false'
138             for k in range(ncols):
139                 m = find_token(document.body, "<cell", m)
140                 if (k == 0):
141                     mend = find_token(document.body, "</cell>", m + 1)
142                     # first look for caption insets
143                     mcap = find_token(document.body, "\\begin_inset Caption", m + 1, mend)
144                     # then look for ERT captions
145                     if mcap == -1:
146                         mcap = find_token(document.body, "caption", m + 1, mend)
147                         if mcap > -1:
148                             mcap = find_token(document.body, "\\backslash", mcap - 1, mcap)
149                     if mcap > -1:
150                         caption = 'true'
151                 if caption == 'true':
152                     if (k == 0):
153                         set_option(document, r, 'caption', 'true')
154                         set_option(document, m, 'multicolumn', '1')
155                         set_option(document, m, 'bottomline', 'false')
156                         set_option(document, m, 'topline', 'false')
157                         set_option(document, m, 'rightline', 'false')
158                         set_option(document, m, 'leftline', 'false')
159                         #j = find_end_of_inset(document.body, j + 1)
160                     else:
161                         set_option(document, m, 'multicolumn', '2')
162                 m = m + 1
163             m = m + 1
164
165         i = j + 1
166
167
168 #FIXME Use of wrap_into_ert can confuse lyx2lyx
169 def revert_ltcaption(document):
170     i = 0
171     while True:
172         i = find_token(document.body, "\\begin_inset Tabular", i)
173         if i == -1:
174             return
175         j = find_end_of_inset(document.body, i + 1)
176         if j == -1:
177             document.warning("Malformed LyX document: Could not find end of tabular.")
178             continue
179
180         m = i + 1
181         nrows = int(document.body[i+1].split('"')[3])
182         ncols = int(document.body[i+1].split('"')[5])
183
184         for k in range(nrows):
185             m = find_token(document.body, "<row", m)
186             caption = get_option(document, m, 'caption', 'false')
187             if caption == 'true':
188                 remove_option(document, m, 'caption')
189                 for k in range(ncols):
190                     m = find_token(document.body, "<cell", m)
191                     remove_option(document, m, 'multicolumn')
192                     if k == 0:
193                         m = find_token(document.body, "\\begin_inset Caption", m)
194                         if m == -1:
195                             return
196                         m = find_end_of_inset(document.body, m + 1)
197                         document.body[m] += wrap_into_ert("","","\\backslash\n\\backslash\n%")
198                     m = m + 1
199             m = m + 1
200         i = j + 1
201
202
203 def convert_tablines(document):
204     i = 0
205     while True:
206         i = find_token(document.body, "\\begin_inset Tabular", i)
207         if i == -1:
208             # LyX 1.3 inserted an extra space between \begin_inset
209             # and Tabular so let us try if this is the case and fix it.
210             i = find_token(document.body, "\\begin_inset  Tabular", i)
211             if i == -1:
212                 return
213             else:
214                 document.body[i] = "\\begin_inset Tabular"
215         j = find_end_of_inset(document.body, i + 1)
216         if j == -1:
217             document.warning("Malformed LyX document: Could not find end of tabular.")
218             continue
219
220         m = i + 1
221         nrows = int(document.body[i+1].split('"')[3])
222         ncols = int(document.body[i+1].split('"')[5])
223
224         col_info = []
225         for k in range(ncols):
226             m = find_token(document.body, "<column", m)
227             left = get_option(document, m, 'leftline', 'false')
228             right = get_option(document, m, 'rightline', 'false')
229             col_info.append([left, right])
230             remove_option(document, m, 'leftline')
231             remove_option(document, m, 'rightline')
232             m = m + 1
233
234         row_info = []
235         for k in range(nrows):
236             m = find_token(document.body, "<row", m)
237             top = get_option(document, m, 'topline', 'false')
238             bottom = get_option(document, m, 'bottomline', 'false')
239             row_info.append([top, bottom])
240             remove_option(document, m, 'topline')
241             remove_option(document, m, 'bottomline')
242             m = m + 1
243
244         m = i + 1
245         mc_info = []
246         for k in range(nrows*ncols):
247             m = find_token(document.body, "<cell", m)
248             mc_info.append(get_option(document, m, 'multicolumn', '0'))
249             m = m + 1
250         m = i + 1
251         for l in range(nrows):
252             for k in range(ncols):
253                 m = find_token(document.body, '<cell', m)
254                 if mc_info[l*ncols + k] == '0':
255                     r = set_option(document, m, 'topline', row_info[l][0])
256                     r = set_option(document, m, 'bottomline', row_info[l][1])
257                     r = set_option(document, m, 'leftline', col_info[k][0])
258                     r = set_option(document, m, 'rightline', col_info[k][1])
259                 elif mc_info[l*ncols + k] == '1':
260                     s = k + 1
261                     while s < ncols and mc_info[l*ncols + s] == '2':
262                         s = s + 1
263                     if s < ncols and mc_info[l*ncols + s] != '1':
264                         r = set_option(document, m, 'rightline', col_info[k][1])
265                     if k > 0 and mc_info[l*ncols + k - 1] == '0':
266                         r = set_option(document, m, 'leftline', col_info[k][0])
267                 m = m + 1
268         i = j + 1
269
270
271 def revert_tablines(document):
272     i = 0
273     while True:
274         i = find_token(document.body, "\\begin_inset Tabular", i)
275         if i == -1:
276             return
277         j = find_end_of_inset(document.body, i + 1)
278         if j == -1:
279             document.warning("Malformed LyX document: Could not find end of tabular.")
280             continue
281
282         m = i + 1
283         nrows = int(document.body[i+1].split('"')[3])
284         ncols = int(document.body[i+1].split('"')[5])
285
286         lines = []
287         for k in range(nrows*ncols):
288             m = find_token(document.body, "<cell", m)
289             top = get_option(document, m, 'topline', 'false')
290             bottom = get_option(document, m, 'bottomline', 'false')
291             left = get_option(document, m, 'leftline', 'false')
292             right = get_option(document, m, 'rightline', 'false')
293             lines.append([top, bottom, left, right])
294             m = m + 1
295
296         # we will want to ignore longtable captions
297         m = i + 1
298         caption_info = []
299         for k in range(nrows):
300             m = find_token(document.body, "<row", m)
301             caption = get_option(document, m, 'caption', 'false')
302             caption_info.append([caption])
303             m = m + 1
304
305         m = i + 1
306         col_info = []
307         for k in range(ncols):
308             m = find_token(document.body, "<column", m)
309             left = 'true'
310             for l in range(nrows):
311                 left = lines[l*ncols + k][2]
312                 if left == 'false' and caption_info[l] == 'false':
313                     break
314             set_option(document, m, 'leftline', left)
315             right = 'true'
316             for l in range(nrows):
317                 right = lines[l*ncols + k][3]
318                 if right == 'false' and caption_info[l] == 'false':
319                     break
320             set_option(document, m, 'rightline', right)
321             m = m + 1
322
323         row_info = []
324         for k in range(nrows):
325             m = find_token(document.body, "<row", m)
326             top = 'true'
327             for l in range(ncols):
328                 top = lines[k*ncols + l][0]
329                 if top == 'false':
330                     break
331             if caption_info[k] == 'false':
332                 top = 'false'
333             set_option(document, m, 'topline', top)
334             bottom = 'true'
335             for l in range(ncols):
336                 bottom = lines[k*ncols + l][1]
337                 if bottom == 'false':
338                     break
339             if caption_info[k] == 'false':
340                 bottom = 'false'
341             set_option(document, m, 'bottomline', bottom)
342             m = m + 1
343
344         i = j + 1
345
346
347 def fix_wrong_tables(document):
348     i = 0
349     while True:
350         i = find_token(document.body, "\\begin_inset Tabular", i)
351         if i == -1:
352             return
353         j = find_end_of_inset(document.body, i + 1)
354         if j == -1:
355             document.warning("Malformed LyX document: Could not find end of tabular.")
356             continue
357
358         m = i + 1
359         nrows = int(document.body[i+1].split('"')[3])
360         ncols = int(document.body[i+1].split('"')[5])
361
362         for l in range(nrows):
363             prev_multicolumn = 0
364             for k in range(ncols):
365                 m = find_token(document.body, '<cell', m)
366
367                 if document.body[m].find('multicolumn') != -1:
368                     multicol_cont = int(document.body[m].split('"')[1])
369
370                     if multicol_cont == 2 and (k == 0 or prev_multicolumn == 0):
371                         document.body[m] = document.body[m][:5] + document.body[m][21:]
372                         prev_multicolumn = 0
373                     else:
374                         prev_multicolumn = multicol_cont
375                 else:
376                     prev_multicolumn = 0
377
378         i = j + 1
379
380
381 def close_begin_deeper(document):
382     i = 0
383     depth = 0
384     while True:
385         i = find_tokens(document.body, ["\\begin_deeper", "\\end_deeper"], i)
386
387         if i == -1:
388             break
389
390         if document.body[i][:13] == "\\begin_deeper":
391             depth += 1
392         else:
393             depth -= 1
394
395         i += 1
396
397     document.body[-2:-2] = ['\\end_deeper' for i in range(depth)]
398
399
400 def long_charstyle_names(document):
401     i = 0
402     while True:
403         i = find_token(document.body, "\\begin_inset CharStyle", i)
404         if i == -1:
405             return
406         document.body[i] = document.body[i].replace("CharStyle ", "CharStyle CharStyle:")
407         i += 1
408
409 def revert_long_charstyle_names(document):
410     i = 0
411     while True:
412         i = find_token(document.body, "\\begin_inset CharStyle", i)
413         if i == -1:
414             return
415         document.body[i] = document.body[i].replace("CharStyle CharStyle:", "CharStyle")
416         i += 1
417
418
419 def axe_show_label(document):
420     i = 0
421     while True:
422         i = find_token(document.body, "\\begin_inset CharStyle", i)
423         if i == -1:
424             return
425         if document.body[i + 1].find("show_label") != -1:
426             if document.body[i + 1].find("true") != -1:
427                 document.body[i + 1] = "status open"
428                 del document.body[ i + 2]
429             else:
430                 if document.body[i + 1].find("false") != -1:
431                     document.body[i + 1] = "status collapsed"
432                     del document.body[ i + 2]
433                 else:
434                     document.warning("Malformed LyX document: show_label neither false nor true.")
435         else:
436             document.warning("Malformed LyX document: show_label missing in CharStyle.")
437
438         i += 1
439
440
441 def revert_show_label(document):
442     i = 0
443     while True:
444         i = find_token(document.body, "\\begin_inset CharStyle", i)
445         if i == -1:
446             return
447         if document.body[i + 1].find("status open") != -1:
448             document.body.insert(i + 1, "show_label true")
449         else:
450             if document.body[i + 1].find("status collapsed") != -1:
451                 document.body.insert(i + 1, "show_label false")
452             else:
453                 document.warning("Malformed LyX document: no legal status line in CharStyle.")
454         i += 1
455
456 def revert_begin_modules(document):
457     i = 0
458     while True:
459         i = find_token(document.header, "\\begin_modules", i)
460         if i == -1:
461             return
462         j = find_end_of(document.header, i, "\\begin_modules", "\\end_modules")
463         if j == -1:
464             # this should not happen
465             break
466         document.header[i : j + 1] = []
467
468 def convert_flex(document):
469     "Convert CharStyle to Flex"
470     i = 0
471     while True:
472         i = find_token(document.body, "\\begin_inset CharStyle", i)
473         if i == -1:
474             return
475         document.body[i] = document.body[i].replace('\\begin_inset CharStyle', '\\begin_inset Flex')
476
477 def revert_flex(document):
478     "Convert Flex to CharStyle"
479     i = 0
480     while True:
481         i = find_token(document.body, "\\begin_inset Flex", i)
482         if i == -1:
483             return
484         document.body[i] = document.body[i].replace('\\begin_inset Flex', '\\begin_inset CharStyle')
485
486
487 #  Discard PDF options for hyperref
488 def revert_pdf_options(document):
489         "Revert PDF options for hyperref."
490         # store the PDF options and delete the entries from the Lyx file
491         i = 0
492         hyperref = False
493         title = ""
494         author = ""
495         subject = ""
496         keywords = ""
497         bookmarks = ""
498         bookmarksnumbered = ""
499         bookmarksopen = ""
500         bookmarksopenlevel = ""
501         breaklinks = ""
502         pdfborder = ""
503         colorlinks = ""
504         backref = ""
505         pagebackref = ""
506         pagemode = ""
507         otheroptions = ""
508         i = find_token(document.header, "\\use_hyperref", i)
509         if i != -1:
510             hyperref = get_value(document.header, "\\use_hyperref", i) == 'true'
511             del document.header[i]
512         i = find_token(document.header, "\\pdf_store_options", i)
513         if i != -1:
514             del document.header[i]
515         i = find_token(document.header, "\\pdf_title", 0)
516         if i != -1:
517             title = get_value_string(document.header, '\\pdf_title', 0, 0, True)
518             title = ' pdftitle={' + title + '}'
519             del document.header[i]
520         i = find_token(document.header, "\\pdf_author", 0)
521         if i != -1:
522             author = get_value_string(document.header, '\\pdf_author', 0, 0, True)
523             if title == "":
524                 author = ' pdfauthor={' + author + '}'
525             else:
526                 author = ',\n pdfauthor={' + author + '}'
527             del document.header[i]
528         i = find_token(document.header, "\\pdf_subject", 0)
529         if i != -1:
530             subject = get_value_string(document.header, '\\pdf_subject', 0, 0, True)
531             if title == "" and author == "":
532                 subject = ' pdfsubject={' + subject + '}'
533             else:
534                 subject = ',\n pdfsubject={' + subject + '}'
535             del document.header[i]
536         i = find_token(document.header, "\\pdf_keywords", 0)
537         if i != -1:
538             keywords = get_value_string(document.header, '\\pdf_keywords', 0, 0, True)
539             if title == "" and author == "" and subject == "":
540                 keywords = ' pdfkeywords={' + keywords + '}'
541             else:
542                 keywords = ',\n pdfkeywords={' + keywords + '}'
543             del document.header[i]
544         i = find_token(document.header, "\\pdf_bookmarks", 0)
545         if i != -1:
546             bookmarks = get_value_string(document.header, '\\pdf_bookmarks', 0)
547             bookmarks = ',\n bookmarks=' + bookmarks
548             del document.header[i]
549         i = find_token(document.header, "\\pdf_bookmarksnumbered", i)
550         if i != -1:
551             bookmarksnumbered = get_value_string(document.header, '\\pdf_bookmarksnumbered', 0)
552             bookmarksnumbered = ',\n bookmarksnumbered=' + bookmarksnumbered
553             del document.header[i]
554         i = find_token(document.header, "\\pdf_bookmarksopen", i)
555         if i != -1:
556             bookmarksopen = get_value_string(document.header, '\\pdf_bookmarksopen', 0)
557             bookmarksopen = ',\n bookmarksopen=' + bookmarksopen
558             del document.header[i]
559         i = find_token(document.header, "\\pdf_bookmarksopenlevel", i)
560         if i != -1:
561             bookmarksopenlevel = get_value_string(document.header, '\\pdf_bookmarksopenlevel', 0, 0, True)
562             bookmarksopenlevel = ',\n bookmarksopenlevel=' + bookmarksopenlevel
563             del document.header[i]
564         i = find_token(document.header, "\\pdf_breaklinks", i)
565         if i != -1:
566             breaklinks = get_value_string(document.header, '\\pdf_breaklinks', 0)
567             breaklinks = ',\n breaklinks=' + breaklinks
568             del document.header[i]
569         i = find_token(document.header, "\\pdf_pdfborder", i)
570         if i != -1:
571             pdfborder = get_value_string(document.header, '\\pdf_pdfborder', 0)
572             if pdfborder == 'true':
573                 pdfborder = ',\n pdfborder={0 0 0}'
574             else:
575                 pdfborder = ',\n pdfborder={0 0 1}'
576             del document.header[i]
577         i = find_token(document.header, "\\pdf_colorlinks", i)
578         if i != -1:
579             colorlinks = get_value_string(document.header, '\\pdf_colorlinks', 0)
580             colorlinks = ',\n colorlinks=' + colorlinks
581             del document.header[i]
582         i = find_token(document.header, "\\pdf_backref", i)
583         if i != -1:
584             backref = get_value_string(document.header, '\\pdf_backref', 0)
585             backref = ',\n backref=' + backref
586             del document.header[i]
587         i = find_token(document.header, "\\pdf_pagebackref", i)
588         if i != -1:
589             pagebackref = get_value_string(document.header, '\\pdf_pagebackref', 0)
590             pagebackref = ',\n pagebackref=' + pagebackref
591             del document.header[i]
592         i = find_token(document.header, "\\pdf_pagemode", 0)
593         if i != -1:
594             pagemode = get_value_string(document.header, '\\pdf_pagemode', 0)
595             pagemode = ',\n pdfpagemode=' + pagemode
596             del document.header[i]
597         i = find_token(document.header, "\\pdf_quoted_options", 0)
598         if i != -1:
599             otheroptions = get_value_string(document.header, '\\pdf_quoted_options', 0, 0, True)
600             if title == "" and author == "" and subject == "" and keywords == "":
601                 otheroptions = ' ' + otheroptions
602             else:
603                 otheroptions = ',\n ' + otheroptions
604             del document.header[i]
605
606         # write to the preamble when hyperref was used
607         if hyperref == True:
608             # preamble write preparations
609             # bookmark numbers are only output when they are turned on
610             if bookmarksopen == ',\n bookmarksopen=true':
611                 bookmarksopen = bookmarksopen + bookmarksopenlevel
612             if bookmarks == ',\n bookmarks=true':
613                 bookmarks = bookmarks + bookmarksnumbered + bookmarksopen
614             else:
615                 bookmarks = bookmarks
616             # hypersetup is only output when there are things to be set up
617             setupstart = '\\hypersetup{%\n'
618             setupend = ' }\n'
619             if otheroptions == "" and title == "" and  author == ""\
620                and  subject == "" and keywords == "":
621                 setupstart = ""
622                 setupend = ""
623             # write the preamble
624             add_to_preamble(document,
625                                 ['% Commands inserted by lyx2lyx for PDF properties',
626                                  '\\usepackage[unicode=true'
627                                  + bookmarks
628                                  + breaklinks
629                                  + pdfborder
630                                  + backref
631                                  + pagebackref
632                                  + colorlinks
633                                  + pagemode
634                                  + ']\n'
635                                  ' {hyperref}\n'
636                                  + setupstart
637                                  + title
638                                  + author
639                                  + subject
640                                  + keywords
641                                  + otheroptions
642                                  + setupend])
643
644
645 def remove_inzip_options(document):
646     "Remove inzipName and embed options from the Graphics inset"
647     i = 0
648     while 1:
649         i = find_token(document.body, "\\begin_inset Graphics", i)
650         if i == -1:
651             return
652         j = find_end_of_inset(document.body, i + 1)
653         if j == -1:
654             # should not happen
655             document.warning("Malformed LyX document: Could not find end of graphics inset.")
656         # If there's a inzip param, just remove that
657         k = find_token(document.body, "\tinzipName", i + 1, j)
658         if k != -1:
659             del document.body[k]
660             # embed option must follow the inzipName option
661             del document.body[k+1]
662         i = i + 1
663
664
665 def convert_inset_command(document):
666     """
667         Convert:
668             \begin_inset LatexCommand cmd
669         to
670             \begin_inset CommandInset InsetType
671             LatexCommand cmd
672     """
673     i = 0
674     while 1:
675         i = find_token(document.body, "\\begin_inset LatexCommand", i)
676         if i == -1:
677             return
678         line = document.body[i]
679         r = re.compile(r'\\begin_inset LatexCommand (.*)$')
680         m = r.match(line)
681         cmdName = m.group(1)
682         insetName = ""
683         #this is adapted from factory.cpp
684         if cmdName[0:4].lower() == "cite":
685             insetName = "citation"
686         elif cmdName == "url" or cmdName == "htmlurl":
687             insetName = "url"
688         elif cmdName[-3:] == "ref":
689             insetName = "ref"
690         elif cmdName == "tableofcontents":
691             insetName = "toc"
692         elif cmdName == "printnomenclature":
693             insetName = "nomencl_print"
694         elif cmdName == "printindex":
695             insetName = "index_print"
696         else:
697             insetName = cmdName
698         insertion = ["\\begin_inset CommandInset " + insetName, "LatexCommand " + cmdName]
699         document.body[i : i+1] = insertion
700
701
702 def revert_inset_command(document):
703     """
704         Convert:
705             \begin_inset CommandInset InsetType
706             LatexCommand cmd
707         to
708             \begin_inset LatexCommand cmd
709         Some insets may end up being converted to insets earlier versions of LyX
710         will not be able to recognize. Not sure what to do about that.
711     """
712     i = 0
713     while 1:
714         i = find_token(document.body, "\\begin_inset CommandInset", i)
715         if i == -1:
716             return
717         nextline = document.body[i+1]
718         r = re.compile(r'LatexCommand\s+(.*)$')
719         m = r.match(nextline)
720         if not m:
721             document.warning("Malformed LyX document: Missing LatexCommand in " + document.body[i] + ".")
722             continue
723         cmdName = m.group(1)
724         insertion = ["\\begin_inset LatexCommand " + cmdName]
725         document.body[i : i+2] = insertion
726
727
728 def convert_wrapfig_options(document):
729     "Convert optional options for wrap floats (wrapfig)."
730     # adds the tokens "lines", "placement", and "overhang"
731     i = 0
732     while True:
733         i = find_token(document.body, "\\begin_inset Wrap figure", i)
734         if i == -1:
735             return
736         document.body.insert(i + 1, "lines 0")
737         j = find_token(document.body, "placement", i)
738         # placement can be already set or not; if not, set it
739         if j == i+2:
740             document.body.insert(i + 3, "overhang 0col%")
741         else:
742            document.body.insert(i + 2, "placement o")
743            document.body.insert(i + 3, "overhang 0col%")
744         i = i + 1
745
746
747 def revert_wrapfig_options(document):
748     "Revert optional options for wrap floats (wrapfig)."
749     i = 0
750     while True:
751         i = find_token(document.body, "lines", i)
752         if i == -1:
753             return
754         j = find_token(document.body, "overhang", i+1)
755         if j != i + 2 and j != -1:
756             document.warning("Malformed LyX document: Couldn't find overhang parameter of wrap float.")
757         if j == -1:
758             return
759         del document.body[i]
760         del document.body[j-1]
761         i = i + 1
762
763
764 # To convert and revert indices, we need to convert between LaTeX 
765 # strings and LyXText. Here we do a minimal conversion to prevent 
766 # crashes and data loss. Manual patch-up may be needed.
767 replacements = [
768   [r'\\\"a', u'ä'], 
769   [r'\\\"o', u'ö'], 
770   [r'\\\"u', u'ü'],
771   [r'\\\'a', u'á'],
772   [r'\\\'e', u'é'],
773   [r'\\\'i', u'í'],
774   [r'\\\'o', u'ó'],
775   [r'\\\'u', u'ú']
776 ]
777
778 def convert_latexcommand_index(document):
779     "Convert from LatexCommand form to collapsable form."
780     i = 0
781     while True:
782         i = find_token(document.body, "\\begin_inset CommandInset index", i)
783         if i == -1:
784             return
785         if document.body[i + 1] != "LatexCommand index": # Might also be index_print
786             return
787         fullcontent = document.body[i + 2][5:]
788         fullcontent.strip()
789         fullcontent = fullcontent[1:-1]
790         document.body[i:i + 3] = ["\\begin_inset Index",
791           "status collapsed",
792           "\\begin_layout Standard"]
793         i += 3
794         # We are now on the blank line preceding "\end_inset"
795         # We will write the content here, into the inset.
796
797         # Do the LaTeX --> LyX text conversion
798         for rep in replacements:
799             fullcontent = fullcontent.replace(rep[0], rep[1])
800         # Generic, \" -> ":
801         fullcontent = wrap_into_ert(fullcontent, r'\"', '"')
802         # Math:
803         r = re.compile('^(.*?)(\$.*?\$)(.*)')
804         lines = fullcontent.split('\n')
805         for line in lines:
806           #document.warning("LINE: " + line)
807           #document.warning(str(i) + ":" + document.body[i])
808           #document.warning("LAST: " + document.body[-1])
809           g = line
810           while r.match(g):
811             m = r.match(g)
812             s = m.group(1)
813             f = m.group(2).replace('\\\\', '\\')
814             g = m.group(3)
815             if s:
816               # this is non-math!
817               s = wrap_into_ert(s, r'\\', '\\backslash')
818               s = wrap_into_ert(s, '{', '{')
819               s = wrap_into_ert(s, '}', '}')
820               subst = s.split('\n')
821               document.body[i:i] = subst
822               i += len(subst)
823             document.body.insert(i + 1, "\\begin_inset Formula " + f)
824             document.body.insert(i + 2, "\\end_inset")
825             i += 2
826           # Generic, \\ -> \backslash:
827           g = wrap_into_ert(g, r'\\', '\\backslash')
828           g = wrap_into_ert(g, '{', '{')
829           g = wrap_into_ert(g, '}', '}')
830           subst = g.split('\n')
831           document.body[i+1:i+1] = subst
832           i += len(subst)
833         document.body.insert(i + 1, "\\end_layout")
834
835
836 def revert_latexcommand_index(document):
837     "Revert from collapsable form to LatexCommand form."
838     i = 0
839     while True:
840         i = find_token(document.body, "\\begin_inset Index", i)
841         if i == -1:
842           return
843         j = find_end_of_inset(document.body, i + 1)
844         if j == -1:
845           return
846         del document.body[j - 1]
847         del document.body[j - 2] # \end_layout
848         document.body[i] =  "\\begin_inset CommandInset index"
849         document.body[i + 1] =  "LatexCommand index"
850         # clean up multiline stuff
851         content = ""
852         ert_end = 0
853         for k in range(i + 3, j - 2):
854           line = document.body[k]
855           if line.startswith("\\begin_inset ERT"):
856               ert_end = find_end_of_inset(document.body, k + 1)
857               line = line[16:]
858           if line.startswith("\\begin_inset Formula"):
859             line = line[20:]
860           if line.startswith("\\begin_layout Standard"):
861             line = line[22:]
862           if line.startswith("\\begin_layout Plain Layout"):
863             line = line[26:]
864           if line.startswith("\\end_layout"):
865             line = line[11:]
866           if line.startswith("\\end_inset"):
867             line = line[10:]
868           if line.startswith("status collapsed"):
869             line = line[16:]
870           if line.startswith("status open"):
871             line = line[11:]
872           # a lossless reversion is not possible
873           # try at least to handle some common insets and settings
874           # do not replace inside ERTs
875           if ert_end < k:
876               # Do the LyX text --> LaTeX conversion
877               for rep in replacements:
878                 line = line.replace(rep[1], rep[0])
879               line = line.replace(r'\backslash', r'\textbackslash{}')
880               line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
881               line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
882               line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
883               line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
884               line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
885               line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
886               line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
887               line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
888               line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
889           else:
890               line = line.replace(r'\backslash', r'\\')
891           content = content + line;
892         document.body[i + 3] = "name " + '"' + content + '"'
893         for k in range(i + 4, j - 2):
894           del document.body[i + 4]
895         document.body.insert(i + 4, "")
896         del document.body[i + 2] # \begin_layout standard
897         i = i + 5
898
899
900 def revert_wraptable(document):
901     "Revert wrap table to wrap figure."
902     i = 0
903     while True:
904         i = find_token(document.body, "\\begin_inset Wrap table", i)
905         if i == -1:
906             return
907         document.body[i] = document.body[i].replace('\\begin_inset Wrap table', '\\begin_inset Wrap figure')
908         i = i + 1
909
910
911 def revert_vietnamese(document):
912     "Set language Vietnamese to English"
913     # Set document language from Vietnamese to English
914     i = 0
915     if document.language == "vietnamese":
916         document.language = "english"
917         i = find_token(document.header, "\\language", 0)
918         if i != -1:
919             document.header[i] = "\\language english"
920     j = 0
921     while True:
922         j = find_token(document.body, "\\lang vietnamese", j)
923         if j == -1:
924             return
925         document.body[j] = document.body[j].replace("\\lang vietnamese", "\\lang english")
926         j = j + 1
927
928
929 def revert_japanese(document):
930     "Set language japanese-plain to japanese"
931     # Set document language from japanese-plain to japanese
932     i = 0
933     if document.language == "japanese-plain":
934         document.language = "japanese"
935         i = find_token(document.header, "\\language", 0)
936         if i != -1:
937             document.header[i] = "\\language japanese"
938     j = 0
939     while True:
940         j = find_token(document.body, "\\lang japanese-plain", j)
941         if j == -1:
942             return
943         document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
944         j = j + 1
945
946
947 def revert_japanese_encoding(document):
948     "Set input encoding form EUC-JP-plain to EUC-JP etc."
949     # Set input encoding form EUC-JP-plain to EUC-JP etc.
950     i = 0
951     i = find_token(document.header, "\\inputencoding EUC-JP-plain", 0)
952     if i != -1:
953         document.header[i] = "\\inputencoding EUC-JP"
954     j = 0
955     j = find_token(document.header, "\\inputencoding JIS-plain", 0)
956     if j != -1:
957         document.header[j] = "\\inputencoding JIS"
958     k = 0
959     k = find_token(document.header, "\\inputencoding SJIS-plain", 0)
960     if k != -1: # convert to UTF8 since there is currently no SJIS encoding
961         document.header[k] = "\\inputencoding UTF8"
962
963
964 def revert_inset_info(document):
965     'Replace info inset with its content'
966     i = 0
967     while 1:
968         i = find_token(document.body, '\\begin_inset Info', i)
969         if i == -1:
970             return
971         j = find_end_of_inset(document.body, i + 1)
972         if j == -1:
973             # should not happen
974             document.warning("Malformed LyX document: Could not find end of Info inset.")
975         type = 'unknown'
976         arg = ''
977         for k in range(i, j+1):
978             if document.body[k].startswith("arg"):
979                 arg = document.body[k][3:].strip().strip('"')
980             if document.body[k].startswith("type"):
981                 type = document.body[k][4:].strip().strip('"')
982         # I think there is a newline after \\end_inset, which should be removed.
983         if document.body[j + 1].strip() == "":
984             document.body[i : (j + 2)] = [type + ':' + arg]
985         else:
986             document.body[i : (j + 1)] = [type + ':' + arg]
987
988
989 def convert_pdf_options(document):
990     # Set the pdfusetitle tag, delete the pdf_store_options,
991     # set quotes for bookmarksopenlevel"
992     has_hr = get_value(document.header, "\\use_hyperref", 0, default = "0")
993     if has_hr == "1":
994         k = find_token(document.header, "\\use_hyperref", 0)
995         document.header.insert(k + 1, "\\pdf_pdfusetitle true")
996     k = find_token(document.header, "\\pdf_store_options", 0)
997     if k != -1:
998         del document.header[k]
999     i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
1000     if i == -1: return
1001     document.header[i] = document.header[i].replace('"', '')
1002
1003
1004 def revert_pdf_options_2(document):
1005     # reset the pdfusetitle tag, set quotes for bookmarksopenlevel"
1006     k = find_token(document.header, "\\use_hyperref", 0)
1007     i = find_token(document.header, "\\pdf_pdfusetitle", k)
1008     if i != -1:
1009         del document.header[i]
1010     i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
1011     if i == -1: return
1012     values = document.header[i].split()
1013     values[1] = ' "' + values[1] + '"'
1014     document.header[i] = ''.join(values)
1015
1016
1017 def convert_htmlurl(document):
1018     'Convert "htmlurl" to "href" insets for docbook'
1019     if document.backend != "docbook":
1020       return
1021     i = 0
1022     while True:
1023       i = find_token(document.body, "\\begin_inset CommandInset url", i)
1024       if i == -1:
1025         return
1026       document.body[i] = "\\begin_inset CommandInset href"
1027       document.body[i + 1] = "LatexCommand href"
1028       i = i + 1
1029
1030
1031 def convert_url(document):
1032     'Convert url insets to url charstyles'
1033     if document.backend == "docbook":
1034       return
1035     i = 0
1036     while True:
1037       i = find_token(document.body, "\\begin_inset CommandInset url", i)
1038       if i == -1:
1039         break
1040       n = find_token(document.body, "name", i)
1041       if n == i + 2:
1042         # place the URL name in typewriter before the new URL insert
1043         # grab the name 'bla' from the e.g. the line 'name "bla"',
1044         # therefore start with the 6th character
1045         name = document.body[n][6:-1]
1046         newname = [name + " "]
1047         document.body[i:i] = newname
1048         i = i + 1
1049       j = find_token(document.body, "target", i)
1050       if j == -1:
1051         document.warning("Malformed LyX document: Can't find target for url inset")
1052         i = j
1053         continue
1054       target = document.body[j][8:-1]
1055       k = find_token(document.body, "\\end_inset", j)
1056       if k == -1:
1057         document.warning("Malformed LyX document: Can't find end of url inset")
1058         i = k
1059         continue
1060       newstuff = ["\\begin_inset Flex URL",
1061         "status collapsed", "",
1062         "\\begin_layout Standard",
1063         "",
1064         target,
1065         "\\end_layout",
1066         ""]
1067       document.body[i:k] = newstuff
1068       i = k
1069
1070 def convert_ams_classes(document):
1071   tc = document.textclass
1072   if (tc != "amsart" and tc != "amsart-plain" and
1073       tc != "amsart-seq" and tc != "amsbook"):
1074     return
1075   if tc == "amsart-plain":
1076     document.textclass = "amsart"
1077     document.set_textclass()
1078     document.add_module("Theorems (Starred)")
1079     return
1080   if tc == "amsart-seq":
1081     document.textclass = "amsart"
1082     document.set_textclass()
1083   document.add_module("Theorems (AMS)")
1084
1085   #Now we want to see if any of the environments in the extended theorems
1086   #module were used in this document. If so, we'll add that module, too.
1087   layouts = ["Criterion", "Algorithm", "Axiom", "Condition", "Note",  \
1088     "Notation", "Summary", "Acknowledgement", "Conclusion", "Fact", \
1089     "Assumption"]
1090
1091   r = re.compile(r'^\\begin_layout (.*?)\*?\s*$')
1092   i = 0
1093   while True:
1094     i = find_token(document.body, "\\begin_layout", i)
1095     if i == -1:
1096       return
1097     m = r.match(document.body[i])
1098     if m == None:
1099       document.warning("Weirdly formed \\begin_layout at line %d of body!" % i)
1100       i += 1
1101       continue
1102     m = m.group(1)
1103     if layouts.count(m) != 0:
1104       document.add_module("Theorems (AMS-Extended)")
1105       return
1106     i += 1
1107
1108 def revert_href(document):
1109     'Reverts hyperlink insets (href) to url insets (url)'
1110     i = 0
1111     while True:
1112       i = find_token(document.body, "\\begin_inset CommandInset href", i)
1113       if i == -1:
1114           return
1115       document.body[i : i + 2] = \
1116         ["\\begin_inset CommandInset url", "LatexCommand url"]
1117       i = i + 2
1118
1119 def revert_url(document):
1120     'Reverts Flex URL insets to old-style URL insets'
1121     i = 0
1122     while True:
1123         i = find_token(document.body, "\\begin_inset Flex URL", i)
1124         if i == -1:
1125             return
1126         j = find_end_of_inset(document.body, i)
1127         if j == -1:
1128             document.warning("Can't find end of inset in revert_url!")
1129             return
1130         k = find_default_layout(document, i, j)
1131         if k == -1:
1132             document.warning("Can't find default layout in revert_url!")
1133             i = j
1134             continue
1135         l = find_end_of(document.body, k, "\\begin_layout", "\\end_layout")
1136         if l == -1 or l >= j:
1137             document.warning("Can't find end of default layout in revert_url!")
1138             i = j
1139             continue
1140         # OK, so the inset's data is between lines k and l.
1141         data =  " ".join(document.body[k+1:l])
1142         data = data.strip()
1143         newinset = ["\\begin_inset LatexCommand url", "target \"" + data + "\"",\
1144                     "", "\\end_inset"]
1145         document.body[i:j+1] = newinset
1146         i = i + len(newinset)
1147
1148
1149 def convert_include(document):
1150   'Converts include insets to new format.'
1151   i = 0
1152   r = re.compile(r'\\begin_inset Include\s+\\([^{]+){([^}]*)}(?:\[(.*)\])?')
1153   while True:
1154     i = find_token(document.body, "\\begin_inset Include", i)
1155     if i == -1:
1156       return
1157     line = document.body[i]
1158     previewline = document.body[i + 1]
1159     m = r.match(line)
1160     if m == None:
1161       document.warning("Unable to match line " + str(i) + " of body!")
1162       i += 1
1163       continue
1164     cmd = m.group(1)
1165     fn  = m.group(2)
1166     opt = m.group(3)
1167     insertion = ["\\begin_inset CommandInset include",
1168        "LatexCommand " + cmd, previewline,
1169        "filename \"" + fn + "\""]
1170     newlines = 2
1171     if opt:
1172       insertion.append("lstparams " + '"' + opt + '"')
1173       newlines += 1
1174     document.body[i : i + 2] = insertion
1175     i += newlines
1176
1177
1178 def revert_include(document):
1179   'Reverts include insets to old format.'
1180   i = 0
1181   r1 = re.compile('LatexCommand (.+)')
1182   r2 = re.compile('filename (.+)')
1183   r3 = re.compile('options (.*)')
1184   while True:
1185     i = find_token(document.body, "\\begin_inset CommandInset include", i)
1186     if i == -1:
1187       return
1188     previewline = document.body[i + 1]
1189     m = r1.match(document.body[i + 2])
1190     if m == None:
1191       document.warning("Malformed LyX document: No LatexCommand line for `" +
1192         document.body[i] + "' on line " + str(i) + ".")
1193       i += 1
1194       continue
1195     cmd = m.group(1)
1196     m = r2.match(document.body[i + 3])
1197     if m == None:
1198       document.warning("Malformed LyX document: No filename line for `" + \
1199         document.body[i] + "' on line " + str(i) + ".")
1200       i += 2
1201       continue
1202     fn = m.group(1)
1203     options = ""
1204     numlines = 4
1205     if (cmd == "lstinputlisting"):
1206       m = r3.match(document.body[i + 4])
1207       if m != None:
1208         options = m.group(1)
1209         numlines = 5
1210     newline = "\\begin_inset Include \\" + cmd + "{" + fn + "}"
1211     if options:
1212       newline += ("[" + options + "]")
1213     insertion = [newline, previewline]
1214     document.body[i : i + numlines] = insertion
1215     i += 2
1216
1217
1218 def revert_albanian(document):
1219     "Set language Albanian to English"
1220     i = 0
1221     if document.language == "albanian":
1222         document.language = "english"
1223         i = find_token(document.header, "\\language", 0)
1224         if i != -1:
1225             document.header[i] = "\\language english"
1226     j = 0
1227     while True:
1228         j = find_token(document.body, "\\lang albanian", j)
1229         if j == -1:
1230             return
1231         document.body[j] = document.body[j].replace("\\lang albanian", "\\lang english")
1232         j = j + 1
1233
1234
1235 def revert_lowersorbian(document):
1236     "Set language lower Sorbian to English"
1237     i = 0
1238     if document.language == "lowersorbian":
1239         document.language = "english"
1240         i = find_token(document.header, "\\language", 0)
1241         if i != -1:
1242             document.header[i] = "\\language english"
1243     j = 0
1244     while True:
1245         j = find_token(document.body, "\\lang lowersorbian", j)
1246         if j == -1:
1247             return
1248         document.body[j] = document.body[j].replace("\\lang lowersorbian", "\\lang english")
1249         j = j + 1
1250
1251
1252 def revert_uppersorbian(document):
1253     "Set language uppersorbian to usorbian as this was used in LyX 1.5"
1254     i = 0
1255     if document.language == "uppersorbian":
1256         document.language = "usorbian"
1257         i = find_token(document.header, "\\language", 0)
1258         if i != -1:
1259             document.header[i] = "\\language usorbian"
1260     j = 0
1261     while True:
1262         j = find_token(document.body, "\\lang uppersorbian", j)
1263         if j == -1:
1264             return
1265         document.body[j] = document.body[j].replace("\\lang uppersorbian", "\\lang usorbian")
1266         j = j + 1
1267
1268
1269 def convert_usorbian(document):
1270     "Set language usorbian to uppersorbian"
1271     i = 0
1272     if document.language == "usorbian":
1273         document.language = "uppersorbian"
1274         i = find_token(document.header, "\\language", 0)
1275         if i != -1:
1276             document.header[i] = "\\language uppersorbian"
1277     j = 0
1278     while True:
1279         j = find_token(document.body, "\\lang usorbian", j)
1280         if j == -1:
1281             return
1282         document.body[j] = document.body[j].replace("\\lang usorbian", "\\lang uppersorbian")
1283         j = j + 1
1284
1285
1286 def revert_macro_optional_params(document):
1287     "Convert macro definitions with optional parameters into ERTs"
1288     # Stub to convert macro definitions with one or more optional parameters
1289     # into uninterpreted ERT insets
1290
1291
1292 def revert_hyperlinktype(document):
1293     'Reverts hyperlink type'
1294     i = 0
1295     j = 0
1296     while True:
1297       i = find_token(document.body, "target", i)
1298       if i == -1:
1299           return
1300       j = find_token(document.body, "type", i)
1301       if j == -1:
1302           return
1303       if j == i + 1:
1304           del document.body[j]
1305       i = i + 1
1306
1307
1308 def revert_pagebreak(document):
1309     'Reverts pagebreak to ERT'
1310     i = 0
1311     while True:
1312       i = find_token(document.body, "\\pagebreak", i)
1313       if i == -1:
1314           return
1315       document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1316       '\\begin_layout Standard\n\n\n\\backslash\n' \
1317       'pagebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1318       i = i + 1
1319
1320
1321 def revert_linebreak(document):
1322     'Reverts linebreak to ERT'
1323     i = 0
1324     while True:
1325       i = find_token(document.body, "\\linebreak", i)
1326       if i == -1:
1327           return
1328       document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1329       '\\begin_layout Standard\n\n\n\\backslash\n' \
1330       'linebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1331       i = i + 1
1332
1333
1334 def revert_latin(document):
1335     "Set language Latin to English"
1336     i = 0
1337     if document.language == "latin":
1338         document.language = "english"
1339         i = find_token(document.header, "\\language", 0)
1340         if i != -1:
1341             document.header[i] = "\\language english"
1342     j = 0
1343     while True:
1344         j = find_token(document.body, "\\lang latin", j)
1345         if j == -1:
1346             return
1347         document.body[j] = document.body[j].replace("\\lang latin", "\\lang english")
1348         j = j + 1
1349
1350
1351 def revert_samin(document):
1352     "Set language North Sami to English"
1353     i = 0
1354     if document.language == "samin":
1355         document.language = "english"
1356         i = find_token(document.header, "\\language", 0)
1357         if i != -1:
1358             document.header[i] = "\\language english"
1359     j = 0
1360     while True:
1361         j = find_token(document.body, "\\lang samin", j)
1362         if j == -1:
1363             return
1364         document.body[j] = document.body[j].replace("\\lang samin", "\\lang english")
1365         j = j + 1
1366
1367
1368 def convert_serbocroatian(document):
1369     "Set language Serbocroatian to Croatian as this was really Croatian in LyX 1.5"
1370     i = 0
1371     if document.language == "serbocroatian":
1372         document.language = "croatian"
1373         i = find_token(document.header, "\\language", 0)
1374         if i != -1:
1375             document.header[i] = "\\language croatian"
1376     j = 0
1377     while True:
1378         j = find_token(document.body, "\\lang serbocroatian", j)
1379         if j == -1:
1380             return
1381         document.body[j] = document.body[j].replace("\\lang serbocroatian", "\\lang croatian")
1382         j = j + 1
1383
1384
1385 def convert_framed_notes(document):
1386     "Convert framed notes to boxes. "
1387     i = 0
1388     while 1:
1389         i = find_tokens(document.body, ["\\begin_inset Note Framed", "\\begin_inset Note Shaded"], i)
1390         if i == -1:
1391             return
1392         subst = [document.body[i].replace("\\begin_inset Note", "\\begin_inset Box"),
1393                  'position "t"',
1394                  'hor_pos "c"',
1395                  'has_inner_box 0',
1396                  'inner_pos "t"', 
1397                  'use_parbox 0',
1398                  'width "100col%"',
1399                  'special "none"',
1400                  'height "1in"',
1401                  'height_special "totalheight"']
1402         document.body[i:i+1] = subst
1403         i = i + 9
1404
1405
1406 def convert_module_names(document):
1407   modulemap = { 'Braille' : 'braille', 'Endnote' : 'endnotes', 'Foot to End' : 'foottoend',\
1408     'Hanging' : 'hanging', 'Linguistics' : 'linguistics', 'Logical Markup' : 'logicalmkup', \
1409     'Theorems (AMS-Extended)' : 'theorems-ams-extended', 'Theorems (AMS)' : 'theorems-ams', \
1410     'Theorems (Order By Chapter)' : 'theorems-chap', 'Theorems (Order By Section)' : 'theorems-sec', \
1411     'Theorems (Starred)' : 'theorems-starred', 'Theorems' : 'theorems-std' }
1412   modlist = document.get_module_list()
1413   if len(modlist) == 0:
1414     return
1415   newmodlist = []
1416   for mod in modlist:
1417     if modulemap.has_key(mod):
1418       newmodlist.append(modulemap[mod])
1419     else:
1420       document.warning("Can't find module %s in the module map!" % mod)
1421       newmodlist.append(mod)
1422   document.set_module_list(newmodlist)
1423
1424
1425 def revert_module_names(document):
1426   modulemap = { 'braille' : 'Braille', 'endnotes' : 'Endnote', 'foottoend' : 'Foot to End',\
1427     'hanging' : 'Hanging', 'linguistics' : 'Linguistics', 'logicalmkup' : 'Logical Markup', \
1428     'theorems-ams-extended' : 'Theorems (AMS-Extended)', 'theorems-ams' : 'Theorems (AMS)', \
1429     'theorems-chap' : 'Theorems (Order By Chapter)', 'theorems-sec' : 'Theorems (Order By Section)', \
1430     'theorems-starred' : 'Theorems (Starred)', 'theorems-std' : 'Theorems'}
1431   modlist = document.get_module_list()
1432   if len(modlist) == 0:
1433     return
1434   newmodlist = []
1435   for mod in modlist:
1436     if modulemap.has_key(mod):
1437       newmodlist.append(modulemap[mod])
1438     else:
1439       document.warning("Can't find module %s in the module map!" % mod)
1440       newmodlist.append(mod)
1441   document.set_module_list(newmodlist)
1442
1443
1444 def revert_colsep(document):
1445     i = find_token(document.header, "\\columnsep", 0)
1446     if i == -1:
1447         return
1448     colsepline = document.header[i]
1449     r = re.compile(r'\\columnsep (.*)')
1450     m = r.match(colsepline)
1451     if not m:
1452         document.warning("Malformed column separation line!")
1453         return
1454     colsep = m.group(1)
1455     del document.header[i]
1456     #it seems to be safe to add the package even if it is already used
1457     pretext = ["\\usepackage{geometry}", "\\geometry{columnsep=" + colsep + "}"]
1458
1459     add_to_preamble(document, pretext)
1460
1461
1462 def revert_framed_notes(document):
1463     "Revert framed boxes to notes. "
1464     i = 0
1465     while 1:
1466         i = find_tokens(document.body, ["\\begin_inset Box Framed", "\\begin_inset Box Shaded"], i)
1467
1468         if i == -1:
1469             return
1470         j = find_end_of_inset(document.body, i + 1)
1471         if j == -1:
1472             # should not happen
1473             document.warning("Malformed LyX document: Could not find end of Box inset.")
1474         k = find_token(document.body, "status", i + 1, j)
1475         if k == -1:
1476             document.warning("Malformed LyX document: Missing `status' tag in Box inset.")
1477             return
1478         status = document.body[k]
1479         l = find_default_layout(document, i + 1, j)
1480         if l == -1:
1481             document.warning("Malformed LyX document: Missing `\\begin_layout' in Box inset.")
1482             return
1483         m = find_token(document.body, "\\end_layout", i + 1, j)
1484         if m == -1:
1485             document.warning("Malformed LyX document: Missing `\\end_layout' in Box inset.")
1486             return
1487         ibox = find_token(document.body, "has_inner_box 1", i + 1, k)
1488         pbox = find_token(document.body, "use_parbox 1", i + 1, k)
1489         if ibox == -1 and pbox == -1:
1490             document.body[i] = document.body[i].replace("\\begin_inset Box", "\\begin_inset Note")
1491             del document.body[i+1:k]
1492         else:
1493             document.body[i] = document.body[i].replace("\\begin_inset Box Shaded", "\\begin_inset Box Frameless")
1494             subst1 = [document.body[l],
1495                       "\\begin_inset Note Shaded",
1496                       status,
1497                       '\\begin_layout Standard']
1498             document.body[l:l + 1] = subst1
1499             subst2 = [document.body[m], "\\end_layout", "\\end_inset"]
1500             document.body[m:m + 1] = subst2
1501         i = i + 1
1502
1503
1504 def revert_slash(document):
1505     'Revert \\SpecialChar \\slash{} to ERT'
1506     r = re.compile(r'\\SpecialChar \\slash{}')
1507     i = 0
1508     while i < len(document.body):
1509         m = r.match(document.body[i])
1510         if m:
1511           subst = ['\\begin_inset ERT',
1512                    'status collapsed', '',
1513                    '\\begin_layout Standard',
1514                    '', '', '\\backslash',
1515                    'slash{}',
1516                    '\\end_layout', '',
1517                    '\\end_inset', '']
1518           document.body[i: i+1] = subst
1519           i = i + len(subst)
1520         else:
1521           i = i + 1
1522
1523
1524 def revert_nobreakdash(document):
1525     'Revert \\SpecialChar \\nobreakdash- to ERT'
1526     i = 0
1527     while i < len(document.body):
1528         line = document.body[i]
1529         r = re.compile(r'\\SpecialChar \\nobreakdash-')
1530         m = r.match(line)
1531         if m:
1532             subst = ['\\begin_inset ERT',
1533                     'status collapsed', '',
1534                     '\\begin_layout Standard', '', '',
1535                     '\\backslash',
1536                     'nobreakdash-',
1537                     '\\end_layout', '',
1538                     '\\end_inset', '']
1539             document.body[i:i+1] = subst
1540             i = i + len(subst)
1541             j = find_token(document.header, "\\use_amsmath", 0)
1542             if j == -1:
1543                 document.warning("Malformed LyX document: Missing '\\use_amsmath'.")
1544                 return
1545             document.header[j] = "\\use_amsmath 2"
1546         else:
1547             i = i + 1
1548
1549
1550 #Returns number of lines added/removed
1551 def revert_nocite_key(body, start, end):
1552     'key "..." -> \nocite{...}' 
1553     r = re.compile(r'^key "(.*)"')
1554     i = start
1555     j = end
1556     while i < j:
1557         m = r.match(body[i])
1558         if m:
1559             body[i:i+1] = ["\\backslash", "nocite{" + m.group(1) + "}"]
1560             j += 1     # because we added a line
1561             i += 2     # skip that line
1562         else:
1563             del body[i]
1564             j -= 1     # because we deleted a line
1565             # no need to change i, since it now points to the next line
1566     return j - end
1567
1568
1569 def revert_nocite(document):
1570     "Revert LatexCommand nocite to ERT"
1571     i = 0
1572     while 1:
1573         i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1574         if i == -1:
1575             return
1576         if (document.body[i+1] != "LatexCommand nocite"):
1577             # note that we already incremented i
1578             i = i + 1
1579             continue
1580         insetEnd = find_end_of_inset(document.body, i)
1581         if insetEnd == -1:
1582             #this should not happen
1583             document.warning("End of CommandInset citation not found in revert_nocite!")
1584             return
1585
1586         paramLocation = i + 2 #start of the inset's parameters
1587         addedLines = 0
1588         document.body[i:i+2] = \
1589             ["\\begin_inset ERT", "status collapsed", "", "\\begin_layout Standard"]
1590         # that added two lines
1591         paramLocation += 2
1592         insetEnd += 2
1593         #print insetEnd, document.body[i: insetEnd + 1]
1594         insetEnd += revert_nocite_key(document.body, paramLocation, insetEnd)
1595         #print insetEnd, document.body[i: insetEnd + 1]
1596         document.body.insert(insetEnd, "\\end_layout")
1597         document.body.insert(insetEnd + 1, "")
1598         i = insetEnd + 1
1599
1600
1601 def revert_btprintall(document):
1602     "Revert (non-bibtopic) btPrintAll option to ERT \nocite{*}"
1603     i = find_token(document.header, '\\use_bibtopic', 0)
1604     if i == -1:
1605         document.warning("Malformed lyx document: Missing '\\use_bibtopic'.")
1606         return
1607     if get_value(document.header, '\\use_bibtopic', 0) == "false":
1608         i = 0
1609         while i < len(document.body):
1610             i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
1611             if i == -1:
1612                 return
1613             j = find_end_of_inset(document.body, i + 1)
1614             if j == -1:
1615                 #this should not happen
1616                 document.warning("End of CommandInset bibtex not found in revert_btprintall!")
1617                 j = len(document.body)
1618             # this range isn't really right, but it should be OK, since we shouldn't
1619             # see more than one matching line in each inset
1620             addedlines = 0
1621             for k in range(i, j):
1622                 if (document.body[k] == 'btprint "btPrintAll"'):
1623                     del document.body[k]
1624                     subst = ["\\begin_inset ERT",
1625                              "status collapsed", "",
1626                              "\\begin_layout Standard", "",
1627                              "\\backslash",
1628                              "nocite{*}",
1629                              "\\end_layout",
1630                              "\\end_inset"]
1631                     document.body[i:i] = subst
1632                     addlines = addedlines + len(subst) - 1
1633             i = j + addedlines
1634
1635
1636 def revert_bahasam(document):
1637     "Set language Bahasa Malaysia to Bahasa Indonesia"
1638     i = 0
1639     if document.language == "bahasam":
1640         document.language = "bahasa"
1641         i = find_token(document.header, "\\language", 0)
1642         if i != -1:
1643             document.header[i] = "\\language bahasa"
1644     j = 0
1645     while True:
1646         j = find_token(document.body, "\\lang bahasam", j)
1647         if j == -1:
1648             return
1649         document.body[j] = document.body[j].replace("\\lang bahasam", "\\lang bahasa")
1650         j = j + 1
1651
1652
1653 def revert_interlingua(document):
1654     "Set language Interlingua to English"
1655     i = 0
1656     if document.language == "interlingua":
1657         document.language = "english"
1658         i = find_token(document.header, "\\language", 0)
1659         if i != -1:
1660             document.header[i] = "\\language english"
1661     j = 0
1662     while True:
1663         j = find_token(document.body, "\\lang interlingua", j)
1664         if j == -1:
1665             return
1666         document.body[j] = document.body[j].replace("\\lang interlingua", "\\lang english")
1667         j = j + 1
1668
1669
1670 def revert_serbianlatin(document):
1671     "Set language Serbian-Latin to Croatian"
1672     i = 0
1673     if document.language == "serbian-latin":
1674         document.language = "croatian"
1675         i = find_token(document.header, "\\language", 0)
1676         if i != -1:
1677             document.header[i] = "\\language croatian"
1678     j = 0
1679     while True:
1680         j = find_token(document.body, "\\lang serbian-latin", j)
1681         if j == -1:
1682             return
1683         document.body[j] = document.body[j].replace("\\lang serbian-latin", "\\lang croatian")
1684         j = j + 1
1685
1686
1687 def revert_rotfloat(document):
1688     " Revert sideways custom floats. "
1689     i = 0
1690     while 1:
1691         # whitespace intended (exclude \\begin_inset FloatList)
1692         i = find_token(document.body, "\\begin_inset Float ", i)
1693         if i == -1:
1694             return
1695         line = document.body[i]
1696         r = re.compile(r'\\begin_inset Float (.*)$')
1697         m = r.match(line)
1698         if m == None:
1699             document.warning("Unable to match line " + str(i) + " of body!")
1700             i += 1
1701             continue
1702         floattype = m.group(1)
1703         if floattype == "figure" or floattype == "table":
1704             i += 1
1705             continue
1706         j = find_end_of_inset(document.body, i)
1707         if j == -1:
1708             document.warning("Malformed lyx document: Missing '\\end_inset' in revert_rotfloat.")
1709             i += 1
1710             continue
1711         addedLines = 0
1712         if get_value(document.body, 'sideways', i, j) == "false":
1713             i += 1
1714             continue
1715         l = find_default_layout(document, i + 1, j)
1716         if l == -1:
1717             document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1718             return
1719         subst = ['\\begin_layout Standard',
1720                   '\\begin_inset ERT',
1721                   'status collapsed', '',
1722                   '\\begin_layout Standard', '', '', 
1723                   '\\backslash', '',
1724                   'end{sideways' + floattype + '}',
1725                   '\\end_layout', '', '\\end_inset']
1726         document.body[j : j+1] = subst
1727         addedLines = len(subst) - 1
1728         del document.body[i+1 : l]
1729         addedLines -= (l-1) - (i+1) 
1730         subst = ['\\begin_inset ERT', 'status collapsed', '',
1731                   '\\begin_layout Standard', '', '', '\\backslash', 
1732                   'begin{sideways' + floattype + '}', 
1733                   '\\end_layout', '', '\\end_inset', '',
1734                   '\\end_layout', '']
1735         document.body[i : i+1] = subst
1736         addedLines += len(subst) - 1
1737         if floattype == "algorithm":
1738             add_to_preamble(document,
1739                             ['% Commands inserted by lyx2lyx for sideways algorithm float',
1740                               '\\usepackage{rotfloat}',
1741                               '\\floatstyle{ruled}',
1742                               '\\newfloat{algorithm}{tbp}{loa}',
1743                               '\\floatname{algorithm}{Algorithm}'])
1744         else:
1745             document.warning("Cannot create preamble definition for custom float" + floattype + ".")
1746         i += addedLines + 1
1747
1748
1749 def revert_widesideways(document):
1750     " Revert wide sideways floats. "
1751     i = 0
1752     while 1:
1753         # whitespace intended (exclude \\begin_inset FloatList)
1754         i = find_token(document.body, '\\begin_inset Float ', i)
1755         if i == -1:
1756             return
1757         line = document.body[i]
1758         r = re.compile(r'\\begin_inset Float (.*)$')
1759         m = r.match(line)
1760         if m == None:
1761             document.warning("Unable to match line " + str(i) + " of body!")
1762             i += 1
1763             continue
1764         floattype = m.group(1)
1765         if floattype != "figure" and floattype != "table":
1766             i += 1
1767             continue
1768         j = find_end_of_inset(document.body, i)
1769         if j == -1:
1770             document.warning("Malformed lyx document: Missing '\\end_inset' in revert_widesideways.")
1771             i += 1
1772             continue
1773         if get_value(document.body, 'sideways', i, j) == "false" or \
1774            get_value(document.body, 'wide', i, j) == "false":
1775              i += 1
1776              continue
1777         l = find_default_layout(document, i + 1, j)
1778         if l == -1:
1779             document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1780             return
1781         subst = ['\\begin_layout Standard', '\\begin_inset ERT', 
1782                   'status collapsed', '', 
1783                   '\\begin_layout Standard', '', '', '\\backslash',
1784                   'end{sideways' + floattype + '*}', 
1785                   '\\end_layout', '', '\\end_inset']
1786         document.body[j : j+1] = subst
1787         addedLines = len(subst) - 1
1788         del document.body[i+1:l-1]
1789         addedLines -= (l-1) - (i+1)
1790         subst = ['\\begin_inset ERT', 'status collapsed', '',
1791                  '\\begin_layout Standard', '', '', '\\backslash',
1792                  'begin{sideways' + floattype + '*}', '\\end_layout', '',
1793                  '\\end_inset', '', '\\end_layout', '']
1794         document.body[i : i+1] = subst
1795         addedLines += len(subst) - 1
1796         add_to_preamble(document, ['\\usepackage{rotfloat}\n'])
1797         i += addedLines + 1
1798
1799
1800 def revert_inset_embedding(document, type):
1801     ' Remove embed tag from certain type of insets'
1802     i = 0
1803     while 1:
1804         i = find_token(document.body, "\\begin_inset %s" % type, i)
1805         if i == -1:
1806             return
1807         j = find_end_of_inset(document.body, i)
1808         if j == -1:
1809             document.warning("Malformed lyx document: Missing '\\end_inset' in revert_inset_embedding.")
1810             i = i + 1
1811             continue
1812         k = find_token(document.body, "\tembed", i, j)
1813         if k == -1:
1814             k = find_token(document.body, "embed", i, j)
1815         if k != -1:
1816             del document.body[k]
1817         i = i + 1
1818
1819
1820 def revert_external_embedding(document):
1821     ' Remove embed tag from external inset '
1822     revert_inset_embedding(document, 'External')
1823
1824
1825 # FIXME This code can still be cleaned up a fair bit.
1826 def convert_subfig(document):
1827     " Convert subfigures to subfloats. "
1828     i = 0
1829     while 1:
1830         i = find_token(document.body, '\\begin_inset Graphics', i)
1831         if i == -1:
1832             return
1833         endInset = find_end_of_inset(document.body, i)
1834         if endInset == -1:
1835             document.warning("Malformed lyx document: Missing '\\end_inset' in convert_subfig.")
1836             i += 1
1837             continue
1838         k = find_token(document.body, '\tsubcaption', i, endInset)
1839         if k == -1:
1840             i += 1
1841             continue
1842         l = find_token(document.body, '\tsubcaptionText', i, endInset)
1843         caption = document.body[l][16:].strip('"')
1844         savestr = document.body[i]
1845         laststr = document.body[endInset]
1846         del document.body[l]
1847         del document.body[k]
1848         addedLines = -2
1849         # savestr should no longer be needed here.
1850         subst = ['\\begin_inset Float figure', 'wide false', 'sideways false', 
1851                  'status open', '', '\\begin_layout Plain Layout', '\\begin_inset Caption', 
1852                  '', '\\begin_layout Plain Layout',
1853                  caption, '\\end_layout', '', '\\end_inset', '', 
1854                  '\\end_layout', '', '\\begin_layout Plain Layout', savestr]
1855         document.body[i : i+1] = subst
1856         addedLines += len(subst) - 1
1857         endInset += addedLines
1858         # There should be an easier way to do this.
1859         subst = ['', '\\end_inset', '', '\\end_layout', laststr]
1860         document.body[endInset : endInset+1] = subst
1861         addedLines += len(subst) - 1
1862         i += addedLines + 1
1863
1864
1865 def revert_subfig(document):
1866     " Revert subfloats. "
1867     i = 0
1868     while 1:
1869         # whitespace intended (exclude \\begin_inset FloatList)
1870         i = find_tokens(document.body, ['\\begin_inset Float ', '\\begin_inset Wrap'], i)
1871         if i == -1:
1872             return
1873         j = 0
1874         addedLines = 0
1875         while j != -1:
1876             j = find_end_of_inset(document.body, i)
1877             if j == -1:
1878                 document.warning("Malformed lyx document: Missing '\\end_inset' (float) at line " + str(i + len(document.header)) + ".\n\t" + document.body[i])
1879                 # document.warning(document.body[i-1] + "\n" + document.body[i+1])
1880                 i += 1
1881                 continue # this will get us back to the outer loop, since j == -1
1882             # look for embedded float (= subfloat)
1883             # whitespace intended (exclude \\begin_inset FloatList)
1884             k = find_token(document.body, '\\begin_inset Float ', i + 1, j)
1885             if k == -1:
1886                 break
1887             l = find_end_of_inset(document.body, k)
1888             if l == -1:
1889                 document.warning("Malformed lyx document: Missing '\\end_inset' (embedded float).")
1890                 i += 1
1891                 j == -1
1892                 continue # escape to the outer loop
1893             m = find_default_layout(document, k + 1, l)
1894             # caption?
1895             cap = find_token(document.body, '\\begin_inset Caption', k + 1, l)
1896             caption = ''
1897             shortcap = ''
1898             capend = cap
1899             if cap != -1:
1900                 capend = find_end_of_inset(document.body, cap)
1901                 if capend == -1:
1902                     document.warning("Malformed lyx document: Missing '\\end_inset' (caption).")
1903                     return
1904                 # label?
1905                 label = ''
1906                 lbl = find_token(document.body, '\\begin_inset CommandInset label', cap, capend)
1907                 if lbl != -1:
1908                     lblend = find_end_of_inset(document.body, lbl + 1)
1909                     if lblend == -1:
1910                         document.warning("Malformed lyx document: Missing '\\end_inset' (label).")
1911                         return
1912                     for line in document.body[lbl:lblend + 1]:
1913                         if line.startswith('name '):
1914                             label = line.split()[1].strip('"')
1915                             break
1916                 else:
1917                     lbl = capend
1918                     lblend = capend
1919                     label = ''
1920                 # opt arg?
1921                 opt = find_token(document.body, '\\begin_inset OptArg', cap, capend)
1922                 if opt != -1:
1923                     optend = find_end_of_inset(document.body, opt)
1924                     if optend == -1:
1925                         document.warning("Malformed lyx document: Missing '\\end_inset' (OptArg).")
1926                         return
1927                     optc = find_default_layout(document, opt, optend)
1928                     if optc == -1:
1929                         document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
1930                         return
1931                     optcend = find_end_of(document.body, optc, "\\begin_layout", "\\end_layout")
1932                     for line in document.body[optc:optcend]:
1933                         if not line.startswith('\\'):
1934                             shortcap += line.strip()
1935                 else:
1936                     opt = capend
1937                     optend = capend
1938                 for line in document.body[cap:capend]:
1939                     if line in document.body[lbl:lblend]:
1940                         continue
1941                     elif line in document.body[opt:optend]:
1942                         continue
1943                     elif not line.startswith('\\'):
1944                         caption += line.strip()
1945                 if len(label) > 0:
1946                     caption += "\\backslash\nlabel{" + label + "}"
1947             subst = '\\begin_layout Plain Layout\n\\begin_inset ERT\nstatus collapsed\n\n' \
1948                       '\\begin_layout Plain Layout\n\n}\n\\end_layout\n\n\\end_inset\n\n' \
1949                       '\\end_layout\n\n\\begin_layout Plain Layout\n'
1950             subst = subst.split('\n')
1951             document.body[l : l+1] = subst
1952             addedLines = len(subst) - 1
1953             # this is before l and so is unchanged by the multiline insertion
1954             if cap != capend:
1955                 del document.body[cap:capend+1]
1956                 addedLines -= (capend + 1 - cap)
1957             del document.body[k+1:m-1]
1958             addedLines -= (m - 1 - (k + 1))
1959             insertion = '\\begin_inset ERT\nstatus collapsed\n\n' \
1960                         '\\begin_layout Plain Layout\n\n\\backslash\n' \
1961                         'subfloat'
1962             if len(shortcap) > 0:
1963                 insertion = insertion + "[" + shortcap + "]"
1964             if len(caption) > 0:
1965                 insertion = insertion + "[" + caption + "]"
1966             insertion = insertion + '{%\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n'
1967             insertion = insertion.split('\n')
1968             document.body[k : k + 1] = insertion
1969             addedLines += len(insertion) - 1
1970             add_to_preamble(document,
1971                             ['\\usepackage{subfig}\n'])
1972         i += addedLines + 1
1973
1974
1975 def revert_wrapplacement(document):
1976     " Revert placement options wrap floats (wrapfig). "
1977     i = 0
1978     while True:
1979         i = find_token(document.body, "lines", i)
1980         if i == -1:
1981             return
1982         j = find_token(document.body, "placement", i+1)
1983         if j != i + 1:
1984             document.warning("Malformed LyX document: Couldn't find placement parameter of wrap float.")
1985             return
1986         document.body[j] = document.body[j].replace("placement O", "placement o")
1987         document.body[j] = document.body[j].replace("placement I", "placement i")
1988         document.body[j] = document.body[j].replace("placement L", "placement l")
1989         document.body[j] = document.body[j].replace("placement R", "placement r")
1990         i = i + 1
1991
1992
1993 def remove_extra_embedded_files(document):
1994     " Remove \extra_embedded_files from buffer params "
1995     i = find_token(document.header, '\\extra_embedded_files', 0)
1996     if i == -1:
1997         return
1998     document.header.pop(i)
1999
2000
2001 def convert_spaceinset(document):
2002     " Convert '\\InsetSpace foo' to '\\begin_inset Space foo\n\\end_inset' "
2003     i = 0
2004     while i < len(document.body):
2005         m = re.match(r'(.*)\\InsetSpace (.*)', document.body[i])
2006         if m:
2007             before = m.group(1)
2008             after = m.group(2)
2009             subst = [before, "\\begin_inset Space " + after, "\\end_inset"]
2010             document.body[i: i+1] = subst
2011             i = i + len(subst)
2012         else:
2013             i = i + 1
2014
2015
2016 def revert_spaceinset(document):
2017     " Revert '\\begin_inset Space foo\n\\end_inset' to '\\InsetSpace foo' "
2018     i = 0
2019     while True:
2020         i = find_token(document.body, "\\begin_inset Space", i)
2021         if i == -1:
2022             return
2023         j = find_end_of_inset(document.body, i)
2024         if j == -1:
2025             document.warning("Malformed LyX document: Could not find end of space inset.")
2026             continue
2027         document.body[i] = document.body[i].replace('\\begin_inset Space', '\\InsetSpace')
2028         del document.body[j]
2029
2030
2031 def convert_hfill(document):
2032     " Convert hfill to space inset "
2033     i = 0
2034     while True:
2035         i = find_token(document.body, "\\hfill", i)
2036         if i == -1:
2037             return
2038         subst = document.body[i].replace('\\hfill', \
2039                   '\n\\begin_inset Space \\hfill{}\n\\end_inset')
2040         subst = subst.split('\n')
2041         document.body[i : i+1] = subst
2042         i += len(subst)
2043
2044
2045 def revert_hfills(document):
2046     ' Revert \\hfill commands '
2047     hfill = re.compile(r'\\hfill')
2048     dotfill = re.compile(r'\\dotfill')
2049     hrulefill = re.compile(r'\\hrulefill')
2050     i = 0
2051     while True:
2052         i = find_token(document.body, "\\InsetSpace", i)
2053         if i == -1:
2054             return
2055         if hfill.search(document.body[i]):
2056             document.body[i] = \
2057               document.body[i].replace('\\InsetSpace \\hfill{}', '\\hfill')
2058             i += 1
2059             continue
2060         if dotfill.search(document.body[i]):
2061             subst = document.body[i].replace('\\InsetSpace \\dotfill{}', \
2062               '\\begin_inset ERT\nstatus collapsed\n\n' \
2063               '\\begin_layout Standard\n\n\n\\backslash\n' \
2064               'dotfill{}\n\\end_layout\n\n\\end_inset\n\n')
2065             subst = subst.split('\n')
2066             document.body[i : i+1] = subst
2067             i += len(subst)
2068             continue
2069         if hrulefill.search(document.body[i]):
2070             subst = document.body[i].replace('\\InsetSpace \\hrulefill{}', \
2071               '\\begin_inset ERT\nstatus collapsed\n\n' \
2072               '\\begin_layout Standard\n\n\n\\backslash\n' \
2073               'hrulefill{}\n\\end_layout\n\n\\end_inset\n\n')
2074             subst = subst.split('\n')
2075             document.body[i : i+1] = subst
2076             i += len(subst)
2077             continue
2078         i += 1
2079
2080 def revert_hspace(document):
2081     ' Revert \\InsetSpace \\hspace{} to ERT '
2082     i = 0
2083     hspace = re.compile(r'\\hspace{}')
2084     hstar  = re.compile(r'\\hspace\*{}')
2085     while True:
2086         i = find_token(document.body, "\\InsetSpace \\hspace", i)
2087         if i == -1:
2088             return
2089         length = get_value(document.body, '\\length', i+1)
2090         if length == '':
2091             document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
2092             return
2093         del document.body[i+1]
2094         addedLines = -1
2095         if hstar.search(document.body[i]):
2096             subst = document.body[i].replace('\\InsetSpace \\hspace*{}', \
2097               '\\begin_inset ERT\nstatus collapsed\n\n' \
2098               '\\begin_layout Standard\n\n\n\\backslash\n' \
2099               'hspace*{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
2100             subst = subst.split('\n')
2101             document.body[i : i+1] = subst
2102             addedLines += len(subst) - 1
2103             i += addedLines + 1
2104             continue
2105         if hspace.search(document.body[i]):
2106             subst = document.body[i].replace('\\InsetSpace \\hspace{}', \
2107               '\\begin_inset ERT\nstatus collapsed\n\n' \
2108               '\\begin_layout Standard\n\n\n\\backslash\n' \
2109               'hspace{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
2110             subst = subst.split('\n')
2111             document.body[i : i+1] = subst
2112             addedLines += len(subst) - 1
2113             i += addedLines + 1
2114             continue
2115         i += 1
2116
2117
2118 def revert_protected_hfill(document):
2119     ' Revert \\begin_inset Space \\hspace*{\\fill} to ERT '
2120     i = 0
2121     while True:
2122         i = find_token(document.body, '\\begin_inset Space \\hspace*{\\fill}', i)
2123         if i == -1:
2124             return
2125         j = find_end_of_inset(document.body, i)
2126         if j == -1:
2127             document.warning("Malformed LyX document: Could not find end of space inset.")
2128             continue
2129         del document.body[j]
2130         subst = document.body[i].replace('\\begin_inset Space \\hspace*{\\fill}', \
2131           '\\begin_inset ERT\nstatus collapsed\n\n' \
2132           '\\begin_layout Standard\n\n\n\\backslash\n' \
2133           'hspace*{\n\\backslash\nfill}\n\\end_layout\n\n\\end_inset\n\n')
2134         subst = subst.split('\n')
2135         document.body[i : i+1] = subst
2136         i += len(subst)
2137
2138
2139 def revert_leftarrowfill(document):
2140     ' Revert \\begin_inset Space \\leftarrowfill{} to ERT '
2141     i = 0
2142     while True:
2143         i = find_token(document.body, '\\begin_inset Space \\leftarrowfill{}', i)
2144         if i == -1:
2145             return
2146         j = find_end_of_inset(document.body, i)
2147         if j == -1:
2148             document.warning("Malformed LyX document: Could not find end of space inset.")
2149             continue
2150         del document.body[j]
2151         subst = document.body[i].replace('\\begin_inset Space \\leftarrowfill{}', \
2152           '\\begin_inset ERT\nstatus collapsed\n\n' \
2153           '\\begin_layout Standard\n\n\n\\backslash\n' \
2154           'leftarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
2155         subst = subst.split('\n')
2156         document.body[i : i+1] = subst
2157         i += len(subst)
2158
2159
2160 def revert_rightarrowfill(document):
2161     ' Revert \\begin_inset Space \\rightarrowfill{} to ERT '
2162     i = 0
2163     while True:
2164         i = find_token(document.body, '\\begin_inset Space \\rightarrowfill{}', i)
2165         if i == -1:
2166             return
2167         j = find_end_of_inset(document.body, i)
2168         if j == -1:
2169             document.warning("Malformed LyX document: Could not find end of space inset.")
2170             continue
2171         del document.body[j]
2172         subst = document.body[i].replace('\\begin_inset Space \\rightarrowfill{}', \
2173           '\\begin_inset ERT\nstatus collapsed\n\n' \
2174           '\\begin_layout Standard\n\n\n\\backslash\n' \
2175           'rightarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
2176         subst = subst.split('\n')
2177         document.body[i : i+1] = subst
2178         i += len(subst)
2179
2180
2181 def revert_upbracefill(document):
2182     ' Revert \\begin_inset Space \\upbracefill{} to ERT '
2183     i = 0
2184     while True:
2185         i = find_token(document.body, '\\begin_inset Space \\upbracefill{}', i)
2186         if i == -1:
2187             return
2188         j = find_end_of_inset(document.body, i)
2189         if j == -1:
2190             document.warning("Malformed LyX document: Could not find end of space inset.")
2191             continue
2192         del document.body[j]
2193         subst = document.body[i].replace('\\begin_inset Space \\upbracefill{}', \
2194           '\\begin_inset ERT\nstatus collapsed\n\n' \
2195           '\\begin_layout Standard\n\n\n\\backslash\n' \
2196           'upbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
2197         subst = subst.split('\n')
2198         document.body[i : i+1] = subst
2199         i += len(subst)
2200
2201
2202 def revert_downbracefill(document):
2203     ' Revert \\begin_inset Space \\downbracefill{} to ERT '
2204     i = 0
2205     while True:
2206         i = find_token(document.body, '\\begin_inset Space \\downbracefill{}', i)
2207         if i == -1:
2208             return
2209         j = find_end_of_inset(document.body, i)
2210         if j == -1:
2211             document.warning("Malformed LyX document: Could not find end of space inset.")
2212             continue
2213         del document.body[j]
2214         subst = document.body[i].replace('\\begin_inset Space \\downbracefill{}', \
2215           '\\begin_inset ERT\nstatus collapsed\n\n' \
2216           '\\begin_layout Standard\n\n\n\\backslash\n' \
2217           'downbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
2218         subst = subst.split('\n')
2219         document.body[i : i+1] = subst
2220         i += len(subst)
2221
2222
2223 def revert_local_layout(document):
2224     ' Revert local layout headers.'
2225     i = 0
2226     while True:
2227         i = find_token(document.header, "\\begin_local_layout", i)
2228         if i == -1:
2229             return
2230         j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
2231         if j == -1:
2232             # this should not happen
2233             break
2234         document.header[i : j + 1] = []
2235
2236
2237 def convert_pagebreaks(document):
2238     ' Convert inline Newpage insets to new format '
2239     i = 0
2240     while True:
2241         i = find_token(document.body, '\\newpage', i)
2242         if i == -1:
2243             break
2244         document.body[i:i+1] = ['\\begin_inset Newpage newpage',
2245                                 '\\end_inset']
2246     i = 0
2247     while True:
2248         i = find_token(document.body, '\\pagebreak', i)
2249         if i == -1:
2250             break
2251         document.body[i:i+1] = ['\\begin_inset Newpage pagebreak',
2252                                 '\\end_inset']
2253     i = 0
2254     while True:
2255         i = find_token(document.body, '\\clearpage', i)
2256         if i == -1:
2257             break
2258         document.body[i:i+1] = ['\\begin_inset Newpage clearpage',
2259                                 '\\end_inset']
2260     i = 0
2261     while True:
2262         i = find_token(document.body, '\\cleardoublepage', i)
2263         if i == -1:
2264             break
2265         document.body[i:i+1] = ['\\begin_inset Newpage cleardoublepage',
2266                                 '\\end_inset']
2267
2268
2269 def revert_pagebreaks(document):
2270     ' Revert \\begin_inset Newpage to previous inline format '
2271     i = 0
2272     while True:
2273         i = find_token(document.body, '\\begin_inset Newpage', i)
2274         if i == -1:
2275             return
2276         j = find_end_of_inset(document.body, i)
2277         if j == -1:
2278             document.warning("Malformed LyX document: Could not find end of Newpage inset.")
2279             continue
2280         del document.body[j]
2281         document.body[i] = document.body[i].replace('\\begin_inset Newpage newpage', '\\newpage')
2282         document.body[i] = document.body[i].replace('\\begin_inset Newpage pagebreak', '\\pagebreak')
2283         document.body[i] = document.body[i].replace('\\begin_inset Newpage clearpage', '\\clearpage')
2284         document.body[i] = document.body[i].replace('\\begin_inset Newpage cleardoublepage', '\\cleardoublepage')
2285
2286
2287 def convert_linebreaks(document):
2288     ' Convert inline Newline insets to new format '
2289     i = 0
2290     while True:
2291         i = find_token(document.body, '\\newline', i)
2292         if i == -1:
2293             break
2294         document.body[i:i+1] = ['\\begin_inset Newline newline',
2295                                 '\\end_inset']
2296     i = 0
2297     while True:
2298         i = find_token(document.body, '\\linebreak', i)
2299         if i == -1:
2300             break
2301         document.body[i:i+1] = ['\\begin_inset Newline linebreak',
2302                                 '\\end_inset']
2303
2304
2305 def revert_linebreaks(document):
2306     ' Revert \\begin_inset Newline to previous inline format '
2307     i = 0
2308     while True:
2309         i = find_token(document.body, '\\begin_inset Newline', i)
2310         if i == -1:
2311             return
2312         j = find_end_of_inset(document.body, i)
2313         if j == -1:
2314             document.warning("Malformed LyX document: Could not find end of Newline inset.")
2315             continue
2316         del document.body[j]
2317         document.body[i] = document.body[i].replace('\\begin_inset Newline newline', '\\newline')
2318         document.body[i] = document.body[i].replace('\\begin_inset Newline linebreak', '\\linebreak')
2319
2320
2321 def convert_japanese_plain(document):
2322     ' Set language japanese-plain to japanese '
2323     i = 0
2324     if document.language == "japanese-plain":
2325         document.language = "japanese"
2326         i = find_token(document.header, "\\language", 0)
2327         if i != -1:
2328             document.header[i] = "\\language japanese"
2329     j = 0
2330     while True:
2331         j = find_token(document.body, "\\lang japanese-plain", j)
2332         if j == -1:
2333             return
2334         document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
2335         j = j + 1
2336
2337
2338 def revert_pdfpages(document):
2339     ' Revert pdfpages external inset to ERT '
2340     i = 0
2341     while 1:
2342         i = find_token(document.body, "\\begin_inset External", i)
2343         if i == -1:
2344             return
2345         j = find_end_of_inset(document.body, i)
2346         if j == -1:
2347             document.warning("Malformed lyx document: Missing '\\end_inset' in revert_pdfpages.")
2348             i = i + 1
2349             continue
2350         if get_value(document.body, 'template', i, j) == "PDFPages":
2351             filename = get_value(document.body, 'filename', i, j)
2352             extra = ''
2353             r = re.compile(r'\textra PDFLaTeX \"(.*)\"$')
2354             for k in range(i, j):
2355                 m = r.match(document.body[k])
2356                 if m:
2357                     extra = m.group(1)
2358             angle = get_value(document.body, 'rotateAngle', i, j)
2359             width = get_value(document.body, 'width', i, j)
2360             height = get_value(document.body, 'height', i, j)
2361             scale = get_value(document.body, 'scale', i, j)
2362             keepAspectRatio = find_token(document.body, "\tkeepAspectRatio", i, j)
2363             options = extra
2364             if angle != '':
2365                  if options != '':
2366                      options += ",angle=" + angle
2367                  else:
2368                      options += "angle=" + angle
2369             if width != '':
2370                  if options != '':
2371                      options += ",width=" + convert_len(width)
2372                  else:
2373                      options += "width=" + convert_len(width)
2374             if height != '':
2375                  if options != '':
2376                      options += ",height=" + convert_len(height)
2377                  else:
2378                      options += "height=" + convert_len(height)
2379             if scale != '':
2380                  if options != '':
2381                      options += ",scale=" + scale
2382                  else:
2383                      options += "scale=" + scale
2384             if keepAspectRatio != '':
2385                  if options != '':
2386                      options += ",keepaspectratio"
2387                  else:
2388                      options += "keepaspectratio"
2389             if options != '':
2390                      options = '[' + options + ']'
2391             del document.body[i+1:j+1]
2392             document.body[i:i+1] = ['\\begin_inset ERT',
2393                                 'status collapsed',
2394                                 '',
2395                                 '\\begin_layout Standard',
2396                                 '',
2397                                 '\\backslash',
2398                                 'includepdf' + options + '{' + filename + '}',
2399                                 '\\end_layout',
2400                                 '',
2401                                 '\\end_inset']
2402             add_to_preamble(document, ['\\usepackage{pdfpages}\n'])
2403             i = i + 1
2404             continue
2405         i = i + 1
2406
2407
2408 def revert_mexican(document):
2409     ' Set language Spanish(Mexico) to Spanish '
2410     i = 0
2411     if document.language == "spanish-mexico":
2412         document.language = "spanish"
2413         i = find_token(document.header, "\\language", 0)
2414         if i != -1:
2415             document.header[i] = "\\language spanish"
2416     j = 0
2417     while True:
2418         j = find_token(document.body, "\\lang spanish-mexico", j)
2419         if j == -1:
2420             return
2421         document.body[j] = document.body[j].replace("\\lang spanish-mexico", "\\lang spanish")
2422         j = j + 1
2423
2424
2425 def remove_embedding(document):
2426     ' Remove embed tag from all insets '
2427     revert_inset_embedding(document, 'Graphics')
2428     revert_inset_embedding(document, 'External')
2429     revert_inset_embedding(document, 'CommandInset include')
2430     revert_inset_embedding(document, 'CommandInset bibtex')
2431
2432
2433 def revert_master(document):
2434     ' Remove master param '
2435     i = find_token(document.header, "\\master", 0)
2436     if i != -1:
2437         del document.header[i]
2438
2439
2440 def revert_graphics_group(document):
2441     ' Revert group information from graphics insets '
2442     i = 0
2443     while 1:
2444         i = find_token(document.body, "\\begin_inset Graphics", i)
2445         if i == -1:
2446             return
2447         j = find_end_of_inset(document.body, i)
2448         if j == -1:
2449             document.warning("Malformed lyx document: Missing '\\end_inset' in revert_graphics_group.")
2450             i = i + 1
2451             continue
2452         k = find_token(document.body, " groupId", i, j)
2453         if k == -1:
2454             i = i + 1
2455             continue
2456         del document.body[k]
2457         i = i + 1
2458
2459
2460 def update_apa_styles(document):
2461     ' Replace obsolete styles '
2462
2463     if document.textclass != "apa":
2464         return
2465
2466     obsoletedby = { "Acknowledgments": "Acknowledgements",
2467                     "Section*":        "Section",
2468                     "Subsection*":     "Subsection",
2469                     "Subsubsection*":  "Subsubsection",
2470                     "Paragraph*":      "Paragraph",
2471                     "Subparagraph*":   "Subparagraph"}
2472     i = 0
2473     while 1:
2474         i = find_token(document.body, "\\begin_layout", i)
2475         if i == -1:
2476             return
2477
2478         layout = document.body[i][14:]
2479         if layout in obsoletedby:
2480             document.body[i] = "\\begin_layout " + obsoletedby[layout]
2481
2482         i += 1
2483
2484
2485 def convert_paper_sizes(document):
2486     ' exchange size options legalpaper and executivepaper to correct order '
2487     # routine is needed to fix http://bugzilla.lyx.org/show_bug.cgi?id=4868
2488     i = 0
2489     j = 0
2490     i = find_token(document.header, "\\papersize executivepaper", 0)
2491     if i != -1:
2492         document.header[i] = "\\papersize legalpaper"
2493         return
2494     j = find_token(document.header, "\\papersize legalpaper", 0)
2495     if j != -1:
2496         document.header[j] = "\\papersize executivepaper"
2497
2498
2499 def revert_paper_sizes(document):
2500     ' exchange size options legalpaper and executivepaper to correct order '
2501     i = 0
2502     j = 0
2503     i = find_token(document.header, "\\papersize executivepaper", 0)
2504     if i != -1:
2505         document.header[i] = "\\papersize legalpaper"
2506         return
2507     j = find_token(document.header, "\\papersize legalpaper", 0)
2508     if j != -1:
2509         document.header[j] = "\\papersize executivepaper"
2510
2511
2512 def convert_InsetSpace(document):
2513     " Convert '\\begin_inset Space foo' to '\\begin_inset space foo'"
2514     i = 0
2515     while True:
2516         i = find_token(document.body, "\\begin_inset Space", i)
2517         if i == -1:
2518             return
2519         document.body[i] = document.body[i].replace('\\begin_inset Space', '\\begin_inset space')
2520
2521
2522 def revert_InsetSpace(document):
2523     " Revert '\\begin_inset space foo' to '\\begin_inset Space foo'"
2524     i = 0
2525     while True:
2526         i = find_token(document.body, "\\begin_inset space", i)
2527         if i == -1:
2528             return
2529         document.body[i] = document.body[i].replace('\\begin_inset space', '\\begin_inset Space')
2530
2531
2532 def convert_display_enum(document):
2533     " Convert 'display foo' to 'display false/true'"
2534     i = 0
2535     while True:
2536         i = find_token(document.body, "\tdisplay", i)
2537         if i == -1:
2538             return
2539         val = get_value(document.body, 'display', i)
2540         if val == "none":
2541             document.body[i] = document.body[i].replace('none', 'false')
2542         if val == "default":
2543             document.body[i] = document.body[i].replace('default', 'true')
2544         if val == "monochrome":
2545             document.body[i] = document.body[i].replace('monochrome', 'true')
2546         if val == "grayscale":
2547             document.body[i] = document.body[i].replace('grayscale', 'true')
2548         if val == "color":
2549             document.body[i] = document.body[i].replace('color', 'true')
2550         if val == "preview":
2551             document.body[i] = document.body[i].replace('preview', 'true')
2552         i += 1
2553
2554
2555 def revert_display_enum(document):
2556     " Revert 'display false/true' to 'display none/color'"
2557     i = 0
2558     while True:
2559         i = find_token(document.body, "\tdisplay", i)
2560         if i == -1:
2561             return
2562         val = get_value(document.body, 'display', i)
2563         if val == "false":
2564             document.body[i] = document.body[i].replace('false', 'none')
2565         if val == "true":
2566             document.body[i] = document.body[i].replace('true', 'default')
2567         i += 1
2568
2569
2570 def remove_fontsCJK(document):
2571     ' Remove font_cjk param '
2572     i = find_token(document.header, "\\font_cjk", 0)
2573     if i != -1:
2574         del document.header[i]
2575
2576
2577 def convert_plain_layout(document):
2578     " Convert 'PlainLayout' to 'Plain Layout'" 
2579     i = 0
2580     while True:
2581         i = find_token(document.body, '\\begin_layout PlainLayout', i)
2582         if i == -1:
2583             return
2584         document.body[i] = document.body[i].replace('\\begin_layout PlainLayout', \
2585           '\\begin_layout Plain Layout')
2586         i += 1
2587
2588
2589 def revert_plain_layout(document):
2590     " Convert 'PlainLayout' to 'Plain Layout'" 
2591     i = 0
2592     while True:
2593         i = find_token(document.body, '\\begin_layout Plain Layout', i)
2594         if i == -1:
2595             return
2596         document.body[i] = document.body[i].replace('\\begin_layout Plain Layout', \
2597           '\\begin_layout PlainLayout')
2598         i += 1
2599
2600
2601 def revert_plainlayout(document):
2602     " Convert 'PlainLayout' to 'Plain Layout'" 
2603     i = 0
2604     while True:
2605         i = find_token(document.body, '\\begin_layout PlainLayout', i)
2606         if i == -1:
2607             return
2608         # This will be incorrect for some document classes, since Standard is not always
2609         # the default. But (a) it is probably the best we can do and (b) it will actually
2610         # work, in fact, since an unknown layout will be converted to default.
2611         document.body[i] = document.body[i].replace('\\begin_layout PlainLayout', \
2612           '\\begin_layout Standard')
2613         i += 1
2614
2615
2616 def revert_polytonicgreek(document):
2617     "Set language polytonic Greek to Greek"
2618     i = 0
2619     if document.language == "polutonikogreek":
2620         document.language = "greek"
2621         i = find_token(document.header, "\\language", 0)
2622         if i != -1:
2623             document.header[i] = "\\language greek"
2624     j = 0
2625     while True:
2626         j = find_token(document.body, "\\lang polutonikogreek", j)
2627         if j == -1:
2628             return
2629         document.body[j] = document.body[j].replace("\\lang polutonikogreek", "\\lang greek")
2630         j = j + 1
2631
2632
2633 ##
2634 # Conversion hub
2635 #
2636
2637 supported_versions = ["1.6.0","1.6"]
2638 convert = [[277, [fix_wrong_tables]],
2639            [278, [close_begin_deeper]],
2640            [279, [long_charstyle_names]],
2641            [280, [axe_show_label]],
2642            [281, []],
2643            [282, []],
2644            [283, [convert_flex]],
2645            [284, []],
2646            [285, []],
2647            [286, []],
2648            [287, [convert_wrapfig_options]],
2649            [288, [convert_inset_command]],
2650            [289, [convert_latexcommand_index]],
2651            [290, []],
2652            [291, []],
2653            [292, []],
2654            [293, []],
2655            [294, [convert_pdf_options]],
2656            [295, [convert_htmlurl, convert_url]],
2657            [296, [convert_include]],
2658            [297, [convert_usorbian]],
2659            [298, []],
2660            [299, []],
2661            [300, []],
2662            [301, []],
2663            [302, []],
2664            [303, [convert_serbocroatian]],
2665            [304, [convert_framed_notes]],
2666            [305, []],
2667            [306, []],
2668            [307, []],
2669            [308, []],
2670            [309, []],
2671            [310, []],
2672            [311, [convert_ams_classes]],
2673            [312, []],
2674            [313, [convert_module_names]],
2675            [314, []],
2676            [315, []],
2677            [316, [convert_subfig]],
2678            [317, []],
2679            [318, []],
2680            [319, [convert_spaceinset, convert_hfill]],
2681            [320, []],
2682            [321, [convert_tablines]],
2683            [322, [convert_plain_layout]],
2684            [323, [convert_pagebreaks]],
2685            [324, [convert_linebreaks]],
2686            [325, [convert_japanese_plain]],
2687            [326, []],
2688            [327, []],
2689            [328, [remove_embedding, remove_extra_embedded_files, remove_inzip_options]],
2690            [329, []],
2691            [330, []],
2692            [331, [convert_ltcaption]],
2693            [332, []],
2694            [333, [update_apa_styles]],
2695            [334, [convert_paper_sizes]],
2696            [335, [convert_InsetSpace]],
2697            [336, []],
2698            [337, [convert_display_enum]],
2699            [338, []],
2700           ]
2701
2702 revert =  [[337, [revert_polytonicgreek]],
2703            [336, [revert_display_enum]],
2704            [335, [remove_fontsCJK]],
2705            [334, [revert_InsetSpace]],
2706            [333, [revert_paper_sizes]],
2707            [332, []],
2708            [331, [revert_graphics_group]],
2709            [330, [revert_ltcaption]],
2710            [329, [revert_leftarrowfill, revert_rightarrowfill, revert_upbracefill, revert_downbracefill]],
2711            [328, [revert_master]],
2712            [327, []],
2713            [326, [revert_mexican]],
2714            [325, [revert_pdfpages]],
2715            [324, []],
2716            [323, [revert_linebreaks]],
2717            [322, [revert_pagebreaks]],
2718            [321, [revert_local_layout, revert_plain_layout]],
2719            [320, [revert_tablines]],
2720            [319, [revert_protected_hfill]],
2721            [318, [revert_spaceinset, revert_hfills, revert_hspace]],
2722            [317, [remove_extra_embedded_files]],
2723            [316, [revert_wrapplacement]],
2724            [315, [revert_subfig]],
2725            [314, [revert_colsep, revert_plainlayout]],
2726            [313, []],
2727            [312, [revert_module_names]],
2728            [311, [revert_rotfloat, revert_widesideways]],
2729            [310, [revert_external_embedding]],
2730            [309, [revert_btprintall]],
2731            [308, [revert_nocite]],
2732            [307, [revert_serbianlatin]],
2733            [306, [revert_slash, revert_nobreakdash]],
2734            [305, [revert_interlingua]],
2735            [304, [revert_bahasam]],
2736            [303, [revert_framed_notes]],
2737            [302, []],
2738            [301, [revert_latin, revert_samin]],
2739            [300, [revert_linebreak]],
2740            [299, [revert_pagebreak]],
2741            [298, [revert_hyperlinktype]],
2742            [297, [revert_macro_optional_params]],
2743            [296, [revert_albanian, revert_lowersorbian, revert_uppersorbian]],
2744            [295, [revert_include]],
2745            [294, [revert_href, revert_url]],
2746            [293, [revert_pdf_options_2]],
2747            [292, [revert_inset_info]],
2748            [291, [revert_japanese, revert_japanese_encoding]],
2749            [290, [revert_vietnamese]],
2750            [289, [revert_wraptable]],
2751            [288, [revert_latexcommand_index]],
2752            [287, [revert_inset_command]],
2753            [286, [revert_wrapfig_options]],
2754            [285, [revert_pdf_options]],
2755            [284, [remove_inzip_options]],
2756            [283, []],
2757            [282, [revert_flex]],
2758            [281, []],
2759            [280, [revert_begin_modules]],
2760            [279, [revert_show_label]],
2761            [278, [revert_long_charstyle_names]],
2762            [277, []],
2763            [276, []]
2764           ]
2765
2766
2767 if __name__ == "__main__":
2768     pass