]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/text.C
fix bug 1446 (tex2lyx nesting)
[lyx.git] / src / tex2lyx / text.C
1 /**
2  * \file tex2lyx/text.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Jean-Marc Lasgouttes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 // {[(
13
14 #include <config.h>
15
16 #include "tex2lyx.h"
17 #include "context.h"
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/tostr.h"
22 #include "support/filetools.h"
23
24 #include <iostream>
25 #include <map>
26 #include <sstream>
27 #include <vector>
28
29 using lyx::support::rtrim;
30 using lyx::support::suffixIs;
31 using lyx::support::contains;
32 using lyx::support::subst;
33
34 using std::cerr;
35 using std::endl;
36
37 using std::map;
38 using std::ostream;
39 using std::ostringstream;
40 using std::istringstream;
41 using std::string;
42 using std::vector;
43
44
45 // thin wrapper around parse_text using a string
46 string parse_text(Parser & p, unsigned flags, const bool outer,
47                   Context & context)
48 {
49         ostringstream os;
50         parse_text(p, os, flags, outer, context);
51         return os.str();
52 }
53
54 // parses a subdocument, usually useful in insets (whence the name)
55 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
56                 Context & context)
57 {
58         Context newcontext(true, context.textclass);
59         parse_text(p, os, flags, outer, newcontext);
60         newcontext.check_end_layout(os);
61 }
62
63
64 // parses a paragraph snippet, useful for example for \emph{...}
65 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
66                 Context & context)
67 {
68         Context newcontext(false, context.textclass);
69         parse_text(p, os, flags, outer, newcontext);
70         // should not be needed
71         newcontext.check_end_layout(os);
72 }
73
74
75 namespace {
76
77 char const * known_latex_commands[] = { "ref", "cite", "label", "index",
78 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
79
80 // LaTeX names for quotes
81 char const * known_quotes[] = { "glqq", "grqq", "quotedblbase",
82 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
83
84 // the same as known_quotes with .lyx names
85 char const * known_coded_quotes[] = { "gld", "grd", "gld",
86 "grd", "gls", "fls", "frd", 0};
87
88 char const * known_sizes[] = { "tiny", "scriptsize", "footnotesize",
89 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
90
91 char const * known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
92 "small", "normal", "large", "larger", "largest",  "huge", "giant", 0};
93
94 // splits "x=z, y=b" into a map
95 map<string, string> split_map(string const & s)
96 {
97         map<string, string> res;
98         vector<string> v;
99         split(s, v);
100         for (size_t i = 0; i < v.size(); ++i) {
101                 size_t const pos   = v[i].find('=');
102                 string const index = v[i].substr(0, pos);
103                 string const value = v[i].substr(pos + 1, string::npos);
104                 res[trim(index)] = trim(value);
105         }
106         return res;
107 }
108
109
110 /*!
111  * Split a LaTeX length into value and unit.
112  * The latter can be a real unit like "pt", or a latex length variable
113  * like "\textwidth". The unit may contain additional stuff like glue
114  * lengths, but we don't care, because such lengths are ERT anyway.
115  * \return true if \param value and \param unit are valid.
116  */
117 bool splitLatexLength(string const & len, string & value, string & unit)
118 {
119         if (len.empty())
120                 return false;
121         const string::size_type i = len.find_first_not_of(" -+0123456789.,");
122         //'4,5' is a valid LaTeX length number. Change it to '4.5'
123         string const length = subst(len, ',', '.');
124         if (i == string::npos)
125                 return false;
126         if (i == 0) {
127                 if (len[0] == '\\') {
128                         // We had something like \textwidth without a factor
129                         value = "1.0";
130                 } else {
131                         return false;
132                 }
133         } else {
134                 value = trim(string(length, 0, i));
135         }
136         if (value == "-")
137                 value = "-1.0";
138         // 'cM' is a valid LaTeX length unit. Change it to 'cm'
139         if (contains(len, '\\'))
140                 unit = trim(string(len, i));
141         else
142                 unit = lyx::support::lowercase(trim(string(len, i)));
143         return true;
144 }
145
146
147 /// A simple function to translate a latex length to something lyx can
148 /// understand. Not perfect, but rather best-effort.
149 bool translate_len(string const & length, string & valstring, string & unit)
150 {
151         if (!splitLatexLength(length, valstring, unit))
152                 return false;
153         // LyX uses percent values
154         double value;
155         istringstream iss(valstring);
156         iss >> value;
157         value *= 100;
158         ostringstream oss;
159         oss << value;
160         string const percentval = oss.str();
161         // a normal length
162         if (unit.empty() || unit[0] != '\\')
163                 return true;
164         string::size_type const i = unit.find(' ');
165         string const endlen = (i == string::npos) ? string() : string(unit, i);
166         if (unit == "\\textwidth") {
167                 valstring = percentval;
168                 unit = "text%" + endlen;
169         } else if (unit == "\\columnwidth") {
170                 valstring = percentval;
171                 unit = "col%" + endlen;
172         } else if (unit == "\\paperwidth") {
173                 valstring = percentval;
174                 unit = "page%" + endlen;
175         } else if (unit == "\\linewidth") {
176                 valstring = percentval;
177                 unit = "line%" + endlen;
178         } else if (unit == "\\paperheight") {
179                 valstring = percentval;
180                 unit = "pheight%" + endlen;
181         } else if (unit == "\\textheight") {
182                 valstring = percentval;
183                 unit = "theight%" + endlen;
184         }
185         return true;
186 }
187
188
189 string translate_len(string const & length)
190 {
191         string unit;
192         string value;
193         if (translate_len(length, value, unit))
194                 return value + unit;
195         // If the input is invalid, return what we have.
196         return length;
197 }
198
199
200 /*!
201  * Translates a LaTeX length into \param value, \param unit and
202  * \param special parts suitable for a box inset.
203  * The difference from translate_len() is that a box inset knows about
204  * some special "units" that are stored in \param special.
205  */
206 void translate_box_len(string const & length, string & value, string & unit, string & special)
207 {
208         if (translate_len(length, value, unit)) {
209                 if (unit == "\\height" || unit == "\\depth" ||
210                     unit == "\\totalheight" || unit == "\\width") {
211                         special = unit.substr(1);
212                         // The unit is not used, but LyX requires a dummy setting
213                         unit = "in";
214                 } else
215                         special = "none";
216         } else {
217                 value.clear();
218                 unit = length;
219                 special = "none";
220         }
221 }
222
223
224 void begin_inset(ostream & os, string const & name)
225 {
226         os << "\n\\begin_inset " << name;
227 }
228
229
230 void end_inset(ostream & os)
231 {
232         os << "\n\\end_inset \n\n";
233 }
234
235
236 void skip_braces(Parser & p)
237 {
238         if (p.next_token().cat() != catBegin)
239                 return;
240         p.get_token();
241         if (p.next_token().cat() == catEnd) {
242                 p.get_token();
243                 return;
244         }
245         p.putback();
246 }
247
248
249 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
250 {
251         if (check_layout) {
252                 // We must have a valid layout before outputting the ERT inset.
253                 context.check_layout(os);
254         }
255         Context newcontext(true, context.textclass);
256         begin_inset(os, "ERT");
257         os << "\nstatus collapsed\n";
258         newcontext.check_layout(os);
259         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
260                 if (*it == '\\')
261                         os << "\n\\backslash \n";
262                 else if (*it == '\n')
263                         os << "\n\\newline \n";
264                 else
265                         os << *it;
266         }
267         newcontext.check_end_layout(os);
268         end_inset(os);
269 }
270
271
272 void handle_comment(ostream & os, string const & s, Context & context)
273 {
274         // TODO: Handle this better
275         Context newcontext(true, context.textclass);
276         begin_inset(os, "ERT");
277         os << "\nstatus collapsed\n";
278         newcontext.check_layout(os);
279         for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
280                 if (*it == '\\')
281                         os << "\n\\backslash \n";
282                 else
283                         os << *it;
284         }
285         // make sure that our comment is the last thing on the line
286         os << "\n\\newline";
287         newcontext.check_end_layout(os);
288         end_inset(os);
289 }
290
291
292 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
293 public:
294         isLayout(string const name) : name_(name) {}
295         bool operator()(LyXLayout_ptr const & ptr) const {
296                 return ptr->latexname() == name_;
297         }
298 private:
299         string const name_;
300 };
301
302
303 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
304                          string const & name)
305 {
306         LyXTextClass::const_iterator beg  = textclass.begin();
307         LyXTextClass::const_iterator end = textclass.end();
308
309         LyXTextClass::const_iterator
310                 it = std::find_if(beg, end, isLayout(name));
311
312         return (it == end) ? LyXLayout_ptr() : *it;
313 }
314
315
316 void eat_whitespace(Parser &, ostream &, Context &, bool);
317
318
319 void output_command_layout(ostream & os, Parser & p, bool outer,
320                            Context & parent_context,
321                            LyXLayout_ptr newlayout)
322 {
323         parent_context.check_end_layout(os);
324         Context context(true, parent_context.textclass, newlayout,
325                         parent_context.layout);
326         if (parent_context.deeper_paragraph) {
327                 // We are beginning a nested environment after a
328                 // deeper paragraph inside the outer list environment.
329                 // Therefore we don't need to output a "begin deeper".
330                 context.need_end_deeper = true;
331         }
332         context.check_deeper(os);
333         context.check_layout(os);
334         if (context.layout->optionalargs > 0) {
335                 eat_whitespace(p, os, context, false);
336                 if (p.next_token().character() == '[') {
337                         p.get_token(); // eat '['
338                         begin_inset(os, "OptArg\n");
339                         os << "status collapsed\n\n";
340                         parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
341                         end_inset(os);
342                         eat_whitespace(p, os, context, false);
343                 }
344         }
345         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
346         context.check_end_layout(os);
347         if (parent_context.deeper_paragraph) {
348                 // We must suppress the "end deeper" because we
349                 // suppressed the "begin deeper" above.
350                 context.need_end_deeper = false;
351         }
352         context.check_end_deeper(os);
353         // We don't need really a new paragraph, but
354         // we must make sure that the next item gets a \begin_layout.
355         parent_context.new_paragraph(os);
356 }
357
358
359 /*!
360  * Output a space if necessary.
361  * This function gets called for every whitespace token.
362  *
363  * We have three cases here:
364  * 1. A space must be suppressed. Example: The lyxcode case below
365  * 2. A space may be suppressed. Example: Spaces before "\par"
366  * 3. A space must not be suppressed. Example: A space between two words
367  *
368  * We currently handle only 1. and 3 and from 2. only the case of
369  * spaces before newlines as a side effect.
370  *
371  * 2. could be used to suppress as many spaces as possible. This has two effects:
372  * - Reimporting LyX generated LaTeX files changes almost no whitespace
373  * - Superflous whitespace from non LyX generated LaTeX files is removed.
374  * The drawback is that the logic inside the function becomes
375  * complicated, and that is the reason why it is not implemented.
376  */
377 void check_space(Parser const & p, ostream & os, Context & context)
378 {
379         Token const next = p.next_token();
380         Token const curr = p.curr_token();
381         // A space before a single newline and vice versa must be ignored
382         // LyX emits a newline before \end{lyxcode}.
383         // This newline must be ignored,
384         // otherwise LyX will add an additional protected space.
385         if (next.cat() == catSpace ||
386             next.cat() == catNewline ||
387             (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
388                 return;
389         }
390         context.check_layout(os);
391         os << ' ';
392 }
393
394
395 /*!
396  * Check whether \p command is a known command. If yes,
397  * handle the command with all arguments.
398  * \return true if the command was parsed, false otherwise.
399  */
400 bool parse_command(string const & command, Parser & p, ostream & os,
401                    bool outer, Context & context)
402 {
403         if (known_commands.find(command) != known_commands.end()) {
404                 vector<ArgumentType> const & template_arguments = known_commands[command];
405                 string ert = command;
406                 size_t no_arguments = template_arguments.size();
407                 for (size_t i = 0; i < no_arguments; ++i) {
408                         switch (template_arguments[i]) {
409                         case required:
410                                 // This argument contains regular LaTeX
411                                 handle_ert(os, ert + '{', context);
412                                 parse_text(p, os, FLAG_ITEM, outer, context);
413                                 ert = "}";
414                                 break;
415                         case verbatim:
416                                 // This argument may contain special characters
417                                 ert += '{' + p.verbatim_item() + '}';
418                                 break;
419                         case optional:
420                                 ert += p.getOpt();
421                                 break;
422                         }
423                 }
424                 handle_ert(os, ert, context);
425                 return true;
426         }
427         return false;
428 }
429
430
431 /// Parses a minipage or parbox
432 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
433                Context & parent_context, bool use_parbox)
434 {
435         string position;
436         string inner_pos;
437         string height_value = "0";
438         string height_unit = "pt";
439         string height_special = "none";
440         string latex_height;
441         if (p.next_token().asInput() == "[") {
442                 position = p.getArg('[', ']');
443                 if (position != "t" && position != "c" && position != "b") {
444                         position = "c";
445                         cerr << "invalid position for minipage/parbox" << endl;
446                 }
447                 if (p.next_token().asInput() == "[") {
448                         latex_height = p.getArg('[', ']');
449                         translate_box_len(latex_height, height_value, height_unit, height_special);
450
451                         if (p.next_token().asInput() == "[") {
452                                 inner_pos = p.getArg('[', ']');
453                                 if (inner_pos != "c" && inner_pos != "t" &&
454                                     inner_pos != "b" && inner_pos != "s") {
455                                         inner_pos = position;
456                                         cerr << "invalid inner_pos for minipage/parbox"
457                                              << endl;
458                                 }
459                         }
460                 }
461         }
462         string width_value;
463         string width_unit;
464         string const latex_width = p.verbatim_item();
465         translate_len(latex_width, width_value, width_unit);
466         if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
467                 // LyX can't handle length variables
468                 ostringstream ss;
469                 if (use_parbox)
470                         ss << "\\parbox";
471                 else
472                         ss << "\\begin{minipage}";
473                 if (!position.empty())
474                         ss << '[' << position << ']';
475                 if (!latex_height.empty())
476                         ss << '[' << latex_height << ']';
477                 if (!inner_pos.empty())
478                         ss << '[' << inner_pos << ']';
479                 ss << "{" << latex_width << "}";
480                 if (use_parbox)
481                         ss << '{';
482                 handle_ert(os, ss.str(), parent_context);
483                 parent_context.new_paragraph(os);
484                 parse_text_in_inset(p, os, flags, outer, parent_context);
485                 if (use_parbox)
486                         handle_ert(os, "}", parent_context);
487                 else
488                         handle_ert(os, "\\end{minipage}", parent_context);
489         } else {
490                 // LyX does not like empty positions, so we have
491                 // to set them to the LaTeX default values here.
492                 if (position.empty())
493                         position = "c";
494                 if (inner_pos.empty())
495                         inner_pos = position;
496                 parent_context.check_layout(os);
497                 begin_inset(os, "Box Frameless\n");
498                 os << "position \"" << position << "\"\n";
499                 os << "hor_pos \"c\"\n";
500                 os << "has_inner_box 1\n";
501                 os << "inner_pos \"" << inner_pos << "\"\n";
502                 os << "use_parbox " << use_parbox << "\n";
503                 os << "width \"" << width_value << width_unit << "\"\n";
504                 os << "special \"none\"\n";
505                 os << "height \"" << height_value << height_unit << "\"\n";
506                 os << "height_special \"" << height_special << "\"\n";
507                 os << "status open\n\n";
508                 parse_text_in_inset(p, os, flags, outer, parent_context);
509                 end_inset(os);
510 #ifdef PRESERVE_LAYOUT
511                 // lyx puts a % after the end of the minipage
512                 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
513                         // new paragraph
514                         //handle_comment(os, "%dummy", parent_context);
515                         p.get_token();
516                         p.skip_spaces();
517                         parent_context.new_paragraph(os);
518                 }
519                 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
520                         //handle_comment(os, "%dummy", parent_context);
521                         p.get_token();
522                         p.skip_spaces();
523                         // We add a protected space if something real follows
524                         if (p.good() && p.next_token().cat() != catComment) {
525                                 os << "\\InsetSpace ~\n";
526                         }
527                 }
528 #endif
529         }
530 }
531
532
533 void parse_environment(Parser & p, ostream & os, bool outer,
534                        Context & parent_context)
535 {
536         LyXLayout_ptr newlayout;
537         string const name = p.getArg('{', '}');
538         const bool is_starred = suffixIs(name, '*');
539         string const unstarred_name = rtrim(name, "*");
540         eat_whitespace(p, os, parent_context, false);
541         active_environments.push_back(name);
542
543         if (is_math_env(name)) {
544                 parent_context.check_layout(os);
545                 begin_inset(os, "Formula ");
546                 os << "\\begin{" << name << "}";
547                 parse_math(p, os, FLAG_END, MATH_MODE);
548                 os << "\\end{" << name << "}";
549                 end_inset(os);
550         }
551
552         else if (name == "tabular") {
553                 parent_context.check_layout(os);
554                 begin_inset(os, "Tabular ");
555                 handle_tabular(p, os, parent_context);
556                 end_inset(os);
557         }
558
559         else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
560                 parent_context.check_layout(os);
561                 begin_inset(os, "Float " + unstarred_name + "\n");
562                 if (p.next_token().asInput() == "[") {
563                         os << "placement " << p.getArg('[', ']') << '\n';
564                 }
565                 os << "wide " << tostr(is_starred)
566                    << "\nstatus open\n\n";
567                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
568                 end_inset(os);
569                 // We don't need really a new paragraph, but
570                 // we must make sure that the next item gets a \begin_layout.
571                 parent_context.new_paragraph(os);
572         }
573
574         else if (name == "minipage")
575                 parse_box(p, os, FLAG_END, outer, parent_context, false);
576
577         // Alignment settings
578         else if (name == "center" || name == "flushleft" || name == "flushright" ||
579                  name == "centering" || name == "raggedright" || name == "raggedleft") {
580                 // We must begin a new paragraph if not already done
581                 if (! parent_context.atParagraphStart()) {
582                         parent_context.check_end_layout(os);
583                         parent_context.new_paragraph(os);
584                 }
585                 if (name == "flushleft" || name == "raggedright")
586                         parent_context.add_extra_stuff("\\align left ");
587                 else if (name == "flushright" || name == "raggedleft")
588                         parent_context.add_extra_stuff("\\align right ");
589                 else
590                         parent_context.add_extra_stuff("\\align center ");
591                 parse_text(p, os, FLAG_END, outer, parent_context);
592                 // Just in case the environment is empty ..
593                 parent_context.extra_stuff.erase();
594                 // We must begin a new paragraph to reset the alignment
595                 parent_context.new_paragraph(os);
596         }
597
598         // The single '=' is meant here.
599         else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
600                    newlayout->isEnvironment()) {
601                 Context context(true, parent_context.textclass, newlayout,
602                                 parent_context.layout);
603                 if (parent_context.deeper_paragraph) {
604                         // We are beginning a nested environment after a
605                         // deeper paragraph inside the outer list environment.
606                         // Therefore we don't need to output a "begin deeper".
607                         context.need_end_deeper = true;
608                 }
609                 parent_context.check_end_layout(os);
610                 switch (context.layout->latextype) {
611                 case  LATEX_LIST_ENVIRONMENT:
612                         context.extra_stuff = "\\labelwidthstring "
613                                 + p.verbatim_item() + '\n';
614                         p.skip_spaces();
615                         break;
616                 case  LATEX_BIB_ENVIRONMENT:
617                         p.verbatim_item(); // swallow next arg
618                         p.skip_spaces();
619                         break;
620                 default:
621                         break;
622                 }
623                 context.check_deeper(os);
624                 parse_text(p, os, FLAG_END, outer, context);
625                 context.check_end_layout(os);
626                 if (parent_context.deeper_paragraph) {
627                         // We must suppress the "end deeper" because we
628                         // suppressed the "begin deeper" above.
629                         context.need_end_deeper = false;
630                 }
631                 context.check_end_deeper(os);
632                 parent_context.new_paragraph(os);
633         }
634
635         else if (name == "appendix") {
636                 // This is no good latex style, but it works and is used in some documents...
637                 parent_context.check_end_layout(os);
638                 Context context(true, parent_context.textclass, parent_context.layout,
639                                 parent_context.layout);
640                 context.check_layout(os);
641                 os << "\\start_of_appendix\n";
642                 parse_text(p, os, FLAG_END, outer, context);
643                 context.check_end_layout(os);
644         }
645
646         else if (name == "comment") {
647                 parent_context.check_layout(os);
648                 begin_inset(os, "Note Comment\n");
649                 os << "status open\n";
650                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
651                 end_inset(os);
652         }
653
654         else if (name == "lyxgreyedout") {
655                 parent_context.check_layout(os);
656                 begin_inset(os, "Note Greyedout\n");
657                 os << "status open\n";
658                 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
659                 end_inset(os);
660         }
661
662         else if (name == "tabbing") {
663                 // We need to remember that we have to handle '\=' specially
664                 handle_ert(os, "\\begin{" + name + "}", parent_context);
665                 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
666                 handle_ert(os, "\\end{" + name + "}", parent_context);
667         }
668
669         else {
670                 handle_ert(os, "\\begin{" + name + "}", parent_context);
671                 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
672                 handle_ert(os, "\\end{" + name + "}", parent_context);
673         }
674
675         active_environments.pop_back();
676         if (name != "math")
677                 p.skip_spaces();
678 }
679
680 /// parses a comment and outputs it to \p os.
681 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
682 {
683         BOOST_ASSERT(t.cat() == catComment);
684         context.check_layout(os);
685         if (!t.cs().empty()) {
686                 handle_comment(os, '%' + t.cs(), context);
687                 if (p.next_token().cat() == catNewline) {
688                         // A newline after a comment line starts a new
689                         // paragraph
690                         if(!context.atParagraphStart()) {
691                                 // Only start a new paragraph if not already
692                                 // done (we might get called recursively)
693                                 context.new_paragraph(os);
694                         }
695                         eat_whitespace(p, os, context, true);
696                 }
697         } else {
698                 // "%\n" combination
699                 p.skip_spaces();
700         }
701 }
702
703
704 /*!
705  * Reads spaces and comments until the first non-space, non-comment token.
706  * New paragraphs (double newlines or \\par) are handled like simple spaces
707  * if \p eatParagraph is true.
708  * Spaces are skipped, but comments are written to \p os.
709  */
710 void eat_whitespace(Parser & p, ostream & os, Context & context,
711                     bool eatParagraph)
712 {
713         while (p.good()) {
714                 Token const & t = p.get_token();
715                 if (t.cat() == catComment)
716                         parse_comment(p, os, t, context);
717                 else if ((! eatParagraph && p.isParagraph()) ||
718                          (t.cat() != catSpace && t.cat() != catNewline)) {
719                         p.putback();
720                         return;
721                 }
722         }
723 }
724
725 } // anonymous namespace
726
727
728 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
729                 Context & context)
730 {
731         LyXLayout_ptr newlayout;
732         // Store the latest bibliographystyle (needed for bibtex inset)
733         string bibliographystyle;
734         while (p.good()) {
735                 Token const & t = p.get_token();
736
737 #ifdef FILEDEBUG
738                 cerr << "t: " << t << " flags: " << flags << "\n";
739 #endif
740
741                 if (flags & FLAG_ITEM) {
742                         if (t.cat() == catSpace)
743                                 continue;
744
745                         flags &= ~FLAG_ITEM;
746                         if (t.cat() == catBegin) {
747                                 // skip the brace and collect everything to the next matching
748                                 // closing brace
749                                 flags |= FLAG_BRACE_LAST;
750                                 continue;
751                         }
752
753                         // handle only this single token, leave the loop if done
754                         flags |= FLAG_LEAVE;
755                 }
756
757                 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
758                         return;
759
760                 //
761                 // cat codes
762                 //
763                 if (t.cat() == catMath) {
764                         // we are inside some text mode thingy, so opening new math is allowed
765                         context.check_layout(os);
766                         begin_inset(os, "Formula ");
767                         Token const & n = p.get_token();
768                         if (n.cat() == catMath && outer) {
769                                 // TeX's $$...$$ syntax for displayed math
770                                 os << "\\[";
771                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
772                                 os << "\\]";
773                                 p.get_token(); // skip the second '$' token
774                         } else {
775                                 // simple $...$  stuff
776                                 p.putback();
777                                 os << '$';
778                                 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
779                                 os << '$';
780                         }
781                         end_inset(os);
782                 }
783
784                 else if (t.cat() == catSuper || t.cat() == catSub)
785                         cerr << "catcode " << t << " illegal in text mode\n";
786
787                 // Basic support for english quotes. This should be
788                 // extended to other quotes, but is not so easy (a
789                 // left english quote is the same as a right german
790                 // quote...)
791                 else if (t.asInput() == "`"
792                          && p.next_token().asInput() == "`") {
793                         context.check_layout(os);
794                         begin_inset(os, "Quotes ");
795                         os << "eld";
796                         end_inset(os);
797                         p.get_token();
798                         skip_braces(p);
799                 }
800                 else if (t.asInput() == "'"
801                          && p.next_token().asInput() == "'") {
802                         context.check_layout(os);
803                         begin_inset(os, "Quotes ");
804                         os << "erd";
805                         end_inset(os);
806                         p.get_token();
807                         skip_braces(p);
808                 }
809
810                 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
811                         check_space(p, os, context);
812
813                 else if (t.cat() == catLetter ||
814                                t.cat() == catOther ||
815                                t.cat() == catAlign ||
816                                t.cat() == catParameter) {
817                         context.check_layout(os);
818                         os << t.character();
819                 }
820
821                 else if (p.isParagraph()) {
822                         context.new_paragraph(os);
823                         eat_whitespace(p, os, context, true);
824                 }
825
826                 else if (t.cat() == catActive) {
827                         context.check_layout(os);
828                         if (t.character() == '~') {
829                                 if (context.layout->free_spacing)
830                                         os << ' ';
831                                 else
832                                         os << "\\InsetSpace ~\n";
833                         } else
834                                 os << t.character();
835                 }
836
837                 else if (t.cat() == catBegin) {
838                         // special handling of size changes
839                         context.check_layout(os);
840                         bool const is_size = is_known(p.next_token().cs(), known_sizes);
841                         Token const prev = p.prev_token();
842                         string const s = parse_text(p, FLAG_BRACE_LAST, outer, context);
843                         if (s.empty() && (p.next_token().character() == '`' ||
844                                           (prev.character() == '-' && p.next_token().character())))
845                                 ; // ignore it in {}`` or -{}-
846                         else if (is_size || s == "[" || s == "]" || s == "*")
847                                 os << s;
848                         else {
849                                 handle_ert(os, "{", context, false);
850                                 // s will end the current layout and begin a new one if necessary
851                                 os << s;
852                                 handle_ert(os, "}", context);
853                         }
854                 }
855
856                 else if (t.cat() == catEnd) {
857                         if (flags & FLAG_BRACE_LAST) {
858                                 return;
859                         }
860                         cerr << "stray '}' in text\n";
861                         handle_ert(os, "}", context);
862                 }
863
864                 else if (t.cat() == catComment)
865                         parse_comment(p, os, t, context);
866
867                 //
868                 // control sequences
869                 //
870
871                 else if (t.cs() == "(") {
872                         context.check_layout(os);
873                         begin_inset(os, "Formula");
874                         os << " \\(";
875                         parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
876                         os << "\\)";
877                         end_inset(os);
878                 }
879
880                 else if (t.cs() == "[") {
881                         context.check_layout(os);
882                         begin_inset(os, "Formula");
883                         os << " \\[";
884                         parse_math(p, os, FLAG_EQUATION, MATH_MODE);
885                         os << "\\]";
886                         end_inset(os);
887                 }
888
889                 else if (t.cs() == "begin")
890                         parse_environment(p, os, outer, context);
891
892                 else if (t.cs() == "end") {
893                         if (flags & FLAG_END) {
894                                 // eat environment name
895                                 string const name = p.getArg('{', '}');
896                                 if (name != active_environment())
897                                         cerr << "\\end{" + name + "} does not match \\begin{"
898                                                 + active_environment() + "}\n";
899                                 return;
900                         }
901                         p.error("found 'end' unexpectedly");
902                 }
903
904                 else if (t.cs() == "item") {
905                         p.skip_spaces();
906                         string s;
907                         bool optarg = false;
908                         if (p.next_token().character() == '[') {
909                                 p.get_token(); // eat '['
910                                 Context newcontext(false, context.textclass);
911                                 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
912                                 optarg = true;
913                         }
914                         context.set_item();
915                         context.check_layout(os);
916                         if (optarg) {
917                                 if (context.layout->labeltype != LABEL_MANUAL) {
918                                         // lyx does not support \item[\mybullet] in itemize environments
919                                         handle_ert(os, "[", context);
920                                         os << s;
921                                         handle_ert(os, "]", context);
922                                 } else if (!s.empty()) {
923                                         // The space is needed to separate the item from the rest of the sentence.
924                                         os << s << ' ';
925                                         eat_whitespace(p, os, context, false);
926                                 }
927                         }
928                 }
929
930                 else if (t.cs() == "bibitem") {
931                         context.set_item();
932                         context.check_layout(os);
933                         os << "\\bibitem ";
934                         os << p.getOpt();
935                         os << '{' << p.verbatim_item() << '}' << "\n";
936                 }
937
938                 else if (t.cs() == "def") {
939                         context.check_layout(os);
940                         eat_whitespace(p, os, context, false);
941                         string name = p.get_token().cs();
942                         while (p.next_token().cat() != catBegin)
943                                 name += p.get_token().asString();
944                         handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
945                 }
946
947                 else if (t.cs() == "noindent") {
948                         p.skip_spaces();
949                         context.add_extra_stuff("\\noindent ");
950                 }
951
952                 else if (t.cs() == "appendix") {
953                         p.skip_spaces();
954                         context.add_extra_stuff("\\start_of_appendix ");
955                 }
956
957                 // Must attempt to parse "Section*" before "Section".
958                 else if ((p.next_token().asInput() == "*") &&
959                          // The single '=' is meant here.
960                          (newlayout = findLayout(context.textclass,
961                                                  t.cs() + '*')).get() &&
962                          newlayout->isCommand()) {
963                         p.get_token();
964                         output_command_layout(os, p, outer, context, newlayout);
965                         p.skip_spaces();
966                 }
967
968                 // The single '=' is meant here.
969                 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
970                          newlayout->isCommand()) {
971                         output_command_layout(os, p, outer, context, newlayout);
972                         p.skip_spaces();
973                 }
974
975                 else if (t.cs() == "includegraphics") {
976                         map<string, string> opts = split_map(p.getArg('[', ']'));
977                         string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
978
979                         context.check_layout(os);
980                         begin_inset(os, "Graphics ");
981                         os << "\n\tfilename " << name << '\n';
982                         if (opts.find("width") != opts.end())
983                                 os << "\twidth "
984                                    << translate_len(opts["width"]) << '\n';
985                         if (opts.find("height") != opts.end())
986                                 os << "\theight "
987                                    << translate_len(opts["height"]) << '\n';
988                         if (opts.find("scale") != opts.end()) {
989                                 istringstream iss(opts["scale"]);
990                                 double val;
991                                 iss >> val;
992                                 val = val*100;
993                                 os << "\tscale " << val << '\n';
994                         }
995                         if (opts.find("angle") != opts.end())
996                                 os << "\trotateAngle "
997                                    << opts["angle"] << '\n';
998                         if (opts.find("origin") != opts.end()) {
999                                 ostringstream ss;
1000                                 string const opt = opts["origin"];
1001                                 if (opt.find('l') != string::npos) ss << "left";
1002                                 if (opt.find('r') != string::npos) ss << "right";
1003                                 if (opt.find('c') != string::npos) ss << "center";
1004                                 if (opt.find('t') != string::npos) ss << "Top";
1005                                 if (opt.find('b') != string::npos) ss << "Bottom";
1006                                 if (opt.find('B') != string::npos) ss << "Baseline";
1007                                 if (!ss.str().empty())
1008                                         os << "\trotateOrigin " << ss.str() << '\n';
1009                                 else
1010                                         cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1011                         }
1012                         if (opts.find("keepaspectratio") != opts.end())
1013                                 os << "\tkeepAspectRatio\n";
1014                         if (opts.find("clip") != opts.end())
1015                                 os << "\tclip\n";
1016                         if (opts.find("draft") != opts.end())
1017                                 os << "\tdraft\n";
1018                         if (opts.find("bb") != opts.end())
1019                                 os << "\tBoundingBox "
1020                                    << opts["bb"] << '\n';
1021                         int numberOfbbOptions = 0;
1022                         if (opts.find("bbllx") != opts.end())
1023                                 numberOfbbOptions++;
1024                         if (opts.find("bblly") != opts.end())
1025                                 numberOfbbOptions++;
1026                         if (opts.find("bburx") != opts.end())
1027                                 numberOfbbOptions++;
1028                         if (opts.find("bbury") != opts.end())
1029                                 numberOfbbOptions++;
1030                         if (numberOfbbOptions == 4)
1031                                 os << "\tBoundingBox "
1032                                    << opts["bbllx"] << opts["bblly"]
1033                                    << opts["bburx"] << opts["bbury"] << '\n';
1034                         else if (numberOfbbOptions > 0)
1035                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1036                         numberOfbbOptions = 0;
1037                         if (opts.find("natwidth") != opts.end())
1038                                 numberOfbbOptions++;
1039                         if (opts.find("natheight") != opts.end())
1040                                 numberOfbbOptions++;
1041                         if (numberOfbbOptions == 2)
1042                                 os << "\tBoundingBox 0bp 0bp "
1043                                    << opts["natwidth"] << opts["natheight"] << '\n';
1044                         else if (numberOfbbOptions > 0)
1045                                 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1046                         ostringstream special;
1047                         if (opts.find("hiresbb") != opts.end())
1048                                 special << "hiresbb,";
1049                         if (opts.find("trim") != opts.end())
1050                                 special << "trim,";
1051                         if (opts.find("viewport") != opts.end())
1052                                 special << "viewport=" << opts["viewport"] << ',';
1053                         if (opts.find("totalheight") != opts.end())
1054                                 special << "totalheight=" << opts["totalheight"] << ',';
1055                         if (opts.find("type") != opts.end())
1056                                 special << "type=" << opts["type"] << ',';
1057                         if (opts.find("ext") != opts.end())
1058                                 special << "ext=" << opts["ext"] << ',';
1059                         if (opts.find("read") != opts.end())
1060                                 special << "read=" << opts["read"] << ',';
1061                         if (opts.find("command") != opts.end())
1062                                 special << "command=" << opts["command"] << ',';
1063                         string s_special = special.str();
1064                         if (!s_special.empty()) {
1065                                 // We had special arguments. Remove the trailing ','.
1066                                 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1067                         }
1068                         // TODO: Handle the unknown settings better.
1069                         // Warn about invalid options.
1070                         // Check whether some option was given twice.
1071                         end_inset(os);
1072                 }
1073
1074                 else if (t.cs() == "footnote") {
1075                         p.skip_spaces();
1076                         context.check_layout(os);
1077                         begin_inset(os, "Foot\n");
1078                         os << "status collapsed\n\n";
1079                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1080                         end_inset(os);
1081                 }
1082
1083                 else if (t.cs() == "marginpar") {
1084                         p.skip_spaces();
1085                         context.check_layout(os);
1086                         begin_inset(os, "Marginal\n");
1087                         os << "status collapsed\n\n";
1088                         parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1089                         end_inset(os);
1090                 }
1091
1092                 else if (t.cs() == "ensuremath") {
1093                         p.skip_spaces();
1094                         context.check_layout(os);
1095                         Context newcontext(false, context.textclass);
1096                         string s = parse_text(p, FLAG_ITEM, false, newcontext);
1097                         if (s == "±" || s == "³" || s == "²" || s == "µ")
1098                                 os << s;
1099                         else
1100                                 handle_ert(os, "\\ensuremath{" + s + "}",
1101                                            context);
1102                 }
1103
1104                 else if (t.cs() == "hfill") {
1105                         context.check_layout(os);
1106                         os << "\n\\hfill \n";
1107                         skip_braces(p);
1108                         p.skip_spaces();
1109                 }
1110
1111                 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1112                         p.skip_spaces();
1113                         skip_braces(p); // swallow this
1114                 }
1115
1116                 else if (t.cs() == "tableofcontents") {
1117                         p.skip_spaces();
1118                         context.check_layout(os);
1119                         begin_inset(os, "LatexCommand \\tableofcontents\n");
1120                         end_inset(os);
1121                         skip_braces(p); // swallow this
1122                 }
1123
1124                 else if (t.cs() == "listoffigures") {
1125                         p.skip_spaces();
1126                         context.check_layout(os);
1127                         begin_inset(os, "FloatList figure\n");
1128                         end_inset(os);
1129                         skip_braces(p); // swallow this
1130                 }
1131
1132                 else if (t.cs() == "listoftables") {
1133                         p.skip_spaces();
1134                         context.check_layout(os);
1135                         begin_inset(os, "FloatList table\n");
1136                         end_inset(os);
1137                         skip_braces(p); // swallow this
1138                 }
1139
1140                 else if (t.cs() == "listof") {
1141                         p.skip_spaces(true);
1142                         string const name = p.get_token().asString();
1143                         if (context.textclass.floats().typeExist(name)) {
1144                                 context.check_layout(os);
1145                                 begin_inset(os, "FloatList ");
1146                                 os << name << "\n";
1147                                 end_inset(os);
1148                                 p.get_token(); // swallow second arg
1149                         } else
1150                                 handle_ert(os, "\\listof{" + name + "}", context);
1151                 }
1152
1153                 else if (t.cs() == "textrm") {
1154                         context.check_layout(os);
1155                         os << "\n\\family roman \n";
1156                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1157                         os << "\n\\family default \n";
1158                 }
1159
1160                 else if (t.cs() == "textsf") {
1161                         context.check_layout(os);
1162                         os << "\n\\family sans \n";
1163                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1164                         os << "\n\\family default \n";
1165                 }
1166
1167                 else if (t.cs() == "textsl") {
1168                         context.check_layout(os);
1169                         os << "\n\\shape slanted \n";
1170                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1171                         os << "\n\\shape default \n";
1172                 }
1173
1174                 else if (t.cs() == "texttt") {
1175                         context.check_layout(os);
1176                         os << "\n\\family typewriter \n";
1177                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1178                         os << "\n\\family default \n";
1179                 }
1180
1181                 else if (t.cs() == "textit") {
1182                         context.check_layout(os);
1183                         os << "\n\\shape italic \n";
1184                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1185                         os << "\n\\shape default \n";
1186                 }
1187
1188                 else if (t.cs() == "textsc") {
1189                         context.check_layout(os);
1190                         os << "\n\\noun on \n";
1191                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1192                         os << "\n\\noun default \n";
1193                 }
1194
1195                 else if (t.cs() == "textbf") {
1196                         context.check_layout(os);
1197                         os << "\n\\series bold \n";
1198                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1199                         os << "\n\\series default \n";
1200                 }
1201
1202                 else if (t.cs() == "underbar") {
1203                         context.check_layout(os);
1204                         os << "\n\\bar under \n";
1205                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1206                         os << "\n\\bar default \n";
1207                 }
1208
1209                 else if (t.cs() == "emph" || t.cs() == "noun") {
1210                         context.check_layout(os);
1211                         os << "\n\\" << t.cs() << " on \n";
1212                         parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1213                         os << "\n\\" << t.cs() << " default \n";
1214                 }
1215
1216                 else if (is_known(t.cs(), known_latex_commands)) {
1217                         context.check_layout(os);
1218                         begin_inset(os, "LatexCommand ");
1219                         os << '\\' << t.cs();
1220                         os << p.getOpt();
1221                         os << p.getOpt();
1222                         os << '{' << p.verbatim_item() << "}\n";
1223                         end_inset(os);
1224                 }
1225
1226                 else if (is_known(t.cs(), known_quotes)) {
1227                         char const ** where = is_known(t.cs(), known_quotes);
1228                         context.check_layout(os);
1229                         begin_inset(os, "Quotes ");
1230                         os << known_coded_quotes[where - known_quotes];
1231                         end_inset(os);
1232                         // LyX adds {} after the quote, so we have to eat
1233                         // spaces here if there are any before a possible
1234                         // {} pair.
1235                         eat_whitespace(p, os, context, false);
1236                         skip_braces(p);
1237                 }
1238
1239                 else if (is_known(t.cs(), known_sizes)) {
1240                         char const ** where = is_known(t.cs(), known_sizes);
1241                         context.check_layout(os);
1242                         os << "\n\\size " << known_coded_sizes[where - known_sizes] << "\n";
1243                         eat_whitespace(p, os, context, false);
1244                 }
1245
1246                 else if (t.cs() == "LyX" || t.cs() == "TeX"
1247                          || t.cs() == "LaTeX") {
1248                         context.check_layout(os);
1249                         os << t.cs();
1250                         skip_braces(p); // eat {}
1251                 }
1252
1253                 else if (t.cs() == "LaTeXe") {
1254                         context.check_layout(os);
1255                         os << "LaTeX2e";
1256                         skip_braces(p); // eat {}
1257                 }
1258
1259                 else if (t.cs() == "ldots") {
1260                         context.check_layout(os);
1261                         skip_braces(p);
1262                         os << "\\SpecialChar \\ldots{}\n";
1263                 }
1264
1265                 else if (t.cs() == "lyxarrow") {
1266                         context.check_layout(os);
1267                         os << "\\SpecialChar \\menuseparator\n";
1268                         skip_braces(p);
1269                 }
1270
1271                 else if (t.cs() == "textcompwordmark") {
1272                         context.check_layout(os);
1273                         os << "\\SpecialChar \\textcompwordmark{}\n";
1274                         skip_braces(p);
1275                 }
1276
1277                 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1278                         context.check_layout(os);
1279                         os << "\\SpecialChar \\@.\n";
1280                         p.get_token();
1281                 }
1282
1283                 else if (t.cs() == "-") {
1284                         context.check_layout(os);
1285                         os << "\\SpecialChar \\-\n";
1286                 }
1287
1288                 else if (t.cs() == "textasciitilde") {
1289                         context.check_layout(os);
1290                         os << '~';
1291                         skip_braces(p);
1292                 }
1293
1294                 else if (t.cs() == "textasciicircum") {
1295                         context.check_layout(os);
1296                         os << '^';
1297                         skip_braces(p);
1298                 }
1299
1300                 else if (t.cs() == "textbackslash") {
1301                         context.check_layout(os);
1302                         os << "\n\\backslash \n";
1303                         skip_braces(p);
1304                 }
1305
1306                 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1307                             || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1308                             || t.cs() == "%") {
1309                         context.check_layout(os);
1310                         os << t.cs();
1311                 }
1312
1313                 else if (t.cs() == "char") {
1314                         context.check_layout(os);
1315                         if (p.next_token().character() == '`') {
1316                                 p.get_token();
1317                                 if (p.next_token().cs() == "\"") {
1318                                         p.get_token();
1319                                         os << '"';
1320                                         skip_braces(p);
1321                                 } else {
1322                                         handle_ert(os, "\\char`", context);
1323                                 }
1324                         } else {
1325                                 handle_ert(os, "\\char", context);
1326                         }
1327                 }
1328
1329                 else if (t.cs() == "\"") {
1330                         context.check_layout(os);
1331                         string const name = p.verbatim_item();
1332                              if (name == "a") os << 'ä';
1333                         else if (name == "o") os << 'ö';
1334                         else if (name == "u") os << 'ü';
1335                         else if (name == "A") os << 'Ä';
1336                         else if (name == "O") os << 'Ö';
1337                         else if (name == "U") os << 'Ü';
1338                         else handle_ert(os, "\"{" + name + "}", context);
1339                 }
1340
1341                 // Problem: \= creates a tabstop inside the tabbing environment
1342                 // and else an accent. In the latter case we really would want
1343                 // \={o} instead of \= o.
1344                 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1345                         handle_ert(os, t.asInput(), context);
1346
1347                 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1348                       || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1349                         // we need the trim as the LyX parser chokes on such spaces
1350                         context.check_layout(os);
1351                         os << "\n\\i \\" << t.cs() << "{"
1352                            << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1353                 }
1354
1355                 else if (t.cs() == "ss") {
1356                         context.check_layout(os);
1357                         os << "ß";
1358                 }
1359
1360                 else if (t.cs() == "i" || t.cs() == "j") {
1361                         context.check_layout(os);
1362                         os << "\\" << t.cs() << ' ';
1363                 }
1364
1365                 else if (t.cs() == "\\") {
1366                         context.check_layout(os);
1367                         string const next = p.next_token().asInput();
1368                         if (next == "[")
1369                                 handle_ert(os, "\\\\" + p.getOpt(), context);
1370                         else if (next == "*") {
1371                                 p.get_token();
1372                                 handle_ert(os, "\\\\*" + p.getOpt(), context);
1373                         }
1374                         else {
1375                                 os << "\n\\newline \n";
1376                         }
1377                 }
1378
1379                 else if (t.cs() == "input" || t.cs() == "include"
1380                          || t.cs() == "verbatiminput") {
1381                         string name = '\\' + t.cs();
1382                         if (t.cs() == "verbatiminput"
1383                             && p.next_token().asInput() == "*")
1384                                 name += p.get_token().asInput();
1385                         context.check_layout(os);
1386                         begin_inset(os, "Include ");
1387                         string filename(p.getArg('{', '}'));
1388                         string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1389                         if (tex2lyx(filename, lyxname)) {
1390                                 os << name << '{' << lyxname << "}\n";
1391                         } else {
1392                                 os << name << '{' << filename << "}\n";
1393                         }
1394                         os << "preview false\n";
1395                         end_inset(os);
1396                 }
1397
1398                 else if (t.cs() == "fancyhead") {
1399                         context.check_layout(os);
1400                         ostringstream ss;
1401                         ss << "\\fancyhead";
1402                         ss << p.getOpt();
1403                         ss << '{' << p.verbatim_item() << "}\n";
1404                         handle_ert(os, ss.str(), context);
1405                 }
1406
1407                 else if (t.cs() == "bibliographystyle") {
1408                         // store new bibliographystyle
1409                         bibliographystyle = p.verbatim_item();
1410                         // output new bibliographystyle.
1411                         // This is only necessary if used in some other macro than \bibliography.
1412                         handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1413                 }
1414
1415                 else if (t.cs() == "bibliography") {
1416                         context.check_layout(os);
1417                         begin_inset(os, "LatexCommand ");
1418                         os << "\\bibtex";
1419                         // Do we have a bibliographystyle set?
1420                         if (!bibliographystyle.empty()) {
1421                                 os << '[' << bibliographystyle << ']';
1422                         }
1423                         os << '{' << p.verbatim_item() << "}\n";
1424                         end_inset(os);
1425                 }
1426
1427                 else if (t.cs() == "parbox")
1428                         parse_box(p, os, FLAG_ITEM, outer, context, true);
1429
1430                 else if (t.cs() == "smallskip" ||
1431                          t.cs() == "medskip" ||
1432                          t.cs() == "bigskip" ||
1433                          t.cs() == "vfill") {
1434                         context.check_layout(os);
1435                         begin_inset(os, "VSpace ");
1436                         os << t.cs();
1437                         end_inset(os);
1438                         skip_braces(p);
1439                 }
1440
1441                 else if (t.cs() == "vspace") {
1442                         bool starred = false;
1443                         if (p.next_token().asInput() == "*") {
1444                                 p.get_token();
1445                                 starred = true;
1446                         }
1447                         string const length = p.verbatim_item();
1448                         string unit;
1449                         string valstring;
1450                         bool valid = splitLatexLength(length, valstring, unit);
1451                         bool known_vspace = false;
1452                         bool known_unit = false;
1453                         double value;
1454                         if (valid) {
1455                                 istringstream iss(valstring);
1456                                 iss >> value;
1457                                 if (value == 1.0) {
1458                                         if (unit == "\\smallskipamount") {
1459                                                 unit = "smallskip";
1460                                                 known_vspace = true;
1461                                         } else if (unit == "\\medskipamount") {
1462                                                 unit = "medskip";
1463                                                 known_vspace = true;
1464                                         } else if (unit == "\\bigskipamount") {
1465                                                 unit = "bigskip";
1466                                                 known_vspace = true;
1467                                         } else if (unit == "\\fill") {
1468                                                 unit = "vfill";
1469                                                 known_vspace = true;
1470                                         }
1471                                 }
1472                                 if (!known_vspace) {
1473                                         switch (unitFromString(unit)) {
1474                                         case LyXLength::SP:
1475                                         case LyXLength::PT:
1476                                         case LyXLength::BP:
1477                                         case LyXLength::DD:
1478                                         case LyXLength::MM:
1479                                         case LyXLength::PC:
1480                                         case LyXLength::CC:
1481                                         case LyXLength::CM:
1482                                         case LyXLength::IN:
1483                                         case LyXLength::EX:
1484                                         case LyXLength::EM:
1485                                         case LyXLength::MU:
1486                                                 known_unit = true;
1487                                                 break;
1488                                         default:
1489                                                 break;
1490                                         }
1491                                 }
1492                         }
1493
1494                         if (known_unit || known_vspace) {
1495                                 // Literal length or known variable
1496                                 context.check_layout(os);
1497                                 begin_inset(os, "VSpace ");
1498                                 if (known_unit)
1499                                         os << value;
1500                                 os << unit;
1501                                 if (starred)
1502                                         os << '*';
1503                                 end_inset(os);
1504                         } else {
1505                                 // LyX can't handle other length variables in Inset VSpace
1506                                 string name = t.asInput();
1507                                 if (starred)
1508                                         name += '*';
1509                                 if (valid) {
1510                                         if (value == 1.0)
1511                                                 handle_ert(os, name + '{' + unit + '}', context);
1512                                         else if (value == -1.0)
1513                                                 handle_ert(os, name + "{-" + unit + '}', context);
1514                                         else
1515                                                 handle_ert(os, name + '{' + valstring + unit + '}', context);
1516                                 } else
1517                                         handle_ert(os, name + '{' + length + '}', context);
1518                         }
1519                 }
1520
1521                 else {
1522                         //cerr << "#: " << t << " mode: " << mode << endl;
1523                         // heuristic: read up to next non-nested space
1524                         /*
1525                         string s = t.asInput();
1526                         string z = p.verbatim_item();
1527                         while (p.good() && z != " " && z.size()) {
1528                                 //cerr << "read: " << z << endl;
1529                                 s += z;
1530                                 z = p.verbatim_item();
1531                         }
1532                         cerr << "found ERT: " << s << endl;
1533                         handle_ert(os, s + ' ', context);
1534                         */
1535                         string name = t.asInput();
1536                         if (p.next_token().asInput() == "*") {
1537                                 // Starred commands like \vspace*{}
1538                                 p.get_token();                          // Eat '*'
1539                                 name += '*';
1540                         }
1541                         if (! parse_command(name, p, os, outer, context))
1542                                 handle_ert(os, name, context);
1543                 }
1544
1545                 if (flags & FLAG_LEAVE) {
1546                         flags &= ~FLAG_LEAVE;
1547                         break;
1548                 }
1549         }
1550 }
1551
1552
1553 // }])