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