]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.cpp
tex2lyx/text.cpp: \InsetSpace has no begin and end (LyX 1.5 was tolerant to the missi...
[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 "FloatList.h"
21 #include "Layout.h"
22 #include "Length.h"
23
24 #include "support/assert.h"
25 #include "support/convert.h"
26 #include "support/FileName.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h"
29
30 #include <algorithm>
31 #include <iostream>
32 #include <map>
33 #include <sstream>
34 #include <vector>
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40
41
42 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
43                 Context const & context)
44 {
45         Context newcontext(true, context.textclass);
46         newcontext.font = context.font;
47         parse_text(p, os, flags, outer, newcontext);
48         newcontext.check_end_layout(os);
49 }
50
51
52 namespace {
53
54 /// parses a paragraph snippet, useful for example for \\emph{...}
55 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
56                 Context & context)
57 {
58         Context newcontext(context);
59         // Don't inherit the extra stuff
60         newcontext.extra_stuff.clear();
61         parse_text(p, os, flags, outer, newcontext);
62         // Make sure that we don't create invalid .lyx files
63         context.need_layout = newcontext.need_layout;
64         context.need_end_layout = newcontext.need_end_layout;
65 }
66
67
68 /*!
69  * Thin wrapper around parse_text_snippet() using a string.
70  *
71  * We completely ignore \c context.need_layout and \c context.need_end_layout,
72  * because our return value is not used directly (otherwise the stream version
73  * of parse_text_snippet() could be used). That means that the caller needs
74  * to do layout management manually.
75  * This is intended to parse text that does not create any layout changes.
76  */
77 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
78                   Context & context)
79 {
80         Context newcontext(context);
81         newcontext.need_layout = false;
82         newcontext.need_end_layout = false;
83         newcontext.new_layout_allowed = false;
84         // Avoid warning by Context::~Context()
85         newcontext.extra_stuff.clear();
86         ostringstream os;
87         parse_text_snippet(p, os, flags, outer, newcontext);
88         return os.str();
89 }
90
91
92 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
93  "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
94  "eqref", 0 };
95
96 /*!
97  * natbib commands.
98  * We can't put these into known_latex_commands because the argument order
99  * is reversed in lyx if there are 2 arguments.
100  * The starred forms are also known.
101  */
102 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
103 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
104 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
105
106 /*!
107  * jurabib commands.
108  * We can't put these into known_latex_commands because the argument order
109  * is reversed in lyx if there are 2 arguments.
110  * No starred form other than "cite*" known.
111  */
112 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 // jurabib commands not (yet) supported by LyX:
115 // "fullcite",
116 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
117 // "footciteauthor", "footciteyear", "footciteyearpar",
118 "citefield", "citetitle", "cite*", 0 };
119
120 /// LaTeX names for quotes
121 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
122 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
123 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
124 "guilsinglleft", "frq", "guilsinglright", 0};
125
126 /// the same as known_quotes with .lyx names
127 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
128 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
129 "gld", "grd", "gls", "ers", "fls",
130 "fls", "frs", "frs", 0};
131
132 /// LaTeX names for font sizes
133 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
134 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
135
136 /// the same as known_sizes with .lyx names
137 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
138 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
139
140 /// LaTeX 2.09 names for font families
141 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
142
143 /// LaTeX names for font families
144 char const * const known_font_families[] = { "rmfamily", "sffamily",
145 "ttfamily", 0};
146
147 /// the same as known_old_font_families and known_font_families with .lyx names
148 char const * const known_coded_font_families[] = { "roman", "sans",
149 "typewriter", 0};
150
151 /// LaTeX 2.09 names for font series
152 char const * const known_old_font_series[] = { "bf", 0};
153
154 /// LaTeX names for font series
155 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
156
157 /// the same as known_old_font_series and known_font_series with .lyx names
158 char const * const known_coded_font_series[] = { "bold", "medium", 0};
159
160 /// LaTeX 2.09 names for font shapes
161 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
162
163 /// LaTeX names for font shapes
164 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
165 "upshape", 0};
166
167 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
168 char const * const known_coded_font_shapes[] = { "italic", "slanted",
169 "smallcaps", "up", 0};
170
171 /*!
172  * Graphics file extensions known by the dvips driver of the graphics package.
173  * These extensions are used to complete the filename of an included
174  * graphics file if it does not contain an extension.
175  * The order must be the same that latex uses to find a file, because we
176  * will use the first extension that matches.
177  * This is only an approximation for the common cases. If we would want to
178  * do it right in all cases, we would need to know which graphics driver is
179  * used and know the extensions of every driver of the graphics package.
180  */
181 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
182 "ps.gz", "eps.Z", "ps.Z", 0};
183
184 /*!
185  * Graphics file extensions known by the pdftex driver of the graphics package.
186  * \sa known_dvips_graphics_formats
187  */
188 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
189 "mps", "tif", 0};
190
191 /*!
192  * Known file extensions for TeX files as used by \\include.
193  */
194 char const * const known_tex_extensions[] = {"tex", 0};
195
196 /// spaces known by InsetSpace
197 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
198 "qquad", "enspace", "enskip", "negthinspace", 0};
199
200 /// the same as known_spaces with .lyx names
201 char const * const known_coded_spaces[] = { "space{}", "space{}",
202 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
203 "negthinspace{}", 0};
204
205
206 /// splits "x=z, y=b" into a map
207 map<string, string> split_map(string const & s)
208 {
209         map<string, string> res;
210         vector<string> v;
211         split(s, v);
212         for (size_t i = 0; i < v.size(); ++i) {
213                 size_t const pos   = v[i].find('=');
214                 string const index = v[i].substr(0, pos);
215                 string const value = v[i].substr(pos + 1, string::npos);
216                 res[trim(index)] = trim(value);
217         }
218         return res;
219 }
220
221
222 /*!
223  * Split a LaTeX length into value and unit.
224  * The latter can be a real unit like "pt", or a latex length variable
225  * like "\textwidth". The unit may contain additional stuff like glue
226  * lengths, but we don't care, because such lengths are ERT anyway.
227  * \returns true if \p value and \p unit are valid.
228  */
229 bool splitLatexLength(string const & len, string & value, string & unit)
230 {
231         if (len.empty())
232                 return false;
233         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
234         //'4,5' is a valid LaTeX length number. Change it to '4.5'
235         string const length = subst(len, ',', '.');
236         if (i == string::npos)
237                 return false;
238         if (i == 0) {
239                 if (len[0] == '\\') {
240                         // We had something like \textwidth without a factor
241                         value = "1.0";
242                 } else {
243                         return false;
244                 }
245         } else {
246                 value = trim(string(length, 0, i));
247         }
248         if (value == "-")
249                 value = "-1.0";
250         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
251         if (contains(len, '\\'))
252                 unit = trim(string(len, i));
253         else
254                 unit = ascii_lowercase(trim(string(len, i)));
255         return true;
256 }
257
258
259 /// A simple function to translate a latex length to something lyx can
260 /// understand. Not perfect, but rather best-effort.
261 bool translate_len(string const & length, string & valstring, string & unit)
262 {
263         if (!splitLatexLength(length, valstring, unit))
264                 return false;
265         // LyX uses percent values
266         double value;
267         istringstream iss(valstring);
268         iss >> value;
269         value *= 100;
270         ostringstream oss;
271         oss << value;
272         string const percentval = oss.str();
273         // a normal length
274         if (unit.empty() || unit[0] != '\\')
275                 return true;
276         string::size_type const i = unit.find(' ');
277         string const endlen = (i == string::npos) ? string() : string(unit, i);
278         if (unit == "\\textwidth") {
279                 valstring = percentval;
280                 unit = "text%" + endlen;
281         } else if (unit == "\\columnwidth") {
282                 valstring = percentval;
283                 unit = "col%" + endlen;
284         } else if (unit == "\\paperwidth") {
285                 valstring = percentval;
286                 unit = "page%" + endlen;
287         } else if (unit == "\\linewidth") {
288                 valstring = percentval;
289                 unit = "line%" + endlen;
290         } else if (unit == "\\paperheight") {
291                 valstring = percentval;
292                 unit = "pheight%" + endlen;
293         } else if (unit == "\\textheight") {
294                 valstring = percentval;
295                 unit = "theight%" + endlen;
296         }
297         return true;
298 }
299
300 }
301
302
303 string translate_len(string const & length)
304 {
305         string unit;
306         string value;
307         if (translate_len(length, value, unit))
308                 return value + unit;
309         // If the input is invalid, return what we have.
310         return length;
311 }
312
313
314 namespace {
315
316 /*!
317  * Translates a LaTeX length into \p value, \p unit and
318  * \p special parts suitable for a box inset.
319  * The difference from translate_len() is that a box inset knows about
320  * some special "units" that are stored in \p special.
321  */
322 void translate_box_len(string const & length, string & value, string & unit, string & special)
323 {
324         if (translate_len(length, value, unit)) {
325                 if (unit == "\\height" || unit == "\\depth" ||
326                     unit == "\\totalheight" || unit == "\\width") {
327                         special = unit.substr(1);
328                         // The unit is not used, but LyX requires a dummy setting
329                         unit = "in";
330                 } else
331                         special = "none";
332         } else {
333                 value.clear();
334                 unit = length;
335                 special = "none";
336         }
337 }
338
339
340 /*!
341  * Find a file with basename \p name in path \p path and an extension
342  * in \p extensions.
343  */
344 string find_file(string const & name, string const & path,
345                  char const * const * extensions)
346 {
347         // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
348         // expects utf8)
349         for (char const * const * what = extensions; *what; ++what) {
350                 string const trial = addExtension(name, *what);
351                 if (makeAbsPath(trial, path).exists())
352                         return trial;
353         }
354         return string();
355 }
356
357
358 void begin_inset(ostream & os, string const & name)
359 {
360         os << "\n\\begin_inset " << name;
361 }
362
363
364 void end_inset(ostream & os)
365 {
366         os << "\n\\end_inset\n\n";
367 }
368
369
370 void skip_braces(Parser & p)
371 {
372         if (p.next_token().cat() != catBegin)
373                 return;
374         p.get_token();
375         if (p.next_token().cat() == catEnd) {
376                 p.get_token();
377                 return;
378         }
379         p.putback();
380 }
381
382
383 void handle_ert(ostream & os, string const & s, Context & context)
384 {
385         // We must have a valid layout before outputting the ERT inset.
386         context.check_layout(os);
387         Context newcontext(true, context.textclass);
388         begin_inset(os, "ERT");
389         os << "\nstatus collapsed\n";
390         newcontext.check_layout(os);
391         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
392                 if (*it == '\\')
393                         os << "\n\\backslash\n";
394                 else if (*it == '\n') {
395                         newcontext.new_paragraph(os);
396                         newcontext.check_layout(os);
397                 } else
398                         os << *it;
399         }
400         newcontext.check_end_layout(os);
401         end_inset(os);
402 }
403
404
405 void handle_comment(ostream & os, string const & s, Context & context)
406 {
407         // TODO: Handle this better
408         Context newcontext(true, context.textclass);
409         begin_inset(os, "ERT");
410         os << "\nstatus collapsed\n";
411         newcontext.check_layout(os);
412         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
413                 if (*it == '\\')
414                         os << "\n\\backslash\n";
415                 else
416                         os << *it;
417         }
418         // make sure that our comment is the last thing on the line
419         newcontext.new_paragraph(os);
420         newcontext.check_layout(os);
421         newcontext.check_end_layout(os);
422         end_inset(os);
423 }
424
425
426 Layout const * findLayout(TextClass const & textclass, string const & name)
427 {
428         DocumentClass::const_iterator lit = textclass.begin();
429         DocumentClass::const_iterator len = textclass.end();
430         for (; lit != len; ++lit)
431                 if (lit->latexname() == name)
432                         return &*lit;
433         return 0;
434 }
435
436
437 void eat_whitespace(Parser &, ostream &, Context &, bool);
438
439
440 Layout * captionlayout()
441 {
442         static Layout * lay = 0;
443         if (!lay) {
444                 lay = new Layout;
445                 lay->name_ = from_ascii("Caption");
446                 lay->latexname_ = "caption";
447                 lay->latextype = LATEX_COMMAND;
448                 lay->optionalargs = 1;
449         }
450         return lay;
451 }
452
453
454 void output_command_layout(ostream & os, Parser & p, bool outer,
455                            Context & parent_context,
456                            Layout const * newlayout)
457 {
458         parent_context.check_end_layout(os);
459         Context context(true, parent_context.textclass, newlayout,
460                         parent_context.layout, parent_context.font);
461         if (parent_context.deeper_paragraph) {
462                 // We are beginning a nested environment after a
463                 // deeper paragraph inside the outer list environment.
464                 // Therefore we don't need to output a "begin deeper".
465                 context.need_end_deeper = true;
466         }
467         context.check_deeper(os);
468         context.check_layout(os);
469         if (context.layout->optionalargs > 0) {
470                 eat_whitespace(p, os, context, false);
471                 if (p.next_token().character() == '[') {
472                         p.get_token(); // eat '['
473                         begin_inset(os, "OptArg\n");
474                         os << "status collapsed\n\n";
475                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
476                         end_inset(os);
477                         eat_whitespace(p, os, context, false);
478                 }
479         }
480         parse_text(p, os, FLAG_ITEM, outer, context);
481         context.check_end_layout(os);
482         if (parent_context.deeper_paragraph) {
483                 // We must suppress the "end deeper" because we
484                 // suppressed the "begin deeper" above.
485                 context.need_end_deeper = false;
486         }
487         context.check_end_deeper(os);
488         // We don't need really a new paragraph, but
489         // we must make sure that the next item gets a \begin_layout.
490         parent_context.new_paragraph(os);
491 }
492
493
494 /*!
495  * Output a space if necessary.
496  * This function gets called for every whitespace token.
497  *
498  * We have three cases here:
499  * 1. A space must be suppressed. Example: The lyxcode case below
500  * 2. A space may be suppressed. Example: Spaces before "\par"
501  * 3. A space must not be suppressed. Example: A space between two words
502  *
503  * We currently handle only 1. and 3 and from 2. only the case of
504  * spaces before newlines as a side effect.
505  *
506  * 2. could be used to suppress as many spaces as possible. This has two effects:
507  * - Reimporting LyX generated LaTeX files changes almost no whitespace
508  * - Superflous whitespace from non LyX generated LaTeX files is removed.
509  * The drawback is that the logic inside the function becomes
510  * complicated, and that is the reason why it is not implemented.
511  */
512 void check_space(Parser const & p, ostream & os, Context & context)
513 {
514         Token const next = p.next_token();
515         Token const curr = p.curr_token();
516         // A space before a single newline and vice versa must be ignored
517         // LyX emits a newline before \end{lyxcode}.
518         // This newline must be ignored,
519         // otherwise LyX will add an additional protected space.
520         if (next.cat() == catSpace ||
521             next.cat() == catNewline ||
522             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
523                 return;
524         }
525         context.check_layout(os);
526         os << ' ';
527 }
528
529
530 /*!
531  * Parse all arguments of \p command
532  */
533 void parse_arguments(string const & command,
534                      vector<ArgumentType> const & template_arguments,
535                      Parser & p, ostream & os, bool outer, Context & context)
536 {
537         string ert = command;
538         size_t no_arguments = template_arguments.size();
539         for (size_t i = 0; i < no_arguments; ++i) {
540                 switch (template_arguments[i]) {
541                 case required:
542                         // This argument contains regular LaTeX
543                         handle_ert(os, ert + '{', context);
544                         eat_whitespace(p, os, context, false);
545                         parse_text(p, os, FLAG_ITEM, outer, context);
546                         ert = "}";
547                         break;
548                 case verbatim:
549                         // This argument may contain special characters
550                         ert += '{' + p.verbatim_item() + '}';
551                         break;
552                 case optional:
553                         ert += p.getOpt();
554                         break;
555                 }
556         }
557         handle_ert(os, ert, context);
558 }
559
560
561 /*!
562  * Check whether \p command is a known command. If yes,
563  * handle the command with all arguments.
564  * \return true if the command was parsed, false otherwise.
565  */
566 bool parse_command(string const & command, Parser & p, ostream & os,
567                    bool outer, Context & context)
568 {
569         if (known_commands.find(command) != known_commands.end()) {
570                 parse_arguments(command, known_commands[command], p, os,
571                                 outer, context);
572                 return true;
573         }
574         return false;
575 }
576
577
578 /// Parses a minipage or parbox
579 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
580                Context & parent_context, bool use_parbox)
581 {
582         string position;
583         string inner_pos;
584         // We need to set the height to the LaTeX default of 1\\totalheight
585         // for the case when no height argument is given
586         string height_value = "1";
587         string height_unit = "in";
588         string height_special = "totalheight";
589         string latex_height;
590         if (p.next_token().asInput() == "[") {
591                 position = p.getArg('[', ']');
592                 if (position != "t" && position != "c" && position != "b") {
593                         position = "c";
594                         cerr << "invalid position for minipage/parbox" << endl;
595                 }
596                 if (p.next_token().asInput() == "[") {
597                         latex_height = p.getArg('[', ']');
598                         translate_box_len(latex_height, height_value, height_unit, height_special);
599
600                         if (p.next_token().asInput() == "[") {
601                                 inner_pos = p.getArg('[', ']');
602                                 if (inner_pos != "c" && inner_pos != "t" &&
603                                     inner_pos != "b" && inner_pos != "s") {
604                                         inner_pos = position;
605                                         cerr << "invalid inner_pos for minipage/parbox"
606                                              << endl;
607                                 }
608                         }
609                 }
610         }
611         string width_value;
612         string width_unit;
613         string const latex_width = p.verbatim_item();
614         translate_len(latex_width, width_value, width_unit);
615         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
616                 // LyX can't handle length variables
617                 ostringstream ss;
618                 if (use_parbox)
619                         ss << "\\parbox";
620                 else
621                         ss << "\\begin{minipage}";
622                 if (!position.empty())
623                         ss << '[' << position << ']';
624                 if (!latex_height.empty())
625                         ss << '[' << latex_height << ']';
626                 if (!inner_pos.empty())
627                         ss << '[' << inner_pos << ']';
628                 ss << "{" << latex_width << "}";
629                 if (use_parbox)
630                         ss << '{';
631                 handle_ert(os, ss.str(), parent_context);
632                 parent_context.new_paragraph(os);
633                 parse_text_in_inset(p, os, flags, outer, parent_context);
634                 if (use_parbox)
635                         handle_ert(os, "}", parent_context);
636                 else
637                         handle_ert(os, "\\end{minipage}", parent_context);
638         } else {
639                 // LyX does not like empty positions, so we have
640                 // to set them to the LaTeX default values here.
641                 if (position.empty())
642                         position = "c";
643                 if (inner_pos.empty())
644                         inner_pos = position;
645                 parent_context.check_layout(os);
646                 begin_inset(os, "Box Frameless\n");
647                 os << "position \"" << position << "\"\n";
648                 os << "hor_pos \"c\"\n";
649                 os << "has_inner_box 1\n";
650                 os << "inner_pos \"" << inner_pos << "\"\n";
651                 os << "use_parbox " << use_parbox << "\n";
652                 os << "width \"" << width_value << width_unit << "\"\n";
653                 os << "special \"none\"\n";
654                 os << "height \"" << height_value << height_unit << "\"\n";
655                 os << "height_special \"" << height_special << "\"\n";
656                 os << "status open\n\n";
657                 parse_text_in_inset(p, os, flags, outer, parent_context);
658                 end_inset(os);
659 #ifdef PRESERVE_LAYOUT
660                 // lyx puts a % after the end of the minipage
661                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
662                         // new paragraph
663                         //handle_comment(os, "%dummy", parent_context);
664                         p.get_token();
665                         p.skip_spaces();
666                         parent_context.new_paragraph(os);
667                 }
668                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
669                         //handle_comment(os, "%dummy", parent_context);
670                         p.get_token();
671                         p.skip_spaces();
672                         // We add a protected space if something real follows
673                         if (p.good() && p.next_token().cat() != catComment) {
674                                 os << "\\InsetSpace ~\n";
675                         }
676                 }
677 #endif
678         }
679 }
680
681
682 /// parse an unknown environment
683 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
684                                unsigned flags, bool outer,
685                                Context & parent_context)
686 {
687         if (name == "tabbing")
688                 // We need to remember that we have to handle '\=' specially
689                 flags |= FLAG_TABBING;
690
691         // We need to translate font changes and paragraphs inside the
692         // environment to ERT if we have a non standard font.
693         // Otherwise things like
694         // \large\begin{foo}\huge bar\end{foo}
695         // will not work.
696         bool const specialfont =
697                 (parent_context.font != parent_context.normalfont);
698         bool const new_layout_allowed = parent_context.new_layout_allowed;
699         if (specialfont)
700                 parent_context.new_layout_allowed = false;
701         handle_ert(os, "\\begin{" + name + "}", parent_context);
702         parse_text_snippet(p, os, flags, outer, parent_context);
703         handle_ert(os, "\\end{" + name + "}", parent_context);
704         if (specialfont)
705                 parent_context.new_layout_allowed = new_layout_allowed;
706 }
707
708
709 void parse_environment(Parser & p, ostream & os, bool outer,
710                        Context & parent_context)
711 {
712         Layout const * newlayout;
713         string const name = p.getArg('{', '}');
714         const bool is_starred = suffixIs(name, '*');
715         string const unstarred_name = rtrim(name, "*");
716         active_environments.push_back(name);
717
718         if (is_math_env(name)) {
719                 parent_context.check_layout(os);
720                 begin_inset(os, "Formula ");
721                 os << "\\begin{" << name << "}";
722                 parse_math(p, os, FLAG_END, MATH_MODE);
723                 os << "\\end{" << name << "}";
724                 end_inset(os);
725         }
726
727         else if (name == "tabular" || name == "longtable") {
728                 eat_whitespace(p, os, parent_context, false);
729                 parent_context.check_layout(os);
730                 begin_inset(os, "Tabular ");
731                 handle_tabular(p, os, name == "longtable", parent_context);
732                 end_inset(os);
733                 p.skip_spaces();
734         }
735
736         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
737                 eat_whitespace(p, os, parent_context, false);
738                 parent_context.check_layout(os);
739                 begin_inset(os, "Float " + unstarred_name + "\n");
740                 if (p.next_token().asInput() == "[") {
741                         os << "placement " << p.getArg('[', ']') << '\n';
742                 }
743                 os << "wide " << convert<string>(is_starred)
744                    << "\nsideways false"
745                    << "\nstatus open\n\n";
746                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
747                 end_inset(os);
748                 // We don't need really a new paragraph, but
749                 // we must make sure that the next item gets a \begin_layout.
750                 parent_context.new_paragraph(os);
751                 p.skip_spaces();
752         }
753
754         else if (name == "minipage") {
755                 eat_whitespace(p, os, parent_context, false);
756                 parse_box(p, os, FLAG_END, outer, parent_context, false);
757                 p.skip_spaces();
758         }
759
760         else if (name == "comment") {
761                 eat_whitespace(p, os, parent_context, false);
762                 parent_context.check_layout(os);
763                 begin_inset(os, "Note Comment\n");
764                 os << "status open\n";
765                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
766                 end_inset(os);
767                 p.skip_spaces();
768                 skip_braces(p); // eat {} that might by set by LyX behind comments
769         }
770
771         else if (name == "lyxgreyedout") {
772                 eat_whitespace(p, os, parent_context, false);
773                 parent_context.check_layout(os);
774                 begin_inset(os, "Note Greyedout\n");
775                 os << "status open\n";
776                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
777                 end_inset(os);
778                 p.skip_spaces();
779         }
780
781         else if (name == "framed") {
782                 eat_whitespace(p, os, parent_context, false);
783                 parent_context.check_layout(os);
784                 begin_inset(os, "Note Framed\n");
785                 os << "status open\n";
786                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787                 end_inset(os);
788                 p.skip_spaces();
789         }
790
791         else if (name == "shaded") {
792                 eat_whitespace(p, os, parent_context, false);
793                 parent_context.check_layout(os);
794                 begin_inset(os, "Note Shaded\n");
795                 os << "status open\n";
796                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
797                 end_inset(os);
798                 p.skip_spaces();
799         }
800
801         else if (!parent_context.new_layout_allowed)
802                 parse_unknown_environment(p, name, os, FLAG_END, outer,
803                                           parent_context);
804
805         // Alignment and spacing settings
806         // FIXME (bug xxxx): These settings can span multiple paragraphs and
807         //                                       therefore are totally broken!
808         // Note that \centering, raggedright, and raggedleft cannot be handled, as
809         // they are commands not environments. They are furthermore switches that
810         // can be ended by another switches, but also by commands like \footnote or
811         // \parbox. So the only safe way is to leave them untouched.
812         else if (name == "center" || name == "flushleft" || name == "flushright") {
813                 eat_whitespace(p, os, parent_context, false);
814                 // We must begin a new paragraph if not already done
815                 if (! parent_context.atParagraphStart()) {
816                         parent_context.check_end_layout(os);
817                         parent_context.new_paragraph(os);
818                 }
819                 if (name == "flushleft")
820                         parent_context.add_extra_stuff("\\align left\n");
821                 else if (name == "flushright")
822                         parent_context.add_extra_stuff("\\align right\n");
823                 else if (name == "center")
824                         parent_context.add_extra_stuff("\\align center\n");
825                 parse_text(p, os, FLAG_END, outer, parent_context);
826                 // Just in case the environment is empty
827                 parent_context.extra_stuff.erase();
828                 // We must begin a new paragraph to reset the alignment
829                 parent_context.new_paragraph(os);
830                 p.skip_spaces();
831         }
832
833         // The single '=' is meant here.
834         else if ((newlayout = findLayout(parent_context.textclass, name)) &&
835                   newlayout->isEnvironment()) {
836                 eat_whitespace(p, os, parent_context, false);
837                 Context context(true, parent_context.textclass, newlayout,
838                                 parent_context.layout, parent_context.font);
839                 if (parent_context.deeper_paragraph) {
840                         // We are beginning a nested environment after a
841                         // deeper paragraph inside the outer list environment.
842                         // Therefore we don't need to output a "begin deeper".
843                         context.need_end_deeper = true;
844                 }
845                 parent_context.check_end_layout(os);
846                 switch (context.layout->latextype) {
847                 case  LATEX_LIST_ENVIRONMENT:
848                         context.extra_stuff = "\\labelwidthstring "
849                                 + p.verbatim_item() + '\n';
850                         p.skip_spaces();
851                         break;
852                 case  LATEX_BIB_ENVIRONMENT:
853                         p.verbatim_item(); // swallow next arg
854                         p.skip_spaces();
855                         break;
856                 default:
857                         break;
858                 }
859                 context.check_deeper(os);
860                 parse_text(p, os, FLAG_END, outer, context);
861                 context.check_end_layout(os);
862                 if (parent_context.deeper_paragraph) {
863                         // We must suppress the "end deeper" because we
864                         // suppressed the "begin deeper" above.
865                         context.need_end_deeper = false;
866                 }
867                 context.check_end_deeper(os);
868                 parent_context.new_paragraph(os);
869                 p.skip_spaces();
870         }
871
872         else if (name == "appendix") {
873                 // This is no good latex style, but it works and is used in some documents...
874                 eat_whitespace(p, os, parent_context, false);
875                 parent_context.check_end_layout(os);
876                 Context context(true, parent_context.textclass, parent_context.layout,
877                                 parent_context.layout, parent_context.font);
878                 context.check_layout(os);
879                 os << "\\start_of_appendix\n";
880                 parse_text(p, os, FLAG_END, outer, context);
881                 context.check_end_layout(os);
882                 p.skip_spaces();
883         }
884
885         else if (known_environments.find(name) != known_environments.end()) {
886                 vector<ArgumentType> arguments = known_environments[name];
887                 // The last "argument" denotes wether we may translate the
888                 // environment contents to LyX
889                 // The default required if no argument is given makes us
890                 // compatible with the reLyXre environment.
891                 ArgumentType contents = arguments.empty() ?
892                         required :
893                         arguments.back();
894                 if (!arguments.empty())
895                         arguments.pop_back();
896                 // See comment in parse_unknown_environment()
897                 bool const specialfont =
898                         (parent_context.font != parent_context.normalfont);
899                 bool const new_layout_allowed =
900                         parent_context.new_layout_allowed;
901                 if (specialfont)
902                         parent_context.new_layout_allowed = false;
903                 parse_arguments("\\begin{" + name + "}", arguments, p, os,
904                                 outer, parent_context);
905                 if (contents == verbatim)
906                         handle_ert(os, p.verbatimEnvironment(name),
907                                    parent_context);
908                 else
909                         parse_text_snippet(p, os, FLAG_END, outer,
910                                            parent_context);
911                 handle_ert(os, "\\end{" + name + "}", parent_context);
912                 if (specialfont)
913                         parent_context.new_layout_allowed = new_layout_allowed;
914         }
915
916         else
917                 parse_unknown_environment(p, name, os, FLAG_END, outer,
918                                           parent_context);
919
920         active_environments.pop_back();
921 }
922
923
924 /// parses a comment and outputs it to \p os.
925 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
926 {
927         LASSERT(t.cat() == catComment, return);
928         if (!t.cs().empty()) {
929                 context.check_layout(os);
930                 handle_comment(os, '%' + t.cs(), context);
931                 if (p.next_token().cat() == catNewline) {
932                         // A newline after a comment line starts a new
933                         // paragraph
934                         if (context.new_layout_allowed) {
935                                 if(!context.atParagraphStart())
936                                         // Only start a new paragraph if not already
937                                         // done (we might get called recursively)
938                                         context.new_paragraph(os);
939                         } else
940                                 handle_ert(os, "\n", context);
941                         eat_whitespace(p, os, context, true);
942                 }
943         } else {
944                 // "%\n" combination
945                 p.skip_spaces();
946         }
947 }
948
949
950 /*!
951  * Reads spaces and comments until the first non-space, non-comment token.
952  * New paragraphs (double newlines or \\par) are handled like simple spaces
953  * if \p eatParagraph is true.
954  * Spaces are skipped, but comments are written to \p os.
955  */
956 void eat_whitespace(Parser & p, ostream & os, Context & context,
957                     bool eatParagraph)
958 {
959         while (p.good()) {
960                 Token const & t = p.get_token();
961                 if (t.cat() == catComment)
962                         parse_comment(p, os, t, context);
963                 else if ((! eatParagraph && p.isParagraph()) ||
964                          (t.cat() != catSpace && t.cat() != catNewline)) {
965                         p.putback();
966                         return;
967                 }
968         }
969 }
970
971
972 /*!
973  * Set a font attribute, parse text and reset the font attribute.
974  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
975  * \param currentvalue Current value of the attribute. Is set to the new
976  * value during parsing.
977  * \param newvalue New value of the attribute
978  */
979 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
980                            Context & context, string const & attribute,
981                            string & currentvalue, string const & newvalue)
982 {
983         context.check_layout(os);
984         string const oldvalue = currentvalue;
985         currentvalue = newvalue;
986         os << '\n' << attribute << ' ' << newvalue << "\n";
987         parse_text_snippet(p, os, flags, outer, context);
988         context.check_layout(os);
989         os << '\n' << attribute << ' ' << oldvalue << "\n";
990         currentvalue = oldvalue;
991 }
992
993
994 /// get the arguments of a natbib or jurabib citation command
995 void get_cite_arguments(Parser & p, bool natbibOrder,
996         string & before, string & after)
997 {
998         // We need to distinguish "" and "[]", so we can't use p.getOpt().
999
1000         // text before the citation
1001         before.clear();
1002         // text after the citation
1003         after = p.getFullOpt();
1004
1005         if (!after.empty()) {
1006                 before = p.getFullOpt();
1007                 if (natbibOrder && !before.empty())
1008                         swap(before, after);
1009         }
1010 }
1011
1012
1013 /// Convert filenames with TeX macros and/or quotes to something LyX
1014 /// can understand
1015 string const normalize_filename(string const & name)
1016 {
1017         Parser p(trim(name, "\""));
1018         ostringstream os;
1019         while (p.good()) {
1020                 Token const & t = p.get_token();
1021                 if (t.cat() != catEscape)
1022                         os << t.asInput();
1023                 else if (t.cs() == "lyxdot") {
1024                         // This is used by LyX for simple dots in relative
1025                         // names
1026                         os << '.';
1027                         p.skip_spaces();
1028                 } else if (t.cs() == "space") {
1029                         os << ' ';
1030                         p.skip_spaces();
1031                 } else
1032                         os << t.asInput();
1033         }
1034         return os.str();
1035 }
1036
1037
1038 /// Convert \p name from TeX convention (relative to master file) to LyX
1039 /// convention (relative to .lyx file) if it is relative
1040 void fix_relative_filename(string & name)
1041 {
1042         FileName fname(name);
1043         if (fname.isAbsolute())
1044                 return;
1045
1046         // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1047         // utf8)
1048         name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1049                                    from_utf8(getParentFilePath())));
1050 }
1051
1052
1053 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1054 void parse_noweb(Parser & p, ostream & os, Context & context)
1055 {
1056         // assemble the rest of the keyword
1057         string name("<<");
1058         bool scrap = false;
1059         while (p.good()) {
1060                 Token const & t = p.get_token();
1061                 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1062                         name += ">>";
1063                         p.get_token();
1064                         scrap = (p.good() && p.next_token().asInput() == "=");
1065                         if (scrap)
1066                                 name += p.get_token().asInput();
1067                         break;
1068                 }
1069                 name += t.asInput();
1070         }
1071
1072         if (!scrap || !context.new_layout_allowed ||
1073             !context.textclass.hasLayout(from_ascii("Scrap"))) {
1074                 cerr << "Warning: Could not interpret '" << name
1075                      << "'. Ignoring it." << endl;
1076                 return;
1077         }
1078
1079         // We use new_paragraph instead of check_end_layout because the stuff
1080         // following the noweb chunk needs to start with a \begin_layout.
1081         // This may create a new paragraph even if there was none in the
1082         // noweb file, but the alternative is an invalid LyX file. Since
1083         // noweb code chunks are implemented with a layout style in LyX they
1084         // always must be in an own paragraph.
1085         context.new_paragraph(os);
1086         Context newcontext(true, context.textclass,
1087                 &context.textclass[from_ascii("Scrap")]);
1088         newcontext.check_layout(os);
1089         os << name;
1090         while (p.good()) {
1091                 Token const & t = p.get_token();
1092                 // We abuse the parser a bit, because this is no TeX syntax
1093                 // at all.
1094                 if (t.cat() == catEscape)
1095                         os << subst(t.asInput(), "\\", "\n\\backslash\n");
1096                 else
1097                         os << subst(t.asInput(), "\n", "\n\\newline\n");
1098                 // The scrap chunk is ended by an @ at the beginning of a line.
1099                 // After the @ the line may contain a comment and/or
1100                 // whitespace, but nothing else.
1101                 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1102                     (p.next_token().cat() == catSpace ||
1103                      p.next_token().cat() == catNewline ||
1104                      p.next_token().cat() == catComment)) {
1105                         while (p.good() && p.next_token().cat() == catSpace)
1106                                 os << p.get_token().asInput();
1107                         if (p.next_token().cat() == catComment)
1108                                 // The comment includes a final '\n'
1109                                 os << p.get_token().asInput();
1110                         else {
1111                                 if (p.next_token().cat() == catNewline)
1112                                         p.get_token();
1113                                 os << '\n';
1114                         }
1115                         break;
1116                 }
1117         }
1118         newcontext.check_end_layout(os);
1119 }
1120
1121 } // anonymous namespace
1122
1123
1124 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1125                 Context & context)
1126 {
1127         Layout const * newlayout = 0;
1128         // store the current selectlanguage to be used after \foreignlanguage
1129         string selectlang;
1130         // Store the latest bibliographystyle (needed for bibtex inset)
1131         string bibliographystyle;
1132         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1133         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1134         while (p.good()) {
1135                 Token const & t = p.get_token();
1136
1137 #ifdef FILEDEBUG
1138                 cerr << "t: " << t << " flags: " << flags << "\n";
1139 #endif
1140
1141                 if (flags & FLAG_ITEM) {
1142                         if (t.cat() == catSpace)
1143                                 continue;
1144
1145                         flags &= ~FLAG_ITEM;
1146                         if (t.cat() == catBegin) {
1147                                 // skip the brace and collect everything to the next matching
1148                                 // closing brace
1149                                 flags |= FLAG_BRACE_LAST;
1150                                 continue;
1151                         }
1152
1153                         // handle only this single token, leave the loop if done
1154                         flags |= FLAG_LEAVE;
1155                 }
1156
1157                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1158                         return;
1159
1160                 //
1161                 // cat codes
1162                 //
1163                 if (t.cat() == catMath) {
1164                         // we are inside some text mode thingy, so opening new math is allowed
1165                         context.check_layout(os);
1166                         begin_inset(os, "Formula ");
1167                         Token const & n = p.get_token();
1168                         if (n.cat() == catMath && outer) {
1169                                 // TeX's $$...$$ syntax for displayed math
1170                                 os << "\\[";
1171                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1172                                 os << "\\]";
1173                                 p.get_token(); // skip the second '$' token
1174                         } else {
1175                                 // simple $...$  stuff
1176                                 p.putback();
1177                                 os << '$';
1178                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1179                                 os << '$';
1180                         }
1181                         end_inset(os);
1182                 }
1183
1184                 else if (t.cat() == catSuper || t.cat() == catSub)
1185                         cerr << "catcode " << t << " illegal in text mode\n";
1186
1187                 // Basic support for english quotes. This should be
1188                 // extended to other quotes, but is not so easy (a
1189                 // left english quote is the same as a right german
1190                 // quote...)
1191                 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1192                         context.check_layout(os);
1193                         begin_inset(os, "Quotes ");
1194                         os << "eld";
1195                         end_inset(os);
1196                         p.get_token();
1197                         skip_braces(p);
1198                 }
1199                 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1200                         context.check_layout(os);
1201                         begin_inset(os, "Quotes ");
1202                         os << "erd";
1203                         end_inset(os);
1204                         p.get_token();
1205                         skip_braces(p);
1206                 }
1207
1208                 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1209                         context.check_layout(os);
1210                         begin_inset(os, "Quotes ");
1211                         os << "ald";
1212                         end_inset(os);
1213                         p.get_token();
1214                         skip_braces(p);
1215                 }
1216
1217                 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1218                         context.check_layout(os);
1219                         begin_inset(os, "Quotes ");
1220                         os << "ard";
1221                         end_inset(os);
1222                         p.get_token();
1223                         skip_braces(p);
1224                 }
1225
1226                 else if (t.asInput() == "<"
1227                          && p.next_token().asInput() == "<" && noweb_mode) {
1228                         p.get_token();
1229                         parse_noweb(p, os, context);
1230                 }
1231
1232                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1233                         check_space(p, os, context);
1234
1235                 else if (t.character() == '[' && noweb_mode &&
1236                          p.next_token().character() == '[') {
1237                         // These can contain underscores
1238                         p.putback();
1239                         string const s = p.getFullOpt() + ']';
1240                         if (p.next_token().character() == ']')
1241                                 p.get_token();
1242                         else
1243                                 cerr << "Warning: Inserting missing ']' in '"
1244                                      << s << "'." << endl;
1245                         handle_ert(os, s, context);
1246                 }
1247
1248                 else if (t.cat() == catLetter ||
1249                                t.cat() == catOther ||
1250                                t.cat() == catAlign ||
1251                                t.cat() == catParameter) {
1252                         // This translates "&" to "\\&" which may be wrong...
1253                         context.check_layout(os);
1254                         os << t.character();
1255                 }
1256
1257                 else if (p.isParagraph()) {
1258                         if (context.new_layout_allowed)
1259                                 context.new_paragraph(os);
1260                         else
1261                                 handle_ert(os, "\\par ", context);
1262                         eat_whitespace(p, os, context, true);
1263                 }
1264
1265                 else if (t.cat() == catActive) {
1266                         context.check_layout(os);
1267                         if (t.character() == '~') {
1268                                 if (context.layout->free_spacing)
1269                                         os << ' ';
1270                                 else
1271                                         os << "\\InsetSpace ~\n";
1272                         } else
1273                                 os << t.character();
1274                 }
1275
1276                 else if (t.cat() == catBegin &&
1277                          p.next_token().cat() == catEnd) {
1278                         // {}
1279                         Token const prev = p.prev_token();
1280                         p.get_token();
1281                         if (p.next_token().character() == '`' ||
1282                             (prev.character() == '-' &&
1283                              p.next_token().character() == '-'))
1284                                 ; // ignore it in {}`` or -{}-
1285                         else
1286                                 handle_ert(os, "{}", context);
1287
1288                 }
1289
1290                 else if (t.cat() == catBegin) {
1291                         context.check_layout(os);
1292                         // special handling of font attribute changes
1293                         Token const prev = p.prev_token();
1294                         Token const next = p.next_token();
1295                         TeXFont const oldFont = context.font;
1296                         if (next.character() == '[' ||
1297                             next.character() == ']' ||
1298                             next.character() == '*') {
1299                                 p.get_token();
1300                                 if (p.next_token().cat() == catEnd) {
1301                                         os << next.character();
1302                                         p.get_token();
1303                                 } else {
1304                                         p.putback();
1305                                         handle_ert(os, "{", context);
1306                                         parse_text_snippet(p, os,
1307                                                         FLAG_BRACE_LAST,
1308                                                         outer, context);
1309                                         handle_ert(os, "}", context);
1310                                 }
1311                         } else if (! context.new_layout_allowed) {
1312                                 handle_ert(os, "{", context);
1313                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1314                                                    outer, context);
1315                                 handle_ert(os, "}", context);
1316                         } else if (is_known(next.cs(), known_sizes)) {
1317                                 // next will change the size, so we must
1318                                 // reset it here
1319                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1320                                                    outer, context);
1321                                 if (!context.atParagraphStart())
1322                                         os << "\n\\size "
1323                                            << context.font.size << "\n";
1324                         } else if (is_known(next.cs(), known_font_families)) {
1325                                 // next will change the font family, so we
1326                                 // must reset it here
1327                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1328                                                    outer, context);
1329                                 if (!context.atParagraphStart())
1330                                         os << "\n\\family "
1331                                            << context.font.family << "\n";
1332                         } else if (is_known(next.cs(), known_font_series)) {
1333                                 // next will change the font series, so we
1334                                 // must reset it here
1335                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1336                                                    outer, context);
1337                                 if (!context.atParagraphStart())
1338                                         os << "\n\\series "
1339                                            << context.font.series << "\n";
1340                         } else if (is_known(next.cs(), known_font_shapes)) {
1341                                 // next will change the font shape, so we
1342                                 // must reset it here
1343                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1344                                                    outer, context);
1345                                 if (!context.atParagraphStart())
1346                                         os << "\n\\shape "
1347                                            << context.font.shape << "\n";
1348                         } else if (is_known(next.cs(), known_old_font_families) ||
1349                                    is_known(next.cs(), known_old_font_series) ||
1350                                    is_known(next.cs(), known_old_font_shapes)) {
1351                                 // next will change the font family, series
1352                                 // and shape, so we must reset it here
1353                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1354                                                    outer, context);
1355                                 if (!context.atParagraphStart())
1356                                         os <<  "\n\\family "
1357                                            << context.font.family
1358                                            << "\n\\series "
1359                                            << context.font.series
1360                                            << "\n\\shape "
1361                                            << context.font.shape << "\n";
1362                         } else {
1363                                 handle_ert(os, "{", context);
1364                                 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1365                                                    outer, context);
1366                                 handle_ert(os, "}", context);
1367                         }
1368                 }
1369
1370                 else if (t.cat() == catEnd) {
1371                         if (flags & FLAG_BRACE_LAST) {
1372                                 return;
1373                         }
1374                         cerr << "stray '}' in text\n";
1375                         handle_ert(os, "}", context);
1376                 }
1377
1378                 else if (t.cat() == catComment)
1379                         parse_comment(p, os, t, context);
1380
1381                 //
1382                 // control sequences
1383                 //
1384
1385                 else if (t.cs() == "(") {
1386                         context.check_layout(os);
1387                         begin_inset(os, "Formula");
1388                         os << " \\(";
1389                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1390                         os << "\\)";
1391                         end_inset(os);
1392                 }
1393
1394                 else if (t.cs() == "[") {
1395                         context.check_layout(os);
1396                         begin_inset(os, "Formula");
1397                         os << " \\[";
1398                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1399                         os << "\\]";
1400                         end_inset(os);
1401                 }
1402
1403                 else if (t.cs() == "begin")
1404                         parse_environment(p, os, outer, context);
1405
1406                 else if (t.cs() == "end") {
1407                         if (flags & FLAG_END) {
1408                                 // eat environment name
1409                                 string const name = p.getArg('{', '}');
1410                                 if (name != active_environment())
1411                                         cerr << "\\end{" + name + "} does not match \\begin{"
1412                                                 + active_environment() + "}\n";
1413                                 return;
1414                         }
1415                         p.error("found 'end' unexpectedly");
1416                 }
1417
1418                 else if (t.cs() == "item") {
1419                         p.skip_spaces();
1420                         string s;
1421                         bool optarg = false;
1422                         if (p.next_token().character() == '[') {
1423                                 p.get_token(); // eat '['
1424                                 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1425                                                        outer, context);
1426                                 optarg = true;
1427                         }
1428                         context.set_item();
1429                         context.check_layout(os);
1430                         if (context.has_item) {
1431                                 // An item in an unknown list-like environment
1432                                 // FIXME: Do this in check_layout()!
1433                                 context.has_item = false;
1434                                 if (optarg)
1435                                         handle_ert(os, "\\item", context);
1436                                 else
1437                                         handle_ert(os, "\\item ", context);
1438                         }
1439                         if (optarg) {
1440                                 if (context.layout->labeltype != LABEL_MANUAL) {
1441                                         // lyx does not support \item[\mybullet]
1442                                         // in itemize environments
1443                                         handle_ert(os, "[", context);
1444                                         os << s;
1445                                         handle_ert(os, "]", context);
1446                                 } else if (!s.empty()) {
1447                                         // The space is needed to separate the
1448                                         // item from the rest of the sentence.
1449                                         os << s << ' ';
1450                                         eat_whitespace(p, os, context, false);
1451                                 }
1452                         }
1453                 }
1454
1455                 else if (t.cs() == "bibitem") {
1456                         context.set_item();
1457                         context.check_layout(os);
1458                         os << "\\bibitem ";
1459                         os << p.getOpt();
1460                         os << '{' << p.verbatim_item() << '}' << "\n";
1461                 } 
1462                 
1463                 else if(t.cs() == "global") {
1464                         // skip global which can appear in front of e.g. "def"
1465                 }
1466                 
1467                 else if (t.cs() == "def") {
1468                         context.check_layout(os);
1469                         eat_whitespace(p, os, context, false);
1470                         string name = p.get_token().cs();
1471                         eat_whitespace(p, os, context, false);
1472
1473                         // parameter text
1474                         bool simple = true;
1475                         string paramtext;
1476                         int arity = 0;
1477                         while (p.next_token().cat() != catBegin) {
1478                                 if (p.next_token().cat() == catParameter) {
1479                                         // # found
1480                                         p.get_token();
1481                                         paramtext += "#";
1482
1483                                         // followed by number?
1484                                         if (p.next_token().cat() == catOther) {
1485                                                 char c = p.getChar();
1486                                                 paramtext += c;
1487                                                 // number = current arity + 1?
1488                                                 if (c == arity + '0' + 1)
1489                                                         ++arity;
1490                                                 else
1491                                                         simple = false;
1492                                         } else
1493                                                 paramtext += p.get_token().asString();
1494                                 } else {
1495                                         paramtext += p.get_token().asString();
1496                                         simple = false;
1497                                 }
1498                         }
1499
1500                         // only output simple (i.e. compatible) macro as FormulaMacros
1501                         string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1502                         if (simple) {
1503                                 context.check_layout(os);
1504                                 begin_inset(os, "FormulaMacro");
1505                                 os << "\n" << ert;
1506                                 end_inset(os);
1507                         } else
1508                                 handle_ert(os, ert, context);
1509                 }
1510
1511                 else if (t.cs() == "noindent") {
1512                         p.skip_spaces();
1513                         context.add_extra_stuff("\\noindent\n");
1514                 }
1515
1516                 else if (t.cs() == "appendix") {
1517                         context.add_extra_stuff("\\start_of_appendix\n");
1518                         // We need to start a new paragraph. Otherwise the
1519                         // appendix in 'bla\appendix\chapter{' would start
1520                         // too late.
1521                         context.new_paragraph(os);
1522                         // We need to make sure that the paragraph is
1523                         // generated even if it is empty. Otherwise the
1524                         // appendix in '\par\appendix\par\chapter{' would
1525                         // start too late.
1526                         context.check_layout(os);
1527                         // FIXME: This is a hack to prevent paragraph
1528                         // deletion if it is empty. Handle this better!
1529                         handle_comment(os,
1530                                 "%dummy comment inserted by tex2lyx to "
1531                                 "ensure that this paragraph is not empty",
1532                                 context);
1533                         // Both measures above may generate an additional
1534                         // empty paragraph, but that does not hurt, because
1535                         // whitespace does not matter here.
1536                         eat_whitespace(p, os, context, true);
1537                 }
1538
1539                 // Must attempt to parse "Section*" before "Section".
1540                 else if ((p.next_token().asInput() == "*") &&
1541                          context.new_layout_allowed &&
1542                          // The single '=' is meant here.
1543                          (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1544                           newlayout->isCommand()) {
1545                         p.get_token();
1546                         output_command_layout(os, p, outer, context, newlayout);
1547                         p.skip_spaces();
1548                 }
1549
1550                 // The single '=' is meant here.
1551                 else if (context.new_layout_allowed &&
1552                          (newlayout = findLayout(context.textclass, t.cs())) &&
1553                          newlayout->isCommand()) {
1554                         output_command_layout(os, p, outer, context, newlayout);
1555                         p.skip_spaces();
1556                 }
1557
1558                 // Special handling for \caption
1559                 // FIXME: remove this when InsetCaption is supported.
1560                 else if (context.new_layout_allowed &&
1561                          t.cs() == captionlayout()->latexname()) {
1562                         output_command_layout(os, p, outer, context, 
1563                                               captionlayout());
1564                         p.skip_spaces();
1565                 }
1566
1567                 else if (t.cs() == "includegraphics") {
1568                         bool const clip = p.next_token().asInput() == "*";
1569                         if (clip)
1570                                 p.get_token();
1571                         map<string, string> opts = split_map(p.getArg('[', ']'));
1572                         if (clip)
1573                                 opts["clip"] = string();
1574                         string name = normalize_filename(p.verbatim_item());
1575
1576                         string const path = getMasterFilePath();
1577                         // We want to preserve relative / absolute filenames,
1578                         // therefore path is only used for testing
1579                         // FIXME UNICODE encoding of name and path may be
1580                         // wrong (makeAbsPath expects utf8)
1581                         if (!makeAbsPath(name, path).exists()) {
1582                                 // The file extension is probably missing.
1583                                 // Now try to find it out.
1584                                 string const dvips_name =
1585                                         find_file(name, path,
1586                                                   known_dvips_graphics_formats);
1587                                 string const pdftex_name =
1588                                         find_file(name, path,
1589                                                   known_pdftex_graphics_formats);
1590                                 if (!dvips_name.empty()) {
1591                                         if (!pdftex_name.empty()) {
1592                                                 cerr << "This file contains the "
1593                                                         "latex snippet\n"
1594                                                         "\"\\includegraphics{"
1595                                                      << name << "}\".\n"
1596                                                         "However, files\n\""
1597                                                      << dvips_name << "\" and\n\""
1598                                                      << pdftex_name << "\"\n"
1599                                                         "both exist, so I had to make a "
1600                                                         "choice and took the first one.\n"
1601                                                         "Please move the unwanted one "
1602                                                         "someplace else and try again\n"
1603                                                         "if my choice was wrong."
1604                                                      << endl;
1605                                         }
1606                                         name = dvips_name;
1607                                 } else if (!pdftex_name.empty())
1608                                         name = pdftex_name;
1609                         }
1610
1611                         // FIXME UNICODE encoding of name and path may be
1612                         // wrong (makeAbsPath expects utf8)
1613                         if (makeAbsPath(name, path).exists())
1614                                 fix_relative_filename(name);
1615                         else
1616                                 cerr << "Warning: Could not find graphics file '"
1617                                      << name << "'." << endl;
1618
1619                         context.check_layout(os);
1620                         begin_inset(os, "Graphics ");
1621                         os << "\n\tfilename " << name << '\n';
1622                         if (opts.find("width") != opts.end())
1623                                 os << "\twidth "
1624                                    << translate_len(opts["width"]) << '\n';
1625                         if (opts.find("height") != opts.end())
1626                                 os << "\theight "
1627                                    << translate_len(opts["height"]) << '\n';
1628                         if (opts.find("scale") != opts.end()) {
1629                                 istringstream iss(opts["scale"]);
1630                                 double val;
1631                                 iss >> val;
1632                                 val = val*100;
1633                                 os << "\tscale " << val << '\n';
1634                         }
1635                         if (opts.find("angle") != opts.end())
1636                                 os << "\trotateAngle "
1637                                    << opts["angle"] << '\n';
1638                         if (opts.find("origin") != opts.end()) {
1639                                 ostringstream ss;
1640                                 string const opt = opts["origin"];
1641                                 if (opt.find('l') != string::npos) ss << "left";
1642                                 if (opt.find('r') != string::npos) ss << "right";
1643                                 if (opt.find('c') != string::npos) ss << "center";
1644                                 if (opt.find('t') != string::npos) ss << "Top";
1645                                 if (opt.find('b') != string::npos) ss << "Bottom";
1646                                 if (opt.find('B') != string::npos) ss << "Baseline";
1647                                 if (!ss.str().empty())
1648                                         os << "\trotateOrigin " << ss.str() << '\n';
1649                                 else
1650                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1651                         }
1652                         if (opts.find("keepaspectratio") != opts.end())
1653                                 os << "\tkeepAspectRatio\n";
1654                         if (opts.find("clip") != opts.end())
1655                                 os << "\tclip\n";
1656                         if (opts.find("draft") != opts.end())
1657                                 os << "\tdraft\n";
1658                         if (opts.find("bb") != opts.end())
1659                                 os << "\tBoundingBox "
1660                                    << opts["bb"] << '\n';
1661                         int numberOfbbOptions = 0;
1662                         if (opts.find("bbllx") != opts.end())
1663                                 numberOfbbOptions++;
1664                         if (opts.find("bblly") != opts.end())
1665                                 numberOfbbOptions++;
1666                         if (opts.find("bburx") != opts.end())
1667                                 numberOfbbOptions++;
1668                         if (opts.find("bbury") != opts.end())
1669                                 numberOfbbOptions++;
1670                         if (numberOfbbOptions == 4)
1671                                 os << "\tBoundingBox "
1672                                    << opts["bbllx"] << " " << opts["bblly"] << " "
1673                                    << opts["bburx"] << " " << opts["bbury"] << '\n';
1674                         else if (numberOfbbOptions > 0)
1675                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1676                         numberOfbbOptions = 0;
1677                         if (opts.find("natwidth") != opts.end())
1678                                 numberOfbbOptions++;
1679                         if (opts.find("natheight") != opts.end())
1680                                 numberOfbbOptions++;
1681                         if (numberOfbbOptions == 2)
1682                                 os << "\tBoundingBox 0bp 0bp "
1683                                    << opts["natwidth"] << " " << opts["natheight"] << '\n';
1684                         else if (numberOfbbOptions > 0)
1685                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1686                         ostringstream special;
1687                         if (opts.find("hiresbb") != opts.end())
1688                                 special << "hiresbb,";
1689                         if (opts.find("trim") != opts.end())
1690                                 special << "trim,";
1691                         if (opts.find("viewport") != opts.end())
1692                                 special << "viewport=" << opts["viewport"] << ',';
1693                         if (opts.find("totalheight") != opts.end())
1694                                 special << "totalheight=" << opts["totalheight"] << ',';
1695                         if (opts.find("type") != opts.end())
1696                                 special << "type=" << opts["type"] << ',';
1697                         if (opts.find("ext") != opts.end())
1698                                 special << "ext=" << opts["ext"] << ',';
1699                         if (opts.find("read") != opts.end())
1700                                 special << "read=" << opts["read"] << ',';
1701                         if (opts.find("command") != opts.end())
1702                                 special << "command=" << opts["command"] << ',';
1703                         string s_special = special.str();
1704                         if (!s_special.empty()) {
1705                                 // We had special arguments. Remove the trailing ','.
1706                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1707                         }
1708                         // TODO: Handle the unknown settings better.
1709                         // Warn about invalid options.
1710                         // Check whether some option was given twice.
1711                         end_inset(os);
1712                 }
1713
1714                 else if (t.cs() == "footnote" ||
1715                          (t.cs() == "thanks" && context.layout->intitle)) {
1716                         p.skip_spaces();
1717                         context.check_layout(os);
1718                         begin_inset(os, "Foot\n");
1719                         os << "status collapsed\n\n";
1720                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1721                         end_inset(os);
1722                 }
1723
1724                 else if (t.cs() == "marginpar") {
1725                         p.skip_spaces();
1726                         context.check_layout(os);
1727                         begin_inset(os, "Marginal\n");
1728                         os << "status collapsed\n\n";
1729                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1730                         end_inset(os);
1731                 }
1732
1733                 else if (t.cs() == "ensuremath") {
1734                         p.skip_spaces();
1735                         context.check_layout(os);
1736                         string const s = p.verbatim_item();
1737                         if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1738                                 os << s;
1739                         else
1740                                 handle_ert(os, "\\ensuremath{" + s + "}",
1741                                            context);
1742                 }
1743
1744                 else if (t.cs() == "hfill") {
1745                         context.check_layout(os);
1746                         os << "\n\\hfill\n";
1747                         skip_braces(p);
1748                         p.skip_spaces();
1749                 }
1750
1751                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1752                         // FIXME: Somehow prevent title layouts if
1753                         // "maketitle" was not found
1754                         p.skip_spaces();
1755                         skip_braces(p); // swallow this
1756                 }
1757
1758                 else if (t.cs() == "tableofcontents") {
1759                         p.skip_spaces();
1760                         context.check_layout(os);
1761                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1762                         end_inset(os);
1763                         skip_braces(p); // swallow this
1764                 }
1765
1766                 else if (t.cs() == "listoffigures") {
1767                         p.skip_spaces();
1768                         context.check_layout(os);
1769                         begin_inset(os, "FloatList figure\n");
1770                         end_inset(os);
1771                         skip_braces(p); // swallow this
1772                 }
1773
1774                 else if (t.cs() == "listoftables") {
1775                         p.skip_spaces();
1776                         context.check_layout(os);
1777                         begin_inset(os, "FloatList table\n");
1778                         end_inset(os);
1779                         skip_braces(p); // swallow this
1780                 }
1781
1782                 else if (t.cs() == "listof") {
1783                         p.skip_spaces(true);
1784                         string const name = p.get_token().asString();
1785                         if (context.textclass.floats().typeExist(name)) {
1786                                 context.check_layout(os);
1787                                 begin_inset(os, "FloatList ");
1788                                 os << name << "\n";
1789                                 end_inset(os);
1790                                 p.get_token(); // swallow second arg
1791                         } else
1792                                 handle_ert(os, "\\listof{" + name + "}", context);
1793                 }
1794
1795                 else if (t.cs() == "textrm")
1796                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1797                                               context, "\\family",
1798                                               context.font.family, "roman");
1799
1800                 else if (t.cs() == "textsf")
1801                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1802                                               context, "\\family",
1803                                               context.font.family, "sans");
1804
1805                 else if (t.cs() == "texttt")
1806                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1807                                               context, "\\family",
1808                                               context.font.family, "typewriter");
1809
1810                 else if (t.cs() == "textmd")
1811                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1812                                               context, "\\series",
1813                                               context.font.series, "medium");
1814
1815                 else if (t.cs() == "textbf")
1816                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1817                                               context, "\\series",
1818                                               context.font.series, "bold");
1819
1820                 else if (t.cs() == "textup")
1821                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1822                                               context, "\\shape",
1823                                               context.font.shape, "up");
1824
1825                 else if (t.cs() == "textit")
1826                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1827                                               context, "\\shape",
1828                                               context.font.shape, "italic");
1829
1830                 else if (t.cs() == "textsl")
1831                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1832                                               context, "\\shape",
1833                                               context.font.shape, "slanted");
1834
1835                 else if (t.cs() == "textsc")
1836                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1837                                               context, "\\shape",
1838                                               context.font.shape, "smallcaps");
1839
1840                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1841                         context.check_layout(os);
1842                         TeXFont oldFont = context.font;
1843                         context.font.init();
1844                         context.font.size = oldFont.size;
1845                         os << "\n\\family " << context.font.family << "\n";
1846                         os << "\n\\series " << context.font.series << "\n";
1847                         os << "\n\\shape " << context.font.shape << "\n";
1848                         if (t.cs() == "textnormal") {
1849                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1850                                 output_font_change(os, context.font, oldFont);
1851                                 context.font = oldFont;
1852                         } else
1853                                 eat_whitespace(p, os, context, false);
1854                 }
1855
1856                 else if (t.cs() == "textcolor") {
1857                         // scheme is \textcolor{color name}{text}
1858                         string const color = p.verbatim_item();
1859                         // we only support the predefined colors of the color package
1860                         if (color == "black" || color == "blue" || color == "cyan"
1861                                 || color == "green" || color == "magenta" || color == "red"
1862                                 || color == "white" || color == "yellow") {
1863                                         context.check_layout(os);
1864                                         os << "\n\\color " << color << "\n";
1865                                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1866                                         context.check_layout(os);
1867                                         os << "\n\\color inherit\n";
1868                         } else
1869                                 // for custom defined colors
1870                                 handle_ert(os, t.asInput() + "{" + color + "}", context);
1871                 }
1872
1873                 else if (t.cs() == "underbar") {
1874                         // Do NOT handle \underline.
1875                         // \underbar cuts through y, g, q, p etc.,
1876                         // \underline does not.
1877                         context.check_layout(os);
1878                         os << "\n\\bar under\n";
1879                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1880                         context.check_layout(os);
1881                         os << "\n\\bar default\n";
1882                 }
1883
1884                 else if (t.cs() == "emph" || t.cs() == "noun") {
1885                         context.check_layout(os);
1886                         os << "\n\\" << t.cs() << " on\n";
1887                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1888                         context.check_layout(os);
1889                         os << "\n\\" << t.cs() << " default\n";
1890                 }
1891
1892                 else if (t.cs() == "lyxline") {
1893                         context.check_layout(os);
1894                         os << "\\lyxline";
1895                 }
1896
1897                 else if (use_natbib &&
1898                          is_known(t.cs(), known_natbib_commands) &&
1899                          ((t.cs() != "citefullauthor" &&
1900                            t.cs() != "citeyear" &&
1901                            t.cs() != "citeyearpar") ||
1902                           p.next_token().asInput() != "*")) {
1903                         context.check_layout(os);
1904                         // tex                       lyx
1905                         // \citet[before][after]{a}  \citet[after][before]{a}
1906                         // \citet[before][]{a}       \citet[][before]{a}
1907                         // \citet[after]{a}          \citet[after]{a}
1908                         // \citet{a}                 \citet{a}
1909                         string command = '\\' + t.cs();
1910                         if (p.next_token().asInput() == "*") {
1911                                 command += '*';
1912                                 p.get_token();
1913                         }
1914                         if (command == "\\citefullauthor")
1915                                 // alternative name for "\\citeauthor*"
1916                                 command = "\\citeauthor*";
1917
1918                         // text before the citation
1919                         string before;
1920                         // text after the citation
1921                         string after;
1922                         get_cite_arguments(p, true, before, after);
1923
1924                         if (command == "\\cite") {
1925                                 // \cite without optional argument means
1926                                 // \citet, \cite with at least one optional
1927                                 // argument means \citep.
1928                                 if (before.empty() && after.empty())
1929                                         command = "\\citet";
1930                                 else
1931                                         command = "\\citep";
1932                         }
1933                         if (before.empty() && after == "[]")
1934                                 // avoid \citet[]{a}
1935                                 after.erase();
1936                         else if (before == "[]" && after == "[]") {
1937                                 // avoid \citet[][]{a}
1938                                 before.erase();
1939                                 after.erase();
1940                         }
1941                         begin_inset(os, "LatexCommand ");
1942                         os << command << after << before
1943                            << '{' << p.verbatim_item() << "}\n";
1944                         end_inset(os);
1945                 }
1946
1947                 else if (use_jurabib &&
1948                          is_known(t.cs(), known_jurabib_commands)) {
1949                         context.check_layout(os);
1950                         string const command = '\\' + t.cs();
1951                         char argumentOrder = '\0';
1952                         vector<string> const & options = used_packages["jurabib"];
1953                         if (find(options.begin(), options.end(),
1954                                       "natbiborder") != options.end())
1955                                 argumentOrder = 'n';
1956                         else if (find(options.begin(), options.end(),
1957                                            "jurabiborder") != options.end())
1958                                 argumentOrder = 'j';
1959
1960                         // text before the citation
1961                         string before;
1962                         // text after the citation
1963                         string after;
1964                         get_cite_arguments(p, argumentOrder != 'j', before, after);
1965
1966                         string const citation = p.verbatim_item();
1967                         if (!before.empty() && argumentOrder == '\0') {
1968                                 cerr << "Warning: Assuming argument order "
1969                                         "of jurabib version 0.6 for\n'"
1970                                      << command << before << after << '{'
1971                                      << citation << "}'.\n"
1972                                         "Add 'jurabiborder' to the jurabib "
1973                                         "package options if you used an\n"
1974                                         "earlier jurabib version." << endl;
1975                         }
1976                         begin_inset(os, "LatexCommand ");
1977                         os << command << after << before
1978                            << '{' << citation << "}\n";
1979                         end_inset(os);
1980                 }
1981
1982                 else if (is_known(t.cs(), known_latex_commands)) {
1983                         // This needs to be after the check for natbib and
1984                         // jurabib commands, because "cite" has different
1985                         // arguments with natbib and jurabib.
1986                         context.check_layout(os);
1987                         begin_inset(os, "LatexCommand ");
1988                         os << '\\' << t.cs();
1989                         // lyx cannot handle newlines in a latex command
1990                         // FIXME: Move the substitution into parser::getOpt()?
1991                         os << subst(p.getOpt(), "\n", " ");
1992                         os << subst(p.getOpt(), "\n", " ");
1993                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1994                         end_inset(os);
1995                 }
1996
1997                 else if (is_known(t.cs(), known_quotes)) {
1998                         char const * const * where = is_known(t.cs(), known_quotes);
1999                         context.check_layout(os);
2000                         begin_inset(os, "Quotes ");
2001                         os << known_coded_quotes[where - known_quotes];
2002                         end_inset(os);
2003                         // LyX adds {} after the quote, so we have to eat
2004                         // spaces here if there are any before a possible
2005                         // {} pair.
2006                         eat_whitespace(p, os, context, false);
2007                         skip_braces(p);
2008                 }
2009
2010                 else if (is_known(t.cs(), known_sizes) &&
2011                          context.new_layout_allowed) {
2012                         char const * const * where = is_known(t.cs(), known_sizes);
2013                         context.check_layout(os);
2014                         TeXFont const oldFont = context.font;
2015                         // the font size index differs by 1, because the known_coded_sizes
2016                         // has additionally a "default" entry
2017                         context.font.size = known_coded_sizes[where - known_sizes + 1];
2018                         output_font_change(os, oldFont, context.font);
2019                         eat_whitespace(p, os, context, false);
2020                 }
2021
2022                 else if (is_known(t.cs(), known_font_families) &&
2023                          context.new_layout_allowed) {
2024                         char const * const * where =
2025                                 is_known(t.cs(), known_font_families);
2026                         context.check_layout(os);
2027                         TeXFont const oldFont = context.font;
2028                         context.font.family =
2029                                 known_coded_font_families[where - known_font_families];
2030                         output_font_change(os, oldFont, context.font);
2031                         eat_whitespace(p, os, context, false);
2032                 }
2033
2034                 else if (is_known(t.cs(), known_font_series) &&
2035                          context.new_layout_allowed) {
2036                         char const * const * where =
2037                                 is_known(t.cs(), known_font_series);
2038                         context.check_layout(os);
2039                         TeXFont const oldFont = context.font;
2040                         context.font.series =
2041                                 known_coded_font_series[where - known_font_series];
2042                         output_font_change(os, oldFont, context.font);
2043                         eat_whitespace(p, os, context, false);
2044                 }
2045
2046                 else if (is_known(t.cs(), known_font_shapes) &&
2047                          context.new_layout_allowed) {
2048                         char const * const * where =
2049                                 is_known(t.cs(), known_font_shapes);
2050                         context.check_layout(os);
2051                         TeXFont const oldFont = context.font;
2052                         context.font.shape =
2053                                 known_coded_font_shapes[where - known_font_shapes];
2054                         output_font_change(os, oldFont, context.font);
2055                         eat_whitespace(p, os, context, false);
2056                 }
2057                 else if (is_known(t.cs(), known_old_font_families) &&
2058                          context.new_layout_allowed) {
2059                         char const * const * where =
2060                                 is_known(t.cs(), known_old_font_families);
2061                         context.check_layout(os);
2062                         TeXFont const oldFont = context.font;
2063                         context.font.init();
2064                         context.font.size = oldFont.size;
2065                         context.font.family =
2066                                 known_coded_font_families[where - known_old_font_families];
2067                         output_font_change(os, oldFont, context.font);
2068                         eat_whitespace(p, os, context, false);
2069                 }
2070
2071                 else if (is_known(t.cs(), known_old_font_series) &&
2072                          context.new_layout_allowed) {
2073                         char const * const * where =
2074                                 is_known(t.cs(), known_old_font_series);
2075                         context.check_layout(os);
2076                         TeXFont const oldFont = context.font;
2077                         context.font.init();
2078                         context.font.size = oldFont.size;
2079                         context.font.series =
2080                                 known_coded_font_series[where - known_old_font_series];
2081                         output_font_change(os, oldFont, context.font);
2082                         eat_whitespace(p, os, context, false);
2083                 }
2084
2085                 else if (is_known(t.cs(), known_old_font_shapes) &&
2086                          context.new_layout_allowed) {
2087                         char const * const * where =
2088                                 is_known(t.cs(), known_old_font_shapes);
2089                         context.check_layout(os);
2090                         TeXFont const oldFont = context.font;
2091                         context.font.init();
2092                         context.font.size = oldFont.size;
2093                         context.font.shape =
2094                                 known_coded_font_shapes[where - known_old_font_shapes];
2095                         output_font_change(os, oldFont, context.font);
2096                         eat_whitespace(p, os, context, false);
2097                 }
2098
2099                 else if (t.cs() == "selectlanguage") {
2100                         context.check_layout(os);
2101                         // save the language for the case that a \foreignlanguage is used 
2102                         selectlang = subst(p.verbatim_item(), "\n", " ");
2103                         os << "\\lang " << selectlang << "\n";
2104                         
2105                 }
2106
2107                 else if (t.cs() == "foreignlanguage") {
2108                         context.check_layout(os);
2109                         os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2110                         os << subst(p.verbatim_item(), "\n", " ");
2111                         // set back to last selectlanguage
2112                         os << "\n\\lang " << selectlang << "\n";
2113                 }
2114
2115                 else if (t.cs() == "inputencoding")
2116                         // write nothing because this is done by LyX using the "\lang"
2117                         // information given by selectlanguage and foreignlanguage
2118                         subst(p.verbatim_item(), "\n", " ");
2119                 
2120                 else if (t.cs() == "LyX" || t.cs() == "TeX"
2121                          || t.cs() == "LaTeX") {
2122                         context.check_layout(os);
2123                         os << t.cs();
2124                         skip_braces(p); // eat {}
2125                 }
2126
2127                 else if (t.cs() == "LaTeXe") {
2128                         context.check_layout(os);
2129                         os << "LaTeX2e";
2130                         skip_braces(p); // eat {}
2131                 }
2132
2133                 else if (t.cs() == "ldots") {
2134                         context.check_layout(os);
2135                         skip_braces(p);
2136                         os << "\\SpecialChar \\ldots{}\n";
2137                 }
2138
2139                 else if (t.cs() == "lyxarrow") {
2140                         context.check_layout(os);
2141                         os << "\\SpecialChar \\menuseparator\n";
2142                         skip_braces(p);
2143                 }
2144
2145                 else if (t.cs() == "textcompwordmark") {
2146                         context.check_layout(os);
2147                         os << "\\SpecialChar \\textcompwordmark{}\n";
2148                         skip_braces(p);
2149                 }
2150
2151                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2152                         context.check_layout(os);
2153                         os << "\\SpecialChar \\@.\n";
2154                         p.get_token();
2155                 }
2156
2157                 else if (t.cs() == "-") {
2158                         context.check_layout(os);
2159                         os << "\\SpecialChar \\-\n";
2160                 }
2161
2162                 else if (t.cs() == "textasciitilde") {
2163                         context.check_layout(os);
2164                         os << '~';
2165                         skip_braces(p);
2166                 }
2167
2168                 else if (t.cs() == "textasciicircum") {
2169                         context.check_layout(os);
2170                         os << '^';
2171                         skip_braces(p);
2172                 }
2173
2174                 else if (t.cs() == "textbackslash") {
2175                         context.check_layout(os);
2176                         os << "\n\\backslash\n";
2177                         skip_braces(p);
2178                 }
2179
2180                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2181                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2182                             || t.cs() == "%") {
2183                         context.check_layout(os);
2184                         os << t.cs();
2185                 }
2186
2187                 else if (t.cs() == "char") {
2188                         context.check_layout(os);
2189                         if (p.next_token().character() == '`') {
2190                                 p.get_token();
2191                                 if (p.next_token().cs() == "\"") {
2192                                         p.get_token();
2193                                         os << '"';
2194                                         skip_braces(p);
2195                                 } else {
2196                                         handle_ert(os, "\\char`", context);
2197                                 }
2198                         } else {
2199                                 handle_ert(os, "\\char", context);
2200                         }
2201                 }
2202
2203                 else if (t.cs() == "verb") {
2204                         context.check_layout(os);
2205                         char const delimiter = p.next_token().character();
2206                         string const arg = p.getArg(delimiter, delimiter);
2207                         ostringstream oss;
2208                         oss << "\\verb" << delimiter << arg << delimiter;
2209                         handle_ert(os, oss.str(), context);
2210                 }
2211
2212                 else if (t.cs() == "\"") {
2213                         context.check_layout(os);
2214                         string const name = p.verbatim_item();
2215                              if (name == "a") os << '\xe4';
2216                         else if (name == "o") os << '\xf6';
2217                         else if (name == "u") os << '\xfc';
2218                         else if (name == "A") os << '\xc4';
2219                         else if (name == "O") os << '\xd6';
2220                         else if (name == "U") os << '\xdc';
2221                         else handle_ert(os, "\"{" + name + "}", context);
2222                 }
2223
2224                 // Problem: \= creates a tabstop inside the tabbing environment
2225                 // and else an accent. In the latter case we really would want
2226                 // \={o} instead of \= o.
2227                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2228                         handle_ert(os, t.asInput(), context);
2229
2230                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2231                          || t.cs() == "'" || t.cs() == "`"
2232                          || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2233                         // we need the trim as the LyX parser chokes on such spaces
2234                         // The argument of InsetLatexAccent is parsed as a
2235                         // subset of LaTeX, so don't parse anything here,
2236                         // but use the raw argument.
2237                         // Otherwise we would convert \~{\i} wrongly.
2238                         // This will of course not translate \~{\ss} to \~{ß},
2239                         // but that does at least compile and does only look
2240                         // strange on screen.
2241                         context.check_layout(os);
2242                         os << "\\i \\" << t.cs() << "{"
2243                            << trim(p.verbatim_item(), " ")
2244                            << "}\n";
2245                 }
2246
2247                 else if (t.cs() == "ss") {
2248                         context.check_layout(os);
2249                         os << "\xdf";
2250                         skip_braces(p); // eat {}
2251                 }
2252
2253                 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2254                          t.cs() == "L") {
2255                         context.check_layout(os);
2256                         os << "\\i \\" << t.cs() << "{}\n";
2257                         skip_braces(p); // eat {}
2258                 }
2259
2260                 else if (t.cs() == "\\") {
2261                         context.check_layout(os);
2262                         string const next = p.next_token().asInput();
2263                         if (next == "[")
2264                                 handle_ert(os, "\\\\" + p.getOpt(), context);
2265                         else if (next == "*") {
2266                                 p.get_token();
2267                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
2268                         }
2269                         else {
2270                                 os << "\n\\newline\n";
2271                         }
2272                 }
2273
2274                 else if (t.cs() == "newline" ||
2275                         t.cs() == "linebreak") {
2276                         context.check_layout(os);
2277                         os << "\n\\" << t.cs() << "\n";
2278                         skip_braces(p); // eat {}
2279                 }
2280
2281                 else if (t.cs() == "href") {
2282                         context.check_layout(os);
2283                         begin_inset(os, "CommandInset ");
2284                         os << t.cs() << "\n";
2285                         os << "LatexCommand " << t.cs() << "\n";
2286                         bool erase = false;
2287                         size_t pos;
2288                         // the first argument is "type:target", "type:" is optional
2289                         // the second argument the name
2290                         string href_target = subst(p.verbatim_item(), "\n", " ");
2291                         string href_name = subst(p.verbatim_item(), "\n", " ");
2292                         string href_type;
2293                         // serach for the ":" to divide type from target
2294                         if ((pos = href_target.find(":", 0)) != string::npos){
2295                                 href_type = href_target;
2296                                 href_type.erase(pos + 1, href_type.length());
2297                                 href_target.erase(0, pos + 1);
2298                             erase = true;                                                                                       
2299                         }
2300                         os << "name " << '"' << href_name << '"' << "\n";
2301                         os << "target " << '"' << href_target << '"' << "\n";
2302                         if(erase)
2303                                 os << "type " << '"' << href_type << '"' << "\n";
2304                         end_inset(os);
2305                 }
2306
2307                 else if (t.cs() == "input" || t.cs() == "include"
2308                          || t.cs() == "verbatiminput") {
2309                         string name = '\\' + t.cs();
2310                         if (t.cs() == "verbatiminput"
2311                             && p.next_token().asInput() == "*")
2312                                 name += p.get_token().asInput();
2313                         context.check_layout(os);
2314                         begin_inset(os, "Include ");
2315                         string filename(normalize_filename(p.getArg('{', '}')));
2316                         string const path = getMasterFilePath();
2317                         // We want to preserve relative / absolute filenames,
2318                         // therefore path is only used for testing
2319                         // FIXME UNICODE encoding of filename and path may be
2320                         // wrong (makeAbsPath expects utf8)
2321                         if ((t.cs() == "include" || t.cs() == "input") &&
2322                             !makeAbsPath(filename, path).exists()) {
2323                                 // The file extension is probably missing.
2324                                 // Now try to find it out.
2325                                 string const tex_name =
2326                                         find_file(filename, path,
2327                                                   known_tex_extensions);
2328                                 if (!tex_name.empty())
2329                                         filename = tex_name;
2330                         }
2331                         // FIXME UNICODE encoding of filename and path may be
2332                         // wrong (makeAbsPath expects utf8)
2333                         if (makeAbsPath(filename, path).exists()) {
2334                                 string const abstexname =
2335                                         makeAbsPath(filename, path).absFilename();
2336                                 string const abslyxname =
2337                                         changeExtension(abstexname, ".lyx");
2338                                 fix_relative_filename(filename);
2339                                 string const lyxname =
2340                                         changeExtension(filename, ".lyx");
2341                                 if (t.cs() != "verbatiminput" &&
2342                                     tex2lyx(abstexname, FileName(abslyxname))) {
2343                                         os << name << '{' << lyxname << "}\n";
2344                                 } else {
2345                                         os << name << '{' << filename << "}\n";
2346                                 }
2347                         } else {
2348                                 cerr << "Warning: Could not find included file '"
2349                                      << filename << "'." << endl;
2350                                 os << name << '{' << filename << "}\n";
2351                         }
2352                         os << "preview false\n";
2353                         end_inset(os);
2354                 }
2355
2356                 else if (t.cs() == "bibliographystyle") {
2357                         // store new bibliographystyle
2358                         bibliographystyle = p.verbatim_item();
2359                         // output new bibliographystyle.
2360                         // This is only necessary if used in some other macro than \bibliography.
2361                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2362                 }
2363
2364                 else if (t.cs() == "bibliography") {
2365                         context.check_layout(os);
2366                         begin_inset(os, "LatexCommand ");
2367                         os << "\\bibtex";
2368                         // Do we have a bibliographystyle set?
2369                         if (!bibliographystyle.empty()) {
2370                                 os << '[' << bibliographystyle << ']';
2371                         }
2372                         os << '{' << p.verbatim_item() << "}\n";
2373                         end_inset(os);
2374                 }
2375
2376                 else if (t.cs() == "parbox")
2377                         parse_box(p, os, FLAG_ITEM, outer, context, true);
2378                 
2379                 //\makebox() is part of the picture environment and different from \makebox{}
2380                 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2381                 else if (t.cs() == "makebox") {
2382                         string arg = t.asInput();
2383                         if (p.next_token().character() == '(')
2384                                 //the syntax is: \makebox(x,y)[position]{content}
2385                                 arg += p.getFullParentheseArg();
2386                         else
2387                                 //the syntax is: \makebox[width][position]{content}
2388                                 arg += p.getFullOpt();
2389                         handle_ert(os, arg + p.getFullOpt(), context);
2390                 }
2391
2392                 else if (t.cs() == "smallskip" ||
2393                          t.cs() == "medskip" ||
2394                          t.cs() == "bigskip" ||
2395                          t.cs() == "vfill") {
2396                         context.check_layout(os);
2397                         begin_inset(os, "VSpace ");
2398                         os << t.cs();
2399                         end_inset(os);
2400                         skip_braces(p);
2401                 }
2402
2403                 else if (is_known(t.cs(), known_spaces)) {
2404                         char const * const * where = is_known(t.cs(), known_spaces);
2405                         context.check_layout(os);
2406                         os << "\\InsetSpace ";
2407                         os << '\\' << known_coded_spaces[where - known_spaces]
2408                            << '\n';
2409                         // LaTeX swallows whitespace after all spaces except
2410                         // "\\,". We have to do that here, too, because LyX
2411                         // adds "{}" which would make the spaces significant.
2412                         if (t.cs() !=  ",")
2413                                 eat_whitespace(p, os, context, false);
2414                         // LyX adds "{}" after all spaces except "\\ " and
2415                         // "\\,", so we have to remove "{}".
2416                         // "\\,{}" is equivalent to "\\," in LaTeX, so we
2417                         // remove the braces after "\\,", too.
2418                         if (t.cs() != " ")
2419                                 skip_braces(p);
2420                 }
2421
2422                 else if (t.cs() == "newpage" ||
2423                         t.cs() == "pagebreak" ||
2424                         t.cs() == "clearpage" ||
2425                         t.cs() == "cleardoublepage") {
2426                         context.check_layout(os);
2427                         os << "\n\\" << t.cs() << "\n";
2428                         skip_braces(p); // eat {}
2429                 }
2430
2431                 else if (t.cs() == "newcommand" ||
2432                          t.cs() == "providecommand" ||
2433                          t.cs() == "renewcommand" ||
2434                          t.cs() == "newlyxcommand") {
2435                         // these could be handled by parse_command(), but
2436                         // we need to call add_known_command() here.
2437                         string name = t.asInput();
2438                         if (p.next_token().asInput() == "*") {
2439                                 // Starred form. Eat '*'
2440                                 p.get_token();
2441                                 name += '*';
2442                         }
2443                         string const command = p.verbatim_item();
2444                         string const opt1 = p.getOpt();
2445                         string optionals;
2446                         unsigned optionalsNum = 0;
2447                         while (true) {
2448                                 string const opt = p.getFullOpt();
2449                                 if (opt.empty())
2450                                         break;
2451                                 optionalsNum++;
2452                                 optionals += opt;
2453                         }
2454                         add_known_command(command, opt1, optionalsNum);
2455                         string const ert = name + '{' + command + '}' + opt1
2456                                 + optionals + '{' + p.verbatim_item() + '}';
2457
2458                         context.check_layout(os);
2459                         begin_inset(os, "FormulaMacro");
2460                         os << "\n" << ert;
2461                         end_inset(os);
2462                 }
2463                 
2464                 else if (t.cs() == "newcommandx" ||
2465                          t.cs() == "renewcommandx") {
2466                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
2467
2468                         // get command name
2469                         string command;
2470                         if (p.next_token().cat() == catBegin)
2471                                 command = p.verbatim_item();
2472                         else 
2473                                 command = "\\" + p.get_token().cs();
2474                         
2475                         // get arity, we do not check that it fits to the given
2476                         // optional parameters here.
2477                         string const opt1 = p.getOpt();
2478                         
2479                         // get options and default values for optional parameters
2480                         std::vector<string> optionalValues;
2481                         int optionalsNum = 0;
2482                         if (p.next_token().character() == '[') {
2483                                 // skip '['
2484                                 p.get_token();
2485                                 
2486                                 // handle 'opt=value' options, separated by ','.
2487                                 eat_whitespace(p, os, context, false);
2488                                 while (p.next_token().character() != ']' && p.good()) {
2489                                         char_type nextc = p.next_token().character();
2490                                         if (nextc >= '1' && nextc <= '9') {
2491                                                 // optional value -> get parameter number
2492                                                 int n = p.getChar() - '0';
2493
2494                                                 // skip '='
2495                                                 if (p.next_token().character() != '=') {
2496                                                         cerr << "'=' expected after numeral option of \\newcommandx" << std::endl;
2497                                                         // try to find ] or ,
2498                                                         while (p.next_token().character() != ','
2499                                                                && p.next_token().character() != ']')
2500                                                                 p.get_token();
2501                                                         continue;
2502                                                 } else
2503                                                         p.get_token();
2504                                                 
2505                                                 // get value
2506                                                 optionalValues.resize(max(size_t(n), optionalValues.size()));
2507                                                 optionalValues[n - 1].clear();
2508                                                 while (p.next_token().character() != ']'
2509                                                        && p.next_token().character() != ',')
2510                                                         optionalValues[n - 1] += p.verbatim_item();
2511                                                 optionalsNum = max(n, optionalsNum);
2512                                         } else if (p.next_token().cat() == catLetter) {
2513                                                 // we in fact ignore every non-optional
2514                                                 // parameters
2515                                                 
2516                                                 // get option name
2517                                                 docstring opt;
2518                                                 while (p.next_token().cat() == catLetter)
2519                                                         opt += p.getChar();
2520                                                 
2521                                                 // value?
2522                                                 eat_whitespace(p, os, context, false);
2523                                                 if (p.next_token().character() == '=') {
2524                                                         p.get_token();
2525                                                         while (p.next_token().character() != ']'
2526                                                                && p.next_token().character() != ',')
2527                                                                 p.verbatim_item();
2528                                                 }
2529                                         } else
2530                                                 return;
2531                                         
2532                                         // skip komma
2533                                         eat_whitespace(p, os, context, false);
2534                                         if (p.next_token().character() == ',') {
2535                                                 p.getChar();
2536                                                 eat_whitespace(p, os, context, false);
2537                                         } else if (p.next_token().character() != ']')
2538                                                 continue;
2539                                 }
2540                                 
2541                                 // skip ']'
2542                                 p.get_token();
2543                         }
2544                         
2545                         // concat the default values to the optionals string
2546                         string optionals;
2547                         for (unsigned i = 0; i < optionalValues.size(); ++i)
2548                                 optionals += "[" + optionalValues[i] + "]";
2549                         
2550                         // register and output command
2551                         add_known_command(command, opt1, optionalsNum);
2552                         string const ert = "\\newcommand{" + command + '}' + opt1
2553                         + optionals + '{' + p.verbatim_item() + '}';
2554                         
2555                         context.check_layout(os);
2556                         begin_inset(os, "FormulaMacro");
2557                         os << "\n" << ert;
2558                         end_inset(os);
2559                 }
2560
2561                 else if (t.cs() == "vspace") {
2562                         bool starred = false;
2563                         if (p.next_token().asInput() == "*") {
2564                                 p.get_token();
2565                                 starred = true;
2566                         }
2567                         string const length = p.verbatim_item();
2568                         string unit;
2569                         string valstring;
2570                         bool valid = splitLatexLength(length, valstring, unit);
2571                         bool known_vspace = false;
2572                         bool known_unit = false;
2573                         double value;
2574                         if (valid) {
2575                                 istringstream iss(valstring);
2576                                 iss >> value;
2577                                 if (value == 1.0) {
2578                                         if (unit == "\\smallskipamount") {
2579                                                 unit = "smallskip";
2580                                                 known_vspace = true;
2581                                         } else if (unit == "\\medskipamount") {
2582                                                 unit = "medskip";
2583                                                 known_vspace = true;
2584                                         } else if (unit == "\\bigskipamount") {
2585                                                 unit = "bigskip";
2586                                                 known_vspace = true;
2587                                         } else if (unit == "\\fill") {
2588                                                 unit = "vfill";
2589                                                 known_vspace = true;
2590                                         }
2591                                 }
2592                                 if (!known_vspace) {
2593                                         switch (unitFromString(unit)) {
2594                                         case Length::SP:
2595                                         case Length::PT:
2596                                         case Length::BP:
2597                                         case Length::DD:
2598                                         case Length::MM:
2599                                         case Length::PC:
2600                                         case Length::CC:
2601                                         case Length::CM:
2602                                         case Length::IN:
2603                                         case Length::EX:
2604                                         case Length::EM:
2605                                         case Length::MU:
2606                                                 known_unit = true;
2607                                                 break;
2608                                         default:
2609                                                 break;
2610                                         }
2611                                 }
2612                         }
2613
2614                         if (known_unit || known_vspace) {
2615                                 // Literal length or known variable
2616                                 context.check_layout(os);
2617                                 begin_inset(os, "VSpace ");
2618                                 if (known_unit)
2619                                         os << value;
2620                                 os << unit;
2621                                 if (starred)
2622                                         os << '*';
2623                                 end_inset(os);
2624                         } else {
2625                                 // LyX can't handle other length variables in Inset VSpace
2626                                 string name = t.asInput();
2627                                 if (starred)
2628                                         name += '*';
2629                                 if (valid) {
2630                                         if (value == 1.0)
2631                                                 handle_ert(os, name + '{' + unit + '}', context);
2632                                         else if (value == -1.0)
2633                                                 handle_ert(os, name + "{-" + unit + '}', context);
2634                                         else
2635                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
2636                                 } else
2637                                         handle_ert(os, name + '{' + length + '}', context);
2638                         }
2639                 }
2640
2641                 else {
2642                         //cerr << "#: " << t << " mode: " << mode << endl;
2643                         // heuristic: read up to next non-nested space
2644                         /*
2645                         string s = t.asInput();
2646                         string z = p.verbatim_item();
2647                         while (p.good() && z != " " && z.size()) {
2648                                 //cerr << "read: " << z << endl;
2649                                 s += z;
2650                                 z = p.verbatim_item();
2651                         }
2652                         cerr << "found ERT: " << s << endl;
2653                         handle_ert(os, s + ' ', context);
2654                         */
2655                         string name = t.asInput();
2656                         if (p.next_token().asInput() == "*") {
2657                                 // Starred commands like \vspace*{}
2658                                 p.get_token();                          // Eat '*'
2659                                 name += '*';
2660                         }
2661                         if (! parse_command(name, p, os, outer, context))
2662                                 handle_ert(os, name, context);
2663                 }
2664
2665                 if (flags & FLAG_LEAVE) {
2666                         flags &= ~FLAG_LEAVE;
2667                         break;
2668                 }
2669         }
2670 }
2671
2672 // }])
2673
2674
2675 } // namespace lyx