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 = removeExtension(name);
2356 //name.erase(name.length() - 4, name.length());
2357 if (!makeAbsPath(name, path).exists()) {
2358 char const * const Gnumeric_formats[] = {"gnumeric",
2360 string const Gnumeric_name =
2361 find_file(name, path, Gnumeric_formats);
2362 if (!Gnumeric_name.empty())
2363 name = Gnumeric_name;
2365 if (makeAbsPath(name, path).exists())
2366 fix_relative_filename(name);
2368 cerr << "Warning: Could not find file '"
2369 << name << "'." << endl;
2370 context.check_layout(os);
2371 begin_inset(os, "External\n\ttemplate ");
2372 os << "GnumericSpreadsheet\n\tfilename "
2375 context.check_layout(os);
2377 // register the packages that are automatically reloaded
2378 // by the Gnumeric template
2379 // Fixme: InsetExternal.cpp should give us that list
2380 preamble.registerAutomaticallyLoadedPackage("array");
2381 preamble.registerAutomaticallyLoadedPackage("calc");
2382 preamble.registerAutomaticallyLoadedPackage("color");
2383 preamble.registerAutomaticallyLoadedPackage("hhline");
2384 preamble.registerAutomaticallyLoadedPackage("ifthen");
2385 preamble.registerAutomaticallyLoadedPackage("longtable");
2386 preamble.registerAutomaticallyLoadedPackage("multirow");
2391 parse_macro(p, os, context);
2394 else if (t.cs() == "noindent") {
2396 context.add_par_extra_stuff("\\noindent\n");
2399 else if (t.cs() == "appendix") {
2400 context.add_par_extra_stuff("\\start_of_appendix\n");
2401 // We need to start a new paragraph. Otherwise the
2402 // appendix in 'bla\appendix\chapter{' would start
2404 context.new_paragraph(os);
2405 // We need to make sure that the paragraph is
2406 // generated even if it is empty. Otherwise the
2407 // appendix in '\par\appendix\par\chapter{' would
2409 context.check_layout(os);
2410 // FIXME: This is a hack to prevent paragraph
2411 // deletion if it is empty. Handle this better!
2413 "%dummy comment inserted by tex2lyx to "
2414 "ensure that this paragraph is not empty",
2416 // Both measures above may generate an additional
2417 // empty paragraph, but that does not hurt, because
2418 // whitespace does not matter here.
2419 eat_whitespace(p, os, context, true);
2422 // Must catch empty dates before findLayout is called below
2423 else if (t.cs() == "date") {
2424 string const date = p.verbatim_item();
2426 preamble.suppressDate(true);
2428 preamble.suppressDate(false);
2429 if (context.new_layout_allowed &&
2430 (newlayout = findLayout(context.textclass,
2433 output_command_layout(os, p, outer,
2434 context, newlayout);
2436 if (!title_layout_found)
2437 title_layout_found = newlayout->intitle;
2438 set<string> const & req = newlayout->requires();
2439 for (set<string>::const_iterator it = req.begin();
2440 it != req.end(); it++)
2441 preamble.registerAutomaticallyLoadedPackage(*it);
2443 handle_ert(os, "\\date{" + date + '}',
2448 // Starred section headings
2449 // Must attempt to parse "Section*" before "Section".
2450 else if ((p.next_token().asInput() == "*") &&
2451 context.new_layout_allowed &&
2452 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2455 output_command_layout(os, p, outer, context, newlayout);
2457 if (!title_layout_found)
2458 title_layout_found = newlayout->intitle;
2459 set<string> const & req = newlayout->requires();
2460 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2461 preamble.registerAutomaticallyLoadedPackage(*it);
2464 // Section headings and the like
2465 else if (context.new_layout_allowed &&
2466 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2468 output_command_layout(os, p, outer, context, newlayout);
2470 if (!title_layout_found)
2471 title_layout_found = newlayout->intitle;
2472 set<string> const & req = newlayout->requires();
2473 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2474 preamble.registerAutomaticallyLoadedPackage(*it);
2477 else if (t.cs() == "caption") {
2479 context.check_layout(os);
2481 begin_inset(os, "Caption\n");
2482 Context newcontext(true, context.textclass);
2483 newcontext.font = context.font;
2484 newcontext.check_layout(os);
2485 if (p.next_token().cat() != catEscape &&
2486 p.next_token().character() == '[') {
2487 p.get_token(); // eat '['
2488 begin_inset(os, "Argument\n");
2489 os << "status collapsed\n";
2490 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2492 eat_whitespace(p, os, context, false);
2494 parse_text(p, os, FLAG_ITEM, outer, context);
2495 context.check_end_layout(os);
2496 // We don't need really a new paragraph, but
2497 // we must make sure that the next item gets a \begin_layout.
2498 context.new_paragraph(os);
2501 newcontext.check_end_layout(os);
2504 else if (t.cs() == "subfloat") {
2505 // the syntax is \subfloat[caption]{content}
2506 // if it is a table of figure depends on the surrounding float
2507 bool has_caption = false;
2509 // do nothing if there is no outer float
2510 if (!float_type.empty()) {
2511 context.check_layout(os);
2513 begin_inset(os, "Float " + float_type + "\n");
2515 << "\nsideways false"
2516 << "\nstatus collapsed\n\n";
2519 if (p.next_token().cat() != catEscape &&
2520 p.next_token().character() == '[') {
2521 p.get_token(); // eat '['
2522 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2526 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2527 // the caption comes always as the last
2529 // we must make sure that the caption gets a \begin_layout
2530 os << "\n\\begin_layout Plain Layout";
2532 begin_inset(os, "Caption\n");
2533 Context newcontext(true, context.textclass);
2534 newcontext.font = context.font;
2535 newcontext.check_layout(os);
2536 os << caption << "\n";
2537 newcontext.check_end_layout(os);
2538 // We don't need really a new paragraph, but
2539 // we must make sure that the next item gets a \begin_layout.
2540 //newcontext.new_paragraph(os);
2544 // We don't need really a new paragraph, but
2545 // we must make sure that the next item gets a \begin_layout.
2547 context.new_paragraph(os);
2550 context.check_end_layout(os);
2551 // close the layout we opened
2553 os << "\n\\end_layout\n";
2555 // if the float type is not supported or there is no surrounding float
2558 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2559 handle_ert(os, t.asInput() + '[' + opt_arg +
2560 "]{" + p.verbatim_item() + '}', context);
2562 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2566 else if (t.cs() == "includegraphics") {
2567 bool const clip = p.next_token().asInput() == "*";
2570 string const arg = p.getArg('[', ']');
2571 map<string, string> opts;
2572 vector<string> keys;
2573 split_map(arg, opts, keys);
2575 opts["clip"] = string();
2576 string name = normalize_filename(p.verbatim_item());
2578 string const path = getMasterFilePath();
2579 // We want to preserve relative / absolute filenames,
2580 // therefore path is only used for testing
2581 if (!makeAbsPath(name, path).exists()) {
2582 // The file extension is probably missing.
2583 // Now try to find it out.
2584 string const dvips_name =
2585 find_file(name, path,
2586 known_dvips_graphics_formats);
2587 string const pdftex_name =
2588 find_file(name, path,
2589 known_pdftex_graphics_formats);
2590 if (!dvips_name.empty()) {
2591 if (!pdftex_name.empty()) {
2592 cerr << "This file contains the "
2594 "\"\\includegraphics{"
2596 "However, files\n\""
2597 << dvips_name << "\" and\n\""
2598 << pdftex_name << "\"\n"
2599 "both exist, so I had to make a "
2600 "choice and took the first one.\n"
2601 "Please move the unwanted one "
2602 "someplace else and try again\n"
2603 "if my choice was wrong."
2607 } else if (!pdftex_name.empty()) {
2613 if (makeAbsPath(name, path).exists())
2614 fix_relative_filename(name);
2616 cerr << "Warning: Could not find graphics file '"
2617 << name << "'." << endl;
2619 context.check_layout(os);
2620 begin_inset(os, "Graphics ");
2621 os << "\n\tfilename " << name << '\n';
2622 if (opts.find("width") != opts.end())
2624 << translate_len(opts["width"]) << '\n';
2625 if (opts.find("height") != opts.end())
2627 << translate_len(opts["height"]) << '\n';
2628 if (opts.find("scale") != opts.end()) {
2629 istringstream iss(opts["scale"]);
2633 os << "\tscale " << val << '\n';
2635 if (opts.find("angle") != opts.end()) {
2636 os << "\trotateAngle "
2637 << opts["angle"] << '\n';
2638 vector<string>::const_iterator a =
2639 find(keys.begin(), keys.end(), "angle");
2640 vector<string>::const_iterator s =
2641 find(keys.begin(), keys.end(), "width");
2642 if (s == keys.end())
2643 s = find(keys.begin(), keys.end(), "height");
2644 if (s == keys.end())
2645 s = find(keys.begin(), keys.end(), "scale");
2646 if (s != keys.end() && distance(s, a) > 0)
2647 os << "\tscaleBeforeRotation\n";
2649 if (opts.find("origin") != opts.end()) {
2651 string const opt = opts["origin"];
2652 if (opt.find('l') != string::npos) ss << "left";
2653 if (opt.find('r') != string::npos) ss << "right";
2654 if (opt.find('c') != string::npos) ss << "center";
2655 if (opt.find('t') != string::npos) ss << "Top";
2656 if (opt.find('b') != string::npos) ss << "Bottom";
2657 if (opt.find('B') != string::npos) ss << "Baseline";
2658 if (!ss.str().empty())
2659 os << "\trotateOrigin " << ss.str() << '\n';
2661 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2663 if (opts.find("keepaspectratio") != opts.end())
2664 os << "\tkeepAspectRatio\n";
2665 if (opts.find("clip") != opts.end())
2667 if (opts.find("draft") != opts.end())
2669 if (opts.find("bb") != opts.end())
2670 os << "\tBoundingBox "
2671 << opts["bb"] << '\n';
2672 int numberOfbbOptions = 0;
2673 if (opts.find("bbllx") != opts.end())
2674 numberOfbbOptions++;
2675 if (opts.find("bblly") != opts.end())
2676 numberOfbbOptions++;
2677 if (opts.find("bburx") != opts.end())
2678 numberOfbbOptions++;
2679 if (opts.find("bbury") != opts.end())
2680 numberOfbbOptions++;
2681 if (numberOfbbOptions == 4)
2682 os << "\tBoundingBox "
2683 << opts["bbllx"] << " " << opts["bblly"] << " "
2684 << opts["bburx"] << " " << opts["bbury"] << '\n';
2685 else if (numberOfbbOptions > 0)
2686 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2687 numberOfbbOptions = 0;
2688 if (opts.find("natwidth") != opts.end())
2689 numberOfbbOptions++;
2690 if (opts.find("natheight") != opts.end())
2691 numberOfbbOptions++;
2692 if (numberOfbbOptions == 2)
2693 os << "\tBoundingBox 0bp 0bp "
2694 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2695 else if (numberOfbbOptions > 0)
2696 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2697 ostringstream special;
2698 if (opts.find("hiresbb") != opts.end())
2699 special << "hiresbb,";
2700 if (opts.find("trim") != opts.end())
2702 if (opts.find("viewport") != opts.end())
2703 special << "viewport=" << opts["viewport"] << ',';
2704 if (opts.find("totalheight") != opts.end())
2705 special << "totalheight=" << opts["totalheight"] << ',';
2706 if (opts.find("type") != opts.end())
2707 special << "type=" << opts["type"] << ',';
2708 if (opts.find("ext") != opts.end())
2709 special << "ext=" << opts["ext"] << ',';
2710 if (opts.find("read") != opts.end())
2711 special << "read=" << opts["read"] << ',';
2712 if (opts.find("command") != opts.end())
2713 special << "command=" << opts["command"] << ',';
2714 string s_special = special.str();
2715 if (!s_special.empty()) {
2716 // We had special arguments. Remove the trailing ','.
2717 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2719 // TODO: Handle the unknown settings better.
2720 // Warn about invalid options.
2721 // Check whether some option was given twice.
2725 else if (t.cs() == "footnote" ||
2726 (t.cs() == "thanks" && context.layout->intitle)) {
2728 context.check_layout(os);
2729 begin_inset(os, "Foot\n");
2730 os << "status collapsed\n\n";
2731 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2735 else if (t.cs() == "marginpar") {
2737 context.check_layout(os);
2738 begin_inset(os, "Marginal\n");
2739 os << "status collapsed\n\n";
2740 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2744 else if (t.cs() == "ensuremath") {
2746 context.check_layout(os);
2747 string const s = p.verbatim_item();
2748 //FIXME: this never triggers in UTF8
2749 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2752 handle_ert(os, "\\ensuremath{" + s + "}",
2756 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2757 if (title_layout_found) {
2759 skip_spaces_braces(p);
2761 handle_ert(os, t.asInput(), context);
2764 else if (t.cs() == "tableofcontents") {
2765 context.check_layout(os);
2766 begin_command_inset(os, "toc", "tableofcontents");
2768 skip_spaces_braces(p);
2771 else if (t.cs() == "listoffigures") {
2772 context.check_layout(os);
2773 begin_inset(os, "FloatList figure\n");
2775 skip_spaces_braces(p);
2778 else if (t.cs() == "listoftables") {
2779 context.check_layout(os);
2780 begin_inset(os, "FloatList table\n");
2782 skip_spaces_braces(p);
2785 else if (t.cs() == "listof") {
2786 p.skip_spaces(true);
2787 string const name = p.get_token().cs();
2788 if (context.textclass.floats().typeExist(name)) {
2789 context.check_layout(os);
2790 begin_inset(os, "FloatList ");
2793 p.get_token(); // swallow second arg
2795 handle_ert(os, "\\listof{" + name + "}", context);
2798 else if ((where = is_known(t.cs(), known_text_font_families)))
2799 parse_text_attributes(p, os, FLAG_ITEM, outer,
2800 context, "\\family", context.font.family,
2801 known_coded_font_families[where - known_text_font_families]);
2803 else if ((where = is_known(t.cs(), known_text_font_series)))
2804 parse_text_attributes(p, os, FLAG_ITEM, outer,
2805 context, "\\series", context.font.series,
2806 known_coded_font_series[where - known_text_font_series]);
2808 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2809 parse_text_attributes(p, os, FLAG_ITEM, outer,
2810 context, "\\shape", context.font.shape,
2811 known_coded_font_shapes[where - known_text_font_shapes]);
2813 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2814 context.check_layout(os);
2815 TeXFont oldFont = context.font;
2816 context.font.init();
2817 context.font.size = oldFont.size;
2818 os << "\n\\family " << context.font.family << "\n";
2819 os << "\n\\series " << context.font.series << "\n";
2820 os << "\n\\shape " << context.font.shape << "\n";
2821 if (t.cs() == "textnormal") {
2822 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2823 output_font_change(os, context.font, oldFont);
2824 context.font = oldFont;
2826 eat_whitespace(p, os, context, false);
2829 else if (t.cs() == "textcolor") {
2830 // scheme is \textcolor{color name}{text}
2831 string const color = p.verbatim_item();
2832 // we only support the predefined colors of the color package
2833 if (color == "black" || color == "blue" || color == "cyan"
2834 || color == "green" || color == "magenta" || color == "red"
2835 || color == "white" || color == "yellow") {
2836 context.check_layout(os);
2837 os << "\n\\color " << color << "\n";
2838 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2839 context.check_layout(os);
2840 os << "\n\\color inherit\n";
2841 preamble.registerAutomaticallyLoadedPackage("color");
2843 // for custom defined colors
2844 handle_ert(os, t.asInput() + "{" + color + "}", context);
2847 else if (t.cs() == "underbar" || t.cs() == "uline") {
2848 // \underbar is not 100% correct (LyX outputs \uline
2849 // of ulem.sty). The difference is that \ulem allows
2850 // line breaks, and \underbar does not.
2851 // Do NOT handle \underline.
2852 // \underbar cuts through y, g, q, p etc.,
2853 // \underline does not.
2854 context.check_layout(os);
2855 os << "\n\\bar under\n";
2856 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2857 context.check_layout(os);
2858 os << "\n\\bar default\n";
2859 preamble.registerAutomaticallyLoadedPackage("ulem");
2862 else if (t.cs() == "sout") {
2863 context.check_layout(os);
2864 os << "\n\\strikeout on\n";
2865 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2866 context.check_layout(os);
2867 os << "\n\\strikeout default\n";
2868 preamble.registerAutomaticallyLoadedPackage("ulem");
2871 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2872 t.cs() == "emph" || t.cs() == "noun") {
2873 context.check_layout(os);
2874 os << "\n\\" << t.cs() << " on\n";
2875 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2876 context.check_layout(os);
2877 os << "\n\\" << t.cs() << " default\n";
2878 if (t.cs() == "uuline" || t.cs() == "uwave")
2879 preamble.registerAutomaticallyLoadedPackage("ulem");
2882 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2883 context.check_layout(os);
2884 string name = p.getArg('{', '}');
2885 string localtime = p.getArg('{', '}');
2886 preamble.registerAuthor(name);
2887 Author const & author = preamble.getAuthor(name);
2888 // from_ctime() will fail if LyX decides to output the
2889 // time in the text language. It might also use a wrong
2890 // time zone (if the original LyX document was exported
2891 // with a different time zone).
2892 time_t ptime = from_ctime(localtime);
2893 if (ptime == static_cast<time_t>(-1)) {
2894 cerr << "Warning: Could not parse time `" << localtime
2895 << "´ for change tracking, using current time instead.\n";
2896 ptime = current_time();
2898 if (t.cs() == "lyxadded")
2899 os << "\n\\change_inserted ";
2901 os << "\n\\change_deleted ";
2902 os << author.bufferId() << ' ' << ptime << '\n';
2903 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2904 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2905 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2906 LaTeXPackages::isAvailable("xcolor");
2907 // No need to test for luatex, since luatex comes in
2908 // two flavours (dvi and pdf), like latex, and those
2909 // are detected by pdflatex.
2910 if (pdflatex || xetex) {
2912 preamble.registerAutomaticallyLoadedPackage("ulem");
2913 preamble.registerAutomaticallyLoadedPackage("xcolor");
2914 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2918 preamble.registerAutomaticallyLoadedPackage("dvipost");
2919 } else if (xcolorulem) {
2920 preamble.registerAutomaticallyLoadedPackage("ulem");
2921 preamble.registerAutomaticallyLoadedPackage("xcolor");
2926 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2927 t.cs() == "vphantom") {
2928 context.check_layout(os);
2929 if (t.cs() == "phantom")
2930 begin_inset(os, "Phantom Phantom\n");
2931 if (t.cs() == "hphantom")
2932 begin_inset(os, "Phantom HPhantom\n");
2933 if (t.cs() == "vphantom")
2934 begin_inset(os, "Phantom VPhantom\n");
2935 os << "status open\n";
2936 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2941 else if (t.cs() == "href") {
2942 context.check_layout(os);
2943 string target = p.getArg('{', '}');
2944 string name = p.getArg('{', '}');
2946 size_t i = target.find(':');
2947 if (i != string::npos) {
2948 type = target.substr(0, i + 1);
2949 if (type == "mailto:" || type == "file:")
2950 target = target.substr(i + 1);
2951 // handle the case that name is equal to target, except of "http://"
2952 else if (target.substr(i + 3) == name && type == "http:")
2955 begin_command_inset(os, "href", "href");
2957 os << "name \"" << name << "\"\n";
2958 os << "target \"" << target << "\"\n";
2959 if (type == "mailto:" || type == "file:")
2960 os << "type \"" << type << "\"\n";
2962 skip_spaces_braces(p);
2965 else if (t.cs() == "lyxline") {
2966 // swallow size argument (it is not used anyway)
2968 if (!context.atParagraphStart()) {
2969 // so our line is in the middle of a paragraph
2970 // we need to add a new line, lest this line
2971 // follow the other content on that line and
2972 // run off the side of the page
2973 // FIXME: This may create an empty paragraph,
2974 // but without that it would not be
2975 // possible to set noindent below.
2976 // Fortunately LaTeX does not care
2977 // about the empty paragraph.
2978 context.new_paragraph(os);
2980 if (preamble.indentParagraphs()) {
2981 // we need to unindent, lest the line be too long
2982 context.add_par_extra_stuff("\\noindent\n");
2984 context.check_layout(os);
2985 begin_command_inset(os, "line", "rule");
2986 os << "offset \"0.5ex\"\n"
2987 "width \"100line%\"\n"
2992 else if (t.cs() == "rule") {
2993 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2994 string const width = p.getArg('{', '}');
2995 string const thickness = p.getArg('{', '}');
2996 context.check_layout(os);
2997 begin_command_inset(os, "line", "rule");
2998 if (!offset.empty())
2999 os << "offset \"" << translate_len(offset) << "\"\n";
3000 os << "width \"" << translate_len(width) << "\"\n"
3001 "height \"" << translate_len(thickness) << "\"\n";
3005 else if (is_known(t.cs(), known_phrases) ||
3006 (t.cs() == "protect" &&
3007 p.next_token().cat() == catEscape &&
3008 is_known(p.next_token().cs(), known_phrases))) {
3009 // LyX sometimes puts a \protect in front, so we have to ignore it
3010 // FIXME: This needs to be changed when bug 4752 is fixed.
3012 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3014 context.check_layout(os);
3015 os << known_coded_phrases[where - known_phrases];
3016 skip_spaces_braces(p);
3019 else if ((where = is_known(t.cs(), known_ref_commands))) {
3020 string const opt = p.getOpt();
3022 context.check_layout(os);
3023 begin_command_inset(os, "ref",
3024 known_coded_ref_commands[where - known_ref_commands]);
3025 os << "reference \""
3026 << convert_command_inset_arg(p.verbatim_item())
3029 if (t.cs() == "vref" || t.cs() == "vpageref")
3030 preamble.registerAutomaticallyLoadedPackage("varioref");
3033 // LyX does not support optional arguments of ref commands
3034 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3035 p.verbatim_item() + "}", context);
3039 else if (use_natbib &&
3040 is_known(t.cs(), known_natbib_commands) &&
3041 ((t.cs() != "citefullauthor" &&
3042 t.cs() != "citeyear" &&
3043 t.cs() != "citeyearpar") ||
3044 p.next_token().asInput() != "*")) {
3045 context.check_layout(os);
3046 string command = t.cs();
3047 if (p.next_token().asInput() == "*") {
3051 if (command == "citefullauthor")
3052 // alternative name for "\\citeauthor*"
3053 command = "citeauthor*";
3055 // text before the citation
3057 // text after the citation
3059 get_cite_arguments(p, true, before, after);
3061 if (command == "cite") {
3062 // \cite without optional argument means
3063 // \citet, \cite with at least one optional
3064 // argument means \citep.
3065 if (before.empty() && after.empty())
3070 if (before.empty() && after == "[]")
3071 // avoid \citet[]{a}
3073 else if (before == "[]" && after == "[]") {
3074 // avoid \citet[][]{a}
3078 // remove the brackets around after and before
3079 if (!after.empty()) {
3081 after.erase(after.length() - 1, 1);
3082 after = convert_command_inset_arg(after);
3084 if (!before.empty()) {
3086 before.erase(before.length() - 1, 1);
3087 before = convert_command_inset_arg(before);
3089 begin_command_inset(os, "citation", command);
3090 os << "after " << '"' << after << '"' << "\n";
3091 os << "before " << '"' << before << '"' << "\n";
3093 << convert_command_inset_arg(p.verbatim_item())
3098 else if (use_jurabib &&
3099 is_known(t.cs(), known_jurabib_commands) &&
3100 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3101 context.check_layout(os);
3102 string command = t.cs();
3103 if (p.next_token().asInput() == "*") {
3107 char argumentOrder = '\0';
3108 vector<string> const options =
3109 preamble.getPackageOptions("jurabib");
3110 if (find(options.begin(), options.end(),
3111 "natbiborder") != options.end())
3112 argumentOrder = 'n';
3113 else if (find(options.begin(), options.end(),
3114 "jurabiborder") != options.end())
3115 argumentOrder = 'j';
3117 // text before the citation
3119 // text after the citation
3121 get_cite_arguments(p, argumentOrder != 'j', before, after);
3123 string const citation = p.verbatim_item();
3124 if (!before.empty() && argumentOrder == '\0') {
3125 cerr << "Warning: Assuming argument order "
3126 "of jurabib version 0.6 for\n'"
3127 << command << before << after << '{'
3128 << citation << "}'.\n"
3129 "Add 'jurabiborder' to the jurabib "
3130 "package options if you used an\n"
3131 "earlier jurabib version." << endl;
3133 if (!after.empty()) {
3135 after.erase(after.length() - 1, 1);
3137 if (!before.empty()) {
3139 before.erase(before.length() - 1, 1);
3141 begin_command_inset(os, "citation", command);
3142 os << "after " << '"' << after << '"' << "\n";
3143 os << "before " << '"' << before << '"' << "\n";
3144 os << "key " << '"' << citation << '"' << "\n";
3148 else if (t.cs() == "cite"
3149 || t.cs() == "nocite") {
3150 context.check_layout(os);
3151 string after = convert_command_inset_arg(p.getArg('[', ']'));
3152 string key = convert_command_inset_arg(p.verbatim_item());
3153 // store the case that it is "\nocite{*}" to use it later for
3156 begin_command_inset(os, "citation", t.cs());
3157 os << "after " << '"' << after << '"' << "\n";
3158 os << "key " << '"' << key << '"' << "\n";
3160 } else if (t.cs() == "nocite")
3164 else if (t.cs() == "index") {
3165 context.check_layout(os);
3166 begin_inset(os, "Index idx\n");
3167 os << "status collapsed\n";
3168 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3172 else if (t.cs() == "nomenclature") {
3173 context.check_layout(os);
3174 begin_command_inset(os, "nomenclature", "nomenclature");
3175 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3176 if (!prefix.empty())
3177 os << "prefix " << '"' << prefix << '"' << "\n";
3178 os << "symbol " << '"'
3179 << convert_command_inset_arg(p.verbatim_item());
3180 os << "\"\ndescription \""
3181 << convert_command_inset_arg(p.verbatim_item())
3184 preamble.registerAutomaticallyLoadedPackage("nomencl");
3187 else if (t.cs() == "label") {
3188 context.check_layout(os);
3189 begin_command_inset(os, "label", "label");
3191 << convert_command_inset_arg(p.verbatim_item())
3196 else if (t.cs() == "printindex") {
3197 context.check_layout(os);
3198 begin_command_inset(os, "index_print", "printindex");
3199 os << "type \"idx\"\n";
3201 skip_spaces_braces(p);
3202 preamble.registerAutomaticallyLoadedPackage("makeidx");
3203 if (preamble.use_indices() == "true")
3204 preamble.registerAutomaticallyLoadedPackage("splitidx");
3207 else if (t.cs() == "printnomenclature") {
3209 string width_type = "";
3210 context.check_layout(os);
3211 begin_command_inset(os, "nomencl_print", "printnomenclature");
3212 // case of a custom width
3214 width = p.getArg('[', ']');
3215 width = translate_len(width);
3216 width_type = "custom";
3218 // case of no custom width
3219 // the case of no custom width but the width set
3220 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3221 // because the user could have set anything, not only the width
3222 // of the longest label (which would be width_type = "auto")
3223 string label = convert_command_inset_arg(p.getArg('{', '}'));
3224 if (label.empty() && width_type.empty())
3225 width_type = "none";
3226 os << "set_width \"" << width_type << "\"\n";
3227 if (width_type == "custom")
3228 os << "width \"" << width << '\"';
3230 skip_spaces_braces(p);
3231 preamble.registerAutomaticallyLoadedPackage("nomencl");
3234 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3235 context.check_layout(os);
3236 begin_inset(os, "script ");
3237 os << t.cs().substr(4) << '\n';
3238 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3240 if (t.cs() == "textsubscript")
3241 preamble.registerAutomaticallyLoadedPackage("subscript");
3244 else if ((where = is_known(t.cs(), known_quotes))) {
3245 context.check_layout(os);
3246 begin_inset(os, "Quotes ");
3247 os << known_coded_quotes[where - known_quotes];
3249 // LyX adds {} after the quote, so we have to eat
3250 // spaces here if there are any before a possible
3252 eat_whitespace(p, os, context, false);
3256 else if ((where = is_known(t.cs(), known_sizes)) &&
3257 context.new_layout_allowed) {
3258 context.check_layout(os);
3259 TeXFont const oldFont = context.font;
3260 context.font.size = known_coded_sizes[where - known_sizes];
3261 output_font_change(os, oldFont, context.font);
3262 eat_whitespace(p, os, context, false);
3265 else if ((where = is_known(t.cs(), known_font_families)) &&
3266 context.new_layout_allowed) {
3267 context.check_layout(os);
3268 TeXFont const oldFont = context.font;
3269 context.font.family =
3270 known_coded_font_families[where - known_font_families];
3271 output_font_change(os, oldFont, context.font);
3272 eat_whitespace(p, os, context, false);
3275 else if ((where = is_known(t.cs(), known_font_series)) &&
3276 context.new_layout_allowed) {
3277 context.check_layout(os);
3278 TeXFont const oldFont = context.font;
3279 context.font.series =
3280 known_coded_font_series[where - known_font_series];
3281 output_font_change(os, oldFont, context.font);
3282 eat_whitespace(p, os, context, false);
3285 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3286 context.new_layout_allowed) {
3287 context.check_layout(os);
3288 TeXFont const oldFont = context.font;
3289 context.font.shape =
3290 known_coded_font_shapes[where - known_font_shapes];
3291 output_font_change(os, oldFont, context.font);
3292 eat_whitespace(p, os, context, false);
3294 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3295 context.new_layout_allowed) {
3296 context.check_layout(os);
3297 TeXFont const oldFont = context.font;
3298 context.font.init();
3299 context.font.size = oldFont.size;
3300 context.font.family =
3301 known_coded_font_families[where - known_old_font_families];
3302 output_font_change(os, oldFont, context.font);
3303 eat_whitespace(p, os, context, false);
3306 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3307 context.new_layout_allowed) {
3308 context.check_layout(os);
3309 TeXFont const oldFont = context.font;
3310 context.font.init();
3311 context.font.size = oldFont.size;
3312 context.font.series =
3313 known_coded_font_series[where - known_old_font_series];
3314 output_font_change(os, oldFont, context.font);
3315 eat_whitespace(p, os, context, false);
3318 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3319 context.new_layout_allowed) {
3320 context.check_layout(os);
3321 TeXFont const oldFont = context.font;
3322 context.font.init();
3323 context.font.size = oldFont.size;
3324 context.font.shape =
3325 known_coded_font_shapes[where - known_old_font_shapes];
3326 output_font_change(os, oldFont, context.font);
3327 eat_whitespace(p, os, context, false);
3330 else if (t.cs() == "selectlanguage") {
3331 context.check_layout(os);
3332 // save the language for the case that a
3333 // \foreignlanguage is used
3335 context.font.language = babel2lyx(p.verbatim_item());
3336 os << "\n\\lang " << context.font.language << "\n";
3339 else if (t.cs() == "foreignlanguage") {
3340 string const lang = babel2lyx(p.verbatim_item());
3341 parse_text_attributes(p, os, FLAG_ITEM, outer,
3343 context.font.language, lang);
3346 else if (t.cs() == "inputencoding") {
3347 // nothing to write here
3348 string const enc = subst(p.verbatim_item(), "\n", " ");
3352 else if ((where = is_known(t.cs(), known_special_chars))) {
3353 context.check_layout(os);
3354 os << "\\SpecialChar \\"
3355 << known_coded_special_chars[where - known_special_chars]
3357 skip_spaces_braces(p);
3360 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3361 context.check_layout(os);
3362 os << "\\SpecialChar \\nobreakdash-\n";
3366 else if (t.cs() == "textquotedbl") {
3367 context.check_layout(os);
3372 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3373 context.check_layout(os);
3374 os << "\\SpecialChar \\@.\n";
3378 else if (t.cs() == "-") {
3379 context.check_layout(os);
3380 os << "\\SpecialChar \\-\n";
3383 else if (t.cs() == "textasciitilde") {
3384 context.check_layout(os);
3386 skip_spaces_braces(p);
3389 else if (t.cs() == "textasciicircum") {
3390 context.check_layout(os);
3392 skip_spaces_braces(p);
3395 else if (t.cs() == "textbackslash") {
3396 context.check_layout(os);
3397 os << "\n\\backslash\n";
3398 skip_spaces_braces(p);
3401 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3402 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3404 context.check_layout(os);
3408 else if (t.cs() == "char") {
3409 context.check_layout(os);
3410 if (p.next_token().character() == '`') {
3412 if (p.next_token().cs() == "\"") {
3417 handle_ert(os, "\\char`", context);
3420 handle_ert(os, "\\char", context);
3424 else if (t.cs() == "verb") {
3425 context.check_layout(os);
3426 char const delimiter = p.next_token().character();
3427 string const arg = p.getArg(delimiter, delimiter);
3429 oss << "\\verb" << delimiter << arg << delimiter;
3430 handle_ert(os, oss.str(), context);
3433 // Problem: \= creates a tabstop inside the tabbing environment
3434 // and else an accent. In the latter case we really would want
3435 // \={o} instead of \= o.
3436 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3437 handle_ert(os, t.asInput(), context);
3439 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3440 else if (t.cs().size() == 1
3441 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3442 context.check_layout(os);
3443 // try to see whether the string is in unicodesymbols
3445 string command = t.asInput() + "{"
3446 + trimSpaceAndEol(p.verbatim_item())
3449 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3450 Encodings::TEXT_CMD | Encodings::MATH_CMD, rem, &req);
3453 cerr << "When parsing " << command
3454 << ", result is " << to_utf8(s)
3455 << "+" << to_utf8(rem) << endl;
3457 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
3458 preamble.registerAutomaticallyLoadedPackage(*it);
3460 // we did not find a non-ert version
3461 handle_ert(os, command, context);
3464 else if (t.cs() == "\\") {
3465 context.check_layout(os);
3467 handle_ert(os, "\\\\" + p.getOpt(), context);
3468 else if (p.next_token().asInput() == "*") {
3470 // getOpt() eats the following space if there
3471 // is no optional argument, but that is OK
3472 // here since it has no effect in the output.
3473 handle_ert(os, "\\\\*" + p.getOpt(), context);
3476 begin_inset(os, "Newline newline");
3481 else if (t.cs() == "newline" ||
3482 (t.cs() == "linebreak" && !p.hasOpt())) {
3483 context.check_layout(os);
3484 begin_inset(os, "Newline ");
3487 skip_spaces_braces(p);
3490 else if (t.cs() == "input" || t.cs() == "include"
3491 || t.cs() == "verbatiminput") {
3492 string name = t.cs();
3493 if (t.cs() == "verbatiminput"
3494 && p.next_token().asInput() == "*")
3495 name += p.get_token().asInput();
3496 context.check_layout(os);
3497 string filename(normalize_filename(p.getArg('{', '}')));
3498 string const path = getMasterFilePath();
3499 // We want to preserve relative / absolute filenames,
3500 // therefore path is only used for testing
3501 if ((t.cs() == "include" || t.cs() == "input") &&
3502 !makeAbsPath(filename, path).exists()) {
3503 // The file extension is probably missing.
3504 // Now try to find it out.
3505 string const tex_name =
3506 find_file(filename, path,
3507 known_tex_extensions);
3508 if (!tex_name.empty())
3509 filename = tex_name;
3511 bool external = false;
3513 if (makeAbsPath(filename, path).exists()) {
3514 string const abstexname =
3515 makeAbsPath(filename, path).absFileName();
3516 string const abslyxname =
3517 changeExtension(abstexname, ".lyx");
3518 string const absfigname =
3519 changeExtension(abstexname, ".fig");
3520 fix_relative_filename(filename);
3521 string const lyxname =
3522 changeExtension(filename, ".lyx");
3524 external = FileName(absfigname).exists();
3525 if (t.cs() == "input") {
3526 string const ext = getExtension(abstexname);
3528 // Combined PS/LaTeX:
3529 // x.eps, x.pstex_t (old xfig)
3530 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3531 FileName const absepsname(
3532 changeExtension(abstexname, ".eps"));
3533 FileName const abspstexname(
3534 changeExtension(abstexname, ".pstex"));
3535 bool const xfigeps =
3536 (absepsname.exists() ||
3537 abspstexname.exists()) &&
3540 // Combined PDF/LaTeX:
3541 // x.pdf, x.pdftex_t (old xfig)
3542 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3543 FileName const abspdfname(
3544 changeExtension(abstexname, ".pdf"));
3545 bool const xfigpdf =
3546 abspdfname.exists() &&
3547 (ext == "pdftex_t" || ext == "pdf_t");
3551 // Combined PS/PDF/LaTeX:
3552 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3553 string const absbase2(
3554 removeExtension(abstexname) + "_pspdftex");
3555 FileName const abseps2name(
3556 addExtension(absbase2, ".eps"));
3557 FileName const abspdf2name(
3558 addExtension(absbase2, ".pdf"));
3559 bool const xfigboth =
3560 abspdf2name.exists() &&
3561 abseps2name.exists() && ext == "pspdftex";
3563 xfig = xfigpdf || xfigeps || xfigboth;
3564 external = external && xfig;
3567 outname = changeExtension(filename, ".fig");
3569 // Don't try to convert, the result
3570 // would be full of ERT.
3572 } else if (t.cs() != "verbatiminput" &&
3573 tex2lyx(abstexname, FileName(abslyxname),
3580 cerr << "Warning: Could not find included file '"
3581 << filename << "'." << endl;
3585 begin_inset(os, "External\n");
3586 os << "\ttemplate XFig\n"
3587 << "\tfilename " << outname << '\n';
3589 begin_command_inset(os, "include", name);
3590 os << "preview false\n"
3591 "filename \"" << outname << "\"\n";
3592 if (t.cs() == "verbatiminput")
3593 preamble.registerAutomaticallyLoadedPackage("verbatim");
3598 else if (t.cs() == "bibliographystyle") {
3599 // store new bibliographystyle
3600 bibliographystyle = p.verbatim_item();
3601 // If any other command than \bibliography and
3602 // \nocite{*} follows, we need to output the style
3603 // (because it might be used by that command).
3604 // Otherwise, it will automatically be output by LyX.
3607 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3608 if (t2.cat() == catBegin)
3610 if (t2.cat() != catEscape)
3612 if (t2.cs() == "nocite") {
3613 if (p.getArg('{', '}') == "*")
3615 } else if (t2.cs() == "bibliography")
3622 "\\bibliographystyle{" + bibliographystyle + '}',
3627 else if (t.cs() == "bibliography") {
3628 context.check_layout(os);
3629 begin_command_inset(os, "bibtex", "bibtex");
3630 if (!btprint.empty()) {
3631 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3632 // clear the string because the next BibTeX inset can be without the
3633 // \nocite{*} option
3636 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3637 // Do we have a bibliographystyle set?
3638 if (!bibliographystyle.empty())
3639 os << "options " << '"' << bibliographystyle << '"' << "\n";
3643 else if (t.cs() == "parbox") {
3644 // Test whether this is an outer box of a shaded box
3646 // swallow arguments
3647 while (p.hasOpt()) {
3649 p.skip_spaces(true);
3652 p.skip_spaces(true);
3654 if (p.next_token().cat() == catBegin)
3656 p.skip_spaces(true);
3657 Token to = p.get_token();
3658 bool shaded = false;
3659 if (to.asInput() == "\\begin") {
3660 p.skip_spaces(true);
3661 if (p.getArg('{', '}') == "shaded")
3666 parse_outer_box(p, os, FLAG_ITEM, outer,
3667 context, "parbox", "shaded");
3669 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3673 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3674 t.cs() == "shadowbox" || t.cs() == "doublebox")
3675 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3677 else if (t.cs() == "framebox") {
3678 if (p.next_token().character() == '(') {
3679 //the syntax is: \framebox(x,y)[position]{content}
3680 string arg = t.asInput();
3681 arg += p.getFullParentheseArg();
3682 arg += p.getFullOpt();
3683 eat_whitespace(p, os, context, false);
3684 handle_ert(os, arg + '{', context);
3685 eat_whitespace(p, os, context, false);
3686 parse_text(p, os, FLAG_ITEM, outer, context);
3687 handle_ert(os, "}", context);
3689 string special = p.getFullOpt();
3690 special += p.getOpt();
3691 parse_outer_box(p, os, FLAG_ITEM, outer,
3692 context, t.cs(), special);
3696 //\makebox() is part of the picture environment and different from \makebox{}
3697 //\makebox{} will be parsed by parse_box
3698 else if (t.cs() == "makebox") {
3699 if (p.next_token().character() == '(') {
3700 //the syntax is: \makebox(x,y)[position]{content}
3701 string arg = t.asInput();
3702 arg += p.getFullParentheseArg();
3703 arg += p.getFullOpt();
3704 eat_whitespace(p, os, context, false);
3705 handle_ert(os, arg + '{', context);
3706 eat_whitespace(p, os, context, false);
3707 parse_text(p, os, FLAG_ITEM, outer, context);
3708 handle_ert(os, "}", context);
3710 //the syntax is: \makebox[width][position]{content}
3711 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3715 else if (t.cs() == "smallskip" ||
3716 t.cs() == "medskip" ||
3717 t.cs() == "bigskip" ||
3718 t.cs() == "vfill") {
3719 context.check_layout(os);
3720 begin_inset(os, "VSpace ");
3723 skip_spaces_braces(p);
3726 else if ((where = is_known(t.cs(), known_spaces))) {
3727 context.check_layout(os);
3728 begin_inset(os, "space ");
3729 os << '\\' << known_coded_spaces[where - known_spaces]
3732 // LaTeX swallows whitespace after all spaces except
3733 // "\\,". We have to do that here, too, because LyX
3734 // adds "{}" which would make the spaces significant.
3736 eat_whitespace(p, os, context, false);
3737 // LyX adds "{}" after all spaces except "\\ " and
3738 // "\\,", so we have to remove "{}".
3739 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3740 // remove the braces after "\\,", too.
3745 else if (t.cs() == "newpage" ||
3746 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3747 t.cs() == "clearpage" ||
3748 t.cs() == "cleardoublepage") {
3749 context.check_layout(os);
3750 begin_inset(os, "Newpage ");
3753 skip_spaces_braces(p);
3756 else if (t.cs() == "DeclareRobustCommand" ||
3757 t.cs() == "DeclareRobustCommandx" ||
3758 t.cs() == "newcommand" ||
3759 t.cs() == "newcommandx" ||
3760 t.cs() == "providecommand" ||
3761 t.cs() == "providecommandx" ||
3762 t.cs() == "renewcommand" ||
3763 t.cs() == "renewcommandx") {
3764 // DeclareRobustCommand, DeclareRobustCommandx,
3765 // providecommand and providecommandx could be handled
3766 // by parse_command(), but we need to call
3767 // add_known_command() here.
3768 string name = t.asInput();
3769 if (p.next_token().asInput() == "*") {
3770 // Starred form. Eat '*'
3774 string const command = p.verbatim_item();
3775 string const opt1 = p.getFullOpt();
3776 string const opt2 = p.getFullOpt();
3777 add_known_command(command, opt1, !opt2.empty());
3778 string const ert = name + '{' + command + '}' +
3780 '{' + p.verbatim_item() + '}';
3782 if (t.cs() == "DeclareRobustCommand" ||
3783 t.cs() == "DeclareRobustCommandx" ||
3784 t.cs() == "providecommand" ||
3785 t.cs() == "providecommandx" ||
3786 name[name.length()-1] == '*')
3787 handle_ert(os, ert, context);
3789 context.check_layout(os);
3790 begin_inset(os, "FormulaMacro");
3796 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3797 // let could be handled by parse_command(),
3798 // but we need to call add_known_command() here.
3799 string ert = t.asInput();
3802 if (p.next_token().cat() == catBegin) {
3803 name = p.verbatim_item();
3804 ert += '{' + name + '}';
3806 name = p.verbatim_item();
3811 if (p.next_token().cat() == catBegin) {
3812 command = p.verbatim_item();
3813 ert += '{' + command + '}';
3815 command = p.verbatim_item();
3818 // If command is known, make name known too, to parse
3819 // its arguments correctly. For this reason we also
3820 // have commands in syntax.default that are hardcoded.
3821 CommandMap::iterator it = known_commands.find(command);
3822 if (it != known_commands.end())
3823 known_commands[t.asInput()] = it->second;
3824 handle_ert(os, ert, context);
3827 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3828 bool starred = false;
3829 if (p.next_token().asInput() == "*") {
3833 string name = t.asInput();
3834 string const length = p.verbatim_item();
3837 bool valid = splitLatexLength(length, valstring, unit);
3838 bool known_hspace = false;
3839 bool known_vspace = false;
3840 bool known_unit = false;
3843 istringstream iss(valstring);
3846 if (t.cs()[0] == 'h') {
3847 if (unit == "\\fill") {
3852 known_hspace = true;
3855 if (unit == "\\smallskipamount") {
3857 known_vspace = true;
3858 } else if (unit == "\\medskipamount") {
3860 known_vspace = true;
3861 } else if (unit == "\\bigskipamount") {
3863 known_vspace = true;
3864 } else if (unit == "\\fill") {
3866 known_vspace = true;
3870 if (!known_hspace && !known_vspace) {
3871 switch (unitFromString(unit)) {
3892 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3893 // Literal horizontal length or known variable
3894 context.check_layout(os);
3895 begin_inset(os, "space ");
3903 if (known_unit && !known_hspace)
3905 << translate_len(length);
3907 } else if (known_unit || known_vspace) {
3908 // Literal vertical length or known variable
3909 context.check_layout(os);
3910 begin_inset(os, "VSpace ");
3918 // LyX can't handle other length variables in Inset VSpace/space
3923 handle_ert(os, name + '{' + unit + '}', context);
3924 else if (value == -1.0)
3925 handle_ert(os, name + "{-" + unit + '}', context);
3927 handle_ert(os, name + '{' + valstring + unit + '}', context);
3929 handle_ert(os, name + '{' + length + '}', context);
3933 // The single '=' is meant here.
3934 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3936 context.check_layout(os);
3937 begin_inset(os, "Flex ");
3938 os << to_utf8(newinsetlayout->name()) << '\n'
3939 << "status collapsed\n";
3940 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3944 else if (t.cs() == "includepdf") {
3946 string const arg = p.getArg('[', ']');
3947 map<string, string> opts;
3948 vector<string> keys;
3949 split_map(arg, opts, keys);
3950 string name = normalize_filename(p.verbatim_item());
3951 string const path = getMasterFilePath();
3952 // We want to preserve relative / absolute filenames,
3953 // therefore path is only used for testing
3954 if (!makeAbsPath(name, path).exists()) {
3955 // The file extension is probably missing.
3956 // Now try to find it out.
3957 char const * const pdfpages_format[] = {"pdf", 0};
3958 string const pdftex_name =
3959 find_file(name, path, pdfpages_format);
3960 if (!pdftex_name.empty()) {
3965 if (makeAbsPath(name, path).exists())
3966 fix_relative_filename(name);
3968 cerr << "Warning: Could not find file '"
3969 << name << "'." << endl;
3971 context.check_layout(os);
3972 begin_inset(os, "External\n\ttemplate ");
3973 os << "PDFPages\n\tfilename "
3975 // parse the options
3976 if (opts.find("pages") != opts.end())
3977 os << "\textra LaTeX \"pages="
3978 << opts["pages"] << "\"\n";
3979 if (opts.find("angle") != opts.end())
3980 os << "\trotateAngle "
3981 << opts["angle"] << '\n';
3982 if (opts.find("origin") != opts.end()) {
3984 string const opt = opts["origin"];
3985 if (opt == "tl") ss << "topleft";
3986 if (opt == "bl") ss << "bottomleft";
3987 if (opt == "Bl") ss << "baselineleft";
3988 if (opt == "c") ss << "center";
3989 if (opt == "tc") ss << "topcenter";
3990 if (opt == "bc") ss << "bottomcenter";
3991 if (opt == "Bc") ss << "baselinecenter";
3992 if (opt == "tr") ss << "topright";
3993 if (opt == "br") ss << "bottomright";
3994 if (opt == "Br") ss << "baselineright";
3995 if (!ss.str().empty())
3996 os << "\trotateOrigin " << ss.str() << '\n';
3998 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4000 if (opts.find("width") != opts.end())
4002 << translate_len(opts["width"]) << '\n';
4003 if (opts.find("height") != opts.end())
4005 << translate_len(opts["height"]) << '\n';
4006 if (opts.find("keepaspectratio") != opts.end())
4007 os << "\tkeepAspectRatio\n";
4009 context.check_layout(os);
4012 else if (t.cs() == "loadgame") {
4014 string name = normalize_filename(p.verbatim_item());
4015 string const path = getMasterFilePath();
4016 // We want to preserve relative / absolute filenames,
4017 // therefore path is only used for testing
4018 if (!makeAbsPath(name, path).exists()) {
4019 // The file extension is probably missing.
4020 // Now try to find it out.
4021 char const * const lyxskak_format[] = {"fen", 0};
4022 string const lyxskak_name =
4023 find_file(name, path, lyxskak_format);
4024 if (!lyxskak_name.empty())
4025 name = lyxskak_name;
4027 if (makeAbsPath(name, path).exists())
4028 fix_relative_filename(name);
4030 cerr << "Warning: Could not find file '"
4031 << name << "'." << endl;
4032 context.check_layout(os);
4033 begin_inset(os, "External\n\ttemplate ");
4034 os << "ChessDiagram\n\tfilename "
4037 context.check_layout(os);
4038 // after a \loadgame follows a \showboard
4039 if (p.get_token().asInput() == "showboard")
4044 // try to see whether the string is in unicodesymbols
4045 // Only use text mode commands, since we are in text mode here,
4046 // and math commands may be invalid (bug 6797)
4049 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4050 Encodings::TEXT_CMD, rem, &req);
4053 cerr << "When parsing " << t.cs()
4054 << ", result is " << to_utf8(s)
4055 << "+" << to_utf8(rem) << endl;
4056 context.check_layout(os);
4058 skip_spaces_braces(p);
4059 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
4060 preamble.registerAutomaticallyLoadedPackage(*it);
4062 //cerr << "#: " << t << " mode: " << mode << endl;
4063 // heuristic: read up to next non-nested space
4065 string s = t.asInput();
4066 string z = p.verbatim_item();
4067 while (p.good() && z != " " && z.size()) {
4068 //cerr << "read: " << z << endl;
4070 z = p.verbatim_item();
4072 cerr << "found ERT: " << s << endl;
4073 handle_ert(os, s + ' ', context);
4076 string name = t.asInput();
4077 if (p.next_token().asInput() == "*") {
4078 // Starred commands like \vspace*{}
4079 p.get_token(); // Eat '*'
4082 if (!parse_command(name, p, os, outer, context))
4083 handle_ert(os, name, context);
4087 if (flags & FLAG_LEAVE) {
4088 flags &= ~FLAG_LEAVE;