1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2007-2008 The LyX Team <lyx-devel@lists.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 1.6"""
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")
36 # document.body[i] = wrap_insert_ert(...)
37 # wrap_into_ert may returns a multiline string, which should NOT appear
38 # in document.body. Insetad, do something like this:
39 # subst = wrap_inset_ert(...)
40 # subst = subst.split('\n')
41 # document.body[i:i+1] = subst
43 # where the last statement resets the counter to accord with the added
45 def wrap_into_ert(string, src, dst):
46 '''Within string, replace occurrences of src with dst, wrapped into ERT
47 E.g.: wrap_into_ert('sch\"on', "\\", "\\backslash") is:
48 sch<ERT>\\backslash</ERT>"on'''
49 return string.replace(src, '\n\\begin_inset ERT\nstatus collapsed\n\\begin_layout Standard\n'
50 + dst + '\n\\end_layout\n\\end_inset\n')
52 def put_cmd_in_ert(string):
53 for rep in unicode_reps:
54 string = string.replace(rep[1], rep[0].replace('\\\\', '\\'))
55 string = string.replace('\\', "\\backslash\n")
56 string = "\\begin_inset ERT\nstatus collapsed\n\\begin_layout Standard\n" \
57 + string + "\n\\end_layout\n\\end_inset"
60 def add_to_preamble(document, text):
61 """ Add text to the preamble if it is not already there.
62 Only the first line is checked!"""
64 if find_token(document.preamble, text[0], 0) != -1:
67 document.preamble.extend(text)
69 def insert_to_preamble(index, document, text):
70 """ Insert text to the preamble at a given line"""
72 document.preamble.insert(index, text)
74 # Convert a LyX length into a LaTeX length
76 units = {"text%":"\\backslash\ntextwidth", "col%":"\\backslash\ncolumnwidth",
77 "page%":"\\backslash\npagewidth", "line%":"\\backslash\nlinewidth",
78 "theight%":"\\backslash\ntextheight", "pheight%":"\\backslash\npageheight"}
80 # Convert LyX units to LaTeX units
81 for unit in units.keys():
82 if len.find(unit) != -1:
83 len = '%f' % (len2value(len) / 100)
84 len = len.strip('0') + units[unit]
89 # Return the value of len without the unit in numerical form.
91 result = re.search('([+-]?[0-9.]+)', len)
93 return float(result.group(1))
97 # Unfortunately, this doesn't really work, since Standard isn't always default.
98 # But it's as good as we can do right now.
99 def find_default_layout(document, start, end):
100 l = find_token(document.body, "\\begin_layout Standard", start, end)
102 l = find_token(document.body, "\\begin_layout PlainLayout", start, end)
104 l = find_token(document.body, "\\begin_layout Plain Layout", start, end)
107 def get_option(document, m, option, default):
108 l = document.body[m].find(option)
111 val = document.body[m][l:].split('"')[1]
114 def remove_option(document, m, option):
115 l = document.body[m].find(option)
117 val = document.body[m][l:].split('"')[1]
118 document.body[m] = document.body[m][:l-1] + document.body[m][l+len(option + '="' + val + '"'):]
121 def set_option(document, m, option, value):
122 l = document.body[m].find(option)
124 oldval = document.body[m][l:].split('"')[1]
125 l = l + len(option + '="')
126 document.body[m] = document.body[m][:l] + value + document.body[m][l+len(oldval):]
128 document.body[m] = document.body[m][:-1] + ' ' + option + '="' + value + '">'
132 def read_unicodesymbols():
133 " Read the unicodesymbols list of unicode characters and corresponding commands."
134 pathname = os.path.abspath(os.path.dirname(sys.argv[0]))
135 fp = open(os.path.join(pathname.strip('lyx2lyx'), 'unicodesymbols'))
137 # Two backslashes, followed by some non-word character, and then a character
138 # in brackets. The idea is to check for constructs like: \"{u}, which is how
139 # they are written in the unicodesymbols file; but they can also be written
140 # as: \"u or even \" u.
141 r = re.compile(r'\\\\(\W)\{(\w)\}')
142 for line in fp.readlines():
143 if line[0] != '#' and line.strip() != "":
144 line=line.replace(' "',' ') # remove all quotation marks with spaces before
145 line=line.replace('" ',' ') # remove all quotation marks with spaces after
146 line=line.replace(r'\"','"') # replace \" by " (for characters with diaeresis)
148 [ucs4,command,dead] = line.split(None,2)
149 if command[0:1] != "\\":
151 spec_chars.append([command, unichr(eval(ucs4))])
157 # If the character is a double-quote, then we need to escape it, too,
158 # since it is done that way in the LyX file.
159 if m.group(1) == "\"":
162 command += m.group(1) + m.group(2)
163 commandbl += m.group(1) + ' ' + m.group(2)
164 spec_chars.append([command, unichr(eval(ucs4))])
165 spec_chars.append([commandbl, unichr(eval(ucs4))])
170 def extract_argument(line):
171 'Extracts a LaTeX argument from the start of line. Returns (arg, rest).'
176 bracere = re.compile("(\s*)(.*)")
177 n = bracere.match(line)
178 whitespace = n.group(1)
181 if brace != "[" and brace != "{":
205 # We never found the matching brace
206 # So, to be on the safe side, let's just return everything
207 # which will then get wrapped as ERT
209 return (line[:pos + 1], line[pos + 1:])
212 def latex2ert(line, isindex):
213 '''Converts LaTeX commands into ERT. line may well be a multi-line
214 string when it is returned.'''
219 ## FIXME Escaped \ ??
220 # This regex looks for a LaTeX command---i.e., something of the form
221 # "\alPhaStuFF", or "\X", where X is any character---where the command
222 # may also be preceded by an additional backslash, which is how it would
223 # appear (e.g.) in an InsetIndex.
224 labelre = re.compile(r'(.*?)\\?(\\(?:[a-zA-Z]+|.))(.*)')
226 m = labelre.match(line)
233 (arg, rest) = extract_argument(end)
238 # If we wanted to put labels into an InsetLabel, for example, then we
239 # would just need to test here for cmd == "label" and then take some
240 # appropriate action, i.e., to use arg to get the content and then
241 # wrap it appropriately.
242 cmd = put_cmd_in_ert(cmd)
243 retval += "\n" + cmd + "\n"
245 m = labelre.match(line)
246 # put all remaining braces in ERT
247 line = wrap_into_ert(line, '}', '}')
248 line = wrap_into_ert(line, '{', '{')
250 # active character that is not available in all font encodings
251 line = wrap_into_ert(line, '|', '|')
256 unicode_reps = read_unicodesymbols()
259 #Might should do latex2ert first, then deal with stuff that DOESN'T
260 #end up inside ERT. That routine could be modified so that it returned
261 #a list of lines, and we could then skip ERT bits and only deal with
263 def latex2lyx(data, isindex):
264 '''Takes a string, possibly multi-line, and returns the result of
265 converting LaTeX constructs into LyX constructs. Returns a list of
266 lines, suitable for insertion into document.body.
267 The bool isindex specifies whether we are in an index macro (which
268 has some specific active characters that need to be ERTed).'''
274 # Convert LaTeX to Unicode
275 # Commands of this sort need to be checked to make sure they are
276 # followed by a non-alpha character, lest we replace too much.
277 hardone = re.compile(r'^\\\\[a-zA-Z]+$')
279 for rep in unicode_reps:
280 if hardone.match(rep[0]):
283 pos = data.find(rep[0], pos)
286 nextpos = pos + len(rep[0])
287 if nextpos < len(data) and data[nextpos].isalpha():
288 # not the end of that command
291 data = data[:pos] + rep[1] + data[nextpos:]
294 data = data.replace(rep[0], rep[1])
298 data = wrap_into_ert(data, r'\"', '"')
300 data = data.replace('\\\\', '\\')
303 mathre = re.compile('^(.*?)(\$.*?\$)(.*)')
304 lines = data.split('\n')
306 #document.warning("LINE: " + line)
307 #document.warning(str(i) + ":" + document.body[i])
308 #document.warning("LAST: " + document.body[-1])
313 f = m.group(2).replace('\\\\', '\\')
317 s = latex2ert(s, isindex)
318 subst = s.split('\n')
320 retval.append("\\begin_inset Formula " + f)
321 retval.append("\\end_inset")
323 # Handle whatever is left, which is just text
324 g = latex2ert(g, isindex)
325 subst = g.split('\n')
330 def lyxline2latex(document, line, inert):
331 'Convert some LyX stuff into corresponding LaTeX stuff line-wise, as best we can.'
332 if line.startswith("\\begin_inset Formula"):
334 elif line.startswith("\\begin_inset Quotes"):
335 # For now, we do a very basic reversion. Someone who understands
336 # quotes is welcome to fix it up.
337 qtype = line[20:].strip()
351 elif line.isspace() or \
352 line.startswith("\\begin_layout") or \
353 line.startswith("\\end_layout") or \
354 line.startswith("\\begin_inset") or \
355 line.startswith("\\end_inset") or \
356 line.startswith("\\lang") or \
357 line.strip() == "status collapsed" or \
358 line.strip() == "status open":
362 # this needs to be added to the preamble because of cases like
363 # \textmu, \textbackslash, etc.
364 add_to_preamble(document, ['% added by lyx2lyx for converted entries',
365 '\\@ifundefined{textmu}',
366 ' {\\usepackage{textcomp}}{}'])
367 # a lossless reversion is not possible
368 # try at least to handle some common insets and settings
370 line = line.replace(r'\backslash', '\\')
372 line = line.replace('&', '\\&{}')
373 line = line.replace('#', '\\#{}')
374 line = line.replace('^', '\\^{}')
375 line = line.replace('%', '\\%{}')
376 line = line.replace('_', '\\_{}')
377 line = line.replace('$', '\\${}')
379 # Do the LyX text --> LaTeX conversion
380 for rep in unicode_reps:
381 line = line.replace(rep[1], rep[0].replace('\\\\', '\\') + "{}")
382 line = line.replace(r'\backslash', r'\textbackslash{}')
383 line = line.replace(r'\series bold', r'\bfseries{}').replace(r'\series default', r'\mdseries{}')
384 line = line.replace(r'\shape italic', r'\itshape{}').replace(r'\shape smallcaps', r'\scshape{}')
385 line = line.replace(r'\shape slanted', r'\slshape{}').replace(r'\shape default', r'\upshape{}')
386 line = line.replace(r'\emph on', r'\em{}').replace(r'\emph default', r'\em{}')
387 line = line.replace(r'\noun on', r'\scshape{}').replace(r'\noun default', r'\upshape{}')
388 line = line.replace(r'\bar under', r'\underbar{').replace(r'\bar default', r'}')
389 line = line.replace(r'\family sans', r'\sffamily{}').replace(r'\family default', r'\normalfont{}')
390 line = line.replace(r'\family typewriter', r'\ttfamily{}').replace(r'\family roman', r'\rmfamily{}')
391 line = line.replace(r'\InsetSpace ', r'').replace(r'\SpecialChar ', r'')
395 def lyx2latex(document, lines):
396 'Convert some LyX stuff into corresponding LaTeX stuff, as best we can.'
397 # clean up multiline stuff
401 for curline in range(len(lines)):
402 line = lines[curline]
403 if line.startswith("\\begin_inset ERT"):
404 # We don't want to replace things inside ERT, so figure out
405 # where the end of the inset is.
406 ert_end = find_end_of_inset(lines, curline + 1)
408 inert = ert_end >= curline
409 content += lyxline2latex(document, lines[curline], inert)
414 ####################################################################
416 def convert_ltcaption(document):
419 i = find_token(document.body, "\\begin_inset Tabular", i)
422 j = find_end_of_inset(document.body, i + 1)
424 document.warning("Malformed LyX document: Could not find end of tabular.")
427 nrows = int(document.body[i+1].split('"')[3])
428 ncols = int(document.body[i+1].split('"')[5])
431 for k in range(nrows):
432 m = find_token(document.body, "<row", m)
435 for k in range(ncols):
436 m = find_token(document.body, "<cell", m)
438 mend = find_token(document.body, "</cell>", m + 1)
439 # first look for caption insets
440 mcap = find_token(document.body, "\\begin_inset Caption", m + 1, mend)
441 # then look for ERT captions
443 mcap = find_token(document.body, "caption", m + 1, mend)
445 mcap = find_token(document.body, "\\backslash", mcap - 1, mcap)
448 if caption == 'true':
450 set_option(document, r, 'caption', 'true')
451 set_option(document, m, 'multicolumn', '1')
452 set_option(document, m, 'bottomline', 'false')
453 set_option(document, m, 'topline', 'false')
454 set_option(document, m, 'rightline', 'false')
455 set_option(document, m, 'leftline', 'false')
456 #j = find_end_of_inset(document.body, j + 1)
458 set_option(document, m, 'multicolumn', '2')
465 #FIXME Use of wrap_into_ert can confuse lyx2lyx
466 def revert_ltcaption(document):
469 i = find_token(document.body, "\\begin_inset Tabular", i)
472 j = find_end_of_inset(document.body, i + 1)
474 document.warning("Malformed LyX document: Could not find end of tabular.")
478 nrows = int(document.body[i+1].split('"')[3])
479 ncols = int(document.body[i+1].split('"')[5])
481 for k in range(nrows):
482 m = find_token(document.body, "<row", m)
483 caption = get_option(document, m, 'caption', 'false')
484 if caption == 'true':
485 remove_option(document, m, 'caption')
486 for k in range(ncols):
487 m = find_token(document.body, "<cell", m)
488 remove_option(document, m, 'multicolumn')
490 m = find_token(document.body, "\\begin_inset Caption", m)
493 m = find_end_of_inset(document.body, m + 1)
494 document.body[m] += wrap_into_ert("","","\\backslash\n\\backslash\n%")
500 def convert_tablines(document):
503 i = find_token(document.body, "\\begin_inset Tabular", i)
505 # LyX 1.3 inserted an extra space between \begin_inset
506 # and Tabular so let us try if this is the case and fix it.
507 i = find_token(document.body, "\\begin_inset Tabular", i)
511 document.body[i] = "\\begin_inset Tabular"
512 j = find_end_of_inset(document.body, i + 1)
514 document.warning("Malformed LyX document: Could not find end of tabular.")
518 nrows = int(document.body[i+1].split('"')[3])
519 ncols = int(document.body[i+1].split('"')[5])
522 for k in range(ncols):
523 m = find_token(document.body, "<column", m)
524 left = get_option(document, m, 'leftline', 'false')
525 right = get_option(document, m, 'rightline', 'false')
526 col_info.append([left, right])
527 remove_option(document, m, 'leftline')
528 remove_option(document, m, 'rightline')
532 for k in range(nrows):
533 m = find_token(document.body, "<row", m)
534 top = get_option(document, m, 'topline', 'false')
535 bottom = get_option(document, m, 'bottomline', 'false')
536 row_info.append([top, bottom])
537 remove_option(document, m, 'topline')
538 remove_option(document, m, 'bottomline')
543 for k in range(nrows*ncols):
544 m = find_token(document.body, "<cell", m)
545 mc_info.append(get_option(document, m, 'multicolumn', '0'))
548 for l in range(nrows):
549 for k in range(ncols):
550 m = find_token(document.body, '<cell', m)
551 if mc_info[l*ncols + k] == '0':
552 r = set_option(document, m, 'topline', row_info[l][0])
553 r = set_option(document, m, 'bottomline', row_info[l][1])
554 r = set_option(document, m, 'leftline', col_info[k][0])
555 r = set_option(document, m, 'rightline', col_info[k][1])
556 elif mc_info[l*ncols + k] == '1':
558 while s < ncols and mc_info[l*ncols + s] == '2':
560 if s < ncols and mc_info[l*ncols + s] != '1':
561 r = set_option(document, m, 'rightline', col_info[k][1])
562 if k > 0 and mc_info[l*ncols + k - 1] == '0':
563 r = set_option(document, m, 'leftline', col_info[k][0])
568 def revert_tablines(document):
571 i = find_token(document.body, "\\begin_inset Tabular", i)
574 j = find_end_of_inset(document.body, i + 1)
576 document.warning("Malformed LyX document: Could not find end of tabular.")
580 nrows = int(document.body[i+1].split('"')[3])
581 ncols = int(document.body[i+1].split('"')[5])
584 for k in range(nrows*ncols):
585 m = find_token(document.body, "<cell", m)
586 top = get_option(document, m, 'topline', 'false')
587 bottom = get_option(document, m, 'bottomline', 'false')
588 left = get_option(document, m, 'leftline', 'false')
589 right = get_option(document, m, 'rightline', 'false')
590 lines.append([top, bottom, left, right])
593 # we will want to ignore longtable captions
596 for k in range(nrows):
597 m = find_token(document.body, "<row", m)
598 caption = get_option(document, m, 'caption', 'false')
599 caption_info.append([caption])
604 for k in range(ncols):
605 m = find_token(document.body, "<column", m)
607 for l in range(nrows):
608 left = lines[l*ncols + k][2]
609 if left == 'false' and caption_info[l] == 'false':
611 set_option(document, m, 'leftline', left)
613 for l in range(nrows):
614 right = lines[l*ncols + k][3]
615 if right == 'false' and caption_info[l] == 'false':
617 set_option(document, m, 'rightline', right)
621 for k in range(nrows):
622 m = find_token(document.body, "<row", m)
624 for l in range(ncols):
625 top = lines[k*ncols + l][0]
628 if caption_info[k] == 'false':
630 set_option(document, m, 'topline', top)
632 for l in range(ncols):
633 bottom = lines[k*ncols + l][1]
634 if bottom == 'false':
636 if caption_info[k] == 'false':
638 set_option(document, m, 'bottomline', bottom)
644 def fix_wrong_tables(document):
647 i = find_token(document.body, "\\begin_inset Tabular", i)
650 j = find_end_of_inset(document.body, i + 1)
652 document.warning("Malformed LyX document: Could not find end of tabular.")
656 nrows = int(document.body[i+1].split('"')[3])
657 ncols = int(document.body[i+1].split('"')[5])
659 for l in range(nrows):
661 for k in range(ncols):
662 m = find_token(document.body, '<cell', m)
664 if document.body[m].find('multicolumn') != -1:
665 multicol_cont = int(document.body[m].split('"')[1])
667 if multicol_cont == 2 and (k == 0 or prev_multicolumn == 0):
668 document.body[m] = document.body[m][:5] + document.body[m][21:]
671 prev_multicolumn = multicol_cont
678 def close_begin_deeper(document):
682 i = find_tokens(document.body, ["\\begin_deeper", "\\end_deeper"], i)
687 if document.body[i][:13] == "\\begin_deeper":
694 document.body[-2:-2] = ['\\end_deeper' for i in range(depth)]
697 def long_charstyle_names(document):
700 i = find_token(document.body, "\\begin_inset CharStyle", i)
703 document.body[i] = document.body[i].replace("CharStyle ", "CharStyle CharStyle:")
706 def revert_long_charstyle_names(document):
709 i = find_token(document.body, "\\begin_inset CharStyle", i)
712 document.body[i] = document.body[i].replace("CharStyle CharStyle:", "CharStyle ")
716 def axe_show_label(document):
719 i = find_token(document.body, "\\begin_inset CharStyle", i)
722 if document.body[i + 1].find("show_label") != -1:
723 if document.body[i + 1].find("true") != -1:
724 document.body[i + 1] = "status open"
725 del document.body[ i + 2]
727 if document.body[i + 1].find("false") != -1:
728 document.body[i + 1] = "status collapsed"
729 del document.body[ i + 2]
731 document.warning("Malformed LyX document: show_label neither false nor true.")
733 document.warning("Malformed LyX document: show_label missing in CharStyle.")
738 def revert_show_label(document):
741 i = find_token(document.body, "\\begin_inset CharStyle", i)
744 if document.body[i + 1].find("status open") != -1:
745 document.body.insert(i + 1, "show_label true")
747 if document.body[i + 1].find("status collapsed") != -1:
748 document.body.insert(i + 1, "show_label false")
750 document.warning("Malformed LyX document: no legal status line in CharStyle.")
753 def revert_begin_modules(document):
756 i = find_token(document.header, "\\begin_modules", i)
759 j = find_end_of(document.header, i, "\\begin_modules", "\\end_modules")
761 # this should not happen
763 document.header[i : j + 1] = []
765 def convert_flex(document):
766 "Convert CharStyle to Flex"
769 i = find_token(document.body, "\\begin_inset CharStyle", i)
772 document.body[i] = document.body[i].replace('\\begin_inset CharStyle', '\\begin_inset Flex')
774 def revert_flex(document):
775 "Convert Flex to CharStyle"
778 i = find_token(document.body, "\\begin_inset Flex", i)
781 document.body[i] = document.body[i].replace('\\begin_inset Flex', '\\begin_inset CharStyle')
784 def revert_pdf_options(document):
785 "Revert PDF options for hyperref."
786 # store the PDF options and delete the entries from the Lyx file
794 bookmarksnumbered = ""
796 bookmarksopenlevel = ""
804 i = find_token(document.header, "\\use_hyperref", i)
806 hyperref = get_value(document.header, "\\use_hyperref", i) == 'true'
807 del document.header[i]
808 i = find_token(document.header, "\\pdf_store_options", i)
810 del document.header[i]
811 i = find_token(document.header, "\\pdf_title", 0)
813 title = get_value_string(document.header, '\\pdf_title', 0, 0, True)
814 title = ' pdftitle={' + title + '}'
815 del document.header[i]
816 i = find_token(document.header, "\\pdf_author", 0)
818 author = get_value_string(document.header, '\\pdf_author', 0, 0, True)
820 author = ' pdfauthor={' + author + '}'
822 author = ',\n pdfauthor={' + author + '}'
823 del document.header[i]
824 i = find_token(document.header, "\\pdf_subject", 0)
826 subject = get_value_string(document.header, '\\pdf_subject', 0, 0, True)
827 if title == "" and author == "":
828 subject = ' pdfsubject={' + subject + '}'
830 subject = ',\n pdfsubject={' + subject + '}'
831 del document.header[i]
832 i = find_token(document.header, "\\pdf_keywords", 0)
834 keywords = get_value_string(document.header, '\\pdf_keywords', 0, 0, True)
835 if title == "" and author == "" and subject == "":
836 keywords = ' pdfkeywords={' + keywords + '}'
838 keywords = ',\n pdfkeywords={' + keywords + '}'
839 del document.header[i]
840 i = find_token(document.header, "\\pdf_bookmarks", 0)
842 bookmarks = get_value_string(document.header, '\\pdf_bookmarks', 0)
843 bookmarks = ',\n bookmarks=' + bookmarks
844 del document.header[i]
845 i = find_token(document.header, "\\pdf_bookmarksnumbered", i)
847 bookmarksnumbered = get_value_string(document.header, '\\pdf_bookmarksnumbered', 0)
848 bookmarksnumbered = ',\n bookmarksnumbered=' + bookmarksnumbered
849 del document.header[i]
850 i = find_token(document.header, "\\pdf_bookmarksopen", i)
852 bookmarksopen = get_value_string(document.header, '\\pdf_bookmarksopen', 0)
853 bookmarksopen = ',\n bookmarksopen=' + bookmarksopen
854 del document.header[i]
855 i = find_token(document.header, "\\pdf_bookmarksopenlevel", i)
857 bookmarksopenlevel = get_value_string(document.header, '\\pdf_bookmarksopenlevel', 0, 0, True)
858 bookmarksopenlevel = ',\n bookmarksopenlevel=' + bookmarksopenlevel
859 del document.header[i]
860 i = find_token(document.header, "\\pdf_breaklinks", i)
862 breaklinks = get_value_string(document.header, '\\pdf_breaklinks', 0)
863 breaklinks = ',\n breaklinks=' + breaklinks
864 del document.header[i]
865 i = find_token(document.header, "\\pdf_pdfborder", i)
867 pdfborder = get_value_string(document.header, '\\pdf_pdfborder', 0)
868 if pdfborder == 'true':
869 pdfborder = ',\n pdfborder={0 0 0}'
871 pdfborder = ',\n pdfborder={0 0 1}'
872 del document.header[i]
873 i = find_token(document.header, "\\pdf_colorlinks", i)
875 colorlinks = get_value_string(document.header, '\\pdf_colorlinks', 0)
876 colorlinks = ',\n colorlinks=' + colorlinks
877 del document.header[i]
878 i = find_token(document.header, "\\pdf_backref", i)
880 backref = get_value_string(document.header, '\\pdf_backref', 0)
881 backref = ',\n backref=' + backref
882 del document.header[i]
883 i = find_token(document.header, "\\pdf_pagebackref", i)
885 pagebackref = get_value_string(document.header, '\\pdf_pagebackref', 0)
886 pagebackref = ',\n pagebackref=' + pagebackref
887 del document.header[i]
888 i = find_token(document.header, "\\pdf_pagemode", 0)
890 pagemode = get_value_string(document.header, '\\pdf_pagemode', 0)
891 pagemode = ',\n pdfpagemode=' + pagemode
892 del document.header[i]
893 i = find_token(document.header, "\\pdf_quoted_options", 0)
895 otheroptions = get_value_string(document.header, '\\pdf_quoted_options', 0, 0, True)
896 if title == "" and author == "" and subject == "" and keywords == "":
897 otheroptions = ' ' + otheroptions
899 otheroptions = ',\n ' + otheroptions
900 del document.header[i]
902 # write to the preamble when hyperref was used
904 # preamble write preparations
905 # bookmark numbers are only output when they are turned on
906 if bookmarksopen == ',\n bookmarksopen=true':
907 bookmarksopen = bookmarksopen + bookmarksopenlevel
908 if bookmarks == ',\n bookmarks=true':
909 bookmarks = bookmarks + bookmarksnumbered + bookmarksopen
911 bookmarks = bookmarks
912 # hypersetup is only output when there are things to be set up
913 setupstart = '\\hypersetup{%\n'
915 if otheroptions == "" and title == "" and author == ""\
916 and subject == "" and keywords == "":
920 # babel must be loaded before hyperref and hyperref the first part
921 # of the preamble, like in LyX 1.6
922 insert_to_preamble(0, document,
923 '% Commands inserted by lyx2lyx for PDF properties\n'
924 + '\\usepackage{babel}\n'
925 + '\\usepackage[unicode=true'
944 def remove_inzip_options(document):
945 "Remove inzipName and embed options from the Graphics inset"
948 i = find_token(document.body, "\\begin_inset Graphics", i)
951 j = find_end_of_inset(document.body, i + 1)
954 document.warning("Malformed LyX document: Could not find end of graphics inset.")
955 # If there's a inzip param, just remove that
956 k = find_token(document.body, "\tinzipName", i + 1, j)
959 # embed option must follow the inzipName option
960 del document.body[k+1]
964 def convert_inset_command(document):
967 \begin_inset LatexCommand cmd
969 \begin_inset CommandInset InsetType
974 i = find_token(document.body, "\\begin_inset LatexCommand", i)
977 line = document.body[i]
978 r = re.compile(r'\\begin_inset LatexCommand (.*)$')
982 #this is adapted from factory.cpp
983 if cmdName[0:4].lower() == "cite":
984 insetName = "citation"
985 elif cmdName == "url" or cmdName == "htmlurl":
987 elif cmdName[-3:] == "ref":
989 elif cmdName == "tableofcontents":
991 elif cmdName == "printnomenclature":
992 insetName = "nomencl_print"
993 elif cmdName == "printindex":
994 insetName = "index_print"
997 insertion = ["\\begin_inset CommandInset " + insetName, "LatexCommand " + cmdName]
998 document.body[i : i+1] = insertion
1001 def revert_inset_command(document):
1004 \begin_inset CommandInset InsetType
1007 \begin_inset LatexCommand cmd
1008 Some insets may end up being converted to insets earlier versions of LyX
1009 will not be able to recognize. Not sure what to do about that.
1013 i = find_token(document.body, "\\begin_inset CommandInset", i)
1016 nextline = document.body[i+1]
1017 r = re.compile(r'LatexCommand\s+(.*)$')
1018 m = r.match(nextline)
1020 document.warning("Malformed LyX document: Missing LatexCommand in " + document.body[i] + ".")
1023 cmdName = m.group(1)
1024 insertion = ["\\begin_inset LatexCommand " + cmdName]
1025 document.body[i : i+2] = insertion
1028 def convert_wrapfig_options(document):
1029 "Convert optional options for wrap floats (wrapfig)."
1030 # adds the tokens "lines", "placement", and "overhang"
1033 i = find_token(document.body, "\\begin_inset Wrap figure", i)
1036 document.body.insert(i + 1, "lines 0")
1037 j = find_token(document.body, "placement", i)
1038 # placement can be already set or not; if not, set it
1040 document.body.insert(i + 3, "overhang 0col%")
1042 document.body.insert(i + 2, "placement o")
1043 document.body.insert(i + 3, "overhang 0col%")
1047 def revert_wrapfig_options(document):
1048 "Revert optional options for wrap floats (wrapfig)."
1051 i = find_token(document.body, "\\begin_inset Wrap figure", i)
1054 j = find_end_of_inset(document.body, i)
1056 document.warning("Can't find end of Wrap inset at line " + str(i))
1059 k = find_default_layout(document, i, j)
1061 document.warning("Can't find default layout for Wrap figure!")
1064 # Options should be between i and k now
1065 l = find_token(document.body, "lines", i, k)
1067 document.warning("Can't find lines option for Wrap figure!")
1070 m = find_token(document.body, "overhang", i + 1, k)
1072 document.warning("Malformed LyX document: Couldn't find overhang parameter of wrap float!")
1075 # Do these in reverse order
1076 del document.body[m]
1077 del document.body[l]
1081 def convert_latexcommand_index(document):
1082 "Convert from LatexCommand form to collapsable form."
1084 r1 = re.compile('name "(.*)"')
1086 i = find_token(document.body, "\\begin_inset CommandInset index", i)
1089 if document.body[i + 1] != "LatexCommand index": # Might also be index_print
1092 j = find_end_of_inset(document.body, i + 1)
1094 document.warning("Unable to find end of index inset at line " + str(i) + "!")
1097 m = r1.match(document.body[i + 2])
1099 document.warning("Unable to match: " + document.body[i+2])
1100 # this can happen with empty index insets!
1103 fullcontent = m.group(1)
1104 linelist = latex2lyx(fullcontent, True)
1105 #document.warning(fullcontent)
1107 linelist = ["\\begin_inset Index", "status collapsed", "\\begin_layout Standard", ""] + \
1108 linelist + ["\\end_layout"]
1109 document.body[i : j] = linelist
1110 i += len(linelist) - (j - i)
1113 def revert_latexcommand_index(document):
1114 "Revert from collapsable form to LatexCommand form."
1117 i = find_token(document.body, "\\begin_inset Index", i)
1120 j = find_end_of_inset(document.body, i + 1)
1124 content = lyx2latex(document, document.body[i:j])
1126 content = content.replace('"', r'\"')
1127 document.body[i:j] = ["\\begin_inset CommandInset index", "LatexCommand index",
1128 "name " + '"' + content + '"', ""]
1132 def revert_wraptable(document):
1133 "Revert wrap table to wrap figure."
1136 i = find_token(document.body, "\\begin_inset Wrap table", i)
1139 document.body[i] = document.body[i].replace('\\begin_inset Wrap table', '\\begin_inset Wrap figure')
1143 def revert_vietnamese(document):
1144 "Set language Vietnamese to English"
1145 # Set document language from Vietnamese to English
1147 if document.language == "vietnamese":
1148 document.language = "english"
1149 i = find_token(document.header, "\\language", 0)
1151 document.header[i] = "\\language english"
1154 j = find_token(document.body, "\\lang vietnamese", j)
1157 document.body[j] = document.body[j].replace("\\lang vietnamese", "\\lang english")
1161 def convert_japanese_cjk(document):
1162 "Set language japanese to japanese-cjk"
1163 # Set document language from japanese-plain to japanese
1165 if document.language == "japanese":
1166 document.language = "japanese-cjk"
1167 i = find_token(document.header, "\\language", 0)
1169 document.header[i] = "\\language japanese-cjk"
1172 j = find_token(document.body, "\\lang japanese", j)
1175 document.body[j] = document.body[j].replace("\\lang japanese", "\\lang japanese-cjk")
1179 def revert_japanese(document):
1180 "Set language japanese-plain to japanese"
1181 # Set document language from japanese-plain to japanese
1183 if document.language == "japanese-plain":
1184 document.language = "japanese"
1185 i = find_token(document.header, "\\language", 0)
1187 document.header[i] = "\\language japanese"
1190 j = find_token(document.body, "\\lang japanese-plain", j)
1193 document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
1197 def revert_japanese_cjk(document):
1198 "Set language japanese-cjk to japanese"
1199 # Set document language from japanese-plain to japanese
1201 if document.language == "japanese-cjk":
1202 document.language = "japanese"
1203 i = find_token(document.header, "\\language", 0)
1205 document.header[i] = "\\language japanese"
1208 j = find_token(document.body, "\\lang japanese-cjk", j)
1211 document.body[j] = document.body[j].replace("\\lang japanese-cjk", "\\lang japanese")
1215 def revert_japanese_encoding(document):
1216 "Set input encoding form EUC-JP-plain to EUC-JP etc."
1217 # Set input encoding form EUC-JP-plain to EUC-JP etc.
1219 i = find_token(document.header, "\\inputencoding EUC-JP-plain", 0)
1221 document.header[i] = "\\inputencoding EUC-JP"
1223 j = find_token(document.header, "\\inputencoding JIS-plain", 0)
1225 document.header[j] = "\\inputencoding JIS"
1227 k = find_token(document.header, "\\inputencoding SJIS-plain", 0)
1228 if k != -1: # convert to UTF8 since there is currently no SJIS encoding
1229 document.header[k] = "\\inputencoding UTF8"
1232 def revert_inset_info(document):
1233 'Replace info inset with its content'
1236 i = find_token(document.body, '\\begin_inset Info', i)
1239 j = find_end_of_inset(document.body, i + 1)
1242 document.warning("Malformed LyX document: Could not find end of Info inset.")
1245 for k in range(i, j+1):
1246 if document.body[k].startswith("arg"):
1247 arg = document.body[k][3:].strip()
1248 # remove embracing quotation marks
1251 if arg[len(arg) - 1] == '"':
1252 arg = arg[:len(arg) - 1]
1253 # \" to straight quote
1254 arg = arg.replace(r'\"', '"')
1256 arg = arg.replace(r'\\', "\\backslash\n")
1257 if document.body[k].startswith("type"):
1258 type = document.body[k][4:].strip().strip('"')
1259 # I think there is a newline after \\end_inset, which should be removed.
1260 if document.body[j + 1].strip() == "":
1261 document.body[i : (j + 2)] = [type + ':' + arg]
1263 document.body[i : (j + 1)] = [type + ':' + arg]
1266 def convert_pdf_options(document):
1267 # Set the pdfusetitle tag, delete the pdf_store_options,
1268 # set quotes for bookmarksopenlevel"
1269 has_hr = get_value(document.header, "\\use_hyperref", 0, default = "0")
1271 k = find_token(document.header, "\\use_hyperref", 0)
1272 document.header.insert(k + 1, "\\pdf_pdfusetitle true")
1273 k = find_token(document.header, "\\pdf_store_options", 0)
1275 del document.header[k]
1276 i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
1278 document.header[i] = document.header[i].replace('"', '')
1281 def revert_pdf_options_2(document):
1282 # reset the pdfusetitle tag, set quotes for bookmarksopenlevel"
1283 k = find_token(document.header, "\\use_hyperref", 0)
1284 i = find_token(document.header, "\\pdf_pdfusetitle", k)
1286 del document.header[i]
1287 i = find_token(document.header, "\\pdf_bookmarksopenlevel", k)
1289 values = document.header[i].split()
1290 values[1] = ' "' + values[1] + '"'
1291 document.header[i] = ''.join(values)
1294 def convert_htmlurl(document):
1295 'Convert "htmlurl" to "href" insets for docbook'
1296 if document.backend != "docbook":
1300 i = find_token(document.body, "\\begin_inset CommandInset url", i)
1303 document.body[i] = "\\begin_inset CommandInset href"
1304 document.body[i + 1] = "LatexCommand href"
1308 def convert_url(document):
1309 'Convert url insets to url charstyles'
1310 if document.backend == "docbook":
1314 i = find_token(document.body, "\\begin_inset CommandInset url", i)
1317 n = find_token(document.body, "name", i)
1319 # place the URL name in typewriter before the new URL insert
1320 # grab the name 'bla' from the e.g. the line 'name "bla"',
1321 # therefore start with the 6th character
1322 name = document.body[n][6:-1]
1323 newname = [name + " "]
1324 document.body[i:i] = newname
1326 j = find_token(document.body, "target", i)
1328 document.warning("Malformed LyX document: Can't find target for url inset")
1331 target = document.body[j][8:-1]
1332 k = find_token(document.body, "\\end_inset", j)
1334 document.warning("Malformed LyX document: Can't find end of url inset")
1337 newstuff = ["\\begin_inset Flex URL",
1338 "status collapsed", "",
1339 "\\begin_layout Standard",
1344 document.body[i:k] = newstuff
1345 i = i + len(newstuff)
1347 def convert_ams_classes(document):
1348 tc = document.textclass
1349 if (tc != "amsart" and tc != "amsart-plain" and
1350 tc != "amsart-seq" and tc != "amsbook"):
1352 if tc == "amsart-plain":
1353 document.textclass = "amsart"
1354 document.set_textclass()
1355 document.add_module("Theorems (Starred)")
1357 if tc == "amsart-seq":
1358 document.textclass = "amsart"
1359 document.set_textclass()
1360 document.add_module("Theorems (AMS)")
1362 #Now we want to see if any of the environments in the extended theorems
1363 #module were used in this document. If so, we'll add that module, too.
1364 layouts = ["Criterion", "Algorithm", "Axiom", "Condition", "Note", \
1365 "Notation", "Summary", "Acknowledgement", "Conclusion", "Fact", \
1368 r = re.compile(r'^\\begin_layout (.*?)\*?\s*$')
1371 i = find_token(document.body, "\\begin_layout", i)
1374 m = r.match(document.body[i])
1376 # This is an empty layout
1377 # document.warning("Weirdly formed \\begin_layout at line %d of body!" % i)
1381 if layouts.count(m) != 0:
1382 document.add_module("Theorems (AMS-Extended)")
1386 def revert_href(document):
1387 'Reverts hyperlink insets (href) to url insets (url)'
1390 i = find_token(document.body, "\\begin_inset CommandInset href", i)
1393 document.body[i : i + 2] = \
1394 ["\\begin_inset CommandInset url", "LatexCommand url"]
1397 def revert_url(document):
1398 'Reverts Flex URL insets to old-style URL insets'
1401 i = find_token(document.body, "\\begin_inset Flex URL", i)
1404 j = find_end_of_inset(document.body, i)
1406 document.warning("Can't find end of inset in revert_url!")
1408 k = find_default_layout(document, i, j)
1410 document.warning("Can't find default layout in revert_url!")
1413 l = find_end_of(document.body, k, "\\begin_layout", "\\end_layout")
1414 if l == -1 or l >= j:
1415 document.warning("Can't find end of default layout in revert_url!")
1418 # OK, so the inset's data is between lines k and l.
1419 data = " ".join(document.body[k+1:l])
1421 newinset = ["\\begin_inset LatexCommand url", "target \"" + data + "\"",\
1423 document.body[i:j+1] = newinset
1424 i = i + len(newinset)
1427 def convert_include(document):
1428 'Converts include insets to new format.'
1430 r = re.compile(r'\\begin_inset Include\s+\\([^{]+){([^}]*)}(?:\[(.*)\])?')
1432 i = find_token(document.body, "\\begin_inset Include", i)
1435 line = document.body[i]
1436 previewline = document.body[i + 1]
1439 document.warning("Unable to match line " + str(i) + " of body!")
1445 insertion = ["\\begin_inset CommandInset include",
1446 "LatexCommand " + cmd, previewline,
1447 "filename \"" + fn + "\""]
1450 insertion.append("lstparams " + '"' + opt + '"')
1452 document.body[i : i + 2] = insertion
1456 def revert_include(document):
1457 'Reverts include insets to old format.'
1459 r0 = re.compile('preview.*')
1460 r1 = re.compile('LatexCommand (.+)')
1461 r2 = re.compile('filename "(.+)"')
1462 r3 = re.compile('lstparams "(.*)"')
1464 i = find_token(document.body, "\\begin_inset CommandInset include", i)
1468 m = r1.match(document.body[nextline])
1470 document.warning("Malformed LyX document: No LatexCommand line for `" +
1471 document.body[i] + "' on line " + str(i) + ".")
1476 if r0.match(document.body[nextline]):
1477 previewline = document.body[nextline]
1481 m = r2.match(document.body[nextline])
1483 document.warning("Malformed LyX document: No filename line for `" + \
1484 document.body[i] + "' on line " + str(i) + ".")
1490 if (cmd == "lstinputlisting"):
1491 m = r3.match(document.body[nextline])
1493 options = m.group(1)
1496 newline = "\\begin_inset Include \\" + cmd + "{" + fn + "}"
1498 newline += ("[" + options + "]")
1499 insertion = [newline]
1500 if previewline != "":
1501 insertion.append(previewline)
1502 document.body[i : nextline] = insertion
1506 def revert_albanian(document):
1507 "Set language Albanian to English"
1509 if document.language == "albanian":
1510 document.language = "english"
1511 i = find_token(document.header, "\\language", 0)
1513 document.header[i] = "\\language english"
1516 j = find_token(document.body, "\\lang albanian", j)
1519 document.body[j] = document.body[j].replace("\\lang albanian", "\\lang english")
1523 def revert_lowersorbian(document):
1524 "Set language lower Sorbian to English"
1526 if document.language == "lowersorbian":
1527 document.language = "english"
1528 i = find_token(document.header, "\\language", 0)
1530 document.header[i] = "\\language english"
1533 j = find_token(document.body, "\\lang lowersorbian", j)
1536 document.body[j] = document.body[j].replace("\\lang lowersorbian", "\\lang english")
1540 def revert_uppersorbian(document):
1541 "Set language uppersorbian to usorbian as this was used in LyX 1.5"
1543 if document.language == "uppersorbian":
1544 document.language = "usorbian"
1545 i = find_token(document.header, "\\language", 0)
1547 document.header[i] = "\\language usorbian"
1550 j = find_token(document.body, "\\lang uppersorbian", j)
1553 document.body[j] = document.body[j].replace("\\lang uppersorbian", "\\lang usorbian")
1557 def convert_usorbian(document):
1558 "Set language usorbian to uppersorbian"
1560 if document.language == "usorbian":
1561 document.language = "uppersorbian"
1562 i = find_token(document.header, "\\language", 0)
1564 document.header[i] = "\\language uppersorbian"
1567 j = find_token(document.body, "\\lang usorbian", j)
1570 document.body[j] = document.body[j].replace("\\lang usorbian", "\\lang uppersorbian")
1574 def convert_macro_global(document):
1575 "Remove TeX code command \global when it is in front of a macro"
1576 # math macros are nowadays already defined \global, so that an additional
1577 # \global would make the document uncompilable, see
1578 # http://bugzilla.lyx.org/show_bug.cgi?id=5371
1579 # We're looking for something like this:
1583 # \begin_layout Plain Layout
1593 # \begin_inset FormulaMacro
1594 # \renewcommand{\foo}{123}
1598 i = find_token(document.body, "\\begin_inset FormulaMacro", i)
1601 # if i <= 13, then there isn't enough room for the ERT
1605 if document.body[i-6] == "global":
1606 del document.body[i-13 : i]
1612 def revert_macro_optional_params(document):
1613 "Convert macro definitions with optional parameters into ERTs"
1614 # Stub to convert macro definitions with one or more optional parameters
1615 # into uninterpreted ERT insets
1618 def revert_hyperlinktype(document):
1619 'Reverts hyperlink type'
1623 i = find_token(document.body, "target", i)
1626 j = find_token(document.body, "type", i)
1630 del document.body[j]
1634 def revert_pagebreak(document):
1635 'Reverts pagebreak to ERT'
1638 i = find_token(document.body, "\\pagebreak", i)
1641 document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1642 '\\begin_layout Standard\n\n\n\\backslash\n' \
1643 'pagebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1647 def revert_linebreak(document):
1648 'Reverts linebreak to ERT'
1651 i = find_token(document.body, "\\linebreak", i)
1654 document.body[i] = '\\begin_inset ERT\nstatus collapsed\n\n' \
1655 '\\begin_layout Standard\n\n\n\\backslash\n' \
1656 'linebreak{}\n\\end_layout\n\n\\end_inset\n\n'
1660 def revert_latin(document):
1661 "Set language Latin to English"
1663 if document.language == "latin":
1664 document.language = "english"
1665 i = find_token(document.header, "\\language", 0)
1667 document.header[i] = "\\language english"
1670 j = find_token(document.body, "\\lang latin", j)
1673 document.body[j] = document.body[j].replace("\\lang latin", "\\lang english")
1677 def revert_samin(document):
1678 "Set language North Sami to English"
1680 if document.language == "samin":
1681 document.language = "english"
1682 i = find_token(document.header, "\\language", 0)
1684 document.header[i] = "\\language english"
1687 j = find_token(document.body, "\\lang samin", j)
1690 document.body[j] = document.body[j].replace("\\lang samin", "\\lang english")
1694 def convert_serbocroatian(document):
1695 "Set language Serbocroatian to Croatian as this was really Croatian in LyX 1.5"
1697 if document.language == "serbocroatian":
1698 document.language = "croatian"
1699 i = find_token(document.header, "\\language", 0)
1701 document.header[i] = "\\language croatian"
1704 j = find_token(document.body, "\\lang serbocroatian", j)
1707 document.body[j] = document.body[j].replace("\\lang serbocroatian", "\\lang croatian")
1711 def convert_framed_notes(document):
1712 "Convert framed notes to boxes. "
1715 i = find_tokens(document.body, ["\\begin_inset Note Framed", "\\begin_inset Note Shaded"], i)
1718 subst = [document.body[i].replace("\\begin_inset Note", "\\begin_inset Box"),
1727 'height_special "totalheight"']
1728 document.body[i:i+1] = subst
1732 def convert_module_names(document):
1733 modulemap = { 'Braille' : 'braille', 'Endnote' : 'endnotes', 'Foot to End' : 'foottoend',\
1734 'Hanging' : 'hanging', 'Linguistics' : 'linguistics', 'Logical Markup' : 'logicalmkup', \
1735 'Theorems (AMS-Extended)' : 'theorems-ams-extended', 'Theorems (AMS)' : 'theorems-ams', \
1736 'Theorems (Order By Chapter)' : 'theorems-chap', 'Theorems (Order By Section)' : 'theorems-sec', \
1737 'Theorems (Starred)' : 'theorems-starred', 'Theorems' : 'theorems-std' }
1738 modlist = document.get_module_list()
1739 if len(modlist) == 0:
1743 if modulemap.has_key(mod):
1744 newmodlist.append(modulemap[mod])
1746 document.warning("Can't find module %s in the module map!" % mod)
1747 newmodlist.append(mod)
1748 document.set_module_list(newmodlist)
1751 def revert_module_names(document):
1752 modulemap = { 'braille' : 'Braille', 'endnotes' : 'Endnote', 'foottoend' : 'Foot to End',\
1753 'hanging' : 'Hanging', 'linguistics' : 'Linguistics', 'logicalmkup' : 'Logical Markup', \
1754 'theorems-ams-extended' : 'Theorems (AMS-Extended)', 'theorems-ams' : 'Theorems (AMS)', \
1755 'theorems-chap' : 'Theorems (Order By Chapter)', 'theorems-sec' : 'Theorems (Order By Section)', \
1756 'theorems-starred' : 'Theorems (Starred)', 'theorems-std' : 'Theorems'}
1757 modlist = document.get_module_list()
1758 if len(modlist) == 0:
1762 if modulemap.has_key(mod):
1763 newmodlist.append(modulemap[mod])
1765 document.warning("Can't find module %s in the module map!" % mod)
1766 newmodlist.append(mod)
1767 document.set_module_list(newmodlist)
1770 def revert_colsep(document):
1771 i = find_token(document.header, "\\columnsep", 0)
1774 colsepline = document.header[i]
1775 r = re.compile(r'\\columnsep (.*)')
1776 m = r.match(colsepline)
1778 document.warning("Malformed column separation line!")
1781 del document.header[i]
1782 #it seems to be safe to add the package even if it is already used
1783 pretext = ["\\usepackage{geometry}", "\\geometry{columnsep=" + colsep + "}"]
1785 add_to_preamble(document, pretext)
1788 def revert_framed_notes(document):
1789 "Revert framed boxes to notes. "
1792 i = find_tokens(document.body, ["\\begin_inset Box Framed", "\\begin_inset Box Shaded"], i)
1796 j = find_end_of_inset(document.body, i + 1)
1799 document.warning("Malformed LyX document: Could not find end of Box inset.")
1800 k = find_token(document.body, "status", i + 1, j)
1802 document.warning("Malformed LyX document: Missing `status' tag in Box inset.")
1804 status = document.body[k]
1805 l = find_default_layout(document, i + 1, j)
1807 document.warning("Malformed LyX document: Missing `\\begin_layout' in Box inset.")
1809 m = find_token(document.body, "\\end_layout", i + 1, j)
1811 document.warning("Malformed LyX document: Missing `\\end_layout' in Box inset.")
1813 ibox = find_token(document.body, "has_inner_box 1", i + 1, k)
1814 pbox = find_token(document.body, "use_parbox 1", i + 1, k)
1815 if ibox == -1 and pbox == -1:
1816 document.body[i] = document.body[i].replace("\\begin_inset Box", "\\begin_inset Note")
1817 del document.body[i+1:k]
1819 document.body[i] = document.body[i].replace("\\begin_inset Box Shaded", "\\begin_inset Box Frameless")
1820 subst1 = [document.body[l],
1821 "\\begin_inset Note Shaded",
1823 '\\begin_layout Standard']
1824 document.body[l:l + 1] = subst1
1825 subst2 = [document.body[m], "\\end_layout", "\\end_inset"]
1826 document.body[m:m + 1] = subst2
1830 def revert_slash(document):
1831 'Revert \\SpecialChar \\slash{} to ERT'
1833 while i < len(document.body):
1834 m = re.match(r'(.*)\\SpecialChar \\slash{}(.*)', document.body[i])
1839 '\\begin_inset ERT',
1840 'status collapsed', '',
1841 '\\begin_layout Standard',
1842 '', '', '\\backslash',
1847 document.body[i: i+1] = subst
1853 def revert_nobreakdash(document):
1854 'Revert \\SpecialChar \\nobreakdash- to ERT'
1856 while i < len(document.body):
1857 m = re.match(r'(.*)\\SpecialChar \\nobreakdash-(.*)', document.body[i])
1862 '\\begin_inset ERT',
1863 'status collapsed', '',
1864 '\\begin_layout Standard', '', '',
1870 document.body[i: i+1] = subst
1872 j = find_token(document.header, "\\use_amsmath", 0)
1874 document.warning("Malformed LyX document: Missing '\\use_amsmath'.")
1876 document.header[j] = "\\use_amsmath 2"
1881 #Returns number of lines added/removed
1882 def revert_nocite_key(body, start, end):
1883 'key "..." -> \nocite{...}'
1884 r = re.compile(r'^key "(.*)"')
1888 m = r.match(body[i])
1890 body[i:i+1] = ["\\backslash", "nocite{" + m.group(1) + "}"]
1891 j += 1 # because we added a line
1892 i += 2 # skip that line
1895 j -= 1 # because we deleted a line
1896 # no need to change i, since it now points to the next line
1900 def revert_nocite(document):
1901 "Revert LatexCommand nocite to ERT"
1904 i = find_token(document.body, "\\begin_inset CommandInset citation", i)
1907 if (document.body[i+1] != "LatexCommand nocite"):
1908 # note that we already incremented i
1911 insetEnd = find_end_of_inset(document.body, i)
1913 #this should not happen
1914 document.warning("End of CommandInset citation not found in revert_nocite!")
1917 paramLocation = i + 2 #start of the inset's parameters
1919 document.body[i:i+2] = \
1920 ["\\begin_inset ERT", "status collapsed", "", "\\begin_layout Standard"]
1921 # that added two lines
1924 #print insetEnd, document.body[i: insetEnd + 1]
1925 insetEnd += revert_nocite_key(document.body, paramLocation, insetEnd)
1926 #print insetEnd, document.body[i: insetEnd + 1]
1927 document.body.insert(insetEnd, "\\end_layout")
1928 document.body.insert(insetEnd + 1, "")
1932 def revert_btprintall(document):
1933 "Revert (non-bibtopic) btPrintAll option to ERT \nocite{*}"
1934 i = find_token(document.header, '\\use_bibtopic', 0)
1936 document.warning("Malformed lyx document: Missing '\\use_bibtopic'.")
1938 if get_value(document.header, '\\use_bibtopic', 0) == "false":
1940 while i < len(document.body):
1941 i = find_token(document.body, "\\begin_inset CommandInset bibtex", i)
1944 j = find_end_of_inset(document.body, i + 1)
1946 #this should not happen
1947 document.warning("End of CommandInset bibtex not found in revert_btprintall!")
1948 j = len(document.body)
1949 # this range isn't really right, but it should be OK, since we shouldn't
1950 # see more than one matching line in each inset
1952 for k in range(i, j):
1953 if (document.body[k] == 'btprint "btPrintAll"'):
1954 del document.body[k]
1955 subst = ["\\begin_inset ERT",
1956 "status collapsed", "",
1957 "\\begin_layout Standard", "",
1962 document.body[i:i] = subst
1963 addlines = addedlines + len(subst) - 1
1967 def revert_bahasam(document):
1968 "Set language Bahasa Malaysia to Bahasa Indonesia"
1970 if document.language == "bahasam":
1971 document.language = "bahasa"
1972 i = find_token(document.header, "\\language", 0)
1974 document.header[i] = "\\language bahasa"
1977 j = find_token(document.body, "\\lang bahasam", j)
1980 document.body[j] = document.body[j].replace("\\lang bahasam", "\\lang bahasa")
1984 def revert_interlingua(document):
1985 "Set language Interlingua to English"
1987 if document.language == "interlingua":
1988 document.language = "english"
1989 i = find_token(document.header, "\\language", 0)
1991 document.header[i] = "\\language english"
1994 j = find_token(document.body, "\\lang interlingua", j)
1997 document.body[j] = document.body[j].replace("\\lang interlingua", "\\lang english")
2001 def revert_serbianlatin(document):
2002 "Set language Serbian-Latin to Croatian"
2004 if document.language == "serbian-latin":
2005 document.language = "croatian"
2006 i = find_token(document.header, "\\language", 0)
2008 document.header[i] = "\\language croatian"
2011 j = find_token(document.body, "\\lang serbian-latin", j)
2014 document.body[j] = document.body[j].replace("\\lang serbian-latin", "\\lang croatian")
2018 def revert_rotfloat(document):
2019 " Revert sideways custom floats. "
2022 # whitespace intended (exclude \\begin_inset FloatList)
2023 i = find_token(document.body, "\\begin_inset Float ", i)
2026 line = document.body[i]
2027 r = re.compile(r'\\begin_inset Float (.*)$')
2030 document.warning("Unable to match line " + str(i) + " of body!")
2033 floattype = m.group(1)
2034 if floattype == "figure" or floattype == "table":
2037 j = find_end_of_inset(document.body, i)
2039 document.warning("Malformed lyx document: Missing '\\end_inset' in revert_rotfloat.")
2043 if get_value(document.body, 'sideways', i, j) == "false":
2046 l = find_default_layout(document, i + 1, j)
2048 document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
2050 subst = ['\\begin_layout Standard',
2051 '\\begin_inset ERT',
2052 'status collapsed', '',
2053 '\\begin_layout Standard', '', '',
2055 'end{sideways' + floattype + '}',
2056 '\\end_layout', '', '\\end_inset']
2057 document.body[j : j+1] = subst
2058 addedLines = len(subst) - 1
2059 del document.body[i+1 : l]
2060 addedLines -= (l-1) - (i+1)
2061 subst = ['\\begin_inset ERT', 'status collapsed', '',
2062 '\\begin_layout Standard', '', '', '\\backslash',
2063 'begin{sideways' + floattype + '}',
2064 '\\end_layout', '', '\\end_inset', '',
2066 document.body[i : i+1] = subst
2067 addedLines += len(subst) - 1
2068 if floattype == "algorithm":
2069 add_to_preamble(document,
2070 ['% Commands inserted by lyx2lyx for sideways algorithm float',
2071 '\\usepackage{rotfloat}',
2072 '\\floatstyle{ruled}',
2073 '\\newfloat{algorithm}{tbp}{loa}',
2074 '\\floatname{algorithm}{Algorithm}'])
2076 document.warning("Cannot create preamble definition for custom float" + floattype + ".")
2080 def revert_widesideways(document):
2081 " Revert wide sideways floats. "
2084 # whitespace intended (exclude \\begin_inset FloatList)
2085 i = find_token(document.body, '\\begin_inset Float ', i)
2088 line = document.body[i]
2089 r = re.compile(r'\\begin_inset Float (.*)$')
2092 document.warning("Unable to match line " + str(i) + " of body!")
2095 floattype = m.group(1)
2096 if floattype != "figure" and floattype != "table":
2099 j = find_end_of_inset(document.body, i)
2101 document.warning("Malformed lyx document: Missing '\\end_inset' in revert_widesideways.")
2104 if get_value(document.body, 'sideways', i, j) == "false" or \
2105 get_value(document.body, 'wide', i, j) == "false":
2108 l = find_default_layout(document, i + 1, j)
2110 document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
2112 subst = ['\\begin_layout Standard', '\\begin_inset ERT',
2113 'status collapsed', '',
2114 '\\begin_layout Standard', '', '', '\\backslash',
2115 'end{sideways' + floattype + '*}',
2116 '\\end_layout', '', '\\end_inset']
2117 document.body[j : j+1] = subst
2118 addedLines = len(subst) - 1
2119 del document.body[i+1:l-1]
2120 addedLines -= (l-1) - (i+1)
2121 subst = ['\\begin_inset ERT', 'status collapsed', '',
2122 '\\begin_layout Standard', '', '', '\\backslash',
2123 'begin{sideways' + floattype + '*}', '\\end_layout', '',
2124 '\\end_inset', '', '\\end_layout', '']
2125 document.body[i : i+1] = subst
2126 addedLines += len(subst) - 1
2127 add_to_preamble(document, ['\\usepackage{rotfloat}\n'])
2131 def revert_inset_embedding(document, type):
2132 ' Remove embed tag from certain type of insets'
2135 i = find_token(document.body, "\\begin_inset %s" % type, i)
2138 j = find_end_of_inset(document.body, i)
2140 document.warning("Malformed lyx document: Missing '\\end_inset' in revert_inset_embedding.")
2143 k = find_token(document.body, "\tembed", i, j)
2145 k = find_token(document.body, "embed", i, j)
2147 del document.body[k]
2151 def revert_external_embedding(document):
2152 ' Remove embed tag from external inset '
2153 revert_inset_embedding(document, 'External')
2156 def convert_subfig(document):
2157 " Convert subfigures to subfloats. "
2161 i = find_token(document.body, '\\begin_inset Graphics', i)
2164 endInset = find_end_of_inset(document.body, i)
2166 document.warning("Malformed lyx document: Missing '\\end_inset' in convert_subfig.")
2169 k = find_token(document.body, '\tsubcaption', i, endInset)
2173 l = find_token(document.body, '\tsubcaptionText', i, endInset)
2177 caption = document.body[l][16:].strip('"')
2178 del document.body[l]
2180 del document.body[k]
2182 subst = ['\\begin_inset Float figure', 'wide false', 'sideways false',
2183 'status open', '', '\\begin_layout Plain Layout', '\\begin_inset Caption',
2184 '', '\\begin_layout Plain Layout'] + latex2lyx(caption, False) + \
2185 [ '\\end_layout', '', '\\end_inset', '',
2186 '\\end_layout', '', '\\begin_layout Plain Layout']
2187 document.body[i : i] = subst
2188 addedLines += len(subst)
2189 endInset += addedLines
2190 subst = ['', '\\end_inset', '', '\\end_layout']
2191 document.body[endInset : endInset] = subst
2192 addedLines += len(subst)
2196 def revert_subfig(document):
2197 " Revert subfloats. "
2200 # whitespace intended (exclude \\begin_inset FloatList)
2201 i = find_tokens(document.body, ['\\begin_inset Float ', '\\begin_inset Wrap'], i)
2207 j = find_end_of_inset(document.body, i)
2209 document.warning("Malformed lyx document: Missing '\\end_inset' (float) at line " + str(i + len(document.header)) + ".\n\t" + document.body[i])
2210 # document.warning(document.body[i-1] + "\n" + document.body[i+1])
2212 continue # this will get us back to the outer loop, since j == -1
2213 # look for embedded float (= subfloat)
2214 # whitespace intended (exclude \\begin_inset FloatList)
2215 k = find_token(document.body, '\\begin_inset Float ', i + 1, j)
2218 # is the subfloat aligned?
2219 al = find_token(document.body, '\\align ', k - 1, j)
2223 if get_value(document.body, '\\align', al) == "center":
2224 alignment_beg = "\\backslash\nbegin{centering}"
2225 alignment_end = "\\backslash\npar\\backslash\nend{centering}"
2226 elif get_value(document.body, '\\align', al) == "left":
2227 alignment_beg = "\\backslash\nbegin{raggedright}"
2228 alignment_end = "\\backslash\npar\\backslash\nend{raggedright}"
2229 elif get_value(document.body, '\\align', al) == "right":
2230 alignment_beg = "\\backslash\nbegin{raggedleft}"
2231 alignment_end = "\\backslash\npar\\backslash\nend{raggedleft}"
2232 l = find_end_of_inset(document.body, k)
2234 document.warning("Malformed lyx document: Missing '\\end_inset' (embedded float).")
2237 continue # escape to the outer loop
2238 m = find_default_layout(document, k + 1, l)
2240 cap = find_token(document.body, '\\begin_inset Caption', k + 1, l)
2245 capend = find_end_of_inset(document.body, cap)
2247 document.warning("Malformed lyx document: Missing '\\end_inset' (caption).")
2251 lbl = find_token(document.body, '\\begin_inset CommandInset label', cap, capend)
2253 lblend = find_end_of_inset(document.body, lbl + 1)
2255 document.warning("Malformed lyx document: Missing '\\end_inset' (label).")
2257 for line in document.body[lbl:lblend + 1]:
2258 if line.startswith('name '):
2259 label = line.split()[1].strip('"')
2266 opt = find_token(document.body, '\\begin_inset OptArg', cap, capend)
2268 optend = find_end_of_inset(document.body, opt)
2270 document.warning("Malformed lyx document: Missing '\\end_inset' (OptArg).")
2272 optc = find_default_layout(document, opt, optend)
2274 document.warning("Malformed LyX document: Missing `\\begin_layout' in Float inset.")
2276 optcend = find_end_of(document.body, optc, "\\begin_layout", "\\end_layout")
2277 for line in document.body[optc:optcend]:
2278 if not line.startswith('\\'):
2279 shortcap += line.strip()
2283 for line in document.body[cap:capend]:
2284 if line in document.body[lbl:lblend]:
2286 elif line in document.body[opt:optend]:
2290 caption += lyxline2latex(document, line, inert)
2292 caption += "\n\\backslash\nlabel{" + label + "}"
2293 subst = '\\begin_layout PlainLayout\n\\begin_inset ERT\nstatus collapsed\n\n' \
2294 '\\begin_layout PlainLayout\n\n}' + alignment_end + \
2295 '\n\\end_layout\n\n\\end_inset\n\n' \
2296 '\\end_layout\n\n\\begin_layout PlainLayout\n'
2297 subst = subst.split('\n')
2298 document.body[l : l+1] = subst
2299 addedLines = len(subst) - 1
2300 # this is before l and so is unchanged by the multiline insertion
2302 del document.body[cap:capend+1]
2303 addedLines -= (capend + 1 - cap)
2304 del document.body[k+1:m-1]
2305 addedLines -= (m - 1 - (k + 1))
2306 insertion = '\\begin_inset ERT\nstatus collapsed\n\n' \
2307 '\\begin_layout PlainLayout\n\n' + alignment_beg + '\n\\backslash\n' \
2309 if len(shortcap) > 0:
2310 insertion = insertion + "[" + shortcap + "]"
2311 if len(caption) > 0:
2312 insertion = insertion + "[" + caption + "]"
2313 insertion = insertion + '{%\n\\end_layout\n\n\\end_inset\n\n\\end_layout\n'
2314 insertion = insertion.split('\n')
2315 document.body[k : k + 1] = insertion
2316 addedLines += len(insertion) - 1
2317 al = find_token(document.body, '\\align ', k - 1, j + addedLines)
2319 del document.body[al]
2321 add_to_preamble(document, ['\\usepackage{subfig}\n'])
2325 def revert_wrapplacement(document):
2326 " Revert placement options wrap floats (wrapfig). "
2329 i = find_token(document.body, "\\begin_inset Wrap figure", i)
2332 e = find_end_of_inset(document.body, i)
2333 j = find_token(document.body, "placement", i + 1, e)
2335 document.warning("Malformed LyX document: Couldn't find placement parameter of wrap float.")
2338 r = re.compile("placement (o|i|l|r|O|I|L|R)")
2339 m = r.match(document.body[j])
2341 document.warning("Malformed LyX document: Placement option isn't O|I|R|L!")
2343 document.body[j] = "placement " + m.group(1).lower()
2347 def remove_extra_embedded_files(document):
2348 " Remove \extra_embedded_files from buffer params "
2349 i = find_token(document.header, '\\extra_embedded_files', 0)
2352 document.header.pop(i)
2355 def convert_spaceinset(document):
2356 " Convert '\\InsetSpace foo' to '\\begin_inset Space foo\n\\end_inset' "
2358 while i < len(document.body):
2359 m = re.match(r'(.*)\\InsetSpace (.*)', document.body[i])
2363 subst = [before, "\\begin_inset Space " + after, "\\end_inset"]
2364 document.body[i: i+1] = subst
2370 def revert_spaceinset(document):
2371 " Revert '\\begin_inset Space foo\n\\end_inset' to '\\InsetSpace foo' "
2374 i = find_token(document.body, "\\begin_inset Space", i)
2377 j = find_end_of_inset(document.body, i)
2379 document.warning("Malformed LyX document: Could not find end of space inset.")
2381 document.body[i] = document.body[i].replace('\\begin_inset Space', '\\InsetSpace')
2382 del document.body[j]
2385 def convert_hfill(document):
2386 " Convert hfill to space inset "
2389 i = find_token(document.body, "\\hfill", i)
2392 subst = document.body[i].replace('\\hfill', \
2393 '\n\\begin_inset Space \\hfill{}\n\\end_inset')
2394 subst = subst.split('\n')
2395 document.body[i : i+1] = subst
2399 def revert_hfills(document):
2400 ' Revert \\hfill commands '
2401 hfill = re.compile(r'\\hfill')
2402 dotfill = re.compile(r'\\dotfill')
2403 hrulefill = re.compile(r'\\hrulefill')
2406 i = find_token(document.body, "\\InsetSpace", i)
2409 if hfill.search(document.body[i]):
2410 document.body[i] = \
2411 document.body[i].replace('\\InsetSpace \\hfill{}', '\\hfill')
2414 if dotfill.search(document.body[i]):
2415 subst = document.body[i].replace('\\InsetSpace \\dotfill{}', \
2416 '\\begin_inset ERT\nstatus collapsed\n\n' \
2417 '\\begin_layout Standard\n\n\n\\backslash\n' \
2418 'dotfill{}\n\\end_layout\n\n\\end_inset\n\n')
2419 subst = subst.split('\n')
2420 document.body[i : i+1] = subst
2423 if hrulefill.search(document.body[i]):
2424 subst = document.body[i].replace('\\InsetSpace \\hrulefill{}', \
2425 '\\begin_inset ERT\nstatus collapsed\n\n' \
2426 '\\begin_layout Standard\n\n\n\\backslash\n' \
2427 'hrulefill{}\n\\end_layout\n\n\\end_inset\n\n')
2428 subst = subst.split('\n')
2429 document.body[i : i+1] = subst
2434 def revert_hspace(document):
2435 ' Revert \\InsetSpace \\hspace{} to ERT '
2437 hspace = re.compile(r'\\hspace{}')
2438 hstar = re.compile(r'\\hspace\*{}')
2440 i = find_token(document.body, "\\InsetSpace \\hspace", i)
2443 length = get_value(document.body, '\\length', i+1)
2445 document.warning("Malformed lyx document: Missing '\\length' in Space inset.")
2447 del document.body[i+1]
2449 if hstar.search(document.body[i]):
2450 subst = document.body[i].replace('\\InsetSpace \\hspace*{}', \
2451 '\\begin_inset ERT\nstatus collapsed\n\n' \
2452 '\\begin_layout Standard\n\n\n\\backslash\n' \
2453 'hspace*{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
2454 subst = subst.split('\n')
2455 document.body[i : i+1] = subst
2456 addedLines += len(subst) - 1
2459 if hspace.search(document.body[i]):
2460 subst = document.body[i].replace('\\InsetSpace \\hspace{}', \
2461 '\\begin_inset ERT\nstatus collapsed\n\n' \
2462 '\\begin_layout Standard\n\n\n\\backslash\n' \
2463 'hspace{' + length + '}\n\\end_layout\n\n\\end_inset\n\n')
2464 subst = subst.split('\n')
2465 document.body[i : i+1] = subst
2466 addedLines += len(subst) - 1
2472 def revert_protected_hfill(document):
2473 ' Revert \\begin_inset Space \\hspace*{\\fill} to ERT '
2476 i = find_token(document.body, '\\begin_inset Space \\hspace*{\\fill}', i)
2479 j = find_end_of_inset(document.body, i)
2481 document.warning("Malformed LyX document: Could not find end of space inset.")
2483 del document.body[j]
2484 subst = document.body[i].replace('\\begin_inset Space \\hspace*{\\fill}', \
2485 '\\begin_inset ERT\nstatus collapsed\n\n' \
2486 '\\begin_layout Standard\n\n\n\\backslash\n' \
2487 'hspace*{\n\\backslash\nfill}\n\\end_layout\n\n\\end_inset\n\n')
2488 subst = subst.split('\n')
2489 document.body[i : i+1] = subst
2493 def revert_leftarrowfill(document):
2494 ' Revert \\begin_inset Space \\leftarrowfill{} to ERT '
2497 i = find_token(document.body, '\\begin_inset Space \\leftarrowfill{}', i)
2500 j = find_end_of_inset(document.body, i)
2502 document.warning("Malformed LyX document: Could not find end of space inset.")
2504 del document.body[j]
2505 subst = document.body[i].replace('\\begin_inset Space \\leftarrowfill{}', \
2506 '\\begin_inset ERT\nstatus collapsed\n\n' \
2507 '\\begin_layout Standard\n\n\n\\backslash\n' \
2508 'leftarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
2509 subst = subst.split('\n')
2510 document.body[i : i+1] = subst
2514 def revert_rightarrowfill(document):
2515 ' Revert \\begin_inset Space \\rightarrowfill{} to ERT '
2518 i = find_token(document.body, '\\begin_inset Space \\rightarrowfill{}', i)
2521 j = find_end_of_inset(document.body, i)
2523 document.warning("Malformed LyX document: Could not find end of space inset.")
2525 del document.body[j]
2526 subst = document.body[i].replace('\\begin_inset Space \\rightarrowfill{}', \
2527 '\\begin_inset ERT\nstatus collapsed\n\n' \
2528 '\\begin_layout Standard\n\n\n\\backslash\n' \
2529 'rightarrowfill{}\n\\end_layout\n\n\\end_inset\n\n')
2530 subst = subst.split('\n')
2531 document.body[i : i+1] = subst
2535 def revert_upbracefill(document):
2536 ' Revert \\begin_inset Space \\upbracefill{} to ERT '
2539 i = find_token(document.body, '\\begin_inset Space \\upbracefill{}', i)
2542 j = find_end_of_inset(document.body, i)
2544 document.warning("Malformed LyX document: Could not find end of space inset.")
2546 del document.body[j]
2547 subst = document.body[i].replace('\\begin_inset Space \\upbracefill{}', \
2548 '\\begin_inset ERT\nstatus collapsed\n\n' \
2549 '\\begin_layout Standard\n\n\n\\backslash\n' \
2550 'upbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
2551 subst = subst.split('\n')
2552 document.body[i : i+1] = subst
2556 def revert_downbracefill(document):
2557 ' Revert \\begin_inset Space \\downbracefill{} to ERT '
2560 i = find_token(document.body, '\\begin_inset Space \\downbracefill{}', i)
2563 j = find_end_of_inset(document.body, i)
2565 document.warning("Malformed LyX document: Could not find end of space inset.")
2567 del document.body[j]
2568 subst = document.body[i].replace('\\begin_inset Space \\downbracefill{}', \
2569 '\\begin_inset ERT\nstatus collapsed\n\n' \
2570 '\\begin_layout Standard\n\n\n\\backslash\n' \
2571 'downbracefill{}\n\\end_layout\n\n\\end_inset\n\n')
2572 subst = subst.split('\n')
2573 document.body[i : i+1] = subst
2577 def revert_local_layout(document):
2578 ' Revert local layout headers.'
2581 i = find_token(document.header, "\\begin_local_layout", i)
2584 j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
2586 # this should not happen
2588 document.header[i : j + 1] = []
2591 def convert_pagebreaks(document):
2592 ' Convert inline Newpage insets to new format '
2595 i = find_token(document.body, '\\newpage', i)
2598 document.body[i:i+1] = ['\\begin_inset Newpage newpage',
2602 i = find_token(document.body, '\\pagebreak', i)
2605 document.body[i:i+1] = ['\\begin_inset Newpage pagebreak',
2609 i = find_token(document.body, '\\clearpage', i)
2612 document.body[i:i+1] = ['\\begin_inset Newpage clearpage',
2616 i = find_token(document.body, '\\cleardoublepage', i)
2619 document.body[i:i+1] = ['\\begin_inset Newpage cleardoublepage',
2623 def revert_pagebreaks(document):
2624 ' Revert \\begin_inset Newpage to previous inline format '
2627 i = find_token(document.body, '\\begin_inset Newpage', i)
2630 j = find_end_of_inset(document.body, i)
2632 document.warning("Malformed LyX document: Could not find end of Newpage inset.")
2634 del document.body[j]
2635 document.body[i] = document.body[i].replace('\\begin_inset Newpage newpage', '\\newpage')
2636 document.body[i] = document.body[i].replace('\\begin_inset Newpage pagebreak', '\\pagebreak')
2637 document.body[i] = document.body[i].replace('\\begin_inset Newpage clearpage', '\\clearpage')
2638 document.body[i] = document.body[i].replace('\\begin_inset Newpage cleardoublepage', '\\cleardoublepage')
2641 def convert_linebreaks(document):
2642 ' Convert inline Newline insets to new format '
2645 i = find_token(document.body, '\\newline', i)
2648 document.body[i:i+1] = ['\\begin_inset Newline newline',
2652 i = find_token(document.body, '\\linebreak', i)
2655 document.body[i:i+1] = ['\\begin_inset Newline linebreak',
2659 def revert_linebreaks(document):
2660 ' Revert \\begin_inset Newline to previous inline format '
2663 i = find_token(document.body, '\\begin_inset Newline', i)
2666 j = find_end_of_inset(document.body, i)
2668 document.warning("Malformed LyX document: Could not find end of Newline inset.")
2670 del document.body[j]
2671 document.body[i] = document.body[i].replace('\\begin_inset Newline newline', '\\newline')
2672 document.body[i] = document.body[i].replace('\\begin_inset Newline linebreak', '\\linebreak')
2675 def convert_japanese_plain(document):
2676 ' Set language japanese-plain to japanese '
2678 if document.language == "japanese-plain":
2679 document.language = "japanese"
2680 i = find_token(document.header, "\\language", 0)
2682 document.header[i] = "\\language japanese"
2685 j = find_token(document.body, "\\lang japanese-plain", j)
2688 document.body[j] = document.body[j].replace("\\lang japanese-plain", "\\lang japanese")
2692 def revert_pdfpages(document):
2693 ' Revert pdfpages external inset to ERT '
2696 i = find_token(document.body, "\\begin_inset External", i)
2699 j = find_end_of_inset(document.body, i)
2701 document.warning("Malformed lyx document: Missing '\\end_inset' in revert_pdfpages.")
2704 if get_value(document.body, 'template', i, j) == "PDFPages":
2705 filename = get_value(document.body, 'filename', i, j)
2707 r = re.compile(r'\textra PDFLaTeX \"(.*)\"$')
2708 for k in range(i, j):
2709 m = r.match(document.body[k])
2712 angle = get_value(document.body, 'rotateAngle', i, j)
2713 width = get_value(document.body, 'width', i, j)
2714 height = get_value(document.body, 'height', i, j)
2715 scale = get_value(document.body, 'scale', i, j)
2716 keepAspectRatio = find_token(document.body, "\tkeepAspectRatio", i, j)
2720 options += ",angle=" + angle
2722 options += "angle=" + angle
2725 options += ",width=" + convert_len(width)
2727 options += "width=" + convert_len(width)
2730 options += ",height=" + convert_len(height)
2732 options += "height=" + convert_len(height)
2735 options += ",scale=" + scale
2737 options += "scale=" + scale
2738 if keepAspectRatio != '':
2740 options += ",keepaspectratio"
2742 options += "keepaspectratio"
2744 options = '[' + options + ']'
2745 del document.body[i+1:j+1]
2746 document.body[i:i+1] = ['\\begin_inset ERT',
2749 '\\begin_layout Standard',
2752 'includepdf' + options + '{' + filename + '}',
2756 add_to_preamble(document, ['\\usepackage{pdfpages}\n'])
2762 def revert_mexican(document):
2763 ' Set language Spanish(Mexico) to Spanish '
2765 if document.language == "spanish-mexico":
2766 document.language = "spanish"
2767 i = find_token(document.header, "\\language", 0)
2769 document.header[i] = "\\language spanish"
2772 j = find_token(document.body, "\\lang spanish-mexico", j)
2775 document.body[j] = document.body[j].replace("\\lang spanish-mexico", "\\lang spanish")
2779 def remove_embedding(document):
2780 ' Remove embed tag from all insets '
2781 revert_inset_embedding(document, 'Graphics')
2782 revert_inset_embedding(document, 'External')
2783 revert_inset_embedding(document, 'CommandInset include')
2784 revert_inset_embedding(document, 'CommandInset bibtex')
2787 def revert_master(document):
2788 ' Remove master param '
2789 i = find_token(document.header, "\\master", 0)
2791 del document.header[i]
2794 def revert_graphics_group(document):
2795 ' Revert group information from graphics insets '
2798 i = find_token(document.body, "\\begin_inset Graphics", i)
2801 j = find_end_of_inset(document.body, i)
2803 document.warning("Malformed lyx document: Missing '\\end_inset' in revert_graphics_group.")
2806 k = find_token(document.body, " groupId", i, j)
2810 del document.body[k]
2814 def update_apa_styles(document):
2815 ' Replace obsolete styles '
2817 if document.textclass != "apa":
2820 obsoletedby = { "Acknowledgments": "Acknowledgements",
2821 "Section*": "Section",
2822 "Subsection*": "Subsection",
2823 "Subsubsection*": "Subsubsection",
2824 "Paragraph*": "Paragraph",
2825 "Subparagraph*": "Subparagraph"}
2828 i = find_token(document.body, "\\begin_layout", i)
2832 layout = document.body[i][14:]
2833 if layout in obsoletedby:
2834 document.body[i] = "\\begin_layout " + obsoletedby[layout]
2839 def convert_paper_sizes(document):
2840 ' exchange size options legalpaper and executivepaper to correct order '
2841 # routine is needed to fix http://bugzilla.lyx.org/show_bug.cgi?id=4868
2844 i = find_token(document.header, "\\papersize executivepaper", 0)
2846 document.header[i] = "\\papersize legalpaper"
2848 j = find_token(document.header, "\\papersize legalpaper", 0)
2850 document.header[j] = "\\papersize executivepaper"
2853 def revert_paper_sizes(document):
2854 ' exchange size options legalpaper and executivepaper to correct order '
2857 i = find_token(document.header, "\\papersize executivepaper", 0)
2859 document.header[i] = "\\papersize legalpaper"
2861 j = find_token(document.header, "\\papersize legalpaper", 0)
2863 document.header[j] = "\\papersize executivepaper"
2866 def convert_InsetSpace(document):
2867 " Convert '\\begin_inset Space foo' to '\\begin_inset space foo'"
2870 i = find_token(document.body, "\\begin_inset Space", i)
2873 document.body[i] = document.body[i].replace('\\begin_inset Space', '\\begin_inset space')
2876 def revert_InsetSpace(document):
2877 " Revert '\\begin_inset space foo' to '\\begin_inset Space foo'"
2880 i = find_token(document.body, "\\begin_inset space", i)
2883 document.body[i] = document.body[i].replace('\\begin_inset space', '\\begin_inset Space')
2886 def convert_display_enum(document):
2887 " Convert 'display foo' to 'display false/true'"
2890 i = find_token(document.body, "\tdisplay", i)
2893 val = get_value(document.body, 'display', i)
2895 document.body[i] = document.body[i].replace('none', 'false')
2896 if val == "default":
2897 document.body[i] = document.body[i].replace('default', 'true')
2898 if val == "monochrome":
2899 document.body[i] = document.body[i].replace('monochrome', 'true')
2900 if val == "grayscale":
2901 document.body[i] = document.body[i].replace('grayscale', 'true')
2903 document.body[i] = document.body[i].replace('color', 'true')
2904 if val == "preview":
2905 document.body[i] = document.body[i].replace('preview', 'true')
2909 def revert_display_enum(document):
2910 " Revert 'display false/true' to 'display none/color'"
2913 i = find_token(document.body, "\tdisplay", i)
2916 val = get_value(document.body, 'display', i)
2918 document.body[i] = document.body[i].replace('false', 'none')
2920 document.body[i] = document.body[i].replace('true', 'default')
2924 def remove_fontsCJK(document):
2925 ' Remove font_cjk param '
2926 i = find_token(document.header, "\\font_cjk", 0)
2928 del document.header[i]
2931 def convert_plain_layout(document):
2932 " Convert 'PlainLayout' to 'Plain Layout'"
2935 i = find_token(document.body, '\\begin_layout PlainLayout', i)
2938 document.body[i] = document.body[i].replace('\\begin_layout PlainLayout', \
2939 '\\begin_layout Plain Layout')
2943 def revert_plain_layout(document):
2944 " Revert 'Plain Layout' to 'PlainLayout'"
2947 i = find_token(document.body, '\\begin_layout Plain Layout', i)
2950 document.body[i] = document.body[i].replace('\\begin_layout Plain Layout', \
2951 '\\begin_layout PlainLayout')
2955 def revert_plainlayout(document):
2956 " Revert 'PlainLayout' to 'Standard'"
2959 i = find_token(document.body, '\\begin_layout PlainLayout', i)
2962 # This will be incorrect for some document classes, since Standard is not always
2963 # the default. But (a) it is probably the best we can do and (b) it will actually
2964 # work, in fact, since an unknown layout will be converted to default.
2965 document.body[i] = document.body[i].replace('\\begin_layout PlainLayout', \
2966 '\\begin_layout Standard')
2970 def revert_polytonicgreek(document):
2971 "Set language polytonic Greek to Greek"
2973 if document.language == "polutonikogreek":
2974 document.language = "greek"
2975 i = find_token(document.header, "\\language", 0)
2977 document.header[i] = "\\language greek"
2980 j = find_token(document.body, "\\lang polutonikogreek", j)
2983 document.body[j] = document.body[j].replace("\\lang polutonikogreek", "\\lang greek")
2987 def revert_removed_modules(document):
2990 i = find_token(document.header, "\\begin_remove_modules", i)
2993 j = find_end_of(document.header, i, "\\begin_remove_modules", "\\end_remove_modules")
2995 # this should not happen
2997 document.header[i : j + 1] = []
3000 def add_plain_layout(document):
3003 i = find_token(document.body, "\\begin_layout", i)
3006 if len(document.body[i].split()) == 1:
3007 document.body[i] = "\\begin_layout Plain Layout"
3011 def revert_tabulators(document):
3012 "Revert tabulators to 4 spaces"
3015 i = find_token(document.body, "\t", i)
3018 document.body[i] = document.body[i].replace("\t", " ")
3022 def revert_tabsize(document):
3023 "Revert the tabsize parameter of listings"
3027 # either it is the only parameter
3028 i = find_token(document.body, 'lstparams "tabsize=4"', i)
3030 del document.body[i]
3032 j = find_token(document.body, "lstparams", j)
3035 pos = document.body[j].find(",tabsize=")
3036 document.body[j] = document.body[j][:pos] + '"'
3041 def revert_mongolian(document):
3042 "Set language Mongolian to English"
3044 if document.language == "mongolian":
3045 document.language = "english"
3046 i = find_token(document.header, "\\language", 0)
3048 document.header[i] = "\\language english"
3051 j = find_token(document.body, "\\lang mongolian", j)
3054 document.body[j] = document.body[j].replace("\\lang mongolian", "\\lang english")
3058 def revert_default_options(document):
3059 ' Remove param use_default_options '
3060 i = find_token(document.header, "\\use_default_options", 0)
3062 del document.header[i]
3065 def convert_default_options(document):
3066 ' Add param use_default_options and set it to false '
3067 i = find_token(document.header, "\\textclass", 0)
3069 document.warning("Malformed LyX document: Missing `\\textclass'.")
3071 document.header.insert(i, '\\use_default_options false')
3074 def revert_backref_options(document):
3075 ' Revert option pdf_backref=page to pagebackref '
3076 i = find_token(document.header, "\\pdf_backref page", 0)
3078 document.header[i] = "\\pdf_pagebackref true"
3081 def convert_backref_options(document):
3082 ' We have changed the option pagebackref to backref=true '
3083 i = find_token(document.header, "\\pdf_pagebackref true", 0)
3085 document.header[i] = "\\pdf_backref page"
3086 j = find_token(document.header, "\\pdf_pagebackref false", 0)
3088 del document.header[j]
3089 # backref=true was not a valid option, we meant backref=section
3090 k = find_token(document.header, "\\pdf_backref true", 0)
3091 if k != -1 and i != -1:
3092 del document.header[k]
3093 elif k != -1 and j != -1:
3094 document.header[k] = "\\pdf_backref section"
3097 def convert_charstyle_element(document):
3098 "Convert CharStyle to Element for docbook backend"
3099 if document.backend != "docbook":
3103 i = find_token(document.body, "\\begin_inset Flex CharStyle:", i)
3106 document.body[i] = document.body[i].replace('\\begin_inset Flex CharStyle:',
3107 '\\begin_inset Flex Element:')
3109 def revert_charstyle_element(document):
3110 "Convert Element to CharStyle for docbook backend"
3111 if document.backend != "docbook":
3115 i = find_token(document.body, "\\begin_inset Flex Element:", i)
3118 document.body[i] = document.body[i].replace('\\begin_inset Flex Element:',
3119 '\\begin_inset Flex CharStyle:')
3125 supported_versions = ["1.6.0","1.6"]
3126 convert = [[277, [fix_wrong_tables]],
3127 [278, [close_begin_deeper]],
3128 [279, [long_charstyle_names]],
3129 [280, [axe_show_label]],
3132 [283, [convert_flex]],
3136 [287, [convert_wrapfig_options]],
3137 [288, [convert_inset_command]],
3138 [289, [convert_latexcommand_index]],
3141 [292, [convert_japanese_cjk]],
3143 [294, [convert_pdf_options]],
3144 [295, [convert_htmlurl, convert_url]],
3145 [296, [convert_include]],
3146 [297, [convert_usorbian]],
3147 [298, [convert_macro_global]],
3152 [303, [convert_serbocroatian]],
3153 [304, [convert_framed_notes]],
3160 [311, [convert_ams_classes]],
3162 [313, [convert_module_names]],
3165 [316, [convert_subfig]],
3168 [319, [convert_spaceinset, convert_hfill]],
3170 [321, [convert_tablines]],
3171 [322, [convert_plain_layout]],
3172 [323, [convert_pagebreaks]],
3173 [324, [convert_linebreaks]],
3174 [325, [convert_japanese_plain]],
3177 [328, [remove_embedding, remove_extra_embedded_files, remove_inzip_options]],
3180 [331, [convert_ltcaption]],
3182 [333, [update_apa_styles]],
3183 [334, [convert_paper_sizes]],
3184 [335, [convert_InsetSpace]],
3186 [337, [convert_display_enum]],
3189 [340, [add_plain_layout]],
3192 [343, [convert_default_options]],
3193 [344, [convert_backref_options]],
3194 [345, [convert_charstyle_element]]
3197 revert = [[344, [revert_charstyle_element]],
3198 [343, [revert_backref_options]],
3199 [342, [revert_default_options]],
3200 [341, [revert_mongolian]],
3201 [340, [revert_tabulators, revert_tabsize]],
3203 [338, [revert_removed_modules]],
3204 [337, [revert_polytonicgreek]],
3205 [336, [revert_display_enum]],
3206 [335, [remove_fontsCJK]],
3207 [334, [revert_InsetSpace]],
3208 [333, [revert_paper_sizes]],
3210 [331, [revert_graphics_group]],
3211 [330, [revert_ltcaption]],
3212 [329, [revert_leftarrowfill, revert_rightarrowfill, revert_upbracefill, revert_downbracefill]],
3213 [328, [revert_master]],
3215 [326, [revert_mexican]],
3216 [325, [revert_pdfpages]],
3218 [323, [revert_linebreaks]],
3219 [322, [revert_pagebreaks]],
3220 [321, [revert_local_layout, revert_plain_layout]],
3221 [320, [revert_tablines]],
3222 [319, [revert_protected_hfill]],
3223 [318, [revert_spaceinset, revert_hfills, revert_hspace]],
3224 [317, [remove_extra_embedded_files]],
3225 [316, [revert_wrapplacement]],
3226 [315, [revert_subfig]],
3227 [314, [revert_colsep, revert_plainlayout]],
3229 [312, [revert_module_names]],
3230 [311, [revert_rotfloat, revert_widesideways]],
3231 [310, [revert_external_embedding]],
3232 [309, [revert_btprintall]],
3233 [308, [revert_nocite]],
3234 [307, [revert_serbianlatin]],
3235 [306, [revert_slash, revert_nobreakdash]],
3236 [305, [revert_interlingua]],
3237 [304, [revert_bahasam]],
3238 [303, [revert_framed_notes]],
3240 [301, [revert_latin, revert_samin]],
3241 [300, [revert_linebreak]],
3242 [299, [revert_pagebreak]],
3243 [298, [revert_hyperlinktype]],
3244 [297, [revert_macro_optional_params]],
3245 [296, [revert_albanian, revert_lowersorbian, revert_uppersorbian]],
3246 [295, [revert_include]],
3247 [294, [revert_href, revert_url]],
3248 [293, [revert_pdf_options_2]],
3249 [292, [revert_inset_info]],
3250 [291, [revert_japanese, revert_japanese_encoding, revert_japanese_cjk]],
3251 [290, [revert_vietnamese]],
3252 [289, [revert_wraptable]],
3253 [288, [revert_latexcommand_index]],
3254 [287, [revert_inset_command]],
3255 [286, [revert_wrapfig_options]],
3256 [285, [revert_pdf_options]],
3257 [284, [remove_inzip_options]],
3259 [282, [revert_flex]],
3261 [280, [revert_begin_modules]],
3262 [279, [revert_show_label]],
3263 [278, [revert_long_charstyle_names]],
3269 if __name__ == "__main__":