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.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
122 * The starred forms are also known except for "citefullauthor",
123 * "citeyear" and "citeyearpar".
125 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
131 * No starred form other than "cite*" known.
133 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
134 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
135 // jurabib commands not (yet) supported by LyX:
137 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
138 // "footciteauthor", "footciteyear", "footciteyearpar",
139 "citefield", "citetitle", 0 };
141 /// LaTeX names for quotes
142 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
143 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
144 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
145 "guilsinglleft", "frq", "guilsinglright", 0};
147 /// the same as known_quotes with .lyx names
148 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
149 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
150 "gld", "grd", "gls", "ers", "fls",
151 "fls", "frs", "frs", 0};
153 /// LaTeX names for font sizes
154 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
155 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
157 /// the same as known_sizes with .lyx names
158 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
159 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
161 /// LaTeX 2.09 names for font families
162 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
164 /// LaTeX names for font families
165 char const * const known_font_families[] = { "rmfamily", "sffamily",
168 /// LaTeX names for font family changing commands
169 char const * const known_text_font_families[] = { "textrm", "textsf",
172 /// The same as known_old_font_families, known_font_families and
173 /// known_text_font_families with .lyx names
174 char const * const known_coded_font_families[] = { "roman", "sans",
177 /// LaTeX 2.09 names for font series
178 char const * const known_old_font_series[] = { "bf", 0};
180 /// LaTeX names for font series
181 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
183 /// LaTeX names for font series changing commands
184 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
186 /// The same as known_old_font_series, known_font_series and
187 /// known_text_font_series with .lyx names
188 char const * const known_coded_font_series[] = { "bold", "medium", 0};
190 /// LaTeX 2.09 names for font shapes
191 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
193 /// LaTeX names for font shapes
194 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
197 /// LaTeX names for font shape changing commands
198 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
201 /// The same as known_old_font_shapes, known_font_shapes and
202 /// known_text_font_shapes with .lyx names
203 char const * const known_coded_font_shapes[] = { "italic", "slanted",
204 "smallcaps", "up", 0};
206 /// Known special characters which need skip_spaces_braces() afterwards
207 char const * const known_special_chars[] = {"ldots", "lyxarrow",
208 "textcompwordmark", "slash", 0};
210 /// the same as known_special_chars with .lyx names
211 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
212 "textcompwordmark{}", "slash{}", 0};
215 * Graphics file extensions known by the dvips driver of the graphics package.
216 * These extensions are used to complete the filename of an included
217 * graphics file if it does not contain an extension.
218 * The order must be the same that latex uses to find a file, because we
219 * will use the first extension that matches.
220 * This is only an approximation for the common cases. If we would want to
221 * do it right in all cases, we would need to know which graphics driver is
222 * used and know the extensions of every driver of the graphics package.
224 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
225 "ps.gz", "eps.Z", "ps.Z", 0};
228 * Graphics file extensions known by the pdftex driver of the graphics package.
229 * \sa known_dvips_graphics_formats
231 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
235 * Known file extensions for TeX files as used by \\include.
237 char const * const known_tex_extensions[] = {"tex", 0};
239 /// spaces known by InsetSpace
240 char const * const known_spaces[] = { " ", "space", ",",
241 "thinspace", "quad", "qquad", "enspace", "enskip",
242 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
243 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
244 "upbracefill", "downbracefill", 0};
246 /// the same as known_spaces with .lyx names
247 char const * const known_coded_spaces[] = { "space{}", "space{}",
248 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
249 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
250 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
251 "upbracefill{}", "downbracefill{}", 0};
253 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
254 /// them in ERT. "LaTeXe" must come before "LaTeX"!
255 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
256 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
257 int const known_phrase_lengths[] = {3, 5, 7, 0};
259 // string to store the float type to be able to determine the type of subfloats
260 string float_type = "";
263 /// splits "x=z, y=b" into a map and an ordered keyword vector
264 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
269 keys.resize(v.size());
270 for (size_t i = 0; i < v.size(); ++i) {
271 size_t const pos = v[i].find('=');
272 string const index = trimSpaceAndEol(v[i].substr(0, pos));
273 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
281 * Split a LaTeX length into value and unit.
282 * The latter can be a real unit like "pt", or a latex length variable
283 * like "\textwidth". The unit may contain additional stuff like glue
284 * lengths, but we don't care, because such lengths are ERT anyway.
285 * \returns true if \p value and \p unit are valid.
287 bool splitLatexLength(string const & len, string & value, string & unit)
291 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
292 //'4,5' is a valid LaTeX length number. Change it to '4.5'
293 string const length = subst(len, ',', '.');
294 if (i == string::npos)
297 if (len[0] == '\\') {
298 // We had something like \textwidth without a factor
304 value = trimSpaceAndEol(string(length, 0, i));
308 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
309 if (contains(len, '\\'))
310 unit = trimSpaceAndEol(string(len, i));
312 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
317 /// A simple function to translate a latex length to something LyX can
318 /// understand. Not perfect, but rather best-effort.
319 bool translate_len(string const & length, string & valstring, string & unit)
321 if (!splitLatexLength(length, valstring, unit))
323 // LyX uses percent values
325 istringstream iss(valstring);
330 string const percentval = oss.str();
332 if (unit.empty() || unit[0] != '\\')
334 string::size_type const i = unit.find(' ');
335 string const endlen = (i == string::npos) ? string() : string(unit, i);
336 if (unit == "\\textwidth") {
337 valstring = percentval;
338 unit = "text%" + endlen;
339 } else if (unit == "\\columnwidth") {
340 valstring = percentval;
341 unit = "col%" + endlen;
342 } else if (unit == "\\paperwidth") {
343 valstring = percentval;
344 unit = "page%" + endlen;
345 } else if (unit == "\\linewidth") {
346 valstring = percentval;
347 unit = "line%" + endlen;
348 } else if (unit == "\\paperheight") {
349 valstring = percentval;
350 unit = "pheight%" + endlen;
351 } else if (unit == "\\textheight") {
352 valstring = percentval;
353 unit = "theight%" + endlen;
361 string translate_len(string const & length)
365 if (translate_len(length, value, unit))
367 // If the input is invalid, return what we have.
375 * Translates a LaTeX length into \p value, \p unit and
376 * \p special parts suitable for a box inset.
377 * The difference from translate_len() is that a box inset knows about
378 * some special "units" that are stored in \p special.
380 void translate_box_len(string const & length, string & value, string & unit, string & special)
382 if (translate_len(length, value, unit)) {
383 if (unit == "\\height" || unit == "\\depth" ||
384 unit == "\\totalheight" || unit == "\\width") {
385 special = unit.substr(1);
386 // The unit is not used, but LyX requires a dummy setting
399 * Find a file with basename \p name in path \p path and an extension
402 string find_file(string const & name, string const & path,
403 char const * const * extensions)
405 for (char const * const * what = extensions; *what; ++what) {
406 string const trial = addExtension(name, *what);
407 if (makeAbsPath(trial, path).exists())
414 void begin_inset(ostream & os, string const & name)
416 os << "\n\\begin_inset " << name;
420 void begin_command_inset(ostream & os, string const & name,
421 string const & latexname)
423 begin_inset(os, "CommandInset ");
424 os << name << "\nLatexCommand " << latexname << '\n';
428 void end_inset(ostream & os)
430 os << "\n\\end_inset\n\n";
434 bool skip_braces(Parser & p)
436 if (p.next_token().cat() != catBegin)
439 if (p.next_token().cat() == catEnd) {
448 /// replace LaTeX commands in \p s from the unicodesymbols file with their
450 docstring convert_unicodesymbols(docstring s)
453 for (size_t i = 0; i < s.size();) {
461 docstring parsed = encodings.fromLaTeXCommand(s,
462 Encodings::TEXT_CMD, rem, &req);
463 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
464 preamble.registerAutomaticallyLoadedPackage(*it);
467 if (s.empty() || s[0] != '\\')
476 /// try to convert \p s to a valid InsetCommand argument
477 string convert_command_inset_arg(string s)
480 // since we don't know the input encoding we can't use from_utf8
481 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
482 // LyX cannot handle newlines in a latex command
483 return subst(s, "\n", " ");
487 void handle_backslash(ostream & os, string const & s)
489 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
491 os << "\n\\backslash\n";
498 void handle_ert(ostream & os, string const & s, Context & context)
500 // We must have a valid layout before outputting the ERT inset.
501 context.check_layout(os);
502 Context newcontext(true, context.textclass);
503 begin_inset(os, "ERT");
504 os << "\nstatus collapsed\n";
505 newcontext.check_layout(os);
506 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
508 os << "\n\\backslash\n";
509 else if (*it == '\n') {
510 newcontext.new_paragraph(os);
511 newcontext.check_layout(os);
515 newcontext.check_end_layout(os);
520 void handle_comment(ostream & os, string const & s, Context & context)
522 // TODO: Handle this better
523 Context newcontext(true, context.textclass);
524 begin_inset(os, "ERT");
525 os << "\nstatus collapsed\n";
526 newcontext.check_layout(os);
527 handle_backslash(os, s);
528 // make sure that our comment is the last thing on the line
529 newcontext.new_paragraph(os);
530 newcontext.check_layout(os);
531 newcontext.check_end_layout(os);
536 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
538 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
541 if (checkModule(name, command))
542 return findLayoutWithoutModule(textclass, name, command);
547 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
549 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
552 if (checkModule(name, command))
553 return findInsetLayoutWithoutModule(textclass, name, command);
558 void eat_whitespace(Parser &, ostream &, Context &, bool);
562 * Skips whitespace and braces.
563 * This should be called after a command has been parsed that is not put into
564 * ERT, and where LyX adds "{}" if needed.
566 void skip_spaces_braces(Parser & p, bool keepws = false)
568 /* The following four examples produce the same typeset output and
569 should be handled by this function:
577 // Unfortunately we need to skip comments, too.
578 // We can't use eat_whitespace since writing them after the {}
579 // results in different output in some cases.
580 bool const skipped_spaces = p.skip_spaces(true);
581 bool const skipped_braces = skip_braces(p);
582 if (keepws && skipped_spaces && !skipped_braces)
583 // put back the space (it is better handled by check_space)
584 p.unskip_spaces(true);
588 void output_command_layout(ostream & os, Parser & p, bool outer,
589 Context & parent_context,
590 Layout const * newlayout)
592 TeXFont const oldFont = parent_context.font;
593 // save the current font size
594 string const size = oldFont.size;
595 // reset the font size to default, because the font size switches
596 // don't affect section headings and the like
597 parent_context.font.size = Context::normalfont.size;
598 // we only need to write the font change if we have an open layout
599 if (!parent_context.atParagraphStart())
600 output_font_change(os, oldFont, parent_context.font);
601 parent_context.check_end_layout(os);
602 Context context(true, parent_context.textclass, newlayout,
603 parent_context.layout, parent_context.font);
604 if (parent_context.deeper_paragraph) {
605 // We are beginning a nested environment after a
606 // deeper paragraph inside the outer list environment.
607 // Therefore we don't need to output a "begin deeper".
608 context.need_end_deeper = true;
610 context.check_deeper(os);
611 context.check_layout(os);
612 unsigned int optargs = 0;
613 while (optargs < context.layout->optargs) {
614 eat_whitespace(p, os, context, false);
615 if (p.next_token().cat() == catEscape ||
616 p.next_token().character() != '[')
618 p.get_token(); // eat '['
619 begin_inset(os, "Argument\n");
620 os << "status collapsed\n\n";
621 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
623 eat_whitespace(p, os, context, false);
626 unsigned int reqargs = 0;
627 while (reqargs < context.layout->reqargs) {
628 eat_whitespace(p, os, context, false);
629 if (p.next_token().cat() != catBegin)
631 p.get_token(); // eat '{'
632 begin_inset(os, "Argument\n");
633 os << "status collapsed\n\n";
634 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
636 eat_whitespace(p, os, context, false);
639 parse_text(p, os, FLAG_ITEM, outer, context);
640 context.check_end_layout(os);
641 if (parent_context.deeper_paragraph) {
642 // We must suppress the "end deeper" because we
643 // suppressed the "begin deeper" above.
644 context.need_end_deeper = false;
646 context.check_end_deeper(os);
647 // We don't need really a new paragraph, but
648 // we must make sure that the next item gets a \begin_layout.
649 parent_context.new_paragraph(os);
650 // Set the font size to the original value. No need to output it here
651 // (Context::begin_layout() will do that if needed)
652 parent_context.font.size = size;
657 * Output a space if necessary.
658 * This function gets called for every whitespace token.
660 * We have three cases here:
661 * 1. A space must be suppressed. Example: The lyxcode case below
662 * 2. A space may be suppressed. Example: Spaces before "\par"
663 * 3. A space must not be suppressed. Example: A space between two words
665 * We currently handle only 1. and 3 and from 2. only the case of
666 * spaces before newlines as a side effect.
668 * 2. could be used to suppress as many spaces as possible. This has two effects:
669 * - Reimporting LyX generated LaTeX files changes almost no whitespace
670 * - Superflous whitespace from non LyX generated LaTeX files is removed.
671 * The drawback is that the logic inside the function becomes
672 * complicated, and that is the reason why it is not implemented.
674 void check_space(Parser & p, ostream & os, Context & context)
676 Token const next = p.next_token();
677 Token const curr = p.curr_token();
678 // A space before a single newline and vice versa must be ignored
679 // LyX emits a newline before \end{lyxcode}.
680 // This newline must be ignored,
681 // otherwise LyX will add an additional protected space.
682 if (next.cat() == catSpace ||
683 next.cat() == catNewline ||
684 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
687 context.check_layout(os);
693 * Parse all arguments of \p command
695 void parse_arguments(string const & command,
696 vector<ArgumentType> const & template_arguments,
697 Parser & p, ostream & os, bool outer, Context & context)
699 string ert = command;
700 size_t no_arguments = template_arguments.size();
701 for (size_t i = 0; i < no_arguments; ++i) {
702 switch (template_arguments[i]) {
705 // This argument contains regular LaTeX
706 handle_ert(os, ert + '{', context);
707 eat_whitespace(p, os, context, false);
708 if (template_arguments[i] == required)
709 parse_text(p, os, FLAG_ITEM, outer, context);
711 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
715 // This argument consists only of a single item.
716 // The presence of '{' or not must be preserved.
718 if (p.next_token().cat() == catBegin)
719 ert += '{' + p.verbatim_item() + '}';
721 ert += p.verbatim_item();
725 // This argument may contain special characters
726 ert += '{' + p.verbatim_item() + '}';
730 // true because we must not eat whitespace
731 // if an optional arg follows we must not strip the
732 // brackets from this one
733 if (i < no_arguments - 1 &&
734 template_arguments[i+1] == optional)
735 ert += p.getFullOpt(true);
737 ert += p.getOpt(true);
741 handle_ert(os, ert, context);
746 * Check whether \p command is a known command. If yes,
747 * handle the command with all arguments.
748 * \return true if the command was parsed, false otherwise.
750 bool parse_command(string const & command, Parser & p, ostream & os,
751 bool outer, Context & context)
753 if (known_commands.find(command) != known_commands.end()) {
754 parse_arguments(command, known_commands[command], p, os,
762 /// Parses a minipage or parbox
763 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
764 unsigned inner_flags, bool outer, Context & parent_context,
765 string const & outer_type, string const & special,
766 string const & inner_type)
770 string hor_pos = "c";
771 // We need to set the height to the LaTeX default of 1\\totalheight
772 // for the case when no height argument is given
773 string height_value = "1";
774 string height_unit = "in";
775 string height_special = "totalheight";
780 string width_special = "none";
781 if (!inner_type.empty() && p.hasOpt()) {
782 if (inner_type != "makebox")
783 position = p.getArg('[', ']');
785 latex_width = p.getArg('[', ']');
786 translate_box_len(latex_width, width_value, width_unit, width_special);
789 if (position != "t" && position != "c" && position != "b") {
790 cerr << "invalid position " << position << " for "
791 << inner_type << endl;
795 if (inner_type != "makebox") {
796 latex_height = p.getArg('[', ']');
797 translate_box_len(latex_height, height_value, height_unit, height_special);
799 hor_pos = p.getArg('[', ']');
802 inner_pos = p.getArg('[', ']');
803 if (inner_pos != "c" && inner_pos != "t" &&
804 inner_pos != "b" && inner_pos != "s") {
805 cerr << "invalid inner_pos "
806 << inner_pos << " for "
807 << inner_type << endl;
808 inner_pos = position;
813 if (inner_type.empty()) {
814 if (special.empty() && outer_type != "framebox")
815 latex_width = "1\\columnwidth";
818 latex_width = p2.getArg('[', ']');
819 string const opt = p2.getArg('[', ']');
822 if (hor_pos != "l" && hor_pos != "c" &&
824 cerr << "invalid hor_pos " << hor_pos
825 << " for " << outer_type << endl;
830 } else if (inner_type != "makebox")
831 latex_width = p.verbatim_item();
832 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
833 // as this is LyX's standard for such cases (except for makebox)
834 // \framebox is more special and handled below
835 if (latex_width.empty() && inner_type != "makebox"
836 && outer_type != "framebox")
837 latex_width = "1\\columnwidth";
839 translate_len(latex_width, width_value, width_unit);
841 bool shadedparbox = false;
842 if (inner_type == "shaded") {
843 eat_whitespace(p, os, parent_context, false);
844 if (outer_type == "parbox") {
846 if (p.next_token().cat() == catBegin)
848 eat_whitespace(p, os, parent_context, false);
854 // If we already read the inner box we have to push the inner env
855 if (!outer_type.empty() && !inner_type.empty() &&
856 (inner_flags & FLAG_END))
857 active_environments.push_back(inner_type);
858 // LyX can't handle length variables
859 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
860 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
861 // Look whether there is some content after the end of the
862 // inner box, but before the end of the outer box.
863 // If yes, we need to output ERT.
865 if (inner_flags & FLAG_END)
866 p.verbatimEnvironment(inner_type);
870 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
871 if ((outer_env && p.next_token().asInput() != "\\end") ||
872 (!outer_env && p.next_token().cat() != catEnd)) {
873 // something is between the end of the inner box and
874 // the end of the outer box, so we need to use ERT.
879 // if only \makebox{content} was used we can set its width to 1\width
880 // because this identic and also identic to \mbox
881 // this doesn't work for \framebox{content}, thus we have to use ERT for this
882 if (latex_width.empty() && inner_type == "makebox") {
885 width_special = "width";
886 } else if (latex_width.empty() && outer_type == "framebox") {
891 if (!outer_type.empty()) {
892 if (outer_flags & FLAG_END)
893 ss << "\\begin{" << outer_type << '}';
895 ss << '\\' << outer_type << '{';
896 if (!special.empty())
900 if (!inner_type.empty()) {
901 if (inner_type != "shaded") {
902 if (inner_flags & FLAG_END)
903 ss << "\\begin{" << inner_type << '}';
905 ss << '\\' << inner_type;
907 if (!position.empty())
908 ss << '[' << position << ']';
909 if (!latex_height.empty())
910 ss << '[' << latex_height << ']';
911 if (!inner_pos.empty())
912 ss << '[' << inner_pos << ']';
913 ss << '{' << latex_width << '}';
914 if (!(inner_flags & FLAG_END))
917 if (inner_type == "shaded")
918 ss << "\\begin{shaded}";
919 handle_ert(os, ss.str(), parent_context);
920 if (!inner_type.empty()) {
921 parse_text(p, os, inner_flags, outer, parent_context);
922 if (inner_flags & FLAG_END)
923 handle_ert(os, "\\end{" + inner_type + '}',
926 handle_ert(os, "}", parent_context);
928 if (!outer_type.empty()) {
929 // If we already read the inner box we have to pop
931 if (!inner_type.empty() && (inner_flags & FLAG_END))
932 active_environments.pop_back();
934 // Ensure that the end of the outer box is parsed correctly:
935 // The opening brace has been eaten by parse_outer_box()
936 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
937 outer_flags &= ~FLAG_ITEM;
938 outer_flags |= FLAG_BRACE_LAST;
940 parse_text(p, os, outer_flags, outer, parent_context);
941 if (outer_flags & FLAG_END)
942 handle_ert(os, "\\end{" + outer_type + '}',
944 else if (inner_type.empty() && outer_type == "framebox")
945 // in this case it is already closed later
948 handle_ert(os, "}", parent_context);
951 // LyX does not like empty positions, so we have
952 // to set them to the LaTeX default values here.
953 if (position.empty())
955 if (inner_pos.empty())
956 inner_pos = position;
957 parent_context.check_layout(os);
958 begin_inset(os, "Box ");
959 if (outer_type == "framed")
961 else if (outer_type == "framebox")
963 else if (outer_type == "shadowbox")
965 else if ((outer_type == "shaded" && inner_type.empty()) ||
966 (outer_type == "minipage" && inner_type == "shaded") ||
967 (outer_type == "parbox" && inner_type == "shaded")) {
969 preamble.registerAutomaticallyLoadedPackage("color");
970 } else if (outer_type == "doublebox")
972 else if (outer_type.empty())
975 os << outer_type << '\n';
976 os << "position \"" << position << "\"\n";
977 os << "hor_pos \"" << hor_pos << "\"\n";
978 os << "has_inner_box " << !inner_type.empty() << "\n";
979 os << "inner_pos \"" << inner_pos << "\"\n";
980 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
982 os << "use_makebox " << (inner_type == "makebox") << '\n';
983 os << "width \"" << width_value << width_unit << "\"\n";
984 os << "special \"" << width_special << "\"\n";
985 os << "height \"" << height_value << height_unit << "\"\n";
986 os << "height_special \"" << height_special << "\"\n";
987 os << "status open\n\n";
989 // Unfortunately we can't use parse_text_in_inset:
990 // InsetBox::forcePlainLayout() is hard coded and does not
991 // use the inset layout. Apart from that do we call parse_text
992 // up to two times, but need only one check_end_layout.
993 bool const forcePlainLayout =
994 (!inner_type.empty() || inner_type == "makebox") &&
995 outer_type != "shaded" && outer_type != "framed";
996 Context context(true, parent_context.textclass);
997 if (forcePlainLayout)
998 context.layout = &context.textclass.plainLayout();
1000 context.font = parent_context.font;
1002 // If we have no inner box the contents will be read with the outer box
1003 if (!inner_type.empty())
1004 parse_text(p, os, inner_flags, outer, context);
1006 // Ensure that the end of the outer box is parsed correctly:
1007 // The opening brace has been eaten by parse_outer_box()
1008 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1009 outer_flags &= ~FLAG_ITEM;
1010 outer_flags |= FLAG_BRACE_LAST;
1013 // Find end of outer box, output contents if inner_type is
1014 // empty and output possible comments
1015 if (!outer_type.empty()) {
1016 // If we already read the inner box we have to pop
1018 if (!inner_type.empty() && (inner_flags & FLAG_END))
1019 active_environments.pop_back();
1020 // This does not output anything but comments if
1021 // inner_type is not empty (see use_ert)
1022 parse_text(p, os, outer_flags, outer, context);
1025 context.check_end_layout(os);
1027 #ifdef PRESERVE_LAYOUT
1028 // LyX puts a % after the end of the minipage
1029 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1031 //handle_comment(os, "%dummy", parent_context);
1034 parent_context.new_paragraph(os);
1036 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1037 //handle_comment(os, "%dummy", parent_context);
1040 // We add a protected space if something real follows
1041 if (p.good() && p.next_token().cat() != catComment) {
1042 begin_inset(os, "space ~\n");
1051 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1052 Context & parent_context, string const & outer_type,
1053 string const & special)
1055 eat_whitespace(p, os, parent_context, false);
1056 if (flags & FLAG_ITEM) {
1058 if (p.next_token().cat() == catBegin)
1061 cerr << "Warning: Ignoring missing '{' after \\"
1062 << outer_type << '.' << endl;
1063 eat_whitespace(p, os, parent_context, false);
1066 unsigned int inner_flags = 0;
1068 if (outer_type == "minipage" || outer_type == "parbox") {
1069 p.skip_spaces(true);
1070 while (p.hasOpt()) {
1072 p.skip_spaces(true);
1075 p.skip_spaces(true);
1076 if (outer_type == "parbox") {
1078 if (p.next_token().cat() == catBegin)
1080 p.skip_spaces(true);
1083 if (outer_type == "shaded") {
1084 // These boxes never have an inner box
1086 } else if (p.next_token().asInput() == "\\parbox") {
1087 inner = p.get_token().cs();
1088 inner_flags = FLAG_ITEM;
1089 } else if (p.next_token().asInput() == "\\begin") {
1090 // Is this a minipage or shaded box?
1093 inner = p.getArg('{', '}');
1095 if (inner == "minipage" || inner == "shaded")
1096 inner_flags = FLAG_END;
1101 if (inner_flags == FLAG_END) {
1102 if (inner != "shaded")
1106 eat_whitespace(p, os, parent_context, false);
1108 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1109 outer_type, special, inner);
1111 if (inner_flags == FLAG_ITEM) {
1113 eat_whitespace(p, os, parent_context, false);
1115 parse_box(p, os, flags, inner_flags, outer, parent_context,
1116 outer_type, special, inner);
1121 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1123 parent_context.check_layout(os);
1124 begin_inset(os, "listings\n");
1125 os << "inline false\n"
1126 << "status collapsed\n";
1127 Context context(true, parent_context.textclass);
1128 context.layout = &parent_context.textclass.plainLayout();
1129 context.check_layout(os);
1130 string const s = p.verbatimEnvironment("lstlisting");
1131 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1133 os << "\n\\backslash\n";
1134 else if (*it == '\n') {
1135 // avoid adding an empty paragraph at the end
1137 context.new_paragraph(os);
1138 context.check_layout(os);
1143 context.check_end_layout(os);
1148 /// parse an unknown environment
1149 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1150 unsigned flags, bool outer,
1151 Context & parent_context)
1153 if (name == "tabbing")
1154 // We need to remember that we have to handle '\=' specially
1155 flags |= FLAG_TABBING;
1157 // We need to translate font changes and paragraphs inside the
1158 // environment to ERT if we have a non standard font.
1159 // Otherwise things like
1160 // \large\begin{foo}\huge bar\end{foo}
1162 bool const specialfont =
1163 (parent_context.font != parent_context.normalfont);
1164 bool const new_layout_allowed = parent_context.new_layout_allowed;
1166 parent_context.new_layout_allowed = false;
1167 handle_ert(os, "\\begin{" + name + "}", parent_context);
1168 parse_text_snippet(p, os, flags, outer, parent_context);
1169 handle_ert(os, "\\end{" + name + "}", parent_context);
1171 parent_context.new_layout_allowed = new_layout_allowed;
1175 void parse_environment(Parser & p, ostream & os, bool outer,
1176 string & last_env, bool & title_layout_found,
1177 Context & parent_context)
1179 Layout const * newlayout;
1180 InsetLayout const * newinsetlayout = 0;
1181 string const name = p.getArg('{', '}');
1182 const bool is_starred = suffixIs(name, '*');
1183 string const unstarred_name = rtrim(name, "*");
1184 active_environments.push_back(name);
1186 if (is_math_env(name)) {
1187 parent_context.check_layout(os);
1188 begin_inset(os, "Formula ");
1189 os << "\\begin{" << name << "}";
1190 parse_math(p, os, FLAG_END, MATH_MODE);
1191 os << "\\end{" << name << "}";
1193 if (is_display_math_env(name)) {
1194 // Prevent the conversion of a line break to a space
1195 // (bug 7668). This does not change the output, but
1196 // looks ugly in LyX.
1197 eat_whitespace(p, os, parent_context, false);
1201 else if (unstarred_name == "tabular" || name == "longtable") {
1202 eat_whitespace(p, os, parent_context, false);
1203 string width = "0pt";
1204 if (name == "tabular*") {
1205 width = lyx::translate_len(p.getArg('{', '}'));
1206 eat_whitespace(p, os, parent_context, false);
1208 parent_context.check_layout(os);
1209 begin_inset(os, "Tabular ");
1210 handle_tabular(p, os, name, width, parent_context);
1215 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1216 eat_whitespace(p, os, parent_context, false);
1217 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1218 eat_whitespace(p, os, parent_context, false);
1219 parent_context.check_layout(os);
1220 begin_inset(os, "Float " + unstarred_name + "\n");
1221 // store the float type for subfloats
1222 // subfloats only work with figures and tables
1223 if (unstarred_name == "figure")
1224 float_type = unstarred_name;
1225 else if (unstarred_name == "table")
1226 float_type = unstarred_name;
1230 os << "placement " << opt << '\n';
1231 if (contains(opt, "H"))
1232 preamble.registerAutomaticallyLoadedPackage("float");
1234 Floating const & fl = parent_context.textclass.floats()
1235 .getType(unstarred_name);
1236 if (!fl.floattype().empty() && fl.usesFloatPkg())
1237 preamble.registerAutomaticallyLoadedPackage("float");
1240 os << "wide " << convert<string>(is_starred)
1241 << "\nsideways false"
1242 << "\nstatus open\n\n";
1243 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1245 // We don't need really a new paragraph, but
1246 // we must make sure that the next item gets a \begin_layout.
1247 parent_context.new_paragraph(os);
1249 // the float is parsed thus delete the type
1253 else if (unstarred_name == "sidewaysfigure"
1254 || unstarred_name == "sidewaystable") {
1255 eat_whitespace(p, os, parent_context, false);
1256 parent_context.check_layout(os);
1257 if (unstarred_name == "sidewaysfigure")
1258 begin_inset(os, "Float figure\n");
1260 begin_inset(os, "Float table\n");
1261 os << "wide " << convert<string>(is_starred)
1262 << "\nsideways true"
1263 << "\nstatus open\n\n";
1264 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1266 // We don't need really a new paragraph, but
1267 // we must make sure that the next item gets a \begin_layout.
1268 parent_context.new_paragraph(os);
1270 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1273 else if (name == "wrapfigure" || name == "wraptable") {
1274 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1275 eat_whitespace(p, os, parent_context, false);
1276 parent_context.check_layout(os);
1279 string overhang = "0col%";
1282 lines = p.getArg('[', ']');
1283 string const placement = p.getArg('{', '}');
1285 overhang = p.getArg('[', ']');
1286 string const width = p.getArg('{', '}');
1288 if (name == "wrapfigure")
1289 begin_inset(os, "Wrap figure\n");
1291 begin_inset(os, "Wrap table\n");
1292 os << "lines " << lines
1293 << "\nplacement " << placement
1294 << "\noverhang " << lyx::translate_len(overhang)
1295 << "\nwidth " << lyx::translate_len(width)
1296 << "\nstatus open\n\n";
1297 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1299 // We don't need really a new paragraph, but
1300 // we must make sure that the next item gets a \begin_layout.
1301 parent_context.new_paragraph(os);
1303 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1306 else if (name == "minipage") {
1307 eat_whitespace(p, os, parent_context, false);
1308 // Test whether this is an outer box of a shaded box
1310 // swallow arguments
1311 while (p.hasOpt()) {
1313 p.skip_spaces(true);
1316 p.skip_spaces(true);
1317 Token t = p.get_token();
1318 bool shaded = false;
1319 if (t.asInput() == "\\begin") {
1320 p.skip_spaces(true);
1321 if (p.getArg('{', '}') == "shaded")
1326 parse_outer_box(p, os, FLAG_END, outer,
1327 parent_context, name, "shaded");
1329 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1334 else if (name == "comment") {
1335 eat_whitespace(p, os, parent_context, false);
1336 parent_context.check_layout(os);
1337 begin_inset(os, "Note Comment\n");
1338 os << "status open\n";
1339 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1342 skip_braces(p); // eat {} that might by set by LyX behind comments
1343 preamble.registerAutomaticallyLoadedPackage("verbatim");
1346 else if (name == "lyxgreyedout") {
1347 eat_whitespace(p, os, parent_context, false);
1348 parent_context.check_layout(os);
1349 begin_inset(os, "Note Greyedout\n");
1350 os << "status open\n";
1351 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1354 if (!preamble.notefontcolor().empty())
1355 preamble.registerAutomaticallyLoadedPackage("color");
1358 else if (name == "framed" || name == "shaded") {
1359 eat_whitespace(p, os, parent_context, false);
1360 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1364 else if (name == "lstlisting") {
1365 eat_whitespace(p, os, parent_context, false);
1366 // FIXME handle listings with parameters
1367 // If this is added, don't forgot to handle the
1368 // automatic color package loading
1370 parse_unknown_environment(p, name, os, FLAG_END,
1371 outer, parent_context);
1373 parse_listings(p, os, parent_context);
1377 else if (!parent_context.new_layout_allowed)
1378 parse_unknown_environment(p, name, os, FLAG_END, outer,
1381 // Alignment and spacing settings
1382 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1383 // therefore are totally broken!
1384 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1385 // they are commands not environments. They are furthermore switches that
1386 // can be ended by another switches, but also by commands like \footnote or
1387 // \parbox. So the only safe way is to leave them untouched.
1388 else if (name == "center" || name == "centering" ||
1389 name == "flushleft" || name == "flushright" ||
1390 name == "singlespace" || name == "onehalfspace" ||
1391 name == "doublespace" || name == "spacing") {
1392 eat_whitespace(p, os, parent_context, false);
1393 // We must begin a new paragraph if not already done
1394 if (! parent_context.atParagraphStart()) {
1395 parent_context.check_end_layout(os);
1396 parent_context.new_paragraph(os);
1398 if (name == "flushleft")
1399 parent_context.add_extra_stuff("\\align left\n");
1400 else if (name == "flushright")
1401 parent_context.add_extra_stuff("\\align right\n");
1402 else if (name == "center" || name == "centering")
1403 parent_context.add_extra_stuff("\\align center\n");
1404 else if (name == "singlespace")
1405 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1406 else if (name == "onehalfspace") {
1407 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1408 preamble.registerAutomaticallyLoadedPackage("setspace");
1409 } else if (name == "doublespace") {
1410 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1411 preamble.registerAutomaticallyLoadedPackage("setspace");
1412 } else if (name == "spacing") {
1413 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1414 preamble.registerAutomaticallyLoadedPackage("setspace");
1416 parse_text(p, os, FLAG_END, outer, parent_context);
1417 // Just in case the environment is empty
1418 parent_context.extra_stuff.erase();
1419 // We must begin a new paragraph to reset the alignment
1420 parent_context.new_paragraph(os);
1424 // The single '=' is meant here.
1425 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1426 eat_whitespace(p, os, parent_context, false);
1427 Context context(true, parent_context.textclass, newlayout,
1428 parent_context.layout, parent_context.font);
1429 if (parent_context.deeper_paragraph) {
1430 // We are beginning a nested environment after a
1431 // deeper paragraph inside the outer list environment.
1432 // Therefore we don't need to output a "begin deeper".
1433 context.need_end_deeper = true;
1435 parent_context.check_end_layout(os);
1436 if (last_env == name) {
1437 // we need to output a separator since LyX would export
1438 // the two environments as one otherwise (bug 5716)
1439 docstring const sep = from_ascii("--Separator--");
1440 TeX2LyXDocClass const & textclass(parent_context.textclass);
1441 if (textclass.hasLayout(sep)) {
1442 Context newcontext(parent_context);
1443 newcontext.layout = &(textclass[sep]);
1444 newcontext.check_layout(os);
1445 newcontext.check_end_layout(os);
1447 parent_context.check_layout(os);
1448 begin_inset(os, "Note Note\n");
1449 os << "status closed\n";
1450 Context newcontext(true, textclass,
1451 &(textclass.defaultLayout()));
1452 newcontext.check_layout(os);
1453 newcontext.check_end_layout(os);
1455 parent_context.check_end_layout(os);
1458 switch (context.layout->latextype) {
1459 case LATEX_LIST_ENVIRONMENT:
1460 context.add_par_extra_stuff("\\labelwidthstring "
1461 + p.verbatim_item() + '\n');
1464 case LATEX_BIB_ENVIRONMENT:
1465 p.verbatim_item(); // swallow next arg
1471 context.check_deeper(os);
1472 // handle known optional and required arguments
1473 // layouts require all optional arguments before the required ones
1474 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1475 // It is impossible to place anything after the environment name,
1476 // but before the first \\item.
1477 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1478 bool need_layout = true;
1479 unsigned int optargs = 0;
1480 while (optargs < context.layout->optargs) {
1481 eat_whitespace(p, os, context, false);
1482 if (p.next_token().cat() == catEscape ||
1483 p.next_token().character() != '[')
1485 p.get_token(); // eat '['
1487 context.check_layout(os);
1488 need_layout = false;
1490 begin_inset(os, "Argument\n");
1491 os << "status collapsed\n\n";
1492 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1494 eat_whitespace(p, os, context, false);
1497 unsigned int reqargs = 0;
1498 while (reqargs < context.layout->reqargs) {
1499 eat_whitespace(p, os, context, false);
1500 if (p.next_token().cat() != catBegin)
1502 p.get_token(); // eat '{'
1504 context.check_layout(os);
1505 need_layout = false;
1507 begin_inset(os, "Argument\n");
1508 os << "status collapsed\n\n";
1509 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1511 eat_whitespace(p, os, context, false);
1515 parse_text(p, os, FLAG_END, outer, context);
1516 context.check_end_layout(os);
1517 if (parent_context.deeper_paragraph) {
1518 // We must suppress the "end deeper" because we
1519 // suppressed the "begin deeper" above.
1520 context.need_end_deeper = false;
1522 context.check_end_deeper(os);
1523 parent_context.new_paragraph(os);
1525 if (!title_layout_found)
1526 title_layout_found = newlayout->intitle;
1527 set<string> const & req = newlayout->requires();
1528 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
1529 preamble.registerAutomaticallyLoadedPackage(*it);
1532 // The single '=' is meant here.
1533 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1534 eat_whitespace(p, os, parent_context, false);
1535 parent_context.check_layout(os);
1536 begin_inset(os, "Flex ");
1537 os << to_utf8(newinsetlayout->name()) << '\n'
1538 << "status collapsed\n";
1539 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1543 else if (name == "appendix") {
1544 // This is no good latex style, but it works and is used in some documents...
1545 eat_whitespace(p, os, parent_context, false);
1546 parent_context.check_end_layout(os);
1547 Context context(true, parent_context.textclass, parent_context.layout,
1548 parent_context.layout, parent_context.font);
1549 context.check_layout(os);
1550 os << "\\start_of_appendix\n";
1551 parse_text(p, os, FLAG_END, outer, context);
1552 context.check_end_layout(os);
1556 else if (known_environments.find(name) != known_environments.end()) {
1557 vector<ArgumentType> arguments = known_environments[name];
1558 // The last "argument" denotes wether we may translate the
1559 // environment contents to LyX
1560 // The default required if no argument is given makes us
1561 // compatible with the reLyXre environment.
1562 ArgumentType contents = arguments.empty() ?
1565 if (!arguments.empty())
1566 arguments.pop_back();
1567 // See comment in parse_unknown_environment()
1568 bool const specialfont =
1569 (parent_context.font != parent_context.normalfont);
1570 bool const new_layout_allowed =
1571 parent_context.new_layout_allowed;
1573 parent_context.new_layout_allowed = false;
1574 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1575 outer, parent_context);
1576 if (contents == verbatim)
1577 handle_ert(os, p.verbatimEnvironment(name),
1580 parse_text_snippet(p, os, FLAG_END, outer,
1582 handle_ert(os, "\\end{" + name + "}", parent_context);
1584 parent_context.new_layout_allowed = new_layout_allowed;
1588 parse_unknown_environment(p, name, os, FLAG_END, outer,
1592 active_environments.pop_back();
1596 /// parses a comment and outputs it to \p os.
1597 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1599 LASSERT(t.cat() == catComment, return);
1600 if (!t.cs().empty()) {
1601 context.check_layout(os);
1602 handle_comment(os, '%' + t.cs(), context);
1603 if (p.next_token().cat() == catNewline) {
1604 // A newline after a comment line starts a new
1606 if (context.new_layout_allowed) {
1607 if(!context.atParagraphStart())
1608 // Only start a new paragraph if not already
1609 // done (we might get called recursively)
1610 context.new_paragraph(os);
1612 handle_ert(os, "\n", context);
1613 eat_whitespace(p, os, context, true);
1616 // "%\n" combination
1623 * Reads spaces and comments until the first non-space, non-comment token.
1624 * New paragraphs (double newlines or \\par) are handled like simple spaces
1625 * if \p eatParagraph is true.
1626 * Spaces are skipped, but comments are written to \p os.
1628 void eat_whitespace(Parser & p, ostream & os, Context & context,
1632 Token const & t = p.get_token();
1633 if (t.cat() == catComment)
1634 parse_comment(p, os, t, context);
1635 else if ((! eatParagraph && p.isParagraph()) ||
1636 (t.cat() != catSpace && t.cat() != catNewline)) {
1645 * Set a font attribute, parse text and reset the font attribute.
1646 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1647 * \param currentvalue Current value of the attribute. Is set to the new
1648 * value during parsing.
1649 * \param newvalue New value of the attribute
1651 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1652 Context & context, string const & attribute,
1653 string & currentvalue, string const & newvalue)
1655 context.check_layout(os);
1656 string const oldvalue = currentvalue;
1657 currentvalue = newvalue;
1658 os << '\n' << attribute << ' ' << newvalue << "\n";
1659 parse_text_snippet(p, os, flags, outer, context);
1660 context.check_layout(os);
1661 os << '\n' << attribute << ' ' << oldvalue << "\n";
1662 currentvalue = oldvalue;
1666 /// get the arguments of a natbib or jurabib citation command
1667 void get_cite_arguments(Parser & p, bool natbibOrder,
1668 string & before, string & after)
1670 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1672 // text before the citation
1674 // text after the citation
1675 after = p.getFullOpt();
1677 if (!after.empty()) {
1678 before = p.getFullOpt();
1679 if (natbibOrder && !before.empty())
1680 swap(before, after);
1685 /// Convert filenames with TeX macros and/or quotes to something LyX
1687 string const normalize_filename(string const & name)
1689 Parser p(trim(name, "\""));
1692 Token const & t = p.get_token();
1693 if (t.cat() != catEscape)
1695 else if (t.cs() == "lyxdot") {
1696 // This is used by LyX for simple dots in relative
1700 } else if (t.cs() == "space") {
1710 /// Convert \p name from TeX convention (relative to master file) to LyX
1711 /// convention (relative to .lyx file) if it is relative
1712 void fix_relative_filename(string & name)
1714 if (FileName::isAbsolute(name))
1717 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1718 from_utf8(getParentFilePath())));
1722 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1723 void parse_noweb(Parser & p, ostream & os, Context & context)
1725 // assemble the rest of the keyword
1729 Token const & t = p.get_token();
1730 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1733 scrap = (p.good() && p.next_token().asInput() == "=");
1735 name += p.get_token().asInput();
1738 name += t.asInput();
1741 if (!scrap || !context.new_layout_allowed ||
1742 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1743 cerr << "Warning: Could not interpret '" << name
1744 << "'. Ignoring it." << endl;
1748 // We use new_paragraph instead of check_end_layout because the stuff
1749 // following the noweb chunk needs to start with a \begin_layout.
1750 // This may create a new paragraph even if there was none in the
1751 // noweb file, but the alternative is an invalid LyX file. Since
1752 // noweb code chunks are implemented with a layout style in LyX they
1753 // always must be in an own paragraph.
1754 context.new_paragraph(os);
1755 Context newcontext(true, context.textclass,
1756 &context.textclass[from_ascii("Scrap")]);
1757 newcontext.check_layout(os);
1760 Token const & t = p.get_token();
1761 // We abuse the parser a bit, because this is no TeX syntax
1763 if (t.cat() == catEscape)
1764 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1767 Context tmp(false, context.textclass,
1768 &context.textclass[from_ascii("Scrap")]);
1769 tmp.need_end_layout = true;
1770 tmp.check_layout(oss);
1771 os << subst(t.asInput(), "\n", oss.str());
1773 // The scrap chunk is ended by an @ at the beginning of a line.
1774 // After the @ the line may contain a comment and/or
1775 // whitespace, but nothing else.
1776 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1777 (p.next_token().cat() == catSpace ||
1778 p.next_token().cat() == catNewline ||
1779 p.next_token().cat() == catComment)) {
1780 while (p.good() && p.next_token().cat() == catSpace)
1781 os << p.get_token().asInput();
1782 if (p.next_token().cat() == catComment)
1783 // The comment includes a final '\n'
1784 os << p.get_token().asInput();
1786 if (p.next_token().cat() == catNewline)
1793 newcontext.check_end_layout(os);
1797 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1798 bool is_macro(Parser & p)
1800 Token first = p.curr_token();
1801 if (first.cat() != catEscape || !p.good())
1803 if (first.cs() == "def")
1805 if (first.cs() != "global" && first.cs() != "long")
1807 Token second = p.get_token();
1809 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1810 second.cat() == catNewline || second.cat() == catComment)) {
1811 second = p.get_token();
1814 bool secondvalid = second.cat() == catEscape;
1816 bool thirdvalid = false;
1817 if (p.good() && first.cs() == "global" && secondvalid &&
1818 second.cs() == "long") {
1819 third = p.get_token();
1821 while (p.good() && !p.isParagraph() &&
1822 (third.cat() == catSpace ||
1823 third.cat() == catNewline ||
1824 third.cat() == catComment)) {
1825 third = p.get_token();
1828 thirdvalid = third.cat() == catEscape;
1830 for (int i = 0; i < pos; ++i)
1835 return (first.cs() == "global" || first.cs() == "long") &&
1836 second.cs() == "def";
1837 return first.cs() == "global" && second.cs() == "long" &&
1838 third.cs() == "def";
1842 /// Parse a macro definition (assumes that is_macro() returned true)
1843 void parse_macro(Parser & p, ostream & os, Context & context)
1845 context.check_layout(os);
1846 Token first = p.curr_token();
1849 string command = first.asInput();
1850 if (first.cs() != "def") {
1852 eat_whitespace(p, os, context, false);
1853 second = p.curr_token();
1854 command += second.asInput();
1855 if (second.cs() != "def") {
1857 eat_whitespace(p, os, context, false);
1858 third = p.curr_token();
1859 command += third.asInput();
1862 eat_whitespace(p, os, context, false);
1863 string const name = p.get_token().cs();
1864 eat_whitespace(p, os, context, false);
1870 while (p.next_token().cat() != catBegin) {
1871 if (p.next_token().cat() == catParameter) {
1876 // followed by number?
1877 if (p.next_token().cat() == catOther) {
1878 char c = p.getChar();
1880 // number = current arity + 1?
1881 if (c == arity + '0' + 1)
1886 paramtext += p.get_token().cs();
1888 paramtext += p.get_token().cs();
1893 // only output simple (i.e. compatible) macro as FormulaMacros
1894 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1896 context.check_layout(os);
1897 begin_inset(os, "FormulaMacro");
1898 os << "\n\\def" << ert;
1901 handle_ert(os, command + ert, context);
1905 void registerExternalTemplatePackages(string const & name)
1907 external::TemplateManager const & etm = external::TemplateManager::get();
1908 external::Template const * const et = etm.getTemplateByName(name);
1911 external::Template::Formats::const_iterator cit = et->formats.end();
1913 cit = et->formats.find("PDFLaTeX");
1914 if (cit == et->formats.end())
1915 // If the template has not specified a PDFLaTeX output,
1916 // we try the LaTeX format.
1917 cit = et->formats.find("LaTeX");
1918 if (cit == et->formats.end())
1920 vector<string>::const_iterator qit = cit->second.requirements.begin();
1921 vector<string>::const_iterator qend = cit->second.requirements.end();
1922 for (; qit != qend; ++qit)
1923 preamble.registerAutomaticallyLoadedPackage(*qit);
1926 } // anonymous namespace
1929 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1932 Layout const * newlayout = 0;
1933 InsetLayout const * newinsetlayout = 0;
1934 char const * const * where = 0;
1935 // Store the latest bibliographystyle and nocite{*} option
1936 // (needed for bibtex inset)
1938 string bibliographystyle;
1939 bool const use_natbib = preamble.isPackageUsed("natbib");
1940 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1942 bool title_layout_found = false;
1944 Token const & t = p.get_token();
1947 debugToken(cerr, t, flags);
1950 if (flags & FLAG_ITEM) {
1951 if (t.cat() == catSpace)
1954 flags &= ~FLAG_ITEM;
1955 if (t.cat() == catBegin) {
1956 // skip the brace and collect everything to the next matching
1958 flags |= FLAG_BRACE_LAST;
1962 // handle only this single token, leave the loop if done
1963 flags |= FLAG_LEAVE;
1966 if (t.cat() != catEscape && t.character() == ']' &&
1967 (flags & FLAG_BRACK_LAST))
1969 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1972 // If there is anything between \end{env} and \begin{env} we
1973 // don't need to output a separator.
1974 if (t.cat() != catSpace && t.cat() != catNewline &&
1975 t.asInput() != "\\begin")
1981 if (t.cat() == catMath) {
1982 // we are inside some text mode thingy, so opening new math is allowed
1983 context.check_layout(os);
1984 begin_inset(os, "Formula ");
1985 Token const & n = p.get_token();
1986 bool const display(n.cat() == catMath && outer);
1988 // TeX's $$...$$ syntax for displayed math
1990 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1992 p.get_token(); // skip the second '$' token
1994 // simple $...$ stuff
1997 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2002 // Prevent the conversion of a line break to a
2003 // space (bug 7668). This does not change the
2004 // output, but looks ugly in LyX.
2005 eat_whitespace(p, os, context, false);
2009 else if (t.cat() == catSuper || t.cat() == catSub)
2010 cerr << "catcode " << t << " illegal in text mode\n";
2012 // Basic support for english quotes. This should be
2013 // extended to other quotes, but is not so easy (a
2014 // left english quote is the same as a right german
2016 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2017 context.check_layout(os);
2018 begin_inset(os, "Quotes ");
2024 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2025 context.check_layout(os);
2026 begin_inset(os, "Quotes ");
2033 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2034 context.check_layout(os);
2035 begin_inset(os, "Quotes ");
2042 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2043 context.check_layout(os);
2044 begin_inset(os, "Quotes ");
2051 else if (t.asInput() == "<"
2052 && p.next_token().asInput() == "<" && noweb_mode) {
2054 parse_noweb(p, os, context);
2057 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2058 check_space(p, os, context);
2060 else if (t.character() == '[' && noweb_mode &&
2061 p.next_token().character() == '[') {
2062 // These can contain underscores
2064 string const s = p.getFullOpt() + ']';
2065 if (p.next_token().character() == ']')
2068 cerr << "Warning: Inserting missing ']' in '"
2069 << s << "'." << endl;
2070 handle_ert(os, s, context);
2073 else if (t.cat() == catLetter) {
2074 context.check_layout(os);
2075 // Workaround for bug 4752.
2076 // FIXME: This whole code block needs to be removed
2077 // when the bug is fixed and tex2lyx produces
2078 // the updated file format.
2079 // The replacement algorithm in LyX is so stupid that
2080 // it even translates a phrase if it is part of a word.
2081 bool handled = false;
2082 for (int const * l = known_phrase_lengths; *l; ++l) {
2083 string phrase = t.cs();
2084 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2085 phrase += p.get_token().cs();
2086 if (is_known(phrase, known_coded_phrases)) {
2087 handle_ert(os, phrase, context);
2091 for (size_t i = 1; i < phrase.length(); ++i)
2099 else if (t.cat() == catOther ||
2100 t.cat() == catAlign ||
2101 t.cat() == catParameter) {
2102 // This translates "&" to "\\&" which may be wrong...
2103 context.check_layout(os);
2107 else if (p.isParagraph()) {
2108 if (context.new_layout_allowed)
2109 context.new_paragraph(os);
2111 handle_ert(os, "\\par ", context);
2112 eat_whitespace(p, os, context, true);
2115 else if (t.cat() == catActive) {
2116 context.check_layout(os);
2117 if (t.character() == '~') {
2118 if (context.layout->free_spacing)
2121 begin_inset(os, "space ~\n");
2128 else if (t.cat() == catBegin) {
2129 Token const next = p.next_token();
2130 Token const end = p.next_next_token();
2131 if (next.cat() == catEnd) {
2133 Token const prev = p.prev_token();
2135 if (p.next_token().character() == '`' ||
2136 (prev.character() == '-' &&
2137 p.next_token().character() == '-'))
2138 ; // ignore it in {}`` or -{}-
2140 handle_ert(os, "{}", context);
2141 } else if (next.cat() == catEscape &&
2142 is_known(next.cs(), known_quotes) &&
2143 end.cat() == catEnd) {
2144 // Something like {\textquoteright} (e.g.
2145 // from writer2latex). LyX writes
2146 // \textquoteright{}, so we may skip the
2147 // braces here for better readability.
2148 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2151 context.check_layout(os);
2152 // special handling of font attribute changes
2153 Token const prev = p.prev_token();
2154 TeXFont const oldFont = context.font;
2155 if (next.character() == '[' ||
2156 next.character() == ']' ||
2157 next.character() == '*') {
2159 if (p.next_token().cat() == catEnd) {
2164 handle_ert(os, "{", context);
2165 parse_text_snippet(p, os,
2168 handle_ert(os, "}", context);
2170 } else if (! context.new_layout_allowed) {
2171 handle_ert(os, "{", context);
2172 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2174 handle_ert(os, "}", context);
2175 } else if (is_known(next.cs(), known_sizes)) {
2176 // next will change the size, so we must
2178 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2180 if (!context.atParagraphStart())
2182 << context.font.size << "\n";
2183 } else if (is_known(next.cs(), known_font_families)) {
2184 // next will change the font family, so we
2185 // must reset it here
2186 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2188 if (!context.atParagraphStart())
2190 << context.font.family << "\n";
2191 } else if (is_known(next.cs(), known_font_series)) {
2192 // next will change the font series, so we
2193 // must reset it here
2194 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2196 if (!context.atParagraphStart())
2198 << context.font.series << "\n";
2199 } else if (is_known(next.cs(), known_font_shapes)) {
2200 // next will change the font shape, so we
2201 // must reset it here
2202 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2204 if (!context.atParagraphStart())
2206 << context.font.shape << "\n";
2207 } else if (is_known(next.cs(), known_old_font_families) ||
2208 is_known(next.cs(), known_old_font_series) ||
2209 is_known(next.cs(), known_old_font_shapes)) {
2210 // next will change the font family, series
2211 // and shape, so we must reset it here
2212 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2214 if (!context.atParagraphStart())
2216 << context.font.family
2218 << context.font.series
2220 << context.font.shape << "\n";
2222 handle_ert(os, "{", context);
2223 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2225 handle_ert(os, "}", context);
2230 else if (t.cat() == catEnd) {
2231 if (flags & FLAG_BRACE_LAST) {
2234 cerr << "stray '}' in text\n";
2235 handle_ert(os, "}", context);
2238 else if (t.cat() == catComment)
2239 parse_comment(p, os, t, context);
2242 // control sequences
2245 else if (t.cs() == "(") {
2246 context.check_layout(os);
2247 begin_inset(os, "Formula");
2249 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2254 else if (t.cs() == "[") {
2255 context.check_layout(os);
2256 begin_inset(os, "Formula");
2258 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2261 // Prevent the conversion of a line break to a space
2262 // (bug 7668). This does not change the output, but
2263 // looks ugly in LyX.
2264 eat_whitespace(p, os, context, false);
2267 else if (t.cs() == "begin")
2268 parse_environment(p, os, outer, last_env,
2269 title_layout_found, context);
2271 else if (t.cs() == "end") {
2272 if (flags & FLAG_END) {
2273 // eat environment name
2274 string const name = p.getArg('{', '}');
2275 if (name != active_environment())
2276 cerr << "\\end{" + name + "} does not match \\begin{"
2277 + active_environment() + "}\n";
2280 p.error("found 'end' unexpectedly");
2283 else if (t.cs() == "item") {
2285 bool const optarg = p.hasOpt();
2287 // FIXME: This swallows comments, but we cannot use
2288 // eat_whitespace() since we must not output
2289 // anything before the item.
2290 p.skip_spaces(true);
2291 s = p.verbatimOption();
2293 p.skip_spaces(false);
2295 context.check_layout(os);
2296 if (context.has_item) {
2297 // An item in an unknown list-like environment
2298 // FIXME: Do this in check_layout()!
2299 context.has_item = false;
2301 handle_ert(os, "\\item", context);
2303 handle_ert(os, "\\item ", context);
2306 if (context.layout->labeltype != LABEL_MANUAL) {
2307 // LyX does not support \item[\mybullet]
2308 // in itemize environments
2310 os << parse_text_snippet(p2,
2311 FLAG_BRACK_LAST, outer, context);
2312 } else if (!s.empty()) {
2313 // LyX adds braces around the argument,
2314 // so we need to remove them here.
2315 if (s.size() > 2 && s[0] == '{' &&
2316 s[s.size()-1] == '}')
2317 s = s.substr(1, s.size()-2);
2318 // If the argument contains a space we
2319 // must put it into ERT: Otherwise LyX
2320 // would misinterpret the space as
2321 // item delimiter (bug 7663)
2322 if (contains(s, ' ')) {
2323 handle_ert(os, s, context);
2326 os << parse_text_snippet(p2,
2330 // The space is needed to separate the
2331 // item from the rest of the sentence.
2333 eat_whitespace(p, os, context, false);
2338 else if (t.cs() == "bibitem") {
2340 context.check_layout(os);
2341 eat_whitespace(p, os, context, false);
2342 string label = convert_command_inset_arg(p.verbatimOption());
2343 string key = convert_command_inset_arg(p.verbatim_item());
2344 if (contains(label, '\\') || contains(key, '\\')) {
2345 // LyX can't handle LaTeX commands in labels or keys
2346 handle_ert(os, t.asInput() + '[' + label +
2347 "]{" + p.verbatim_item() + '}',
2350 begin_command_inset(os, "bibitem", "bibitem");
2351 os << "label \"" << label << "\"\n"
2352 "key \"" << key << "\"\n";
2357 else if (is_macro(p)) {
2358 // catch the case of \def\inputGnumericTable
2360 if (t.cs() == "def") {
2361 Token second = p.next_token();
2362 if (second.cs() == "inputGnumericTable") {
2366 Token third = p.get_token();
2368 if (third.cs() == "input") {
2372 string name = normalize_filename(p.verbatim_item());
2373 string const path = getMasterFilePath();
2374 // We want to preserve relative / absolute filenames,
2375 // therefore path is only used for testing
2376 // The file extension is in every case ".tex".
2377 // So we need to remove this extension and check for
2378 // the original one.
2379 name = removeExtension(name);
2380 if (!makeAbsPath(name, path).exists()) {
2381 char const * const Gnumeric_formats[] = {"gnumeric",
2383 string const Gnumeric_name =
2384 find_file(name, path, Gnumeric_formats);
2385 if (!Gnumeric_name.empty())
2386 name = Gnumeric_name;
2388 if (makeAbsPath(name, path).exists())
2389 fix_relative_filename(name);
2391 cerr << "Warning: Could not find file '"
2392 << name << "'." << endl;
2393 context.check_layout(os);
2394 begin_inset(os, "External\n\ttemplate ");
2395 os << "GnumericSpreadsheet\n\tfilename "
2398 context.check_layout(os);
2400 // register the packages that are automatically reloaded
2401 // by the Gnumeric template
2402 registerExternalTemplatePackages("GnumericSpreadsheet");
2407 parse_macro(p, os, context);
2410 else if (t.cs() == "noindent") {
2412 context.add_par_extra_stuff("\\noindent\n");
2415 else if (t.cs() == "appendix") {
2416 context.add_par_extra_stuff("\\start_of_appendix\n");
2417 // We need to start a new paragraph. Otherwise the
2418 // appendix in 'bla\appendix\chapter{' would start
2420 context.new_paragraph(os);
2421 // We need to make sure that the paragraph is
2422 // generated even if it is empty. Otherwise the
2423 // appendix in '\par\appendix\par\chapter{' would
2425 context.check_layout(os);
2426 // FIXME: This is a hack to prevent paragraph
2427 // deletion if it is empty. Handle this better!
2429 "%dummy comment inserted by tex2lyx to "
2430 "ensure that this paragraph is not empty",
2432 // Both measures above may generate an additional
2433 // empty paragraph, but that does not hurt, because
2434 // whitespace does not matter here.
2435 eat_whitespace(p, os, context, true);
2438 // Must catch empty dates before findLayout is called below
2439 else if (t.cs() == "date") {
2440 string const date = p.verbatim_item();
2442 preamble.suppressDate(true);
2444 preamble.suppressDate(false);
2445 if (context.new_layout_allowed &&
2446 (newlayout = findLayout(context.textclass,
2449 output_command_layout(os, p, outer,
2450 context, newlayout);
2452 if (!title_layout_found)
2453 title_layout_found = newlayout->intitle;
2454 set<string> const & req = newlayout->requires();
2455 for (set<string>::const_iterator it = req.begin();
2456 it != req.end(); it++)
2457 preamble.registerAutomaticallyLoadedPackage(*it);
2459 handle_ert(os, "\\date{" + date + '}',
2464 // Starred section headings
2465 // Must attempt to parse "Section*" before "Section".
2466 else if ((p.next_token().asInput() == "*") &&
2467 context.new_layout_allowed &&
2468 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2471 output_command_layout(os, p, outer, context, newlayout);
2473 if (!title_layout_found)
2474 title_layout_found = newlayout->intitle;
2475 set<string> const & req = newlayout->requires();
2476 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2477 preamble.registerAutomaticallyLoadedPackage(*it);
2480 // Section headings and the like
2481 else if (context.new_layout_allowed &&
2482 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2484 output_command_layout(os, p, outer, context, newlayout);
2486 if (!title_layout_found)
2487 title_layout_found = newlayout->intitle;
2488 set<string> const & req = newlayout->requires();
2489 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2490 preamble.registerAutomaticallyLoadedPackage(*it);
2493 else if (t.cs() == "caption") {
2495 context.check_layout(os);
2497 begin_inset(os, "Caption\n");
2498 Context newcontext(true, context.textclass);
2499 newcontext.font = context.font;
2500 newcontext.check_layout(os);
2501 if (p.next_token().cat() != catEscape &&
2502 p.next_token().character() == '[') {
2503 p.get_token(); // eat '['
2504 begin_inset(os, "Argument\n");
2505 os << "status collapsed\n";
2506 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2508 eat_whitespace(p, os, context, false);
2510 parse_text(p, os, FLAG_ITEM, outer, context);
2511 context.check_end_layout(os);
2512 // We don't need really a new paragraph, but
2513 // we must make sure that the next item gets a \begin_layout.
2514 context.new_paragraph(os);
2517 newcontext.check_end_layout(os);
2520 else if (t.cs() == "subfloat") {
2521 // the syntax is \subfloat[caption]{content}
2522 // if it is a table of figure depends on the surrounding float
2523 bool has_caption = false;
2525 // do nothing if there is no outer float
2526 if (!float_type.empty()) {
2527 context.check_layout(os);
2529 begin_inset(os, "Float " + float_type + "\n");
2531 << "\nsideways false"
2532 << "\nstatus collapsed\n\n";
2535 if (p.next_token().cat() != catEscape &&
2536 p.next_token().character() == '[') {
2537 p.get_token(); // eat '['
2538 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2542 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2543 // the caption comes always as the last
2545 // we must make sure that the caption gets a \begin_layout
2546 os << "\n\\begin_layout Plain Layout";
2548 begin_inset(os, "Caption\n");
2549 Context newcontext(true, context.textclass);
2550 newcontext.font = context.font;
2551 newcontext.check_layout(os);
2552 os << caption << "\n";
2553 newcontext.check_end_layout(os);
2554 // We don't need really a new paragraph, but
2555 // we must make sure that the next item gets a \begin_layout.
2556 //newcontext.new_paragraph(os);
2560 // We don't need really a new paragraph, but
2561 // we must make sure that the next item gets a \begin_layout.
2563 context.new_paragraph(os);
2566 context.check_end_layout(os);
2567 // close the layout we opened
2569 os << "\n\\end_layout\n";
2571 // if the float type is not supported or there is no surrounding float
2574 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2575 handle_ert(os, t.asInput() + '[' + opt_arg +
2576 "]{" + p.verbatim_item() + '}', context);
2578 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2582 else if (t.cs() == "includegraphics") {
2583 bool const clip = p.next_token().asInput() == "*";
2586 string const arg = p.getArg('[', ']');
2587 map<string, string> opts;
2588 vector<string> keys;
2589 split_map(arg, opts, keys);
2591 opts["clip"] = string();
2592 string name = normalize_filename(p.verbatim_item());
2594 string const path = getMasterFilePath();
2595 // We want to preserve relative / absolute filenames,
2596 // therefore path is only used for testing
2597 if (!makeAbsPath(name, path).exists()) {
2598 // The file extension is probably missing.
2599 // Now try to find it out.
2600 string const dvips_name =
2601 find_file(name, path,
2602 known_dvips_graphics_formats);
2603 string const pdftex_name =
2604 find_file(name, path,
2605 known_pdftex_graphics_formats);
2606 if (!dvips_name.empty()) {
2607 if (!pdftex_name.empty()) {
2608 cerr << "This file contains the "
2610 "\"\\includegraphics{"
2612 "However, files\n\""
2613 << dvips_name << "\" and\n\""
2614 << pdftex_name << "\"\n"
2615 "both exist, so I had to make a "
2616 "choice and took the first one.\n"
2617 "Please move the unwanted one "
2618 "someplace else and try again\n"
2619 "if my choice was wrong."
2623 } else if (!pdftex_name.empty()) {
2629 if (makeAbsPath(name, path).exists())
2630 fix_relative_filename(name);
2632 cerr << "Warning: Could not find graphics file '"
2633 << name << "'." << endl;
2635 context.check_layout(os);
2636 begin_inset(os, "Graphics ");
2637 os << "\n\tfilename " << name << '\n';
2638 if (opts.find("width") != opts.end())
2640 << translate_len(opts["width"]) << '\n';
2641 if (opts.find("height") != opts.end())
2643 << translate_len(opts["height"]) << '\n';
2644 if (opts.find("scale") != opts.end()) {
2645 istringstream iss(opts["scale"]);
2649 os << "\tscale " << val << '\n';
2651 if (opts.find("angle") != opts.end()) {
2652 os << "\trotateAngle "
2653 << opts["angle"] << '\n';
2654 vector<string>::const_iterator a =
2655 find(keys.begin(), keys.end(), "angle");
2656 vector<string>::const_iterator s =
2657 find(keys.begin(), keys.end(), "width");
2658 if (s == keys.end())
2659 s = find(keys.begin(), keys.end(), "height");
2660 if (s == keys.end())
2661 s = find(keys.begin(), keys.end(), "scale");
2662 if (s != keys.end() && distance(s, a) > 0)
2663 os << "\tscaleBeforeRotation\n";
2665 if (opts.find("origin") != opts.end()) {
2667 string const opt = opts["origin"];
2668 if (opt.find('l') != string::npos) ss << "left";
2669 if (opt.find('r') != string::npos) ss << "right";
2670 if (opt.find('c') != string::npos) ss << "center";
2671 if (opt.find('t') != string::npos) ss << "Top";
2672 if (opt.find('b') != string::npos) ss << "Bottom";
2673 if (opt.find('B') != string::npos) ss << "Baseline";
2674 if (!ss.str().empty())
2675 os << "\trotateOrigin " << ss.str() << '\n';
2677 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2679 if (opts.find("keepaspectratio") != opts.end())
2680 os << "\tkeepAspectRatio\n";
2681 if (opts.find("clip") != opts.end())
2683 if (opts.find("draft") != opts.end())
2685 if (opts.find("bb") != opts.end())
2686 os << "\tBoundingBox "
2687 << opts["bb"] << '\n';
2688 int numberOfbbOptions = 0;
2689 if (opts.find("bbllx") != opts.end())
2690 numberOfbbOptions++;
2691 if (opts.find("bblly") != opts.end())
2692 numberOfbbOptions++;
2693 if (opts.find("bburx") != opts.end())
2694 numberOfbbOptions++;
2695 if (opts.find("bbury") != opts.end())
2696 numberOfbbOptions++;
2697 if (numberOfbbOptions == 4)
2698 os << "\tBoundingBox "
2699 << opts["bbllx"] << " " << opts["bblly"] << " "
2700 << opts["bburx"] << " " << opts["bbury"] << '\n';
2701 else if (numberOfbbOptions > 0)
2702 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2703 numberOfbbOptions = 0;
2704 if (opts.find("natwidth") != opts.end())
2705 numberOfbbOptions++;
2706 if (opts.find("natheight") != opts.end())
2707 numberOfbbOptions++;
2708 if (numberOfbbOptions == 2)
2709 os << "\tBoundingBox 0bp 0bp "
2710 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2711 else if (numberOfbbOptions > 0)
2712 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2713 ostringstream special;
2714 if (opts.find("hiresbb") != opts.end())
2715 special << "hiresbb,";
2716 if (opts.find("trim") != opts.end())
2718 if (opts.find("viewport") != opts.end())
2719 special << "viewport=" << opts["viewport"] << ',';
2720 if (opts.find("totalheight") != opts.end())
2721 special << "totalheight=" << opts["totalheight"] << ',';
2722 if (opts.find("type") != opts.end())
2723 special << "type=" << opts["type"] << ',';
2724 if (opts.find("ext") != opts.end())
2725 special << "ext=" << opts["ext"] << ',';
2726 if (opts.find("read") != opts.end())
2727 special << "read=" << opts["read"] << ',';
2728 if (opts.find("command") != opts.end())
2729 special << "command=" << opts["command"] << ',';
2730 string s_special = special.str();
2731 if (!s_special.empty()) {
2732 // We had special arguments. Remove the trailing ','.
2733 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2735 // TODO: Handle the unknown settings better.
2736 // Warn about invalid options.
2737 // Check whether some option was given twice.
2739 preamble.registerAutomaticallyLoadedPackage("graphicx");
2742 else if (t.cs() == "footnote" ||
2743 (t.cs() == "thanks" && context.layout->intitle)) {
2745 context.check_layout(os);
2746 begin_inset(os, "Foot\n");
2747 os << "status collapsed\n\n";
2748 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2752 else if (t.cs() == "marginpar") {
2754 context.check_layout(os);
2755 begin_inset(os, "Marginal\n");
2756 os << "status collapsed\n\n";
2757 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2761 else if (t.cs() == "ensuremath") {
2763 context.check_layout(os);
2764 string const s = p.verbatim_item();
2765 //FIXME: this never triggers in UTF8
2766 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2769 handle_ert(os, "\\ensuremath{" + s + "}",
2773 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2774 if (title_layout_found) {
2776 skip_spaces_braces(p);
2778 handle_ert(os, t.asInput(), context);
2781 else if (t.cs() == "tableofcontents") {
2782 context.check_layout(os);
2783 begin_command_inset(os, "toc", "tableofcontents");
2785 skip_spaces_braces(p);
2788 else if (t.cs() == "listoffigures") {
2789 context.check_layout(os);
2790 begin_inset(os, "FloatList figure\n");
2792 skip_spaces_braces(p);
2795 else if (t.cs() == "listoftables") {
2796 context.check_layout(os);
2797 begin_inset(os, "FloatList table\n");
2799 skip_spaces_braces(p);
2802 else if (t.cs() == "listof") {
2803 p.skip_spaces(true);
2804 string const name = p.get_token().cs();
2805 if (context.textclass.floats().typeExist(name)) {
2806 context.check_layout(os);
2807 begin_inset(os, "FloatList ");
2810 p.get_token(); // swallow second arg
2812 handle_ert(os, "\\listof{" + name + "}", context);
2815 else if ((where = is_known(t.cs(), known_text_font_families)))
2816 parse_text_attributes(p, os, FLAG_ITEM, outer,
2817 context, "\\family", context.font.family,
2818 known_coded_font_families[where - known_text_font_families]);
2820 else if ((where = is_known(t.cs(), known_text_font_series)))
2821 parse_text_attributes(p, os, FLAG_ITEM, outer,
2822 context, "\\series", context.font.series,
2823 known_coded_font_series[where - known_text_font_series]);
2825 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2826 parse_text_attributes(p, os, FLAG_ITEM, outer,
2827 context, "\\shape", context.font.shape,
2828 known_coded_font_shapes[where - known_text_font_shapes]);
2830 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2831 context.check_layout(os);
2832 TeXFont oldFont = context.font;
2833 context.font.init();
2834 context.font.size = oldFont.size;
2835 os << "\n\\family " << context.font.family << "\n";
2836 os << "\n\\series " << context.font.series << "\n";
2837 os << "\n\\shape " << context.font.shape << "\n";
2838 if (t.cs() == "textnormal") {
2839 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2840 output_font_change(os, context.font, oldFont);
2841 context.font = oldFont;
2843 eat_whitespace(p, os, context, false);
2846 else if (t.cs() == "textcolor") {
2847 // scheme is \textcolor{color name}{text}
2848 string const color = p.verbatim_item();
2849 // we only support the predefined colors of the color package
2850 if (color == "black" || color == "blue" || color == "cyan"
2851 || color == "green" || color == "magenta" || color == "red"
2852 || color == "white" || color == "yellow") {
2853 context.check_layout(os);
2854 os << "\n\\color " << color << "\n";
2855 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2856 context.check_layout(os);
2857 os << "\n\\color inherit\n";
2858 preamble.registerAutomaticallyLoadedPackage("color");
2860 // for custom defined colors
2861 handle_ert(os, t.asInput() + "{" + color + "}", context);
2864 else if (t.cs() == "underbar" || t.cs() == "uline") {
2865 // \underbar is not 100% correct (LyX outputs \uline
2866 // of ulem.sty). The difference is that \ulem allows
2867 // line breaks, and \underbar does not.
2868 // Do NOT handle \underline.
2869 // \underbar cuts through y, g, q, p etc.,
2870 // \underline does not.
2871 context.check_layout(os);
2872 os << "\n\\bar under\n";
2873 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2874 context.check_layout(os);
2875 os << "\n\\bar default\n";
2876 preamble.registerAutomaticallyLoadedPackage("ulem");
2879 else if (t.cs() == "sout") {
2880 context.check_layout(os);
2881 os << "\n\\strikeout on\n";
2882 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2883 context.check_layout(os);
2884 os << "\n\\strikeout default\n";
2885 preamble.registerAutomaticallyLoadedPackage("ulem");
2888 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2889 t.cs() == "emph" || t.cs() == "noun") {
2890 context.check_layout(os);
2891 os << "\n\\" << t.cs() << " on\n";
2892 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2893 context.check_layout(os);
2894 os << "\n\\" << t.cs() << " default\n";
2895 if (t.cs() == "uuline" || t.cs() == "uwave")
2896 preamble.registerAutomaticallyLoadedPackage("ulem");
2899 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2900 context.check_layout(os);
2901 string name = p.getArg('{', '}');
2902 string localtime = p.getArg('{', '}');
2903 preamble.registerAuthor(name);
2904 Author const & author = preamble.getAuthor(name);
2905 // from_ctime() will fail if LyX decides to output the
2906 // time in the text language. It might also use a wrong
2907 // time zone (if the original LyX document was exported
2908 // with a different time zone).
2909 time_t ptime = from_ctime(localtime);
2910 if (ptime == static_cast<time_t>(-1)) {
2911 cerr << "Warning: Could not parse time `" << localtime
2912 << "´ for change tracking, using current time instead.\n";
2913 ptime = current_time();
2915 if (t.cs() == "lyxadded")
2916 os << "\n\\change_inserted ";
2918 os << "\n\\change_deleted ";
2919 os << author.bufferId() << ' ' << ptime << '\n';
2920 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2921 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2922 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2923 LaTeXPackages::isAvailable("xcolor");
2924 // No need to test for luatex, since luatex comes in
2925 // two flavours (dvi and pdf), like latex, and those
2926 // are detected by pdflatex.
2927 if (pdflatex || xetex) {
2929 preamble.registerAutomaticallyLoadedPackage("ulem");
2930 preamble.registerAutomaticallyLoadedPackage("xcolor");
2931 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2935 preamble.registerAutomaticallyLoadedPackage("dvipost");
2936 } else if (xcolorulem) {
2937 preamble.registerAutomaticallyLoadedPackage("ulem");
2938 preamble.registerAutomaticallyLoadedPackage("xcolor");
2943 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2944 t.cs() == "vphantom") {
2945 context.check_layout(os);
2946 if (t.cs() == "phantom")
2947 begin_inset(os, "Phantom Phantom\n");
2948 if (t.cs() == "hphantom")
2949 begin_inset(os, "Phantom HPhantom\n");
2950 if (t.cs() == "vphantom")
2951 begin_inset(os, "Phantom VPhantom\n");
2952 os << "status open\n";
2953 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2958 else if (t.cs() == "href") {
2959 context.check_layout(os);
2960 string target = p.getArg('{', '}');
2961 string name = p.getArg('{', '}');
2963 size_t i = target.find(':');
2964 if (i != string::npos) {
2965 type = target.substr(0, i + 1);
2966 if (type == "mailto:" || type == "file:")
2967 target = target.substr(i + 1);
2968 // handle the case that name is equal to target, except of "http://"
2969 else if (target.substr(i + 3) == name && type == "http:")
2972 begin_command_inset(os, "href", "href");
2974 os << "name \"" << name << "\"\n";
2975 os << "target \"" << target << "\"\n";
2976 if (type == "mailto:" || type == "file:")
2977 os << "type \"" << type << "\"\n";
2979 skip_spaces_braces(p);
2982 else if (t.cs() == "lyxline") {
2983 // swallow size argument (it is not used anyway)
2985 if (!context.atParagraphStart()) {
2986 // so our line is in the middle of a paragraph
2987 // we need to add a new line, lest this line
2988 // follow the other content on that line and
2989 // run off the side of the page
2990 // FIXME: This may create an empty paragraph,
2991 // but without that it would not be
2992 // possible to set noindent below.
2993 // Fortunately LaTeX does not care
2994 // about the empty paragraph.
2995 context.new_paragraph(os);
2997 if (preamble.indentParagraphs()) {
2998 // we need to unindent, lest the line be too long
2999 context.add_par_extra_stuff("\\noindent\n");
3001 context.check_layout(os);
3002 begin_command_inset(os, "line", "rule");
3003 os << "offset \"0.5ex\"\n"
3004 "width \"100line%\"\n"
3009 else if (t.cs() == "rule") {
3010 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3011 string const width = p.getArg('{', '}');
3012 string const thickness = p.getArg('{', '}');
3013 context.check_layout(os);
3014 begin_command_inset(os, "line", "rule");
3015 if (!offset.empty())
3016 os << "offset \"" << translate_len(offset) << "\"\n";
3017 os << "width \"" << translate_len(width) << "\"\n"
3018 "height \"" << translate_len(thickness) << "\"\n";
3022 else if (is_known(t.cs(), known_phrases) ||
3023 (t.cs() == "protect" &&
3024 p.next_token().cat() == catEscape &&
3025 is_known(p.next_token().cs(), known_phrases))) {
3026 // LyX sometimes puts a \protect in front, so we have to ignore it
3027 // FIXME: This needs to be changed when bug 4752 is fixed.
3029 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3031 context.check_layout(os);
3032 os << known_coded_phrases[where - known_phrases];
3033 skip_spaces_braces(p);
3036 else if ((where = is_known(t.cs(), known_ref_commands))) {
3037 string const opt = p.getOpt();
3039 context.check_layout(os);
3040 begin_command_inset(os, "ref",
3041 known_coded_ref_commands[where - known_ref_commands]);
3042 os << "reference \""
3043 << convert_command_inset_arg(p.verbatim_item())
3046 if (t.cs() == "vref" || t.cs() == "vpageref")
3047 preamble.registerAutomaticallyLoadedPackage("varioref");
3050 // LyX does not support optional arguments of ref commands
3051 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3052 p.verbatim_item() + "}", context);
3056 else if (use_natbib &&
3057 is_known(t.cs(), known_natbib_commands) &&
3058 ((t.cs() != "citefullauthor" &&
3059 t.cs() != "citeyear" &&
3060 t.cs() != "citeyearpar") ||
3061 p.next_token().asInput() != "*")) {
3062 context.check_layout(os);
3063 string command = t.cs();
3064 if (p.next_token().asInput() == "*") {
3068 if (command == "citefullauthor")
3069 // alternative name for "\\citeauthor*"
3070 command = "citeauthor*";
3072 // text before the citation
3074 // text after the citation
3076 get_cite_arguments(p, true, before, after);
3078 if (command == "cite") {
3079 // \cite without optional argument means
3080 // \citet, \cite with at least one optional
3081 // argument means \citep.
3082 if (before.empty() && after.empty())
3087 if (before.empty() && after == "[]")
3088 // avoid \citet[]{a}
3090 else if (before == "[]" && after == "[]") {
3091 // avoid \citet[][]{a}
3095 // remove the brackets around after and before
3096 if (!after.empty()) {
3098 after.erase(after.length() - 1, 1);
3099 after = convert_command_inset_arg(after);
3101 if (!before.empty()) {
3103 before.erase(before.length() - 1, 1);
3104 before = convert_command_inset_arg(before);
3106 begin_command_inset(os, "citation", command);
3107 os << "after " << '"' << after << '"' << "\n";
3108 os << "before " << '"' << before << '"' << "\n";
3110 << convert_command_inset_arg(p.verbatim_item())
3115 else if (use_jurabib &&
3116 is_known(t.cs(), known_jurabib_commands) &&
3117 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3118 context.check_layout(os);
3119 string command = t.cs();
3120 if (p.next_token().asInput() == "*") {
3124 char argumentOrder = '\0';
3125 vector<string> const options =
3126 preamble.getPackageOptions("jurabib");
3127 if (find(options.begin(), options.end(),
3128 "natbiborder") != options.end())
3129 argumentOrder = 'n';
3130 else if (find(options.begin(), options.end(),
3131 "jurabiborder") != options.end())
3132 argumentOrder = 'j';
3134 // text before the citation
3136 // text after the citation
3138 get_cite_arguments(p, argumentOrder != 'j', before, after);
3140 string const citation = p.verbatim_item();
3141 if (!before.empty() && argumentOrder == '\0') {
3142 cerr << "Warning: Assuming argument order "
3143 "of jurabib version 0.6 for\n'"
3144 << command << before << after << '{'
3145 << citation << "}'.\n"
3146 "Add 'jurabiborder' to the jurabib "
3147 "package options if you used an\n"
3148 "earlier jurabib version." << endl;
3150 if (!after.empty()) {
3152 after.erase(after.length() - 1, 1);
3154 if (!before.empty()) {
3156 before.erase(before.length() - 1, 1);
3158 begin_command_inset(os, "citation", command);
3159 os << "after " << '"' << after << '"' << "\n";
3160 os << "before " << '"' << before << '"' << "\n";
3161 os << "key " << '"' << citation << '"' << "\n";
3165 else if (t.cs() == "cite"
3166 || t.cs() == "nocite") {
3167 context.check_layout(os);
3168 string after = convert_command_inset_arg(p.getArg('[', ']'));
3169 string key = convert_command_inset_arg(p.verbatim_item());
3170 // store the case that it is "\nocite{*}" to use it later for
3173 begin_command_inset(os, "citation", t.cs());
3174 os << "after " << '"' << after << '"' << "\n";
3175 os << "key " << '"' << key << '"' << "\n";
3177 } else if (t.cs() == "nocite")
3181 else if (t.cs() == "index") {
3182 context.check_layout(os);
3183 begin_inset(os, "Index idx\n");
3184 os << "status collapsed\n";
3185 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3189 else if (t.cs() == "nomenclature") {
3190 context.check_layout(os);
3191 begin_command_inset(os, "nomenclature", "nomenclature");
3192 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3193 if (!prefix.empty())
3194 os << "prefix " << '"' << prefix << '"' << "\n";
3195 os << "symbol " << '"'
3196 << convert_command_inset_arg(p.verbatim_item());
3197 os << "\"\ndescription \""
3198 << convert_command_inset_arg(p.verbatim_item())
3201 preamble.registerAutomaticallyLoadedPackage("nomencl");
3204 else if (t.cs() == "label") {
3205 context.check_layout(os);
3206 begin_command_inset(os, "label", "label");
3208 << convert_command_inset_arg(p.verbatim_item())
3213 else if (t.cs() == "printindex") {
3214 context.check_layout(os);
3215 begin_command_inset(os, "index_print", "printindex");
3216 os << "type \"idx\"\n";
3218 skip_spaces_braces(p);
3219 preamble.registerAutomaticallyLoadedPackage("makeidx");
3220 if (preamble.use_indices() == "true")
3221 preamble.registerAutomaticallyLoadedPackage("splitidx");
3224 else if (t.cs() == "printnomenclature") {
3226 string width_type = "";
3227 context.check_layout(os);
3228 begin_command_inset(os, "nomencl_print", "printnomenclature");
3229 // case of a custom width
3231 width = p.getArg('[', ']');
3232 width = translate_len(width);
3233 width_type = "custom";
3235 // case of no custom width
3236 // the case of no custom width but the width set
3237 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3238 // because the user could have set anything, not only the width
3239 // of the longest label (which would be width_type = "auto")
3240 string label = convert_command_inset_arg(p.getArg('{', '}'));
3241 if (label.empty() && width_type.empty())
3242 width_type = "none";
3243 os << "set_width \"" << width_type << "\"\n";
3244 if (width_type == "custom")
3245 os << "width \"" << width << '\"';
3247 skip_spaces_braces(p);
3248 preamble.registerAutomaticallyLoadedPackage("nomencl");
3251 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3252 context.check_layout(os);
3253 begin_inset(os, "script ");
3254 os << t.cs().substr(4) << '\n';
3255 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3257 if (t.cs() == "textsubscript")
3258 preamble.registerAutomaticallyLoadedPackage("subscript");
3261 else if ((where = is_known(t.cs(), known_quotes))) {
3262 context.check_layout(os);
3263 begin_inset(os, "Quotes ");
3264 os << known_coded_quotes[where - known_quotes];
3266 // LyX adds {} after the quote, so we have to eat
3267 // spaces here if there are any before a possible
3269 eat_whitespace(p, os, context, false);
3273 else if ((where = is_known(t.cs(), known_sizes)) &&
3274 context.new_layout_allowed) {
3275 context.check_layout(os);
3276 TeXFont const oldFont = context.font;
3277 context.font.size = known_coded_sizes[where - known_sizes];
3278 output_font_change(os, oldFont, context.font);
3279 eat_whitespace(p, os, context, false);
3282 else if ((where = is_known(t.cs(), known_font_families)) &&
3283 context.new_layout_allowed) {
3284 context.check_layout(os);
3285 TeXFont const oldFont = context.font;
3286 context.font.family =
3287 known_coded_font_families[where - known_font_families];
3288 output_font_change(os, oldFont, context.font);
3289 eat_whitespace(p, os, context, false);
3292 else if ((where = is_known(t.cs(), known_font_series)) &&
3293 context.new_layout_allowed) {
3294 context.check_layout(os);
3295 TeXFont const oldFont = context.font;
3296 context.font.series =
3297 known_coded_font_series[where - known_font_series];
3298 output_font_change(os, oldFont, context.font);
3299 eat_whitespace(p, os, context, false);
3302 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3303 context.new_layout_allowed) {
3304 context.check_layout(os);
3305 TeXFont const oldFont = context.font;
3306 context.font.shape =
3307 known_coded_font_shapes[where - known_font_shapes];
3308 output_font_change(os, oldFont, context.font);
3309 eat_whitespace(p, os, context, false);
3311 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3312 context.new_layout_allowed) {
3313 context.check_layout(os);
3314 TeXFont const oldFont = context.font;
3315 context.font.init();
3316 context.font.size = oldFont.size;
3317 context.font.family =
3318 known_coded_font_families[where - known_old_font_families];
3319 output_font_change(os, oldFont, context.font);
3320 eat_whitespace(p, os, context, false);
3323 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3324 context.new_layout_allowed) {
3325 context.check_layout(os);
3326 TeXFont const oldFont = context.font;
3327 context.font.init();
3328 context.font.size = oldFont.size;
3329 context.font.series =
3330 known_coded_font_series[where - known_old_font_series];
3331 output_font_change(os, oldFont, context.font);
3332 eat_whitespace(p, os, context, false);
3335 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3336 context.new_layout_allowed) {
3337 context.check_layout(os);
3338 TeXFont const oldFont = context.font;
3339 context.font.init();
3340 context.font.size = oldFont.size;
3341 context.font.shape =
3342 known_coded_font_shapes[where - known_old_font_shapes];
3343 output_font_change(os, oldFont, context.font);
3344 eat_whitespace(p, os, context, false);
3347 else if (t.cs() == "selectlanguage") {
3348 context.check_layout(os);
3349 // save the language for the case that a
3350 // \foreignlanguage is used
3352 context.font.language = babel2lyx(p.verbatim_item());
3353 os << "\n\\lang " << context.font.language << "\n";
3356 else if (t.cs() == "foreignlanguage") {
3357 string const lang = babel2lyx(p.verbatim_item());
3358 parse_text_attributes(p, os, FLAG_ITEM, outer,
3360 context.font.language, lang);
3363 else if (t.cs() == "inputencoding") {
3364 // nothing to write here
3365 string const enc = subst(p.verbatim_item(), "\n", " ");
3369 else if ((where = is_known(t.cs(), known_special_chars))) {
3370 context.check_layout(os);
3371 os << "\\SpecialChar \\"
3372 << known_coded_special_chars[where - known_special_chars]
3374 skip_spaces_braces(p);
3377 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3378 context.check_layout(os);
3379 os << "\\SpecialChar \\nobreakdash-\n";
3383 else if (t.cs() == "textquotedbl") {
3384 context.check_layout(os);
3389 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3390 context.check_layout(os);
3391 os << "\\SpecialChar \\@.\n";
3395 else if (t.cs() == "-") {
3396 context.check_layout(os);
3397 os << "\\SpecialChar \\-\n";
3400 else if (t.cs() == "textasciitilde") {
3401 context.check_layout(os);
3403 skip_spaces_braces(p);
3406 else if (t.cs() == "textasciicircum") {
3407 context.check_layout(os);
3409 skip_spaces_braces(p);
3412 else if (t.cs() == "textbackslash") {
3413 context.check_layout(os);
3414 os << "\n\\backslash\n";
3415 skip_spaces_braces(p);
3418 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3419 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3421 context.check_layout(os);
3425 else if (t.cs() == "char") {
3426 context.check_layout(os);
3427 if (p.next_token().character() == '`') {
3429 if (p.next_token().cs() == "\"") {
3434 handle_ert(os, "\\char`", context);
3437 handle_ert(os, "\\char", context);
3441 else if (t.cs() == "verb") {
3442 context.check_layout(os);
3443 char const delimiter = p.next_token().character();
3444 string const arg = p.getArg(delimiter, delimiter);
3446 oss << "\\verb" << delimiter << arg << delimiter;
3447 handle_ert(os, oss.str(), context);
3450 // Problem: \= creates a tabstop inside the tabbing environment
3451 // and else an accent. In the latter case we really would want
3452 // \={o} instead of \= o.
3453 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3454 handle_ert(os, t.asInput(), context);
3456 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3457 else if (t.cs().size() == 1
3458 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3459 context.check_layout(os);
3460 // try to see whether the string is in unicodesymbols
3462 string command = t.asInput() + "{"
3463 + trimSpaceAndEol(p.verbatim_item())
3466 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3467 Encodings::TEXT_CMD | Encodings::MATH_CMD, rem, &req);
3470 cerr << "When parsing " << command
3471 << ", result is " << to_utf8(s)
3472 << "+" << to_utf8(rem) << endl;
3474 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
3475 preamble.registerAutomaticallyLoadedPackage(*it);
3477 // we did not find a non-ert version
3478 handle_ert(os, command, context);
3481 else if (t.cs() == "\\") {
3482 context.check_layout(os);
3484 handle_ert(os, "\\\\" + p.getOpt(), context);
3485 else if (p.next_token().asInput() == "*") {
3487 // getOpt() eats the following space if there
3488 // is no optional argument, but that is OK
3489 // here since it has no effect in the output.
3490 handle_ert(os, "\\\\*" + p.getOpt(), context);
3493 begin_inset(os, "Newline newline");
3498 else if (t.cs() == "newline" ||
3499 (t.cs() == "linebreak" && !p.hasOpt())) {
3500 context.check_layout(os);
3501 begin_inset(os, "Newline ");
3504 skip_spaces_braces(p);
3507 else if (t.cs() == "input" || t.cs() == "include"
3508 || t.cs() == "verbatiminput") {
3509 string name = t.cs();
3510 if (t.cs() == "verbatiminput"
3511 && p.next_token().asInput() == "*")
3512 name += p.get_token().asInput();
3513 context.check_layout(os);
3514 string filename(normalize_filename(p.getArg('{', '}')));
3515 string const path = getMasterFilePath();
3516 // We want to preserve relative / absolute filenames,
3517 // therefore path is only used for testing
3518 if ((t.cs() == "include" || t.cs() == "input") &&
3519 !makeAbsPath(filename, path).exists()) {
3520 // The file extension is probably missing.
3521 // Now try to find it out.
3522 string const tex_name =
3523 find_file(filename, path,
3524 known_tex_extensions);
3525 if (!tex_name.empty())
3526 filename = tex_name;
3528 bool external = false;
3530 if (makeAbsPath(filename, path).exists()) {
3531 string const abstexname =
3532 makeAbsPath(filename, path).absFileName();
3533 string const abslyxname =
3534 changeExtension(abstexname, ".lyx");
3535 string const absfigname =
3536 changeExtension(abstexname, ".fig");
3537 fix_relative_filename(filename);
3538 string const lyxname =
3539 changeExtension(filename, ".lyx");
3541 external = FileName(absfigname).exists();
3542 if (t.cs() == "input") {
3543 string const ext = getExtension(abstexname);
3545 // Combined PS/LaTeX:
3546 // x.eps, x.pstex_t (old xfig)
3547 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3548 FileName const absepsname(
3549 changeExtension(abstexname, ".eps"));
3550 FileName const abspstexname(
3551 changeExtension(abstexname, ".pstex"));
3552 bool const xfigeps =
3553 (absepsname.exists() ||
3554 abspstexname.exists()) &&
3557 // Combined PDF/LaTeX:
3558 // x.pdf, x.pdftex_t (old xfig)
3559 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3560 FileName const abspdfname(
3561 changeExtension(abstexname, ".pdf"));
3562 bool const xfigpdf =
3563 abspdfname.exists() &&
3564 (ext == "pdftex_t" || ext == "pdf_t");
3568 // Combined PS/PDF/LaTeX:
3569 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3570 string const absbase2(
3571 removeExtension(abstexname) + "_pspdftex");
3572 FileName const abseps2name(
3573 addExtension(absbase2, ".eps"));
3574 FileName const abspdf2name(
3575 addExtension(absbase2, ".pdf"));
3576 bool const xfigboth =
3577 abspdf2name.exists() &&
3578 abseps2name.exists() && ext == "pspdftex";
3580 xfig = xfigpdf || xfigeps || xfigboth;
3581 external = external && xfig;
3584 outname = changeExtension(filename, ".fig");
3586 // Don't try to convert, the result
3587 // would be full of ERT.
3589 } else if (t.cs() != "verbatiminput" &&
3590 tex2lyx(abstexname, FileName(abslyxname),
3597 cerr << "Warning: Could not find included file '"
3598 << filename << "'." << endl;
3602 begin_inset(os, "External\n");
3603 os << "\ttemplate XFig\n"
3604 << "\tfilename " << outname << '\n';
3605 registerExternalTemplatePackages("XFig");
3607 begin_command_inset(os, "include", name);
3608 os << "preview false\n"
3609 "filename \"" << outname << "\"\n";
3610 if (t.cs() == "verbatiminput")
3611 preamble.registerAutomaticallyLoadedPackage("verbatim");
3616 else if (t.cs() == "bibliographystyle") {
3617 // store new bibliographystyle
3618 bibliographystyle = p.verbatim_item();
3619 // If any other command than \bibliography and
3620 // \nocite{*} follows, we need to output the style
3621 // (because it might be used by that command).
3622 // Otherwise, it will automatically be output by LyX.
3625 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3626 if (t2.cat() == catBegin)
3628 if (t2.cat() != catEscape)
3630 if (t2.cs() == "nocite") {
3631 if (p.getArg('{', '}') == "*")
3633 } else if (t2.cs() == "bibliography")
3640 "\\bibliographystyle{" + bibliographystyle + '}',
3645 else if (t.cs() == "bibliography") {
3646 context.check_layout(os);
3647 begin_command_inset(os, "bibtex", "bibtex");
3648 if (!btprint.empty()) {
3649 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3650 // clear the string because the next BibTeX inset can be without the
3651 // \nocite{*} option
3654 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3655 // Do we have a bibliographystyle set?
3656 if (!bibliographystyle.empty())
3657 os << "options " << '"' << bibliographystyle << '"' << "\n";
3661 else if (t.cs() == "parbox") {
3662 // Test whether this is an outer box of a shaded box
3664 // swallow arguments
3665 while (p.hasOpt()) {
3667 p.skip_spaces(true);
3670 p.skip_spaces(true);
3672 if (p.next_token().cat() == catBegin)
3674 p.skip_spaces(true);
3675 Token to = p.get_token();
3676 bool shaded = false;
3677 if (to.asInput() == "\\begin") {
3678 p.skip_spaces(true);
3679 if (p.getArg('{', '}') == "shaded")
3684 parse_outer_box(p, os, FLAG_ITEM, outer,
3685 context, "parbox", "shaded");
3687 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3691 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3692 t.cs() == "shadowbox" || t.cs() == "doublebox")
3693 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3695 else if (t.cs() == "framebox") {
3696 if (p.next_token().character() == '(') {
3697 //the syntax is: \framebox(x,y)[position]{content}
3698 string arg = t.asInput();
3699 arg += p.getFullParentheseArg();
3700 arg += p.getFullOpt();
3701 eat_whitespace(p, os, context, false);
3702 handle_ert(os, arg + '{', context);
3703 eat_whitespace(p, os, context, false);
3704 parse_text(p, os, FLAG_ITEM, outer, context);
3705 handle_ert(os, "}", context);
3707 string special = p.getFullOpt();
3708 special += p.getOpt();
3709 parse_outer_box(p, os, FLAG_ITEM, outer,
3710 context, t.cs(), special);
3714 //\makebox() is part of the picture environment and different from \makebox{}
3715 //\makebox{} will be parsed by parse_box
3716 else if (t.cs() == "makebox") {
3717 if (p.next_token().character() == '(') {
3718 //the syntax is: \makebox(x,y)[position]{content}
3719 string arg = t.asInput();
3720 arg += p.getFullParentheseArg();
3721 arg += p.getFullOpt();
3722 eat_whitespace(p, os, context, false);
3723 handle_ert(os, arg + '{', context);
3724 eat_whitespace(p, os, context, false);
3725 parse_text(p, os, FLAG_ITEM, outer, context);
3726 handle_ert(os, "}", context);
3728 //the syntax is: \makebox[width][position]{content}
3729 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3733 else if (t.cs() == "smallskip" ||
3734 t.cs() == "medskip" ||
3735 t.cs() == "bigskip" ||
3736 t.cs() == "vfill") {
3737 context.check_layout(os);
3738 begin_inset(os, "VSpace ");
3741 skip_spaces_braces(p);
3744 else if ((where = is_known(t.cs(), known_spaces))) {
3745 context.check_layout(os);
3746 begin_inset(os, "space ");
3747 os << '\\' << known_coded_spaces[where - known_spaces]
3750 // LaTeX swallows whitespace after all spaces except
3751 // "\\,". We have to do that here, too, because LyX
3752 // adds "{}" which would make the spaces significant.
3754 eat_whitespace(p, os, context, false);
3755 // LyX adds "{}" after all spaces except "\\ " and
3756 // "\\,", so we have to remove "{}".
3757 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3758 // remove the braces after "\\,", too.
3763 else if (t.cs() == "newpage" ||
3764 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3765 t.cs() == "clearpage" ||
3766 t.cs() == "cleardoublepage") {
3767 context.check_layout(os);
3768 begin_inset(os, "Newpage ");
3771 skip_spaces_braces(p);
3774 else if (t.cs() == "DeclareRobustCommand" ||
3775 t.cs() == "DeclareRobustCommandx" ||
3776 t.cs() == "newcommand" ||
3777 t.cs() == "newcommandx" ||
3778 t.cs() == "providecommand" ||
3779 t.cs() == "providecommandx" ||
3780 t.cs() == "renewcommand" ||
3781 t.cs() == "renewcommandx") {
3782 // DeclareRobustCommand, DeclareRobustCommandx,
3783 // providecommand and providecommandx could be handled
3784 // by parse_command(), but we need to call
3785 // add_known_command() here.
3786 string name = t.asInput();
3787 if (p.next_token().asInput() == "*") {
3788 // Starred form. Eat '*'
3792 string const command = p.verbatim_item();
3793 string const opt1 = p.getFullOpt();
3794 string const opt2 = p.getFullOpt();
3795 add_known_command(command, opt1, !opt2.empty());
3796 string const ert = name + '{' + command + '}' +
3798 '{' + p.verbatim_item() + '}';
3800 if (t.cs() == "DeclareRobustCommand" ||
3801 t.cs() == "DeclareRobustCommandx" ||
3802 t.cs() == "providecommand" ||
3803 t.cs() == "providecommandx" ||
3804 name[name.length()-1] == '*')
3805 handle_ert(os, ert, context);
3807 context.check_layout(os);
3808 begin_inset(os, "FormulaMacro");
3814 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3815 // let could be handled by parse_command(),
3816 // but we need to call add_known_command() here.
3817 string ert = t.asInput();
3820 if (p.next_token().cat() == catBegin) {
3821 name = p.verbatim_item();
3822 ert += '{' + name + '}';
3824 name = p.verbatim_item();
3829 if (p.next_token().cat() == catBegin) {
3830 command = p.verbatim_item();
3831 ert += '{' + command + '}';
3833 command = p.verbatim_item();
3836 // If command is known, make name known too, to parse
3837 // its arguments correctly. For this reason we also
3838 // have commands in syntax.default that are hardcoded.
3839 CommandMap::iterator it = known_commands.find(command);
3840 if (it != known_commands.end())
3841 known_commands[t.asInput()] = it->second;
3842 handle_ert(os, ert, context);
3845 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3846 bool starred = false;
3847 if (p.next_token().asInput() == "*") {
3851 string name = t.asInput();
3852 string const length = p.verbatim_item();
3855 bool valid = splitLatexLength(length, valstring, unit);
3856 bool known_hspace = false;
3857 bool known_vspace = false;
3858 bool known_unit = false;
3861 istringstream iss(valstring);
3864 if (t.cs()[0] == 'h') {
3865 if (unit == "\\fill") {
3870 known_hspace = true;
3873 if (unit == "\\smallskipamount") {
3875 known_vspace = true;
3876 } else if (unit == "\\medskipamount") {
3878 known_vspace = true;
3879 } else if (unit == "\\bigskipamount") {
3881 known_vspace = true;
3882 } else if (unit == "\\fill") {
3884 known_vspace = true;
3888 if (!known_hspace && !known_vspace) {
3889 switch (unitFromString(unit)) {
3910 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3911 // Literal horizontal length or known variable
3912 context.check_layout(os);
3913 begin_inset(os, "space ");
3921 if (known_unit && !known_hspace)
3923 << translate_len(length);
3925 } else if (known_unit || known_vspace) {
3926 // Literal vertical length or known variable
3927 context.check_layout(os);
3928 begin_inset(os, "VSpace ");
3936 // LyX can't handle other length variables in Inset VSpace/space
3941 handle_ert(os, name + '{' + unit + '}', context);
3942 else if (value == -1.0)
3943 handle_ert(os, name + "{-" + unit + '}', context);
3945 handle_ert(os, name + '{' + valstring + unit + '}', context);
3947 handle_ert(os, name + '{' + length + '}', context);
3951 // The single '=' is meant here.
3952 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3954 context.check_layout(os);
3955 begin_inset(os, "Flex ");
3956 os << to_utf8(newinsetlayout->name()) << '\n'
3957 << "status collapsed\n";
3958 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3962 else if (t.cs() == "includepdf") {
3964 string const arg = p.getArg('[', ']');
3965 map<string, string> opts;
3966 vector<string> keys;
3967 split_map(arg, opts, keys);
3968 string name = normalize_filename(p.verbatim_item());
3969 string const path = getMasterFilePath();
3970 // We want to preserve relative / absolute filenames,
3971 // therefore path is only used for testing
3972 if (!makeAbsPath(name, path).exists()) {
3973 // The file extension is probably missing.
3974 // Now try to find it out.
3975 char const * const pdfpages_format[] = {"pdf", 0};
3976 string const pdftex_name =
3977 find_file(name, path, pdfpages_format);
3978 if (!pdftex_name.empty()) {
3983 if (makeAbsPath(name, path).exists())
3984 fix_relative_filename(name);
3986 cerr << "Warning: Could not find file '"
3987 << name << "'." << endl;
3989 context.check_layout(os);
3990 begin_inset(os, "External\n\ttemplate ");
3991 os << "PDFPages\n\tfilename "
3993 // parse the options
3994 if (opts.find("pages") != opts.end())
3995 os << "\textra LaTeX \"pages="
3996 << opts["pages"] << "\"\n";
3997 if (opts.find("angle") != opts.end())
3998 os << "\trotateAngle "
3999 << opts["angle"] << '\n';
4000 if (opts.find("origin") != opts.end()) {
4002 string const opt = opts["origin"];
4003 if (opt == "tl") ss << "topleft";
4004 if (opt == "bl") ss << "bottomleft";
4005 if (opt == "Bl") ss << "baselineleft";
4006 if (opt == "c") ss << "center";
4007 if (opt == "tc") ss << "topcenter";
4008 if (opt == "bc") ss << "bottomcenter";
4009 if (opt == "Bc") ss << "baselinecenter";
4010 if (opt == "tr") ss << "topright";
4011 if (opt == "br") ss << "bottomright";
4012 if (opt == "Br") ss << "baselineright";
4013 if (!ss.str().empty())
4014 os << "\trotateOrigin " << ss.str() << '\n';
4016 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4018 if (opts.find("width") != opts.end())
4020 << translate_len(opts["width"]) << '\n';
4021 if (opts.find("height") != opts.end())
4023 << translate_len(opts["height"]) << '\n';
4024 if (opts.find("keepaspectratio") != opts.end())
4025 os << "\tkeepAspectRatio\n";
4027 context.check_layout(os);
4028 registerExternalTemplatePackages("PDFPages");
4031 else if (t.cs() == "loadgame") {
4033 string name = normalize_filename(p.verbatim_item());
4034 string const path = getMasterFilePath();
4035 // We want to preserve relative / absolute filenames,
4036 // therefore path is only used for testing
4037 if (!makeAbsPath(name, path).exists()) {
4038 // The file extension is probably missing.
4039 // Now try to find it out.
4040 char const * const lyxskak_format[] = {"fen", 0};
4041 string const lyxskak_name =
4042 find_file(name, path, lyxskak_format);
4043 if (!lyxskak_name.empty())
4044 name = lyxskak_name;
4046 if (makeAbsPath(name, path).exists())
4047 fix_relative_filename(name);
4049 cerr << "Warning: Could not find file '"
4050 << name << "'." << endl;
4051 context.check_layout(os);
4052 begin_inset(os, "External\n\ttemplate ");
4053 os << "ChessDiagram\n\tfilename "
4056 context.check_layout(os);
4057 // after a \loadgame follows a \showboard
4058 if (p.get_token().asInput() == "showboard")
4060 registerExternalTemplatePackages("ChessDiagram");
4064 // try to see whether the string is in unicodesymbols
4065 // Only use text mode commands, since we are in text mode here,
4066 // and math commands may be invalid (bug 6797)
4069 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4070 Encodings::TEXT_CMD, rem, &req);
4073 cerr << "When parsing " << t.cs()
4074 << ", result is " << to_utf8(s)
4075 << "+" << to_utf8(rem) << endl;
4076 context.check_layout(os);
4078 skip_spaces_braces(p);
4079 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
4080 preamble.registerAutomaticallyLoadedPackage(*it);
4082 //cerr << "#: " << t << " mode: " << mode << endl;
4083 // heuristic: read up to next non-nested space
4085 string s = t.asInput();
4086 string z = p.verbatim_item();
4087 while (p.good() && z != " " && z.size()) {
4088 //cerr << "read: " << z << endl;
4090 z = p.verbatim_item();
4092 cerr << "found ERT: " << s << endl;
4093 handle_ert(os, s + ' ', context);
4096 string name = t.asInput();
4097 if (p.next_token().asInput() == "*") {
4098 // Starred commands like \vspace*{}
4099 p.get_token(); // Eat '*'
4102 if (!parse_command(name, p, os, outer, context))
4103 handle_ert(os, name, context);
4107 if (flags & FLAG_LEAVE) {
4108 flags &= ~FLAG_LEAVE;