]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
Add quote style information to languages
[lyx.git] / src / tex2lyx / text.cpp
1 /**
2  * \file tex2lyx/text.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  * \author Uwe Stöhr
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 // {[(
14
15 #include <config.h>
16
17 #include "tex2lyx.h"
18
19 #include "Context.h"
20 #include "Encoding.h"
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
23 #include "Layout.h"
24 #include "Length.h"
25 #include "Preamble.h"
26
27 #include "insets/ExternalTemplate.h"
28
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
35
36 #include <algorithm>
37 #include <iostream>
38 #include <map>
39 #include <sstream>
40 #include <vector>
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49                 Context const & context, InsetLayout const * layout)
50 {
51         bool const forcePlainLayout =
52                 layout ? layout->forcePlainLayout() : false;
53         Context newcontext(true, context.textclass);
54         if (forcePlainLayout)
55                 newcontext.layout = &context.textclass.plainLayout();
56         else
57                 newcontext.font = context.font;
58         parse_text(p, os, flags, outer, newcontext);
59         newcontext.check_end_layout(os);
60 }
61
62
63 namespace {
64
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66                 Context const & context, string const & name)
67 {
68         InsetLayout const * layout = 0;
69         DocumentClass::InsetLayouts::const_iterator it =
70                 context.textclass.insetLayouts().find(from_ascii(name));
71         if (it != context.textclass.insetLayouts().end())
72                 layout = &(it->second);
73         parse_text_in_inset(p, os, flags, outer, context, layout);
74 }
75
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78                 Context & context)
79 {
80         Context newcontext(context);
81         // Don't inherit the paragraph-level extra stuff
82         newcontext.par_extra_stuff.clear();
83         parse_text(p, os, flags, outer, newcontext);
84         // Make sure that we don't create invalid .lyx files
85         context.need_layout = newcontext.need_layout;
86         context.need_end_layout = newcontext.need_end_layout;
87 }
88
89
90 /*!
91  * Thin wrapper around parse_text_snippet() using a string.
92  *
93  * We completely ignore \c context.need_layout and \c context.need_end_layout,
94  * because our return value is not used directly (otherwise the stream version
95  * of parse_text_snippet() could be used). That means that the caller needs
96  * to do layout management manually.
97  * This is intended to parse text that does not create any layout changes.
98  */
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100                   Context & context)
101 {
102         Context newcontext(context);
103         newcontext.need_layout = false;
104         newcontext.need_end_layout = false;
105         newcontext.new_layout_allowed = false;
106         // Avoid warning by Context::~Context()
107         newcontext.par_extra_stuff.clear();
108         ostringstream os;
109         parse_text_snippet(p, os, flags, outer, newcontext);
110         return os.str();
111 }
112
113
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115  "vpageref", "prettyref", "eqref", 0 };
116
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118  "vpageref", "formatted", "eqref", 0 };
119
120 /**
121  * supported CJK encodings
122  */
123 const char * const supported_CJK_encodings[] = {
124 "EUC-JP", "KS", "GB", "UTF8", 0};
125
126 /**
127  * the same as supported_CJK_encodings with their corresponding LyX language name
128  * please keep this in sync with supported_CJK_encodings line by line!
129  */
130 const char * const coded_supported_CJK_encodings[] = {
131 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional", 0};
132
133 string CJK2lyx(string const & encoding)
134 {
135         char const * const * where = is_known(encoding, supported_CJK_encodings);
136         if (where)
137                 return coded_supported_CJK_encodings[where - supported_CJK_encodings];
138         return encoding;
139 }
140
141 /*!
142  * natbib commands.
143  * The starred forms are also known except for "citefullauthor",
144  * "citeyear" and "citeyearpar".
145  */
146 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
147 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
148 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
149
150 /*!
151  * jurabib commands.
152  * No starred form other than "cite*" known.
153  */
154 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
155 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
156 // jurabib commands not (yet) supported by LyX:
157 // "fullcite",
158 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
159 // "footciteauthor", "footciteyear", "footciteyearpar",
160 "citefield", "citetitle", 0 };
161
162 /// LaTeX names for quotes
163 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
164 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
165 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
166 "guilsinglleft", "frq", "guilsinglright", 0};
167
168 /// the same as known_quotes with .lyx names
169 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
170 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
171 "gld", "grd", "gls", "ers", "fls",
172 "fls", "frs", "frs", 0};
173
174 /// LaTeX names for font sizes
175 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
176 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
177
178 /// the same as known_sizes with .lyx names
179 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
180 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
181
182 /// LaTeX 2.09 names for font families
183 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
184
185 /// LaTeX names for font families
186 char const * const known_font_families[] = { "rmfamily", "sffamily",
187 "ttfamily", 0};
188
189 /// LaTeX names for font family changing commands
190 char const * const known_text_font_families[] = { "textrm", "textsf",
191 "texttt", 0};
192
193 /// The same as known_old_font_families, known_font_families and
194 /// known_text_font_families with .lyx names
195 char const * const known_coded_font_families[] = { "roman", "sans",
196 "typewriter", 0};
197
198 /// LaTeX 2.09 names for font series
199 char const * const known_old_font_series[] = { "bf", 0};
200
201 /// LaTeX names for font series
202 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
203
204 /// LaTeX names for font series changing commands
205 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
206
207 /// The same as known_old_font_series, known_font_series and
208 /// known_text_font_series with .lyx names
209 char const * const known_coded_font_series[] = { "bold", "medium", 0};
210
211 /// LaTeX 2.09 names for font shapes
212 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
213
214 /// LaTeX names for font shapes
215 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
216 "upshape", 0};
217
218 /// LaTeX names for font shape changing commands
219 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
220 "textup", 0};
221
222 /// The same as known_old_font_shapes, known_font_shapes and
223 /// known_text_font_shapes with .lyx names
224 char const * const known_coded_font_shapes[] = { "italic", "slanted",
225 "smallcaps", "up", 0};
226
227 /// Known special characters which need skip_spaces_braces() afterwards
228 char const * const known_special_chars[] = {"ldots", "lyxarrow",
229 "textcompwordmark", "slash", 0};
230
231 /// the same as known_special_chars with .lyx names
232 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
233 "textcompwordmark{}", "slash{}", 0};
234
235 /*!
236  * Graphics file extensions known by the dvips driver of the graphics package.
237  * These extensions are used to complete the filename of an included
238  * graphics file if it does not contain an extension.
239  * The order must be the same that latex uses to find a file, because we
240  * will use the first extension that matches.
241  * This is only an approximation for the common cases. If we would want to
242  * do it right in all cases, we would need to know which graphics driver is
243  * used and know the extensions of every driver of the graphics package.
244  */
245 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
246 "ps.gz", "eps.Z", "ps.Z", 0};
247
248 /*!
249  * Graphics file extensions known by the pdftex driver of the graphics package.
250  * \sa known_dvips_graphics_formats
251  */
252 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
253 "mps", "tif", 0};
254
255 /*!
256  * Known file extensions for TeX files as used by \\include.
257  */
258 char const * const known_tex_extensions[] = {"tex", 0};
259
260 /// spaces known by InsetSpace
261 char const * const known_spaces[] = { " ", "space", ",",
262 "thinspace", "quad", "qquad", "enspace", "enskip",
263 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
264 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
265 "upbracefill", "downbracefill", 0};
266
267 /// the same as known_spaces with .lyx names
268 char const * const known_coded_spaces[] = { "space{}", "space{}",
269 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
270 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
271 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
272 "upbracefill{}", "downbracefill{}", 0};
273
274 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
275 /// them in ERT. "LaTeXe" must come before "LaTeX"!
276 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
277 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
278 int const known_phrase_lengths[] = {3, 5, 7, 0};
279
280 // string to store the float type to be able to determine the type of subfloats
281 string float_type = "";
282
283
284 /// splits "x=z, y=b" into a map and an ordered keyword vector
285 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
286 {
287         vector<string> v;
288         split(s, v);
289         res.clear();
290         keys.resize(v.size());
291         for (size_t i = 0; i < v.size(); ++i) {
292                 size_t const pos   = v[i].find('=');
293                 string const index = trimSpaceAndEol(v[i].substr(0, pos));
294                 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
295                 res[index] = value;
296                 keys[i] = index;
297         }
298 }
299
300
301 /*!
302  * Split a LaTeX length into value and unit.
303  * The latter can be a real unit like "pt", or a latex length variable
304  * like "\textwidth". The unit may contain additional stuff like glue
305  * lengths, but we don't care, because such lengths are ERT anyway.
306  * \returns true if \p value and \p unit are valid.
307  */
308 bool splitLatexLength(string const & len, string & value, string & unit)
309 {
310         if (len.empty())
311                 return false;
312         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
313         //'4,5' is a valid LaTeX length number. Change it to '4.5'
314         string const length = subst(len, ',', '.');
315         if (i == string::npos)
316                 return false;
317         if (i == 0) {
318                 if (len[0] == '\\') {
319                         // We had something like \textwidth without a factor
320                         value = "1.0";
321                 } else {
322                         return false;
323                 }
324         } else {
325                 value = trimSpaceAndEol(string(length, 0, i));
326         }
327         if (value == "-")
328                 value = "-1.0";
329         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
330         if (contains(len, '\\'))
331                 unit = trimSpaceAndEol(string(len, i));
332         else
333                 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
334         return true;
335 }
336
337
338 /// A simple function to translate a latex length to something LyX can
339 /// understand. Not perfect, but rather best-effort.
340 bool translate_len(string const & length, string & valstring, string & unit)
341 {
342         if (!splitLatexLength(length, valstring, unit))
343                 return false;
344         // LyX uses percent values
345         double value;
346         istringstream iss(valstring);
347         iss >> value;
348         value *= 100;
349         ostringstream oss;
350         oss << value;
351         string const percentval = oss.str();
352         // a normal length
353         if (unit.empty() || unit[0] != '\\')
354                 return true;
355         string::size_type const i = unit.find(' ');
356         string const endlen = (i == string::npos) ? string() : string(unit, i);
357         if (unit == "\\textwidth") {
358                 valstring = percentval;
359                 unit = "text%" + endlen;
360         } else if (unit == "\\columnwidth") {
361                 valstring = percentval;
362                 unit = "col%" + endlen;
363         } else if (unit == "\\paperwidth") {
364                 valstring = percentval;
365                 unit = "page%" + endlen;
366         } else if (unit == "\\linewidth") {
367                 valstring = percentval;
368                 unit = "line%" + endlen;
369         } else if (unit == "\\paperheight") {
370                 valstring = percentval;
371                 unit = "pheight%" + endlen;
372         } else if (unit == "\\textheight") {
373                 valstring = percentval;
374                 unit = "theight%" + endlen;
375         }
376         return true;
377 }
378
379 }
380
381
382 string translate_len(string const & length)
383 {
384         string unit;
385         string value;
386         if (translate_len(length, value, unit))
387                 return value + unit;
388         // If the input is invalid, return what we have.
389         return length;
390 }
391
392
393 namespace {
394
395 /*!
396  * Translates a LaTeX length into \p value, \p unit and
397  * \p special parts suitable for a box inset.
398  * The difference from translate_len() is that a box inset knows about
399  * some special "units" that are stored in \p special.
400  */
401 void translate_box_len(string const & length, string & value, string & unit, string & special)
402 {
403         if (translate_len(length, value, unit)) {
404                 if (unit == "\\height" || unit == "\\depth" ||
405                     unit == "\\totalheight" || unit == "\\width") {
406                         special = unit.substr(1);
407                         // The unit is not used, but LyX requires a dummy setting
408                         unit = "in";
409                 } else
410                         special = "none";
411         } else {
412                 value.clear();
413                 unit = length;
414                 special = "none";
415         }
416 }
417
418
419 /*!
420  * Find a file with basename \p name in path \p path and an extension
421  * in \p extensions.
422  */
423 string find_file(string const & name, string const & path,
424                  char const * const * extensions)
425 {
426         for (char const * const * what = extensions; *what; ++what) {
427                 string const trial = addExtension(name, *what);
428                 if (makeAbsPath(trial, path).exists())
429                         return trial;
430         }
431         return string();
432 }
433
434
435 void begin_inset(ostream & os, string const & name)
436 {
437         os << "\n\\begin_inset " << name;
438 }
439
440
441 void begin_command_inset(ostream & os, string const & name,
442                          string const & latexname)
443 {
444         begin_inset(os, "CommandInset ");
445         os << name << "\nLatexCommand " << latexname << '\n';
446 }
447
448
449 void end_inset(ostream & os)
450 {
451         os << "\n\\end_inset\n\n";
452 }
453
454
455 bool skip_braces(Parser & p)
456 {
457         if (p.next_token().cat() != catBegin)
458                 return false;
459         p.get_token();
460         if (p.next_token().cat() == catEnd) {
461                 p.get_token();
462                 return true;
463         }
464         p.putback();
465         return false;
466 }
467
468
469 /// replace LaTeX commands in \p s from the unicodesymbols file with their
470 /// unicode points
471 docstring convert_unicodesymbols(docstring s)
472 {
473         odocstringstream os;
474         for (size_t i = 0; i < s.size();) {
475                 if (s[i] != '\\') {
476                         os.put(s[i++]);
477                         continue;
478                 }
479                 s = s.substr(i);
480                 bool termination;
481                 docstring rem;
482                 set<string> req;
483                 docstring parsed = encodings.fromLaTeXCommand(s,
484                                 Encodings::TEXT_CMD, termination, rem, &req);
485                 set<string>::const_iterator it = req.begin();
486                 set<string>::const_iterator en = req.end();
487                 for (; it != en; ++it)
488                         preamble.registerAutomaticallyLoadedPackage(*it);
489                 os << parsed;
490                 s = rem;
491                 if (s.empty() || s[0] != '\\')
492                         i = 0;
493                 else
494                         i = 1;
495         }
496         return os.str();
497 }
498
499
500 /// try to convert \p s to a valid InsetCommand argument
501 string convert_command_inset_arg(string s)
502 {
503         if (isAscii(s))
504                 // since we don't know the input encoding we can't use from_utf8
505                 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
506         // LyX cannot handle newlines in a latex command
507         return subst(s, "\n", " ");
508 }
509
510
511 void handle_backslash(ostream & os, string const & s)
512 {
513         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
514                 if (*it == '\\')
515                         os << "\n\\backslash\n";
516                 else
517                         os << *it;
518         }
519 }
520
521
522 void handle_ert(ostream & os, string const & s, Context & context)
523 {
524         // We must have a valid layout before outputting the ERT inset.
525         context.check_layout(os);
526         Context newcontext(true, context.textclass);
527         begin_inset(os, "ERT");
528         os << "\nstatus collapsed\n";
529         newcontext.check_layout(os);
530         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
531                 if (*it == '\\')
532                         os << "\n\\backslash\n";
533                 else if (*it == '\n') {
534                         newcontext.new_paragraph(os);
535                         newcontext.check_layout(os);
536                 } else
537                         os << *it;
538         }
539         newcontext.check_end_layout(os);
540         end_inset(os);
541 }
542
543
544 void handle_comment(ostream & os, string const & s, Context & context)
545 {
546         // TODO: Handle this better
547         Context newcontext(true, context.textclass);
548         begin_inset(os, "ERT");
549         os << "\nstatus collapsed\n";
550         newcontext.check_layout(os);
551         handle_backslash(os, s);
552         // make sure that our comment is the last thing on the line
553         newcontext.new_paragraph(os);
554         newcontext.check_layout(os);
555         newcontext.check_end_layout(os);
556         end_inset(os);
557 }
558
559
560 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
561 {
562         Layout const * layout = findLayoutWithoutModule(textclass, name, command);
563         if (layout)
564                 return layout;
565         if (checkModule(name, command))
566                 return findLayoutWithoutModule(textclass, name, command);
567         return layout;
568 }
569
570
571 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
572 {
573         InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
574         if (insetlayout)
575                 return insetlayout;
576         if (checkModule(name, command))
577                 return findInsetLayoutWithoutModule(textclass, name, command);
578         return insetlayout;
579 }
580
581
582 void eat_whitespace(Parser &, ostream &, Context &, bool);
583
584
585 /*!
586  * Skips whitespace and braces.
587  * This should be called after a command has been parsed that is not put into
588  * ERT, and where LyX adds "{}" if needed.
589  */
590 void skip_spaces_braces(Parser & p, bool keepws = false)
591 {
592         /* The following four examples produce the same typeset output and
593            should be handled by this function:
594            - abc \j{} xyz
595            - abc \j {} xyz
596            - abc \j
597              {} xyz
598            - abc \j %comment
599              {} xyz
600          */
601         // Unfortunately we need to skip comments, too.
602         // We can't use eat_whitespace since writing them after the {}
603         // results in different output in some cases.
604         bool const skipped_spaces = p.skip_spaces(true);
605         bool const skipped_braces = skip_braces(p);
606         if (keepws && skipped_spaces && !skipped_braces)
607                 // put back the space (it is better handled by check_space)
608                 p.unskip_spaces(true);
609 }
610
611
612 void output_command_layout(ostream & os, Parser & p, bool outer,
613                            Context & parent_context,
614                            Layout const * newlayout)
615 {
616         TeXFont const oldFont = parent_context.font;
617         // save the current font size
618         string const size = oldFont.size;
619         // reset the font size to default, because the font size switches
620         // don't affect section headings and the like
621         parent_context.font.size = Context::normalfont.size;
622         // we only need to write the font change if we have an open layout
623         if (!parent_context.atParagraphStart())
624                 output_font_change(os, oldFont, parent_context.font);
625         parent_context.check_end_layout(os);
626         Context context(true, parent_context.textclass, newlayout,
627                         parent_context.layout, parent_context.font);
628         if (parent_context.deeper_paragraph) {
629                 // We are beginning a nested environment after a
630                 // deeper paragraph inside the outer list environment.
631                 // Therefore we don't need to output a "begin deeper".
632                 context.need_end_deeper = true;
633         }
634         context.check_deeper(os);
635         context.check_layout(os);
636         unsigned int optargs = 0;
637         while (optargs < context.layout->optargs) {
638                 eat_whitespace(p, os, context, false);
639                 if (p.next_token().cat() == catEscape ||
640                     p.next_token().character() != '[')
641                         break;
642                 p.get_token(); // eat '['
643                 begin_inset(os, "Argument\n");
644                 os << "status collapsed\n\n";
645                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
646                 end_inset(os);
647                 eat_whitespace(p, os, context, false);
648                 ++optargs;
649         }
650         unsigned int reqargs = 0;
651         while (reqargs < context.layout->reqargs) {
652                 eat_whitespace(p, os, context, false);
653                 if (p.next_token().cat() != catBegin)
654                         break;
655                 p.get_token(); // eat '{'
656                 begin_inset(os, "Argument\n");
657                 os << "status collapsed\n\n";
658                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
659                 end_inset(os);
660                 eat_whitespace(p, os, context, false);
661                 ++reqargs;
662         }
663         parse_text(p, os, FLAG_ITEM, outer, context);
664         context.check_end_layout(os);
665         if (parent_context.deeper_paragraph) {
666                 // We must suppress the "end deeper" because we
667                 // suppressed the "begin deeper" above.
668                 context.need_end_deeper = false;
669         }
670         context.check_end_deeper(os);
671         // We don't need really a new paragraph, but
672         // we must make sure that the next item gets a \begin_layout.
673         parent_context.new_paragraph(os);
674         // Set the font size to the original value. No need to output it here
675         // (Context::begin_layout() will do that if needed)
676         parent_context.font.size = size;
677 }
678
679
680 /*!
681  * Output a space if necessary.
682  * This function gets called for every whitespace token.
683  *
684  * We have three cases here:
685  * 1. A space must be suppressed. Example: The lyxcode case below
686  * 2. A space may be suppressed. Example: Spaces before "\par"
687  * 3. A space must not be suppressed. Example: A space between two words
688  *
689  * We currently handle only 1. and 3 and from 2. only the case of
690  * spaces before newlines as a side effect.
691  *
692  * 2. could be used to suppress as many spaces as possible. This has two effects:
693  * - Reimporting LyX generated LaTeX files changes almost no whitespace
694  * - Superflous whitespace from non LyX generated LaTeX files is removed.
695  * The drawback is that the logic inside the function becomes
696  * complicated, and that is the reason why it is not implemented.
697  */
698 void check_space(Parser & p, ostream & os, Context & context)
699 {
700         Token const next = p.next_token();
701         Token const curr = p.curr_token();
702         // A space before a single newline and vice versa must be ignored
703         // LyX emits a newline before \end{lyxcode}.
704         // This newline must be ignored,
705         // otherwise LyX will add an additional protected space.
706         if (next.cat() == catSpace ||
707             next.cat() == catNewline ||
708             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
709                 return;
710         }
711         context.check_layout(os);
712         os << ' ';
713 }
714
715
716 /*!
717  * Parse all arguments of \p command
718  */
719 void parse_arguments(string const & command,
720                      vector<ArgumentType> const & template_arguments,
721                      Parser & p, ostream & os, bool outer, Context & context)
722 {
723         string ert = command;
724         size_t no_arguments = template_arguments.size();
725         for (size_t i = 0; i < no_arguments; ++i) {
726                 switch (template_arguments[i]) {
727                 case required:
728                 case req_group:
729                         // This argument contains regular LaTeX
730                         handle_ert(os, ert + '{', context);
731                         eat_whitespace(p, os, context, false);
732                         if (template_arguments[i] == required)
733                                 parse_text(p, os, FLAG_ITEM, outer, context);
734                         else
735                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
736                         ert = "}";
737                         break;
738                 case item:
739                         // This argument consists only of a single item.
740                         // The presence of '{' or not must be preserved.
741                         p.skip_spaces();
742                         if (p.next_token().cat() == catBegin)
743                                 ert += '{' + p.verbatim_item() + '}';
744                         else
745                                 ert += p.verbatim_item();
746                         break;
747                 case displaymath:
748                 case verbatim:
749                         // This argument may contain special characters
750                         ert += '{' + p.verbatim_item() + '}';
751                         break;
752                 case optional:
753                 case opt_group:
754                         // true because we must not eat whitespace
755                         // if an optional arg follows we must not strip the
756                         // brackets from this one
757                         if (i < no_arguments - 1 &&
758                             template_arguments[i+1] == optional)
759                                 ert += p.getFullOpt(true);
760                         else
761                                 ert += p.getOpt(true);
762                         break;
763                 }
764         }
765         handle_ert(os, ert, context);
766 }
767
768
769 /*!
770  * Check whether \p command is a known command. If yes,
771  * handle the command with all arguments.
772  * \return true if the command was parsed, false otherwise.
773  */
774 bool parse_command(string const & command, Parser & p, ostream & os,
775                    bool outer, Context & context)
776 {
777         if (known_commands.find(command) != known_commands.end()) {
778                 parse_arguments(command, known_commands[command], p, os,
779                                 outer, context);
780                 return true;
781         }
782         return false;
783 }
784
785
786 /// Parses a minipage or parbox
787 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
788                unsigned inner_flags, bool outer, Context & parent_context,
789                string const & outer_type, string const & special,
790                string const & inner_type)
791 {
792         string position;
793         string inner_pos;
794         string hor_pos = "c";
795         // We need to set the height to the LaTeX default of 1\\totalheight
796         // for the case when no height argument is given
797         string height_value = "1";
798         string height_unit = "in";
799         string height_special = "totalheight";
800         string latex_height;
801         string width_value;
802         string width_unit;
803         string latex_width;
804         string width_special = "none";
805         if (!inner_type.empty() && p.hasOpt()) {
806                 if (inner_type != "makebox")
807                         position = p.getArg('[', ']');
808                 else {
809                         latex_width = p.getArg('[', ']');
810                         translate_box_len(latex_width, width_value, width_unit, width_special);
811                         position = "t";
812                 }
813                 if (position != "t" && position != "c" && position != "b") {
814                         cerr << "invalid position " << position << " for "
815                              << inner_type << endl;
816                         position = "c";
817                 }
818                 if (p.hasOpt()) {
819                         if (inner_type != "makebox") {
820                                 latex_height = p.getArg('[', ']');
821                                 translate_box_len(latex_height, height_value, height_unit, height_special);
822                         } else
823                                 hor_pos = p.getArg('[', ']');
824
825                         if (p.hasOpt()) {
826                                 inner_pos = p.getArg('[', ']');
827                                 if (inner_pos != "c" && inner_pos != "t" &&
828                                     inner_pos != "b" && inner_pos != "s") {
829                                         cerr << "invalid inner_pos "
830                                              << inner_pos << " for "
831                                              << inner_type << endl;
832                                         inner_pos = position;
833                                 }
834                         }
835                 }
836         }
837         if (inner_type.empty()) {
838                 if (special.empty() && outer_type != "framebox")
839                         latex_width = "1\\columnwidth";
840                 else {
841                         Parser p2(special);
842                         latex_width = p2.getArg('[', ']');
843                         string const opt = p2.getArg('[', ']');
844                         if (!opt.empty()) {
845                                 hor_pos = opt;
846                                 if (hor_pos != "l" && hor_pos != "c" &&
847                                     hor_pos != "r") {
848                                         cerr << "invalid hor_pos " << hor_pos
849                                              << " for " << outer_type << endl;
850                                         hor_pos = "c";
851                                 }
852                         }
853                 }
854         } else if (inner_type != "makebox")
855                 latex_width = p.verbatim_item();
856         // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
857         // as this is LyX's standard for such cases (except for makebox)
858         // \framebox is more special and handled below
859         if (latex_width.empty() && inner_type != "makebox"
860                 && outer_type != "framebox")
861                 latex_width = "1\\columnwidth";
862
863         translate_len(latex_width, width_value, width_unit);
864
865         bool shadedparbox = false;
866         if (inner_type == "shaded") {
867                 eat_whitespace(p, os, parent_context, false);
868                 if (outer_type == "parbox") {
869                         // Eat '{'
870                         if (p.next_token().cat() == catBegin)
871                                 p.get_token();
872                         eat_whitespace(p, os, parent_context, false);
873                         shadedparbox = true;
874                 }
875                 p.get_token();
876                 p.getArg('{', '}');
877         }
878         // If we already read the inner box we have to push the inner env
879         if (!outer_type.empty() && !inner_type.empty() &&
880             (inner_flags & FLAG_END))
881                 active_environments.push_back(inner_type);
882         // LyX can't handle length variables
883         bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
884         if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
885                 // Look whether there is some content after the end of the
886                 // inner box, but before the end of the outer box.
887                 // If yes, we need to output ERT.
888                 p.pushPosition();
889                 if (inner_flags & FLAG_END)
890                         p.verbatimEnvironment(inner_type);
891                 else
892                         p.verbatim_item();
893                 p.skip_spaces(true);
894                 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
895                 if ((outer_env && p.next_token().asInput() != "\\end") ||
896                     (!outer_env && p.next_token().cat() != catEnd)) {
897                         // something is between the end of the inner box and
898                         // the end of the outer box, so we need to use ERT.
899                         use_ert = true;
900                 }
901                 p.popPosition();
902         }
903         // if only \makebox{content} was used we can set its width to 1\width
904         // because this identic and also identic to \mbox
905         // this doesn't work for \framebox{content}, thus we have to use ERT for this
906         if (latex_width.empty() && inner_type == "makebox") {
907                 width_value = "1";
908                 width_unit = "in";
909                 width_special = "width";
910         } else if (latex_width.empty() && outer_type == "framebox") {
911                 use_ert = true;
912         }
913         if (use_ert) {
914                 ostringstream ss;
915                 if (!outer_type.empty()) {
916                         if (outer_flags & FLAG_END)
917                                 ss << "\\begin{" << outer_type << '}';
918                         else {
919                                 ss << '\\' << outer_type << '{';
920                                 if (!special.empty())
921                                         ss << special;
922                         }
923                 }
924                 if (!inner_type.empty()) {
925                         if (inner_type != "shaded") {
926                                 if (inner_flags & FLAG_END)
927                                         ss << "\\begin{" << inner_type << '}';
928                                 else
929                                         ss << '\\' << inner_type;
930                         }
931                         if (!position.empty())
932                                 ss << '[' << position << ']';
933                         if (!latex_height.empty())
934                                 ss << '[' << latex_height << ']';
935                         if (!inner_pos.empty())
936                                 ss << '[' << inner_pos << ']';
937                         ss << '{' << latex_width << '}';
938                         if (!(inner_flags & FLAG_END))
939                                 ss << '{';
940                 }
941                 if (inner_type == "shaded")
942                         ss << "\\begin{shaded}";
943                 handle_ert(os, ss.str(), parent_context);
944                 if (!inner_type.empty()) {
945                         parse_text(p, os, inner_flags, outer, parent_context);
946                         if (inner_flags & FLAG_END)
947                                 handle_ert(os, "\\end{" + inner_type + '}',
948                                            parent_context);
949                         else
950                                 handle_ert(os, "}", parent_context);
951                 }
952                 if (!outer_type.empty()) {
953                         // If we already read the inner box we have to pop
954                         // the inner env
955                         if (!inner_type.empty() && (inner_flags & FLAG_END))
956                                 active_environments.pop_back();
957
958                         // Ensure that the end of the outer box is parsed correctly:
959                         // The opening brace has been eaten by parse_outer_box()
960                         if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
961                                 outer_flags &= ~FLAG_ITEM;
962                                 outer_flags |= FLAG_BRACE_LAST;
963                         }
964                         parse_text(p, os, outer_flags, outer, parent_context);
965                         if (outer_flags & FLAG_END)
966                                 handle_ert(os, "\\end{" + outer_type + '}',
967                                            parent_context);
968                         else if (inner_type.empty() && outer_type == "framebox")
969                                 // in this case it is already closed later
970                                 ;
971                         else
972                                 handle_ert(os, "}", parent_context);
973                 }
974         } else {
975                 // LyX does not like empty positions, so we have
976                 // to set them to the LaTeX default values here.
977                 if (position.empty())
978                         position = "c";
979                 if (inner_pos.empty())
980                         inner_pos = position;
981                 parent_context.check_layout(os);
982                 begin_inset(os, "Box ");
983                 if (outer_type == "framed")
984                         os << "Framed\n";
985                 else if (outer_type == "framebox")
986                         os << "Boxed\n";
987                 else if (outer_type == "shadowbox")
988                         os << "Shadowbox\n";
989                 else if ((outer_type == "shaded" && inner_type.empty()) ||
990                              (outer_type == "minipage" && inner_type == "shaded") ||
991                              (outer_type == "parbox" && inner_type == "shaded")) {
992                         os << "Shaded\n";
993                         preamble.registerAutomaticallyLoadedPackage("color");
994                 } else if (outer_type == "doublebox")
995                         os << "Doublebox\n";
996                 else if (outer_type.empty())
997                         os << "Frameless\n";
998                 else
999                         os << outer_type << '\n';
1000                 os << "position \"" << position << "\"\n";
1001                 os << "hor_pos \"" << hor_pos << "\"\n";
1002                 os << "has_inner_box " << !inner_type.empty() << "\n";
1003                 os << "inner_pos \"" << inner_pos << "\"\n";
1004                 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1005                    << '\n';
1006                 os << "use_makebox " << (inner_type == "makebox") << '\n';
1007                 os << "width \"" << width_value << width_unit << "\"\n";
1008                 os << "special \"" << width_special << "\"\n";
1009                 os << "height \"" << height_value << height_unit << "\"\n";
1010                 os << "height_special \"" << height_special << "\"\n";
1011                 os << "status open\n\n";
1012
1013                 // Unfortunately we can't use parse_text_in_inset:
1014                 // InsetBox::forcePlainLayout() is hard coded and does not
1015                 // use the inset layout. Apart from that do we call parse_text
1016                 // up to two times, but need only one check_end_layout.
1017                 bool const forcePlainLayout =
1018                         (!inner_type.empty() || inner_type == "makebox") &&
1019                         outer_type != "shaded" && outer_type != "framed";
1020                 Context context(true, parent_context.textclass);
1021                 if (forcePlainLayout)
1022                         context.layout = &context.textclass.plainLayout();
1023                 else
1024                         context.font = parent_context.font;
1025
1026                 // If we have no inner box the contents will be read with the outer box
1027                 if (!inner_type.empty())
1028                         parse_text(p, os, inner_flags, outer, context);
1029
1030                 // Ensure that the end of the outer box is parsed correctly:
1031                 // The opening brace has been eaten by parse_outer_box()
1032                 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1033                         outer_flags &= ~FLAG_ITEM;
1034                         outer_flags |= FLAG_BRACE_LAST;
1035                 }
1036
1037                 // Find end of outer box, output contents if inner_type is
1038                 // empty and output possible comments
1039                 if (!outer_type.empty()) {
1040                         // If we already read the inner box we have to pop
1041                         // the inner env
1042                         if (!inner_type.empty() && (inner_flags & FLAG_END))
1043                                 active_environments.pop_back();
1044                         // This does not output anything but comments if
1045                         // inner_type is not empty (see use_ert)
1046                         parse_text(p, os, outer_flags, outer, context);
1047                 }
1048
1049                 context.check_end_layout(os);
1050                 end_inset(os);
1051 #ifdef PRESERVE_LAYOUT
1052                 // LyX puts a % after the end of the minipage
1053                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1054                         // new paragraph
1055                         //handle_comment(os, "%dummy", parent_context);
1056                         p.get_token();
1057                         p.skip_spaces();
1058                         parent_context.new_paragraph(os);
1059                 }
1060                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1061                         //handle_comment(os, "%dummy", parent_context);
1062                         p.get_token();
1063                         p.skip_spaces();
1064                         // We add a protected space if something real follows
1065                         if (p.good() && p.next_token().cat() != catComment) {
1066                                 begin_inset(os, "space ~\n");
1067                                 end_inset(os);
1068                         }
1069                 }
1070 #endif
1071         }
1072 }
1073
1074
1075 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1076                      Context & parent_context, string const & outer_type,
1077                      string const & special)
1078 {
1079         eat_whitespace(p, os, parent_context, false);
1080         if (flags & FLAG_ITEM) {
1081                 // Eat '{'
1082                 if (p.next_token().cat() == catBegin)
1083                         p.get_token();
1084                 else
1085                         cerr << "Warning: Ignoring missing '{' after \\"
1086                              << outer_type << '.' << endl;
1087                 eat_whitespace(p, os, parent_context, false);
1088         }
1089         string inner;
1090         unsigned int inner_flags = 0;
1091         p.pushPosition();
1092         if (outer_type == "minipage" || outer_type == "parbox") {
1093                 p.skip_spaces(true);
1094                 while (p.hasOpt()) {
1095                         p.getArg('[', ']');
1096                         p.skip_spaces(true);
1097                 }
1098                 p.getArg('{', '}');
1099                 p.skip_spaces(true);
1100                 if (outer_type == "parbox") {
1101                         // Eat '{'
1102                         if (p.next_token().cat() == catBegin)
1103                                 p.get_token();
1104                         p.skip_spaces(true);
1105                 }
1106         }
1107         if (outer_type == "shaded") {
1108                 // These boxes never have an inner box
1109                 ;
1110         } else if (p.next_token().asInput() == "\\parbox") {
1111                 inner = p.get_token().cs();
1112                 inner_flags = FLAG_ITEM;
1113         } else if (p.next_token().asInput() == "\\begin") {
1114                 // Is this a minipage or shaded box?
1115                 p.pushPosition();
1116                 p.get_token();
1117                 inner = p.getArg('{', '}');
1118                 p.popPosition();
1119                 if (inner == "minipage" || inner == "shaded")
1120                         inner_flags = FLAG_END;
1121                 else
1122                         inner = "";
1123         }
1124         p.popPosition();
1125         if (inner_flags == FLAG_END) {
1126                 if (inner != "shaded")
1127                 {
1128                         p.get_token();
1129                         p.getArg('{', '}');
1130                         eat_whitespace(p, os, parent_context, false);
1131                 }
1132                 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1133                           outer_type, special, inner);
1134         } else {
1135                 if (inner_flags == FLAG_ITEM) {
1136                         p.get_token();
1137                         eat_whitespace(p, os, parent_context, false);
1138                 }
1139                 parse_box(p, os, flags, inner_flags, outer, parent_context,
1140                           outer_type, special, inner);
1141         }
1142 }
1143
1144
1145 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1146 {
1147         parent_context.check_layout(os);
1148         begin_inset(os, "listings\n");
1149         if (p.hasOpt()) {
1150                 string arg = p.verbatimOption();
1151                 os << "lstparams " << '"' << arg << '"' << '\n';
1152         }
1153         if (in_line)
1154                 os << "inline true\n";
1155         else
1156                 os << "inline false\n";
1157         os << "status collapsed\n";
1158         Context context(true, parent_context.textclass);
1159         context.layout = &parent_context.textclass.plainLayout();
1160         string s;
1161         if (in_line) {
1162                 s = p.plainCommand('!', '!', "lstinline");
1163                 context.new_paragraph(os);
1164                 context.check_layout(os);
1165         } else
1166                 s = p.plainEnvironment("lstlisting");
1167         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1168                 if (*it == '\\')
1169                         os << "\n\\backslash\n";
1170                 else if (*it == '\n') {
1171                         // avoid adding an empty paragraph at the end
1172                         if (it + 1 != et) {
1173                                 context.new_paragraph(os);
1174                                 context.check_layout(os);
1175                         }
1176                 } else
1177                         os << *it;
1178         }
1179         context.check_end_layout(os);
1180         end_inset(os);
1181 }
1182
1183
1184 /// parse an unknown environment
1185 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1186                                unsigned flags, bool outer,
1187                                Context & parent_context)
1188 {
1189         if (name == "tabbing")
1190                 // We need to remember that we have to handle '\=' specially
1191                 flags |= FLAG_TABBING;
1192
1193         // We need to translate font changes and paragraphs inside the
1194         // environment to ERT if we have a non standard font.
1195         // Otherwise things like
1196         // \large\begin{foo}\huge bar\end{foo}
1197         // will not work.
1198         bool const specialfont =
1199                 (parent_context.font != parent_context.normalfont);
1200         bool const new_layout_allowed = parent_context.new_layout_allowed;
1201         if (specialfont)
1202                 parent_context.new_layout_allowed = false;
1203         handle_ert(os, "\\begin{" + name + "}", parent_context);
1204         parse_text_snippet(p, os, flags, outer, parent_context);
1205         handle_ert(os, "\\end{" + name + "}", parent_context);
1206         if (specialfont)
1207                 parent_context.new_layout_allowed = new_layout_allowed;
1208 }
1209
1210
1211 void parse_environment(Parser & p, ostream & os, bool outer,
1212                        string & last_env, Context & parent_context)
1213 {
1214         Layout const * newlayout;
1215         InsetLayout const * newinsetlayout = 0;
1216         string const name = p.getArg('{', '}');
1217         const bool is_starred = suffixIs(name, '*');
1218         string const unstarred_name = rtrim(name, "*");
1219         active_environments.push_back(name);
1220
1221         if (is_math_env(name)) {
1222                 parent_context.check_layout(os);
1223                 begin_inset(os, "Formula ");
1224                 os << "\\begin{" << name << "}";
1225                 parse_math(p, os, FLAG_END, MATH_MODE);
1226                 os << "\\end{" << name << "}";
1227                 end_inset(os);
1228                 if (is_display_math_env(name)) {
1229                         // Prevent the conversion of a line break to a space
1230                         // (bug 7668). This does not change the output, but
1231                         // looks ugly in LyX.
1232                         eat_whitespace(p, os, parent_context, false);
1233                 }
1234         }
1235
1236         else if (is_known(name, preamble.polyglossia_languages)) {
1237                 // We must begin a new paragraph if not already done
1238                 if (! parent_context.atParagraphStart()) {
1239                         parent_context.check_end_layout(os);
1240                         parent_context.new_paragraph(os);
1241                 }
1242                 // save the language in the context so that it is
1243                 // handled by parse_text
1244                 parent_context.font.language = preamble.polyglossia2lyx(name);
1245                 parse_text(p, os, FLAG_END, outer, parent_context);
1246                 // Just in case the environment is empty
1247                 parent_context.extra_stuff.erase();
1248                 // We must begin a new paragraph to reset the language
1249                 parent_context.new_paragraph(os);
1250                 p.skip_spaces();
1251         }
1252
1253         else if (unstarred_name == "tabular" || name == "longtable") {
1254                 eat_whitespace(p, os, parent_context, false);
1255                 string width = "0pt";
1256                 if (name == "tabular*") {
1257                         width = lyx::translate_len(p.getArg('{', '}'));
1258                         eat_whitespace(p, os, parent_context, false);
1259                 }
1260                 parent_context.check_layout(os);
1261                 begin_inset(os, "Tabular ");
1262                 handle_tabular(p, os, name, width, parent_context);
1263                 end_inset(os);
1264                 p.skip_spaces();
1265         }
1266
1267         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1268                 eat_whitespace(p, os, parent_context, false);
1269                 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1270                 eat_whitespace(p, os, parent_context, false);
1271                 parent_context.check_layout(os);
1272                 begin_inset(os, "Float " + unstarred_name + "\n");
1273                 // store the float type for subfloats
1274                 // subfloats only work with figures and tables
1275                 if (unstarred_name == "figure")
1276                         float_type = unstarred_name;
1277                 else if (unstarred_name == "table")
1278                         float_type = unstarred_name;
1279                 else
1280                         float_type = "";
1281                 if (!opt.empty())
1282                         os << "placement " << opt << '\n';
1283                 if (contains(opt, "H"))
1284                         preamble.registerAutomaticallyLoadedPackage("float");
1285                 else {
1286                         Floating const & fl = parent_context.textclass.floats()
1287                                 .getType(unstarred_name);
1288                         if (!fl.floattype().empty() && fl.usesFloatPkg())
1289                                 preamble.registerAutomaticallyLoadedPackage("float");
1290                 }
1291
1292                 os << "wide " << convert<string>(is_starred)
1293                    << "\nsideways false"
1294                    << "\nstatus open\n\n";
1295                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1296                 end_inset(os);
1297                 // We don't need really a new paragraph, but
1298                 // we must make sure that the next item gets a \begin_layout.
1299                 parent_context.new_paragraph(os);
1300                 p.skip_spaces();
1301                 // the float is parsed thus delete the type
1302                 float_type = "";
1303         }
1304
1305         else if (unstarred_name == "sidewaysfigure"
1306                 || unstarred_name == "sidewaystable") {
1307                 eat_whitespace(p, os, parent_context, false);
1308                 parent_context.check_layout(os);
1309                 if (unstarred_name == "sidewaysfigure")
1310                         begin_inset(os, "Float figure\n");
1311                 else
1312                         begin_inset(os, "Float table\n");
1313                 os << "wide " << convert<string>(is_starred)
1314                    << "\nsideways true"
1315                    << "\nstatus open\n\n";
1316                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1317                 end_inset(os);
1318                 // We don't need really a new paragraph, but
1319                 // we must make sure that the next item gets a \begin_layout.
1320                 parent_context.new_paragraph(os);
1321                 p.skip_spaces();
1322                 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1323         }
1324
1325         else if (name == "wrapfigure" || name == "wraptable") {
1326                 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1327                 eat_whitespace(p, os, parent_context, false);
1328                 parent_context.check_layout(os);
1329                 // default values
1330                 string lines = "0";
1331                 string overhang = "0col%";
1332                 // parse
1333                 if (p.hasOpt())
1334                         lines = p.getArg('[', ']');
1335                 string const placement = p.getArg('{', '}');
1336                 if (p.hasOpt())
1337                         overhang = p.getArg('[', ']');
1338                 string const width = p.getArg('{', '}');
1339                 // write
1340                 if (name == "wrapfigure")
1341                         begin_inset(os, "Wrap figure\n");
1342                 else
1343                         begin_inset(os, "Wrap table\n");
1344                 os << "lines " << lines
1345                    << "\nplacement " << placement
1346                    << "\noverhang " << lyx::translate_len(overhang)
1347                    << "\nwidth " << lyx::translate_len(width)
1348                    << "\nstatus open\n\n";
1349                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1350                 end_inset(os);
1351                 // We don't need really a new paragraph, but
1352                 // we must make sure that the next item gets a \begin_layout.
1353                 parent_context.new_paragraph(os);
1354                 p.skip_spaces();
1355                 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1356         }
1357
1358         else if (name == "minipage") {
1359                 eat_whitespace(p, os, parent_context, false);
1360                 // Test whether this is an outer box of a shaded box
1361                 p.pushPosition();
1362                 // swallow arguments
1363                 while (p.hasOpt()) {
1364                         p.getArg('[', ']');
1365                         p.skip_spaces(true);
1366                 }
1367                 p.getArg('{', '}');
1368                 p.skip_spaces(true);
1369                 Token t = p.get_token();
1370                 bool shaded = false;
1371                 if (t.asInput() == "\\begin") {
1372                         p.skip_spaces(true);
1373                         if (p.getArg('{', '}') == "shaded")
1374                                 shaded = true;
1375                 }
1376                 p.popPosition();
1377                 if (shaded)
1378                         parse_outer_box(p, os, FLAG_END, outer,
1379                                         parent_context, name, "shaded");
1380                 else
1381                         parse_box(p, os, 0, FLAG_END, outer, parent_context,
1382                                   "", "", name);
1383                 p.skip_spaces();
1384         }
1385
1386         else if (name == "comment") {
1387                 eat_whitespace(p, os, parent_context, false);
1388                 parent_context.check_layout(os);
1389                 begin_inset(os, "Note Comment\n");
1390                 os << "status open\n";
1391                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1392                 end_inset(os);
1393                 p.skip_spaces();
1394                 skip_braces(p); // eat {} that might by set by LyX behind comments
1395                 preamble.registerAutomaticallyLoadedPackage("verbatim");
1396         }
1397
1398         else if (name == "verbatim") {
1399                 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1400                 string const s = p.plainEnvironment("verbatim");
1401                 string::const_iterator it2 = s.begin();
1402                 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1403                         if (*it == '\\')
1404                                 os << "\\backslash ";
1405                         else if (*it == '\n') {
1406                                 it2 = it + 1;
1407                                 // avoid adding an empty paragraph at the end
1408                                 // FIXME: if there are 2 consecutive spaces at the end ignore it
1409                                 // because LyX will re-add a \n
1410                                 // This hack must be removed once bug 8049 is fixed!
1411                                 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1412                                         os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1413                         } else 
1414                                 os << *it;
1415                 }
1416                 os << "\n\\end_layout\n\n";
1417                 p.skip_spaces();
1418                 // reset to Standard layout
1419                 os << "\n\\begin_layout Standard\n";
1420         }
1421
1422         else if (name == "CJK") {
1423                 // the scheme is \begin{CJK}{encoding}{mapping}{text}
1424                 // It is impossible to decide if a CJK environment was in its own paragraph or within
1425                 // a line. We therefore always assume a paragraph since the latter is a rare case.
1426                 eat_whitespace(p, os, parent_context, false);
1427                 parent_context.check_end_layout(os);
1428                 // store the encoding to be able to reset it
1429                 string const encoding_old = p.getEncoding();
1430                 string const encoding = p.getArg('{', '}');
1431                 // SJIS and BIG5 don't work with LaTeX according to the comment in unicode.cpp
1432                 // JIS does not work with LyX's encoding conversion
1433                 if (encoding != "SJIS" && encoding != "BIG5" && encoding != "JIS")
1434                         p.setEncoding(encoding);
1435                 else
1436                         p.setEncoding("utf8");
1437                 // LyX doesn't support the second argument so if
1438                 // this is used we need to output everything as ERT
1439                 string const mapping = p.getArg('{', '}');
1440                 if ((!mapping.empty() && mapping != " ")
1441                         || (!is_known(encoding, supported_CJK_encodings))) {
1442                         parent_context.check_layout(os);
1443                         handle_ert(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1444                                        parent_context);
1445                         // we must parse the content as verbatim because e.g. SJIS can contain
1446                         // normally invalid characters
1447                         string const s = p.plainEnvironment("CJK");
1448                         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1449                                 if (*it == '\\')
1450                                         handle_ert(os, "\\", parent_context);
1451                                 else if (*it == '$')
1452                                         handle_ert(os, "$", parent_context);
1453                                 else 
1454                                         os << *it;
1455                         }
1456                         p.skip_spaces();
1457                         handle_ert(os, "\\end{" + name + "}",
1458                                        parent_context);
1459                 } else {
1460                         string const lang = CJK2lyx(encoding);
1461                         // store the language because we must reset it at the end
1462                         string const lang_old = parent_context.font.language;
1463                         parent_context.font.language = lang;
1464                         parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1465                         parent_context.font.language = lang_old;
1466                         parent_context.new_paragraph(os);
1467                 }
1468                 p.setEncoding(encoding_old);
1469                 p.skip_spaces();
1470         }
1471
1472         else if (name == "lyxgreyedout") {
1473                 eat_whitespace(p, os, parent_context, false);
1474                 parent_context.check_layout(os);
1475                 begin_inset(os, "Note Greyedout\n");
1476                 os << "status open\n";
1477                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1478                 end_inset(os);
1479                 p.skip_spaces();
1480                 if (!preamble.notefontcolor().empty())
1481                         preamble.registerAutomaticallyLoadedPackage("color");
1482         }
1483
1484         else if (name == "framed" || name == "shaded") {
1485                 eat_whitespace(p, os, parent_context, false);
1486                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1487                 p.skip_spaces();
1488         }
1489
1490         else if (name == "lstlisting") {
1491                 eat_whitespace(p, os, parent_context, false);
1492                 // FIXME handle the automatic color package loading
1493                 // uwestoehr asks: In what case color is loaded?
1494                 parse_listings(p, os, parent_context, false);
1495                 p.skip_spaces();
1496         }
1497
1498         else if (!parent_context.new_layout_allowed)
1499                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1500                                           parent_context);
1501
1502         // Alignment and spacing settings
1503         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1504         //                                       therefore are totally broken!
1505         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1506         // they are commands not environments. They are furthermore switches that
1507         // can be ended by another switches, but also by commands like \footnote or
1508         // \parbox. So the only safe way is to leave them untouched.
1509         else if (name == "center" || name == "centering" ||
1510                  name == "flushleft" || name == "flushright" ||
1511                  name == "singlespace" || name == "onehalfspace" ||
1512                  name == "doublespace" || name == "spacing") {
1513                 eat_whitespace(p, os, parent_context, false);
1514                 // We must begin a new paragraph if not already done
1515                 if (! parent_context.atParagraphStart()) {
1516                         parent_context.check_end_layout(os);
1517                         parent_context.new_paragraph(os);
1518                 }
1519                 if (name == "flushleft")
1520                         parent_context.add_extra_stuff("\\align left\n");
1521                 else if (name == "flushright")
1522                         parent_context.add_extra_stuff("\\align right\n");
1523                 else if (name == "center" || name == "centering")
1524                         parent_context.add_extra_stuff("\\align center\n");
1525                 else if (name == "singlespace")
1526                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1527                 else if (name == "onehalfspace") {
1528                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1529                         preamble.registerAutomaticallyLoadedPackage("setspace");
1530                 } else if (name == "doublespace") {
1531                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1532                         preamble.registerAutomaticallyLoadedPackage("setspace");
1533                 } else if (name == "spacing") {
1534                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1535                         preamble.registerAutomaticallyLoadedPackage("setspace");
1536                 }
1537                 parse_text(p, os, FLAG_END, outer, parent_context);
1538                 // Just in case the environment is empty
1539                 parent_context.extra_stuff.erase();
1540                 // We must begin a new paragraph to reset the alignment
1541                 parent_context.new_paragraph(os);
1542                 p.skip_spaces();
1543         }
1544
1545         // The single '=' is meant here.
1546         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1547                 eat_whitespace(p, os, parent_context, false);
1548                 Context context(true, parent_context.textclass, newlayout,
1549                                 parent_context.layout, parent_context.font);
1550                 if (parent_context.deeper_paragraph) {
1551                         // We are beginning a nested environment after a
1552                         // deeper paragraph inside the outer list environment.
1553                         // Therefore we don't need to output a "begin deeper".
1554                         context.need_end_deeper = true;
1555                 }
1556                 parent_context.check_end_layout(os);
1557                 if (last_env == name) {
1558                         // we need to output a separator since LyX would export
1559                         // the two environments as one otherwise (bug 5716)
1560                         docstring const sep = from_ascii("--Separator--");
1561                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1562                         if (textclass.hasLayout(sep)) {
1563                                 Context newcontext(parent_context);
1564                                 newcontext.layout = &(textclass[sep]);
1565                                 newcontext.check_layout(os);
1566                                 newcontext.check_end_layout(os);
1567                         } else {
1568                                 parent_context.check_layout(os);
1569                                 begin_inset(os, "Note Note\n");
1570                                 os << "status closed\n";
1571                                 Context newcontext(true, textclass,
1572                                                 &(textclass.defaultLayout()));
1573                                 newcontext.check_layout(os);
1574                                 newcontext.check_end_layout(os);
1575                                 end_inset(os);
1576                                 parent_context.check_end_layout(os);
1577                         }
1578                 }
1579                 switch (context.layout->latextype) {
1580                 case  LATEX_LIST_ENVIRONMENT:
1581                         context.add_par_extra_stuff("\\labelwidthstring "
1582                                                     + p.verbatim_item() + '\n');
1583                         p.skip_spaces();
1584                         break;
1585                 case  LATEX_BIB_ENVIRONMENT:
1586                         p.verbatim_item(); // swallow next arg
1587                         p.skip_spaces();
1588                         break;
1589                 default:
1590                         break;
1591                 }
1592                 context.check_deeper(os);
1593                 // handle known optional and required arguments
1594                 // layouts require all optional arguments before the required ones
1595                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1596                 // It is impossible to place anything after the environment name,
1597                 // but before the first \\item.
1598                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1599                         bool need_layout = true;
1600                         unsigned int optargs = 0;
1601                         while (optargs < context.layout->optargs) {
1602                                 eat_whitespace(p, os, context, false);
1603                                 if (p.next_token().cat() == catEscape ||
1604                                     p.next_token().character() != '[')
1605                                         break;
1606                                 p.get_token(); // eat '['
1607                                 if (need_layout) {
1608                                         context.check_layout(os);
1609                                         need_layout = false;
1610                                 }
1611                                 begin_inset(os, "Argument\n");
1612                                 os << "status collapsed\n\n";
1613                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1614                                 end_inset(os);
1615                                 eat_whitespace(p, os, context, false);
1616                                 ++optargs;
1617                         }
1618                         unsigned int reqargs = 0;
1619                         while (reqargs < context.layout->reqargs) {
1620                                 eat_whitespace(p, os, context, false);
1621                                 if (p.next_token().cat() != catBegin)
1622                                         break;
1623                                 p.get_token(); // eat '{'
1624                                 if (need_layout) {
1625                                         context.check_layout(os);
1626                                         need_layout = false;
1627                                 }
1628                                 begin_inset(os, "Argument\n");
1629                                 os << "status collapsed\n\n";
1630                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1631                                 end_inset(os);
1632                                 eat_whitespace(p, os, context, false);
1633                                 ++reqargs;
1634                         }
1635                 }
1636                 parse_text(p, os, FLAG_END, outer, context);
1637                 context.check_end_layout(os);
1638                 if (parent_context.deeper_paragraph) {
1639                         // We must suppress the "end deeper" because we
1640                         // suppressed the "begin deeper" above.
1641                         context.need_end_deeper = false;
1642                 }
1643                 context.check_end_deeper(os);
1644                 parent_context.new_paragraph(os);
1645                 p.skip_spaces();
1646                 if (!preamble.titleLayoutFound())
1647                         preamble.titleLayoutFound(newlayout->intitle);
1648                 set<string> const & req = newlayout->requires();
1649                 set<string>::const_iterator it = req.begin();
1650                 set<string>::const_iterator en = req.end();
1651                 for (; it != en; ++it)
1652                         preamble.registerAutomaticallyLoadedPackage(*it);
1653         }
1654
1655         // The single '=' is meant here.
1656         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1657                 eat_whitespace(p, os, parent_context, false);
1658                 parent_context.check_layout(os);
1659                 begin_inset(os, "Flex ");
1660                 os << to_utf8(newinsetlayout->name()) << '\n'
1661                    << "status collapsed\n";
1662                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1663                 end_inset(os);
1664         }
1665
1666         else if (name == "appendix") {
1667                 // This is no good latex style, but it works and is used in some documents...
1668                 eat_whitespace(p, os, parent_context, false);
1669                 parent_context.check_end_layout(os);
1670                 Context context(true, parent_context.textclass, parent_context.layout,
1671                                 parent_context.layout, parent_context.font);
1672                 context.check_layout(os);
1673                 os << "\\start_of_appendix\n";
1674                 parse_text(p, os, FLAG_END, outer, context);
1675                 context.check_end_layout(os);
1676                 p.skip_spaces();
1677         }
1678
1679         else if (known_environments.find(name) != known_environments.end()) {
1680                 vector<ArgumentType> arguments = known_environments[name];
1681                 // The last "argument" denotes wether we may translate the
1682                 // environment contents to LyX
1683                 // The default required if no argument is given makes us
1684                 // compatible with the reLyXre environment.
1685                 ArgumentType contents = arguments.empty() ?
1686                         required :
1687                         arguments.back();
1688                 if (!arguments.empty())
1689                         arguments.pop_back();
1690                 // See comment in parse_unknown_environment()
1691                 bool const specialfont =
1692                         (parent_context.font != parent_context.normalfont);
1693                 bool const new_layout_allowed =
1694                         parent_context.new_layout_allowed;
1695                 if (specialfont)
1696                         parent_context.new_layout_allowed = false;
1697                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1698                                 outer, parent_context);
1699                 if (contents == verbatim)
1700                         handle_ert(os, p.verbatimEnvironment(name),
1701                                    parent_context);
1702                 else
1703                         parse_text_snippet(p, os, FLAG_END, outer,
1704                                            parent_context);
1705                 handle_ert(os, "\\end{" + name + "}", parent_context);
1706                 if (specialfont)
1707                         parent_context.new_layout_allowed = new_layout_allowed;
1708         }
1709
1710         else
1711                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1712                                           parent_context);
1713
1714         last_env = name;
1715         active_environments.pop_back();
1716 }
1717
1718
1719 /// parses a comment and outputs it to \p os.
1720 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1721 {
1722         LASSERT(t.cat() == catComment, return);
1723         if (!t.cs().empty()) {
1724                 context.check_layout(os);
1725                 handle_comment(os, '%' + t.cs(), context);
1726                 if (p.next_token().cat() == catNewline) {
1727                         // A newline after a comment line starts a new
1728                         // paragraph
1729                         if (context.new_layout_allowed) {
1730                                 if(!context.atParagraphStart())
1731                                         // Only start a new paragraph if not already
1732                                         // done (we might get called recursively)
1733                                         context.new_paragraph(os);
1734                         } else
1735                                 handle_ert(os, "\n", context);
1736                         eat_whitespace(p, os, context, true);
1737                 }
1738         } else {
1739                 // "%\n" combination
1740                 p.skip_spaces();
1741         }
1742 }
1743
1744
1745 /*!
1746  * Reads spaces and comments until the first non-space, non-comment token.
1747  * New paragraphs (double newlines or \\par) are handled like simple spaces
1748  * if \p eatParagraph is true.
1749  * Spaces are skipped, but comments are written to \p os.
1750  */
1751 void eat_whitespace(Parser & p, ostream & os, Context & context,
1752                     bool eatParagraph)
1753 {
1754         while (p.good()) {
1755                 Token const & t = p.get_token();
1756                 if (t.cat() == catComment)
1757                         parse_comment(p, os, t, context);
1758                 else if ((! eatParagraph && p.isParagraph()) ||
1759                          (t.cat() != catSpace && t.cat() != catNewline)) {
1760                         p.putback();
1761                         return;
1762                 }
1763         }
1764 }
1765
1766
1767 /*!
1768  * Set a font attribute, parse text and reset the font attribute.
1769  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1770  * \param currentvalue Current value of the attribute. Is set to the new
1771  * value during parsing.
1772  * \param newvalue New value of the attribute
1773  */
1774 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1775                            Context & context, string const & attribute,
1776                            string & currentvalue, string const & newvalue)
1777 {
1778         context.check_layout(os);
1779         string const oldvalue = currentvalue;
1780         currentvalue = newvalue;
1781         os << '\n' << attribute << ' ' << newvalue << "\n";
1782         parse_text_snippet(p, os, flags, outer, context);
1783         context.check_layout(os);
1784         os << '\n' << attribute << ' ' << oldvalue << "\n";
1785         currentvalue = oldvalue;
1786 }
1787
1788
1789 /// get the arguments of a natbib or jurabib citation command
1790 void get_cite_arguments(Parser & p, bool natbibOrder,
1791         string & before, string & after)
1792 {
1793         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1794
1795         // text before the citation
1796         before.clear();
1797         // text after the citation
1798         after = p.getFullOpt();
1799
1800         if (!after.empty()) {
1801                 before = p.getFullOpt();
1802                 if (natbibOrder && !before.empty())
1803                         swap(before, after);
1804         }
1805 }
1806
1807
1808 /// Convert filenames with TeX macros and/or quotes to something LyX
1809 /// can understand
1810 string const normalize_filename(string const & name)
1811 {
1812         Parser p(trim(name, "\""));
1813         ostringstream os;
1814         while (p.good()) {
1815                 Token const & t = p.get_token();
1816                 if (t.cat() != catEscape)
1817                         os << t.asInput();
1818                 else if (t.cs() == "lyxdot") {
1819                         // This is used by LyX for simple dots in relative
1820                         // names
1821                         os << '.';
1822                         p.skip_spaces();
1823                 } else if (t.cs() == "space") {
1824                         os << ' ';
1825                         p.skip_spaces();
1826                 } else
1827                         os << t.asInput();
1828         }
1829         return os.str();
1830 }
1831
1832
1833 /// Convert \p name from TeX convention (relative to master file) to LyX
1834 /// convention (relative to .lyx file) if it is relative
1835 void fix_relative_filename(string & name)
1836 {
1837         if (FileName::isAbsolute(name))
1838                 return;
1839
1840         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1841                                    from_utf8(getParentFilePath())));
1842 }
1843
1844
1845 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1846 void parse_noweb(Parser & p, ostream & os, Context & context)
1847 {
1848         // assemble the rest of the keyword
1849         string name("<<");
1850         bool scrap = false;
1851         while (p.good()) {
1852                 Token const & t = p.get_token();
1853                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1854                         name += ">>";
1855                         p.get_token();
1856                         scrap = (p.good() && p.next_token().asInput() == "=");
1857                         if (scrap)
1858                                 name += p.get_token().asInput();
1859                         break;
1860                 }
1861                 name += t.asInput();
1862         }
1863
1864         if (!scrap || !context.new_layout_allowed ||
1865             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1866                 cerr << "Warning: Could not interpret '" << name
1867                      << "'. Ignoring it." << endl;
1868                 return;
1869         }
1870
1871         // We use new_paragraph instead of check_end_layout because the stuff
1872         // following the noweb chunk needs to start with a \begin_layout.
1873         // This may create a new paragraph even if there was none in the
1874         // noweb file, but the alternative is an invalid LyX file. Since
1875         // noweb code chunks are implemented with a layout style in LyX they
1876         // always must be in an own paragraph.
1877         context.new_paragraph(os);
1878         Context newcontext(true, context.textclass,
1879                 &context.textclass[from_ascii("Scrap")]);
1880         newcontext.check_layout(os);
1881         os << name;
1882         while (p.good()) {
1883                 Token const & t = p.get_token();
1884                 // We abuse the parser a bit, because this is no TeX syntax
1885                 // at all.
1886                 if (t.cat() == catEscape)
1887                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1888                 else {
1889                         ostringstream oss;
1890                         Context tmp(false, context.textclass,
1891                                     &context.textclass[from_ascii("Scrap")]);
1892                         tmp.need_end_layout = true;
1893                         tmp.check_layout(oss);
1894                         os << subst(t.asInput(), "\n", oss.str());
1895                 }
1896                 // The scrap chunk is ended by an @ at the beginning of a line.
1897                 // After the @ the line may contain a comment and/or
1898                 // whitespace, but nothing else.
1899                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1900                     (p.next_token().cat() == catSpace ||
1901                      p.next_token().cat() == catNewline ||
1902                      p.next_token().cat() == catComment)) {
1903                         while (p.good() && p.next_token().cat() == catSpace)
1904                                 os << p.get_token().asInput();
1905                         if (p.next_token().cat() == catComment)
1906                                 // The comment includes a final '\n'
1907                                 os << p.get_token().asInput();
1908                         else {
1909                                 if (p.next_token().cat() == catNewline)
1910                                         p.get_token();
1911                                 os << '\n';
1912                         }
1913                         break;
1914                 }
1915         }
1916         newcontext.check_end_layout(os);
1917 }
1918
1919
1920 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1921 bool is_macro(Parser & p)
1922 {
1923         Token first = p.curr_token();
1924         if (first.cat() != catEscape || !p.good())
1925                 return false;
1926         if (first.cs() == "def")
1927                 return true;
1928         if (first.cs() != "global" && first.cs() != "long")
1929                 return false;
1930         Token second = p.get_token();
1931         int pos = 1;
1932         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1933                second.cat() == catNewline || second.cat() == catComment)) {
1934                 second = p.get_token();
1935                 pos++;
1936         }
1937         bool secondvalid = second.cat() == catEscape;
1938         Token third;
1939         bool thirdvalid = false;
1940         if (p.good() && first.cs() == "global" && secondvalid &&
1941             second.cs() == "long") {
1942                 third = p.get_token();
1943                 pos++;
1944                 while (p.good() && !p.isParagraph() &&
1945                        (third.cat() == catSpace ||
1946                         third.cat() == catNewline ||
1947                         third.cat() == catComment)) {
1948                         third = p.get_token();
1949                         pos++;
1950                 }
1951                 thirdvalid = third.cat() == catEscape;
1952         }
1953         for (int i = 0; i < pos; ++i)
1954                 p.putback();
1955         if (!secondvalid)
1956                 return false;
1957         if (!thirdvalid)
1958                 return (first.cs() == "global" || first.cs() == "long") &&
1959                        second.cs() == "def";
1960         return first.cs() == "global" && second.cs() == "long" &&
1961                third.cs() == "def";
1962 }
1963
1964
1965 /// Parse a macro definition (assumes that is_macro() returned true)
1966 void parse_macro(Parser & p, ostream & os, Context & context)
1967 {
1968         context.check_layout(os);
1969         Token first = p.curr_token();
1970         Token second;
1971         Token third;
1972         string command = first.asInput();
1973         if (first.cs() != "def") {
1974                 p.get_token();
1975                 eat_whitespace(p, os, context, false);
1976                 second = p.curr_token();
1977                 command += second.asInput();
1978                 if (second.cs() != "def") {
1979                         p.get_token();
1980                         eat_whitespace(p, os, context, false);
1981                         third = p.curr_token();
1982                         command += third.asInput();
1983                 }
1984         }
1985         eat_whitespace(p, os, context, false);
1986         string const name = p.get_token().cs();
1987         eat_whitespace(p, os, context, false);
1988
1989         // parameter text
1990         bool simple = true;
1991         string paramtext;
1992         int arity = 0;
1993         while (p.next_token().cat() != catBegin) {
1994                 if (p.next_token().cat() == catParameter) {
1995                         // # found
1996                         p.get_token();
1997                         paramtext += "#";
1998
1999                         // followed by number?
2000                         if (p.next_token().cat() == catOther) {
2001                                 char c = p.getChar();
2002                                 paramtext += c;
2003                                 // number = current arity + 1?
2004                                 if (c == arity + '0' + 1)
2005                                         ++arity;
2006                                 else
2007                                         simple = false;
2008                         } else
2009                                 paramtext += p.get_token().cs();
2010                 } else {
2011                         paramtext += p.get_token().cs();
2012                         simple = false;
2013                 }
2014         }
2015
2016         // only output simple (i.e. compatible) macro as FormulaMacros
2017         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2018         if (simple) {
2019                 context.check_layout(os);
2020                 begin_inset(os, "FormulaMacro");
2021                 os << "\n\\def" << ert;
2022                 end_inset(os);
2023         } else
2024                 handle_ert(os, command + ert, context);
2025 }
2026
2027
2028 void registerExternalTemplatePackages(string const & name)
2029 {
2030         external::TemplateManager const & etm = external::TemplateManager::get();
2031         external::Template const * const et = etm.getTemplateByName(name);
2032         if (!et)
2033                 return;
2034         external::Template::Formats::const_iterator cit = et->formats.end();
2035         if (pdflatex)
2036                 cit = et->formats.find("PDFLaTeX");
2037         if (cit == et->formats.end())
2038                 // If the template has not specified a PDFLaTeX output,
2039                 // we try the LaTeX format.
2040                 cit = et->formats.find("LaTeX");
2041         if (cit == et->formats.end())
2042                 return;
2043         vector<string>::const_iterator qit = cit->second.requirements.begin();
2044         vector<string>::const_iterator qend = cit->second.requirements.end();
2045         for (; qit != qend; ++qit)
2046                 preamble.registerAutomaticallyLoadedPackage(*qit);
2047 }
2048
2049 } // anonymous namespace
2050
2051
2052 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2053                 Context & context)
2054 {
2055         Layout const * newlayout = 0;
2056         InsetLayout const * newinsetlayout = 0;
2057         char const * const * where = 0;
2058         // Store the latest bibliographystyle and nocite{*} option
2059         // (needed for bibtex inset)
2060         string btprint;
2061         string bibliographystyle = "default";
2062         bool const use_natbib = preamble.isPackageUsed("natbib");
2063         bool const use_jurabib = preamble.isPackageUsed("jurabib");
2064         string last_env;
2065         while (p.good()) {
2066                 Token const & t = p.get_token();
2067
2068         // it is impossible to determine the correct document language if CJK is used.
2069         // Therefore write a note at the beginning of the document
2070         if (have_CJK) {
2071                 context.check_layout(os);
2072                 begin_inset(os, "Note Note\n");
2073                 os << "status open\n\\begin_layout Plain Layout\n"
2074                    << "\\series bold\n"
2075                    << "Important information:\n"
2076                    << "\\end_layout\n\n"
2077                    << "\\begin_layout Plain Layout\n"
2078                    << "This document contains text in Chinese, Japanese or Korean.\n"
2079                    << " It was therefore impossible for tex2lyx to set the correct document langue for your document."
2080                    << " Please set the language manually in the document settings.\n"
2081                    << "\\end_layout\n";
2082                 end_inset(os);
2083                 have_CJK = false;
2084         }
2085
2086         // it is impossible to determine the correct encoding for non-CJK Japanese.
2087         // Therefore write a note at the beginning of the document
2088         if (is_nonCJKJapanese) {
2089                 context.check_layout(os);
2090                 begin_inset(os, "Note Note\n");
2091                 os << "status open\n\\begin_layout Plain Layout\n"
2092                    << "\\series bold\n"
2093                    << "Important information:\n"
2094                    << "\\end_layout\n\n"
2095                    << "\\begin_layout Plain Layout\n"
2096                    << "This document is in Japanese (non-CJK).\n"
2097                    << " It was therefore impossible for tex2lyx to determine the correct encoding."
2098                    << " The encoding EUC-JP was assumed. If this is incorrect, please set the correct"
2099                    << " encoding in the document settings.\n"
2100                    << "\\end_layout\n";
2101                 end_inset(os);
2102                 is_nonCJKJapanese = false;
2103         }
2104
2105 #ifdef FILEDEBUG
2106                 debugToken(cerr, t, flags);
2107 #endif
2108
2109                 if (flags & FLAG_ITEM) {
2110                         if (t.cat() == catSpace)
2111                                 continue;
2112
2113                         flags &= ~FLAG_ITEM;
2114                         if (t.cat() == catBegin) {
2115                                 // skip the brace and collect everything to the next matching
2116                                 // closing brace
2117                                 flags |= FLAG_BRACE_LAST;
2118                                 continue;
2119                         }
2120
2121                         // handle only this single token, leave the loop if done
2122                         flags |= FLAG_LEAVE;
2123                 }
2124
2125                 if (t.cat() != catEscape && t.character() == ']' &&
2126                     (flags & FLAG_BRACK_LAST))
2127                         return;
2128                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2129                         return;
2130
2131                 // If there is anything between \end{env} and \begin{env} we
2132                 // don't need to output a separator.
2133                 if (t.cat() != catSpace && t.cat() != catNewline &&
2134                     t.asInput() != "\\begin")
2135                         last_env = "";
2136
2137                 //
2138                 // cat codes
2139                 //
2140                 if (t.cat() == catMath) {
2141                         // we are inside some text mode thingy, so opening new math is allowed
2142                         context.check_layout(os);
2143                         begin_inset(os, "Formula ");
2144                         Token const & n = p.get_token();
2145                         bool const display(n.cat() == catMath && outer);
2146                         if (display) {
2147                                 // TeX's $$...$$ syntax for displayed math
2148                                 os << "\\[";
2149                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2150                                 os << "\\]";
2151                                 p.get_token(); // skip the second '$' token
2152                         } else {
2153                                 // simple $...$  stuff
2154                                 p.putback();
2155                                 os << '$';
2156                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2157                                 os << '$';
2158                         }
2159                         end_inset(os);
2160                         if (display) {
2161                                 // Prevent the conversion of a line break to a
2162                                 // space (bug 7668). This does not change the
2163                                 // output, but looks ugly in LyX.
2164                                 eat_whitespace(p, os, context, false);
2165                         }
2166                 }
2167
2168                 else if (t.cat() == catSuper || t.cat() == catSub)
2169                         cerr << "catcode " << t << " illegal in text mode\n";
2170
2171                 // Basic support for english quotes. This should be
2172                 // extended to other quotes, but is not so easy (a
2173                 // left english quote is the same as a right german
2174                 // quote...)
2175                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2176                         context.check_layout(os);
2177                         begin_inset(os, "Quotes ");
2178                         os << "eld";
2179                         end_inset(os);
2180                         p.get_token();
2181                         skip_braces(p);
2182                 }
2183                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2184                         context.check_layout(os);
2185                         begin_inset(os, "Quotes ");
2186                         os << "erd";
2187                         end_inset(os);
2188                         p.get_token();
2189                         skip_braces(p);
2190                 }
2191
2192                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2193                         context.check_layout(os);
2194                         begin_inset(os, "Quotes ");
2195                         os << "ald";
2196                         end_inset(os);
2197                         p.get_token();
2198                         skip_braces(p);
2199                 }
2200
2201                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2202                         context.check_layout(os);
2203                         begin_inset(os, "Quotes ");
2204                         os << "ard";
2205                         end_inset(os);
2206                         p.get_token();
2207                         skip_braces(p);
2208                 }
2209
2210                 else if (t.asInput() == "<"
2211                          && p.next_token().asInput() == "<" && noweb_mode) {
2212                         p.get_token();
2213                         parse_noweb(p, os, context);
2214                 }
2215
2216                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2217                         check_space(p, os, context);
2218
2219                 else if (t.character() == '[' && noweb_mode &&
2220                          p.next_token().character() == '[') {
2221                         // These can contain underscores
2222                         p.putback();
2223                         string const s = p.getFullOpt() + ']';
2224                         if (p.next_token().character() == ']')
2225                                 p.get_token();
2226                         else
2227                                 cerr << "Warning: Inserting missing ']' in '"
2228                                      << s << "'." << endl;
2229                         handle_ert(os, s, context);
2230                 }
2231
2232                 else if (t.cat() == catLetter) {
2233                         context.check_layout(os);
2234                         // Workaround for bug 4752.
2235                         // FIXME: This whole code block needs to be removed
2236                         //        when the bug is fixed and tex2lyx produces
2237                         //        the updated file format.
2238                         // The replacement algorithm in LyX is so stupid that
2239                         // it even translates a phrase if it is part of a word.
2240                         bool handled = false;
2241                         for (int const * l = known_phrase_lengths; *l; ++l) {
2242                                 string phrase = t.cs();
2243                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2244                                         phrase += p.get_token().cs();
2245                                 if (is_known(phrase, known_coded_phrases)) {
2246                                         handle_ert(os, phrase, context);
2247                                         handled = true;
2248                                         break;
2249                                 } else {
2250                                         for (size_t i = 1; i < phrase.length(); ++i)
2251                                                 p.putback();
2252                                 }
2253                         }
2254                         if (!handled)
2255                                 os << t.cs();
2256                 }
2257
2258                 else if (t.cat() == catOther ||
2259                                t.cat() == catAlign ||
2260                                t.cat() == catParameter) {
2261                         // This translates "&" to "\\&" which may be wrong...
2262                         context.check_layout(os);
2263                         os << t.cs();
2264                 }
2265
2266                 else if (p.isParagraph()) {
2267                         if (context.new_layout_allowed)
2268                                 context.new_paragraph(os);
2269                         else
2270                                 handle_ert(os, "\\par ", context);
2271                         eat_whitespace(p, os, context, true);
2272                 }
2273
2274                 else if (t.cat() == catActive) {
2275                         context.check_layout(os);
2276                         if (t.character() == '~') {
2277                                 if (context.layout->free_spacing)
2278                                         os << ' ';
2279                                 else {
2280                                         begin_inset(os, "space ~\n");
2281                                         end_inset(os);
2282                                 }
2283                         } else
2284                                 os << t.cs();
2285                 }
2286
2287                 else if (t.cat() == catBegin) {
2288                         Token const next = p.next_token();
2289                         Token const end = p.next_next_token();
2290                         if (next.cat() == catEnd) {
2291                         // {}
2292                         Token const prev = p.prev_token();
2293                         p.get_token();
2294                         if (p.next_token().character() == '`' ||
2295                             (prev.character() == '-' &&
2296                              p.next_token().character() == '-'))
2297                                 ; // ignore it in {}`` or -{}-
2298                         else
2299                                 handle_ert(os, "{}", context);
2300                         } else if (next.cat() == catEscape &&
2301                                    is_known(next.cs(), known_quotes) &&
2302                                    end.cat() == catEnd) {
2303                                 // Something like {\textquoteright} (e.g.
2304                                 // from writer2latex). LyX writes
2305                                 // \textquoteright{}, so we may skip the
2306                                 // braces here for better readability.
2307                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2308                                                    outer, context);
2309                         } else {
2310                         context.check_layout(os);
2311                         // special handling of font attribute changes
2312                         Token const prev = p.prev_token();
2313                         TeXFont const oldFont = context.font;
2314                         if (next.character() == '[' ||
2315                             next.character() == ']' ||
2316                             next.character() == '*') {
2317                                 p.get_token();
2318                                 if (p.next_token().cat() == catEnd) {
2319                                         os << next.cs();
2320                                         p.get_token();
2321                                 } else {
2322                                         p.putback();
2323                                         handle_ert(os, "{", context);
2324                                         parse_text_snippet(p, os,
2325                                                         FLAG_BRACE_LAST,
2326                                                         outer, context);
2327                                         handle_ert(os, "}", context);
2328                                 }
2329                         } else if (! context.new_layout_allowed) {
2330                                 handle_ert(os, "{", context);
2331                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2332                                                    outer, context);
2333                                 handle_ert(os, "}", context);
2334                         } else if (is_known(next.cs(), known_sizes)) {
2335                                 // next will change the size, so we must
2336                                 // reset it here
2337                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2338                                                    outer, context);
2339                                 if (!context.atParagraphStart())
2340                                         os << "\n\\size "
2341                                            << context.font.size << "\n";
2342                         } else if (is_known(next.cs(), known_font_families)) {
2343                                 // next will change the font family, so we
2344                                 // must reset it here
2345                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2346                                                    outer, context);
2347                                 if (!context.atParagraphStart())
2348                                         os << "\n\\family "
2349                                            << context.font.family << "\n";
2350                         } else if (is_known(next.cs(), known_font_series)) {
2351                                 // next will change the font series, so we
2352                                 // must reset it here
2353                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2354                                                    outer, context);
2355                                 if (!context.atParagraphStart())
2356                                         os << "\n\\series "
2357                                            << context.font.series << "\n";
2358                         } else if (is_known(next.cs(), known_font_shapes)) {
2359                                 // next will change the font shape, so we
2360                                 // must reset it here
2361                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2362                                                    outer, context);
2363                                 if (!context.atParagraphStart())
2364                                         os << "\n\\shape "
2365                                            << context.font.shape << "\n";
2366                         } else if (is_known(next.cs(), known_old_font_families) ||
2367                                    is_known(next.cs(), known_old_font_series) ||
2368                                    is_known(next.cs(), known_old_font_shapes)) {
2369                                 // next will change the font family, series
2370                                 // and shape, so we must reset it here
2371                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2372                                                    outer, context);
2373                                 if (!context.atParagraphStart())
2374                                         os <<  "\n\\family "
2375                                            << context.font.family
2376                                            << "\n\\series "
2377                                            << context.font.series
2378                                            << "\n\\shape "
2379                                            << context.font.shape << "\n";
2380                         } else {
2381                                 handle_ert(os, "{", context);
2382                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2383                                                    outer, context);
2384                                 handle_ert(os, "}", context);
2385                                 }
2386                         }
2387                 }
2388
2389                 else if (t.cat() == catEnd) {
2390                         if (flags & FLAG_BRACE_LAST) {
2391                                 return;
2392                         }
2393                         cerr << "stray '}' in text\n";
2394                         handle_ert(os, "}", context);
2395                 }
2396
2397                 else if (t.cat() == catComment)
2398                         parse_comment(p, os, t, context);
2399
2400                 //
2401                 // control sequences
2402                 //
2403
2404                 else if (t.cs() == "(") {
2405                         context.check_layout(os);
2406                         begin_inset(os, "Formula");
2407                         os << " \\(";
2408                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2409                         os << "\\)";
2410                         end_inset(os);
2411                 }
2412
2413                 else if (t.cs() == "[") {
2414                         context.check_layout(os);
2415                         begin_inset(os, "Formula");
2416                         os << " \\[";
2417                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2418                         os << "\\]";
2419                         end_inset(os);
2420                         // Prevent the conversion of a line break to a space
2421                         // (bug 7668). This does not change the output, but
2422                         // looks ugly in LyX.
2423                         eat_whitespace(p, os, context, false);
2424                 }
2425
2426                 else if (t.cs() == "begin")
2427                         parse_environment(p, os, outer, last_env,
2428                                           context);
2429
2430                 else if (t.cs() == "end") {
2431                         if (flags & FLAG_END) {
2432                                 // eat environment name
2433                                 string const name = p.getArg('{', '}');
2434                                 if (name != active_environment())
2435                                         cerr << "\\end{" + name + "} does not match \\begin{"
2436                                                 + active_environment() + "}\n";
2437                                 return;
2438                         }
2439                         p.error("found 'end' unexpectedly");
2440                 }
2441
2442                 else if (t.cs() == "item") {
2443                         string s;
2444                         bool const optarg = p.hasOpt();
2445                         if (optarg) {
2446                                 // FIXME: This swallows comments, but we cannot use
2447                                 //        eat_whitespace() since we must not output
2448                                 //        anything before the item.
2449                                 p.skip_spaces(true);
2450                                 s = p.verbatimOption();
2451                         } else
2452                                 p.skip_spaces(false);
2453                         context.set_item();
2454                         context.check_layout(os);
2455                         if (context.has_item) {
2456                                 // An item in an unknown list-like environment
2457                                 // FIXME: Do this in check_layout()!
2458                                 context.has_item = false;
2459                                 if (optarg)
2460                                         handle_ert(os, "\\item", context);
2461                                 else
2462                                         handle_ert(os, "\\item ", context);
2463                         }
2464                         if (optarg) {
2465                                 if (context.layout->labeltype != LABEL_MANUAL) {
2466                                         // LyX does not support \item[\mybullet]
2467                                         // in itemize environments
2468                                         Parser p2(s + ']');
2469                                         os << parse_text_snippet(p2,
2470                                                 FLAG_BRACK_LAST, outer, context);
2471                                 } else if (!s.empty()) {
2472                                         // LyX adds braces around the argument,
2473                                         // so we need to remove them here.
2474                                         if (s.size() > 2 && s[0] == '{' &&
2475                                             s[s.size()-1] == '}')
2476                                                 s = s.substr(1, s.size()-2);
2477                                         // If the argument contains a space we
2478                                         // must put it into ERT: Otherwise LyX
2479                                         // would misinterpret the space as
2480                                         // item delimiter (bug 7663)
2481                                         if (contains(s, ' ')) {
2482                                                 handle_ert(os, s, context);
2483                                         } else {
2484                                                 Parser p2(s + ']');
2485                                                 os << parse_text_snippet(p2,
2486                                                         FLAG_BRACK_LAST,
2487                                                         outer, context);
2488                                         }
2489                                         // The space is needed to separate the
2490                                         // item from the rest of the sentence.
2491                                         os << ' ';
2492                                         eat_whitespace(p, os, context, false);
2493                                 }
2494                         }
2495                 }
2496
2497                 else if (t.cs() == "bibitem") {
2498                         context.set_item();
2499                         context.check_layout(os);
2500                         eat_whitespace(p, os, context, false);
2501                         string label = convert_command_inset_arg(p.verbatimOption());
2502                         string key = convert_command_inset_arg(p.verbatim_item());
2503                         if (contains(label, '\\') || contains(key, '\\')) {
2504                                 // LyX can't handle LaTeX commands in labels or keys
2505                                 handle_ert(os, t.asInput() + '[' + label +
2506                                                "]{" + p.verbatim_item() + '}',
2507                                            context);
2508                         } else {
2509                                 begin_command_inset(os, "bibitem", "bibitem");
2510                                 os << "label \"" << label << "\"\n"
2511                                       "key \"" << key << "\"\n";
2512                                 end_inset(os);
2513                         }
2514                 }
2515
2516                 else if (is_macro(p)) {
2517                         // catch the case of \def\inputGnumericTable
2518                         bool macro = true;
2519                         if (t.cs() == "def") {
2520                                 Token second = p.next_token();
2521                                 if (second.cs() == "inputGnumericTable") {
2522                                         p.pushPosition();
2523                                         p.get_token();
2524                                         skip_braces(p);
2525                                         Token third = p.get_token();
2526                                         p.popPosition();
2527                                         if (third.cs() == "input") {
2528                                                 p.get_token();
2529                                                 skip_braces(p);
2530                                                 p.get_token();
2531                                                 string name = normalize_filename(p.verbatim_item());
2532                                                 string const path = getMasterFilePath();
2533                                                 // We want to preserve relative / absolute filenames,
2534                                                 // therefore path is only used for testing
2535                                                 // The file extension is in every case ".tex".
2536                                                 // So we need to remove this extension and check for
2537                                                 // the original one.
2538                                                 name = removeExtension(name);
2539                                                 if (!makeAbsPath(name, path).exists()) {
2540                                                         char const * const Gnumeric_formats[] = {"gnumeric",
2541                                                                 "ods", "xls", 0};
2542                                                         string const Gnumeric_name =
2543                                                                 find_file(name, path, Gnumeric_formats);
2544                                                         if (!Gnumeric_name.empty())
2545                                                                 name = Gnumeric_name;
2546                                                 }
2547                                                 if (makeAbsPath(name, path).exists())
2548                                                         fix_relative_filename(name);
2549                                                 else
2550                                                         cerr << "Warning: Could not find file '"
2551                                                              << name << "'." << endl;
2552                                                 context.check_layout(os);
2553                                                 begin_inset(os, "External\n\ttemplate ");
2554                                                 os << "GnumericSpreadsheet\n\tfilename "
2555                                                    << name << "\n";
2556                                                 end_inset(os);
2557                                                 context.check_layout(os);
2558                                                 macro = false;
2559                                                 // register the packages that are automatically reloaded
2560                                                 // by the Gnumeric template
2561                                                 registerExternalTemplatePackages("GnumericSpreadsheet");
2562                                         }
2563                                 }
2564                         }
2565                         if (macro)
2566                                 parse_macro(p, os, context);
2567                 }
2568
2569                 else if (t.cs() == "noindent") {
2570                         p.skip_spaces();
2571                         context.add_par_extra_stuff("\\noindent\n");
2572                 }
2573
2574                 else if (t.cs() == "appendix") {
2575                         context.add_par_extra_stuff("\\start_of_appendix\n");
2576                         // We need to start a new paragraph. Otherwise the
2577                         // appendix in 'bla\appendix\chapter{' would start
2578                         // too late.
2579                         context.new_paragraph(os);
2580                         // We need to make sure that the paragraph is
2581                         // generated even if it is empty. Otherwise the
2582                         // appendix in '\par\appendix\par\chapter{' would
2583                         // start too late.
2584                         context.check_layout(os);
2585                         // FIXME: This is a hack to prevent paragraph
2586                         // deletion if it is empty. Handle this better!
2587                         handle_comment(os,
2588                                 "%dummy comment inserted by tex2lyx to "
2589                                 "ensure that this paragraph is not empty",
2590                                 context);
2591                         // Both measures above may generate an additional
2592                         // empty paragraph, but that does not hurt, because
2593                         // whitespace does not matter here.
2594                         eat_whitespace(p, os, context, true);
2595                 }
2596
2597                 // Must catch empty dates before findLayout is called below
2598                 else if (t.cs() == "date") {
2599                         eat_whitespace(p, os, context, false);
2600                         p.pushPosition();
2601                         string const date = p.verbatim_item();
2602                         p.popPosition();
2603                         if (date.empty()) {
2604                                 preamble.suppressDate(true);
2605                                 p.verbatim_item();
2606                         } else {
2607                                 preamble.suppressDate(false);
2608                                 if (context.new_layout_allowed &&
2609                                     (newlayout = findLayout(context.textclass,
2610                                                             t.cs(), true))) {
2611                                         // write the layout
2612                                         output_command_layout(os, p, outer,
2613                                                         context, newlayout);
2614                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2615                                         if (!preamble.titleLayoutFound())
2616                                                 preamble.titleLayoutFound(newlayout->intitle);
2617                                         set<string> const & req = newlayout->requires();
2618                                         set<string>::const_iterator it = req.begin();
2619                                         set<string>::const_iterator en = req.end();
2620                                         for (; it != en; ++it)
2621                                                 preamble.registerAutomaticallyLoadedPackage(*it);
2622                                 } else
2623                                         handle_ert(os,
2624                                                 "\\date{" + p.verbatim_item() + '}',
2625                                                 context);
2626                         }
2627                 }
2628
2629                 // Starred section headings
2630                 // Must attempt to parse "Section*" before "Section".
2631                 else if ((p.next_token().asInput() == "*") &&
2632                          context.new_layout_allowed &&
2633                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2634                         // write the layout
2635                         p.get_token();
2636                         output_command_layout(os, p, outer, context, newlayout);
2637                         p.skip_spaces();
2638                         if (!preamble.titleLayoutFound())
2639                                 preamble.titleLayoutFound(newlayout->intitle);
2640                         set<string> const & req = newlayout->requires();
2641                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2642                                 preamble.registerAutomaticallyLoadedPackage(*it);
2643                 }
2644
2645                 // Section headings and the like
2646                 else if (context.new_layout_allowed &&
2647                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2648                         // write the layout
2649                         output_command_layout(os, p, outer, context, newlayout);
2650                         p.skip_spaces();
2651                         if (!preamble.titleLayoutFound())
2652                                 preamble.titleLayoutFound(newlayout->intitle);
2653                         set<string> const & req = newlayout->requires();
2654                         for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2655                                 preamble.registerAutomaticallyLoadedPackage(*it);
2656                 }
2657
2658                 else if (t.cs() == "caption") {
2659                         p.skip_spaces();
2660                         context.check_layout(os);
2661                         p.skip_spaces();
2662                         begin_inset(os, "Caption\n");
2663                         Context newcontext(true, context.textclass);
2664                         newcontext.font = context.font;
2665                         newcontext.check_layout(os);
2666                         if (p.next_token().cat() != catEscape &&
2667                             p.next_token().character() == '[') {
2668                                 p.get_token(); // eat '['
2669                                 begin_inset(os, "Argument\n");
2670                                 os << "status collapsed\n";
2671                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2672                                 end_inset(os);
2673                                 eat_whitespace(p, os, context, false);
2674                         }
2675                         parse_text(p, os, FLAG_ITEM, outer, context);
2676                         context.check_end_layout(os);
2677                         // We don't need really a new paragraph, but
2678                         // we must make sure that the next item gets a \begin_layout.
2679                         context.new_paragraph(os);
2680                         end_inset(os);
2681                         p.skip_spaces();
2682                         newcontext.check_end_layout(os);
2683                 }
2684
2685                 else if (t.cs() == "subfloat") {
2686                         // the syntax is \subfloat[caption]{content}
2687                         // if it is a table of figure depends on the surrounding float
2688                         bool has_caption = false;
2689                         p.skip_spaces();
2690                         // do nothing if there is no outer float
2691                         if (!float_type.empty()) {
2692                                 context.check_layout(os);
2693                                 p.skip_spaces();
2694                                 begin_inset(os, "Float " + float_type + "\n");
2695                                 os << "wide false"
2696                                    << "\nsideways false"
2697                                    << "\nstatus collapsed\n\n";
2698                                 // test for caption
2699                                 string caption;
2700                                 if (p.next_token().cat() != catEscape &&
2701                                                 p.next_token().character() == '[') {
2702                                                         p.get_token(); // eat '['
2703                                                         caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2704                                                         has_caption = true;
2705                                 }
2706                                 // the content
2707                                 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2708                                 // the caption comes always as the last
2709                                 if (has_caption) {
2710                                         // we must make sure that the caption gets a \begin_layout
2711                                         os << "\n\\begin_layout Plain Layout";
2712                                         p.skip_spaces();
2713                                         begin_inset(os, "Caption\n");
2714                                         Context newcontext(true, context.textclass);
2715                                         newcontext.font = context.font;
2716                                         newcontext.check_layout(os);
2717                                         os << caption << "\n";
2718                                         newcontext.check_end_layout(os);
2719                                         // We don't need really a new paragraph, but
2720                                         // we must make sure that the next item gets a \begin_layout.
2721                                         //newcontext.new_paragraph(os);
2722                                         end_inset(os);
2723                                         p.skip_spaces();
2724                                 }
2725                                 // We don't need really a new paragraph, but
2726                                 // we must make sure that the next item gets a \begin_layout.
2727                                 if (has_caption)
2728                                         context.new_paragraph(os);
2729                                 end_inset(os);
2730                                 p.skip_spaces();
2731                                 context.check_end_layout(os);
2732                                 // close the layout we opened
2733                                 if (has_caption)
2734                                         os << "\n\\end_layout\n";
2735                         } else {
2736                                 // if the float type is not supported or there is no surrounding float
2737                                 // output it as ERT
2738                                 if (p.hasOpt()) {
2739                                         string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2740                                         handle_ert(os, t.asInput() + '[' + opt_arg +
2741                                                "]{" + p.verbatim_item() + '}', context);
2742                                 } else
2743                                         handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2744                         }
2745                 }
2746
2747                 else if (t.cs() == "includegraphics") {
2748                         bool const clip = p.next_token().asInput() == "*";
2749                         if (clip)
2750                                 p.get_token();
2751                         string const arg = p.getArg('[', ']');
2752                         map<string, string> opts;
2753                         vector<string> keys;
2754                         split_map(arg, opts, keys);
2755                         if (clip)
2756                                 opts["clip"] = string();
2757                         string name = normalize_filename(p.verbatim_item());
2758
2759                         string const path = getMasterFilePath();
2760                         // We want to preserve relative / absolute filenames,
2761                         // therefore path is only used for testing
2762                         if (!makeAbsPath(name, path).exists()) {
2763                                 // The file extension is probably missing.
2764                                 // Now try to find it out.
2765                                 string const dvips_name =
2766                                         find_file(name, path,
2767                                                   known_dvips_graphics_formats);
2768                                 string const pdftex_name =
2769                                         find_file(name, path,
2770                                                   known_pdftex_graphics_formats);
2771                                 if (!dvips_name.empty()) {
2772                                         if (!pdftex_name.empty()) {
2773                                                 cerr << "This file contains the "
2774                                                         "latex snippet\n"
2775                                                         "\"\\includegraphics{"
2776                                                      << name << "}\".\n"
2777                                                         "However, files\n\""
2778                                                      << dvips_name << "\" and\n\""
2779                                                      << pdftex_name << "\"\n"
2780                                                         "both exist, so I had to make a "
2781                                                         "choice and took the first one.\n"
2782                                                         "Please move the unwanted one "
2783                                                         "someplace else and try again\n"
2784                                                         "if my choice was wrong."
2785                                                      << endl;
2786                                         }
2787                                         name = dvips_name;
2788                                 } else if (!pdftex_name.empty()) {
2789                                         name = pdftex_name;
2790                                         pdflatex = true;
2791                                 }
2792                         }
2793
2794                         if (makeAbsPath(name, path).exists())
2795                                 fix_relative_filename(name);
2796                         else
2797                                 cerr << "Warning: Could not find graphics file '"
2798                                      << name << "'." << endl;
2799
2800                         context.check_layout(os);
2801                         begin_inset(os, "Graphics ");
2802                         os << "\n\tfilename " << name << '\n';
2803                         if (opts.find("width") != opts.end())
2804                                 os << "\twidth "
2805                                    << translate_len(opts["width"]) << '\n';
2806                         if (opts.find("height") != opts.end())
2807                                 os << "\theight "
2808                                    << translate_len(opts["height"]) << '\n';
2809                         if (opts.find("scale") != opts.end()) {
2810                                 istringstream iss(opts["scale"]);
2811                                 double val;
2812                                 iss >> val;
2813                                 val = val*100;
2814                                 os << "\tscale " << val << '\n';
2815                         }
2816                         if (opts.find("angle") != opts.end()) {
2817                                 os << "\trotateAngle "
2818                                    << opts["angle"] << '\n';
2819                                 vector<string>::const_iterator a =
2820                                         find(keys.begin(), keys.end(), "angle");
2821                                 vector<string>::const_iterator s =
2822                                         find(keys.begin(), keys.end(), "width");
2823                                 if (s == keys.end())
2824                                         s = find(keys.begin(), keys.end(), "height");
2825                                 if (s == keys.end())
2826                                         s = find(keys.begin(), keys.end(), "scale");
2827                                 if (s != keys.end() && distance(s, a) > 0)
2828                                         os << "\tscaleBeforeRotation\n";
2829                         }
2830                         if (opts.find("origin") != opts.end()) {
2831                                 ostringstream ss;
2832                                 string const opt = opts["origin"];
2833                                 if (opt.find('l') != string::npos) ss << "left";
2834                                 if (opt.find('r') != string::npos) ss << "right";
2835                                 if (opt.find('c') != string::npos) ss << "center";
2836                                 if (opt.find('t') != string::npos) ss << "Top";
2837                                 if (opt.find('b') != string::npos) ss << "Bottom";
2838                                 if (opt.find('B') != string::npos) ss << "Baseline";
2839                                 if (!ss.str().empty())
2840                                         os << "\trotateOrigin " << ss.str() << '\n';
2841                                 else
2842                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2843                         }
2844                         if (opts.find("keepaspectratio") != opts.end())
2845                                 os << "\tkeepAspectRatio\n";
2846                         if (opts.find("clip") != opts.end())
2847                                 os << "\tclip\n";
2848                         if (opts.find("draft") != opts.end())
2849                                 os << "\tdraft\n";
2850                         if (opts.find("bb") != opts.end())
2851                                 os << "\tBoundingBox "
2852                                    << opts["bb"] << '\n';
2853                         int numberOfbbOptions = 0;
2854                         if (opts.find("bbllx") != opts.end())
2855                                 numberOfbbOptions++;
2856                         if (opts.find("bblly") != opts.end())
2857                                 numberOfbbOptions++;
2858                         if (opts.find("bburx") != opts.end())
2859                                 numberOfbbOptions++;
2860                         if (opts.find("bbury") != opts.end())
2861                                 numberOfbbOptions++;
2862                         if (numberOfbbOptions == 4)
2863                                 os << "\tBoundingBox "
2864                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2865                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2866                         else if (numberOfbbOptions > 0)
2867                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2868                         numberOfbbOptions = 0;
2869                         if (opts.find("natwidth") != opts.end())
2870                                 numberOfbbOptions++;
2871                         if (opts.find("natheight") != opts.end())
2872                                 numberOfbbOptions++;
2873                         if (numberOfbbOptions == 2)
2874                                 os << "\tBoundingBox 0bp 0bp "
2875                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2876                         else if (numberOfbbOptions > 0)
2877                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2878                         ostringstream special;
2879                         if (opts.find("hiresbb") != opts.end())
2880                                 special << "hiresbb,";
2881                         if (opts.find("trim") != opts.end())
2882                                 special << "trim,";
2883                         if (opts.find("viewport") != opts.end())
2884                                 special << "viewport=" << opts["viewport"] << ',';
2885                         if (opts.find("totalheight") != opts.end())
2886                                 special << "totalheight=" << opts["totalheight"] << ',';
2887                         if (opts.find("type") != opts.end())
2888                                 special << "type=" << opts["type"] << ',';
2889                         if (opts.find("ext") != opts.end())
2890                                 special << "ext=" << opts["ext"] << ',';
2891                         if (opts.find("read") != opts.end())
2892                                 special << "read=" << opts["read"] << ',';
2893                         if (opts.find("command") != opts.end())
2894                                 special << "command=" << opts["command"] << ',';
2895                         string s_special = special.str();
2896                         if (!s_special.empty()) {
2897                                 // We had special arguments. Remove the trailing ','.
2898                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2899                         }
2900                         // TODO: Handle the unknown settings better.
2901                         // Warn about invalid options.
2902                         // Check whether some option was given twice.
2903                         end_inset(os);
2904                         preamble.registerAutomaticallyLoadedPackage("graphicx");
2905                 }
2906
2907                 else if (t.cs() == "footnote" ||
2908                          (t.cs() == "thanks" && context.layout->intitle)) {
2909                         p.skip_spaces();
2910                         context.check_layout(os);
2911                         begin_inset(os, "Foot\n");
2912                         os << "status collapsed\n\n";
2913                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2914                         end_inset(os);
2915                 }
2916
2917                 else if (t.cs() == "marginpar") {
2918                         p.skip_spaces();
2919                         context.check_layout(os);
2920                         begin_inset(os, "Marginal\n");
2921                         os << "status collapsed\n\n";
2922                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2923                         end_inset(os);
2924                 }
2925
2926                 else if (t.cs() == "lstinline") {
2927                         p.skip_spaces();
2928                         parse_listings(p, os, context, true);
2929                 }
2930
2931                 else if (t.cs() == "ensuremath") {
2932                         p.skip_spaces();
2933                         context.check_layout(os);
2934                         string const s = p.verbatim_item();
2935                         //FIXME: this never triggers in UTF8
2936                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2937                                 os << s;
2938                         else
2939                                 handle_ert(os, "\\ensuremath{" + s + "}",
2940                                            context);
2941                 }
2942
2943                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2944                         if (preamble.titleLayoutFound()) {
2945                                 // swallow this
2946                                 skip_spaces_braces(p);
2947                         } else
2948                                 handle_ert(os, t.asInput(), context);
2949                 }
2950
2951                 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2952                         context.check_layout(os);
2953                         begin_command_inset(os, "toc", t.cs());
2954                         end_inset(os);
2955                         skip_spaces_braces(p);
2956                         if (t.cs() == "lstlistoflistings")
2957                                 preamble.registerAutomaticallyLoadedPackage("listings");
2958                 }
2959
2960                 else if (t.cs() == "listoffigures") {
2961                         context.check_layout(os);
2962                         begin_inset(os, "FloatList figure\n");
2963                         end_inset(os);
2964                         skip_spaces_braces(p);
2965                 }
2966
2967                 else if (t.cs() == "listoftables") {
2968                         context.check_layout(os);
2969                         begin_inset(os, "FloatList table\n");
2970                         end_inset(os);
2971                         skip_spaces_braces(p);
2972                 }
2973
2974                 else if (t.cs() == "listof") {
2975                         p.skip_spaces(true);
2976                         string const name = p.get_token().cs();
2977                         if (context.textclass.floats().typeExist(name)) {
2978                                 context.check_layout(os);
2979                                 begin_inset(os, "FloatList ");
2980                                 os << name << "\n";
2981                                 end_inset(os);
2982                                 p.get_token(); // swallow second arg
2983                         } else
2984                                 handle_ert(os, "\\listof{" + name + "}", context);
2985                 }
2986
2987                 else if ((where = is_known(t.cs(), known_text_font_families)))
2988                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2989                                 context, "\\family", context.font.family,
2990                                 known_coded_font_families[where - known_text_font_families]);
2991
2992                 else if ((where = is_known(t.cs(), known_text_font_series)))
2993                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2994                                 context, "\\series", context.font.series,
2995                                 known_coded_font_series[where - known_text_font_series]);
2996
2997                 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2998                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2999                                 context, "\\shape", context.font.shape,
3000                                 known_coded_font_shapes[where - known_text_font_shapes]);
3001
3002                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3003                         context.check_layout(os);
3004                         TeXFont oldFont = context.font;
3005                         context.font.init();
3006                         context.font.size = oldFont.size;
3007                         os << "\n\\family " << context.font.family << "\n";
3008                         os << "\n\\series " << context.font.series << "\n";
3009                         os << "\n\\shape " << context.font.shape << "\n";
3010                         if (t.cs() == "textnormal") {
3011                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3012                                 output_font_change(os, context.font, oldFont);
3013                                 context.font = oldFont;
3014                         } else
3015                                 eat_whitespace(p, os, context, false);
3016                 }
3017
3018                 else if (t.cs() == "textcolor") {
3019                         // scheme is \textcolor{color name}{text}
3020                         string const color = p.verbatim_item();
3021                         // we only support the predefined colors of the color package
3022                         if (color == "black" || color == "blue" || color == "cyan"
3023                                 || color == "green" || color == "magenta" || color == "red"
3024                                 || color == "white" || color == "yellow") {
3025                                         context.check_layout(os);
3026                                         os << "\n\\color " << color << "\n";
3027                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3028                                         context.check_layout(os);
3029                                         os << "\n\\color inherit\n";
3030                                         preamble.registerAutomaticallyLoadedPackage("color");
3031                         } else
3032                                 // for custom defined colors
3033                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
3034                 }
3035
3036                 else if (t.cs() == "underbar" || t.cs() == "uline") {
3037                         // \underbar is not 100% correct (LyX outputs \uline
3038                         // of ulem.sty). The difference is that \ulem allows
3039                         // line breaks, and \underbar does not.
3040                         // Do NOT handle \underline.
3041                         // \underbar cuts through y, g, q, p etc.,
3042                         // \underline does not.
3043                         context.check_layout(os);
3044                         os << "\n\\bar under\n";
3045                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3046                         context.check_layout(os);
3047                         os << "\n\\bar default\n";
3048                         preamble.registerAutomaticallyLoadedPackage("ulem");
3049                 }
3050
3051                 else if (t.cs() == "sout") {
3052                         context.check_layout(os);
3053                         os << "\n\\strikeout on\n";
3054                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3055                         context.check_layout(os);
3056                         os << "\n\\strikeout default\n";
3057                         preamble.registerAutomaticallyLoadedPackage("ulem");
3058                 }
3059
3060                 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3061                          t.cs() == "emph" || t.cs() == "noun") {
3062                         context.check_layout(os);
3063                         os << "\n\\" << t.cs() << " on\n";
3064                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3065                         context.check_layout(os);
3066                         os << "\n\\" << t.cs() << " default\n";
3067                         if (t.cs() == "uuline" || t.cs() == "uwave")
3068                                 preamble.registerAutomaticallyLoadedPackage("ulem");
3069                 }
3070
3071                 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3072                         context.check_layout(os);
3073                         string name = p.getArg('{', '}');
3074                         string localtime = p.getArg('{', '}');
3075                         preamble.registerAuthor(name);
3076                         Author const & author = preamble.getAuthor(name);
3077                         // from_ctime() will fail if LyX decides to output the
3078                         // time in the text language. It might also use a wrong
3079                         // time zone (if the original LyX document was exported
3080                         // with a different time zone).
3081                         time_t ptime = from_ctime(localtime);
3082                         if (ptime == static_cast<time_t>(-1)) {
3083                                 cerr << "Warning: Could not parse time `" << localtime
3084                                      << "´ for change tracking, using current time instead.\n";
3085                                 ptime = current_time();
3086                         }
3087                         if (t.cs() == "lyxadded")
3088                                 os << "\n\\change_inserted ";
3089                         else
3090                                 os << "\n\\change_deleted ";
3091                         os << author.bufferId() << ' ' << ptime << '\n';
3092                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3093                         bool dvipost    = LaTeXPackages::isAvailable("dvipost");
3094                         bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3095                                           LaTeXPackages::isAvailable("xcolor");
3096                         // No need to test for luatex, since luatex comes in
3097                         // two flavours (dvi and pdf), like latex, and those
3098                         // are detected by pdflatex.
3099                         if (pdflatex || xetex) {
3100                                 if (xcolorulem) {
3101                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3102                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3103                                         preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3104                                 }
3105                         } else {
3106                                 if (dvipost) {
3107                                         preamble.registerAutomaticallyLoadedPackage("dvipost");
3108                                 } else if (xcolorulem) {
3109                                         preamble.registerAutomaticallyLoadedPackage("ulem");
3110                                         preamble.registerAutomaticallyLoadedPackage("xcolor");
3111                                 }
3112                         }
3113                 }
3114
3115                 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3116                              t.cs() == "vphantom") {
3117                         context.check_layout(os);
3118                         if (t.cs() == "phantom")
3119                                 begin_inset(os, "Phantom Phantom\n");
3120                         if (t.cs() == "hphantom")
3121                                 begin_inset(os, "Phantom HPhantom\n");
3122                         if (t.cs() == "vphantom")
3123                                 begin_inset(os, "Phantom VPhantom\n");
3124                         os << "status open\n";
3125                         parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3126                                             "Phantom");
3127                         end_inset(os);
3128                 }
3129
3130                 else if (t.cs() == "href") {
3131                         context.check_layout(os);
3132                         string target = p.getArg('{', '}');
3133                         string name = p.getArg('{', '}');
3134                         string type;
3135                         size_t i = target.find(':');
3136                         if (i != string::npos) {
3137                                 type = target.substr(0, i + 1);
3138                                 if (type == "mailto:" || type == "file:")
3139                                         target = target.substr(i + 1);
3140                                 // handle the case that name is equal to target, except of "http://"
3141                                 else if (target.substr(i + 3) == name && type == "http:")
3142                                         target = name;
3143                         }
3144                         begin_command_inset(os, "href", "href");
3145                         if (name != target)
3146                                 os << "name \"" << name << "\"\n";
3147                         os << "target \"" << target << "\"\n";
3148                         if (type == "mailto:" || type == "file:")
3149                                 os << "type \"" << type << "\"\n";
3150                         end_inset(os);
3151                         skip_spaces_braces(p);
3152                 }
3153
3154                 else if (t.cs() == "lyxline") {
3155                         // swallow size argument (it is not used anyway)
3156                         p.getArg('{', '}');
3157                         if (!context.atParagraphStart()) {
3158                                 // so our line is in the middle of a paragraph
3159                                 // we need to add a new line, lest this line
3160                                 // follow the other content on that line and
3161                                 // run off the side of the page
3162                                 // FIXME: This may create an empty paragraph,
3163                                 //        but without that it would not be
3164                                 //        possible to set noindent below.
3165                                 //        Fortunately LaTeX does not care
3166                                 //        about the empty paragraph.
3167                                 context.new_paragraph(os);
3168                         }
3169                         if (preamble.indentParagraphs()) {
3170                                 // we need to unindent, lest the line be too long
3171                                 context.add_par_extra_stuff("\\noindent\n");
3172                         }
3173                         context.check_layout(os);
3174                         begin_command_inset(os, "line", "rule");
3175                         os << "offset \"0.5ex\"\n"
3176                               "width \"100line%\"\n"
3177                               "height \"1pt\"\n";
3178                         end_inset(os);
3179                 }
3180
3181                 else if (t.cs() == "rule") {
3182                         string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3183                         string const width = p.getArg('{', '}');
3184                         string const thickness = p.getArg('{', '}');
3185                         context.check_layout(os);
3186                         begin_command_inset(os, "line", "rule");
3187                         if (!offset.empty())
3188                                 os << "offset \"" << translate_len(offset) << "\"\n";
3189                         os << "width \"" << translate_len(width) << "\"\n"
3190                                   "height \"" << translate_len(thickness) << "\"\n";
3191                         end_inset(os);
3192                 }
3193
3194                 else if (is_known(t.cs(), known_phrases) ||
3195                          (t.cs() == "protect" &&
3196                           p.next_token().cat() == catEscape &&
3197                           is_known(p.next_token().cs(), known_phrases))) {
3198                         // LyX sometimes puts a \protect in front, so we have to ignore it
3199                         // FIXME: This needs to be changed when bug 4752 is fixed.
3200                         where = is_known(
3201                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3202                                 known_phrases);
3203                         context.check_layout(os);
3204                         os << known_coded_phrases[where - known_phrases];
3205                         skip_spaces_braces(p);
3206                 }
3207
3208                 else if ((where = is_known(t.cs(), known_ref_commands))) {
3209                         string const opt = p.getOpt();
3210                         if (opt.empty()) {
3211                                 context.check_layout(os);
3212                                 begin_command_inset(os, "ref",
3213                                         known_coded_ref_commands[where - known_ref_commands]);
3214                                 os << "reference \""
3215                                    << convert_command_inset_arg(p.verbatim_item())
3216                                    << "\"\n";
3217                                 end_inset(os);
3218                                 if (t.cs() == "vref" || t.cs() == "vpageref")
3219                                         preamble.registerAutomaticallyLoadedPackage("varioref");
3220
3221                         } else {
3222                                 // LyX does not support optional arguments of ref commands
3223                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3224                                                p.verbatim_item() + "}", context);
3225                         }
3226                 }
3227
3228                 else if (use_natbib &&
3229                          is_known(t.cs(), known_natbib_commands) &&
3230                          ((t.cs() != "citefullauthor" &&
3231                            t.cs() != "citeyear" &&
3232                            t.cs() != "citeyearpar") ||
3233                           p.next_token().asInput() != "*")) {
3234                         context.check_layout(os);
3235                         string command = t.cs();
3236                         if (p.next_token().asInput() == "*") {
3237                                 command += '*';
3238                                 p.get_token();
3239                         }
3240                         if (command == "citefullauthor")
3241                                 // alternative name for "\\citeauthor*"
3242                                 command = "citeauthor*";
3243
3244                         // text before the citation
3245                         string before;
3246                         // text after the citation
3247                         string after;
3248                         get_cite_arguments(p, true, before, after);
3249
3250                         if (command == "cite") {
3251                                 // \cite without optional argument means
3252                                 // \citet, \cite with at least one optional
3253                                 // argument means \citep.
3254                                 if (before.empty() && after.empty())
3255                                         command = "citet";
3256                                 else
3257                                         command = "citep";
3258                         }
3259                         if (before.empty() && after == "[]")
3260                                 // avoid \citet[]{a}
3261                                 after.erase();
3262                         else if (before == "[]" && after == "[]") {
3263                                 // avoid \citet[][]{a}
3264                                 before.erase();
3265                                 after.erase();
3266                         }
3267                         // remove the brackets around after and before
3268                         if (!after.empty()) {
3269                                 after.erase(0, 1);
3270                                 after.erase(after.length() - 1, 1);
3271                                 after = convert_command_inset_arg(after);
3272                         }
3273                         if (!before.empty()) {
3274                                 before.erase(0, 1);
3275                                 before.erase(before.length() - 1, 1);
3276                                 before = convert_command_inset_arg(before);
3277                         }
3278                         begin_command_inset(os, "citation", command);
3279                         os << "after " << '"' << after << '"' << "\n";
3280                         os << "before " << '"' << before << '"' << "\n";
3281                         os << "key \""
3282                            << convert_command_inset_arg(p.verbatim_item())
3283                            << "\"\n";
3284                         end_inset(os);
3285                 }
3286
3287                 else if (use_jurabib &&
3288                          is_known(t.cs(), known_jurabib_commands) &&
3289                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3290                         context.check_layout(os);
3291                         string command = t.cs();
3292                         if (p.next_token().asInput() == "*") {
3293                                 command += '*';
3294                                 p.get_token();
3295                         }
3296                         char argumentOrder = '\0';
3297                         vector<string> const options =
3298                                 preamble.getPackageOptions("jurabib");
3299                         if (find(options.begin(), options.end(),
3300                                       "natbiborder") != options.end())
3301                                 argumentOrder = 'n';
3302                         else if (find(options.begin(), options.end(),
3303                                            "jurabiborder") != options.end())
3304                                 argumentOrder = 'j';
3305
3306                         // text before the citation
3307                         string before;
3308                         // text after the citation
3309                         string after;
3310                         get_cite_arguments(p, argumentOrder != 'j', before, after);
3311
3312                         string const citation = p.verbatim_item();
3313                         if (!before.empty() && argumentOrder == '\0') {
3314                                 cerr << "Warning: Assuming argument order "
3315                                         "of jurabib version 0.6 for\n'"
3316                                      << command << before << after << '{'
3317                                      << citation << "}'.\n"
3318                                         "Add 'jurabiborder' to the jurabib "
3319                                         "package options if you used an\n"
3320                                         "earlier jurabib version." << endl;
3321                         }
3322                         if (!after.empty()) {
3323                                 after.erase(0, 1);
3324                                 after.erase(after.length() - 1, 1);
3325                         }
3326                         if (!before.empty()) {
3327                                 before.erase(0, 1);
3328                                 before.erase(before.length() - 1, 1);
3329                         }
3330                         begin_command_inset(os, "citation", command);
3331                         os << "after " << '"' << after << '"' << "\n";
3332                         os << "before " << '"' << before << '"' << "\n";
3333                         os << "key " << '"' << citation << '"' << "\n";
3334                         end_inset(os);
3335                 }
3336
3337                 else if (t.cs() == "cite"
3338                         || t.cs() == "nocite") {
3339                         context.check_layout(os);
3340                         string after = convert_command_inset_arg(p.getArg('[', ']'));
3341                         string key = convert_command_inset_arg(p.verbatim_item());
3342                         // store the case that it is "\nocite{*}" to use it later for
3343                         // the BibTeX inset
3344                         if (key != "*") {
3345                                 begin_command_inset(os, "citation", t.cs());
3346                                 os << "after " << '"' << after << '"' << "\n";
3347                                 os << "key " << '"' << key << '"' << "\n";
3348                                 end_inset(os);
3349                         } else if (t.cs() == "nocite")
3350                                 btprint = key;
3351                 }
3352
3353                 else if (t.cs() == "index" ||
3354                          (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3355                         context.check_layout(os);
3356                         string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3357                                 p.getArg('[', ']') : "";
3358                         string const kind = arg.empty() ? "idx" : arg;
3359                         begin_inset(os, "Index ");
3360                         os << kind << "\nstatus collapsed\n";
3361                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3362                         end_inset(os);
3363                         if (kind != "idx")
3364                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3365                 }
3366
3367                 else if (t.cs() == "nomenclature") {
3368                         context.check_layout(os);
3369                         begin_command_inset(os, "nomenclature", "nomenclature");
3370                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3371                         if (!prefix.empty())
3372                                 os << "prefix " << '"' << prefix << '"' << "\n";
3373                         os << "symbol " << '"'
3374                            << convert_command_inset_arg(p.verbatim_item());
3375                         os << "\"\ndescription \""
3376                            << convert_command_inset_arg(p.verbatim_item())
3377                            << "\"\n";
3378                         end_inset(os);
3379                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3380                 }
3381
3382                 else if (t.cs() == "label") {
3383                         context.check_layout(os);
3384                         begin_command_inset(os, "label", "label");
3385                         os << "name \""
3386                            << convert_command_inset_arg(p.verbatim_item())
3387                            << "\"\n";
3388                         end_inset(os);
3389                 }
3390
3391                 else if (t.cs() == "printindex") {
3392                         context.check_layout(os);
3393                         begin_command_inset(os, "index_print", "printindex");
3394                         os << "type \"idx\"\n";
3395                         end_inset(os);
3396                         skip_spaces_braces(p);
3397                         preamble.registerAutomaticallyLoadedPackage("makeidx");
3398                         if (preamble.use_indices() == "true")
3399                                 preamble.registerAutomaticallyLoadedPackage("splitidx");
3400                 }
3401
3402                 else if (t.cs() == "printnomenclature") {
3403                         string width = "";
3404                         string width_type = "";
3405                         context.check_layout(os);
3406                         begin_command_inset(os, "nomencl_print", "printnomenclature");
3407                         // case of a custom width
3408                         if (p.hasOpt()) {
3409                                 width = p.getArg('[', ']');
3410                                 width = translate_len(width);
3411                                 width_type = "custom";
3412                         }
3413                         // case of no custom width
3414                         // the case of no custom width but the width set
3415                         // via \settowidth{\nomlabelwidth}{***} cannot be supported
3416                         // because the user could have set anything, not only the width
3417                         // of the longest label (which would be width_type = "auto")
3418                         string label = convert_command_inset_arg(p.getArg('{', '}'));
3419                         if (label.empty() && width_type.empty())
3420                                 width_type = "none";
3421                         os << "set_width \"" << width_type << "\"\n";
3422                         if (width_type == "custom")
3423                                 os << "width \"" << width << '\"';
3424                         end_inset(os);
3425                         skip_spaces_braces(p);
3426                         preamble.registerAutomaticallyLoadedPackage("nomencl");
3427                 }
3428
3429                 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3430                         context.check_layout(os);
3431                         begin_inset(os, "script ");
3432                         os << t.cs().substr(4) << '\n';
3433                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3434                         end_inset(os);
3435                         if (t.cs() == "textsubscript")
3436                                 preamble.registerAutomaticallyLoadedPackage("subscript");
3437                 }
3438
3439                 else if ((where = is_known(t.cs(), known_quotes))) {
3440                         context.check_layout(os);
3441                         begin_inset(os, "Quotes ");
3442                         os << known_coded_quotes[where - known_quotes];
3443                         end_inset(os);
3444                         // LyX adds {} after the quote, so we have to eat
3445                         // spaces here if there are any before a possible
3446                         // {} pair.
3447                         eat_whitespace(p, os, context, false);
3448                         skip_braces(p);
3449                 }
3450
3451                 else if ((where = is_known(t.cs(), known_sizes)) &&
3452                          context.new_layout_allowed) {
3453                         context.check_layout(os);
3454                         TeXFont const oldFont = context.font;
3455                         context.font.size = known_coded_sizes[where - known_sizes];
3456                         output_font_change(os, oldFont, context.font);
3457                         eat_whitespace(p, os, context, false);
3458                 }
3459
3460                 else if ((where = is_known(t.cs(), known_font_families)) &&
3461                          context.new_layout_allowed) {
3462                         context.check_layout(os);
3463                         TeXFont const oldFont = context.font;
3464                         context.font.family =
3465                                 known_coded_font_families[where - known_font_families];
3466                         output_font_change(os, oldFont, context.font);
3467                         eat_whitespace(p, os, context, false);
3468                 }
3469
3470                 else if ((where = is_known(t.cs(), known_font_series)) &&
3471                          context.new_layout_allowed) {
3472                         context.check_layout(os);
3473                         TeXFont const oldFont = context.font;
3474                         context.font.series =
3475                                 known_coded_font_series[where - known_font_series];
3476                         output_font_change(os, oldFont, context.font);
3477                         eat_whitespace(p, os, context, false);
3478                 }
3479
3480                 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3481                          context.new_layout_allowed) {
3482                         context.check_layout(os);
3483                         TeXFont const oldFont = context.font;
3484                         context.font.shape =
3485                                 known_coded_font_shapes[where - known_font_shapes];
3486                         output_font_change(os, oldFont, context.font);
3487                         eat_whitespace(p, os, context, false);
3488                 }
3489                 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3490                          context.new_layout_allowed) {
3491                         context.check_layout(os);
3492                         TeXFont const oldFont = context.font;
3493                         context.font.init();
3494                         context.font.size = oldFont.size;
3495                         context.font.family =
3496                                 known_coded_font_families[where - known_old_font_families];
3497                         output_font_change(os, oldFont, context.font);
3498                         eat_whitespace(p, os, context, false);
3499                 }
3500
3501                 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3502                          context.new_layout_allowed) {
3503                         context.check_layout(os);
3504                         TeXFont const oldFont = context.font;
3505                         context.font.init();
3506                         context.font.size = oldFont.size;
3507                         context.font.series =
3508                                 known_coded_font_series[where - known_old_font_series];
3509                         output_font_change(os, oldFont, context.font);
3510                         eat_whitespace(p, os, context, false);
3511                 }
3512
3513                 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3514                          context.new_layout_allowed) {
3515                         context.check_layout(os);
3516                         TeXFont const oldFont = context.font;
3517                         context.font.init();
3518                         context.font.size = oldFont.size;
3519                         context.font.shape =
3520                                 known_coded_font_shapes[where - known_old_font_shapes];
3521                         output_font_change(os, oldFont, context.font);
3522                         eat_whitespace(p, os, context, false);
3523                 }
3524
3525                 else if (t.cs() == "selectlanguage") {
3526                         context.check_layout(os);
3527                         // save the language for the case that a
3528                         // \foreignlanguage is used
3529                         context.font.language = babel2lyx(p.verbatim_item());
3530                         os << "\n\\lang " << context.font.language << "\n";
3531                 }
3532
3533                 else if (t.cs() == "foreignlanguage") {
3534                         string const lang = babel2lyx(p.verbatim_item());
3535                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3536                                               context, "\\lang",
3537                                               context.font.language, lang);
3538                 }
3539                 
3540                 else if (prefixIs(t.cs(), "text") 
3541                          && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3542                         // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3543                         string lang;
3544                         // We have to output the whole command if it has an option
3545                         // because LyX doesn't support this yet, see bug #8214,
3546                         // only if there is a single option specifying a variant, we can handle it.
3547                         if (p.hasOpt()) {
3548                                 string langopts = p.getOpt();
3549                                 // check if the option contains a variant, if yes, extract it
3550                                 string::size_type pos_var = langopts.find("variant");
3551                                 string::size_type i = langopts.find(',');
3552                                 string::size_type k = langopts.find('=', pos_var);
3553                                 if (pos_var != string::npos && i == string::npos) {
3554                                         string variant;
3555                                         variant = langopts.substr(k + 1, langopts.length() - k - 2);
3556                                         lang = preamble.polyglossia2lyx(variant);
3557                                         parse_text_attributes(p, os, FLAG_ITEM, outer,
3558                                                                   context, "\\lang",
3559                                                                   context.font.language, lang);
3560                                 } else
3561                                         handle_ert(os, t.asInput() + langopts, context);
3562                         } else {
3563                                 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3564                                 parse_text_attributes(p, os, FLAG_ITEM, outer,
3565                                                           context, "\\lang",
3566                                                           context.font.language, lang);
3567                         }
3568                 }
3569
3570                 else if (t.cs() == "inputencoding") {
3571                         // nothing to write here
3572                         string const enc = subst(p.verbatim_item(), "\n", " ");
3573                         p.setEncoding(enc);
3574                 }
3575
3576                 else if ((where = is_known(t.cs(), known_special_chars))) {
3577                         context.check_layout(os);
3578                         os << "\\SpecialChar \\"
3579                            << known_coded_special_chars[where - known_special_chars]
3580                            << '\n';
3581                         skip_spaces_braces(p);
3582                 }
3583
3584                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3585                         context.check_layout(os);
3586                         os << "\\SpecialChar \\nobreakdash-\n";
3587                         p.get_token();
3588                 }
3589
3590                 else if (t.cs() == "textquotedbl") {
3591                         context.check_layout(os);
3592                         os << "\"";
3593                         skip_braces(p);
3594                 }
3595
3596                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3597                         context.check_layout(os);
3598                         os << "\\SpecialChar \\@.\n";
3599                         p.get_token();
3600                 }
3601
3602                 else if (t.cs() == "-") {
3603                         context.check_layout(os);
3604                         os << "\\SpecialChar \\-\n";
3605                 }
3606
3607                 else if (t.cs() == "textasciitilde") {
3608                         context.check_layout(os);
3609                         os << '~';
3610                         skip_spaces_braces(p);
3611                 }
3612
3613                 else if (t.cs() == "textasciicircum") {
3614                         context.check_layout(os);
3615                         os << '^';
3616                         skip_spaces_braces(p);
3617                 }
3618
3619                 else if (t.cs() == "textbackslash") {
3620                         context.check_layout(os);
3621                         os << "\n\\backslash\n";
3622                         skip_spaces_braces(p);
3623                 }
3624
3625                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3626                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3627                             || t.cs() == "%") {
3628                         context.check_layout(os);
3629                         os << t.cs();
3630                 }
3631
3632                 else if (t.cs() == "char") {
3633                         context.check_layout(os);
3634                         if (p.next_token().character() == '`') {
3635                                 p.get_token();
3636                                 if (p.next_token().cs() == "\"") {
3637                                         p.get_token();
3638                                         os << '"';
3639                                         skip_braces(p);
3640                                 } else {
3641                                         handle_ert(os, "\\char`", context);
3642                                 }
3643                         } else {
3644                                 handle_ert(os, "\\char", context);
3645                         }
3646                 }
3647
3648                 else if (t.cs() == "verb") {
3649                         context.check_layout(os);
3650                         char const delimiter = p.next_token().character();
3651                         string const arg = p.getArg(delimiter, delimiter);
3652                         ostringstream oss;
3653                         oss << "\\verb" << delimiter << arg << delimiter;
3654                         handle_ert(os, oss.str(), context);
3655                 }
3656
3657                 // Problem: \= creates a tabstop inside the tabbing environment
3658                 // and else an accent. In the latter case we really would want
3659                 // \={o} instead of \= o.
3660                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3661                         handle_ert(os, t.asInput(), context);
3662
3663                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3664                 else if (t.cs().size() == 1
3665                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3666                         context.check_layout(os);
3667                         // try to see whether the string is in unicodesymbols
3668                         bool termination;
3669                         docstring rem;
3670                         string command = t.asInput() + "{"
3671                                 + trimSpaceAndEol(p.verbatim_item())
3672                                 + "}";
3673                         set<string> req;
3674                         docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3675                                 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3676                                 termination, rem, &req);
3677                         if (!s.empty()) {
3678                                 if (!rem.empty())
3679                                         cerr << "When parsing " << command
3680                                              << ", result is " << to_utf8(s)
3681                                              << "+" << to_utf8(rem) << endl;
3682                                 os << to_utf8(s);
3683                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3684                                         preamble.registerAutomaticallyLoadedPackage(*it);
3685                         } else
3686                                 // we did not find a non-ert version
3687                                 handle_ert(os, command, context);
3688                 }
3689
3690                 else if (t.cs() == "\\") {
3691                         context.check_layout(os);
3692                         if (p.hasOpt())
3693                                 handle_ert(os, "\\\\" + p.getOpt(), context);
3694                         else if (p.next_token().asInput() == "*") {
3695                                 p.get_token();
3696                                 // getOpt() eats the following space if there
3697                                 // is no optional argument, but that is OK
3698                                 // here since it has no effect in the output.
3699                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
3700                         }
3701                         else {
3702                                 begin_inset(os, "Newline newline");
3703                                 end_inset(os);
3704                         }
3705                 }
3706
3707                 else if (t.cs() == "newline" ||
3708                          (t.cs() == "linebreak" && !p.hasOpt())) {
3709                         context.check_layout(os);
3710                         begin_inset(os, "Newline ");
3711                         os << t.cs();
3712                         end_inset(os);
3713                         skip_spaces_braces(p);
3714                 }
3715
3716                 else if (t.cs() == "input" || t.cs() == "include"
3717                          || t.cs() == "verbatiminput") {
3718                         string name = t.cs();
3719                         if (t.cs() == "verbatiminput"
3720                             && p.next_token().asInput() == "*")
3721                                 name += p.get_token().asInput();
3722                         context.check_layout(os);
3723                         string filename(normalize_filename(p.getArg('{', '}')));
3724                         string const path = getMasterFilePath();
3725                         // We want to preserve relative / absolute filenames,
3726                         // therefore path is only used for testing
3727                         if ((t.cs() == "include" || t.cs() == "input") &&
3728                             !makeAbsPath(filename, path).exists()) {
3729                                 // The file extension is probably missing.
3730                                 // Now try to find it out.
3731                                 string const tex_name =
3732                                         find_file(filename, path,
3733                                                   known_tex_extensions);
3734                                 if (!tex_name.empty())
3735                                         filename = tex_name;
3736                         }
3737                         bool external = false;
3738                         string outname;
3739                         if (makeAbsPath(filename, path).exists()) {
3740                                 string const abstexname =
3741                                         makeAbsPath(filename, path).absFileName();
3742                                 string const abslyxname =
3743                                         changeExtension(abstexname, ".lyx");
3744                                 string const absfigname =
3745                                         changeExtension(abstexname, ".fig");
3746                                 fix_relative_filename(filename);
3747                                 string const lyxname =
3748                                         changeExtension(filename, ".lyx");
3749                                 bool xfig = false;
3750                                 external = FileName(absfigname).exists();
3751                                 if (t.cs() == "input") {
3752                                         string const ext = getExtension(abstexname);
3753
3754                                         // Combined PS/LaTeX:
3755                                         // x.eps, x.pstex_t (old xfig)
3756                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3757                                         FileName const absepsname(
3758                                                 changeExtension(abstexname, ".eps"));
3759                                         FileName const abspstexname(
3760                                                 changeExtension(abstexname, ".pstex"));
3761                                         bool const xfigeps =
3762                                                 (absepsname.exists() ||
3763                                                  abspstexname.exists()) &&
3764                                                 ext == "pstex_t";
3765
3766                                         // Combined PDF/LaTeX:
3767                                         // x.pdf, x.pdftex_t (old xfig)
3768                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3769                                         FileName const abspdfname(
3770                                                 changeExtension(abstexname, ".pdf"));
3771                                         bool const xfigpdf =
3772                                                 abspdfname.exists() &&
3773                                                 (ext == "pdftex_t" || ext == "pdf_t");
3774                                         if (xfigpdf)
3775                                                 pdflatex = true;
3776
3777                                         // Combined PS/PDF/LaTeX:
3778                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3779                                         string const absbase2(
3780                                                 removeExtension(abstexname) + "_pspdftex");
3781                                         FileName const abseps2name(
3782                                                 addExtension(absbase2, ".eps"));
3783                                         FileName const abspdf2name(
3784                                                 addExtension(absbase2, ".pdf"));
3785                                         bool const xfigboth =
3786                                                 abspdf2name.exists() &&
3787                                                 abseps2name.exists() && ext == "pspdftex";
3788
3789                                         xfig = xfigpdf || xfigeps || xfigboth;
3790                                         external = external && xfig;
3791                                 }
3792                                 if (external) {
3793                                         outname = changeExtension(filename, ".fig");
3794                                 } else if (xfig) {
3795                                         // Don't try to convert, the result
3796                                         // would be full of ERT.
3797                                         outname = filename;
3798                                 } else if (t.cs() != "verbatiminput" &&
3799                                     tex2lyx(abstexname, FileName(abslyxname),
3800                                             p.getEncoding())) {
3801                                         outname = lyxname;
3802                                 } else {
3803                                         outname = filename;
3804                                 }
3805                         } else {
3806                                 cerr << "Warning: Could not find included file '"
3807                                      << filename << "'." << endl;
3808                                 outname = filename;
3809                         }
3810                         if (external) {
3811                                 begin_inset(os, "External\n");
3812                                 os << "\ttemplate XFig\n"
3813                                    << "\tfilename " << outname << '\n';
3814                                 registerExternalTemplatePackages("XFig");
3815                         } else {
3816                                 begin_command_inset(os, "include", name);
3817                                 os << "preview false\n"
3818                                       "filename \"" << outname << "\"\n";
3819                                 if (t.cs() == "verbatiminput")
3820                                         preamble.registerAutomaticallyLoadedPackage("verbatim");
3821                         }
3822                         end_inset(os);
3823                 }
3824
3825                 else if (t.cs() == "bibliographystyle") {
3826                         // store new bibliographystyle
3827                         bibliographystyle = p.verbatim_item();
3828                         // If any other command than \bibliography and
3829                         // \nocite{*} follows, we need to output the style
3830                         // (because it might be used by that command).
3831                         // Otherwise, it will automatically be output by LyX.
3832                         p.pushPosition();
3833                         bool output = true;
3834                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3835                                 if (t2.cat() == catBegin)
3836                                         break;
3837                                 if (t2.cat() != catEscape)
3838                                         continue;
3839                                 if (t2.cs() == "nocite") {
3840                                         if (p.getArg('{', '}') == "*")
3841                                                 continue;
3842                                 } else if (t2.cs() == "bibliography")
3843                                         output = false;
3844                                 break;
3845                         }
3846                         p.popPosition();
3847                         if (output) {
3848                                 handle_ert(os,
3849                                         "\\bibliographystyle{" + bibliographystyle + '}',
3850                                         context);
3851                         }
3852                 }
3853
3854                 else if (t.cs() == "bibliography") {
3855                         context.check_layout(os);
3856                         begin_command_inset(os, "bibtex", "bibtex");
3857                         if (!btprint.empty()) {
3858                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3859                                 // clear the string because the next BibTeX inset can be without the
3860                                 // \nocite{*} option
3861                                 btprint.clear();
3862                         }
3863                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3864                         // Do we have a bibliographystyle set?
3865                         if (!bibliographystyle.empty())
3866                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3867                         end_inset(os);
3868                 }
3869
3870                 else if (t.cs() == "parbox") {
3871                         // Test whether this is an outer box of a shaded box
3872                         p.pushPosition();
3873                         // swallow arguments
3874                         while (p.hasOpt()) {
3875                                 p.getArg('[', ']');
3876                                 p.skip_spaces(true);
3877                         }
3878                         p.getArg('{', '}');
3879                         p.skip_spaces(true);
3880                         // eat the '{'
3881                         if (p.next_token().cat() == catBegin)
3882                                 p.get_token();
3883                         p.skip_spaces(true);
3884                         Token to = p.get_token();
3885                         bool shaded = false;
3886                         if (to.asInput() == "\\begin") {
3887                                 p.skip_spaces(true);
3888                                 if (p.getArg('{', '}') == "shaded")
3889                                         shaded = true;
3890                         }
3891                         p.popPosition();
3892                         if (shaded) {
3893                                 parse_outer_box(p, os, FLAG_ITEM, outer,
3894                                                 context, "parbox", "shaded");
3895                         } else
3896                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3897                                           "", "", t.cs());
3898                 }
3899
3900                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3901                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3902                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3903
3904                 else if (t.cs() == "framebox") {
3905                         if (p.next_token().character() == '(') {
3906                                 //the syntax is: \framebox(x,y)[position]{content}
3907                                 string arg = t.asInput();
3908                                 arg += p.getFullParentheseArg();
3909                                 arg += p.getFullOpt();
3910                                 eat_whitespace(p, os, context, false);
3911                                 handle_ert(os, arg + '{', context);
3912                                 eat_whitespace(p, os, context, false);
3913                                 parse_text(p, os, FLAG_ITEM, outer, context);
3914                                 handle_ert(os, "}", context);
3915                         } else {
3916                                 string special = p.getFullOpt();
3917                                 special += p.getOpt();
3918                                 // LyX does not yet support \framebox without any option
3919                                 if (!special.empty())
3920                                         parse_outer_box(p, os, FLAG_ITEM, outer,
3921                                                         context, t.cs(), special);
3922                                 else {
3923                                         eat_whitespace(p, os, context, false);
3924                                         handle_ert(os, "\\framebox{", context);
3925                                         eat_whitespace(p, os, context, false);
3926                                         parse_text(p, os, FLAG_ITEM, outer, context);
3927                                         handle_ert(os, "}", context);
3928                                 }
3929                         }
3930                 }
3931
3932                 //\makebox() is part of the picture environment and different from \makebox{}
3933                 //\makebox{} will be parsed by parse_box
3934                 else if (t.cs() == "makebox") {
3935                         if (p.next_token().character() == '(') {
3936                                 //the syntax is: \makebox(x,y)[position]{content}
3937                                 string arg = t.asInput();
3938                                 arg += p.getFullParentheseArg();
3939                                 arg += p.getFullOpt();
3940                                 eat_whitespace(p, os, context, false);
3941                                 handle_ert(os, arg + '{', context);
3942                                 eat_whitespace(p, os, context, false);
3943                                 parse_text(p, os, FLAG_ITEM, outer, context);
3944                                 handle_ert(os, "}", context);
3945                         } else
3946                                 //the syntax is: \makebox[width][position]{content}
3947                                 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3948                                           "", "", t.cs());
3949                 }
3950
3951                 else if (t.cs() == "smallskip" ||
3952                          t.cs() == "medskip" ||
3953                          t.cs() == "bigskip" ||
3954                          t.cs() == "vfill") {
3955                         context.check_layout(os);
3956                         begin_inset(os, "VSpace ");
3957                         os << t.cs();
3958                         end_inset(os);
3959                         skip_spaces_braces(p);
3960                 }
3961
3962                 else if ((where = is_known(t.cs(), known_spaces))) {
3963                         context.check_layout(os);
3964                         begin_inset(os, "space ");
3965                         os << '\\' << known_coded_spaces[where - known_spaces]
3966                            << '\n';
3967                         end_inset(os);
3968                         // LaTeX swallows whitespace after all spaces except
3969                         // "\\,". We have to do that here, too, because LyX
3970                         // adds "{}" which would make the spaces significant.
3971                         if (t.cs() !=  ",")
3972                                 eat_whitespace(p, os, context, false);
3973                         // LyX adds "{}" after all spaces except "\\ " and
3974                         // "\\,", so we have to remove "{}".
3975                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3976                         // remove the braces after "\\,", too.
3977                         if (t.cs() != " ")
3978                                 skip_braces(p);
3979                 }
3980
3981                 else if (t.cs() == "newpage" ||
3982                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3983                          t.cs() == "clearpage" ||
3984                          t.cs() == "cleardoublepage") {
3985                         context.check_layout(os);
3986                         begin_inset(os, "Newpage ");
3987                         os << t.cs();
3988                         end_inset(os);
3989                         skip_spaces_braces(p);
3990                 }
3991
3992                 else if (t.cs() == "DeclareRobustCommand" ||
3993                          t.cs() == "DeclareRobustCommandx" ||
3994                          t.cs() == "newcommand" ||
3995                          t.cs() == "newcommandx" ||
3996                          t.cs() == "providecommand" ||
3997                          t.cs() == "providecommandx" ||
3998                          t.cs() == "renewcommand" ||
3999                          t.cs() == "renewcommandx") {
4000                         // DeclareRobustCommand, DeclareRobustCommandx,
4001                         // providecommand and providecommandx could be handled
4002                         // by parse_command(), but we need to call
4003                         // add_known_command() here.
4004                         string name = t.asInput();
4005                         if (p.next_token().asInput() == "*") {
4006                                 // Starred form. Eat '*'
4007                                 p.get_token();
4008                                 name += '*';
4009                         }
4010                         string const command = p.verbatim_item();
4011                         string const opt1 = p.getFullOpt();
4012                         string const opt2 = p.getFullOpt();
4013                         add_known_command(command, opt1, !opt2.empty());
4014                         string const ert = name + '{' + command + '}' +
4015                                            opt1 + opt2 +
4016                                            '{' + p.verbatim_item() + '}';
4017
4018                         if (t.cs() == "DeclareRobustCommand" ||
4019                             t.cs() == "DeclareRobustCommandx" ||
4020                             t.cs() == "providecommand" ||
4021                             t.cs() == "providecommandx" ||
4022                             name[name.length()-1] == '*')
4023                                 handle_ert(os, ert, context);
4024                         else {
4025                                 context.check_layout(os);
4026                                 begin_inset(os, "FormulaMacro");
4027                                 os << "\n" << ert;
4028                                 end_inset(os);
4029                         }
4030                 }
4031
4032                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4033                         // let could be handled by parse_command(),
4034                         // but we need to call add_known_command() here.
4035                         string ert = t.asInput();
4036                         string name;
4037                         p.skip_spaces();
4038                         if (p.next_token().cat() == catBegin) {
4039                                 name = p.verbatim_item();
4040                                 ert += '{' + name + '}';
4041                         } else {
4042                                 name = p.verbatim_item();
4043                                 ert += name;
4044                         }
4045                         string command;
4046                         p.skip_spaces();
4047                         if (p.next_token().cat() == catBegin) {
4048                                 command = p.verbatim_item();
4049                                 ert += '{' + command + '}';
4050                         } else {
4051                                 command = p.verbatim_item();
4052                                 ert += command;
4053                         }
4054                         // If command is known, make name known too, to parse
4055                         // its arguments correctly. For this reason we also
4056                         // have commands in syntax.default that are hardcoded.
4057                         CommandMap::iterator it = known_commands.find(command);
4058                         if (it != known_commands.end())
4059                                 known_commands[t.asInput()] = it->second;
4060                         handle_ert(os, ert, context);
4061                 }
4062
4063                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4064                         bool starred = false;
4065                         if (p.next_token().asInput() == "*") {
4066                                 p.get_token();
4067                                 starred = true;
4068                         }
4069                         string name = t.asInput();
4070                         string const length = p.verbatim_item();
4071                         string unit;
4072                         string valstring;
4073                         bool valid = splitLatexLength(length, valstring, unit);
4074                         bool known_hspace = false;
4075                         bool known_vspace = false;
4076                         bool known_unit = false;
4077                         double value;
4078                         if (valid) {
4079                                 istringstream iss(valstring);
4080                                 iss >> value;
4081                                 if (value == 1.0) {
4082                                         if (t.cs()[0] == 'h') {
4083                                                 if (unit == "\\fill") {
4084                                                         if (!starred) {
4085                                                                 unit = "";
4086                                                                 name = "\\hfill";
4087                                                         }
4088                                                         known_hspace = true;
4089                                                 }
4090                                         } else {
4091                                                 if (unit == "\\smallskipamount") {
4092                                                         unit = "smallskip";
4093                                                         known_vspace = true;
4094                                                 } else if (unit == "\\medskipamount") {
4095                                                         unit = "medskip";
4096                                                         known_vspace = true;
4097                                                 } else if (unit == "\\bigskipamount") {
4098                                                         unit = "bigskip";
4099                                                         known_vspace = true;
4100                                                 } else if (unit == "\\fill") {
4101                                                         unit = "vfill";
4102                                                         known_vspace = true;
4103                                                 }
4104                                         }
4105                                 }
4106                                 if (!known_hspace && !known_vspace) {
4107                                         switch (unitFromString(unit)) {
4108                                         case Length::SP:
4109                                         case Length::PT:
4110                                         case Length::BP:
4111                                         case Length::DD:
4112                                         case Length::MM:
4113                                         case Length::PC:
4114                                         case Length::CC:
4115                                         case Length::CM:
4116                                         case Length::IN:
4117                                         case Length::EX:
4118                                         case Length::EM:
4119                                         case Length::MU:
4120                                                 known_unit = true;
4121                                                 break;
4122                                         default:
4123                                                 break;
4124                                         }
4125                                 }
4126                         }
4127
4128                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
4129                                 // Literal horizontal length or known variable
4130                                 context.check_layout(os);
4131                                 begin_inset(os, "space ");
4132                                 os << name;
4133                                 if (starred)
4134                                         os << '*';
4135                                 os << '{';
4136                                 if (known_hspace)
4137                                         os << unit;
4138                                 os << "}";
4139                                 if (known_unit && !known_hspace)
4140                                         os << "\n\\length "
4141                                            << translate_len(length);
4142                                 end_inset(os);
4143                         } else if (known_unit || known_vspace) {
4144                                 // Literal vertical length or known variable
4145                                 context.check_layout(os);
4146                                 begin_inset(os, "VSpace ");
4147                                 if (known_unit)
4148                                         os << value;
4149                                 os << unit;
4150                                 if (starred)
4151                                         os << '*';
4152                                 end_inset(os);
4153                         } else {
4154                                 // LyX can't handle other length variables in Inset VSpace/space
4155                                 if (starred)
4156                                         name += '*';
4157                                 if (valid) {
4158                                         if (value == 1.0)
4159                                                 handle_ert(os, name + '{' + unit + '}', context);
4160                                         else if (value == -1.0)
4161                                                 handle_ert(os, name + "{-" + unit + '}', context);
4162                                         else
4163                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
4164                                 } else
4165                                         handle_ert(os, name + '{' + length + '}', context);
4166                         }
4167                 }
4168
4169                 // The single '=' is meant here.
4170                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4171                         p.skip_spaces();
4172                         context.check_layout(os);
4173                         begin_inset(os, "Flex ");
4174                         os << to_utf8(newinsetlayout->name()) << '\n'
4175                            << "status collapsed\n";
4176                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4177                         end_inset(os);
4178                 }
4179
4180                 else if (t.cs() == "includepdf") {
4181                         p.skip_spaces();
4182                         string const arg = p.getArg('[', ']');
4183                         map<string, string> opts;
4184                         vector<string> keys;
4185                         split_map(arg, opts, keys);
4186                         string name = normalize_filename(p.verbatim_item());
4187                         string const path = getMasterFilePath();
4188                         // We want to preserve relative / absolute filenames,
4189                         // therefore path is only used for testing
4190                         if (!makeAbsPath(name, path).exists()) {
4191                                 // The file extension is probably missing.
4192                                 // Now try to find it out.
4193                                 char const * const pdfpages_format[] = {"pdf", 0};
4194                                 string const pdftex_name =
4195                                         find_file(name, path, pdfpages_format);
4196                                 if (!pdftex_name.empty()) {
4197                                         name = pdftex_name;
4198                                         pdflatex = true;
4199                                 }
4200                         }
4201                         if (makeAbsPath(name, path).exists())
4202                                 fix_relative_filename(name);
4203                         else
4204                                 cerr << "Warning: Could not find file '"
4205                                      << name << "'." << endl;
4206                         // write output
4207                         context.check_layout(os);
4208                         begin_inset(os, "External\n\ttemplate ");
4209                         os << "PDFPages\n\tfilename "
4210                            << name << "\n";
4211                         // parse the options
4212                         if (opts.find("pages") != opts.end())
4213                                 os << "\textra LaTeX \"pages="
4214                                    << opts["pages"] << "\"\n";
4215                         if (opts.find("angle") != opts.end())
4216                                 os << "\trotateAngle "
4217                                    << opts["angle"] << '\n';
4218                         if (opts.find("origin") != opts.end()) {
4219                                 ostringstream ss;
4220                                 string const opt = opts["origin"];
4221                                 if (opt == "tl") ss << "topleft";
4222                                 if (opt == "bl") ss << "bottomleft";
4223                                 if (opt == "Bl") ss << "baselineleft";
4224                                 if (opt == "c") ss << "center";
4225                                 if (opt == "tc") ss << "topcenter";
4226                                 if (opt == "bc") ss << "bottomcenter";
4227                                 if (opt == "Bc") ss << "baselinecenter";
4228                                 if (opt == "tr") ss << "topright";
4229                                 if (opt == "br") ss << "bottomright";
4230                                 if (opt == "Br") ss << "baselineright";
4231                                 if (!ss.str().empty())
4232                                         os << "\trotateOrigin " << ss.str() << '\n';
4233                                 else
4234                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4235                         }
4236                         if (opts.find("width") != opts.end())
4237                                 os << "\twidth "
4238                                    << translate_len(opts["width"]) << '\n';
4239                         if (opts.find("height") != opts.end())
4240                                 os << "\theight "
4241                                    << translate_len(opts["height"]) << '\n';
4242                         if (opts.find("keepaspectratio") != opts.end())
4243                                 os << "\tkeepAspectRatio\n";
4244                         end_inset(os);
4245                         context.check_layout(os);
4246                         registerExternalTemplatePackages("PDFPages");
4247                 }
4248
4249                 else if (t.cs() == "loadgame") {
4250                         p.skip_spaces();
4251                         string name = normalize_filename(p.verbatim_item());
4252                         string const path = getMasterFilePath();
4253                         // We want to preserve relative / absolute filenames,
4254                         // therefore path is only used for testing
4255                         if (!makeAbsPath(name, path).exists()) {
4256                                 // The file extension is probably missing.
4257                                 // Now try to find it out.
4258                                 char const * const lyxskak_format[] = {"fen", 0};
4259                                 string const lyxskak_name =
4260                                         find_file(name, path, lyxskak_format);
4261                                 if (!lyxskak_name.empty())
4262                                         name = lyxskak_name;
4263                         }
4264                         if (makeAbsPath(name, path).exists())
4265                                 fix_relative_filename(name);
4266                         else
4267                                 cerr << "Warning: Could not find file '"
4268                                      << name << "'." << endl;
4269                         context.check_layout(os);
4270                         begin_inset(os, "External\n\ttemplate ");
4271                         os << "ChessDiagram\n\tfilename "
4272                            << name << "\n";
4273                         end_inset(os);
4274                         context.check_layout(os);
4275                         // after a \loadgame follows a \showboard
4276                         if (p.get_token().asInput() == "showboard")
4277                                 p.get_token();
4278                         registerExternalTemplatePackages("ChessDiagram");
4279                 }
4280
4281                 else {
4282                         // try to see whether the string is in unicodesymbols
4283                         // Only use text mode commands, since we are in text mode here,
4284                         // and math commands may be invalid (bug 6797)
4285                         bool termination;
4286                         docstring rem;
4287                         set<string> req;
4288                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4289                                         Encodings::TEXT_CMD, termination, rem, &req);
4290                         if (!s.empty()) {
4291                                 if (!rem.empty())
4292                                         cerr << "When parsing " << t.cs()
4293                                              << ", result is " << to_utf8(s)
4294                                              << "+" << to_utf8(rem) << endl;
4295                                 context.check_layout(os);
4296                                 os << to_utf8(s);
4297                                 if (termination)
4298                                         skip_spaces_braces(p);
4299                                 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4300                                         preamble.registerAutomaticallyLoadedPackage(*it);
4301                         }
4302                         //cerr << "#: " << t << " mode: " << mode << endl;
4303                         // heuristic: read up to next non-nested space
4304                         /*
4305                         string s = t.asInput();
4306                         string z = p.verbatim_item();
4307                         while (p.good() && z != " " && z.size()) {
4308                                 //cerr << "read: " << z << endl;
4309                                 s += z;
4310                                 z = p.verbatim_item();
4311                         }
4312                         cerr << "found ERT: " << s << endl;
4313                         handle_ert(os, s + ' ', context);
4314                         */
4315                         else {
4316                                 string name = t.asInput();
4317                                 if (p.next_token().asInput() == "*") {
4318                                         // Starred commands like \vspace*{}
4319                                         p.get_token();  // Eat '*'
4320                                         name += '*';
4321                                 }
4322                                 if (!parse_command(name, p, os, outer, context))
4323                                         handle_ert(os, name, context);
4324                         }
4325                 }
4326
4327                 if (flags & FLAG_LEAVE) {
4328                         flags &= ~FLAG_LEAVE;
4329                         break;
4330                 }
4331         }
4332 }
4333
4334 // }])
4335
4336
4337 } // namespace lyx