]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/lyx_2_3.py
whitespace.
[lyx.git] / lib / lyx2lyx / lyx_2_3.py
1 # -*- coding: utf-8 -*-
2 # This file is part of lyx2lyx
3 # -*- coding: utf-8 -*-
4 # Copyright (C) 2016 The LyX team
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 """ Convert files to the file format generated by lyx 2.3"""
21
22 import re, string
23 import unicodedata
24 import sys, os
25
26 # Uncomment only what you need to import, please.
27
28 from parser_tools import find_end_of, find_token_backwards, find_end_of_layout#,
29 #  find_token, find_tokens, \
30 #  find_token_exact, find_end_of_inset, \
31 #  is_in_inset, get_value, get_quoted_value, \
32 #  del_token, check_token, get_option_value, get_bool_value
33
34 from parser_tools import find_token, find_end_of_inset, get_value, \
35      get_bool_value, get_containing_layout
36
37 from lyx2lyx_tools import add_to_preamble, put_cmd_in_ert
38 #  get_ert, lyx2latex, \
39 #  lyx2verbatim, length_in_bp, convert_info_insets
40 #  insert_to_preamble, latex_length, revert_flex_inset, \
41 #  revert_font_attrs, hex2ratio, str2bool
42
43 from lyx2lyx_tools import add_to_preamble, put_cmd_in_ert
44
45 ####################################################################
46 # Private helper functions
47
48
49
50 ###############################################################################
51 ###
52 ### Conversion and reversion routines
53 ###
54 ###############################################################################
55
56 def convert_microtype(document):
57     " Add microtype settings. "
58     i = find_token(document.header, "\\font_tt_scale" , 0)
59     if i == -1:
60         document.warning("Malformed LyX document: Can't find \\font_tt_scale.")
61         i = len(document.header) - 1
62
63     j = find_token(document.preamble, "\\usepackage{microtype}", 0)
64     if j == -1:
65         document.header.insert(i + 1, "\\use_microtype false")
66     else:
67         document.header.insert(i + 1, "\\use_microtype true")
68         del document.preamble[j]
69
70
71 def revert_microtype(document):
72     " Remove microtype settings. "
73     i = find_token(document.header, "\\use_microtype", 0)
74     if i == -1:
75         return
76     use_microtype = get_bool_value(document.header, "\\use_microtype" , i)
77     del document.header[i]
78     if use_microtype:
79         add_to_preamble(document, ["\\usepackage{microtype}"])
80
81
82 def convert_dateinset(document):
83     ' Convert date external inset to ERT '
84     i = 0
85     while True:
86         i = find_token(document.body, "\\begin_inset External", i)
87         if i == -1:
88             return
89         j = find_end_of_inset(document.body, i)
90         if j == -1:
91             document.warning("Malformed lyx document: Missing '\\end_inset' in convert_dateinset.")
92             i += 1
93             continue
94         if get_value(document.body, 'template', i, j) == "Date":
95             document.body[i : j + 1] = put_cmd_in_ert("\\today ")
96         i += 1
97         continue
98
99
100 def convert_inputenc(document):
101     " Replace no longer supported input encoding settings. "
102     i = find_token(document.header, "\\inputenc", 0)
103     if i == -1:
104         return
105     if get_value(document.header, "\\inputencoding", i) == "pt254":
106         document.header[i] = "\\inputencoding pt154"
107     
108
109 def convert_ibranches(document):
110     ' Add "inverted 0" to branch insets'
111     i = 0
112     while True:
113         i = find_token(document.body, "\\begin_inset Branch", i)
114         if i == -1:
115             return
116         document.body.insert(i + 1, "inverted 0")
117         i += 1
118
119
120 def revert_ibranches(document):
121     ' Convert inverted branches to explicit anti-branches'
122     # Get list of branches
123     ourbranches = {}
124     i = 0
125     while True:
126         i = find_token(document.header, "\\branch", i)
127         if i == -1:
128             break
129         branch = document.header[i][8:].strip()
130         if document.header[i+1].startswith("\\selected "):
131             #document.warning(document.header[i+1])
132             #document.warning(document.header[i+1][10])
133             selected = int(document.header[i+1][10])
134         else:
135             document.warning("Malformed LyX document: No selection indicator for branch " + branch)
136             selected = 1
137             
138         # the value tells us whether the branch is selected
139         ourbranches[document.header[i][8:].strip()] = selected
140         i += 1
141
142     # Figure out what inverted branches, if any, have been used
143     # and convert them to "Anti-OldBranch"
144     ibranches = {}
145     i = 0
146     while True:
147         i = find_token(document.body, "\\begin_inset Branch", i)
148         if i == -1:
149             break
150         if not document.body[i+1].startswith("inverted "):
151             document.warning("Malformed LyX document: Missing 'inverted' tag!")
152             i += 1
153             continue
154         inverted = document.body[i+1][9]
155         #document.warning(document.body[i+1])
156
157         if inverted == "1":
158             branch = document.body[i][20:].strip()
159             #document.warning(branch)
160             if not branch in ibranches:
161                 antibranch = "Anti-" + branch
162                 while antibranch in ibranches:
163                     antibranch = "x" + antibranch
164                 ibranches[branch] = antibranch
165             else:
166                 antibranch = ibranches[branch]
167             #document.warning(antibranch)
168             document.body[i] = "\\begin_inset Branch " + antibranch
169
170         # remove "inverted" key
171         del document.body[i+1]
172         i += 1
173
174     # now we need to add the new branches to the header
175     for old, new in ibranches.iteritems():
176         i = find_token(document.header, "\\branch " + old, 0)
177         if i == -1:
178             document.warning("Can't find branch %s even though we found it before!" % (old))
179             continue
180         j = find_token(document.header, "\\end_branch", i)
181         if j == -1:
182             document.warning("Malformed LyX document! Can't find end of branch " + old)
183             continue
184         # ourbranches[old] - 1 inverts the selection status of the old branch
185         lines = ["\\branch " + new,
186                  "\\selected " + str(ourbranches[old] - 1)]
187         # these are the old lines telling us color, etc.
188         lines += document.header[i+2 : j+1]
189         document.header[i:i] = lines
190
191
192 def revert_beamer_article_styles(document):
193     " Include (scr)article styles in beamer article "
194
195     beamer_articles = ["article-beamer", "scrarticle-beamer"]
196     if document.textclass not in beamer_articles:
197         return
198
199     inclusion = "article.layout"
200     if document.textclass == "scrarticle-beamer":
201         inclusion = "scrartcl.layout"
202
203     i = find_token(document.header, "\\begin_local_layout", 0)
204     if i == -1:
205         k = find_token(document.header, "\\language", 0)
206         if k == -1:
207             # this should not happen
208             document.warning("Malformed LyX document! No \\language header found!")
209             return
210         document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
211         i = k - 1
212
213     j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
214     if j == -1:
215         # this should not happen
216         document.warning("Malformed LyX document: Can't find end of local layout!")
217         return
218
219     document.header[i+1 : i+1] = [
220         "### Inserted by lyx2lyx (more [scr]article styles) ###",
221         "Input " + inclusion,
222         "Input beamer.layout",
223         "Provides geometry 0",
224         "Provides hyperref 0",
225         "DefaultFont",
226         "     Family                Roman",
227         "     Series                Medium",
228         "     Shape                 Up",
229         "     Size                  Normal",
230         "     Color                 None",
231         "EndFont",
232         "Preamble",
233         "     \\usepackage{beamerarticle,pgf}",
234         "     % this default might be overridden by plain title style",
235         "     \\newcommand\makebeamertitle{\\frame{\\maketitle}}%",
236         "     \\AtBeginDocument{",
237         "             \\let\\origtableofcontents=\\tableofcontents",
238         "             \\def\\tableofcontents{\\@ifnextchar[{\\origtableofcontents}{\\gobbletableofcontents}}",
239         "             \\def\\gobbletableofcontents#1{\\origtableofcontents}",
240         "     }",
241         "EndPreamble",
242         "### End of insertion by lyx2lyx (more [scr]article styles) ###"
243     ]
244
245
246 def convert_beamer_article_styles(document):
247     " Remove included (scr)article styles in beamer article "
248
249     beamer_articles = ["article-beamer", "scrarticle-beamer"]
250     if document.textclass not in beamer_articles:
251         return
252
253     i = find_token(document.header, "\\begin_local_layout", 0)
254     if i == -1:
255         return
256
257     j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
258     if j == -1:
259         # this should not happen
260         document.warning("Malformed LyX document: Can't find end of local layout!")
261         return
262
263     k = find_token(document.header, "### Inserted by lyx2lyx (more [scr]article styles) ###", i, j)
264     if k != -1:
265         l = find_token(document.header, "### End of insertion by lyx2lyx (more [scr]article styles) ###", i, j)
266         if l == -1:
267             # this should not happen
268             document.warning("End of lyx2lyx local layout insertion not found!")
269             return
270
271         if k == i + 1 and l == j - 1:
272             # that was all the local layout there was
273             document.header[i : j + 1] = []
274         else:
275             document.header[k : l + 1] = []
276
277
278 def revert_bosnian(document):
279     "Set the document language to English but assure Bosnian output"
280
281     if document.language == "bosnian":
282         document.language = "english"
283         i = find_token(document.header, "\\language bosnian", 0)
284         if i != -1:
285             document.header[i] = "\\language english"
286         j = find_token(document.header, "\\language_package default", 0)
287         if j != -1:
288             document.header[j] = "\\language_package babel"
289         k = find_token(document.header, "\\options", 0)
290         if k != -1:
291             document.header[k] = document.header[k].replace("\\options", "\\options bosnian,")
292         else:
293             l = find_token(document.header, "\\use_default_options", 0)
294             document.header.insert(l + 1, "\\options bosnian")
295
296
297 def revert_friulan(document):
298     "Set the document language to English but assure Friulan output"
299
300     if document.language == "friulan":
301         document.language = "english"
302         i = find_token(document.header, "\\language friulan", 0)
303         if i != -1:
304             document.header[i] = "\\language english"
305         j = find_token(document.header, "\\language_package default", 0)
306         if j != -1:
307             document.header[j] = "\\language_package babel"
308         k = find_token(document.header, "\\options", 0)
309         if k != -1:
310             document.header[k] = document.header[k].replace("\\options", "\\options friulan,")
311         else:
312             l = find_token(document.header, "\\use_default_options", 0)
313             document.header.insert(l + 1, "\\options friulan")
314
315
316 def revert_macedonian(document):
317     "Set the document language to English but assure Macedonian output"
318
319     if document.language == "macedonian":
320         document.language = "english"
321         i = find_token(document.header, "\\language macedonian", 0)
322         if i != -1:
323             document.header[i] = "\\language english"
324         j = find_token(document.header, "\\language_package default", 0)
325         if j != -1:
326             document.header[j] = "\\language_package babel"
327         k = find_token(document.header, "\\options", 0)
328         if k != -1:
329             document.header[k] = document.header[k].replace("\\options", "\\options macedonian,")
330         else:
331             l = find_token(document.header, "\\use_default_options", 0)
332             document.header.insert(l + 1, "\\options macedonian")
333
334
335 def revert_piedmontese(document):
336     "Set the document language to English but assure Piedmontese output"
337
338     if document.language == "piedmontese":
339         document.language = "english"
340         i = find_token(document.header, "\\language piedmontese", 0)
341         if i != -1:
342             document.header[i] = "\\language english"
343         j = find_token(document.header, "\\language_package default", 0)
344         if j != -1:
345             document.header[j] = "\\language_package babel"
346         k = find_token(document.header, "\\options", 0)
347         if k != -1:
348             document.header[k] = document.header[k].replace("\\options", "\\options piedmontese,")
349         else:
350             l = find_token(document.header, "\\use_default_options", 0)
351             document.header.insert(l + 1, "\\options piedmontese")
352
353
354 def revert_romansh(document):
355     "Set the document language to English but assure Romansh output"
356
357     if document.language == "romansh":
358         document.language = "english"
359         i = find_token(document.header, "\\language romansh", 0)
360         if i != -1:
361             document.header[i] = "\\language english"
362         j = find_token(document.header, "\\language_package default", 0)
363         if j != -1:
364             document.header[j] = "\\language_package babel"
365         k = find_token(document.header, "\\options", 0)
366         if k != -1:
367             document.header[k] = document.header[k].replace("\\options", "\\options romansh,")
368         else:
369             l = find_token(document.header, "\\use_default_options", 0)
370             document.header.insert(l + 1, "\\options romansh")
371
372
373 def revert_amharic(document):
374     "Set the document language to English but assure Amharic output"
375
376     if document.language == "amharic":
377         document.language = "english"
378         i = find_token(document.header, "\\language amharic", 0)
379         if i != -1:
380             document.header[i] = "\\language english"
381         j = find_token(document.header, "\\language_package default", 0)
382         if j != -1:
383             document.header[j] = "\\language_package default"
384         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{amharic}}"])
385         document.body[2 : 2] = ["\\begin_layout Standard",
386                                 "\\begin_inset ERT", "status open", "",
387                                 "\\begin_layout Plain Layout", "", "",
388                                 "\\backslash",
389                                 "resetdefaultlanguage{amharic}",
390                                 "\\end_layout", "", "\\end_inset", "", "",
391                                 "\\end_layout", ""]
392
393
394 def revert_asturian(document):
395     "Set the document language to English but assure Asturian output"
396
397     if document.language == "asturian":
398         document.language = "english"
399         i = find_token(document.header, "\\language asturian", 0)
400         if i != -1:
401             document.header[i] = "\\language english"
402         j = find_token(document.header, "\\language_package default", 0)
403         if j != -1:
404             document.header[j] = "\\language_package default"
405         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{asturian}}"])
406         document.body[2 : 2] = ["\\begin_layout Standard",
407                                 "\\begin_inset ERT", "status open", "",
408                                 "\\begin_layout Plain Layout", "", "",
409                                 "\\backslash",
410                                 "resetdefaultlanguage{asturian}",
411                                 "\\end_layout", "", "\\end_inset", "", "",
412                                 "\\end_layout", ""]
413
414
415 def revert_kannada(document):
416     "Set the document language to English but assure Kannada output"
417
418     if document.language == "kannada":
419         document.language = "english"
420         i = find_token(document.header, "\\language kannada", 0)
421         if i != -1:
422             document.header[i] = "\\language english"
423         j = find_token(document.header, "\\language_package default", 0)
424         if j != -1:
425             document.header[j] = "\\language_package default"
426         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{kannada}}"])
427         document.body[2 : 2] = ["\\begin_layout Standard",
428                                 "\\begin_inset ERT", "status open", "",
429                                 "\\begin_layout Plain Layout", "", "",
430                                 "\\backslash",
431                                 "resetdefaultlanguage{kannada}",
432                                 "\\end_layout", "", "\\end_inset", "", "",
433                                 "\\end_layout", ""]
434
435
436 def revert_khmer(document):
437     "Set the document language to English but assure Khmer output"
438
439     if document.language == "khmer":
440         document.language = "english"
441         i = find_token(document.header, "\\language khmer", 0)
442         if i != -1:
443             document.header[i] = "\\language english"
444         j = find_token(document.header, "\\language_package default", 0)
445         if j != -1:
446             document.header[j] = "\\language_package default"
447         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{khmer}}"])
448         document.body[2 : 2] = ["\\begin_layout Standard",
449                                 "\\begin_inset ERT", "status open", "",
450                                 "\\begin_layout Plain Layout", "", "",
451                                 "\\backslash",
452                                 "resetdefaultlanguage{khmer}",
453                                 "\\end_layout", "", "\\end_inset", "", "",
454                                 "\\end_layout", ""]
455
456
457 def revert_urdu(document):
458     "Set the document language to English but assure Urdu output"
459
460     if document.language == "urdu":
461         document.language = "english"
462         i = find_token(document.header, "\\language urdu", 0)
463         if i != -1:
464             document.header[i] = "\\language english"
465         j = find_token(document.header, "\\language_package default", 0)
466         if j != -1:
467             document.header[j] = "\\language_package default"
468         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{urdu}}"])
469         document.body[2 : 2] = ["\\begin_layout Standard",
470                                 "\\begin_inset ERT", "status open", "",
471                                 "\\begin_layout Plain Layout", "", "",
472                                 "\\backslash",
473                                 "resetdefaultlanguage{urdu}",
474                                 "\\end_layout", "", "\\end_inset", "", "",
475                                 "\\end_layout", ""]
476
477
478 def revert_syriac(document):
479     "Set the document language to English but assure Syriac output"
480
481     if document.language == "syriac":
482         document.language = "english"
483         i = find_token(document.header, "\\language syriac", 0)
484         if i != -1:
485             document.header[i] = "\\language english"
486         j = find_token(document.header, "\\language_package default", 0)
487         if j != -1:
488             document.header[j] = "\\language_package default"
489         add_to_preamble(document, ["\\AtBeginDocument{\setotherlanguage{syriac}}"])
490         document.body[2 : 2] = ["\\begin_layout Standard",
491                                 "\\begin_inset ERT", "status open", "",
492                                 "\\begin_layout Plain Layout", "", "",
493                                 "\\backslash",
494                                 "resetdefaultlanguage{syriac}",
495                                 "\\end_layout", "", "\\end_inset", "", "",
496                                 "\\end_layout", ""]
497
498
499 def revert_quotes(document):
500     " Revert Quote Insets in verbatim or Hebrew context to plain quotes "
501
502     # First handle verbatim insets
503     i = 0
504     j = 0
505     while i < len(document.body):
506         words = document.body[i].split()
507         if len(words) > 1 and words[0] == "\\begin_inset" and \
508            ( words[1] in ["ERT", "listings"] or ( len(words) > 2 and words[2] in ["URL", "Chunk", "Sweave", "S/R"]) ):
509             j = find_end_of_inset(document.body, i)
510             if j == -1:
511                 document.warning("Malformed LyX document: Can't find end of " + words[1] + " inset at line " + str(i))
512                 i += 1
513                 continue
514             while True:
515                 k = find_token(document.body, '\\begin_inset Quotes', i, j)
516                 if k == -1:
517                     i += 1
518                     break
519                 l = find_end_of_inset(document.body, k)
520                 if l == -1:
521                     document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
522                     i = k
523                     continue
524                 replace = "\""
525                 if document.body[k].endswith("s"):
526                     replace = "'"
527                 document.body[k:l+1] = [replace]
528         else:
529             i += 1
530             continue
531
532     # Now verbatim layouts
533     i = 0
534     j = 0
535     while i < len(document.body):
536         words = document.body[i].split()
537         if len(words) > 1 and words[0] == "\\begin_layout" and \
538            words[1] in ["Verbatim", "Verbatim*", "Code", "Author_Email", "Author_URL"]:
539             j = find_end_of_layout(document.body, i)
540             if j == -1:
541                 document.warning("Malformed LyX document: Can't find end of " + words[1] + " layout at line " + str(i))
542                 i += 1
543                 continue
544             while True:
545                 k = find_token(document.body, '\\begin_inset Quotes', i, j)
546                 if k == -1:
547                     i += 1
548                     break
549                 l = find_end_of_inset(document.body, k)
550                 if l == -1:
551                     document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
552                     i = k
553                     continue
554                 replace = "\""
555                 if document.body[k].endswith("s"):
556                     replace = "'"
557                 document.body[k:l+1] = [replace]
558         else:
559             i += 1
560             continue
561
562     # Now handle Hebrew
563     if not document.language == "hebrew" and find_token(document.body, '\\lang hebrew', 0) == -1:
564         return
565
566     i = 0
567     j = 0
568     while True:
569         k = find_token(document.body, '\\begin_inset Quotes', i)
570         if k == -1:
571             return
572         l = find_end_of_inset(document.body, k)
573         if l == -1:
574             document.warning("Malformed LyX document: Can't find end of Quote inset at line " + str(k))
575             i = k
576             continue
577         hebrew = False
578         parent = get_containing_layout(document.body, k)
579         ql = find_token_backwards(document.body, "\\lang", k)
580         if ql == -1 or ql < parent[1]:
581             hebrew = document.language == "hebrew"
582         elif document.body[ql] == "\\lang hebrew":
583             hebrew = True
584         if hebrew:
585             replace = "\""
586             if document.body[k].endswith("s"):
587                 replace = "'"
588             document.body[k:l+1] = [replace]
589         i = l
590     
591
592 def revert_iopart(document):
593     " Input new styles via local layout "
594     if document.textclass != "iopart":
595         return
596
597     i = find_token(document.header, "\\begin_local_layout", 0)
598     if i == -1:
599         k = find_token(document.header, "\\language", 0)
600         if k == -1:
601             # this should not happen
602             document.warning("Malformed LyX document! No \\language header found!")
603             return
604         document.header[k-1 : k-1] = ["\\begin_local_layout", "\\end_local_layout"]
605         i = k-1
606
607     j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
608     if j == -1:
609         # this should not happen
610         document.warning("Malformed LyX document! Can't find end of local layout!")
611         return
612
613     document.header[i+1 : i+1] = [
614         "### Inserted by lyx2lyx (stdlayouts) ###",
615         "Input stdlayouts.inc",
616         "### End of insertion by lyx2lyx (stdlayouts) ###"
617     ]
618
619
620 def convert_iopart(document):
621     " Remove local layout we added, if it is there "
622     if document.textclass != "iopart":
623         return
624
625     i = find_token(document.header, "\\begin_local_layout", 0)
626     if i == -1:
627         return
628
629     j = find_end_of(document.header, i, "\\begin_local_layout", "\\end_local_layout")
630     if j == -1:
631         # this should not happen
632         document.warning("Malformed LyX document! Can't find end of local layout!")
633         return
634
635     k = find_token(document.header, "### Inserted by lyx2lyx (stdlayouts) ###", i, j)
636     if k != -1:
637         l = find_token(document.header, "### End of insertion by lyx2lyx (stdlayouts) ###", i, j)
638         if l == -1:
639             # this should not happen
640             document.warning("End of lyx2lyx local layout insertion not found!")
641             return
642         if k == i + 1 and l == j - 1:
643             # that was all the local layout there was
644             document.header[i : j + 1] = []
645         else:
646             document.header[k : l + 1] = []
647
648
649 ##
650 # Conversion hub
651 #
652
653 supported_versions = ["2.3.0", "2.3"]
654 convert = [
655            [509, [convert_microtype]],
656            [510, [convert_dateinset]],
657            [511, [convert_ibranches]],
658            [512, [convert_beamer_article_styles]],
659            [513, []],
660            [514, []],
661            [515, []],
662            [516, [convert_inputenc]],
663            [517, []],
664            [518, [convert_iopart]]
665           ]
666
667 revert =  [
668            [517, [revert_iopart]],
669            [516, [revert_quotes]],
670            [515, []],
671            [514, [revert_urdu, revert_syriac]],
672            [513, [revert_amharic, revert_asturian, revert_kannada, revert_khmer]],
673            [512, [revert_bosnian, revert_friulan, revert_macedonian, revert_piedmontese, revert_romansh]],
674            [511, [revert_beamer_article_styles]],
675            [510, [revert_ibranches]],
676            [509, []],
677            [508, [revert_microtype]]
678           ]
679
680
681 if __name__ == "__main__":
682     pass