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 "support/lassert.h"
28 #include "support/convert.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/lstrings.h"
32 #include "support/lyxtime.h"
41 using namespace lyx::support;
46 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
47 Context const & context, InsetLayout const * layout)
49 bool const forcePlainLayout =
50 layout ? layout->forcePlainLayout() : false;
51 Context newcontext(true, context.textclass);
53 newcontext.layout = &context.textclass.plainLayout();
55 newcontext.font = context.font;
56 parse_text(p, os, flags, outer, newcontext);
57 newcontext.check_end_layout(os);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
64 Context const & context, string const & name)
66 InsetLayout const * layout = 0;
67 DocumentClass::InsetLayouts::const_iterator it =
68 context.textclass.insetLayouts().find(from_ascii(name));
69 if (it != context.textclass.insetLayouts().end())
70 layout = &(it->second);
71 parse_text_in_inset(p, os, flags, outer, context, layout);
74 /// parses a paragraph snippet, useful for example for \\emph{...}
75 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
78 Context newcontext(context);
79 // Don't inherit the paragraph-level extra stuff
80 newcontext.par_extra_stuff.clear();
81 parse_text(p, os, flags, outer, newcontext);
82 // Make sure that we don't create invalid .lyx files
83 context.need_layout = newcontext.need_layout;
84 context.need_end_layout = newcontext.need_end_layout;
89 * Thin wrapper around parse_text_snippet() using a string.
91 * We completely ignore \c context.need_layout and \c context.need_end_layout,
92 * because our return value is not used directly (otherwise the stream version
93 * of parse_text_snippet() could be used). That means that the caller needs
94 * to do layout management manually.
95 * This is intended to parse text that does not create any layout changes.
97 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
100 Context newcontext(context);
101 newcontext.need_layout = false;
102 newcontext.need_end_layout = false;
103 newcontext.new_layout_allowed = false;
104 // Avoid warning by Context::~Context()
105 newcontext.par_extra_stuff.clear();
107 parse_text_snippet(p, os, flags, outer, newcontext);
112 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
113 "vpageref", "prettyref", "eqref", 0 };
115 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
116 "vpageref", "formatted", "eqref", 0 };
120 * The starred forms are also known except for "citefullauthor",
121 * "citeyear" and "citeyearpar".
123 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
124 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
125 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
129 * No starred form other than "cite*" known.
131 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
132 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
133 // jurabib commands not (yet) supported by LyX:
135 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
136 // "footciteauthor", "footciteyear", "footciteyearpar",
137 "citefield", "citetitle", 0 };
139 /// LaTeX names for quotes
140 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
141 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
142 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
143 "guilsinglleft", "frq", "guilsinglright", 0};
145 /// the same as known_quotes with .lyx names
146 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
147 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
148 "gld", "grd", "gls", "ers", "fls",
149 "fls", "frs", "frs", 0};
151 /// LaTeX names for font sizes
152 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
153 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
155 /// the same as known_sizes with .lyx names
156 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
157 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
159 /// LaTeX 2.09 names for font families
160 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
162 /// LaTeX names for font families
163 char const * const known_font_families[] = { "rmfamily", "sffamily",
166 /// LaTeX names for font family changing commands
167 char const * const known_text_font_families[] = { "textrm", "textsf",
170 /// The same as known_old_font_families, known_font_families and
171 /// known_text_font_families with .lyx names
172 char const * const known_coded_font_families[] = { "roman", "sans",
175 /// LaTeX 2.09 names for font series
176 char const * const known_old_font_series[] = { "bf", 0};
178 /// LaTeX names for font series
179 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
181 /// LaTeX names for font series changing commands
182 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
184 /// The same as known_old_font_series, known_font_series and
185 /// known_text_font_series with .lyx names
186 char const * const known_coded_font_series[] = { "bold", "medium", 0};
188 /// LaTeX 2.09 names for font shapes
189 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
191 /// LaTeX names for font shapes
192 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
195 /// LaTeX names for font shape changing commands
196 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
199 /// The same as known_old_font_shapes, known_font_shapes and
200 /// known_text_font_shapes with .lyx names
201 char const * const known_coded_font_shapes[] = { "italic", "slanted",
202 "smallcaps", "up", 0};
204 /// Known special characters which need skip_spaces_braces() afterwards
205 char const * const known_special_chars[] = {"ldots", "lyxarrow",
206 "textcompwordmark", "slash", 0};
208 /// the same as known_special_chars with .lyx names
209 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
210 "textcompwordmark{}", "slash{}", 0};
213 * Graphics file extensions known by the dvips driver of the graphics package.
214 * These extensions are used to complete the filename of an included
215 * graphics file if it does not contain an extension.
216 * The order must be the same that latex uses to find a file, because we
217 * will use the first extension that matches.
218 * This is only an approximation for the common cases. If we would want to
219 * do it right in all cases, we would need to know which graphics driver is
220 * used and know the extensions of every driver of the graphics package.
222 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
223 "ps.gz", "eps.Z", "ps.Z", 0};
226 * Graphics file extensions known by the pdftex driver of the graphics package.
227 * \sa known_dvips_graphics_formats
229 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
233 * Known file extensions for TeX files as used by \\include.
235 char const * const known_tex_extensions[] = {"tex", 0};
237 /// spaces known by InsetSpace
238 char const * const known_spaces[] = { " ", "space", ",",
239 "thinspace", "quad", "qquad", "enspace", "enskip",
240 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
241 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
242 "upbracefill", "downbracefill", 0};
244 /// the same as known_spaces with .lyx names
245 char const * const known_coded_spaces[] = { "space{}", "space{}",
246 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
247 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
248 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
249 "upbracefill{}", "downbracefill{}", 0};
251 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
252 /// them in ERT. "LaTeXe" must come before "LaTeX"!
253 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
254 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
255 int const known_phrase_lengths[] = {3, 5, 7, 0};
257 // string to store the float type to be able to determine the type of subfloats
258 string float_type = "";
261 /// splits "x=z, y=b" into a map and an ordered keyword vector
262 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
267 keys.resize(v.size());
268 for (size_t i = 0; i < v.size(); ++i) {
269 size_t const pos = v[i].find('=');
270 string const index = trimSpaceAndEol(v[i].substr(0, pos));
271 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
279 * Split a LaTeX length into value and unit.
280 * The latter can be a real unit like "pt", or a latex length variable
281 * like "\textwidth". The unit may contain additional stuff like glue
282 * lengths, but we don't care, because such lengths are ERT anyway.
283 * \returns true if \p value and \p unit are valid.
285 bool splitLatexLength(string const & len, string & value, string & unit)
289 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
290 //'4,5' is a valid LaTeX length number. Change it to '4.5'
291 string const length = subst(len, ',', '.');
292 if (i == string::npos)
295 if (len[0] == '\\') {
296 // We had something like \textwidth without a factor
302 value = trimSpaceAndEol(string(length, 0, i));
306 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
307 if (contains(len, '\\'))
308 unit = trimSpaceAndEol(string(len, i));
310 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
315 /// A simple function to translate a latex length to something LyX can
316 /// understand. Not perfect, but rather best-effort.
317 bool translate_len(string const & length, string & valstring, string & unit)
319 if (!splitLatexLength(length, valstring, unit))
321 // LyX uses percent values
323 istringstream iss(valstring);
328 string const percentval = oss.str();
330 if (unit.empty() || unit[0] != '\\')
332 string::size_type const i = unit.find(' ');
333 string const endlen = (i == string::npos) ? string() : string(unit, i);
334 if (unit == "\\textwidth") {
335 valstring = percentval;
336 unit = "text%" + endlen;
337 } else if (unit == "\\columnwidth") {
338 valstring = percentval;
339 unit = "col%" + endlen;
340 } else if (unit == "\\paperwidth") {
341 valstring = percentval;
342 unit = "page%" + endlen;
343 } else if (unit == "\\linewidth") {
344 valstring = percentval;
345 unit = "line%" + endlen;
346 } else if (unit == "\\paperheight") {
347 valstring = percentval;
348 unit = "pheight%" + endlen;
349 } else if (unit == "\\textheight") {
350 valstring = percentval;
351 unit = "theight%" + endlen;
359 string translate_len(string const & length)
363 if (translate_len(length, value, unit))
365 // If the input is invalid, return what we have.
373 * Translates a LaTeX length into \p value, \p unit and
374 * \p special parts suitable for a box inset.
375 * The difference from translate_len() is that a box inset knows about
376 * some special "units" that are stored in \p special.
378 void translate_box_len(string const & length, string & value, string & unit, string & special)
380 if (translate_len(length, value, unit)) {
381 if (unit == "\\height" || unit == "\\depth" ||
382 unit == "\\totalheight" || unit == "\\width") {
383 special = unit.substr(1);
384 // The unit is not used, but LyX requires a dummy setting
397 * Find a file with basename \p name in path \p path and an extension
400 string find_file(string const & name, string const & path,
401 char const * const * extensions)
403 for (char const * const * what = extensions; *what; ++what) {
404 string const trial = addExtension(name, *what);
405 if (makeAbsPath(trial, path).exists())
412 void begin_inset(ostream & os, string const & name)
414 os << "\n\\begin_inset " << name;
418 void begin_command_inset(ostream & os, string const & name,
419 string const & latexname)
421 begin_inset(os, "CommandInset ");
422 os << name << "\nLatexCommand " << latexname << '\n';
426 void end_inset(ostream & os)
428 os << "\n\\end_inset\n\n";
432 bool skip_braces(Parser & p)
434 if (p.next_token().cat() != catBegin)
437 if (p.next_token().cat() == catEnd) {
446 /// replace LaTeX commands in \p s from the unicodesymbols file with their
448 docstring convert_unicodesymbols(docstring s)
451 for (size_t i = 0; i < s.size();) {
459 docstring parsed = encodings.fromLaTeXCommand(s,
460 Encodings::TEXT_CMD, rem, &req);
461 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
462 preamble.registerAutomaticallyLoadedPackage(*it);
465 if (s.empty() || s[0] != '\\')
474 /// try to convert \p s to a valid InsetCommand argument
475 string convert_command_inset_arg(string s)
478 // since we don't know the input encoding we can't use from_utf8
479 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
480 // LyX cannot handle newlines in a latex command
481 return subst(s, "\n", " ");
485 void handle_backslash(ostream & os, string const & s)
487 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
489 os << "\n\\backslash\n";
496 void handle_ert(ostream & os, string const & s, Context & context)
498 // We must have a valid layout before outputting the ERT inset.
499 context.check_layout(os);
500 Context newcontext(true, context.textclass);
501 begin_inset(os, "ERT");
502 os << "\nstatus collapsed\n";
503 newcontext.check_layout(os);
504 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
506 os << "\n\\backslash\n";
507 else if (*it == '\n') {
508 newcontext.new_paragraph(os);
509 newcontext.check_layout(os);
513 newcontext.check_end_layout(os);
518 void handle_comment(ostream & os, string const & s, Context & context)
520 // TODO: Handle this better
521 Context newcontext(true, context.textclass);
522 begin_inset(os, "ERT");
523 os << "\nstatus collapsed\n";
524 newcontext.check_layout(os);
525 handle_backslash(os, s);
526 // make sure that our comment is the last thing on the line
527 newcontext.new_paragraph(os);
528 newcontext.check_layout(os);
529 newcontext.check_end_layout(os);
534 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
536 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
539 if (checkModule(name, command))
540 return findLayoutWithoutModule(textclass, name, command);
545 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
547 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
550 if (checkModule(name, command))
551 return findInsetLayoutWithoutModule(textclass, name, command);
556 void eat_whitespace(Parser &, ostream &, Context &, bool);
560 * Skips whitespace and braces.
561 * This should be called after a command has been parsed that is not put into
562 * ERT, and where LyX adds "{}" if needed.
564 void skip_spaces_braces(Parser & p, bool keepws = false)
566 /* The following four examples produce the same typeset output and
567 should be handled by this function:
575 // Unfortunately we need to skip comments, too.
576 // We can't use eat_whitespace since writing them after the {}
577 // results in different output in some cases.
578 bool const skipped_spaces = p.skip_spaces(true);
579 bool const skipped_braces = skip_braces(p);
580 if (keepws && skipped_spaces && !skipped_braces)
581 // put back the space (it is better handled by check_space)
582 p.unskip_spaces(true);
586 void output_command_layout(ostream & os, Parser & p, bool outer,
587 Context & parent_context,
588 Layout const * newlayout)
590 TeXFont const oldFont = parent_context.font;
591 // save the current font size
592 string const size = oldFont.size;
593 // reset the font size to default, because the font size switches
594 // don't affect section headings and the like
595 parent_context.font.size = Context::normalfont.size;
596 // we only need to write the font change if we have an open layout
597 if (!parent_context.atParagraphStart())
598 output_font_change(os, oldFont, parent_context.font);
599 parent_context.check_end_layout(os);
600 Context context(true, parent_context.textclass, newlayout,
601 parent_context.layout, parent_context.font);
602 if (parent_context.deeper_paragraph) {
603 // We are beginning a nested environment after a
604 // deeper paragraph inside the outer list environment.
605 // Therefore we don't need to output a "begin deeper".
606 context.need_end_deeper = true;
608 context.check_deeper(os);
609 context.check_layout(os);
610 unsigned int optargs = 0;
611 while (optargs < context.layout->optargs) {
612 eat_whitespace(p, os, context, false);
613 if (p.next_token().cat() == catEscape ||
614 p.next_token().character() != '[')
616 p.get_token(); // eat '['
617 begin_inset(os, "Argument\n");
618 os << "status collapsed\n\n";
619 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
621 eat_whitespace(p, os, context, false);
624 unsigned int reqargs = 0;
625 while (reqargs < context.layout->reqargs) {
626 eat_whitespace(p, os, context, false);
627 if (p.next_token().cat() != catBegin)
629 p.get_token(); // eat '{'
630 begin_inset(os, "Argument\n");
631 os << "status collapsed\n\n";
632 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
634 eat_whitespace(p, os, context, false);
637 parse_text(p, os, FLAG_ITEM, outer, context);
638 context.check_end_layout(os);
639 if (parent_context.deeper_paragraph) {
640 // We must suppress the "end deeper" because we
641 // suppressed the "begin deeper" above.
642 context.need_end_deeper = false;
644 context.check_end_deeper(os);
645 // We don't need really a new paragraph, but
646 // we must make sure that the next item gets a \begin_layout.
647 parent_context.new_paragraph(os);
648 // Set the font size to the original value. No need to output it here
649 // (Context::begin_layout() will do that if needed)
650 parent_context.font.size = size;
655 * Output a space if necessary.
656 * This function gets called for every whitespace token.
658 * We have three cases here:
659 * 1. A space must be suppressed. Example: The lyxcode case below
660 * 2. A space may be suppressed. Example: Spaces before "\par"
661 * 3. A space must not be suppressed. Example: A space between two words
663 * We currently handle only 1. and 3 and from 2. only the case of
664 * spaces before newlines as a side effect.
666 * 2. could be used to suppress as many spaces as possible. This has two effects:
667 * - Reimporting LyX generated LaTeX files changes almost no whitespace
668 * - Superflous whitespace from non LyX generated LaTeX files is removed.
669 * The drawback is that the logic inside the function becomes
670 * complicated, and that is the reason why it is not implemented.
672 void check_space(Parser & p, ostream & os, Context & context)
674 Token const next = p.next_token();
675 Token const curr = p.curr_token();
676 // A space before a single newline and vice versa must be ignored
677 // LyX emits a newline before \end{lyxcode}.
678 // This newline must be ignored,
679 // otherwise LyX will add an additional protected space.
680 if (next.cat() == catSpace ||
681 next.cat() == catNewline ||
682 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
685 context.check_layout(os);
691 * Parse all arguments of \p command
693 void parse_arguments(string const & command,
694 vector<ArgumentType> const & template_arguments,
695 Parser & p, ostream & os, bool outer, Context & context)
697 string ert = command;
698 size_t no_arguments = template_arguments.size();
699 for (size_t i = 0; i < no_arguments; ++i) {
700 switch (template_arguments[i]) {
703 // This argument contains regular LaTeX
704 handle_ert(os, ert + '{', context);
705 eat_whitespace(p, os, context, false);
706 if (template_arguments[i] == required)
707 parse_text(p, os, FLAG_ITEM, outer, context);
709 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
713 // This argument consists only of a single item.
714 // The presence of '{' or not must be preserved.
716 if (p.next_token().cat() == catBegin)
717 ert += '{' + p.verbatim_item() + '}';
719 ert += p.verbatim_item();
723 // This argument may contain special characters
724 ert += '{' + p.verbatim_item() + '}';
728 // true because we must not eat whitespace
729 // if an optional arg follows we must not strip the
730 // brackets from this one
731 if (i < no_arguments - 1 &&
732 template_arguments[i+1] == optional)
733 ert += p.getFullOpt(true);
735 ert += p.getOpt(true);
739 handle_ert(os, ert, context);
744 * Check whether \p command is a known command. If yes,
745 * handle the command with all arguments.
746 * \return true if the command was parsed, false otherwise.
748 bool parse_command(string const & command, Parser & p, ostream & os,
749 bool outer, Context & context)
751 if (known_commands.find(command) != known_commands.end()) {
752 parse_arguments(command, known_commands[command], p, os,
760 /// Parses a minipage or parbox
761 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
762 unsigned inner_flags, bool outer, Context & parent_context,
763 string const & outer_type, string const & special,
764 string const & inner_type)
768 string hor_pos = "c";
769 // We need to set the height to the LaTeX default of 1\\totalheight
770 // for the case when no height argument is given
771 string height_value = "1";
772 string height_unit = "in";
773 string height_special = "totalheight";
778 string width_special = "none";
779 if (!inner_type.empty() && p.hasOpt()) {
780 if (inner_type != "makebox")
781 position = p.getArg('[', ']');
783 latex_width = p.getArg('[', ']');
784 translate_box_len(latex_width, width_value, width_unit, width_special);
787 if (position != "t" && position != "c" && position != "b") {
788 cerr << "invalid position " << position << " for "
789 << inner_type << endl;
793 if (inner_type != "makebox") {
794 latex_height = p.getArg('[', ']');
795 translate_box_len(latex_height, height_value, height_unit, height_special);
797 hor_pos = p.getArg('[', ']');
800 inner_pos = p.getArg('[', ']');
801 if (inner_pos != "c" && inner_pos != "t" &&
802 inner_pos != "b" && inner_pos != "s") {
803 cerr << "invalid inner_pos "
804 << inner_pos << " for "
805 << inner_type << endl;
806 inner_pos = position;
811 if (inner_type.empty()) {
812 if (special.empty() && outer_type != "framebox")
813 latex_width = "1\\columnwidth";
816 latex_width = p2.getArg('[', ']');
817 string const opt = p2.getArg('[', ']');
820 if (hor_pos != "l" && hor_pos != "c" &&
822 cerr << "invalid hor_pos " << hor_pos
823 << " for " << outer_type << endl;
828 } else if (inner_type != "makebox")
829 latex_width = p.verbatim_item();
830 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
831 // as this is LyX's standard for such cases (except for makebox)
832 // \framebox is more special and handled below
833 if (latex_width.empty() && inner_type != "makebox"
834 && outer_type != "framebox")
835 latex_width = "1\\columnwidth";
837 translate_len(latex_width, width_value, width_unit);
839 bool shadedparbox = false;
840 if (inner_type == "shaded") {
841 eat_whitespace(p, os, parent_context, false);
842 if (outer_type == "parbox") {
844 if (p.next_token().cat() == catBegin)
846 eat_whitespace(p, os, parent_context, false);
852 // If we already read the inner box we have to push the inner env
853 if (!outer_type.empty() && !inner_type.empty() &&
854 (inner_flags & FLAG_END))
855 active_environments.push_back(inner_type);
856 // LyX can't handle length variables
857 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
858 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
859 // Look whether there is some content after the end of the
860 // inner box, but before the end of the outer box.
861 // If yes, we need to output ERT.
863 if (inner_flags & FLAG_END)
864 p.verbatimEnvironment(inner_type);
868 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
869 if ((outer_env && p.next_token().asInput() != "\\end") ||
870 (!outer_env && p.next_token().cat() != catEnd)) {
871 // something is between the end of the inner box and
872 // the end of the outer box, so we need to use ERT.
877 // if only \makebox{content} was used we can set its width to 1\width
878 // because this identic and also identic to \mbox
879 // this doesn't work for \framebox{content}, thus we have to use ERT for this
880 if (latex_width.empty() && inner_type == "makebox") {
883 width_special = "width";
884 } else if (latex_width.empty() && outer_type == "framebox") {
889 if (!outer_type.empty()) {
890 if (outer_flags & FLAG_END)
891 ss << "\\begin{" << outer_type << '}';
893 ss << '\\' << outer_type << '{';
894 if (!special.empty())
898 if (!inner_type.empty()) {
899 if (inner_type != "shaded") {
900 if (inner_flags & FLAG_END)
901 ss << "\\begin{" << inner_type << '}';
903 ss << '\\' << inner_type;
905 if (!position.empty())
906 ss << '[' << position << ']';
907 if (!latex_height.empty())
908 ss << '[' << latex_height << ']';
909 if (!inner_pos.empty())
910 ss << '[' << inner_pos << ']';
911 ss << '{' << latex_width << '}';
912 if (!(inner_flags & FLAG_END))
915 if (inner_type == "shaded")
916 ss << "\\begin{shaded}";
917 handle_ert(os, ss.str(), parent_context);
918 if (!inner_type.empty()) {
919 parse_text(p, os, inner_flags, outer, parent_context);
920 if (inner_flags & FLAG_END)
921 handle_ert(os, "\\end{" + inner_type + '}',
924 handle_ert(os, "}", parent_context);
926 if (!outer_type.empty()) {
927 // If we already read the inner box we have to pop
929 if (!inner_type.empty() && (inner_flags & FLAG_END))
930 active_environments.pop_back();
932 // Ensure that the end of the outer box is parsed correctly:
933 // The opening brace has been eaten by parse_outer_box()
934 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
935 outer_flags &= ~FLAG_ITEM;
936 outer_flags |= FLAG_BRACE_LAST;
938 parse_text(p, os, outer_flags, outer, parent_context);
939 if (outer_flags & FLAG_END)
940 handle_ert(os, "\\end{" + outer_type + '}',
942 else if (inner_type.empty() && outer_type == "framebox")
943 // in this case it is already closed later
946 handle_ert(os, "}", parent_context);
949 // LyX does not like empty positions, so we have
950 // to set them to the LaTeX default values here.
951 if (position.empty())
953 if (inner_pos.empty())
954 inner_pos = position;
955 parent_context.check_layout(os);
956 begin_inset(os, "Box ");
957 if (outer_type == "framed")
959 else if (outer_type == "framebox")
961 else if (outer_type == "shadowbox")
963 else if ((outer_type == "shaded" && inner_type.empty()) ||
964 (outer_type == "minipage" && inner_type == "shaded") ||
965 (outer_type == "parbox" && inner_type == "shaded")) {
967 preamble.registerAutomaticallyLoadedPackage("color");
968 } else if (outer_type == "doublebox")
970 else if (outer_type.empty())
973 os << outer_type << '\n';
974 os << "position \"" << position << "\"\n";
975 os << "hor_pos \"" << hor_pos << "\"\n";
976 os << "has_inner_box " << !inner_type.empty() << "\n";
977 os << "inner_pos \"" << inner_pos << "\"\n";
978 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
980 os << "use_makebox " << (inner_type == "makebox") << '\n';
981 os << "width \"" << width_value << width_unit << "\"\n";
982 os << "special \"" << width_special << "\"\n";
983 os << "height \"" << height_value << height_unit << "\"\n";
984 os << "height_special \"" << height_special << "\"\n";
985 os << "status open\n\n";
987 // Unfortunately we can't use parse_text_in_inset:
988 // InsetBox::forcePlainLayout() is hard coded and does not
989 // use the inset layout. Apart from that do we call parse_text
990 // up to two times, but need only one check_end_layout.
991 bool const forcePlainLayout =
992 (!inner_type.empty() || inner_type == "makebox") &&
993 outer_type != "shaded" && outer_type != "framed";
994 Context context(true, parent_context.textclass);
995 if (forcePlainLayout)
996 context.layout = &context.textclass.plainLayout();
998 context.font = parent_context.font;
1000 // If we have no inner box the contents will be read with the outer box
1001 if (!inner_type.empty())
1002 parse_text(p, os, inner_flags, outer, context);
1004 // Ensure that the end of the outer box is parsed correctly:
1005 // The opening brace has been eaten by parse_outer_box()
1006 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1007 outer_flags &= ~FLAG_ITEM;
1008 outer_flags |= FLAG_BRACE_LAST;
1011 // Find end of outer box, output contents if inner_type is
1012 // empty and output possible comments
1013 if (!outer_type.empty()) {
1014 // If we already read the inner box we have to pop
1016 if (!inner_type.empty() && (inner_flags & FLAG_END))
1017 active_environments.pop_back();
1018 // This does not output anything but comments if
1019 // inner_type is not empty (see use_ert)
1020 parse_text(p, os, outer_flags, outer, context);
1023 context.check_end_layout(os);
1025 #ifdef PRESERVE_LAYOUT
1026 // LyX puts a % after the end of the minipage
1027 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1029 //handle_comment(os, "%dummy", parent_context);
1032 parent_context.new_paragraph(os);
1034 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1035 //handle_comment(os, "%dummy", parent_context);
1038 // We add a protected space if something real follows
1039 if (p.good() && p.next_token().cat() != catComment) {
1040 begin_inset(os, "space ~\n");
1049 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1050 Context & parent_context, string const & outer_type,
1051 string const & special)
1053 eat_whitespace(p, os, parent_context, false);
1054 if (flags & FLAG_ITEM) {
1056 if (p.next_token().cat() == catBegin)
1059 cerr << "Warning: Ignoring missing '{' after \\"
1060 << outer_type << '.' << endl;
1061 eat_whitespace(p, os, parent_context, false);
1064 unsigned int inner_flags = 0;
1066 if (outer_type == "minipage" || outer_type == "parbox") {
1067 p.skip_spaces(true);
1068 while (p.hasOpt()) {
1070 p.skip_spaces(true);
1073 p.skip_spaces(true);
1074 if (outer_type == "parbox") {
1076 if (p.next_token().cat() == catBegin)
1078 p.skip_spaces(true);
1081 if (outer_type == "shaded") {
1082 // These boxes never have an inner box
1084 } else if (p.next_token().asInput() == "\\parbox") {
1085 inner = p.get_token().cs();
1086 inner_flags = FLAG_ITEM;
1087 } else if (p.next_token().asInput() == "\\begin") {
1088 // Is this a minipage or shaded box?
1091 inner = p.getArg('{', '}');
1093 if (inner == "minipage" || inner == "shaded")
1094 inner_flags = FLAG_END;
1099 if (inner_flags == FLAG_END) {
1100 if (inner != "shaded")
1104 eat_whitespace(p, os, parent_context, false);
1106 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1107 outer_type, special, inner);
1109 if (inner_flags == FLAG_ITEM) {
1111 eat_whitespace(p, os, parent_context, false);
1113 parse_box(p, os, flags, inner_flags, outer, parent_context,
1114 outer_type, special, inner);
1119 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1121 parent_context.check_layout(os);
1122 begin_inset(os, "listings\n");
1123 os << "inline false\n"
1124 << "status collapsed\n";
1125 Context context(true, parent_context.textclass);
1126 context.layout = &parent_context.textclass.plainLayout();
1127 context.check_layout(os);
1128 string const s = p.verbatimEnvironment("lstlisting");
1129 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1131 os << "\n\\backslash\n";
1132 else if (*it == '\n') {
1133 // avoid adding an empty paragraph at the end
1135 context.new_paragraph(os);
1136 context.check_layout(os);
1141 context.check_end_layout(os);
1146 /// parse an unknown environment
1147 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1148 unsigned flags, bool outer,
1149 Context & parent_context)
1151 if (name == "tabbing")
1152 // We need to remember that we have to handle '\=' specially
1153 flags |= FLAG_TABBING;
1155 // We need to translate font changes and paragraphs inside the
1156 // environment to ERT if we have a non standard font.
1157 // Otherwise things like
1158 // \large\begin{foo}\huge bar\end{foo}
1160 bool const specialfont =
1161 (parent_context.font != parent_context.normalfont);
1162 bool const new_layout_allowed = parent_context.new_layout_allowed;
1164 parent_context.new_layout_allowed = false;
1165 handle_ert(os, "\\begin{" + name + "}", parent_context);
1166 parse_text_snippet(p, os, flags, outer, parent_context);
1167 handle_ert(os, "\\end{" + name + "}", parent_context);
1169 parent_context.new_layout_allowed = new_layout_allowed;
1173 void parse_environment(Parser & p, ostream & os, bool outer,
1174 string & last_env, bool & title_layout_found,
1175 Context & parent_context)
1177 Layout const * newlayout;
1178 InsetLayout const * newinsetlayout = 0;
1179 string const name = p.getArg('{', '}');
1180 const bool is_starred = suffixIs(name, '*');
1181 string const unstarred_name = rtrim(name, "*");
1182 active_environments.push_back(name);
1184 if (is_math_env(name)) {
1185 parent_context.check_layout(os);
1186 begin_inset(os, "Formula ");
1187 os << "\\begin{" << name << "}";
1188 parse_math(p, os, FLAG_END, MATH_MODE);
1189 os << "\\end{" << name << "}";
1191 if (is_display_math_env(name)) {
1192 // Prevent the conversion of a line break to a space
1193 // (bug 7668). This does not change the output, but
1194 // looks ugly in LyX.
1195 eat_whitespace(p, os, parent_context, false);
1199 else if (unstarred_name == "tabular" || name == "longtable") {
1200 eat_whitespace(p, os, parent_context, false);
1201 string width = "0pt";
1202 if (name == "tabular*") {
1203 width = lyx::translate_len(p.getArg('{', '}'));
1204 eat_whitespace(p, os, parent_context, false);
1206 parent_context.check_layout(os);
1207 begin_inset(os, "Tabular ");
1208 handle_tabular(p, os, name, width, parent_context);
1213 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1214 eat_whitespace(p, os, parent_context, false);
1215 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1216 eat_whitespace(p, os, parent_context, false);
1217 parent_context.check_layout(os);
1218 begin_inset(os, "Float " + unstarred_name + "\n");
1219 // store the float type for subfloats
1220 // subfloats only work with figures and tables
1221 if (unstarred_name == "figure")
1222 float_type = unstarred_name;
1223 else if (unstarred_name == "table")
1224 float_type = unstarred_name;
1228 os << "placement " << opt << '\n';
1229 if (contains(opt, "H"))
1230 preamble.registerAutomaticallyLoadedPackage("float");
1232 Floating const & fl = parent_context.textclass.floats()
1233 .getType(unstarred_name);
1234 if (!fl.floattype().empty() && fl.usesFloatPkg())
1235 preamble.registerAutomaticallyLoadedPackage("float");
1238 os << "wide " << convert<string>(is_starred)
1239 << "\nsideways false"
1240 << "\nstatus open\n\n";
1241 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1243 // We don't need really a new paragraph, but
1244 // we must make sure that the next item gets a \begin_layout.
1245 parent_context.new_paragraph(os);
1247 // the float is parsed thus delete the type
1251 else if (unstarred_name == "sidewaysfigure"
1252 || unstarred_name == "sidewaystable") {
1253 eat_whitespace(p, os, parent_context, false);
1254 parent_context.check_layout(os);
1255 if (unstarred_name == "sidewaysfigure")
1256 begin_inset(os, "Float figure\n");
1258 begin_inset(os, "Float table\n");
1259 os << "wide " << convert<string>(is_starred)
1260 << "\nsideways true"
1261 << "\nstatus open\n\n";
1262 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1264 // We don't need really a new paragraph, but
1265 // we must make sure that the next item gets a \begin_layout.
1266 parent_context.new_paragraph(os);
1268 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1271 else if (name == "wrapfigure" || name == "wraptable") {
1272 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1273 eat_whitespace(p, os, parent_context, false);
1274 parent_context.check_layout(os);
1277 string overhang = "0col%";
1280 lines = p.getArg('[', ']');
1281 string const placement = p.getArg('{', '}');
1283 overhang = p.getArg('[', ']');
1284 string const width = p.getArg('{', '}');
1286 if (name == "wrapfigure")
1287 begin_inset(os, "Wrap figure\n");
1289 begin_inset(os, "Wrap table\n");
1290 os << "lines " << lines
1291 << "\nplacement " << placement
1292 << "\noverhang " << lyx::translate_len(overhang)
1293 << "\nwidth " << lyx::translate_len(width)
1294 << "\nstatus open\n\n";
1295 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1297 // We don't need really a new paragraph, but
1298 // we must make sure that the next item gets a \begin_layout.
1299 parent_context.new_paragraph(os);
1301 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1304 else if (name == "minipage") {
1305 eat_whitespace(p, os, parent_context, false);
1306 // Test whether this is an outer box of a shaded box
1308 // swallow arguments
1309 while (p.hasOpt()) {
1311 p.skip_spaces(true);
1314 p.skip_spaces(true);
1315 Token t = p.get_token();
1316 bool shaded = false;
1317 if (t.asInput() == "\\begin") {
1318 p.skip_spaces(true);
1319 if (p.getArg('{', '}') == "shaded")
1324 parse_outer_box(p, os, FLAG_END, outer,
1325 parent_context, name, "shaded");
1327 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1332 else if (name == "comment") {
1333 eat_whitespace(p, os, parent_context, false);
1334 parent_context.check_layout(os);
1335 begin_inset(os, "Note Comment\n");
1336 os << "status open\n";
1337 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1340 skip_braces(p); // eat {} that might by set by LyX behind comments
1341 preamble.registerAutomaticallyLoadedPackage("verbatim");
1344 else if (name == "lyxgreyedout") {
1345 eat_whitespace(p, os, parent_context, false);
1346 parent_context.check_layout(os);
1347 begin_inset(os, "Note Greyedout\n");
1348 os << "status open\n";
1349 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1352 if (!preamble.notefontcolor().empty())
1353 preamble.registerAutomaticallyLoadedPackage("color");
1356 else if (name == "framed" || name == "shaded") {
1357 eat_whitespace(p, os, parent_context, false);
1358 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1362 else if (name == "lstlisting") {
1363 eat_whitespace(p, os, parent_context, false);
1364 // FIXME handle listings with parameters
1365 // If this is added, don't forgot to handle the
1366 // automatic color package loading
1368 parse_unknown_environment(p, name, os, FLAG_END,
1369 outer, parent_context);
1371 parse_listings(p, os, parent_context);
1375 else if (!parent_context.new_layout_allowed)
1376 parse_unknown_environment(p, name, os, FLAG_END, outer,
1379 // Alignment and spacing settings
1380 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1381 // therefore are totally broken!
1382 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1383 // they are commands not environments. They are furthermore switches that
1384 // can be ended by another switches, but also by commands like \footnote or
1385 // \parbox. So the only safe way is to leave them untouched.
1386 else if (name == "center" || name == "centering" ||
1387 name == "flushleft" || name == "flushright" ||
1388 name == "singlespace" || name == "onehalfspace" ||
1389 name == "doublespace" || name == "spacing") {
1390 eat_whitespace(p, os, parent_context, false);
1391 // We must begin a new paragraph if not already done
1392 if (! parent_context.atParagraphStart()) {
1393 parent_context.check_end_layout(os);
1394 parent_context.new_paragraph(os);
1396 if (name == "flushleft")
1397 parent_context.add_extra_stuff("\\align left\n");
1398 else if (name == "flushright")
1399 parent_context.add_extra_stuff("\\align right\n");
1400 else if (name == "center" || name == "centering")
1401 parent_context.add_extra_stuff("\\align center\n");
1402 else if (name == "singlespace")
1403 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1404 else if (name == "onehalfspace") {
1405 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1406 preamble.registerAutomaticallyLoadedPackage("setspace");
1407 } else if (name == "doublespace") {
1408 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1409 preamble.registerAutomaticallyLoadedPackage("setspace");
1410 } else if (name == "spacing") {
1411 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1412 preamble.registerAutomaticallyLoadedPackage("setspace");
1414 parse_text(p, os, FLAG_END, outer, parent_context);
1415 // Just in case the environment is empty
1416 parent_context.extra_stuff.erase();
1417 // We must begin a new paragraph to reset the alignment
1418 parent_context.new_paragraph(os);
1422 // The single '=' is meant here.
1423 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1424 eat_whitespace(p, os, parent_context, false);
1425 Context context(true, parent_context.textclass, newlayout,
1426 parent_context.layout, parent_context.font);
1427 if (parent_context.deeper_paragraph) {
1428 // We are beginning a nested environment after a
1429 // deeper paragraph inside the outer list environment.
1430 // Therefore we don't need to output a "begin deeper".
1431 context.need_end_deeper = true;
1433 parent_context.check_end_layout(os);
1434 if (last_env == name) {
1435 // we need to output a separator since LyX would export
1436 // the two environments as one otherwise (bug 5716)
1437 docstring const sep = from_ascii("--Separator--");
1438 TeX2LyXDocClass const & textclass(parent_context.textclass);
1439 if (textclass.hasLayout(sep)) {
1440 Context newcontext(parent_context);
1441 newcontext.layout = &(textclass[sep]);
1442 newcontext.check_layout(os);
1443 newcontext.check_end_layout(os);
1445 parent_context.check_layout(os);
1446 begin_inset(os, "Note Note\n");
1447 os << "status closed\n";
1448 Context newcontext(true, textclass,
1449 &(textclass.defaultLayout()));
1450 newcontext.check_layout(os);
1451 newcontext.check_end_layout(os);
1453 parent_context.check_end_layout(os);
1456 switch (context.layout->latextype) {
1457 case LATEX_LIST_ENVIRONMENT:
1458 context.add_par_extra_stuff("\\labelwidthstring "
1459 + p.verbatim_item() + '\n');
1462 case LATEX_BIB_ENVIRONMENT:
1463 p.verbatim_item(); // swallow next arg
1469 context.check_deeper(os);
1470 // handle known optional and required arguments
1471 // layouts require all optional arguments before the required ones
1472 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1473 // It is impossible to place anything after the environment name,
1474 // but before the first \\item.
1475 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1476 bool need_layout = true;
1477 unsigned int optargs = 0;
1478 while (optargs < context.layout->optargs) {
1479 eat_whitespace(p, os, context, false);
1480 if (p.next_token().cat() == catEscape ||
1481 p.next_token().character() != '[')
1483 p.get_token(); // eat '['
1485 context.check_layout(os);
1486 need_layout = false;
1488 begin_inset(os, "Argument\n");
1489 os << "status collapsed\n\n";
1490 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1492 eat_whitespace(p, os, context, false);
1495 unsigned int reqargs = 0;
1496 while (reqargs < context.layout->reqargs) {
1497 eat_whitespace(p, os, context, false);
1498 if (p.next_token().cat() != catBegin)
1500 p.get_token(); // eat '{'
1502 context.check_layout(os);
1503 need_layout = false;
1505 begin_inset(os, "Argument\n");
1506 os << "status collapsed\n\n";
1507 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1509 eat_whitespace(p, os, context, false);
1513 parse_text(p, os, FLAG_END, outer, context);
1514 context.check_end_layout(os);
1515 if (parent_context.deeper_paragraph) {
1516 // We must suppress the "end deeper" because we
1517 // suppressed the "begin deeper" above.
1518 context.need_end_deeper = false;
1520 context.check_end_deeper(os);
1521 parent_context.new_paragraph(os);
1523 if (!title_layout_found)
1524 title_layout_found = newlayout->intitle;
1525 set<string> const & req = newlayout->requires();
1526 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
1527 preamble.registerAutomaticallyLoadedPackage(*it);
1530 // The single '=' is meant here.
1531 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1532 eat_whitespace(p, os, parent_context, false);
1533 parent_context.check_layout(os);
1534 begin_inset(os, "Flex ");
1535 os << to_utf8(newinsetlayout->name()) << '\n'
1536 << "status collapsed\n";
1537 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1541 else if (name == "appendix") {
1542 // This is no good latex style, but it works and is used in some documents...
1543 eat_whitespace(p, os, parent_context, false);
1544 parent_context.check_end_layout(os);
1545 Context context(true, parent_context.textclass, parent_context.layout,
1546 parent_context.layout, parent_context.font);
1547 context.check_layout(os);
1548 os << "\\start_of_appendix\n";
1549 parse_text(p, os, FLAG_END, outer, context);
1550 context.check_end_layout(os);
1554 else if (known_environments.find(name) != known_environments.end()) {
1555 vector<ArgumentType> arguments = known_environments[name];
1556 // The last "argument" denotes wether we may translate the
1557 // environment contents to LyX
1558 // The default required if no argument is given makes us
1559 // compatible with the reLyXre environment.
1560 ArgumentType contents = arguments.empty() ?
1563 if (!arguments.empty())
1564 arguments.pop_back();
1565 // See comment in parse_unknown_environment()
1566 bool const specialfont =
1567 (parent_context.font != parent_context.normalfont);
1568 bool const new_layout_allowed =
1569 parent_context.new_layout_allowed;
1571 parent_context.new_layout_allowed = false;
1572 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1573 outer, parent_context);
1574 if (contents == verbatim)
1575 handle_ert(os, p.verbatimEnvironment(name),
1578 parse_text_snippet(p, os, FLAG_END, outer,
1580 handle_ert(os, "\\end{" + name + "}", parent_context);
1582 parent_context.new_layout_allowed = new_layout_allowed;
1586 parse_unknown_environment(p, name, os, FLAG_END, outer,
1590 active_environments.pop_back();
1594 /// parses a comment and outputs it to \p os.
1595 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1597 LASSERT(t.cat() == catComment, return);
1598 if (!t.cs().empty()) {
1599 context.check_layout(os);
1600 handle_comment(os, '%' + t.cs(), context);
1601 if (p.next_token().cat() == catNewline) {
1602 // A newline after a comment line starts a new
1604 if (context.new_layout_allowed) {
1605 if(!context.atParagraphStart())
1606 // Only start a new paragraph if not already
1607 // done (we might get called recursively)
1608 context.new_paragraph(os);
1610 handle_ert(os, "\n", context);
1611 eat_whitespace(p, os, context, true);
1614 // "%\n" combination
1621 * Reads spaces and comments until the first non-space, non-comment token.
1622 * New paragraphs (double newlines or \\par) are handled like simple spaces
1623 * if \p eatParagraph is true.
1624 * Spaces are skipped, but comments are written to \p os.
1626 void eat_whitespace(Parser & p, ostream & os, Context & context,
1630 Token const & t = p.get_token();
1631 if (t.cat() == catComment)
1632 parse_comment(p, os, t, context);
1633 else if ((! eatParagraph && p.isParagraph()) ||
1634 (t.cat() != catSpace && t.cat() != catNewline)) {
1643 * Set a font attribute, parse text and reset the font attribute.
1644 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1645 * \param currentvalue Current value of the attribute. Is set to the new
1646 * value during parsing.
1647 * \param newvalue New value of the attribute
1649 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1650 Context & context, string const & attribute,
1651 string & currentvalue, string const & newvalue)
1653 context.check_layout(os);
1654 string const oldvalue = currentvalue;
1655 currentvalue = newvalue;
1656 os << '\n' << attribute << ' ' << newvalue << "\n";
1657 parse_text_snippet(p, os, flags, outer, context);
1658 context.check_layout(os);
1659 os << '\n' << attribute << ' ' << oldvalue << "\n";
1660 currentvalue = oldvalue;
1664 /// get the arguments of a natbib or jurabib citation command
1665 void get_cite_arguments(Parser & p, bool natbibOrder,
1666 string & before, string & after)
1668 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1670 // text before the citation
1672 // text after the citation
1673 after = p.getFullOpt();
1675 if (!after.empty()) {
1676 before = p.getFullOpt();
1677 if (natbibOrder && !before.empty())
1678 swap(before, after);
1683 /// Convert filenames with TeX macros and/or quotes to something LyX
1685 string const normalize_filename(string const & name)
1687 Parser p(trim(name, "\""));
1690 Token const & t = p.get_token();
1691 if (t.cat() != catEscape)
1693 else if (t.cs() == "lyxdot") {
1694 // This is used by LyX for simple dots in relative
1698 } else if (t.cs() == "space") {
1708 /// Convert \p name from TeX convention (relative to master file) to LyX
1709 /// convention (relative to .lyx file) if it is relative
1710 void fix_relative_filename(string & name)
1712 if (FileName::isAbsolute(name))
1715 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1716 from_utf8(getParentFilePath())));
1720 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1721 void parse_noweb(Parser & p, ostream & os, Context & context)
1723 // assemble the rest of the keyword
1727 Token const & t = p.get_token();
1728 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1731 scrap = (p.good() && p.next_token().asInput() == "=");
1733 name += p.get_token().asInput();
1736 name += t.asInput();
1739 if (!scrap || !context.new_layout_allowed ||
1740 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1741 cerr << "Warning: Could not interpret '" << name
1742 << "'. Ignoring it." << endl;
1746 // We use new_paragraph instead of check_end_layout because the stuff
1747 // following the noweb chunk needs to start with a \begin_layout.
1748 // This may create a new paragraph even if there was none in the
1749 // noweb file, but the alternative is an invalid LyX file. Since
1750 // noweb code chunks are implemented with a layout style in LyX they
1751 // always must be in an own paragraph.
1752 context.new_paragraph(os);
1753 Context newcontext(true, context.textclass,
1754 &context.textclass[from_ascii("Scrap")]);
1755 newcontext.check_layout(os);
1758 Token const & t = p.get_token();
1759 // We abuse the parser a bit, because this is no TeX syntax
1761 if (t.cat() == catEscape)
1762 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1765 Context tmp(false, context.textclass,
1766 &context.textclass[from_ascii("Scrap")]);
1767 tmp.need_end_layout = true;
1768 tmp.check_layout(oss);
1769 os << subst(t.asInput(), "\n", oss.str());
1771 // The scrap chunk is ended by an @ at the beginning of a line.
1772 // After the @ the line may contain a comment and/or
1773 // whitespace, but nothing else.
1774 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1775 (p.next_token().cat() == catSpace ||
1776 p.next_token().cat() == catNewline ||
1777 p.next_token().cat() == catComment)) {
1778 while (p.good() && p.next_token().cat() == catSpace)
1779 os << p.get_token().asInput();
1780 if (p.next_token().cat() == catComment)
1781 // The comment includes a final '\n'
1782 os << p.get_token().asInput();
1784 if (p.next_token().cat() == catNewline)
1791 newcontext.check_end_layout(os);
1795 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1796 bool is_macro(Parser & p)
1798 Token first = p.curr_token();
1799 if (first.cat() != catEscape || !p.good())
1801 if (first.cs() == "def")
1803 if (first.cs() != "global" && first.cs() != "long")
1805 Token second = p.get_token();
1807 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1808 second.cat() == catNewline || second.cat() == catComment)) {
1809 second = p.get_token();
1812 bool secondvalid = second.cat() == catEscape;
1814 bool thirdvalid = false;
1815 if (p.good() && first.cs() == "global" && secondvalid &&
1816 second.cs() == "long") {
1817 third = p.get_token();
1819 while (p.good() && !p.isParagraph() &&
1820 (third.cat() == catSpace ||
1821 third.cat() == catNewline ||
1822 third.cat() == catComment)) {
1823 third = p.get_token();
1826 thirdvalid = third.cat() == catEscape;
1828 for (int i = 0; i < pos; ++i)
1833 return (first.cs() == "global" || first.cs() == "long") &&
1834 second.cs() == "def";
1835 return first.cs() == "global" && second.cs() == "long" &&
1836 third.cs() == "def";
1840 /// Parse a macro definition (assumes that is_macro() returned true)
1841 void parse_macro(Parser & p, ostream & os, Context & context)
1843 context.check_layout(os);
1844 Token first = p.curr_token();
1847 string command = first.asInput();
1848 if (first.cs() != "def") {
1850 eat_whitespace(p, os, context, false);
1851 second = p.curr_token();
1852 command += second.asInput();
1853 if (second.cs() != "def") {
1855 eat_whitespace(p, os, context, false);
1856 third = p.curr_token();
1857 command += third.asInput();
1860 eat_whitespace(p, os, context, false);
1861 string const name = p.get_token().cs();
1862 eat_whitespace(p, os, context, false);
1868 while (p.next_token().cat() != catBegin) {
1869 if (p.next_token().cat() == catParameter) {
1874 // followed by number?
1875 if (p.next_token().cat() == catOther) {
1876 char c = p.getChar();
1878 // number = current arity + 1?
1879 if (c == arity + '0' + 1)
1884 paramtext += p.get_token().cs();
1886 paramtext += p.get_token().cs();
1891 // only output simple (i.e. compatible) macro as FormulaMacros
1892 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1894 context.check_layout(os);
1895 begin_inset(os, "FormulaMacro");
1896 os << "\n\\def" << ert;
1899 handle_ert(os, command + ert, context);
1902 } // anonymous namespace
1905 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1908 Layout const * newlayout = 0;
1909 InsetLayout const * newinsetlayout = 0;
1910 char const * const * where = 0;
1911 // Store the latest bibliographystyle and nocite{*} option
1912 // (needed for bibtex inset)
1914 string bibliographystyle;
1915 bool const use_natbib = preamble.isPackageUsed("natbib");
1916 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1918 bool title_layout_found = false;
1920 Token const & t = p.get_token();
1923 debugToken(cerr, t, flags);
1926 if (flags & FLAG_ITEM) {
1927 if (t.cat() == catSpace)
1930 flags &= ~FLAG_ITEM;
1931 if (t.cat() == catBegin) {
1932 // skip the brace and collect everything to the next matching
1934 flags |= FLAG_BRACE_LAST;
1938 // handle only this single token, leave the loop if done
1939 flags |= FLAG_LEAVE;
1942 if (t.cat() != catEscape && t.character() == ']' &&
1943 (flags & FLAG_BRACK_LAST))
1945 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1948 // If there is anything between \end{env} and \begin{env} we
1949 // don't need to output a separator.
1950 if (t.cat() != catSpace && t.cat() != catNewline &&
1951 t.asInput() != "\\begin")
1957 if (t.cat() == catMath) {
1958 // we are inside some text mode thingy, so opening new math is allowed
1959 context.check_layout(os);
1960 begin_inset(os, "Formula ");
1961 Token const & n = p.get_token();
1962 bool const display(n.cat() == catMath && outer);
1964 // TeX's $$...$$ syntax for displayed math
1966 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1968 p.get_token(); // skip the second '$' token
1970 // simple $...$ stuff
1973 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1978 // Prevent the conversion of a line break to a
1979 // space (bug 7668). This does not change the
1980 // output, but looks ugly in LyX.
1981 eat_whitespace(p, os, context, false);
1985 else if (t.cat() == catSuper || t.cat() == catSub)
1986 cerr << "catcode " << t << " illegal in text mode\n";
1988 // Basic support for english quotes. This should be
1989 // extended to other quotes, but is not so easy (a
1990 // left english quote is the same as a right german
1992 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1993 context.check_layout(os);
1994 begin_inset(os, "Quotes ");
2000 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2001 context.check_layout(os);
2002 begin_inset(os, "Quotes ");
2009 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2010 context.check_layout(os);
2011 begin_inset(os, "Quotes ");
2018 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2019 context.check_layout(os);
2020 begin_inset(os, "Quotes ");
2027 else if (t.asInput() == "<"
2028 && p.next_token().asInput() == "<" && noweb_mode) {
2030 parse_noweb(p, os, context);
2033 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2034 check_space(p, os, context);
2036 else if (t.character() == '[' && noweb_mode &&
2037 p.next_token().character() == '[') {
2038 // These can contain underscores
2040 string const s = p.getFullOpt() + ']';
2041 if (p.next_token().character() == ']')
2044 cerr << "Warning: Inserting missing ']' in '"
2045 << s << "'." << endl;
2046 handle_ert(os, s, context);
2049 else if (t.cat() == catLetter) {
2050 context.check_layout(os);
2051 // Workaround for bug 4752.
2052 // FIXME: This whole code block needs to be removed
2053 // when the bug is fixed and tex2lyx produces
2054 // the updated file format.
2055 // The replacement algorithm in LyX is so stupid that
2056 // it even translates a phrase if it is part of a word.
2057 bool handled = false;
2058 for (int const * l = known_phrase_lengths; *l; ++l) {
2059 string phrase = t.cs();
2060 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2061 phrase += p.get_token().cs();
2062 if (is_known(phrase, known_coded_phrases)) {
2063 handle_ert(os, phrase, context);
2067 for (size_t i = 1; i < phrase.length(); ++i)
2075 else if (t.cat() == catOther ||
2076 t.cat() == catAlign ||
2077 t.cat() == catParameter) {
2078 // This translates "&" to "\\&" which may be wrong...
2079 context.check_layout(os);
2083 else if (p.isParagraph()) {
2084 if (context.new_layout_allowed)
2085 context.new_paragraph(os);
2087 handle_ert(os, "\\par ", context);
2088 eat_whitespace(p, os, context, true);
2091 else if (t.cat() == catActive) {
2092 context.check_layout(os);
2093 if (t.character() == '~') {
2094 if (context.layout->free_spacing)
2097 begin_inset(os, "space ~\n");
2104 else if (t.cat() == catBegin) {
2105 Token const next = p.next_token();
2106 Token const end = p.next_next_token();
2107 if (next.cat() == catEnd) {
2109 Token const prev = p.prev_token();
2111 if (p.next_token().character() == '`' ||
2112 (prev.character() == '-' &&
2113 p.next_token().character() == '-'))
2114 ; // ignore it in {}`` or -{}-
2116 handle_ert(os, "{}", context);
2117 } else if (next.cat() == catEscape &&
2118 is_known(next.cs(), known_quotes) &&
2119 end.cat() == catEnd) {
2120 // Something like {\textquoteright} (e.g.
2121 // from writer2latex). LyX writes
2122 // \textquoteright{}, so we may skip the
2123 // braces here for better readability.
2124 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2127 context.check_layout(os);
2128 // special handling of font attribute changes
2129 Token const prev = p.prev_token();
2130 TeXFont const oldFont = context.font;
2131 if (next.character() == '[' ||
2132 next.character() == ']' ||
2133 next.character() == '*') {
2135 if (p.next_token().cat() == catEnd) {
2140 handle_ert(os, "{", context);
2141 parse_text_snippet(p, os,
2144 handle_ert(os, "}", context);
2146 } else if (! context.new_layout_allowed) {
2147 handle_ert(os, "{", context);
2148 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2150 handle_ert(os, "}", context);
2151 } else if (is_known(next.cs(), known_sizes)) {
2152 // next will change the size, so we must
2154 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2156 if (!context.atParagraphStart())
2158 << context.font.size << "\n";
2159 } else if (is_known(next.cs(), known_font_families)) {
2160 // next will change the font family, so we
2161 // must reset it here
2162 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2164 if (!context.atParagraphStart())
2166 << context.font.family << "\n";
2167 } else if (is_known(next.cs(), known_font_series)) {
2168 // next will change the font series, so we
2169 // must reset it here
2170 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2172 if (!context.atParagraphStart())
2174 << context.font.series << "\n";
2175 } else if (is_known(next.cs(), known_font_shapes)) {
2176 // next will change the font shape, so we
2177 // must reset it here
2178 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2180 if (!context.atParagraphStart())
2182 << context.font.shape << "\n";
2183 } else if (is_known(next.cs(), known_old_font_families) ||
2184 is_known(next.cs(), known_old_font_series) ||
2185 is_known(next.cs(), known_old_font_shapes)) {
2186 // next will change the font family, series
2187 // and shape, so we must reset it here
2188 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2190 if (!context.atParagraphStart())
2192 << context.font.family
2194 << context.font.series
2196 << context.font.shape << "\n";
2198 handle_ert(os, "{", context);
2199 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2201 handle_ert(os, "}", context);
2206 else if (t.cat() == catEnd) {
2207 if (flags & FLAG_BRACE_LAST) {
2210 cerr << "stray '}' in text\n";
2211 handle_ert(os, "}", context);
2214 else if (t.cat() == catComment)
2215 parse_comment(p, os, t, context);
2218 // control sequences
2221 else if (t.cs() == "(") {
2222 context.check_layout(os);
2223 begin_inset(os, "Formula");
2225 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2230 else if (t.cs() == "[") {
2231 context.check_layout(os);
2232 begin_inset(os, "Formula");
2234 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2237 // Prevent the conversion of a line break to a space
2238 // (bug 7668). This does not change the output, but
2239 // looks ugly in LyX.
2240 eat_whitespace(p, os, context, false);
2243 else if (t.cs() == "begin")
2244 parse_environment(p, os, outer, last_env,
2245 title_layout_found, context);
2247 else if (t.cs() == "end") {
2248 if (flags & FLAG_END) {
2249 // eat environment name
2250 string const name = p.getArg('{', '}');
2251 if (name != active_environment())
2252 cerr << "\\end{" + name + "} does not match \\begin{"
2253 + active_environment() + "}\n";
2256 p.error("found 'end' unexpectedly");
2259 else if (t.cs() == "item") {
2261 bool const optarg = p.hasOpt();
2263 // FIXME: This swallows comments, but we cannot use
2264 // eat_whitespace() since we must not output
2265 // anything before the item.
2266 p.skip_spaces(true);
2267 s = p.verbatimOption();
2269 p.skip_spaces(false);
2271 context.check_layout(os);
2272 if (context.has_item) {
2273 // An item in an unknown list-like environment
2274 // FIXME: Do this in check_layout()!
2275 context.has_item = false;
2277 handle_ert(os, "\\item", context);
2279 handle_ert(os, "\\item ", context);
2282 if (context.layout->labeltype != LABEL_MANUAL) {
2283 // LyX does not support \item[\mybullet]
2284 // in itemize environments
2286 os << parse_text_snippet(p2,
2287 FLAG_BRACK_LAST, outer, context);
2288 } else if (!s.empty()) {
2289 // LyX adds braces around the argument,
2290 // so we need to remove them here.
2291 if (s.size() > 2 && s[0] == '{' &&
2292 s[s.size()-1] == '}')
2293 s = s.substr(1, s.size()-2);
2294 // If the argument contains a space we
2295 // must put it into ERT: Otherwise LyX
2296 // would misinterpret the space as
2297 // item delimiter (bug 7663)
2298 if (contains(s, ' ')) {
2299 handle_ert(os, s, context);
2302 os << parse_text_snippet(p2,
2306 // The space is needed to separate the
2307 // item from the rest of the sentence.
2309 eat_whitespace(p, os, context, false);
2314 else if (t.cs() == "bibitem") {
2316 context.check_layout(os);
2317 eat_whitespace(p, os, context, false);
2318 string label = convert_command_inset_arg(p.verbatimOption());
2319 string key = convert_command_inset_arg(p.verbatim_item());
2320 if (contains(label, '\\') || contains(key, '\\')) {
2321 // LyX can't handle LaTeX commands in labels or keys
2322 handle_ert(os, t.asInput() + '[' + label +
2323 "]{" + p.verbatim_item() + '}',
2326 begin_command_inset(os, "bibitem", "bibitem");
2327 os << "label \"" << label << "\"\n"
2328 "key \"" << key << "\"\n";
2333 else if (is_macro(p)) {
2334 // catch the case of \def\inputGnumericTable
2336 if (t.cs() == "def") {
2337 Token second = p.next_token();
2338 if (second.cs() == "inputGnumericTable") {
2342 Token third = p.get_token();
2344 if (third.cs() == "input") {
2348 string name = normalize_filename(p.verbatim_item());
2349 string const path = getMasterFilePath();
2350 // We want to preserve relative / absolute filenames,
2351 // therefore path is only used for testing
2352 // The file extension is in every case ".tex".
2353 // So we need to remove this extension and check for
2354 // the original one.
2355 name.erase(name.length() - 4, name.length());
2356 if (!makeAbsPath(name, path).exists()) {
2357 char const * const Gnumeric_formats[] = {"gnumeric"
2359 string const Gnumeric_name =
2360 find_file(name, path, Gnumeric_formats);
2361 if (!Gnumeric_name.empty())
2362 name = Gnumeric_name;
2364 if (makeAbsPath(name, path).exists())
2365 fix_relative_filename(name);
2367 cerr << "Warning: Could not find file '"
2368 << name << "'." << endl;
2369 context.check_layout(os);
2370 begin_inset(os, "External\n\ttemplate ");
2371 os << "GnumericSpreadsheet\n\tfilename "
2374 context.check_layout(os);
2376 // register the packages that are automatically reloaded
2377 // by the Gnumeric template
2378 // Fixme: InsetExternal.cpp should give us that list
2379 preamble.registerAutomaticallyLoadedPackage("array");
2380 preamble.registerAutomaticallyLoadedPackage("calc");
2381 preamble.registerAutomaticallyLoadedPackage("color");
2382 preamble.registerAutomaticallyLoadedPackage("hhline");
2383 preamble.registerAutomaticallyLoadedPackage("ifthen");
2384 preamble.registerAutomaticallyLoadedPackage("longtable");
2385 preamble.registerAutomaticallyLoadedPackage("multirow");
2390 parse_macro(p, os, context);
2393 else if (t.cs() == "noindent") {
2395 context.add_par_extra_stuff("\\noindent\n");
2398 else if (t.cs() == "appendix") {
2399 context.add_par_extra_stuff("\\start_of_appendix\n");
2400 // We need to start a new paragraph. Otherwise the
2401 // appendix in 'bla\appendix\chapter{' would start
2403 context.new_paragraph(os);
2404 // We need to make sure that the paragraph is
2405 // generated even if it is empty. Otherwise the
2406 // appendix in '\par\appendix\par\chapter{' would
2408 context.check_layout(os);
2409 // FIXME: This is a hack to prevent paragraph
2410 // deletion if it is empty. Handle this better!
2412 "%dummy comment inserted by tex2lyx to "
2413 "ensure that this paragraph is not empty",
2415 // Both measures above may generate an additional
2416 // empty paragraph, but that does not hurt, because
2417 // whitespace does not matter here.
2418 eat_whitespace(p, os, context, true);
2421 // Must catch empty dates before findLayout is called below
2422 else if (t.cs() == "date") {
2423 string const date = p.verbatim_item();
2425 preamble.suppressDate(true);
2427 preamble.suppressDate(false);
2428 if (context.new_layout_allowed &&
2429 (newlayout = findLayout(context.textclass,
2432 output_command_layout(os, p, outer,
2433 context, newlayout);
2435 if (!title_layout_found)
2436 title_layout_found = newlayout->intitle;
2437 set<string> const & req = newlayout->requires();
2438 for (set<string>::const_iterator it = req.begin();
2439 it != req.end(); it++)
2440 preamble.registerAutomaticallyLoadedPackage(*it);
2442 handle_ert(os, "\\date{" + date + '}',
2447 // Starred section headings
2448 // Must attempt to parse "Section*" before "Section".
2449 else if ((p.next_token().asInput() == "*") &&
2450 context.new_layout_allowed &&
2451 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2454 output_command_layout(os, p, outer, context, newlayout);
2456 if (!title_layout_found)
2457 title_layout_found = newlayout->intitle;
2458 set<string> const & req = newlayout->requires();
2459 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2460 preamble.registerAutomaticallyLoadedPackage(*it);
2463 // Section headings and the like
2464 else if (context.new_layout_allowed &&
2465 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2467 output_command_layout(os, p, outer, context, newlayout);
2469 if (!title_layout_found)
2470 title_layout_found = newlayout->intitle;
2471 set<string> const & req = newlayout->requires();
2472 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2473 preamble.registerAutomaticallyLoadedPackage(*it);
2476 else if (t.cs() == "caption") {
2478 context.check_layout(os);
2480 begin_inset(os, "Caption\n");
2481 Context newcontext(true, context.textclass);
2482 newcontext.font = context.font;
2483 newcontext.check_layout(os);
2484 if (p.next_token().cat() != catEscape &&
2485 p.next_token().character() == '[') {
2486 p.get_token(); // eat '['
2487 begin_inset(os, "Argument\n");
2488 os << "status collapsed\n";
2489 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2491 eat_whitespace(p, os, context, false);
2493 parse_text(p, os, FLAG_ITEM, outer, context);
2494 context.check_end_layout(os);
2495 // We don't need really a new paragraph, but
2496 // we must make sure that the next item gets a \begin_layout.
2497 context.new_paragraph(os);
2500 newcontext.check_end_layout(os);
2503 else if (t.cs() == "subfloat") {
2504 // the syntax is \subfloat[caption]{content}
2505 // if it is a table of figure depends on the surrounding float
2506 bool has_caption = false;
2508 // do nothing if there is no outer float
2509 if (!float_type.empty()) {
2510 context.check_layout(os);
2512 begin_inset(os, "Float " + float_type + "\n");
2514 << "\nsideways false"
2515 << "\nstatus collapsed\n\n";
2518 if (p.next_token().cat() != catEscape &&
2519 p.next_token().character() == '[') {
2520 p.get_token(); // eat '['
2521 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2525 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2526 // the caption comes always as the last
2528 // we must make sure that the caption gets a \begin_layout
2529 os << "\n\\begin_layout Plain Layout";
2531 begin_inset(os, "Caption\n");
2532 Context newcontext(true, context.textclass);
2533 newcontext.font = context.font;
2534 newcontext.check_layout(os);
2535 os << caption << "\n";
2536 newcontext.check_end_layout(os);
2537 // We don't need really a new paragraph, but
2538 // we must make sure that the next item gets a \begin_layout.
2539 //newcontext.new_paragraph(os);
2543 // We don't need really a new paragraph, but
2544 // we must make sure that the next item gets a \begin_layout.
2546 context.new_paragraph(os);
2549 context.check_end_layout(os);
2550 // close the layout we opened
2552 os << "\n\\end_layout\n";
2554 // if the float type is not supported or there is no surrounding float
2557 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2558 handle_ert(os, t.asInput() + '[' + opt_arg +
2559 "]{" + p.verbatim_item() + '}', context);
2561 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2565 else if (t.cs() == "includegraphics") {
2566 bool const clip = p.next_token().asInput() == "*";
2569 string const arg = p.getArg('[', ']');
2570 map<string, string> opts;
2571 vector<string> keys;
2572 split_map(arg, opts, keys);
2574 opts["clip"] = string();
2575 string name = normalize_filename(p.verbatim_item());
2577 string const path = getMasterFilePath();
2578 // We want to preserve relative / absolute filenames,
2579 // therefore path is only used for testing
2580 if (!makeAbsPath(name, path).exists()) {
2581 // The file extension is probably missing.
2582 // Now try to find it out.
2583 string const dvips_name =
2584 find_file(name, path,
2585 known_dvips_graphics_formats);
2586 string const pdftex_name =
2587 find_file(name, path,
2588 known_pdftex_graphics_formats);
2589 if (!dvips_name.empty()) {
2590 if (!pdftex_name.empty()) {
2591 cerr << "This file contains the "
2593 "\"\\includegraphics{"
2595 "However, files\n\""
2596 << dvips_name << "\" and\n\""
2597 << pdftex_name << "\"\n"
2598 "both exist, so I had to make a "
2599 "choice and took the first one.\n"
2600 "Please move the unwanted one "
2601 "someplace else and try again\n"
2602 "if my choice was wrong."
2606 } else if (!pdftex_name.empty()) {
2612 if (makeAbsPath(name, path).exists())
2613 fix_relative_filename(name);
2615 cerr << "Warning: Could not find graphics file '"
2616 << name << "'." << endl;
2618 context.check_layout(os);
2619 begin_inset(os, "Graphics ");
2620 os << "\n\tfilename " << name << '\n';
2621 if (opts.find("width") != opts.end())
2623 << translate_len(opts["width"]) << '\n';
2624 if (opts.find("height") != opts.end())
2626 << translate_len(opts["height"]) << '\n';
2627 if (opts.find("scale") != opts.end()) {
2628 istringstream iss(opts["scale"]);
2632 os << "\tscale " << val << '\n';
2634 if (opts.find("angle") != opts.end()) {
2635 os << "\trotateAngle "
2636 << opts["angle"] << '\n';
2637 vector<string>::const_iterator a =
2638 find(keys.begin(), keys.end(), "angle");
2639 vector<string>::const_iterator s =
2640 find(keys.begin(), keys.end(), "width");
2641 if (s == keys.end())
2642 s = find(keys.begin(), keys.end(), "height");
2643 if (s == keys.end())
2644 s = find(keys.begin(), keys.end(), "scale");
2645 if (s != keys.end() && distance(s, a) > 0)
2646 os << "\tscaleBeforeRotation\n";
2648 if (opts.find("origin") != opts.end()) {
2650 string const opt = opts["origin"];
2651 if (opt.find('l') != string::npos) ss << "left";
2652 if (opt.find('r') != string::npos) ss << "right";
2653 if (opt.find('c') != string::npos) ss << "center";
2654 if (opt.find('t') != string::npos) ss << "Top";
2655 if (opt.find('b') != string::npos) ss << "Bottom";
2656 if (opt.find('B') != string::npos) ss << "Baseline";
2657 if (!ss.str().empty())
2658 os << "\trotateOrigin " << ss.str() << '\n';
2660 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2662 if (opts.find("keepaspectratio") != opts.end())
2663 os << "\tkeepAspectRatio\n";
2664 if (opts.find("clip") != opts.end())
2666 if (opts.find("draft") != opts.end())
2668 if (opts.find("bb") != opts.end())
2669 os << "\tBoundingBox "
2670 << opts["bb"] << '\n';
2671 int numberOfbbOptions = 0;
2672 if (opts.find("bbllx") != opts.end())
2673 numberOfbbOptions++;
2674 if (opts.find("bblly") != opts.end())
2675 numberOfbbOptions++;
2676 if (opts.find("bburx") != opts.end())
2677 numberOfbbOptions++;
2678 if (opts.find("bbury") != opts.end())
2679 numberOfbbOptions++;
2680 if (numberOfbbOptions == 4)
2681 os << "\tBoundingBox "
2682 << opts["bbllx"] << " " << opts["bblly"] << " "
2683 << opts["bburx"] << " " << opts["bbury"] << '\n';
2684 else if (numberOfbbOptions > 0)
2685 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2686 numberOfbbOptions = 0;
2687 if (opts.find("natwidth") != opts.end())
2688 numberOfbbOptions++;
2689 if (opts.find("natheight") != opts.end())
2690 numberOfbbOptions++;
2691 if (numberOfbbOptions == 2)
2692 os << "\tBoundingBox 0bp 0bp "
2693 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2694 else if (numberOfbbOptions > 0)
2695 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2696 ostringstream special;
2697 if (opts.find("hiresbb") != opts.end())
2698 special << "hiresbb,";
2699 if (opts.find("trim") != opts.end())
2701 if (opts.find("viewport") != opts.end())
2702 special << "viewport=" << opts["viewport"] << ',';
2703 if (opts.find("totalheight") != opts.end())
2704 special << "totalheight=" << opts["totalheight"] << ',';
2705 if (opts.find("type") != opts.end())
2706 special << "type=" << opts["type"] << ',';
2707 if (opts.find("ext") != opts.end())
2708 special << "ext=" << opts["ext"] << ',';
2709 if (opts.find("read") != opts.end())
2710 special << "read=" << opts["read"] << ',';
2711 if (opts.find("command") != opts.end())
2712 special << "command=" << opts["command"] << ',';
2713 string s_special = special.str();
2714 if (!s_special.empty()) {
2715 // We had special arguments. Remove the trailing ','.
2716 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2718 // TODO: Handle the unknown settings better.
2719 // Warn about invalid options.
2720 // Check whether some option was given twice.
2724 else if (t.cs() == "footnote" ||
2725 (t.cs() == "thanks" && context.layout->intitle)) {
2727 context.check_layout(os);
2728 begin_inset(os, "Foot\n");
2729 os << "status collapsed\n\n";
2730 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2734 else if (t.cs() == "marginpar") {
2736 context.check_layout(os);
2737 begin_inset(os, "Marginal\n");
2738 os << "status collapsed\n\n";
2739 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2743 else if (t.cs() == "ensuremath") {
2745 context.check_layout(os);
2746 string const s = p.verbatim_item();
2747 //FIXME: this never triggers in UTF8
2748 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2751 handle_ert(os, "\\ensuremath{" + s + "}",
2755 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2756 if (title_layout_found) {
2758 skip_spaces_braces(p);
2760 handle_ert(os, t.asInput(), context);
2763 else if (t.cs() == "tableofcontents") {
2764 context.check_layout(os);
2765 begin_command_inset(os, "toc", "tableofcontents");
2767 skip_spaces_braces(p);
2770 else if (t.cs() == "listoffigures") {
2771 context.check_layout(os);
2772 begin_inset(os, "FloatList figure\n");
2774 skip_spaces_braces(p);
2777 else if (t.cs() == "listoftables") {
2778 context.check_layout(os);
2779 begin_inset(os, "FloatList table\n");
2781 skip_spaces_braces(p);
2784 else if (t.cs() == "listof") {
2785 p.skip_spaces(true);
2786 string const name = p.get_token().cs();
2787 if (context.textclass.floats().typeExist(name)) {
2788 context.check_layout(os);
2789 begin_inset(os, "FloatList ");
2792 p.get_token(); // swallow second arg
2794 handle_ert(os, "\\listof{" + name + "}", context);
2797 else if ((where = is_known(t.cs(), known_text_font_families)))
2798 parse_text_attributes(p, os, FLAG_ITEM, outer,
2799 context, "\\family", context.font.family,
2800 known_coded_font_families[where - known_text_font_families]);
2802 else if ((where = is_known(t.cs(), known_text_font_series)))
2803 parse_text_attributes(p, os, FLAG_ITEM, outer,
2804 context, "\\series", context.font.series,
2805 known_coded_font_series[where - known_text_font_series]);
2807 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2808 parse_text_attributes(p, os, FLAG_ITEM, outer,
2809 context, "\\shape", context.font.shape,
2810 known_coded_font_shapes[where - known_text_font_shapes]);
2812 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2813 context.check_layout(os);
2814 TeXFont oldFont = context.font;
2815 context.font.init();
2816 context.font.size = oldFont.size;
2817 os << "\n\\family " << context.font.family << "\n";
2818 os << "\n\\series " << context.font.series << "\n";
2819 os << "\n\\shape " << context.font.shape << "\n";
2820 if (t.cs() == "textnormal") {
2821 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2822 output_font_change(os, context.font, oldFont);
2823 context.font = oldFont;
2825 eat_whitespace(p, os, context, false);
2828 else if (t.cs() == "textcolor") {
2829 // scheme is \textcolor{color name}{text}
2830 string const color = p.verbatim_item();
2831 // we only support the predefined colors of the color package
2832 if (color == "black" || color == "blue" || color == "cyan"
2833 || color == "green" || color == "magenta" || color == "red"
2834 || color == "white" || color == "yellow") {
2835 context.check_layout(os);
2836 os << "\n\\color " << color << "\n";
2837 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2838 context.check_layout(os);
2839 os << "\n\\color inherit\n";
2840 preamble.registerAutomaticallyLoadedPackage("color");
2842 // for custom defined colors
2843 handle_ert(os, t.asInput() + "{" + color + "}", context);
2846 else if (t.cs() == "underbar" || t.cs() == "uline") {
2847 // \underbar is not 100% correct (LyX outputs \uline
2848 // of ulem.sty). The difference is that \ulem allows
2849 // line breaks, and \underbar does not.
2850 // Do NOT handle \underline.
2851 // \underbar cuts through y, g, q, p etc.,
2852 // \underline does not.
2853 context.check_layout(os);
2854 os << "\n\\bar under\n";
2855 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2856 context.check_layout(os);
2857 os << "\n\\bar default\n";
2858 preamble.registerAutomaticallyLoadedPackage("ulem");
2861 else if (t.cs() == "sout") {
2862 context.check_layout(os);
2863 os << "\n\\strikeout on\n";
2864 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2865 context.check_layout(os);
2866 os << "\n\\strikeout default\n";
2867 preamble.registerAutomaticallyLoadedPackage("ulem");
2870 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2871 t.cs() == "emph" || t.cs() == "noun") {
2872 context.check_layout(os);
2873 os << "\n\\" << t.cs() << " on\n";
2874 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2875 context.check_layout(os);
2876 os << "\n\\" << t.cs() << " default\n";
2877 if (t.cs() == "uuline" || t.cs() == "uwave")
2878 preamble.registerAutomaticallyLoadedPackage("ulem");
2881 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2882 context.check_layout(os);
2883 string name = p.getArg('{', '}');
2884 string localtime = p.getArg('{', '}');
2885 preamble.registerAuthor(name);
2886 Author const & author = preamble.getAuthor(name);
2887 // from_ctime() will fail if LyX decides to output the
2888 // time in the text language. It might also use a wrong
2889 // time zone (if the original LyX document was exported
2890 // with a different time zone).
2891 time_t ptime = from_ctime(localtime);
2892 if (ptime == static_cast<time_t>(-1)) {
2893 cerr << "Warning: Could not parse time `" << localtime
2894 << "´ for change tracking, using current time instead.\n";
2895 ptime = current_time();
2897 if (t.cs() == "lyxadded")
2898 os << "\n\\change_inserted ";
2900 os << "\n\\change_deleted ";
2901 os << author.bufferId() << ' ' << ptime << '\n';
2902 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2903 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2904 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2905 LaTeXPackages::isAvailable("xcolor");
2906 // No need to test for luatex, since luatex comes in
2907 // two flavours (dvi and pdf), like latex, and those
2908 // are detected by pdflatex.
2909 if (pdflatex || xetex) {
2911 preamble.registerAutomaticallyLoadedPackage("ulem");
2912 preamble.registerAutomaticallyLoadedPackage("xcolor");
2913 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2917 preamble.registerAutomaticallyLoadedPackage("dvipost");
2918 } else if (xcolorulem) {
2919 preamble.registerAutomaticallyLoadedPackage("ulem");
2920 preamble.registerAutomaticallyLoadedPackage("xcolor");
2925 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2926 t.cs() == "vphantom") {
2927 context.check_layout(os);
2928 if (t.cs() == "phantom")
2929 begin_inset(os, "Phantom Phantom\n");
2930 if (t.cs() == "hphantom")
2931 begin_inset(os, "Phantom HPhantom\n");
2932 if (t.cs() == "vphantom")
2933 begin_inset(os, "Phantom VPhantom\n");
2934 os << "status open\n";
2935 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2940 else if (t.cs() == "href") {
2941 context.check_layout(os);
2942 string target = p.getArg('{', '}');
2943 string name = p.getArg('{', '}');
2945 size_t i = target.find(':');
2946 if (i != string::npos) {
2947 type = target.substr(0, i + 1);
2948 if (type == "mailto:" || type == "file:")
2949 target = target.substr(i + 1);
2950 // handle the case that name is equal to target, except of "http://"
2951 else if (target.substr(i + 3) == name && type == "http:")
2954 begin_command_inset(os, "href", "href");
2956 os << "name \"" << name << "\"\n";
2957 os << "target \"" << target << "\"\n";
2958 if (type == "mailto:" || type == "file:")
2959 os << "type \"" << type << "\"\n";
2961 skip_spaces_braces(p);
2964 else if (t.cs() == "lyxline") {
2965 // swallow size argument (it is not used anyway)
2967 if (!context.atParagraphStart()) {
2968 // so our line is in the middle of a paragraph
2969 // we need to add a new line, lest this line
2970 // follow the other content on that line and
2971 // run off the side of the page
2972 // FIXME: This may create an empty paragraph,
2973 // but without that it would not be
2974 // possible to set noindent below.
2975 // Fortunately LaTeX does not care
2976 // about the empty paragraph.
2977 context.new_paragraph(os);
2979 if (preamble.indentParagraphs()) {
2980 // we need to unindent, lest the line be too long
2981 context.add_par_extra_stuff("\\noindent\n");
2983 context.check_layout(os);
2984 begin_command_inset(os, "line", "rule");
2985 os << "offset \"0.5ex\"\n"
2986 "width \"100line%\"\n"
2991 else if (t.cs() == "rule") {
2992 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2993 string const width = p.getArg('{', '}');
2994 string const thickness = p.getArg('{', '}');
2995 context.check_layout(os);
2996 begin_command_inset(os, "line", "rule");
2997 if (!offset.empty())
2998 os << "offset \"" << translate_len(offset) << "\"\n";
2999 os << "width \"" << translate_len(width) << "\"\n"
3000 "height \"" << translate_len(thickness) << "\"\n";
3004 else if (is_known(t.cs(), known_phrases) ||
3005 (t.cs() == "protect" &&
3006 p.next_token().cat() == catEscape &&
3007 is_known(p.next_token().cs(), known_phrases))) {
3008 // LyX sometimes puts a \protect in front, so we have to ignore it
3009 // FIXME: This needs to be changed when bug 4752 is fixed.
3011 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3013 context.check_layout(os);
3014 os << known_coded_phrases[where - known_phrases];
3015 skip_spaces_braces(p);
3018 else if ((where = is_known(t.cs(), known_ref_commands))) {
3019 string const opt = p.getOpt();
3021 context.check_layout(os);
3022 begin_command_inset(os, "ref",
3023 known_coded_ref_commands[where - known_ref_commands]);
3024 os << "reference \""
3025 << convert_command_inset_arg(p.verbatim_item())
3028 if (t.cs() == "vref" || t.cs() == "vpageref")
3029 preamble.registerAutomaticallyLoadedPackage("varioref");
3032 // LyX does not support optional arguments of ref commands
3033 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3034 p.verbatim_item() + "}", context);
3038 else if (use_natbib &&
3039 is_known(t.cs(), known_natbib_commands) &&
3040 ((t.cs() != "citefullauthor" &&
3041 t.cs() != "citeyear" &&
3042 t.cs() != "citeyearpar") ||
3043 p.next_token().asInput() != "*")) {
3044 context.check_layout(os);
3045 string command = t.cs();
3046 if (p.next_token().asInput() == "*") {
3050 if (command == "citefullauthor")
3051 // alternative name for "\\citeauthor*"
3052 command = "citeauthor*";
3054 // text before the citation
3056 // text after the citation
3058 get_cite_arguments(p, true, before, after);
3060 if (command == "cite") {
3061 // \cite without optional argument means
3062 // \citet, \cite with at least one optional
3063 // argument means \citep.
3064 if (before.empty() && after.empty())
3069 if (before.empty() && after == "[]")
3070 // avoid \citet[]{a}
3072 else if (before == "[]" && after == "[]") {
3073 // avoid \citet[][]{a}
3077 // remove the brackets around after and before
3078 if (!after.empty()) {
3080 after.erase(after.length() - 1, 1);
3081 after = convert_command_inset_arg(after);
3083 if (!before.empty()) {
3085 before.erase(before.length() - 1, 1);
3086 before = convert_command_inset_arg(before);
3088 begin_command_inset(os, "citation", command);
3089 os << "after " << '"' << after << '"' << "\n";
3090 os << "before " << '"' << before << '"' << "\n";
3092 << convert_command_inset_arg(p.verbatim_item())
3097 else if (use_jurabib &&
3098 is_known(t.cs(), known_jurabib_commands) &&
3099 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3100 context.check_layout(os);
3101 string command = t.cs();
3102 if (p.next_token().asInput() == "*") {
3106 char argumentOrder = '\0';
3107 vector<string> const options =
3108 preamble.getPackageOptions("jurabib");
3109 if (find(options.begin(), options.end(),
3110 "natbiborder") != options.end())
3111 argumentOrder = 'n';
3112 else if (find(options.begin(), options.end(),
3113 "jurabiborder") != options.end())
3114 argumentOrder = 'j';
3116 // text before the citation
3118 // text after the citation
3120 get_cite_arguments(p, argumentOrder != 'j', before, after);
3122 string const citation = p.verbatim_item();
3123 if (!before.empty() && argumentOrder == '\0') {
3124 cerr << "Warning: Assuming argument order "
3125 "of jurabib version 0.6 for\n'"
3126 << command << before << after << '{'
3127 << citation << "}'.\n"
3128 "Add 'jurabiborder' to the jurabib "
3129 "package options if you used an\n"
3130 "earlier jurabib version." << endl;
3132 if (!after.empty()) {
3134 after.erase(after.length() - 1, 1);
3136 if (!before.empty()) {
3138 before.erase(before.length() - 1, 1);
3140 begin_command_inset(os, "citation", command);
3141 os << "after " << '"' << after << '"' << "\n";
3142 os << "before " << '"' << before << '"' << "\n";
3143 os << "key " << '"' << citation << '"' << "\n";
3147 else if (t.cs() == "cite"
3148 || t.cs() == "nocite") {
3149 context.check_layout(os);
3150 string after = convert_command_inset_arg(p.getArg('[', ']'));
3151 string key = convert_command_inset_arg(p.verbatim_item());
3152 // store the case that it is "\nocite{*}" to use it later for
3155 begin_command_inset(os, "citation", t.cs());
3156 os << "after " << '"' << after << '"' << "\n";
3157 os << "key " << '"' << key << '"' << "\n";
3159 } else if (t.cs() == "nocite")
3163 else if (t.cs() == "index") {
3164 context.check_layout(os);
3165 begin_inset(os, "Index idx\n");
3166 os << "status collapsed\n";
3167 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3171 else if (t.cs() == "nomenclature") {
3172 context.check_layout(os);
3173 begin_command_inset(os, "nomenclature", "nomenclature");
3174 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3175 if (!prefix.empty())
3176 os << "prefix " << '"' << prefix << '"' << "\n";
3177 os << "symbol " << '"'
3178 << convert_command_inset_arg(p.verbatim_item());
3179 os << "\"\ndescription \""
3180 << convert_command_inset_arg(p.verbatim_item())
3183 preamble.registerAutomaticallyLoadedPackage("nomencl");
3186 else if (t.cs() == "label") {
3187 context.check_layout(os);
3188 begin_command_inset(os, "label", "label");
3190 << convert_command_inset_arg(p.verbatim_item())
3195 else if (t.cs() == "printindex") {
3196 context.check_layout(os);
3197 begin_command_inset(os, "index_print", "printindex");
3198 os << "type \"idx\"\n";
3200 skip_spaces_braces(p);
3201 preamble.registerAutomaticallyLoadedPackage("makeidx");
3202 if (preamble.use_indices() == "true")
3203 preamble.registerAutomaticallyLoadedPackage("splitidx");
3206 else if (t.cs() == "printnomenclature") {
3208 string width_type = "";
3209 context.check_layout(os);
3210 begin_command_inset(os, "nomencl_print", "printnomenclature");
3211 // case of a custom width
3213 width = p.getArg('[', ']');
3214 width = translate_len(width);
3215 width_type = "custom";
3217 // case of no custom width
3218 // the case of no custom width but the width set
3219 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3220 // because the user could have set anything, not only the width
3221 // of the longest label (which would be width_type = "auto")
3222 string label = convert_command_inset_arg(p.getArg('{', '}'));
3223 if (label.empty() && width_type.empty())
3224 width_type = "none";
3225 os << "set_width \"" << width_type << "\"\n";
3226 if (width_type == "custom")
3227 os << "width \"" << width << '\"';
3229 skip_spaces_braces(p);
3230 preamble.registerAutomaticallyLoadedPackage("nomencl");
3233 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3234 context.check_layout(os);
3235 begin_inset(os, "script ");
3236 os << t.cs().substr(4) << '\n';
3237 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3239 if (t.cs() == "textsubscript")
3240 preamble.registerAutomaticallyLoadedPackage("subscript");
3243 else if ((where = is_known(t.cs(), known_quotes))) {
3244 context.check_layout(os);
3245 begin_inset(os, "Quotes ");
3246 os << known_coded_quotes[where - known_quotes];
3248 // LyX adds {} after the quote, so we have to eat
3249 // spaces here if there are any before a possible
3251 eat_whitespace(p, os, context, false);
3255 else if ((where = is_known(t.cs(), known_sizes)) &&
3256 context.new_layout_allowed) {
3257 context.check_layout(os);
3258 TeXFont const oldFont = context.font;
3259 context.font.size = known_coded_sizes[where - known_sizes];
3260 output_font_change(os, oldFont, context.font);
3261 eat_whitespace(p, os, context, false);
3264 else if ((where = is_known(t.cs(), known_font_families)) &&
3265 context.new_layout_allowed) {
3266 context.check_layout(os);
3267 TeXFont const oldFont = context.font;
3268 context.font.family =
3269 known_coded_font_families[where - known_font_families];
3270 output_font_change(os, oldFont, context.font);
3271 eat_whitespace(p, os, context, false);
3274 else if ((where = is_known(t.cs(), known_font_series)) &&
3275 context.new_layout_allowed) {
3276 context.check_layout(os);
3277 TeXFont const oldFont = context.font;
3278 context.font.series =
3279 known_coded_font_series[where - known_font_series];
3280 output_font_change(os, oldFont, context.font);
3281 eat_whitespace(p, os, context, false);
3284 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3285 context.new_layout_allowed) {
3286 context.check_layout(os);
3287 TeXFont const oldFont = context.font;
3288 context.font.shape =
3289 known_coded_font_shapes[where - known_font_shapes];
3290 output_font_change(os, oldFont, context.font);
3291 eat_whitespace(p, os, context, false);
3293 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3294 context.new_layout_allowed) {
3295 context.check_layout(os);
3296 TeXFont const oldFont = context.font;
3297 context.font.init();
3298 context.font.size = oldFont.size;
3299 context.font.family =
3300 known_coded_font_families[where - known_old_font_families];
3301 output_font_change(os, oldFont, context.font);
3302 eat_whitespace(p, os, context, false);
3305 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3306 context.new_layout_allowed) {
3307 context.check_layout(os);
3308 TeXFont const oldFont = context.font;
3309 context.font.init();
3310 context.font.size = oldFont.size;
3311 context.font.series =
3312 known_coded_font_series[where - known_old_font_series];
3313 output_font_change(os, oldFont, context.font);
3314 eat_whitespace(p, os, context, false);
3317 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3318 context.new_layout_allowed) {
3319 context.check_layout(os);
3320 TeXFont const oldFont = context.font;
3321 context.font.init();
3322 context.font.size = oldFont.size;
3323 context.font.shape =
3324 known_coded_font_shapes[where - known_old_font_shapes];
3325 output_font_change(os, oldFont, context.font);
3326 eat_whitespace(p, os, context, false);
3329 else if (t.cs() == "selectlanguage") {
3330 context.check_layout(os);
3331 // save the language for the case that a
3332 // \foreignlanguage is used
3334 context.font.language = babel2lyx(p.verbatim_item());
3335 os << "\n\\lang " << context.font.language << "\n";
3338 else if (t.cs() == "foreignlanguage") {
3339 string const lang = babel2lyx(p.verbatim_item());
3340 parse_text_attributes(p, os, FLAG_ITEM, outer,
3342 context.font.language, lang);
3345 else if (t.cs() == "inputencoding") {
3346 // nothing to write here
3347 string const enc = subst(p.verbatim_item(), "\n", " ");
3351 else if ((where = is_known(t.cs(), known_special_chars))) {
3352 context.check_layout(os);
3353 os << "\\SpecialChar \\"
3354 << known_coded_special_chars[where - known_special_chars]
3356 skip_spaces_braces(p);
3359 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3360 context.check_layout(os);
3361 os << "\\SpecialChar \\nobreakdash-\n";
3365 else if (t.cs() == "textquotedbl") {
3366 context.check_layout(os);
3371 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3372 context.check_layout(os);
3373 os << "\\SpecialChar \\@.\n";
3377 else if (t.cs() == "-") {
3378 context.check_layout(os);
3379 os << "\\SpecialChar \\-\n";
3382 else if (t.cs() == "textasciitilde") {
3383 context.check_layout(os);
3385 skip_spaces_braces(p);
3388 else if (t.cs() == "textasciicircum") {
3389 context.check_layout(os);
3391 skip_spaces_braces(p);
3394 else if (t.cs() == "textbackslash") {
3395 context.check_layout(os);
3396 os << "\n\\backslash\n";
3397 skip_spaces_braces(p);
3400 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3401 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3403 context.check_layout(os);
3407 else if (t.cs() == "char") {
3408 context.check_layout(os);
3409 if (p.next_token().character() == '`') {
3411 if (p.next_token().cs() == "\"") {
3416 handle_ert(os, "\\char`", context);
3419 handle_ert(os, "\\char", context);
3423 else if (t.cs() == "verb") {
3424 context.check_layout(os);
3425 char const delimiter = p.next_token().character();
3426 string const arg = p.getArg(delimiter, delimiter);
3428 oss << "\\verb" << delimiter << arg << delimiter;
3429 handle_ert(os, oss.str(), context);
3432 // Problem: \= creates a tabstop inside the tabbing environment
3433 // and else an accent. In the latter case we really would want
3434 // \={o} instead of \= o.
3435 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3436 handle_ert(os, t.asInput(), context);
3438 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3439 else if (t.cs().size() == 1
3440 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3441 context.check_layout(os);
3442 // try to see whether the string is in unicodesymbols
3444 string command = t.asInput() + "{"
3445 + trimSpaceAndEol(p.verbatim_item())
3448 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3449 Encodings::TEXT_CMD | Encodings::MATH_CMD, rem, &req);
3452 cerr << "When parsing " << command
3453 << ", result is " << to_utf8(s)
3454 << "+" << to_utf8(rem) << endl;
3456 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
3457 preamble.registerAutomaticallyLoadedPackage(*it);
3459 // we did not find a non-ert version
3460 handle_ert(os, command, context);
3463 else if (t.cs() == "\\") {
3464 context.check_layout(os);
3466 handle_ert(os, "\\\\" + p.getOpt(), context);
3467 else if (p.next_token().asInput() == "*") {
3469 // getOpt() eats the following space if there
3470 // is no optional argument, but that is OK
3471 // here since it has no effect in the output.
3472 handle_ert(os, "\\\\*" + p.getOpt(), context);
3475 begin_inset(os, "Newline newline");
3480 else if (t.cs() == "newline" ||
3481 (t.cs() == "linebreak" && !p.hasOpt())) {
3482 context.check_layout(os);
3483 begin_inset(os, "Newline ");
3486 skip_spaces_braces(p);
3489 else if (t.cs() == "input" || t.cs() == "include"
3490 || t.cs() == "verbatiminput") {
3491 string name = t.cs();
3492 if (t.cs() == "verbatiminput"
3493 && p.next_token().asInput() == "*")
3494 name += p.get_token().asInput();
3495 context.check_layout(os);
3496 string filename(normalize_filename(p.getArg('{', '}')));
3497 string const path = getMasterFilePath();
3498 // We want to preserve relative / absolute filenames,
3499 // therefore path is only used for testing
3500 if ((t.cs() == "include" || t.cs() == "input") &&
3501 !makeAbsPath(filename, path).exists()) {
3502 // The file extension is probably missing.
3503 // Now try to find it out.
3504 string const tex_name =
3505 find_file(filename, path,
3506 known_tex_extensions);
3507 if (!tex_name.empty())
3508 filename = tex_name;
3510 bool external = false;
3512 if (makeAbsPath(filename, path).exists()) {
3513 string const abstexname =
3514 makeAbsPath(filename, path).absFileName();
3515 string const abslyxname =
3516 changeExtension(abstexname, ".lyx");
3517 string const absfigname =
3518 changeExtension(abstexname, ".fig");
3519 fix_relative_filename(filename);
3520 string const lyxname =
3521 changeExtension(filename, ".lyx");
3523 external = FileName(absfigname).exists();
3524 if (t.cs() == "input") {
3525 string const ext = getExtension(abstexname);
3527 // Combined PS/LaTeX:
3528 // x.eps, x.pstex_t (old xfig)
3529 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3530 FileName const absepsname(
3531 changeExtension(abstexname, ".eps"));
3532 FileName const abspstexname(
3533 changeExtension(abstexname, ".pstex"));
3534 bool const xfigeps =
3535 (absepsname.exists() ||
3536 abspstexname.exists()) &&
3539 // Combined PDF/LaTeX:
3540 // x.pdf, x.pdftex_t (old xfig)
3541 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3542 FileName const abspdfname(
3543 changeExtension(abstexname, ".pdf"));
3544 bool const xfigpdf =
3545 abspdfname.exists() &&
3546 (ext == "pdftex_t" || ext == "pdf_t");
3550 // Combined PS/PDF/LaTeX:
3551 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3552 string const absbase2(
3553 removeExtension(abstexname) + "_pspdftex");
3554 FileName const abseps2name(
3555 addExtension(absbase2, ".eps"));
3556 FileName const abspdf2name(
3557 addExtension(absbase2, ".pdf"));
3558 bool const xfigboth =
3559 abspdf2name.exists() &&
3560 abseps2name.exists() && ext == "pspdftex";
3562 xfig = xfigpdf || xfigeps || xfigboth;
3563 external = external && xfig;
3566 outname = changeExtension(filename, ".fig");
3568 // Don't try to convert, the result
3569 // would be full of ERT.
3571 } else if (t.cs() != "verbatiminput" &&
3572 tex2lyx(abstexname, FileName(abslyxname),
3579 cerr << "Warning: Could not find included file '"
3580 << filename << "'." << endl;
3584 begin_inset(os, "External\n");
3585 os << "\ttemplate XFig\n"
3586 << "\tfilename " << outname << '\n';
3588 begin_command_inset(os, "include", name);
3589 os << "preview false\n"
3590 "filename \"" << outname << "\"\n";
3591 if (t.cs() == "verbatiminput")
3592 preamble.registerAutomaticallyLoadedPackage("verbatim");
3597 else if (t.cs() == "bibliographystyle") {
3598 // store new bibliographystyle
3599 bibliographystyle = p.verbatim_item();
3600 // If any other command than \bibliography and
3601 // \nocite{*} follows, we need to output the style
3602 // (because it might be used by that command).
3603 // Otherwise, it will automatically be output by LyX.
3606 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3607 if (t2.cat() == catBegin)
3609 if (t2.cat() != catEscape)
3611 if (t2.cs() == "nocite") {
3612 if (p.getArg('{', '}') == "*")
3614 } else if (t2.cs() == "bibliography")
3621 "\\bibliographystyle{" + bibliographystyle + '}',
3626 else if (t.cs() == "bibliography") {
3627 context.check_layout(os);
3628 begin_command_inset(os, "bibtex", "bibtex");
3629 if (!btprint.empty()) {
3630 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3631 // clear the string because the next BibTeX inset can be without the
3632 // \nocite{*} option
3635 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3636 // Do we have a bibliographystyle set?
3637 if (!bibliographystyle.empty())
3638 os << "options " << '"' << bibliographystyle << '"' << "\n";
3642 else if (t.cs() == "parbox") {
3643 // Test whether this is an outer box of a shaded box
3645 // swallow arguments
3646 while (p.hasOpt()) {
3648 p.skip_spaces(true);
3651 p.skip_spaces(true);
3653 if (p.next_token().cat() == catBegin)
3655 p.skip_spaces(true);
3656 Token to = p.get_token();
3657 bool shaded = false;
3658 if (to.asInput() == "\\begin") {
3659 p.skip_spaces(true);
3660 if (p.getArg('{', '}') == "shaded")
3665 parse_outer_box(p, os, FLAG_ITEM, outer,
3666 context, "parbox", "shaded");
3668 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3672 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3673 t.cs() == "shadowbox" || t.cs() == "doublebox")
3674 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3676 else if (t.cs() == "framebox") {
3677 if (p.next_token().character() == '(') {
3678 //the syntax is: \framebox(x,y)[position]{content}
3679 string arg = t.asInput();
3680 arg += p.getFullParentheseArg();
3681 arg += p.getFullOpt();
3682 eat_whitespace(p, os, context, false);
3683 handle_ert(os, arg + '{', context);
3684 eat_whitespace(p, os, context, false);
3685 parse_text(p, os, FLAG_ITEM, outer, context);
3686 handle_ert(os, "}", context);
3688 string special = p.getFullOpt();
3689 special += p.getOpt();
3690 parse_outer_box(p, os, FLAG_ITEM, outer,
3691 context, t.cs(), special);
3695 //\makebox() is part of the picture environment and different from \makebox{}
3696 //\makebox{} will be parsed by parse_box
3697 else if (t.cs() == "makebox") {
3698 if (p.next_token().character() == '(') {
3699 //the syntax is: \makebox(x,y)[position]{content}
3700 string arg = t.asInput();
3701 arg += p.getFullParentheseArg();
3702 arg += p.getFullOpt();
3703 eat_whitespace(p, os, context, false);
3704 handle_ert(os, arg + '{', context);
3705 eat_whitespace(p, os, context, false);
3706 parse_text(p, os, FLAG_ITEM, outer, context);
3707 handle_ert(os, "}", context);
3709 //the syntax is: \makebox[width][position]{content}
3710 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3714 else if (t.cs() == "smallskip" ||
3715 t.cs() == "medskip" ||
3716 t.cs() == "bigskip" ||
3717 t.cs() == "vfill") {
3718 context.check_layout(os);
3719 begin_inset(os, "VSpace ");
3722 skip_spaces_braces(p);
3725 else if ((where = is_known(t.cs(), known_spaces))) {
3726 context.check_layout(os);
3727 begin_inset(os, "space ");
3728 os << '\\' << known_coded_spaces[where - known_spaces]
3731 // LaTeX swallows whitespace after all spaces except
3732 // "\\,". We have to do that here, too, because LyX
3733 // adds "{}" which would make the spaces significant.
3735 eat_whitespace(p, os, context, false);
3736 // LyX adds "{}" after all spaces except "\\ " and
3737 // "\\,", so we have to remove "{}".
3738 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3739 // remove the braces after "\\,", too.
3744 else if (t.cs() == "newpage" ||
3745 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3746 t.cs() == "clearpage" ||
3747 t.cs() == "cleardoublepage") {
3748 context.check_layout(os);
3749 begin_inset(os, "Newpage ");
3752 skip_spaces_braces(p);
3755 else if (t.cs() == "DeclareRobustCommand" ||
3756 t.cs() == "DeclareRobustCommandx" ||
3757 t.cs() == "newcommand" ||
3758 t.cs() == "newcommandx" ||
3759 t.cs() == "providecommand" ||
3760 t.cs() == "providecommandx" ||
3761 t.cs() == "renewcommand" ||
3762 t.cs() == "renewcommandx") {
3763 // DeclareRobustCommand, DeclareRobustCommandx,
3764 // providecommand and providecommandx could be handled
3765 // by parse_command(), but we need to call
3766 // add_known_command() here.
3767 string name = t.asInput();
3768 if (p.next_token().asInput() == "*") {
3769 // Starred form. Eat '*'
3773 string const command = p.verbatim_item();
3774 string const opt1 = p.getFullOpt();
3775 string const opt2 = p.getFullOpt();
3776 add_known_command(command, opt1, !opt2.empty());
3777 string const ert = name + '{' + command + '}' +
3779 '{' + p.verbatim_item() + '}';
3781 if (t.cs() == "DeclareRobustCommand" ||
3782 t.cs() == "DeclareRobustCommandx" ||
3783 t.cs() == "providecommand" ||
3784 t.cs() == "providecommandx" ||
3785 name[name.length()-1] == '*')
3786 handle_ert(os, ert, context);
3788 context.check_layout(os);
3789 begin_inset(os, "FormulaMacro");
3795 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3796 // let could be handled by parse_command(),
3797 // but we need to call add_known_command() here.
3798 string ert = t.asInput();
3801 if (p.next_token().cat() == catBegin) {
3802 name = p.verbatim_item();
3803 ert += '{' + name + '}';
3805 name = p.verbatim_item();
3810 if (p.next_token().cat() == catBegin) {
3811 command = p.verbatim_item();
3812 ert += '{' + command + '}';
3814 command = p.verbatim_item();
3817 // If command is known, make name known too, to parse
3818 // its arguments correctly. For this reason we also
3819 // have commands in syntax.default that are hardcoded.
3820 CommandMap::iterator it = known_commands.find(command);
3821 if (it != known_commands.end())
3822 known_commands[t.asInput()] = it->second;
3823 handle_ert(os, ert, context);
3826 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3827 bool starred = false;
3828 if (p.next_token().asInput() == "*") {
3832 string name = t.asInput();
3833 string const length = p.verbatim_item();
3836 bool valid = splitLatexLength(length, valstring, unit);
3837 bool known_hspace = false;
3838 bool known_vspace = false;
3839 bool known_unit = false;
3842 istringstream iss(valstring);
3845 if (t.cs()[0] == 'h') {
3846 if (unit == "\\fill") {
3851 known_hspace = true;
3854 if (unit == "\\smallskipamount") {
3856 known_vspace = true;
3857 } else if (unit == "\\medskipamount") {
3859 known_vspace = true;
3860 } else if (unit == "\\bigskipamount") {
3862 known_vspace = true;
3863 } else if (unit == "\\fill") {
3865 known_vspace = true;
3869 if (!known_hspace && !known_vspace) {
3870 switch (unitFromString(unit)) {
3891 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3892 // Literal horizontal length or known variable
3893 context.check_layout(os);
3894 begin_inset(os, "space ");
3902 if (known_unit && !known_hspace)
3904 << translate_len(length);
3906 } else if (known_unit || known_vspace) {
3907 // Literal vertical length or known variable
3908 context.check_layout(os);
3909 begin_inset(os, "VSpace ");
3917 // LyX can't handle other length variables in Inset VSpace/space
3922 handle_ert(os, name + '{' + unit + '}', context);
3923 else if (value == -1.0)
3924 handle_ert(os, name + "{-" + unit + '}', context);
3926 handle_ert(os, name + '{' + valstring + unit + '}', context);
3928 handle_ert(os, name + '{' + length + '}', context);
3932 // The single '=' is meant here.
3933 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3935 context.check_layout(os);
3936 begin_inset(os, "Flex ");
3937 os << to_utf8(newinsetlayout->name()) << '\n'
3938 << "status collapsed\n";
3939 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3943 else if (t.cs() == "includepdf") {
3945 string const arg = p.getArg('[', ']');
3946 map<string, string> opts;
3947 vector<string> keys;
3948 split_map(arg, opts, keys);
3949 string name = normalize_filename(p.verbatim_item());
3950 string const path = getMasterFilePath();
3951 // We want to preserve relative / absolute filenames,
3952 // therefore path is only used for testing
3953 if (!makeAbsPath(name, path).exists()) {
3954 // The file extension is probably missing.
3955 // Now try to find it out.
3956 char const * const pdfpages_format[] = {"pdf", 0};
3957 string const pdftex_name =
3958 find_file(name, path, pdfpages_format);
3959 if (!pdftex_name.empty()) {
3964 if (makeAbsPath(name, path).exists())
3965 fix_relative_filename(name);
3967 cerr << "Warning: Could not find file '"
3968 << name << "'." << endl;
3970 context.check_layout(os);
3971 begin_inset(os, "External\n\ttemplate ");
3972 os << "PDFPages\n\tfilename "
3974 // parse the options
3975 if (opts.find("pages") != opts.end())
3976 os << "\textra LaTeX \"pages="
3977 << opts["pages"] << "\"\n";
3978 if (opts.find("angle") != opts.end())
3979 os << "\trotateAngle "
3980 << opts["angle"] << '\n';
3981 if (opts.find("origin") != opts.end()) {
3983 string const opt = opts["origin"];
3984 if (opt == "tl") ss << "topleft";
3985 if (opt == "bl") ss << "bottomleft";
3986 if (opt == "Bl") ss << "baselineleft";
3987 if (opt == "c") ss << "center";
3988 if (opt == "tc") ss << "topcenter";
3989 if (opt == "bc") ss << "bottomcenter";
3990 if (opt == "Bc") ss << "baselinecenter";
3991 if (opt == "tr") ss << "topright";
3992 if (opt == "br") ss << "bottomright";
3993 if (opt == "Br") ss << "baselineright";
3994 if (!ss.str().empty())
3995 os << "\trotateOrigin " << ss.str() << '\n';
3997 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3999 if (opts.find("width") != opts.end())
4001 << translate_len(opts["width"]) << '\n';
4002 if (opts.find("height") != opts.end())
4004 << translate_len(opts["height"]) << '\n';
4005 if (opts.find("keepaspectratio") != opts.end())
4006 os << "\tkeepAspectRatio\n";
4008 context.check_layout(os);
4011 else if (t.cs() == "loadgame") {
4013 string name = normalize_filename(p.verbatim_item());
4014 string const path = getMasterFilePath();
4015 // We want to preserve relative / absolute filenames,
4016 // therefore path is only used for testing
4017 if (!makeAbsPath(name, path).exists()) {
4018 // The file extension is probably missing.
4019 // Now try to find it out.
4020 char const * const lyxskak_format[] = {"fen", 0};
4021 string const lyxskak_name =
4022 find_file(name, path, lyxskak_format);
4023 if (!lyxskak_name.empty())
4024 name = lyxskak_name;
4026 if (makeAbsPath(name, path).exists())
4027 fix_relative_filename(name);
4029 cerr << "Warning: Could not find file '"
4030 << name << "'." << endl;
4031 context.check_layout(os);
4032 begin_inset(os, "External\n\ttemplate ");
4033 os << "ChessDiagram\n\tfilename "
4036 context.check_layout(os);
4037 // after a \loadgame follows a \showboard
4038 if (p.get_token().asInput() == "showboard")
4043 // try to see whether the string is in unicodesymbols
4044 // Only use text mode commands, since we are in text mode here,
4045 // and math commands may be invalid (bug 6797)
4048 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4049 Encodings::TEXT_CMD, rem, &req);
4052 cerr << "When parsing " << t.cs()
4053 << ", result is " << to_utf8(s)
4054 << "+" << to_utf8(rem) << endl;
4055 context.check_layout(os);
4057 skip_spaces_braces(p);
4058 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
4059 preamble.registerAutomaticallyLoadedPackage(*it);
4061 //cerr << "#: " << t << " mode: " << mode << endl;
4062 // heuristic: read up to next non-nested space
4064 string s = t.asInput();
4065 string z = p.verbatim_item();
4066 while (p.good() && z != " " && z.size()) {
4067 //cerr << "read: " << z << endl;
4069 z = p.verbatim_item();
4071 cerr << "found ERT: " << s << endl;
4072 handle_ert(os, s + ' ', context);
4075 string name = t.asInput();
4076 if (p.next_token().asInput() == "*") {
4077 // Starred commands like \vspace*{}
4078 p.get_token(); // Eat '*'
4081 if (!parse_command(name, p, os, outer, context))
4082 handle_ert(os, name, context);
4086 if (flags & FLAG_LEAVE) {
4087 flags &= ~FLAG_LEAVE;