]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
- Link against qt-mt333.lib which is what the current qt3 cvs produces
[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 << "\n\\size " << context.font.size
1002                                    << "\n";
1003                         else if (is_known(next.cs(), known_font_families))
1004                                 // s will change the font family, so we must
1005                                 // reset it here
1006                                 os << s << "\n\\family "
1007                                    << context.font.family << "\n";
1008                         else if (is_known(next.cs(), known_font_series))
1009                                 // s will change the font series, so we must
1010                                 // reset it here
1011                                 os << s << "\n\\series "
1012                                    << context.font.series << "\n";
1013                         else if (is_known(next.cs(), known_font_shapes))
1014                                 // s will change the font shape, so we must
1015                                 // reset it here
1016                                 os << s << "\n\\shape "
1017                                    << context.font.shape << "\n";
1018                         else if (is_known(next.cs(), known_old_font_families) ||
1019                                  is_known(next.cs(), known_old_font_series) ||
1020                                  is_known(next.cs(), known_old_font_shapes))
1021                                 // s will change the font family, series
1022                                 // and shape, so we must reset it here
1023                                 os << s
1024                                    <<  "\n\\family " << context.font.family
1025                                    << "\n\\series " << context.font.series
1026                                    << "\n\\shape "  << context.font.shape
1027                                    << "\n";
1028                         else {
1029                                 handle_ert(os, "{", context, false);
1030                                 // s will end the current layout and begin a
1031                                 // new one if necessary
1032                                 os << s;
1033                                 handle_ert(os, "}", context);
1034                         }
1035                 }
1036
1037                 else if (t.cat() == catEnd) {
1038                         if (flags & FLAG_BRACE_LAST) {
1039                                 return;
1040                         }
1041                         cerr << "stray '}' in text\n";
1042                         handle_ert(os, "}", context);
1043                 }
1044
1045                 else if (t.cat() == catComment)
1046                         parse_comment(p, os, t, context);
1047
1048                 //
1049                 // control sequences
1050                 //
1051
1052                 else if (t.cs() == "(") {
1053                         context.check_layout(os);
1054                         begin_inset(os, "Formula");
1055                         os << " \\(";
1056                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1057                         os << "\\)";
1058                         end_inset(os);
1059                 }
1060
1061                 else if (t.cs() == "[") {
1062                         context.check_layout(os);
1063                         begin_inset(os, "Formula");
1064                         os << " \\[";
1065                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1066                         os << "\\]";
1067                         end_inset(os);
1068                 }
1069
1070                 else if (t.cs() == "begin")
1071                         parse_environment(p, os, outer, context);
1072
1073                 else if (t.cs() == "end") {
1074                         if (flags & FLAG_END) {
1075                                 // eat environment name
1076                                 string const name = p.getArg('{', '}');
1077                                 if (name != active_environment())
1078                                         cerr << "\\end{" + name + "} does not match \\begin{"
1079                                                 + active_environment() + "}\n";
1080                                 return;
1081                         }
1082                         p.error("found 'end' unexpectedly");
1083                 }
1084
1085                 else if (t.cs() == "item") {
1086                         p.skip_spaces();
1087                         string s;
1088                         bool optarg = false;
1089                         if (p.next_token().character() == '[') {
1090                                 p.get_token(); // eat '['
1091                                 Context newcontext(false, context.textclass);
1092                                 newcontext.font = context.font;
1093                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1094                                 optarg = true;
1095                         }
1096                         context.set_item();
1097                         context.check_layout(os);
1098                         if (optarg) {
1099                                 if (context.layout->labeltype != LABEL_MANUAL) {
1100                                         // lyx does not support \item[\mybullet]
1101                                         // in itemize environments
1102                                         handle_ert(os, "[", context);
1103                                         os << s;
1104                                         handle_ert(os, "]", context);
1105                                 } else if (!s.empty()) {
1106                                         // The space is needed to separate the
1107                                         // item from the rest of the sentence.
1108                                         os << s << ' ';
1109                                         eat_whitespace(p, os, context, false);
1110                                 }
1111                         }
1112                 }
1113
1114                 else if (t.cs() == "bibitem") {
1115                         context.set_item();
1116                         context.check_layout(os);
1117                         os << "\\bibitem ";
1118                         os << p.getOpt();
1119                         os << '{' << p.verbatim_item() << '}' << "\n";
1120                 }
1121
1122                 else if (t.cs() == "def") {
1123                         context.check_layout(os);
1124                         eat_whitespace(p, os, context, false);
1125                         string name = p.get_token().cs();
1126                         while (p.next_token().cat() != catBegin)
1127                                 name += p.get_token().asString();
1128                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1129                 }
1130
1131                 else if (t.cs() == "noindent") {
1132                         p.skip_spaces();
1133                         context.add_extra_stuff("\\noindent ");
1134                 }
1135
1136                 else if (t.cs() == "appendix") {
1137                         p.skip_spaces();
1138                         context.add_extra_stuff("\\start_of_appendix ");
1139                 }
1140
1141                 // Must attempt to parse "Section*" before "Section".
1142                 else if ((p.next_token().asInput() == "*") &&
1143                          // The single '=' is meant here.
1144                          (newlayout = findLayout(context.textclass,
1145                                                  t.cs() + '*')).get() &&
1146                          newlayout->isCommand()) {
1147                         p.get_token();
1148                         output_command_layout(os, p, outer, context, newlayout);
1149                         p.skip_spaces();
1150                 }
1151
1152                 // The single '=' is meant here.
1153                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1154                          newlayout->isCommand()) {
1155                         output_command_layout(os, p, outer, context, newlayout);
1156                         p.skip_spaces();
1157                 }
1158
1159                 else if (t.cs() == "includegraphics") {
1160                         map<string, string> opts = split_map(p.getArg('[', ']'));
1161                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
1162
1163                         string const path = getMasterFilePath();
1164                         // We want to preserve relative / absolute filenames,
1165                         // therefore path is only used for testing
1166                         if (!fs::exists(MakeAbsPath(name, path))) {
1167                                 // The file extension is probably missing.
1168                                 // Now try to find it out.
1169                                 string const dvips_name =
1170                                         find_file(name, path,
1171                                                   known_dvips_graphics_formats);
1172                                 string const pdftex_name =
1173                                         find_file(name, path,
1174                                                   known_pdftex_graphics_formats);
1175                                 if (!dvips_name.empty()) {
1176                                         if (!pdftex_name.empty()) {
1177                                                 cerr << "This file contains the "
1178                                                         "latex snippet\n"
1179                                                         "\"\\includegraphics{"
1180                                                      << name << "}\".\n"
1181                                                         "However, files\n\""
1182                                                      << dvips_name << "\" and\n\""
1183                                                      << pdftex_name << "\"\n"
1184                                                         "both exist, so I had to make a "
1185                                                         "choice and took the first one.\n"
1186                                                         "Please move the unwanted one "
1187                                                         "someplace else and try again\n"
1188                                                         "if my choice was wrong."
1189                                                      << endl;
1190                                         }
1191                                         name = dvips_name;
1192                                 } else if (!pdftex_name.empty())
1193                                         name = pdftex_name;
1194
1195                                 if (!fs::exists(MakeAbsPath(name, path)))
1196                                         cerr << "Warning: Could not find graphics file '"
1197                                              << name << "'." << endl;
1198                         }
1199
1200                         context.check_layout(os);
1201                         begin_inset(os, "Graphics ");
1202                         os << "\n\tfilename " << name << '\n';
1203                         if (opts.find("width") != opts.end())
1204                                 os << "\twidth "
1205                                    << translate_len(opts["width"]) << '\n';
1206                         if (opts.find("height") != opts.end())
1207                                 os << "\theight "
1208                                    << translate_len(opts["height"]) << '\n';
1209                         if (opts.find("scale") != opts.end()) {
1210                                 istringstream iss(opts["scale"]);
1211                                 double val;
1212                                 iss >> val;
1213                                 val = val*100;
1214                                 os << "\tscale " << val << '\n';
1215                         }
1216                         if (opts.find("angle") != opts.end())
1217                                 os << "\trotateAngle "
1218                                    << opts["angle"] << '\n';
1219                         if (opts.find("origin") != opts.end()) {
1220                                 ostringstream ss;
1221                                 string const opt = opts["origin"];
1222                                 if (opt.find('l') != string::npos) ss << "left";
1223                                 if (opt.find('r') != string::npos) ss << "right";
1224                                 if (opt.find('c') != string::npos) ss << "center";
1225                                 if (opt.find('t') != string::npos) ss << "Top";
1226                                 if (opt.find('b') != string::npos) ss << "Bottom";
1227                                 if (opt.find('B') != string::npos) ss << "Baseline";
1228                                 if (!ss.str().empty())
1229                                         os << "\trotateOrigin " << ss.str() << '\n';
1230                                 else
1231                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1232                         }
1233                         if (opts.find("keepaspectratio") != opts.end())
1234                                 os << "\tkeepAspectRatio\n";
1235                         if (opts.find("clip") != opts.end())
1236                                 os << "\tclip\n";
1237                         if (opts.find("draft") != opts.end())
1238                                 os << "\tdraft\n";
1239                         if (opts.find("bb") != opts.end())
1240                                 os << "\tBoundingBox "
1241                                    << opts["bb"] << '\n';
1242                         int numberOfbbOptions = 0;
1243                         if (opts.find("bbllx") != opts.end())
1244                                 numberOfbbOptions++;
1245                         if (opts.find("bblly") != opts.end())
1246                                 numberOfbbOptions++;
1247                         if (opts.find("bburx") != opts.end())
1248                                 numberOfbbOptions++;
1249                         if (opts.find("bbury") != opts.end())
1250                                 numberOfbbOptions++;
1251                         if (numberOfbbOptions == 4)
1252                                 os << "\tBoundingBox "
1253                                    << opts["bbllx"] << opts["bblly"]
1254                                    << opts["bburx"] << opts["bbury"] << '\n';
1255                         else if (numberOfbbOptions > 0)
1256                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1257                         numberOfbbOptions = 0;
1258                         if (opts.find("natwidth") != opts.end())
1259                                 numberOfbbOptions++;
1260                         if (opts.find("natheight") != opts.end())
1261                                 numberOfbbOptions++;
1262                         if (numberOfbbOptions == 2)
1263                                 os << "\tBoundingBox 0bp 0bp "
1264                                    << opts["natwidth"] << opts["natheight"] << '\n';
1265                         else if (numberOfbbOptions > 0)
1266                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1267                         ostringstream special;
1268                         if (opts.find("hiresbb") != opts.end())
1269                                 special << "hiresbb,";
1270                         if (opts.find("trim") != opts.end())
1271                                 special << "trim,";
1272                         if (opts.find("viewport") != opts.end())
1273                                 special << "viewport=" << opts["viewport"] << ',';
1274                         if (opts.find("totalheight") != opts.end())
1275                                 special << "totalheight=" << opts["totalheight"] << ',';
1276                         if (opts.find("type") != opts.end())
1277                                 special << "type=" << opts["type"] << ',';
1278                         if (opts.find("ext") != opts.end())
1279                                 special << "ext=" << opts["ext"] << ',';
1280                         if (opts.find("read") != opts.end())
1281                                 special << "read=" << opts["read"] << ',';
1282                         if (opts.find("command") != opts.end())
1283                                 special << "command=" << opts["command"] << ',';
1284                         string s_special = special.str();
1285                         if (!s_special.empty()) {
1286                                 // We had special arguments. Remove the trailing ','.
1287                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1288                         }
1289                         // TODO: Handle the unknown settings better.
1290                         // Warn about invalid options.
1291                         // Check whether some option was given twice.
1292                         end_inset(os);
1293                 }
1294
1295                 else if (t.cs() == "footnote") {
1296                         p.skip_spaces();
1297                         context.check_layout(os);
1298                         begin_inset(os, "Foot\n");
1299                         os << "status collapsed\n\n";
1300                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1301                         end_inset(os);
1302                 }
1303
1304                 else if (t.cs() == "marginpar") {
1305                         p.skip_spaces();
1306                         context.check_layout(os);
1307                         begin_inset(os, "Marginal\n");
1308                         os << "status collapsed\n\n";
1309                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1310                         end_inset(os);
1311                 }
1312
1313                 else if (t.cs() == "ensuremath") {
1314                         p.skip_spaces();
1315                         context.check_layout(os);
1316                         Context newcontext(false, context.textclass);
1317                         newcontext.font = context.font;
1318                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1319                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1320                                 os << s;
1321                         else
1322                                 handle_ert(os, "\\ensuremath{" + s + "}",
1323                                            context);
1324                 }
1325
1326                 else if (t.cs() == "hfill") {
1327                         context.check_layout(os);
1328                         os << "\n\\hfill\n";
1329                         skip_braces(p);
1330                         p.skip_spaces();
1331                 }
1332
1333                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1334                         p.skip_spaces();
1335                         skip_braces(p); // swallow this
1336                 }
1337
1338                 else if (t.cs() == "tableofcontents") {
1339                         p.skip_spaces();
1340                         context.check_layout(os);
1341                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1342                         end_inset(os);
1343                         skip_braces(p); // swallow this
1344                 }
1345
1346                 else if (t.cs() == "listoffigures") {
1347                         p.skip_spaces();
1348                         context.check_layout(os);
1349                         begin_inset(os, "FloatList figure\n");
1350                         end_inset(os);
1351                         skip_braces(p); // swallow this
1352                 }
1353
1354                 else if (t.cs() == "listoftables") {
1355                         p.skip_spaces();
1356                         context.check_layout(os);
1357                         begin_inset(os, "FloatList table\n");
1358                         end_inset(os);
1359                         skip_braces(p); // swallow this
1360                 }
1361
1362                 else if (t.cs() == "listof") {
1363                         p.skip_spaces(true);
1364                         string const name = p.get_token().asString();
1365                         if (context.textclass.floats().typeExist(name)) {
1366                                 context.check_layout(os);
1367                                 begin_inset(os, "FloatList ");
1368                                 os << name << "\n";
1369                                 end_inset(os);
1370                                 p.get_token(); // swallow second arg
1371                         } else
1372                                 handle_ert(os, "\\listof{" + name + "}", context);
1373                 }
1374
1375                 else if (t.cs() == "textrm")
1376                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1377                                               context, "\\family",
1378                                               context.font.family, "roman");
1379
1380                 else if (t.cs() == "textsf")
1381                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1382                                               context, "\\family",
1383                                               context.font.family, "sans");
1384
1385                 else if (t.cs() == "texttt")
1386                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1387                                               context, "\\family",
1388                                               context.font.family, "typewriter");
1389
1390                 else if (t.cs() == "textmd")
1391                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1392                                               context, "\\series",
1393                                               context.font.series, "medium");
1394
1395                 else if (t.cs() == "textbf")
1396                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1397                                               context, "\\series",
1398                                               context.font.series, "bold");
1399
1400                 else if (t.cs() == "textup")
1401                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1402                                               context, "\\shape",
1403                                               context.font.shape, "up");
1404
1405                 else if (t.cs() == "textit")
1406                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1407                                               context, "\\shape",
1408                                               context.font.shape, "italic");
1409
1410                 else if (t.cs() == "textsl")
1411                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1412                                               context, "\\shape",
1413                                               context.font.shape, "slanted");
1414
1415                 else if (t.cs() == "textsc")
1416                         parse_text_attributes(p, os, FLAG_ITEM, outer,
1417                                               context, "\\shape",
1418                                               context.font.shape, "smallcaps");
1419
1420                 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1421                         context.check_layout(os);
1422                         Font oldFont = context.font;
1423                         context.font.init();
1424                         context.font.size = oldFont.size;
1425                         os << "\n\\family " << context.font.family << "\n";
1426                         os << "\n\\series " << context.font.series << "\n";
1427                         os << "\n\\shape " << context.font.shape << "\n";
1428                         if (t.cs() == "textnormal") {
1429                                 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1430                                 context.font = oldFont;
1431                                 os << "\n\\shape " << oldFont.shape << "\n";
1432                                 os << "\n\\series " << oldFont.series << "\n";
1433                                 os << "\n\\family " << oldFont.family << "\n";
1434                         } else
1435                                 eat_whitespace(p, os, context, false);
1436                 }
1437
1438                 else if (t.cs() == "underbar") {
1439                         // Do NOT handle \underline.
1440                         // \underbar cuts through y, g, q, p etc.,
1441                         // \underline does not.
1442                         context.check_layout(os);
1443                         os << "\n\\bar under\n";
1444                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1445                         os << "\n\\bar default\n";
1446                 }
1447
1448                 else if (t.cs() == "emph" || t.cs() == "noun") {
1449                         context.check_layout(os);
1450                         os << "\n\\" << t.cs() << " on\n";
1451                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1452                         os << "\n\\" << t.cs() << " default\n";
1453                 }
1454
1455                 else if (use_natbib &&
1456                          is_known(t.cs(), known_natbib_commands) &&
1457                          ((t.cs() != "citefullauthor" &&
1458                            t.cs() != "citeyear" &&
1459                            t.cs() != "citeyearpar") ||
1460                           p.next_token().asInput() != "*")) {
1461                         context.check_layout(os);
1462                         // tex                       lyx
1463                         // \citet[before][after]{a}  \citet[after][before]{a}
1464                         // \citet[before][]{a}       \citet[][before]{a}
1465                         // \citet[after]{a}          \citet[after]{a}
1466                         // \citet{a}                 \citet{a}
1467                         string command = '\\' + t.cs();
1468                         if (p.next_token().asInput() == "*") {
1469                                 command += '*';
1470                                 p.get_token();
1471                         }
1472                         if (command == "\\citefullauthor")
1473                                 // alternative name for "\\citeauthor*"
1474                                 command = "\\citeauthor*";
1475
1476                         // text before the citation
1477                         string before;
1478                         // text after the citation
1479                         string after;
1480
1481                         boost::tie(before, after) = getCiteArguments(p, true);
1482                         if (command == "\\cite") {
1483                                 // \cite without optional argument means
1484                                 // \citet, \cite with at least one optional
1485                                 // argument means \citep.
1486                                 if (before.empty() && after.empty())
1487                                         command = "\\citet";
1488                                 else
1489                                         command = "\\citep";
1490                         }
1491                         if (before.empty() && after == "[]")
1492                                 // avoid \citet[]{a}
1493                                 after.erase();
1494                         else if (before == "[]" && after == "[]") {
1495                                 // avoid \citet[][]{a}
1496                                 before.erase();
1497                                 after.erase();
1498                         }
1499                         begin_inset(os, "LatexCommand ");
1500                         os << command << after << before
1501                            << '{' << p.verbatim_item() << "}\n";
1502                         end_inset(os);
1503                 }
1504
1505                 else if (use_jurabib &&
1506                          is_known(t.cs(), known_jurabib_commands)) {
1507                         context.check_layout(os);
1508                         string const command = '\\' + t.cs();
1509                         char argumentOrder = '\0';
1510                         vector<string> const & options = used_packages["jurabib"];
1511                         if (std::find(options.begin(), options.end(),
1512                                       "natbiborder") != options.end())
1513                                 argumentOrder = 'n';
1514                         else if (std::find(options.begin(), options.end(),
1515                                            "jurabiborder") != options.end())
1516                                 argumentOrder = 'j';
1517
1518                         // text before the citation
1519                         string before;
1520                         // text after the citation
1521                         string after;
1522
1523                         boost::tie(before, after) =
1524                                 getCiteArguments(p, argumentOrder != 'j');
1525                         string const citation = p.verbatim_item();
1526                         if (!before.empty() && argumentOrder == '\0') {
1527                                 cerr << "Warning: Assuming argument order "
1528                                      << "of jurabib version 0.6 for\n'"
1529                                      << command << before << after << '{'
1530                                      << citation << "}'.\n"
1531                                      << "Add 'jurabiborder' to the jurabib "
1532                                      << "package options if you used an\n"
1533                                      << "earlier jurabib version." << endl;
1534                         }
1535                         begin_inset(os, "LatexCommand ");
1536                         os << command << after << before
1537                            << '{' << citation << "}\n";
1538                         end_inset(os);
1539                 }
1540
1541                 else if (is_known(t.cs(), known_latex_commands)) {
1542                         // This needs to be after the check for natbib and
1543                         // jurabib commands, because "cite" has different
1544                         // arguments with natbib and jurabib.
1545                         context.check_layout(os);
1546                         begin_inset(os, "LatexCommand ");
1547                         os << '\\' << t.cs();
1548                         // lyx cannot handle newlines in a latex command
1549                         // FIXME: Move the substitution into parser::getOpt()?
1550                         os << subst(p.getOpt(), "\n", " ");
1551                         os << subst(p.getOpt(), "\n", " ");
1552                         os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1553                         end_inset(os);
1554                 }
1555
1556                 else if (is_known(t.cs(), known_quotes)) {
1557                         char const * const * where = is_known(t.cs(), known_quotes);
1558                         context.check_layout(os);
1559                         begin_inset(os, "Quotes ");
1560                         os << known_coded_quotes[where - known_quotes];
1561                         end_inset(os);
1562                         // LyX adds {} after the quote, so we have to eat
1563                         // spaces here if there are any before a possible
1564                         // {} pair.
1565                         eat_whitespace(p, os, context, false);
1566                         skip_braces(p);
1567                 }
1568
1569                 else if (is_known(t.cs(), known_sizes)) {
1570                         char const * const * where = is_known(t.cs(), known_sizes);
1571                         context.check_layout(os);
1572                         context.font.size = known_coded_sizes[where - known_sizes];
1573                         os << "\n\\size " << context.font.size << '\n';
1574                         eat_whitespace(p, os, context, false);
1575                 }
1576
1577                 else if (is_known(t.cs(), known_font_families)) {
1578                         char const * const * where =
1579                                 is_known(t.cs(), known_font_families);
1580                         context.check_layout(os);
1581                         context.font.family =
1582                                 known_coded_font_families[where - known_font_families];
1583                         os << "\n\\family " << context.font.family << '\n';
1584                         eat_whitespace(p, os, context, false);
1585                 }
1586
1587                 else if (is_known(t.cs(), known_font_series)) {
1588                         char const * const * where =
1589                                 is_known(t.cs(), known_font_series);
1590                         context.check_layout(os);
1591                         context.font.series =
1592                                 known_coded_font_series[where - known_font_series];
1593                         os << "\n\\series " << context.font.series << '\n';
1594                         eat_whitespace(p, os, context, false);
1595                 }
1596
1597                 else if (is_known(t.cs(), known_font_shapes)) {
1598                         char const * const * where =
1599                                 is_known(t.cs(), known_font_shapes);
1600                         context.check_layout(os);
1601                         context.font.shape =
1602                                 known_coded_font_shapes[where - known_font_shapes];
1603                         os << "\n\\shape " << context.font.shape << '\n';
1604                         eat_whitespace(p, os, context, false);
1605                 }
1606                 else if (is_known(t.cs(), known_old_font_families)) {
1607                         char const * const * where =
1608                                 is_known(t.cs(), known_old_font_families);
1609                         context.check_layout(os);
1610                         string oldsize = context.font.size;
1611                         context.font.init();
1612                         context.font.size = oldsize;
1613                         context.font.family =
1614                                 known_coded_font_families[where - known_old_font_families];
1615                         os << "\n\\family " << context.font.family << "\n"
1616                            <<   "\\series " << context.font.series << "\n"
1617                            <<   "\\shape "  << context.font.shape  << "\n";
1618                         eat_whitespace(p, os, context, false);
1619                 }
1620
1621                 else if (is_known(t.cs(), known_old_font_series)) {
1622                         char const * const * where =
1623                                 is_known(t.cs(), known_old_font_series);
1624                         context.check_layout(os);
1625                         string oldsize = context.font.size;
1626                         context.font.init();
1627                         context.font.size = oldsize;
1628                         context.font.series =
1629                                 known_coded_font_series[where - known_old_font_series];
1630                         os << "\n\\family " << context.font.family << "\n"
1631                            <<   "\\series " << context.font.series << "\n"
1632                            <<   "\\shape "  << context.font.shape  << "\n";
1633                         eat_whitespace(p, os, context, false);
1634                 }
1635
1636                 else if (is_known(t.cs(), known_old_font_shapes)) {
1637                         char const * const * where =
1638                                 is_known(t.cs(), known_old_font_shapes);
1639                         context.check_layout(os);
1640                         string oldsize = context.font.size;
1641                         context.font.init();
1642                         context.font.size = oldsize;
1643                         context.font.shape =
1644                                 known_coded_font_shapes[where - known_old_font_shapes];
1645                         os << "\n\\family " << context.font.family << "\n"
1646                            <<   "\\series " << context.font.series << "\n"
1647                            <<   "\\shape "  << context.font.shape  << "\n";
1648                         eat_whitespace(p, os, context, false);
1649                 }
1650
1651                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1652                          || t.cs() == "LaTeX") {
1653                         context.check_layout(os);
1654                         os << t.cs();
1655                         skip_braces(p); // eat {}
1656                 }
1657
1658                 else if (t.cs() == "LaTeXe") {
1659                         context.check_layout(os);
1660                         os << "LaTeX2e";
1661                         skip_braces(p); // eat {}
1662                 }
1663
1664                 else if (t.cs() == "ldots") {
1665                         context.check_layout(os);
1666                         skip_braces(p);
1667                         os << "\\SpecialChar \\ldots{}\n";
1668                 }
1669
1670                 else if (t.cs() == "lyxarrow") {
1671                         context.check_layout(os);
1672                         os << "\\SpecialChar \\menuseparator\n";
1673                         skip_braces(p);
1674                 }
1675
1676                 else if (t.cs() == "textcompwordmark") {
1677                         context.check_layout(os);
1678                         os << "\\SpecialChar \\textcompwordmark{}\n";
1679                         skip_braces(p);
1680                 }
1681
1682                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1683                         context.check_layout(os);
1684                         os << "\\SpecialChar \\@.\n";
1685                         p.get_token();
1686                 }
1687
1688                 else if (t.cs() == "-") {
1689                         context.check_layout(os);
1690                         os << "\\SpecialChar \\-\n";
1691                 }
1692
1693                 else if (t.cs() == "textasciitilde") {
1694                         context.check_layout(os);
1695                         os << '~';
1696                         skip_braces(p);
1697                 }
1698
1699                 else if (t.cs() == "textasciicircum") {
1700                         context.check_layout(os);
1701                         os << '^';
1702                         skip_braces(p);
1703                 }
1704
1705                 else if (t.cs() == "textbackslash") {
1706                         context.check_layout(os);
1707                         os << "\n\\backslash\n";
1708                         skip_braces(p);
1709                 }
1710
1711                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1712                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1713                             || t.cs() == "%") {
1714                         context.check_layout(os);
1715                         os << t.cs();
1716                 }
1717
1718                 else if (t.cs() == "char") {
1719                         context.check_layout(os);
1720                         if (p.next_token().character() == '`') {
1721                                 p.get_token();
1722                                 if (p.next_token().cs() == "\"") {
1723                                         p.get_token();
1724                                         os << '"';
1725                                         skip_braces(p);
1726                                 } else {
1727                                         handle_ert(os, "\\char`", context);
1728                                 }
1729                         } else {
1730                                 handle_ert(os, "\\char", context);
1731                         }
1732                 }
1733
1734                 else if (t.cs() == "\"") {
1735                         context.check_layout(os);
1736                         string const name = p.verbatim_item();
1737                              if (name == "a") os << 'ä';
1738                         else if (name == "o") os << 'ö';
1739                         else if (name == "u") os << 'ü';
1740                         else if (name == "A") os << 'Ä';
1741                         else if (name == "O") os << 'Ö';
1742                         else if (name == "U") os << 'Ü';
1743                         else handle_ert(os, "\"{" + name + "}", context);
1744                 }
1745
1746                 // Problem: \= creates a tabstop inside the tabbing environment
1747                 // and else an accent. In the latter case we really would want
1748                 // \={o} instead of \= o.
1749                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1750                         handle_ert(os, t.asInput(), context);
1751
1752                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1753                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1754                         // we need the trim as the LyX parser chokes on such spaces
1755                         context.check_layout(os);
1756                         os << "\n\\i \\" << t.cs() << "{"
1757                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1758                 }
1759
1760                 else if (t.cs() == "ss") {
1761                         context.check_layout(os);
1762                         os << "ß";
1763                 }
1764
1765                 else if (t.cs() == "i" || t.cs() == "j") {
1766                         context.check_layout(os);
1767                         os << "\\" << t.cs() << ' ';
1768                 }
1769
1770                 else if (t.cs() == "\\") {
1771                         context.check_layout(os);
1772                         string const next = p.next_token().asInput();
1773                         if (next == "[")
1774                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1775                         else if (next == "*") {
1776                                 p.get_token();
1777                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1778                         }
1779                         else {
1780                                 os << "\n\\newline\n";
1781                         }
1782                 }
1783
1784                 else if (t.cs() == "input" || t.cs() == "include"
1785                          || t.cs() == "verbatiminput") {
1786                         string name = '\\' + t.cs();
1787                         if (t.cs() == "verbatiminput"
1788                             && p.next_token().asInput() == "*")
1789                                 name += p.get_token().asInput();
1790                         context.check_layout(os);
1791                         begin_inset(os, "Include ");
1792                         string filename(p.getArg('{', '}'));
1793                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1794                         if (tex2lyx(filename, lyxname)) {
1795                                 os << name << '{' << lyxname << "}\n";
1796                         } else {
1797                                 os << name << '{' << filename << "}\n";
1798                         }
1799                         os << "preview false\n";
1800                         end_inset(os);
1801                 }
1802
1803                 else if (t.cs() == "fancyhead") {
1804                         context.check_layout(os);
1805                         ostringstream ss;
1806                         ss << "\\fancyhead";
1807                         ss << p.getOpt();
1808                         ss << '{' << p.verbatim_item() << "}\n";
1809                         handle_ert(os, ss.str(), context);
1810                 }
1811
1812                 else if (t.cs() == "bibliographystyle") {
1813                         // store new bibliographystyle
1814                         bibliographystyle = p.verbatim_item();
1815                         // output new bibliographystyle.
1816                         // This is only necessary if used in some other macro than \bibliography.
1817                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1818                 }
1819
1820                 else if (t.cs() == "bibliography") {
1821                         context.check_layout(os);
1822                         begin_inset(os, "LatexCommand ");
1823                         os << "\\bibtex";
1824                         // Do we have a bibliographystyle set?
1825                         if (!bibliographystyle.empty()) {
1826                                 os << '[' << bibliographystyle << ']';
1827                         }
1828                         os << '{' << p.verbatim_item() << "}\n";
1829                         end_inset(os);
1830                 }
1831
1832                 else if (t.cs() == "parbox")
1833                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1834
1835                 else if (t.cs() == "smallskip" ||
1836                          t.cs() == "medskip" ||
1837                          t.cs() == "bigskip" ||
1838                          t.cs() == "vfill") {
1839                         context.check_layout(os);
1840                         begin_inset(os, "VSpace ");
1841                         os << t.cs();
1842                         end_inset(os);
1843                         skip_braces(p);
1844                 }
1845
1846                 else if (t.cs() == "newcommand" ||
1847                          t.cs() == "providecommand" ||
1848                          t.cs() == "renewcommand") {
1849                         // these could be handled by parse_command(), but
1850                         // we need to call add_known_command() here.
1851                         string name = t.asInput();
1852                         if (p.next_token().asInput() == "*") {
1853                                 // Starred form. Eat '*'
1854                                 p.get_token();
1855                                 name += '*';
1856                         }
1857                         string const command = p.verbatim_item();
1858                         string const opt1 = p.getOpt();
1859                         string const opt2 = p.getFullOpt();
1860                         add_known_command(command, opt1, !opt2.empty());
1861                         string const ert = name + '{' + command + '}' +
1862                                            opt1 + opt2 +
1863                                            '{' + p.verbatim_item() + '}';
1864                         handle_ert(os, ert, context);
1865                 }
1866
1867                 else if (t.cs() == "vspace") {
1868                         bool starred = false;
1869                         if (p.next_token().asInput() == "*") {
1870                                 p.get_token();
1871                                 starred = true;
1872                         }
1873                         string const length = p.verbatim_item();
1874                         string unit;
1875                         string valstring;
1876                         bool valid = splitLatexLength(length, valstring, unit);
1877                         bool known_vspace = false;
1878                         bool known_unit = false;
1879                         double value;
1880                         if (valid) {
1881                                 istringstream iss(valstring);
1882                                 iss >> value;
1883                                 if (value == 1.0) {
1884                                         if (unit == "\\smallskipamount") {
1885                                                 unit = "smallskip";
1886                                                 known_vspace = true;
1887                                         } else if (unit == "\\medskipamount") {
1888                                                 unit = "medskip";
1889                                                 known_vspace = true;
1890                                         } else if (unit == "\\bigskipamount") {
1891                                                 unit = "bigskip";
1892                                                 known_vspace = true;
1893                                         } else if (unit == "\\fill") {
1894                                                 unit = "vfill";
1895                                                 known_vspace = true;
1896                                         }
1897                                 }
1898                                 if (!known_vspace) {
1899                                         switch (unitFromString(unit)) {
1900                                         case LyXLength::SP:
1901                                         case LyXLength::PT:
1902                                         case LyXLength::BP:
1903                                         case LyXLength::DD:
1904                                         case LyXLength::MM:
1905                                         case LyXLength::PC:
1906                                         case LyXLength::CC:
1907                                         case LyXLength::CM:
1908                                         case LyXLength::IN:
1909                                         case LyXLength::EX:
1910                                         case LyXLength::EM:
1911                                         case LyXLength::MU:
1912                                                 known_unit = true;
1913                                                 break;
1914                                         default:
1915                                                 break;
1916                                         }
1917                                 }
1918                         }
1919
1920                         if (known_unit || known_vspace) {
1921                                 // Literal length or known variable
1922                                 context.check_layout(os);
1923                                 begin_inset(os, "VSpace ");
1924                                 if (known_unit)
1925                                         os << value;
1926                                 os << unit;
1927                                 if (starred)
1928                                         os << '*';
1929                                 end_inset(os);
1930                         } else {
1931                                 // LyX can't handle other length variables in Inset VSpace
1932                                 string name = t.asInput();
1933                                 if (starred)
1934                                         name += '*';
1935                                 if (valid) {
1936                                         if (value == 1.0)
1937                                                 handle_ert(os, name + '{' + unit + '}', context);
1938                                         else if (value == -1.0)
1939                                                 handle_ert(os, name + "{-" + unit + '}', context);
1940                                         else
1941                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1942                                 } else
1943                                         handle_ert(os, name + '{' + length + '}', context);
1944                         }
1945                 }
1946
1947                 else {
1948                         //cerr << "#: " << t << " mode: " << mode << endl;
1949                         // heuristic: read up to next non-nested space
1950                         /*
1951                         string s = t.asInput();
1952                         string z = p.verbatim_item();
1953                         while (p.good() && z != " " && z.size()) {
1954                                 //cerr << "read: " << z << endl;
1955                                 s += z;
1956                                 z = p.verbatim_item();
1957                         }
1958                         cerr << "found ERT: " << s << endl;
1959                         handle_ert(os, s + ' ', context);
1960                         */
1961                         string name = t.asInput();
1962                         if (p.next_token().asInput() == "*") {
1963                                 // Starred commands like \vspace*{}
1964                                 p.get_token();                          // Eat '*'
1965                                 name += '*';
1966                         }
1967                         if (! parse_command(name, p, os, outer, context))
1968                                 handle_ert(os, name, context);
1969                 }
1970
1971                 if (flags & FLAG_LEAVE) {
1972                         flags &= ~FLAG_LEAVE;
1973                         break;
1974                 }
1975         }
1976 }
1977
1978
1979 // }])