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