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)
282 z = find_end_of_inset(document.body, i)
284 document.warning("Malformed LyX document: Can't find end of Flex " + name + " inset.")
286 # remove the \end_inset
287 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
288 # we need to reset character layouts if necessary
289 j = find_token(document.body, '\\emph on', i)
290 k = find_token(document.body, '\\noun on', i)
291 l = find_token(document.body, '\\series', i)
292 m = find_token(document.body, '\\family', i)
293 n = find_token(document.body, '\\shape', i)
294 o = find_token(document.body, '\\color', i)
295 p = find_token(document.body, '\\size', i)
296 q = find_token(document.body, '\\bar under', i)
297 r = find_token(document.body, '\\uuline on', i)
298 s = find_token(document.body, '\\uwave on', i)
299 t = find_token(document.body, '\\strikeout on', i)
300 if j != -1 and j < z:
301 document.body.insert(z-2, "\\emph default")
302 if k != -1 and k < z:
303 document.body.insert(z-2, "\\noun default")
304 if l != -1 and l < z:
305 document.body.insert(z-2, "\\series default")
306 if m != -1 and m < z:
307 document.body.insert(z-2, "\\family default")
308 if n != -1 and n < z:
309 document.body.insert(z-2, "\\shape default")
310 if o != -1 and o < z:
311 document.body.insert(z-2, "\\color inherit")
312 if p != -1 and p < z:
313 document.body.insert(z-2, "\\size default")
314 if q != -1 and q < z:
315 document.body.insert(z-2, "\\bar default")
316 if r != -1 and r < z:
317 document.body.insert(z-2, "\\uuline default")
318 if s != -1 and s < z:
319 document.body.insert(z-2, "\\uwave default")
320 if t != -1 and t < z:
321 document.body.insert(z-2, "\\strikeout default")
322 document.body[i:i + 4] = put_cmd_in_ert(LaTeXname + "{")
326 def revert_charstyles(document, name, LaTeXname, changed):
327 " Reverts character styles to TeX code "
330 i = find_token(document.body, name + ' on', i)
334 j = find_token(document.body, name + ' default', i)
335 k = find_token(document.body, name + ' on', i + 1)
336 # if there is no default set, the style ends with the layout
337 # assure hereby that we found the correct layout end
338 if j != -1 and (j < k or k ==-1):
339 document.body[j:j+1] = put_cmd_in_ert("}")
341 j = find_token(document.body, '\\end_layout', i)
342 document.body[j:j] = put_cmd_in_ert("}")
343 document.body[i:i + 1] = put_cmd_in_ert(LaTeXname + "{")
348 ####################################################################
351 def revert_swiss(document):
352 " Set language german-ch to ngerman "
354 if document.language == "german-ch":
355 document.language = "ngerman"
356 i = find_token(document.header, "\\language", 0)
358 document.header[i] = "\\language ngerman"
361 j = find_token(document.body, "\\lang german-ch", j)
364 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
368 def revert_tabularvalign(document):
369 " Revert the tabular valign option "
372 i = find_token(document.body, "\\begin_inset Tabular", i)
375 j = find_token(document.body, "</cell>", i)
377 document.warning("Malformed LyX document: Could not find end of tabular cell.")
380 # don't set a box for longtables, only delete tabularvalignment
381 # the alignment is 2 lines below \\begin_inset Tabular
382 p = document.body[i+2].find("islongtable")
384 q = document.body[i+2].find("tabularvalignment")
386 document.body[i+2] = document.body[i+2][:q-1]
387 document.body[i+2] = document.body[i+2] + '>'
392 tabularvalignment = 'c'
393 # which valignment is specified?
394 m = document.body[i+2].find('tabularvalignment="top"')
396 tabularvalignment = 't'
397 m = document.body[i+2].find('tabularvalignment="bottom"')
399 tabularvalignment = 'b'
400 # delete tabularvalignment
401 q = document.body[i+2].find("tabularvalignment")
403 document.body[i+2] = document.body[i+2][:q-1]
404 document.body[i+2] = document.body[i+2] + '>'
406 # don't add a box when centered
407 if tabularvalignment == 'c':
410 subst = ['\\end_layout', '\\end_inset']
411 document.body[j:j] = subst # just inserts those lines
412 subst = ['\\begin_inset Box Frameless',
413 'position "' + tabularvalignment +'"',
418 # we don't know the width, assume 50%
422 'height_special "totalheight"',
425 '\\begin_layout Plain Layout']
426 document.body[i:i] = subst # this just inserts the array at i
427 i += len(subst) + 2 # adjust i to save a few cycles
430 def revert_phantom(document):
431 " Reverts phantom to ERT "
435 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
438 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
439 '\\begin_inset ERT\nstatus collapsed\n\n' \
440 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
441 'phantom{\n\\end_layout\n\n\\end_inset\n')
442 substi = substi.split('\n')
443 document.body[i : i+4] = substi
445 j = find_token(document.body, "\\end_layout", i)
447 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
449 substj = document.body[j].replace('\\end_layout', \
450 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
451 '\\begin_layout Plain Layout\n\n' \
452 '}\n\\end_layout\n\n\\end_inset\n')
453 substj = substj.split('\n')
454 document.body[j : j+4] = substj
458 def revert_hphantom(document):
459 " Reverts hphantom to ERT "
463 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
466 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
467 '\\begin_inset ERT\nstatus collapsed\n\n' \
468 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
469 'hphantom{\n\\end_layout\n\n\\end_inset\n')
470 substi = substi.split('\n')
471 document.body[i : i+4] = substi
473 j = find_token(document.body, "\\end_layout", i)
475 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
477 substj = document.body[j].replace('\\end_layout', \
478 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
479 '\\begin_layout Plain Layout\n\n' \
480 '}\n\\end_layout\n\n\\end_inset\n')
481 substj = substj.split('\n')
482 document.body[j : j+4] = substj
486 def revert_vphantom(document):
487 " Reverts vphantom to ERT "
491 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
494 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
495 '\\begin_inset ERT\nstatus collapsed\n\n' \
496 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
497 'vphantom{\n\\end_layout\n\n\\end_inset\n')
498 substi = substi.split('\n')
499 document.body[i : i+4] = substi
501 j = find_token(document.body, "\\end_layout", i)
503 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
505 substj = document.body[j].replace('\\end_layout', \
506 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
507 '\\begin_layout Plain Layout\n\n' \
508 '}\n\\end_layout\n\n\\end_inset\n')
509 substj = substj.split('\n')
510 document.body[j : j+4] = substj
514 def revert_xetex(document):
515 " Reverts documents that use XeTeX "
516 i = find_token(document.header, '\\use_xetex', 0)
518 document.warning("Malformed LyX document: Missing \\use_xetex.")
520 if get_value(document.header, "\\use_xetex", i) == 'false':
521 del document.header[i]
523 del document.header[i]
524 # 1.) set doc encoding to utf8-plain
525 i = find_token(document.header, "\\inputencoding", 0)
527 document.warning("Malformed LyX document: Missing \\inputencoding.")
528 document.header[i] = "\\inputencoding utf8-plain"
529 # 2.) check font settings
530 l = find_token(document.header, "\\font_roman", 0)
532 document.warning("Malformed LyX document: Missing \\font_roman.")
533 line = document.header[l]
534 l = re.compile(r'\\font_roman (.*)$')
537 l = find_token(document.header, "\\font_sans", 0)
539 document.warning("Malformed LyX document: Missing \\font_sans.")
540 line = document.header[l]
541 l = re.compile(r'\\font_sans (.*)$')
544 l = find_token(document.header, "\\font_typewriter", 0)
546 document.warning("Malformed LyX document: Missing \\font_typewriter.")
547 line = document.header[l]
548 l = re.compile(r'\\font_typewriter (.*)$')
550 typewriter = m.group(1)
551 osf = get_value(document.header, '\\font_osf', 0) == "true"
552 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
553 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
554 # 3.) set preamble stuff
555 pretext = '%% This document must be processed with xelatex!\n'
556 pretext += '\\usepackage{fontspec}\n'
557 if roman != "default":
558 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
559 if sans != "default":
560 pretext += '\\setsansfont['
562 pretext += 'Scale=' + str(sf_scale / 100) + ','
563 pretext += 'Mapping=tex-text]{' + sans + '}\n'
564 if typewriter != "default":
565 pretext += '\\setmonofont'
567 pretext += '[Scale=' + str(tt_scale / 100) + ']'
568 pretext += '{' + typewriter + '}\n'
570 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
571 pretext += '\usepackage{xunicode}\n'
572 pretext += '\usepackage{xltxtra}\n'
573 insert_to_preamble(0, document, pretext)
574 # 4.) reset font settings
575 i = find_token(document.header, "\\font_roman", 0)
577 document.warning("Malformed LyX document: Missing \\font_roman.")
578 document.header[i] = "\\font_roman default"
579 i = find_token(document.header, "\\font_sans", 0)
581 document.warning("Malformed LyX document: Missing \\font_sans.")
582 document.header[i] = "\\font_sans default"
583 i = find_token(document.header, "\\font_typewriter", 0)
585 document.warning("Malformed LyX document: Missing \\font_typewriter.")
586 document.header[i] = "\\font_typewriter default"
587 i = find_token(document.header, "\\font_osf", 0)
589 document.warning("Malformed LyX document: Missing \\font_osf.")
590 document.header[i] = "\\font_osf false"
591 i = find_token(document.header, "\\font_sc", 0)
593 document.warning("Malformed LyX document: Missing \\font_sc.")
594 document.header[i] = "\\font_sc false"
595 i = find_token(document.header, "\\font_sf_scale", 0)
597 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
598 document.header[i] = "\\font_sf_scale 100"
599 i = find_token(document.header, "\\font_tt_scale", 0)
601 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
602 document.header[i] = "\\font_tt_scale 100"
605 def revert_outputformat(document):
606 " Remove default output format param "
607 i = find_token(document.header, '\\default_output_format', 0)
609 document.warning("Malformed LyX document: Missing \\default_output_format.")
611 del document.header[i]
614 def revert_backgroundcolor(document):
615 " Reverts background color to preamble code "
619 i = find_token(document.header, "\\backgroundcolor", i)
622 colorcode = get_value(document.header, '\\backgroundcolor', 0)
623 del document.header[i]
624 # don't clutter the preamble if backgroundcolor is not set
625 if colorcode == "#ffffff":
627 # the color code is in the form #rrggbb where every character denotes a hex number
628 # convert the string to an int
629 red = string.atoi(colorcode[1:3],16)
630 # we want the output "0.5" for the value "127" therefore add here
633 redout = float(red) / 256
634 green = string.atoi(colorcode[3:5],16)
637 greenout = float(green) / 256
638 blue = string.atoi(colorcode[5:7],16)
641 blueout = float(blue) / 256
643 insert_to_preamble(0, document,
644 '% Commands inserted by lyx2lyx to set the background color\n'
645 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
646 + '\\definecolor{page_backgroundcolor}{rgb}{'
647 + str(redout) + ', ' + str(greenout)
648 + ', ' + str(blueout) + '}\n'
649 + '\\pagecolor{page_backgroundcolor}\n')
652 def revert_splitindex(document):
653 " Reverts splitindex-aware documents "
654 i = find_token(document.header, '\\use_indices', 0)
656 document.warning("Malformed LyX document: Missing \\use_indices.")
658 indices = get_value(document.header, "\\use_indices", i)
660 if indices == "true":
661 preamble += "\\usepackage{splitidx}\n"
662 del document.header[i]
665 i = find_token(document.header, "\\index", i)
668 k = find_token(document.header, "\\end_index", i)
670 document.warning("Malformed LyX document: Missing \\end_index.")
672 line = document.header[i]
673 l = re.compile(r'\\index (.*)$')
676 ishortcut = get_value(document.header, '\\shortcut', i, k)
677 if ishortcut != "" and indices == "true":
678 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
679 del document.header[i:k+1]
682 insert_to_preamble(0, document, preamble)
685 i = find_token(document.body, "\\begin_inset Index", i)
688 line = document.body[i]
689 l = re.compile(r'\\begin_inset Index (.*)$')
692 if itype == "idx" or indices == "false":
693 document.body[i] = "\\begin_inset Index"
695 k = find_end_of_inset(document.body, i)
698 content = lyx2latex(document, document.body[i:k])
700 content = content.replace('"', r'\"')
701 subst = [old_put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
702 document.body[i:k+1] = subst
706 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
709 k = find_end_of_inset(document.body, i)
710 ptype = get_value(document.body, 'type', i, k).strip('"')
712 j = find_token(document.body, "type", i, k)
714 elif indices == "false":
715 del document.body[i:k+1]
717 subst = [old_put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
718 document.body[i:k+1] = subst
722 def convert_splitindex(document):
723 " Converts index and printindex insets to splitindex-aware format "
726 i = find_token(document.body, "\\begin_inset Index", i)
729 document.body[i] = document.body[i].replace("\\begin_inset Index",
730 "\\begin_inset Index idx")
734 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
737 if document.body[i + 1].find('LatexCommand printindex') == -1:
738 document.warning("Malformed LyX document: Incomplete printindex inset.")
740 subst = ["LatexCommand printindex",
742 document.body[i + 1:i + 2] = subst
746 def revert_subindex(document):
747 " Reverts \\printsubindex CommandInset types "
748 i = find_token(document.header, '\\use_indices', 0)
750 document.warning("Malformed LyX document: Missing \\use_indices.")
752 indices = get_value(document.header, "\\use_indices", i)
755 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
758 k = find_end_of_inset(document.body, i)
759 ctype = get_value(document.body, 'LatexCommand', i, k)
760 if ctype != "printsubindex":
763 ptype = get_value(document.body, 'type', i, k).strip('"')
764 if indices == "false":
765 del document.body[i:k+1]
767 subst = [old_put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
768 document.body[i:k+1] = subst
772 def revert_printindexall(document):
773 " Reverts \\print[sub]index* CommandInset types "
774 i = find_token(document.header, '\\use_indices', 0)
776 document.warning("Malformed LyX document: Missing \\use_indices.")
778 indices = get_value(document.header, "\\use_indices", i)
781 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
784 k = find_end_of_inset(document.body, i)
785 ctype = get_value(document.body, 'LatexCommand', i, k)
786 if ctype != "printindex*" and ctype != "printsubindex*":
789 if indices == "false":
790 del document.body[i:k+1]
792 subst = [old_put_cmd_in_ert("\\" + ctype + "{}")]
793 document.body[i:k+1] = subst
797 def revert_strikeout(document):
798 " Reverts \\strikeout character style "
800 changed = revert_charstyles(document, "\\uuline", "\\uuline", changed)
801 changed = revert_charstyles(document, "\\uwave", "\\uwave", changed)
802 changed = revert_charstyles(document, "\\strikeout", "\\sout", changed)
804 insert_to_preamble(0, document,
805 '% Commands inserted by lyx2lyx for proper underlining\n'
806 + '\\PassOptionsToPackage{normalem}{ulem}\n'
807 + '\\usepackage{ulem}\n')
810 def revert_ulinelatex(document):
811 " Reverts \\uline character style "
812 i = find_token(document.body, '\\bar under', 0)
815 insert_to_preamble(0, document,
816 '% Commands inserted by lyx2lyx for proper underlining\n'
817 + '\\PassOptionsToPackage{normalem}{ulem}\n'
818 + '\\usepackage{ulem}\n'
819 + '\\let\\cite@rig\\cite\n'
820 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
821 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
822 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
825 def revert_custom_processors(document):
826 " Remove bibtex_command and index_command params "
827 i = find_token(document.header, '\\bibtex_command', 0)
829 document.warning("Malformed LyX document: Missing \\bibtex_command.")
831 del document.header[i]
832 i = find_token(document.header, '\\index_command', 0)
834 document.warning("Malformed LyX document: Missing \\index_command.")
836 del document.header[i]
839 def convert_nomencl_width(document):
840 " Add set_width param to nomencl_print "
843 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
846 document.body.insert(i + 2, "set_width \"none\"")
850 def revert_nomencl_width(document):
851 " Remove set_width param from nomencl_print "
854 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
857 j = find_end_of_inset(document.body, i)
858 l = find_token(document.body, "set_width", i, j)
860 document.warning("Can't find set_width option for nomencl_print!")
867 def revert_nomencl_cwidth(document):
868 " Remove width param from nomencl_print "
871 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
874 j = find_end_of_inset(document.body, i)
875 l = find_token(document.body, "width", i, j)
877 #Can't find width option for nomencl_print
880 width = get_value(document.body, "width", i, j).strip('"')
882 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
883 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
887 def revert_applemac(document):
888 " Revert applemac encoding to auto "
890 if document.encoding == "applemac":
891 document.encoding = "auto"
892 i = find_token(document.header, "\\encoding", 0)
894 document.header[i] = "\\encoding auto"
897 def revert_longtable_align(document):
898 " Remove longtable alignment setting "
902 i = find_token(document.body, "\\begin_inset Tabular", i)
905 # the alignment is 2 lines below \\begin_inset Tabular
906 j = document.body[i+2].find("longtabularalignment")
909 document.body[i+2] = document.body[i+2][:j-1]
910 document.body[i+2] = document.body[i+2] + '>'
914 def revert_branch_filename(document):
915 " Remove \\filename_suffix parameter from branches "
918 i = find_token(document.header, "\\filename_suffix", i)
921 del document.header[i]
924 def revert_paragraph_indentation(document):
925 " Revert custom paragraph indentation to preamble code "
928 i = find_token(document.header, "\\paragraph_indentation", i)
931 # only remove the preamble line if default
932 # otherwise also write the value to the preamble
933 length = get_value(document.header, "\\paragraph_indentation", i)
934 if length == "default":
935 del document.header[i]
938 # handle percent lengths
939 # latex_length returns "bool,length"
940 length = latex_length(length).split(",")[1]
941 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
942 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
943 del document.header[i]
947 def revert_percent_skip_lengths(document):
948 " Revert relative lengths for paragraph skip separation to preamble code "
951 i = find_token(document.header, "\\defskip", i)
954 length = get_value(document.header, "\\defskip", i)
955 # only revert when a custom length was set and when
956 # it used a percent length
957 if length not in ('smallskip', 'medskip', 'bigskip'):
958 # handle percent lengths
959 length = latex_length(length)
960 # latex_length returns "bool,length"
961 percent = length.split(",")[0]
962 length = length.split(",")[1]
963 if percent == "True":
964 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
965 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
966 # set defskip to medskip as default
967 document.header[i] = "\\defskip medskip"
971 def revert_percent_vspace_lengths(document):
972 " Revert relative VSpace lengths to ERT "
975 i = find_token(document.body, "\\begin_inset VSpace", i)
978 # only revert if a custom length was set and if
979 # it used a percent length
980 line = document.body[i]
981 r = re.compile(r'\\begin_inset VSpace (.*)$')
984 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
985 # check if the space has a star (protected space)
986 protected = (document.body[i].rfind("*") != -1)
988 length = length.rstrip('*')
989 # handle percent lengths
990 length = latex_length(length)
991 # latex_length returns "bool,length"
992 percent = length.split(",")[0]
993 length = length.split(",")[1]
994 # revert the VSpace inset to ERT
995 if percent == "True":
997 subst = [old_put_cmd_in_ert("\\vspace*{" + length + "}")]
999 subst = [old_put_cmd_in_ert("\\vspace{" + length + "}")]
1000 document.body[i:i+2] = subst
1004 def revert_percent_hspace_lengths(document):
1005 " Revert relative HSpace lengths to ERT "
1008 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1011 protected = (document.body[i].find("\\hspace*{}") != -1)
1012 # only revert if a custom length was set and if
1013 # it used a percent length
1014 length = get_value(document.body, '\\length', i+1)
1016 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1018 # handle percent lengths
1019 length = latex_length(length)
1020 # latex_length returns "bool,length"
1021 percent = length.split(",")[0]
1022 length = length.split(",")[1]
1023 # revert the HSpace inset to ERT
1024 if percent == "True":
1026 subst = [old_put_cmd_in_ert("\\hspace*{" + length + "}")]
1028 subst = [old_put_cmd_in_ert("\\hspace{" + length + "}")]
1029 document.body[i:i+3] = subst
1033 def revert_hspace_glue_lengths(document):
1034 " Revert HSpace glue lengths to ERT "
1037 i = find_token(document.body, "\\begin_inset space \\hspace", i)
1040 protected = (document.body[i].find("\\hspace*{}") != -1)
1041 length = get_value(document.body, '\\length', i+1)
1043 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
1045 # only revert if the length contains a plus or minus at pos != 0
1046 glue = re.compile(r'.+[\+-]')
1047 if glue.search(length):
1048 # handle percent lengths
1049 # latex_length returns "bool,length"
1050 length = latex_length(length).split(",")[1]
1051 # revert the HSpace inset to ERT
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
1059 def convert_author_id(document):
1060 " Add the author_id to the \\author definition and make sure 0 is not used"
1064 i = find_token(document.header, "\\author", i)
1068 r = re.compile(r'(\\author) (\".*\")\s?(.*)$')
1069 m = r.match(document.header[i])
1074 if m.lastindex == 3:
1076 document.header[i] = "\\author %i %s %s" % (j, name, email)
1082 k = find_token(document.body, "\\change_", k)
1086 change = document.body[k].split(' ');
1087 if len(change) == 3:
1089 author_id = int(change[1])
1091 document.body[k] = "%s %i %s" % (type, author_id + 1, time)
1094 def revert_author_id(document):
1095 " Remove the author_id from the \\author definition "
1100 i = find_token(document.header, "\\author", i)
1104 r = re.compile(r'(\\author) (\d+) (\".*\")\s?(.*)$')
1105 m = r.match(document.header[i])
1107 author_id = int(m.group(2))
1108 idmap[author_id] = j
1112 if m.lastindex == 4:
1114 document.header[i] = "\\author %s %s" % (name, email)
1120 k = find_token(document.body, "\\change_", k)
1124 change = document.body[k].split(' ');
1125 if len(change) == 3:
1127 author_id = int(change[1])
1129 document.body[k] = "%s %i %s" % (type, idmap[author_id], time)
1133 def revert_suppress_date(document):
1134 " Revert suppressing of default document date to preamble code "
1137 i = find_token(document.header, "\\suppress_date", i)
1140 # remove the preamble line and write to the preamble
1141 # when suppress_date was true
1142 date = get_value(document.header, "\\suppress_date", i)
1144 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1145 add_to_preamble(document, ["\\date{}"])
1146 del document.header[i]
1150 def revert_mhchem(document):
1151 "Revert mhchem loading to preamble code"
1156 i = find_token(document.header, "\\use_mhchem 1", 0)
1160 i = find_token(document.header, "\\use_mhchem 2", 0)
1163 if mhchem == "auto":
1164 j = find_token(document.body, "\\cf{", 0)
1168 j = find_token(document.body, "\\ce{", 0)
1172 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1173 add_to_preamble(document, ["\\PassOptionsToPackage{version=3}{mhchem}"])
1174 add_to_preamble(document, ["\\usepackage{mhchem}"])
1175 k = find_token(document.header, "\\use_mhchem", 0)
1177 document.warning("Malformed LyX document: Could not find mhchem setting.")
1179 del document.header[k]
1182 def revert_fontenc(document):
1183 " Remove fontencoding param "
1184 i = find_token(document.header, '\\fontencoding', 0)
1186 document.warning("Malformed LyX document: Missing \\fontencoding.")
1188 del document.header[i]
1191 def merge_gbrief(document):
1192 " Merge g-brief-en and g-brief-de to one class "
1194 if document.textclass != "g-brief-de":
1195 if document.textclass == "g-brief-en":
1196 document.textclass = "g-brief"
1197 document.set_textclass()
1200 obsoletedby = { "Brieftext": "Letter",
1201 "Unterschrift": "Signature",
1202 "Strasse": "Street",
1203 "Zusatz": "Addition",
1206 "RetourAdresse": "ReturnAddress",
1207 "MeinZeichen": "MyRef",
1208 "IhrZeichen": "YourRef",
1209 "IhrSchreiben": "YourMail",
1212 "Konto": "BankAccount",
1213 "Postvermerk": "PostalComment",
1214 "Adresse": "Address",
1216 "Betreff": "Reference",
1217 "Anrede": "Opening",
1223 i = find_token(document.body, "\\begin_layout", i)
1227 layout = document.body[i][14:]
1228 if layout in obsoletedby:
1229 document.body[i] = "\\begin_layout " + obsoletedby[layout]
1233 document.textclass = "g-brief"
1234 document.set_textclass()
1237 def revert_gbrief(document):
1238 " Revert g-brief to g-brief-en "
1239 if document.textclass == "g-brief":
1240 document.textclass = "g-brief-en"
1241 document.set_textclass()
1244 def revert_html_options(document):
1245 " Remove html options "
1246 i = find_token(document.header, '\\html_use_mathml', 0)
1248 del document.header[i]
1249 i = find_token(document.header, '\\html_be_strict', 0)
1251 del document.header[i]
1254 def revert_includeonly(document):
1257 i = find_token(document.header, "\\begin_includeonly", i)
1260 j = find_end_of(document.header, i, "\\begin_includeonly", "\\end_includeonly")
1262 # this should not happen
1264 document.header[i : j + 1] = []
1267 def revert_includeall(document):
1268 " Remove maintain_unincluded_children param "
1269 i = find_token(document.header, '\\maintain_unincluded_children', 0)
1271 del document.header[i]
1274 def revert_multirow(document):
1275 " Revert multirow cells in tables "
1279 # cell type 3 is multirow begin cell
1280 i = find_token(document.body, '<cell multirow="3"', i)
1283 # a multirow cell was found
1285 # remove the multirow tag, set the valignment to top
1286 # and remove the bottom line
1287 document.body[i] = document.body[i].replace(' multirow="3" ', ' ')
1288 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1289 document.body[i] = document.body[i].replace(' bottomline="true" ', ' ')
1290 # write ERT to create the multirow cell
1291 # use 2 rows and 2cm as default with because the multirow span
1292 # and the column width is only hardly accessible
1293 subst = [old_put_cmd_in_ert("\\multirow{2}{2cm}{")]
1294 document.body[i + 4:i + 4] = subst
1295 i = find_token(document.body, "</cell>", i)
1297 document.warning("Malformed LyX document: Could not find end of tabular cell.")
1299 subst = [old_put_cmd_in_ert("}")]
1300 document.body[i - 3:i - 3] = subst
1301 # cell type 4 is multirow part cell
1302 i = find_token(document.body, '<cell multirow="4"', i)
1305 # remove the multirow tag, set the valignment to top
1306 # and remove the top line
1307 document.body[i] = document.body[i].replace(' multirow="4" ', ' ')
1308 document.body[i] = document.body[i].replace('valignment="middle"', 'valignment="top"')
1309 document.body[i] = document.body[i].replace(' topline="true" ', ' ')
1311 if multirow == True:
1312 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
1313 add_to_preamble(document, ["\\usepackage{multirow}"])
1316 def convert_math_output(document):
1317 " Convert \html_use_mathml to \html_math_output "
1318 i = find_token(document.header, "\\html_use_mathml", 0)
1321 rgx = re.compile(r'\\html_use_mathml\s+(\w+)')
1322 m = rgx.match(document.header[i])
1324 newval = "0" # MathML
1327 newval = "2" # Images
1328 document.header[i] = "\\html_math_output " + newval
1331 def revert_math_output(document):
1332 " Revert \html_math_output to \html_use_mathml "
1333 i = find_token(document.header, "\\html_math_output", 0)
1336 rgx = re.compile(r'\\html_math_output\s+(\d)')
1337 m = rgx.match(document.header[i])
1341 if val == "1" or val == "2":
1344 document.warning("Unable to match " + document.header[i])
1345 document.header[i] = "\\html_use_mathml " + newval
1349 def revert_inset_preview(document):
1350 " Dissolves the preview inset "
1355 i = find_token(document.body, "\\begin_inset Preview", i)
1358 j = find_end_of_inset(document.body, i)
1360 document.warning("Malformed LyX document: Could not find end of Preview inset.")
1362 #If the layout is Standard we need to remove it, otherwise there
1363 #will be paragraph breaks that shouldn't be there.
1364 k = find_token(document.body, "\\begin_layout Standard", i)
1366 del document.body[i : i+3]
1367 del document.body[j-5 : j-2]
1370 del document.body[i]
1371 del document.body[j-1]
1375 def revert_equalspacing_xymatrix(document):
1376 " Revert a Formula with xymatrix@! to an ERT inset "
1379 has_preamble = False
1380 has_equal_spacing = False
1383 i = find_token(document.body, "\\begin_inset Formula", i)
1386 j = find_end_of_inset(document.body, i)
1388 document.warning("Malformed LyX document: Could not find end of Formula inset.")
1391 for curline in range(i,j):
1392 found = document.body[curline].find("\\xymatrix@!")
1397 has_equal_spacing = True
1398 content = [document.body[i][21:]]
1399 content += document.body[i+1:j]
1400 subst = put_cmd_in_ert(content)
1401 document.body[i:j+1] = subst
1404 for curline in range(i,j):
1405 l = document.body[curline].find("\\xymatrix")
1407 has_preamble = True;
1410 if has_equal_spacing and not has_preamble:
1411 add_to_preamble(document, ['\\usepackage[all]{xy}'])
1414 def revert_notefontcolor(document):
1415 " Reverts greyed-out note font color to preamble code "
1419 i = find_token(document.header, "\\notefontcolor", i)
1422 colorcode = get_value(document.header, '\\notefontcolor', 0)
1423 del document.header[i]
1424 # the color code is in the form #rrggbb where every character denotes a hex number
1425 # convert the string to an int
1426 red = string.atoi(colorcode[1:3],16)
1427 # we want the output "0.5" for the value "127" therefore increment here
1430 redout = float(red) / 256
1431 green = string.atoi(colorcode[3:5],16)
1434 greenout = float(green) / 256
1435 blue = string.atoi(colorcode[5:7],16)
1438 blueout = float(blue) / 256
1439 # write the preamble
1440 insert_to_preamble(0, document,
1441 '% Commands inserted by lyx2lyx to set the font color\n'
1442 '% for greyed-out notes\n'
1443 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1444 + '\\definecolor{note_fontcolor}{rgb}{'
1445 + str(redout) + ', ' + str(greenout)
1446 + ', ' + str(blueout) + '}\n'
1447 + '\\renewenvironment{lyxgreyedout}\n'
1448 + ' {\\textcolor{note_fontcolor}\\bgroup}{\\egroup}\n')
1451 def revert_turkmen(document):
1452 "Set language Turkmen to English"
1454 if document.language == "turkmen":
1455 document.language = "english"
1456 i = find_token(document.header, "\\language", 0)
1458 document.header[i] = "\\language english"
1461 j = find_token(document.body, "\\lang turkmen", j)
1464 document.body[j] = document.body[j].replace("\\lang turkmen", "\\lang english")
1468 def revert_fontcolor(document):
1469 " Reverts font color to preamble code "
1473 i = find_token(document.header, "\\fontcolor", i)
1476 colorcode = get_value(document.header, '\\fontcolor', 0)
1477 del document.header[i]
1478 # don't clutter the preamble if backgroundcolor is not set
1479 if colorcode == "#000000":
1481 # the color code is in the form #rrggbb where every character denotes a hex number
1482 # convert the string to an int
1483 red = string.atoi(colorcode[1:3],16)
1484 # we want the output "0.5" for the value "127" therefore add here
1487 redout = float(red) / 256
1488 green = string.atoi(colorcode[3:5],16)
1491 greenout = float(green) / 256
1492 blue = string.atoi(colorcode[5:7],16)
1495 blueout = float(blue) / 256
1496 # write the preamble
1497 insert_to_preamble(0, document,
1498 '% Commands inserted by lyx2lyx to set the font color\n'
1499 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1500 + '\\definecolor{document_fontcolor}{rgb}{'
1501 + str(redout) + ', ' + str(greenout)
1502 + ', ' + str(blueout) + '}\n'
1503 + '\\color{document_fontcolor}\n')
1506 def revert_shadedboxcolor(document):
1507 " Reverts shaded box color to preamble code "
1511 i = find_token(document.header, "\\boxbgcolor", i)
1514 colorcode = get_value(document.header, '\\boxbgcolor', 0)
1515 del document.header[i]
1516 # the color code is in the form #rrggbb where every character denotes a hex number
1517 # convert the string to an int
1518 red = string.atoi(colorcode[1:3],16)
1519 # we want the output "0.5" for the value "127" therefore increment here
1522 redout = float(red) / 256
1523 green = string.atoi(colorcode[3:5],16)
1526 greenout = float(green) / 256
1527 blue = string.atoi(colorcode[5:7],16)
1530 blueout = float(blue) / 256
1531 # write the preamble
1532 insert_to_preamble(0, document,
1533 '% Commands inserted by lyx2lyx to set the color\n'
1534 '% of boxes with shaded background\n'
1535 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
1536 + '\\definecolor{shadecolor}{rgb}{'
1537 + str(redout) + ', ' + str(greenout)
1538 + ', ' + str(blueout) + '}\n')
1541 def revert_lyx_version(document):
1542 " Reverts LyX Version information from Inset Info "
1543 version = "LyX version"
1545 import lyx2lyx_version
1546 version = lyx2lyx_version.version
1552 i = find_token(document.body, '\\begin_inset Info', i)
1555 j = find_end_of_inset(document.body, i + 1)
1558 document.warning("Malformed LyX document: Could not find end of Info inset.")
1564 # but we shall try to be forgiving.
1566 for k in range(i, j):
1567 if document.body[k].startswith("arg"):
1568 arg = document.body[k][3:].strip().strip('"')
1569 if document.body[k].startswith("type"):
1570 typ = document.body[k][4:].strip().strip('"')
1571 if arg != "version" or typ != "lyxinfo":
1575 # We do not actually know the version of LyX used to produce the document.
1576 # But we can use our version, since we are reverting.
1578 # Now we want to check if the line after "\end_inset" is empty. It normally
1579 # is, so we want to remove it, too.
1581 if document.body[j+1].strip() == "":
1583 document.body[i: lastline] = s
1587 def revert_math_scale(document):
1588 " Remove math scaling and LaTeX options "
1589 i = find_token(document.header, '\\html_math_img_scale', 0)
1591 del document.header[i]
1592 i = find_token(document.header, '\\html_latex_start', 0)
1594 del document.header[i]
1595 i = find_token(document.header, '\\html_latex_end', 0)
1597 del document.header[i]
1600 def revert_pagesizes(document):
1602 " Revert page sizes to default "
1603 i = find_token(document.header, '\\papersize', 0)
1605 size = document.header[i][11:]
1606 if size == "a0paper" or size == "a1paper" or size == "a2paper" \
1607 or size == "a6paper" or size == "b0paper" or size == "b1paper" \
1608 or size == "b2paper" or size == "b6paper" or size == "b0j" \
1609 or size == "b1j" or size == "b2j" or size == "b3j" or size == "b4j" \
1610 or size == "b5j" or size == "b6j":
1611 del document.header[i]
1614 def convert_html_quotes(document):
1615 " Remove quotes around html_latex_start and html_latex_end "
1617 i = find_token(document.header, '\\html_latex_start', 0)
1619 line = document.header[i]
1620 l = re.compile(r'\\html_latex_start\s+"(.*)"')
1623 document.header[i] = "\\html_latex_start " + m.group(1)
1625 i = find_token(document.header, '\\html_latex_end', 0)
1627 line = document.header[i]
1628 l = re.compile(r'\\html_latex_end\s+"(.*)"')
1631 document.header[i] = "\\html_latex_end " + m.group(1)
1634 def revert_html_quotes(document):
1635 " Remove quotes around html_latex_start and html_latex_end "
1637 i = find_token(document.header, '\\html_latex_start', 0)
1639 line = document.header[i]
1640 l = re.compile(r'\\html_latex_start\s+(.*)')
1642 document.header[i] = "\\html_latex_start \"" + m.group(1) + "\""
1644 i = find_token(document.header, '\\html_latex_end', 0)
1646 line = document.header[i]
1647 l = re.compile(r'\\html_latex_end\s+(.*)')
1649 document.header[i] = "\\html_latex_end \"" + m.group(1) + "\""
1652 def revert_output_sync(document):
1653 " Remove forward search options "
1654 i = find_token(document.header, '\\output_sync_macro', 0)
1656 del document.header[i]
1657 i = find_token(document.header, '\\output_sync', 0)
1659 del document.header[i]
1662 def convert_beamer_args(document):
1663 " Convert ERT arguments in Beamer to InsetArguments "
1665 if document.textclass != "beamer" and document.textclass != "article-beamer":
1668 layouts = ("Block", "ExampleBlock", "AlertBlock")
1669 for layout in layouts:
1672 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1675 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1677 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1680 bert = find_token(document.body, '\\begin_inset ERT', blay)
1682 document.warning("Malformed Beamer LyX document: Can't find argument of " + layout + " layout.")
1685 eert = find_end_of_inset(document.body, bert)
1687 document.warning("Malformed LyX document: Can't find end of ERT.")
1691 # So the ERT inset begins at line k and goes to line l. We now wrap it in
1692 # an argument inset.
1693 # Do the end first, so as not to mess up the variables.
1694 document.body[eert + 1:eert + 1] = ['', '\\end_layout', '', '\\end_inset', '']
1695 document.body[bert:bert] = ['\\begin_inset OptArg', 'status open', '',
1696 '\\begin_layout Plain Layout']
1700 def revert_beamer_args(document):
1701 " Revert Beamer arguments to ERT "
1703 if document.textclass != "beamer" and document.textclass != "article-beamer":
1706 layouts = ("Block", "ExampleBlock", "AlertBlock")
1707 for layout in layouts:
1710 blay = find_token(document.body, '\\begin_layout ' + layout, blay)
1713 elay = find_end_of(document.body, blay, '\\begin_layout', '\\end_layout')
1715 document.warning("Malformed LyX document: Can't find end of " + layout + " layout.")
1718 bopt = find_token(document.body, '\\begin_inset OptArg', blay)
1720 # it is legal not to have one of these
1723 eopt = find_end_of_inset(document.body, bopt)
1725 document.warning("Malformed LyX document: Can't find end of argument.")
1728 bplay = find_token(document.body, '\\begin_layout Plain Layout', blay)
1730 document.warning("Malformed LyX document: Can't find plain layout.")
1733 eplay = find_end_of(document.body, bplay, '\\begin_layout', '\\end_layout')
1735 document.warning("Malformed LyX document: Can't find end of plain layout.")
1738 # So the content of the argument inset goes from bplay + 1 to eplay - 1
1742 document.warning(str(bcont) + " " + str(eplay))
1745 # we convert the content of the argument into pure LaTeX...
1746 content = lyx2latex(document, document.body[bcont:eplay])
1747 strlist = put_cmd_in_ert(["{" + content + "}"])
1749 # now replace the optional argument with the ERT
1750 document.body[bopt:eopt + 1] = strlist
1754 def revert_align_decimal(document):
1757 l = document.body[l].find('alignment=decimal')
1760 remove_option(document, l, 'decimal_point')
1761 document.body[l].replace('decimal', 'center')
1764 def convert_optarg(document):
1765 " Convert \\begin_inset OptArg to \\begin_inset Argument "
1768 i = find_token(document.body, '\\begin_inset OptArg', i)
1771 document.body[i] = "\\begin_inset Argument"
1775 def revert_argument(document):
1776 " Convert \\begin_inset Argument to \\begin_inset OptArg "
1779 i = find_token(document.body, '\\begin_inset Argument', i)
1782 document.body[i] = "\\begin_inset OptArg"
1786 def revert_makebox(document):
1787 " Convert \\makebox to TeX code "
1790 # only revert frameless boxes without an inner box
1791 i = find_token(document.body, '\\begin_inset Box Frameless', i)
1795 z = find_end_of_inset(document.body, i)
1797 document.warning("Malformed LyX document: Can't find end of box inset.")
1799 j = find_token(document.body, 'use_makebox 1', i)
1800 # assure we found the makebox of the current box
1801 if j > i + 7 or j == -1:
1804 # remove the \end_inset
1805 document.body[z - 2:z + 1] = put_cmd_in_ert("}")
1806 # determine the alignment
1807 k = find_token(document.body, 'hor_pos', j - 4)
1808 align = document.body[k][9]
1809 # determine the width
1810 l = find_token(document.body, 'width "', j + 1)
1811 length = document.body[l][7:]
1812 # remove trailing '"'
1813 length = length[:-1]
1814 # latex_length returns "bool,length"
1815 length = latex_length(length).split(",")[1]
1816 subst = "\\makebox[" + length + "][" \
1818 document.body[i:i + 13] = put_cmd_in_ert(subst)
1822 def revert_IEEEtran(document):
1823 " Convert IEEEtran layouts and styles to TeX code "
1824 revert_flex_inset(document, "IEEE membership", "\\IEEEmembership", 0)
1825 revert_flex_inset(document, "Lowercase", "\\MakeLowercase", 0)
1832 supported_versions = ["2.0.0","2.0"]
1833 convert = [[346, []],
1839 [352, [convert_splitindex]],
1846 [359, [convert_nomencl_width]],
1856 [369, [convert_author_id]],
1860 [373, [merge_gbrief]],
1866 [379, [convert_math_output]],
1876 [389, [convert_html_quotes]],
1879 [392, [convert_beamer_args]],
1880 [393, [convert_optarg]],
1884 revert = [[393, [revert_makebox]],
1885 [392, [revert_argument]],
1886 [391, [revert_beamer_args]],
1887 [390, [revert_align_decimal, revert_IEEEtran]],
1888 [389, [revert_output_sync]],
1889 [388, [revert_html_quotes]],
1890 [387, [revert_pagesizes]],
1891 [386, [revert_math_scale]],
1892 [385, [revert_lyx_version]],
1893 [384, [revert_shadedboxcolor]],
1894 [383, [revert_fontcolor]],
1895 [382, [revert_turkmen]],
1896 [381, [revert_notefontcolor]],
1897 [380, [revert_equalspacing_xymatrix]],
1898 [379, [revert_inset_preview]],
1899 [378, [revert_math_output]],
1901 [376, [revert_multirow]],
1902 [375, [revert_includeall]],
1903 [374, [revert_includeonly]],
1904 [373, [revert_html_options]],
1905 [372, [revert_gbrief]],
1906 [371, [revert_fontenc]],
1907 [370, [revert_mhchem]],
1908 [369, [revert_suppress_date]],
1909 [368, [revert_author_id]],
1910 [367, [revert_hspace_glue_lengths]],
1911 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
1912 [365, [revert_percent_skip_lengths]],
1913 [364, [revert_paragraph_indentation]],
1914 [363, [revert_branch_filename]],
1915 [362, [revert_longtable_align]],
1916 [361, [revert_applemac]],
1918 [359, [revert_nomencl_cwidth]],
1919 [358, [revert_nomencl_width]],
1920 [357, [revert_custom_processors]],
1921 [356, [revert_ulinelatex]],
1923 [354, [revert_strikeout]],
1924 [353, [revert_printindexall]],
1925 [352, [revert_subindex]],
1926 [351, [revert_splitindex]],
1927 [350, [revert_backgroundcolor]],
1928 [349, [revert_outputformat]],
1929 [348, [revert_xetex]],
1930 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1931 [346, [revert_tabularvalign]],
1932 [345, [revert_swiss]]
1936 if __name__ == "__main__":