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