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