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, find_token_backwards, \
28 is_in_inset, get_value, get_quoted_value, del_token
30 from lyx2lyx_tools import add_to_preamble, insert_to_preamble, \
31 put_cmd_in_ert, lyx2latex, latex_length, revert_flex_inset, \
32 revert_font_attrs, hex2ratio, str2bool
34 ####################################################################
35 # Private helper functions
37 def remove_option(lines, m, option):
38 ''' removes option from line m. returns whether we did anything '''
39 l = lines[m].find(option)
42 val = lines[m][l:].split('"')[1]
43 lines[m] = lines[m][:l - 1] + lines[m][l+len(option + '="' + val + '"'):]
47 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
48 # have been made of it with uses of put_cmd_in_ert.
49 def old_put_cmd_in_ert(string):
50 for rep in unicode_reps:
51 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
52 string = string.replace('\\', "\\backslash\n")
53 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
54 + string + "\n\\end_layout\n\\end_inset"
58 ###############################################################################
60 ### Conversion and reversion routines
62 ###############################################################################
64 def revert_swiss(document):
65 " Set language german-ch to ngerman "
67 if document.language == "german-ch":
68 document.language = "ngerman"
69 i = find_token(document.header, "\\language", 0)
71 document.header[i] = "\\language ngerman"
74 j = find_token(document.body, "\\lang german-ch", j)
77 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
81 def revert_tabularvalign(document):
82 " Revert the tabular valign option "
85 i = find_token(document.body, "\\begin_inset Tabular", i)
88 end = find_end_of_inset(document.body, i)
90 document.warning("Can't find end of inset at line " + str(i))
93 fline = find_token(document.body, "<features", i, end)
95 document.warning("Can't find features for inset at line " + str(i))
98 p = document.body[fline].find("islongtable")
100 q = document.body[fline].find("tabularvalignment")
103 # This seems wrong: It removes everything after
104 # tabularvalignment, too.
105 document.body[fline] = document.body[fline][:q - 1] + '>'
110 tabularvalignment = 'c'
111 # which valignment is specified?
112 m = document.body[fline].find('tabularvalignment="top"')
114 tabularvalignment = 't'
115 m = document.body[fline].find('tabularvalignment="bottom"')
117 tabularvalignment = 'b'
118 # delete tabularvalignment
119 q = document.body[fline].find("tabularvalignment")
122 # This seems wrong: It removes everything after
123 # tabularvalignment, too.
124 document.body[fline] = document.body[fline][:q - 1] + '>'
126 # don't add a box when centered
127 if tabularvalignment == 'c':
130 subst = ['\\end_layout', '\\end_inset']
131 document.body[end:end] = subst # just inserts those lines
132 subst = ['\\begin_inset Box Frameless',
133 'position "' + tabularvalignment +'"',
138 # we don't know the width, assume 50%
142 'height_special "totalheight"',
145 '\\begin_layout Plain Layout']
146 document.body[i:i] = subst # this just inserts the array at i
147 # since there could be a tabular inside a tabular, we cannot
152 def revert_phantom_types(document, ptype, cmd):
153 " Reverts phantom to ERT "
156 i = find_token(document.body, "\\begin_inset Phantom " + ptype, i)
159 end = find_end_of_inset(document.body, i)
161 document.warning("Can't find end of inset at line " + str(i))
164 blay = find_token(document.body, "\\begin_layout Plain Layout", i, end)
166 document.warning("Can't find layout for inset at line " + str(i))
169 bend = find_token(document.body, "\\end_layout", blay, end)
171 document.warning("Malformed LyX document: Could not find end of Phantom inset's layout.")
174 substi = ["\\begin_inset ERT", "status collapsed", "",
175 "\\begin_layout Plain Layout", "", "", "\\backslash",
176 cmd + "{", "\\end_layout", "", "\\end_inset"]
177 substj = ["\\size default", "", "\\begin_inset ERT", "status collapsed", "",
178 "\\begin_layout Plain Layout", "", "}", "\\end_layout", "", "\\end_inset"]
179 # do the later one first so as not to mess up the numbering
180 document.body[bend:end + 1] = substj
181 document.body[i:blay + 1] = substi
182 i = end + len(substi) + len(substj) - (end - bend) - (blay - i) - 2
185 def revert_phantom(document):
186 revert_phantom_types(document, "Phantom", "phantom")
188 def revert_hphantom(document):
189 revert_phantom_types(document, "HPhantom", "hphantom")
191 def revert_vphantom(document):
192 revert_phantom_types(document, "VPhantom", "vphantom")
195 def revert_xetex(document):
196 " Reverts documents that use XeTeX "
198 i = find_token(document.header, '\\use_xetex', 0)
200 document.warning("Malformed LyX document: Missing \\use_xetex.")
202 if not str2bool(get_value(document.header, "\\use_xetex", i)):
203 del document.header[i]
205 del document.header[i]
207 # 1.) set doc encoding to utf8-plain
208 i = find_token(document.header, "\\inputencoding", 0)
210 document.warning("Malformed LyX document: Missing \\inputencoding.")
212 document.header[i] = "\\inputencoding utf8-plain"
214 # 2.) check font settings
216 roman = sans = typew = default
218 sf_scale = tt_scale = 100.0
220 i = find_token(document.header, "\\font_roman", 0)
222 document.warning("Malformed LyX document: Missing \\font_roman.")
224 roman = get_value(document.header, "\\font_roman", i)
225 document.header[i] = "\\font_roman default"
227 i = find_token(document.header, "\\font_sans", 0)
229 document.warning("Malformed LyX document: Missing \\font_sans.")
231 sans = get_value(document.header, "\\font_sans", i)
232 document.header[i] = "\\font_sans default"
234 i = find_token(document.header, "\\font_typewriter", 0)
236 document.warning("Malformed LyX document: Missing \\font_typewriter.")
238 typew = get_value(document.header, "\\font_typewriter", i)
239 document.header[i] = "\\font_typewriter default"
241 i = find_token(document.header, "\\font_osf", 0)
243 document.warning("Malformed LyX document: Missing \\font_osf.")
245 osf = str2bool(get_value(document.header, "\\font_osf", i))
246 document.header[i] = "\\font_osf false"
248 i = find_token(document.header, "\\font_sc", 0)
250 document.warning("Malformed LyX document: Missing \\font_sc.")
252 # we do not need this value.
253 document.header[i] = "\\font_sc false"
255 i = find_token(document.header, "\\font_sf_scale", 0)
257 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
259 val = get_value(document.header, '\\font_sf_scale', i)
262 sf_scale = float(val)
264 document.warning("Invalid font_sf_scale value: " + val)
265 document.header[i] = "\\font_sf_scale 100"
267 i = find_token(document.header, "\\font_tt_scale", 0)
269 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
271 val = get_value(document.header, '\\font_tt_scale', i)
274 tt_scale = float(val)
276 document.warning("Invalid font_tt_scale value: " + val)
277 document.header[i] = "\\font_tt_scale 100"
279 # 3.) set preamble stuff
280 pretext = ['%% This document must be processed with xelatex!']
281 pretext.append('\\usepackage{fontspec}')
282 if roman != "default":
283 pretext.append('\\setmainfont[Mapping=tex-text]{' + roman + '}')
284 if sans != "default":
285 sf = '\\setsansfont['
286 if sf_scale != 100.0:
287 sf += 'Scale=' + str(sf_scale / 100.0) + ','
288 sf += 'Mapping=tex-text]{' + sans + '}'
290 if typewriter != "default":
292 if tt_scale != 100.0:
293 tw += '[Scale=' + str(tt_scale / 100.0) + ']'
294 tw += '{' + typewriter + '}'
297 pretext.append('\\defaultfontfeatures{Numbers=OldStyle}')
298 pretext.append('\usepackage{xunicode}')
299 pretext.append('\usepackage{xltxtra}')
300 insert_to_preamble(0, document, pretext)
303 def revert_outputformat(document):
304 " Remove default output format param "
306 if not del_token(document.header, '\\default_output_format', 0):
307 document.warning("Malformed LyX document: Missing \\default_output_format.")
310 def revert_backgroundcolor(document):
311 " Reverts background color to preamble code "
312 i = find_token(document.header, "\\backgroundcolor", 0)
315 colorcode = get_value(document.header, '\\backgroundcolor', i)
316 del document.header[i]
317 # don't clutter the preamble if backgroundcolor is not set
318 if colorcode == "#ffffff":
320 red = hex2ratio(colorcode[1:3])
321 green = hex2ratio(colorcode[3:5])
322 blue = hex2ratio(colorcode[5:7])
323 insert_to_preamble(0, document,
324 '% Commands inserted by lyx2lyx to set the background color\n'
325 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
326 + '\\definecolor{page_backgroundcolor}{rgb}{'
327 + red + ',' + green + ',' + blue + '}\n'
328 + '\\pagecolor{page_backgroundcolor}\n')
331 def revert_splitindex(document):
332 " Reverts splitindex-aware documents "
333 i = find_token(document.header, '\\use_indices', 0)
335 document.warning("Malformed LyX document: Missing \\use_indices.")
337 useindices = str2bool(get_value(document.header, "\\use_indices", i))
338 del document.header[i]
341 preamble.append("\\usepackage{splitidx})")
343 # deal with index declarations in the preamble
346 i = find_token(document.header, "\\index", i)
349 k = find_token(document.header, "\\end_index", i)
351 document.warning("Malformed LyX document: Missing \\end_index.")
354 line = document.header[i]
355 l = re.compile(r'\\index (.*)$')
358 ishortcut = get_value(document.header, '\\shortcut', i, k)
360 preamble.append("\\newindex[" + iname + "]{" + ishortcut + "}")
361 del document.header[i:k + 1]
363 insert_to_preamble(0, document, preamble)
365 # deal with index insets
366 # these need to have the argument removed
369 i = find_token(document.body, "\\begin_inset Index", i)
372 line = document.body[i]
373 l = re.compile(r'\\begin_inset Index (.*)$')
376 if itype == "idx" or indices == "false":
377 document.body[i] = "\\begin_inset Index"
379 k = find_end_of_inset(document.body, i)
381 document.warning("Can't find end of index inset!")
384 content = lyx2latex(document, document.body[i:k])
386 content = content.replace('"', r'\"')
387 subst = put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")
388 document.body[i:k + 1] = subst
391 # deal with index_print insets
394 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
397 k = find_end_of_inset(document.body, i)
398 ptype = get_quoted_value(document.body, 'type', i, k)
400 j = find_token(document.body, "type", i, k)
403 del document.body[i:k + 1]
405 subst = put_cmd_in_ert("\\printindex[" + ptype + "]{}")
406 document.body[i:k + 1] = subst
410 def convert_splitindex(document):
411 " Converts index and printindex insets to splitindex-aware format "
414 i = find_token(document.body, "\\begin_inset Index", i)
417 document.body[i] = document.body[i].replace("\\begin_inset Index",
418 "\\begin_inset Index idx")
422 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
425 if document.body[i + 1].find('LatexCommand printindex') == -1:
426 document.warning("Malformed LyX document: Incomplete printindex inset.")
428 subst = ["LatexCommand printindex",
430 document.body[i + 1:i + 2] = subst
434 def revert_subindex(document):
435 " Reverts \\printsubindex CommandInset types "
436 i = find_token(document.header, '\\use_indices', 0)
438 document.warning("Malformed LyX document: Missing \\use_indices.")
440 useindices = str2bool(get_value(document.header, "\\use_indices", i))
443 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
446 k = find_end_of_inset(document.body, i)
447 ctype = get_value(document.body, 'LatexCommand', i, k)
448 if ctype != "printsubindex":
451 ptype = get_quoted_value(document.body, 'type', i, k)
453 del document.body[i:k + 1]
455 subst = put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")
456 document.body[i:k + 1] = subst
460 def revert_printindexall(document):
461 " Reverts \\print[sub]index* CommandInset types "
462 i = find_token(document.header, '\\use_indices', 0)
464 document.warning("Malformed LyX document: Missing \\use_indices.")
466 useindices = str2bool(get_value(document.header, "\\use_indices", i))
469 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
472 k = find_end_of_inset(document.body, i)
473 ctype = get_value(document.body, 'LatexCommand', i, k)
474 if ctype != "printindex*" and ctype != "printsubindex*":
478 del document.body[i:k + 1]
480 subst = put_cmd_in_ert("\\" + ctype + "{}")
481 document.body[i:k + 1] = subst
485 def revert_strikeout(document):
486 " Reverts \\strikeout font attribute "
487 changed = revert_font_attrs(document.body, "\\uuline", "\\uuline")
488 changed = revert_font_attrs(document.body, "\\uwave", "\\uwave") or changed
489 changed = revert_font_attrs(document.body, "\\strikeout", "\\sout") or changed
491 insert_to_preamble(0, document,
492 '% Commands inserted by lyx2lyx for proper underlining\n'
493 + '\\PassOptionsToPackage{normalem}{ulem}\n'
494 + '\\usepackage{ulem}\n')
497 def revert_ulinelatex(document):
498 " Reverts \\uline font attribute "
499 i = find_token(document.body, '\\bar under', 0)
502 insert_to_preamble(0, document,
503 '% Commands inserted by lyx2lyx for proper underlining\n'
504 + '\\PassOptionsToPackage{normalem}{ulem}\n'
505 + '\\usepackage{ulem}\n'
506 + '\\let\\cite@rig\\cite\n'
507 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
508 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
509 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
512 def revert_custom_processors(document):
513 " Remove bibtex_command and index_command params "
515 if not del_token(document.header, '\\bibtex_command', 0):
516 document.warning("Malformed LyX document: Missing \\bibtex_command.")
518 if not del_token(document.header, '\\index_command', 0):
519 document.warning("Malformed LyX document: Missing \\index_command.")
522 def convert_nomencl_width(document):
523 " Add set_width param to nomencl_print "
526 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
529 document.body.insert(i + 2, "set_width \"none\"")
533 def revert_nomencl_width(document):
534 " Remove set_width param from nomencl_print "
537 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
540 j = find_end_of_inset(document.body, i)
541 if not del_token(document.body, "set_width", i, j):
542 document.warning("Can't find set_width option for nomencl_print!")
546 def revert_nomencl_cwidth(document):
547 " Remove width param from nomencl_print "
550 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
553 j = find_end_of_inset(document.body, i)
554 l = find_token(document.body, "width", i, j)
556 document.warning("Can't find width option for nomencl_print!")
559 width = get_quoted_value(document.body, "width", i, j)
561 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
562 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
566 def revert_applemac(document):
567 " Revert applemac encoding to auto "
568 if document.encoding != "applemac":
570 document.encoding = "auto"
571 i = find_token(document.header, "\\encoding", 0)
573 document.header[i] = "\\encoding auto"
576 def revert_longtable_align(document):
577 " Remove longtable alignment setting "
580 i = find_token(document.body, "\\begin_inset Tabular", i)
583 end = find_end_of_inset(document.body, i)
585 document.warning("Can't find end of inset at line " + str(i))
588 fline = find_token(document.body, "<features", i, end)
590 document.warning("Can't find features for inset at line " + str(i))
593 j = document.body[fline].find("longtabularalignment")
597 # FIXME Is this correct? It wipes out everything after the
599 document.body[fline] = document.body[fline][:j - 1] + '>'
600 # since there could be a tabular inside this one, we
601 # cannot jump to end.
605 def revert_branch_filename(document):
606 " Remove \\filename_suffix parameter from branches "
609 i = find_token(document.header, "\\filename_suffix", i)
612 del document.header[i]
615 def revert_paragraph_indentation(document):
616 " Revert custom paragraph indentation to preamble code "
617 i = find_token(document.header, "\\paragraph_indentation", 0)
620 length = get_value(document.header, "\\paragraph_indentation", i)
621 # we need only remove the line if indentation is default
622 if length != "default":
623 # handle percent lengths
624 length = latex_length(length)[1]
625 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
626 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
627 del document.header[i]
630 def revert_percent_skip_lengths(document):
631 " Revert relative lengths for paragraph skip separation to preamble code "
632 i = find_token(document.header, "\\defskip", 0)
635 length = get_value(document.header, "\\defskip", i)
636 # only revert when a custom length was set and when
637 # it used a percent length
638 if length in ('smallskip', 'medskip', 'bigskip'):
640 # handle percent lengths
641 percent, length = latex_length(length)
643 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
644 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
645 # set defskip to medskip as default
646 document.header[i] = "\\defskip medskip"
649 def revert_percent_vspace_lengths(document):
650 " Revert relative VSpace lengths to ERT "
653 i = find_token(document.body, "\\begin_inset VSpace", i)
656 # only revert if a custom length was set and if
657 # it used a percent length
658 r = re.compile(r'\\begin_inset VSpace (.*)$')
659 m = r.match(document.body[i])
661 if length in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
664 # check if the space has a star (protected space)
665 protected = (document.body[i].rfind("*") != -1)
667 length = length.rstrip('*')
668 # handle percent lengths
669 percent, length = latex_length(length)
670 # revert the VSpace inset to ERT
673 subst = put_cmd_in_ert("\\vspace*{" + length + "}")
675 subst = put_cmd_in_ert("\\vspace{" + length + "}")
676 document.body[i:i + 2] = subst
680 def revert_percent_hspace_lengths(document):
681 " Revert relative HSpace lengths to ERT "
684 i = find_token(document.body, "\\begin_inset space \\hspace", i)
687 j = find_end_of_inset(document.body, i)
689 document.warning("Can't find end of inset at line " + str(i))
692 # only revert if a custom length was set...
693 length = get_value(document.body, '\\length', i + 1, j)
695 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
699 if document.body[i].find("\\hspace*{}") != -1:
701 # ...and if it used a percent length
702 percent, length = latex_length(length)
703 # revert the HSpace inset to ERT
705 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
706 document.body[i:j + 1] = subst
707 # if we did a substitution, this will still be ok
711 def revert_hspace_glue_lengths(document):
712 " Revert HSpace glue lengths to ERT "
715 i = find_token(document.body, "\\begin_inset space \\hspace", i)
718 j = find_end_of_inset(document.body, i)
720 document.warning("Can't find end of inset at line " + str(i))
723 length = get_value(document.body, '\\length', i + 1, j)
725 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
729 if document.body[i].find("\\hspace*{}") != -1:
731 # only revert if the length contains a plus or minus at pos != 0
732 if length.find('-',1) != -1 or length.find('+',1) != -1:
733 # handle percent lengths
734 length = latex_length(length)[1]
735 # revert the HSpace inset to ERT
736 subst = put_cmd_in_ert("\\hspace" + protected + "{" + length + "}")
737 document.body[i:j+1] = subst
741 def convert_author_id(document):
742 " Add the author_id to the \\author definition and make sure 0 is not used"
745 re_author = re.compile(r'(\\author) (\".*\")\s*(.*)$')
748 i = find_token(document.header, "\\author", i)
751 m = re_author.match(document.header[i])
755 document.header[i] = "\\author %i %s %s" % (anum, name, email)
756 # FIXME Should this really be incremented if we didn't match?
762 i = find_token(document.body, "\\change_", i)
765 change = document.body[i].split(' ');
768 author_id = int(change[1])
770 document.body[i] = "%s %i %s" % (type, author_id + 1, time)
774 def revert_author_id(document):
775 " Remove the author_id from the \\author definition "
778 rx = re.compile(r'(\\author)\s+(\d+)\s+(\".*\")\s*(.*)$')
782 i = find_token(document.header, "\\author", i)
785 m = rx.match(document.header[i])
787 author_id = int(m.group(2))
788 idmap[author_id] = anum
791 document.header[i] = "\\author %s %s" % (name, email)
793 # FIXME Should this be incremented if we didn't match?
798 i = find_token(document.body, "\\change_", i)
801 change = document.body[i].split(' ');
804 author_id = int(change[1])
806 document.body[i] = "%s %i %s" % (type, idmap[author_id], time)
810 def revert_suppress_date(document):
811 " Revert suppressing of default document date to preamble code "
812 i = find_token(document.header, "\\suppress_date", 0)
815 # remove the preamble line and write to the preamble
816 # when suppress_date was true
817 date = str2bool(get_value(document.header, "\\suppress_date", i))
819 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
820 add_to_preamble(document, ["\\date{}"])
821 del document.header[i]
824 def revert_mhchem(document):
825 "Revert mhchem loading to preamble code"
828 i = find_token(document.header, "\\use_mhchem", 0)
830 document.warning("Malformed LyX document: Could not find mhchem setting.")
833 val = get_value(document.header, "\\use_mhchem", i)
838 del document.header[i]
847 i = find_token(document.body, "\\begin_inset Formula", i)
850 line = document.body[i]
851 if line.find("\\ce{") != -1 or line.find("\\cf{") != -1:
857 pre = ["% lyx2lyx mhchem commands",
858 "\\PassOptionsToPackage{version=3}{mhchem}",
859 "\\usepackage{mhchem}"]
860 add_to_preamble(document, pre)
863 def revert_fontenc(document):
864 " Remove fontencoding param "
865 if not del_token(document.header, '\\fontencoding', 0):
866 document.warning("Malformed LyX document: Missing \\fontencoding.")
869 def merge_gbrief(document):
870 " Merge g-brief-en and g-brief-de to one class "
872 if document.textclass != "g-brief-de":
873 if document.textclass == "g-brief-en":
874 document.textclass = "g-brief"
875 document.set_textclass()
878 obsoletedby = { "Brieftext": "Letter",
879 "Unterschrift": "Signature",
881 "Zusatz": "Addition",
884 "RetourAdresse": "ReturnAddress",
885 "MeinZeichen": "MyRef",
886 "IhrZeichen": "YourRef",
887 "IhrSchreiben": "YourMail",
890 "Konto": "BankAccount",
891 "Postvermerk": "PostalComment",
892 "Adresse": "Address",
894 "Betreff": "Reference",
901 i = find_token(document.body, "\\begin_layout", i)
905 layout = document.body[i][14:]
906 if layout in obsoletedby:
907 document.body[i] = "\\begin_layout " + obsoletedby[layout]
911 document.textclass = "g-brief"
912 document.set_textclass()
915 def revert_gbrief(document):
916 " Revert g-brief to g-brief-en "
917 if document.textclass == "g-brief":
918 document.textclass = "g-brief-en"
919 document.set_textclass()
922 def revert_html_options(document):
923 " Remove html options "
924 del_token(document.header, '\\html_use_mathml', 0)
925 del_token(document.header, '\\html_be_strict', 0)
928 def revert_includeonly(document):
931 i = find_token(document.header, "\\begin_includeonly", i)
934 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
936 document.warning("Unable to find end of includeonly section!!")
938 document.header[i : j + 1] = []
941 def revert_includeall(document):
942 " Remove maintain_unincluded_children param "
943 del_token(document.header, '\\maintain_unincluded_children', 0)
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
1018 val = str2bool(m.group(1))
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 typ = get_quoted_value(document.body, "type", i, j)
1267 arg = get_quoted_value(document.body, "arg", i, j)
1268 if arg != "version" or typ != "lyxinfo":
1272 # We do not actually know the version of LyX used to produce the document.
1273 # But we can use our version, since we are reverting.
1275 # Now we want to check if the line after "\end_inset" is empty. It normally
1276 # is, so we want to remove it, too.
1278 if document.body[j + 1].strip() == "":
1280 document.body[i: lastline] = s
1284 def revert_math_scale(document):
1285 " Remove math scaling and LaTeX options "
1286 del_token(document.header, '\\html_math_img_scale', 0)
1287 del_token(document.header, '\\html_latex_start', 0)
1288 del_token(document.header, '\\html_latex_end', 0)
1291 def revert_pagesizes(document):
1292 " Revert page sizes to default "
1293 i = find_token(document.header, '\\papersize', 0)
1295 size = document.header[i][11:]
1296 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1297 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1298 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1299 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1300 or size == "b5j" or size == "b6j":
1301 del document.header[i]
1304 def revert_DIN_C_pagesizes(document):
1305 " Revert DIN C page sizes to default "
1306 i = find_token(document.header, '\\papersize', 0)
1308 size = document.header[i][11:]
1309 if size == "c0paper" or size == "c1paper" or size == "c2paper" \
1310 or size == "c3paper" or size == "c4paper" or size == "c5paper" \
1311 or size == "c6paper":
1312 del document.header[i]
1315 def convert_html_quotes(document):
1316 " Remove quotes around html_latex_start and html_latex_end "
1318 i = find_token(document.header, '\\html_latex_start', 0)
1320 line = document.header[i]
1321 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1324 document.header[i] = "\\html_latex_start " + m.group(1)
1326 i = find_token(document.header, '\\html_latex_end', 0)
1328 line = document.header[i]
1329 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1332 document.header[i] = "\\html_latex_end " + m.group(1)
1335 def revert_html_quotes(document):
1336 " Remove quotes around html_latex_start and html_latex_end "
1338 i = find_token(document.header, '\\html_latex_start', 0)
1340 line = document.header[i]
1341 l = re.compile(r'\\html_latex_start\s+(.*)')
1344 document.warning("Weird html_latex_start line: " + line)
1345 del document.header[i]
1347 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1349 i = find_token(document.header, '\\html_latex_end', 0)
1351 line = document.header[i]
1352 l = re.compile(r'\\html_latex_end\s+(.*)')
1355 document.warning("Weird html_latex_end line: " + line)
1356 del document.header[i]
1358 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1361 def revert_output_sync(document):
1362 " Remove forward search options "
1363 del_token(document.header, '\\output_sync_macro', 0)
1364 del_token(document.header, '\\output_sync', 0)
1367 def revert_align_decimal(document):
1370 i = find_token(document.body, "\\begin_inset Tabular", i)
1373 j = find_end_of_inset(document.body, i)
1375 document.warning("Unable to find end of Tabular inset at line " + str(i))
1378 cell = find_token(document.body, "<cell", i, j)
1380 document.warning("Can't find any cells in Tabular inset at line " + str(i))
1385 k = find_token(document.body, "<column", k, cell)
1388 if document.body[k].find('alignment="decimal"') == -1:
1391 remove_option(document.body, k, 'decimal_point')
1392 document.body[k] = \
1393 document.body[k].replace('alignment="decimal"', 'alignment="center"')
1397 def convert_optarg(document):
1398 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1401 i = find_token(document.body, '\\begin_inset OptArg', i)
1404 document.body[i] = "\\begin_inset Argument"
1408 def revert_argument(document):
1409 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1412 i = find_token(document.body, '\\begin_inset Argument', i)
1415 document.body[i] = "\\begin_inset OptArg"
1419 def revert_makebox(document):
1420 " Convert \\makebox to TeX code "
1423 # only revert frameless boxes without an inner box
1424 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1427 z = find_end_of_inset(document.body, i)
1429 document.warning("Malformed LyX document: Can't find end of box inset.")
1432 blay = find_token(document.body, "\\begin_layout", i, z)
1434 document.warning("Malformed LyX document: Can't find layout in box.")
1437 # by looking before the layout we make sure we're actually finding
1438 # an option, not text.
1439 j = find_token(document.body, 'use_makebox', i, blay)
1443 val = get_value(document.body, 'use_makebox', j)
1445 del document.body[j]
1448 bend = find_end_of_layout(document.body, blay)
1449 if bend == -1 or bend > z:
1450 document.warning("Malformed LyX document: Can't find end of layout in box.")
1453 # determine the alignment
1454 align = get_quoted_value(document.body, 'hor_pos', i, blay, "c")
1455 # determine the width
1456 length = get_quoted_value(document.body, 'width', i, blay, "50col%")
1457 length = latex_length(length)[1]
1458 # remove the \end_layout \end_inset pair
1459 document.body[bend:z + 1] = put_cmd_in_ert("}")
1460 subst = "\\makebox[" + length + "][" \
1462 document.body[i:blay + 1] = put_cmd_in_ert(subst)
1466 def convert_use_makebox(document):
1467 " Adds use_makebox option for boxes "
1470 i = find_token(document.body, '\\begin_inset Box', i)
1473 # all of this is to make sure we actually find the use_parbox
1474 # that is an option for this box, not some text elsewhere.
1475 z = find_end_of_inset(document.body, i)
1477 document.warning("Can't find end of box inset!!")
1480 blay = find_token(document.body, "\\begin_layout", i, z)
1482 document.warning("Can't find layout in box inset!!")
1485 # so now we are looking for use_parbox before the box's layout
1486 k = find_token(document.body, 'use_parbox', i, blay)
1488 document.warning("Malformed LyX document: Can't find use_parbox statement in box.")
1491 document.body.insert(k + 1, "use_makebox 0")
1495 def revert_IEEEtran(document):
1496 " Convert IEEEtran layouts and styles to TeX code "
1497 if document.textclass != "IEEEtran":
1499 revert_flex_inset(document.body, "IEEE membership", "\\IEEEmembership")
1500 revert_flex_inset(document.body, "Lowercase", "\\MakeLowercase")
1501 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1502 "Page headings", "Biography without photo")
1503 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1504 "After Title Text": "\\IEEEaftertitletext",
1505 "Publication ID": "\\IEEEpubid"}
1506 obsoletedby = {"Page headings": "MarkBoth",
1507 "Biography without photo": "BiographyNoPhoto"}
1508 for layout in layouts:
1511 i = find_token(document.body, '\\begin_layout ' + layout, i)
1514 j = find_end_of_layout(document.body, i)
1516 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1519 if layout in obsoletedby:
1520 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1523 content = lyx2latex(document, document.body[i:j + 1])
1524 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1525 del document.body[i:j + 1]
1526 # no need to reset i
1529 def convert_prettyref(document):
1530 " Converts prettyref references to neutral formatted refs "
1531 re_ref = re.compile("^\s*reference\s+\"(\w+):(\S+)\"")
1532 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1536 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1539 j = find_end_of_inset(document.body, i)
1541 document.warning("Malformed LyX document: No end of InsetRef!")
1544 k = find_token(document.body, "LatexCommand prettyref", i, j)
1546 document.body[k] = "LatexCommand formatted"
1548 document.header.insert(-1, "\\use_refstyle 0")
1551 def revert_refstyle(document):
1552 " Reverts neutral formatted refs to prettyref "
1553 re_ref = re.compile("^reference\s+\"(\w+):(\S+)\"")
1554 nm_ref = re.compile("^\s*name\s+\"(\w+):(\S+)\"")
1558 i = find_token(document.body, "\\begin_inset CommandInset ref", i)
1561 j = find_end_of_inset(document.body, i)
1563 document.warning("Malformed LyX document: No end of InsetRef")
1566 k = find_token(document.body, "LatexCommand formatted", i, j)
1568 document.body[k] = "LatexCommand prettyref"
1570 i = find_token(document.header, "\\use_refstyle", 0)
1572 document.header.pop(i)
1575 def revert_nameref(document):
1576 " Convert namerefs to regular references "
1577 cmds = ["Nameref", "nameref"]
1579 rx = re.compile(r'reference "(.*)"')
1582 oldcmd = "LatexCommand " + cmd
1584 # It seems better to look for this, as most of the reference
1585 # insets won't be ones we care about.
1586 i = find_token(document.body, oldcmd, i)
1591 # Make sure it is actually in an inset!
1592 # A normal line could begin with "LatexCommand nameref"!
1593 val = is_in_inset(document.body, cmdloc, \
1594 "\\begin_inset CommandInset ref")
1599 # ok, so it is in an InsetRef
1600 refline = find_token(document.body, "reference", stins, endins)
1602 document.warning("Can't find reference for inset at line " + stinst + "!!")
1604 m = rx.match(document.body[refline])
1606 document.warning("Can't match reference line: " + document.body[ref])
1610 newcontent = put_cmd_in_ert('\\' + cmd + '{' + ref + '}')
1611 document.body[stins:endins + 1] = newcontent
1614 add_to_preamble(document, "\usepackage{nameref}")
1617 def remove_Nameref(document):
1618 " Convert Nameref commands to nameref commands "
1621 # It seems better to look for this, as most of the reference
1622 # insets won't be ones we care about.
1623 i = find_token(document.body, "LatexCommand Nameref" , i)
1629 # Make sure it is actually in an inset!
1630 val = is_in_inset(document.body, cmdloc, \
1631 "\\begin_inset CommandInset ref")
1634 document.body[cmdloc] = "LatexCommand nameref"
1637 def revert_mathrsfs(document):
1638 " Load mathrsfs if \mathrsfs us use in the document "
1640 for line in document.body:
1641 if line.find("\\mathscr{") != -1:
1642 add_to_preamble(document, ["% lyx2lyx mathrsfs addition", "\\usepackage{mathrsfs}"])
1646 def convert_flexnames(document):
1647 "Convert \\begin_inset Flex Custom:Style to \\begin_inset Flex Style and similarly for CharStyle and Element."
1650 rx = re.compile(r'^\\begin_inset Flex (?:Custom|CharStyle|Element):(.+)$')
1652 i = find_token(document.body, "\\begin_inset Flex", i)
1655 m = rx.match(document.body[i])
1657 document.body[i] = "\\begin_inset Flex " + m.group(1)
1662 "Alert" : "CharStyle:Alert",
1663 "Code" : "CharStyle:Code",
1664 "Concepts" : "CharStyle:Concepts",
1665 "E-Mail" : "CharStyle:E-Mail",
1666 "Emph" : "CharStyle:Emph",
1667 "Expression" : "CharStyle:Expression",
1668 "Initial" : "CharStyle:Initial",
1669 "Institute" : "CharStyle:Institute",
1670 "Meaning" : "CharStyle:Meaning",
1671 "Noun" : "CharStyle:Noun",
1672 "Strong" : "CharStyle:Strong",
1673 "Structure" : "CharStyle:Structure",
1674 "ArticleMode" : "Custom:ArticleMode",
1675 "Endnote" : "Custom:Endnote",
1676 "Glosse" : "Custom:Glosse",
1677 "PresentationMode" : "Custom:PresentationMode",
1678 "Tri-Glosse" : "Custom:Tri-Glosse"
1682 "Abbrev" : "Element:Abbrev",
1683 "CCC-Code" : "Element:CCC-Code",
1684 "Citation-number" : "Element:Citation-number",
1685 "City" : "Element:City",
1686 "Code" : "Element:Code",
1687 "CODEN" : "Element:CODEN",
1688 "Country" : "Element:Country",
1689 "Day" : "Element:Day",
1690 "Directory" : "Element:Directory",
1691 "Dscr" : "Element:Dscr",
1692 "Email" : "Element:Email",
1693 "Emph" : "Element:Emph",
1694 "Filename" : "Element:Filename",
1695 "Firstname" : "Element:Firstname",
1696 "Fname" : "Element:Fname",
1697 "GuiButton" : "Element:GuiButton",
1698 "GuiMenu" : "Element:GuiMenu",
1699 "GuiMenuItem" : "Element:GuiMenuItem",
1700 "ISSN" : "Element:ISSN",
1701 "Issue-day" : "Element:Issue-day",
1702 "Issue-months" : "Element:Issue-months",
1703 "Issue-number" : "Element:Issue-number",
1704 "KeyCap" : "Element:KeyCap",
1705 "KeyCombo" : "Element:KeyCombo",
1706 "Keyword" : "Element:Keyword",
1707 "Literal" : "Element:Literal",
1708 "MenuChoice" : "Element:MenuChoice",
1709 "Month" : "Element:Month",
1710 "Orgdiv" : "Element:Orgdiv",
1711 "Orgname" : "Element:Orgname",
1712 "Postcode" : "Element:Postcode",
1713 "SS-Code" : "Element:SS-Code",
1714 "SS-Title" : "Element:SS-Title",
1715 "State" : "Element:State",
1716 "Street" : "Element:Street",
1717 "Surname" : "Element:Surname",
1718 "Volume" : "Element:Volume",
1719 "Year" : "Element:Year"
1723 def revert_flexnames(document):
1724 if document.backend == "latex":
1725 flexlist = flex_insets
1727 flexlist = flex_elements
1729 rx = re.compile(r'^\\begin_inset Flex\s+(.+)$')
1732 i = find_token(document.body, "\\begin_inset Flex", i)
1735 m = rx.match(document.body[i])
1737 document.warning("Illegal flex inset: " + document.body[i])
1741 if style in flexlist:
1742 document.body[i] = "\\begin_inset Flex " + flexlist[style]
1746 def convert_mathdots(document):
1747 " Load mathdots automatically "
1748 i = find_token(document.header, "\\use_esint" , 0)
1750 document.header.insert(i + 1, "\\use_mathdots 1")
1753 def revert_mathdots(document):
1754 " Load mathdots if used in the document "
1756 mathdots = find_token(document.header, "\\use_mathdots" , 0)
1758 document.warning("No \\usemathdots line. Assuming auto.")
1760 val = get_value(document.header, "\\use_mathdots", mathdots)
1761 del document.header[mathdots]
1765 document.warning("Invalid \\use_mathdots value: " + val + ". Assuming auto.")
1766 # probably usedots has not been changed, but be safe.
1774 add_to_preamble(["% lyx2lyx mathdots addition", "\\usepackage{mathdots}"])
1777 # so we are in the auto case. we want to load mathdots if \iddots is used.
1780 i = find_token(document.body, '\\begin_inset Formula', i)
1783 j = find_end_of_inset(document.body, i)
1785 document.warning("Malformed LyX document: Can't find end of Formula inset at line " + str(i))
1788 code = "\n".join(document.body[i:j])
1789 if code.find("\\iddots") != -1:
1790 add_to_preamble(document, ["% lyx2lyx mathdots addition",
1791 "\\@ifundefined{iddots}{\\usepackage{mathdots}}"])
1796 def convert_rule(document):
1797 " Convert \\lyxline to CommandInset line. "
1800 inset = ['\\begin_inset CommandInset line',
1801 'LatexCommand rule',
1805 '\\end_inset', '', '']
1807 # if paragraphs are indented, we may have to unindent to get the
1808 # line to be full-width.
1809 indent = get_value(document.header, "\\paragraph_separation", 0)
1810 have_indent = (indent == "indent")
1813 i = find_token(document.body, "\\lyxline" , i)
1817 # we need to find out if this line follows other content
1818 # in its paragraph. find its layout....
1819 lastlay = find_token_backwards(document.body, "\\begin_layout", i)
1821 document.warning("Can't find layout for line at " + str(i))
1822 # do the best we can.
1823 document.body[i:i+1] = inset
1827 # ...and look for other content before it.
1829 for line in document.body[lastlay + 1:i]:
1830 # is it empty or a paragraph option?
1831 if not line or line[0] == '\\':
1837 document.body[i:i+1] = inset
1839 # we need to unindent, lest the line be too long
1840 document.body.insert(lastlay + 1, "\\noindent")
1843 # so our line is in the middle of a paragraph
1844 # we need to add a new line, lest this line follow the
1845 # other content on that line and run off the side of the page
1846 document.body[i:i+1] = inset
1847 document.body[i:i] = ["\\begin_inset Newline newline", "\\end_inset", ""]
1851 def revert_rule(document):
1852 " Revert line insets to Tex code "
1855 i = find_token(document.body, "\\begin_inset CommandInset line" , i)
1859 j = find_token(document.body, "\\end_inset" , i)
1861 document.warning("Malformed LyX document: Can't find end of line inset.")
1863 # determine the optional offset
1864 offset = get_quoted_value(document.body, 'offset', i, j)
1866 offset = '[' + offset + ']'
1867 # determine the width
1868 width = get_quoted_value(document.body, 'width', i, j, "100col%")
1869 width = latex_length(width)[1]
1870 # determine the height
1871 height = get_quoted_value(document.body, 'height', i, j, "1pt")
1872 height = latex_length(height)[1]
1873 # output the \rule command
1874 subst = "\\rule[" + offset + "]{" + width + "}{" + height + "}"
1875 document.body[i:j + 1] = put_cmd_in_ert(subst)
1876 i += len(subst) - (j - i)
1879 def revert_diagram(document):
1880 " Add the feyn package if \\Diagram is used in math "
1883 i = find_token(document.body, '\\begin_inset Formula', i)
1886 j = find_end_of_inset(document.body, i)
1888 document.warning("Malformed LyX document: Can't find end of Formula inset.")
1890 lines = "\n".join(document.body[i:j])
1891 if lines.find("\\Diagram") == -1:
1894 add_to_preamble(document, ["% lyx2lyx feyn package insertion ", "\\usepackage{feyn}"])
1895 # only need to do it once!
1899 def convert_bibtex_clearpage(document):
1900 " insert a clear(double)page bibliographystyle if bibtotoc option is used "
1902 i = find_token(document.header, '\\papersides', 0)
1905 document.warning("Malformed LyX document: Can't find papersides definition.")
1906 document.warning("Assuming single sided.")
1909 val = get_value(document.header, "\\papersides", i)
1914 if sides != 1 and sides != 2:
1915 document.warning("Invalid papersides value: " + val)
1916 document.warning("Assuming single sided.")
1921 j = find_token(document.body, "\\begin_inset CommandInset bibtex", j)
1925 k = find_end_of_inset(document.body, j)
1927 document.warning("Can't find end of Bibliography inset at line " + str(j))
1931 # only act if there is the option "bibtotoc"
1932 val = get_value(document.body, 'options', j, k)
1934 document.warning("Can't find options for bibliography inset at line " + str(j))
1938 if val.find("bibtotoc") == -1:
1942 # so we want to insert a new page right before the paragraph that
1943 # this bibliography thing is in.
1944 lay = find_token_backwards(document.body, "\\begin_layout", j)
1946 document.warning("Can't find layout containing bibliography inset at line " + str(j))
1953 cmd = "cleardoublepage"
1954 subst = ['\\begin_layout Standard',
1955 '\\begin_inset Newpage ' + cmd,
1956 '\\end_inset', '', '',
1958 document.body[lay:lay] = subst
1966 supported_versions = ["2.0.0","2.0"]
1967 convert = [[346, []],
1973 [352, [convert_splitindex]],
1980 [359, [convert_nomencl_width]],
1990 [369, [convert_author_id]],
1994 [373, [merge_gbrief]],
2000 [379, [convert_math_output]],
2010 [389, [convert_html_quotes]],
2014 [393, [convert_optarg]],
2015 [394, [convert_use_makebox]],
2018 [397, [remove_Nameref]],
2020 [399, [convert_mathdots]],
2021 [400, [convert_rule]],
2023 [402, [convert_bibtex_clearpage]],
2024 [403, [convert_flexnames]],
2025 [404, [convert_prettyref]]
2028 revert = [[403, [revert_refstyle]],
2029 [402, [revert_flexnames]],
2031 [400, [revert_diagram]],
2032 [399, [revert_rule]],
2033 [398, [revert_mathdots]],
2034 [397, [revert_mathrsfs]],
2036 [395, [revert_nameref]],
2037 [394, [revert_DIN_C_pagesizes]],
2038 [393, [revert_makebox]],
2039 [392, [revert_argument]],
2041 [390, [revert_align_decimal, revert_IEEEtran]],
2042 [389, [revert_output_sync]],
2043 [388, [revert_html_quotes]],
2044 [387, [revert_pagesizes]],
2045 [386, [revert_math_scale]],
2046 [385, [revert_lyx_version]],
2047 [384, [revert_shadedboxcolor]],
2048 [383, [revert_fontcolor]],
2049 [382, [revert_turkmen]],
2050 [381, [revert_notefontcolor]],
2051 [380, [revert_equalspacing_xymatrix]],
2052 [379, [revert_inset_preview]],
2053 [378, [revert_math_output]],
2055 [376, [revert_multirow]],
2056 [375, [revert_includeall]],
2057 [374, [revert_includeonly]],
2058 [373, [revert_html_options]],
2059 [372, [revert_gbrief]],
2060 [371, [revert_fontenc]],
2061 [370, [revert_mhchem]],
2062 [369, [revert_suppress_date]],
2063 [368, [revert_author_id]],
2064 [367, [revert_hspace_glue_lengths]],
2065 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
2066 [365, [revert_percent_skip_lengths]],
2067 [364, [revert_paragraph_indentation]],
2068 [363, [revert_branch_filename]],
2069 [362, [revert_longtable_align]],
2070 [361, [revert_applemac]],
2072 [359, [revert_nomencl_cwidth]],
2073 [358, [revert_nomencl_width]],
2074 [357, [revert_custom_processors]],
2075 [356, [revert_ulinelatex]],
2077 [354, [revert_strikeout]],
2078 [353, [revert_printindexall]],
2079 [352, [revert_subindex]],
2080 [351, [revert_splitindex]],
2081 [350, [revert_backgroundcolor]],
2082 [349, [revert_outputformat]],
2083 [348, [revert_xetex]],
2084 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2085 [346, [revert_tabularvalign]],
2086 [345, [revert_swiss]]
2090 if __name__ == "__main__":