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. It returns a
112 # LIST of strings. This is how lyx2lyx works: with a list of strings,
113 # each representing a line of a LyX file. Embedded newlines confuse
115 # For this same reason, we expect as input a LIST of strings, not
116 # something with embedded newlines. That said, if any of your strings
117 # do have embedded newlines, the string will eventually get split on
118 # them and you'll get a list back.
120 # A call to this routine will often go something like this:
121 # i = find_token('\\begin_inset FunkyInset', ...)
123 # j = find_end_of_inset(document.body, i)
124 # content = ...extract content from insets
125 # ert = put_cmd_in_ert(content)
126 # document.body[i:j] = ert
127 # Now, before we continue, we need to reset i appropriately. Normally,
130 # That puts us right after the ERT we just inserted.
131 def put_cmd_in_ert(strlist):
132 ret = ["\\begin_inset ERT", "status collapsed", "\\begin_layout Plain Layout", ""]
133 # Despite the warnings just given, it will be faster for us to work
134 # with a single string internally. That way, we only go through the
135 # unicode_reps loop once.
136 s = "\n".join(strlist)
137 for rep in unicode_reps:
138 s = s.replace(rep[1], rep[0].replace('\\\\', '\\'))
139 s = s.replace('\\', "\\backslash\n")
140 ret += s.splitlines()
141 ret += ["\\end_layout", "\\end_inset"]
145 def lyx2latex(document, lines):
146 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
147 # clean up multiline stuff
151 for curline in range(len(lines)):
152 line = lines[curline]
153 if line.startswith("\\begin_inset ERT"):
154 # We don't want to replace things inside ERT, so figure out
155 # where the end of the inset is.
156 ert_end = find_end_of_inset(lines, curline + 1)
158 elif line.startswith("\\begin_inset Formula"):
160 elif line.startswith("\\begin_inset Quotes"):
161 # For now, we do a very basic reversion. Someone who understands
162 # quotes is welcome to fix it up.
163 qtype = line[20:].strip()
177 elif line.isspace() or \
178 line.startswith("\\begin_layout") or \
179 line.startswith("\\end_layout") or \
180 line.startswith("\\begin_inset") or \
181 line.startswith("\\end_inset") or \
182 line.startswith("\\lang") or \
183 line.strip() == "status collapsed" or \
184 line.strip() == "status open":
188 # this needs to be added to the preamble because of cases like
189 # \textmu, \textbackslash, etc.
190 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
191 '\\@ifundefined{textmu}',
192 ' {\\usepackage{textcomp}}{}'])
193 # a lossless reversion is not possible
194 # try at least to handle some common insets and settings
195 if ert_end >= curline:
196 line = line.replace(r'\backslash', r'\\')
198 line = line.replace('&', '\\&{}')
199 line = line.replace('#', '\\#{}')
200 line = line.replace('^', '\\^{}')
201 line = line.replace('%', '\\%{}')
202 line = line.replace('_', '\\_{}')
203 line = line.replace('$', '\\${}')
205 # Do the LyX text --> LaTeX conversion
206 for rep in unicode_reps:
207 line = line.replace(rep[1], rep[0] + "{}")
208 line = line.replace(r'\backslash', r'\textbackslash{}')
209 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
210 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
211 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
212 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
213 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
214 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
215 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
216 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
217 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
222 def latex_length(string):
223 'Convert lengths to their LaTeX representation.'
226 # the string has the form
227 # ValueUnit+ValueUnit-ValueUnit or
228 # ValueUnit+-ValueUnit
229 # the + and - (glue lengths) are optional
230 # the + always precedes the -
232 # Convert relative lengths to LaTeX units
233 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
234 "page%":"\\paperwidth", "line%":"\\linewidth",
235 "theight%":"\\textheight", "pheight%":"\\paperheight"}
236 for unit in units.keys():
237 i = string.find(unit)
240 minus = string.rfind("-", 1, i)
241 plus = string.rfind("+", 0, i)
242 latex_unit = units[unit]
243 if plus == -1 and minus == -1:
245 value = str(float(value)/100)
246 end = string[i + len(unit):]
247 string = value + latex_unit + end
249 value = string[plus+1:i]
250 value = str(float(value)/100)
251 begin = string[:plus+1]
252 end = string[i+len(unit):]
253 string = begin + value + latex_unit + end
255 value = string[minus+1:i]
256 value = str(float(value)/100)
257 begin = string[:minus+1]
258 string = begin + value + latex_unit
260 # replace + and -, but only if the - is not the first character
261 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
262 # handle the case where "+-1mm" was used, because LaTeX only understands
263 # "plus 1mm minus 1mm"
264 if string.find("plus minus"):
265 lastvaluepos = string.rfind(" ")
266 lastvalue = string[lastvaluepos:]
267 string = string.replace(" ", lastvalue + " ")
269 return "False," + string
271 return "True," + string
274 def revert_flex_inset(document, name, LaTeXname, position):
275 " Convert flex insets to TeX code "
278 i = find_token(document.body, '\\begin_inset Flex ' + name, i)
281 z = find_end_of_inset(document.body, i)
283 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
285 # remove the \end_inset
286 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
287 # we need to reset character layouts if necessary
288 j = find_token(document.body, '\\emph on', i)
289 k = find_token(document.body, '\\noun on', i)
290 l = find_token(document.body, '\\series', i)
291 m = find_token(document.body, '\\family', i)
292 n = find_token(document.body, '\\shape', i)
293 o = find_token(document.body, '\\color', i)
294 p = find_token(document.body, '\\size', i)
295 q = find_token(document.body, '\\bar under', i)
296 r = find_token(document.body, '\\uuline on', i)
297 s = find_token(document.body, '\\uwave on', i)
298 t = find_token(document.body, '\\strikeout on', i)
299 if j != -1 and j < z:
300 document.body.insert(z-2, "\\emph default")
301 if k != -1 and k < z:
302 document.body.insert(z-2, "\\noun default")
303 if l != -1 and l < z:
304 document.body.insert(z-2, "\\series default")
305 if m != -1 and m < z:
306 document.body.insert(z-2, "\\family default")
307 if n != -1 and n < z:
308 document.body.insert(z-2, "\\shape default")
309 if o != -1 and o < z:
310 document.body.insert(z-2, "\\color inherit")
311 if p != -1 and p < z:
312 document.body.insert(z-2, "\\size default")
313 if q != -1 and q < z:
314 document.body.insert(z-2, "\\bar default")
315 if r != -1 and r < z:
316 document.body.insert(z-2, "\\uuline default")
317 if s != -1 and s < z:
318 document.body.insert(z-2, "\\uwave default")
319 if t != -1 and t < z:
320 document.body.insert(z-2, "\\strikeout default")
321 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
325 def revert_charstyles(document, name, LaTeXname, changed):
326 " Reverts character styles to TeX code "
329 i = find_token(document.body, name + ' on', i)
332 j = find_token(document.body, name + ' default', i)
333 k = find_token(document.body, name + ' on', i + 1)
334 # if there is no default set, the style ends with the layout
335 # assure hereby that we found the correct layout end
336 if j != -1 and (j < k or k ==-1):
337 document.body[j:j+1] = put_cmd_in_ert("}")
339 j = find_token(document.body, '\\end_layout', i)
340 document.body[j:j] = put_cmd_in_ert("}")
341 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
346 def revert_layout_command(document, name, LaTeXname, position):
347 " Reverts a command from a layout to TeX code "
350 i = find_token(document.body, '\\begin_layout ' + name, i)
355 # find the next layout
358 j = find_token(document.body, '\\begin_layout', j)
359 l = len(document.body)
360 # if nothing was found it was the last layout of the document
362 document.body[l - 4:l - 4] = put_cmd_in_ert("}")
364 # exclude plain layout because this can be TeX code or another inset
365 elif document.body[j] != '\\begin_layout Plain Layout':
366 document.body[j - 2:j - 2] = put_cmd_in_ert("}")
370 document.body[i] = '\\begin_layout Standard'
371 document.body[i + 1:i + 1] = put_cmd_in_ert(LaTeXname + "{")
375 ####################################################################
378 def revert_swiss(document):
379 " Set language german-ch to ngerman "
381 if document.language == "german-ch":
382 document.language = "ngerman"
383 i = find_token(document.header, "\\language", 0)
385 document.header[i] = "\\language ngerman"
388 j = find_token(document.body, "\\lang german-ch", j)
391 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
395 def revert_tabularvalign(document):
396 " Revert the tabular valign option "
399 i = find_token(document.body, "\\begin_inset Tabular", i)
402 j = find_token(document.body, "</cell>", i)
404 document.warning("Malformed LyX document: Could not find end of tabular cell.")
407 # don't set a box for longtables, only delete tabularvalignment
408 # the alignment is 2 lines below \\begin_inset Tabular
409 p = document.body[i+2].find("islongtable")
411 q = document.body[i+2].find("tabularvalignment")
413 document.body[i+2] = document.body[i+2][:q-1]
414 document.body[i+2] = document.body[i+2] + '>'
419 tabularvalignment = 'c'
420 # which valignment is specified?
421 m = document.body[i+2].find('tabularvalignment="top"')
423 tabularvalignment = 't'
424 m = document.body[i+2].find('tabularvalignment="bottom"')
426 tabularvalignment = 'b'
427 # delete tabularvalignment
428 q = document.body[i+2].find("tabularvalignment")
430 document.body[i+2] = document.body[i+2][:q-1]
431 document.body[i+2] = document.body[i+2] + '>'
433 # don't add a box when centered
434 if tabularvalignment == 'c':
437 subst = ['\\end_layout', '\\end_inset']
438 document.body[j:j] = subst # just inserts those lines
439 subst = ['\\begin_inset Box Frameless',
440 'position "' + tabularvalignment +'"',
445 # we don't know the width, assume 50%
449 'height_special "totalheight"',
452 '\\begin_layout Plain Layout']
453 document.body[i:i] = subst # this just inserts the array at i
454 i += len(subst) + 2 # adjust i to save a few cycles
457 def revert_phantom(document):
458 " Reverts phantom to ERT "
462 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
465 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
466 '\\begin_inset ERT\nstatus collapsed\n\n' \
467 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
468 'phantom{\n\\end_layout\n\n\\end_inset\n')
469 substi = substi.split('\n')
470 document.body[i : i+4] = substi
472 j = find_token(document.body, "\\end_layout", i)
474 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
476 substj = document.body[j].replace('\\end_layout', \
477 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
478 '\\begin_layout Plain Layout\n\n' \
479 '}\n\\end_layout\n\n\\end_inset\n')
480 substj = substj.split('\n')
481 document.body[j : j+4] = substj
485 def revert_hphantom(document):
486 " Reverts hphantom to ERT "
490 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
493 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
494 '\\begin_inset ERT\nstatus collapsed\n\n' \
495 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
496 'hphantom{\n\\end_layout\n\n\\end_inset\n')
497 substi = substi.split('\n')
498 document.body[i : i+4] = substi
500 j = find_token(document.body, "\\end_layout", i)
502 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
504 substj = document.body[j].replace('\\end_layout', \
505 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
506 '\\begin_layout Plain Layout\n\n' \
507 '}\n\\end_layout\n\n\\end_inset\n')
508 substj = substj.split('\n')
509 document.body[j : j+4] = substj
513 def revert_vphantom(document):
514 " Reverts vphantom to ERT "
518 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
521 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
522 '\\begin_inset ERT\nstatus collapsed\n\n' \
523 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
524 'vphantom{\n\\end_layout\n\n\\end_inset\n')
525 substi = substi.split('\n')
526 document.body[i : i+4] = substi
528 j = find_token(document.body, "\\end_layout", i)
530 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
532 substj = document.body[j].replace('\\end_layout', \
533 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
534 '\\begin_layout Plain Layout\n\n' \
535 '}\n\\end_layout\n\n\\end_inset\n')
536 substj = substj.split('\n')
537 document.body[j : j+4] = substj
541 def revert_xetex(document):
542 " Reverts documents that use XeTeX "
543 i = find_token(document.header, '\\use_xetex', 0)
545 document.warning("Malformed LyX document: Missing \\use_xetex.")
547 if get_value(document.header, "\\use_xetex", i) == 'false':
548 del document.header[i]
550 del document.header[i]
551 # 1.) set doc encoding to utf8-plain
552 i = find_token(document.header, "\\inputencoding", 0)
554 document.warning("Malformed LyX document: Missing \\inputencoding.")
555 document.header[i] = "\\inputencoding utf8-plain"
556 # 2.) check font settings
557 l = find_token(document.header, "\\font_roman", 0)
559 document.warning("Malformed LyX document: Missing \\font_roman.")
560 line = document.header[l]
561 l = re.compile(r'\\font_roman (.*)$')
564 l = find_token(document.header, "\\font_sans", 0)
566 document.warning("Malformed LyX document: Missing \\font_sans.")
567 line = document.header[l]
568 l = re.compile(r'\\font_sans (.*)$')
571 l = find_token(document.header, "\\font_typewriter", 0)
573 document.warning("Malformed LyX document: Missing \\font_typewriter.")
574 line = document.header[l]
575 l = re.compile(r'\\font_typewriter (.*)$')
577 typewriter = m.group(1)
578 osf = get_value(document.header, '\\font_osf', 0) == "true"
579 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
580 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
581 # 3.) set preamble stuff
582 pretext = '%% This document must be processed with xelatex!\n'
583 pretext += '\\usepackage{fontspec}\n'
584 if roman != "default":
585 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
586 if sans != "default":
587 pretext += '\\setsansfont['
589 pretext += 'Scale=' + str(sf_scale / 100) + ','
590 pretext += 'Mapping=tex-text]{' + sans + '}\n'
591 if typewriter != "default":
592 pretext += '\\setmonofont'
594 pretext += '[Scale=' + str(tt_scale / 100) + ']'
595 pretext += '{' + typewriter + '}\n'
597 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
598 pretext += '\usepackage{xunicode}\n'
599 pretext += '\usepackage{xltxtra}\n'
600 insert_to_preamble(0, document, pretext)
601 # 4.) reset font settings
602 i = find_token(document.header, "\\font_roman", 0)
604 document.warning("Malformed LyX document: Missing \\font_roman.")
605 document.header[i] = "\\font_roman default"
606 i = find_token(document.header, "\\font_sans", 0)
608 document.warning("Malformed LyX document: Missing \\font_sans.")
609 document.header[i] = "\\font_sans default"
610 i = find_token(document.header, "\\font_typewriter", 0)
612 document.warning("Malformed LyX document: Missing \\font_typewriter.")
613 document.header[i] = "\\font_typewriter default"
614 i = find_token(document.header, "\\font_osf", 0)
616 document.warning("Malformed LyX document: Missing \\font_osf.")
617 document.header[i] = "\\font_osf false"
618 i = find_token(document.header, "\\font_sc", 0)
620 document.warning("Malformed LyX document: Missing \\font_sc.")
621 document.header[i] = "\\font_sc false"
622 i = find_token(document.header, "\\font_sf_scale", 0)
624 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
625 document.header[i] = "\\font_sf_scale 100"
626 i = find_token(document.header, "\\font_tt_scale", 0)
628 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
629 document.header[i] = "\\font_tt_scale 100"
632 def revert_outputformat(document):
633 " Remove default output format param "
634 i = find_token(document.header, '\\default_output_format', 0)
636 document.warning("Malformed LyX document: Missing \\default_output_format.")
638 del document.header[i]
641 def revert_backgroundcolor(document):
642 " Reverts background color to preamble code "
646 i = find_token(document.header, "\\backgroundcolor", i)
649 colorcode = get_value(document.header, '\\backgroundcolor', 0)
650 del document.header[i]
651 # don't clutter the preamble if backgroundcolor is not set
652 if colorcode == "#ffffff":
654 # the color code is in the form #rrggbb where every character denotes a hex number
655 # convert the string to an int
656 red = string.atoi(colorcode[1:3],16)
657 # we want the output "0.5" for the value "127" therefore add here
660 redout = float(red) / 256
661 green = string.atoi(colorcode[3:5],16)
664 greenout = float(green) / 256
665 blue = string.atoi(colorcode[5:7],16)
668 blueout = float(blue) / 256
670 insert_to_preamble(0, document,
671 '% Commands inserted by lyx2lyx to set the background color\n'
672 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
673 + '\\definecolor{page_backgroundcolor}{rgb}{'
674 + str(redout) + ', ' + str(greenout)
675 + ', ' + str(blueout) + '}\n'
676 + '\\pagecolor{page_backgroundcolor}\n')
679 def revert_splitindex(document):
680 " Reverts splitindex-aware documents "
681 i = find_token(document.header, '\\use_indices', 0)
683 document.warning("Malformed LyX document: Missing \\use_indices.")
685 indices = get_value(document.header, "\\use_indices", i)
687 if indices == "true":
688 preamble += "\\usepackage{splitidx}\n"
689 del document.header[i]
692 i = find_token(document.header, "\\index", i)
695 k = find_token(document.header, "\\end_index", i)
697 document.warning("Malformed LyX document: Missing \\end_index.")
699 line = document.header[i]
700 l = re.compile(r'\\index (.*)$')
703 ishortcut = get_value(document.header, '\\shortcut', i, k)
704 if ishortcut != "" and indices == "true":
705 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
706 del document.header[i:k+1]
709 insert_to_preamble(0, document, preamble)
712 i = find_token(document.body, "\\begin_inset Index", i)
715 line = document.body[i]
716 l = re.compile(r'\\begin_inset Index (.*)$')
719 if itype == "idx" or indices == "false":
720 document.body[i] = "\\begin_inset Index"
722 k = find_end_of_inset(document.body, i)
725 content = lyx2latex(document, document.body[i:k])
727 content = content.replace('"', r'\"')
728 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
729 document.body[i:k+1] = subst
733 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
736 k = find_end_of_inset(document.body, i)
737 ptype = get_value(document.body, 'type', i, k).strip('"')
739 j = find_token(document.body, "type", i, k)
741 elif indices == "false":
742 del document.body[i:k+1]
744 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
745 document.body[i:k+1] = subst
749 def convert_splitindex(document):
750 " Converts index and printindex insets to splitindex-aware format "
753 i = find_token(document.body, "\\begin_inset Index", i)
756 document.body[i] = document.body[i].replace("\\begin_inset Index",
757 "\\begin_inset Index idx")
761 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
764 if document.body[i + 1].find('LatexCommand printindex') == -1:
765 document.warning("Malformed LyX document: Incomplete printindex inset.")
767 subst = ["LatexCommand printindex",
769 document.body[i + 1:i + 2] = subst
773 def revert_subindex(document):
774 " Reverts \\printsubindex CommandInset types "
775 i = find_token(document.header, '\\use_indices', 0)
777 document.warning("Malformed LyX document: Missing \\use_indices.")
779 indices = get_value(document.header, "\\use_indices", i)
782 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
785 k = find_end_of_inset(document.body, i)
786 ctype = get_value(document.body, 'LatexCommand', i, k)
787 if ctype != "printsubindex":
790 ptype = get_value(document.body, 'type', i, k).strip('"')
791 if indices == "false":
792 del document.body[i:k+1]
794 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
795 document.body[i:k+1] = subst
799 def revert_printindexall(document):
800 " Reverts \\print[sub]index* CommandInset types "
801 i = find_token(document.header, '\\use_indices', 0)
803 document.warning("Malformed LyX document: Missing \\use_indices.")
805 indices = get_value(document.header, "\\use_indices", i)
808 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
811 k = find_end_of_inset(document.body, i)
812 ctype = get_value(document.body, 'LatexCommand', i, k)
813 if ctype != "printindex*" and ctype != "printsubindex*":
816 if indices == "false":
817 del document.body[i:k+1]
819 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
820 document.body[i:k+1] = subst
824 def revert_strikeout(document):
825 " Reverts \\strikeout character style "
827 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
828 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
829 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
831 insert_to_preamble(0, document,
832 '% Commands inserted by lyx2lyx for proper underlining\n'
833 + '\\PassOptionsToPackage{normalem}{ulem}\n'
834 + '\\usepackage{ulem}\n')
837 def revert_ulinelatex(document):
838 " Reverts \\uline character style "
839 i = find_token(document.body, '\\bar under', 0)
842 insert_to_preamble(0, document,
843 '% Commands inserted by lyx2lyx for proper underlining\n'
844 + '\\PassOptionsToPackage{normalem}{ulem}\n'
845 + '\\usepackage{ulem}\n'
846 + '\\let\\cite@rig\\cite\n'
847 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
848 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
849 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
852 def revert_custom_processors(document):
853 " Remove bibtex_command and index_command params "
854 i = find_token(document.header, '\\bibtex_command', 0)
856 document.warning("Malformed LyX document: Missing \\bibtex_command.")
858 del document.header[i]
859 i = find_token(document.header, '\\index_command', 0)
861 document.warning("Malformed LyX document: Missing \\index_command.")
863 del document.header[i]
866 def convert_nomencl_width(document):
867 " Add set_width param to nomencl_print "
870 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
873 document.body.insert(i + 2, "set_width \"none\"")
877 def revert_nomencl_width(document):
878 " Remove set_width param from nomencl_print "
881 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
884 j = find_end_of_inset(document.body, i)
885 l = find_token(document.body, "set_width", i, j)
887 document.warning("Can't find set_width option for nomencl_print!")
894 def revert_nomencl_cwidth(document):
895 " Remove width param from nomencl_print "
898 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
901 j = find_end_of_inset(document.body, i)
902 l = find_token(document.body, "width", i, j)
904 #Can't find width option for nomencl_print
907 width = get_value(document.body, "width", i, j).strip('"')
909 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
910 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
914 def revert_applemac(document):
915 " Revert applemac encoding to auto "
917 if document.encoding == "applemac":
918 document.encoding = "auto"
919 i = find_token(document.header, "\\encoding", 0)
921 document.header[i] = "\\encoding auto"
924 def revert_longtable_align(document):
925 " Remove longtable alignment setting "
929 i = find_token(document.body, "\\begin_inset Tabular", i)
932 # the alignment is 2 lines below \\begin_inset Tabular
933 j = document.body[i+2].find("longtabularalignment")
936 document.body[i+2] = document.body[i+2][:j-1]
937 document.body[i+2] = document.body[i+2] + '>'
941 def revert_branch_filename(document):
942 " Remove \\filename_suffix parameter from branches "
945 i = find_token(document.header, "\\filename_suffix", i)
948 del document.header[i]
951 def revert_paragraph_indentation(document):
952 " Revert custom paragraph indentation to preamble code "
955 i = find_token(document.header, "\\paragraph_indentation", i)
958 # only remove the preamble line if default
959 # otherwise also write the value to the preamble
960 length = get_value(document.header, "\\paragraph_indentation", i)
961 if length == "default":
962 del document.header[i]
965 # handle percent lengths
966 # latex_length returns "bool,length"
967 length = latex_length(length).split(",")[1]
968 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
969 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
970 del document.header[i]
974 def revert_percent_skip_lengths(document):
975 " Revert relative lengths for paragraph skip separation to preamble code "
978 i = find_token(document.header, "\\defskip", i)
981 length = get_value(document.header, "\\defskip", i)
982 # only revert when a custom length was set and when
983 # it used a percent length
984 if length not in ('smallskip', 'medskip', 'bigskip'):
985 # handle percent lengths
986 length = latex_length(length)
987 # latex_length returns "bool,length"
988 percent = length.split(",")[0]
989 length = length.split(",")[1]
990 if percent == "True":
991 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
992 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
993 # set defskip to medskip as default
994 document.header[i] = "\\defskip medskip"
998 def revert_percent_vspace_lengths(document):
999 " Revert relative VSpace lengths to ERT "
1002 i = find_token(document.body, "\\begin_inset VSpace", i)
1005 # only revert if a custom length was set and if
1006 # it used a percent length
1007 line = document.body[i]
1008 r = re.compile(r'\\begin_inset VSpace (.*)$')
1011 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
1012 # check if the space has a star (protected space)
1013 protected = (document.body[i].rfind("*") != -1)
1015 length = length.rstrip('*')
1016 # handle percent lengths
1017 length = latex_length(length)
1018 # latex_length returns "bool,length"
1019 percent = length.split(",")[0]
1020 length = length.split(",")[1]
1021 # revert the VSpace inset to ERT
1022 if percent == "True":
1024 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
1026 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1027 document.body[i:i+2] = subst
1031 def revert_percent_hspace_lengths(document):
1032 " Revert relative HSpace lengths to ERT "
1035 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1038 protected = (document.body[i].find("\\hspace*{}") != -1)
1039 # only revert if a custom length was set and if
1040 # it used a percent length
1041 length = get_value(document.body, '\\length', i+1)
1043 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1045 # handle percent lengths
1046 length = latex_length(length)
1047 # latex_length returns "bool,length"
1048 percent = length.split(",")[0]
1049 length = length.split(",")[1]
1050 # revert the HSpace inset to ERT
1051 if percent == "True":
1053 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1055 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1056 document.body[i:i+3] = subst
1060 def revert_hspace_glue_lengths(document):
1061 " Revert HSpace glue lengths to ERT "
1064 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1067 protected = (document.body[i].find("\\hspace*{}") != -1)
1068 length = get_value(document.body, '\\length', i+1)
1070 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1072 # only revert if the length contains a plus or minus at pos != 0
1073 glue = re.compile(r'.+[\+-]')
1074 if glue.search(length):
1075 # handle percent lengths
1076 # latex_length returns "bool,length"
1077 length = latex_length(length).split(",")[1]
1078 # revert the HSpace inset to ERT
1080 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1082 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1083 document.body[i:i+3] = subst
1086 def convert_author_id(document):
1087 " Add the author_id to the \\author definition and make sure 0 is not used"
1091 i = find_token(document.header, "\\author", i)
1095 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1096 m = r.match(document.header[i])
1101 if m.lastindex == 3:
1103 document.header[i] = "\\author %i %s %s" % (j, name, email)
1109 k = find_token(document.body, "\\change_", k)
1113 change = document.body[k].split(' ');
1114 if len(change) == 3:
1116 author_id = int(change[1])
1118 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1121 def revert_author_id(document):
1122 " Remove the author_id from the \\author definition "
1127 i = find_token(document.header, "\\author", i)
1131 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1132 m = r.match(document.header[i])
1134 author_id = int(m.group(2))
1135 idmap[author_id] = j
1139 if m.lastindex == 4:
1141 document.header[i] = "\\author %s %s" % (name, email)
1147 k = find_token(document.body, "\\change_", k)
1151 change = document.body[k].split(' ');
1152 if len(change) == 3:
1154 author_id = int(change[1])
1156 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1160 def revert_suppress_date(document):
1161 " Revert suppressing of default document date to preamble code "
1164 i = find_token(document.header, "\\suppress_date", i)
1167 # remove the preamble line and write to the preamble
1168 # when suppress_date was true
1169 date = get_value(document.header, "\\suppress_date", i)
1171 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1172 add_to_preamble(document, ["\\date{}"])
1173 del document.header[i]
1177 def revert_mhchem(document):
1178 "Revert mhchem loading to preamble code"
1183 i = find_token(document.header, "\\use_mhchem 1", 0)
1187 i = find_token(document.header, "\\use_mhchem 2", 0)
1190 if mhchem == "auto":
1191 j = find_token(document.body, "\\cf{", 0)
1195 j = find_token(document.body, "\\ce{", 0)
1199 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1200 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1201 add_to_preamble(document, ["\\usepackage{mhchem}"])
1202 k = find_token(document.header, "\\use_mhchem", 0)
1204 document.warning("Malformed LyX document: Could not find mhchem setting.")
1206 del document.header[k]
1209 def revert_fontenc(document):
1210 " Remove fontencoding param "
1211 i = find_token(document.header, '\\fontencoding', 0)
1213 document.warning("Malformed LyX document: Missing \\fontencoding.")
1215 del document.header[i]
1218 def merge_gbrief(document):
1219 " Merge g-brief-en and g-brief-de to one class "
1221 if document.textclass != "g-brief-de":
1222 if document.textclass == "g-brief-en":
1223 document.textclass = "g-brief"
1224 document.set_textclass()
1227 obsoletedby = { "Brieftext": "Letter",
1228 "Unterschrift": "Signature",
1229 "Strasse": "Street",
1230 "Zusatz": "Addition",
1233 "RetourAdresse": "ReturnAddress",
1234 "MeinZeichen": "MyRef",
1235 "IhrZeichen": "YourRef",
1236 "IhrSchreiben": "YourMail",
1239 "Konto": "BankAccount",
1240 "Postvermerk": "PostalComment",
1241 "Adresse": "Address",
1243 "Betreff": "Reference",
1244 "Anrede": "Opening",
1250 i = find_token(document.body, "\\begin_layout", i)
1254 layout = document.body[i][14:]
1255 if layout in obsoletedby:
1256 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1260 document.textclass = "g-brief"
1261 document.set_textclass()
1264 def revert_gbrief(document):
1265 " Revert g-brief to g-brief-en "
1266 if document.textclass == "g-brief":
1267 document.textclass = "g-brief-en"
1268 document.set_textclass()
1271 def revert_html_options(document):
1272 " Remove html options "
1273 i = find_token(document.header, '\\html_use_mathml', 0)
1275 del document.header[i]
1276 i = find_token(document.header, '\\html_be_strict', 0)
1278 del document.header[i]
1281 def revert_includeonly(document):
1284 i = find_token(document.header, "\\begin_includeonly", i)
1287 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1289 # this should not happen
1291 document.header[i : j + 1] = []
1294 def revert_includeall(document):
1295 " Remove maintain_unincluded_children param "
1296 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1298 del document.header[i]
1301 def revert_multirow(document):
1302 " Revert multirow cells in tables "
1306 # cell type 3 is multirow begin cell
1307 i = find_token(document.body, '<cell multirow="3"', i)
1310 # a multirow cell was found
1312 # remove the multirow tag, set the valignment to top
1313 # and remove the bottom line
1314 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1315 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1316 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1317 # write ERT to create the multirow cell
1318 # use 2 rows and 2cm as default with because the multirow span
1319 # and the column width is only hardly accessible
1320 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1321 document.body[i + 4:i + 4] = subst
1322 i = find_token(document.body, "</cell>", i)
1324 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1326 subst = [old_put_cmd_in_ert("}")]
1327 document.body[i - 3:i - 3] = subst
1328 # cell type 4 is multirow part cell
1329 i = find_token(document.body, '<cell multirow="4"', i)
1332 # remove the multirow tag, set the valignment to top
1333 # and remove the top line
1334 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1335 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1336 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1338 if multirow == True:
1339 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1340 add_to_preamble(document, ["\\usepackage{multirow}"])
1343 def convert_math_output(document):
1344 " Convert \html_use_mathml to \html_math_output "
1345 i = find_token(document.header, "\\html_use_mathml", 0)
1348 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1349 m = rgx.match(document.header[i])
1351 newval = "0" # MathML
1354 newval = "2" # Images
1355 document.header[i] = "\\html_math_output " + newval
1358 def revert_math_output(document):
1359 " Revert \html_math_output to \html_use_mathml "
1360 i = find_token(document.header, "\\html_math_output", 0)
1363 rgx = re.compile(r'\\html_math_output\s+(\d)')
1364 m = rgx.match(document.header[i])
1368 if val == "1" or val == "2":
1371 document.warning("Unable to match " + document.header[i])
1372 document.header[i] = "\\html_use_mathml " + newval
1376 def revert_inset_preview(document):
1377 " Dissolves the preview inset "
1382 i = find_token(document.body, "\\begin_inset Preview", i)
1385 j = find_end_of_inset(document.body, i)
1387 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1389 #If the layout is Standard we need to remove it, otherwise there
1390 #will be paragraph breaks that shouldn't be there.
1391 k = find_token(document.body, "\\begin_layout Standard", i)
1393 del document.body[i : i+3]
1394 del document.body[j-5 : j-2]
1397 del document.body[i]
1398 del document.body[j-1]
1402 def revert_equalspacing_xymatrix(document):
1403 " Revert a Formula with xymatrix@! to an ERT inset "
1406 has_preamble = False
1407 has_equal_spacing = False
1410 i = find_token(document.body, "\\begin_inset Formula", i)
1413 j = find_end_of_inset(document.body, i)
1415 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1418 for curline in range(i,j):
1419 found = document.body[curline].find("\\xymatrix@!")
1424 has_equal_spacing = True
1425 content = [document.body[i][21:]]
1426 content += document.body[i+1:j]
1427 subst = put_cmd_in_ert(content)
1428 document.body[i:j+1] = subst
1431 for curline in range(i,j):
1432 l = document.body[curline].find("\\xymatrix")
1434 has_preamble = True;
1437 if has_equal_spacing and not has_preamble:
1438 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1441 def revert_notefontcolor(document):
1442 " Reverts greyed-out note font color to preamble code "
1446 i = find_token(document.header, "\\notefontcolor", i)
1449 colorcode = get_value(document.header, '\\notefontcolor', 0)
1450 del document.header[i]
1451 # the color code is in the form #rrggbb where every character denotes a hex number
1452 # convert the string to an int
1453 red = string.atoi(colorcode[1:3],16)
1454 # we want the output "0.5" for the value "127" therefore increment here
1457 redout = float(red) / 256
1458 green = string.atoi(colorcode[3:5],16)
1461 greenout = float(green) / 256
1462 blue = string.atoi(colorcode[5:7],16)
1465 blueout = float(blue) / 256
1466 # write the preamble
1467 insert_to_preamble(0, document,
1468 '% Commands inserted by lyx2lyx to set the font color\n'
1469 '% for greyed-out notes\n'
1470 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1471 + '\\definecolor{note_fontcolor}{rgb}{'
1472 + str(redout) + ', ' + str(greenout)
1473 + ', ' + str(blueout) + '}\n'
1474 + '\\renewenvironment{lyxgreyedout}\n'
1475 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1478 def revert_turkmen(document):
1479 "Set language Turkmen to English"
1481 if document.language == "turkmen":
1482 document.language = "english"
1483 i = find_token(document.header, "\\language", 0)
1485 document.header[i] = "\\language english"
1488 j = find_token(document.body, "\\lang turkmen", j)
1491 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1495 def revert_fontcolor(document):
1496 " Reverts font color to preamble code "
1500 i = find_token(document.header, "\\fontcolor", i)
1503 colorcode = get_value(document.header, '\\fontcolor', 0)
1504 del document.header[i]
1505 # don't clutter the preamble if backgroundcolor is not set
1506 if colorcode == "#000000":
1508 # the color code is in the form #rrggbb where every character denotes a hex number
1509 # convert the string to an int
1510 red = string.atoi(colorcode[1:3],16)
1511 # we want the output "0.5" for the value "127" therefore add here
1514 redout = float(red) / 256
1515 green = string.atoi(colorcode[3:5],16)
1518 greenout = float(green) / 256
1519 blue = string.atoi(colorcode[5:7],16)
1522 blueout = float(blue) / 256
1523 # write the preamble
1524 insert_to_preamble(0, document,
1525 '% Commands inserted by lyx2lyx to set the font color\n'
1526 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1527 + '\\definecolor{document_fontcolor}{rgb}{'
1528 + str(redout) + ', ' + str(greenout)
1529 + ', ' + str(blueout) + '}\n'
1530 + '\\color{document_fontcolor}\n')
1533 def revert_shadedboxcolor(document):
1534 " Reverts shaded box color to preamble code "
1538 i = find_token(document.header, "\\boxbgcolor", i)
1541 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1542 del document.header[i]
1543 # the color code is in the form #rrggbb where every character denotes a hex number
1544 # convert the string to an int
1545 red = string.atoi(colorcode[1:3],16)
1546 # we want the output "0.5" for the value "127" therefore increment here
1549 redout = float(red) / 256
1550 green = string.atoi(colorcode[3:5],16)
1553 greenout = float(green) / 256
1554 blue = string.atoi(colorcode[5:7],16)
1557 blueout = float(blue) / 256
1558 # write the preamble
1559 insert_to_preamble(0, document,
1560 '% Commands inserted by lyx2lyx to set the color\n'
1561 '% of boxes with shaded background\n'
1562 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1563 + '\\definecolor{shadecolor}{rgb}{'
1564 + str(redout) + ', ' + str(greenout)
1565 + ', ' + str(blueout) + '}\n')
1568 def revert_lyx_version(document):
1569 " Reverts LyX Version information from Inset Info "
1570 version = "LyX version"
1572 import lyx2lyx_version
1573 version = lyx2lyx_version.version
1579 i = find_token(document.body, '\\begin_inset Info', i)
1582 j = find_end_of_inset(document.body, i + 1)
1585 document.warning("Malformed LyX document: Could not find end of Info inset.")
1591 # but we shall try to be forgiving.
1593 for k in range(i, j):
1594 if document.body[k].startswith("arg"):
1595 arg = document.body[k][3:].strip().strip('"')
1596 if document.body[k].startswith("type"):
1597 typ = document.body[k][4:].strip().strip('"')
1598 if arg != "version" or typ != "lyxinfo":
1602 # We do not actually know the version of LyX used to produce the document.
1603 # But we can use our version, since we are reverting.
1605 # Now we want to check if the line after "\end_inset" is empty. It normally
1606 # is, so we want to remove it, too.
1608 if document.body[j+1].strip() == "":
1610 document.body[i: lastline] = s
1614 def revert_math_scale(document):
1615 " Remove math scaling and LaTeX options "
1616 i = find_token(document.header, '\\html_math_img_scale', 0)
1618 del document.header[i]
1619 i = find_token(document.header, '\\html_latex_start', 0)
1621 del document.header[i]
1622 i = find_token(document.header, '\\html_latex_end', 0)
1624 del document.header[i]
1627 def revert_pagesizes(document):
1629 " Revert page sizes to default "
1630 i = find_token(document.header, '\\papersize', 0)
1632 size = document.header[i][11:]
1633 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1634 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1635 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1636 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1637 or size == "b5j" or size == "b6j":
1638 del document.header[i]
1641 def convert_html_quotes(document):
1642 " Remove quotes around html_latex_start and html_latex_end "
1644 i = find_token(document.header, '\\html_latex_start', 0)
1646 line = document.header[i]
1647 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1650 document.header[i] = "\\html_latex_start " + m.group(1)
1652 i = find_token(document.header, '\\html_latex_end', 0)
1654 line = document.header[i]
1655 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1658 document.header[i] = "\\html_latex_end " + m.group(1)
1661 def revert_html_quotes(document):
1662 " Remove quotes around html_latex_start and html_latex_end "
1664 i = find_token(document.header, '\\html_latex_start', 0)
1666 line = document.header[i]
1667 l = re.compile(r'\\html_latex_start\s+(.*)')
1669 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1671 i = find_token(document.header, '\\html_latex_end', 0)
1673 line = document.header[i]
1674 l = re.compile(r'\\html_latex_end\s+(.*)')
1676 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1679 def revert_output_sync(document):
1680 " Remove forward search options "
1681 i = find_token(document.header, '\\output_sync_macro', 0)
1683 del document.header[i]
1684 i = find_token(document.header, '\\output_sync', 0)
1686 del document.header[i]
1689 def convert_beamer_args(document):
1690 " Convert ERT arguments in Beamer to InsetArguments "
1692 if document.textclass != "beamer" and document.textclass != "article-beamer":
1695 layouts = ("Block", "ExampleBlock", "AlertBlock")
1696 for layout in layouts:
1699 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1702 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1704 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1707 bert = find_token(document.body, '\\begin_inset ERT', blay)
1709 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1712 eert = find_end_of_inset(document.body, bert)
1714 document.warning("Malformed LyX document: Can't find end of ERT.")
1718 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1719 # an argument inset.
1720 # Do the end first, so as not to mess up the variables.
1721 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1722 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1723 '\\begin_layout Plain Layout']
1727 def revert_beamer_args(document):
1728 " Revert Beamer arguments to ERT "
1730 if document.textclass != "beamer" and document.textclass != "article-beamer":
1733 layouts = ("Block", "ExampleBlock", "AlertBlock")
1734 for layout in layouts:
1737 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1740 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1742 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1745 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1747 # it is legal not to have one of these
1750 eopt = find_end_of_inset(document.body, bopt)
1752 document.warning("Malformed LyX document: Can't find end of argument.")
1755 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1757 document.warning("Malformed LyX document: Can't find plain layout.")
1760 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1762 document.warning("Malformed LyX document: Can't find end of plain layout.")
1765 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1769 document.warning(str(bcont) + " " + str(eplay))
1772 # we convert the content of the argument into pure LaTeX...
1773 content = lyx2latex(document, document.body[bcont:eplay])
1774 strlist = put_cmd_in_ert(["{" + content + "}"])
1776 # now replace the optional argument with the ERT
1777 document.body[bopt:eopt + 1] = strlist
1781 def revert_align_decimal(document):
1784 l = document.body[l].find('alignment=decimal')
1787 remove_option(document, l, 'decimal_point')
1788 document.body[l].replace('decimal', 'center')
1791 def convert_optarg(document):
1792 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1795 i = find_token(document.body, '\\begin_inset OptArg', i)
1798 document.body[i] = "\\begin_inset Argument"
1802 def revert_argument(document):
1803 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1806 i = find_token(document.body, '\\begin_inset Argument', i)
1809 document.body[i] = "\\begin_inset OptArg"
1813 def revert_makebox(document):
1814 " Convert \\makebox to TeX code "
1817 # only revert frameless boxes without an inner box
1818 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1822 z = find_end_of_inset(document.body, i)
1824 document.warning("Malformed LyX document: Can't find end of box inset.")
1826 j = find_token(document.body, 'use_makebox 1', i)
1827 # assure we found the makebox of the current box
1828 if j > i + 7 or j == -1:
1831 # remove the \end_inset
1832 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1833 # determine the alignment
1834 k = find_token(document.body, 'hor_pos', j - 4)
1835 align = document.body[k][9]
1836 # determine the width
1837 l = find_token(document.body, 'width "', j + 1)
1838 length = document.body[l][7:]
1839 # remove trailing '"'
1840 length = length[:-1]
1841 # latex_length returns "bool,length"
1842 length = latex_length(length).split(",")[1]
1843 subst = "\\makebox[" + length + "][" \
1845 document.body[i:i + 13] = put_cmd_in_ert(subst)
1849 def revert_IEEEtran(document):
1850 " Convert IEEEtran layouts and styles to TeX code "
1851 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1852 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1853 revert_layout_command(document, "Special Paper Notice", "\\IEEEspecialpapernotice", 0)
1854 revert_layout_command(document, "After Title Text", "\\IEEEaftertitletext", 0)
1855 revert_layout_command(document, "Page headings", "\\markboth", 0)
1856 revert_layout_command(document, "Publication ID", "\\IEEEpubid", 0)
1857 note = '\\begin_layout Standard\n' \
1858 + '\\begin_inset Note Note\n' \
1859 + 'status open\n\n' \
1860 + '\\begin_layout Plain Layout\n\n' \
1861 + '\series bold\n' \
1862 + 'IMPORTANT NOTICE!!!:\n' \
1863 + '\\series default\n' \
1866 + 'This document was created from a newer LyX version.\n' \
1867 + ' To be able to view/export it with LyX 1.6.x or earlier, the title and author\n' \
1868 + ' must be specified by using TeX code.\n' \
1869 + ' Do not use then the standard title and author environment!\n' \
1870 + '\\end_layout\n\n' \
1871 + '\\end_inset\n\n\n' \
1872 + '\\end_layout\n\n'
1873 if document.textclass == "IEEEtran":
1874 # insert a note that title and author must be given in TeX code
1875 document.body.insert(0, note)
1876 # we need to revert title and author to TeX code to set \maketitle correctly
1877 revert_layout_command(document, "Title", "\\title", 0)
1878 revert_layout_command(document, "Author", "\\author", 0)
1879 # write \markboth code to the preamble
1880 insert_to_preamble(0, document,
1881 '% Commands inserted by lyx2lyx\n'
1882 + '% protect \\markboth against an old bug reintroduced in babel >= 3.8g\n'
1883 + '\\let\\oldforeign@language\\foreign@language\n'
1884 + '\\DeclareRobustCommand{\\foreign@language}[1]{%\n'
1885 + ' \\lowercase{\\oldforeign@language{#1}}}\n')
1887 y = find_token(document.body, '\\begin_layout Abstract', 0)
1889 document.warning("Malformed LyX document: Can't find abstract of IEEEtran paper.")
1891 maketitle = ['\\begin_layout Standard\n', \
1892 '\\begin_inset ERT\n', \
1893 'status collapsed\n', \
1894 '\\begin_layout Plain Layout\n', \
1900 document.body[y:y] = maketitle
1907 supported_versions = ["2.0.0","2.0"]
1908 convert = [[346, []],
1914 [352, [convert_splitindex]],
1921 [359, [convert_nomencl_width]],
1931 [369, [convert_author_id]],
1935 [373, [merge_gbrief]],
1941 [379, [convert_math_output]],
1951 [389, [convert_html_quotes]],
1954 [392, [convert_beamer_args]],
1955 [393, [convert_optarg]],
1959 revert = [[393, [revert_makebox]],
1960 [392, [revert_argument]],
1961 [391, [revert_beamer_args]],
1962 [390, [revert_align_decimal, revert_IEEEtran]],
1963 [389, [revert_output_sync]],
1964 [388, [revert_html_quotes]],
1965 [387, [revert_pagesizes]],
1966 [386, [revert_math_scale]],
1967 [385, [revert_lyx_version]],
1968 [384, [revert_shadedboxcolor]],
1969 [383, [revert_fontcolor]],
1970 [382, [revert_turkmen]],
1971 [381, [revert_notefontcolor]],
1972 [380, [revert_equalspacing_xymatrix]],
1973 [379, [revert_inset_preview]],
1974 [378, [revert_math_output]],
1976 [376, [revert_multirow]],
1977 [375, [revert_includeall]],
1978 [374, [revert_includeonly]],
1979 [373, [revert_html_options]],
1980 [372, [revert_gbrief]],
1981 [371, [revert_fontenc]],
1982 [370, [revert_mhchem]],
1983 [369, [revert_suppress_date]],
1984 [368, [revert_author_id]],
1985 [367, [revert_hspace_glue_lengths]],
1986 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1987 [365, [revert_percent_skip_lengths]],
1988 [364, [revert_paragraph_indentation]],
1989 [363, [revert_branch_filename]],
1990 [362, [revert_longtable_align]],
1991 [361, [revert_applemac]],
1993 [359, [revert_nomencl_cwidth]],
1994 [358, [revert_nomencl_width]],
1995 [357, [revert_custom_processors]],
1996 [356, [revert_ulinelatex]],
1998 [354, [revert_strikeout]],
1999 [353, [revert_printindexall]],
2000 [352, [revert_subindex]],
2001 [351, [revert_splitindex]],
2002 [350, [revert_backgroundcolor]],
2003 [349, [revert_outputformat]],
2004 [348, [revert_xetex]],
2005 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
2006 [346, [revert_tabularvalign]],
2007 [345, [revert_swiss]]
2011 if __name__ == "__main__":