]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
some more gettext work
[lyx.git] / src / tex2lyx / text.C
1 /**
2  * \file tex2lyx/text.C
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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 // {[(
13
14 #include <config.h>
15
16 #include "tex2lyx.h"
17 #include "context.h"
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/tostr.h"
22 #include "support/filetools.h"
23
24 #include <iostream>
25 #include <map>
26 #include <sstream>
27 #include <vector>
28
29 using lyx::support::rtrim;
30 using lyx::support::suffixIs;
31 using lyx::support::contains;
32 using lyx::support::subst;
33
34 using std::cerr;
35 using std::endl;
36
37 using std::map;
38 using std::ostream;
39 using std::ostringstream;
40 using std::istringstream;
41 using std::string;
42 using std::vector;
43
44
45 // thin wrapper around parse_text using a string
46 string parse_text(Parser & p, unsigned flags, const bool outer,
47                   Context & context)
48 {
49         ostringstream os;
50         parse_text(p, os, flags, outer, context);
51         return os.str();
52 }
53
54 // parses a subdocument, usually useful in insets (whence the name)
55 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
56                 Context & context)
57 {
58         Context newcontext(true, context.textclass);
59         parse_text(p, os, flags, outer, newcontext);
60         newcontext.check_end_layout(os);
61 }
62
63
64 // parses a paragraph snippet, useful for example for \emph{...}
65 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
66                 Context & context)
67 {
68         Context newcontext(false, context.textclass);
69         parse_text(p, os, flags, outer, newcontext);
70         // should not be needed
71         newcontext.check_end_layout(os);
72 }
73
74
75 namespace {
76
77 char const * known_latex_commands[] = { "ref", "cite", "label", "index",
78 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
79
80 // LaTeX names for quotes
81 char const * known_quotes[] = { "glqq", "grqq", "quotedblbase",
82 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
83
84 // the same as known_quotes with .lyx names
85 char const * known_coded_quotes[] = { "gld", "grd", "gld",
86 "grd", "gls", "fls", "frd", 0};
87
88 char const * known_sizes[] = { "tiny", "scriptsize", "footnotesize",
89 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
90
91 char const * known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
92 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
93
94 // splits "x=z, y=b" into a map
95 map<string, string> split_map(string const & s)
96 {
97         map<string, string> res;
98         vector<string> v;
99         split(s, v);
100         for (size_t i = 0; i < v.size(); ++i) {
101                 size_t const pos   = v[i].find('=');
102                 string const index = v[i].substr(0, pos);
103                 string const value = v[i].substr(pos + 1, string::npos);
104                 res[trim(index)] = trim(value);
105         }
106         return res;
107 }
108
109
110 /*!
111  * Split a LaTeX length into value and unit.
112  * The latter can be a real unit like "pt", or a latex length variable
113  * like "\textwidth". The unit may contain additional stuff like glue
114  * lengths, but we don't care, because such lengths are ERT anyway.
115  * \return true if \param value and \param unit are valid.
116  */
117 bool splitLatexLength(string const & len, string & value, string & unit)
118 {
119         if (len.empty())
120                 return false;
121         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
122         //'4,5' is a valid LaTeX length number. Change it to '4.5'
123         string const length = subst(len, ',', '.');
124         if (i == string::npos)
125                 return false;
126         if (i == 0) {
127                 if (len[0] == '\\') {
128                         // We had something like \textwidth without a factor
129                         value = "1.0";
130                 } else {
131                         return false;
132                 }
133         } else {
134                 value = trim(string(length, 0, i));
135         }
136         if (value == "-")
137                 value = "-1.0";
138         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
139         if (contains(len, '\\'))
140                 unit = trim(string(len, i));
141         else
142                 unit = lyx::support::lowercase(trim(string(len, i)));
143         return true;
144 }
145
146
147 // A simple function to translate a latex length to something lyx can
148 // understand. Not perfect, but rather best-effort.
149 bool translate_len(string const & length, string & valstring, string & unit)
150 {
151         if (!splitLatexLength(length, valstring, unit))
152                 return false;
153         // LyX uses percent values
154         double value;
155         istringstream iss(valstring);
156         iss >> value;
157         value *= 100;
158         ostringstream oss;
159         oss << value;
160         string const percentval = oss.str();
161         // a normal length
162         if (unit.empty() || unit[0] != '\\')
163                 return true;
164         string::size_type const i = unit.find(' ');
165         string const endlen = (i == string::npos) ? string() : string(unit, i);
166         if (unit == "\\textwidth") {
167                 valstring = percentval;
168                 unit = "text%" + endlen;
169         } else if (unit == "\\columnwidth") {
170                 valstring = percentval;
171                 unit = "col%" + endlen;
172         } else if (unit == "\\paperwidth") {
173                 valstring = percentval;
174                 unit = "page%" + endlen;
175         } else if (unit == "\\linewidth") {
176                 valstring = percentval;
177                 unit = "line%" + endlen;
178         } else if (unit == "\\paperheight") {
179                 valstring = percentval;
180                 unit = "pheight%" + endlen;
181         } else if (unit == "\\textheight") {
182                 valstring = percentval;
183                 unit = "theight%" + endlen;
184         }
185         return true;
186 }
187
188
189 string translate_len(string const & length)
190 {
191         string unit;
192         string value;
193         if (translate_len(length, value, unit))
194                 return value + unit;
195         // If the input is invalid, return what we have.
196         return length;
197 }
198
199
200 /*!
201  * Translates a LaTeX length into \param value, \param unit and
202  * \param special parts suitable for a box inset.
203  * The difference from translate_len() is that a box inset knows about
204  * some special "units" that are stored in \param special.
205  */
206 void translate_box_len(string const & length, string & value, string & unit, string & special)
207 {
208         if (translate_len(length, value, unit)) {
209                 if (unit == "\\height" || unit == "\\depth" ||
210                     unit == "\\totalheight" || unit == "\\width") {
211                         special = unit.substr(1);
212                         // The unit is not used, but LyX requires a dummy setting
213                         unit = "in";
214                 } else
215                         special = "none";
216         } else {
217                 value.clear();
218                 unit = length;
219                 special = "none";
220         }
221 }
222
223
224 void begin_inset(ostream & os, string const & name)
225 {
226         os << "\n\\begin_inset " << name;
227 }
228
229
230 void end_inset(ostream & os)
231 {
232         os << "\n\\end_inset \n\n";
233 }
234
235
236 void skip_braces(Parser & p)
237 {
238         if (p.next_token().cat() != catBegin)
239                 return;
240         p.get_token();
241         if (p.next_token().cat() == catEnd) {
242                 p.get_token();
243                 return;
244         }
245         p.putback();
246 }
247
248
249 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
250 {
251         if (check_layout) {
252                 // We must have a valid layout before outputting the ERT inset.
253                 context.check_layout(os);
254         }
255         Context newcontext(true, context.textclass);
256         begin_inset(os, "ERT");
257         os << "\nstatus collapsed\n";
258         newcontext.check_layout(os);
259         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
260                 if (*it == '\\')
261                         os << "\n\\backslash \n";
262                 else if (*it == '\n')
263                         os << "\n\\newline \n";
264                 else
265                         os << *it;
266         }
267         newcontext.check_end_layout(os);
268         end_inset(os);
269 }
270
271
272 void handle_comment(ostream & os, string const & s, Context & context)
273 {
274         // TODO: Handle this better
275         Context newcontext(true, context.textclass);
276         begin_inset(os, "ERT");
277         os << "\nstatus collapsed\n";
278         newcontext.check_layout(os);
279         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
280                 if (*it == '\\')
281                         os << "\n\\backslash \n";
282                 else
283                         os << *it;
284         }
285         // make sure that our comment is the last thing on the line
286         os << "\n\\newline";
287         newcontext.check_end_layout(os);
288         end_inset(os);
289 }
290
291
292 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
293 public:
294         isLayout(string const name) : name_(name) {}
295         bool operator()(LyXLayout_ptr const & ptr) const {
296                 return ptr->latexname() == name_;
297         }
298 private:
299         string const name_;
300 };
301
302
303 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
304                          string const & name)
305 {
306         LyXTextClass::const_iterator beg  = textclass.begin();
307         LyXTextClass::const_iterator end = textclass.end();
308
309         LyXTextClass::const_iterator
310                 it = std::find_if(beg, end, isLayout(name));
311
312         return (it == end) ? LyXLayout_ptr() : *it;
313 }
314
315
316 void output_command_layout(ostream & os, Parser & p, bool outer,
317                            Context & parent_context,
318                            LyXLayout_ptr newlayout)
319 {
320         parent_context.check_end_layout(os);
321         Context context(true, parent_context.textclass, newlayout,
322                         parent_context.layout);
323         context.check_deeper(os);
324         context.check_layout(os);
325         if (context.layout->optionalargs > 0) {
326                 p.skip_spaces();
327                 if (p.next_token().character() == '[') {
328                         p.get_token(); // eat '['
329                         begin_inset(os, "OptArg\n");
330                         os << "status collapsed\n\n";
331                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
332                         end_inset(os);
333                 }
334         }
335         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
336         context.check_end_layout(os);
337         context.check_end_deeper(os);
338         // We don't need really a new paragraph, but
339         // we must make sure that the next item gets a \begin_layout.
340         parent_context.new_paragraph(os);
341 }
342
343
344 /*!
345  * Output a space if necessary.
346  * This function gets called for every whitespace token.
347  *
348  * We have three cases here:
349  * 1. A space must be suppressed. Example: The lyxcode case below
350  * 2. A space may be suppressed. Example: Spaces before "\par"
351  * 3. A space must not be suppressed. Example: A space between two words
352  *
353  * We currently handle only 1. and 3 and from 2. only the case of
354  * spaces before newlines as a side effect.
355  *
356  * 2. could be used to suppress as many spaces as possible. This has two effects:
357  * - Reimporting LyX generated LaTeX files changes almost no whitespace
358  * - Superflous whitespace from non LyX generated LaTeX files is removed.
359  * The drawback is that the logic inside the function becomes
360  * complicated, and that is the reason why it is not implemented.
361  */
362 void check_space(Parser const & p, ostream & os, Context & context)
363 {
364         Token const next = p.next_token();
365         Token const curr = p.curr_token();
366         // A space before a single newline and vice versa must be ignored
367         // LyX emits a newline before \end{lyxcode}.
368         // This newline must be ignored,
369         // otherwise LyX will add an additional protected space.
370         if (next.cat() == catSpace ||
371             next.cat() == catNewline ||
372             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
373                 return;
374         }
375         context.check_layout(os);
376         os << ' ';
377 }
378
379
380 /*!
381  * Check wether \param command is a known command. If yes,
382  * handle the command with all arguments.
383  * \return true if the command was parsed, false otherwise.
384  */
385 bool parse_command(string const & command, Parser & p, ostream & os,
386                    bool outer, Context & context)
387 {
388         if (known_commands.find(command) != known_commands.end()) {
389                 vector<ArgumentType> const & template_arguments = known_commands[command];
390                 string ert = command;
391                 size_t no_arguments = template_arguments.size();
392                 for (size_t i = 0; i < no_arguments; ++i) {
393                         switch (template_arguments[i]) {
394                         case required:
395                                 // This argument contains regular LaTeX
396                                 handle_ert(os, ert + '{', context);
397                                 parse_text(p, os, FLAG_ITEM, outer, context);
398                                 ert = "}";
399                                 break;
400                         case verbatim:
401                                 // This argument may contain special characters
402                                 ert += '{' + p.verbatim_item() + '}';
403                                 break;
404                         case optional:
405                                 ert += p.getOpt();
406                                 break;
407                         }
408                 }
409                 handle_ert(os, ert, context);
410                 return true;
411         }
412         return false;
413 }
414
415
416 /// Parses a minipage or parbox
417 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
418                Context & parent_context, bool use_parbox)
419 {
420         string position;
421         string inner_pos;
422         string height_value = "0";
423         string height_unit = "pt";
424         string height_special = "none";
425         string latex_height;
426         if (p.next_token().asInput() == "[") {
427                 position = p.getArg('[', ']');
428                 if (position != "t" && position != "c" && position != "b") {
429                         position = "c";
430                         cerr << "invalid position for minipage/parbox" << endl;
431                 }
432                 if (p.next_token().asInput() == "[") {
433                         latex_height = p.getArg('[', ']');
434                         translate_box_len(latex_height, height_value, height_unit, height_special);
435
436                         if (p.next_token().asInput() == "[") {
437                                 inner_pos = p.getArg('[', ']');
438                                 if (inner_pos != "c" && inner_pos != "t" &&
439                                     inner_pos != "b" && inner_pos != "s") {
440                                         inner_pos = position;
441                                         cerr << "invalid inner_pos for minipage/parbox"
442                                              << endl;
443                                 }
444                         }
445                 }
446         }
447         string width_value;
448         string width_unit;
449         string const latex_width = p.verbatim_item();
450         translate_len(latex_width, width_value, width_unit);
451         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
452                 // LyX can't handle length variables
453                 ostringstream ss;
454                 if (use_parbox)
455                         ss << "\\parbox";
456                 else
457                         ss << "\\begin{minipage}";
458                 if (!position.empty())
459                         ss << '[' << position << ']';
460                 if (!latex_height.empty())
461                         ss << '[' << latex_height << ']';
462                 if (!inner_pos.empty())
463                         ss << '[' << inner_pos << ']';
464                 ss << "{" << latex_width << "}";
465                 if (use_parbox)
466                         ss << '{';
467                 handle_ert(os, ss.str(), parent_context);
468                 parent_context.new_paragraph(os);
469                 parse_text_in_inset(p, os, flags, outer, parent_context);
470                 if (use_parbox)
471                         handle_ert(os, "}", parent_context);
472                 else
473                         handle_ert(os, "\\end{minipage}", parent_context);
474         } else {
475                 // LyX does not like empty positions, so we have
476                 // to set them to the LaTeX default values here.
477                 if (position.empty())
478                         position = "c";
479                 if (inner_pos.empty())
480                         inner_pos = position;
481                 parent_context.check_layout(os);
482                 begin_inset(os, "Box Frameless\n");
483                 os << "position \"" << position << "\"\n";
484                 os << "hor_pos \"c\"\n";
485                 os << "has_inner_box 1\n";
486                 os << "inner_pos \"" << inner_pos << "\"\n";
487                 os << "use_parbox " << use_parbox << "\n";
488                 os << "width \"" << width_value << width_unit << "\"\n";
489                 os << "special \"none\"\n";
490                 os << "height \"" << height_value << height_unit << "\"\n";
491                 os << "height_special \"" << height_special << "\"\n";
492                 os << "status open\n\n";
493                 parse_text_in_inset(p, os, flags, outer, parent_context);
494                 end_inset(os);
495 #ifdef PRESERVE_LAYOUT
496                 // lyx puts a % after the end of the minipage
497                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
498                         // new paragraph
499                         //handle_comment(os, "%dummy", parent_context);
500                         p.get_token();
501                         p.skip_spaces();
502                         parent_context.new_paragraph(os);
503                 }
504                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
505                         //handle_comment(os, "%dummy", parent_context);
506                         p.get_token();
507                         p.skip_spaces();
508                         // We add a protected space if something real follows
509                         if (p.good() && p.next_token().cat() != catComment) {
510                                 os << "\\InsetSpace ~\n";
511                         }
512                 }
513 #endif
514         }
515 }
516
517
518 void parse_environment(Parser & p, ostream & os, bool outer,
519                        Context & parent_context)
520 {
521         LyXLayout_ptr newlayout;
522         string const name = p.getArg('{', '}');
523         const bool is_starred = suffixIs(name, '*');
524         string const unstarred_name = rtrim(name, "*");
525         active_environments.push_back(name);
526         p.skip_spaces();
527
528         if (is_math_env(name)) {
529                 parent_context.check_layout(os);
530                 begin_inset(os, "Formula ");
531                 os << "\\begin{" << name << "}";
532                 parse_math(p, os, FLAG_END, MATH_MODE);
533                 os << "\\end{" << name << "}";
534                 end_inset(os);
535         }
536
537         else if (name == "tabular") {
538                 parent_context.check_layout(os);
539                 begin_inset(os, "Tabular ");
540                 handle_tabular(p, os, parent_context);
541                 end_inset(os);
542         }
543
544         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
545                 parent_context.check_layout(os);
546                 begin_inset(os, "Float " + unstarred_name + "\n");
547                 if (p.next_token().asInput() == "[") {
548                         os << "placement " << p.getArg('[', ']') << '\n';
549                 }
550                 os << "wide " << tostr(is_starred)
551                    << "\nstatus open\n\n";
552                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
553                 end_inset(os);
554                 // We don't need really a new paragraph, but
555                 // we must make sure that the next item gets a \begin_layout.
556                 parent_context.new_paragraph(os);
557         }
558
559         else if (name == "minipage")
560                 parse_box(p, os, FLAG_END, outer, parent_context, false);
561
562         // Alignment settings
563         else if (name == "center" || name == "flushleft" || name == "flushright" ||
564                  name == "centering" || name == "raggedright" || name == "raggedleft") {
565                 // We must begin a new paragraph if not already done
566                 if (! parent_context.atParagraphStart()) {
567                         parent_context.check_end_layout(os);
568                         parent_context.new_paragraph(os);
569                 }
570                 if (name == "flushleft" || name == "raggedright")
571                         parent_context.add_extra_stuff("\\align left ");
572                 else if (name == "flushright" || name == "raggedleft")
573                         parent_context.add_extra_stuff("\\align right ");
574                 else
575                         parent_context.add_extra_stuff("\\align center ");
576                 parse_text(p, os, FLAG_END, outer, parent_context);
577                 // Just in case the environment is empty ..
578                 parent_context.extra_stuff.erase();
579                 // We must begin a new paragraph to reset the alignment
580                 parent_context.new_paragraph(os);
581         }
582
583         // The single '=' is meant here.
584         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
585                    newlayout->isEnvironment()) {
586                 Context context(true, parent_context.textclass, newlayout,
587                                 parent_context.layout);
588                 parent_context.check_end_layout(os);
589                 switch (context.layout->latextype) {
590                 case  LATEX_LIST_ENVIRONMENT:
591                         context.extra_stuff = "\\labelwidthstring "
592                                 + p.verbatim_item() + '\n';
593                         p.skip_spaces();
594                         break;
595                 case  LATEX_BIB_ENVIRONMENT:
596                         p.verbatim_item(); // swallow next arg
597                         p.skip_spaces();
598                         break;
599                 default:
600                         break;
601                 }
602                 context.check_deeper(os);
603                 parse_text(p, os, FLAG_END, outer, context);
604                 context.check_end_layout(os);
605                 context.check_end_deeper(os);
606                 parent_context.new_paragraph(os);
607         }
608
609         else if (name == "appendix") {
610                 // This is no good latex style, but it works and is used in some documents...
611                 parent_context.check_end_layout(os);
612                 Context context(true, parent_context.textclass, parent_context.layout,
613                                 parent_context.layout);
614                 context.check_layout(os);
615                 os << "\\start_of_appendix\n";
616                 parse_text(p, os, FLAG_END, outer, context);
617                 context.check_end_layout(os);
618         }
619
620         else if (name == "comment") {
621                 parent_context.check_layout(os);
622                 begin_inset(os, "Note Comment\n");
623                 os << "status open\n";
624                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
625                 end_inset(os);
626         }
627
628         else if (name == "lyxgreyedout") {
629                 parent_context.check_layout(os);
630                 begin_inset(os, "Note Greyedout\n");
631                 os << "status open\n";
632                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
633                 end_inset(os);
634         }
635
636         else if (name == "tabbing") {
637                 // We need to remember that we have to handle '\=' specially
638                 handle_ert(os, "\\begin{" + name + "}", parent_context);
639                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
640                 handle_ert(os, "\\end{" + name + "}", parent_context);
641         }
642
643         else {
644                 handle_ert(os, "\\begin{" + name + "}", parent_context);
645                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
646                 handle_ert(os, "\\end{" + name + "}", parent_context);
647         }
648
649         active_environments.pop_back();
650         if (name != "math")
651                 p.skip_spaces();
652 }
653
654 } // anonymous namespace
655
656
657
658
659 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
660                 Context & context)
661 {
662         LyXLayout_ptr newlayout;
663         // Store the latest bibliographystyle (needed for bibtex inset)
664         string bibliographystyle;
665         while (p.good()) {
666                 Token const & t = p.get_token();
667
668 #ifdef FILEDEBUG
669                 cerr << "t: " << t << " flags: " << flags << "\n";
670 #endif
671
672                 if (flags & FLAG_ITEM) {
673                         if (t.cat() == catSpace)
674                                 continue;
675
676                         flags &= ~FLAG_ITEM;
677                         if (t.cat() == catBegin) {
678                                 // skip the brace and collect everything to the next matching
679                                 // closing brace
680                                 flags |= FLAG_BRACE_LAST;
681                                 continue;
682                         }
683
684                         // handle only this single token, leave the loop if done
685                         flags |= FLAG_LEAVE;
686                 }
687
688                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
689                         return;
690
691                 //
692                 // cat codes
693                 //
694                 if (t.cat() == catMath) {
695                         // we are inside some text mode thingy, so opening new math is allowed
696                         context.check_layout(os);
697                         begin_inset(os, "Formula ");
698                         Token const & n = p.get_token();
699                         if (n.cat() == catMath && outer) {
700                                 // TeX's $$...$$ syntax for displayed math
701                                 os << "\\[";
702                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
703                                 os << "\\]";
704                                 p.get_token(); // skip the second '$' token
705                         } else {
706                                 // simple $...$  stuff
707                                 p.putback();
708                                 os << '$';
709                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
710                                 os << '$';
711                         }
712                         end_inset(os);
713                 }
714
715                 else if (t.cat() == catSuper || t.cat() == catSub)
716                         cerr << "catcode " << t << " illegal in text mode\n";
717
718                 // Basic support for english quotes. This should be
719                 // extended to other quotes, but is not so easy (a
720                 // left english quote is the same as a right german
721                 // quote...)
722                 else if (t.asInput() == "`"
723                          && p.next_token().asInput() == "`") {
724                         context.check_layout(os);
725                         begin_inset(os, "Quotes ");
726                         os << "eld";
727                         end_inset(os);
728                         p.get_token();
729                         skip_braces(p);
730                 }
731                 else if (t.asInput() == "'"
732                          && p.next_token().asInput() == "'") {
733                         context.check_layout(os);
734                         begin_inset(os, "Quotes ");
735                         os << "erd";
736                         end_inset(os);
737                         p.get_token();
738                         skip_braces(p);
739                 }
740
741                 else if (t.cat() == catSpace || (t.cat() == catNewline && t.cs().size() == 1))
742                         check_space(p, os, context);
743
744                 else if (t.cat() == catLetter ||
745                                t.cat() == catOther ||
746                                t.cat() == catAlign ||
747                                t.cat() == catParameter) {
748                         context.check_layout(os);
749                         os << t.character();
750                 }
751
752                 else if (t.cat() == catNewline || (t.cat() == catEscape && t.cs() == "par")) {
753                         p.skip_spaces();
754                         context.new_paragraph(os);
755                 }
756
757                 else if (t.cat() == catActive) {
758                         context.check_layout(os);
759                         if (t.character() == '~') {
760                                 if (context.layout->free_spacing)
761                                         os << ' ';
762                                 else
763                                         os << "\\InsetSpace ~\n";
764                         } else
765                                 os << t.character();
766                 }
767
768                 else if (t.cat() == catBegin) {
769                         // special handling of size changes
770                         context.check_layout(os);
771                         bool const is_size = is_known(p.next_token().cs(), known_sizes);
772                         Token const prev = p.prev_token();
773                         string const s = parse_text(p, FLAG_BRACE_LAST, outer, context);
774                         if (s.empty() && (p.next_token().character() == '`' ||
775                                           (prev.character() == '-' && p.next_token().character())))
776                                 ; // ignore it in {}`` or -{}-
777                         else if (is_size || s == "[" || s == "]" || s == "*")
778                                 os << s;
779                         else {
780                                 handle_ert(os, "{", context, false);
781                                 // s will end the current layout and begin a new one if necessary
782                                 os << s;
783                                 handle_ert(os, "}", context);
784                         }
785                 }
786
787                 else if (t.cat() == catEnd) {
788                         if (flags & FLAG_BRACE_LAST) {
789                                 return;
790                         }
791                         cerr << "stray '}' in text\n";
792                         handle_ert(os, "}", context);
793                 }
794
795                 else if (t.cat() == catComment) {
796                         context.check_layout(os);
797                         if (!t.cs().empty()) {
798                                 handle_comment(os, '%' + t.cs(), context);
799                                 if (p.next_token().cat() == catNewline) {
800                                         // A newline after a comment line starts a new paragraph
801                                         context.new_paragraph(os);
802                                         p.skip_spaces();
803                                 }
804                         } else {
805                                 // "%\n" combination
806                                 p.skip_spaces();
807                         }
808                 }
809
810                 //
811                 // control sequences
812                 //
813
814                 else if (t.cs() == "(") {
815                         context.check_layout(os);
816                         begin_inset(os, "Formula");
817                         os << " \\(";
818                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
819                         os << "\\)";
820                         end_inset(os);
821                 }
822
823                 else if (t.cs() == "[") {
824                         context.check_layout(os);
825                         begin_inset(os, "Formula");
826                         os << " \\[";
827                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
828                         os << "\\]";
829                         end_inset(os);
830                 }
831
832                 else if (t.cs() == "begin")
833                         parse_environment(p, os, outer, context);
834
835                 else if (t.cs() == "end") {
836                         if (flags & FLAG_END) {
837                                 // eat environment name
838                                 string const name = p.getArg('{', '}');
839                                 if (name != active_environment())
840                                         cerr << "\\end{" + name + "} does not match \\begin{"
841                                                 + active_environment() + "}\n";
842                                 return;
843                         }
844                         p.error("found 'end' unexpectedly");
845                 }
846
847                 else if (t.cs() == "item") {
848                         p.skip_spaces();
849                         string s;
850                         bool optarg = false;
851                         if (p.next_token().character() == '[') {
852                                 p.get_token(); // eat '['
853                                 Context newcontext(false, context.textclass);
854                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
855                                 optarg = true;
856                         }
857                         context.set_item();
858                         context.check_layout(os);
859                         if (optarg) {
860                                 if (context.layout->labeltype != LABEL_MANUAL) {
861                                         // lyx does not support \item[\mybullet] in itemize environments
862                                         handle_ert(os, "[", context);
863                                         os << s;
864                                         handle_ert(os, "]", context);
865                                 } else if (!s.empty()) {
866                                         // The space is needed to separate the item from the rest of the sentence.
867                                         os << s << ' ';
868                                         p.skip_spaces();
869                                 }
870                         }
871                 }
872
873                 else if (t.cs() == "bibitem") {
874                         context.set_item();
875                         context.check_layout(os);
876                         os << "\\bibitem ";
877                         os << p.getOpt();
878                         os << '{' << p.verbatim_item() << '}' << "\n";
879                 }
880
881                 else if (t.cs() == "def") {
882                         p.skip_spaces();
883                         context.check_layout(os);
884                         string name = p.get_token().cs();
885                         while (p.next_token().cat() != catBegin)
886                                 name += p.get_token().asString();
887                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
888                 }
889
890                 else if (t.cs() == "noindent") {
891                         p.skip_spaces();
892                         context.add_extra_stuff("\\noindent ");
893                 }
894
895                 else if (t.cs() == "appendix") {
896                         p.skip_spaces();
897                         context.add_extra_stuff("\\start_of_appendix ");
898                 }
899
900                 // Must attempt to parse "Section*" before "Section".
901                 else if ((p.next_token().asInput() == "*") &&
902                          // The single '=' is meant here.
903                          (newlayout = findLayout(context.textclass,
904                                                  t.cs() + '*')).get() &&
905                          newlayout->isCommand()) {
906                         p.get_token();
907                         output_command_layout(os, p, outer, context, newlayout);
908                         p.skip_spaces();
909                 }
910
911                 // The single '=' is meant here.
912                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
913                          newlayout->isCommand()) {
914                         output_command_layout(os, p, outer, context, newlayout);
915                         p.skip_spaces();
916                 }
917
918                 else if (t.cs() == "includegraphics") {
919                         map<string, string> opts = split_map(p.getArg('[', ']'));
920                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
921
922                         context.check_layout(os);
923                         begin_inset(os, "Graphics ");
924                         os << "\n\tfilename " << name << '\n';
925                         if (opts.find("width") != opts.end())
926                                 os << "\twidth "
927                                    << translate_len(opts["width"]) << '\n';
928                         if (opts.find("height") != opts.end())
929                                 os << "\theight "
930                                    << translate_len(opts["height"]) << '\n';
931                         if (opts.find("scale") != opts.end()) {
932                                 istringstream iss(opts["scale"]);
933                                 double val;
934                                 iss >> val;
935                                 val = val*100;
936                                 os << "\tscale " << val << '\n';
937                         }
938                         if (opts.find("angle") != opts.end())
939                                 os << "\trotateAngle "
940                                    << opts["angle"] << '\n';
941                         if (opts.find("origin") != opts.end()) {
942                                 ostringstream ss;
943                                 string const opt = opts["origin"];
944                                 if (opt.find('l') != string::npos) ss << "left";
945                                 if (opt.find('r') != string::npos) ss << "right";
946                                 if (opt.find('c') != string::npos) ss << "center";
947                                 if (opt.find('t') != string::npos) ss << "Top";
948                                 if (opt.find('b') != string::npos) ss << "Bottom";
949                                 if (opt.find('B') != string::npos) ss << "Baseline";
950                                 if (!ss.str().empty())
951                                         os << "\trotateOrigin " << ss.str() << '\n';
952                                 else
953                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
954                         }
955                         if (opts.find("keepaspectratio") != opts.end())
956                                 os << "\tkeepAspectRatio\n";
957                         if (opts.find("clip") != opts.end())
958                                 os << "\tclip\n";
959                         if (opts.find("draft") != opts.end())
960                                 os << "\tdraft\n";
961                         if (opts.find("bb") != opts.end())
962                                 os << "\tBoundingBox "
963                                    << opts["bb"] << '\n';
964                         int numberOfbbOptions = 0;
965                         if (opts.find("bbllx") != opts.end())
966                                 numberOfbbOptions++;
967                         if (opts.find("bblly") != opts.end())
968                                 numberOfbbOptions++;
969                         if (opts.find("bburx") != opts.end())
970                                 numberOfbbOptions++;
971                         if (opts.find("bbury") != opts.end())
972                                 numberOfbbOptions++;
973                         if (numberOfbbOptions == 4)
974                                 os << "\tBoundingBox "
975                                    << opts["bbllx"] << opts["bblly"]
976                                    << opts["bburx"] << opts["bbury"] << '\n';
977                         else if (numberOfbbOptions > 0)
978                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
979                         numberOfbbOptions = 0;
980                         if (opts.find("natwidth") != opts.end())
981                                 numberOfbbOptions++;
982                         if (opts.find("natheight") != opts.end())
983                                 numberOfbbOptions++;
984                         if (numberOfbbOptions == 2)
985                                 os << "\tBoundingBox 0bp 0bp "
986                                    << opts["natwidth"] << opts["natheight"] << '\n';
987                         else if (numberOfbbOptions > 0)
988                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
989                         ostringstream special;
990                         if (opts.find("hiresbb") != opts.end())
991                                 special << "hiresbb,";
992                         if (opts.find("trim") != opts.end())
993                                 special << "trim,";
994                         if (opts.find("viewport") != opts.end())
995                                 special << "viewport=" << opts["viewport"] << ',';
996                         if (opts.find("totalheight") != opts.end())
997                                 special << "totalheight=" << opts["totalheight"] << ',';
998                         if (opts.find("type") != opts.end())
999                                 special << "type=" << opts["type"] << ',';
1000                         if (opts.find("ext") != opts.end())
1001                                 special << "ext=" << opts["ext"] << ',';
1002                         if (opts.find("read") != opts.end())
1003                                 special << "read=" << opts["read"] << ',';
1004                         if (opts.find("command") != opts.end())
1005                                 special << "command=" << opts["command"] << ',';
1006                         string s_special = special.str();
1007                         if (!s_special.empty()) {
1008                                 // We had special arguments. Remove the trailing ','.
1009                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1010                         }
1011                         // TODO: Handle the unknown settings better.
1012                         // Warn about invalid options.
1013                         // Check wether some option was given twice.
1014                         end_inset(os);
1015                 }
1016
1017                 else if (t.cs() == "footnote") {
1018                         p.skip_spaces();
1019                         context.check_layout(os);
1020                         begin_inset(os, "Foot\n");
1021                         os << "status collapsed\n\n";
1022                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1023                         end_inset(os);
1024                 }
1025
1026                 else if (t.cs() == "marginpar") {
1027                         p.skip_spaces();
1028                         context.check_layout(os);
1029                         begin_inset(os, "Marginal\n");
1030                         os << "status collapsed\n\n";
1031                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1032                         end_inset(os);
1033                 }
1034
1035                 else if (t.cs() == "ensuremath") {
1036                         p.skip_spaces();
1037                         context.check_layout(os);
1038                         Context newcontext(false, context.textclass);
1039                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1040                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1041                                 os << s;
1042                         else
1043                                 handle_ert(os, "\\ensuremath{" + s + "}",
1044                                            context);
1045                 }
1046
1047                 else if (t.cs() == "hfill") {
1048                         context.check_layout(os);
1049                         os << "\n\\hfill\n";
1050                         skip_braces(p);
1051                         p.skip_spaces();
1052                 }
1053
1054                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1055                         p.skip_spaces();
1056                         skip_braces(p); // swallow this
1057                 }
1058
1059                 else if (t.cs() == "tableofcontents") {
1060                         p.skip_spaces();
1061                         context.check_layout(os);
1062                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1063                         end_inset(os);
1064                         skip_braces(p); // swallow this
1065                 }
1066
1067                 else if (t.cs() == "listoffigures") {
1068                         p.skip_spaces();
1069                         context.check_layout(os);
1070                         begin_inset(os, "FloatList figure\n");
1071                         end_inset(os);
1072                         skip_braces(p); // swallow this
1073                 }
1074
1075                 else if (t.cs() == "listoftables") {
1076                         p.skip_spaces();
1077                         context.check_layout(os);
1078                         begin_inset(os, "FloatList table\n");
1079                         end_inset(os);
1080                         skip_braces(p); // swallow this
1081                 }
1082
1083                 else if (t.cs() == "listof") {
1084                         p.skip_spaces(true);
1085                         string const name = p.get_token().asString();
1086                         if (context.textclass.floats().typeExist(name)) {
1087                                 context.check_layout(os);
1088                                 begin_inset(os, "FloatList ");
1089                                 os << name << "\n";
1090                                 end_inset(os);
1091                                 p.get_token(); // swallow second arg
1092                         } else
1093                                 handle_ert(os, "\\listof{" + name + "}", context);
1094                 }
1095
1096                 else if (t.cs() == "textrm") {
1097                         context.check_layout(os);
1098                         os << "\n\\family roman \n";
1099                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1100                         os << "\n\\family default \n";
1101                 }
1102
1103                 else if (t.cs() == "textsf") {
1104                         context.check_layout(os);
1105                         os << "\n\\family sans \n";
1106                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1107                         os << "\n\\family default \n";
1108                 }
1109
1110                 else if (t.cs() == "textsl") {
1111                         context.check_layout(os);
1112                         os << "\n\\shape slanted \n";
1113                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1114                         os << "\n\\shape default \n";
1115                 }
1116
1117                 else if (t.cs() == "texttt") {
1118                         context.check_layout(os);
1119                         os << "\n\\family typewriter \n";
1120                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1121                         os << "\n\\family default \n";
1122                 }
1123
1124                 else if (t.cs() == "textit") {
1125                         context.check_layout(os);
1126                         os << "\n\\shape italic \n";
1127                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1128                         os << "\n\\shape default \n";
1129                 }
1130
1131                 else if (t.cs() == "textsc") {
1132                         context.check_layout(os);
1133                         os << "\n\\noun on \n";
1134                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1135                         os << "\n\\noun default \n";
1136                 }
1137
1138                 else if (t.cs() == "textbf") {
1139                         context.check_layout(os);
1140                         os << "\n\\series bold \n";
1141                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1142                         os << "\n\\series default \n";
1143                 }
1144
1145                 else if (t.cs() == "underbar") {
1146                         context.check_layout(os);
1147                         os << "\n\\bar under \n";
1148                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1149                         os << "\n\\bar default \n";
1150                 }
1151
1152                 else if (t.cs() == "emph" || t.cs() == "noun") {
1153                         context.check_layout(os);
1154                         os << "\n\\" << t.cs() << " on \n";
1155                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1156                         os << "\n\\" << t.cs() << " default \n";
1157                 }
1158
1159                 else if (is_known(t.cs(), known_latex_commands)) {
1160                         context.check_layout(os);
1161                         begin_inset(os, "LatexCommand ");
1162                         os << '\\' << t.cs();
1163                         os << p.getOpt();
1164                         os << p.getOpt();
1165                         os << '{' << p.verbatim_item() << "}\n";
1166                         end_inset(os);
1167                 }
1168
1169                 else if (is_known(t.cs(), known_quotes)) {
1170                         char const ** where = is_known(t.cs(), known_quotes);
1171                         context.check_layout(os);
1172                         begin_inset(os, "Quotes ");
1173                         os << known_coded_quotes[where - known_quotes];
1174                         end_inset(os);
1175                         skip_braces(p);
1176                 }
1177
1178                 else if (is_known(t.cs(), known_sizes)) {
1179                         char const ** where = is_known(t.cs(), known_sizes);
1180                         context.check_layout(os);
1181                         os << "\n\\size " << known_coded_sizes[where - known_sizes] << "\n";
1182                         p.skip_spaces();
1183                 }
1184
1185                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1186                          || t.cs() == "LaTeX") {
1187                         context.check_layout(os);
1188                         os << t.cs();
1189                         skip_braces(p); // eat {}
1190                 }
1191
1192                 else if (t.cs() == "LaTeXe") {
1193                         context.check_layout(os);
1194                         os << "LaTeX2e";
1195                         skip_braces(p); // eat {}
1196                 }
1197
1198                 else if (t.cs() == "ldots") {
1199                         context.check_layout(os);
1200                         skip_braces(p);
1201                         os << "\\SpecialChar \\ldots{}\n";
1202                 }
1203
1204                 else if (t.cs() == "lyxarrow") {
1205                         context.check_layout(os);
1206                         os << "\\SpecialChar \\menuseparator\n";
1207                         skip_braces(p);
1208                 }
1209
1210                 else if (t.cs() == "textcompwordmark") {
1211                         context.check_layout(os);
1212                         os << "\\SpecialChar \\textcompwordmark{}\n";
1213                         skip_braces(p);
1214                 }
1215
1216                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1217                         context.check_layout(os);
1218                         os << "\\SpecialChar \\@.\n";
1219                         p.get_token();
1220                 }
1221
1222                 else if (t.cs() == "-") {
1223                         context.check_layout(os);
1224                         os << "\\SpecialChar \\-\n";
1225                 }
1226
1227                 else if (t.cs() == "textasciitilde") {
1228                         context.check_layout(os);
1229                         os << '~';
1230                         skip_braces(p);
1231                 }
1232
1233                 else if (t.cs() == "textasciicircum") {
1234                         context.check_layout(os);
1235                         os << '^';
1236                         skip_braces(p);
1237                 }
1238
1239                 else if (t.cs() == "textbackslash") {
1240                         context.check_layout(os);
1241                         os << "\n\\backslash \n";
1242                         skip_braces(p);
1243                 }
1244
1245                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1246                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1247                             || t.cs() == "%") {
1248                         context.check_layout(os);
1249                         os << t.cs();
1250                 }
1251
1252                 else if (t.cs() == "char") {
1253                         context.check_layout(os);
1254                         if (p.next_token().character() == '`') {
1255                                 p.get_token();
1256                                 if (p.next_token().cs() == "\"") {
1257                                         p.get_token();
1258                                         os << '"';
1259                                         skip_braces(p);
1260                                 } else {
1261                                         handle_ert(os, "\\char`", context);
1262                                 }
1263                         } else {
1264                                 handle_ert(os, "\\char", context);
1265                         }
1266                 }
1267
1268                 else if (t.cs() == "\"") {
1269                         context.check_layout(os);
1270                         string const name = p.verbatim_item();
1271                              if (name == "a") os << 'ä';
1272                         else if (name == "o") os << 'ö';
1273                         else if (name == "u") os << 'ü';
1274                         else if (name == "A") os << 'Ä';
1275                         else if (name == "O") os << 'Ö';
1276                         else if (name == "U") os << 'Ü';
1277                         else handle_ert(os, "\"{" + name + "}", context);
1278                 }
1279
1280                 // Problem: \= creates a tabstop inside the tabbing environment
1281                 // and else an accent. In the latter case we really would want
1282                 // \={o} instead of \= o.
1283                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1284                         handle_ert(os, t.asInput(), context);
1285
1286                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1287                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1288                         // we need the trim as the LyX parser chokes on such spaces
1289                         context.check_layout(os);
1290                         os << "\n\\i \\" << t.cs() << "{"
1291                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1292                 }
1293
1294                 else if (t.cs() == "ss") {
1295                         context.check_layout(os);
1296                         os << "ß";
1297                 }
1298
1299                 else if (t.cs() == "i" || t.cs() == "j") {
1300                         context.check_layout(os);
1301                         os << "\\" << t.cs() << ' ';
1302                 }
1303
1304                 else if (t.cs() == "\\") {
1305                         context.check_layout(os);
1306                         string const next = p.next_token().asInput();
1307                         if (next == "[")
1308                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1309                         else if (next == "*") {
1310                                 p.get_token();
1311                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1312                         }
1313                         else {
1314                                 os << "\n\\newline \n";
1315                         }
1316                 }
1317
1318                 else if (t.cs() == "input" || t.cs() == "include"
1319                          || t.cs() == "verbatiminput") {
1320                         string name = '\\' + t.cs();
1321                         if (t.cs() == "verbatiminput"
1322                             && p.next_token().asInput() == "*")
1323                                 name += p.get_token().asInput();
1324                         context.check_layout(os);
1325                         begin_inset(os, "Include ");
1326                         string filename(p.getArg('{', '}'));
1327                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1328                         if (tex2lyx(filename, lyxname)) {
1329                                 os << name << '{' << lyxname << "}\n";
1330                         } else {
1331                                 os << name << '{' << filename << "}\n";
1332                         }
1333                         os << "preview false\n";
1334                         end_inset(os);
1335                 }
1336
1337                 else if (t.cs() == "fancyhead") {
1338                         context.check_layout(os);
1339                         ostringstream ss;
1340                         ss << "\\fancyhead";
1341                         ss << p.getOpt();
1342                         ss << '{' << p.verbatim_item() << "}\n";
1343                         handle_ert(os, ss.str(), context);
1344                 }
1345
1346                 else if (t.cs() == "bibliographystyle") {
1347                         // store new bibliographystyle
1348                         bibliographystyle = p.verbatim_item();
1349                         // output new bibliographystyle.
1350                         // This is only necessary if used in some other macro than \bibliography.
1351                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1352                 }
1353
1354                 else if (t.cs() == "bibliography") {
1355                         context.check_layout(os);
1356                         begin_inset(os, "LatexCommand ");
1357                         os << "\\bibtex";
1358                         // Do we have a bibliographystyle set?
1359                         if (!bibliographystyle.empty()) {
1360                                 os << '[' << bibliographystyle << ']';
1361                         }
1362                         os << '{' << p.verbatim_item() << "}\n";
1363                         end_inset(os);
1364                 }
1365
1366                 else if (t.cs() == "parbox")
1367                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1368
1369                 else if (t.cs() == "smallskip" ||
1370                          t.cs() == "medskip" ||
1371                          t.cs() == "bigskip" ||
1372                          t.cs() == "vfill") {
1373                         context.check_layout(os);
1374                         begin_inset(os, "VSpace ");
1375                         os << t.cs();
1376                         end_inset(os);
1377                 }
1378
1379                 else if (t.cs() == "vspace") {
1380                         bool starred = false;
1381                         if (p.next_token().asInput() == "*") {
1382                                 p.get_token();
1383                                 starred = true;
1384                         }
1385                         string const length = p.verbatim_item();
1386                         string unit;
1387                         string valstring;
1388                         bool valid = splitLatexLength(length, valstring, unit);
1389                         bool known_vspace = false;
1390                         bool known_unit = false;
1391                         double value;
1392                         if (valid) {
1393                                 istringstream iss(valstring);
1394                                 iss >> value;
1395                                 if (value == 1.0) {
1396                                         if (unit == "\\smallskipamount") {
1397                                                 unit = "smallskip";
1398                                                 known_vspace = true;
1399                                         } else if (unit == "\\medskipamount") {
1400                                                 unit = "medskip";
1401                                                 known_vspace = true;
1402                                         } else if (unit == "\\bigskipamount") {
1403                                                 unit = "bigskip";
1404                                                 known_vspace = true;
1405                                         } else if (unit == "\\fill") {
1406                                                 unit = "vfill";
1407                                                 known_vspace = true;
1408                                         }
1409                                 }
1410                                 if (!known_vspace) {
1411                                         switch (unitFromString(unit)) {
1412                                         case LyXLength::SP:
1413                                         case LyXLength::PT:
1414                                         case LyXLength::BP:
1415                                         case LyXLength::DD:
1416                                         case LyXLength::MM:
1417                                         case LyXLength::PC:
1418                                         case LyXLength::CC:
1419                                         case LyXLength::CM:
1420                                         case LyXLength::IN:
1421                                         case LyXLength::EX:
1422                                         case LyXLength::EM:
1423                                         case LyXLength::MU:
1424                                                 known_unit = true;
1425                                                 break;
1426                                         default:
1427                                                 break;
1428                                         }
1429                                 }
1430                         }
1431
1432                         if (known_unit || known_vspace) {
1433                                 // Literal length or known variable
1434                                 context.check_layout(os);
1435                                 begin_inset(os, "VSpace ");
1436                                 if (known_unit)
1437                                         os << value;
1438                                 os << unit;
1439                                 if (starred)
1440                                         os << '*';
1441                                 end_inset(os);
1442                         } else {
1443                                 // LyX can't handle other length variables in Inset VSpace
1444                                 string name = t.asInput();
1445                                 if (starred)
1446                                         name += '*';
1447                                 if (valid) {
1448                                         if (value == 1.0)
1449                                                 handle_ert(os, name + '{' + unit + '}', context);
1450                                         else if (value == -1.0)
1451                                                 handle_ert(os, name + "{-" + unit + '}', context);
1452                                         else
1453                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1454                                 } else
1455                                         handle_ert(os, name + '{' + length + '}', context);
1456                         }
1457                 }
1458
1459                 else {
1460                         //cerr << "#: " << t << " mode: " << mode << endl;
1461                         // heuristic: read up to next non-nested space
1462                         /*
1463                         string s = t.asInput();
1464                         string z = p.verbatim_item();
1465                         while (p.good() && z != " " && z.size()) {
1466                                 //cerr << "read: " << z << endl;
1467                                 s += z;
1468                                 z = p.verbatim_item();
1469                         }
1470                         cerr << "found ERT: " << s << endl;
1471                         handle_ert(os, s + ' ', context);
1472                         */
1473                         string name = t.asInput();
1474                         if (p.next_token().asInput() == "*") {
1475                                 // Starred commands like \vspace*{}
1476                                 p.get_token();                          // Eat '*'
1477                                 name += '*';
1478                         }
1479                         if (! parse_command(name, p, os, outer, context))
1480                                 handle_ert(os, name, context);
1481                 }
1482
1483                 if (flags & FLAG_LEAVE) {
1484                         flags &= ~FLAG_LEAVE;
1485                         break;
1486                 }
1487         }
1488 }
1489
1490
1491 // }])