]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
Get rid of extraneous whitespace.
[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/FileInfo.h"
21 #include "support/lstrings.h"
22 #include "support/convert.h"
23 #include "support/filetools.h"
24
25 #include <boost/tuple/tuple.hpp>
26
27 #include <iostream>
28 #include <map>
29 #include <sstream>
30 #include <vector>
31
32 using lyx::support::FileInfo;
33 using lyx::support::MakeAbsPath;
34 using lyx::support::rtrim;
35 using lyx::support::suffixIs;
36 using lyx::support::contains;
37 using lyx::support::subst;
38
39 using std::cerr;
40 using std::endl;
41
42 using std::map;
43 using std::ostream;
44 using std::ostringstream;
45 using std::istringstream;
46 using std::string;
47 using std::vector;
48
49
50 /// thin wrapper around parse_text using a string
51 string parse_text(Parser & p, unsigned flags, const bool outer,
52                   Context & context)
53 {
54         ostringstream os;
55         parse_text(p, os, flags, outer, context);
56         return os.str();
57 }
58
59
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61                 Context & context)
62 {
63         Context newcontext(true, context.textclass);
64         newcontext.font = context.font;
65         parse_text(p, os, flags, outer, newcontext);
66         newcontext.check_end_layout(os);
67 }
68
69
70 /// parses a paragraph snippet, useful for example for \emph{...}
71 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
72                 Context & context)
73 {
74         Context newcontext(false, context.textclass);
75         newcontext.font = context.font;
76         parse_text(p, os, flags, outer, newcontext);
77         // should not be needed
78         newcontext.check_end_layout(os);
79 }
80
81
82 namespace {
83
84 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
85 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
86
87 /*!
88  * natbib commands.
89  * We can't put these into known_latex_commands because the argument order
90  * is reversed in lyx if there are 2 arguments.
91  * The starred forms are also known.
92  */
93 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
94 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
95 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
96
97 /*!
98  * jurabib commands.
99  * We can't put these into known_latex_commands because the argument order
100  * is reversed in lyx if there are 2 arguments.
101  * No starred form other than "cite*" known.
102  */
103 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
104 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
105 // jurabib commands not (yet) supported by LyX:
106 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
107 // "footciteauthor", "footciteyear", "footciteyearpar",
108 "citefield", "citetitle", "cite*", 0 };
109
110 /// LaTeX names for quotes
111 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
112 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
113
114 /// the same as known_quotes with .lyx names
115 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
116 "grd", "gls", "fls", "frd", 0};
117
118 /// LaTeX names for font sizes
119 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
120 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
121
122 /// the same as known_sizes with .lyx names
123 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
124 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
125
126 /// LaTeX 2.09 names for font families
127 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
128
129 /// LaTeX names for font families
130 char const * const known_font_families[] = { "rmfamily", "sffamily",
131 "ttfamily", 0};
132
133 /// the same as known_old_font_families and known_font_families with .lyx names
134 char const * const known_coded_font_families[] = { "roman", "sans",
135 "typewriter", 0};
136
137 /// LaTeX 2.09 names for font series
138 char const * const known_old_font_series[] = { "bf", 0};
139
140 /// LaTeX names for font series
141 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
142
143 /// the same as known_old_font_series and known_font_series with .lyx names
144 char const * const known_coded_font_series[] = { "bold", "medium", 0};
145
146 /// LaTeX 2.09 names for font shapes
147 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
148
149 /// LaTeX names for font shapes
150 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
151 "upshape", 0};
152
153 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
154 char const * const known_coded_font_shapes[] = { "italic", "slanted",
155 "smallcaps", "up", 0};
156
157 /*!
158  * Graphics file extensions known by the dvips driver of the graphics package.
159  * These extensions are used to complete the filename of an included
160  * graphics file if it does not contain an extension.
161  * The order must be the same that latex uses to find a file, because we
162  * will use the first extension that matches.
163  * This is only an approximation for the common cases. If we would want to
164  * do it right in all cases, we would need to know which graphics driver is
165  * used and know the extensions of every driver of the graphics package.
166  */
167 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
168 "ps.gz", "eps.Z", "ps.Z", 0};
169
170 /*!
171  * Graphics file extensions known by the pdftex driver of the graphics package.
172  * \see known_dvips_graphics_formats
173  */
174 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
175 "mps", "tif", 0};
176
177
178 /// splits "x=z, y=b" into a map
179 map<string, string> split_map(string const & s)
180 {
181         map<string, string> res;
182         vector<string> v;
183         split(s, v);
184         for (size_t i = 0; i < v.size(); ++i) {
185                 size_t const pos   = v[i].find('=');
186                 string const index = v[i].substr(0, pos);
187                 string const value = v[i].substr(pos + 1, string::npos);
188                 res[trim(index)] = trim(value);
189         }
190         return res;
191 }
192
193
194 /*!
195  * Split a LaTeX length into value and unit.
196  * The latter can be a real unit like "pt", or a latex length variable
197  * like "\textwidth". The unit may contain additional stuff like glue
198  * lengths, but we don't care, because such lengths are ERT anyway.
199  * \return true if \param value and \param unit are valid.
200  */
201 bool splitLatexLength(string const & len, string & value, string & unit)
202 {
203         if (len.empty())
204                 return false;
205         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
206         //'4,5' is a valid LaTeX length number. Change it to '4.5'
207         string const length = subst(len, ',', '.');
208         if (i == string::npos)
209                 return false;
210         if (i == 0) {
211                 if (len[0] == '\\') {
212                         // We had something like \textwidth without a factor
213                         value = "1.0";
214                 } else {
215                         return false;
216                 }
217         } else {
218                 value = trim(string(length, 0, i));
219         }
220         if (value == "-")
221                 value = "-1.0";
222         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
223         if (contains(len, '\\'))
224                 unit = trim(string(len, i));
225         else
226                 unit = lyx::support::lowercase(trim(string(len, i)));
227         return true;
228 }
229
230
231 /// A simple function to translate a latex length to something lyx can
232 /// understand. Not perfect, but rather best-effort.
233 bool translate_len(string const & length, string & valstring, string & unit)
234 {
235         if (!splitLatexLength(length, valstring, unit))
236                 return false;
237         // LyX uses percent values
238         double value;
239         istringstream iss(valstring);
240         iss >> value;
241         value *= 100;
242         ostringstream oss;
243         oss << value;
244         string const percentval = oss.str();
245         // a normal length
246         if (unit.empty() || unit[0] != '\\')
247                 return true;
248         string::size_type const i = unit.find(' ');
249         string const endlen = (i == string::npos) ? string() : string(unit, i);
250         if (unit == "\\textwidth") {
251                 valstring = percentval;
252                 unit = "text%" + endlen;
253         } else if (unit == "\\columnwidth") {
254                 valstring = percentval;
255                 unit = "col%" + endlen;
256         } else if (unit == "\\paperwidth") {
257                 valstring = percentval;
258                 unit = "page%" + endlen;
259         } else if (unit == "\\linewidth") {
260                 valstring = percentval;
261                 unit = "line%" + endlen;
262         } else if (unit == "\\paperheight") {
263                 valstring = percentval;
264                 unit = "pheight%" + endlen;
265         } else if (unit == "\\textheight") {
266                 valstring = percentval;
267                 unit = "theight%" + endlen;
268         }
269         return true;
270 }
271
272
273 string translate_len(string const & length)
274 {
275         string unit;
276         string value;
277         if (translate_len(length, value, unit))
278                 return value + unit;
279         // If the input is invalid, return what we have.
280         return length;
281 }
282
283
284 /*!
285  * Translates a LaTeX length into \param value, \param unit and
286  * \param special parts suitable for a box inset.
287  * The difference from translate_len() is that a box inset knows about
288  * some special "units" that are stored in \param special.
289  */
290 void translate_box_len(string const & length, string & value, string & unit, string & special)
291 {
292         if (translate_len(length, value, unit)) {
293                 if (unit == "\\height" || unit == "\\depth" ||
294                     unit == "\\totalheight" || unit == "\\width") {
295                         special = unit.substr(1);
296                         // The unit is not used, but LyX requires a dummy setting
297                         unit = "in";
298                 } else
299                         special = "none";
300         } else {
301                 value.clear();
302                 unit = length;
303                 special = "none";
304         }
305 }
306
307
308 /*!
309  * Find a file with basename \p name in path \p path and an extension
310  * in \p extensions.
311  */
312 string find_file(string const & name, string const & path,
313                  char const * const * extensions)
314 {
315         for (char const * const * what = extensions; *what; ++what) {
316                 // We don't use ChangeExtension() because it does the wrong
317                 // thing if name contains a dot.
318                 string const trial = name + '.' + (*what);
319                 if (FileInfo(MakeAbsPath(trial, path)).exist())
320                         return trial;
321         }
322         return string();
323 }
324
325
326 void begin_inset(ostream & os, string const & name)
327 {
328         os << "\n\\begin_inset " << name;
329 }
330
331
332 void end_inset(ostream & os)
333 {
334         os << "\n\\end_inset\n\n";
335 }
336
337
338 void skip_braces(Parser & p)
339 {
340         if (p.next_token().cat() != catBegin)
341                 return;
342         p.get_token();
343         if (p.next_token().cat() == catEnd) {
344                 p.get_token();
345                 return;
346         }
347         p.putback();
348 }
349
350
351 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
352 {
353         if (check_layout) {
354                 // We must have a valid layout before outputting the ERT inset.
355                 context.check_layout(os);
356         }
357         Context newcontext(true, context.textclass);
358         begin_inset(os, "ERT");
359         os << "\nstatus collapsed\n";
360         newcontext.check_layout(os);
361         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
362                 if (*it == '\\')
363                         os << "\n\\backslash\n";
364                 else if (*it == '\n')
365                         os << "\n\\newline\n";
366                 else
367                         os << *it;
368         }
369         newcontext.check_end_layout(os);
370         end_inset(os);
371 }
372
373
374 void handle_comment(ostream & os, string const & s, Context & context)
375 {
376         // TODO: Handle this better
377         Context newcontext(true, context.textclass);
378         begin_inset(os, "ERT");
379         os << "\nstatus collapsed\n";
380         newcontext.check_layout(os);
381         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
382                 if (*it == '\\')
383                         os << "\n\\backslash\n";
384                 else
385                         os << *it;
386         }
387         // make sure that our comment is the last thing on the line
388         os << "\n\\newline";
389         newcontext.check_end_layout(os);
390         end_inset(os);
391 }
392
393
394 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
395 public:
396         isLayout(string const name) : name_(name) {}
397         bool operator()(LyXLayout_ptr const & ptr) const {
398                 return ptr->latexname() == name_;
399         }
400 private:
401         string const name_;
402 };
403
404
405 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
406                          string const & name)
407 {
408         LyXTextClass::const_iterator beg  = textclass.begin();
409         LyXTextClass::const_iterator end = textclass.end();
410
411         LyXTextClass::const_iterator
412                 it = std::find_if(beg, end, isLayout(name));
413
414         return (it == end) ? LyXLayout_ptr() : *it;
415 }
416
417
418 void eat_whitespace(Parser &, ostream &, Context &, bool);
419
420
421 void output_command_layout(ostream & os, Parser & p, bool outer,
422                            Context & parent_context,
423                            LyXLayout_ptr newlayout)
424 {
425         parent_context.check_end_layout(os);
426         Context context(true, parent_context.textclass, newlayout,
427                         parent_context.layout, parent_context.font);
428         if (parent_context.deeper_paragraph) {
429                 // We are beginning a nested environment after a
430                 // deeper paragraph inside the outer list environment.
431                 // Therefore we don't need to output a "begin deeper".
432                 context.need_end_deeper = true;
433         }
434         context.check_deeper(os);
435         context.check_layout(os);
436         if (context.layout->optionalargs > 0) {
437                 eat_whitespace(p, os, context, false);
438                 if (p.next_token().character() == '[') {
439                         p.get_token(); // eat '['
440                         begin_inset(os, "OptArg\n");
441                         os << "status collapsed\n\n";
442                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
443                         end_inset(os);
444                         eat_whitespace(p, os, context, false);
445                 }
446         }
447         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
448         context.check_end_layout(os);
449         if (parent_context.deeper_paragraph) {
450                 // We must suppress the "end deeper" because we
451                 // suppressed the "begin deeper" above.
452                 context.need_end_deeper = false;
453         }
454         context.check_end_deeper(os);
455         // We don't need really a new paragraph, but
456         // we must make sure that the next item gets a \begin_layout.
457         parent_context.new_paragraph(os);
458 }
459
460
461 /*!
462  * Output a space if necessary.
463  * This function gets called for every whitespace token.
464  *
465  * We have three cases here:
466  * 1. A space must be suppressed. Example: The lyxcode case below
467  * 2. A space may be suppressed. Example: Spaces before "\par"
468  * 3. A space must not be suppressed. Example: A space between two words
469  *
470  * We currently handle only 1. and 3 and from 2. only the case of
471  * spaces before newlines as a side effect.
472  *
473  * 2. could be used to suppress as many spaces as possible. This has two effects:
474  * - Reimporting LyX generated LaTeX files changes almost no whitespace
475  * - Superflous whitespace from non LyX generated LaTeX files is removed.
476  * The drawback is that the logic inside the function becomes
477  * complicated, and that is the reason why it is not implemented.
478  */
479 void check_space(Parser const & p, ostream & os, Context & context)
480 {
481         Token const next = p.next_token();
482         Token const curr = p.curr_token();
483         // A space before a single newline and vice versa must be ignored
484         // LyX emits a newline before \end{lyxcode}.
485         // This newline must be ignored,
486         // otherwise LyX will add an additional protected space.
487         if (next.cat() == catSpace ||
488             next.cat() == catNewline ||
489             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
490                 return;
491         }
492         context.check_layout(os);
493         os << ' ';
494 }
495
496
497 /*!
498  * Check whether \p command is a known command. If yes,
499  * handle the command with all arguments.
500  * \return true if the command was parsed, false otherwise.
501  */
502 bool parse_command(string const & command, Parser & p, ostream & os,
503                    bool outer, Context & context)
504 {
505         if (known_commands.find(command) != known_commands.end()) {
506                 vector<ArgumentType> const & template_arguments = known_commands[command];
507                 string ert = command;
508                 size_t no_arguments = template_arguments.size();
509                 for (size_t i = 0; i < no_arguments; ++i) {
510                         switch (template_arguments[i]) {
511                         case required:
512                                 // This argument contains regular LaTeX
513                                 handle_ert(os, ert + '{', context);
514                                 parse_text(p, os, FLAG_ITEM, outer, context);
515                                 ert = "}";
516                                 break;
517                         case verbatim:
518                                 // This argument may contain special characters
519                                 ert += '{' + p.verbatim_item() + '}';
520                                 break;
521                         case optional:
522                                 ert += p.getOpt();
523                                 break;
524                         }
525                 }
526                 handle_ert(os, ert, context);
527                 return true;
528         }
529         return false;
530 }
531
532
533 /// Parses a minipage or parbox
534 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
535                Context & parent_context, bool use_parbox)
536 {
537         string position;
538         string inner_pos;
539         string height_value = "0";
540         string height_unit = "pt";
541         string height_special = "none";
542         string latex_height;
543         if (p.next_token().asInput() == "[") {
544                 position = p.getArg('[', ']');
545                 if (position != "t" && position != "c" && position != "b") {
546                         position = "c";
547                         cerr << "invalid position for minipage/parbox" << endl;
548                 }
549                 if (p.next_token().asInput() == "[") {
550                         latex_height = p.getArg('[', ']');
551                         translate_box_len(latex_height, height_value, height_unit, height_special);
552
553                         if (p.next_token().asInput() == "[") {
554                                 inner_pos = p.getArg('[', ']');
555                                 if (inner_pos != "c" && inner_pos != "t" &&
556                                     inner_pos != "b" && inner_pos != "s") {
557                                         inner_pos = position;
558                                         cerr << "invalid inner_pos for minipage/parbox"
559                                              << endl;
560                                 }
561                         }
562                 }
563         }
564         string width_value;
565         string width_unit;
566         string const latex_width = p.verbatim_item();
567         translate_len(latex_width, width_value, width_unit);
568         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
569                 // LyX can't handle length variables
570                 ostringstream ss;
571                 if (use_parbox)
572                         ss << "\\parbox";
573                 else
574                         ss << "\\begin{minipage}";
575                 if (!position.empty())
576                         ss << '[' << position << ']';
577                 if (!latex_height.empty())
578                         ss << '[' << latex_height << ']';
579                 if (!inner_pos.empty())
580                         ss << '[' << inner_pos << ']';
581                 ss << "{" << latex_width << "}";
582                 if (use_parbox)
583                         ss << '{';
584                 handle_ert(os, ss.str(), parent_context);
585                 parent_context.new_paragraph(os);
586                 parse_text_in_inset(p, os, flags, outer, parent_context);
587                 if (use_parbox)
588                         handle_ert(os, "}", parent_context);
589                 else
590                         handle_ert(os, "\\end{minipage}", parent_context);
591         } else {
592                 // LyX does not like empty positions, so we have
593                 // to set them to the LaTeX default values here.
594                 if (position.empty())
595                         position = "c";
596                 if (inner_pos.empty())
597                         inner_pos = position;
598                 parent_context.check_layout(os);
599                 begin_inset(os, "Box Frameless\n");
600                 os << "position \"" << position << "\"\n";
601                 os << "hor_pos \"c\"\n";
602                 os << "has_inner_box 1\n";
603                 os << "inner_pos \"" << inner_pos << "\"\n";
604                 os << "use_parbox " << use_parbox << "\n";
605                 os << "width \"" << width_value << width_unit << "\"\n";
606                 os << "special \"none\"\n";
607                 os << "height \"" << height_value << height_unit << "\"\n";
608                 os << "height_special \"" << height_special << "\"\n";
609                 os << "status open\n\n";
610                 parse_text_in_inset(p, os, flags, outer, parent_context);
611                 end_inset(os);
612 #ifdef PRESERVE_LAYOUT
613                 // lyx puts a % after the end of the minipage
614                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
615                         // new paragraph
616                         //handle_comment(os, "%dummy", parent_context);
617                         p.get_token();
618                         p.skip_spaces();
619                         parent_context.new_paragraph(os);
620                 }
621                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
622                         //handle_comment(os, "%dummy", parent_context);
623                         p.get_token();
624                         p.skip_spaces();
625                         // We add a protected space if something real follows
626                         if (p.good() && p.next_token().cat() != catComment) {
627                                 os << "\\InsetSpace ~\n";
628                         }
629                 }
630 #endif
631         }
632 }
633
634
635 void parse_environment(Parser & p, ostream & os, bool outer,
636                        Context & parent_context)
637 {
638         LyXLayout_ptr newlayout;
639         string const name = p.getArg('{', '}');
640         const bool is_starred = suffixIs(name, '*');
641         string const unstarred_name = rtrim(name, "*");
642         eat_whitespace(p, os, parent_context, false);
643         active_environments.push_back(name);
644
645         if (is_math_env(name)) {
646                 parent_context.check_layout(os);
647                 begin_inset(os, "Formula ");
648                 os << "\\begin{" << name << "}";
649                 parse_math(p, os, FLAG_END, MATH_MODE);
650                 os << "\\end{" << name << "}";
651                 end_inset(os);
652         }
653
654         else if (name == "tabular" || name == "longtable") {
655                 parent_context.check_layout(os);
656                 begin_inset(os, "Tabular ");
657                 handle_tabular(p, os, name == "longtable", parent_context);
658                 end_inset(os);
659         }
660
661         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
662                 parent_context.check_layout(os);
663                 begin_inset(os, "Float " + unstarred_name + "\n");
664                 if (p.next_token().asInput() == "[") {
665                         os << "placement " << p.getArg('[', ']') << '\n';
666                 }
667                 os << "wide " << convert<string>(is_starred)
668                    << "\nsideways false"
669                    << "\nstatus open\n\n";
670                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
671                 end_inset(os);
672                 // We don't need really a new paragraph, but
673                 // we must make sure that the next item gets a \begin_layout.
674                 parent_context.new_paragraph(os);
675         }
676
677         else if (name == "minipage")
678                 parse_box(p, os, FLAG_END, outer, parent_context, false);
679
680         // Alignment settings
681         else if (name == "center" || name == "flushleft" || name == "flushright" ||
682                  name == "centering" || name == "raggedright" || name == "raggedleft") {
683                 // We must begin a new paragraph if not already done
684                 if (! parent_context.atParagraphStart()) {
685                         parent_context.check_end_layout(os);
686                         parent_context.new_paragraph(os);
687                 }
688                 if (name == "flushleft" || name == "raggedright")
689                         parent_context.add_extra_stuff("\\align left ");
690                 else if (name == "flushright" || name == "raggedleft")
691                         parent_context.add_extra_stuff("\\align right ");
692                 else
693                         parent_context.add_extra_stuff("\\align center ");
694                 parse_text(p, os, FLAG_END, outer, parent_context);
695                 // Just in case the environment is empty ..
696                 parent_context.extra_stuff.erase();
697                 // We must begin a new paragraph to reset the alignment
698                 parent_context.new_paragraph(os);
699         }
700
701         // The single '=' is meant here.
702         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
703                    newlayout->isEnvironment()) {
704                 Context context(true, parent_context.textclass, newlayout,
705                                 parent_context.layout, parent_context.font);
706                 if (parent_context.deeper_paragraph) {
707                         // We are beginning a nested environment after a
708                         // deeper paragraph inside the outer list environment.
709                         // Therefore we don't need to output a "begin deeper".
710                         context.need_end_deeper = true;
711                 }
712                 parent_context.check_end_layout(os);
713                 switch (context.layout->latextype) {
714                 case  LATEX_LIST_ENVIRONMENT:
715                         context.extra_stuff = "\\labelwidthstring "
716                                 + p.verbatim_item() + '\n';
717                         p.skip_spaces();
718                         break;
719                 case  LATEX_BIB_ENVIRONMENT:
720                         p.verbatim_item(); // swallow next arg
721                         p.skip_spaces();
722                         break;
723                 default:
724                         break;
725                 }
726                 context.check_deeper(os);
727                 parse_text(p, os, FLAG_END, outer, context);
728                 context.check_end_layout(os);
729                 if (parent_context.deeper_paragraph) {
730                         // We must suppress the "end deeper" because we
731                         // suppressed the "begin deeper" above.
732                         context.need_end_deeper = false;
733                 }
734                 context.check_end_deeper(os);
735                 parent_context.new_paragraph(os);
736         }
737
738         else if (name == "appendix") {
739                 // This is no good latex style, but it works and is used in some documents...
740                 parent_context.check_end_layout(os);
741                 Context context(true, parent_context.textclass, parent_context.layout,
742                                 parent_context.layout, parent_context.font);
743                 context.check_layout(os);
744                 os << "\\start_of_appendix\n";
745                 parse_text(p, os, FLAG_END, outer, context);
746                 context.check_end_layout(os);
747         }
748
749         else if (name == "comment") {
750                 parent_context.check_layout(os);
751                 begin_inset(os, "Note Comment\n");
752                 os << "status open\n";
753                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
754                 end_inset(os);
755         }
756
757         else if (name == "lyxgreyedout") {
758                 parent_context.check_layout(os);
759                 begin_inset(os, "Note Greyedout\n");
760                 os << "status open\n";
761                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
762                 end_inset(os);
763         }
764
765         else if (name == "tabbing") {
766                 // We need to remember that we have to handle '\=' specially
767                 handle_ert(os, "\\begin{" + name + "}", parent_context);
768                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
769                 handle_ert(os, "\\end{" + name + "}", parent_context);
770         }
771
772         else {
773                 handle_ert(os, "\\begin{" + name + "}", parent_context);
774                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
775                 handle_ert(os, "\\end{" + name + "}", parent_context);
776         }
777
778         active_environments.pop_back();
779         if (name != "math")
780                 p.skip_spaces();
781 }
782
783 /// parses a comment and outputs it to \p os.
784 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
785 {
786         BOOST_ASSERT(t.cat() == catComment);
787         context.check_layout(os);
788         if (!t.cs().empty()) {
789                 handle_comment(os, '%' + t.cs(), context);
790                 if (p.next_token().cat() == catNewline) {
791                         // A newline after a comment line starts a new
792                         // paragraph
793                         if(!context.atParagraphStart()) {
794                                 // Only start a new paragraph if not already
795                                 // done (we might get called recursively)
796                                 context.new_paragraph(os);
797                         }
798                         eat_whitespace(p, os, context, true);
799                 }
800         } else {
801                 // "%\n" combination
802                 p.skip_spaces();
803         }
804 }
805
806
807 /*!
808  * Reads spaces and comments until the first non-space, non-comment token.
809  * New paragraphs (double newlines or \\par) are handled like simple spaces
810  * if \p eatParagraph is true.
811  * Spaces are skipped, but comments are written to \p os.
812  */
813 void eat_whitespace(Parser & p, ostream & os, Context & context,
814                     bool eatParagraph)
815 {
816         while (p.good()) {
817                 Token const & t = p.get_token();
818                 if (t.cat() == catComment)
819                         parse_comment(p, os, t, context);
820                 else if ((! eatParagraph && p.isParagraph()) ||
821                          (t.cat() != catSpace && t.cat() != catNewline)) {
822                         p.putback();
823                         return;
824                 }
825         }
826 }
827
828
829 /*!
830  * Set a font attribute, parse text and reset the font attribute.
831  * \param attribute Attribute name (e.g. \\family, \\shape etc.)
832  * \param currentvalue Current value of the attribute. Is set to the new
833  * value during parsing.
834  * \param newvalue New value of the attribute
835  */
836 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
837                            Context & context, string const & attribute,
838                            string & currentvalue, string const & newvalue)
839 {
840         context.check_layout(os);
841         string oldvalue = currentvalue;
842         currentvalue = newvalue;
843         os << '\n' << attribute << ' ' << newvalue << "\n";
844         parse_text_snippet(p, os, flags, outer, context);
845         currentvalue = oldvalue;
846         os << '\n' << attribute << ' ' << oldvalue << "\n";
847 }
848
849
850 /// get the arguments of a natbib or jurabib citation command
851 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
852 {
853         // We need to distinguish "" and "[]", so we can't use p.getOpt().
854
855         // text before the citation
856         string before;
857         // text after the citation
858         string after = p.getFullOpt();
859
860         if (!after.empty()) {
861                 before = p.getFullOpt();
862                 if (natbibOrder && !before.empty())
863                         std::swap(before, after);
864         }
865         return std::make_pair(before, after);
866 }
867
868 } // anonymous namespace
869
870
871 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
872                 Context & context)
873 {
874         LyXLayout_ptr newlayout;
875         // Store the latest bibliographystyle (needed for bibtex inset)
876         string bibliographystyle;
877         bool const use_natbib = used_packages.find("natbib") != used_packages.end();
878         bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
879         while (p.good()) {
880                 Token const & t = p.get_token();
881
882 #ifdef FILEDEBUG
883                 cerr << "t: " << t << " flags: " << flags << "\n";
884 #endif
885
886                 if (flags & FLAG_ITEM) {
887                         if (t.cat() == catSpace)
888                                 continue;
889
890                         flags &= ~FLAG_ITEM;
891                         if (t.cat() == catBegin) {
892                                 // skip the brace and collect everything to the next matching
893                                 // closing brace
894                                 flags |= FLAG_BRACE_LAST;
895                                 continue;
896                         }
897
898                         // handle only this single token, leave the loop if done
899                         flags |= FLAG_LEAVE;
900                 }
901
902                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
903                         return;
904
905                 //
906                 // cat codes
907                 //
908                 if (t.cat() == catMath) {
909                         // we are inside some text mode thingy, so opening new math is allowed
910                         context.check_layout(os);
911                         begin_inset(os, "Formula ");
912                         Token const & n = p.get_token();
913                         if (n.cat() == catMath && outer) {
914                                 // TeX's $$...$$ syntax for displayed math
915                                 os << "\\[";
916                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
917                                 os << "\\]";
918                                 p.get_token(); // skip the second '$' token
919                         } else {
920                                 // simple $...$  stuff
921                                 p.putback();
922                                 os << '$';
923                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
924                                 os << '$';
925                         }
926                         end_inset(os);
927                 }
928
929                 else if (t.cat() == catSuper || t.cat() == catSub)
930                         cerr << "catcode " << t << " illegal in text mode\n";
931
932                 // Basic support for english quotes. This should be
933                 // extended to other quotes, but is not so easy (a
934                 // left english quote is the same as a right german
935                 // quote...)
936                 else if (t.asInput() == "`"
937                          && p.next_token().asInput() == "`") {
938                         context.check_layout(os);
939                         begin_inset(os, "Quotes ");
940                         os << "eld";
941                         end_inset(os);
942                         p.get_token();
943                         skip_braces(p);
944                 }
945                 else if (t.asInput() == "'"
946                          && p.next_token().asInput() == "'") {
947                         context.check_layout(os);
948                         begin_inset(os, "Quotes ");
949                         os << "erd";
950                         end_inset(os);
951                         p.get_token();
952                         skip_braces(p);
953                 }
954
955                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
956                         check_space(p, os, context);
957
958                 else if (t.cat() == catLetter ||
959                                t.cat() == catOther ||
960                                t.cat() == catAlign ||
961                                t.cat() == catParameter) {
962                         context.check_layout(os);
963                         os << t.character();
964                 }
965
966                 else if (p.isParagraph()) {
967                         context.new_paragraph(os);
968                         eat_whitespace(p, os, context, true);
969                 }
970
971                 else if (t.cat() == catActive) {
972                         context.check_layout(os);
973                         if (t.character() == '~') {
974                                 if (context.layout->free_spacing)
975                                         os << ' ';
976                                 else
977                                         os << "\\InsetSpace ~\n";
978                         } else
979                                 os << t.character();
980                 }
981
982                 else if (t.cat() == catBegin) {
983                         context.check_layout(os);
984                         // special handling of font attribute changes
985                         Token const prev = p.prev_token();
986                         Token const next = p.next_token();
987                         Font const oldFont = context.font;
988                         string const s = parse_text(p, FLAG_BRACE_LAST, outer,
989                                                     context);
990                         context.font = oldFont;
991                         if (s.empty() && (p.next_token().character() == '`' ||
992                                           (prev.character() == '-' &&
993                                            p.next_token().character() == '-')))
994                                 ; // ignore it in {}`` or -{}-
995                         else if (s == "[" || s == "]" || s == "*")
996                                 os << s;
997                         else if (is_known(next.cs(), known_sizes))
998                                 // s will change the size, so we must reset
999                                 // it here
1000                                 os << s << "\n\\size " << context.font.size
1001                                    << "\n";
1002                         else if (is_known(next.cs(), known_font_families))
1003                                 // s will change the font family, so we must
1004                                 // reset it here
1005                                 os << s << "\n\\family "
1006                                    << context.font.family << "\n";
1007                         else if (is_known(next.cs(), known_font_series))
1008                                 // s will change the font series, so we must
1009                                 // reset it here
1010                                 os << s << "\n\\series "
1011                                    << context.font.series << "\n";
1012                         else if (is_known(next.cs(), known_font_shapes))
1013                                 // s will change the font shape, so we must
1014                                 // reset it here
1015                                 os << s << "\n\\shape "
1016                                    << context.font.shape << "\n";
1017                         else if (is_known(next.cs(), known_old_font_families) ||
1018                                  is_known(next.cs(), known_old_font_series) ||
1019                                  is_known(next.cs(), known_old_font_shapes))
1020                                 // s will change the font family, series
1021                                 // and shape, so we must reset it here
1022                                 os << s
1023                                    <<  "\n\\family " << context.font.family
1024                                    << "\n\\series " << context.font.series
1025                                    << "\n\\shape "  << context.font.shape
1026                                    << "\n";
1027                         else {
1028                                 handle_ert(os, "{", context, false);
1029                                 // s will end the current layout and begin a
1030                                 // new one if necessary
1031                                 os << s;
1032                                 handle_ert(os, "}", context);
1033                         }
1034                 }
1035
1036                 else if (t.cat() == catEnd) {
1037                         if (flags & FLAG_BRACE_LAST) {
1038                                 return;
1039                         }
1040                         cerr << "stray '}' in text\n";
1041                         handle_ert(os, "}", context);
1042                 }
1043
1044                 else if (t.cat() == catComment)
1045                         parse_comment(p, os, t, context);
1046
1047                 //
1048                 // control sequences
1049                 //
1050
1051                 else if (t.cs() == "(") {
1052                         context.check_layout(os);
1053                         begin_inset(os, "Formula");
1054                         os << " \\(";
1055                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1056                         os << "\\)";
1057                         end_inset(os);
1058                 }
1059
1060                 else if (t.cs() == "[") {
1061                         context.check_layout(os);
1062                         begin_inset(os, "Formula");
1063                         os << " \\[";
1064                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1065                         os << "\\]";
1066                         end_inset(os);
1067                 }
1068
1069                 else if (t.cs() == "begin")
1070                         parse_environment(p, os, outer, context);
1071
1072                 else if (t.cs() == "end") {
1073                         if (flags & FLAG_END) {
1074                                 // eat environment name
1075                                 string const name = p.getArg('{', '}');
1076                                 if (name != active_environment())
1077                                         cerr << "\\end{" + name + "} does not match \\begin{"
1078                                                 + active_environment() + "}\n";
1079                                 return;
1080                         }
1081                         p.error("found 'end' unexpectedly");
1082                 }
1083
1084                 else if (t.cs() == "item") {
1085                         p.skip_spaces();
1086                         string s;
1087                         bool optarg = false;
1088                         if (p.next_token().character() == '[') {
1089                                 p.get_token(); // eat '['
1090                                 Context newcontext(false, context.textclass);
1091                                 newcontext.font = context.font;
1092                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1093                                 optarg = true;
1094                         }
1095                         context.set_item();
1096                         context.check_layout(os);
1097                         if (optarg) {
1098                                 if (context.layout->labeltype != LABEL_MANUAL) {
1099                                         // lyx does not support \item[\mybullet]
1100                                         // in itemize environments
1101                                         handle_ert(os, "[", context);
1102                                         os << s;
1103                                         handle_ert(os, "]", context);
1104                                 } else if (!s.empty()) {
1105                                         // The space is needed to separate the
1106                                         // item from the rest of the sentence.
1107                                         os << s << ' ';
1108                                         eat_whitespace(p, os, context, false);
1109                                 }
1110                         }
1111                 }
1112
1113                 else if (t.cs() == "bibitem") {
1114                         context.set_item();
1115                         context.check_layout(os);
1116                         os << "\\bibitem ";
1117                         os << p.getOpt();
1118                         os << '{' << p.verbatim_item() << '}' << "\n";
1119                 }
1120
1121                 else if (t.cs() == "def") {
1122                         context.check_layout(os);
1123                         eat_whitespace(p, os, context, false);
1124                         string name = p.get_token().cs();
1125                         while (p.next_token().cat() != catBegin)
1126                                 name += p.get_token().asString();
1127                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1128                 }
1129
1130                 else if (t.cs() == "noindent") {
1131                         p.skip_spaces();
1132                         context.add_extra_stuff("\\noindent ");
1133                 }
1134
1135                 else if (t.cs() == "appendix") {
1136                         p.skip_spaces();
1137                         context.add_extra_stuff("\\start_of_appendix ");
1138                 }
1139
1140                 // Must attempt to parse "Section*" before "Section".
1141                 else if ((p.next_token().asInput() == "*") &&
1142                          // The single '=' is meant here.
1143                          (newlayout = findLayout(context.textclass,
1144                                                  t.cs() + '*')).get() &&
1145                          newlayout->isCommand()) {
1146                         p.get_token();
1147                         output_command_layout(os, p, outer, context, newlayout);
1148                         p.skip_spaces();
1149                 }
1150
1151                 // The single '=' is meant here.
1152                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1153                          newlayout->isCommand()) {
1154                         output_command_layout(os, p, outer, context, newlayout);
1155                         p.skip_spaces();
1156                 }
1157
1158                 else if (t.cs() == "includegraphics") {
1159                         map<string, string> opts = split_map(p.getArg('[', ']'));
1160                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
1161
1162                         string const path = getMasterFilePath();
1163                         // We want to preserve relative / absolute filenames,
1164                         // therefore path is only used for testing
1165                         if (!FileInfo(MakeAbsPath(name, path)).exist()) {
1166                                 // The file extension is probably missing.
1167                                 // Now try to find it out.
1168                                 string const dvips_name =
1169                                         find_file(name, path,
1170                                                   known_dvips_graphics_formats);
1171                                 string const pdftex_name =
1172                                         find_file(name, path,
1173                                                   known_pdftex_graphics_formats);
1174                                 if (!dvips_name.empty()) {
1175                                         if (!pdftex_name.empty()) {
1176                                                 cerr << "This file contains the "
1177                                                         "latex snippet\n"
1178                                                         "\"\\includegraphics{"
1179                                                      << name << "}\".\n"
1180                                                         "However, files\n\""
1181                                                      << dvips_name << "\" and\n\""
1182                                                      << pdftex_name << "\"\n"
1183                                                         "both exist, so I had to make a "
1184                                                         "choice and took the first one.\n"
1185                                                         "Please move the unwanted one "
1186                                                         "someplace else and try again\n"
1187                                                         "if my choice was wrong."
1188                                                      << endl;
1189                                         }
1190                                         name = dvips_name;
1191                                 } else if (!pdftex_name.empty())
1192                                         name = pdftex_name;
1193
1194                                 if (!FileInfo(MakeAbsPath(name, path)).exist())
1195                                         cerr << "Warning: Could not find graphics file '"
1196                                              << name << "'." << endl;
1197                         }
1198
1199                         context.check_layout(os);
1200                         begin_inset(os, "Graphics ");
1201                         os << "\n\tfilename " << name << '\n';
1202                         if (opts.find("width") != opts.end())
1203                                 os << "\twidth "
1204                                    << translate_len(opts["width"]) << '\n';
1205                         if (opts.find("height") != opts.end())
1206                                 os << "\theight "
1207                                    << translate_len(opts["height"]) << '\n';
1208                         if (opts.find("scale") != opts.end()) {
1209                                 istringstream iss(opts["scale"]);
1210                                 double val;
1211                                 iss >> val;
1212                                 val = val*100;
1213                                 os << "\tscale " << val << '\n';
1214                         }
1215                         if (opts.find("angle") != opts.end())
1216                                 os << "\trotateAngle "
1217                                    << opts["angle"] << '\n';
1218                         if (opts.find("origin") != opts.end()) {
1219                                 ostringstream ss;
1220                                 string const opt = opts["origin"];
1221                                 if (opt.find('l') != string::npos) ss << "left";
1222                                 if (opt.find('r') != string::npos) ss << "right";
1223                                 if (opt.find('c') != string::npos) ss << "center";
1224                                 if (opt.find('t') != string::npos) ss << "Top";
1225                                 if (opt.find('b') != string::npos) ss << "Bottom";
1226                                 if (opt.find('B') != string::npos) ss << "Baseline";
1227                                 if (!ss.str().empty())
1228                                         os << "\trotateOrigin " << ss.str() << '\n';
1229                                 else
1230                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1231                         }
1232                         if (opts.find("keepaspectratio") != opts.end())
1233                                 os << "\tkeepAspectRatio\n";
1234                         if (opts.find("clip") != opts.end())
1235                                 os << "\tclip\n";
1236                         if (opts.find("draft") != opts.end())
1237                                 os << "\tdraft\n";
1238                         if (opts.find("bb") != opts.end())
1239                                 os << "\tBoundingBox "
1240                                    << opts["bb"] << '\n';
1241                         int numberOfbbOptions = 0;
1242                         if (opts.find("bbllx") != opts.end())
1243                                 numberOfbbOptions++;
1244                         if (opts.find("bblly") != opts.end())
1245                                 numberOfbbOptions++;
1246                         if (opts.find("bburx") != opts.end())
1247                                 numberOfbbOptions++;
1248                         if (opts.find("bbury") != opts.end())
1249                                 numberOfbbOptions++;
1250                         if (numberOfbbOptions == 4)
1251                                 os << "\tBoundingBox "
1252                                    << opts["bbllx"] << opts["bblly"]
1253                                    << opts["bburx"] << opts["bbury"] << '\n';
1254                         else if (numberOfbbOptions > 0)
1255                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1256                         numberOfbbOptions = 0;
1257                         if (opts.find("natwidth") != opts.end())
1258                                 numberOfbbOptions++;
1259                         if (opts.find("natheight") != opts.end())
1260                                 numberOfbbOptions++;
1261                         if (numberOfbbOptions == 2)
1262                                 os << "\tBoundingBox 0bp 0bp "
1263                                    << opts["natwidth"] << opts["natheight"] << '\n';
1264                         else if (numberOfbbOptions > 0)
1265                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1266                         ostringstream special;
1267                         if (opts.find("hiresbb") != opts.end())
1268                                 special << "hiresbb,";
1269                         if (opts.find("trim") != opts.end())
1270                                 special << "trim,";
1271                         if (opts.find("viewport") != opts.end())
1272                                 special << "viewport=" << opts["viewport"] << ',';
1273                         if (opts.find("totalheight") != opts.end())
1274                                 special << "totalheight=" << opts["totalheight"] << ',';
1275                         if (opts.find("type") != opts.end())
1276                                 special << "type=" << opts["type"] << ',';
1277                         if (opts.find("ext") != opts.end())
1278                                 special << "ext=" << opts["ext"] << ',';
1279                         if (opts.find("read") != opts.end())
1280                                 special << "read=" << opts["read"] << ',';
1281                         if (opts.find("command") != opts.end())
1282                                 special << "command=" << opts["command"] << ',';
1283                         string s_special = special.str();
1284                         if (!s_special.empty()) {
1285                                 // We had special arguments. Remove the trailing ','.
1286                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1287                         }
1288                         // TODO: Handle the unknown settings better.
1289                         // Warn about invalid options.
1290                         // Check whether some option was given twice.
1291                         end_inset(os);
1292                 }
1293
1294                 else if (t.cs() == "footnote") {
1295                         p.skip_spaces();
1296                         context.check_layout(os);
1297                         begin_inset(os, "Foot\n");
1298                         os << "status collapsed\n\n";
1299                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1300                         end_inset(os);
1301                 }
1302
1303                 else if (t.cs() == "marginpar") {
1304                         p.skip_spaces();
1305                         context.check_layout(os);
1306                         begin_inset(os, "Marginal\n");
1307                         os << "status collapsed\n\n";
1308                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1309                         end_inset(os);
1310                 }
1311
1312                 else if (t.cs() == "ensuremath") {
1313                         p.skip_spaces();
1314                         context.check_layout(os);
1315                         Context newcontext(false, context.textclass);
1316                         newcontext.font = context.font;
1317                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1318                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1319                                 os << s;
1320                         else
1321                                 handle_ert(os, "\\ensuremath{" + s + "}",
1322                                            context);
1323                 }
1324
1325                 else if (t.cs() == "hfill") {
1326                         context.check_layout(os);
1327                         os << "\n\\hfill\n";
1328                         skip_braces(p);
1329                         p.skip_spaces();
1330                 }
1331
1332                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1333                         p.skip_spaces();
1334                         skip_braces(p); // swallow this
1335                 }
1336
1337                 else if (t.cs() == "tableofcontents") {
1338                         p.skip_spaces();
1339                         context.check_layout(os);
1340                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1341                         end_inset(os);
1342                         skip_braces(p); // swallow this
1343                 }
1344
1345                 else if (t.cs() == "listoffigures") {
1346                         p.skip_spaces();
1347                         context.check_layout(os);
1348                         begin_inset(os, "FloatList figure\n");
1349                         end_inset(os);
1350                         skip_braces(p); // swallow this
1351                 }
1352
1353                 else if (t.cs() == "listoftables") {
1354                         p.skip_spaces();
1355                         context.check_layout(os);
1356                         begin_inset(os, "FloatList table\n");
1357                         end_inset(os);
1358                         skip_braces(p); // swallow this
1359                 }
1360
1361                 else if (t.cs() == "listof") {
1362                         p.skip_spaces(true);
1363                         string const name = p.get_token().asString();
1364                         if (context.textclass.floats().typeExist(name)) {
1365                                 context.check_layout(os);
1366                                 begin_inset(os, "FloatList ");
1367                                 os << name << "\n";
1368                                 end_inset(os);
1369                                 p.get_token(); // swallow second arg
1370                         } else
1371                                 handle_ert(os, "\\listof{" + name + "}", context);
1372                 }
1373
1374                 else if (t.cs() == "textrm")
1375                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1376                                               context, "\\family",
1377                                               context.font.family, "roman");
1378
1379                 else if (t.cs() == "textsf")
1380                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1381                                               context, "\\family",
1382                                               context.font.family, "sans");
1383
1384                 else if (t.cs() == "texttt")
1385                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1386                                               context, "\\family",
1387                                               context.font.family, "typewriter");
1388
1389                 else if (t.cs() == "textmd")
1390                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1391                                               context, "\\series",
1392                                               context.font.series, "medium");
1393
1394                 else if (t.cs() == "textbf")
1395                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1396                                               context, "\\series",
1397                                               context.font.series, "bold");
1398
1399                 else if (t.cs() == "textup")
1400                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1401                                               context, "\\shape",
1402                                               context.font.shape, "up");
1403
1404                 else if (t.cs() == "textit")
1405                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1406                                               context, "\\shape",
1407                                               context.font.shape, "italic");
1408
1409                 else if (t.cs() == "textsl")
1410                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1411                                               context, "\\shape",
1412                                               context.font.shape, "slanted");
1413
1414                 else if (t.cs() == "textsc")
1415                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1416                                               context, "\\shape",
1417                                               context.font.shape, "smallcaps");
1418
1419                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1420                         context.check_layout(os);
1421                         Font oldFont = context.font;
1422                         context.font.init();
1423                         context.font.size = oldFont.size;
1424                         os << "\n\\family " << context.font.family << "\n";
1425                         os << "\n\\series " << context.font.series << "\n";
1426                         os << "\n\\shape " << context.font.shape << "\n";
1427                         if (t.cs() == "textnormal") {
1428                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1429                                 context.font = oldFont;
1430                                 os << "\n\\shape " << oldFont.shape << "\n";
1431                                 os << "\n\\series " << oldFont.series << "\n";
1432                                 os << "\n\\family " << oldFont.family << "\n";
1433                         } else
1434                                 eat_whitespace(p, os, context, false);
1435                 }
1436
1437                 else if (t.cs() == "underbar") {
1438                         // Do NOT handle \underline.
1439                         // \underbar cuts through y, g, q, p etc.,
1440                         // \underline does not.
1441                         context.check_layout(os);
1442                         os << "\n\\bar under\n";
1443                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1444                         os << "\n\\bar default\n";
1445                 }
1446
1447                 else if (t.cs() == "emph" || t.cs() == "noun") {
1448                         context.check_layout(os);
1449                         os << "\n\\" << t.cs() << " on\n";
1450                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1451                         os << "\n\\" << t.cs() << " default\n";
1452                 }
1453
1454                 else if (use_natbib &&
1455                          is_known(t.cs(), known_natbib_commands) &&
1456                          ((t.cs() != "citefullauthor" &&
1457                            t.cs() != "citeyear" &&
1458                            t.cs() != "citeyearpar") ||
1459                           p.next_token().asInput() != "*")) {
1460                         context.check_layout(os);
1461                         // tex                       lyx
1462                         // \citet[before][after]{a}  \citet[after][before]{a}
1463                         // \citet[before][]{a}       \citet[][before]{a}
1464                         // \citet[after]{a}          \citet[after]{a}
1465                         // \citet{a}                 \citet{a}
1466                         string command = '\\' + t.cs();
1467                         if (p.next_token().asInput() == "*") {
1468                                 command += '*';
1469                                 p.get_token();
1470                         }
1471                         if (command == "\\citefullauthor")
1472                                 // alternative name for "\\citeauthor*"
1473                                 command = "\\citeauthor*";
1474
1475                         // text before the citation
1476                         string before;
1477                         // text after the citation
1478                         string after;
1479
1480                         boost::tie(before, after) = getCiteArguments(p, true);
1481                         if (command == "\\cite") {
1482                                 // \cite without optional argument means
1483                                 // \citet, \cite with at least one optional
1484                                 // argument means \citep.
1485                                 if (before.empty() && after.empty())
1486                                         command = "\\citet";
1487                                 else
1488                                         command = "\\citep";
1489                         }
1490                         if (before.empty() && after == "[]")
1491                                 // avoid \citet[]{a}
1492                                 after.erase();
1493                         else if (before == "[]" && after == "[]") {
1494                                 // avoid \citet[][]{a}
1495                                 before.erase();
1496                                 after.erase();
1497                         }
1498                         begin_inset(os, "LatexCommand ");
1499                         os << command << after << before
1500                            << '{' << p.verbatim_item() << "}\n";
1501                         end_inset(os);
1502                 }
1503
1504                 else if (use_jurabib &&
1505                          is_known(t.cs(), known_jurabib_commands)) {
1506                         context.check_layout(os);
1507                         string const command = '\\' + t.cs();
1508                         char argumentOrder = '\0';
1509                         vector<string> const & options = used_packages["jurabib"];
1510                         if (std::find(options.begin(), options.end(),
1511                                       "natbiborder") != options.end())
1512                                 argumentOrder = 'n';
1513                         else if (std::find(options.begin(), options.end(),
1514                                            "jurabiborder") != options.end())
1515                                 argumentOrder = 'j';
1516
1517                         // text before the citation
1518                         string before;
1519                         // text after the citation
1520                         string after;
1521
1522                         boost::tie(before, after) =
1523                                 getCiteArguments(p, argumentOrder != 'j');
1524                         string const citation = p.verbatim_item();
1525                         if (!before.empty() && argumentOrder == '\0') {
1526                                 cerr << "Warning: Assuming argument order "
1527                                      << "of jurabib version 0.6 for\n'"
1528                                      << command << before << after << '{'
1529                                      << citation << "}'.\n"
1530                                      << "Add 'jurabiborder' to the jurabib "
1531                                      << "package options if you used an\n"
1532                                      << "earlier jurabib version." << endl;
1533                         }
1534                         begin_inset(os, "LatexCommand ");
1535                         os << command << after << before
1536                            << '{' << citation << "}\n";
1537                         end_inset(os);
1538                 }
1539
1540                 else if (is_known(t.cs(), known_latex_commands)) {
1541                         // This needs to be after the check for natbib and
1542                         // jurabib commands, because "cite" has different
1543                         // arguments with natbib and jurabib.
1544                         context.check_layout(os);
1545                         begin_inset(os, "LatexCommand ");
1546                         os << '\\' << t.cs();
1547                         // lyx cannot handle newlines in a latex command
1548                         // FIXME: Move the substitution into parser::getOpt()?
1549                         os << subst(p.getOpt(), "\n", " ");
1550                         os << subst(p.getOpt(), "\n", " ");
1551                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1552                         end_inset(os);
1553                 }
1554
1555                 else if (is_known(t.cs(), known_quotes)) {
1556                         char const * const * where = is_known(t.cs(), known_quotes);
1557                         context.check_layout(os);
1558                         begin_inset(os, "Quotes ");
1559                         os << known_coded_quotes[where - known_quotes];
1560                         end_inset(os);
1561                         // LyX adds {} after the quote, so we have to eat
1562                         // spaces here if there are any before a possible
1563                         // {} pair.
1564                         eat_whitespace(p, os, context, false);
1565                         skip_braces(p);
1566                 }
1567
1568                 else if (is_known(t.cs(), known_sizes)) {
1569                         char const * const * where = is_known(t.cs(), known_sizes);
1570                         context.check_layout(os);
1571                         context.font.size = known_coded_sizes[where - known_sizes];
1572                         os << "\n\\size " << context.font.size << '\n';
1573                         eat_whitespace(p, os, context, false);
1574                 }
1575
1576                 else if (is_known(t.cs(), known_font_families)) {
1577                         char const * const * where =
1578                                 is_known(t.cs(), known_font_families);
1579                         context.check_layout(os);
1580                         context.font.family =
1581                                 known_coded_font_families[where - known_font_families];
1582                         os << "\n\\family " << context.font.family << '\n';
1583                         eat_whitespace(p, os, context, false);
1584                 }
1585
1586                 else if (is_known(t.cs(), known_font_series)) {
1587                         char const * const * where =
1588                                 is_known(t.cs(), known_font_series);
1589                         context.check_layout(os);
1590                         context.font.series =
1591                                 known_coded_font_series[where - known_font_series];
1592                         os << "\n\\series " << context.font.series << '\n';
1593                         eat_whitespace(p, os, context, false);
1594                 }
1595
1596                 else if (is_known(t.cs(), known_font_shapes)) {
1597                         char const * const * where =
1598                                 is_known(t.cs(), known_font_shapes);
1599                         context.check_layout(os);
1600                         context.font.shape =
1601                                 known_coded_font_shapes[where - known_font_shapes];
1602                         os << "\n\\shape " << context.font.shape << '\n';
1603                         eat_whitespace(p, os, context, false);
1604                 }
1605                 else if (is_known(t.cs(), known_old_font_families)) {
1606                         char const * const * where =
1607                                 is_known(t.cs(), known_old_font_families);
1608                         context.check_layout(os);
1609                         string oldsize = context.font.size;
1610                         context.font.init();
1611                         context.font.size = oldsize;
1612                         context.font.family =
1613                                 known_coded_font_families[where - known_old_font_families];
1614                         os << "\n\\family " << context.font.family << "\n"
1615                            <<   "\\series " << context.font.series << "\n"
1616                            <<   "\\shape "  << context.font.shape  << "\n";
1617                         eat_whitespace(p, os, context, false);
1618                 }
1619
1620                 else if (is_known(t.cs(), known_old_font_series)) {
1621                         char const * const * where =
1622                                 is_known(t.cs(), known_old_font_series);
1623                         context.check_layout(os);
1624                         string oldsize = context.font.size;
1625                         context.font.init();
1626                         context.font.size = oldsize;
1627                         context.font.series =
1628                                 known_coded_font_series[where - known_old_font_series];
1629                         os << "\n\\family " << context.font.family << "\n"
1630                            <<   "\\series " << context.font.series << "\n"
1631                            <<   "\\shape "  << context.font.shape  << "\n";
1632                         eat_whitespace(p, os, context, false);
1633                 }
1634
1635                 else if (is_known(t.cs(), known_old_font_shapes)) {
1636                         char const * const * where =
1637                                 is_known(t.cs(), known_old_font_shapes);
1638                         context.check_layout(os);
1639                         string oldsize = context.font.size;
1640                         context.font.init();
1641                         context.font.size = oldsize;
1642                         context.font.shape =
1643                                 known_coded_font_shapes[where - known_old_font_shapes];
1644                         os << "\n\\family " << context.font.family << "\n"
1645                            <<   "\\series " << context.font.series << "\n"
1646                            <<   "\\shape "  << context.font.shape  << "\n";
1647                         eat_whitespace(p, os, context, false);
1648                 }
1649
1650                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1651                          || t.cs() == "LaTeX") {
1652                         context.check_layout(os);
1653                         os << t.cs();
1654                         skip_braces(p); // eat {}
1655                 }
1656
1657                 else if (t.cs() == "LaTeXe") {
1658                         context.check_layout(os);
1659                         os << "LaTeX2e";
1660                         skip_braces(p); // eat {}
1661                 }
1662
1663                 else if (t.cs() == "ldots") {
1664                         context.check_layout(os);
1665                         skip_braces(p);
1666                         os << "\\SpecialChar \\ldots{}\n";
1667                 }
1668
1669                 else if (t.cs() == "lyxarrow") {
1670                         context.check_layout(os);
1671                         os << "\\SpecialChar \\menuseparator\n";
1672                         skip_braces(p);
1673                 }
1674
1675                 else if (t.cs() == "textcompwordmark") {
1676                         context.check_layout(os);
1677                         os << "\\SpecialChar \\textcompwordmark{}\n";
1678                         skip_braces(p);
1679                 }
1680
1681                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1682                         context.check_layout(os);
1683                         os << "\\SpecialChar \\@.\n";
1684                         p.get_token();
1685                 }
1686
1687                 else if (t.cs() == "-") {
1688                         context.check_layout(os);
1689                         os << "\\SpecialChar \\-\n";
1690                 }
1691
1692                 else if (t.cs() == "textasciitilde") {
1693                         context.check_layout(os);
1694                         os << '~';
1695                         skip_braces(p);
1696                 }
1697
1698                 else if (t.cs() == "textasciicircum") {
1699                         context.check_layout(os);
1700                         os << '^';
1701                         skip_braces(p);
1702                 }
1703
1704                 else if (t.cs() == "textbackslash") {
1705                         context.check_layout(os);
1706                         os << "\n\\backslash\n";
1707                         skip_braces(p);
1708                 }
1709
1710                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1711                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1712                             || t.cs() == "%") {
1713                         context.check_layout(os);
1714                         os << t.cs();
1715                 }
1716
1717                 else if (t.cs() == "char") {
1718                         context.check_layout(os);
1719                         if (p.next_token().character() == '`') {
1720                                 p.get_token();
1721                                 if (p.next_token().cs() == "\"") {
1722                                         p.get_token();
1723                                         os << '"';
1724                                         skip_braces(p);
1725                                 } else {
1726                                         handle_ert(os, "\\char`", context);
1727                                 }
1728                         } else {
1729                                 handle_ert(os, "\\char", context);
1730                         }
1731                 }
1732
1733                 else if (t.cs() == "\"") {
1734                         context.check_layout(os);
1735                         string const name = p.verbatim_item();
1736                              if (name == "a") os << 'ä';
1737                         else if (name == "o") os << 'ö';
1738                         else if (name == "u") os << 'ü';
1739                         else if (name == "A") os << 'Ä';
1740                         else if (name == "O") os << 'Ö';
1741                         else if (name == "U") os << 'Ü';
1742                         else handle_ert(os, "\"{" + name + "}", context);
1743                 }
1744
1745                 // Problem: \= creates a tabstop inside the tabbing environment
1746                 // and else an accent. In the latter case we really would want
1747                 // \={o} instead of \= o.
1748                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1749                         handle_ert(os, t.asInput(), context);
1750
1751                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1752                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1753                         // we need the trim as the LyX parser chokes on such spaces
1754                         context.check_layout(os);
1755                         os << "\n\\i \\" << t.cs() << "{"
1756                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1757                 }
1758
1759                 else if (t.cs() == "ss") {
1760                         context.check_layout(os);
1761                         os << "ß";
1762                 }
1763
1764                 else if (t.cs() == "i" || t.cs() == "j") {
1765                         context.check_layout(os);
1766                         os << "\\" << t.cs() << ' ';
1767                 }
1768
1769                 else if (t.cs() == "\\") {
1770                         context.check_layout(os);
1771                         string const next = p.next_token().asInput();
1772                         if (next == "[")
1773                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1774                         else if (next == "*") {
1775                                 p.get_token();
1776                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1777                         }
1778                         else {
1779                                 os << "\n\\newline\n";
1780                         }
1781                 }
1782
1783                 else if (t.cs() == "input" || t.cs() == "include"
1784                          || t.cs() == "verbatiminput") {
1785                         string name = '\\' + t.cs();
1786                         if (t.cs() == "verbatiminput"
1787                             && p.next_token().asInput() == "*")
1788                                 name += p.get_token().asInput();
1789                         context.check_layout(os);
1790                         begin_inset(os, "Include ");
1791                         string filename(p.getArg('{', '}'));
1792                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1793                         if (tex2lyx(filename, lyxname)) {
1794                                 os << name << '{' << lyxname << "}\n";
1795                         } else {
1796                                 os << name << '{' << filename << "}\n";
1797                         }
1798                         os << "preview false\n";
1799                         end_inset(os);
1800                 }
1801
1802                 else if (t.cs() == "fancyhead") {
1803                         context.check_layout(os);
1804                         ostringstream ss;
1805                         ss << "\\fancyhead";
1806                         ss << p.getOpt();
1807                         ss << '{' << p.verbatim_item() << "}\n";
1808                         handle_ert(os, ss.str(), context);
1809                 }
1810
1811                 else if (t.cs() == "bibliographystyle") {
1812                         // store new bibliographystyle
1813                         bibliographystyle = p.verbatim_item();
1814                         // output new bibliographystyle.
1815                         // This is only necessary if used in some other macro than \bibliography.
1816                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1817                 }
1818
1819                 else if (t.cs() == "bibliography") {
1820                         context.check_layout(os);
1821                         begin_inset(os, "LatexCommand ");
1822                         os << "\\bibtex";
1823                         // Do we have a bibliographystyle set?
1824                         if (!bibliographystyle.empty()) {
1825                                 os << '[' << bibliographystyle << ']';
1826                         }
1827                         os << '{' << p.verbatim_item() << "}\n";
1828                         end_inset(os);
1829                 }
1830
1831                 else if (t.cs() == "parbox")
1832                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1833
1834                 else if (t.cs() == "smallskip" ||
1835                          t.cs() == "medskip" ||
1836                          t.cs() == "bigskip" ||
1837                          t.cs() == "vfill") {
1838                         context.check_layout(os);
1839                         begin_inset(os, "VSpace ");
1840                         os << t.cs();
1841                         end_inset(os);
1842                         skip_braces(p);
1843                 }
1844
1845                 else if (t.cs() == "newcommand" ||
1846                          t.cs() == "providecommand" ||
1847                          t.cs() == "renewcommand") {
1848                         // these could be handled by parse_command(), but
1849                         // we need to call add_known_command() here.
1850                         string name = t.asInput();
1851                         if (p.next_token().asInput() == "*") {
1852                                 // Starred form. Eat '*'
1853                                 p.get_token();
1854                                 name += '*';
1855                         }
1856                         string const command = p.verbatim_item();
1857                         string const opt1 = p.getOpt();
1858                         string const opt2 = p.getFullOpt();
1859                         add_known_command(command, opt1, !opt2.empty());
1860                         string const ert = name + '{' + command + '}' +
1861                                            opt1 + opt2 +
1862                                            '{' + p.verbatim_item() + '}';
1863                         handle_ert(os, ert, context);
1864                 }
1865
1866                 else if (t.cs() == "vspace") {
1867                         bool starred = false;
1868                         if (p.next_token().asInput() == "*") {
1869                                 p.get_token();
1870                                 starred = true;
1871                         }
1872                         string const length = p.verbatim_item();
1873                         string unit;
1874                         string valstring;
1875                         bool valid = splitLatexLength(length, valstring, unit);
1876                         bool known_vspace = false;
1877                         bool known_unit = false;
1878                         double value;
1879                         if (valid) {
1880                                 istringstream iss(valstring);
1881                                 iss >> value;
1882                                 if (value == 1.0) {
1883                                         if (unit == "\\smallskipamount") {
1884                                                 unit = "smallskip";
1885                                                 known_vspace = true;
1886                                         } else if (unit == "\\medskipamount") {
1887                                                 unit = "medskip";
1888                                                 known_vspace = true;
1889                                         } else if (unit == "\\bigskipamount") {
1890                                                 unit = "bigskip";
1891                                                 known_vspace = true;
1892                                         } else if (unit == "\\fill") {
1893                                                 unit = "vfill";
1894                                                 known_vspace = true;
1895                                         }
1896                                 }
1897                                 if (!known_vspace) {
1898                                         switch (unitFromString(unit)) {
1899                                         case LyXLength::SP:
1900                                         case LyXLength::PT:
1901                                         case LyXLength::BP:
1902                                         case LyXLength::DD:
1903                                         case LyXLength::MM:
1904                                         case LyXLength::PC:
1905                                         case LyXLength::CC:
1906                                         case LyXLength::CM:
1907                                         case LyXLength::IN:
1908                                         case LyXLength::EX:
1909                                         case LyXLength::EM:
1910                                         case LyXLength::MU:
1911                                                 known_unit = true;
1912                                                 break;
1913                                         default:
1914                                                 break;
1915                                         }
1916                                 }
1917                         }
1918
1919                         if (known_unit || known_vspace) {
1920                                 // Literal length or known variable
1921                                 context.check_layout(os);
1922                                 begin_inset(os, "VSpace ");
1923                                 if (known_unit)
1924                                         os << value;
1925                                 os << unit;
1926                                 if (starred)
1927                                         os << '*';
1928                                 end_inset(os);
1929                         } else {
1930                                 // LyX can't handle other length variables in Inset VSpace
1931                                 string name = t.asInput();
1932                                 if (starred)
1933                                         name += '*';
1934                                 if (valid) {
1935                                         if (value == 1.0)
1936                                                 handle_ert(os, name + '{' + unit + '}', context);
1937                                         else if (value == -1.0)
1938                                                 handle_ert(os, name + "{-" + unit + '}', context);
1939                                         else
1940                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1941                                 } else
1942                                         handle_ert(os, name + '{' + length + '}', context);
1943                         }
1944                 }
1945
1946                 else {
1947                         //cerr << "#: " << t << " mode: " << mode << endl;
1948                         // heuristic: read up to next non-nested space
1949                         /*
1950                         string s = t.asInput();
1951                         string z = p.verbatim_item();
1952                         while (p.good() && z != " " && z.size()) {
1953                                 //cerr << "read: " << z << endl;
1954                                 s += z;
1955                                 z = p.verbatim_item();
1956                         }
1957                         cerr << "found ERT: " << s << endl;
1958                         handle_ert(os, s + ' ', context);
1959                         */
1960                         string name = t.asInput();
1961                         if (p.next_token().asInput() == "*") {
1962                                 // Starred commands like \vspace*{}
1963                                 p.get_token();                          // Eat '*'
1964                                 name += '*';
1965                         }
1966                         if (! parse_command(name, p, os, outer, context))
1967                                 handle_ert(os, name, context);
1968                 }
1969
1970                 if (flags & FLAG_LEAVE) {
1971                         flags &= ~FLAG_LEAVE;
1972                         break;
1973                 }
1974         }
1975 }
1976
1977
1978 // }])