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