]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
930b318c53e8e7e2360c98079c49f7c882c74c50
[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 "Layout.h"
23 #include "Length.h"
24
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
30
31 #include <algorithm>
32 #include <iostream>
33 #include <map>
34 #include <sstream>
35 #include <vector>
36
37 using namespace std;
38 using namespace lyx::support;
39
40 namespace lyx {
41
42
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44                 Context const & context, InsetLayout const * layout)
45 {
46         bool const forcePlainLayout =
47                 layout ? layout->forcePlainLayout() : false;
48         Context newcontext(true, context.textclass);
49         if (forcePlainLayout)
50                 newcontext.layout = &context.textclass.plainLayout();
51         else
52                 newcontext.font = context.font;
53         parse_text(p, os, flags, outer, newcontext);
54         newcontext.check_end_layout(os);
55 }
56
57
58 namespace {
59
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61                 Context const & context, string const & name)
62 {
63         InsetLayout const * layout = 0;
64         DocumentClass::InsetLayouts::const_iterator it =
65                 context.textclass.insetLayouts().find(from_ascii(name));
66         if (it != context.textclass.insetLayouts().end())
67                 layout = &(it->second);
68         parse_text_in_inset(p, os, flags, outer, context, layout);
69 }
70
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
73                 Context & context)
74 {
75         Context newcontext(context);
76         // Don't inherit the paragraph-level extra stuff
77         newcontext.par_extra_stuff.clear();
78         parse_text(p, os, flags, outer, newcontext);
79         // Make sure that we don't create invalid .lyx files
80         context.need_layout = newcontext.need_layout;
81         context.need_end_layout = newcontext.need_end_layout;
82 }
83
84
85 /*!
86  * Thin wrapper around parse_text_snippet() using a string.
87  *
88  * We completely ignore \c context.need_layout and \c context.need_end_layout,
89  * because our return value is not used directly (otherwise the stream version
90  * of parse_text_snippet() could be used). That means that the caller needs
91  * to do layout management manually.
92  * This is intended to parse text that does not create any layout changes.
93  */
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
95                   Context & context)
96 {
97         Context newcontext(context);
98         newcontext.need_layout = false;
99         newcontext.need_end_layout = false;
100         newcontext.new_layout_allowed = false;
101         // Avoid warning by Context::~Context()
102         newcontext.par_extra_stuff.clear();
103         ostringstream os;
104         parse_text_snippet(p, os, flags, outer, newcontext);
105         return os.str();
106 }
107
108
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110  "vpageref", "prettyref", "eqref", 0 };
111
112 /*!
113  * natbib commands.
114  * The starred forms are also known except for "citefullauthor",
115  * "citeyear" and "citeyearpar".
116  */
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
120
121 /*!
122  * jurabib commands.
123  * No starred form other than "cite*" known.
124  */
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
128 // "fullcite",
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", 0 };
132
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
135 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
136 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
137 "guilsinglleft", "frq", "guilsinglright", 0};
138
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
141 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
142 "gld", "grd", "gls", "ers", "fls",
143 "fls", "frs", "frs", 0};
144
145 /// LaTeX names for font sizes
146 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
148
149 /// the same as known_sizes with .lyx names
150 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
152
153 /// LaTeX 2.09 names for font families
154 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
155
156 /// LaTeX names for font families
157 char const * const known_font_families[] = { "rmfamily", "sffamily",
158 "ttfamily", 0};
159
160 /// the same as known_old_font_families and known_font_families with .lyx names
161 char const * const known_coded_font_families[] = { "roman", "sans",
162 "typewriter", 0};
163
164 /// LaTeX 2.09 names for font series
165 char const * const known_old_font_series[] = { "bf", 0};
166
167 /// LaTeX names for font series
168 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
169
170 /// the same as known_old_font_series and known_font_series with .lyx names
171 char const * const known_coded_font_series[] = { "bold", "medium", 0};
172
173 /// LaTeX 2.09 names for font shapes
174 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
175
176 /// LaTeX names for font shapes
177 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
178 "upshape", 0};
179
180 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
181 char const * const known_coded_font_shapes[] = { "italic", "slanted",
182 "smallcaps", "up", 0};
183
184 /*!
185  * Graphics file extensions known by the dvips driver of the graphics package.
186  * These extensions are used to complete the filename of an included
187  * graphics file if it does not contain an extension.
188  * The order must be the same that latex uses to find a file, because we
189  * will use the first extension that matches.
190  * This is only an approximation for the common cases. If we would want to
191  * do it right in all cases, we would need to know which graphics driver is
192  * used and know the extensions of every driver of the graphics package.
193  */
194 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
195 "ps.gz", "eps.Z", "ps.Z", 0};
196
197 /*!
198  * Graphics file extensions known by the pdftex driver of the graphics package.
199  * \sa known_dvips_graphics_formats
200  */
201 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
202 "mps", "tif", 0};
203
204 /*!
205  * Known file extensions for TeX files as used by \\include.
206  */
207 char const * const known_tex_extensions[] = {"tex", 0};
208
209 /// spaces known by InsetSpace
210 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
211 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
212 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
213
214 /// the same as known_spaces with .lyx names
215 char const * const known_coded_spaces[] = { "space{}", "space{}",
216 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
217 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
218 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
219
220 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
221 /// them in ERT. "LaTeXe" must come before "LaTeX"!
222 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
223 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
224 int const known_phrase_lengths[] = {3, 5, 7, 0};
225
226
227 /// splits "x=z, y=b" into a map and an ordered keyword vector
228 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
229 {
230         vector<string> v;
231         split(s, v);
232         res.clear();
233         keys.resize(v.size());
234         for (size_t i = 0; i < v.size(); ++i) {
235                 size_t const pos   = v[i].find('=');
236                 string const index = trimSpaceAndEol(v[i].substr(0, pos));
237                 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
238                 res[index] = value;
239                 keys[i] = index;
240         }
241 }
242
243
244 /*!
245  * Split a LaTeX length into value and unit.
246  * The latter can be a real unit like "pt", or a latex length variable
247  * like "\textwidth". The unit may contain additional stuff like glue
248  * lengths, but we don't care, because such lengths are ERT anyway.
249  * \returns true if \p value and \p unit are valid.
250  */
251 bool splitLatexLength(string const & len, string & value, string & unit)
252 {
253         if (len.empty())
254                 return false;
255         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
256         //'4,5' is a valid LaTeX length number. Change it to '4.5'
257         string const length = subst(len, ',', '.');
258         if (i == string::npos)
259                 return false;
260         if (i == 0) {
261                 if (len[0] == '\\') {
262                         // We had something like \textwidth without a factor
263                         value = "1.0";
264                 } else {
265                         return false;
266                 }
267         } else {
268                 value = trimSpaceAndEol(string(length, 0, i));
269         }
270         if (value == "-")
271                 value = "-1.0";
272         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
273         if (contains(len, '\\'))
274                 unit = trimSpaceAndEol(string(len, i));
275         else
276                 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
277         return true;
278 }
279
280
281 /// A simple function to translate a latex length to something LyX can
282 /// understand. Not perfect, but rather best-effort.
283 bool translate_len(string const & length, string & valstring, string & unit)
284 {
285         if (!splitLatexLength(length, valstring, unit))
286                 return false;
287         // LyX uses percent values
288         double value;
289         istringstream iss(valstring);
290         iss >> value;
291         value *= 100;
292         ostringstream oss;
293         oss << value;
294         string const percentval = oss.str();
295         // a normal length
296         if (unit.empty() || unit[0] != '\\')
297                 return true;
298         string::size_type const i = unit.find(' ');
299         string const endlen = (i == string::npos) ? string() : string(unit, i);
300         if (unit == "\\textwidth") {
301                 valstring = percentval;
302                 unit = "text%" + endlen;
303         } else if (unit == "\\columnwidth") {
304                 valstring = percentval;
305                 unit = "col%" + endlen;
306         } else if (unit == "\\paperwidth") {
307                 valstring = percentval;
308                 unit = "page%" + endlen;
309         } else if (unit == "\\linewidth") {
310                 valstring = percentval;
311                 unit = "line%" + endlen;
312         } else if (unit == "\\paperheight") {
313                 valstring = percentval;
314                 unit = "pheight%" + endlen;
315         } else if (unit == "\\textheight") {
316                 valstring = percentval;
317                 unit = "theight%" + endlen;
318         }
319         return true;
320 }
321
322 }
323
324
325 string translate_len(string const & length)
326 {
327         string unit;
328         string value;
329         if (translate_len(length, value, unit))
330                 return value + unit;
331         // If the input is invalid, return what we have.
332         return length;
333 }
334
335
336 namespace {
337
338 /*!
339  * Translates a LaTeX length into \p value, \p unit and
340  * \p special parts suitable for a box inset.
341  * The difference from translate_len() is that a box inset knows about
342  * some special "units" that are stored in \p special.
343  */
344 void translate_box_len(string const & length, string & value, string & unit, string & special)
345 {
346         if (translate_len(length, value, unit)) {
347                 if (unit == "\\height" || unit == "\\depth" ||
348                     unit == "\\totalheight" || unit == "\\width") {
349                         special = unit.substr(1);
350                         // The unit is not used, but LyX requires a dummy setting
351                         unit = "in";
352                 } else
353                         special = "none";
354         } else {
355                 value.clear();
356                 unit = length;
357                 special = "none";
358         }
359 }
360
361
362 /*!
363  * Find a file with basename \p name in path \p path and an extension
364  * in \p extensions.
365  */
366 string find_file(string const & name, string const & path,
367                  char const * const * extensions)
368 {
369         for (char const * const * what = extensions; *what; ++what) {
370                 string const trial = addExtension(name, *what);
371                 if (makeAbsPath(trial, path).exists())
372                         return trial;
373         }
374         return string();
375 }
376
377
378 void begin_inset(ostream & os, string const & name)
379 {
380         os << "\n\\begin_inset " << name;
381 }
382
383
384 void begin_command_inset(ostream & os, string const & name,
385                          string const & latexname)
386 {
387         begin_inset(os, "CommandInset ");
388         os << name << "\nLatexCommand " << latexname << '\n';
389 }
390
391
392 void end_inset(ostream & os)
393 {
394         os << "\n\\end_inset\n\n";
395 }
396
397
398 bool skip_braces(Parser & p)
399 {
400         if (p.next_token().cat() != catBegin)
401                 return false;
402         p.get_token();
403         if (p.next_token().cat() == catEnd) {
404                 p.get_token();
405                 return true;
406         }
407         p.putback();
408         return false;
409 }
410
411
412 /// replace LaTeX commands in \p s from the unicodesymbols file with their
413 /// unicode points
414 docstring convert_unicodesymbols(docstring s)
415 {
416         odocstringstream os;
417         for (size_t i = 0; i < s.size();) {
418                 if (s[i] != '\\') {
419                         os.put(s[i++]);
420                         continue;
421                 }
422                 s = s.substr(i);
423                 docstring rem;
424                 docstring parsed = encodings.fromLaTeXCommand(s, rem,
425                                 Encodings::TEXT_CMD);
426                 os << parsed;
427                 s = rem;
428                 if (s.empty() || s[0] != '\\')
429                         i = 0;
430                 else
431                         i = 1;
432         }
433         return os.str();
434 }
435
436
437 /// try to convert \p s to a valid InsetCommand argument
438 string convert_command_inset_arg(string s)
439 {
440         if (isAscii(s))
441                 // since we don't know the input encoding we can't use from_utf8
442                 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
443         // LyX cannot handle newlines in a latex command
444         return subst(s, "\n", " ");
445 }
446
447
448 void handle_backslash(ostream & os, string const & s)
449 {
450         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
451                 if (*it == '\\')
452                         os << "\n\\backslash\n";
453                 else
454                         os << *it;
455         }
456 }
457
458
459 void handle_ert(ostream & os, string const & s, Context & context)
460 {
461         // We must have a valid layout before outputting the ERT inset.
462         context.check_layout(os);
463         Context newcontext(true, context.textclass);
464         begin_inset(os, "ERT");
465         os << "\nstatus collapsed\n";
466         newcontext.check_layout(os);
467         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
468                 if (*it == '\\')
469                         os << "\n\\backslash\n";
470                 else if (*it == '\n') {
471                         newcontext.new_paragraph(os);
472                         newcontext.check_layout(os);
473                 } else
474                         os << *it;
475         }
476         newcontext.check_end_layout(os);
477         end_inset(os);
478 }
479
480
481 void handle_comment(ostream & os, string const & s, Context & context)
482 {
483         // TODO: Handle this better
484         Context newcontext(true, context.textclass);
485         begin_inset(os, "ERT");
486         os << "\nstatus collapsed\n";
487         newcontext.check_layout(os);
488         handle_backslash(os, s);
489         // make sure that our comment is the last thing on the line
490         newcontext.new_paragraph(os);
491         newcontext.check_layout(os);
492         newcontext.check_end_layout(os);
493         end_inset(os);
494 }
495
496
497 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
498 {
499         Layout const * layout = findLayoutWithoutModule(textclass, name, command);
500         if (layout)
501                 return layout;
502         if (checkModule(name, command))
503                 return findLayoutWithoutModule(textclass, name, command);
504         return layout;
505 }
506
507
508 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
509 {
510         InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
511         if (insetlayout)
512                 return insetlayout;
513         if (checkModule(name, command))
514                 return findInsetLayoutWithoutModule(textclass, name, command);
515         return insetlayout;
516 }
517
518
519 void eat_whitespace(Parser &, ostream &, Context &, bool);
520
521
522 /*!
523  * Skips whitespace and braces.
524  * This should be called after a command has been parsed that is not put into
525  * ERT, and where LyX adds "{}" if needed.
526  */
527 void skip_spaces_braces(Parser & p, bool keepws = false)
528 {
529         /* The following four examples produce the same typeset output and
530            should be handled by this function:
531            - abc \j{} xyz
532            - abc \j {} xyz
533            - abc \j 
534              {} xyz
535            - abc \j %comment
536              {} xyz
537          */
538         // Unfortunately we need to skip comments, too.
539         // We can't use eat_whitespace since writing them after the {}
540         // results in different output in some cases.
541         bool const skipped_spaces = p.skip_spaces(true);
542         bool const skipped_braces = skip_braces(p);
543         if (keepws && skipped_spaces && !skipped_braces)
544                 // put back the space (it is better handled by check_space)
545                 p.unskip_spaces(true);
546 }
547
548
549 void output_command_layout(ostream & os, Parser & p, bool outer,
550                            Context & parent_context,
551                            Layout const * newlayout)
552 {
553         TeXFont const oldFont = parent_context.font;
554         // save the current font size
555         string const size = oldFont.size;
556         // reset the font size to default, because the font size switches
557         // don't affect section headings and the like
558         parent_context.font.size = Context::normalfont.size;
559         // we only need to write the font change if we have an open layout
560         if (!parent_context.atParagraphStart())
561                 output_font_change(os, oldFont, parent_context.font);
562         parent_context.check_end_layout(os);
563         Context context(true, parent_context.textclass, newlayout,
564                         parent_context.layout, parent_context.font);
565         if (parent_context.deeper_paragraph) {
566                 // We are beginning a nested environment after a
567                 // deeper paragraph inside the outer list environment.
568                 // Therefore we don't need to output a "begin deeper".
569                 context.need_end_deeper = true;
570         }
571         context.check_deeper(os);
572         context.check_layout(os);
573         unsigned int optargs = 0;
574         while (optargs < context.layout->optargs) {
575                 eat_whitespace(p, os, context, false);
576                 if (p.next_token().cat() == catEscape ||
577                     p.next_token().character() != '[') 
578                         break;
579                 p.get_token(); // eat '['
580                 begin_inset(os, "Argument\n");
581                 os << "status collapsed\n\n";
582                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
583                 end_inset(os);
584                 eat_whitespace(p, os, context, false);
585                 ++optargs;
586         }
587         unsigned int reqargs = 0;
588         while (reqargs < context.layout->reqargs) {
589                 eat_whitespace(p, os, context, false);
590                 if (p.next_token().cat() != catBegin)
591                         break;
592                 p.get_token(); // eat '{'
593                 begin_inset(os, "Argument\n");
594                 os << "status collapsed\n\n";
595                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
596                 end_inset(os);
597                 eat_whitespace(p, os, context, false);
598                 ++reqargs;
599         }
600         parse_text(p, os, FLAG_ITEM, outer, context);
601         context.check_end_layout(os);
602         if (parent_context.deeper_paragraph) {
603                 // We must suppress the "end deeper" because we
604                 // suppressed the "begin deeper" above.
605                 context.need_end_deeper = false;
606         }
607         context.check_end_deeper(os);
608         // We don't need really a new paragraph, but
609         // we must make sure that the next item gets a \begin_layout.
610         parent_context.new_paragraph(os);
611         // Set the font size to the original value. No need to output it here
612         // (Context::begin_layout() will do that if needed)
613         parent_context.font.size = size;
614 }
615
616
617 /*!
618  * Output a space if necessary.
619  * This function gets called for every whitespace token.
620  *
621  * We have three cases here:
622  * 1. A space must be suppressed. Example: The lyxcode case below
623  * 2. A space may be suppressed. Example: Spaces before "\par"
624  * 3. A space must not be suppressed. Example: A space between two words
625  *
626  * We currently handle only 1. and 3 and from 2. only the case of
627  * spaces before newlines as a side effect.
628  *
629  * 2. could be used to suppress as many spaces as possible. This has two effects:
630  * - Reimporting LyX generated LaTeX files changes almost no whitespace
631  * - Superflous whitespace from non LyX generated LaTeX files is removed.
632  * The drawback is that the logic inside the function becomes
633  * complicated, and that is the reason why it is not implemented.
634  */
635 void check_space(Parser & p, ostream & os, Context & context)
636 {
637         Token const next = p.next_token();
638         Token const curr = p.curr_token();
639         // A space before a single newline and vice versa must be ignored
640         // LyX emits a newline before \end{lyxcode}.
641         // This newline must be ignored,
642         // otherwise LyX will add an additional protected space.
643         if (next.cat() == catSpace ||
644             next.cat() == catNewline ||
645             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
646                 return;
647         }
648         context.check_layout(os);
649         os << ' ';
650 }
651
652
653 /*!
654  * Parse all arguments of \p command
655  */
656 void parse_arguments(string const & command,
657                      vector<ArgumentType> const & template_arguments,
658                      Parser & p, ostream & os, bool outer, Context & context)
659 {
660         string ert = command;
661         size_t no_arguments = template_arguments.size();
662         for (size_t i = 0; i < no_arguments; ++i) {
663                 switch (template_arguments[i]) {
664                 case required:
665                         // This argument contains regular LaTeX
666                         handle_ert(os, ert + '{', context);
667                         eat_whitespace(p, os, context, false);
668                         parse_text(p, os, FLAG_ITEM, outer, context);
669                         ert = "}";
670                         break;
671                 case item:
672                         // This argument consists only of a single item.
673                         // The presence of '{' or not must be preserved.
674                         p.skip_spaces();
675                         if (p.next_token().cat() == catBegin)
676                                 ert += '{' + p.verbatim_item() + '}';
677                         else
678                                 ert += p.verbatim_item();
679                         break;
680                 case verbatim:
681                         // This argument may contain special characters
682                         ert += '{' + p.verbatim_item() + '}';
683                         break;
684                 case optional:
685                         // true because we must not eat whitespace
686                         // if an optional arg follows we must not strip the
687                         // brackets from this one
688                         if (i < no_arguments - 1 &&
689                             template_arguments[i+1] == optional)
690                                 ert += p.getFullOpt(true);
691                         else
692                                 ert += p.getOpt(true);
693                         break;
694                 }
695         }
696         handle_ert(os, ert, context);
697 }
698
699
700 /*!
701  * Check whether \p command is a known command. If yes,
702  * handle the command with all arguments.
703  * \return true if the command was parsed, false otherwise.
704  */
705 bool parse_command(string const & command, Parser & p, ostream & os,
706                    bool outer, Context & context)
707 {
708         if (known_commands.find(command) != known_commands.end()) {
709                 parse_arguments(command, known_commands[command], p, os,
710                                 outer, context);
711                 return true;
712         }
713         return false;
714 }
715
716
717 /// Parses a minipage or parbox
718 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
719                unsigned inner_flags, bool outer, Context & parent_context,
720                string const & outer_type, string const & special,
721                string const & inner_type)
722 {
723         string position;
724         string inner_pos;
725         string hor_pos = "c";
726         // We need to set the height to the LaTeX default of 1\\totalheight
727         // for the case when no height argument is given
728         string height_value = "1";
729         string height_unit = "in";
730         string height_special = "totalheight";
731         string latex_height;
732         if (!inner_type.empty() && p.hasOpt()) {
733                 position = p.getArg('[', ']');
734                 if (position != "t" && position != "c" && position != "b") {
735                         cerr << "invalid position " << position << " for "
736                              << inner_type << endl;
737                         position = "c";
738                 }
739                 if (p.hasOpt()) {
740                         latex_height = p.getArg('[', ']');
741                         translate_box_len(latex_height, height_value, height_unit, height_special);
742
743                         if (p.hasOpt()) {
744                                 inner_pos = p.getArg('[', ']');
745                                 if (inner_pos != "c" && inner_pos != "t" &&
746                                     inner_pos != "b" && inner_pos != "s") {
747                                         cerr << "invalid inner_pos "
748                                              << inner_pos << " for "
749                                              << inner_type << endl;
750                                         inner_pos = position;
751                                 }
752                         }
753                 }
754         }
755         string width_value;
756         string width_unit;
757         string latex_width;
758         if (inner_type.empty()) {
759                 if (special.empty())
760                         latex_width = "\\columnwidth";
761                 else {
762                         Parser p2(special);
763                         latex_width = p2.getArg('[', ']');
764                         string const opt = p2.getArg('[', ']');
765                         if (!opt.empty()) {
766                                 hor_pos = opt;
767                                 if (hor_pos != "l" && hor_pos != "c" &&
768                                     hor_pos != "r") {
769                                         cerr << "invalid hor_pos " << hor_pos
770                                              << " for " << outer_type << endl;
771                                         hor_pos = "c";
772                                 }
773                         }
774                 }
775         } else
776                 latex_width = p.verbatim_item();
777         translate_len(latex_width, width_value, width_unit);
778         // LyX can't handle length variables
779         bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
780         if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
781                 // Look whether there is some content after the end of the
782                 // inner box, but before the end of the outer box.
783                 // If yes, we need to output ERT.
784                 p.pushPosition();
785                 if (inner_flags & FLAG_END)
786                         p.verbatimEnvironment(inner_type);
787                 else
788                         p.verbatim_item();
789                 p.skip_spaces(true);
790                 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
791                     (outer_type != "framed" && p.next_token().cat() != catEnd)) {
792                         // something is between the end of the inner box and
793                         // the end of the outer box, so we need to use ERT.
794                         use_ert = true;
795                 }
796                 p.popPosition();
797         }
798         if (use_ert) {
799                 ostringstream ss;
800                 if (!outer_type.empty()) {
801                         if (outer_flags & FLAG_END)
802                                 ss << "\\begin{" << outer_type << '}';
803                         else {
804                                 ss << '\\' << outer_type << '{';
805                                 if (!special.empty())
806                                         ss << special;
807                         }
808                 }
809                 if (!inner_type.empty()) {
810                         if (inner_flags & FLAG_END)
811                                 ss << "\\begin{" << inner_type << '}';
812                         else
813                                 ss << '\\' << inner_type;
814                         if (!position.empty())
815                                 ss << '[' << position << ']';
816                         if (!latex_height.empty())
817                                 ss << '[' << latex_height << ']';
818                         if (!inner_pos.empty())
819                                 ss << '[' << inner_pos << ']';
820                         ss << '{' << latex_width << '}';
821                         if (!(inner_flags & FLAG_END))
822                                 ss << '{';
823                 }
824                 handle_ert(os, ss.str(), parent_context);
825                 if (!inner_type.empty()) {
826                         parse_text(p, os, inner_flags, outer, parent_context);
827                         if (inner_flags & FLAG_END)
828                                 handle_ert(os, "\\end{" + inner_type + '}',
829                                            parent_context);
830                         else
831                                 handle_ert(os, "}", parent_context);
832                 }
833                 if (!outer_type.empty()) {
834                         parse_text(p, os, outer_flags, outer, parent_context);
835                         if (outer_flags & FLAG_END)
836                                 handle_ert(os, "\\end{" + outer_type + '}',
837                                            parent_context);
838                         else
839                                 handle_ert(os, "}", parent_context);
840                 }
841         } else {
842                 // LyX does not like empty positions, so we have
843                 // to set them to the LaTeX default values here.
844                 if (position.empty())
845                         position = "c";
846                 if (inner_pos.empty())
847                         inner_pos = position;
848                 parent_context.check_layout(os);
849                 begin_inset(os, "Box ");
850                 if (outer_type == "framed")
851                         os << "Framed\n";
852                 else if (outer_type == "framebox")
853                         os << "Boxed\n";
854                 else if (outer_type == "shadowbox")
855                         os << "Shadowbox\n";
856                 else if (outer_type == "shaded")
857                         os << "Shaded\n";
858                 else if (outer_type == "doublebox")
859                         os << "Doublebox\n";
860                 else if (outer_type.empty())
861                         os << "Frameless\n";
862                 else
863                         os << outer_type << '\n';
864                 os << "position \"" << position << "\"\n";
865                 os << "hor_pos \"" << hor_pos << "\"\n";
866                 os << "has_inner_box " << !inner_type.empty() << "\n";
867                 os << "inner_pos \"" << inner_pos << "\"\n";
868                 os << "use_parbox " << (inner_type == "parbox") << '\n';
869                 os << "use_makebox 0\n";
870                 os << "width \"" << width_value << width_unit << "\"\n";
871                 os << "special \"none\"\n";
872                 os << "height \"" << height_value << height_unit << "\"\n";
873                 os << "height_special \"" << height_special << "\"\n";
874                 os << "status open\n\n";
875                 Context context(true, parent_context.textclass);
876                 context.font = parent_context.font;
877
878                 // If we have no inner box the contens will be read with the outer box
879                 if (!inner_type.empty())
880                         parse_text(p, os, inner_flags, outer, context);
881
882                 // Ensure that the end of the outer box is parsed correctly:
883                 // The opening brace has been eaten by parse_outer_box()
884                 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
885                         outer_flags &= ~FLAG_ITEM;
886                         outer_flags |= FLAG_BRACE_LAST;
887                 }
888
889                 // Find end of outer box, output contents if inner_type is
890                 // empty and output possible comments
891                 if (!outer_type.empty()) {
892                         // This does not output anything but comments if
893                         // inner_type is not empty (see use_ert)
894                         parse_text(p, os, outer_flags, outer, context);
895                 }
896
897                 context.check_end_layout(os);
898                 end_inset(os);
899 #ifdef PRESERVE_LAYOUT
900                 // LyX puts a % after the end of the minipage
901                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
902                         // new paragraph
903                         //handle_comment(os, "%dummy", parent_context);
904                         p.get_token();
905                         p.skip_spaces();
906                         parent_context.new_paragraph(os);
907                 }
908                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
909                         //handle_comment(os, "%dummy", parent_context);
910                         p.get_token();
911                         p.skip_spaces();
912                         // We add a protected space if something real follows
913                         if (p.good() && p.next_token().cat() != catComment) {
914                                 begin_inset(os, "space ~\n");
915                                 end_inset(os);
916                         }
917                 }
918 #endif
919         }
920 }
921
922
923 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
924                      Context & parent_context, string const & outer_type,
925                      string const & special)
926 {
927         eat_whitespace(p, os, parent_context, false);
928         if (flags & FLAG_ITEM) {
929                 // Eat '{'
930                 if (p.next_token().cat() == catBegin)
931                         p.get_token();
932                 else
933                         cerr << "Warning: Ignoring missing '{' after \\"
934                              << outer_type << '.' << endl;
935                 eat_whitespace(p, os, parent_context, false);
936         }
937         string inner;
938         unsigned int inner_flags = 0;
939         if (outer_type == "shaded") {
940                 // These boxes never have an inner box
941                 ;
942         } else if (p.next_token().asInput() == "\\parbox") {
943                 inner = p.get_token().cs();
944                 inner_flags = FLAG_ITEM;
945         } else if (p.next_token().asInput() == "\\begin") {
946                 // Is this a minipage?
947                 p.pushPosition();
948                 p.get_token();
949                 inner = p.getArg('{', '}');
950                 p.popPosition();
951                 if (inner == "minipage") {
952                         p.get_token();
953                         p.getArg('{', '}');
954                         eat_whitespace(p, os, parent_context, false);
955                         inner_flags = FLAG_END;
956                 } else
957                         inner = "";
958         }
959         if (inner_flags == FLAG_END) {
960                 active_environments.push_back(inner);
961                 parse_box(p, os, flags, FLAG_END, outer, parent_context,
962                           outer_type, special, inner);
963                 active_environments.pop_back();
964         } else {
965                 parse_box(p, os, flags, inner_flags, outer, parent_context,
966                           outer_type, special, inner);
967         }
968 }
969
970
971 void parse_listings(Parser & p, ostream & os, Context & parent_context)
972 {
973         parent_context.check_layout(os);
974         begin_inset(os, "listings\n");
975         os << "inline false\n"
976            << "status collapsed\n";
977         Context context(true, parent_context.textclass);
978         context.layout = &parent_context.textclass.plainLayout();
979         context.check_layout(os);
980         string const s = p.verbatimEnvironment("lstlisting");
981         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
982                 if (*it == '\\')
983                         os << "\n\\backslash\n";
984                 else if (*it == '\n') {
985                         // avoid adding an empty paragraph at the end
986                         if (it + 1 != et) {
987                                 context.new_paragraph(os);
988                                 context.check_layout(os);
989                         }
990                 } else
991                         os << *it;
992         }
993         context.check_end_layout(os);
994         end_inset(os);
995 }
996
997
998 /// parse an unknown environment
999 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1000                                unsigned flags, bool outer,
1001                                Context & parent_context)
1002 {
1003         if (name == "tabbing")
1004                 // We need to remember that we have to handle '\=' specially
1005                 flags |= FLAG_TABBING;
1006
1007         // We need to translate font changes and paragraphs inside the
1008         // environment to ERT if we have a non standard font.
1009         // Otherwise things like
1010         // \large\begin{foo}\huge bar\end{foo}
1011         // will not work.
1012         bool const specialfont =
1013                 (parent_context.font != parent_context.normalfont);
1014         bool const new_layout_allowed = parent_context.new_layout_allowed;
1015         if (specialfont)
1016                 parent_context.new_layout_allowed = false;
1017         handle_ert(os, "\\begin{" + name + "}", parent_context);
1018         parse_text_snippet(p, os, flags, outer, parent_context);
1019         handle_ert(os, "\\end{" + name + "}", parent_context);
1020         if (specialfont)
1021                 parent_context.new_layout_allowed = new_layout_allowed;
1022 }
1023
1024
1025 void parse_environment(Parser & p, ostream & os, bool outer,
1026                        string & last_env, Context & parent_context)
1027 {
1028         Layout const * newlayout;
1029         InsetLayout const * newinsetlayout = 0;
1030         string const name = p.getArg('{', '}');
1031         const bool is_starred = suffixIs(name, '*');
1032         string const unstarred_name = rtrim(name, "*");
1033         active_environments.push_back(name);
1034
1035         if (is_math_env(name)) {
1036                 parent_context.check_layout(os);
1037                 begin_inset(os, "Formula ");
1038                 os << "\\begin{" << name << "}";
1039                 parse_math(p, os, FLAG_END, MATH_MODE);
1040                 os << "\\end{" << name << "}";
1041                 end_inset(os);
1042         }
1043
1044         else if (name == "tabular" || name == "longtable") {
1045                 eat_whitespace(p, os, parent_context, false);
1046                 parent_context.check_layout(os);
1047                 begin_inset(os, "Tabular ");
1048                 handle_tabular(p, os, name == "longtable", parent_context);
1049                 end_inset(os);
1050                 p.skip_spaces();
1051         }
1052
1053         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1054                 eat_whitespace(p, os, parent_context, false);
1055                 parent_context.check_layout(os);
1056                 begin_inset(os, "Float " + unstarred_name + "\n");
1057                 if (p.hasOpt())
1058                         os << "placement " << p.getArg('[', ']') << '\n';
1059                 os << "wide " << convert<string>(is_starred)
1060                    << "\nsideways false"
1061                    << "\nstatus open\n\n";
1062                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1063                 end_inset(os);
1064                 // We don't need really a new paragraph, but
1065                 // we must make sure that the next item gets a \begin_layout.
1066                 parent_context.new_paragraph(os);
1067                 p.skip_spaces();
1068         }
1069
1070         else if (name == "minipage") {
1071                 eat_whitespace(p, os, parent_context, false);
1072                 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1073                 p.skip_spaces();
1074         }
1075
1076         else if (name == "comment") {
1077                 eat_whitespace(p, os, parent_context, false);
1078                 parent_context.check_layout(os);
1079                 begin_inset(os, "Note Comment\n");
1080                 os << "status open\n";
1081                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1082                 end_inset(os);
1083                 p.skip_spaces();
1084                 skip_braces(p); // eat {} that might by set by LyX behind comments
1085         }
1086
1087         else if (name == "lyxgreyedout") {
1088                 eat_whitespace(p, os, parent_context, false);
1089                 parent_context.check_layout(os);
1090                 begin_inset(os, "Note Greyedout\n");
1091                 os << "status open\n";
1092                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1093                 end_inset(os);
1094                 p.skip_spaces();
1095         }
1096
1097         else if (name == "framed" || name == "shaded") {
1098                 eat_whitespace(p, os, parent_context, false);
1099                 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1100                 p.skip_spaces();
1101         }
1102
1103         else if (name == "lstlisting") {
1104                 eat_whitespace(p, os, parent_context, false);
1105                 // FIXME handle listings with parameters
1106                 if (p.hasOpt())
1107                         parse_unknown_environment(p, name, os, FLAG_END,
1108                                                   outer, parent_context);
1109                 else
1110                         parse_listings(p, os, parent_context);
1111                 p.skip_spaces();
1112         }
1113
1114         else if (!parent_context.new_layout_allowed)
1115                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1116                                           parent_context);
1117
1118         // Alignment and spacing settings
1119         // FIXME (bug xxxx): These settings can span multiple paragraphs and
1120         //                                       therefore are totally broken!
1121         // Note that \centering, raggedright, and raggedleft cannot be handled, as
1122         // they are commands not environments. They are furthermore switches that
1123         // can be ended by another switches, but also by commands like \footnote or
1124         // \parbox. So the only safe way is to leave them untouched.
1125         else if (name == "center" || name == "centering" ||
1126                  name == "flushleft" || name == "flushright" ||
1127                  name == "singlespace" || name == "onehalfspace" ||
1128                  name == "doublespace" || name == "spacing") {
1129                 eat_whitespace(p, os, parent_context, false);
1130                 // We must begin a new paragraph if not already done
1131                 if (! parent_context.atParagraphStart()) {
1132                         parent_context.check_end_layout(os);
1133                         parent_context.new_paragraph(os);
1134                 }
1135                 if (name == "flushleft")
1136                         parent_context.add_extra_stuff("\\align left\n");
1137                 else if (name == "flushright")
1138                         parent_context.add_extra_stuff("\\align right\n");
1139                 else if (name == "center" || name == "centering")
1140                         parent_context.add_extra_stuff("\\align center\n");
1141                 else if (name == "singlespace")
1142                         parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1143                 else if (name == "onehalfspace")
1144                         parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1145                 else if (name == "doublespace")
1146                         parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1147                 else if (name == "spacing")
1148                         parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1149                 parse_text(p, os, FLAG_END, outer, parent_context);
1150                 // Just in case the environment is empty
1151                 parent_context.extra_stuff.erase();
1152                 // We must begin a new paragraph to reset the alignment
1153                 parent_context.new_paragraph(os);
1154                 p.skip_spaces();
1155         }
1156
1157         // The single '=' is meant here.
1158         else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1159                 eat_whitespace(p, os, parent_context, false);
1160                 Context context(true, parent_context.textclass, newlayout,
1161                                 parent_context.layout, parent_context.font);
1162                 if (parent_context.deeper_paragraph) {
1163                         // We are beginning a nested environment after a
1164                         // deeper paragraph inside the outer list environment.
1165                         // Therefore we don't need to output a "begin deeper".
1166                         context.need_end_deeper = true;
1167                 }
1168                 parent_context.check_end_layout(os);
1169                 if (last_env == name) {
1170                         // we need to output a separator since LyX would export
1171                         // the two environments as one otherwise (bug 5716)
1172                         docstring const sep = from_ascii("--Separator--");
1173                         TeX2LyXDocClass const & textclass(parent_context.textclass);
1174                         if (textclass.hasLayout(sep)) {
1175                                 Context newcontext(parent_context);
1176                                 newcontext.layout = &(textclass[sep]);
1177                                 newcontext.check_layout(os);
1178                                 newcontext.check_end_layout(os);
1179                         } else {
1180                                 parent_context.check_layout(os);
1181                                 begin_inset(os, "Note Note\n");
1182                                 os << "status closed\n";
1183                                 Context newcontext(true, textclass,
1184                                                 &(textclass.defaultLayout()));
1185                                 newcontext.check_layout(os);
1186                                 newcontext.check_end_layout(os);
1187                                 end_inset(os);
1188                                 parent_context.check_end_layout(os);
1189                         }
1190                 }
1191                 switch (context.layout->latextype) {
1192                 case  LATEX_LIST_ENVIRONMENT:
1193                         context.add_par_extra_stuff("\\labelwidthstring "
1194                                                     + p.verbatim_item() + '\n');
1195                         p.skip_spaces();
1196                         break;
1197                 case  LATEX_BIB_ENVIRONMENT:
1198                         p.verbatim_item(); // swallow next arg
1199                         p.skip_spaces();
1200                         break;
1201                 default:
1202                         break;
1203                 }
1204                 context.check_deeper(os);
1205                 // handle known optional and required arguments
1206                 // layouts require all optional arguments before the required ones
1207                 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1208                 // It is impossible to place anything after the environment name,
1209                 // but before the first \\item.
1210                 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1211                         bool need_layout = true;
1212                         unsigned int optargs = 0;
1213                         while (optargs < context.layout->optargs) {
1214                                 eat_whitespace(p, os, context, false);
1215                                 if (p.next_token().cat() == catEscape ||
1216                                     p.next_token().character() != '[') 
1217                                         break;
1218                                 p.get_token(); // eat '['
1219                                 if (need_layout) {
1220                                         context.check_layout(os);
1221                                         need_layout = false;
1222                                 }
1223                                 begin_inset(os, "Argument\n");
1224                                 os << "status collapsed\n\n";
1225                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1226                                 end_inset(os);
1227                                 eat_whitespace(p, os, context, false);
1228                                 ++optargs;
1229                         }
1230                         unsigned int reqargs = 0;
1231                         while (reqargs < context.layout->reqargs) {
1232                                 eat_whitespace(p, os, context, false);
1233                                 if (p.next_token().cat() != catBegin)
1234                                         break;
1235                                 p.get_token(); // eat '{'
1236                                 if (need_layout) {
1237                                         context.check_layout(os);
1238                                         need_layout = false;
1239                                 }
1240                                 begin_inset(os, "Argument\n");
1241                                 os << "status collapsed\n\n";
1242                                 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1243                                 end_inset(os);
1244                                 eat_whitespace(p, os, context, false);
1245                                 ++reqargs;
1246                         }
1247                 }
1248                 parse_text(p, os, FLAG_END, outer, context);
1249                 context.check_end_layout(os);
1250                 if (parent_context.deeper_paragraph) {
1251                         // We must suppress the "end deeper" because we
1252                         // suppressed the "begin deeper" above.
1253                         context.need_end_deeper = false;
1254                 }
1255                 context.check_end_deeper(os);
1256                 parent_context.new_paragraph(os);
1257                 p.skip_spaces();
1258         }
1259
1260         // The single '=' is meant here.
1261         else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1262                 eat_whitespace(p, os, parent_context, false);
1263                 parent_context.check_layout(os);
1264                 begin_inset(os, "Flex ");
1265                 os << to_utf8(newinsetlayout->name()) << '\n'
1266                    << "status collapsed\n";
1267                 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1268                 end_inset(os);
1269         }
1270
1271         else if (name == "appendix") {
1272                 // This is no good latex style, but it works and is used in some documents...
1273                 eat_whitespace(p, os, parent_context, false);
1274                 parent_context.check_end_layout(os);
1275                 Context context(true, parent_context.textclass, parent_context.layout,
1276                                 parent_context.layout, parent_context.font);
1277                 context.check_layout(os);
1278                 os << "\\start_of_appendix\n";
1279                 parse_text(p, os, FLAG_END, outer, context);
1280                 context.check_end_layout(os);
1281                 p.skip_spaces();
1282         }
1283
1284         else if (known_environments.find(name) != known_environments.end()) {
1285                 vector<ArgumentType> arguments = known_environments[name];
1286                 // The last "argument" denotes wether we may translate the
1287                 // environment contents to LyX
1288                 // The default required if no argument is given makes us
1289                 // compatible with the reLyXre environment.
1290                 ArgumentType contents = arguments.empty() ?
1291                         required :
1292                         arguments.back();
1293                 if (!arguments.empty())
1294                         arguments.pop_back();
1295                 // See comment in parse_unknown_environment()
1296                 bool const specialfont =
1297                         (parent_context.font != parent_context.normalfont);
1298                 bool const new_layout_allowed =
1299                         parent_context.new_layout_allowed;
1300                 if (specialfont)
1301                         parent_context.new_layout_allowed = false;
1302                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1303                                 outer, parent_context);
1304                 if (contents == verbatim)
1305                         handle_ert(os, p.verbatimEnvironment(name),
1306                                    parent_context);
1307                 else
1308                         parse_text_snippet(p, os, FLAG_END, outer,
1309                                            parent_context);
1310                 handle_ert(os, "\\end{" + name + "}", parent_context);
1311                 if (specialfont)
1312                         parent_context.new_layout_allowed = new_layout_allowed;
1313         }
1314
1315         else
1316                 parse_unknown_environment(p, name, os, FLAG_END, outer,
1317                                           parent_context);
1318
1319         last_env = name;
1320         active_environments.pop_back();
1321 }
1322
1323
1324 /// parses a comment and outputs it to \p os.
1325 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1326 {
1327         LASSERT(t.cat() == catComment, return);
1328         if (!t.cs().empty()) {
1329                 context.check_layout(os);
1330                 handle_comment(os, '%' + t.cs(), context);
1331                 if (p.next_token().cat() == catNewline) {
1332                         // A newline after a comment line starts a new
1333                         // paragraph
1334                         if (context.new_layout_allowed) {
1335                                 if(!context.atParagraphStart())
1336                                         // Only start a new paragraph if not already
1337                                         // done (we might get called recursively)
1338                                         context.new_paragraph(os);
1339                         } else
1340                                 handle_ert(os, "\n", context);
1341                         eat_whitespace(p, os, context, true);
1342                 }
1343         } else {
1344                 // "%\n" combination
1345                 p.skip_spaces();
1346         }
1347 }
1348
1349
1350 /*!
1351  * Reads spaces and comments until the first non-space, non-comment token.
1352  * New paragraphs (double newlines or \\par) are handled like simple spaces
1353  * if \p eatParagraph is true.
1354  * Spaces are skipped, but comments are written to \p os.
1355  */
1356 void eat_whitespace(Parser & p, ostream & os, Context & context,
1357                     bool eatParagraph)
1358 {
1359         while (p.good()) {
1360                 Token const & t = p.get_token();
1361                 if (t.cat() == catComment)
1362                         parse_comment(p, os, t, context);
1363                 else if ((! eatParagraph && p.isParagraph()) ||
1364                          (t.cat() != catSpace && t.cat() != catNewline)) {
1365                         p.putback();
1366                         return;
1367                 }
1368         }
1369 }
1370
1371
1372 /*!
1373  * Set a font attribute, parse text and reset the font attribute.
1374  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1375  * \param currentvalue Current value of the attribute. Is set to the new
1376  * value during parsing.
1377  * \param newvalue New value of the attribute
1378  */
1379 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1380                            Context & context, string const & attribute,
1381                            string & currentvalue, string const & newvalue)
1382 {
1383         context.check_layout(os);
1384         string const oldvalue = currentvalue;
1385         currentvalue = newvalue;
1386         os << '\n' << attribute << ' ' << newvalue << "\n";
1387         parse_text_snippet(p, os, flags, outer, context);
1388         context.check_layout(os);
1389         os << '\n' << attribute << ' ' << oldvalue << "\n";
1390         currentvalue = oldvalue;
1391 }
1392
1393
1394 /// get the arguments of a natbib or jurabib citation command
1395 void get_cite_arguments(Parser & p, bool natbibOrder,
1396         string & before, string & after)
1397 {
1398         // We need to distinguish "" and "[]", so we can't use p.getOpt().
1399
1400         // text before the citation
1401         before.clear();
1402         // text after the citation
1403         after = p.getFullOpt();
1404
1405         if (!after.empty()) {
1406                 before = p.getFullOpt();
1407                 if (natbibOrder && !before.empty())
1408                         swap(before, after);
1409         }
1410 }
1411
1412
1413 /// Convert filenames with TeX macros and/or quotes to something LyX
1414 /// can understand
1415 string const normalize_filename(string const & name)
1416 {
1417         Parser p(trim(name, "\""));
1418         ostringstream os;
1419         while (p.good()) {
1420                 Token const & t = p.get_token();
1421                 if (t.cat() != catEscape)
1422                         os << t.asInput();
1423                 else if (t.cs() == "lyxdot") {
1424                         // This is used by LyX for simple dots in relative
1425                         // names
1426                         os << '.';
1427                         p.skip_spaces();
1428                 } else if (t.cs() == "space") {
1429                         os << ' ';
1430                         p.skip_spaces();
1431                 } else
1432                         os << t.asInput();
1433         }
1434         return os.str();
1435 }
1436
1437
1438 /// Convert \p name from TeX convention (relative to master file) to LyX
1439 /// convention (relative to .lyx file) if it is relative
1440 void fix_relative_filename(string & name)
1441 {
1442         if (FileName::isAbsolute(name))
1443                 return;
1444
1445         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1446                                    from_utf8(getParentFilePath())));
1447 }
1448
1449
1450 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1451 void parse_noweb(Parser & p, ostream & os, Context & context)
1452 {
1453         // assemble the rest of the keyword
1454         string name("<<");
1455         bool scrap = false;
1456         while (p.good()) {
1457                 Token const & t = p.get_token();
1458                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1459                         name += ">>";
1460                         p.get_token();
1461                         scrap = (p.good() && p.next_token().asInput() == "=");
1462                         if (scrap)
1463                                 name += p.get_token().asInput();
1464                         break;
1465                 }
1466                 name += t.asInput();
1467         }
1468
1469         if (!scrap || !context.new_layout_allowed ||
1470             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1471                 cerr << "Warning: Could not interpret '" << name
1472                      << "'. Ignoring it." << endl;
1473                 return;
1474         }
1475
1476         // We use new_paragraph instead of check_end_layout because the stuff
1477         // following the noweb chunk needs to start with a \begin_layout.
1478         // This may create a new paragraph even if there was none in the
1479         // noweb file, but the alternative is an invalid LyX file. Since
1480         // noweb code chunks are implemented with a layout style in LyX they
1481         // always must be in an own paragraph.
1482         context.new_paragraph(os);
1483         Context newcontext(true, context.textclass,
1484                 &context.textclass[from_ascii("Scrap")]);
1485         newcontext.check_layout(os);
1486         os << name;
1487         while (p.good()) {
1488                 Token const & t = p.get_token();
1489                 // We abuse the parser a bit, because this is no TeX syntax
1490                 // at all.
1491                 if (t.cat() == catEscape)
1492                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1493                 else {
1494                         ostringstream oss;
1495                         begin_inset(oss, "Newline newline");
1496                         end_inset(oss);
1497                         os << subst(t.asInput(), "\n", oss.str());
1498                 }
1499                 // The scrap chunk is ended by an @ at the beginning of a line.
1500                 // After the @ the line may contain a comment and/or
1501                 // whitespace, but nothing else.
1502                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1503                     (p.next_token().cat() == catSpace ||
1504                      p.next_token().cat() == catNewline ||
1505                      p.next_token().cat() == catComment)) {
1506                         while (p.good() && p.next_token().cat() == catSpace)
1507                                 os << p.get_token().asInput();
1508                         if (p.next_token().cat() == catComment)
1509                                 // The comment includes a final '\n'
1510                                 os << p.get_token().asInput();
1511                         else {
1512                                 if (p.next_token().cat() == catNewline)
1513                                         p.get_token();
1514                                 os << '\n';
1515                         }
1516                         break;
1517                 }
1518         }
1519         newcontext.check_end_layout(os);
1520 }
1521
1522
1523 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1524 bool is_macro(Parser & p)
1525 {
1526         Token first = p.curr_token();
1527         if (first.cat() != catEscape || !p.good())
1528                 return false;
1529         if (first.cs() == "def")
1530                 return true;
1531         if (first.cs() != "global" && first.cs() != "long")
1532                 return false;
1533         Token second = p.get_token();
1534         int pos = 1;
1535         while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1536                second.cat() == catNewline || second.cat() == catComment)) {
1537                 second = p.get_token();
1538                 pos++;
1539         }
1540         bool secondvalid = second.cat() == catEscape;
1541         Token third;
1542         bool thirdvalid = false;
1543         if (p.good() && first.cs() == "global" && secondvalid &&
1544             second.cs() == "long") {
1545                 third = p.get_token();
1546                 pos++;
1547                 while (p.good() && !p.isParagraph() &&
1548                        (third.cat() == catSpace ||
1549                         third.cat() == catNewline ||
1550                         third.cat() == catComment)) {
1551                         third = p.get_token();
1552                         pos++;
1553                 }
1554                 thirdvalid = third.cat() == catEscape;
1555         }
1556         for (int i = 0; i < pos; ++i)
1557                 p.putback();
1558         if (!secondvalid)
1559                 return false;
1560         if (!thirdvalid)
1561                 return (first.cs() == "global" || first.cs() == "long") &&
1562                        second.cs() == "def";
1563         return first.cs() == "global" && second.cs() == "long" &&
1564                third.cs() == "def";
1565 }
1566
1567
1568 /// Parse a macro definition (assumes that is_macro() returned true)
1569 void parse_macro(Parser & p, ostream & os, Context & context)
1570 {
1571         context.check_layout(os);
1572         Token first = p.curr_token();
1573         Token second;
1574         Token third;
1575         string command = first.asInput();
1576         if (first.cs() != "def") {
1577                 p.get_token();
1578                 eat_whitespace(p, os, context, false);
1579                 second = p.curr_token();
1580                 command += second.asInput();
1581                 if (second.cs() != "def") {
1582                         p.get_token();
1583                         eat_whitespace(p, os, context, false);
1584                         third = p.curr_token();
1585                         command += third.asInput();
1586                 }
1587         }
1588         eat_whitespace(p, os, context, false);
1589         string const name = p.get_token().cs();
1590         eat_whitespace(p, os, context, false);
1591
1592         // parameter text
1593         bool simple = true;
1594         string paramtext;
1595         int arity = 0;
1596         while (p.next_token().cat() != catBegin) {
1597                 if (p.next_token().cat() == catParameter) {
1598                         // # found
1599                         p.get_token();
1600                         paramtext += "#";
1601
1602                         // followed by number?
1603                         if (p.next_token().cat() == catOther) {
1604                                 char c = p.getChar();
1605                                 paramtext += c;
1606                                 // number = current arity + 1?
1607                                 if (c == arity + '0' + 1)
1608                                         ++arity;
1609                                 else
1610                                         simple = false;
1611                         } else
1612                                 paramtext += p.get_token().cs();
1613                 } else {
1614                         paramtext += p.get_token().cs();
1615                         simple = false;
1616                 }
1617         }
1618
1619         // only output simple (i.e. compatible) macro as FormulaMacros
1620         string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1621         if (simple) {
1622                 context.check_layout(os);
1623                 begin_inset(os, "FormulaMacro");
1624                 os << "\n\\def" << ert;
1625                 end_inset(os);
1626         } else
1627                 handle_ert(os, command + ert, context);
1628 }
1629
1630 } // anonymous namespace
1631
1632
1633 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1634                 Context & context)
1635 {
1636         Layout const * newlayout = 0;
1637         InsetLayout const * newinsetlayout = 0;
1638         // Store the latest bibliographystyle and nocite{*} option
1639         // (needed for bibtex inset)
1640         string btprint;
1641         string bibliographystyle;
1642         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1643         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1644         string last_env;
1645         while (p.good()) {
1646                 Token const & t = p.get_token();
1647
1648 #ifdef FILEDEBUG
1649                 debugToken(cerr, t, flags);
1650 #endif
1651
1652                 if (flags & FLAG_ITEM) {
1653                         if (t.cat() == catSpace)
1654                                 continue;
1655
1656                         flags &= ~FLAG_ITEM;
1657                         if (t.cat() == catBegin) {
1658                                 // skip the brace and collect everything to the next matching
1659                                 // closing brace
1660                                 flags |= FLAG_BRACE_LAST;
1661                                 continue;
1662                         }
1663
1664                         // handle only this single token, leave the loop if done
1665                         flags |= FLAG_LEAVE;
1666                 }
1667
1668                 if (t.cat() != catEscape && t.character() == ']' &&
1669                     (flags & FLAG_BRACK_LAST))
1670                         return;
1671                 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1672                         return;
1673
1674                 // If there is anything between \end{env} and \begin{env} we
1675                 // don't need to output a separator.
1676                 if (t.cat() != catSpace && t.cat() != catNewline &&
1677                     t.asInput() != "\\begin")
1678                         last_env = "";
1679
1680                 //
1681                 // cat codes
1682                 //
1683                 if (t.cat() == catMath) {
1684                         // we are inside some text mode thingy, so opening new math is allowed
1685                         context.check_layout(os);
1686                         begin_inset(os, "Formula ");
1687                         Token const & n = p.get_token();
1688                         if (n.cat() == catMath && outer) {
1689                                 // TeX's $$...$$ syntax for displayed math
1690                                 os << "\\[";
1691                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1692                                 os << "\\]";
1693                                 p.get_token(); // skip the second '$' token
1694                         } else {
1695                                 // simple $...$  stuff
1696                                 p.putback();
1697                                 os << '$';
1698                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1699                                 os << '$';
1700                         }
1701                         end_inset(os);
1702                 }
1703
1704                 else if (t.cat() == catSuper || t.cat() == catSub)
1705                         cerr << "catcode " << t << " illegal in text mode\n";
1706
1707                 // Basic support for english quotes. This should be
1708                 // extended to other quotes, but is not so easy (a
1709                 // left english quote is the same as a right german
1710                 // quote...)
1711                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1712                         context.check_layout(os);
1713                         begin_inset(os, "Quotes ");
1714                         os << "eld";
1715                         end_inset(os);
1716                         p.get_token();
1717                         skip_braces(p);
1718                 }
1719                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1720                         context.check_layout(os);
1721                         begin_inset(os, "Quotes ");
1722                         os << "erd";
1723                         end_inset(os);
1724                         p.get_token();
1725                         skip_braces(p);
1726                 }
1727
1728                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1729                         context.check_layout(os);
1730                         begin_inset(os, "Quotes ");
1731                         os << "ald";
1732                         end_inset(os);
1733                         p.get_token();
1734                         skip_braces(p);
1735                 }
1736
1737                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1738                         context.check_layout(os);
1739                         begin_inset(os, "Quotes ");
1740                         os << "ard";
1741                         end_inset(os);
1742                         p.get_token();
1743                         skip_braces(p);
1744                 }
1745
1746                 else if (t.asInput() == "<"
1747                          && p.next_token().asInput() == "<" && noweb_mode) {
1748                         p.get_token();
1749                         parse_noweb(p, os, context);
1750                 }
1751
1752                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1753                         check_space(p, os, context);
1754
1755                 else if (t.character() == '[' && noweb_mode &&
1756                          p.next_token().character() == '[') {
1757                         // These can contain underscores
1758                         p.putback();
1759                         string const s = p.getFullOpt() + ']';
1760                         if (p.next_token().character() == ']')
1761                                 p.get_token();
1762                         else
1763                                 cerr << "Warning: Inserting missing ']' in '"
1764                                      << s << "'." << endl;
1765                         handle_ert(os, s, context);
1766                 }
1767
1768                 else if (t.cat() == catLetter) {
1769                         context.check_layout(os);
1770                         // Workaround for bug 4752.
1771                         // FIXME: This whole code block needs to be removed
1772                         //        when the bug is fixed and tex2lyx produces
1773                         //        the updated file format.
1774                         // The replacement algorithm in LyX is so stupid that
1775                         // it even translates a phrase if it is part of a word.
1776                         bool handled = false;
1777                         for (int const * l = known_phrase_lengths; *l; ++l) {
1778                                 string phrase = t.cs();
1779                                 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1780                                         phrase += p.get_token().cs();
1781                                 if (is_known(phrase, known_coded_phrases)) {
1782                                         handle_ert(os, phrase, context);
1783                                         handled = true;
1784                                         break;
1785                                 } else {
1786                                         for (size_t i = 1; i < phrase.length(); ++i)
1787                                                 p.putback();
1788                                 }
1789                         }
1790                         if (!handled)
1791                                 os << t.cs();
1792                 }
1793
1794                 else if (t.cat() == catOther ||
1795                                t.cat() == catAlign ||
1796                                t.cat() == catParameter) {
1797                         // This translates "&" to "\\&" which may be wrong...
1798                         context.check_layout(os);
1799                         os << t.cs();
1800                 }
1801
1802                 else if (p.isParagraph()) {
1803                         if (context.new_layout_allowed)
1804                                 context.new_paragraph(os);
1805                         else
1806                                 handle_ert(os, "\\par ", context);
1807                         eat_whitespace(p, os, context, true);
1808                 }
1809
1810                 else if (t.cat() == catActive) {
1811                         context.check_layout(os);
1812                         if (t.character() == '~') {
1813                                 if (context.layout->free_spacing)
1814                                         os << ' ';
1815                                 else {
1816                                         begin_inset(os, "space ~\n");
1817                                         end_inset(os);
1818                                 }
1819                         } else
1820                                 os << t.cs();
1821                 }
1822
1823                 else if (t.cat() == catBegin &&
1824                          p.next_token().cat() == catEnd) {
1825                         // {}
1826                         Token const prev = p.prev_token();
1827                         p.get_token();
1828                         if (p.next_token().character() == '`' ||
1829                             (prev.character() == '-' &&
1830                              p.next_token().character() == '-'))
1831                                 ; // ignore it in {}`` or -{}-
1832                         else
1833                                 handle_ert(os, "{}", context);
1834
1835                 }
1836
1837                 else if (t.cat() == catBegin) {
1838                         context.check_layout(os);
1839                         // special handling of font attribute changes
1840                         Token const prev = p.prev_token();
1841                         Token const next = p.next_token();
1842                         TeXFont const oldFont = context.font;
1843                         if (next.character() == '[' ||
1844                             next.character() == ']' ||
1845                             next.character() == '*') {
1846                                 p.get_token();
1847                                 if (p.next_token().cat() == catEnd) {
1848                                         os << next.cs();
1849                                         p.get_token();
1850                                 } else {
1851                                         p.putback();
1852                                         handle_ert(os, "{", context);
1853                                         parse_text_snippet(p, os,
1854                                                         FLAG_BRACE_LAST,
1855                                                         outer, context);
1856                                         handle_ert(os, "}", context);
1857                                 }
1858                         } else if (! context.new_layout_allowed) {
1859                                 handle_ert(os, "{", context);
1860                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1861                                                    outer, context);
1862                                 handle_ert(os, "}", context);
1863                         } else if (is_known(next.cs(), known_sizes)) {
1864                                 // next will change the size, so we must
1865                                 // reset it here
1866                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1867                                                    outer, context);
1868                                 if (!context.atParagraphStart())
1869                                         os << "\n\\size "
1870                                            << context.font.size << "\n";
1871                         } else if (is_known(next.cs(), known_font_families)) {
1872                                 // next will change the font family, so we
1873                                 // must reset it here
1874                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1875                                                    outer, context);
1876                                 if (!context.atParagraphStart())
1877                                         os << "\n\\family "
1878                                            << context.font.family << "\n";
1879                         } else if (is_known(next.cs(), known_font_series)) {
1880                                 // next will change the font series, so we
1881                                 // must reset it here
1882                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1883                                                    outer, context);
1884                                 if (!context.atParagraphStart())
1885                                         os << "\n\\series "
1886                                            << context.font.series << "\n";
1887                         } else if (is_known(next.cs(), known_font_shapes)) {
1888                                 // next will change the font shape, so we
1889                                 // must reset it here
1890                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1891                                                    outer, context);
1892                                 if (!context.atParagraphStart())
1893                                         os << "\n\\shape "
1894                                            << context.font.shape << "\n";
1895                         } else if (is_known(next.cs(), known_old_font_families) ||
1896                                    is_known(next.cs(), known_old_font_series) ||
1897                                    is_known(next.cs(), known_old_font_shapes)) {
1898                                 // next will change the font family, series
1899                                 // and shape, so we must reset it here
1900                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1901                                                    outer, context);
1902                                 if (!context.atParagraphStart())
1903                                         os <<  "\n\\family "
1904                                            << context.font.family
1905                                            << "\n\\series "
1906                                            << context.font.series
1907                                            << "\n\\shape "
1908                                            << context.font.shape << "\n";
1909                         } else {
1910                                 handle_ert(os, "{", context);
1911                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1912                                                    outer, context);
1913                                 handle_ert(os, "}", context);
1914                         }
1915                 }
1916
1917                 else if (t.cat() == catEnd) {
1918                         if (flags & FLAG_BRACE_LAST) {
1919                                 return;
1920                         }
1921                         cerr << "stray '}' in text\n";
1922                         handle_ert(os, "}", context);
1923                 }
1924
1925                 else if (t.cat() == catComment)
1926                         parse_comment(p, os, t, context);
1927
1928                 //
1929                 // control sequences
1930                 //
1931
1932                 else if (t.cs() == "(") {
1933                         context.check_layout(os);
1934                         begin_inset(os, "Formula");
1935                         os << " \\(";
1936                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1937                         os << "\\)";
1938                         end_inset(os);
1939                 }
1940
1941                 else if (t.cs() == "[") {
1942                         context.check_layout(os);
1943                         begin_inset(os, "Formula");
1944                         os << " \\[";
1945                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1946                         os << "\\]";
1947                         end_inset(os);
1948                 }
1949
1950                 else if (t.cs() == "begin")
1951                         parse_environment(p, os, outer, last_env, context);
1952
1953                 else if (t.cs() == "end") {
1954                         if (flags & FLAG_END) {
1955                                 // eat environment name
1956                                 string const name = p.getArg('{', '}');
1957                                 if (name != active_environment())
1958                                         cerr << "\\end{" + name + "} does not match \\begin{"
1959                                                 + active_environment() + "}\n";
1960                                 return;
1961                         }
1962                         p.error("found 'end' unexpectedly");
1963                 }
1964
1965                 else if (t.cs() == "item") {
1966                         p.skip_spaces();
1967                         string s;
1968                         bool optarg = false;
1969                         if (p.next_token().cat() != catEscape &&
1970                             p.next_token().character() == '[') {
1971                                 p.get_token(); // eat '['
1972                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1973                                                        outer, context);
1974                                 optarg = true;
1975                         }
1976                         context.set_item();
1977                         context.check_layout(os);
1978                         if (context.has_item) {
1979                                 // An item in an unknown list-like environment
1980                                 // FIXME: Do this in check_layout()!
1981                                 context.has_item = false;
1982                                 if (optarg)
1983                                         handle_ert(os, "\\item", context);
1984                                 else
1985                                         handle_ert(os, "\\item ", context);
1986                         }
1987                         if (optarg) {
1988                                 if (context.layout->labeltype != LABEL_MANUAL) {
1989                                         // LyX does not support \item[\mybullet]
1990                                         // in itemize environments
1991                                         handle_ert(os, "[", context);
1992                                         os << s;
1993                                         handle_ert(os, "]", context);
1994                                 } else if (!s.empty()) {
1995                                         // The space is needed to separate the
1996                                         // item from the rest of the sentence.
1997                                         os << s << ' ';
1998                                         eat_whitespace(p, os, context, false);
1999                                 }
2000                         }
2001                 }
2002
2003                 else if (t.cs() == "bibitem") {
2004                         context.set_item();
2005                         context.check_layout(os);
2006                         string label = convert_command_inset_arg(p.getArg('[', ']'));
2007                         string key = convert_command_inset_arg(p.verbatim_item());
2008                         if (contains(label, '\\') || contains(key, '\\')) {
2009                                 // LyX can't handle LaTeX commands in labels or keys
2010                                 handle_ert(os, t.asInput() + '[' + label +
2011                                                "]{" + p.verbatim_item() + '}',
2012                                            context);
2013                         } else {
2014                                 begin_command_inset(os, "bibitem", "bibitem");
2015                                 os << "label \"" << label << "\"\n"
2016                                       "key \"" << key << "\"\n";
2017                                 end_inset(os);
2018                         }
2019                 }
2020
2021                 else if (is_macro(p))
2022                         parse_macro(p, os, context);
2023
2024                 else if (t.cs() == "noindent") {
2025                         p.skip_spaces();
2026                         context.add_par_extra_stuff("\\noindent\n");
2027                 }
2028
2029                 else if (t.cs() == "appendix") {
2030                         context.add_par_extra_stuff("\\start_of_appendix\n");
2031                         // We need to start a new paragraph. Otherwise the
2032                         // appendix in 'bla\appendix\chapter{' would start
2033                         // too late.
2034                         context.new_paragraph(os);
2035                         // We need to make sure that the paragraph is
2036                         // generated even if it is empty. Otherwise the
2037                         // appendix in '\par\appendix\par\chapter{' would
2038                         // start too late.
2039                         context.check_layout(os);
2040                         // FIXME: This is a hack to prevent paragraph
2041                         // deletion if it is empty. Handle this better!
2042                         handle_comment(os,
2043                                 "%dummy comment inserted by tex2lyx to "
2044                                 "ensure that this paragraph is not empty",
2045                                 context);
2046                         // Both measures above may generate an additional
2047                         // empty paragraph, but that does not hurt, because
2048                         // whitespace does not matter here.
2049                         eat_whitespace(p, os, context, true);
2050                 }
2051
2052                 // Starred section headings
2053                 // Must attempt to parse "Section*" before "Section".
2054                 else if ((p.next_token().asInput() == "*") &&
2055                          context.new_layout_allowed &&
2056                          (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2057                         // write the layout
2058                         p.get_token();
2059                         output_command_layout(os, p, outer, context, newlayout);
2060                         p.skip_spaces();
2061                 }
2062
2063                 // Section headings and the like
2064                 else if (context.new_layout_allowed &&
2065                          (newlayout = findLayout(context.textclass, t.cs(), true))) {
2066                         // write the layout
2067                         output_command_layout(os, p, outer, context, newlayout);
2068                         p.skip_spaces();
2069                 }
2070
2071                 else if (t.cs() == "caption") {
2072                         p.skip_spaces();
2073                         context.check_layout(os);
2074                         p.skip_spaces();
2075                         begin_inset(os, "Caption\n\n");
2076                         Context newcontext(true, context.textclass);
2077                         newcontext.font = context.font;
2078                         newcontext.check_layout(os);
2079                         if (p.next_token().cat() != catEscape &&
2080                             p.next_token().character() == '[') {
2081                                 p.get_token(); // eat '['
2082                                 begin_inset(os, "Argument\n");
2083                                 os << "status collapsed\n";
2084                                 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2085                                 end_inset(os);
2086                                 eat_whitespace(p, os, context, false);
2087                         }
2088                         parse_text(p, os, FLAG_ITEM, outer, context);
2089                         context.check_end_layout(os);
2090                         // We don't need really a new paragraph, but
2091                         // we must make sure that the next item gets a \begin_layout.
2092                         context.new_paragraph(os);
2093                         end_inset(os);
2094                         p.skip_spaces();
2095                         newcontext.check_end_layout(os);
2096                 }
2097
2098                 else if (t.cs() == "includegraphics") {
2099                         bool const clip = p.next_token().asInput() == "*";
2100                         if (clip)
2101                                 p.get_token();
2102                         string const arg = p.getArg('[', ']');
2103                         map<string, string> opts;
2104                         vector<string> keys;
2105                         split_map(arg, opts, keys);
2106                         if (clip)
2107                                 opts["clip"] = string();
2108                         string name = normalize_filename(p.verbatim_item());
2109
2110                         string const path = getMasterFilePath();
2111                         // We want to preserve relative / absolute filenames,
2112                         // therefore path is only used for testing
2113                         if (!makeAbsPath(name, path).exists()) {
2114                                 // The file extension is probably missing.
2115                                 // Now try to find it out.
2116                                 string const dvips_name =
2117                                         find_file(name, path,
2118                                                   known_dvips_graphics_formats);
2119                                 string const pdftex_name =
2120                                         find_file(name, path,
2121                                                   known_pdftex_graphics_formats);
2122                                 if (!dvips_name.empty()) {
2123                                         if (!pdftex_name.empty()) {
2124                                                 cerr << "This file contains the "
2125                                                         "latex snippet\n"
2126                                                         "\"\\includegraphics{"
2127                                                      << name << "}\".\n"
2128                                                         "However, files\n\""
2129                                                      << dvips_name << "\" and\n\""
2130                                                      << pdftex_name << "\"\n"
2131                                                         "both exist, so I had to make a "
2132                                                         "choice and took the first one.\n"
2133                                                         "Please move the unwanted one "
2134                                                         "someplace else and try again\n"
2135                                                         "if my choice was wrong."
2136                                                      << endl;
2137                                         }
2138                                         name = dvips_name;
2139                                 } else if (!pdftex_name.empty()) {
2140                                         name = pdftex_name;
2141                                         pdflatex = true;
2142                                 }
2143                         }
2144
2145                         if (makeAbsPath(name, path).exists())
2146                                 fix_relative_filename(name);
2147                         else
2148                                 cerr << "Warning: Could not find graphics file '"
2149                                      << name << "'." << endl;
2150
2151                         context.check_layout(os);
2152                         begin_inset(os, "Graphics ");
2153                         os << "\n\tfilename " << name << '\n';
2154                         if (opts.find("width") != opts.end())
2155                                 os << "\twidth "
2156                                    << translate_len(opts["width"]) << '\n';
2157                         if (opts.find("height") != opts.end())
2158                                 os << "\theight "
2159                                    << translate_len(opts["height"]) << '\n';
2160                         if (opts.find("scale") != opts.end()) {
2161                                 istringstream iss(opts["scale"]);
2162                                 double val;
2163                                 iss >> val;
2164                                 val = val*100;
2165                                 os << "\tscale " << val << '\n';
2166                         }
2167                         if (opts.find("angle") != opts.end()) {
2168                                 os << "\trotateAngle "
2169                                    << opts["angle"] << '\n';
2170                                 vector<string>::const_iterator a =
2171                                         find(keys.begin(), keys.end(), "angle");
2172                                 vector<string>::const_iterator s =
2173                                         find(keys.begin(), keys.end(), "width");
2174                                 if (s == keys.end())
2175                                         s = find(keys.begin(), keys.end(), "height");
2176                                 if (s == keys.end())
2177                                         s = find(keys.begin(), keys.end(), "scale");
2178                                 if (s != keys.end() && distance(s, a) > 0)
2179                                         os << "\tscaleBeforeRotation\n";
2180                         }
2181                         if (opts.find("origin") != opts.end()) {
2182                                 ostringstream ss;
2183                                 string const opt = opts["origin"];
2184                                 if (opt.find('l') != string::npos) ss << "left";
2185                                 if (opt.find('r') != string::npos) ss << "right";
2186                                 if (opt.find('c') != string::npos) ss << "center";
2187                                 if (opt.find('t') != string::npos) ss << "Top";
2188                                 if (opt.find('b') != string::npos) ss << "Bottom";
2189                                 if (opt.find('B') != string::npos) ss << "Baseline";
2190                                 if (!ss.str().empty())
2191                                         os << "\trotateOrigin " << ss.str() << '\n';
2192                                 else
2193                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2194                         }
2195                         if (opts.find("keepaspectratio") != opts.end())
2196                                 os << "\tkeepAspectRatio\n";
2197                         if (opts.find("clip") != opts.end())
2198                                 os << "\tclip\n";
2199                         if (opts.find("draft") != opts.end())
2200                                 os << "\tdraft\n";
2201                         if (opts.find("bb") != opts.end())
2202                                 os << "\tBoundingBox "
2203                                    << opts["bb"] << '\n';
2204                         int numberOfbbOptions = 0;
2205                         if (opts.find("bbllx") != opts.end())
2206                                 numberOfbbOptions++;
2207                         if (opts.find("bblly") != opts.end())
2208                                 numberOfbbOptions++;
2209                         if (opts.find("bburx") != opts.end())
2210                                 numberOfbbOptions++;
2211                         if (opts.find("bbury") != opts.end())
2212                                 numberOfbbOptions++;
2213                         if (numberOfbbOptions == 4)
2214                                 os << "\tBoundingBox "
2215                                    << opts["bbllx"] << " " << opts["bblly"] << " "
2216                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
2217                         else if (numberOfbbOptions > 0)
2218                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2219                         numberOfbbOptions = 0;
2220                         if (opts.find("natwidth") != opts.end())
2221                                 numberOfbbOptions++;
2222                         if (opts.find("natheight") != opts.end())
2223                                 numberOfbbOptions++;
2224                         if (numberOfbbOptions == 2)
2225                                 os << "\tBoundingBox 0bp 0bp "
2226                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
2227                         else if (numberOfbbOptions > 0)
2228                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2229                         ostringstream special;
2230                         if (opts.find("hiresbb") != opts.end())
2231                                 special << "hiresbb,";
2232                         if (opts.find("trim") != opts.end())
2233                                 special << "trim,";
2234                         if (opts.find("viewport") != opts.end())
2235                                 special << "viewport=" << opts["viewport"] << ',';
2236                         if (opts.find("totalheight") != opts.end())
2237                                 special << "totalheight=" << opts["totalheight"] << ',';
2238                         if (opts.find("type") != opts.end())
2239                                 special << "type=" << opts["type"] << ',';
2240                         if (opts.find("ext") != opts.end())
2241                                 special << "ext=" << opts["ext"] << ',';
2242                         if (opts.find("read") != opts.end())
2243                                 special << "read=" << opts["read"] << ',';
2244                         if (opts.find("command") != opts.end())
2245                                 special << "command=" << opts["command"] << ',';
2246                         string s_special = special.str();
2247                         if (!s_special.empty()) {
2248                                 // We had special arguments. Remove the trailing ','.
2249                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2250                         }
2251                         // TODO: Handle the unknown settings better.
2252                         // Warn about invalid options.
2253                         // Check whether some option was given twice.
2254                         end_inset(os);
2255                 }
2256
2257                 else if (t.cs() == "footnote" ||
2258                          (t.cs() == "thanks" && context.layout->intitle)) {
2259                         p.skip_spaces();
2260                         context.check_layout(os);
2261                         begin_inset(os, "Foot\n");
2262                         os << "status collapsed\n\n";
2263                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2264                         end_inset(os);
2265                 }
2266
2267                 else if (t.cs() == "marginpar") {
2268                         p.skip_spaces();
2269                         context.check_layout(os);
2270                         begin_inset(os, "Marginal\n");
2271                         os << "status collapsed\n\n";
2272                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2273                         end_inset(os);
2274                 }
2275
2276                 else if (t.cs() == "ensuremath") {
2277                         p.skip_spaces();
2278                         context.check_layout(os);
2279                         string const s = p.verbatim_item();
2280                         //FIXME: this never triggers in UTF8
2281                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2282                                 os << s;
2283                         else
2284                                 handle_ert(os, "\\ensuremath{" + s + "}",
2285                                            context);
2286                 }
2287
2288                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2289                         // FIXME: Somehow prevent title layouts if
2290                         // "maketitle" was not found
2291                         // swallow this
2292                         skip_spaces_braces(p);
2293                 }
2294
2295                 else if (t.cs() == "tableofcontents") {
2296                         context.check_layout(os);
2297                         begin_command_inset(os, "toc", "tableofcontents");
2298                         end_inset(os);
2299                         skip_spaces_braces(p);
2300                 }
2301
2302                 else if (t.cs() == "listoffigures") {
2303                         context.check_layout(os);
2304                         begin_inset(os, "FloatList figure\n");
2305                         end_inset(os);
2306                         skip_spaces_braces(p);
2307                 }
2308
2309                 else if (t.cs() == "listoftables") {
2310                         context.check_layout(os);
2311                         begin_inset(os, "FloatList table\n");
2312                         end_inset(os);
2313                         skip_spaces_braces(p);
2314                 }
2315
2316                 else if (t.cs() == "listof") {
2317                         p.skip_spaces(true);
2318                         string const name = p.get_token().cs();
2319                         if (context.textclass.floats().typeExist(name)) {
2320                                 context.check_layout(os);
2321                                 begin_inset(os, "FloatList ");
2322                                 os << name << "\n";
2323                                 end_inset(os);
2324                                 p.get_token(); // swallow second arg
2325                         } else
2326                                 handle_ert(os, "\\listof{" + name + "}", context);
2327                 }
2328
2329                 else if (t.cs() == "textrm")
2330                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2331                                               context, "\\family",
2332                                               context.font.family, "roman");
2333
2334                 else if (t.cs() == "textsf")
2335                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2336                                               context, "\\family",
2337                                               context.font.family, "sans");
2338
2339                 else if (t.cs() == "texttt")
2340                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2341                                               context, "\\family",
2342                                               context.font.family, "typewriter");
2343
2344                 else if (t.cs() == "textmd")
2345                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2346                                               context, "\\series",
2347                                               context.font.series, "medium");
2348
2349                 else if (t.cs() == "textbf")
2350                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2351                                               context, "\\series",
2352                                               context.font.series, "bold");
2353
2354                 else if (t.cs() == "textup")
2355                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2356                                               context, "\\shape",
2357                                               context.font.shape, "up");
2358
2359                 else if (t.cs() == "textit")
2360                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2361                                               context, "\\shape",
2362                                               context.font.shape, "italic");
2363
2364                 else if (t.cs() == "textsl")
2365                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2366                                               context, "\\shape",
2367                                               context.font.shape, "slanted");
2368
2369                 else if (t.cs() == "textsc")
2370                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2371                                               context, "\\shape",
2372                                               context.font.shape, "smallcaps");
2373
2374                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2375                         context.check_layout(os);
2376                         TeXFont oldFont = context.font;
2377                         context.font.init();
2378                         context.font.size = oldFont.size;
2379                         os << "\n\\family " << context.font.family << "\n";
2380                         os << "\n\\series " << context.font.series << "\n";
2381                         os << "\n\\shape " << context.font.shape << "\n";
2382                         if (t.cs() == "textnormal") {
2383                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2384                                 output_font_change(os, context.font, oldFont);
2385                                 context.font = oldFont;
2386                         } else
2387                                 eat_whitespace(p, os, context, false);
2388                 }
2389
2390                 else if (t.cs() == "textcolor") {
2391                         // scheme is \textcolor{color name}{text}
2392                         string const color = p.verbatim_item();
2393                         // we only support the predefined colors of the color package
2394                         if (color == "black" || color == "blue" || color == "cyan"
2395                                 || color == "green" || color == "magenta" || color == "red"
2396                                 || color == "white" || color == "yellow") {
2397                                         context.check_layout(os);
2398                                         os << "\n\\color " << color << "\n";
2399                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2400                                         context.check_layout(os);
2401                                         os << "\n\\color inherit\n";
2402                         } else
2403                                 // for custom defined colors
2404                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
2405                 }
2406
2407                 else if (t.cs() == "underbar" || t.cs() == "uline") {
2408                         // \underbar is not 100% correct (LyX outputs \uline
2409                         // of ulem.sty). The difference is that \ulem allows
2410                         // line breaks, and \underbar does not.
2411                         // Do NOT handle \underline.
2412                         // \underbar cuts through y, g, q, p etc.,
2413                         // \underline does not.
2414                         context.check_layout(os);
2415                         os << "\n\\bar under\n";
2416                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2417                         context.check_layout(os);
2418                         os << "\n\\bar default\n";
2419                 }
2420
2421                 else if (t.cs() == "emph" || t.cs() == "noun") {
2422                         context.check_layout(os);
2423                         os << "\n\\" << t.cs() << " on\n";
2424                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2425                         context.check_layout(os);
2426                         os << "\n\\" << t.cs() << " default\n";
2427                 }
2428
2429                 else if (t.cs() == "lyxline") {
2430                         // swallow size argument (it is not used anyway)
2431                         p.getArg('{', '}');
2432                         if (!context.atParagraphStart()) {
2433                                 // so our line is in the middle of a paragraph
2434                                 // we need to add a new line, lest this line
2435                                 // follow the other content on that line and
2436                                 // run off the side of the page
2437                                 // FIXME: This may create an empty paragraph,
2438                                 //        but without that it would not be
2439                                 //        possible to set noindent below.
2440                                 //        Fortunately LaTeX does not care
2441                                 //        about the empty paragraph.
2442                                 context.new_paragraph(os);
2443                         }
2444                         if (h_paragraph_separation == "indent") {
2445                                 // we need to unindent, lest the line be too long
2446                                 context.add_par_extra_stuff("\\noindent\n");
2447                         }
2448                         context.check_layout(os);
2449                         begin_command_inset(os, "line", "rule");
2450                         os << "offset \"0.5ex\"\n"
2451                               "width \"100line%\"\n"
2452                               "height \"1pt\"\n";
2453                         end_inset(os);
2454                 }
2455
2456                 else if (is_known(t.cs(), known_phrases) ||
2457                          (t.cs() == "protect" &&
2458                           p.next_token().cat() == catEscape &&
2459                           is_known(p.next_token().cs(), known_phrases))) {
2460                         // LyX sometimes puts a \protect in front, so we have to ignore it
2461                         // FIXME: This needs to be changed when bug 4752 is fixed.
2462                         char const * const * where = is_known(
2463                                 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2464                                 known_phrases);
2465                         context.check_layout(os);
2466                         os << known_coded_phrases[where - known_phrases];
2467                         skip_spaces_braces(p);
2468                 }
2469
2470                 else if (is_known(t.cs(), known_ref_commands)) {
2471                         string const opt = p.getOpt();
2472                         if (opt.empty()) {
2473                                 context.check_layout(os);
2474                                 begin_command_inset(os, "ref", t.cs());
2475                                 os << "reference \""
2476                                    << convert_command_inset_arg(p.verbatim_item())
2477                                    << "\"\n";
2478                                 end_inset(os);
2479                         } else {
2480                                 // LyX does not support optional arguments of ref commands
2481                                 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2482                                                p.verbatim_item() + "}", context);
2483                         }
2484                 }
2485
2486                 else if (use_natbib &&
2487                          is_known(t.cs(), known_natbib_commands) &&
2488                          ((t.cs() != "citefullauthor" &&
2489                            t.cs() != "citeyear" &&
2490                            t.cs() != "citeyearpar") ||
2491                           p.next_token().asInput() != "*")) {
2492                         context.check_layout(os);
2493                         string command = t.cs();
2494                         if (p.next_token().asInput() == "*") {
2495                                 command += '*';
2496                                 p.get_token();
2497                         }
2498                         if (command == "citefullauthor")
2499                                 // alternative name for "\\citeauthor*"
2500                                 command = "citeauthor*";
2501
2502                         // text before the citation
2503                         string before;
2504                         // text after the citation
2505                         string after;
2506                         get_cite_arguments(p, true, before, after);
2507
2508                         if (command == "cite") {
2509                                 // \cite without optional argument means
2510                                 // \citet, \cite with at least one optional
2511                                 // argument means \citep.
2512                                 if (before.empty() && after.empty())
2513                                         command = "citet";
2514                                 else
2515                                         command = "citep";
2516                         }
2517                         if (before.empty() && after == "[]")
2518                                 // avoid \citet[]{a}
2519                                 after.erase();
2520                         else if (before == "[]" && after == "[]") {
2521                                 // avoid \citet[][]{a}
2522                                 before.erase();
2523                                 after.erase();
2524                         }
2525                         // remove the brackets around after and before
2526                         if (!after.empty()) {
2527                                 after.erase(0, 1);
2528                                 after.erase(after.length() - 1, 1);
2529                                 after = convert_command_inset_arg(after);
2530                         }
2531                         if (!before.empty()) {
2532                                 before.erase(0, 1);
2533                                 before.erase(before.length() - 1, 1);
2534                                 before = convert_command_inset_arg(before);
2535                         }
2536                         begin_command_inset(os, "citation", command);
2537                         os << "after " << '"' << after << '"' << "\n";
2538                         os << "before " << '"' << before << '"' << "\n";
2539                         os << "key \""
2540                            << convert_command_inset_arg(p.verbatim_item())
2541                            << "\"\n";
2542                         end_inset(os);
2543                 }
2544
2545                 else if (use_jurabib &&
2546                          is_known(t.cs(), known_jurabib_commands) &&
2547                          (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2548                         context.check_layout(os);
2549                         string command = t.cs();
2550                         if (p.next_token().asInput() == "*") {
2551                                 command += '*';
2552                                 p.get_token();
2553                         }
2554                         char argumentOrder = '\0';
2555                         vector<string> const & options = used_packages["jurabib"];
2556                         if (find(options.begin(), options.end(),
2557                                       "natbiborder") != options.end())
2558                                 argumentOrder = 'n';
2559                         else if (find(options.begin(), options.end(),
2560                                            "jurabiborder") != options.end())
2561                                 argumentOrder = 'j';
2562
2563                         // text before the citation
2564                         string before;
2565                         // text after the citation
2566                         string after;
2567                         get_cite_arguments(p, argumentOrder != 'j', before, after);
2568
2569                         string const citation = p.verbatim_item();
2570                         if (!before.empty() && argumentOrder == '\0') {
2571                                 cerr << "Warning: Assuming argument order "
2572                                         "of jurabib version 0.6 for\n'"
2573                                      << command << before << after << '{'
2574                                      << citation << "}'.\n"
2575                                         "Add 'jurabiborder' to the jurabib "
2576                                         "package options if you used an\n"
2577                                         "earlier jurabib version." << endl;
2578                         }
2579                         if (!after.empty()) {
2580                                 after.erase(0, 1);
2581                                 after.erase(after.length() - 1, 1);
2582                         }
2583                         if (!before.empty()) {
2584                                 before.erase(0, 1);
2585                                 before.erase(before.length() - 1, 1);
2586                         }
2587                         begin_command_inset(os, "citation", command);
2588                         os << "after " << '"' << after << '"' << "\n";
2589                         os << "before " << '"' << before << '"' << "\n";
2590                         os << "key " << '"' << citation << '"' << "\n";
2591                         end_inset(os);
2592                 }
2593
2594                 else if (t.cs() == "cite"
2595                         || t.cs() == "nocite") {
2596                         context.check_layout(os);
2597                         string after = convert_command_inset_arg(p.getArg('[', ']'));
2598                         string key = convert_command_inset_arg(p.verbatim_item());
2599                         // store the case that it is "\nocite{*}" to use it later for
2600                         // the BibTeX inset
2601                         if (key != "*") {
2602                                 begin_command_inset(os, "citation", t.cs());
2603                                 os << "after " << '"' << after << '"' << "\n";
2604                                 os << "key " << '"' << key << '"' << "\n";
2605                                 end_inset(os);
2606                         } else if (t.cs() == "nocite")
2607                                 btprint = key;
2608                 }
2609
2610                 else if (t.cs() == "index") {
2611                         context.check_layout(os);
2612                         begin_inset(os, "Index idx\n");
2613                         os << "status collapsed\n";
2614                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2615                         end_inset(os);
2616                 }
2617
2618                 else if (t.cs() == "nomenclature") {
2619                         context.check_layout(os);
2620                         begin_command_inset(os, "nomenclature", "nomenclature");
2621                         string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2622                         if (!prefix.empty())
2623                                 os << "prefix " << '"' << prefix << '"' << "\n";
2624                         os << "symbol " << '"'
2625                            << convert_command_inset_arg(p.verbatim_item());
2626                         os << "\"\ndescription \""
2627                            << convert_command_inset_arg(p.verbatim_item())
2628                            << "\"\n";
2629                         end_inset(os);
2630                 }
2631                 
2632                 else if (t.cs() == "label") {
2633                         context.check_layout(os);
2634                         begin_command_inset(os, "label", "label");
2635                         os << "name \""
2636                            << convert_command_inset_arg(p.verbatim_item())
2637                            << "\"\n";
2638                         end_inset(os);
2639                 }
2640
2641                 else if (t.cs() == "printindex") {
2642                         context.check_layout(os);
2643                         begin_command_inset(os, "index_print", "printindex");
2644                         os << "type \"idx\"\n";
2645                         end_inset(os);
2646                         skip_spaces_braces(p);
2647                 }
2648
2649                 else if (t.cs() == "printnomenclature") {
2650                         context.check_layout(os);
2651                         begin_command_inset(os, "nomencl_print", "printnomenclature");
2652                         end_inset(os);
2653                         skip_spaces_braces(p);
2654                 }
2655
2656                 else if (LYX_FORMAT >= 408 &&
2657                          (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2658                         context.check_layout(os);
2659                         begin_inset(os, "script ");
2660                         os << t.cs().substr(4) << '\n';
2661                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2662                         end_inset(os);
2663                 }
2664
2665                 else if (is_known(t.cs(), known_quotes)) {
2666                         char const * const * where = is_known(t.cs(), known_quotes);
2667                         context.check_layout(os);
2668                         begin_inset(os, "Quotes ");
2669                         os << known_coded_quotes[where - known_quotes];
2670                         end_inset(os);
2671                         // LyX adds {} after the quote, so we have to eat
2672                         // spaces here if there are any before a possible
2673                         // {} pair.
2674                         eat_whitespace(p, os, context, false);
2675                         skip_braces(p);
2676                 }
2677
2678                 else if (is_known(t.cs(), known_sizes) &&
2679                          context.new_layout_allowed) {
2680                         char const * const * where = is_known(t.cs(), known_sizes);
2681                         context.check_layout(os);
2682                         TeXFont const oldFont = context.font;
2683                         context.font.size = known_coded_sizes[where - known_sizes];
2684                         output_font_change(os, oldFont, context.font);
2685                         eat_whitespace(p, os, context, false);
2686                 }
2687
2688                 else if (is_known(t.cs(), known_font_families) &&
2689                          context.new_layout_allowed) {
2690                         char const * const * where =
2691                                 is_known(t.cs(), known_font_families);
2692                         context.check_layout(os);
2693                         TeXFont const oldFont = context.font;
2694                         context.font.family =
2695                                 known_coded_font_families[where - known_font_families];
2696                         output_font_change(os, oldFont, context.font);
2697                         eat_whitespace(p, os, context, false);
2698                 }
2699
2700                 else if (is_known(t.cs(), known_font_series) &&
2701                          context.new_layout_allowed) {
2702                         char const * const * where =
2703                                 is_known(t.cs(), known_font_series);
2704                         context.check_layout(os);
2705                         TeXFont const oldFont = context.font;
2706                         context.font.series =
2707                                 known_coded_font_series[where - known_font_series];
2708                         output_font_change(os, oldFont, context.font);
2709                         eat_whitespace(p, os, context, false);
2710                 }
2711
2712                 else if (is_known(t.cs(), known_font_shapes) &&
2713                          context.new_layout_allowed) {
2714                         char const * const * where =
2715                                 is_known(t.cs(), known_font_shapes);
2716                         context.check_layout(os);
2717                         TeXFont const oldFont = context.font;
2718                         context.font.shape =
2719                                 known_coded_font_shapes[where - known_font_shapes];
2720                         output_font_change(os, oldFont, context.font);
2721                         eat_whitespace(p, os, context, false);
2722                 }
2723                 else if (is_known(t.cs(), known_old_font_families) &&
2724                          context.new_layout_allowed) {
2725                         char const * const * where =
2726                                 is_known(t.cs(), known_old_font_families);
2727                         context.check_layout(os);
2728                         TeXFont const oldFont = context.font;
2729                         context.font.init();
2730                         context.font.size = oldFont.size;
2731                         context.font.family =
2732                                 known_coded_font_families[where - known_old_font_families];
2733                         output_font_change(os, oldFont, context.font);
2734                         eat_whitespace(p, os, context, false);
2735                 }
2736
2737                 else if (is_known(t.cs(), known_old_font_series) &&
2738                          context.new_layout_allowed) {
2739                         char const * const * where =
2740                                 is_known(t.cs(), known_old_font_series);
2741                         context.check_layout(os);
2742                         TeXFont const oldFont = context.font;
2743                         context.font.init();
2744                         context.font.size = oldFont.size;
2745                         context.font.series =
2746                                 known_coded_font_series[where - known_old_font_series];
2747                         output_font_change(os, oldFont, context.font);
2748                         eat_whitespace(p, os, context, false);
2749                 }
2750
2751                 else if (is_known(t.cs(), known_old_font_shapes) &&
2752                          context.new_layout_allowed) {
2753                         char const * const * where =
2754                                 is_known(t.cs(), known_old_font_shapes);
2755                         context.check_layout(os);
2756                         TeXFont const oldFont = context.font;
2757                         context.font.init();
2758                         context.font.size = oldFont.size;
2759                         context.font.shape =
2760                                 known_coded_font_shapes[where - known_old_font_shapes];
2761                         output_font_change(os, oldFont, context.font);
2762                         eat_whitespace(p, os, context, false);
2763                 }
2764
2765                 else if (t.cs() == "selectlanguage") {
2766                         context.check_layout(os);
2767                         // save the language for the case that a
2768                         // \foreignlanguage is used 
2769
2770                         context.font.language = babel2lyx(p.verbatim_item());
2771                         os << "\n\\lang " << context.font.language << "\n";
2772                 }
2773
2774                 else if (t.cs() == "foreignlanguage") {
2775                         string const lang = babel2lyx(p.verbatim_item());
2776                         parse_text_attributes(p, os, FLAG_ITEM, outer,
2777                                               context, "\\lang",
2778                                               context.font.language, lang);
2779                 }
2780
2781                 else if (t.cs() == "inputencoding") {
2782                         // nothing to write here
2783                         string const enc = subst(p.verbatim_item(), "\n", " ");
2784                         p.setEncoding(enc);
2785                 }
2786
2787                 else if (t.cs() == "ldots") {
2788                         context.check_layout(os);
2789                         os << "\\SpecialChar \\ldots{}\n";
2790                         skip_spaces_braces(p);
2791                 }
2792
2793                 else if (t.cs() == "lyxarrow") {
2794                         context.check_layout(os);
2795                         os << "\\SpecialChar \\menuseparator\n";
2796                         skip_spaces_braces(p);
2797                 }
2798
2799                 else if (t.cs() == "textcompwordmark") {
2800                         context.check_layout(os);
2801                         os << "\\SpecialChar \\textcompwordmark{}\n";
2802                         skip_spaces_braces(p);
2803                 }
2804
2805                 else if (t.cs() == "slash") {
2806                         context.check_layout(os);
2807                         os << "\\SpecialChar \\slash{}\n";
2808                         skip_spaces_braces(p);
2809                 }
2810
2811                 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2812                         context.check_layout(os);
2813                         os << "\\SpecialChar \\nobreakdash-\n";
2814                         p.get_token();
2815                 }
2816
2817                 else if (t.cs() == "textquotedbl") {
2818                         context.check_layout(os);
2819                         os << "\"";
2820                         skip_braces(p);
2821                 }
2822
2823                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2824                         context.check_layout(os);
2825                         os << "\\SpecialChar \\@.\n";
2826                         p.get_token();
2827                 }
2828
2829                 else if (t.cs() == "-") {
2830                         context.check_layout(os);
2831                         os << "\\SpecialChar \\-\n";
2832                 }
2833
2834                 else if (t.cs() == "textasciitilde") {
2835                         context.check_layout(os);
2836                         os << '~';
2837                         skip_spaces_braces(p);
2838                 }
2839
2840                 else if (t.cs() == "textasciicircum") {
2841                         context.check_layout(os);
2842                         os << '^';
2843                         skip_spaces_braces(p);
2844                 }
2845
2846                 else if (t.cs() == "textbackslash") {
2847                         context.check_layout(os);
2848                         os << "\n\\backslash\n";
2849                         skip_spaces_braces(p);
2850                 }
2851
2852                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2853                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2854                             || t.cs() == "%") {
2855                         context.check_layout(os);
2856                         os << t.cs();
2857                 }
2858
2859                 else if (t.cs() == "char") {
2860                         context.check_layout(os);
2861                         if (p.next_token().character() == '`') {
2862                                 p.get_token();
2863                                 if (p.next_token().cs() == "\"") {
2864                                         p.get_token();
2865                                         os << '"';
2866                                         skip_braces(p);
2867                                 } else {
2868                                         handle_ert(os, "\\char`", context);
2869                                 }
2870                         } else {
2871                                 handle_ert(os, "\\char", context);
2872                         }
2873                 }
2874
2875                 else if (t.cs() == "verb") {
2876                         context.check_layout(os);
2877                         char const delimiter = p.next_token().character();
2878                         string const arg = p.getArg(delimiter, delimiter);
2879                         ostringstream oss;
2880                         oss << "\\verb" << delimiter << arg << delimiter;
2881                         handle_ert(os, oss.str(), context);
2882                 }
2883
2884                 // Problem: \= creates a tabstop inside the tabbing environment
2885                 // and else an accent. In the latter case we really would want
2886                 // \={o} instead of \= o.
2887                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2888                         handle_ert(os, t.asInput(), context);
2889
2890                 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2891                 else if (t.cs().size() == 1 
2892                          && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2893                         context.check_layout(os);
2894                         // try to see whether the string is in unicodesymbols
2895                         docstring rem;
2896                         string command = t.asInput() + "{" 
2897                                 + trimSpaceAndEol(p.verbatim_item())
2898                                 + "}";
2899                         docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2900                         if (!s.empty()) {
2901                                 if (!rem.empty())
2902                                         cerr << "When parsing " << command 
2903                                              << ", result is " << to_utf8(s)
2904                                              << "+" << to_utf8(rem) << endl;
2905                                 os << to_utf8(s);
2906                         } else
2907                                 // we did not find a non-ert version
2908                                 handle_ert(os, command, context);
2909                 }
2910
2911                 else if (t.cs() == "\\") {
2912                         context.check_layout(os);
2913                         if (p.hasOpt())
2914                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2915                         else if (p.next_token().asInput() == "*") {
2916                                 p.get_token();
2917                                 // getOpt() eats the following space if there
2918                                 // is no optional argument, but that is OK
2919                                 // here since it has no effect in the output.
2920                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2921                         }
2922                         else {
2923                                 begin_inset(os, "Newline newline");
2924                                 end_inset(os);
2925                         }
2926                 }
2927
2928                 else if (t.cs() == "newline" ||
2929                          (t.cs() == "linebreak" && !p.hasOpt())) {
2930                         context.check_layout(os);
2931                         begin_inset(os, "Newline ");
2932                         os << t.cs();
2933                         end_inset(os);
2934                         skip_spaces_braces(p);
2935                 }
2936
2937                 else if (t.cs() == "input" || t.cs() == "include"
2938                          || t.cs() == "verbatiminput") {
2939                         string name = t.cs();
2940                         if (t.cs() == "verbatiminput"
2941                             && p.next_token().asInput() == "*")
2942                                 name += p.get_token().asInput();
2943                         context.check_layout(os);
2944                         string filename(normalize_filename(p.getArg('{', '}')));
2945                         string const path = getMasterFilePath();
2946                         // We want to preserve relative / absolute filenames,
2947                         // therefore path is only used for testing
2948                         if ((t.cs() == "include" || t.cs() == "input") &&
2949                             !makeAbsPath(filename, path).exists()) {
2950                                 // The file extension is probably missing.
2951                                 // Now try to find it out.
2952                                 string const tex_name =
2953                                         find_file(filename, path,
2954                                                   known_tex_extensions);
2955                                 if (!tex_name.empty())
2956                                         filename = tex_name;
2957                         }
2958                         bool external = false;
2959                         string outname;
2960                         if (makeAbsPath(filename, path).exists()) {
2961                                 string const abstexname =
2962                                         makeAbsPath(filename, path).absFileName();
2963                                 string const abslyxname =
2964                                         changeExtension(abstexname, ".lyx");
2965                                 string const absfigname =
2966                                         changeExtension(abstexname, ".fig");
2967                                 fix_relative_filename(filename);
2968                                 string const lyxname =
2969                                         changeExtension(filename, ".lyx");
2970                                 bool xfig = false;
2971                                 external = FileName(absfigname).exists();
2972                                 if (t.cs() == "input") {
2973                                         string const ext = getExtension(abstexname);
2974
2975                                         // Combined PS/LaTeX:
2976                                         // x.eps, x.pstex_t (old xfig)
2977                                         // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2978                                         FileName const absepsname(
2979                                                 changeExtension(abstexname, ".eps"));
2980                                         FileName const abspstexname(
2981                                                 changeExtension(abstexname, ".pstex"));
2982                                         bool const xfigeps =
2983                                                 (absepsname.exists() ||
2984                                                  abspstexname.exists()) &&
2985                                                 ext == "pstex_t";
2986
2987                                         // Combined PDF/LaTeX:
2988                                         // x.pdf, x.pdftex_t (old xfig)
2989                                         // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2990                                         FileName const abspdfname(
2991                                                 changeExtension(abstexname, ".pdf"));
2992                                         bool const xfigpdf =
2993                                                 abspdfname.exists() &&
2994                                                 (ext == "pdftex_t" || ext == "pdf_t");
2995                                         if (xfigpdf)
2996                                                 pdflatex = true;
2997
2998                                         // Combined PS/PDF/LaTeX:
2999                                         // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3000                                         string const absbase2(
3001                                                 removeExtension(abstexname) + "_pspdftex");
3002                                         FileName const abseps2name(
3003                                                 addExtension(absbase2, ".eps"));
3004                                         FileName const abspdf2name(
3005                                                 addExtension(absbase2, ".pdf"));
3006                                         bool const xfigboth =
3007                                                 abspdf2name.exists() &&
3008                                                 abseps2name.exists() && ext == "pspdftex";
3009
3010                                         xfig = xfigpdf || xfigeps || xfigboth;
3011                                         external = external && xfig;
3012                                 }
3013                                 if (external) {
3014                                         outname = changeExtension(filename, ".fig");
3015                                 } else if (xfig) {
3016                                         // Don't try to convert, the result
3017                                         // would be full of ERT.
3018                                         outname = filename;
3019                                 } else if (t.cs() != "verbatiminput" &&
3020                                     tex2lyx(abstexname, FileName(abslyxname),
3021                                             p.getEncoding())) {
3022                                         outname = lyxname;
3023                                 } else {
3024                                         outname = filename;
3025                                 }
3026                         } else {
3027                                 cerr << "Warning: Could not find included file '"
3028                                      << filename << "'." << endl;
3029                                 outname = filename;
3030                         }
3031                         if (external) {
3032                                 begin_inset(os, "External\n");
3033                                 os << "\ttemplate XFig\n"
3034                                    << "\tfilename " << outname << '\n';
3035                         } else {
3036                                 begin_command_inset(os, "include", name);
3037                                 os << "preview false\n"
3038                                       "filename \"" << outname << "\"\n";
3039                         }
3040                         end_inset(os);
3041                 }
3042
3043                 else if (t.cs() == "bibliographystyle") {
3044                         // store new bibliographystyle
3045                         bibliographystyle = p.verbatim_item();
3046                         // If any other command than \bibliography and
3047                         // \nocite{*} follows, we need to output the style
3048                         // (because it might be used by that command).
3049                         // Otherwise, it will automatically be output by LyX.
3050                         p.pushPosition();
3051                         bool output = true;
3052                         for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3053                                 if (t2.cat() == catBegin)
3054                                         break;
3055                                 if (t2.cat() != catEscape)
3056                                         continue;
3057                                 if (t2.cs() == "nocite") {
3058                                         if (p.getArg('{', '}') == "*")
3059                                                 continue;
3060                                 } else if (t2.cs() == "bibliography")
3061                                         output = false;
3062                                 break;
3063                         }
3064                         p.popPosition();
3065                         if (output) {
3066                                 handle_ert(os,
3067                                         "\\bibliographystyle{" + bibliographystyle + '}',
3068                                         context);
3069                         }
3070                 }
3071
3072                 else if (t.cs() == "bibliography") {
3073                         context.check_layout(os);
3074                         begin_command_inset(os, "bibtex", "bibtex");
3075                         if (!btprint.empty()) {
3076                                 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3077                                 // clear the string because the next BibTeX inset can be without the
3078                                 // \nocite{*} option
3079                                 btprint.clear();
3080                         }
3081                         os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3082                         // Do we have a bibliographystyle set?
3083                         if (!bibliographystyle.empty())
3084                                 os << "options " << '"' << bibliographystyle << '"' << "\n";
3085                         end_inset(os);
3086                 }
3087
3088                 else if (t.cs() == "parbox")
3089                         parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3090
3091                 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3092                          t.cs() == "shadowbox" || t.cs() == "doublebox")
3093                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3094
3095                 else if (t.cs() == "framebox") {
3096                         string special = p.getFullOpt();
3097                         special += p.getOpt();
3098                         parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3099                 }
3100
3101                 //\makebox() is part of the picture environment and different from \makebox{}
3102                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3103                 else if (t.cs() == "makebox") {
3104                         string arg = t.asInput();
3105                         if (p.next_token().character() == '(')
3106                                 //the syntax is: \makebox(x,y)[position]{content}
3107                                 arg += p.getFullParentheseArg();
3108                         else
3109                                 //the syntax is: \makebox[width][position]{content}
3110                                 arg += p.getFullOpt();
3111                         handle_ert(os, arg + p.getFullOpt(), context);
3112                 }
3113
3114                 else if (t.cs() == "smallskip" ||
3115                          t.cs() == "medskip" ||
3116                          t.cs() == "bigskip" ||
3117                          t.cs() == "vfill") {
3118                         context.check_layout(os);
3119                         begin_inset(os, "VSpace ");
3120                         os << t.cs();
3121                         end_inset(os);
3122                         skip_spaces_braces(p);
3123                 }
3124
3125                 else if (is_known(t.cs(), known_spaces)) {
3126                         char const * const * where = is_known(t.cs(), known_spaces);
3127                         context.check_layout(os);
3128                         begin_inset(os, "space ");
3129                         os << '\\' << known_coded_spaces[where - known_spaces]
3130                            << '\n';
3131                         end_inset(os);
3132                         // LaTeX swallows whitespace after all spaces except
3133                         // "\\,". We have to do that here, too, because LyX
3134                         // adds "{}" which would make the spaces significant.
3135                         if (t.cs() !=  ",")
3136                                 eat_whitespace(p, os, context, false);
3137                         // LyX adds "{}" after all spaces except "\\ " and
3138                         // "\\,", so we have to remove "{}".
3139                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
3140                         // remove the braces after "\\,", too.
3141                         if (t.cs() != " ")
3142                                 skip_braces(p);
3143                 }
3144
3145                 else if (t.cs() == "newpage" ||
3146                          (t.cs() == "pagebreak" && !p.hasOpt()) ||
3147                          t.cs() == "clearpage" ||
3148                          t.cs() == "cleardoublepage") {
3149                         context.check_layout(os);
3150                         begin_inset(os, "Newpage ");
3151                         os << t.cs();
3152                         end_inset(os);
3153                         skip_spaces_braces(p);
3154                 }
3155
3156                 else if (t.cs() == "DeclareRobustCommand" ||
3157                          t.cs() == "DeclareRobustCommandx" ||
3158                          t.cs() == "newcommand" ||
3159                          t.cs() == "newcommandx" ||
3160                          t.cs() == "providecommand" ||
3161                          t.cs() == "providecommandx" ||
3162                          t.cs() == "renewcommand" ||
3163                          t.cs() == "renewcommandx") {
3164                         // DeclareRobustCommand, DeclareRobustCommandx,
3165                         // providecommand and providecommandx could be handled
3166                         // by parse_command(), but we need to call
3167                         // add_known_command() here.
3168                         string name = t.asInput();
3169                         if (p.next_token().asInput() == "*") {
3170                                 // Starred form. Eat '*'
3171                                 p.get_token();
3172                                 name += '*';
3173                         }
3174                         string const command = p.verbatim_item();
3175                         string const opt1 = p.getFullOpt();
3176                         string const opt2 = p.getFullOpt();
3177                         add_known_command(command, opt1, !opt2.empty());
3178                         string const ert = name + '{' + command + '}' +
3179                                            opt1 + opt2 +
3180                                            '{' + p.verbatim_item() + '}';
3181
3182                         if (t.cs() == "DeclareRobustCommand" ||
3183                             t.cs() == "DeclareRobustCommandx" ||
3184                             t.cs() == "providecommand" ||
3185                             t.cs() == "providecommandx" ||
3186                             name[name.length()-1] == '*')
3187                                 handle_ert(os, ert, context);
3188                         else {
3189                                 context.check_layout(os);
3190                                 begin_inset(os, "FormulaMacro");
3191                                 os << "\n" << ert;
3192                                 end_inset(os);
3193                         }
3194                 }
3195
3196                 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3197                         // let could be handled by parse_command(),
3198                         // but we need to call add_known_command() here.
3199                         string ert = t.asInput();
3200                         string name;
3201                         p.skip_spaces();
3202                         if (p.next_token().cat() == catBegin) {
3203                                 name = p.verbatim_item();
3204                                 ert += '{' + name + '}';
3205                         } else {
3206                                 name = p.verbatim_item();
3207                                 ert += name;
3208                         }
3209                         string command;
3210                         p.skip_spaces();
3211                         if (p.next_token().cat() == catBegin) {
3212                                 command = p.verbatim_item();
3213                                 ert += '{' + command + '}';
3214                         } else {
3215                                 command = p.verbatim_item();
3216                                 ert += command;
3217                         }
3218                         // If command is known, make name known too, to parse
3219                         // its arguments correctly. For this reason we also
3220                         // have commands in syntax.default that are hardcoded.
3221                         CommandMap::iterator it = known_commands.find(command);
3222                         if (it != known_commands.end())
3223                                 known_commands[t.asInput()] = it->second;
3224                         handle_ert(os, ert, context);
3225                 }
3226
3227                 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3228                         bool starred = false;
3229                         if (p.next_token().asInput() == "*") {
3230                                 p.get_token();
3231                                 starred = true;
3232                         }
3233                         string name = t.asInput();
3234                         string const length = p.verbatim_item();
3235                         string unit;
3236                         string valstring;
3237                         bool valid = splitLatexLength(length, valstring, unit);
3238                         bool known_hspace = false;
3239                         bool known_vspace = false;
3240                         bool known_unit = false;
3241                         double value;
3242                         if (valid) {
3243                                 istringstream iss(valstring);
3244                                 iss >> value;
3245                                 if (value == 1.0) {
3246                                         if (t.cs()[0] == 'h') {
3247                                                 if (unit == "\\fill") {
3248                                                         if (!starred) {
3249                                                                 unit = "";
3250                                                                 name = "\\hfill";
3251                                                         }
3252                                                         known_hspace = true;
3253                                                 }
3254                                         } else {
3255                                                 if (unit == "\\smallskipamount") {
3256                                                         unit = "smallskip";
3257                                                         known_vspace = true;
3258                                                 } else if (unit == "\\medskipamount") {
3259                                                         unit = "medskip";
3260                                                         known_vspace = true;
3261                                                 } else if (unit == "\\bigskipamount") {
3262                                                         unit = "bigskip";
3263                                                         known_vspace = true;
3264                                                 } else if (unit == "\\fill") {
3265                                                         unit = "vfill";
3266                                                         known_vspace = true;
3267                                                 }
3268                                         }
3269                                 }
3270                                 if (!known_hspace && !known_vspace) {
3271                                         switch (unitFromString(unit)) {
3272                                         case Length::SP:
3273                                         case Length::PT:
3274                                         case Length::BP:
3275                                         case Length::DD:
3276                                         case Length::MM:
3277                                         case Length::PC:
3278                                         case Length::CC:
3279                                         case Length::CM:
3280                                         case Length::IN:
3281                                         case Length::EX:
3282                                         case Length::EM:
3283                                         case Length::MU:
3284                                                 known_unit = true;
3285                                                 break;
3286                                         default:
3287                                                 break;
3288                                         }
3289                                 }
3290                         }
3291
3292                         if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3293                                 // Literal horizontal length or known variable
3294                                 context.check_layout(os);
3295                                 begin_inset(os, "space ");
3296                                 os << name;
3297                                 if (starred)
3298                                         os << '*';
3299                                 os << '{';
3300                                 if (known_hspace)
3301                                         os << unit;
3302                                 os << "}";
3303                                 if (known_unit && !known_hspace)
3304                                         os << "\n\\length "
3305                                            << translate_len(length);
3306                                 end_inset(os);
3307                         } else if (known_unit || known_vspace) {
3308                                 // Literal vertical length or known variable
3309                                 context.check_layout(os);
3310                                 begin_inset(os, "VSpace ");
3311                                 if (known_unit)
3312                                         os << value;
3313                                 os << unit;
3314                                 if (starred)
3315                                         os << '*';
3316                                 end_inset(os);
3317                         } else {
3318                                 // LyX can't handle other length variables in Inset VSpace/space
3319                                 if (starred)
3320                                         name += '*';
3321                                 if (valid) {
3322                                         if (value == 1.0)
3323                                                 handle_ert(os, name + '{' + unit + '}', context);
3324                                         else if (value == -1.0)
3325                                                 handle_ert(os, name + "{-" + unit + '}', context);
3326                                         else
3327                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
3328                                 } else
3329                                         handle_ert(os, name + '{' + length + '}', context);
3330                         }
3331                 }
3332
3333                 // The single '=' is meant here.
3334                 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3335                         p.skip_spaces();
3336                         context.check_layout(os);
3337                         begin_inset(os, "Flex ");
3338                         os << to_utf8(newinsetlayout->name()) << '\n'
3339                            << "status collapsed\n";
3340                         parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3341                         end_inset(os);
3342                 }
3343
3344                 else {
3345                         // try to see whether the string is in unicodesymbols
3346                         // Only use text mode commands, since we are in text mode here,
3347                         // and math commands may be invalid (bug 6797)
3348                         docstring rem;
3349                         docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3350                                                                  rem, Encodings::TEXT_CMD);
3351                         if (!s.empty()) {
3352                                 if (!rem.empty())
3353                                         cerr << "When parsing " << t.cs() 
3354                                              << ", result is " << to_utf8(s)
3355                                              << "+" << to_utf8(rem) << endl;
3356                                 context.check_layout(os);
3357                                 os << to_utf8(s);
3358                                 skip_spaces_braces(p);
3359                         }
3360                         //cerr << "#: " << t << " mode: " << mode << endl;
3361                         // heuristic: read up to next non-nested space
3362                         /*
3363                         string s = t.asInput();
3364                         string z = p.verbatim_item();
3365                         while (p.good() && z != " " && z.size()) {
3366                                 //cerr << "read: " << z << endl;
3367                                 s += z;
3368                                 z = p.verbatim_item();
3369                         }
3370                         cerr << "found ERT: " << s << endl;
3371                         handle_ert(os, s + ' ', context);
3372                         */
3373                         else {
3374                                 string name = t.asInput();
3375                                 if (p.next_token().asInput() == "*") {
3376                                         // Starred commands like \vspace*{}
3377                                         p.get_token();  // Eat '*'
3378                                         name += '*';
3379                                 }
3380                                 if (!parse_command(name, p, os, outer, context))
3381                                         handle_ert(os, name, context);
3382                         }
3383                 }
3384
3385                 if (flags & FLAG_LEAVE) {
3386                         flags &= ~FLAG_LEAVE;
3387                         break;
3388                 }
3389         }
3390 }
3391
3392 // }])
3393
3394
3395 } // namespace lyx