1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2008 José Matos <jamatos@lyx.org>
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, get_value, get_value_string
28 ####################################################################
29 # Private helper functions
31 def remove_option(document, m, option):
32 l = document.body[m].find(option)
34 val = document.body[m][l:].split('"')[1]
35 document.body[m] = document.body[m][:l-1] + document.body[m][l+len(option + '="' + val + '"'):]
38 def find_end_of_inset(lines, i):
39 " Find end of inset, where lines[i] is included."
40 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
43 def add_to_preamble(document, text):
44 """ Add text to the preamble if it is not already there.
45 Only the first line is checked!"""
47 if find_token(document.preamble, text[0], 0) != -1:
50 document.preamble.extend(text)
53 def insert_to_preamble(index, document, text):
54 """ Insert text to the preamble at a given line"""
56 document.preamble.insert(index, text)
59 def read_unicodesymbols():
60 " Read the unicodesymbols list of unicode characters and corresponding commands."
61 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
62 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
64 # Two backslashes, followed by some non-word character, and then a character
65 # in brackets. The idea is to check for constructs like: \"{u}, which is how
66 # they are written in the unicodesymbols file; but they can also be written
67 # as: \"u or even \" u.
68 r = re.compile(r'\\\\(\W)\{(\w)\}')
69 for line in fp.readlines():
70 if line[0] != '#' and line.strip() != "":
71 line=line.replace(' "',' ') # remove all quotation marks with spaces before
72 line=line.replace('" ',' ') # remove all quotation marks with spaces after
73 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
75 [ucs4,command,dead] = line.split(None,2)
76 if command[0:1] != "\\":
78 spec_chars.append([command, unichr(eval(ucs4))])
84 # If the character is a double-quote, then we need to escape it, too,
85 # since it is done that way in the LyX file.
86 if m.group(1) == "\"":
89 command += m.group(1) + m.group(2)
90 commandbl += m.group(1) + ' ' + m.group(2)
91 spec_chars.append([command, unichr(eval(ucs4))])
92 spec_chars.append([commandbl, unichr(eval(ucs4))])
97 unicode_reps = read_unicodesymbols()
100 # DO NOT USE THIS ROUTINE ANY MORE. Better yet, replace the uses that
101 # have been made of it with uses of put_cmd_in_ert.
102 def old_put_cmd_in_ert(string):
103 for rep in unicode_reps:
104 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
105 string = string.replace('\\', "\\backslash\n")
106 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
107 + string + "\n\\end_layout\n\\end_inset"
111 # This routine wraps some content in an ERT inset.
113 # NOTE: The function accepts either a single string or a LIST of strings as
114 # argument. But it returns a LIST of strings, split on \n, so that it does
115 # not have embedded newlines.
117 # This is how lyx2lyx represents a LyX document: as a list of strings,
118 # each representing a line of a LyX file. Embedded newlines confuse
121 # A call to this routine will often go something like this:
122 # i = find_token('\\begin_inset FunkyInset', ...)
124 # j = find_end_of_inset(document.body, i)
125 # content = ...extract content from insets
126 # # that could be as simple as:
127 # # content = lyx2latex(document[i:j+1])
128 # ert = put_cmd_in_ert(content)
129 # document.body[i:j] = ert
130 # Now, before we continue, we need to reset i appropriately. Normally,
133 # That puts us right after the ERT we just inserted.
135 def put_cmd_in_ert(arg):
136 ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
137 # Despite the warnings just given, it will be faster for us to work
138 # with a single string internally. That way, we only go through the
139 # unicode_reps loop once.
140 if type(arg) is list:
144 for rep in unicode_reps:
145 s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
146 s = s.replace('\\', "\\backslash\n")
147 ret += s.splitlines()
148 ret += ["\\end_layout", "\\end_inset"]
152 def lyx2latex(document, lines):
153 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
154 # clean up multiline stuff
158 for curline in range(len(lines)):
159 line = lines[curline]
160 if line.startswith("\\begin_inset ERT"):
161 # We don't want to replace things inside ERT, so figure out
162 # where the end of the inset is.
163 ert_end = find_end_of_inset(lines, curline + 1)
165 elif line.startswith("\\begin_inset Formula"):
167 elif line.startswith("\\begin_inset Quotes"):
168 # For now, we do a very basic reversion. Someone who understands
169 # quotes is welcome to fix it up.
170 qtype = line[20:].strip()
184 elif line.isspace() or \
185 line.startswith("\\begin_layout") or \
186 line.startswith("\\end_layout") or \
187 line.startswith("\\begin_inset") or \
188 line.startswith("\\end_inset") or \
189 line.startswith("\\lang") or \
190 line.strip() == "status collapsed" or \
191 line.strip() == "status open":
195 # this needs to be added to the preamble because of cases like
196 # \textmu, \textbackslash, etc.
197 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
198 '\\@ifundefined{textmu}',
199 ' {\\usepackage{textcomp}}{}'])
200 # a lossless reversion is not possible
201 # try at least to handle some common insets and settings
202 if ert_end >= curline:
203 line = line.replace(r'\backslash', r'\\')
205 line = line.replace('&', '\\&{}')
206 line = line.replace('#', '\\#{}')
207 line = line.replace('^', '\\^{}')
208 line = line.replace('%', '\\%{}')
209 line = line.replace('_', '\\_{}')
210 line = line.replace('$', '\\${}')
212 # Do the LyX text --> LaTeX conversion
213 for rep in unicode_reps:
214 line = line.replace(rep[1], rep[0] + "{}")
215 line = line.replace(r'\backslash', r'\textbackslash{}')
216 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
217 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
218 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
219 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
220 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
221 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
222 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
223 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
224 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
229 def latex_length(string):
230 'Convert lengths to their LaTeX representation.'
233 # the string has the form
234 # ValueUnit+ValueUnit-ValueUnit or
235 # ValueUnit+-ValueUnit
236 # the + and - (glue lengths) are optional
237 # the + always precedes the -
239 # Convert relative lengths to LaTeX units
240 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
241 "page%":"\\paperwidth", "line%":"\\linewidth",
242 "theight%":"\\textheight", "pheight%":"\\paperheight"}
243 for unit in units.keys():
244 i = string.find(unit)
247 minus = string.rfind("-", 1, i)
248 plus = string.rfind("+", 0, i)
249 latex_unit = units[unit]
250 if plus == -1 and minus == -1:
252 value = str(float(value)/100)
253 end = string[i + len(unit):]
254 string = value + latex_unit + end
256 value = string[plus+1:i]
257 value = str(float(value)/100)
258 begin = string[:plus+1]
259 end = string[i+len(unit):]
260 string = begin + value + latex_unit + end
262 value = string[minus+1:i]
263 value = str(float(value)/100)
264 begin = string[:minus+1]
265 string = begin + value + latex_unit
267 # replace + and -, but only if the - is not the first character
268 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
269 # handle the case where "+-1mm" was used, because LaTeX only understands
270 # "plus 1mm minus 1mm"
271 if string.find("plus minus"):
272 lastvaluepos = string.rfind(" ")
273 lastvalue = string[lastvaluepos:]
274 string = string.replace(" ", lastvalue + " ")
276 return "False," + string
278 return "True," + string
281 def revert_flex_inset(document, name, LaTeXname, position):
282 " Convert flex insets to TeX code "
285 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
288 z = find_end_of_inset(document.body, i)
290 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
292 # remove the \end_inset
293 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
294 # we need to reset character layouts if necessary
295 j = find_token(document.body, '\\emph on', i)
296 k = find_token(document.body, '\\noun on', i)
297 l = find_token(document.body, '\\series', i)
298 m = find_token(document.body, '\\family', i)
299 n = find_token(document.body, '\\shape', i)
300 o = find_token(document.body, '\\color', i)
301 p = find_token(document.body, '\\size', i)
302 q = find_token(document.body, '\\bar under', i)
303 r = find_token(document.body, '\\uuline on', i)
304 s = find_token(document.body, '\\uwave on', i)
305 t = find_token(document.body, '\\strikeout on', i)
306 if j != -1 and j < z:
307 document.body.insert(z-2, "\\emph default")
308 if k != -1 and k < z:
309 document.body.insert(z-2, "\\noun default")
310 if l != -1 and l < z:
311 document.body.insert(z-2, "\\series default")
312 if m != -1 and m < z:
313 document.body.insert(z-2, "\\family default")
314 if n != -1 and n < z:
315 document.body.insert(z-2, "\\shape default")
316 if o != -1 and o < z:
317 document.body.insert(z-2, "\\color inherit")
318 if p != -1 and p < z:
319 document.body.insert(z-2, "\\size default")
320 if q != -1 and q < z:
321 document.body.insert(z-2, "\\bar default")
322 if r != -1 and r < z:
323 document.body.insert(z-2, "\\uuline default")
324 if s != -1 and s < z:
325 document.body.insert(z-2, "\\uwave default")
326 if t != -1 and t < z:
327 document.body.insert(z-2, "\\strikeout default")
328 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
332 def revert_charstyles(document, name, LaTeXname, changed):
333 " Reverts character styles to TeX code "
336 i = find_token(document.body, name + ' on', i)
339 j = find_token(document.body, name + ' default', i)
340 k = find_token(document.body, name + ' on', i + 1)
341 # if there is no default set, the style ends with the layout
342 # assure hereby that we found the correct layout end
343 if j != -1 and (j < k or k == -1):
344 document.body[j:j+1] = put_cmd_in_ert("}")
346 j = find_token(document.body, '\\end_layout', i)
347 document.body[j:j] = put_cmd_in_ert("}")
348 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
353 def revert_layout_command(document, name, LaTeXname, position):
354 " Reverts a command from a layout to TeX code "
357 i = find_token(document.body, '\\begin_layout ' + name, i)
361 # find the next layout
364 j = find_token(document.body, '\\begin_layout', j)
365 l = len(document.body)
366 # if nothing was found it was the last layout of the document
368 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
370 # exclude plain layout because this can be TeX code or another inset
371 elif document.body[j] != '\\begin_layout Plain Layout':
372 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
376 document.body[i] = '\\begin_layout Standard'
377 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
381 ####################################################################
384 def revert_swiss(document):
385 " Set language german-ch to ngerman "
387 if document.language == "german-ch":
388 document.language = "ngerman"
389 i = find_token(document.header, "\\language", 0)
391 document.header[i] = "\\language ngerman"
394 j = find_token(document.body, "\\lang german-ch", j)
397 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
401 def revert_tabularvalign(document):
402 " Revert the tabular valign option "
405 i = find_token(document.body, "\\begin_inset Tabular", i)
408 j = find_token(document.body, "</cell>", i)
410 document.warning("Malformed LyX document: Could not find end of tabular cell.")
413 # don't set a box for longtables, only delete tabularvalignment
414 # the alignment is 2 lines below \\begin_inset Tabular
415 p = document.body[i+2].find("islongtable")
417 q = document.body[i+2].find("tabularvalignment")
419 document.body[i+2] = document.body[i+2][:q-1]
420 document.body[i+2] = document.body[i+2] + '>'
425 tabularvalignment = 'c'
426 # which valignment is specified?
427 m = document.body[i+2].find('tabularvalignment="top"')
429 tabularvalignment = 't'
430 m = document.body[i+2].find('tabularvalignment="bottom"')
432 tabularvalignment = 'b'
433 # delete tabularvalignment
434 q = document.body[i+2].find("tabularvalignment")
436 document.body[i+2] = document.body[i+2][:q-1]
437 document.body[i+2] = document.body[i+2] + '>'
439 # don't add a box when centered
440 if tabularvalignment == 'c':
443 subst = ['\\end_layout', '\\end_inset']
444 document.body[j:j] = subst # just inserts those lines
445 subst = ['\\begin_inset Box Frameless',
446 'position "' + tabularvalignment +'"',
451 # we don't know the width, assume 50%
455 'height_special "totalheight"',
458 '\\begin_layout Plain Layout']
459 document.body[i:i] = subst # this just inserts the array at i
460 i += len(subst) + 2 # adjust i to save a few cycles
463 def revert_phantom(document):
464 " Reverts phantom to ERT "
468 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
471 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
472 '\\begin_inset ERT\nstatus collapsed\n\n' \
473 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
474 'phantom{\n\\end_layout\n\n\\end_inset\n')
475 substi = substi.split('\n')
476 document.body[i : i+4] = substi
478 j = find_token(document.body, "\\end_layout", i)
480 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
482 substj = document.body[j].replace('\\end_layout', \
483 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
484 '\\begin_layout Plain Layout\n\n' \
485 '}\n\\end_layout\n\n\\end_inset\n')
486 substj = substj.split('\n')
487 document.body[j : j+4] = substj
491 def revert_hphantom(document):
492 " Reverts hphantom to ERT "
496 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
499 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
500 '\\begin_inset ERT\nstatus collapsed\n\n' \
501 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
502 'hphantom{\n\\end_layout\n\n\\end_inset\n')
503 substi = substi.split('\n')
504 document.body[i : i+4] = substi
506 j = find_token(document.body, "\\end_layout", i)
508 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
510 substj = document.body[j].replace('\\end_layout', \
511 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
512 '\\begin_layout Plain Layout\n\n' \
513 '}\n\\end_layout\n\n\\end_inset\n')
514 substj = substj.split('\n')
515 document.body[j : j+4] = substj
519 def revert_vphantom(document):
520 " Reverts vphantom to ERT "
524 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
527 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
528 '\\begin_inset ERT\nstatus collapsed\n\n' \
529 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
530 'vphantom{\n\\end_layout\n\n\\end_inset\n')
531 substi = substi.split('\n')
532 document.body[i : i+4] = substi
534 j = find_token(document.body, "\\end_layout", i)
536 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
538 substj = document.body[j].replace('\\end_layout', \
539 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
540 '\\begin_layout Plain Layout\n\n' \
541 '}\n\\end_layout\n\n\\end_inset\n')
542 substj = substj.split('\n')
543 document.body[j : j+4] = substj
547 def revert_xetex(document):
548 " Reverts documents that use XeTeX "
549 i = find_token(document.header, '\\use_xetex', 0)
551 document.warning("Malformed LyX document: Missing \\use_xetex.")
553 if get_value(document.header, "\\use_xetex", i) == 'false':
554 del document.header[i]
556 del document.header[i]
557 # 1.) set doc encoding to utf8-plain
558 i = find_token(document.header, "\\inputencoding", 0)
560 document.warning("Malformed LyX document: Missing \\inputencoding.")
561 document.header[i] = "\\inputencoding utf8-plain"
562 # 2.) check font settings
563 l = find_token(document.header, "\\font_roman", 0)
565 document.warning("Malformed LyX document: Missing \\font_roman.")
566 line = document.header[l]
567 l = re.compile(r'\\font_roman (.*)$')
570 l = find_token(document.header, "\\font_sans", 0)
572 document.warning("Malformed LyX document: Missing \\font_sans.")
573 line = document.header[l]
574 l = re.compile(r'\\font_sans (.*)$')
577 l = find_token(document.header, "\\font_typewriter", 0)
579 document.warning("Malformed LyX document: Missing \\font_typewriter.")
580 line = document.header[l]
581 l = re.compile(r'\\font_typewriter (.*)$')
583 typewriter = m.group(1)
584 osf = get_value(document.header, '\\font_osf', 0) == "true"
585 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
586 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
587 # 3.) set preamble stuff
588 pretext = '%% This document must be processed with xelatex!\n'
589 pretext += '\\usepackage{fontspec}\n'
590 if roman != "default":
591 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
592 if sans != "default":
593 pretext += '\\setsansfont['
595 pretext += 'Scale=' + str(sf_scale / 100) + ','
596 pretext += 'Mapping=tex-text]{' + sans + '}\n'
597 if typewriter != "default":
598 pretext += '\\setmonofont'
600 pretext += '[Scale=' + str(tt_scale / 100) + ']'
601 pretext += '{' + typewriter + '}\n'
603 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
604 pretext += '\usepackage{xunicode}\n'
605 pretext += '\usepackage{xltxtra}\n'
606 insert_to_preamble(0, document, pretext)
607 # 4.) reset font settings
608 i = find_token(document.header, "\\font_roman", 0)
610 document.warning("Malformed LyX document: Missing \\font_roman.")
611 document.header[i] = "\\font_roman default"
612 i = find_token(document.header, "\\font_sans", 0)
614 document.warning("Malformed LyX document: Missing \\font_sans.")
615 document.header[i] = "\\font_sans default"
616 i = find_token(document.header, "\\font_typewriter", 0)
618 document.warning("Malformed LyX document: Missing \\font_typewriter.")
619 document.header[i] = "\\font_typewriter default"
620 i = find_token(document.header, "\\font_osf", 0)
622 document.warning("Malformed LyX document: Missing \\font_osf.")
623 document.header[i] = "\\font_osf false"
624 i = find_token(document.header, "\\font_sc", 0)
626 document.warning("Malformed LyX document: Missing \\font_sc.")
627 document.header[i] = "\\font_sc false"
628 i = find_token(document.header, "\\font_sf_scale", 0)
630 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
631 document.header[i] = "\\font_sf_scale 100"
632 i = find_token(document.header, "\\font_tt_scale", 0)
634 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
635 document.header[i] = "\\font_tt_scale 100"
638 def revert_outputformat(document):
639 " Remove default output format param "
640 i = find_token(document.header, '\\default_output_format', 0)
642 document.warning("Malformed LyX document: Missing \\default_output_format.")
644 del document.header[i]
647 def revert_backgroundcolor(document):
648 " Reverts background color to preamble code "
652 i = find_token(document.header, "\\backgroundcolor", i)
655 colorcode = get_value(document.header, '\\backgroundcolor', 0)
656 del document.header[i]
657 # don't clutter the preamble if backgroundcolor is not set
658 if colorcode == "#ffffff":
660 # the color code is in the form #rrggbb where every character denotes a hex number
661 # convert the string to an int
662 red = string.atoi(colorcode[1:3],16)
663 # we want the output "0.5" for the value "127" therefore add here
666 redout = float(red) / 256
667 green = string.atoi(colorcode[3:5],16)
670 greenout = float(green) / 256
671 blue = string.atoi(colorcode[5:7],16)
674 blueout = float(blue) / 256
676 insert_to_preamble(0, document,
677 '% Commands inserted by lyx2lyx to set the background color\n'
678 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
679 + '\\definecolor{page_backgroundcolor}{rgb}{'
680 + str(redout) + ', ' + str(greenout)
681 + ', ' + str(blueout) + '}\n'
682 + '\\pagecolor{page_backgroundcolor}\n')
685 def revert_splitindex(document):
686 " Reverts splitindex-aware documents "
687 i = find_token(document.header, '\\use_indices', 0)
689 document.warning("Malformed LyX document: Missing \\use_indices.")
691 indices = get_value(document.header, "\\use_indices", i)
693 if indices == "true":
694 preamble += "\\usepackage{splitidx}\n"
695 del document.header[i]
698 i = find_token(document.header, "\\index", i)
701 k = find_token(document.header, "\\end_index", i)
703 document.warning("Malformed LyX document: Missing \\end_index.")
705 line = document.header[i]
706 l = re.compile(r'\\index (.*)$')
709 ishortcut = get_value(document.header, '\\shortcut', i, k)
710 if ishortcut != "" and indices == "true":
711 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
712 del document.header[i:k+1]
715 insert_to_preamble(0, document, preamble)
718 i = find_token(document.body, "\\begin_inset Index", i)
721 line = document.body[i]
722 l = re.compile(r'\\begin_inset Index (.*)$')
725 if itype == "idx" or indices == "false":
726 document.body[i] = "\\begin_inset Index"
728 k = find_end_of_inset(document.body, i)
731 content = lyx2latex(document, document.body[i:k])
733 content = content.replace('"', r'\"')
734 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
735 document.body[i:k+1] = subst
739 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
742 k = find_end_of_inset(document.body, i)
743 ptype = get_value(document.body, 'type', i, k).strip('"')
745 j = find_token(document.body, "type", i, k)
747 elif indices == "false":
748 del document.body[i:k+1]
750 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
751 document.body[i:k+1] = subst
755 def convert_splitindex(document):
756 " Converts index and printindex insets to splitindex-aware format "
759 i = find_token(document.body, "\\begin_inset Index", i)
762 document.body[i] = document.body[i].replace("\\begin_inset Index",
763 "\\begin_inset Index idx")
767 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
770 if document.body[i + 1].find('LatexCommand printindex') == -1:
771 document.warning("Malformed LyX document: Incomplete printindex inset.")
773 subst = ["LatexCommand printindex",
775 document.body[i + 1:i + 2] = subst
779 def revert_subindex(document):
780 " Reverts \\printsubindex CommandInset types "
781 i = find_token(document.header, '\\use_indices', 0)
783 document.warning("Malformed LyX document: Missing \\use_indices.")
785 indices = get_value(document.header, "\\use_indices", i)
788 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
791 k = find_end_of_inset(document.body, i)
792 ctype = get_value(document.body, 'LatexCommand', i, k)
793 if ctype != "printsubindex":
796 ptype = get_value(document.body, 'type', i, k).strip('"')
797 if indices == "false":
798 del document.body[i:k+1]
800 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
801 document.body[i:k+1] = subst
805 def revert_printindexall(document):
806 " Reverts \\print[sub]index* CommandInset types "
807 i = find_token(document.header, '\\use_indices', 0)
809 document.warning("Malformed LyX document: Missing \\use_indices.")
811 indices = get_value(document.header, "\\use_indices", i)
814 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
817 k = find_end_of_inset(document.body, i)
818 ctype = get_value(document.body, 'LatexCommand', i, k)
819 if ctype != "printindex*" and ctype != "printsubindex*":
822 if indices == "false":
823 del document.body[i:k+1]
825 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
826 document.body[i:k+1] = subst
830 def revert_strikeout(document):
831 " Reverts \\strikeout character style "
833 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
834 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
835 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
837 insert_to_preamble(0, document,
838 '% Commands inserted by lyx2lyx for proper underlining\n'
839 + '\\PassOptionsToPackage{normalem}{ulem}\n'
840 + '\\usepackage{ulem}\n')
843 def revert_ulinelatex(document):
844 " Reverts \\uline character style "
845 i = find_token(document.body, '\\bar under', 0)
848 insert_to_preamble(0, document,
849 '% Commands inserted by lyx2lyx for proper underlining\n'
850 + '\\PassOptionsToPackage{normalem}{ulem}\n'
851 + '\\usepackage{ulem}\n'
852 + '\\let\\cite@rig\\cite\n'
853 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
854 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
855 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
858 def revert_custom_processors(document):
859 " Remove bibtex_command and index_command params "
860 i = find_token(document.header, '\\bibtex_command', 0)
862 document.warning("Malformed LyX document: Missing \\bibtex_command.")
864 del document.header[i]
865 i = find_token(document.header, '\\index_command', 0)
867 document.warning("Malformed LyX document: Missing \\index_command.")
869 del document.header[i]
872 def convert_nomencl_width(document):
873 " Add set_width param to nomencl_print "
876 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
879 document.body.insert(i + 2, "set_width \"none\"")
883 def revert_nomencl_width(document):
884 " Remove set_width param from nomencl_print "
887 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
890 j = find_end_of_inset(document.body, i)
891 l = find_token(document.body, "set_width", i, j)
893 document.warning("Can't find set_width option for nomencl_print!")
900 def revert_nomencl_cwidth(document):
901 " Remove width param from nomencl_print "
904 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
907 j = find_end_of_inset(document.body, i)
908 l = find_token(document.body, "width", i, j)
910 #Can't find width option for nomencl_print
913 width = get_value(document.body, "width", i, j).strip('"')
915 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
916 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
920 def revert_applemac(document):
921 " Revert applemac encoding to auto "
923 if document.encoding == "applemac":
924 document.encoding = "auto"
925 i = find_token(document.header, "\\encoding", 0)
927 document.header[i] = "\\encoding auto"
930 def revert_longtable_align(document):
931 " Remove longtable alignment setting "
935 i = find_token(document.body, "\\begin_inset Tabular", i)
938 # the alignment is 2 lines below \\begin_inset Tabular
939 j = document.body[i+2].find("longtabularalignment")
942 document.body[i+2] = document.body[i+2][:j-1]
943 document.body[i+2] = document.body[i+2] + '>'
947 def revert_branch_filename(document):
948 " Remove \\filename_suffix parameter from branches "
951 i = find_token(document.header, "\\filename_suffix", i)
954 del document.header[i]
957 def revert_paragraph_indentation(document):
958 " Revert custom paragraph indentation to preamble code "
961 i = find_token(document.header, "\\paragraph_indentation", i)
964 # only remove the preamble line if default
965 # otherwise also write the value to the preamble
966 length = get_value(document.header, "\\paragraph_indentation", i)
967 if length == "default":
968 del document.header[i]
971 # handle percent lengths
972 # latex_length returns "bool,length"
973 length = latex_length(length).split(",")[1]
974 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
975 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
976 del document.header[i]
980 def revert_percent_skip_lengths(document):
981 " Revert relative lengths for paragraph skip separation to preamble code "
984 i = find_token(document.header, "\\defskip", i)
987 length = get_value(document.header, "\\defskip", i)
988 # only revert when a custom length was set and when
989 # it used a percent length
990 if length not in ('smallskip', 'medskip', 'bigskip'):
991 # handle percent lengths
992 length = latex_length(length)
993 # latex_length returns "bool,length"
994 percent = length.split(",")[0]
995 length = length.split(",")[1]
996 if percent == "True":
997 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
998 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
999 # set defskip to medskip as default
1000 document.header[i] = "\\defskip medskip"
1004 def revert_percent_vspace_lengths(document):
1005 " Revert relative VSpace lengths to ERT "
1008 i = find_token(document.body, "\\begin_inset VSpace", i)
1011 # only revert if a custom length was set and if
1012 # it used a percent length
1013 line = document.body[i]
1014 r = re.compile(r'\\begin_inset VSpace (.*)$')
1017 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1018 # check if the space has a star (protected space)
1019 protected = (document.body[i].rfind("*") != -1)
1021 length = length.rstrip('*')
1022 # handle percent lengths
1023 length = latex_length(length)
1024 # latex_length returns "bool,length"
1025 percent = length.split(",")[0]
1026 length = length.split(",")[1]
1027 # revert the VSpace inset to ERT
1028 if percent == "True":
1030 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1032 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1033 document.body[i:i+2] = subst
1037 def revert_percent_hspace_lengths(document):
1038 " Revert relative HSpace lengths to ERT "
1041 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1044 protected = (document.body[i].find("\\hspace*{}") != -1)
1045 # only revert if a custom length was set and if
1046 # it used a percent length
1047 length = get_value(document.body, '\\length', i+1)
1049 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1051 # handle percent lengths
1052 length = latex_length(length)
1053 # latex_length returns "bool,length"
1054 percent = length.split(",")[0]
1055 length = length.split(",")[1]
1056 # revert the HSpace inset to ERT
1057 if percent == "True":
1059 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1061 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1062 document.body[i:i+3] = subst
1066 def revert_hspace_glue_lengths(document):
1067 " Revert HSpace glue lengths to ERT "
1070 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1073 protected = (document.body[i].find("\\hspace*{}") != -1)
1074 length = get_value(document.body, '\\length', i+1)
1076 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1078 # only revert if the length contains a plus or minus at pos != 0
1079 glue = re.compile(r'.+[\+-]')
1080 if glue.search(length):
1081 # handle percent lengths
1082 # latex_length returns "bool,length"
1083 length = latex_length(length).split(",")[1]
1084 # revert the HSpace inset to ERT
1086 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1088 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1089 document.body[i:i+3] = subst
1092 def convert_author_id(document):
1093 " Add the author_id to the \\author definition and make sure 0 is not used"
1097 i = find_token(document.header, "\\author", i)
1101 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1102 m = r.match(document.header[i])
1107 if m.lastindex == 3:
1109 document.header[i] = "\\author %i %s %s" % (j, name, email)
1115 k = find_token(document.body, "\\change_", k)
1119 change = document.body[k].split(' ');
1120 if len(change) == 3:
1122 author_id = int(change[1])
1124 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1127 def revert_author_id(document):
1128 " Remove the author_id from the \\author definition "
1133 i = find_token(document.header, "\\author", i)
1137 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1138 m = r.match(document.header[i])
1140 author_id = int(m.group(2))
1141 idmap[author_id] = j
1145 if m.lastindex == 4:
1147 document.header[i] = "\\author %s %s" % (name, email)
1153 k = find_token(document.body, "\\change_", k)
1157 change = document.body[k].split(' ');
1158 if len(change) == 3:
1160 author_id = int(change[1])
1162 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1166 def revert_suppress_date(document):
1167 " Revert suppressing of default document date to preamble code "
1170 i = find_token(document.header, "\\suppress_date", i)
1173 # remove the preamble line and write to the preamble
1174 # when suppress_date was true
1175 date = get_value(document.header, "\\suppress_date", i)
1177 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1178 add_to_preamble(document, ["\\date{}"])
1179 del document.header[i]
1183 def revert_mhchem(document):
1184 "Revert mhchem loading to preamble code"
1189 i = find_token(document.header, "\\use_mhchem 1", 0)
1193 i = find_token(document.header, "\\use_mhchem 2", 0)
1196 if mhchem == "auto":
1197 j = find_token(document.body, "\\cf{", 0)
1201 j = find_token(document.body, "\\ce{", 0)
1205 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1206 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1207 add_to_preamble(document, ["\\usepackage{mhchem}"])
1208 k = find_token(document.header, "\\use_mhchem", 0)
1210 document.warning("Malformed LyX document: Could not find mhchem setting.")
1212 del document.header[k]
1215 def revert_fontenc(document):
1216 " Remove fontencoding param "
1217 i = find_token(document.header, '\\fontencoding', 0)
1219 document.warning("Malformed LyX document: Missing \\fontencoding.")
1221 del document.header[i]
1224 def merge_gbrief(document):
1225 " Merge g-brief-en and g-brief-de to one class "
1227 if document.textclass != "g-brief-de":
1228 if document.textclass == "g-brief-en":
1229 document.textclass = "g-brief"
1230 document.set_textclass()
1233 obsoletedby = { "Brieftext": "Letter",
1234 "Unterschrift": "Signature",
1235 "Strasse": "Street",
1236 "Zusatz": "Addition",
1239 "RetourAdresse": "ReturnAddress",
1240 "MeinZeichen": "MyRef",
1241 "IhrZeichen": "YourRef",
1242 "IhrSchreiben": "YourMail",
1245 "Konto": "BankAccount",
1246 "Postvermerk": "PostalComment",
1247 "Adresse": "Address",
1249 "Betreff": "Reference",
1250 "Anrede": "Opening",
1256 i = find_token(document.body, "\\begin_layout", i)
1260 layout = document.body[i][14:]
1261 if layout in obsoletedby:
1262 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1266 document.textclass = "g-brief"
1267 document.set_textclass()
1270 def revert_gbrief(document):
1271 " Revert g-brief to g-brief-en "
1272 if document.textclass == "g-brief":
1273 document.textclass = "g-brief-en"
1274 document.set_textclass()
1277 def revert_html_options(document):
1278 " Remove html options "
1279 i = find_token(document.header, '\\html_use_mathml', 0)
1281 del document.header[i]
1282 i = find_token(document.header, '\\html_be_strict', 0)
1284 del document.header[i]
1287 def revert_includeonly(document):
1290 i = find_token(document.header, "\\begin_includeonly", i)
1293 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1295 # this should not happen
1297 document.header[i : j + 1] = []
1300 def revert_includeall(document):
1301 " Remove maintain_unincluded_children param "
1302 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1304 del document.header[i]
1307 def revert_multirow(document):
1308 " Revert multirow cells in tables "
1312 # cell type 3 is multirow begin cell
1313 i = find_token(document.body, '<cell multirow="3"', i)
1316 # a multirow cell was found
1318 # remove the multirow tag, set the valignment to top
1319 # and remove the bottom line
1320 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1321 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1322 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1323 # write ERT to create the multirow cell
1324 # use 2 rows and 2cm as default with because the multirow span
1325 # and the column width is only hardly accessible
1326 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1327 document.body[i + 4:i + 4] = subst
1328 i = find_token(document.body, "</cell>", i)
1330 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1332 subst = [old_put_cmd_in_ert("}")]
1333 document.body[i - 3:i - 3] = subst
1334 # cell type 4 is multirow part cell
1335 i = find_token(document.body, '<cell multirow="4"', i)
1338 # remove the multirow tag, set the valignment to top
1339 # and remove the top line
1340 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1341 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1342 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1344 if multirow == True:
1345 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1346 add_to_preamble(document, ["\\usepackage{multirow}"])
1349 def convert_math_output(document):
1350 " Convert \html_use_mathml to \html_math_output "
1351 i = find_token(document.header, "\\html_use_mathml", 0)
1354 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1355 m = rgx.match(document.header[i])
1357 newval = "0" # MathML
1360 newval = "2" # Images
1361 document.header[i] = "\\html_math_output " + newval
1364 def revert_math_output(document):
1365 " Revert \html_math_output to \html_use_mathml "
1366 i = find_token(document.header, "\\html_math_output", 0)
1369 rgx = re.compile(r'\\html_math_output\s+(\d)')
1370 m = rgx.match(document.header[i])
1374 if val == "1" or val == "2":
1377 document.warning("Unable to match " + document.header[i])
1378 document.header[i] = "\\html_use_mathml " + newval
1382 def revert_inset_preview(document):
1383 " Dissolves the preview inset "
1388 i = find_token(document.body, "\\begin_inset Preview", i)
1391 j = find_end_of_inset(document.body, i)
1393 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1395 #If the layout is Standard we need to remove it, otherwise there
1396 #will be paragraph breaks that shouldn't be there.
1397 k = find_token(document.body, "\\begin_layout Standard", i)
1399 del document.body[i : i+3]
1400 del document.body[j-5 : j-2]
1403 del document.body[i]
1404 del document.body[j-1]
1408 def revert_equalspacing_xymatrix(document):
1409 " Revert a Formula with xymatrix@! to an ERT inset "
1412 has_preamble = False
1413 has_equal_spacing = False
1416 i = find_token(document.body, "\\begin_inset Formula", i)
1419 j = find_end_of_inset(document.body, i)
1421 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1424 for curline in range(i,j):
1425 found = document.body[curline].find("\\xymatrix@!")
1430 has_equal_spacing = True
1431 content = [document.body[i][21:]]
1432 content += document.body[i+1:j]
1433 subst = put_cmd_in_ert(content)
1434 document.body[i:j+1] = subst
1437 for curline in range(i,j):
1438 l = document.body[curline].find("\\xymatrix")
1440 has_preamble = True;
1443 if has_equal_spacing and not has_preamble:
1444 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1447 def revert_notefontcolor(document):
1448 " Reverts greyed-out note font color to preamble code "
1452 i = find_token(document.header, "\\notefontcolor", i)
1455 colorcode = get_value(document.header, '\\notefontcolor', 0)
1456 del document.header[i]
1457 # the color code is in the form #rrggbb where every character denotes a hex number
1458 # convert the string to an int
1459 red = string.atoi(colorcode[1:3],16)
1460 # we want the output "0.5" for the value "127" therefore increment here
1463 redout = float(red) / 256
1464 green = string.atoi(colorcode[3:5],16)
1467 greenout = float(green) / 256
1468 blue = string.atoi(colorcode[5:7],16)
1471 blueout = float(blue) / 256
1472 # write the preamble
1473 insert_to_preamble(0, document,
1474 '% Commands inserted by lyx2lyx to set the font color\n'
1475 '% for greyed-out notes\n'
1476 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1477 + '\\definecolor{note_fontcolor}{rgb}{'
1478 + str(redout) + ', ' + str(greenout)
1479 + ', ' + str(blueout) + '}\n'
1480 + '\\renewenvironment{lyxgreyedout}\n'
1481 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1484 def revert_turkmen(document):
1485 "Set language Turkmen to English"
1487 if document.language == "turkmen":
1488 document.language = "english"
1489 i = find_token(document.header, "\\language", 0)
1491 document.header[i] = "\\language english"
1494 j = find_token(document.body, "\\lang turkmen", j)
1497 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1501 def revert_fontcolor(document):
1502 " Reverts font color to preamble code "
1506 i = find_token(document.header, "\\fontcolor", i)
1509 colorcode = get_value(document.header, '\\fontcolor', 0)
1510 del document.header[i]
1511 # don't clutter the preamble if backgroundcolor is not set
1512 if colorcode == "#000000":
1514 # the color code is in the form #rrggbb where every character denotes a hex number
1515 # convert the string to an int
1516 red = string.atoi(colorcode[1:3],16)
1517 # we want the output "0.5" for the value "127" therefore add here
1520 redout = float(red) / 256
1521 green = string.atoi(colorcode[3:5],16)
1524 greenout = float(green) / 256
1525 blue = string.atoi(colorcode[5:7],16)
1528 blueout = float(blue) / 256
1529 # write the preamble
1530 insert_to_preamble(0, document,
1531 '% Commands inserted by lyx2lyx to set the font color\n'
1532 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1533 + '\\definecolor{document_fontcolor}{rgb}{'
1534 + str(redout) + ', ' + str(greenout)
1535 + ', ' + str(blueout) + '}\n'
1536 + '\\color{document_fontcolor}\n')
1539 def revert_shadedboxcolor(document):
1540 " Reverts shaded box color to preamble code "
1544 i = find_token(document.header, "\\boxbgcolor", i)
1547 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1548 del document.header[i]
1549 # the color code is in the form #rrggbb where every character denotes a hex number
1550 # convert the string to an int
1551 red = string.atoi(colorcode[1:3],16)
1552 # we want the output "0.5" for the value "127" therefore increment here
1555 redout = float(red) / 256
1556 green = string.atoi(colorcode[3:5],16)
1559 greenout = float(green) / 256
1560 blue = string.atoi(colorcode[5:7],16)
1563 blueout = float(blue) / 256
1564 # write the preamble
1565 insert_to_preamble(0, document,
1566 '% Commands inserted by lyx2lyx to set the color\n'
1567 '% of boxes with shaded background\n'
1568 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1569 + '\\definecolor{shadecolor}{rgb}{'
1570 + str(redout) + ', ' + str(greenout)
1571 + ', ' + str(blueout) + '}\n')
1574 def revert_lyx_version(document):
1575 " Reverts LyX Version information from Inset Info "
1576 version = "LyX version"
1578 import lyx2lyx_version
1579 version = lyx2lyx_version.version
1585 i = find_token(document.body, '\\begin_inset Info', i)
1588 j = find_end_of_inset(document.body, i + 1)
1591 document.warning("Malformed LyX document: Could not find end of Info inset.")
1597 # but we shall try to be forgiving.
1599 for k in range(i, j):
1600 if document.body[k].startswith("arg"):
1601 arg = document.body[k][3:].strip().strip('"')
1602 if document.body[k].startswith("type"):
1603 typ = document.body[k][4:].strip().strip('"')
1604 if arg != "version" or typ != "lyxinfo":
1608 # We do not actually know the version of LyX used to produce the document.
1609 # But we can use our version, since we are reverting.
1611 # Now we want to check if the line after "\end_inset" is empty. It normally
1612 # is, so we want to remove it, too.
1614 if document.body[j+1].strip() == "":
1616 document.body[i: lastline] = s
1620 def revert_math_scale(document):
1621 " Remove math scaling and LaTeX options "
1622 i = find_token(document.header, '\\html_math_img_scale', 0)
1624 del document.header[i]
1625 i = find_token(document.header, '\\html_latex_start', 0)
1627 del document.header[i]
1628 i = find_token(document.header, '\\html_latex_end', 0)
1630 del document.header[i]
1633 def revert_pagesizes(document):
1635 " Revert page sizes to default "
1636 i = find_token(document.header, '\\papersize', 0)
1638 size = document.header[i][11:]
1639 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1640 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1641 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1642 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1643 or size == "b5j" or size == "b6j":
1644 del document.header[i]
1647 def convert_html_quotes(document):
1648 " Remove quotes around html_latex_start and html_latex_end "
1650 i = find_token(document.header, '\\html_latex_start', 0)
1652 line = document.header[i]
1653 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1656 document.header[i] = "\\html_latex_start " + m.group(1)
1658 i = find_token(document.header, '\\html_latex_end', 0)
1660 line = document.header[i]
1661 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1664 document.header[i] = "\\html_latex_end " + m.group(1)
1667 def revert_html_quotes(document):
1668 " Remove quotes around html_latex_start and html_latex_end "
1670 i = find_token(document.header, '\\html_latex_start', 0)
1672 line = document.header[i]
1673 l = re.compile(r'\\html_latex_start\s+(.*)')
1675 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1677 i = find_token(document.header, '\\html_latex_end', 0)
1679 line = document.header[i]
1680 l = re.compile(r'\\html_latex_end\s+(.*)')
1682 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1685 def revert_output_sync(document):
1686 " Remove forward search options "
1687 i = find_token(document.header, '\\output_sync_macro', 0)
1689 del document.header[i]
1690 i = find_token(document.header, '\\output_sync', 0)
1692 del document.header[i]
1695 def convert_beamer_args(document):
1696 " Convert ERT arguments in Beamer to InsetArguments "
1698 if document.textclass != "beamer" and document.textclass != "article-beamer":
1701 layouts = ("Block", "ExampleBlock", "AlertBlock")
1702 for layout in layouts:
1705 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1708 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1710 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1713 bert = find_token(document.body, '\\begin_inset ERT', blay)
1715 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1718 eert = find_end_of_inset(document.body, bert)
1720 document.warning("Malformed LyX document: Can't find end of ERT.")
1724 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1725 # an argument inset.
1726 # Do the end first, so as not to mess up the variables.
1727 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1728 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1729 '\\begin_layout Plain Layout']
1733 def revert_beamer_args(document):
1734 " Revert Beamer arguments to ERT "
1736 if document.textclass != "beamer" and document.textclass != "article-beamer":
1739 layouts = ("Block", "ExampleBlock", "AlertBlock")
1740 for layout in layouts:
1743 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1746 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1748 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1751 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1753 # it is legal not to have one of these
1756 eopt = find_end_of_inset(document.body, bopt)
1758 document.warning("Malformed LyX document: Can't find end of argument.")
1761 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1763 document.warning("Malformed LyX document: Can't find plain layout.")
1766 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1768 document.warning("Malformed LyX document: Can't find end of plain layout.")
1771 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1775 document.warning(str(bcont) + " " + str(eplay))
1778 # we convert the content of the argument into pure LaTeX...
1779 content = lyx2latex(document, document.body[bcont:eplay])
1780 strlist = put_cmd_in_ert(["{" + content + "}"])
1782 # now replace the optional argument with the ERT
1783 document.body[bopt:eopt + 1] = strlist
1787 def revert_align_decimal(document):
1790 l = document.body[l].find('alignment=decimal')
1793 remove_option(document, l, 'decimal_point')
1794 document.body[l].replace('decimal', 'center')
1797 def convert_optarg(document):
1798 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1801 i = find_token(document.body, '\\begin_inset OptArg', i)
1804 document.body[i] = "\\begin_inset Argument"
1808 def revert_argument(document):
1809 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1812 i = find_token(document.body, '\\begin_inset Argument', i)
1815 document.body[i] = "\\begin_inset OptArg"
1819 def revert_makebox(document):
1820 " Convert \\makebox to TeX code "
1823 # only revert frameless boxes without an inner box
1824 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1827 z = find_end_of_inset(document.body, i)
1829 document.warning("Malformed LyX document: Can't find end of box inset.")
1831 j = find_token(document.body, 'use_makebox 1', i)
1832 # assure we found the makebox of the current box
1833 if j > i + 7 or j == -1:
1835 # remove the \end_inset
1836 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1837 # determine the alignment
1838 k = find_token(document.body, 'hor_pos', j - 4)
1839 align = document.body[k][9]
1840 # determine the width
1841 l = find_token(document.body, 'width "', j + 1)
1842 length = document.body[l][7:]
1843 # remove trailing '"'
1844 length = length[:-1]
1845 # latex_length returns "bool,length"
1846 length = latex_length(length).split(",")[1]
1847 subst = "\\makebox[" + length + "][" \
1849 document.body[i:i + 13] = put_cmd_in_ert(subst)
1853 def revert_IEEEtran(document):
1854 " Convert IEEEtran layouts and styles to TeX code "
1855 if document.textclass != "IEEEtran":
1858 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1859 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1860 revert_layout_command(document, "Special Paper Notice", "\\IEEEspecialpapernotice", 0)
1861 revert_layout_command(document, "After Title Text", "\\IEEEaftertitletext", 0)
1862 revert_layout_command(document, "Page headings", "\\markboth", 0)
1863 revert_layout_command(document, "Publication ID", "\\IEEEpubid", 0)
1864 note = '\\begin_layout Standard\n' \
1865 + '\\begin_inset Note Note\n' \
1866 + 'status open\n\n' \
1867 + '\\begin_layout Plain Layout\n\n' \
1868 + '\series bold\n' \
1869 + 'IMPORTANT NOTICE!!!:\n' \
1870 + '\\series default\n' \
1873 + 'This document was created from a newer LyX version.\n' \
1874 + ' To be able to view/export it with LyX 1.6.x or earlier, the title and author\n' \
1875 + ' must be specified by using TeX code.\n' \
1876 + ' Do not use then the standard title and author environment!\n' \
1877 + '\\end_layout\n\n' \
1878 + '\\end_inset\n\n\n' \
1879 + '\\end_layout\n\n'
1880 # insert a note that title and author must be given in TeX code
1881 document.body.insert(0, note)
1882 # we need to revert title and author to TeX code to set \maketitle correctly
1883 revert_layout_command(document, "Title", "\\title", 0)
1884 revert_layout_command(document, "Author", "\\author", 0)
1885 # write \markboth code to the preamble
1886 insert_to_preamble(0, document,
1887 '% Commands inserted by lyx2lyx\n'
1888 + '% protect \\markboth against an old bug reintroduced in babel >= 3.8g\n'
1889 + '\\let\\oldforeign@language\\foreign@language\n'
1890 + '\\DeclareRobustCommand{\\foreign@language}[1]{%\n'
1891 + ' \\lowercase{\\oldforeign@language{#1}}}\n')
1893 y = find_token(document.body, '\\begin_layout Abstract', 0)
1895 document.warning("Malformed LyX document: Can't find abstract of IEEEtran paper.")
1897 maketitle = ['\\begin_layout Standard\n', \
1898 '\\begin_inset ERT\n', \
1899 'status collapsed\n', \
1900 '\\begin_layout Plain Layout\n', \
1906 document.body[y:y] = maketitle
1913 supported_versions = ["2.0.0","2.0"]
1914 convert = [[346, []],
1920 [352, [convert_splitindex]],
1927 [359, [convert_nomencl_width]],
1937 [369, [convert_author_id]],
1941 [373, [merge_gbrief]],
1947 [379, [convert_math_output]],
1957 [389, [convert_html_quotes]],
1960 [392, [convert_beamer_args]],
1961 [393, [convert_optarg]],
1965 revert = [[393, [revert_makebox]],
1966 [392, [revert_argument]],
1967 [391, [revert_beamer_args]],
1968 [390, [revert_align_decimal, revert_IEEEtran]],
1969 [389, [revert_output_sync]],
1970 [388, [revert_html_quotes]],
1971 [387, [revert_pagesizes]],
1972 [386, [revert_math_scale]],
1973 [385, [revert_lyx_version]],
1974 [384, [revert_shadedboxcolor]],
1975 [383, [revert_fontcolor]],
1976 [382, [revert_turkmen]],
1977 [381, [revert_notefontcolor]],
1978 [380, [revert_equalspacing_xymatrix]],
1979 [379, [revert_inset_preview]],
1980 [378, [revert_math_output]],
1982 [376, [revert_multirow]],
1983 [375, [revert_includeall]],
1984 [374, [revert_includeonly]],
1985 [373, [revert_html_options]],
1986 [372, [revert_gbrief]],
1987 [371, [revert_fontenc]],
1988 [370, [revert_mhchem]],
1989 [369, [revert_suppress_date]],
1990 [368, [revert_author_id]],
1991 [367, [revert_hspace_glue_lengths]],
1992 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1993 [365, [revert_percent_skip_lengths]],
1994 [364, [revert_paragraph_indentation]],
1995 [363, [revert_branch_filename]],
1996 [362, [revert_longtable_align]],
1997 [361, [revert_applemac]],
1999 [359, [revert_nomencl_cwidth]],
2000 [358, [revert_nomencl_width]],
2001 [357, [revert_custom_processors]],
2002 [356, [revert_ulinelatex]],
2004 [354, [revert_strikeout]],
2005 [353, [revert_printindexall]],
2006 [352, [revert_subindex]],
2007 [351, [revert_splitindex]],
2008 [350, [revert_backgroundcolor]],
2009 [349, [revert_outputformat]],
2010 [348, [revert_xetex]],
2011 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2012 [346, [revert_tabularvalign]],
2013 [345, [revert_swiss]]
2017 if __name__ == "__main__":