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.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
20 #include "FloatList.h"
24 #include "support/convert.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
29 #include <boost/assert.hpp>
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context)
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);
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context newcontext(context);
60 // Don't inherit the extra stuff
61 newcontext.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;
70 * Thin wrapper around parse_text_snippet() using a string.
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.
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
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.extra_stuff.clear();
88 parse_text_snippet(p, os, flags, outer, newcontext);
93 char const * const known_latex_commands[] = { "ref", "cite", "nocite", "label",
94 "index", "printindex", "pageref", "url", "vref", "vpageref", "prettyref",
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.
103 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
104 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
105 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
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.
113 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
114 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
115 // jurabib commands not (yet) supported by LyX:
117 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
118 // "footciteauthor", "footciteyear", "footciteyearpar",
119 "citefield", "citetitle", "cite*", 0 };
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};
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};
133 /// LaTeX names for font sizes
134 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
135 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
137 /// the same as known_sizes with .lyx names
138 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
139 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
141 /// LaTeX 2.09 names for font families
142 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
144 /// LaTeX names for font families
145 char const * const known_font_families[] = { "rmfamily", "sffamily",
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",
152 /// LaTeX 2.09 names for font series
153 char const * const known_old_font_series[] = { "bf", 0};
155 /// LaTeX names for font series
156 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
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};
161 /// LaTeX 2.09 names for font shapes
162 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
164 /// LaTeX names for font shapes
165 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
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};
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.
182 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
183 "ps.gz", "eps.Z", "ps.Z", 0};
186 * Graphics file extensions known by the pdftex driver of the graphics package.
187 * \sa known_dvips_graphics_formats
189 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
193 * Known file extensions for TeX files as used by \\include.
195 char const * const known_tex_extensions[] = {"tex", 0};
197 /// spaces known by InsetSpace
198 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
199 "qquad", "enspace", "enskip", "negthinspace", 0};
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};
207 /// splits "x=z, y=b" into a map
208 map<string, string> split_map(string const & s)
210 map<string, string> res;
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);
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.
230 bool splitLatexLength(string const & len, string & value, string & unit)
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)
240 if (len[0] == '\\') {
241 // We had something like \textwidth without a factor
247 value = trim(string(length, 0, i));
251 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
252 if (contains(len, '\\'))
253 unit = trim(string(len, i));
255 unit = ascii_lowercase(trim(string(len, i)));
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)
264 if (!splitLatexLength(length, valstring, unit))
266 // LyX uses percent values
268 istringstream iss(valstring);
273 string const percentval = oss.str();
275 if (unit.empty() || unit[0] != '\\')
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;
304 string translate_len(string const & length)
308 if (translate_len(length, value, unit))
310 // If the input is invalid, return what we have.
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.
323 void translate_box_len(string const & length, string & value, string & unit, string & special)
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
342 * Find a file with basename \p name in path \p path and an extension
345 string find_file(string const & name, string const & path,
346 char const * const * extensions)
348 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
350 for (char const * const * what = extensions; *what; ++what) {
351 string const trial = addExtension(name, *what);
352 if (makeAbsPath(trial, path).exists())
359 void begin_inset(ostream & os, string const & name)
361 os << "\n\\begin_inset " << name;
365 void end_inset(ostream & os)
367 os << "\n\\end_inset\n\n";
371 void skip_braces(Parser & p)
373 if (p.next_token().cat() != catBegin)
376 if (p.next_token().cat() == catEnd) {
384 void handle_ert(ostream & os, string const & s, Context & context)
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) {
394 os << "\n\\backslash\n";
395 else if (*it == '\n') {
396 newcontext.new_paragraph(os);
397 newcontext.check_layout(os);
401 newcontext.check_end_layout(os);
406 void handle_comment(ostream & os, string const & s, Context & context)
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) {
415 os << "\n\\backslash\n";
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);
427 Layout const * findLayout(TextClass const & textclass, string const & name)
429 DocumentClass::const_iterator lit = textclass.begin();
430 DocumentClass::const_iterator len = textclass.end();
431 for (; lit != len; ++lit)
432 if (lit->latexname() == name)
438 void eat_whitespace(Parser &, ostream &, Context &, bool);
441 Layout * captionlayout()
443 static Layout * lay = 0;
446 lay->name_ = from_ascii("Caption");
447 lay->latexname_ = "caption";
448 lay->latextype = LATEX_COMMAND;
449 lay->optionalargs = 1;
455 void output_command_layout(ostream & os, Parser & p, bool outer,
456 Context & parent_context,
457 Layout const * newlayout)
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;
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);
478 eat_whitespace(p, os, context, false);
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;
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);
496 * Output a space if necessary.
497 * This function gets called for every whitespace token.
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
504 * We currently handle only 1. and 3 and from 2. only the case of
505 * spaces before newlines as a side effect.
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.
513 void check_space(Parser const & p, ostream & os, Context & context)
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)) {
526 context.check_layout(os);
532 * Parse all arguments of \p command
534 void parse_arguments(string const & command,
535 vector<ArgumentType> const & template_arguments,
536 Parser & p, ostream & os, bool outer, Context & context)
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]) {
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);
550 // This argument may contain special characters
551 ert += '{' + p.verbatim_item() + '}';
558 handle_ert(os, ert, context);
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.
567 bool parse_command(string const & command, Parser & p, ostream & os,
568 bool outer, Context & context)
570 if (known_commands.find(command) != known_commands.end()) {
571 parse_arguments(command, known_commands[command], p, os,
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)
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";
591 if (p.next_token().asInput() == "[") {
592 position = p.getArg('[', ']');
593 if (position != "t" && position != "c" && position != "b") {
595 cerr << "invalid position for minipage/parbox" << endl;
597 if (p.next_token().asInput() == "[") {
598 latex_height = p.getArg('[', ']');
599 translate_box_len(latex_height, height_value, height_unit, height_special);
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"
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
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 << "}";
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);
636 handle_ert(os, "}", parent_context);
638 handle_ert(os, "\\end{minipage}", parent_context);
640 // LyX does not like empty positions, so we have
641 // to set them to the LaTeX default values here.
642 if (position.empty())
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);
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) {
664 //handle_comment(os, "%dummy", parent_context);
667 parent_context.new_paragraph(os);
669 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
670 //handle_comment(os, "%dummy", parent_context);
673 // We add a protected space if something real follows
674 if (p.good() && p.next_token().cat() != catComment) {
675 os << "\\InsetSpace ~\n";
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)
688 if (name == "tabbing")
689 // We need to remember that we have to handle '\=' specially
690 flags |= FLAG_TABBING;
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}
697 bool const specialfont =
698 (parent_context.font != parent_context.normalfont);
699 bool const new_layout_allowed = parent_context.new_layout_allowed;
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);
706 parent_context.new_layout_allowed = new_layout_allowed;
710 void parse_environment(Parser & p, ostream & os, bool outer,
711 Context & parent_context)
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);
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 << "}";
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);
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';
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);
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);
755 else if (name == "minipage") {
756 eat_whitespace(p, os, parent_context, false);
757 parse_box(p, os, FLAG_END, outer, parent_context, false);
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);
771 else if (name == "lyxgreyedout") {
772 eat_whitespace(p, os, parent_context, false);
773 parent_context.check_layout(os);
774 begin_inset(os, "Note Greyedout\n");
775 os << "status open\n";
776 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
781 else if (name == "framed") {
782 eat_whitespace(p, os, parent_context, false);
783 parent_context.check_layout(os);
784 begin_inset(os, "Note Framed\n");
785 os << "status open\n";
786 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
791 else if (name == "shaded") {
792 eat_whitespace(p, os, parent_context, false);
793 parent_context.check_layout(os);
794 begin_inset(os, "Note Shaded\n");
795 os << "status open\n";
796 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
801 else if (!parent_context.new_layout_allowed)
802 parse_unknown_environment(p, name, os, FLAG_END, outer,
805 // Alignment settings
806 else if (name == "center" || name == "flushleft" || name == "flushright" ||
807 name == "centering" || name == "raggedright" || name == "raggedleft") {
808 eat_whitespace(p, os, parent_context, false);
809 // We must begin a new paragraph if not already done
810 if (! parent_context.atParagraphStart()) {
811 parent_context.check_end_layout(os);
812 parent_context.new_paragraph(os);
814 if (name == "flushleft" || name == "raggedright")
815 parent_context.add_extra_stuff("\\align left\n");
816 else if (name == "flushright" || name == "raggedleft")
817 parent_context.add_extra_stuff("\\align right\n");
819 parent_context.add_extra_stuff("\\align center\n");
820 parse_text(p, os, FLAG_END, outer, parent_context);
821 // Just in case the environment is empty ..
822 parent_context.extra_stuff.erase();
823 // We must begin a new paragraph to reset the alignment
824 parent_context.new_paragraph(os);
828 // The single '=' is meant here.
829 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
830 newlayout->isEnvironment()) {
831 eat_whitespace(p, os, parent_context, false);
832 Context context(true, parent_context.textclass, newlayout,
833 parent_context.layout, parent_context.font);
834 if (parent_context.deeper_paragraph) {
835 // We are beginning a nested environment after a
836 // deeper paragraph inside the outer list environment.
837 // Therefore we don't need to output a "begin deeper".
838 context.need_end_deeper = true;
840 parent_context.check_end_layout(os);
841 switch (context.layout->latextype) {
842 case LATEX_LIST_ENVIRONMENT:
843 context.extra_stuff = "\\labelwidthstring "
844 + p.verbatim_item() + '\n';
847 case LATEX_BIB_ENVIRONMENT:
848 p.verbatim_item(); // swallow next arg
854 context.check_deeper(os);
855 parse_text(p, os, FLAG_END, outer, context);
856 context.check_end_layout(os);
857 if (parent_context.deeper_paragraph) {
858 // We must suppress the "end deeper" because we
859 // suppressed the "begin deeper" above.
860 context.need_end_deeper = false;
862 context.check_end_deeper(os);
863 parent_context.new_paragraph(os);
867 else if (name == "appendix") {
868 // This is no good latex style, but it works and is used in some documents...
869 eat_whitespace(p, os, parent_context, false);
870 parent_context.check_end_layout(os);
871 Context context(true, parent_context.textclass, parent_context.layout,
872 parent_context.layout, parent_context.font);
873 context.check_layout(os);
874 os << "\\start_of_appendix\n";
875 parse_text(p, os, FLAG_END, outer, context);
876 context.check_end_layout(os);
880 else if (known_environments.find(name) != known_environments.end()) {
881 vector<ArgumentType> arguments = known_environments[name];
882 // The last "argument" denotes wether we may translate the
883 // environment contents to LyX
884 // The default required if no argument is given makes us
885 // compatible with the reLyXre environment.
886 ArgumentType contents = arguments.empty() ?
889 if (!arguments.empty())
890 arguments.pop_back();
891 // See comment in parse_unknown_environment()
892 bool const specialfont =
893 (parent_context.font != parent_context.normalfont);
894 bool const new_layout_allowed =
895 parent_context.new_layout_allowed;
897 parent_context.new_layout_allowed = false;
898 parse_arguments("\\begin{" + name + "}", arguments, p, os,
899 outer, parent_context);
900 if (contents == verbatim)
901 handle_ert(os, p.verbatimEnvironment(name),
904 parse_text_snippet(p, os, FLAG_END, outer,
906 handle_ert(os, "\\end{" + name + "}", parent_context);
908 parent_context.new_layout_allowed = new_layout_allowed;
912 parse_unknown_environment(p, name, os, FLAG_END, outer,
915 active_environments.pop_back();
919 /// parses a comment and outputs it to \p os.
920 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
922 BOOST_ASSERT(t.cat() == catComment);
923 if (!t.cs().empty()) {
924 context.check_layout(os);
925 handle_comment(os, '%' + t.cs(), context);
926 if (p.next_token().cat() == catNewline) {
927 // A newline after a comment line starts a new
929 if (context.new_layout_allowed) {
930 if(!context.atParagraphStart())
931 // Only start a new paragraph if not already
932 // done (we might get called recursively)
933 context.new_paragraph(os);
935 handle_ert(os, "\n", context);
936 eat_whitespace(p, os, context, true);
946 * Reads spaces and comments until the first non-space, non-comment token.
947 * New paragraphs (double newlines or \\par) are handled like simple spaces
948 * if \p eatParagraph is true.
949 * Spaces are skipped, but comments are written to \p os.
951 void eat_whitespace(Parser & p, ostream & os, Context & context,
955 Token const & t = p.get_token();
956 if (t.cat() == catComment)
957 parse_comment(p, os, t, context);
958 else if ((! eatParagraph && p.isParagraph()) ||
959 (t.cat() != catSpace && t.cat() != catNewline)) {
968 * Set a font attribute, parse text and reset the font attribute.
969 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
970 * \param currentvalue Current value of the attribute. Is set to the new
971 * value during parsing.
972 * \param newvalue New value of the attribute
974 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
975 Context & context, string const & attribute,
976 string & currentvalue, string const & newvalue)
978 context.check_layout(os);
979 string const oldvalue = currentvalue;
980 currentvalue = newvalue;
981 os << '\n' << attribute << ' ' << newvalue << "\n";
982 parse_text_snippet(p, os, flags, outer, context);
983 context.check_layout(os);
984 os << '\n' << attribute << ' ' << oldvalue << "\n";
985 currentvalue = oldvalue;
989 /// get the arguments of a natbib or jurabib citation command
990 void get_cite_arguments(Parser & p, bool natbibOrder,
991 string & before, string & after)
993 // We need to distinguish "" and "[]", so we can't use p.getOpt().
995 // text before the citation
997 // text after the citation
998 after = p.getFullOpt();
1000 if (!after.empty()) {
1001 before = p.getFullOpt();
1002 if (natbibOrder && !before.empty())
1003 swap(before, after);
1008 /// Convert filenames with TeX macros and/or quotes to something LyX
1010 string const normalize_filename(string const & name)
1012 Parser p(trim(name, "\""));
1015 Token const & t = p.get_token();
1016 if (t.cat() != catEscape)
1018 else if (t.cs() == "lyxdot") {
1019 // This is used by LyX for simple dots in relative
1023 } else if (t.cs() == "space") {
1033 /// Convert \p name from TeX convention (relative to master file) to LyX
1034 /// convention (relative to .lyx file) if it is relative
1035 void fix_relative_filename(string & name)
1037 FileName fname(name);
1038 if (fname.isAbsolute())
1041 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1043 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1044 from_utf8(getParentFilePath())));
1048 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1049 void parse_noweb(Parser & p, ostream & os, Context & context)
1051 // assemble the rest of the keyword
1055 Token const & t = p.get_token();
1056 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1059 scrap = (p.good() && p.next_token().asInput() == "=");
1061 name += p.get_token().asInput();
1064 name += t.asInput();
1067 if (!scrap || !context.new_layout_allowed ||
1068 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1069 cerr << "Warning: Could not interpret '" << name
1070 << "'. Ignoring it." << endl;
1074 // We use new_paragraph instead of check_end_layout because the stuff
1075 // following the noweb chunk needs to start with a \begin_layout.
1076 // This may create a new paragraph even if there was none in the
1077 // noweb file, but the alternative is an invalid LyX file. Since
1078 // noweb code chunks are implemented with a layout style in LyX they
1079 // always must be in an own paragraph.
1080 context.new_paragraph(os);
1081 Context newcontext(true, context.textclass,
1082 &context.textclass[from_ascii("Scrap")]);
1083 newcontext.check_layout(os);
1086 Token const & t = p.get_token();
1087 // We abuse the parser a bit, because this is no TeX syntax
1089 if (t.cat() == catEscape)
1090 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1092 os << subst(t.asInput(), "\n", "\n\\newline\n");
1093 // The scrap chunk is ended by an @ at the beginning of a line.
1094 // After the @ the line may contain a comment and/or
1095 // whitespace, but nothing else.
1096 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1097 (p.next_token().cat() == catSpace ||
1098 p.next_token().cat() == catNewline ||
1099 p.next_token().cat() == catComment)) {
1100 while (p.good() && p.next_token().cat() == catSpace)
1101 os << p.get_token().asInput();
1102 if (p.next_token().cat() == catComment)
1103 // The comment includes a final '\n'
1104 os << p.get_token().asInput();
1106 if (p.next_token().cat() == catNewline)
1113 newcontext.check_end_layout(os);
1116 } // anonymous namespace
1119 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1122 Layout const * newlayout = 0;
1123 // store the current selectlanguage to be used after \foreignlanguage
1125 // Store the latest bibliographystyle (needed for bibtex inset)
1126 string bibliographystyle;
1127 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1128 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1130 Token const & t = p.get_token();
1133 cerr << "t: " << t << " flags: " << flags << "\n";
1136 if (flags & FLAG_ITEM) {
1137 if (t.cat() == catSpace)
1140 flags &= ~FLAG_ITEM;
1141 if (t.cat() == catBegin) {
1142 // skip the brace and collect everything to the next matching
1144 flags |= FLAG_BRACE_LAST;
1148 // handle only this single token, leave the loop if done
1149 flags |= FLAG_LEAVE;
1152 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1158 if (t.cat() == catMath) {
1159 // we are inside some text mode thingy, so opening new math is allowed
1160 context.check_layout(os);
1161 begin_inset(os, "Formula ");
1162 Token const & n = p.get_token();
1163 if (n.cat() == catMath && outer) {
1164 // TeX's $$...$$ syntax for displayed math
1166 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1168 p.get_token(); // skip the second '$' token
1170 // simple $...$ stuff
1173 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1179 else if (t.cat() == catSuper || t.cat() == catSub)
1180 cerr << "catcode " << t << " illegal in text mode\n";
1182 // Basic support for english quotes. This should be
1183 // extended to other quotes, but is not so easy (a
1184 // left english quote is the same as a right german
1186 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1187 context.check_layout(os);
1188 begin_inset(os, "Quotes ");
1194 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1195 context.check_layout(os);
1196 begin_inset(os, "Quotes ");
1203 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1204 context.check_layout(os);
1205 begin_inset(os, "Quotes ");
1212 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1213 context.check_layout(os);
1214 begin_inset(os, "Quotes ");
1221 else if (t.asInput() == "<"
1222 && p.next_token().asInput() == "<" && noweb_mode) {
1224 parse_noweb(p, os, context);
1227 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1228 check_space(p, os, context);
1230 else if (t.character() == '[' && noweb_mode &&
1231 p.next_token().character() == '[') {
1232 // These can contain underscores
1234 string const s = p.getFullOpt() + ']';
1235 if (p.next_token().character() == ']')
1238 cerr << "Warning: Inserting missing ']' in '"
1239 << s << "'." << endl;
1240 handle_ert(os, s, context);
1243 else if (t.cat() == catLetter ||
1244 t.cat() == catOther ||
1245 t.cat() == catAlign ||
1246 t.cat() == catParameter) {
1247 // This translates "&" to "\\&" which may be wrong...
1248 context.check_layout(os);
1249 os << t.character();
1252 else if (p.isParagraph()) {
1253 if (context.new_layout_allowed)
1254 context.new_paragraph(os);
1256 handle_ert(os, "\\par ", context);
1257 eat_whitespace(p, os, context, true);
1260 else if (t.cat() == catActive) {
1261 context.check_layout(os);
1262 if (t.character() == '~') {
1263 if (context.layout->free_spacing)
1266 os << "\\InsetSpace ~\n";
1268 os << t.character();
1271 else if (t.cat() == catBegin &&
1272 p.next_token().cat() == catEnd) {
1274 Token const prev = p.prev_token();
1276 if (p.next_token().character() == '`' ||
1277 (prev.character() == '-' &&
1278 p.next_token().character() == '-'))
1279 ; // ignore it in {}`` or -{}-
1281 handle_ert(os, "{}", context);
1285 else if (t.cat() == catBegin) {
1286 context.check_layout(os);
1287 // special handling of font attribute changes
1288 Token const prev = p.prev_token();
1289 Token const next = p.next_token();
1290 TeXFont const oldFont = context.font;
1291 if (next.character() == '[' ||
1292 next.character() == ']' ||
1293 next.character() == '*') {
1295 if (p.next_token().cat() == catEnd) {
1296 os << next.character();
1300 handle_ert(os, "{", context);
1301 parse_text_snippet(p, os,
1304 handle_ert(os, "}", context);
1306 } else if (! context.new_layout_allowed) {
1307 handle_ert(os, "{", context);
1308 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1310 handle_ert(os, "}", context);
1311 } else if (is_known(next.cs(), known_sizes)) {
1312 // next will change the size, so we must
1314 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1316 if (!context.atParagraphStart())
1318 << context.font.size << "\n";
1319 } else if (is_known(next.cs(), known_font_families)) {
1320 // next will change the font family, so we
1321 // must reset it here
1322 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1324 if (!context.atParagraphStart())
1326 << context.font.family << "\n";
1327 } else if (is_known(next.cs(), known_font_series)) {
1328 // next will change the font series, so we
1329 // must reset it here
1330 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1332 if (!context.atParagraphStart())
1334 << context.font.series << "\n";
1335 } else if (is_known(next.cs(), known_font_shapes)) {
1336 // next will change the font shape, so we
1337 // must reset it here
1338 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1340 if (!context.atParagraphStart())
1342 << context.font.shape << "\n";
1343 } else if (is_known(next.cs(), known_old_font_families) ||
1344 is_known(next.cs(), known_old_font_series) ||
1345 is_known(next.cs(), known_old_font_shapes)) {
1346 // next will change the font family, series
1347 // and shape, so we must reset it here
1348 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1350 if (!context.atParagraphStart())
1352 << context.font.family
1354 << context.font.series
1356 << context.font.shape << "\n";
1358 handle_ert(os, "{", context);
1359 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1361 handle_ert(os, "}", context);
1365 else if (t.cat() == catEnd) {
1366 if (flags & FLAG_BRACE_LAST) {
1369 cerr << "stray '}' in text\n";
1370 handle_ert(os, "}", context);
1373 else if (t.cat() == catComment)
1374 parse_comment(p, os, t, context);
1377 // control sequences
1380 else if (t.cs() == "(") {
1381 context.check_layout(os);
1382 begin_inset(os, "Formula");
1384 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1389 else if (t.cs() == "[") {
1390 context.check_layout(os);
1391 begin_inset(os, "Formula");
1393 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1398 else if (t.cs() == "begin")
1399 parse_environment(p, os, outer, context);
1401 else if (t.cs() == "end") {
1402 if (flags & FLAG_END) {
1403 // eat environment name
1404 string const name = p.getArg('{', '}');
1405 if (name != active_environment())
1406 cerr << "\\end{" + name + "} does not match \\begin{"
1407 + active_environment() + "}\n";
1410 p.error("found 'end' unexpectedly");
1413 else if (t.cs() == "item") {
1416 bool optarg = false;
1417 if (p.next_token().character() == '[') {
1418 p.get_token(); // eat '['
1419 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1424 context.check_layout(os);
1425 if (context.has_item) {
1426 // An item in an unknown list-like environment
1427 // FIXME: Do this in check_layout()!
1428 context.has_item = false;
1430 handle_ert(os, "\\item", context);
1432 handle_ert(os, "\\item ", context);
1435 if (context.layout->labeltype != LABEL_MANUAL) {
1436 // lyx does not support \item[\mybullet]
1437 // in itemize environments
1438 handle_ert(os, "[", context);
1440 handle_ert(os, "]", context);
1441 } else if (!s.empty()) {
1442 // The space is needed to separate the
1443 // item from the rest of the sentence.
1445 eat_whitespace(p, os, context, false);
1450 else if (t.cs() == "bibitem") {
1452 context.check_layout(os);
1455 os << '{' << p.verbatim_item() << '}' << "\n";
1458 else if(t.cs() == "global") {
1459 // skip global which can appear in front of e.g. "def"
1462 else if (t.cs() == "def") {
1463 context.check_layout(os);
1464 eat_whitespace(p, os, context, false);
1465 string name = p.get_token().cs();
1466 eat_whitespace(p, os, context, false);
1472 while (p.next_token().cat() != catBegin) {
1473 if (p.next_token().cat() == catParameter) {
1478 // followed by number?
1479 if (p.next_token().cat() == catOther) {
1480 char c = p.getChar();
1482 // number = current arity + 1?
1483 if (c == arity + '0' + 1)
1488 paramtext += p.get_token().asString();
1490 paramtext += p.get_token().asString();
1495 // only output simple (i.e. compatible) macro as FormulaMacros
1496 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1498 context.check_layout(os);
1499 begin_inset(os, "FormulaMacro");
1503 handle_ert(os, ert, context);
1506 else if (t.cs() == "noindent") {
1508 context.add_extra_stuff("\\noindent\n");
1511 else if (t.cs() == "appendix") {
1512 context.add_extra_stuff("\\start_of_appendix\n");
1513 // We need to start a new paragraph. Otherwise the
1514 // appendix in 'bla\appendix\chapter{' would start
1516 context.new_paragraph(os);
1517 // We need to make sure that the paragraph is
1518 // generated even if it is empty. Otherwise the
1519 // appendix in '\par\appendix\par\chapter{' would
1521 context.check_layout(os);
1522 // FIXME: This is a hack to prevent paragraph
1523 // deletion if it is empty. Handle this better!
1525 "%dummy comment inserted by tex2lyx to "
1526 "ensure that this paragraph is not empty",
1528 // Both measures above may generate an additional
1529 // empty paragraph, but that does not hurt, because
1530 // whitespace does not matter here.
1531 eat_whitespace(p, os, context, true);
1534 // Must attempt to parse "Section*" before "Section".
1535 else if ((p.next_token().asInput() == "*") &&
1536 context.new_layout_allowed &&
1537 // The single '=' is meant here.
1538 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1539 newlayout->isCommand()) {
1541 output_command_layout(os, p, outer, context, newlayout);
1545 // The single '=' is meant here.
1546 else if (context.new_layout_allowed &&
1547 (newlayout = findLayout(context.textclass, t.cs())) &&
1548 newlayout->isCommand()) {
1549 output_command_layout(os, p, outer, context, newlayout);
1553 // Special handling for \caption
1554 // FIXME: remove this when InsetCaption is supported.
1555 else if (context.new_layout_allowed &&
1556 t.cs() == captionlayout()->latexname()) {
1557 output_command_layout(os, p, outer, context,
1562 else if (t.cs() == "includegraphics") {
1563 bool const clip = p.next_token().asInput() == "*";
1566 map<string, string> opts = split_map(p.getArg('[', ']'));
1568 opts["clip"] = string();
1569 string name = normalize_filename(p.verbatim_item());
1571 string const path = getMasterFilePath();
1572 // We want to preserve relative / absolute filenames,
1573 // therefore path is only used for testing
1574 // FIXME UNICODE encoding of name and path may be
1575 // wrong (makeAbsPath expects utf8)
1576 if (!makeAbsPath(name, path).exists()) {
1577 // The file extension is probably missing.
1578 // Now try to find it out.
1579 string const dvips_name =
1580 find_file(name, path,
1581 known_dvips_graphics_formats);
1582 string const pdftex_name =
1583 find_file(name, path,
1584 known_pdftex_graphics_formats);
1585 if (!dvips_name.empty()) {
1586 if (!pdftex_name.empty()) {
1587 cerr << "This file contains the "
1589 "\"\\includegraphics{"
1591 "However, files\n\""
1592 << dvips_name << "\" and\n\""
1593 << pdftex_name << "\"\n"
1594 "both exist, so I had to make a "
1595 "choice and took the first one.\n"
1596 "Please move the unwanted one "
1597 "someplace else and try again\n"
1598 "if my choice was wrong."
1602 } else if (!pdftex_name.empty())
1606 // FIXME UNICODE encoding of name and path may be
1607 // wrong (makeAbsPath expects utf8)
1608 if (makeAbsPath(name, path).exists())
1609 fix_relative_filename(name);
1611 cerr << "Warning: Could not find graphics file '"
1612 << name << "'." << endl;
1614 context.check_layout(os);
1615 begin_inset(os, "Graphics ");
1616 os << "\n\tfilename " << name << '\n';
1617 if (opts.find("width") != opts.end())
1619 << translate_len(opts["width"]) << '\n';
1620 if (opts.find("height") != opts.end())
1622 << translate_len(opts["height"]) << '\n';
1623 if (opts.find("scale") != opts.end()) {
1624 istringstream iss(opts["scale"]);
1628 os << "\tscale " << val << '\n';
1630 if (opts.find("angle") != opts.end())
1631 os << "\trotateAngle "
1632 << opts["angle"] << '\n';
1633 if (opts.find("origin") != opts.end()) {
1635 string const opt = opts["origin"];
1636 if (opt.find('l') != string::npos) ss << "left";
1637 if (opt.find('r') != string::npos) ss << "right";
1638 if (opt.find('c') != string::npos) ss << "center";
1639 if (opt.find('t') != string::npos) ss << "Top";
1640 if (opt.find('b') != string::npos) ss << "Bottom";
1641 if (opt.find('B') != string::npos) ss << "Baseline";
1642 if (!ss.str().empty())
1643 os << "\trotateOrigin " << ss.str() << '\n';
1645 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1647 if (opts.find("keepaspectratio") != opts.end())
1648 os << "\tkeepAspectRatio\n";
1649 if (opts.find("clip") != opts.end())
1651 if (opts.find("draft") != opts.end())
1653 if (opts.find("bb") != opts.end())
1654 os << "\tBoundingBox "
1655 << opts["bb"] << '\n';
1656 int numberOfbbOptions = 0;
1657 if (opts.find("bbllx") != opts.end())
1658 numberOfbbOptions++;
1659 if (opts.find("bblly") != opts.end())
1660 numberOfbbOptions++;
1661 if (opts.find("bburx") != opts.end())
1662 numberOfbbOptions++;
1663 if (opts.find("bbury") != opts.end())
1664 numberOfbbOptions++;
1665 if (numberOfbbOptions == 4)
1666 os << "\tBoundingBox "
1667 << opts["bbllx"] << " " << opts["bblly"] << " "
1668 << opts["bburx"] << " " << opts["bbury"] << '\n';
1669 else if (numberOfbbOptions > 0)
1670 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1671 numberOfbbOptions = 0;
1672 if (opts.find("natwidth") != opts.end())
1673 numberOfbbOptions++;
1674 if (opts.find("natheight") != opts.end())
1675 numberOfbbOptions++;
1676 if (numberOfbbOptions == 2)
1677 os << "\tBoundingBox 0bp 0bp "
1678 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1679 else if (numberOfbbOptions > 0)
1680 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1681 ostringstream special;
1682 if (opts.find("hiresbb") != opts.end())
1683 special << "hiresbb,";
1684 if (opts.find("trim") != opts.end())
1686 if (opts.find("viewport") != opts.end())
1687 special << "viewport=" << opts["viewport"] << ',';
1688 if (opts.find("totalheight") != opts.end())
1689 special << "totalheight=" << opts["totalheight"] << ',';
1690 if (opts.find("type") != opts.end())
1691 special << "type=" << opts["type"] << ',';
1692 if (opts.find("ext") != opts.end())
1693 special << "ext=" << opts["ext"] << ',';
1694 if (opts.find("read") != opts.end())
1695 special << "read=" << opts["read"] << ',';
1696 if (opts.find("command") != opts.end())
1697 special << "command=" << opts["command"] << ',';
1698 string s_special = special.str();
1699 if (!s_special.empty()) {
1700 // We had special arguments. Remove the trailing ','.
1701 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1703 // TODO: Handle the unknown settings better.
1704 // Warn about invalid options.
1705 // Check whether some option was given twice.
1709 else if (t.cs() == "footnote" ||
1710 (t.cs() == "thanks" && context.layout->intitle)) {
1712 context.check_layout(os);
1713 begin_inset(os, "Foot\n");
1714 os << "status collapsed\n\n";
1715 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1719 else if (t.cs() == "marginpar") {
1721 context.check_layout(os);
1722 begin_inset(os, "Marginal\n");
1723 os << "status collapsed\n\n";
1724 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1728 else if (t.cs() == "ensuremath") {
1730 context.check_layout(os);
1731 string const s = p.verbatim_item();
1732 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1735 handle_ert(os, "\\ensuremath{" + s + "}",
1739 else if (t.cs() == "hfill") {
1740 context.check_layout(os);
1741 os << "\n\\hfill\n";
1746 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1747 // FIXME: Somehow prevent title layouts if
1748 // "maketitle" was not found
1750 skip_braces(p); // swallow this
1753 else if (t.cs() == "tableofcontents") {
1755 context.check_layout(os);
1756 begin_inset(os, "LatexCommand \\tableofcontents\n");
1758 skip_braces(p); // swallow this
1761 else if (t.cs() == "listoffigures") {
1763 context.check_layout(os);
1764 begin_inset(os, "FloatList figure\n");
1766 skip_braces(p); // swallow this
1769 else if (t.cs() == "listoftables") {
1771 context.check_layout(os);
1772 begin_inset(os, "FloatList table\n");
1774 skip_braces(p); // swallow this
1777 else if (t.cs() == "listof") {
1778 p.skip_spaces(true);
1779 string const name = p.get_token().asString();
1780 if (context.textclass.floats().typeExist(name)) {
1781 context.check_layout(os);
1782 begin_inset(os, "FloatList ");
1785 p.get_token(); // swallow second arg
1787 handle_ert(os, "\\listof{" + name + "}", context);
1790 else if (t.cs() == "textrm")
1791 parse_text_attributes(p, os, FLAG_ITEM, outer,
1792 context, "\\family",
1793 context.font.family, "roman");
1795 else if (t.cs() == "textsf")
1796 parse_text_attributes(p, os, FLAG_ITEM, outer,
1797 context, "\\family",
1798 context.font.family, "sans");
1800 else if (t.cs() == "texttt")
1801 parse_text_attributes(p, os, FLAG_ITEM, outer,
1802 context, "\\family",
1803 context.font.family, "typewriter");
1805 else if (t.cs() == "textmd")
1806 parse_text_attributes(p, os, FLAG_ITEM, outer,
1807 context, "\\series",
1808 context.font.series, "medium");
1810 else if (t.cs() == "textbf")
1811 parse_text_attributes(p, os, FLAG_ITEM, outer,
1812 context, "\\series",
1813 context.font.series, "bold");
1815 else if (t.cs() == "textup")
1816 parse_text_attributes(p, os, FLAG_ITEM, outer,
1818 context.font.shape, "up");
1820 else if (t.cs() == "textit")
1821 parse_text_attributes(p, os, FLAG_ITEM, outer,
1823 context.font.shape, "italic");
1825 else if (t.cs() == "textsl")
1826 parse_text_attributes(p, os, FLAG_ITEM, outer,
1828 context.font.shape, "slanted");
1830 else if (t.cs() == "textsc")
1831 parse_text_attributes(p, os, FLAG_ITEM, outer,
1833 context.font.shape, "smallcaps");
1835 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1836 context.check_layout(os);
1837 TeXFont oldFont = context.font;
1838 context.font.init();
1839 context.font.size = oldFont.size;
1840 os << "\n\\family " << context.font.family << "\n";
1841 os << "\n\\series " << context.font.series << "\n";
1842 os << "\n\\shape " << context.font.shape << "\n";
1843 if (t.cs() == "textnormal") {
1844 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1845 output_font_change(os, context.font, oldFont);
1846 context.font = oldFont;
1848 eat_whitespace(p, os, context, false);
1851 else if (t.cs() == "underbar") {
1852 // Do NOT handle \underline.
1853 // \underbar cuts through y, g, q, p etc.,
1854 // \underline does not.
1855 context.check_layout(os);
1856 os << "\n\\bar under\n";
1857 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1858 context.check_layout(os);
1859 os << "\n\\bar default\n";
1862 else if (t.cs() == "emph" || t.cs() == "noun") {
1863 context.check_layout(os);
1864 os << "\n\\" << t.cs() << " on\n";
1865 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1866 context.check_layout(os);
1867 os << "\n\\" << t.cs() << " default\n";
1870 else if (use_natbib &&
1871 is_known(t.cs(), known_natbib_commands) &&
1872 ((t.cs() != "citefullauthor" &&
1873 t.cs() != "citeyear" &&
1874 t.cs() != "citeyearpar") ||
1875 p.next_token().asInput() != "*")) {
1876 context.check_layout(os);
1878 // \citet[before][after]{a} \citet[after][before]{a}
1879 // \citet[before][]{a} \citet[][before]{a}
1880 // \citet[after]{a} \citet[after]{a}
1881 // \citet{a} \citet{a}
1882 string command = '\\' + t.cs();
1883 if (p.next_token().asInput() == "*") {
1887 if (command == "\\citefullauthor")
1888 // alternative name for "\\citeauthor*"
1889 command = "\\citeauthor*";
1891 // text before the citation
1893 // text after the citation
1895 get_cite_arguments(p, true, before, after);
1897 if (command == "\\cite") {
1898 // \cite without optional argument means
1899 // \citet, \cite with at least one optional
1900 // argument means \citep.
1901 if (before.empty() && after.empty())
1902 command = "\\citet";
1904 command = "\\citep";
1906 if (before.empty() && after == "[]")
1907 // avoid \citet[]{a}
1909 else if (before == "[]" && after == "[]") {
1910 // avoid \citet[][]{a}
1914 begin_inset(os, "LatexCommand ");
1915 os << command << after << before
1916 << '{' << p.verbatim_item() << "}\n";
1920 else if (use_jurabib &&
1921 is_known(t.cs(), known_jurabib_commands)) {
1922 context.check_layout(os);
1923 string const command = '\\' + t.cs();
1924 char argumentOrder = '\0';
1925 vector<string> const & options = used_packages["jurabib"];
1926 if (find(options.begin(), options.end(),
1927 "natbiborder") != options.end())
1928 argumentOrder = 'n';
1929 else if (find(options.begin(), options.end(),
1930 "jurabiborder") != options.end())
1931 argumentOrder = 'j';
1933 // text before the citation
1935 // text after the citation
1937 get_cite_arguments(p, argumentOrder != 'j', before, after);
1939 string const citation = p.verbatim_item();
1940 if (!before.empty() && argumentOrder == '\0') {
1941 cerr << "Warning: Assuming argument order "
1942 "of jurabib version 0.6 for\n'"
1943 << command << before << after << '{'
1944 << citation << "}'.\n"
1945 "Add 'jurabiborder' to the jurabib "
1946 "package options if you used an\n"
1947 "earlier jurabib version." << endl;
1949 begin_inset(os, "LatexCommand ");
1950 os << command << after << before
1951 << '{' << citation << "}\n";
1955 else if (is_known(t.cs(), known_latex_commands)) {
1956 // This needs to be after the check for natbib and
1957 // jurabib commands, because "cite" has different
1958 // arguments with natbib and jurabib.
1959 context.check_layout(os);
1960 begin_inset(os, "LatexCommand ");
1961 os << '\\' << t.cs();
1962 // lyx cannot handle newlines in a latex command
1963 // FIXME: Move the substitution into parser::getOpt()?
1964 os << subst(p.getOpt(), "\n", " ");
1965 os << subst(p.getOpt(), "\n", " ");
1966 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1970 else if (is_known(t.cs(), known_quotes)) {
1971 char const * const * where = is_known(t.cs(), known_quotes);
1972 context.check_layout(os);
1973 begin_inset(os, "Quotes ");
1974 os << known_coded_quotes[where - known_quotes];
1976 // LyX adds {} after the quote, so we have to eat
1977 // spaces here if there are any before a possible
1979 eat_whitespace(p, os, context, false);
1983 else if (is_known(t.cs(), known_sizes) &&
1984 context.new_layout_allowed) {
1985 char const * const * where = is_known(t.cs(), known_sizes);
1986 context.check_layout(os);
1987 TeXFont const oldFont = context.font;
1988 context.font.size = known_coded_sizes[where - known_sizes];
1989 output_font_change(os, oldFont, context.font);
1990 eat_whitespace(p, os, context, false);
1993 else if (is_known(t.cs(), known_font_families) &&
1994 context.new_layout_allowed) {
1995 char const * const * where =
1996 is_known(t.cs(), known_font_families);
1997 context.check_layout(os);
1998 TeXFont const oldFont = context.font;
1999 context.font.family =
2000 known_coded_font_families[where - known_font_families];
2001 output_font_change(os, oldFont, context.font);
2002 eat_whitespace(p, os, context, false);
2005 else if (is_known(t.cs(), known_font_series) &&
2006 context.new_layout_allowed) {
2007 char const * const * where =
2008 is_known(t.cs(), known_font_series);
2009 context.check_layout(os);
2010 TeXFont const oldFont = context.font;
2011 context.font.series =
2012 known_coded_font_series[where - known_font_series];
2013 output_font_change(os, oldFont, context.font);
2014 eat_whitespace(p, os, context, false);
2017 else if (is_known(t.cs(), known_font_shapes) &&
2018 context.new_layout_allowed) {
2019 char const * const * where =
2020 is_known(t.cs(), known_font_shapes);
2021 context.check_layout(os);
2022 TeXFont const oldFont = context.font;
2023 context.font.shape =
2024 known_coded_font_shapes[where - known_font_shapes];
2025 output_font_change(os, oldFont, context.font);
2026 eat_whitespace(p, os, context, false);
2028 else if (is_known(t.cs(), known_old_font_families) &&
2029 context.new_layout_allowed) {
2030 char const * const * where =
2031 is_known(t.cs(), known_old_font_families);
2032 context.check_layout(os);
2033 TeXFont const oldFont = context.font;
2034 context.font.init();
2035 context.font.size = oldFont.size;
2036 context.font.family =
2037 known_coded_font_families[where - known_old_font_families];
2038 output_font_change(os, oldFont, context.font);
2039 eat_whitespace(p, os, context, false);
2042 else if (is_known(t.cs(), known_old_font_series) &&
2043 context.new_layout_allowed) {
2044 char const * const * where =
2045 is_known(t.cs(), known_old_font_series);
2046 context.check_layout(os);
2047 TeXFont const oldFont = context.font;
2048 context.font.init();
2049 context.font.size = oldFont.size;
2050 context.font.series =
2051 known_coded_font_series[where - known_old_font_series];
2052 output_font_change(os, oldFont, context.font);
2053 eat_whitespace(p, os, context, false);
2056 else if (is_known(t.cs(), known_old_font_shapes) &&
2057 context.new_layout_allowed) {
2058 char const * const * where =
2059 is_known(t.cs(), known_old_font_shapes);
2060 context.check_layout(os);
2061 TeXFont const oldFont = context.font;
2062 context.font.init();
2063 context.font.size = oldFont.size;
2064 context.font.shape =
2065 known_coded_font_shapes[where - known_old_font_shapes];
2066 output_font_change(os, oldFont, context.font);
2067 eat_whitespace(p, os, context, false);
2070 else if (t.cs() == "selectlanguage") {
2071 context.check_layout(os);
2072 // save the language for the case that a \foreignlanguage is used
2073 selectlang = subst(p.verbatim_item(), "\n", " ");
2074 os << "\\lang " << selectlang << "\n";
2078 else if (t.cs() == "foreignlanguage") {
2079 context.check_layout(os);
2080 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2081 os << subst(p.verbatim_item(), "\n", " ");
2082 // set back to last selectlanguage
2083 os << "\n\\lang " << selectlang << "\n";
2086 else if (t.cs() == "inputencoding")
2087 // write nothing because this is done by LyX using the "\lang"
2088 // information given by selectlanguage and foreignlanguage
2089 subst(p.verbatim_item(), "\n", " ");
2091 else if (t.cs() == "LyX" || t.cs() == "TeX"
2092 || t.cs() == "LaTeX") {
2093 context.check_layout(os);
2095 skip_braces(p); // eat {}
2098 else if (t.cs() == "LaTeXe") {
2099 context.check_layout(os);
2101 skip_braces(p); // eat {}
2104 else if (t.cs() == "ldots") {
2105 context.check_layout(os);
2107 os << "\\SpecialChar \\ldots{}\n";
2110 else if (t.cs() == "lyxarrow") {
2111 context.check_layout(os);
2112 os << "\\SpecialChar \\menuseparator\n";
2116 else if (t.cs() == "textcompwordmark") {
2117 context.check_layout(os);
2118 os << "\\SpecialChar \\textcompwordmark{}\n";
2122 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2123 context.check_layout(os);
2124 os << "\\SpecialChar \\@.\n";
2128 else if (t.cs() == "-") {
2129 context.check_layout(os);
2130 os << "\\SpecialChar \\-\n";
2133 else if (t.cs() == "textasciitilde") {
2134 context.check_layout(os);
2139 else if (t.cs() == "textasciicircum") {
2140 context.check_layout(os);
2145 else if (t.cs() == "textbackslash") {
2146 context.check_layout(os);
2147 os << "\n\\backslash\n";
2151 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2152 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2154 context.check_layout(os);
2158 else if (t.cs() == "char") {
2159 context.check_layout(os);
2160 if (p.next_token().character() == '`') {
2162 if (p.next_token().cs() == "\"") {
2167 handle_ert(os, "\\char`", context);
2170 handle_ert(os, "\\char", context);
2174 else if (t.cs() == "verb") {
2175 context.check_layout(os);
2176 char const delimiter = p.next_token().character();
2177 string const arg = p.getArg(delimiter, delimiter);
2179 oss << "\\verb" << delimiter << arg << delimiter;
2180 handle_ert(os, oss.str(), context);
2183 else if (t.cs() == "\"") {
2184 context.check_layout(os);
2185 string const name = p.verbatim_item();
2186 if (name == "a") os << '\xe4';
2187 else if (name == "o") os << '\xf6';
2188 else if (name == "u") os << '\xfc';
2189 else if (name == "A") os << '\xc4';
2190 else if (name == "O") os << '\xd6';
2191 else if (name == "U") os << '\xdc';
2192 else handle_ert(os, "\"{" + name + "}", context);
2195 // Problem: \= creates a tabstop inside the tabbing environment
2196 // and else an accent. In the latter case we really would want
2197 // \={o} instead of \= o.
2198 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2199 handle_ert(os, t.asInput(), context);
2201 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2202 || t.cs() == "'" || t.cs() == "`"
2203 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2204 // we need the trim as the LyX parser chokes on such spaces
2205 // The argument of InsetLatexAccent is parsed as a
2206 // subset of LaTeX, so don't parse anything here,
2207 // but use the raw argument.
2208 // Otherwise we would convert \~{\i} wrongly.
2209 // This will of course not translate \~{\ss} to \~{ß},
2210 // but that does at least compile and does only look
2211 // strange on screen.
2212 context.check_layout(os);
2213 os << "\\i \\" << t.cs() << "{"
2214 << trim(p.verbatim_item(), " ")
2218 else if (t.cs() == "ss") {
2219 context.check_layout(os);
2221 skip_braces(p); // eat {}
2224 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2226 context.check_layout(os);
2227 os << "\\i \\" << t.cs() << "{}\n";
2228 skip_braces(p); // eat {}
2231 else if (t.cs() == "\\") {
2232 context.check_layout(os);
2233 string const next = p.next_token().asInput();
2235 handle_ert(os, "\\\\" + p.getOpt(), context);
2236 else if (next == "*") {
2238 handle_ert(os, "\\\\*" + p.getOpt(), context);
2241 os << "\n\\newline\n";
2245 else if (t.cs() == "newline" ||
2246 t.cs() == "linebreak") {
2247 context.check_layout(os);
2248 os << "\n\\" << t.cs() << "\n";
2249 skip_braces(p); // eat {}
2252 else if (t.cs() == "href") {
2253 context.check_layout(os);
2254 begin_inset(os, "CommandInset ");
2255 os << t.cs() << "\n";
2256 os << "LatexCommand " << t.cs() << "\n";
2259 // the first argument is "type:target", "type:" is optional
2260 // the second argument the name
2261 string href_target = subst(p.verbatim_item(), "\n", " ");
2262 string href_name = subst(p.verbatim_item(), "\n", " ");
2264 // serach for the ":" to divide type from target
2265 if ((pos = href_target.find(":", 0)) != string::npos){
2266 href_type = href_target;
2267 href_type.erase(pos + 1, href_type.length());
2268 href_target.erase(0, pos + 1);
2271 os << "name " << '"' << href_name << '"' << "\n";
2272 os << "target " << '"' << href_target << '"' << "\n";
2274 os << "type " << '"' << href_type << '"' << "\n";
2278 else if (t.cs() == "input" || t.cs() == "include"
2279 || t.cs() == "verbatiminput") {
2280 string name = '\\' + t.cs();
2281 if (t.cs() == "verbatiminput"
2282 && p.next_token().asInput() == "*")
2283 name += p.get_token().asInput();
2284 context.check_layout(os);
2285 begin_inset(os, "Include ");
2286 string filename(normalize_filename(p.getArg('{', '}')));
2287 string const path = getMasterFilePath();
2288 // We want to preserve relative / absolute filenames,
2289 // therefore path is only used for testing
2290 // FIXME UNICODE encoding of filename and path may be
2291 // wrong (makeAbsPath expects utf8)
2292 if ((t.cs() == "include" || t.cs() == "input") &&
2293 !makeAbsPath(filename, path).exists()) {
2294 // The file extension is probably missing.
2295 // Now try to find it out.
2296 string const tex_name =
2297 find_file(filename, path,
2298 known_tex_extensions);
2299 if (!tex_name.empty())
2300 filename = tex_name;
2302 // FIXME UNICODE encoding of filename and path may be
2303 // wrong (makeAbsPath expects utf8)
2304 if (makeAbsPath(filename, path).exists()) {
2305 string const abstexname =
2306 makeAbsPath(filename, path).absFilename();
2307 string const abslyxname =
2308 changeExtension(abstexname, ".lyx");
2309 fix_relative_filename(filename);
2310 string const lyxname =
2311 changeExtension(filename, ".lyx");
2312 if (t.cs() != "verbatiminput" &&
2313 tex2lyx(abstexname, FileName(abslyxname))) {
2314 os << name << '{' << lyxname << "}\n";
2316 os << name << '{' << filename << "}\n";
2319 cerr << "Warning: Could not find included file '"
2320 << filename << "'." << endl;
2321 os << name << '{' << filename << "}\n";
2323 os << "preview false\n";
2327 else if (t.cs() == "bibliographystyle") {
2328 // store new bibliographystyle
2329 bibliographystyle = p.verbatim_item();
2330 // output new bibliographystyle.
2331 // This is only necessary if used in some other macro than \bibliography.
2332 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2335 else if (t.cs() == "bibliography") {
2336 context.check_layout(os);
2337 begin_inset(os, "LatexCommand ");
2339 // Do we have a bibliographystyle set?
2340 if (!bibliographystyle.empty()) {
2341 os << '[' << bibliographystyle << ']';
2343 os << '{' << p.verbatim_item() << "}\n";
2347 else if (t.cs() == "parbox")
2348 parse_box(p, os, FLAG_ITEM, outer, context, true);
2350 else if (t.cs() == "smallskip" ||
2351 t.cs() == "medskip" ||
2352 t.cs() == "bigskip" ||
2353 t.cs() == "vfill") {
2354 context.check_layout(os);
2355 begin_inset(os, "VSpace ");
2361 else if (is_known(t.cs(), known_spaces)) {
2362 char const * const * where = is_known(t.cs(), known_spaces);
2363 context.check_layout(os);
2364 begin_inset(os, "InsetSpace ");
2365 os << '\\' << known_coded_spaces[where - known_spaces]
2367 // LaTeX swallows whitespace after all spaces except
2368 // "\\,". We have to do that here, too, because LyX
2369 // adds "{}" which would make the spaces significant.
2371 eat_whitespace(p, os, context, false);
2372 // LyX adds "{}" after all spaces except "\\ " and
2373 // "\\,", so we have to remove "{}".
2374 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2375 // remove the braces after "\\,", too.
2380 else if (t.cs() == "newpage" ||
2381 t.cs() == "pagebreak" ||
2382 t.cs() == "clearpage" ||
2383 t.cs() == "cleardoublepage") {
2384 context.check_layout(os);
2385 os << "\n\\" << t.cs() << "\n";
2386 skip_braces(p); // eat {}
2389 else if (t.cs() == "newcommand" ||
2390 t.cs() == "providecommand" ||
2391 t.cs() == "renewcommand" ||
2392 t.cs() == "newlyxcommand") {
2393 // these could be handled by parse_command(), but
2394 // we need to call add_known_command() here.
2395 string name = t.asInput();
2396 if (p.next_token().asInput() == "*") {
2397 // Starred form. Eat '*'
2401 string const command = p.verbatim_item();
2402 string const opt1 = p.getOpt();
2404 unsigned optionalsNum = 0;
2406 string const opt = p.getFullOpt();
2412 add_known_command(command, opt1, optionalsNum);
2413 string const ert = name + '{' + command + '}' + opt1
2414 + optionals + '{' + p.verbatim_item() + '}';
2416 context.check_layout(os);
2417 begin_inset(os, "FormulaMacro");
2422 else if (t.cs() == "newcommandx" ||
2423 t.cs() == "renewcommandx") {
2424 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
2428 if (p.next_token().cat() == catBegin)
2429 command = p.verbatim_item();
2431 command = "\\" + p.get_token().cs();
2433 // get arity, we do not check that it fits to the given
2434 // optional parameters here.
2435 string const opt1 = p.getOpt();
2437 // get options and default values for optional parameters
2438 std::vector<string> optionalValues;
2439 int optionalsNum = 0;
2440 if (p.next_token().character() == '[') {
2444 // handle 'opt=value' options, separated by ','.
2445 eat_whitespace(p, os, context, false);
2446 while (p.next_token().character() != ']' && p.good()) {
2447 char_type nextc = p.next_token().character();
2448 if (nextc >= '1' && nextc <= '9') {
2449 // optional value -> get parameter number
2450 int n = p.getChar() - '0';
2453 if (p.next_token().character() != '=') {
2454 cerr << "'=' expected after numeral option of \\newcommandx" << std::endl;
2455 // try to find ] or ,
2456 while (p.next_token().character() != ','
2457 && p.next_token().character() != ']')
2464 optionalValues.resize(max(size_t(n), optionalValues.size()));
2465 optionalValues[n - 1].clear();
2466 while (p.next_token().character() != ']'
2467 && p.next_token().character() != ',')
2468 optionalValues[n - 1] += p.verbatim_item();
2469 optionalsNum = max(n, optionalsNum);
2470 } else if (p.next_token().cat() == catLetter) {
2471 // we in fact ignore every non-optional
2476 while (p.next_token().cat() == catLetter)
2480 eat_whitespace(p, os, context, false);
2481 if (p.next_token().character() == '=') {
2483 while (p.next_token().character() != ']'
2484 && p.next_token().character() != ',')
2491 eat_whitespace(p, os, context, false);
2492 if (p.next_token().character() == ',') {
2494 eat_whitespace(p, os, context, false);
2495 } else if (p.next_token().character() != ']')
2503 // concat the default values to the optionals string
2505 for (unsigned i = 0; i < optionalValues.size(); ++i)
2506 optionals += "[" + optionalValues[i] + "]";
2508 // register and output command
2509 add_known_command(command, opt1, optionalsNum);
2510 string const ert = "\\newcommand{" + command + '}' + opt1
2511 + optionals + '{' + p.verbatim_item() + '}';
2513 context.check_layout(os);
2514 begin_inset(os, "FormulaMacro");
2519 else if (t.cs() == "vspace") {
2520 bool starred = false;
2521 if (p.next_token().asInput() == "*") {
2525 string const length = p.verbatim_item();
2528 bool valid = splitLatexLength(length, valstring, unit);
2529 bool known_vspace = false;
2530 bool known_unit = false;
2533 istringstream iss(valstring);
2536 if (unit == "\\smallskipamount") {
2538 known_vspace = true;
2539 } else if (unit == "\\medskipamount") {
2541 known_vspace = true;
2542 } else if (unit == "\\bigskipamount") {
2544 known_vspace = true;
2545 } else if (unit == "\\fill") {
2547 known_vspace = true;
2550 if (!known_vspace) {
2551 switch (unitFromString(unit)) {
2572 if (known_unit || known_vspace) {
2573 // Literal length or known variable
2574 context.check_layout(os);
2575 begin_inset(os, "VSpace ");
2583 // LyX can't handle other length variables in Inset VSpace
2584 string name = t.asInput();
2589 handle_ert(os, name + '{' + unit + '}', context);
2590 else if (value == -1.0)
2591 handle_ert(os, name + "{-" + unit + '}', context);
2593 handle_ert(os, name + '{' + valstring + unit + '}', context);
2595 handle_ert(os, name + '{' + length + '}', context);
2600 //cerr << "#: " << t << " mode: " << mode << endl;
2601 // heuristic: read up to next non-nested space
2603 string s = t.asInput();
2604 string z = p.verbatim_item();
2605 while (p.good() && z != " " && z.size()) {
2606 //cerr << "read: " << z << endl;
2608 z = p.verbatim_item();
2610 cerr << "found ERT: " << s << endl;
2611 handle_ert(os, s + ' ', context);
2613 string name = t.asInput();
2614 if (p.next_token().asInput() == "*") {
2615 // Starred commands like \vspace*{}
2616 p.get_token(); // Eat '*'
2619 if (! parse_command(name, p, os, outer, context))
2620 handle_ert(os, name, context);
2623 if (flags & FLAG_LEAVE) {
2624 flags &= ~FLAG_LEAVE;