1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2008 José Matos <jamatos@lyx.org>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 """ Convert files to the file format generated by lyx 2.0"""
25 from parser_tools import find_token, find_end_of, find_tokens, get_value, get_value_string
27 ####################################################################
28 # Private helper functions
30 def find_end_of_inset(lines, i):
31 " Find end of inset, where lines[i] is included."
32 return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
35 def add_to_preamble(document, text):
36 """ Add text to the preamble if it is not already there.
37 Only the first line is checked!"""
39 if find_token(document.preamble, text[0], 0) != -1:
42 document.preamble.extend(text)
45 def insert_to_preamble(index, document, text):
46 """ Insert text to the preamble at a given line"""
48 document.preamble.insert(index, text)
51 def read_unicodesymbols():
52 " Read the unicodesymbols list of unicode characters and corresponding commands."
53 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
54 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
56 # Two backslashes, followed by some non-word character, and then a character
57 # in brackets. The idea is to check for constructs like: \"{u}, which is how
58 # they are written in the unicodesymbols file; but they can also be written
59 # as: \"u or even \" u.
60 r = re.compile(r'\\\\(\W)\{(\w)\}')
61 for line in fp.readlines():
62 if line[0] != '#' and line.strip() != "":
63 line=line.replace(' "',' ') # remove all quotation marks with spaces before
64 line=line.replace('" ',' ') # remove all quotation marks with spaces after
65 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
67 [ucs4,command,dead] = line.split(None,2)
68 if command[0:1] != "\\":
70 spec_chars.append([command, unichr(eval(ucs4))])
76 # If the character is a double-quote, then we need to escape it, too,
77 # since it is done that way in the LyX file.
78 if m.group(1) == "\"":
81 command += m.group(1) + m.group(2)
82 commandbl += m.group(1) + ' ' + m.group(2)
83 spec_chars.append([command, unichr(eval(ucs4))])
84 spec_chars.append([commandbl, unichr(eval(ucs4))])
89 unicode_reps = read_unicodesymbols()
92 def put_cmd_in_ert(string):
93 for rep in unicode_reps:
94 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
95 string = string.replace('\\', "\\backslash\n")
96 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Plain Layout\n" \
97 + string + "\n\\end_layout\n\\end_inset"
101 def lyx2latex(document, lines):
102 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
103 # clean up multiline stuff
107 for curline in range(len(lines)):
108 line = lines[curline]
109 if line.startswith("\\begin_inset ERT"):
110 # We don't want to replace things inside ERT, so figure out
111 # where the end of the inset is.
112 ert_end = find_end_of_inset(lines, curline + 1)
114 elif line.startswith("\\begin_inset Formula"):
116 elif line.startswith("\\begin_inset Quotes"):
117 # For now, we do a very basic reversion. Someone who understands
118 # quotes is welcome to fix it up.
119 qtype = line[20:].strip()
133 elif line.isspace() or \
134 line.startswith("\\begin_layout") or \
135 line.startswith("\\end_layout") or \
136 line.startswith("\\begin_inset") or \
137 line.startswith("\\end_inset") or \
138 line.startswith("\\lang") or \
139 line.strip() == "status collapsed" or \
140 line.strip() == "status open":
144 # this needs to be added to the preamble because of cases like
145 # \textmu, \textbackslash, etc.
146 add_to_preamble(document, ['% added by lyx2lyx for converted index entries',
147 '\\@ifundefined{textmu}',
148 ' {\\usepackage{textcomp}}{}'])
149 # a lossless reversion is not possible
150 # try at least to handle some common insets and settings
151 if ert_end >= curline:
152 line = line.replace(r'\backslash', r'\\')
154 line = line.replace('&', '\\&{}')
155 line = line.replace('#', '\\#{}')
156 line = line.replace('^', '\\^{}')
157 line = line.replace('%', '\\%{}')
158 line = line.replace('_', '\\_{}')
159 line = line.replace('$', '\\${}')
161 # Do the LyX text --> LaTeX conversion
162 for rep in unicode_reps:
163 line = line.replace(rep[1], rep[0] + "{}")
164 line = line.replace(r'\backslash', r'\textbackslash{}')
165 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
166 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
167 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
168 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
169 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
170 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
171 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
172 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
173 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
178 def latex_length(string):
179 'Convert lengths to their LaTeX representation.'
182 # the string has the form
183 # ValueUnit+ValueUnit-ValueUnit or
184 # ValueUnit+-ValueUnit
185 # the + and - (glue lengths) are optional
186 # the + always precedes the -
188 # Convert relative lengths to LaTeX units
189 units = {"text%":"\\textwidth", "col%":"\\columnwidth",
190 "page%":"\\pagewidth", "line%":"\\linewidth",
191 "theight%":"\\textheight", "pheight%":"\\pageheight"}
192 for unit in units.keys():
193 i = string.find(unit)
196 minus = string.rfind("-", 1, i)
197 plus = string.rfind("+", 0, i)
198 latex_unit = units[unit]
199 if plus == -1 and minus == -1:
201 value = str(float(value)/100)
202 end = string[i + len(unit):]
203 string = value + latex_unit + end
205 value = string[plus+1:i]
206 value = str(float(value)/100)
207 begin = string[:plus+1]
208 end = string[i+len(unit):]
209 string = begin + value + latex_unit + end
211 value = string[minus+1:i]
212 value = str(float(value)/100)
213 begin = string[:minus+1]
214 string = begin + value + latex_unit
216 # replace + and -, but only if the - is not the first character
217 string = string[0] + string[1:].replace("+", " plus ").replace("-", " minus ")
218 # handle the case where "+-1mm" was used, because LaTeX only understands
219 # "plus 1mm minus 1mm"
220 if string.find("plus minus"):
221 lastvaluepos = string.rfind(" ")
222 lastvalue = string[lastvaluepos:]
223 string = string.replace(" ", lastvalue + " ")
225 return "False," + string
227 return "True," + string
230 ####################################################################
233 def revert_swiss(document):
234 " Set language german-ch to ngerman "
236 if document.language == "german-ch":
237 document.language = "ngerman"
238 i = find_token(document.header, "\\language", 0)
240 document.header[i] = "\\language ngerman"
243 j = find_token(document.body, "\\lang german-ch", j)
246 document.body[j] = document.body[j].replace("\\lang german-ch", "\\lang ngerman")
250 def revert_tabularvalign(document):
251 " Revert the tabular valign option "
254 i = find_token(document.body, "\\begin_inset Tabular", i)
257 j = find_end_of_inset(document.body, i)
259 document.warning("Malformed LyX document: Could not find end of tabular.")
262 # don't set a box for longtables, only delete tabularvalignment
263 # the alignment is 2 lines below \\begin_inset Tabular
264 p = document.body[i+2].find("islongtable")
266 q = document.body[i+2].find("tabularvalignment")
268 document.body[i+2] = document.body[i+2][:q-1]
269 document.body[i+2] = document.body[i+2] + '>'
274 tabularvalignment = 'c'
275 # which valignment is specified?
276 m = document.body[i+2].find('tabularvalignment="top"')
278 tabularvalignment = 't'
279 m = document.body[i+2].find('tabularvalignment="bottom"')
281 tabularvalignment = 'b'
282 # delete tabularvalignment
283 q = document.body[i+2].find("tabularvalignment")
285 document.body[i+2] = document.body[i+2][:q-1]
286 document.body[i+2] = document.body[i+2] + '>'
288 # don't add a box when centered
289 if tabularvalignment == 'c':
292 subst = ['\\end_layout', '\\end_inset']
293 document.body[j+1:j+1] = subst # just inserts those lines
294 subst = ['\\begin_inset Box Frameless',
295 'position "' + tabularvalignment +'"',
300 # we don't know the width, assume 50%
304 'height_special "totalheight"',
307 '\\begin_layout Plain Layout']
308 document.body[i:i] = subst # this just inserts the array at i
309 i += len(subst) + 2 # adjust i to save a few cycles
312 def revert_phantom(document):
313 " Reverts phantom to ERT "
317 i = find_token(document.body, "\\begin_inset Phantom Phantom", i)
320 substi = document.body[i].replace('\\begin_inset Phantom Phantom', \
321 '\\begin_inset ERT\nstatus collapsed\n\n' \
322 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
323 'phantom{\n\\end_layout\n\n\\end_inset\n')
324 substi = substi.split('\n')
325 document.body[i : i+4] = substi
327 j = find_token(document.body, "\\end_layout", i)
329 document.warning("Malformed LyX document: Could not find end of Phantom inset.")
331 substj = document.body[j].replace('\\end_layout', \
332 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
333 '\\begin_layout Plain Layout\n\n' \
334 '}\n\\end_layout\n\n\\end_inset\n')
335 substj = substj.split('\n')
336 document.body[j : j+4] = substj
340 def revert_hphantom(document):
341 " Reverts hphantom to ERT "
345 i = find_token(document.body, "\\begin_inset Phantom HPhantom", i)
348 substi = document.body[i].replace('\\begin_inset Phantom HPhantom', \
349 '\\begin_inset ERT\nstatus collapsed\n\n' \
350 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
351 'hphantom{\n\\end_layout\n\n\\end_inset\n')
352 substi = substi.split('\n')
353 document.body[i : i+4] = substi
355 j = find_token(document.body, "\\end_layout", i)
357 document.warning("Malformed LyX document: Could not find end of HPhantom inset.")
359 substj = document.body[j].replace('\\end_layout', \
360 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
361 '\\begin_layout Plain Layout\n\n' \
362 '}\n\\end_layout\n\n\\end_inset\n')
363 substj = substj.split('\n')
364 document.body[j : j+4] = substj
368 def revert_vphantom(document):
369 " Reverts vphantom to ERT "
373 i = find_token(document.body, "\\begin_inset Phantom VPhantom", i)
376 substi = document.body[i].replace('\\begin_inset Phantom VPhantom', \
377 '\\begin_inset ERT\nstatus collapsed\n\n' \
378 '\\begin_layout Plain Layout\n\n\n\\backslash\n' \
379 'vphantom{\n\\end_layout\n\n\\end_inset\n')
380 substi = substi.split('\n')
381 document.body[i : i+4] = substi
383 j = find_token(document.body, "\\end_layout", i)
385 document.warning("Malformed LyX document: Could not find end of VPhantom inset.")
387 substj = document.body[j].replace('\\end_layout', \
388 '\\size default\n\n\\begin_inset ERT\nstatus collapsed\n\n' \
389 '\\begin_layout Plain Layout\n\n' \
390 '}\n\\end_layout\n\n\\end_inset\n')
391 substj = substj.split('\n')
392 document.body[j : j+4] = substj
396 def revert_xetex(document):
397 " Reverts documents that use XeTeX "
398 i = find_token(document.header, '\\use_xetex', 0)
400 document.warning("Malformed LyX document: Missing \\use_xetex.")
402 if get_value(document.header, "\\use_xetex", i) == 'false':
403 del document.header[i]
405 del document.header[i]
406 # 1.) set doc encoding to utf8-plain
407 i = find_token(document.header, "\\inputencoding", 0)
409 document.warning("Malformed LyX document: Missing \\inputencoding.")
410 document.header[i] = "\\inputencoding utf8-plain"
411 # 2.) check font settings
412 l = find_token(document.header, "\\font_roman", 0)
414 document.warning("Malformed LyX document: Missing \\font_roman.")
415 line = document.header[l]
416 l = re.compile(r'\\font_roman (.*)$')
419 l = find_token(document.header, "\\font_sans", 0)
421 document.warning("Malformed LyX document: Missing \\font_sans.")
422 line = document.header[l]
423 l = re.compile(r'\\font_sans (.*)$')
426 l = find_token(document.header, "\\font_typewriter", 0)
428 document.warning("Malformed LyX document: Missing \\font_typewriter.")
429 line = document.header[l]
430 l = re.compile(r'\\font_typewriter (.*)$')
432 typewriter = m.group(1)
433 osf = get_value(document.header, '\\font_osf', 0) == "true"
434 sf_scale = float(get_value(document.header, '\\font_sf_scale', 0))
435 tt_scale = float(get_value(document.header, '\\font_tt_scale', 0))
436 # 3.) set preamble stuff
437 pretext = '%% This document must be processed with xelatex!\n'
438 pretext += '\\usepackage{fontspec}\n'
439 if roman != "default":
440 pretext += '\\setmainfont[Mapping=tex-text]{' + roman + '}\n'
441 if sans != "default":
442 pretext += '\\setsansfont['
444 pretext += 'Scale=' + str(sf_scale / 100) + ','
445 pretext += 'Mapping=tex-text]{' + sans + '}\n'
446 if typewriter != "default":
447 pretext += '\\setmonofont'
449 pretext += '[Scale=' + str(tt_scale / 100) + ']'
450 pretext += '{' + typewriter + '}\n'
452 pretext += '\\defaultfontfeatures{Numbers=OldStyle}\n'
453 pretext += '\usepackage{xunicode}\n'
454 pretext += '\usepackage{xltxtra}\n'
455 insert_to_preamble(0, document, pretext)
456 # 4.) reset font settings
457 i = find_token(document.header, "\\font_roman", 0)
459 document.warning("Malformed LyX document: Missing \\font_roman.")
460 document.header[i] = "\\font_roman default"
461 i = find_token(document.header, "\\font_sans", 0)
463 document.warning("Malformed LyX document: Missing \\font_sans.")
464 document.header[i] = "\\font_sans default"
465 i = find_token(document.header, "\\font_typewriter", 0)
467 document.warning("Malformed LyX document: Missing \\font_typewriter.")
468 document.header[i] = "\\font_typewriter default"
469 i = find_token(document.header, "\\font_osf", 0)
471 document.warning("Malformed LyX document: Missing \\font_osf.")
472 document.header[i] = "\\font_osf false"
473 i = find_token(document.header, "\\font_sc", 0)
475 document.warning("Malformed LyX document: Missing \\font_sc.")
476 document.header[i] = "\\font_sc false"
477 i = find_token(document.header, "\\font_sf_scale", 0)
479 document.warning("Malformed LyX document: Missing \\font_sf_scale.")
480 document.header[i] = "\\font_sf_scale 100"
481 i = find_token(document.header, "\\font_tt_scale", 0)
483 document.warning("Malformed LyX document: Missing \\font_tt_scale.")
484 document.header[i] = "\\font_tt_scale 100"
487 def revert_outputformat(document):
488 " Remove default output format param "
489 i = find_token(document.header, '\\default_output_format', 0)
491 document.warning("Malformed LyX document: Missing \\default_output_format.")
493 del document.header[i]
496 def revert_backgroundcolor(document):
497 " Reverts background color to preamble code "
501 i = find_token(document.header, "\\backgroundcolor", i)
504 colorcode = get_value(document.header, '\\backgroundcolor', 0)
505 del document.header[i]
506 # don't clutter the preamble if backgroundcolor is not set
507 if colorcode == "#ffffff":
509 # the color code is in the form #rrggbb where every character denotes a hex number
510 # convert the string to an int
511 red = string.atoi(colorcode[1:3],16)
512 # we want the output "0.5" for the value "127" therefore add here
515 redout = float(red) / 256
516 green = string.atoi(colorcode[3:5],16)
519 greenout = float(green) / 256
520 blue = string.atoi(colorcode[5:7],16)
523 blueout = float(blue) / 256
525 insert_to_preamble(0, document,
526 '% Commands inserted by lyx2lyx to set the background color\n'
527 + '\\@ifundefined{definecolor}{\\usepackage{color}}{}\n'
528 + '\\definecolor{page_backgroundcolor}{rgb}{'
529 + str(redout) + ', ' + str(greenout)
530 + ', ' + str(blueout) + '}\n'
531 + '\\pagecolor{page_backgroundcolor}\n')
534 def revert_splitindex(document):
535 " Reverts splitindex-aware documents "
536 i = find_token(document.header, '\\use_indices', 0)
538 document.warning("Malformed LyX document: Missing \\use_indices.")
540 indices = get_value(document.header, "\\use_indices", i)
542 if indices == "true":
543 preamble += "\\usepackage{splitidx}\n"
544 del document.header[i]
547 i = find_token(document.header, "\\index", i)
550 k = find_token(document.header, "\\end_index", i)
552 document.warning("Malformed LyX document: Missing \\end_index.")
554 line = document.header[i]
555 l = re.compile(r'\\index (.*)$')
558 ishortcut = get_value(document.header, '\\shortcut', i, k)
559 if ishortcut != "" and indices == "true":
560 preamble += "\\newindex[" + iname + "]{" + ishortcut + "}\n"
561 del document.header[i:k+1]
564 insert_to_preamble(0, document, preamble)
567 i = find_token(document.body, "\\begin_inset Index", i)
570 line = document.body[i]
571 l = re.compile(r'\\begin_inset Index (.*)$')
574 if itype == "idx" or indices == "false":
575 document.body[i] = "\\begin_inset Index"
577 k = find_end_of_inset(document.body, i)
580 content = lyx2latex(document, document.body[i:k])
582 content = content.replace('"', r'\"')
583 subst = [put_cmd_in_ert("\\sindex[" + itype + "]{" + content + "}")]
584 document.body[i:k+1] = subst
588 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
591 k = find_end_of_inset(document.body, i)
592 ptype = get_value(document.body, 'type', i, k).strip('"')
594 j = find_token(document.body, "type", i, k)
596 elif indices == "false":
597 del document.body[i:k+1]
599 subst = [put_cmd_in_ert("\\printindex[" + ptype + "]{}")]
600 document.body[i:k+1] = subst
604 def convert_splitindex(document):
605 " Converts index and printindex insets to splitindex-aware format "
608 i = find_token(document.body, "\\begin_inset Index", i)
611 document.body[i] = document.body[i].replace("\\begin_inset Index",
612 "\\begin_inset Index idx")
616 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
619 if document.body[i + 1].find('LatexCommand printindex') == -1:
620 document.warning("Malformed LyX document: Incomplete printindex inset.")
622 subst = ["LatexCommand printindex",
624 document.body[i + 1:i + 2] = subst
628 def revert_subindex(document):
629 " Reverts \\printsubindex CommandInset types "
630 i = find_token(document.header, '\\use_indices', 0)
632 document.warning("Malformed LyX document: Missing \\use_indices.")
634 indices = get_value(document.header, "\\use_indices", i)
637 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
640 k = find_end_of_inset(document.body, i)
641 ctype = get_value(document.body, 'LatexCommand', i, k)
642 if ctype != "printsubindex":
645 ptype = get_value(document.body, 'type', i, k).strip('"')
646 if indices == "false":
647 del document.body[i:k+1]
649 subst = [put_cmd_in_ert("\\printsubindex[" + ptype + "]{}")]
650 document.body[i:k+1] = subst
654 def revert_printindexall(document):
655 " Reverts \\print[sub]index* CommandInset types "
656 i = find_token(document.header, '\\use_indices', 0)
658 document.warning("Malformed LyX document: Missing \\use_indices.")
660 indices = get_value(document.header, "\\use_indices", i)
663 i = find_token(document.body, "\\begin_inset CommandInset index_print", i)
666 k = find_end_of_inset(document.body, i)
667 ctype = get_value(document.body, 'LatexCommand', i, k)
668 if ctype != "printindex*" and ctype != "printsubindex*":
671 if indices == "false":
672 del document.body[i:k+1]
674 subst = [put_cmd_in_ert("\\" + ctype + "{}")]
675 document.body[i:k+1] = subst
679 def revert_strikeout(document):
680 " Reverts \\strikeout character style "
682 i = find_token(document.body, '\\strikeout', 0)
688 def revert_uulinewave(document):
689 " Reverts \\uuline, and \\uwave character styles "
691 i = find_token(document.body, '\\uuline', 0)
696 i = find_token(document.body, '\\uwave', 0)
702 def revert_ulinelatex(document):
703 " Reverts \\uline character style "
704 i = find_token(document.body, '\\bar under', 0)
707 insert_to_preamble(0, document,
708 '% Commands inserted by lyx2lyx for proper underlining\n'
709 + '\\PassOptionsToPackage{normalem}{ulem}\n'
710 + '\\usepackage{ulem}\n'
711 + '\\let\\cite@rig\\cite\n'
712 + '\\newcommand{\\b@xcite}[2][\\%]{\\def\\def@pt{\\%}\\def\\pas@pt{#1}\n'
713 + ' \\mbox{\\ifx\\def@pt\\pas@pt\\cite@rig{#2}\\else\\cite@rig[#1]{#2}\\fi}}\n'
714 + '\\renewcommand{\\underbar}[1]{{\\let\\cite\\b@xcite\\uline{#1}}}\n')
717 def revert_custom_processors(document):
718 " Remove bibtex_command and index_command params "
719 i = find_token(document.header, '\\bibtex_command', 0)
721 document.warning("Malformed LyX document: Missing \\bibtex_command.")
723 del document.header[i]
724 i = find_token(document.header, '\\index_command', 0)
726 document.warning("Malformed LyX document: Missing \\index_command.")
728 del document.header[i]
731 def convert_nomencl_width(document):
732 " Add set_width param to nomencl_print "
735 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
738 document.body.insert(i + 2, "set_width \"none\"")
742 def revert_nomencl_width(document):
743 " Remove set_width param from nomencl_print "
746 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
749 j = find_end_of_inset(document.body, i)
750 l = find_token(document.body, "set_width", i, j)
752 document.warning("Can't find set_width option for nomencl_print!")
759 def revert_nomencl_cwidth(document):
760 " Remove width param from nomencl_print "
763 i = find_token(document.body, "\\begin_inset CommandInset nomencl_print", i)
766 j = find_end_of_inset(document.body, i)
767 l = find_token(document.body, "width", i, j)
769 document.warning("Can't find width option for nomencl_print!")
772 width = get_value(document.body, "width", i, j).strip('"')
774 add_to_preamble(document, ["\\setlength{\\nomlabelwidth}{" + width + "}"])
778 def revert_applemac(document):
779 " Revert applemac encoding to auto "
781 if document.encoding == "applemac":
782 document.encoding = "auto"
783 i = find_token(document.header, "\\encoding", 0)
785 document.header[i] = "\\encoding auto"
788 def revert_longtable_align(document):
789 " Remove longtable alignment setting "
793 i = find_token(document.body, "\\begin_inset Tabular", i)
796 # the alignment is 2 lines below \\begin_inset Tabular
797 j = document.body[i+2].find("longtabularalignment")
800 document.body[i+2] = document.body[i+2][:j-1]
801 document.body[i+2] = document.body[i+2] + '>'
805 def revert_branch_filename(document):
806 " Remove \\filename_suffix parameter from branches "
809 i = find_token(document.header, "\\filename_suffix", i)
812 del document.header[i]
815 def revert_paragraph_indentation(document):
816 " Revert custom paragraph indentation to preamble code "
819 i = find_token(document.header, "\\paragraph_indentation", i)
822 # only remove the preamble line if default
823 # otherwise also write the value to the preamble
824 length = get_value(document.header, "\\paragraph_indentation", i)
825 if length == "default":
826 del document.header[i]
829 # handle percent lengths
830 # latex_length returns "bool,length"
831 length = latex_length(length).split(",")[1]
832 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
833 add_to_preamble(document, ["\\setlength{\\parindent}{" + length + "}"])
834 del document.header[i]
838 def revert_percent_skip_lengths(document):
839 " Revert relative lengths for paragraph skip separation to preamble code "
842 i = find_token(document.header, "\\defskip", i)
845 length = get_value(document.header, "\\defskip", i)
846 # only revert when a custom length was set and when
847 # it used a percent length
848 if length not in ('smallskip', 'medskip', 'bigskip'):
849 # handle percent lengths
850 length = latex_length(length)
851 # latex_length returns "bool,length"
852 percent = length.split(",")[0]
853 length = length.split(",")[1]
854 if percent == "True":
855 add_to_preamble(document, ["% this command was inserted by lyx2lyx"])
856 add_to_preamble(document, ["\\setlength{\\parskip}{" + length + "}"])
857 # set defskip to medskip as default
858 document.header[i] = "\\defskip medskip"
862 def revert_percent_vspace_lengths(document):
863 " Revert relative VSpace lengths to ERT "
866 i = find_token(document.body, "\\begin_inset VSpace", i)
869 # only revert if a custom length was set and if
870 # it used a percent length
871 line = document.body[i]
872 r = re.compile(r'\\begin_inset VSpace (.*)$')
875 if length not in ('defskip', 'smallskip', 'medskip', 'bigskip', 'vfill'):
876 # check if the space has a star (protected space)
877 protected = (document.body[i].rfind("*") != -1)
879 length = length.rstrip('*')
880 # handle percent lengths
881 length = latex_length(length)
882 # latex_length returns "bool,length"
883 percent = length.split(",")[0]
884 length = length.split(",")[1]
885 # revert the VSpace inset to ERT
886 if percent == "True":
888 subst = [put_cmd_in_ert("\\vspace*{" + length + "}")]
890 subst = [put_cmd_in_ert("\\vspace{" + length + "}")]
891 document.body[i:i+2] = subst
895 def revert_percent_hspace_lengths(document):
896 " Revert relative HSpace lengths to ERT "
899 i = find_token(document.body, "\\begin_inset space \\hspace", i)
902 protected = (document.body[i].find("\\hspace*{}") != -1)
903 # only revert if a custom length was set and if
904 # it used a percent length
905 length = get_value(document.body, '\\length', i+1)
907 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
909 # handle percent lengths
910 length = latex_length(length)
911 # latex_length returns "bool,length"
912 percent = length.split(",")[0]
913 length = length.split(",")[1]
914 # revert the HSpace inset to ERT
915 if percent == "True":
917 subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
919 subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
920 document.body[i:i+3] = subst
924 def revert_hspace_glue_lengths(document):
925 " Revert HSpace glue lengths to ERT "
928 i = find_token(document.body, "\\begin_inset space \\hspace", i)
931 protected = (document.body[i].find("\\hspace*{}") != -1)
932 length = get_value(document.body, '\\length', i+1)
934 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
936 # only revert if the length contains a plus or minus at pos != 0
937 glue = re.compile(r'.+[\+-]')
938 if glue.search(length):
939 # handle percent lengths
940 # latex_length returns "bool,length"
941 length = latex_length(length).split(",")[1]
942 # revert the HSpace inset to ERT
944 subst = [put_cmd_in_ert("\\hspace*{" + length + "}")]
946 subst = [put_cmd_in_ert("\\hspace{" + length + "}")]
947 document.body[i:i+3] = subst
955 supported_versions = ["2.0.0","2.0"]
956 convert = [[346, []],
962 [352, [convert_splitindex]],
969 [359, [convert_nomencl_width]],
981 revert = [[367, [revert_hspace_glue_lengths]],
982 [366, [revert_percent_vspace_lengths, revert_percent_hspace_lengths]],
983 [365, [revert_percent_skip_lengths]],
984 [364, [revert_paragraph_indentation]],
985 [363, [revert_branch_filename]],
986 [362, [revert_longtable_align]],
987 [361, [revert_applemac]],
989 [359, [revert_nomencl_cwidth]],
990 [358, [revert_nomencl_width]],
991 [357, [revert_custom_processors]],
992 [356, [revert_ulinelatex]],
993 [355, [revert_uulinewave]],
994 [354, [revert_strikeout]],
995 [353, [revert_printindexall]],
996 [352, [revert_subindex]],
997 [351, [revert_splitindex]],
998 [350, [revert_backgroundcolor]],
999 [349, [revert_outputformat]],
1000 [348, [revert_xetex]],
1001 [347, [revert_phantom, revert_hphantom, revert_vphantom]],
1002 [346, [revert_tabularvalign]],
1003 [345, [revert_swiss]]
1007 if __name__ == "__main__":