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
159 for curline in range(len(lines)):
160 line = lines[curline]
161 if line.startswith("\\begin_inset ERT"):
162 # We don't want to replace things inside ERT, so figure out
163 # where the end of the inset is.
164 ert_end = find_end_of_inset(lines, curline + 1)
166 elif line.startswith("\\begin_inset Formula"):
168 elif line.startswith("\\begin_inset Quotes"):
169 # For now, we do a very basic reversion. Someone who understands
170 # quotes is welcome to fix it up.
171 qtype = line[20:].strip()
185 elif line.startswith("\\begin_inset Note Note"):
186 # We want to skip LyX notes, so remember where the inset ends
187 note_end = find_end_of_inset(lines, curline + 1)
189 elif line.isspace() or \
190 line.startswith("\\begin_layout") or \
191 line.startswith("\\end_layout") or \
192 line.startswith("\\begin_inset") or \
193 line.startswith("\\end_inset") or \
194 line.startswith("\\lang") or \
195 line.strip() == "status collapsed" or \
196 line.strip() == "status open":
201 if note_end >= curline:
204 # this needs to be added to the preamble because of cases like
205 # \textmu, \textbackslash, etc.
206 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
207 '\\@ifundefined{textmu}',
208 ' {\\usepackage{textcomp}}{}'])
209 # a lossless reversion is not possible
210 # try at least to handle some common insets and settings
211 if ert_end >= curline:
212 line = line.replace(r'\backslash', r'\\')
214 line = line.replace('&', '\\&{}')
215 line = line.replace('#', '\\#{}')
216 line = line.replace('^', '\\^{}')
217 line = line.replace('%', '\\%{}')
218 line = line.replace('_', '\\_{}')
219 line = line.replace('$', '\\${}')
221 # Do the LyX text --> LaTeX conversion
222 for rep in unicode_reps:
223 line = line.replace(rep[1], rep[0] + "{}")
224 line = line.replace(r'\backslash', r'\textbackslash{}')
225 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
226 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
227 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
228 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
229 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
230 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
231 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
232 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
233 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
238 def latex_length(string):
239 'Convert lengths to their LaTeX representation.'
242 # the string has the form
243 # ValueUnit+ValueUnit-ValueUnit or
244 # ValueUnit+-ValueUnit
245 # the + and - (glue lengths) are optional
246 # the + always precedes the -
248 # Convert relative lengths to LaTeX units
249 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
250 "page%":"\\paperwidth", "line%":"\\linewidth",
251 "theight%":"\\textheight", "pheight%":"\\paperheight"}
252 for unit in units.keys():
253 i = string.find(unit)
256 minus = string.rfind("-", 1, i)
257 plus = string.rfind("+", 0, i)
258 latex_unit = units[unit]
259 if plus == -1 and minus == -1:
261 value = str(float(value)/100)
262 end = string[i + len(unit):]
263 string = value + latex_unit + end
265 value = string[plus+1:i]
266 value = str(float(value)/100)
267 begin = string[:plus+1]
268 end = string[i+len(unit):]
269 string = begin + value + latex_unit + end
271 value = string[minus+1:i]
272 value = str(float(value)/100)
273 begin = string[:minus+1]
274 string = begin + value + latex_unit
276 # replace + and -, but only if the - is not the first character
277 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
278 # handle the case where "+-1mm" was used, because LaTeX only understands
279 # "plus 1mm minus 1mm"
280 if string.find("plus minus"):
281 lastvaluepos = string.rfind(" ")
282 lastvalue = string[lastvaluepos:]
283 string = string.replace(" ", lastvalue + " ")
285 return "False," + string
287 return "True," + string
290 def revert_flex_inset(document, name, LaTeXname, position):
291 " Convert flex insets to TeX code "
294 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
297 z = find_end_of_inset(document.body, i)
299 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
301 # remove the \end_inset
302 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
303 # we need to reset character layouts if necessary
304 j = find_token(document.body, '\\emph on', i)
305 k = find_token(document.body, '\\noun on', i)
306 l = find_token(document.body, '\\series', i)
307 m = find_token(document.body, '\\family', i)
308 n = find_token(document.body, '\\shape', i)
309 o = find_token(document.body, '\\color', i)
310 p = find_token(document.body, '\\size', i)
311 q = find_token(document.body, '\\bar under', i)
312 r = find_token(document.body, '\\uuline on', i)
313 s = find_token(document.body, '\\uwave on', i)
314 t = find_token(document.body, '\\strikeout on', i)
315 if j != -1 and j < z:
316 document.body.insert(z-2, "\\emph default")
317 if k != -1 and k < z:
318 document.body.insert(z-2, "\\noun default")
319 if l != -1 and l < z:
320 document.body.insert(z-2, "\\series default")
321 if m != -1 and m < z:
322 document.body.insert(z-2, "\\family default")
323 if n != -1 and n < z:
324 document.body.insert(z-2, "\\shape default")
325 if o != -1 and o < z:
326 document.body.insert(z-2, "\\color inherit")
327 if p != -1 and p < z:
328 document.body.insert(z-2, "\\size default")
329 if q != -1 and q < z:
330 document.body.insert(z-2, "\\bar default")
331 if r != -1 and r < z:
332 document.body.insert(z-2, "\\uuline default")
333 if s != -1 and s < z:
334 document.body.insert(z-2, "\\uwave default")
335 if t != -1 and t < z:
336 document.body.insert(z-2, "\\strikeout default")
337 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
341 def revert_charstyles(document, name, LaTeXname, changed):
342 " Reverts character styles to TeX code "
345 i = find_token(document.body, name + ' on', i)
348 j = find_token(document.body, name + ' default', i)
349 k = find_token(document.body, name + ' on', i + 1)
350 # if there is no default set, the style ends with the layout
351 # assure hereby that we found the correct layout end
352 if j != -1 and (j < k or k == -1):
353 document.body[j:j+1] = put_cmd_in_ert("}")
355 j = find_token(document.body, '\\end_layout', i)
356 document.body[j:j] = put_cmd_in_ert("}")
357 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
362 def revert_layout_command(document, name, LaTeXname, position):
363 " Reverts a command from a layout to TeX code "
366 i = find_token(document.body, '\\begin_layout ' + name, i)
370 # find the next layout
373 j = find_token(document.body, '\\begin_layout', j)
374 l = len(document.body)
375 # if nothing was found it was the last layout of the document
377 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
379 # exclude plain layout because this can be TeX code or another inset
380 elif document.body[j] != '\\begin_layout Plain Layout':
381 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
385 document.body[i] = '\\begin_layout Standard'
386 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
390 ####################################################################
393 def revert_swiss(document):
394 " Set language german-ch to ngerman "
396 if document.language == "german-ch":
397 document.language = "ngerman"
398 i = find_token(document.header, "\\language", 0)
400 document.header[i] = "\\language ngerman"
403 j = find_token(document.body, "\\lang german-ch", j)
406 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
410 def revert_tabularvalign(document):
411 " Revert the tabular valign option "
414 i = find_token(document.body, "\\begin_inset Tabular", i)
417 j = find_token(document.body, "</cell>", i)
419 document.warning("Malformed LyX document: Could not find end of tabular cell.")
422 # don't set a box for longtables, only delete tabularvalignment
423 # the alignment is 2 lines below \\begin_inset Tabular
424 p = document.body[i+2].find("islongtable")
426 q = document.body[i+2].find("tabularvalignment")
428 document.body[i+2] = document.body[i+2][:q-1]
429 document.body[i+2] = document.body[i+2] + '>'
434 tabularvalignment = 'c'
435 # which valignment is specified?
436 m = document.body[i+2].find('tabularvalignment="top"')
438 tabularvalignment = 't'
439 m = document.body[i+2].find('tabularvalignment="bottom"')
441 tabularvalignment = 'b'
442 # delete tabularvalignment
443 q = document.body[i+2].find("tabularvalignment")
445 document.body[i+2] = document.body[i+2][:q-1]
446 document.body[i+2] = document.body[i+2] + '>'
448 # don't add a box when centered
449 if tabularvalignment == 'c':
452 subst = ['\\end_layout', '\\end_inset']
453 document.body[j:j] = subst # just inserts those lines
454 subst = ['\\begin_inset Box Frameless',
455 'position "' + tabularvalignment +'"',
460 # we don't know the width, assume 50%
464 'height_special "totalheight"',
467 '\\begin_layout Plain Layout']
468 document.body[i:i] = subst # this just inserts the array at i
469 i += len(subst) + 2 # adjust i to save a few cycles
472 def revert_phantom(document):
473 " Reverts phantom to ERT "
477 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
480 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
481 '\\begin_inset ERT\nstatus collapsed\n\n' \
482 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
483 'phantom{\n\\end_layout\n\n\\end_inset\n')
484 substi = substi.split('\n')
485 document.body[i : i+4] = substi
487 j = find_token(document.body, "\\end_layout", i)
489 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
491 substj = document.body[j].replace('\\end_layout', \
492 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
493 '\\begin_layout Plain Layout\n\n' \
494 '}\n\\end_layout\n\n\\end_inset\n')
495 substj = substj.split('\n')
496 document.body[j : j+4] = substj
500 def revert_hphantom(document):
501 " Reverts hphantom to ERT "
505 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
508 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
509 '\\begin_inset ERT\nstatus collapsed\n\n' \
510 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
511 'hphantom{\n\\end_layout\n\n\\end_inset\n')
512 substi = substi.split('\n')
513 document.body[i : i+4] = substi
515 j = find_token(document.body, "\\end_layout", i)
517 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
519 substj = document.body[j].replace('\\end_layout', \
520 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
521 '\\begin_layout Plain Layout\n\n' \
522 '}\n\\end_layout\n\n\\end_inset\n')
523 substj = substj.split('\n')
524 document.body[j : j+4] = substj
528 def revert_vphantom(document):
529 " Reverts vphantom to ERT "
533 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
536 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
537 '\\begin_inset ERT\nstatus collapsed\n\n' \
538 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
539 'vphantom{\n\\end_layout\n\n\\end_inset\n')
540 substi = substi.split('\n')
541 document.body[i : i+4] = substi
543 j = find_token(document.body, "\\end_layout", i)
545 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
547 substj = document.body[j].replace('\\end_layout', \
548 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
549 '\\begin_layout Plain Layout\n\n' \
550 '}\n\\end_layout\n\n\\end_inset\n')
551 substj = substj.split('\n')
552 document.body[j : j+4] = substj
556 def revert_xetex(document):
557 " Reverts documents that use XeTeX "
558 i = find_token(document.header, '\\use_xetex', 0)
560 document.warning("Malformed LyX document: Missing \\use_xetex.")
562 if get_value(document.header, "\\use_xetex", i) == 'false':
563 del document.header[i]
565 del document.header[i]
566 # 1.) set doc encoding to utf8-plain
567 i = find_token(document.header, "\\inputencoding", 0)
569 document.warning("Malformed LyX document: Missing \\inputencoding.")
570 document.header[i] = "\\inputencoding utf8-plain"
571 # 2.) check font settings
572 l = find_token(document.header, "\\font_roman", 0)
574 document.warning("Malformed LyX document: Missing \\font_roman.")
575 line = document.header[l]
576 l = re.compile(r'\\font_roman (.*)$')
579 l = find_token(document.header, "\\font_sans", 0)
581 document.warning("Malformed LyX document: Missing \\font_sans.")
582 line = document.header[l]
583 l = re.compile(r'\\font_sans (.*)$')
586 l = find_token(document.header, "\\font_typewriter", 0)
588 document.warning("Malformed LyX document: Missing \\font_typewriter.")
589 line = document.header[l]
590 l = re.compile(r'\\font_typewriter (.*)$')
592 typewriter = m.group(1)
593 osf = get_value(document.header, '\\font_osf', 0) == "true"
594 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
595 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
596 # 3.) set preamble stuff
597 pretext = '%% This document must be processed with xelatex!\n'
598 pretext += '\\usepackage{fontspec}\n'
599 if roman != "default":
600 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
601 if sans != "default":
602 pretext += '\\setsansfont['
604 pretext += 'Scale=' + str(sf_scale / 100) + ','
605 pretext += 'Mapping=tex-text]{' + sans + '}\n'
606 if typewriter != "default":
607 pretext += '\\setmonofont'
609 pretext += '[Scale=' + str(tt_scale / 100) + ']'
610 pretext += '{' + typewriter + '}\n'
612 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
613 pretext += '\usepackage{xunicode}\n'
614 pretext += '\usepackage{xltxtra}\n'
615 insert_to_preamble(0, document, pretext)
616 # 4.) reset font settings
617 i = find_token(document.header, "\\font_roman", 0)
619 document.warning("Malformed LyX document: Missing \\font_roman.")
620 document.header[i] = "\\font_roman default"
621 i = find_token(document.header, "\\font_sans", 0)
623 document.warning("Malformed LyX document: Missing \\font_sans.")
624 document.header[i] = "\\font_sans default"
625 i = find_token(document.header, "\\font_typewriter", 0)
627 document.warning("Malformed LyX document: Missing \\font_typewriter.")
628 document.header[i] = "\\font_typewriter default"
629 i = find_token(document.header, "\\font_osf", 0)
631 document.warning("Malformed LyX document: Missing \\font_osf.")
632 document.header[i] = "\\font_osf false"
633 i = find_token(document.header, "\\font_sc", 0)
635 document.warning("Malformed LyX document: Missing \\font_sc.")
636 document.header[i] = "\\font_sc false"
637 i = find_token(document.header, "\\font_sf_scale", 0)
639 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
640 document.header[i] = "\\font_sf_scale 100"
641 i = find_token(document.header, "\\font_tt_scale", 0)
643 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
644 document.header[i] = "\\font_tt_scale 100"
647 def revert_outputformat(document):
648 " Remove default output format param "
649 i = find_token(document.header, '\\default_output_format', 0)
651 document.warning("Malformed LyX document: Missing \\default_output_format.")
653 del document.header[i]
656 def revert_backgroundcolor(document):
657 " Reverts background color to preamble code "
661 i = find_token(document.header, "\\backgroundcolor", i)
664 colorcode = get_value(document.header, '\\backgroundcolor', 0)
665 del document.header[i]
666 # don't clutter the preamble if backgroundcolor is not set
667 if colorcode == "#ffffff":
669 # the color code is in the form #rrggbb where every character denotes a hex number
670 # convert the string to an int
671 red = string.atoi(colorcode[1:3],16)
672 # we want the output "0.5" for the value "127" therefore add here
675 redout = float(red) / 256
676 green = string.atoi(colorcode[3:5],16)
679 greenout = float(green) / 256
680 blue = string.atoi(colorcode[5:7],16)
683 blueout = float(blue) / 256
685 insert_to_preamble(0, document,
686 '% Commands inserted by lyx2lyx to set the background color\n'
687 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
688 + '\\definecolor{page_backgroundcolor}{rgb}{'
689 + str(redout) + ', ' + str(greenout)
690 + ', ' + str(blueout) + '}\n'
691 + '\\pagecolor{page_backgroundcolor}\n')
694 def revert_splitindex(document):
695 " Reverts splitindex-aware documents "
696 i = find_token(document.header, '\\use_indices', 0)
698 document.warning("Malformed LyX document: Missing \\use_indices.")
700 indices = get_value(document.header, "\\use_indices", i)
702 if indices == "true":
703 preamble += "\\usepackage{splitidx}\n"
704 del document.header[i]
707 i = find_token(document.header, "\\index", i)
710 k = find_token(document.header, "\\end_index", i)
712 document.warning("Malformed LyX document: Missing \\end_index.")
714 line = document.header[i]
715 l = re.compile(r'\\index (.*)$')
718 ishortcut = get_value(document.header, '\\shortcut', i, k)
719 if ishortcut != "" and indices == "true":
720 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
721 del document.header[i:k+1]
724 insert_to_preamble(0, document, preamble)
727 i = find_token(document.body, "\\begin_inset Index", i)
730 line = document.body[i]
731 l = re.compile(r'\\begin_inset Index (.*)$')
734 if itype == "idx" or indices == "false":
735 document.body[i] = "\\begin_inset Index"
737 k = find_end_of_inset(document.body, i)
740 content = lyx2latex(document, document.body[i:k])
742 content = content.replace('"', r'\"')
743 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
744 document.body[i:k+1] = subst
748 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
751 k = find_end_of_inset(document.body, i)
752 ptype = get_value(document.body, 'type', i, k).strip('"')
754 j = find_token(document.body, "type", i, k)
756 elif indices == "false":
757 del document.body[i:k+1]
759 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
760 document.body[i:k+1] = subst
764 def convert_splitindex(document):
765 " Converts index and printindex insets to splitindex-aware format "
768 i = find_token(document.body, "\\begin_inset Index", i)
771 document.body[i] = document.body[i].replace("\\begin_inset Index",
772 "\\begin_inset Index idx")
776 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
779 if document.body[i + 1].find('LatexCommand printindex') == -1:
780 document.warning("Malformed LyX document: Incomplete printindex inset.")
782 subst = ["LatexCommand printindex",
784 document.body[i + 1:i + 2] = subst
788 def revert_subindex(document):
789 " Reverts \\printsubindex CommandInset types "
790 i = find_token(document.header, '\\use_indices', 0)
792 document.warning("Malformed LyX document: Missing \\use_indices.")
794 indices = get_value(document.header, "\\use_indices", i)
797 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
800 k = find_end_of_inset(document.body, i)
801 ctype = get_value(document.body, 'LatexCommand', i, k)
802 if ctype != "printsubindex":
805 ptype = get_value(document.body, 'type', i, k).strip('"')
806 if indices == "false":
807 del document.body[i:k+1]
809 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
810 document.body[i:k+1] = subst
814 def revert_printindexall(document):
815 " Reverts \\print[sub]index* CommandInset types "
816 i = find_token(document.header, '\\use_indices', 0)
818 document.warning("Malformed LyX document: Missing \\use_indices.")
820 indices = get_value(document.header, "\\use_indices", i)
823 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
826 k = find_end_of_inset(document.body, i)
827 ctype = get_value(document.body, 'LatexCommand', i, k)
828 if ctype != "printindex*" and ctype != "printsubindex*":
831 if indices == "false":
832 del document.body[i:k+1]
834 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
835 document.body[i:k+1] = subst
839 def revert_strikeout(document):
840 " Reverts \\strikeout character style "
842 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
843 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
844 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
846 insert_to_preamble(0, document,
847 '% Commands inserted by lyx2lyx for proper underlining\n'
848 + '\\PassOptionsToPackage{normalem}{ulem}\n'
849 + '\\usepackage{ulem}\n')
852 def revert_ulinelatex(document):
853 " Reverts \\uline character style "
854 i = find_token(document.body, '\\bar under', 0)
857 insert_to_preamble(0, document,
858 '% Commands inserted by lyx2lyx for proper underlining\n'
859 + '\\PassOptionsToPackage{normalem}{ulem}\n'
860 + '\\usepackage{ulem}\n'
861 + '\\let\\cite@rig\\cite\n'
862 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
863 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
864 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
867 def revert_custom_processors(document):
868 " Remove bibtex_command and index_command params "
869 i = find_token(document.header, '\\bibtex_command', 0)
871 document.warning("Malformed LyX document: Missing \\bibtex_command.")
873 del document.header[i]
874 i = find_token(document.header, '\\index_command', 0)
876 document.warning("Malformed LyX document: Missing \\index_command.")
878 del document.header[i]
881 def convert_nomencl_width(document):
882 " Add set_width param to nomencl_print "
885 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
888 document.body.insert(i + 2, "set_width \"none\"")
892 def revert_nomencl_width(document):
893 " Remove set_width param from nomencl_print "
896 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
899 j = find_end_of_inset(document.body, i)
900 l = find_token(document.body, "set_width", i, j)
902 document.warning("Can't find set_width option for nomencl_print!")
909 def revert_nomencl_cwidth(document):
910 " Remove width param from nomencl_print "
913 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
916 j = find_end_of_inset(document.body, i)
917 l = find_token(document.body, "width", i, j)
919 #Can't find width option for nomencl_print
922 width = get_value(document.body, "width", i, j).strip('"')
924 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
925 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
929 def revert_applemac(document):
930 " Revert applemac encoding to auto "
932 if document.encoding == "applemac":
933 document.encoding = "auto"
934 i = find_token(document.header, "\\encoding", 0)
936 document.header[i] = "\\encoding auto"
939 def revert_longtable_align(document):
940 " Remove longtable alignment setting "
944 i = find_token(document.body, "\\begin_inset Tabular", i)
947 # the alignment is 2 lines below \\begin_inset Tabular
948 j = document.body[i+2].find("longtabularalignment")
951 document.body[i+2] = document.body[i+2][:j-1]
952 document.body[i+2] = document.body[i+2] + '>'
956 def revert_branch_filename(document):
957 " Remove \\filename_suffix parameter from branches "
960 i = find_token(document.header, "\\filename_suffix", i)
963 del document.header[i]
966 def revert_paragraph_indentation(document):
967 " Revert custom paragraph indentation to preamble code "
970 i = find_token(document.header, "\\paragraph_indentation", i)
973 # only remove the preamble line if default
974 # otherwise also write the value to the preamble
975 length = get_value(document.header, "\\paragraph_indentation", i)
976 if length == "default":
977 del document.header[i]
980 # handle percent lengths
981 # latex_length returns "bool,length"
982 length = latex_length(length).split(",")[1]
983 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
984 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
985 del document.header[i]
989 def revert_percent_skip_lengths(document):
990 " Revert relative lengths for paragraph skip separation to preamble code "
993 i = find_token(document.header, "\\defskip", i)
996 length = get_value(document.header, "\\defskip", i)
997 # only revert when a custom length was set and when
998 # it used a percent length
999 if length not in ('smallskip', 'medskip', 'bigskip'):
1000 # handle percent lengths
1001 length = latex_length(length)
1002 # latex_length returns "bool,length"
1003 percent = length.split(",")[0]
1004 length = length.split(",")[1]
1005 if percent == "True":
1006 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1007 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
1008 # set defskip to medskip as default
1009 document.header[i] = "\\defskip medskip"
1013 def revert_percent_vspace_lengths(document):
1014 " Revert relative VSpace lengths to ERT "
1017 i = find_token(document.body, "\\begin_inset VSpace", i)
1020 # only revert if a custom length was set and if
1021 # it used a percent length
1022 line = document.body[i]
1023 r = re.compile(r'\\begin_inset VSpace (.*)$')
1026 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1027 # check if the space has a star (protected space)
1028 protected = (document.body[i].rfind("*") != -1)
1030 length = length.rstrip('*')
1031 # handle percent lengths
1032 length = latex_length(length)
1033 # latex_length returns "bool,length"
1034 percent = length.split(",")[0]
1035 length = length.split(",")[1]
1036 # revert the VSpace inset to ERT
1037 if percent == "True":
1039 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1041 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1042 document.body[i:i+2] = subst
1046 def revert_percent_hspace_lengths(document):
1047 " Revert relative HSpace lengths to ERT "
1050 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1053 protected = (document.body[i].find("\\hspace*{}") != -1)
1054 # only revert if a custom length was set and if
1055 # it used a percent length
1056 length = get_value(document.body, '\\length', i+1)
1058 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1060 # handle percent lengths
1061 length = latex_length(length)
1062 # latex_length returns "bool,length"
1063 percent = length.split(",")[0]
1064 length = length.split(",")[1]
1065 # revert the HSpace inset to ERT
1066 if percent == "True":
1068 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1070 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1071 document.body[i:i+3] = subst
1075 def revert_hspace_glue_lengths(document):
1076 " Revert HSpace glue lengths to ERT "
1079 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1082 protected = (document.body[i].find("\\hspace*{}") != -1)
1083 length = get_value(document.body, '\\length', i+1)
1085 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1087 # only revert if the length contains a plus or minus at pos != 0
1088 glue = re.compile(r'.+[\+-]')
1089 if glue.search(length):
1090 # handle percent lengths
1091 # latex_length returns "bool,length"
1092 length = latex_length(length).split(",")[1]
1093 # revert the HSpace inset to ERT
1095 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1097 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1098 document.body[i:i+3] = subst
1101 def convert_author_id(document):
1102 " Add the author_id to the \\author definition and make sure 0 is not used"
1106 i = find_token(document.header, "\\author", i)
1110 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1111 m = r.match(document.header[i])
1116 if m.lastindex == 3:
1118 document.header[i] = "\\author %i %s %s" % (j, name, email)
1124 k = find_token(document.body, "\\change_", k)
1128 change = document.body[k].split(' ');
1129 if len(change) == 3:
1131 author_id = int(change[1])
1133 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1136 def revert_author_id(document):
1137 " Remove the author_id from the \\author definition "
1142 i = find_token(document.header, "\\author", i)
1146 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1147 m = r.match(document.header[i])
1149 author_id = int(m.group(2))
1150 idmap[author_id] = j
1154 if m.lastindex == 4:
1156 document.header[i] = "\\author %s %s" % (name, email)
1162 k = find_token(document.body, "\\change_", k)
1166 change = document.body[k].split(' ');
1167 if len(change) == 3:
1169 author_id = int(change[1])
1171 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1175 def revert_suppress_date(document):
1176 " Revert suppressing of default document date to preamble code "
1179 i = find_token(document.header, "\\suppress_date", i)
1182 # remove the preamble line and write to the preamble
1183 # when suppress_date was true
1184 date = get_value(document.header, "\\suppress_date", i)
1186 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1187 add_to_preamble(document, ["\\date{}"])
1188 del document.header[i]
1192 def revert_mhchem(document):
1193 "Revert mhchem loading to preamble code"
1198 i = find_token(document.header, "\\use_mhchem 1", 0)
1202 i = find_token(document.header, "\\use_mhchem 2", 0)
1205 if mhchem == "auto":
1206 j = find_token(document.body, "\\cf{", 0)
1210 j = find_token(document.body, "\\ce{", 0)
1214 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1215 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1216 add_to_preamble(document, ["\\usepackage{mhchem}"])
1217 k = find_token(document.header, "\\use_mhchem", 0)
1219 document.warning("Malformed LyX document: Could not find mhchem setting.")
1221 del document.header[k]
1224 def revert_fontenc(document):
1225 " Remove fontencoding param "
1226 i = find_token(document.header, '\\fontencoding', 0)
1228 document.warning("Malformed LyX document: Missing \\fontencoding.")
1230 del document.header[i]
1233 def merge_gbrief(document):
1234 " Merge g-brief-en and g-brief-de to one class "
1236 if document.textclass != "g-brief-de":
1237 if document.textclass == "g-brief-en":
1238 document.textclass = "g-brief"
1239 document.set_textclass()
1242 obsoletedby = { "Brieftext": "Letter",
1243 "Unterschrift": "Signature",
1244 "Strasse": "Street",
1245 "Zusatz": "Addition",
1248 "RetourAdresse": "ReturnAddress",
1249 "MeinZeichen": "MyRef",
1250 "IhrZeichen": "YourRef",
1251 "IhrSchreiben": "YourMail",
1254 "Konto": "BankAccount",
1255 "Postvermerk": "PostalComment",
1256 "Adresse": "Address",
1258 "Betreff": "Reference",
1259 "Anrede": "Opening",
1265 i = find_token(document.body, "\\begin_layout", i)
1269 layout = document.body[i][14:]
1270 if layout in obsoletedby:
1271 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1275 document.textclass = "g-brief"
1276 document.set_textclass()
1279 def revert_gbrief(document):
1280 " Revert g-brief to g-brief-en "
1281 if document.textclass == "g-brief":
1282 document.textclass = "g-brief-en"
1283 document.set_textclass()
1286 def revert_html_options(document):
1287 " Remove html options "
1288 i = find_token(document.header, '\\html_use_mathml', 0)
1290 del document.header[i]
1291 i = find_token(document.header, '\\html_be_strict', 0)
1293 del document.header[i]
1296 def revert_includeonly(document):
1299 i = find_token(document.header, "\\begin_includeonly", i)
1302 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1304 # this should not happen
1306 document.header[i : j + 1] = []
1309 def revert_includeall(document):
1310 " Remove maintain_unincluded_children param "
1311 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1313 del document.header[i]
1316 def revert_multirow(document):
1317 " Revert multirow cells in tables "
1321 # cell type 3 is multirow begin cell
1322 i = find_token(document.body, '<cell multirow="3"', i)
1325 # a multirow cell was found
1327 # remove the multirow tag, set the valignment to top
1328 # and remove the bottom line
1329 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1330 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1331 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1332 # write ERT to create the multirow cell
1333 # use 2 rows and 2cm as default with because the multirow span
1334 # and the column width is only hardly accessible
1335 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1336 document.body[i + 4:i + 4] = subst
1337 i = find_token(document.body, "</cell>", i)
1339 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1341 subst = [old_put_cmd_in_ert("}")]
1342 document.body[i - 3:i - 3] = subst
1343 # cell type 4 is multirow part cell
1344 i = find_token(document.body, '<cell multirow="4"', i)
1347 # remove the multirow tag, set the valignment to top
1348 # and remove the top line
1349 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1350 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1351 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1353 if multirow == True:
1354 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1355 add_to_preamble(document, ["\\usepackage{multirow}"])
1358 def convert_math_output(document):
1359 " Convert \html_use_mathml to \html_math_output "
1360 i = find_token(document.header, "\\html_use_mathml", 0)
1363 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1364 m = rgx.match(document.header[i])
1366 newval = "0" # MathML
1369 newval = "2" # Images
1370 document.header[i] = "\\html_math_output " + newval
1373 def revert_math_output(document):
1374 " Revert \html_math_output to \html_use_mathml "
1375 i = find_token(document.header, "\\html_math_output", 0)
1378 rgx = re.compile(r'\\html_math_output\s+(\d)')
1379 m = rgx.match(document.header[i])
1383 if val == "1" or val == "2":
1386 document.warning("Unable to match " + document.header[i])
1387 document.header[i] = "\\html_use_mathml " + newval
1391 def revert_inset_preview(document):
1392 " Dissolves the preview inset "
1397 i = find_token(document.body, "\\begin_inset Preview", i)
1400 j = find_end_of_inset(document.body, i)
1402 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1404 #If the layout is Standard we need to remove it, otherwise there
1405 #will be paragraph breaks that shouldn't be there.
1406 k = find_token(document.body, "\\begin_layout Standard", i)
1408 del document.body[i : i+3]
1409 del document.body[j-5 : j-2]
1412 del document.body[i]
1413 del document.body[j-1]
1417 def revert_equalspacing_xymatrix(document):
1418 " Revert a Formula with xymatrix@! to an ERT inset "
1421 has_preamble = False
1422 has_equal_spacing = False
1425 i = find_token(document.body, "\\begin_inset Formula", i)
1428 j = find_end_of_inset(document.body, i)
1430 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1433 for curline in range(i,j):
1434 found = document.body[curline].find("\\xymatrix@!")
1439 has_equal_spacing = True
1440 content = [document.body[i][21:]]
1441 content += document.body[i+1:j]
1442 subst = put_cmd_in_ert(content)
1443 document.body[i:j+1] = subst
1446 for curline in range(i,j):
1447 l = document.body[curline].find("\\xymatrix")
1449 has_preamble = True;
1452 if has_equal_spacing and not has_preamble:
1453 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1456 def revert_notefontcolor(document):
1457 " Reverts greyed-out note font color to preamble code "
1461 i = find_token(document.header, "\\notefontcolor", i)
1464 colorcode = get_value(document.header, '\\notefontcolor', 0)
1465 del document.header[i]
1466 # the color code is in the form #rrggbb where every character denotes a hex number
1467 # convert the string to an int
1468 red = string.atoi(colorcode[1:3],16)
1469 # we want the output "0.5" for the value "127" therefore increment here
1472 redout = float(red) / 256
1473 green = string.atoi(colorcode[3:5],16)
1476 greenout = float(green) / 256
1477 blue = string.atoi(colorcode[5:7],16)
1480 blueout = float(blue) / 256
1481 # write the preamble
1482 insert_to_preamble(0, document,
1483 '% Commands inserted by lyx2lyx to set the font color\n'
1484 '% for greyed-out notes\n'
1485 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1486 + '\\definecolor{note_fontcolor}{rgb}{'
1487 + str(redout) + ', ' + str(greenout)
1488 + ', ' + str(blueout) + '}\n'
1489 + '\\renewenvironment{lyxgreyedout}\n'
1490 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1493 def revert_turkmen(document):
1494 "Set language Turkmen to English"
1496 if document.language == "turkmen":
1497 document.language = "english"
1498 i = find_token(document.header, "\\language", 0)
1500 document.header[i] = "\\language english"
1503 j = find_token(document.body, "\\lang turkmen", j)
1506 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1510 def revert_fontcolor(document):
1511 " Reverts font color to preamble code "
1515 i = find_token(document.header, "\\fontcolor", i)
1518 colorcode = get_value(document.header, '\\fontcolor', 0)
1519 del document.header[i]
1520 # don't clutter the preamble if backgroundcolor is not set
1521 if colorcode == "#000000":
1523 # the color code is in the form #rrggbb where every character denotes a hex number
1524 # convert the string to an int
1525 red = string.atoi(colorcode[1:3],16)
1526 # we want the output "0.5" for the value "127" therefore add here
1529 redout = float(red) / 256
1530 green = string.atoi(colorcode[3:5],16)
1533 greenout = float(green) / 256
1534 blue = string.atoi(colorcode[5:7],16)
1537 blueout = float(blue) / 256
1538 # write the preamble
1539 insert_to_preamble(0, document,
1540 '% Commands inserted by lyx2lyx to set the font color\n'
1541 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1542 + '\\definecolor{document_fontcolor}{rgb}{'
1543 + str(redout) + ', ' + str(greenout)
1544 + ', ' + str(blueout) + '}\n'
1545 + '\\color{document_fontcolor}\n')
1548 def revert_shadedboxcolor(document):
1549 " Reverts shaded box color to preamble code "
1553 i = find_token(document.header, "\\boxbgcolor", i)
1556 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1557 del document.header[i]
1558 # the color code is in the form #rrggbb where every character denotes a hex number
1559 # convert the string to an int
1560 red = string.atoi(colorcode[1:3],16)
1561 # we want the output "0.5" for the value "127" therefore increment here
1564 redout = float(red) / 256
1565 green = string.atoi(colorcode[3:5],16)
1568 greenout = float(green) / 256
1569 blue = string.atoi(colorcode[5:7],16)
1572 blueout = float(blue) / 256
1573 # write the preamble
1574 insert_to_preamble(0, document,
1575 '% Commands inserted by lyx2lyx to set the color\n'
1576 '% of boxes with shaded background\n'
1577 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1578 + '\\definecolor{shadecolor}{rgb}{'
1579 + str(redout) + ', ' + str(greenout)
1580 + ', ' + str(blueout) + '}\n')
1583 def revert_lyx_version(document):
1584 " Reverts LyX Version information from Inset Info "
1585 version = "LyX version"
1587 import lyx2lyx_version
1588 version = lyx2lyx_version.version
1594 i = find_token(document.body, '\\begin_inset Info', i)
1597 j = find_end_of_inset(document.body, i + 1)
1600 document.warning("Malformed LyX document: Could not find end of Info inset.")
1606 # but we shall try to be forgiving.
1608 for k in range(i, j):
1609 if document.body[k].startswith("arg"):
1610 arg = document.body[k][3:].strip().strip('"')
1611 if document.body[k].startswith("type"):
1612 typ = document.body[k][4:].strip().strip('"')
1613 if arg != "version" or typ != "lyxinfo":
1617 # We do not actually know the version of LyX used to produce the document.
1618 # But we can use our version, since we are reverting.
1620 # Now we want to check if the line after "\end_inset" is empty. It normally
1621 # is, so we want to remove it, too.
1623 if document.body[j+1].strip() == "":
1625 document.body[i: lastline] = s
1629 def revert_math_scale(document):
1630 " Remove math scaling and LaTeX options "
1631 i = find_token(document.header, '\\html_math_img_scale', 0)
1633 del document.header[i]
1634 i = find_token(document.header, '\\html_latex_start', 0)
1636 del document.header[i]
1637 i = find_token(document.header, '\\html_latex_end', 0)
1639 del document.header[i]
1642 def revert_pagesizes(document):
1644 " Revert page sizes to default "
1645 i = find_token(document.header, '\\papersize', 0)
1647 size = document.header[i][11:]
1648 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1649 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1650 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1651 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1652 or size == "b5j" or size == "b6j":
1653 del document.header[i]
1656 def convert_html_quotes(document):
1657 " Remove quotes around html_latex_start and html_latex_end "
1659 i = find_token(document.header, '\\html_latex_start', 0)
1661 line = document.header[i]
1662 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1665 document.header[i] = "\\html_latex_start " + m.group(1)
1667 i = find_token(document.header, '\\html_latex_end', 0)
1669 line = document.header[i]
1670 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1673 document.header[i] = "\\html_latex_end " + m.group(1)
1676 def revert_html_quotes(document):
1677 " Remove quotes around html_latex_start and html_latex_end "
1679 i = find_token(document.header, '\\html_latex_start', 0)
1681 line = document.header[i]
1682 l = re.compile(r'\\html_latex_start\s+(.*)')
1684 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1686 i = find_token(document.header, '\\html_latex_end', 0)
1688 line = document.header[i]
1689 l = re.compile(r'\\html_latex_end\s+(.*)')
1691 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1694 def revert_output_sync(document):
1695 " Remove forward search options "
1696 i = find_token(document.header, '\\output_sync_macro', 0)
1698 del document.header[i]
1699 i = find_token(document.header, '\\output_sync', 0)
1701 del document.header[i]
1704 def convert_beamer_args(document):
1705 " Convert ERT arguments in Beamer to InsetArguments "
1707 if document.textclass != "beamer" and document.textclass != "article-beamer":
1710 layouts = ("Block", "ExampleBlock", "AlertBlock")
1711 for layout in layouts:
1714 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1717 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1719 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1722 bert = find_token(document.body, '\\begin_inset ERT', blay)
1724 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1727 eert = find_end_of_inset(document.body, bert)
1729 document.warning("Malformed LyX document: Can't find end of ERT.")
1733 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1734 # an argument inset.
1735 # Do the end first, so as not to mess up the variables.
1736 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1737 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1738 '\\begin_layout Plain Layout']
1742 def revert_beamer_args(document):
1743 " Revert Beamer arguments to ERT "
1745 if document.textclass != "beamer" and document.textclass != "article-beamer":
1748 layouts = ("Block", "ExampleBlock", "AlertBlock")
1749 for layout in layouts:
1752 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1755 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1757 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1760 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1762 # it is legal not to have one of these
1765 eopt = find_end_of_inset(document.body, bopt)
1767 document.warning("Malformed LyX document: Can't find end of argument.")
1770 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1772 document.warning("Malformed LyX document: Can't find plain layout.")
1775 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1777 document.warning("Malformed LyX document: Can't find end of plain layout.")
1780 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1784 document.warning(str(bcont) + " " + str(eplay))
1787 # we convert the content of the argument into pure LaTeX...
1788 content = lyx2latex(document, document.body[bcont:eplay])
1789 strlist = put_cmd_in_ert(["{" + content + "}"])
1791 # now replace the optional argument with the ERT
1792 document.body[bopt:eopt + 1] = strlist
1796 def revert_align_decimal(document):
1799 l = document.body[l].find('alignment=decimal')
1802 remove_option(document, l, 'decimal_point')
1803 document.body[l].replace('decimal', 'center')
1806 def convert_optarg(document):
1807 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1810 i = find_token(document.body, '\\begin_inset OptArg', i)
1813 document.body[i] = "\\begin_inset Argument"
1817 def revert_argument(document):
1818 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1821 i = find_token(document.body, '\\begin_inset Argument', i)
1824 document.body[i] = "\\begin_inset OptArg"
1828 def revert_makebox(document):
1829 " Convert \\makebox to TeX code "
1832 # only revert frameless boxes without an inner box
1833 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1836 z = find_end_of_inset(document.body, i)
1838 document.warning("Malformed LyX document: Can't find end of box inset.")
1840 j = find_token(document.body, 'use_makebox 1', i)
1841 # assure we found the makebox of the current box
1842 if j > z or j == -1:
1844 y = find_token(document.body, "\\begin_layout", i)
1845 if y > z or y == -1:
1846 document.warning("Malformed LyX document: Can't find layout in box.")
1848 # remove the \end_layout \end_inset pair
1849 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1850 # determine the alignment
1851 k = find_token(document.body, 'hor_pos', j - 4)
1852 align = document.body[k][9]
1853 # determine the width
1854 l = find_token(document.body, 'width "', j + 1)
1855 length = document.body[l][7:]
1856 # remove trailing '"'
1857 length = length[:-1]
1858 # latex_length returns "bool,length"
1859 length = latex_length(length).split(",")[1]
1860 subst = "\\makebox[" + length + "][" \
1862 document.body[i:y+1] = put_cmd_in_ert(subst)
1866 def revert_IEEEtran(document):
1867 " Convert IEEEtran layouts and styles to TeX code "
1868 if document.textclass != "IEEEtran":
1871 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1872 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1874 layouts = ("Special Paper Notice", "After Title Text", "Publication ID",
1875 "Page headings", "Biography without photo")
1877 latexcmd = {"Special Paper Notice": "\\IEEEspecialpapernotice",
1878 "After Title Text": "\\IEEEaftertitletext",
1879 "Publication ID": "\\IEEEpubid"}
1881 obsoletedby = {"Page headings": "MarkBoth",
1882 "Biography without photo": "BiographyNoPhoto"}
1884 for layout in layouts:
1887 i = find_token(document.body, '\\begin_layout ' + layout, i)
1890 j = find_end_of(document.body, i, '\\begin_layout', '\\end_layout')
1892 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1895 if layout in obsoletedby:
1896 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1899 content = lyx2latex(document, document.body[i:j+1])
1900 add_to_preamble(document, [latexcmd[layout] + "{" + content + "}"])
1901 del document.body[i:j+1]
1908 supported_versions = ["2.0.0","2.0"]
1909 convert = [[346, []],
1915 [352, [convert_splitindex]],
1922 [359, [convert_nomencl_width]],
1932 [369, [convert_author_id]],
1936 [373, [merge_gbrief]],
1942 [379, [convert_math_output]],
1952 [389, [convert_html_quotes]],
1955 [392, [convert_beamer_args]],
1956 [393, [convert_optarg]],
1960 revert = [[393, [revert_makebox]],
1961 [392, [revert_argument]],
1962 [391, [revert_beamer_args]],
1963 [390, [revert_align_decimal, revert_IEEEtran]],
1964 [389, [revert_output_sync]],
1965 [388, [revert_html_quotes]],
1966 [387, [revert_pagesizes]],
1967 [386, [revert_math_scale]],
1968 [385, [revert_lyx_version]],
1969 [384, [revert_shadedboxcolor]],
1970 [383, [revert_fontcolor]],
1971 [382, [revert_turkmen]],
1972 [381, [revert_notefontcolor]],
1973 [380, [revert_equalspacing_xymatrix]],
1974 [379, [revert_inset_preview]],
1975 [378, [revert_math_output]],
1977 [376, [revert_multirow]],
1978 [375, [revert_includeall]],
1979 [374, [revert_includeonly]],
1980 [373, [revert_html_options]],
1981 [372, [revert_gbrief]],
1982 [371, [revert_fontenc]],
1983 [370, [revert_mhchem]],
1984 [369, [revert_suppress_date]],
1985 [368, [revert_author_id]],
1986 [367, [revert_hspace_glue_lengths]],
1987 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1988 [365, [revert_percent_skip_lengths]],
1989 [364, [revert_paragraph_indentation]],
1990 [363, [revert_branch_filename]],
1991 [362, [revert_longtable_align]],
1992 [361, [revert_applemac]],
1994 [359, [revert_nomencl_cwidth]],
1995 [358, [revert_nomencl_width]],
1996 [357, [revert_custom_processors]],
1997 [356, [revert_ulinelatex]],
1999 [354, [revert_strikeout]],
2000 [353, [revert_printindexall]],
2001 [352, [revert_subindex]],
2002 [351, [revert_splitindex]],
2003 [350, [revert_backgroundcolor]],
2004 [349, [revert_outputformat]],
2005 [348, [revert_xetex]],
2006 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2007 [346, [revert_tabularvalign]],
2008 [345, [revert_swiss]]
2012 if __name__ == "__main__":