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