1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2010 The LyX team
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 """ Convert files to the file format generated by lyx 2.0"""
26 from parser_tools import find_token, find_end_of, find_tokens, \
27 find_end_of_inset, find_end_of_layout, get_value, get_value_string
29 from lyx2lyx_tools import add_to_preamble, insert_to_preamble, \
30 put_cmd_in_ert, lyx2latex, latex_length, revert_flex_inset, \
31 revert_font_attrs, revert_layout_command, hex2ratio
33 ####################################################################
34 # Private helper functions
36 def remove_option(document, m, option):
37 ''' removes option from line m. returns whether we did anything '''
38 l = document.body[m].find(option)
41 val = document.body[m][l:].split('"')[1]
42 document.body[m] = document.body[m][:l - 1] + document.body[m][l+len(option + '="' + val + '"'):]
46 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
47 # have been made of it with uses of put_cmd_in_ert.
48 def old_put_cmd_in_ert(string):
49 for rep in unicode_reps:
50 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
51 string = string.replace('\\', "\\backslash\n")
52 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
53 + string + "\n\\end_layout\n\\end_inset"
57 ###############################################################################
59 ### Conversion and reversion routines
61 ###############################################################################
63 def revert_swiss(document):
64 " Set language german-ch to ngerman "
66 if document.language == "german-ch":
67 document.language = "ngerman"
68 i = find_token(document.header, "\\language", 0)
70 document.header[i] = "\\language ngerman"
73 j = find_token(document.body, "\\lang german-ch", j)
76 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
80 def revert_tabularvalign(document):
81 " Revert the tabular valign option "
84 i = find_token(document.body, "\\begin_inset Tabular", i)
87 end = find_end_of_inset(document.body, i)
89 document.warning("Can't find end of inset at line " + str(i))
92 fline = find_token(document.body, "<features", i, end)
94 document.warning("Can't find features for inset at line " + str(i))
97 p = document.body[fline].find("islongtable")
99 q = document.body[fline].find("tabularvalignment")
102 # This seems wrong: It removes everything after
103 # tabularvalignment, too.
104 document.body[fline] = document.body[fline][:q - 1] + '>'
109 tabularvalignment = 'c'
110 # which valignment is specified?
111 m = document.body[fline].find('tabularvalignment="top"')
113 tabularvalignment = 't'
114 m = document.body[fline].find('tabularvalignment="bottom"')
116 tabularvalignment = 'b'
117 # delete tabularvalignment
118 q = document.body[fline].find("tabularvalignment")
121 # This seems wrong: It removes everything after
122 # tabularvalignment, too.
123 document.body[fline] = document.body[fline][:q - 1] + '>'
125 # don't add a box when centered
126 if tabularvalignment == 'c':
129 subst = ['\\end_layout', '\\end_inset']
130 document.body[end:end] = subst # just inserts those lines
131 subst = ['\\begin_inset Box Frameless',
132 'position "' + tabularvalignment +'"',
137 # we don't know the width, assume 50%
141 'height_special "totalheight"',
144 '\\begin_layout Plain Layout']
145 document.body[i:i] = subst # this just inserts the array at i
146 # since there could be a tabular inside a tabular, we cannot
151 def revert_phantom_types(document, ptype, cmd):
152 " Reverts phantom to ERT "
155 i = find_token(document.body, "\\begin_inset Phantom " + ptype, i)
158 end = find_end_of_inset(document.body, i)
160 document.warning("Can't find end of inset at line " + str(i))
163 blay = find_token(document.body, "\\begin_layout Plain Layout", i, end)
165 document.warning("Can't find layout for inset at line " + str(i))
168 bend = find_token(document.body, "\\end_layout", blay, end)
170 document.warning("Malformed LyX document: Could not find end of Phantom inset's layout.")
173 substi = ["\\begin_inset ERT", "status collapsed", "",
174 "\\begin_layout Plain Layout", "", "", "\\backslash",
175 cmd + "{", "\\end_layout", "", "\\end_inset"]
176 substj = ["\\size default", "", "\\begin_inset ERT", "status collapsed", "",
177 "\\begin_layout Plain Layout", "", "}", "\\end_layout", "", "\\end_inset"]
178 # do the later one first so as not to mess up the numbering
179 document.body[bend:end + 1] = substj
180 document.body[i:blay + 1] = substi
181 i = end + len(substi) + len(substj) - (end - bend) - (blay - i) - 2
184 def revert_phantom(document):
185 revert_phantom_types(document, "Phantom", "phantom")
187 def revert_hphantom(document):
188 revert_phantom_types(document, "HPhantom", "hphantom")
190 def revert_vphantom(document):
191 revert_phantom_types(document, "VPhantom", "vphantom")
194 def revert_xetex(document):
195 " Reverts documents that use XeTeX "
196 i = find_token(document.header, '\\use_xetex', 0)
198 document.warning("Malformed LyX document: Missing \\use_xetex.")
200 if get_value(document.header, "\\use_xetex", i) == 'false':
201 del document.header[i]
203 del document.header[i]
204 # 1.) set doc encoding to utf8-plain
205 i = find_token(document.header, "\\inputencoding", 0)
207 document.warning("Malformed LyX document: Missing \\inputencoding.")
208 document.header[i] = "\\inputencoding utf8-plain"
209 # 2.) check font settings
210 l = find_token(document.header, "\\font_roman", 0)
212 document.warning("Malformed LyX document: Missing \\font_roman.")
213 line = document.header[l]
214 l = re.compile(r'\\font_roman (.*)$')
217 l = find_token(document.header, "\\font_sans", 0)
219 document.warning("Malformed LyX document: Missing \\font_sans.")
220 line = document.header[l]
221 l = re.compile(r'\\font_sans (.*)$')
224 l = find_token(document.header, "\\font_typewriter", 0)
226 document.warning("Malformed LyX document: Missing \\font_typewriter.")
227 line = document.header[l]
228 l = re.compile(r'\\font_typewriter (.*)$')
230 typewriter = m.group(1)
231 osf = get_value(document.header, '\\font_osf', 0) == "true"
232 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
233 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
234 # 3.) set preamble stuff
235 pretext = '%% This document must be processed with xelatex!\n'
236 pretext += '\\usepackage{fontspec}\n'
237 if roman != "default":
238 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
239 if sans != "default":
240 pretext += '\\setsansfont['
242 pretext += 'Scale=' + str(sf_scale / 100) + ','
243 pretext += 'Mapping=tex-text]{' + sans + '}\n'
244 if typewriter != "default":
245 pretext += '\\setmonofont'
247 pretext += '[Scale=' + str(tt_scale / 100) + ']'
248 pretext += '{' + typewriter + '}\n'
250 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
251 pretext += '\usepackage{xunicode}\n'
252 pretext += '\usepackage{xltxtra}\n'
253 insert_to_preamble(0, document, pretext)
254 # 4.) reset font settings
255 i = find_token(document.header, "\\font_roman", 0)
257 document.warning("Malformed LyX document: Missing \\font_roman.")
258 document.header[i] = "\\font_roman default"
259 i = find_token(document.header, "\\font_sans", 0)
261 document.warning("Malformed LyX document: Missing \\font_sans.")
262 document.header[i] = "\\font_sans default"
263 i = find_token(document.header, "\\font_typewriter", 0)
265 document.warning("Malformed LyX document: Missing \\font_typewriter.")
266 document.header[i] = "\\font_typewriter default"
267 i = find_token(document.header, "\\font_osf", 0)
269 document.warning("Malformed LyX document: Missing \\font_osf.")
270 document.header[i] = "\\font_osf false"
271 i = find_token(document.header, "\\font_sc", 0)
273 document.warning("Malformed LyX document: Missing \\font_sc.")
274 document.header[i] = "\\font_sc false"
275 i = find_token(document.header, "\\font_sf_scale", 0)
277 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
278 document.header[i] = "\\font_sf_scale 100"
279 i = find_token(document.header, "\\font_tt_scale", 0)
281 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
282 document.header[i] = "\\font_tt_scale 100"
285 def revert_outputformat(document):
286 " Remove default output format param "
287 i = find_token(document.header, '\\default_output_format', 0)
289 document.warning("Malformed LyX document: Missing \\default_output_format.")
291 del document.header[i]
294 def revert_backgroundcolor(document):
295 " Reverts background color to preamble code "
296 i = find_token(document.header, "\\backgroundcolor", 0)
299 colorcode = get_value(document.header, '\\backgroundcolor', i)
300 del document.header[i]
301 # don't clutter the preamble if backgroundcolor is not set
302 if colorcode == "#ffffff":
304 red = hex2ratio(colorcode[1:3])
305 green = hex2ratio(colorcode[3:5])
306 blue = hex2ratio(colorcode[5:7])
307 insert_to_preamble(0, document,
308 '% Commands inserted by lyx2lyx to set the background color\n'
309 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
310 + '\\definecolor{page_backgroundcolor}{rgb}{'
311 + red + ',' + green + ',' + blue + '}\n'
312 + '\\pagecolor{page_backgroundcolor}\n')
315 def revert_splitindex(document):
316 " Reverts splitindex-aware documents "
317 i = find_token(document.header, '\\use_indices', 0)
319 document.warning("Malformed LyX document: Missing \\use_indices.")
321 indices = get_value(document.header, "\\use_indices", i)
323 useindices = (indices == "true")
325 preamble += "\\usepackage{splitidx}\n"
326 del document.header[i]
328 # deal with index declarations in the preamble
331 i = find_token(document.header, "\\index", i)
334 k = find_token(document.header, "\\end_index", i)
336 document.warning("Malformed LyX document: Missing \\end_index.")
339 line = document.header[i]
340 l = re.compile(r'\\index (.*)$')
343 ishortcut = get_value(document.header, '\\shortcut', i, k)
345 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
346 del document.header[i:k + 1]
348 insert_to_preamble(0, document, preamble)
350 # deal with index insets
351 # these need to have the argument removed
354 i = find_token(document.body, "\\begin_inset Index", i)
357 line = document.body[i]
358 l = re.compile(r'\\begin_inset Index (.*)$')
361 if itype == "idx" or indices == "false":
362 document.body[i] = "\\begin_inset Index"
364 k = find_end_of_inset(document.body, i)
366 document.warning("Can't find end of index inset!")
369 content = lyx2latex(document, document.body[i:k])
371 content = content.replace('"', r'\"')
372 subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
373 document.body[i:k + 1] = subst
376 # deal with index_print insets
379 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
382 k = find_end_of_inset(document.body, i)
383 ptype = get_value(document.body, 'type', i, k).strip('"')
385 j = find_token(document.body, "type", i, k)
388 del document.body[i:k + 1]
390 subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
391 document.body[i:k + 1] = subst
395 def convert_splitindex(document):
396 " Converts index and printindex insets to splitindex-aware format "
399 i = find_token(document.body, "\\begin_inset Index", i)
402 document.body[i] = document.body[i].replace("\\begin_inset Index",
403 "\\begin_inset Index idx")
407 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
410 if document.body[i + 1].find('LatexCommand printindex') == -1:
411 document.warning("Malformed LyX document: Incomplete printindex inset.")
413 subst = ["LatexCommand printindex",
415 document.body[i + 1:i + 2] = subst
419 def revert_subindex(document):
420 " Reverts \\printsubindex CommandInset types "
421 i = find_token(document.header, '\\use_indices', 0)
423 document.warning("Malformed LyX document: Missing \\use_indices.")
425 indices = get_value(document.header, "\\use_indices", i)
426 useindices = (indices == "true")
429 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
432 k = find_end_of_inset(document.body, i)
433 ctype = get_value(document.body, 'LatexCommand', i, k)
434 if ctype != "printsubindex":
437 ptype = get_value(document.body, 'type', i, k).strip('"')
439 del document.body[i:k + 1]
441 subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
442 document.body[i:k + 1] = subst
446 def revert_printindexall(document):
447 " Reverts \\print[sub]index* CommandInset types "
448 i = find_token(document.header, '\\use_indices', 0)
450 document.warning("Malformed LyX document: Missing \\use_indices.")
452 indices = get_value(document.header, "\\use_indices", i)
453 useindices = (indices == "true")
456 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
459 k = find_end_of_inset(document.body, i)
460 ctype = get_value(document.body, 'LatexCommand', i, k)
461 if ctype != "printindex*" and ctype != "printsubindex*":
465 del document.body[i:k + 1]
467 subst = put_cmd_in_ert("\\" + ctype + "{}")
468 document.body[i:k + 1] = subst
472 def revert_strikeout(document):
473 " Reverts \\strikeout font attribute "
474 changed = revert_font_attrs(document, "\\uuline", "\\uuline")
475 changed = revert_font_attrs(document, "\\uwave", "\\uwave") or changed
476 changed = revert_font_attrs(document, "\\strikeout", "\\sout") or changed
478 insert_to_preamble(0, document,
479 '% Commands inserted by lyx2lyx for proper underlining\n'
480 + '\\PassOptionsToPackage{normalem}{ulem}\n'
481 + '\\usepackage{ulem}\n')
484 def revert_ulinelatex(document):
485 " Reverts \\uline font attribute "
486 i = find_token(document.body, '\\bar under', 0)
489 insert_to_preamble(0, document,
490 '% Commands inserted by lyx2lyx for proper underlining\n'
491 + '\\PassOptionsToPackage{normalem}{ulem}\n'
492 + '\\usepackage{ulem}\n'
493 + '\\let\\cite@rig\\cite\n'
494 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
495 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
496 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
499 def revert_custom_processors(document):
500 " Remove bibtex_command and index_command params "
501 i = find_token(document.header, '\\bibtex_command', 0)
503 document.warning("Malformed LyX document: Missing \\bibtex_command.")
505 del document.header[i]
506 i = find_token(document.header, '\\index_command', 0)
508 document.warning("Malformed LyX document: Missing \\index_command.")
510 del document.header[i]
513 def convert_nomencl_width(document):
514 " Add set_width param to nomencl_print "
517 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
520 document.body.insert(i + 2, "set_width \"none\"")
524 def revert_nomencl_width(document):
525 " Remove set_width param from nomencl_print "
528 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
531 j = find_end_of_inset(document.body, i)
532 l = find_token(document.body, "set_width", i, j)
534 document.warning("Can't find set_width option for nomencl_print!")
541 def revert_nomencl_cwidth(document):
542 " Remove width param from nomencl_print "
545 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
548 j = find_end_of_inset(document.body, i)
549 l = find_token(document.body, "width", i, j)
551 document.warning("Can't find width option for nomencl_print!")
554 width = get_value(document.body, "width", i, j).strip('"')
556 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
557 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
561 def revert_applemac(document):
562 " Revert applemac encoding to auto "
563 if document.encoding != "applemac":
565 document.encoding = "auto"
566 i = find_token(document.header, "\\encoding", 0)
568 document.header[i] = "\\encoding auto"
571 def revert_longtable_align(document):
572 " Remove longtable alignment setting "
575 i = find_token(document.body, "\\begin_inset Tabular", i)
578 end = find_end_of_inset(document.body, i)
580 document.warning("Can't find end of inset at line " + str(i))
583 fline = find_token(document.body, "<features", i, end)
585 document.warning("Can't find features for inset at line " + str(i))
588 j = document.body[fline].find("longtabularalignment")
592 # FIXME Is this correct? It wipes out everything after the
594 document.body[fline] = document.body[fline][:j - 1] + '>'
595 # since there could be a tabular inside this one, we
596 # cannot jump to end.
600 def revert_branch_filename(document):
601 " Remove \\filename_suffix parameter from branches "
604 i = find_token(document.header, "\\filename_suffix", i)
607 del document.header[i]
610 def revert_paragraph_indentation(document):
611 " Revert custom paragraph indentation to preamble code "
612 i = find_token(document.header, "\\paragraph_indentation", 0)
615 length = get_value(document.header, "\\paragraph_indentation", i)
616 # we need only remove the line if indentation is default
617 if length != "default":
618 # handle percent lengths
619 length = latex_length(length)[1]
620 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
621 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
622 del document.header[i]
625 def revert_percent_skip_lengths(document):
626 " Revert relative lengths for paragraph skip separation to preamble code "
627 i = find_token(document.header, "\\defskip", 0)
630 length = get_value(document.header, "\\defskip", i)
631 # only revert when a custom length was set and when
632 # it used a percent length
633 if length in ('smallskip', 'medskip', 'bigskip'):
635 # handle percent lengths
636 percent, length = latex_length(length)
638 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
639 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
640 # set defskip to medskip as default
641 document.header[i] = "\\defskip medskip"
644 def revert_percent_vspace_lengths(document):
645 " Revert relative VSpace lengths to ERT "
648 i = find_token(document.body, "\\begin_inset VSpace", i)
651 # only revert if a custom length was set and if
652 # it used a percent length
653 r = re.compile(r'\\begin_inset VSpace (.*)$')
654 m = r.match(document.body[i])
656 if length in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
659 # check if the space has a star (protected space)
660 protected = (document.body[i].rfind("*") != -1)
662 length = length.rstrip('*')
663 # handle percent lengths
664 percent, length = latex_length(length)
665 # revert the VSpace inset to ERT
668 subst = put_cmd_in_ert("\\vspace*{" + length + "}")
670 subst = put_cmd_in_ert("\\vspace{" + length + "}")
671 document.body[i:i + 2] = subst
675 def revert_percent_hspace_lengths(document):
676 " Revert relative HSpace lengths to ERT "
679 i = find_token(document.body, "\\begin_inset space \\hspace", i)
682 j = find_end_of_inset(document.body, i)
684 document.warning("Can't find end of inset at line " + str(i))
687 # only revert if a custom length was set...
688 length = get_value(document.body, '\\length', i + 1, j)
690 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
694 if document.body[i].find("\\hspace*{}") != -1:
696 # ...and if it used a percent length
697 percent, length = latex_length(length)
698 # revert the HSpace inset to ERT
700 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
701 document.body[i:j + 1] = subst
702 # if we did a substitution, this will still be ok
706 def revert_hspace_glue_lengths(document):
707 " Revert HSpace glue lengths to ERT "
710 i = find_token(document.body, "\\begin_inset space \\hspace", i)
713 j = find_end_of_inset(document.body, i)
715 document.warning("Can't find end of inset at line " + str(i))
718 length = get_value(document.body, '\\length', i + 1, j)
720 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
724 if document.body[i].find("\\hspace*{}") != -1:
726 # only revert if the length contains a plus or minus at pos != 0
727 if length.find('-',1) != -1 or length.find('+',1) != -1:
728 # handle percent lengths
729 length = latex_length(length)[1]
730 # revert the HSpace inset to ERT
731 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
732 document.body[i:j+1] = subst
736 def convert_author_id(document):
737 " Add the author_id to the \\author definition and make sure 0 is not used"
740 re_author = re.compile(r'(\\author) (\".*\")\s*(.*)$')
743 i = find_token(document.header, "\\author", i)
746 m = re_author.match(document.header[i])
750 document.header[i] = "\\author %i %s %s" % (anum, name, email)
751 # FIXME Should this really be incremented if we didn't match?
757 i = find_token(document.body, "\\change_", i)
760 change = document.body[i].split(' ');
763 author_id = int(change[1])
765 document.body[i] = "%s %i %s" % (type, author_id + 1, time)
769 def revert_author_id(document):
770 " Remove the author_id from the \\author definition "
773 rx = re.compile(r'(\\author)\s+(\d+)\s+(\".*\")\s*(.*)$')
777 i = find_token(document.header, "\\author", i)
780 m = rx.match(document.header[i])
782 author_id = int(m.group(2))
783 idmap[author_id] = anum
786 document.header[i] = "\\author %s %s" % (name, email)
788 # FIXME Should this be incremented if we didn't match?
793 i = find_token(document.body, "\\change_", i)
796 change = document.body[i].split(' ');
799 author_id = int(change[1])
801 document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
805 def revert_suppress_date(document):
806 " Revert suppressing of default document date to preamble code "
807 i = find_token(document.header, "\\suppress_date", 0)
810 # remove the preamble line and write to the preamble
811 # when suppress_date was true
812 date = get_value(document.header, "\\suppress_date", i)
814 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
815 add_to_preamble(document, ["\\date{}"])
816 del document.header[i]
819 def revert_mhchem(document):
820 "Revert mhchem loading to preamble code"
823 i = find_token(document.header, "\\use_mhchem", 0)
825 document.warning("Malformed LyX document: Could not find mhchem setting.")
828 val = get_value(document.header, "\\use_mhchem", i)
833 del document.header[i]
838 i = find_token(document.body, "\\begin_inset Formula", i)
841 line = document.body[i]
842 if line.find("\\ce{") != -1 or line.find("\\cf{") != 1:
848 pre = ["% lyx2lyx mhchem commands",
849 "\\PassOptionsToPackage{version=3}{mhchem}",
850 "\\usepackage{mhchem}"]
851 add_to_preamble(document, pre)
854 def revert_fontenc(document):
855 " Remove fontencoding param "
856 i = find_token(document.header, '\\fontencoding', 0)
858 document.warning("Malformed LyX document: Missing \\fontencoding.")
860 del document.header[i]
863 def merge_gbrief(document):
864 " Merge g-brief-en and g-brief-de to one class "
866 if document.textclass != "g-brief-de":
867 if document.textclass == "g-brief-en":
868 document.textclass = "g-brief"
869 document.set_textclass()
872 obsoletedby = { "Brieftext": "Letter",
873 "Unterschrift": "Signature",
875 "Zusatz": "Addition",
878 "RetourAdresse": "ReturnAddress",
879 "MeinZeichen": "MyRef",
880 "IhrZeichen": "YourRef",
881 "IhrSchreiben": "YourMail",
884 "Konto": "BankAccount",
885 "Postvermerk": "PostalComment",
886 "Adresse": "Address",
888 "Betreff": "Reference",
895 i = find_token(document.body, "\\begin_layout", i)
899 layout = document.body[i][14:]
900 if layout in obsoletedby:
901 document.body[i] = "\\begin_layout " + obsoletedby[layout]
905 document.textclass = "g-brief"
906 document.set_textclass()
909 def revert_gbrief(document):
910 " Revert g-brief to g-brief-en "
911 if document.textclass == "g-brief":
912 document.textclass = "g-brief-en"
913 document.set_textclass()
916 def revert_html_options(document):
917 " Remove html options "
918 i = find_token(document.header, '\\html_use_mathml', 0)
920 del document.header[i]
921 i = find_token(document.header, '\\html_be_strict', 0)
923 del document.header[i]
926 def revert_includeonly(document):
929 i = find_token(document.header, "\\begin_includeonly", i)
932 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
934 document.warning("Unable to find end of includeonly section!!")
936 document.header[i : j + 1] = []
939 def revert_includeall(document):
940 " Remove maintain_unincluded_children param "
941 i = find_token(document.header, '\\maintain_unincluded_children', 0)
943 del document.header[i]
946 def revert_multirow(document):
947 " Revert multirow cells in tables to TeX-code"
951 # cell type 3 is multirow begin cell
952 i = find_token(document.body, '<cell multirow="3"', i)
955 # a multirow cell was found
957 # remove the multirow tag, set the valignment to top
958 # and remove the bottom line
959 # FIXME Are we sure these always have space around them?
960 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
961 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
962 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
963 # write ERT to create the multirow cell
964 # use 2 rows and 2cm as default with because the multirow span
965 # and the column width is only hardly accessible
966 cend = find_token(document.body, "</cell>", i)
968 document.warning("Malformed LyX document: Could not find end of tabular cell.")
971 blay = find_token(document.body, "\\begin_layout", i, cend)
973 document.warning("Can't find layout for cell!")
976 bend = find_end_of_layout(document.body, blay)
978 document.warning("Can't find end of layout for cell!")
982 # do the later one first, so as not to mess up the numbering
983 # we are wrapping the whole cell in this ert
984 # so before the end of the layout...
985 document.body[bend:bend] = put_cmd_in_ert("}")
986 # ...and after the beginning
987 document.body[blay+1:blay+1] = put_cmd_in_ert("\\multirow{2}{2cm}{")
990 # cell type 4 is multirow part cell
991 k = find_token(document.body, '<cell multirow="4"', cend)
994 # remove the multirow tag, set the valignment to top
995 # and remove the top line
996 # FIXME Are we sure these always have space around them?
997 document.body[k] = document.body[k].replace(' multirow="4" ', ' ')
998 document.body[k] = document.body[k].replace('valignment="middle"', 'valignment="top"')
999 document.body[k] = document.body[k].replace(' topline="true" ', ' ')
1001 # this will always be ok
1004 if multirow == True:
1005 add_to_preamble(document,
1006 ["% lyx2lyx multirow additions ", "\\usepackage{multirow}"])
1009 def convert_math_output(document):
1010 " Convert \html_use_mathml to \html_math_output "
1011 i = find_token(document.header, "\\html_use_mathml", 0)
1014 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1015 m = rgx.match(document.header[i])
1016 newval = "0" # MathML
1020 newval = "2" # Images
1022 document.warning("Can't match " + document.header[i])
1023 document.header[i] = "\\html_math_output " + newval
1026 def revert_math_output(document):
1027 " Revert \html_math_output to \html_use_mathml "
1028 i = find_token(document.header, "\\html_math_output", 0)
1031 rgx = re.compile(r'\\html_math_output\s+(\d)')
1032 m = rgx.match(document.header[i])
1036 if val == "1" or val == "2":
1039 document.warning("Unable to match " + document.header[i])
1040 document.header[i] = "\\html_use_mathml " + newval
1044 def revert_inset_preview(document):
1045 " Dissolves the preview inset "
1048 i = find_token(document.body, "\\begin_inset Preview", i)
1051 iend = find_end_of_inset(document.body, i)
1053 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1057 # This has several issues.
1058 # We need to do something about the layouts inside InsetPreview.
1059 # If we just leave the first one, then we have something like:
1060 # \begin_layout Standard
1062 # \begin_layout Standard
1063 # and we get a "no \end_layout" error. So something has to be done.
1064 # Ideally, we would check if it is the same as the layout we are in.
1065 # If so, we just remove it; if not, we end the active one. But it is
1066 # not easy to know what layout we are in, due to depth changes, etc,
1067 # and it is not clear to me how much work it is worth doing. In most
1068 # cases, the layout will probably be the same.
1070 # For the same reason, we have to remove the \end_layout tag at the
1071 # end of the last layout in the inset. Again, that will sometimes be
1072 # wrong, but it will usually be right. To know what to do, we would
1073 # again have to know what layout the inset is in.
1075 blay = find_token(document.body, "\\begin_layout", i, iend)
1077 document.warning("Can't find layout for preview inset!")
1078 # always do the later one first...
1079 del document.body[iend]
1080 del document.body[i]
1081 # deletions mean we do not need to reset i
1084 # This is where we would check what layout we are in.
1085 # The check for Standard is definitely wrong.
1087 # lay = document.body[blay].split(None, 1)[1]
1088 # if lay != oldlayout:
1089 # # record a boolean to tell us what to do later....
1090 # # better to do it later, since (a) it won't mess up
1091 # # the numbering and (b) we only modify at the end.
1093 # we want to delete the last \\end_layout in this inset, too.
1094 # note that this may not be the \\end_layout that goes with blay!!
1095 bend = find_end_of_layout(document.body, blay)
1097 tmp = find_token(document.body, "\\end_layout", bend + 1, iend)
1102 document.warning("Unable to find last layout in preview inset!")
1103 del document.body[iend]
1104 del document.body[i]
1105 # deletions mean we do not need to reset i
1107 # always do the later one first...
1108 del document.body[iend]
1109 del document.body[bend]
1110 del document.body[i:blay + 1]
1111 # we do not need to reset i
1114 def revert_equalspacing_xymatrix(document):
1115 " Revert a Formula with xymatrix@! to an ERT inset "
1117 has_preamble = False
1118 has_equal_spacing = False
1121 i = find_token(document.body, "\\begin_inset Formula", i)
1124 j = find_end_of_inset(document.body, i)
1126 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1130 for curline in range(i,j):
1131 found = document.body[curline].find("\\xymatrix@!")
1136 has_equal_spacing = True
1137 content = [document.body[i][21:]]
1138 content += document.body[i + 1:j]
1139 subst = put_cmd_in_ert(content)
1140 document.body[i:j + 1] = subst
1141 i += len(subst) - (j - i) + 1
1143 for curline in range(i,j):
1144 l = document.body[curline].find("\\xymatrix")
1146 has_preamble = True;
1150 if has_equal_spacing and not has_preamble:
1151 add_to_preamble(document, ['% lyx2lyx xymatrix addition', '\\usepackage[all]{xy}'])
1154 def revert_notefontcolor(document):
1155 " Reverts greyed-out note font color to preamble code "
1157 i = find_token(document.header, "\\notefontcolor", 0)
1161 # are there any grey notes?
1162 if find_token(document.body, "\\begin_inset Note Greyedout", 0) == -1:
1163 # no need to do anything, and \renewcommand will throw an error
1164 # since lyxgreyedout will not exist.
1167 colorcode = get_value(document.header, '\\notefontcolor', i)
1168 del document.header[i]
1169 # the color code is in the form #rrggbb where every character denotes a hex number
1170 red = hex2ratio(colorcode[1:3])
1171 green = hex2ratio(colorcode[3:5])
1172 blue = hex2ratio(colorcode[5:7])
1173 # write the preamble
1174 insert_to_preamble(0, document,
1175 ['% Commands inserted by lyx2lyx to set the font color',
1176 '% for greyed-out notes',
1177 '\\@ifundefined{definecolor}{\\usepackage{color}}{}'
1178 '\\definecolor{note_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1179 '\\renewenvironment{lyxgreyedout}',
1180 ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}'])
1183 def revert_turkmen(document):
1184 "Set language Turkmen to English"
1186 if document.language == "turkmen":
1187 document.language = "english"
1188 i = find_token(document.header, "\\language", 0)
1190 document.header[i] = "\\language english"
1194 j = find_token(document.body, "\\lang turkmen", j)
1197 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1201 def revert_fontcolor(document):
1202 " Reverts font color to preamble code "
1203 i = find_token(document.header, "\\fontcolor", 0)
1206 colorcode = get_value(document.header, '\\fontcolor', i)
1207 del document.header[i]
1208 # don't clutter the preamble if font color is not set
1209 if colorcode == "#000000":
1211 # the color code is in the form #rrggbb where every character denotes a hex number
1212 red = hex2ratio(colorcode[1:3])
1213 green = hex2ratio(colorcode[3:5])
1214 blue = hex2ratio(colorcode[5:7])
1215 # write the preamble
1216 insert_to_preamble(0, document,
1217 ['% Commands inserted by lyx2lyx to set the font color',
1218 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1219 '\\definecolor{document_fontcolor}{rgb}{%s,%s,%s}' % (red, green, blue),
1220 '\\color{document_fontcolor}'])
1223 def revert_shadedboxcolor(document):
1224 " Reverts shaded box color to preamble code "
1225 i = find_token(document.header, "\\boxbgcolor", 0)
1228 colorcode = get_value(document.header, '\\boxbgcolor', i)
1229 del document.header[i]
1230 # the color code is in the form #rrggbb
1231 red = hex2ratio(colorcode[1:3])
1232 green = hex2ratio(colorcode[3:5])
1233 blue = hex2ratio(colorcode[5:7])
1234 # write the preamble
1235 insert_to_preamble(0, document,
1236 ['% Commands inserted by lyx2lyx to set the color of boxes with shaded background',
1237 '\\@ifundefined{definecolor}{\\usepackage{color}}{}',
1238 "\\definecolor{shadecolor}{rgb}{%s,%s,%s}" % (red, green, blue)])
1241 def revert_lyx_version(document):
1242 " Reverts LyX Version information from Inset Info "
1243 version = "LyX version"
1245 import lyx2lyx_version
1246 version = lyx2lyx_version.version
1252 i = find_token(document.body, '\\begin_inset Info', i)
1255 j = find_end_of_inset(document.body, i + 1)
1257 document.warning("Malformed LyX document: Could not find end of Info inset.")
1266 # but we shall try to be forgiving.
1268 for k in range(i, j):
1269 if document.body[k].startswith("arg"):
1270 arg = document.body[k][3:].strip().strip('"')
1271 if document.body[k].startswith("type"):
1272 typ = document.body[k][4:].strip().strip('"')
1273 if arg != "version" or typ != "lyxinfo":
1277 # We do not actually know the version of LyX used to produce the document.
1278 # But we can use our version, since we are reverting.
1280 # Now we want to check if the line after "\end_inset" is empty. It normally
1281 # is, so we want to remove it, too.
1283 if document.body[j + 1].strip() == "":
1285 document.body[i: lastline] = s
1289 def revert_math_scale(document):
1290 " Remove math scaling and LaTeX options "
1291 i = find_token(document.header, '\\html_math_img_scale', 0)
1293 del document.header[i]
1294 i = find_token(document.header, '\\html_latex_start', 0)
1296 del document.header[i]
1297 i = find_token(document.header, '\\html_latex_end', 0)
1299 del document.header[i]
1302 def revert_pagesizes(document):
1303 " Revert page sizes to default "
1304 i = find_token(document.header, '\\papersize', 0)
1306 size = document.header[i][11:]
1307 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1308 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1309 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1310 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1311 or size == "b5j" or size == "b6j":
1312 del document.header[i]
1315 def revert_DIN_C_pagesizes(document):
1316 " Revert DIN C page sizes to default "
1317 i = find_token(document.header, '\\papersize', 0)
1319 size = document.header[i][11:]
1320 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1321 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1322 or size == "c6paper":
1323 del document.header[i]
1326 def convert_html_quotes(document):
1327 " Remove quotes around html_latex_start and html_latex_end "
1329 i = find_token(document.header, '\\html_latex_start', 0)
1331 line = document.header[i]
1332 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1335 document.header[i] = "\\html_latex_start " + m.group(1)
1337 i = find_token(document.header, '\\html_latex_end', 0)
1339 line = document.header[i]
1340 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1343 document.header[i] = "\\html_latex_end " + m.group(1)
1346 def revert_html_quotes(document):
1347 " Remove quotes around html_latex_start and html_latex_end "
1349 i = find_token(document.header, '\\html_latex_start', 0)
1351 line = document.header[i]
1352 l = re.compile(r'\\html_latex_start\s+(.*)')
1355 document.warning("Weird html_latex_start line: " + line)
1356 del document.header[i]
1358 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1360 i = find_token(document.header, '\\html_latex_end', 0)
1362 line = document.header[i]
1363 l = re.compile(r'\\html_latex_end\s+(.*)')
1366 document.warning("Weird html_latex_end line: " + line)
1367 del document.header[i]
1369 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1372 def revert_output_sync(document):
1373 " Remove forward search options "
1374 i = find_token(document.header, '\\output_sync_macro', 0)
1376 del document.header[i]
1377 i = find_token(document.header, '\\output_sync', 0)
1379 del document.header[i]
1382 # FIXME This doesn't do anything!!
1383 def revert_align_decimal(document):
1386 l = document.body[l].find('alignment=decimal')
1389 remove_option(document, l, 'decimal_point')
1390 document.body[l].replace('decimal', 'center')
1393 def convert_optarg(document):
1394 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1397 i = find_token(document.body, '\\begin_inset OptArg', i)
1400 document.body[i] = "\\begin_inset Argument"
1404 def revert_argument(document):
1405 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1408 i = find_token(document.body, '\\begin_inset Argument', i)
1411 document.body[i] = "\\begin_inset OptArg"
1415 def revert_makebox(document):
1416 " Convert \\makebox to TeX code "
1419 # only revert frameless boxes without an inner box
1420 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1423 z = find_end_of_inset(document.body, i)
1425 document.warning("Malformed LyX document: Can't find end of box inset.")
1428 blay = find_token(document.body, "\\begin_layout", i, z)
1430 document.warning("Malformed LyX document: Can't find layout in box.")
1433 # by looking before the layout we make sure we're actually finding
1434 # an option, not text.
1435 j = find_token(document.body, 'use_makebox', i, blay)
1439 val = get_value(document.body, 'use_makebox', j)
1441 del document.body[j]
1444 bend = find_end_of_layout(document.body, blay)
1445 if bend == -1 or bend > z:
1446 document.warning("Malformed LyX document: Can't find end of layout in box.")
1449 # determine the alignment
1450 align = get_value(document.body, 'hor_pos', i, blay, "c").strip('"')
1451 # determine the width
1452 length = get_value(document.body, 'width', i, blay, "50col%").strip('"')
1453 length = latex_length(length)[1]
1454 # remove the \end_layout \end_inset pair
1455 document.body[bend:z + 1] = put_cmd_in_ert("}")
1456 subst = "\\makebox[" + length + "][" \
1458 document.body[i:blay + 1] = put_cmd_in_ert(subst)
1462 def convert_use_makebox(document):
1463 " Adds use_makebox option for boxes "
1466 i = find_token(document.body, '\\begin_inset Box', i)
1469 # all of this is to make sure we actually find the use_parbox
1470 # that is an option for this box, not some text elsewhere.
1471 z = find_end_of_inset(document.body, i)
1473 document.warning("Can't find end of box inset!!")
1476 blay = find_token(document.body, "\\begin_layout", i, z)
1478 document.warning("Can't find layout in box inset!!")
1481 # so now we are looking for use_parbox before the box's layout
1482 k = find_token(document.body, 'use_parbox', i, blay)
1484 document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1487 document.body.insert(k + 1, "use_makebox 0")
1491 def revert_IEEEtran(document):
1492 " Convert IEEEtran layouts and styles to TeX code "
1493 if document.textclass != "IEEEtran":
1495 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1496 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1497 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1498 "Page headings", "Biography without photo")
1499 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1500 "After Title Text": "\\IEEEaftertitletext",
1501 "Publication ID": "\\IEEEpubid"}
1502 obsoletedby = {"Page headings": "MarkBoth",
1503 "Biography without photo": "BiographyNoPhoto"}
1504 for layout in layouts:
1507 i = find_token(document.body, '\\begin_layout ' + layout, i)
1510 j = find_end_of_layout(document.body, i)
1512 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1515 if layout in obsoletedby:
1516 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1519 content = lyx2latex(document, document.body[i:j + 1])
1520 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1521 del document.body[i:j + 1]
1522 # no need to reset i
1525 def convert_prettyref(document):
1526 " Converts prettyref references to neutral formatted refs "
1527 re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1528 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1532 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1535 j = find_end_of_inset(document.body, i)
1537 document.warning("Malformed LyX document: No end of InsetRef!")
1540 k = find_token(document.body, "LatexCommand prettyref", i, j)
1542 document.body[k] = "LatexCommand formatted"
1544 document.header.insert(-1, "\\use_refstyle 0")
1547 def revert_refstyle(document):
1548 " Reverts neutral formatted refs to prettyref "
1549 re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1550 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1554 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1557 j = find_end_of_inset(document.body, i)
1559 document.warning("Malformed LyX document: No end of InsetRef")
1562 k = find_token(document.body, "LatexCommand formatted", i, j)
1564 document.body[k] = "LatexCommand prettyref"
1566 i = find_token(document.header, "\\use_refstyle", 0)
1568 document.header.pop(i)
1571 def revert_nameref(document):
1572 " Convert namerefs to regular references "
1573 cmds = ["Nameref", "nameref"]
1575 rx = re.compile(r'reference "(.*)"')
1578 oldcmd = "LatexCommand " + cmd
1580 # It seems better to look for this, as most of the reference
1581 # insets won't be ones we care about.
1582 i = find_token(document.body, oldcmd, i)
1587 # Make sure it is actually in an inset!
1588 # We could just check document.lines[i-1], but that relies
1589 # upon something that might easily change.
1590 # We'll look back a few lines.
1594 stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
1595 if stins == -1 or stins > cmdloc:
1597 endins = find_end_of_inset(document.body, stins)
1599 document.warning("Can't find end of inset at line " + stins + "!!")
1603 refline = find_token(document.body, "reference", stins)
1604 if refline == -1 or refline > endins:
1605 document.warning("Can't find reference for inset at line " + stinst + "!!")
1607 m = rx.match(document.body[refline])
1609 document.warning("Can't match reference line: " + document.body[ref])
1613 newcontent = ['\\begin_inset ERT', 'status collapsed', '', \
1614 '\\begin_layout Plain Layout', '', '\\backslash', \
1615 cmd + '{' + ref + '}', '\\end_layout', '', '\\end_inset']
1616 document.body[stins:endins + 1] = newcontent
1618 add_to_preamble(document, "\usepackage{nameref}")
1621 def remove_Nameref(document):
1622 " Convert Nameref commands to nameref commands "
1625 # It seems better to look for this, as most of the reference
1626 # insets won't be ones we care about.
1627 i = find_token(document.body, "LatexCommand Nameref" , i)
1633 # Make sure it is actually in an inset!
1634 # We could just check document.lines[i-1], but that relies
1635 # upon something that might easily change.
1636 # We'll look back a few lines.
1640 stins = find_token(document.body, "\\begin_inset CommandInset ref", stins)
1641 if stins == -1 or stins > cmdloc:
1643 endins = find_end_of_inset(document.body, stins)
1645 document.warning("Can't find end of inset at line " + stins + "!!")
1649 document.body[cmdloc] = "LatexCommand nameref"
1652 def revert_mathrsfs(document):
1653 " Load mathrsfs if \mathrsfs us use in the document "
1655 end = len(document.body) - 1
1657 j = document.body[i].find("\\mathscr{")
1659 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1660 add_to_preamble(document, ["\\usepackage{mathrsfs}"])
1667 def convert_flexnames(document):
1668 "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1671 rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1673 i = find_token(document.body, "\\begin_inset Flex", i)
1676 m = rx.match(document.body[i])
1678 document.body[i] = "\\begin_inset Flex " + m.group(1)
1683 ["Alert", "CharStyle:Alert"],
1684 ["Code", "CharStyle:Code"],
1685 ["Concepts", "CharStyle:Concepts"],
1686 ["E-Mail", "CharStyle:E-Mail"],
1687 ["Emph", "CharStyle:Emph"],
1688 ["Expression", "CharStyle:Expression"],
1689 ["Initial", "CharStyle:Initial"],
1690 ["Institute", "CharStyle:Institute"],
1691 ["Meaning", "CharStyle:Meaning"],
1692 ["Noun", "CharStyle:Noun"],
1693 ["Strong", "CharStyle:Strong"],
1694 ["Structure", "CharStyle:Structure"],
1695 ["ArticleMode", "Custom:ArticleMode"],
1696 ["Endnote", "Custom:Endnote"],
1697 ["Glosse", "Custom:Glosse"],
1698 ["PresentationMode", "Custom:PresentationMode"],
1699 ["Tri-Glosse", "Custom:Tri-Glosse"]
1703 ["Abbrev", "Element:Abbrev"],
1704 ["CCC-Code", "Element:CCC-Code"],
1705 ["Citation-number", "Element:Citation-number"],
1706 ["City", "Element:City"],
1707 ["Code", "Element:Code"],
1708 ["CODEN", "Element:CODEN"],
1709 ["Country", "Element:Country"],
1710 ["Day", "Element:Day"],
1711 ["Directory", "Element:Directory"],
1712 ["Dscr", "Element:Dscr"],
1713 ["Email", "Element:Email"],
1714 ["Emph", "Element:Emph"],
1715 ["Filename", "Element:Filename"],
1716 ["Firstname", "Element:Firstname"],
1717 ["Fname", "Element:Fname"],
1718 ["GuiButton", "Element:GuiButton"],
1719 ["GuiMenu", "Element:GuiMenu"],
1720 ["GuiMenuItem", "Element:GuiMenuItem"],
1721 ["ISSN", "Element:ISSN"],
1722 ["Issue-day", "Element:Issue-day"],
1723 ["Issue-months", "Element:Issue-months"],
1724 ["Issue-number", "Element:Issue-number"],
1725 ["KeyCap", "Element:KeyCap"],
1726 ["KeyCombo", "Element:KeyCombo"],
1727 ["Keyword", "Element:Keyword"],
1728 ["Literal", "Element:Literal"],
1729 ["MenuChoice", "Element:MenuChoice"],
1730 ["Month", "Element:Month"],
1731 ["Orgdiv", "Element:Orgdiv"],
1732 ["Orgname", "Element:Orgname"],
1733 ["Postcode", "Element:Postcode"],
1734 ["SS-Code", "Element:SS-Code"],
1735 ["SS-Title", "Element:SS-Title"],
1736 ["State", "Element:State"],
1737 ["Street", "Element:Street"],
1738 ["Surname", "Element:Surname"],
1739 ["Volume", "Element:Volume"],
1740 ["Year", "Element:Year"]
1744 def revert_flexnames(document):
1745 if document.backend == "latex":
1746 flexlist = flex_insets
1748 flexlist = flex_elements
1750 rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1753 i = find_token(document.body, "\\begin_inset Flex", i)
1756 m = rx.match(document.body[i])
1758 document.warning("Illegal flex inset: " + document.body[i])
1765 document.body[i] = "\\begin_inset Flex " + f[1]
1771 def convert_mathdots(document):
1772 " Load mathdots automatically "
1774 i = find_token(document.header, "\\use_esint" , 0)
1776 document.header.insert(i + 1, "\\use_mathdots 1")
1780 def revert_mathdots(document):
1781 " Load mathdots if used in the document "
1783 ddots = re.compile(r'\\begin_inset Formula .*\\ddots', re.DOTALL)
1784 vdots = re.compile(r'\\begin_inset Formula .*\\vdots', re.DOTALL)
1785 iddots = re.compile(r'\\begin_inset Formula .*\\iddots', re.DOTALL)
1786 mathdots = find_token(document.header, "\\use_mathdots" , 0)
1787 no = find_token(document.header, "\\use_mathdots 0" , 0)
1788 auto = find_token(document.header, "\\use_mathdots 1" , 0)
1789 yes = find_token(document.header, "\\use_mathdots 2" , 0)
1791 del document.header[mathdots]
1793 i = find_token(document.body, '\\begin_inset Formula', i)
1796 j = find_end_of_inset(document.body, i)
1798 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1800 k = ddots.search("\n".join(document.body[i:j]))
1801 l = vdots.search("\n".join(document.body[i:j]))
1802 m = iddots.search("\n".join(document.body[i:j]))
1803 if (yes == -1) and ((no != -1) or (not k and not l and not m) or (auto != -1 and not m)):
1806 # use \@ifundefined to catch also the "auto" case
1807 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1808 add_to_preamble(document, ["\\@ifundefined{iddots}{\\usepackage{mathdots}}\n"])
1812 def convert_rule(document):
1813 " Convert \\lyxline to CommandInset line "
1816 i = find_token(document.body, "\\lyxline" , i)
1820 j = find_token(document.body, "\\color" , i - 2)
1822 color = document.body[j] + '\n'
1825 k = find_token(document.body, "\\begin_layout Standard" , i - 4)
1826 # we need to handle the case that \lyxline is in a separate paragraph and that it is colored
1827 # the result is then an extra empty paragraph which we get by adding an empty ERT inset
1828 if k == i - 4 and j == i - 2 and document.body[i - 1] == '':
1829 layout = '\\begin_inset ERT\nstatus collapsed\n\n\\begin_layout Plain Layout\n\n\n\\end_layout\n\n\\end_inset\n' \
1830 + '\\end_layout\n\n' \
1831 + '\\begin_layout Standard\n'
1832 elif k == i - 2 and document.body[i - 1] == '':
1835 layout = '\\end_layout\n\n' \
1836 + '\\begin_layout Standard\n'
1837 l = find_token(document.body, "\\begin_layout Standard" , i + 4)
1838 if l == i + 4 and document.body[i + 1] == '':
1841 layout2 = '\\end_layout\n' \
1842 + '\n\\begin_layout Standard\n'
1844 + '\\noindent\n\n' \
1846 + '\\begin_inset CommandInset line\n' \
1847 + 'LatexCommand rule\n' \
1848 + 'offset "0.5ex"\n' \
1849 + 'width "100line%"\n' \
1850 + 'height "1pt"\n' \
1851 + '\n\\end_inset\n\n\n' \
1853 document.body[i] = subst
1857 def revert_rule(document):
1858 " Revert line insets to Tex code "
1861 i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1865 j = find_token(document.body, "\\end_inset" , i)
1866 # assure we found the end_inset of the current inset
1867 if j > i + 6 or j == -1:
1868 document.warning("Malformed LyX document: Can't find end of line inset.")
1870 # determine the optional offset
1871 k = find_token(document.body, 'offset', i, j)
1873 offset = document.body[k][8:-1]
1876 # determine the width
1877 l = find_token(document.body, 'width', i, j)
1879 width = document.body[l][7:-1]
1882 # determine the height
1883 m = find_token(document.body, 'height', i, j)
1885 height = document.body[m][8:-1]
1888 # output the \rule command
1890 subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1892 subst = "\\rule{" + width + "}{" + height + "}"
1893 document.body[i:j + 1] = put_cmd_in_ert(subst)
1897 def revert_diagram(document):
1898 " Add the feyn package if \\Diagram is used in math "
1900 re_diagram = re.compile(r'\\begin_inset Formula .*\\Diagram', re.DOTALL)
1902 i = find_token(document.body, '\\begin_inset Formula', i)
1905 j = find_end_of_inset(document.body, i)
1907 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1909 m = re_diagram.search("\n".join(document.body[i:j]))
1913 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1914 add_to_preamble(document, "\\usepackage{feyn}")
1915 # only need to do it once!
1919 def convert_bibtex_clearpage(document):
1920 " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1922 i = find_token(document.header, '\\papersides', 0)
1924 document.warning("Malformed LyX document: Can't find papersides definition.")
1926 sides = int(document.header[i][12])
1930 j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
1934 k = find_end_of_inset(document.body, j)
1936 document.warning("Can't find end of Bibliography inset at line " + str(j))
1940 # only act if there is the option "bibtotoc"
1941 m = find_token(document.body, 'options', j, k)
1943 document.warning("Can't find options for bibliography inset at line " + str(j))
1947 optline = document.body[m]
1948 idx = optline.find("bibtotoc")
1953 # so we want to insert a new page right before the paragraph that
1954 # this bibliography thing is in. we'll look for it backwards.
1957 if document.body[lay].startswith("\\begin_layout"):
1962 document.warning("Can't find layout containing bibliography inset at line " + str(j))
1966 subst1 = '\\begin_layout Standard\n' \
1967 + '\\begin_inset Newpage clearpage\n' \
1968 + '\\end_inset\n\n\n' \
1970 subst2 = '\\begin_layout Standard\n' \
1971 + '\\begin_inset Newpage cleardoublepage\n' \
1972 + '\\end_inset\n\n\n' \
1975 document.body.insert(lay, subst1)
1976 document.warning(subst1)
1978 document.body.insert(lay, subst2)
1979 document.warning(subst2)
1988 supported_versions = ["2.0.0","2.0"]
1989 convert = [[346, []],
1995 [352, [convert_splitindex]],
2002 [359, [convert_nomencl_width]],
2012 [369, [convert_author_id]],
2016 [373, [merge_gbrief]],
2022 [379, [convert_math_output]],
2032 [389, [convert_html_quotes]],
2036 [393, [convert_optarg]],
2037 [394, [convert_use_makebox]],
2040 [397, [remove_Nameref]],
2042 [399, [convert_mathdots]],
2043 [400, [convert_rule]],
2045 [402, [convert_bibtex_clearpage]],
2046 [403, [convert_flexnames]],
2047 [404, [convert_prettyref]]
2050 revert = [[403, [revert_refstyle]],
2051 [402, [revert_flexnames]],
2053 [400, [revert_diagram]],
2054 [399, [revert_rule]],
2055 [398, [revert_mathdots]],
2056 [397, [revert_mathrsfs]],
2058 [395, [revert_nameref]],
2059 [394, [revert_DIN_C_pagesizes]],
2060 [393, [revert_makebox]],
2061 [392, [revert_argument]],
2063 [390, [revert_align_decimal, revert_IEEEtran]],
2064 [389, [revert_output_sync]],
2065 [388, [revert_html_quotes]],
2066 [387, [revert_pagesizes]],
2067 [386, [revert_math_scale]],
2068 [385, [revert_lyx_version]],
2069 [384, [revert_shadedboxcolor]],
2070 [383, [revert_fontcolor]],
2071 [382, [revert_turkmen]],
2072 [381, [revert_notefontcolor]],
2073 [380, [revert_equalspacing_xymatrix]],
2074 [379, [revert_inset_preview]],
2075 [378, [revert_math_output]],
2077 [376, [revert_multirow]],
2078 [375, [revert_includeall]],
2079 [374, [revert_includeonly]],
2080 [373, [revert_html_options]],
2081 [372, [revert_gbrief]],
2082 [371, [revert_fontenc]],
2083 [370, [revert_mhchem]],
2084 [369, [revert_suppress_date]],
2085 [368, [revert_author_id]],
2086 [367, [revert_hspace_glue_lengths]],
2087 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2088 [365, [revert_percent_skip_lengths]],
2089 [364, [revert_paragraph_indentation]],
2090 [363, [revert_branch_filename]],
2091 [362, [revert_longtable_align]],
2092 [361, [revert_applemac]],
2094 [359, [revert_nomencl_cwidth]],
2095 [358, [revert_nomencl_width]],
2096 [357, [revert_custom_processors]],
2097 [356, [revert_ulinelatex]],
2099 [354, [revert_strikeout]],
2100 [353, [revert_printindexall]],
2101 [352, [revert_subindex]],
2102 [351, [revert_splitindex]],
2103 [350, [revert_backgroundcolor]],
2104 [349, [revert_outputformat]],
2105 [348, [revert_xetex]],
2106 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2107 [346, [revert_tabularvalign]],
2108 [345, [revert_swiss]]
2112 if __name__ == "__main__":