]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
improve tex2lyx paragraph and comment handling
[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 eat_whitespace(Parser &, ostream &, Context &, bool);
317
318
319 void output_command_layout(ostream & os, Parser & p, bool outer,
320                            Context & parent_context,
321                            LyXLayout_ptr newlayout)
322 {
323         parent_context.check_end_layout(os);
324         Context context(true, parent_context.textclass, newlayout,
325                         parent_context.layout);
326         context.check_deeper(os);
327         context.check_layout(os);
328         if (context.layout->optionalargs > 0) {
329                 eat_whitespace(p, os, context, false);
330                 if (p.next_token().character() == '[') {
331                         p.get_token(); // eat '['
332                         begin_inset(os, "OptArg\n");
333                         os << "status collapsed\n\n";
334                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
335                         end_inset(os);
336                         eat_whitespace(p, os, context, false);
337                 }
338         }
339         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
340         context.check_end_layout(os);
341         context.check_end_deeper(os);
342         // We don't need really a new paragraph, but
343         // we must make sure that the next item gets a \begin_layout.
344         parent_context.new_paragraph(os);
345 }
346
347
348 /*!
349  * Output a space if necessary.
350  * This function gets called for every whitespace token.
351  *
352  * We have three cases here:
353  * 1. A space must be suppressed. Example: The lyxcode case below
354  * 2. A space may be suppressed. Example: Spaces before "\par"
355  * 3. A space must not be suppressed. Example: A space between two words
356  *
357  * We currently handle only 1. and 3 and from 2. only the case of
358  * spaces before newlines as a side effect.
359  *
360  * 2. could be used to suppress as many spaces as possible. This has two effects:
361  * - Reimporting LyX generated LaTeX files changes almost no whitespace
362  * - Superflous whitespace from non LyX generated LaTeX files is removed.
363  * The drawback is that the logic inside the function becomes
364  * complicated, and that is the reason why it is not implemented.
365  */
366 void check_space(Parser const & p, ostream & os, Context & context)
367 {
368         Token const next = p.next_token();
369         Token const curr = p.curr_token();
370         // A space before a single newline and vice versa must be ignored
371         // LyX emits a newline before \end{lyxcode}.
372         // This newline must be ignored,
373         // otherwise LyX will add an additional protected space.
374         if (next.cat() == catSpace ||
375             next.cat() == catNewline ||
376             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
377                 return;
378         }
379         context.check_layout(os);
380         os << ' ';
381 }
382
383
384 /*!
385  * Check whether \p command is a known command. If yes,
386  * handle the command with all arguments.
387  * \return true if the command was parsed, false otherwise.
388  */
389 bool parse_command(string const & command, Parser & p, ostream & os,
390                    bool outer, Context & context)
391 {
392         if (known_commands.find(command) != known_commands.end()) {
393                 vector<ArgumentType> const & template_arguments = known_commands[command];
394                 string ert = command;
395                 size_t no_arguments = template_arguments.size();
396                 for (size_t i = 0; i < no_arguments; ++i) {
397                         switch (template_arguments[i]) {
398                         case required:
399                                 // This argument contains regular LaTeX
400                                 handle_ert(os, ert + '{', context);
401                                 parse_text(p, os, FLAG_ITEM, outer, context);
402                                 ert = "}";
403                                 break;
404                         case verbatim:
405                                 // This argument may contain special characters
406                                 ert += '{' + p.verbatim_item() + '}';
407                                 break;
408                         case optional:
409                                 ert += p.getOpt();
410                                 break;
411                         }
412                 }
413                 handle_ert(os, ert, context);
414                 return true;
415         }
416         return false;
417 }
418
419
420 /// Parses a minipage or parbox
421 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
422                Context & parent_context, bool use_parbox)
423 {
424         string position;
425         string inner_pos;
426         string height_value = "0";
427         string height_unit = "pt";
428         string height_special = "none";
429         string latex_height;
430         if (p.next_token().asInput() == "[") {
431                 position = p.getArg('[', ']');
432                 if (position != "t" && position != "c" && position != "b") {
433                         position = "c";
434                         cerr << "invalid position for minipage/parbox" << endl;
435                 }
436                 if (p.next_token().asInput() == "[") {
437                         latex_height = p.getArg('[', ']');
438                         translate_box_len(latex_height, height_value, height_unit, height_special);
439
440                         if (p.next_token().asInput() == "[") {
441                                 inner_pos = p.getArg('[', ']');
442                                 if (inner_pos != "c" && inner_pos != "t" &&
443                                     inner_pos != "b" && inner_pos != "s") {
444                                         inner_pos = position;
445                                         cerr << "invalid inner_pos for minipage/parbox"
446                                              << endl;
447                                 }
448                         }
449                 }
450         }
451         string width_value;
452         string width_unit;
453         string const latex_width = p.verbatim_item();
454         translate_len(latex_width, width_value, width_unit);
455         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
456                 // LyX can't handle length variables
457                 ostringstream ss;
458                 if (use_parbox)
459                         ss << "\\parbox";
460                 else
461                         ss << "\\begin{minipage}";
462                 if (!position.empty())
463                         ss << '[' << position << ']';
464                 if (!latex_height.empty())
465                         ss << '[' << latex_height << ']';
466                 if (!inner_pos.empty())
467                         ss << '[' << inner_pos << ']';
468                 ss << "{" << latex_width << "}";
469                 if (use_parbox)
470                         ss << '{';
471                 handle_ert(os, ss.str(), parent_context);
472                 parent_context.new_paragraph(os);
473                 parse_text_in_inset(p, os, flags, outer, parent_context);
474                 if (use_parbox)
475                         handle_ert(os, "}", parent_context);
476                 else
477                         handle_ert(os, "\\end{minipage}", parent_context);
478         } else {
479                 // LyX does not like empty positions, so we have
480                 // to set them to the LaTeX default values here.
481                 if (position.empty())
482                         position = "c";
483                 if (inner_pos.empty())
484                         inner_pos = position;
485                 parent_context.check_layout(os);
486                 begin_inset(os, "Box Frameless\n");
487                 os << "position \"" << position << "\"\n";
488                 os << "hor_pos \"c\"\n";
489                 os << "has_inner_box 1\n";
490                 os << "inner_pos \"" << inner_pos << "\"\n";
491                 os << "use_parbox " << use_parbox << "\n";
492                 os << "width \"" << width_value << width_unit << "\"\n";
493                 os << "special \"none\"\n";
494                 os << "height \"" << height_value << height_unit << "\"\n";
495                 os << "height_special \"" << height_special << "\"\n";
496                 os << "status open\n\n";
497                 parse_text_in_inset(p, os, flags, outer, parent_context);
498                 end_inset(os);
499 #ifdef PRESERVE_LAYOUT
500                 // lyx puts a % after the end of the minipage
501                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
502                         // new paragraph
503                         //handle_comment(os, "%dummy", parent_context);
504                         p.get_token();
505                         p.skip_spaces();
506                         parent_context.new_paragraph(os);
507                 }
508                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
509                         //handle_comment(os, "%dummy", parent_context);
510                         p.get_token();
511                         p.skip_spaces();
512                         // We add a protected space if something real follows
513                         if (p.good() && p.next_token().cat() != catComment) {
514                                 os << "\\InsetSpace ~\n";
515                         }
516                 }
517 #endif
518         }
519 }
520
521
522 void parse_environment(Parser & p, ostream & os, bool outer,
523                        Context & parent_context)
524 {
525         LyXLayout_ptr newlayout;
526         string const name = p.getArg('{', '}');
527         const bool is_starred = suffixIs(name, '*');
528         string const unstarred_name = rtrim(name, "*");
529         eat_whitespace(p, os, parent_context, false);
530         active_environments.push_back(name);
531
532         if (is_math_env(name)) {
533                 parent_context.check_layout(os);
534                 begin_inset(os, "Formula ");
535                 os << "\\begin{" << name << "}";
536                 parse_math(p, os, FLAG_END, MATH_MODE);
537                 os << "\\end{" << name << "}";
538                 end_inset(os);
539         }
540
541         else if (name == "tabular") {
542                 parent_context.check_layout(os);
543                 begin_inset(os, "Tabular ");
544                 handle_tabular(p, os, parent_context);
545                 end_inset(os);
546         }
547
548         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
549                 parent_context.check_layout(os);
550                 begin_inset(os, "Float " + unstarred_name + "\n");
551                 if (p.next_token().asInput() == "[") {
552                         os << "placement " << p.getArg('[', ']') << '\n';
553                 }
554                 os << "wide " << tostr(is_starred)
555                    << "\nstatus open\n\n";
556                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
557                 end_inset(os);
558                 // We don't need really a new paragraph, but
559                 // we must make sure that the next item gets a \begin_layout.
560                 parent_context.new_paragraph(os);
561         }
562
563         else if (name == "minipage")
564                 parse_box(p, os, FLAG_END, outer, parent_context, false);
565
566         // Alignment settings
567         else if (name == "center" || name == "flushleft" || name == "flushright" ||
568                  name == "centering" || name == "raggedright" || name == "raggedleft") {
569                 // We must begin a new paragraph if not already done
570                 if (! parent_context.atParagraphStart()) {
571                         parent_context.check_end_layout(os);
572                         parent_context.new_paragraph(os);
573                 }
574                 if (name == "flushleft" || name == "raggedright")
575                         parent_context.add_extra_stuff("\\align left ");
576                 else if (name == "flushright" || name == "raggedleft")
577                         parent_context.add_extra_stuff("\\align right ");
578                 else
579                         parent_context.add_extra_stuff("\\align center ");
580                 parse_text(p, os, FLAG_END, outer, parent_context);
581                 // Just in case the environment is empty ..
582                 parent_context.extra_stuff.erase();
583                 // We must begin a new paragraph to reset the alignment
584                 parent_context.new_paragraph(os);
585         }
586
587         // The single '=' is meant here.
588         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
589                    newlayout->isEnvironment()) {
590                 Context context(true, parent_context.textclass, newlayout,
591                                 parent_context.layout);
592                 parent_context.check_end_layout(os);
593                 switch (context.layout->latextype) {
594                 case  LATEX_LIST_ENVIRONMENT:
595                         context.extra_stuff = "\\labelwidthstring "
596                                 + p.verbatim_item() + '\n';
597                         p.skip_spaces();
598                         break;
599                 case  LATEX_BIB_ENVIRONMENT:
600                         p.verbatim_item(); // swallow next arg
601                         p.skip_spaces();
602                         break;
603                 default:
604                         break;
605                 }
606                 context.check_deeper(os);
607                 parse_text(p, os, FLAG_END, outer, context);
608                 context.check_end_layout(os);
609                 context.check_end_deeper(os);
610                 parent_context.new_paragraph(os);
611         }
612
613         else if (name == "appendix") {
614                 // This is no good latex style, but it works and is used in some documents...
615                 parent_context.check_end_layout(os);
616                 Context context(true, parent_context.textclass, parent_context.layout,
617                                 parent_context.layout);
618                 context.check_layout(os);
619                 os << "\\start_of_appendix\n";
620                 parse_text(p, os, FLAG_END, outer, context);
621                 context.check_end_layout(os);
622         }
623
624         else if (name == "comment") {
625                 parent_context.check_layout(os);
626                 begin_inset(os, "Note Comment\n");
627                 os << "status open\n";
628                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
629                 end_inset(os);
630         }
631
632         else if (name == "lyxgreyedout") {
633                 parent_context.check_layout(os);
634                 begin_inset(os, "Note Greyedout\n");
635                 os << "status open\n";
636                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
637                 end_inset(os);
638         }
639
640         else if (name == "tabbing") {
641                 // We need to remember that we have to handle '\=' specially
642                 handle_ert(os, "\\begin{" + name + "}", parent_context);
643                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
644                 handle_ert(os, "\\end{" + name + "}", parent_context);
645         }
646
647         else {
648                 handle_ert(os, "\\begin{" + name + "}", parent_context);
649                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
650                 handle_ert(os, "\\end{" + name + "}", parent_context);
651         }
652
653         active_environments.pop_back();
654         if (name != "math")
655                 p.skip_spaces();
656 }
657
658 /// parses a comment and outputs it to \p os.
659 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
660 {
661         BOOST_ASSERT(t.cat() == catComment);
662         context.check_layout(os);
663         if (!t.cs().empty()) {
664                 handle_comment(os, '%' + t.cs(), context);
665                 if (p.next_token().cat() == catNewline) {
666                         // A newline after a comment line starts a new
667                         // paragraph
668                         if(!context.atParagraphStart()) {
669                                 // Only start a new paragraph if not already
670                                 // done (we might get called recursively)
671                                 context.new_paragraph(os);
672                         }
673                         eat_whitespace(p, os, context, true);
674                 }
675         } else {
676                 // "%\n" combination
677                 p.skip_spaces();
678         }
679 }
680
681
682 /*!
683  * Reads spaces and comments until the first non-space, non-comment token.
684  * New paragraphs (double newlines or \\par) are handled like simple spaces
685  * if \p eatParagraph is true.
686  * Spaces are skipped, but comments are written to \p os.
687  */
688 void eat_whitespace(Parser & p, ostream & os, Context & context,
689                     bool eatParagraph)
690 {
691         while (p.good()) {
692                 Token const & t = p.get_token();
693                 if (t.cat() == catComment)
694                         parse_comment(p, os, t, context);
695                 else if ((! eatParagraph && p.isParagraph()) ||
696                          (t.cat() != catSpace && t.cat() != catNewline)) {
697                         p.putback();
698                         return;
699                 }
700         }
701 }
702
703 } // anonymous namespace
704
705
706 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
707                 Context & context)
708 {
709         LyXLayout_ptr newlayout;
710         // Store the latest bibliographystyle (needed for bibtex inset)
711         string bibliographystyle;
712         while (p.good()) {
713                 Token const & t = p.get_token();
714
715 #ifdef FILEDEBUG
716                 cerr << "t: " << t << " flags: " << flags << "\n";
717 #endif
718
719                 if (flags & FLAG_ITEM) {
720                         if (t.cat() == catSpace)
721                                 continue;
722
723                         flags &= ~FLAG_ITEM;
724                         if (t.cat() == catBegin) {
725                                 // skip the brace and collect everything to the next matching
726                                 // closing brace
727                                 flags |= FLAG_BRACE_LAST;
728                                 continue;
729                         }
730
731                         // handle only this single token, leave the loop if done
732                         flags |= FLAG_LEAVE;
733                 }
734
735                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
736                         return;
737
738                 //
739                 // cat codes
740                 //
741                 if (t.cat() == catMath) {
742                         // we are inside some text mode thingy, so opening new math is allowed
743                         context.check_layout(os);
744                         begin_inset(os, "Formula ");
745                         Token const & n = p.get_token();
746                         if (n.cat() == catMath && outer) {
747                                 // TeX's $$...$$ syntax for displayed math
748                                 os << "\\[";
749                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
750                                 os << "\\]";
751                                 p.get_token(); // skip the second '$' token
752                         } else {
753                                 // simple $...$  stuff
754                                 p.putback();
755                                 os << '$';
756                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
757                                 os << '$';
758                         }
759                         end_inset(os);
760                 }
761
762                 else if (t.cat() == catSuper || t.cat() == catSub)
763                         cerr << "catcode " << t << " illegal in text mode\n";
764
765                 // Basic support for english quotes. This should be
766                 // extended to other quotes, but is not so easy (a
767                 // left english quote is the same as a right german
768                 // quote...)
769                 else if (t.asInput() == "`"
770                          && p.next_token().asInput() == "`") {
771                         context.check_layout(os);
772                         begin_inset(os, "Quotes ");
773                         os << "eld";
774                         end_inset(os);
775                         p.get_token();
776                         skip_braces(p);
777                 }
778                 else if (t.asInput() == "'"
779                          && p.next_token().asInput() == "'") {
780                         context.check_layout(os);
781                         begin_inset(os, "Quotes ");
782                         os << "erd";
783                         end_inset(os);
784                         p.get_token();
785                         skip_braces(p);
786                 }
787
788                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
789                         check_space(p, os, context);
790
791                 else if (t.cat() == catLetter ||
792                                t.cat() == catOther ||
793                                t.cat() == catAlign ||
794                                t.cat() == catParameter) {
795                         context.check_layout(os);
796                         os << t.character();
797                 }
798
799                 else if (p.isParagraph()) {
800                         context.new_paragraph(os);
801                         eat_whitespace(p, os, context, true);
802                 }
803
804                 else if (t.cat() == catActive) {
805                         context.check_layout(os);
806                         if (t.character() == '~') {
807                                 if (context.layout->free_spacing)
808                                         os << ' ';
809                                 else
810                                         os << "\\InsetSpace ~\n";
811                         } else
812                                 os << t.character();
813                 }
814
815                 else if (t.cat() == catBegin) {
816                         // special handling of size changes
817                         context.check_layout(os);
818                         bool const is_size = is_known(p.next_token().cs(), known_sizes);
819                         Token const prev = p.prev_token();
820                         string const s = parse_text(p, FLAG_BRACE_LAST, outer, context);
821                         if (s.empty() && (p.next_token().character() == '`' ||
822                                           (prev.character() == '-' && p.next_token().character())))
823                                 ; // ignore it in {}`` or -{}-
824                         else if (is_size || s == "[" || s == "]" || s == "*")
825                                 os << s;
826                         else {
827                                 handle_ert(os, "{", context, false);
828                                 // s will end the current layout and begin a new one if necessary
829                                 os << s;
830                                 handle_ert(os, "}", context);
831                         }
832                 }
833
834                 else if (t.cat() == catEnd) {
835                         if (flags & FLAG_BRACE_LAST) {
836                                 return;
837                         }
838                         cerr << "stray '}' in text\n";
839                         handle_ert(os, "}", context);
840                 }
841
842                 else if (t.cat() == catComment)
843                         parse_comment(p, os, t, context);
844
845                 //
846                 // control sequences
847                 //
848
849                 else if (t.cs() == "(") {
850                         context.check_layout(os);
851                         begin_inset(os, "Formula");
852                         os << " \\(";
853                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
854                         os << "\\)";
855                         end_inset(os);
856                 }
857
858                 else if (t.cs() == "[") {
859                         context.check_layout(os);
860                         begin_inset(os, "Formula");
861                         os << " \\[";
862                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
863                         os << "\\]";
864                         end_inset(os);
865                 }
866
867                 else if (t.cs() == "begin")
868                         parse_environment(p, os, outer, context);
869
870                 else if (t.cs() == "end") {
871                         if (flags & FLAG_END) {
872                                 // eat environment name
873                                 string const name = p.getArg('{', '}');
874                                 if (name != active_environment())
875                                         cerr << "\\end{" + name + "} does not match \\begin{"
876                                                 + active_environment() + "}\n";
877                                 return;
878                         }
879                         p.error("found 'end' unexpectedly");
880                 }
881
882                 else if (t.cs() == "item") {
883                         p.skip_spaces();
884                         string s;
885                         bool optarg = false;
886                         if (p.next_token().character() == '[') {
887                                 p.get_token(); // eat '['
888                                 Context newcontext(false, context.textclass);
889                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
890                                 optarg = true;
891                         }
892                         context.set_item();
893                         context.check_layout(os);
894                         if (optarg) {
895                                 if (context.layout->labeltype != LABEL_MANUAL) {
896                                         // lyx does not support \item[\mybullet] in itemize environments
897                                         handle_ert(os, "[", context);
898                                         os << s;
899                                         handle_ert(os, "]", context);
900                                 } else if (!s.empty()) {
901                                         // The space is needed to separate the item from the rest of the sentence.
902                                         os << s << ' ';
903                                         eat_whitespace(p, os, context, false);
904                                 }
905                         }
906                 }
907
908                 else if (t.cs() == "bibitem") {
909                         context.set_item();
910                         context.check_layout(os);
911                         os << "\\bibitem ";
912                         os << p.getOpt();
913                         os << '{' << p.verbatim_item() << '}' << "\n";
914                 }
915
916                 else if (t.cs() == "def") {
917                         context.check_layout(os);
918                         eat_whitespace(p, os, context, false);
919                         string name = p.get_token().cs();
920                         while (p.next_token().cat() != catBegin)
921                                 name += p.get_token().asString();
922                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
923                 }
924
925                 else if (t.cs() == "noindent") {
926                         p.skip_spaces();
927                         context.add_extra_stuff("\\noindent ");
928                 }
929
930                 else if (t.cs() == "appendix") {
931                         p.skip_spaces();
932                         context.add_extra_stuff("\\start_of_appendix ");
933                 }
934
935                 // Must attempt to parse "Section*" before "Section".
936                 else if ((p.next_token().asInput() == "*") &&
937                          // The single '=' is meant here.
938                          (newlayout = findLayout(context.textclass,
939                                                  t.cs() + '*')).get() &&
940                          newlayout->isCommand()) {
941                         p.get_token();
942                         output_command_layout(os, p, outer, context, newlayout);
943                         p.skip_spaces();
944                 }
945
946                 // The single '=' is meant here.
947                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
948                          newlayout->isCommand()) {
949                         output_command_layout(os, p, outer, context, newlayout);
950                         p.skip_spaces();
951                 }
952
953                 else if (t.cs() == "includegraphics") {
954                         map<string, string> opts = split_map(p.getArg('[', ']'));
955                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
956
957                         context.check_layout(os);
958                         begin_inset(os, "Graphics ");
959                         os << "\n\tfilename " << name << '\n';
960                         if (opts.find("width") != opts.end())
961                                 os << "\twidth "
962                                    << translate_len(opts["width"]) << '\n';
963                         if (opts.find("height") != opts.end())
964                                 os << "\theight "
965                                    << translate_len(opts["height"]) << '\n';
966                         if (opts.find("scale") != opts.end()) {
967                                 istringstream iss(opts["scale"]);
968                                 double val;
969                                 iss >> val;
970                                 val = val*100;
971                                 os << "\tscale " << val << '\n';
972                         }
973                         if (opts.find("angle") != opts.end())
974                                 os << "\trotateAngle "
975                                    << opts["angle"] << '\n';
976                         if (opts.find("origin") != opts.end()) {
977                                 ostringstream ss;
978                                 string const opt = opts["origin"];
979                                 if (opt.find('l') != string::npos) ss << "left";
980                                 if (opt.find('r') != string::npos) ss << "right";
981                                 if (opt.find('c') != string::npos) ss << "center";
982                                 if (opt.find('t') != string::npos) ss << "Top";
983                                 if (opt.find('b') != string::npos) ss << "Bottom";
984                                 if (opt.find('B') != string::npos) ss << "Baseline";
985                                 if (!ss.str().empty())
986                                         os << "\trotateOrigin " << ss.str() << '\n';
987                                 else
988                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
989                         }
990                         if (opts.find("keepaspectratio") != opts.end())
991                                 os << "\tkeepAspectRatio\n";
992                         if (opts.find("clip") != opts.end())
993                                 os << "\tclip\n";
994                         if (opts.find("draft") != opts.end())
995                                 os << "\tdraft\n";
996                         if (opts.find("bb") != opts.end())
997                                 os << "\tBoundingBox "
998                                    << opts["bb"] << '\n';
999                         int numberOfbbOptions = 0;
1000                         if (opts.find("bbllx") != opts.end())
1001                                 numberOfbbOptions++;
1002                         if (opts.find("bblly") != opts.end())
1003                                 numberOfbbOptions++;
1004                         if (opts.find("bburx") != opts.end())
1005                                 numberOfbbOptions++;
1006                         if (opts.find("bbury") != opts.end())
1007                                 numberOfbbOptions++;
1008                         if (numberOfbbOptions == 4)
1009                                 os << "\tBoundingBox "
1010                                    << opts["bbllx"] << opts["bblly"]
1011                                    << opts["bburx"] << opts["bbury"] << '\n';
1012                         else if (numberOfbbOptions > 0)
1013                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1014                         numberOfbbOptions = 0;
1015                         if (opts.find("natwidth") != opts.end())
1016                                 numberOfbbOptions++;
1017                         if (opts.find("natheight") != opts.end())
1018                                 numberOfbbOptions++;
1019                         if (numberOfbbOptions == 2)
1020                                 os << "\tBoundingBox 0bp 0bp "
1021                                    << opts["natwidth"] << opts["natheight"] << '\n';
1022                         else if (numberOfbbOptions > 0)
1023                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1024                         ostringstream special;
1025                         if (opts.find("hiresbb") != opts.end())
1026                                 special << "hiresbb,";
1027                         if (opts.find("trim") != opts.end())
1028                                 special << "trim,";
1029                         if (opts.find("viewport") != opts.end())
1030                                 special << "viewport=" << opts["viewport"] << ',';
1031                         if (opts.find("totalheight") != opts.end())
1032                                 special << "totalheight=" << opts["totalheight"] << ',';
1033                         if (opts.find("type") != opts.end())
1034                                 special << "type=" << opts["type"] << ',';
1035                         if (opts.find("ext") != opts.end())
1036                                 special << "ext=" << opts["ext"] << ',';
1037                         if (opts.find("read") != opts.end())
1038                                 special << "read=" << opts["read"] << ',';
1039                         if (opts.find("command") != opts.end())
1040                                 special << "command=" << opts["command"] << ',';
1041                         string s_special = special.str();
1042                         if (!s_special.empty()) {
1043                                 // We had special arguments. Remove the trailing ','.
1044                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1045                         }
1046                         // TODO: Handle the unknown settings better.
1047                         // Warn about invalid options.
1048                         // Check whether some option was given twice.
1049                         end_inset(os);
1050                 }
1051
1052                 else if (t.cs() == "footnote") {
1053                         p.skip_spaces();
1054                         context.check_layout(os);
1055                         begin_inset(os, "Foot\n");
1056                         os << "status collapsed\n\n";
1057                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1058                         end_inset(os);
1059                 }
1060
1061                 else if (t.cs() == "marginpar") {
1062                         p.skip_spaces();
1063                         context.check_layout(os);
1064                         begin_inset(os, "Marginal\n");
1065                         os << "status collapsed\n\n";
1066                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1067                         end_inset(os);
1068                 }
1069
1070                 else if (t.cs() == "ensuremath") {
1071                         p.skip_spaces();
1072                         context.check_layout(os);
1073                         Context newcontext(false, context.textclass);
1074                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1075                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1076                                 os << s;
1077                         else
1078                                 handle_ert(os, "\\ensuremath{" + s + "}",
1079                                            context);
1080                 }
1081
1082                 else if (t.cs() == "hfill") {
1083                         context.check_layout(os);
1084                         os << "\n\\hfill \n";
1085                         skip_braces(p);
1086                         p.skip_spaces();
1087                 }
1088
1089                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1090                         p.skip_spaces();
1091                         skip_braces(p); // swallow this
1092                 }
1093
1094                 else if (t.cs() == "tableofcontents") {
1095                         p.skip_spaces();
1096                         context.check_layout(os);
1097                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1098                         end_inset(os);
1099                         skip_braces(p); // swallow this
1100                 }
1101
1102                 else if (t.cs() == "listoffigures") {
1103                         p.skip_spaces();
1104                         context.check_layout(os);
1105                         begin_inset(os, "FloatList figure\n");
1106                         end_inset(os);
1107                         skip_braces(p); // swallow this
1108                 }
1109
1110                 else if (t.cs() == "listoftables") {
1111                         p.skip_spaces();
1112                         context.check_layout(os);
1113                         begin_inset(os, "FloatList table\n");
1114                         end_inset(os);
1115                         skip_braces(p); // swallow this
1116                 }
1117
1118                 else if (t.cs() == "listof") {
1119                         p.skip_spaces(true);
1120                         string const name = p.get_token().asString();
1121                         if (context.textclass.floats().typeExist(name)) {
1122                                 context.check_layout(os);
1123                                 begin_inset(os, "FloatList ");
1124                                 os << name << "\n";
1125                                 end_inset(os);
1126                                 p.get_token(); // swallow second arg
1127                         } else
1128                                 handle_ert(os, "\\listof{" + name + "}", context);
1129                 }
1130
1131                 else if (t.cs() == "textrm") {
1132                         context.check_layout(os);
1133                         os << "\n\\family roman \n";
1134                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1135                         os << "\n\\family default \n";
1136                 }
1137
1138                 else if (t.cs() == "textsf") {
1139                         context.check_layout(os);
1140                         os << "\n\\family sans \n";
1141                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1142                         os << "\n\\family default \n";
1143                 }
1144
1145                 else if (t.cs() == "textsl") {
1146                         context.check_layout(os);
1147                         os << "\n\\shape slanted \n";
1148                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1149                         os << "\n\\shape default \n";
1150                 }
1151
1152                 else if (t.cs() == "texttt") {
1153                         context.check_layout(os);
1154                         os << "\n\\family typewriter \n";
1155                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1156                         os << "\n\\family default \n";
1157                 }
1158
1159                 else if (t.cs() == "textit") {
1160                         context.check_layout(os);
1161                         os << "\n\\shape italic \n";
1162                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1163                         os << "\n\\shape default \n";
1164                 }
1165
1166                 else if (t.cs() == "textsc") {
1167                         context.check_layout(os);
1168                         os << "\n\\noun on \n";
1169                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1170                         os << "\n\\noun default \n";
1171                 }
1172
1173                 else if (t.cs() == "textbf") {
1174                         context.check_layout(os);
1175                         os << "\n\\series bold \n";
1176                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1177                         os << "\n\\series default \n";
1178                 }
1179
1180                 else if (t.cs() == "underbar") {
1181                         context.check_layout(os);
1182                         os << "\n\\bar under \n";
1183                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1184                         os << "\n\\bar default \n";
1185                 }
1186
1187                 else if (t.cs() == "emph" || t.cs() == "noun") {
1188                         context.check_layout(os);
1189                         os << "\n\\" << t.cs() << " on \n";
1190                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1191                         os << "\n\\" << t.cs() << " default \n";
1192                 }
1193
1194                 else if (is_known(t.cs(), known_latex_commands)) {
1195                         context.check_layout(os);
1196                         begin_inset(os, "LatexCommand ");
1197                         os << '\\' << t.cs();
1198                         os << p.getOpt();
1199                         os << p.getOpt();
1200                         os << '{' << p.verbatim_item() << "}\n";
1201                         end_inset(os);
1202                 }
1203
1204                 else if (is_known(t.cs(), known_quotes)) {
1205                         char const ** where = is_known(t.cs(), known_quotes);
1206                         context.check_layout(os);
1207                         begin_inset(os, "Quotes ");
1208                         os << known_coded_quotes[where - known_quotes];
1209                         end_inset(os);
1210                         // LyX adds {} after the quote, so we have to eat
1211                         // spaces here if there are any before a possible
1212                         // {} pair.
1213                         eat_whitespace(p, os, context, false);
1214                         skip_braces(p);
1215                 }
1216
1217                 else if (is_known(t.cs(), known_sizes)) {
1218                         char const ** where = is_known(t.cs(), known_sizes);
1219                         context.check_layout(os);
1220                         os << "\n\\size " << known_coded_sizes[where - known_sizes] << "\n";
1221                         eat_whitespace(p, os, context, false);
1222                 }
1223
1224                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1225                          || t.cs() == "LaTeX") {
1226                         context.check_layout(os);
1227                         os << t.cs();
1228                         skip_braces(p); // eat {}
1229                 }
1230
1231                 else if (t.cs() == "LaTeXe") {
1232                         context.check_layout(os);
1233                         os << "LaTeX2e";
1234                         skip_braces(p); // eat {}
1235                 }
1236
1237                 else if (t.cs() == "ldots") {
1238                         context.check_layout(os);
1239                         skip_braces(p);
1240                         os << "\\SpecialChar \\ldots{}\n";
1241                 }
1242
1243                 else if (t.cs() == "lyxarrow") {
1244                         context.check_layout(os);
1245                         os << "\\SpecialChar \\menuseparator\n";
1246                         skip_braces(p);
1247                 }
1248
1249                 else if (t.cs() == "textcompwordmark") {
1250                         context.check_layout(os);
1251                         os << "\\SpecialChar \\textcompwordmark{}\n";
1252                         skip_braces(p);
1253                 }
1254
1255                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1256                         context.check_layout(os);
1257                         os << "\\SpecialChar \\@.\n";
1258                         p.get_token();
1259                 }
1260
1261                 else if (t.cs() == "-") {
1262                         context.check_layout(os);
1263                         os << "\\SpecialChar \\-\n";
1264                 }
1265
1266                 else if (t.cs() == "textasciitilde") {
1267                         context.check_layout(os);
1268                         os << '~';
1269                         skip_braces(p);
1270                 }
1271
1272                 else if (t.cs() == "textasciicircum") {
1273                         context.check_layout(os);
1274                         os << '^';
1275                         skip_braces(p);
1276                 }
1277
1278                 else if (t.cs() == "textbackslash") {
1279                         context.check_layout(os);
1280                         os << "\n\\backslash \n";
1281                         skip_braces(p);
1282                 }
1283
1284                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1285                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1286                             || t.cs() == "%") {
1287                         context.check_layout(os);
1288                         os << t.cs();
1289                 }
1290
1291                 else if (t.cs() == "char") {
1292                         context.check_layout(os);
1293                         if (p.next_token().character() == '`') {
1294                                 p.get_token();
1295                                 if (p.next_token().cs() == "\"") {
1296                                         p.get_token();
1297                                         os << '"';
1298                                         skip_braces(p);
1299                                 } else {
1300                                         handle_ert(os, "\\char`", context);
1301                                 }
1302                         } else {
1303                                 handle_ert(os, "\\char", context);
1304                         }
1305                 }
1306
1307                 else if (t.cs() == "\"") {
1308                         context.check_layout(os);
1309                         string const name = p.verbatim_item();
1310                              if (name == "a") os << 'ä';
1311                         else if (name == "o") os << 'ö';
1312                         else if (name == "u") os << 'ü';
1313                         else if (name == "A") os << 'Ä';
1314                         else if (name == "O") os << 'Ö';
1315                         else if (name == "U") os << 'Ü';
1316                         else handle_ert(os, "\"{" + name + "}", context);
1317                 }
1318
1319                 // Problem: \= creates a tabstop inside the tabbing environment
1320                 // and else an accent. In the latter case we really would want
1321                 // \={o} instead of \= o.
1322                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1323                         handle_ert(os, t.asInput(), context);
1324
1325                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1326                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1327                         // we need the trim as the LyX parser chokes on such spaces
1328                         context.check_layout(os);
1329                         os << "\n\\i \\" << t.cs() << "{"
1330                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1331                 }
1332
1333                 else if (t.cs() == "ss") {
1334                         context.check_layout(os);
1335                         os << "ß";
1336                 }
1337
1338                 else if (t.cs() == "i" || t.cs() == "j") {
1339                         context.check_layout(os);
1340                         os << "\\" << t.cs() << ' ';
1341                 }
1342
1343                 else if (t.cs() == "\\") {
1344                         context.check_layout(os);
1345                         string const next = p.next_token().asInput();
1346                         if (next == "[")
1347                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1348                         else if (next == "*") {
1349                                 p.get_token();
1350                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1351                         }
1352                         else {
1353                                 os << "\n\\newline \n";
1354                         }
1355                 }
1356
1357                 else if (t.cs() == "input" || t.cs() == "include"
1358                          || t.cs() == "verbatiminput") {
1359                         string name = '\\' + t.cs();
1360                         if (t.cs() == "verbatiminput"
1361                             && p.next_token().asInput() == "*")
1362                                 name += p.get_token().asInput();
1363                         context.check_layout(os);
1364                         begin_inset(os, "Include ");
1365                         string filename(p.getArg('{', '}'));
1366                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1367                         if (tex2lyx(filename, lyxname)) {
1368                                 os << name << '{' << lyxname << "}\n";
1369                         } else {
1370                                 os << name << '{' << filename << "}\n";
1371                         }
1372                         os << "preview false\n";
1373                         end_inset(os);
1374                 }
1375
1376                 else if (t.cs() == "fancyhead") {
1377                         context.check_layout(os);
1378                         ostringstream ss;
1379                         ss << "\\fancyhead";
1380                         ss << p.getOpt();
1381                         ss << '{' << p.verbatim_item() << "}\n";
1382                         handle_ert(os, ss.str(), context);
1383                 }
1384
1385                 else if (t.cs() == "bibliographystyle") {
1386                         // store new bibliographystyle
1387                         bibliographystyle = p.verbatim_item();
1388                         // output new bibliographystyle.
1389                         // This is only necessary if used in some other macro than \bibliography.
1390                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1391                 }
1392
1393                 else if (t.cs() == "bibliography") {
1394                         context.check_layout(os);
1395                         begin_inset(os, "LatexCommand ");
1396                         os << "\\bibtex";
1397                         // Do we have a bibliographystyle set?
1398                         if (!bibliographystyle.empty()) {
1399                                 os << '[' << bibliographystyle << ']';
1400                         }
1401                         os << '{' << p.verbatim_item() << "}\n";
1402                         end_inset(os);
1403                 }
1404
1405                 else if (t.cs() == "parbox")
1406                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1407
1408                 else if (t.cs() == "smallskip" ||
1409                          t.cs() == "medskip" ||
1410                          t.cs() == "bigskip" ||
1411                          t.cs() == "vfill") {
1412                         context.check_layout(os);
1413                         begin_inset(os, "VSpace ");
1414                         os << t.cs();
1415                         end_inset(os);
1416                         skip_braces(p);
1417                 }
1418
1419                 else if (t.cs() == "vspace") {
1420                         bool starred = false;
1421                         if (p.next_token().asInput() == "*") {
1422                                 p.get_token();
1423                                 starred = true;
1424                         }
1425                         string const length = p.verbatim_item();
1426                         string unit;
1427                         string valstring;
1428                         bool valid = splitLatexLength(length, valstring, unit);
1429                         bool known_vspace = false;
1430                         bool known_unit = false;
1431                         double value;
1432                         if (valid) {
1433                                 istringstream iss(valstring);
1434                                 iss >> value;
1435                                 if (value == 1.0) {
1436                                         if (unit == "\\smallskipamount") {
1437                                                 unit = "smallskip";
1438                                                 known_vspace = true;
1439                                         } else if (unit == "\\medskipamount") {
1440                                                 unit = "medskip";
1441                                                 known_vspace = true;
1442                                         } else if (unit == "\\bigskipamount") {
1443                                                 unit = "bigskip";
1444                                                 known_vspace = true;
1445                                         } else if (unit == "\\fill") {
1446                                                 unit = "vfill";
1447                                                 known_vspace = true;
1448                                         }
1449                                 }
1450                                 if (!known_vspace) {
1451                                         switch (unitFromString(unit)) {
1452                                         case LyXLength::SP:
1453                                         case LyXLength::PT:
1454                                         case LyXLength::BP:
1455                                         case LyXLength::DD:
1456                                         case LyXLength::MM:
1457                                         case LyXLength::PC:
1458                                         case LyXLength::CC:
1459                                         case LyXLength::CM:
1460                                         case LyXLength::IN:
1461                                         case LyXLength::EX:
1462                                         case LyXLength::EM:
1463                                         case LyXLength::MU:
1464                                                 known_unit = true;
1465                                                 break;
1466                                         default:
1467                                                 break;
1468                                         }
1469                                 }
1470                         }
1471
1472                         if (known_unit || known_vspace) {
1473                                 // Literal length or known variable
1474                                 context.check_layout(os);
1475                                 begin_inset(os, "VSpace ");
1476                                 if (known_unit)
1477                                         os << value;
1478                                 os << unit;
1479                                 if (starred)
1480                                         os << '*';
1481                                 end_inset(os);
1482                         } else {
1483                                 // LyX can't handle other length variables in Inset VSpace
1484                                 string name = t.asInput();
1485                                 if (starred)
1486                                         name += '*';
1487                                 if (valid) {
1488                                         if (value == 1.0)
1489                                                 handle_ert(os, name + '{' + unit + '}', context);
1490                                         else if (value == -1.0)
1491                                                 handle_ert(os, name + "{-" + unit + '}', context);
1492                                         else
1493                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1494                                 } else
1495                                         handle_ert(os, name + '{' + length + '}', context);
1496                         }
1497                 }
1498
1499                 else {
1500                         //cerr << "#: " << t << " mode: " << mode << endl;
1501                         // heuristic: read up to next non-nested space
1502                         /*
1503                         string s = t.asInput();
1504                         string z = p.verbatim_item();
1505                         while (p.good() && z != " " && z.size()) {
1506                                 //cerr << "read: " << z << endl;
1507                                 s += z;
1508                                 z = p.verbatim_item();
1509                         }
1510                         cerr << "found ERT: " << s << endl;
1511                         handle_ert(os, s + ' ', context);
1512                         */
1513                         string name = t.asInput();
1514                         if (p.next_token().asInput() == "*") {
1515                                 // Starred commands like \vspace*{}
1516                                 p.get_token();                          // Eat '*'
1517                                 name += '*';
1518                         }
1519                         if (! parse_command(name, p, os, outer, context))
1520                                 handle_ert(os, name, context);
1521                 }
1522
1523                 if (flags & FLAG_LEAVE) {
1524                         flags &= ~FLAG_LEAVE;
1525                         break;
1526                 }
1527         }
1528 }
1529
1530
1531 // }])