2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
48 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
49 Context const & context, InsetLayout const * layout)
51 bool const forcePlainLayout =
52 layout ? layout->forcePlainLayout() : false;
53 Context newcontext(true, context.textclass);
55 newcontext.layout = &context.textclass.plainLayout();
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context const & context, string const & name)
68 InsetLayout const * layout = 0;
69 DocumentClass::InsetLayouts::const_iterator it =
70 context.textclass.insetLayouts().find(from_ascii(name));
71 if (it != context.textclass.insetLayouts().end())
72 layout = &(it->second);
73 parse_text_in_inset(p, os, flags, outer, context, layout);
76 /// parses a paragraph snippet, useful for example for \\emph{...}
77 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context newcontext(context);
81 // Don't inherit the paragraph-level extra stuff
82 newcontext.par_extra_stuff.clear();
83 parse_text(p, os, flags, outer, newcontext);
84 // Make sure that we don't create invalid .lyx files
85 context.need_layout = newcontext.need_layout;
86 context.need_end_layout = newcontext.need_end_layout;
91 * Thin wrapper around parse_text_snippet() using a string.
93 * We completely ignore \c context.need_layout and \c context.need_end_layout,
94 * because our return value is not used directly (otherwise the stream version
95 * of parse_text_snippet() could be used). That means that the caller needs
96 * to do layout management manually.
97 * This is intended to parse text that does not create any layout changes.
99 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
102 Context newcontext(context);
103 newcontext.need_layout = false;
104 newcontext.need_end_layout = false;
105 newcontext.new_layout_allowed = false;
106 // Avoid warning by Context::~Context()
107 newcontext.par_extra_stuff.clear();
109 parse_text_snippet(p, os, flags, outer, newcontext);
114 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
115 "vpageref", "prettyref", "eqref", 0 };
117 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
118 "vpageref", "formatted", "eqref", 0 };
122 * The starred forms are also known except for "citefullauthor",
123 * "citeyear" and "citeyearpar".
125 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
131 * No starred form other than "cite*" known.
133 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
134 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
135 // jurabib commands not (yet) supported by LyX:
137 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
138 // "footciteauthor", "footciteyear", "footciteyearpar",
139 "citefield", "citetitle", 0 };
141 /// LaTeX names for quotes
142 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
143 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
144 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
145 "guilsinglleft", "frq", "guilsinglright", 0};
147 /// the same as known_quotes with .lyx names
148 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
149 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
150 "gld", "grd", "gls", "ers", "fls",
151 "fls", "frs", "frs", 0};
153 /// LaTeX names for font sizes
154 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
155 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
157 /// the same as known_sizes with .lyx names
158 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
159 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
161 /// LaTeX 2.09 names for font families
162 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
164 /// LaTeX names for font families
165 char const * const known_font_families[] = { "rmfamily", "sffamily",
168 /// LaTeX names for font family changing commands
169 char const * const known_text_font_families[] = { "textrm", "textsf",
172 /// The same as known_old_font_families, known_font_families and
173 /// known_text_font_families with .lyx names
174 char const * const known_coded_font_families[] = { "roman", "sans",
177 /// LaTeX 2.09 names for font series
178 char const * const known_old_font_series[] = { "bf", 0};
180 /// LaTeX names for font series
181 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
183 /// LaTeX names for font series changing commands
184 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
186 /// The same as known_old_font_series, known_font_series and
187 /// known_text_font_series with .lyx names
188 char const * const known_coded_font_series[] = { "bold", "medium", 0};
190 /// LaTeX 2.09 names for font shapes
191 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
193 /// LaTeX names for font shapes
194 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
197 /// LaTeX names for font shape changing commands
198 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
201 /// The same as known_old_font_shapes, known_font_shapes and
202 /// known_text_font_shapes with .lyx names
203 char const * const known_coded_font_shapes[] = { "italic", "slanted",
204 "smallcaps", "up", 0};
206 /// Known special characters which need skip_spaces_braces() afterwards
207 char const * const known_special_chars[] = {"ldots", "lyxarrow",
208 "textcompwordmark", "slash", 0};
210 /// the same as known_special_chars with .lyx names
211 char const * const known_coded_special_chars[] = {"ldots{}", "menuseparator",
212 "textcompwordmark{}", "slash{}", 0};
215 * Graphics file extensions known by the dvips driver of the graphics package.
216 * These extensions are used to complete the filename of an included
217 * graphics file if it does not contain an extension.
218 * The order must be the same that latex uses to find a file, because we
219 * will use the first extension that matches.
220 * This is only an approximation for the common cases. If we would want to
221 * do it right in all cases, we would need to know which graphics driver is
222 * used and know the extensions of every driver of the graphics package.
224 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
225 "ps.gz", "eps.Z", "ps.Z", 0};
228 * Graphics file extensions known by the pdftex driver of the graphics package.
229 * \sa known_dvips_graphics_formats
231 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
235 * Known file extensions for TeX files as used by \\include.
237 char const * const known_tex_extensions[] = {"tex", 0};
239 /// spaces known by InsetSpace
240 char const * const known_spaces[] = { " ", "space", ",",
241 "thinspace", "quad", "qquad", "enspace", "enskip",
242 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
243 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
244 "upbracefill", "downbracefill", 0};
246 /// the same as known_spaces with .lyx names
247 char const * const known_coded_spaces[] = { "space{}", "space{}",
248 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
249 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
250 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
251 "upbracefill{}", "downbracefill{}", 0};
253 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
254 /// them in ERT. "LaTeXe" must come before "LaTeX"!
255 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
256 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
257 int const known_phrase_lengths[] = {3, 5, 7, 0};
259 // string to store the float type to be able to determine the type of subfloats
260 string float_type = "";
263 /// splits "x=z, y=b" into a map and an ordered keyword vector
264 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
269 keys.resize(v.size());
270 for (size_t i = 0; i < v.size(); ++i) {
271 size_t const pos = v[i].find('=');
272 string const index = trimSpaceAndEol(v[i].substr(0, pos));
273 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
281 * Split a LaTeX length into value and unit.
282 * The latter can be a real unit like "pt", or a latex length variable
283 * like "\textwidth". The unit may contain additional stuff like glue
284 * lengths, but we don't care, because such lengths are ERT anyway.
285 * \returns true if \p value and \p unit are valid.
287 bool splitLatexLength(string const & len, string & value, string & unit)
291 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
292 //'4,5' is a valid LaTeX length number. Change it to '4.5'
293 string const length = subst(len, ',', '.');
294 if (i == string::npos)
297 if (len[0] == '\\') {
298 // We had something like \textwidth without a factor
304 value = trimSpaceAndEol(string(length, 0, i));
308 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
309 if (contains(len, '\\'))
310 unit = trimSpaceAndEol(string(len, i));
312 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
317 /// A simple function to translate a latex length to something LyX can
318 /// understand. Not perfect, but rather best-effort.
319 bool translate_len(string const & length, string & valstring, string & unit)
321 if (!splitLatexLength(length, valstring, unit))
323 // LyX uses percent values
325 istringstream iss(valstring);
330 string const percentval = oss.str();
332 if (unit.empty() || unit[0] != '\\')
334 string::size_type const i = unit.find(' ');
335 string const endlen = (i == string::npos) ? string() : string(unit, i);
336 if (unit == "\\textwidth") {
337 valstring = percentval;
338 unit = "text%" + endlen;
339 } else if (unit == "\\columnwidth") {
340 valstring = percentval;
341 unit = "col%" + endlen;
342 } else if (unit == "\\paperwidth") {
343 valstring = percentval;
344 unit = "page%" + endlen;
345 } else if (unit == "\\linewidth") {
346 valstring = percentval;
347 unit = "line%" + endlen;
348 } else if (unit == "\\paperheight") {
349 valstring = percentval;
350 unit = "pheight%" + endlen;
351 } else if (unit == "\\textheight") {
352 valstring = percentval;
353 unit = "theight%" + endlen;
361 string translate_len(string const & length)
365 if (translate_len(length, value, unit))
367 // If the input is invalid, return what we have.
375 * Translates a LaTeX length into \p value, \p unit and
376 * \p special parts suitable for a box inset.
377 * The difference from translate_len() is that a box inset knows about
378 * some special "units" that are stored in \p special.
380 void translate_box_len(string const & length, string & value, string & unit, string & special)
382 if (translate_len(length, value, unit)) {
383 if (unit == "\\height" || unit == "\\depth" ||
384 unit == "\\totalheight" || unit == "\\width") {
385 special = unit.substr(1);
386 // The unit is not used, but LyX requires a dummy setting
399 * Find a file with basename \p name in path \p path and an extension
402 string find_file(string const & name, string const & path,
403 char const * const * extensions)
405 for (char const * const * what = extensions; *what; ++what) {
406 string const trial = addExtension(name, *what);
407 if (makeAbsPath(trial, path).exists())
414 void begin_inset(ostream & os, string const & name)
416 os << "\n\\begin_inset " << name;
420 void begin_command_inset(ostream & os, string const & name,
421 string const & latexname)
423 begin_inset(os, "CommandInset ");
424 os << name << "\nLatexCommand " << latexname << '\n';
428 void end_inset(ostream & os)
430 os << "\n\\end_inset\n\n";
434 bool skip_braces(Parser & p)
436 if (p.next_token().cat() != catBegin)
439 if (p.next_token().cat() == catEnd) {
448 /// replace LaTeX commands in \p s from the unicodesymbols file with their
450 docstring convert_unicodesymbols(docstring s)
453 for (size_t i = 0; i < s.size();) {
462 docstring parsed = encodings.fromLaTeXCommand(s,
463 Encodings::TEXT_CMD, termination, rem, &req);
464 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
465 preamble.registerAutomaticallyLoadedPackage(*it);
468 if (s.empty() || s[0] != '\\')
477 /// try to convert \p s to a valid InsetCommand argument
478 string convert_command_inset_arg(string s)
481 // since we don't know the input encoding we can't use from_utf8
482 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
483 // LyX cannot handle newlines in a latex command
484 return subst(s, "\n", " ");
488 void handle_backslash(ostream & os, string const & s)
490 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
492 os << "\n\\backslash\n";
499 void handle_ert(ostream & os, string const & s, Context & context)
501 // We must have a valid layout before outputting the ERT inset.
502 context.check_layout(os);
503 Context newcontext(true, context.textclass);
504 begin_inset(os, "ERT");
505 os << "\nstatus collapsed\n";
506 newcontext.check_layout(os);
507 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
509 os << "\n\\backslash\n";
510 else if (*it == '\n') {
511 newcontext.new_paragraph(os);
512 newcontext.check_layout(os);
516 newcontext.check_end_layout(os);
521 void handle_comment(ostream & os, string const & s, Context & context)
523 // TODO: Handle this better
524 Context newcontext(true, context.textclass);
525 begin_inset(os, "ERT");
526 os << "\nstatus collapsed\n";
527 newcontext.check_layout(os);
528 handle_backslash(os, s);
529 // make sure that our comment is the last thing on the line
530 newcontext.new_paragraph(os);
531 newcontext.check_layout(os);
532 newcontext.check_end_layout(os);
537 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
539 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
542 if (checkModule(name, command))
543 return findLayoutWithoutModule(textclass, name, command);
548 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
550 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
553 if (checkModule(name, command))
554 return findInsetLayoutWithoutModule(textclass, name, command);
559 void eat_whitespace(Parser &, ostream &, Context &, bool);
563 * Skips whitespace and braces.
564 * This should be called after a command has been parsed that is not put into
565 * ERT, and where LyX adds "{}" if needed.
567 void skip_spaces_braces(Parser & p, bool keepws = false)
569 /* The following four examples produce the same typeset output and
570 should be handled by this function:
578 // Unfortunately we need to skip comments, too.
579 // We can't use eat_whitespace since writing them after the {}
580 // results in different output in some cases.
581 bool const skipped_spaces = p.skip_spaces(true);
582 bool const skipped_braces = skip_braces(p);
583 if (keepws && skipped_spaces && !skipped_braces)
584 // put back the space (it is better handled by check_space)
585 p.unskip_spaces(true);
589 void output_command_layout(ostream & os, Parser & p, bool outer,
590 Context & parent_context,
591 Layout const * newlayout)
593 TeXFont const oldFont = parent_context.font;
594 // save the current font size
595 string const size = oldFont.size;
596 // reset the font size to default, because the font size switches
597 // don't affect section headings and the like
598 parent_context.font.size = Context::normalfont.size;
599 // we only need to write the font change if we have an open layout
600 if (!parent_context.atParagraphStart())
601 output_font_change(os, oldFont, parent_context.font);
602 parent_context.check_end_layout(os);
603 Context context(true, parent_context.textclass, newlayout,
604 parent_context.layout, parent_context.font);
605 if (parent_context.deeper_paragraph) {
606 // We are beginning a nested environment after a
607 // deeper paragraph inside the outer list environment.
608 // Therefore we don't need to output a "begin deeper".
609 context.need_end_deeper = true;
611 context.check_deeper(os);
612 context.check_layout(os);
613 unsigned int optargs = 0;
614 while (optargs < context.layout->optargs) {
615 eat_whitespace(p, os, context, false);
616 if (p.next_token().cat() == catEscape ||
617 p.next_token().character() != '[')
619 p.get_token(); // eat '['
620 begin_inset(os, "Argument\n");
621 os << "status collapsed\n\n";
622 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
624 eat_whitespace(p, os, context, false);
627 unsigned int reqargs = 0;
628 while (reqargs < context.layout->reqargs) {
629 eat_whitespace(p, os, context, false);
630 if (p.next_token().cat() != catBegin)
632 p.get_token(); // eat '{'
633 begin_inset(os, "Argument\n");
634 os << "status collapsed\n\n";
635 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
637 eat_whitespace(p, os, context, false);
640 parse_text(p, os, FLAG_ITEM, outer, context);
641 context.check_end_layout(os);
642 if (parent_context.deeper_paragraph) {
643 // We must suppress the "end deeper" because we
644 // suppressed the "begin deeper" above.
645 context.need_end_deeper = false;
647 context.check_end_deeper(os);
648 // We don't need really a new paragraph, but
649 // we must make sure that the next item gets a \begin_layout.
650 parent_context.new_paragraph(os);
651 // Set the font size to the original value. No need to output it here
652 // (Context::begin_layout() will do that if needed)
653 parent_context.font.size = size;
658 * Output a space if necessary.
659 * This function gets called for every whitespace token.
661 * We have three cases here:
662 * 1. A space must be suppressed. Example: The lyxcode case below
663 * 2. A space may be suppressed. Example: Spaces before "\par"
664 * 3. A space must not be suppressed. Example: A space between two words
666 * We currently handle only 1. and 3 and from 2. only the case of
667 * spaces before newlines as a side effect.
669 * 2. could be used to suppress as many spaces as possible. This has two effects:
670 * - Reimporting LyX generated LaTeX files changes almost no whitespace
671 * - Superflous whitespace from non LyX generated LaTeX files is removed.
672 * The drawback is that the logic inside the function becomes
673 * complicated, and that is the reason why it is not implemented.
675 void check_space(Parser & p, ostream & os, Context & context)
677 Token const next = p.next_token();
678 Token const curr = p.curr_token();
679 // A space before a single newline and vice versa must be ignored
680 // LyX emits a newline before \end{lyxcode}.
681 // This newline must be ignored,
682 // otherwise LyX will add an additional protected space.
683 if (next.cat() == catSpace ||
684 next.cat() == catNewline ||
685 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
688 context.check_layout(os);
694 * Parse all arguments of \p command
696 void parse_arguments(string const & command,
697 vector<ArgumentType> const & template_arguments,
698 Parser & p, ostream & os, bool outer, Context & context)
700 string ert = command;
701 size_t no_arguments = template_arguments.size();
702 for (size_t i = 0; i < no_arguments; ++i) {
703 switch (template_arguments[i]) {
706 // This argument contains regular LaTeX
707 handle_ert(os, ert + '{', context);
708 eat_whitespace(p, os, context, false);
709 if (template_arguments[i] == required)
710 parse_text(p, os, FLAG_ITEM, outer, context);
712 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
716 // This argument consists only of a single item.
717 // The presence of '{' or not must be preserved.
719 if (p.next_token().cat() == catBegin)
720 ert += '{' + p.verbatim_item() + '}';
722 ert += p.verbatim_item();
726 // This argument may contain special characters
727 ert += '{' + p.verbatim_item() + '}';
731 // true because we must not eat whitespace
732 // if an optional arg follows we must not strip the
733 // brackets from this one
734 if (i < no_arguments - 1 &&
735 template_arguments[i+1] == optional)
736 ert += p.getFullOpt(true);
738 ert += p.getOpt(true);
742 handle_ert(os, ert, context);
747 * Check whether \p command is a known command. If yes,
748 * handle the command with all arguments.
749 * \return true if the command was parsed, false otherwise.
751 bool parse_command(string const & command, Parser & p, ostream & os,
752 bool outer, Context & context)
754 if (known_commands.find(command) != known_commands.end()) {
755 parse_arguments(command, known_commands[command], p, os,
763 /// Parses a minipage or parbox
764 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
765 unsigned inner_flags, bool outer, Context & parent_context,
766 string const & outer_type, string const & special,
767 string const & inner_type)
771 string hor_pos = "c";
772 // We need to set the height to the LaTeX default of 1\\totalheight
773 // for the case when no height argument is given
774 string height_value = "1";
775 string height_unit = "in";
776 string height_special = "totalheight";
781 string width_special = "none";
782 if (!inner_type.empty() && p.hasOpt()) {
783 if (inner_type != "makebox")
784 position = p.getArg('[', ']');
786 latex_width = p.getArg('[', ']');
787 translate_box_len(latex_width, width_value, width_unit, width_special);
790 if (position != "t" && position != "c" && position != "b") {
791 cerr << "invalid position " << position << " for "
792 << inner_type << endl;
796 if (inner_type != "makebox") {
797 latex_height = p.getArg('[', ']');
798 translate_box_len(latex_height, height_value, height_unit, height_special);
800 hor_pos = p.getArg('[', ']');
803 inner_pos = p.getArg('[', ']');
804 if (inner_pos != "c" && inner_pos != "t" &&
805 inner_pos != "b" && inner_pos != "s") {
806 cerr << "invalid inner_pos "
807 << inner_pos << " for "
808 << inner_type << endl;
809 inner_pos = position;
814 if (inner_type.empty()) {
815 if (special.empty() && outer_type != "framebox")
816 latex_width = "1\\columnwidth";
819 latex_width = p2.getArg('[', ']');
820 string const opt = p2.getArg('[', ']');
823 if (hor_pos != "l" && hor_pos != "c" &&
825 cerr << "invalid hor_pos " << hor_pos
826 << " for " << outer_type << endl;
831 } else if (inner_type != "makebox")
832 latex_width = p.verbatim_item();
833 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
834 // as this is LyX's standard for such cases (except for makebox)
835 // \framebox is more special and handled below
836 if (latex_width.empty() && inner_type != "makebox"
837 && outer_type != "framebox")
838 latex_width = "1\\columnwidth";
840 translate_len(latex_width, width_value, width_unit);
842 bool shadedparbox = false;
843 if (inner_type == "shaded") {
844 eat_whitespace(p, os, parent_context, false);
845 if (outer_type == "parbox") {
847 if (p.next_token().cat() == catBegin)
849 eat_whitespace(p, os, parent_context, false);
855 // If we already read the inner box we have to push the inner env
856 if (!outer_type.empty() && !inner_type.empty() &&
857 (inner_flags & FLAG_END))
858 active_environments.push_back(inner_type);
859 // LyX can't handle length variables
860 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
861 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
862 // Look whether there is some content after the end of the
863 // inner box, but before the end of the outer box.
864 // If yes, we need to output ERT.
866 if (inner_flags & FLAG_END)
867 p.verbatimEnvironment(inner_type);
871 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
872 if ((outer_env && p.next_token().asInput() != "\\end") ||
873 (!outer_env && p.next_token().cat() != catEnd)) {
874 // something is between the end of the inner box and
875 // the end of the outer box, so we need to use ERT.
880 // if only \makebox{content} was used we can set its width to 1\width
881 // because this identic and also identic to \mbox
882 // this doesn't work for \framebox{content}, thus we have to use ERT for this
883 if (latex_width.empty() && inner_type == "makebox") {
886 width_special = "width";
887 } else if (latex_width.empty() && outer_type == "framebox") {
892 if (!outer_type.empty()) {
893 if (outer_flags & FLAG_END)
894 ss << "\\begin{" << outer_type << '}';
896 ss << '\\' << outer_type << '{';
897 if (!special.empty())
901 if (!inner_type.empty()) {
902 if (inner_type != "shaded") {
903 if (inner_flags & FLAG_END)
904 ss << "\\begin{" << inner_type << '}';
906 ss << '\\' << inner_type;
908 if (!position.empty())
909 ss << '[' << position << ']';
910 if (!latex_height.empty())
911 ss << '[' << latex_height << ']';
912 if (!inner_pos.empty())
913 ss << '[' << inner_pos << ']';
914 ss << '{' << latex_width << '}';
915 if (!(inner_flags & FLAG_END))
918 if (inner_type == "shaded")
919 ss << "\\begin{shaded}";
920 handle_ert(os, ss.str(), parent_context);
921 if (!inner_type.empty()) {
922 parse_text(p, os, inner_flags, outer, parent_context);
923 if (inner_flags & FLAG_END)
924 handle_ert(os, "\\end{" + inner_type + '}',
927 handle_ert(os, "}", parent_context);
929 if (!outer_type.empty()) {
930 // If we already read the inner box we have to pop
932 if (!inner_type.empty() && (inner_flags & FLAG_END))
933 active_environments.pop_back();
935 // Ensure that the end of the outer box is parsed correctly:
936 // The opening brace has been eaten by parse_outer_box()
937 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
938 outer_flags &= ~FLAG_ITEM;
939 outer_flags |= FLAG_BRACE_LAST;
941 parse_text(p, os, outer_flags, outer, parent_context);
942 if (outer_flags & FLAG_END)
943 handle_ert(os, "\\end{" + outer_type + '}',
945 else if (inner_type.empty() && outer_type == "framebox")
946 // in this case it is already closed later
949 handle_ert(os, "}", parent_context);
952 // LyX does not like empty positions, so we have
953 // to set them to the LaTeX default values here.
954 if (position.empty())
956 if (inner_pos.empty())
957 inner_pos = position;
958 parent_context.check_layout(os);
959 begin_inset(os, "Box ");
960 if (outer_type == "framed")
962 else if (outer_type == "framebox")
964 else if (outer_type == "shadowbox")
966 else if ((outer_type == "shaded" && inner_type.empty()) ||
967 (outer_type == "minipage" && inner_type == "shaded") ||
968 (outer_type == "parbox" && inner_type == "shaded")) {
970 preamble.registerAutomaticallyLoadedPackage("color");
971 } else if (outer_type == "doublebox")
973 else if (outer_type.empty())
976 os << outer_type << '\n';
977 os << "position \"" << position << "\"\n";
978 os << "hor_pos \"" << hor_pos << "\"\n";
979 os << "has_inner_box " << !inner_type.empty() << "\n";
980 os << "inner_pos \"" << inner_pos << "\"\n";
981 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
983 os << "use_makebox " << (inner_type == "makebox") << '\n';
984 os << "width \"" << width_value << width_unit << "\"\n";
985 os << "special \"" << width_special << "\"\n";
986 os << "height \"" << height_value << height_unit << "\"\n";
987 os << "height_special \"" << height_special << "\"\n";
988 os << "status open\n\n";
990 // Unfortunately we can't use parse_text_in_inset:
991 // InsetBox::forcePlainLayout() is hard coded and does not
992 // use the inset layout. Apart from that do we call parse_text
993 // up to two times, but need only one check_end_layout.
994 bool const forcePlainLayout =
995 (!inner_type.empty() || inner_type == "makebox") &&
996 outer_type != "shaded" && outer_type != "framed";
997 Context context(true, parent_context.textclass);
998 if (forcePlainLayout)
999 context.layout = &context.textclass.plainLayout();
1001 context.font = parent_context.font;
1003 // If we have no inner box the contents will be read with the outer box
1004 if (!inner_type.empty())
1005 parse_text(p, os, inner_flags, outer, context);
1007 // Ensure that the end of the outer box is parsed correctly:
1008 // The opening brace has been eaten by parse_outer_box()
1009 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1010 outer_flags &= ~FLAG_ITEM;
1011 outer_flags |= FLAG_BRACE_LAST;
1014 // Find end of outer box, output contents if inner_type is
1015 // empty and output possible comments
1016 if (!outer_type.empty()) {
1017 // If we already read the inner box we have to pop
1019 if (!inner_type.empty() && (inner_flags & FLAG_END))
1020 active_environments.pop_back();
1021 // This does not output anything but comments if
1022 // inner_type is not empty (see use_ert)
1023 parse_text(p, os, outer_flags, outer, context);
1026 context.check_end_layout(os);
1028 #ifdef PRESERVE_LAYOUT
1029 // LyX puts a % after the end of the minipage
1030 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1032 //handle_comment(os, "%dummy", parent_context);
1035 parent_context.new_paragraph(os);
1037 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1038 //handle_comment(os, "%dummy", parent_context);
1041 // We add a protected space if something real follows
1042 if (p.good() && p.next_token().cat() != catComment) {
1043 begin_inset(os, "space ~\n");
1052 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1053 Context & parent_context, string const & outer_type,
1054 string const & special)
1056 eat_whitespace(p, os, parent_context, false);
1057 if (flags & FLAG_ITEM) {
1059 if (p.next_token().cat() == catBegin)
1062 cerr << "Warning: Ignoring missing '{' after \\"
1063 << outer_type << '.' << endl;
1064 eat_whitespace(p, os, parent_context, false);
1067 unsigned int inner_flags = 0;
1069 if (outer_type == "minipage" || outer_type == "parbox") {
1070 p.skip_spaces(true);
1071 while (p.hasOpt()) {
1073 p.skip_spaces(true);
1076 p.skip_spaces(true);
1077 if (outer_type == "parbox") {
1079 if (p.next_token().cat() == catBegin)
1081 p.skip_spaces(true);
1084 if (outer_type == "shaded") {
1085 // These boxes never have an inner box
1087 } else if (p.next_token().asInput() == "\\parbox") {
1088 inner = p.get_token().cs();
1089 inner_flags = FLAG_ITEM;
1090 } else if (p.next_token().asInput() == "\\begin") {
1091 // Is this a minipage or shaded box?
1094 inner = p.getArg('{', '}');
1096 if (inner == "minipage" || inner == "shaded")
1097 inner_flags = FLAG_END;
1102 if (inner_flags == FLAG_END) {
1103 if (inner != "shaded")
1107 eat_whitespace(p, os, parent_context, false);
1109 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1110 outer_type, special, inner);
1112 if (inner_flags == FLAG_ITEM) {
1114 eat_whitespace(p, os, parent_context, false);
1116 parse_box(p, os, flags, inner_flags, outer, parent_context,
1117 outer_type, special, inner);
1122 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1124 parent_context.check_layout(os);
1125 begin_inset(os, "listings\n");
1127 string arg = p.verbatimOption();
1128 os << "lstparams " << '"' << arg << '"' << '\n';
1131 os << "inline true\n";
1133 os << "inline false\n";
1134 os << "status collapsed\n";
1135 Context context(true, parent_context.textclass);
1136 context.layout = &parent_context.textclass.plainLayout();
1139 s = p.plainCommand('!', '!', "lstinline");
1140 context.new_paragraph(os);
1141 context.check_layout(os);
1143 s = p.plainEnvironment("lstlisting");
1144 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1146 os << "\n\\backslash\n";
1147 else if (*it == '\n') {
1148 // avoid adding an empty paragraph at the end
1150 context.new_paragraph(os);
1151 context.check_layout(os);
1156 context.check_end_layout(os);
1161 /// parse an unknown environment
1162 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1163 unsigned flags, bool outer,
1164 Context & parent_context)
1166 if (name == "tabbing")
1167 // We need to remember that we have to handle '\=' specially
1168 flags |= FLAG_TABBING;
1170 // We need to translate font changes and paragraphs inside the
1171 // environment to ERT if we have a non standard font.
1172 // Otherwise things like
1173 // \large\begin{foo}\huge bar\end{foo}
1175 bool const specialfont =
1176 (parent_context.font != parent_context.normalfont);
1177 bool const new_layout_allowed = parent_context.new_layout_allowed;
1179 parent_context.new_layout_allowed = false;
1180 handle_ert(os, "\\begin{" + name + "}", parent_context);
1181 parse_text_snippet(p, os, flags, outer, parent_context);
1182 handle_ert(os, "\\end{" + name + "}", parent_context);
1184 parent_context.new_layout_allowed = new_layout_allowed;
1188 void parse_environment(Parser & p, ostream & os, bool outer,
1189 string & last_env, bool & title_layout_found,
1190 Context & parent_context)
1192 Layout const * newlayout;
1193 InsetLayout const * newinsetlayout = 0;
1194 string const name = p.getArg('{', '}');
1195 const bool is_starred = suffixIs(name, '*');
1196 string const unstarred_name = rtrim(name, "*");
1197 active_environments.push_back(name);
1199 if (is_math_env(name)) {
1200 parent_context.check_layout(os);
1201 begin_inset(os, "Formula ");
1202 os << "\\begin{" << name << "}";
1203 parse_math(p, os, FLAG_END, MATH_MODE);
1204 os << "\\end{" << name << "}";
1206 if (is_display_math_env(name)) {
1207 // Prevent the conversion of a line break to a space
1208 // (bug 7668). This does not change the output, but
1209 // looks ugly in LyX.
1210 eat_whitespace(p, os, parent_context, false);
1214 else if (unstarred_name == "tabular" || name == "longtable") {
1215 eat_whitespace(p, os, parent_context, false);
1216 string width = "0pt";
1217 if (name == "tabular*") {
1218 width = lyx::translate_len(p.getArg('{', '}'));
1219 eat_whitespace(p, os, parent_context, false);
1221 parent_context.check_layout(os);
1222 begin_inset(os, "Tabular ");
1223 handle_tabular(p, os, name, width, parent_context);
1228 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1229 eat_whitespace(p, os, parent_context, false);
1230 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1231 eat_whitespace(p, os, parent_context, false);
1232 parent_context.check_layout(os);
1233 begin_inset(os, "Float " + unstarred_name + "\n");
1234 // store the float type for subfloats
1235 // subfloats only work with figures and tables
1236 if (unstarred_name == "figure")
1237 float_type = unstarred_name;
1238 else if (unstarred_name == "table")
1239 float_type = unstarred_name;
1243 os << "placement " << opt << '\n';
1244 if (contains(opt, "H"))
1245 preamble.registerAutomaticallyLoadedPackage("float");
1247 Floating const & fl = parent_context.textclass.floats()
1248 .getType(unstarred_name);
1249 if (!fl.floattype().empty() && fl.usesFloatPkg())
1250 preamble.registerAutomaticallyLoadedPackage("float");
1253 os << "wide " << convert<string>(is_starred)
1254 << "\nsideways false"
1255 << "\nstatus open\n\n";
1256 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1258 // We don't need really a new paragraph, but
1259 // we must make sure that the next item gets a \begin_layout.
1260 parent_context.new_paragraph(os);
1262 // the float is parsed thus delete the type
1266 else if (unstarred_name == "sidewaysfigure"
1267 || unstarred_name == "sidewaystable") {
1268 eat_whitespace(p, os, parent_context, false);
1269 parent_context.check_layout(os);
1270 if (unstarred_name == "sidewaysfigure")
1271 begin_inset(os, "Float figure\n");
1273 begin_inset(os, "Float table\n");
1274 os << "wide " << convert<string>(is_starred)
1275 << "\nsideways true"
1276 << "\nstatus open\n\n";
1277 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1279 // We don't need really a new paragraph, but
1280 // we must make sure that the next item gets a \begin_layout.
1281 parent_context.new_paragraph(os);
1283 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1286 else if (name == "wrapfigure" || name == "wraptable") {
1287 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1288 eat_whitespace(p, os, parent_context, false);
1289 parent_context.check_layout(os);
1292 string overhang = "0col%";
1295 lines = p.getArg('[', ']');
1296 string const placement = p.getArg('{', '}');
1298 overhang = p.getArg('[', ']');
1299 string const width = p.getArg('{', '}');
1301 if (name == "wrapfigure")
1302 begin_inset(os, "Wrap figure\n");
1304 begin_inset(os, "Wrap table\n");
1305 os << "lines " << lines
1306 << "\nplacement " << placement
1307 << "\noverhang " << lyx::translate_len(overhang)
1308 << "\nwidth " << lyx::translate_len(width)
1309 << "\nstatus open\n\n";
1310 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1312 // We don't need really a new paragraph, but
1313 // we must make sure that the next item gets a \begin_layout.
1314 parent_context.new_paragraph(os);
1316 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1319 else if (name == "minipage") {
1320 eat_whitespace(p, os, parent_context, false);
1321 // Test whether this is an outer box of a shaded box
1323 // swallow arguments
1324 while (p.hasOpt()) {
1326 p.skip_spaces(true);
1329 p.skip_spaces(true);
1330 Token t = p.get_token();
1331 bool shaded = false;
1332 if (t.asInput() == "\\begin") {
1333 p.skip_spaces(true);
1334 if (p.getArg('{', '}') == "shaded")
1339 parse_outer_box(p, os, FLAG_END, outer,
1340 parent_context, name, "shaded");
1342 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1347 else if (name == "comment") {
1348 eat_whitespace(p, os, parent_context, false);
1349 parent_context.check_layout(os);
1350 begin_inset(os, "Note Comment\n");
1351 os << "status open\n";
1352 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1355 skip_braces(p); // eat {} that might by set by LyX behind comments
1356 preamble.registerAutomaticallyLoadedPackage("verbatim");
1359 else if (name == "verbatim") {
1360 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1361 string const s = p.plainEnvironment("verbatim");
1362 string::const_iterator it2 = s.begin();
1363 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1365 os << "\\backslash ";
1366 else if (*it == '\n') {
1368 // avoid adding an empty paragraph at the end
1369 // FIXME: if there are 2 consecutive spaces at the end ignore it
1370 // because LyX will re-add a \n
1371 // This hack must be removed once bug 8049 is fixed!
1372 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1373 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1377 os << "\n\\end_layout\n\n";
1379 // reset to Standard layout
1380 os << "\n\\begin_layout Standard\n";
1383 else if (name == "lyxgreyedout") {
1384 eat_whitespace(p, os, parent_context, false);
1385 parent_context.check_layout(os);
1386 begin_inset(os, "Note Greyedout\n");
1387 os << "status open\n";
1388 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1391 if (!preamble.notefontcolor().empty())
1392 preamble.registerAutomaticallyLoadedPackage("color");
1395 else if (name == "framed" || name == "shaded") {
1396 eat_whitespace(p, os, parent_context, false);
1397 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1401 else if (name == "lstlisting") {
1402 eat_whitespace(p, os, parent_context, false);
1403 // FIXME handle the automatic color package loading
1404 // uwestoehr asks: In what case color is loaded?
1405 parse_listings(p, os, parent_context, false);
1409 else if (!parent_context.new_layout_allowed)
1410 parse_unknown_environment(p, name, os, FLAG_END, outer,
1413 // Alignment and spacing settings
1414 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1415 // therefore are totally broken!
1416 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1417 // they are commands not environments. They are furthermore switches that
1418 // can be ended by another switches, but also by commands like \footnote or
1419 // \parbox. So the only safe way is to leave them untouched.
1420 else if (name == "center" || name == "centering" ||
1421 name == "flushleft" || name == "flushright" ||
1422 name == "singlespace" || name == "onehalfspace" ||
1423 name == "doublespace" || name == "spacing") {
1424 eat_whitespace(p, os, parent_context, false);
1425 // We must begin a new paragraph if not already done
1426 if (! parent_context.atParagraphStart()) {
1427 parent_context.check_end_layout(os);
1428 parent_context.new_paragraph(os);
1430 if (name == "flushleft")
1431 parent_context.add_extra_stuff("\\align left\n");
1432 else if (name == "flushright")
1433 parent_context.add_extra_stuff("\\align right\n");
1434 else if (name == "center" || name == "centering")
1435 parent_context.add_extra_stuff("\\align center\n");
1436 else if (name == "singlespace")
1437 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1438 else if (name == "onehalfspace") {
1439 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1440 preamble.registerAutomaticallyLoadedPackage("setspace");
1441 } else if (name == "doublespace") {
1442 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1443 preamble.registerAutomaticallyLoadedPackage("setspace");
1444 } else if (name == "spacing") {
1445 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1446 preamble.registerAutomaticallyLoadedPackage("setspace");
1448 parse_text(p, os, FLAG_END, outer, parent_context);
1449 // Just in case the environment is empty
1450 parent_context.extra_stuff.erase();
1451 // We must begin a new paragraph to reset the alignment
1452 parent_context.new_paragraph(os);
1456 // The single '=' is meant here.
1457 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1458 eat_whitespace(p, os, parent_context, false);
1459 Context context(true, parent_context.textclass, newlayout,
1460 parent_context.layout, parent_context.font);
1461 if (parent_context.deeper_paragraph) {
1462 // We are beginning a nested environment after a
1463 // deeper paragraph inside the outer list environment.
1464 // Therefore we don't need to output a "begin deeper".
1465 context.need_end_deeper = true;
1467 parent_context.check_end_layout(os);
1468 if (last_env == name) {
1469 // we need to output a separator since LyX would export
1470 // the two environments as one otherwise (bug 5716)
1471 docstring const sep = from_ascii("--Separator--");
1472 TeX2LyXDocClass const & textclass(parent_context.textclass);
1473 if (textclass.hasLayout(sep)) {
1474 Context newcontext(parent_context);
1475 newcontext.layout = &(textclass[sep]);
1476 newcontext.check_layout(os);
1477 newcontext.check_end_layout(os);
1479 parent_context.check_layout(os);
1480 begin_inset(os, "Note Note\n");
1481 os << "status closed\n";
1482 Context newcontext(true, textclass,
1483 &(textclass.defaultLayout()));
1484 newcontext.check_layout(os);
1485 newcontext.check_end_layout(os);
1487 parent_context.check_end_layout(os);
1490 switch (context.layout->latextype) {
1491 case LATEX_LIST_ENVIRONMENT:
1492 context.add_par_extra_stuff("\\labelwidthstring "
1493 + p.verbatim_item() + '\n');
1496 case LATEX_BIB_ENVIRONMENT:
1497 p.verbatim_item(); // swallow next arg
1503 context.check_deeper(os);
1504 // handle known optional and required arguments
1505 // layouts require all optional arguments before the required ones
1506 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1507 // It is impossible to place anything after the environment name,
1508 // but before the first \\item.
1509 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1510 bool need_layout = true;
1511 unsigned int optargs = 0;
1512 while (optargs < context.layout->optargs) {
1513 eat_whitespace(p, os, context, false);
1514 if (p.next_token().cat() == catEscape ||
1515 p.next_token().character() != '[')
1517 p.get_token(); // eat '['
1519 context.check_layout(os);
1520 need_layout = false;
1522 begin_inset(os, "Argument\n");
1523 os << "status collapsed\n\n";
1524 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1526 eat_whitespace(p, os, context, false);
1529 unsigned int reqargs = 0;
1530 while (reqargs < context.layout->reqargs) {
1531 eat_whitespace(p, os, context, false);
1532 if (p.next_token().cat() != catBegin)
1534 p.get_token(); // eat '{'
1536 context.check_layout(os);
1537 need_layout = false;
1539 begin_inset(os, "Argument\n");
1540 os << "status collapsed\n\n";
1541 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1543 eat_whitespace(p, os, context, false);
1547 parse_text(p, os, FLAG_END, outer, context);
1548 context.check_end_layout(os);
1549 if (parent_context.deeper_paragraph) {
1550 // We must suppress the "end deeper" because we
1551 // suppressed the "begin deeper" above.
1552 context.need_end_deeper = false;
1554 context.check_end_deeper(os);
1555 parent_context.new_paragraph(os);
1557 if (!title_layout_found)
1558 title_layout_found = newlayout->intitle;
1559 set<string> const & req = newlayout->requires();
1560 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
1561 preamble.registerAutomaticallyLoadedPackage(*it);
1564 // The single '=' is meant here.
1565 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1566 eat_whitespace(p, os, parent_context, false);
1567 parent_context.check_layout(os);
1568 begin_inset(os, "Flex ");
1569 os << to_utf8(newinsetlayout->name()) << '\n'
1570 << "status collapsed\n";
1571 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1575 else if (name == "appendix") {
1576 // This is no good latex style, but it works and is used in some documents...
1577 eat_whitespace(p, os, parent_context, false);
1578 parent_context.check_end_layout(os);
1579 Context context(true, parent_context.textclass, parent_context.layout,
1580 parent_context.layout, parent_context.font);
1581 context.check_layout(os);
1582 os << "\\start_of_appendix\n";
1583 parse_text(p, os, FLAG_END, outer, context);
1584 context.check_end_layout(os);
1588 else if (known_environments.find(name) != known_environments.end()) {
1589 vector<ArgumentType> arguments = known_environments[name];
1590 // The last "argument" denotes wether we may translate the
1591 // environment contents to LyX
1592 // The default required if no argument is given makes us
1593 // compatible with the reLyXre environment.
1594 ArgumentType contents = arguments.empty() ?
1597 if (!arguments.empty())
1598 arguments.pop_back();
1599 // See comment in parse_unknown_environment()
1600 bool const specialfont =
1601 (parent_context.font != parent_context.normalfont);
1602 bool const new_layout_allowed =
1603 parent_context.new_layout_allowed;
1605 parent_context.new_layout_allowed = false;
1606 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1607 outer, parent_context);
1608 if (contents == verbatim)
1609 handle_ert(os, p.verbatimEnvironment(name),
1612 parse_text_snippet(p, os, FLAG_END, outer,
1614 handle_ert(os, "\\end{" + name + "}", parent_context);
1616 parent_context.new_layout_allowed = new_layout_allowed;
1620 parse_unknown_environment(p, name, os, FLAG_END, outer,
1624 active_environments.pop_back();
1628 /// parses a comment and outputs it to \p os.
1629 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1631 LASSERT(t.cat() == catComment, return);
1632 if (!t.cs().empty()) {
1633 context.check_layout(os);
1634 handle_comment(os, '%' + t.cs(), context);
1635 if (p.next_token().cat() == catNewline) {
1636 // A newline after a comment line starts a new
1638 if (context.new_layout_allowed) {
1639 if(!context.atParagraphStart())
1640 // Only start a new paragraph if not already
1641 // done (we might get called recursively)
1642 context.new_paragraph(os);
1644 handle_ert(os, "\n", context);
1645 eat_whitespace(p, os, context, true);
1648 // "%\n" combination
1655 * Reads spaces and comments until the first non-space, non-comment token.
1656 * New paragraphs (double newlines or \\par) are handled like simple spaces
1657 * if \p eatParagraph is true.
1658 * Spaces are skipped, but comments are written to \p os.
1660 void eat_whitespace(Parser & p, ostream & os, Context & context,
1664 Token const & t = p.get_token();
1665 if (t.cat() == catComment)
1666 parse_comment(p, os, t, context);
1667 else if ((! eatParagraph && p.isParagraph()) ||
1668 (t.cat() != catSpace && t.cat() != catNewline)) {
1677 * Set a font attribute, parse text and reset the font attribute.
1678 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1679 * \param currentvalue Current value of the attribute. Is set to the new
1680 * value during parsing.
1681 * \param newvalue New value of the attribute
1683 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1684 Context & context, string const & attribute,
1685 string & currentvalue, string const & newvalue)
1687 context.check_layout(os);
1688 string const oldvalue = currentvalue;
1689 currentvalue = newvalue;
1690 os << '\n' << attribute << ' ' << newvalue << "\n";
1691 parse_text_snippet(p, os, flags, outer, context);
1692 context.check_layout(os);
1693 os << '\n' << attribute << ' ' << oldvalue << "\n";
1694 currentvalue = oldvalue;
1698 /// get the arguments of a natbib or jurabib citation command
1699 void get_cite_arguments(Parser & p, bool natbibOrder,
1700 string & before, string & after)
1702 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1704 // text before the citation
1706 // text after the citation
1707 after = p.getFullOpt();
1709 if (!after.empty()) {
1710 before = p.getFullOpt();
1711 if (natbibOrder && !before.empty())
1712 swap(before, after);
1717 /// Convert filenames with TeX macros and/or quotes to something LyX
1719 string const normalize_filename(string const & name)
1721 Parser p(trim(name, "\""));
1724 Token const & t = p.get_token();
1725 if (t.cat() != catEscape)
1727 else if (t.cs() == "lyxdot") {
1728 // This is used by LyX for simple dots in relative
1732 } else if (t.cs() == "space") {
1742 /// Convert \p name from TeX convention (relative to master file) to LyX
1743 /// convention (relative to .lyx file) if it is relative
1744 void fix_relative_filename(string & name)
1746 if (FileName::isAbsolute(name))
1749 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1750 from_utf8(getParentFilePath())));
1754 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1755 void parse_noweb(Parser & p, ostream & os, Context & context)
1757 // assemble the rest of the keyword
1761 Token const & t = p.get_token();
1762 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1765 scrap = (p.good() && p.next_token().asInput() == "=");
1767 name += p.get_token().asInput();
1770 name += t.asInput();
1773 if (!scrap || !context.new_layout_allowed ||
1774 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1775 cerr << "Warning: Could not interpret '" << name
1776 << "'. Ignoring it." << endl;
1780 // We use new_paragraph instead of check_end_layout because the stuff
1781 // following the noweb chunk needs to start with a \begin_layout.
1782 // This may create a new paragraph even if there was none in the
1783 // noweb file, but the alternative is an invalid LyX file. Since
1784 // noweb code chunks are implemented with a layout style in LyX they
1785 // always must be in an own paragraph.
1786 context.new_paragraph(os);
1787 Context newcontext(true, context.textclass,
1788 &context.textclass[from_ascii("Scrap")]);
1789 newcontext.check_layout(os);
1792 Token const & t = p.get_token();
1793 // We abuse the parser a bit, because this is no TeX syntax
1795 if (t.cat() == catEscape)
1796 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1799 Context tmp(false, context.textclass,
1800 &context.textclass[from_ascii("Scrap")]);
1801 tmp.need_end_layout = true;
1802 tmp.check_layout(oss);
1803 os << subst(t.asInput(), "\n", oss.str());
1805 // The scrap chunk is ended by an @ at the beginning of a line.
1806 // After the @ the line may contain a comment and/or
1807 // whitespace, but nothing else.
1808 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1809 (p.next_token().cat() == catSpace ||
1810 p.next_token().cat() == catNewline ||
1811 p.next_token().cat() == catComment)) {
1812 while (p.good() && p.next_token().cat() == catSpace)
1813 os << p.get_token().asInput();
1814 if (p.next_token().cat() == catComment)
1815 // The comment includes a final '\n'
1816 os << p.get_token().asInput();
1818 if (p.next_token().cat() == catNewline)
1825 newcontext.check_end_layout(os);
1829 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1830 bool is_macro(Parser & p)
1832 Token first = p.curr_token();
1833 if (first.cat() != catEscape || !p.good())
1835 if (first.cs() == "def")
1837 if (first.cs() != "global" && first.cs() != "long")
1839 Token second = p.get_token();
1841 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1842 second.cat() == catNewline || second.cat() == catComment)) {
1843 second = p.get_token();
1846 bool secondvalid = second.cat() == catEscape;
1848 bool thirdvalid = false;
1849 if (p.good() && first.cs() == "global" && secondvalid &&
1850 second.cs() == "long") {
1851 third = p.get_token();
1853 while (p.good() && !p.isParagraph() &&
1854 (third.cat() == catSpace ||
1855 third.cat() == catNewline ||
1856 third.cat() == catComment)) {
1857 third = p.get_token();
1860 thirdvalid = third.cat() == catEscape;
1862 for (int i = 0; i < pos; ++i)
1867 return (first.cs() == "global" || first.cs() == "long") &&
1868 second.cs() == "def";
1869 return first.cs() == "global" && second.cs() == "long" &&
1870 third.cs() == "def";
1874 /// Parse a macro definition (assumes that is_macro() returned true)
1875 void parse_macro(Parser & p, ostream & os, Context & context)
1877 context.check_layout(os);
1878 Token first = p.curr_token();
1881 string command = first.asInput();
1882 if (first.cs() != "def") {
1884 eat_whitespace(p, os, context, false);
1885 second = p.curr_token();
1886 command += second.asInput();
1887 if (second.cs() != "def") {
1889 eat_whitespace(p, os, context, false);
1890 third = p.curr_token();
1891 command += third.asInput();
1894 eat_whitespace(p, os, context, false);
1895 string const name = p.get_token().cs();
1896 eat_whitespace(p, os, context, false);
1902 while (p.next_token().cat() != catBegin) {
1903 if (p.next_token().cat() == catParameter) {
1908 // followed by number?
1909 if (p.next_token().cat() == catOther) {
1910 char c = p.getChar();
1912 // number = current arity + 1?
1913 if (c == arity + '0' + 1)
1918 paramtext += p.get_token().cs();
1920 paramtext += p.get_token().cs();
1925 // only output simple (i.e. compatible) macro as FormulaMacros
1926 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1928 context.check_layout(os);
1929 begin_inset(os, "FormulaMacro");
1930 os << "\n\\def" << ert;
1933 handle_ert(os, command + ert, context);
1937 void registerExternalTemplatePackages(string const & name)
1939 external::TemplateManager const & etm = external::TemplateManager::get();
1940 external::Template const * const et = etm.getTemplateByName(name);
1943 external::Template::Formats::const_iterator cit = et->formats.end();
1945 cit = et->formats.find("PDFLaTeX");
1946 if (cit == et->formats.end())
1947 // If the template has not specified a PDFLaTeX output,
1948 // we try the LaTeX format.
1949 cit = et->formats.find("LaTeX");
1950 if (cit == et->formats.end())
1952 vector<string>::const_iterator qit = cit->second.requirements.begin();
1953 vector<string>::const_iterator qend = cit->second.requirements.end();
1954 for (; qit != qend; ++qit)
1955 preamble.registerAutomaticallyLoadedPackage(*qit);
1958 } // anonymous namespace
1961 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1964 Layout const * newlayout = 0;
1965 InsetLayout const * newinsetlayout = 0;
1966 char const * const * where = 0;
1967 // Store the latest bibliographystyle and nocite{*} option
1968 // (needed for bibtex inset)
1970 string bibliographystyle = "default";
1971 bool const use_natbib = preamble.isPackageUsed("natbib");
1972 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1974 bool title_layout_found = false;
1976 Token const & t = p.get_token();
1979 debugToken(cerr, t, flags);
1982 if (flags & FLAG_ITEM) {
1983 if (t.cat() == catSpace)
1986 flags &= ~FLAG_ITEM;
1987 if (t.cat() == catBegin) {
1988 // skip the brace and collect everything to the next matching
1990 flags |= FLAG_BRACE_LAST;
1994 // handle only this single token, leave the loop if done
1995 flags |= FLAG_LEAVE;
1998 if (t.cat() != catEscape && t.character() == ']' &&
1999 (flags & FLAG_BRACK_LAST))
2001 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2004 // If there is anything between \end{env} and \begin{env} we
2005 // don't need to output a separator.
2006 if (t.cat() != catSpace && t.cat() != catNewline &&
2007 t.asInput() != "\\begin")
2013 if (t.cat() == catMath) {
2014 // we are inside some text mode thingy, so opening new math is allowed
2015 context.check_layout(os);
2016 begin_inset(os, "Formula ");
2017 Token const & n = p.get_token();
2018 bool const display(n.cat() == catMath && outer);
2020 // TeX's $$...$$ syntax for displayed math
2022 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2024 p.get_token(); // skip the second '$' token
2026 // simple $...$ stuff
2029 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2034 // Prevent the conversion of a line break to a
2035 // space (bug 7668). This does not change the
2036 // output, but looks ugly in LyX.
2037 eat_whitespace(p, os, context, false);
2041 else if (t.cat() == catSuper || t.cat() == catSub)
2042 cerr << "catcode " << t << " illegal in text mode\n";
2044 // Basic support for english quotes. This should be
2045 // extended to other quotes, but is not so easy (a
2046 // left english quote is the same as a right german
2048 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2049 context.check_layout(os);
2050 begin_inset(os, "Quotes ");
2056 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2057 context.check_layout(os);
2058 begin_inset(os, "Quotes ");
2065 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2066 context.check_layout(os);
2067 begin_inset(os, "Quotes ");
2074 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2075 context.check_layout(os);
2076 begin_inset(os, "Quotes ");
2083 else if (t.asInput() == "<"
2084 && p.next_token().asInput() == "<" && noweb_mode) {
2086 parse_noweb(p, os, context);
2089 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2090 check_space(p, os, context);
2092 else if (t.character() == '[' && noweb_mode &&
2093 p.next_token().character() == '[') {
2094 // These can contain underscores
2096 string const s = p.getFullOpt() + ']';
2097 if (p.next_token().character() == ']')
2100 cerr << "Warning: Inserting missing ']' in '"
2101 << s << "'." << endl;
2102 handle_ert(os, s, context);
2105 else if (t.cat() == catLetter) {
2106 context.check_layout(os);
2107 // Workaround for bug 4752.
2108 // FIXME: This whole code block needs to be removed
2109 // when the bug is fixed and tex2lyx produces
2110 // the updated file format.
2111 // The replacement algorithm in LyX is so stupid that
2112 // it even translates a phrase if it is part of a word.
2113 bool handled = false;
2114 for (int const * l = known_phrase_lengths; *l; ++l) {
2115 string phrase = t.cs();
2116 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2117 phrase += p.get_token().cs();
2118 if (is_known(phrase, known_coded_phrases)) {
2119 handle_ert(os, phrase, context);
2123 for (size_t i = 1; i < phrase.length(); ++i)
2131 else if (t.cat() == catOther ||
2132 t.cat() == catAlign ||
2133 t.cat() == catParameter) {
2134 // This translates "&" to "\\&" which may be wrong...
2135 context.check_layout(os);
2139 else if (p.isParagraph()) {
2140 if (context.new_layout_allowed)
2141 context.new_paragraph(os);
2143 handle_ert(os, "\\par ", context);
2144 eat_whitespace(p, os, context, true);
2147 else if (t.cat() == catActive) {
2148 context.check_layout(os);
2149 if (t.character() == '~') {
2150 if (context.layout->free_spacing)
2153 begin_inset(os, "space ~\n");
2160 else if (t.cat() == catBegin) {
2161 Token const next = p.next_token();
2162 Token const end = p.next_next_token();
2163 if (next.cat() == catEnd) {
2165 Token const prev = p.prev_token();
2167 if (p.next_token().character() == '`' ||
2168 (prev.character() == '-' &&
2169 p.next_token().character() == '-'))
2170 ; // ignore it in {}`` or -{}-
2172 handle_ert(os, "{}", context);
2173 } else if (next.cat() == catEscape &&
2174 is_known(next.cs(), known_quotes) &&
2175 end.cat() == catEnd) {
2176 // Something like {\textquoteright} (e.g.
2177 // from writer2latex). LyX writes
2178 // \textquoteright{}, so we may skip the
2179 // braces here for better readability.
2180 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2183 context.check_layout(os);
2184 // special handling of font attribute changes
2185 Token const prev = p.prev_token();
2186 TeXFont const oldFont = context.font;
2187 if (next.character() == '[' ||
2188 next.character() == ']' ||
2189 next.character() == '*') {
2191 if (p.next_token().cat() == catEnd) {
2196 handle_ert(os, "{", context);
2197 parse_text_snippet(p, os,
2200 handle_ert(os, "}", context);
2202 } else if (! context.new_layout_allowed) {
2203 handle_ert(os, "{", context);
2204 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2206 handle_ert(os, "}", context);
2207 } else if (is_known(next.cs(), known_sizes)) {
2208 // next will change the size, so we must
2210 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2212 if (!context.atParagraphStart())
2214 << context.font.size << "\n";
2215 } else if (is_known(next.cs(), known_font_families)) {
2216 // next will change the font family, so we
2217 // must reset it here
2218 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2220 if (!context.atParagraphStart())
2222 << context.font.family << "\n";
2223 } else if (is_known(next.cs(), known_font_series)) {
2224 // next will change the font series, so we
2225 // must reset it here
2226 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2228 if (!context.atParagraphStart())
2230 << context.font.series << "\n";
2231 } else if (is_known(next.cs(), known_font_shapes)) {
2232 // next will change the font shape, so we
2233 // must reset it here
2234 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2236 if (!context.atParagraphStart())
2238 << context.font.shape << "\n";
2239 } else if (is_known(next.cs(), known_old_font_families) ||
2240 is_known(next.cs(), known_old_font_series) ||
2241 is_known(next.cs(), known_old_font_shapes)) {
2242 // next will change the font family, series
2243 // and shape, so we must reset it here
2244 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2246 if (!context.atParagraphStart())
2248 << context.font.family
2250 << context.font.series
2252 << context.font.shape << "\n";
2254 handle_ert(os, "{", context);
2255 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2257 handle_ert(os, "}", context);
2262 else if (t.cat() == catEnd) {
2263 if (flags & FLAG_BRACE_LAST) {
2266 cerr << "stray '}' in text\n";
2267 handle_ert(os, "}", context);
2270 else if (t.cat() == catComment)
2271 parse_comment(p, os, t, context);
2274 // control sequences
2277 else if (t.cs() == "(") {
2278 context.check_layout(os);
2279 begin_inset(os, "Formula");
2281 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2286 else if (t.cs() == "[") {
2287 context.check_layout(os);
2288 begin_inset(os, "Formula");
2290 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2293 // Prevent the conversion of a line break to a space
2294 // (bug 7668). This does not change the output, but
2295 // looks ugly in LyX.
2296 eat_whitespace(p, os, context, false);
2299 else if (t.cs() == "begin")
2300 parse_environment(p, os, outer, last_env,
2301 title_layout_found, context);
2303 else if (t.cs() == "end") {
2304 if (flags & FLAG_END) {
2305 // eat environment name
2306 string const name = p.getArg('{', '}');
2307 if (name != active_environment())
2308 cerr << "\\end{" + name + "} does not match \\begin{"
2309 + active_environment() + "}\n";
2312 p.error("found 'end' unexpectedly");
2315 else if (t.cs() == "item") {
2317 bool const optarg = p.hasOpt();
2319 // FIXME: This swallows comments, but we cannot use
2320 // eat_whitespace() since we must not output
2321 // anything before the item.
2322 p.skip_spaces(true);
2323 s = p.verbatimOption();
2325 p.skip_spaces(false);
2327 context.check_layout(os);
2328 if (context.has_item) {
2329 // An item in an unknown list-like environment
2330 // FIXME: Do this in check_layout()!
2331 context.has_item = false;
2333 handle_ert(os, "\\item", context);
2335 handle_ert(os, "\\item ", context);
2338 if (context.layout->labeltype != LABEL_MANUAL) {
2339 // LyX does not support \item[\mybullet]
2340 // in itemize environments
2342 os << parse_text_snippet(p2,
2343 FLAG_BRACK_LAST, outer, context);
2344 } else if (!s.empty()) {
2345 // LyX adds braces around the argument,
2346 // so we need to remove them here.
2347 if (s.size() > 2 && s[0] == '{' &&
2348 s[s.size()-1] == '}')
2349 s = s.substr(1, s.size()-2);
2350 // If the argument contains a space we
2351 // must put it into ERT: Otherwise LyX
2352 // would misinterpret the space as
2353 // item delimiter (bug 7663)
2354 if (contains(s, ' ')) {
2355 handle_ert(os, s, context);
2358 os << parse_text_snippet(p2,
2362 // The space is needed to separate the
2363 // item from the rest of the sentence.
2365 eat_whitespace(p, os, context, false);
2370 else if (t.cs() == "bibitem") {
2372 context.check_layout(os);
2373 eat_whitespace(p, os, context, false);
2374 string label = convert_command_inset_arg(p.verbatimOption());
2375 string key = convert_command_inset_arg(p.verbatim_item());
2376 if (contains(label, '\\') || contains(key, '\\')) {
2377 // LyX can't handle LaTeX commands in labels or keys
2378 handle_ert(os, t.asInput() + '[' + label +
2379 "]{" + p.verbatim_item() + '}',
2382 begin_command_inset(os, "bibitem", "bibitem");
2383 os << "label \"" << label << "\"\n"
2384 "key \"" << key << "\"\n";
2389 else if (is_macro(p)) {
2390 // catch the case of \def\inputGnumericTable
2392 if (t.cs() == "def") {
2393 Token second = p.next_token();
2394 if (second.cs() == "inputGnumericTable") {
2398 Token third = p.get_token();
2400 if (third.cs() == "input") {
2404 string name = normalize_filename(p.verbatim_item());
2405 string const path = getMasterFilePath();
2406 // We want to preserve relative / absolute filenames,
2407 // therefore path is only used for testing
2408 // The file extension is in every case ".tex".
2409 // So we need to remove this extension and check for
2410 // the original one.
2411 name = removeExtension(name);
2412 if (!makeAbsPath(name, path).exists()) {
2413 char const * const Gnumeric_formats[] = {"gnumeric",
2415 string const Gnumeric_name =
2416 find_file(name, path, Gnumeric_formats);
2417 if (!Gnumeric_name.empty())
2418 name = Gnumeric_name;
2420 if (makeAbsPath(name, path).exists())
2421 fix_relative_filename(name);
2423 cerr << "Warning: Could not find file '"
2424 << name << "'." << endl;
2425 context.check_layout(os);
2426 begin_inset(os, "External\n\ttemplate ");
2427 os << "GnumericSpreadsheet\n\tfilename "
2430 context.check_layout(os);
2432 // register the packages that are automatically reloaded
2433 // by the Gnumeric template
2434 registerExternalTemplatePackages("GnumericSpreadsheet");
2439 parse_macro(p, os, context);
2442 else if (t.cs() == "noindent") {
2444 context.add_par_extra_stuff("\\noindent\n");
2447 else if (t.cs() == "appendix") {
2448 context.add_par_extra_stuff("\\start_of_appendix\n");
2449 // We need to start a new paragraph. Otherwise the
2450 // appendix in 'bla\appendix\chapter{' would start
2452 context.new_paragraph(os);
2453 // We need to make sure that the paragraph is
2454 // generated even if it is empty. Otherwise the
2455 // appendix in '\par\appendix\par\chapter{' would
2457 context.check_layout(os);
2458 // FIXME: This is a hack to prevent paragraph
2459 // deletion if it is empty. Handle this better!
2461 "%dummy comment inserted by tex2lyx to "
2462 "ensure that this paragraph is not empty",
2464 // Both measures above may generate an additional
2465 // empty paragraph, but that does not hurt, because
2466 // whitespace does not matter here.
2467 eat_whitespace(p, os, context, true);
2470 // Must catch empty dates before findLayout is called below
2471 else if (t.cs() == "date") {
2472 string const date = p.verbatim_item();
2474 preamble.suppressDate(true);
2476 preamble.suppressDate(false);
2477 if (context.new_layout_allowed &&
2478 (newlayout = findLayout(context.textclass,
2481 output_command_layout(os, p, outer,
2482 context, newlayout);
2484 if (!title_layout_found)
2485 title_layout_found = newlayout->intitle;
2486 set<string> const & req = newlayout->requires();
2487 for (set<string>::const_iterator it = req.begin();
2488 it != req.end(); it++)
2489 preamble.registerAutomaticallyLoadedPackage(*it);
2491 handle_ert(os, "\\date{" + date + '}',
2496 // Starred section headings
2497 // Must attempt to parse "Section*" before "Section".
2498 else if ((p.next_token().asInput() == "*") &&
2499 context.new_layout_allowed &&
2500 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2503 output_command_layout(os, p, outer, context, newlayout);
2505 if (!title_layout_found)
2506 title_layout_found = newlayout->intitle;
2507 set<string> const & req = newlayout->requires();
2508 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2509 preamble.registerAutomaticallyLoadedPackage(*it);
2512 // Section headings and the like
2513 else if (context.new_layout_allowed &&
2514 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2516 output_command_layout(os, p, outer, context, newlayout);
2518 if (!title_layout_found)
2519 title_layout_found = newlayout->intitle;
2520 set<string> const & req = newlayout->requires();
2521 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
2522 preamble.registerAutomaticallyLoadedPackage(*it);
2525 else if (t.cs() == "caption") {
2527 context.check_layout(os);
2529 begin_inset(os, "Caption\n");
2530 Context newcontext(true, context.textclass);
2531 newcontext.font = context.font;
2532 newcontext.check_layout(os);
2533 if (p.next_token().cat() != catEscape &&
2534 p.next_token().character() == '[') {
2535 p.get_token(); // eat '['
2536 begin_inset(os, "Argument\n");
2537 os << "status collapsed\n";
2538 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2540 eat_whitespace(p, os, context, false);
2542 parse_text(p, os, FLAG_ITEM, outer, context);
2543 context.check_end_layout(os);
2544 // We don't need really a new paragraph, but
2545 // we must make sure that the next item gets a \begin_layout.
2546 context.new_paragraph(os);
2549 newcontext.check_end_layout(os);
2552 else if (t.cs() == "subfloat") {
2553 // the syntax is \subfloat[caption]{content}
2554 // if it is a table of figure depends on the surrounding float
2555 bool has_caption = false;
2557 // do nothing if there is no outer float
2558 if (!float_type.empty()) {
2559 context.check_layout(os);
2561 begin_inset(os, "Float " + float_type + "\n");
2563 << "\nsideways false"
2564 << "\nstatus collapsed\n\n";
2567 if (p.next_token().cat() != catEscape &&
2568 p.next_token().character() == '[') {
2569 p.get_token(); // eat '['
2570 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2574 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2575 // the caption comes always as the last
2577 // we must make sure that the caption gets a \begin_layout
2578 os << "\n\\begin_layout Plain Layout";
2580 begin_inset(os, "Caption\n");
2581 Context newcontext(true, context.textclass);
2582 newcontext.font = context.font;
2583 newcontext.check_layout(os);
2584 os << caption << "\n";
2585 newcontext.check_end_layout(os);
2586 // We don't need really a new paragraph, but
2587 // we must make sure that the next item gets a \begin_layout.
2588 //newcontext.new_paragraph(os);
2592 // We don't need really a new paragraph, but
2593 // we must make sure that the next item gets a \begin_layout.
2595 context.new_paragraph(os);
2598 context.check_end_layout(os);
2599 // close the layout we opened
2601 os << "\n\\end_layout\n";
2603 // if the float type is not supported or there is no surrounding float
2606 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2607 handle_ert(os, t.asInput() + '[' + opt_arg +
2608 "]{" + p.verbatim_item() + '}', context);
2610 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2614 else if (t.cs() == "includegraphics") {
2615 bool const clip = p.next_token().asInput() == "*";
2618 string const arg = p.getArg('[', ']');
2619 map<string, string> opts;
2620 vector<string> keys;
2621 split_map(arg, opts, keys);
2623 opts["clip"] = string();
2624 string name = normalize_filename(p.verbatim_item());
2626 string const path = getMasterFilePath();
2627 // We want to preserve relative / absolute filenames,
2628 // therefore path is only used for testing
2629 if (!makeAbsPath(name, path).exists()) {
2630 // The file extension is probably missing.
2631 // Now try to find it out.
2632 string const dvips_name =
2633 find_file(name, path,
2634 known_dvips_graphics_formats);
2635 string const pdftex_name =
2636 find_file(name, path,
2637 known_pdftex_graphics_formats);
2638 if (!dvips_name.empty()) {
2639 if (!pdftex_name.empty()) {
2640 cerr << "This file contains the "
2642 "\"\\includegraphics{"
2644 "However, files\n\""
2645 << dvips_name << "\" and\n\""
2646 << pdftex_name << "\"\n"
2647 "both exist, so I had to make a "
2648 "choice and took the first one.\n"
2649 "Please move the unwanted one "
2650 "someplace else and try again\n"
2651 "if my choice was wrong."
2655 } else if (!pdftex_name.empty()) {
2661 if (makeAbsPath(name, path).exists())
2662 fix_relative_filename(name);
2664 cerr << "Warning: Could not find graphics file '"
2665 << name << "'." << endl;
2667 context.check_layout(os);
2668 begin_inset(os, "Graphics ");
2669 os << "\n\tfilename " << name << '\n';
2670 if (opts.find("width") != opts.end())
2672 << translate_len(opts["width"]) << '\n';
2673 if (opts.find("height") != opts.end())
2675 << translate_len(opts["height"]) << '\n';
2676 if (opts.find("scale") != opts.end()) {
2677 istringstream iss(opts["scale"]);
2681 os << "\tscale " << val << '\n';
2683 if (opts.find("angle") != opts.end()) {
2684 os << "\trotateAngle "
2685 << opts["angle"] << '\n';
2686 vector<string>::const_iterator a =
2687 find(keys.begin(), keys.end(), "angle");
2688 vector<string>::const_iterator s =
2689 find(keys.begin(), keys.end(), "width");
2690 if (s == keys.end())
2691 s = find(keys.begin(), keys.end(), "height");
2692 if (s == keys.end())
2693 s = find(keys.begin(), keys.end(), "scale");
2694 if (s != keys.end() && distance(s, a) > 0)
2695 os << "\tscaleBeforeRotation\n";
2697 if (opts.find("origin") != opts.end()) {
2699 string const opt = opts["origin"];
2700 if (opt.find('l') != string::npos) ss << "left";
2701 if (opt.find('r') != string::npos) ss << "right";
2702 if (opt.find('c') != string::npos) ss << "center";
2703 if (opt.find('t') != string::npos) ss << "Top";
2704 if (opt.find('b') != string::npos) ss << "Bottom";
2705 if (opt.find('B') != string::npos) ss << "Baseline";
2706 if (!ss.str().empty())
2707 os << "\trotateOrigin " << ss.str() << '\n';
2709 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2711 if (opts.find("keepaspectratio") != opts.end())
2712 os << "\tkeepAspectRatio\n";
2713 if (opts.find("clip") != opts.end())
2715 if (opts.find("draft") != opts.end())
2717 if (opts.find("bb") != opts.end())
2718 os << "\tBoundingBox "
2719 << opts["bb"] << '\n';
2720 int numberOfbbOptions = 0;
2721 if (opts.find("bbllx") != opts.end())
2722 numberOfbbOptions++;
2723 if (opts.find("bblly") != opts.end())
2724 numberOfbbOptions++;
2725 if (opts.find("bburx") != opts.end())
2726 numberOfbbOptions++;
2727 if (opts.find("bbury") != opts.end())
2728 numberOfbbOptions++;
2729 if (numberOfbbOptions == 4)
2730 os << "\tBoundingBox "
2731 << opts["bbllx"] << " " << opts["bblly"] << " "
2732 << opts["bburx"] << " " << opts["bbury"] << '\n';
2733 else if (numberOfbbOptions > 0)
2734 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2735 numberOfbbOptions = 0;
2736 if (opts.find("natwidth") != opts.end())
2737 numberOfbbOptions++;
2738 if (opts.find("natheight") != opts.end())
2739 numberOfbbOptions++;
2740 if (numberOfbbOptions == 2)
2741 os << "\tBoundingBox 0bp 0bp "
2742 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2743 else if (numberOfbbOptions > 0)
2744 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2745 ostringstream special;
2746 if (opts.find("hiresbb") != opts.end())
2747 special << "hiresbb,";
2748 if (opts.find("trim") != opts.end())
2750 if (opts.find("viewport") != opts.end())
2751 special << "viewport=" << opts["viewport"] << ',';
2752 if (opts.find("totalheight") != opts.end())
2753 special << "totalheight=" << opts["totalheight"] << ',';
2754 if (opts.find("type") != opts.end())
2755 special << "type=" << opts["type"] << ',';
2756 if (opts.find("ext") != opts.end())
2757 special << "ext=" << opts["ext"] << ',';
2758 if (opts.find("read") != opts.end())
2759 special << "read=" << opts["read"] << ',';
2760 if (opts.find("command") != opts.end())
2761 special << "command=" << opts["command"] << ',';
2762 string s_special = special.str();
2763 if (!s_special.empty()) {
2764 // We had special arguments. Remove the trailing ','.
2765 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2767 // TODO: Handle the unknown settings better.
2768 // Warn about invalid options.
2769 // Check whether some option was given twice.
2771 preamble.registerAutomaticallyLoadedPackage("graphicx");
2774 else if (t.cs() == "footnote" ||
2775 (t.cs() == "thanks" && context.layout->intitle)) {
2777 context.check_layout(os);
2778 begin_inset(os, "Foot\n");
2779 os << "status collapsed\n\n";
2780 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2784 else if (t.cs() == "marginpar") {
2786 context.check_layout(os);
2787 begin_inset(os, "Marginal\n");
2788 os << "status collapsed\n\n";
2789 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2793 else if (t.cs() == "lstinline") {
2795 parse_listings(p, os, context, true);
2798 else if (t.cs() == "ensuremath") {
2800 context.check_layout(os);
2801 string const s = p.verbatim_item();
2802 //FIXME: this never triggers in UTF8
2803 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2806 handle_ert(os, "\\ensuremath{" + s + "}",
2810 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2811 if (title_layout_found) {
2813 skip_spaces_braces(p);
2815 handle_ert(os, t.asInput(), context);
2818 else if (t.cs() == "tableofcontents") {
2819 context.check_layout(os);
2820 begin_command_inset(os, "toc", "tableofcontents");
2822 skip_spaces_braces(p);
2825 else if (t.cs() == "listoffigures") {
2826 context.check_layout(os);
2827 begin_inset(os, "FloatList figure\n");
2829 skip_spaces_braces(p);
2832 else if (t.cs() == "listoftables") {
2833 context.check_layout(os);
2834 begin_inset(os, "FloatList table\n");
2836 skip_spaces_braces(p);
2839 else if (t.cs() == "listof") {
2840 p.skip_spaces(true);
2841 string const name = p.get_token().cs();
2842 if (context.textclass.floats().typeExist(name)) {
2843 context.check_layout(os);
2844 begin_inset(os, "FloatList ");
2847 p.get_token(); // swallow second arg
2849 handle_ert(os, "\\listof{" + name + "}", context);
2852 else if ((where = is_known(t.cs(), known_text_font_families)))
2853 parse_text_attributes(p, os, FLAG_ITEM, outer,
2854 context, "\\family", context.font.family,
2855 known_coded_font_families[where - known_text_font_families]);
2857 else if ((where = is_known(t.cs(), known_text_font_series)))
2858 parse_text_attributes(p, os, FLAG_ITEM, outer,
2859 context, "\\series", context.font.series,
2860 known_coded_font_series[where - known_text_font_series]);
2862 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2863 parse_text_attributes(p, os, FLAG_ITEM, outer,
2864 context, "\\shape", context.font.shape,
2865 known_coded_font_shapes[where - known_text_font_shapes]);
2867 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2868 context.check_layout(os);
2869 TeXFont oldFont = context.font;
2870 context.font.init();
2871 context.font.size = oldFont.size;
2872 os << "\n\\family " << context.font.family << "\n";
2873 os << "\n\\series " << context.font.series << "\n";
2874 os << "\n\\shape " << context.font.shape << "\n";
2875 if (t.cs() == "textnormal") {
2876 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2877 output_font_change(os, context.font, oldFont);
2878 context.font = oldFont;
2880 eat_whitespace(p, os, context, false);
2883 else if (t.cs() == "textcolor") {
2884 // scheme is \textcolor{color name}{text}
2885 string const color = p.verbatim_item();
2886 // we only support the predefined colors of the color package
2887 if (color == "black" || color == "blue" || color == "cyan"
2888 || color == "green" || color == "magenta" || color == "red"
2889 || color == "white" || color == "yellow") {
2890 context.check_layout(os);
2891 os << "\n\\color " << color << "\n";
2892 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2893 context.check_layout(os);
2894 os << "\n\\color inherit\n";
2895 preamble.registerAutomaticallyLoadedPackage("color");
2897 // for custom defined colors
2898 handle_ert(os, t.asInput() + "{" + color + "}", context);
2901 else if (t.cs() == "underbar" || t.cs() == "uline") {
2902 // \underbar is not 100% correct (LyX outputs \uline
2903 // of ulem.sty). The difference is that \ulem allows
2904 // line breaks, and \underbar does not.
2905 // Do NOT handle \underline.
2906 // \underbar cuts through y, g, q, p etc.,
2907 // \underline does not.
2908 context.check_layout(os);
2909 os << "\n\\bar under\n";
2910 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2911 context.check_layout(os);
2912 os << "\n\\bar default\n";
2913 preamble.registerAutomaticallyLoadedPackage("ulem");
2916 else if (t.cs() == "sout") {
2917 context.check_layout(os);
2918 os << "\n\\strikeout on\n";
2919 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2920 context.check_layout(os);
2921 os << "\n\\strikeout default\n";
2922 preamble.registerAutomaticallyLoadedPackage("ulem");
2925 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2926 t.cs() == "emph" || t.cs() == "noun") {
2927 context.check_layout(os);
2928 os << "\n\\" << t.cs() << " on\n";
2929 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2930 context.check_layout(os);
2931 os << "\n\\" << t.cs() << " default\n";
2932 if (t.cs() == "uuline" || t.cs() == "uwave")
2933 preamble.registerAutomaticallyLoadedPackage("ulem");
2936 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2937 context.check_layout(os);
2938 string name = p.getArg('{', '}');
2939 string localtime = p.getArg('{', '}');
2940 preamble.registerAuthor(name);
2941 Author const & author = preamble.getAuthor(name);
2942 // from_ctime() will fail if LyX decides to output the
2943 // time in the text language. It might also use a wrong
2944 // time zone (if the original LyX document was exported
2945 // with a different time zone).
2946 time_t ptime = from_ctime(localtime);
2947 if (ptime == static_cast<time_t>(-1)) {
2948 cerr << "Warning: Could not parse time `" << localtime
2949 << "´ for change tracking, using current time instead.\n";
2950 ptime = current_time();
2952 if (t.cs() == "lyxadded")
2953 os << "\n\\change_inserted ";
2955 os << "\n\\change_deleted ";
2956 os << author.bufferId() << ' ' << ptime << '\n';
2957 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2958 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2959 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2960 LaTeXPackages::isAvailable("xcolor");
2961 // No need to test for luatex, since luatex comes in
2962 // two flavours (dvi and pdf), like latex, and those
2963 // are detected by pdflatex.
2964 if (pdflatex || xetex) {
2966 preamble.registerAutomaticallyLoadedPackage("ulem");
2967 preamble.registerAutomaticallyLoadedPackage("xcolor");
2968 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2972 preamble.registerAutomaticallyLoadedPackage("dvipost");
2973 } else if (xcolorulem) {
2974 preamble.registerAutomaticallyLoadedPackage("ulem");
2975 preamble.registerAutomaticallyLoadedPackage("xcolor");
2980 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2981 t.cs() == "vphantom") {
2982 context.check_layout(os);
2983 if (t.cs() == "phantom")
2984 begin_inset(os, "Phantom Phantom\n");
2985 if (t.cs() == "hphantom")
2986 begin_inset(os, "Phantom HPhantom\n");
2987 if (t.cs() == "vphantom")
2988 begin_inset(os, "Phantom VPhantom\n");
2989 os << "status open\n";
2990 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2995 else if (t.cs() == "href") {
2996 context.check_layout(os);
2997 string target = p.getArg('{', '}');
2998 string name = p.getArg('{', '}');
3000 size_t i = target.find(':');
3001 if (i != string::npos) {
3002 type = target.substr(0, i + 1);
3003 if (type == "mailto:" || type == "file:")
3004 target = target.substr(i + 1);
3005 // handle the case that name is equal to target, except of "http://"
3006 else if (target.substr(i + 3) == name && type == "http:")
3009 begin_command_inset(os, "href", "href");
3011 os << "name \"" << name << "\"\n";
3012 os << "target \"" << target << "\"\n";
3013 if (type == "mailto:" || type == "file:")
3014 os << "type \"" << type << "\"\n";
3016 skip_spaces_braces(p);
3019 else if (t.cs() == "lyxline") {
3020 // swallow size argument (it is not used anyway)
3022 if (!context.atParagraphStart()) {
3023 // so our line is in the middle of a paragraph
3024 // we need to add a new line, lest this line
3025 // follow the other content on that line and
3026 // run off the side of the page
3027 // FIXME: This may create an empty paragraph,
3028 // but without that it would not be
3029 // possible to set noindent below.
3030 // Fortunately LaTeX does not care
3031 // about the empty paragraph.
3032 context.new_paragraph(os);
3034 if (preamble.indentParagraphs()) {
3035 // we need to unindent, lest the line be too long
3036 context.add_par_extra_stuff("\\noindent\n");
3038 context.check_layout(os);
3039 begin_command_inset(os, "line", "rule");
3040 os << "offset \"0.5ex\"\n"
3041 "width \"100line%\"\n"
3046 else if (t.cs() == "rule") {
3047 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3048 string const width = p.getArg('{', '}');
3049 string const thickness = p.getArg('{', '}');
3050 context.check_layout(os);
3051 begin_command_inset(os, "line", "rule");
3052 if (!offset.empty())
3053 os << "offset \"" << translate_len(offset) << "\"\n";
3054 os << "width \"" << translate_len(width) << "\"\n"
3055 "height \"" << translate_len(thickness) << "\"\n";
3059 else if (is_known(t.cs(), known_phrases) ||
3060 (t.cs() == "protect" &&
3061 p.next_token().cat() == catEscape &&
3062 is_known(p.next_token().cs(), known_phrases))) {
3063 // LyX sometimes puts a \protect in front, so we have to ignore it
3064 // FIXME: This needs to be changed when bug 4752 is fixed.
3066 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3068 context.check_layout(os);
3069 os << known_coded_phrases[where - known_phrases];
3070 skip_spaces_braces(p);
3073 else if ((where = is_known(t.cs(), known_ref_commands))) {
3074 string const opt = p.getOpt();
3076 context.check_layout(os);
3077 begin_command_inset(os, "ref",
3078 known_coded_ref_commands[where - known_ref_commands]);
3079 os << "reference \""
3080 << convert_command_inset_arg(p.verbatim_item())
3083 if (t.cs() == "vref" || t.cs() == "vpageref")
3084 preamble.registerAutomaticallyLoadedPackage("varioref");
3087 // LyX does not support optional arguments of ref commands
3088 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3089 p.verbatim_item() + "}", context);
3093 else if (use_natbib &&
3094 is_known(t.cs(), known_natbib_commands) &&
3095 ((t.cs() != "citefullauthor" &&
3096 t.cs() != "citeyear" &&
3097 t.cs() != "citeyearpar") ||
3098 p.next_token().asInput() != "*")) {
3099 context.check_layout(os);
3100 string command = t.cs();
3101 if (p.next_token().asInput() == "*") {
3105 if (command == "citefullauthor")
3106 // alternative name for "\\citeauthor*"
3107 command = "citeauthor*";
3109 // text before the citation
3111 // text after the citation
3113 get_cite_arguments(p, true, before, after);
3115 if (command == "cite") {
3116 // \cite without optional argument means
3117 // \citet, \cite with at least one optional
3118 // argument means \citep.
3119 if (before.empty() && after.empty())
3124 if (before.empty() && after == "[]")
3125 // avoid \citet[]{a}
3127 else if (before == "[]" && after == "[]") {
3128 // avoid \citet[][]{a}
3132 // remove the brackets around after and before
3133 if (!after.empty()) {
3135 after.erase(after.length() - 1, 1);
3136 after = convert_command_inset_arg(after);
3138 if (!before.empty()) {
3140 before.erase(before.length() - 1, 1);
3141 before = convert_command_inset_arg(before);
3143 begin_command_inset(os, "citation", command);
3144 os << "after " << '"' << after << '"' << "\n";
3145 os << "before " << '"' << before << '"' << "\n";
3147 << convert_command_inset_arg(p.verbatim_item())
3152 else if (use_jurabib &&
3153 is_known(t.cs(), known_jurabib_commands) &&
3154 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3155 context.check_layout(os);
3156 string command = t.cs();
3157 if (p.next_token().asInput() == "*") {
3161 char argumentOrder = '\0';
3162 vector<string> const options =
3163 preamble.getPackageOptions("jurabib");
3164 if (find(options.begin(), options.end(),
3165 "natbiborder") != options.end())
3166 argumentOrder = 'n';
3167 else if (find(options.begin(), options.end(),
3168 "jurabiborder") != options.end())
3169 argumentOrder = 'j';
3171 // text before the citation
3173 // text after the citation
3175 get_cite_arguments(p, argumentOrder != 'j', before, after);
3177 string const citation = p.verbatim_item();
3178 if (!before.empty() && argumentOrder == '\0') {
3179 cerr << "Warning: Assuming argument order "
3180 "of jurabib version 0.6 for\n'"
3181 << command << before << after << '{'
3182 << citation << "}'.\n"
3183 "Add 'jurabiborder' to the jurabib "
3184 "package options if you used an\n"
3185 "earlier jurabib version." << endl;
3187 if (!after.empty()) {
3189 after.erase(after.length() - 1, 1);
3191 if (!before.empty()) {
3193 before.erase(before.length() - 1, 1);
3195 begin_command_inset(os, "citation", command);
3196 os << "after " << '"' << after << '"' << "\n";
3197 os << "before " << '"' << before << '"' << "\n";
3198 os << "key " << '"' << citation << '"' << "\n";
3202 else if (t.cs() == "cite"
3203 || t.cs() == "nocite") {
3204 context.check_layout(os);
3205 string after = convert_command_inset_arg(p.getArg('[', ']'));
3206 string key = convert_command_inset_arg(p.verbatim_item());
3207 // store the case that it is "\nocite{*}" to use it later for
3210 begin_command_inset(os, "citation", t.cs());
3211 os << "after " << '"' << after << '"' << "\n";
3212 os << "key " << '"' << key << '"' << "\n";
3214 } else if (t.cs() == "nocite")
3218 else if (t.cs() == "index" ||
3219 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3220 context.check_layout(os);
3221 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3222 p.getArg('[', ']') : "";
3223 string const kind = arg.empty() ? "idx" : arg;
3224 begin_inset(os, "Index ");
3225 os << kind << "\nstatus collapsed\n";
3226 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3229 preamble.registerAutomaticallyLoadedPackage("splitidx");
3232 else if (t.cs() == "nomenclature") {
3233 context.check_layout(os);
3234 begin_command_inset(os, "nomenclature", "nomenclature");
3235 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3236 if (!prefix.empty())
3237 os << "prefix " << '"' << prefix << '"' << "\n";
3238 os << "symbol " << '"'
3239 << convert_command_inset_arg(p.verbatim_item());
3240 os << "\"\ndescription \""
3241 << convert_command_inset_arg(p.verbatim_item())
3244 preamble.registerAutomaticallyLoadedPackage("nomencl");
3247 else if (t.cs() == "label") {
3248 context.check_layout(os);
3249 begin_command_inset(os, "label", "label");
3251 << convert_command_inset_arg(p.verbatim_item())
3256 else if (t.cs() == "printindex") {
3257 context.check_layout(os);
3258 begin_command_inset(os, "index_print", "printindex");
3259 os << "type \"idx\"\n";
3261 skip_spaces_braces(p);
3262 preamble.registerAutomaticallyLoadedPackage("makeidx");
3263 if (preamble.use_indices() == "true")
3264 preamble.registerAutomaticallyLoadedPackage("splitidx");
3267 else if (t.cs() == "printnomenclature") {
3269 string width_type = "";
3270 context.check_layout(os);
3271 begin_command_inset(os, "nomencl_print", "printnomenclature");
3272 // case of a custom width
3274 width = p.getArg('[', ']');
3275 width = translate_len(width);
3276 width_type = "custom";
3278 // case of no custom width
3279 // the case of no custom width but the width set
3280 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3281 // because the user could have set anything, not only the width
3282 // of the longest label (which would be width_type = "auto")
3283 string label = convert_command_inset_arg(p.getArg('{', '}'));
3284 if (label.empty() && width_type.empty())
3285 width_type = "none";
3286 os << "set_width \"" << width_type << "\"\n";
3287 if (width_type == "custom")
3288 os << "width \"" << width << '\"';
3290 skip_spaces_braces(p);
3291 preamble.registerAutomaticallyLoadedPackage("nomencl");
3294 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3295 context.check_layout(os);
3296 begin_inset(os, "script ");
3297 os << t.cs().substr(4) << '\n';
3298 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3300 if (t.cs() == "textsubscript")
3301 preamble.registerAutomaticallyLoadedPackage("subscript");
3304 else if ((where = is_known(t.cs(), known_quotes))) {
3305 context.check_layout(os);
3306 begin_inset(os, "Quotes ");
3307 os << known_coded_quotes[where - known_quotes];
3309 // LyX adds {} after the quote, so we have to eat
3310 // spaces here if there are any before a possible
3312 eat_whitespace(p, os, context, false);
3316 else if ((where = is_known(t.cs(), known_sizes)) &&
3317 context.new_layout_allowed) {
3318 context.check_layout(os);
3319 TeXFont const oldFont = context.font;
3320 context.font.size = known_coded_sizes[where - known_sizes];
3321 output_font_change(os, oldFont, context.font);
3322 eat_whitespace(p, os, context, false);
3325 else if ((where = is_known(t.cs(), known_font_families)) &&
3326 context.new_layout_allowed) {
3327 context.check_layout(os);
3328 TeXFont const oldFont = context.font;
3329 context.font.family =
3330 known_coded_font_families[where - known_font_families];
3331 output_font_change(os, oldFont, context.font);
3332 eat_whitespace(p, os, context, false);
3335 else if ((where = is_known(t.cs(), known_font_series)) &&
3336 context.new_layout_allowed) {
3337 context.check_layout(os);
3338 TeXFont const oldFont = context.font;
3339 context.font.series =
3340 known_coded_font_series[where - known_font_series];
3341 output_font_change(os, oldFont, context.font);
3342 eat_whitespace(p, os, context, false);
3345 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3346 context.new_layout_allowed) {
3347 context.check_layout(os);
3348 TeXFont const oldFont = context.font;
3349 context.font.shape =
3350 known_coded_font_shapes[where - known_font_shapes];
3351 output_font_change(os, oldFont, context.font);
3352 eat_whitespace(p, os, context, false);
3354 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3355 context.new_layout_allowed) {
3356 context.check_layout(os);
3357 TeXFont const oldFont = context.font;
3358 context.font.init();
3359 context.font.size = oldFont.size;
3360 context.font.family =
3361 known_coded_font_families[where - known_old_font_families];
3362 output_font_change(os, oldFont, context.font);
3363 eat_whitespace(p, os, context, false);
3366 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3367 context.new_layout_allowed) {
3368 context.check_layout(os);
3369 TeXFont const oldFont = context.font;
3370 context.font.init();
3371 context.font.size = oldFont.size;
3372 context.font.series =
3373 known_coded_font_series[where - known_old_font_series];
3374 output_font_change(os, oldFont, context.font);
3375 eat_whitespace(p, os, context, false);
3378 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3379 context.new_layout_allowed) {
3380 context.check_layout(os);
3381 TeXFont const oldFont = context.font;
3382 context.font.init();
3383 context.font.size = oldFont.size;
3384 context.font.shape =
3385 known_coded_font_shapes[where - known_old_font_shapes];
3386 output_font_change(os, oldFont, context.font);
3387 eat_whitespace(p, os, context, false);
3390 else if (t.cs() == "selectlanguage") {
3391 context.check_layout(os);
3392 // save the language for the case that a
3393 // \foreignlanguage is used
3395 context.font.language = babel2lyx(p.verbatim_item());
3396 os << "\n\\lang " << context.font.language << "\n";
3399 else if (t.cs() == "foreignlanguage") {
3400 string const lang = babel2lyx(p.verbatim_item());
3401 parse_text_attributes(p, os, FLAG_ITEM, outer,
3403 context.font.language, lang);
3406 else if (t.cs() == "inputencoding") {
3407 // nothing to write here
3408 string const enc = subst(p.verbatim_item(), "\n", " ");
3412 else if ((where = is_known(t.cs(), known_special_chars))) {
3413 context.check_layout(os);
3414 os << "\\SpecialChar \\"
3415 << known_coded_special_chars[where - known_special_chars]
3417 skip_spaces_braces(p);
3420 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3421 context.check_layout(os);
3422 os << "\\SpecialChar \\nobreakdash-\n";
3426 else if (t.cs() == "textquotedbl") {
3427 context.check_layout(os);
3432 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3433 context.check_layout(os);
3434 os << "\\SpecialChar \\@.\n";
3438 else if (t.cs() == "-") {
3439 context.check_layout(os);
3440 os << "\\SpecialChar \\-\n";
3443 else if (t.cs() == "textasciitilde") {
3444 context.check_layout(os);
3446 skip_spaces_braces(p);
3449 else if (t.cs() == "textasciicircum") {
3450 context.check_layout(os);
3452 skip_spaces_braces(p);
3455 else if (t.cs() == "textbackslash") {
3456 context.check_layout(os);
3457 os << "\n\\backslash\n";
3458 skip_spaces_braces(p);
3461 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3462 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3464 context.check_layout(os);
3468 else if (t.cs() == "char") {
3469 context.check_layout(os);
3470 if (p.next_token().character() == '`') {
3472 if (p.next_token().cs() == "\"") {
3477 handle_ert(os, "\\char`", context);
3480 handle_ert(os, "\\char", context);
3484 else if (t.cs() == "verb") {
3485 context.check_layout(os);
3486 char const delimiter = p.next_token().character();
3487 string const arg = p.getArg(delimiter, delimiter);
3489 oss << "\\verb" << delimiter << arg << delimiter;
3490 handle_ert(os, oss.str(), context);
3493 // Problem: \= creates a tabstop inside the tabbing environment
3494 // and else an accent. In the latter case we really would want
3495 // \={o} instead of \= o.
3496 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3497 handle_ert(os, t.asInput(), context);
3499 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3500 else if (t.cs().size() == 1
3501 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3502 context.check_layout(os);
3503 // try to see whether the string is in unicodesymbols
3506 string command = t.asInput() + "{"
3507 + trimSpaceAndEol(p.verbatim_item())
3510 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3511 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3512 termination, rem, &req);
3515 cerr << "When parsing " << command
3516 << ", result is " << to_utf8(s)
3517 << "+" << to_utf8(rem) << endl;
3519 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
3520 preamble.registerAutomaticallyLoadedPackage(*it);
3522 // we did not find a non-ert version
3523 handle_ert(os, command, context);
3526 else if (t.cs() == "\\") {
3527 context.check_layout(os);
3529 handle_ert(os, "\\\\" + p.getOpt(), context);
3530 else if (p.next_token().asInput() == "*") {
3532 // getOpt() eats the following space if there
3533 // is no optional argument, but that is OK
3534 // here since it has no effect in the output.
3535 handle_ert(os, "\\\\*" + p.getOpt(), context);
3538 begin_inset(os, "Newline newline");
3543 else if (t.cs() == "newline" ||
3544 (t.cs() == "linebreak" && !p.hasOpt())) {
3545 context.check_layout(os);
3546 begin_inset(os, "Newline ");
3549 skip_spaces_braces(p);
3552 else if (t.cs() == "input" || t.cs() == "include"
3553 || t.cs() == "verbatiminput") {
3554 string name = t.cs();
3555 if (t.cs() == "verbatiminput"
3556 && p.next_token().asInput() == "*")
3557 name += p.get_token().asInput();
3558 context.check_layout(os);
3559 string filename(normalize_filename(p.getArg('{', '}')));
3560 string const path = getMasterFilePath();
3561 // We want to preserve relative / absolute filenames,
3562 // therefore path is only used for testing
3563 if ((t.cs() == "include" || t.cs() == "input") &&
3564 !makeAbsPath(filename, path).exists()) {
3565 // The file extension is probably missing.
3566 // Now try to find it out.
3567 string const tex_name =
3568 find_file(filename, path,
3569 known_tex_extensions);
3570 if (!tex_name.empty())
3571 filename = tex_name;
3573 bool external = false;
3575 if (makeAbsPath(filename, path).exists()) {
3576 string const abstexname =
3577 makeAbsPath(filename, path).absFileName();
3578 string const abslyxname =
3579 changeExtension(abstexname, ".lyx");
3580 string const absfigname =
3581 changeExtension(abstexname, ".fig");
3582 fix_relative_filename(filename);
3583 string const lyxname =
3584 changeExtension(filename, ".lyx");
3586 external = FileName(absfigname).exists();
3587 if (t.cs() == "input") {
3588 string const ext = getExtension(abstexname);
3590 // Combined PS/LaTeX:
3591 // x.eps, x.pstex_t (old xfig)
3592 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3593 FileName const absepsname(
3594 changeExtension(abstexname, ".eps"));
3595 FileName const abspstexname(
3596 changeExtension(abstexname, ".pstex"));
3597 bool const xfigeps =
3598 (absepsname.exists() ||
3599 abspstexname.exists()) &&
3602 // Combined PDF/LaTeX:
3603 // x.pdf, x.pdftex_t (old xfig)
3604 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3605 FileName const abspdfname(
3606 changeExtension(abstexname, ".pdf"));
3607 bool const xfigpdf =
3608 abspdfname.exists() &&
3609 (ext == "pdftex_t" || ext == "pdf_t");
3613 // Combined PS/PDF/LaTeX:
3614 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3615 string const absbase2(
3616 removeExtension(abstexname) + "_pspdftex");
3617 FileName const abseps2name(
3618 addExtension(absbase2, ".eps"));
3619 FileName const abspdf2name(
3620 addExtension(absbase2, ".pdf"));
3621 bool const xfigboth =
3622 abspdf2name.exists() &&
3623 abseps2name.exists() && ext == "pspdftex";
3625 xfig = xfigpdf || xfigeps || xfigboth;
3626 external = external && xfig;
3629 outname = changeExtension(filename, ".fig");
3631 // Don't try to convert, the result
3632 // would be full of ERT.
3634 } else if (t.cs() != "verbatiminput" &&
3635 tex2lyx(abstexname, FileName(abslyxname),
3642 cerr << "Warning: Could not find included file '"
3643 << filename << "'." << endl;
3647 begin_inset(os, "External\n");
3648 os << "\ttemplate XFig\n"
3649 << "\tfilename " << outname << '\n';
3650 registerExternalTemplatePackages("XFig");
3652 begin_command_inset(os, "include", name);
3653 os << "preview false\n"
3654 "filename \"" << outname << "\"\n";
3655 if (t.cs() == "verbatiminput")
3656 preamble.registerAutomaticallyLoadedPackage("verbatim");
3661 else if (t.cs() == "bibliographystyle") {
3662 // store new bibliographystyle
3663 bibliographystyle = p.verbatim_item();
3664 // If any other command than \bibliography and
3665 // \nocite{*} follows, we need to output the style
3666 // (because it might be used by that command).
3667 // Otherwise, it will automatically be output by LyX.
3670 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3671 if (t2.cat() == catBegin)
3673 if (t2.cat() != catEscape)
3675 if (t2.cs() == "nocite") {
3676 if (p.getArg('{', '}') == "*")
3678 } else if (t2.cs() == "bibliography")
3685 "\\bibliographystyle{" + bibliographystyle + '}',
3690 else if (t.cs() == "bibliography") {
3691 context.check_layout(os);
3692 begin_command_inset(os, "bibtex", "bibtex");
3693 if (!btprint.empty()) {
3694 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3695 // clear the string because the next BibTeX inset can be without the
3696 // \nocite{*} option
3699 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3700 // Do we have a bibliographystyle set?
3701 if (!bibliographystyle.empty())
3702 os << "options " << '"' << bibliographystyle << '"' << "\n";
3706 else if (t.cs() == "parbox") {
3707 // Test whether this is an outer box of a shaded box
3709 // swallow arguments
3710 while (p.hasOpt()) {
3712 p.skip_spaces(true);
3715 p.skip_spaces(true);
3717 if (p.next_token().cat() == catBegin)
3719 p.skip_spaces(true);
3720 Token to = p.get_token();
3721 bool shaded = false;
3722 if (to.asInput() == "\\begin") {
3723 p.skip_spaces(true);
3724 if (p.getArg('{', '}') == "shaded")
3729 parse_outer_box(p, os, FLAG_ITEM, outer,
3730 context, "parbox", "shaded");
3732 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3736 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3737 t.cs() == "shadowbox" || t.cs() == "doublebox")
3738 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3740 else if (t.cs() == "framebox") {
3741 if (p.next_token().character() == '(') {
3742 //the syntax is: \framebox(x,y)[position]{content}
3743 string arg = t.asInput();
3744 arg += p.getFullParentheseArg();
3745 arg += p.getFullOpt();
3746 eat_whitespace(p, os, context, false);
3747 handle_ert(os, arg + '{', context);
3748 eat_whitespace(p, os, context, false);
3749 parse_text(p, os, FLAG_ITEM, outer, context);
3750 handle_ert(os, "}", context);
3752 string special = p.getFullOpt();
3753 special += p.getOpt();
3754 parse_outer_box(p, os, FLAG_ITEM, outer,
3755 context, t.cs(), special);
3759 //\makebox() is part of the picture environment and different from \makebox{}
3760 //\makebox{} will be parsed by parse_box
3761 else if (t.cs() == "makebox") {
3762 if (p.next_token().character() == '(') {
3763 //the syntax is: \makebox(x,y)[position]{content}
3764 string arg = t.asInput();
3765 arg += p.getFullParentheseArg();
3766 arg += p.getFullOpt();
3767 eat_whitespace(p, os, context, false);
3768 handle_ert(os, arg + '{', context);
3769 eat_whitespace(p, os, context, false);
3770 parse_text(p, os, FLAG_ITEM, outer, context);
3771 handle_ert(os, "}", context);
3773 //the syntax is: \makebox[width][position]{content}
3774 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3778 else if (t.cs() == "smallskip" ||
3779 t.cs() == "medskip" ||
3780 t.cs() == "bigskip" ||
3781 t.cs() == "vfill") {
3782 context.check_layout(os);
3783 begin_inset(os, "VSpace ");
3786 skip_spaces_braces(p);
3789 else if ((where = is_known(t.cs(), known_spaces))) {
3790 context.check_layout(os);
3791 begin_inset(os, "space ");
3792 os << '\\' << known_coded_spaces[where - known_spaces]
3795 // LaTeX swallows whitespace after all spaces except
3796 // "\\,". We have to do that here, too, because LyX
3797 // adds "{}" which would make the spaces significant.
3799 eat_whitespace(p, os, context, false);
3800 // LyX adds "{}" after all spaces except "\\ " and
3801 // "\\,", so we have to remove "{}".
3802 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3803 // remove the braces after "\\,", too.
3808 else if (t.cs() == "newpage" ||
3809 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3810 t.cs() == "clearpage" ||
3811 t.cs() == "cleardoublepage") {
3812 context.check_layout(os);
3813 begin_inset(os, "Newpage ");
3816 skip_spaces_braces(p);
3819 else if (t.cs() == "DeclareRobustCommand" ||
3820 t.cs() == "DeclareRobustCommandx" ||
3821 t.cs() == "newcommand" ||
3822 t.cs() == "newcommandx" ||
3823 t.cs() == "providecommand" ||
3824 t.cs() == "providecommandx" ||
3825 t.cs() == "renewcommand" ||
3826 t.cs() == "renewcommandx") {
3827 // DeclareRobustCommand, DeclareRobustCommandx,
3828 // providecommand and providecommandx could be handled
3829 // by parse_command(), but we need to call
3830 // add_known_command() here.
3831 string name = t.asInput();
3832 if (p.next_token().asInput() == "*") {
3833 // Starred form. Eat '*'
3837 string const command = p.verbatim_item();
3838 string const opt1 = p.getFullOpt();
3839 string const opt2 = p.getFullOpt();
3840 add_known_command(command, opt1, !opt2.empty());
3841 string const ert = name + '{' + command + '}' +
3843 '{' + p.verbatim_item() + '}';
3845 if (t.cs() == "DeclareRobustCommand" ||
3846 t.cs() == "DeclareRobustCommandx" ||
3847 t.cs() == "providecommand" ||
3848 t.cs() == "providecommandx" ||
3849 name[name.length()-1] == '*')
3850 handle_ert(os, ert, context);
3852 context.check_layout(os);
3853 begin_inset(os, "FormulaMacro");
3859 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3860 // let could be handled by parse_command(),
3861 // but we need to call add_known_command() here.
3862 string ert = t.asInput();
3865 if (p.next_token().cat() == catBegin) {
3866 name = p.verbatim_item();
3867 ert += '{' + name + '}';
3869 name = p.verbatim_item();
3874 if (p.next_token().cat() == catBegin) {
3875 command = p.verbatim_item();
3876 ert += '{' + command + '}';
3878 command = p.verbatim_item();
3881 // If command is known, make name known too, to parse
3882 // its arguments correctly. For this reason we also
3883 // have commands in syntax.default that are hardcoded.
3884 CommandMap::iterator it = known_commands.find(command);
3885 if (it != known_commands.end())
3886 known_commands[t.asInput()] = it->second;
3887 handle_ert(os, ert, context);
3890 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3891 bool starred = false;
3892 if (p.next_token().asInput() == "*") {
3896 string name = t.asInput();
3897 string const length = p.verbatim_item();
3900 bool valid = splitLatexLength(length, valstring, unit);
3901 bool known_hspace = false;
3902 bool known_vspace = false;
3903 bool known_unit = false;
3906 istringstream iss(valstring);
3909 if (t.cs()[0] == 'h') {
3910 if (unit == "\\fill") {
3915 known_hspace = true;
3918 if (unit == "\\smallskipamount") {
3920 known_vspace = true;
3921 } else if (unit == "\\medskipamount") {
3923 known_vspace = true;
3924 } else if (unit == "\\bigskipamount") {
3926 known_vspace = true;
3927 } else if (unit == "\\fill") {
3929 known_vspace = true;
3933 if (!known_hspace && !known_vspace) {
3934 switch (unitFromString(unit)) {
3955 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3956 // Literal horizontal length or known variable
3957 context.check_layout(os);
3958 begin_inset(os, "space ");
3966 if (known_unit && !known_hspace)
3968 << translate_len(length);
3970 } else if (known_unit || known_vspace) {
3971 // Literal vertical length or known variable
3972 context.check_layout(os);
3973 begin_inset(os, "VSpace ");
3981 // LyX can't handle other length variables in Inset VSpace/space
3986 handle_ert(os, name + '{' + unit + '}', context);
3987 else if (value == -1.0)
3988 handle_ert(os, name + "{-" + unit + '}', context);
3990 handle_ert(os, name + '{' + valstring + unit + '}', context);
3992 handle_ert(os, name + '{' + length + '}', context);
3996 // The single '=' is meant here.
3997 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3999 context.check_layout(os);
4000 begin_inset(os, "Flex ");
4001 os << to_utf8(newinsetlayout->name()) << '\n'
4002 << "status collapsed\n";
4003 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4007 else if (t.cs() == "includepdf") {
4009 string const arg = p.getArg('[', ']');
4010 map<string, string> opts;
4011 vector<string> keys;
4012 split_map(arg, opts, keys);
4013 string name = normalize_filename(p.verbatim_item());
4014 string const path = getMasterFilePath();
4015 // We want to preserve relative / absolute filenames,
4016 // therefore path is only used for testing
4017 if (!makeAbsPath(name, path).exists()) {
4018 // The file extension is probably missing.
4019 // Now try to find it out.
4020 char const * const pdfpages_format[] = {"pdf", 0};
4021 string const pdftex_name =
4022 find_file(name, path, pdfpages_format);
4023 if (!pdftex_name.empty()) {
4028 if (makeAbsPath(name, path).exists())
4029 fix_relative_filename(name);
4031 cerr << "Warning: Could not find file '"
4032 << name << "'." << endl;
4034 context.check_layout(os);
4035 begin_inset(os, "External\n\ttemplate ");
4036 os << "PDFPages\n\tfilename "
4038 // parse the options
4039 if (opts.find("pages") != opts.end())
4040 os << "\textra LaTeX \"pages="
4041 << opts["pages"] << "\"\n";
4042 if (opts.find("angle") != opts.end())
4043 os << "\trotateAngle "
4044 << opts["angle"] << '\n';
4045 if (opts.find("origin") != opts.end()) {
4047 string const opt = opts["origin"];
4048 if (opt == "tl") ss << "topleft";
4049 if (opt == "bl") ss << "bottomleft";
4050 if (opt == "Bl") ss << "baselineleft";
4051 if (opt == "c") ss << "center";
4052 if (opt == "tc") ss << "topcenter";
4053 if (opt == "bc") ss << "bottomcenter";
4054 if (opt == "Bc") ss << "baselinecenter";
4055 if (opt == "tr") ss << "topright";
4056 if (opt == "br") ss << "bottomright";
4057 if (opt == "Br") ss << "baselineright";
4058 if (!ss.str().empty())
4059 os << "\trotateOrigin " << ss.str() << '\n';
4061 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4063 if (opts.find("width") != opts.end())
4065 << translate_len(opts["width"]) << '\n';
4066 if (opts.find("height") != opts.end())
4068 << translate_len(opts["height"]) << '\n';
4069 if (opts.find("keepaspectratio") != opts.end())
4070 os << "\tkeepAspectRatio\n";
4072 context.check_layout(os);
4073 registerExternalTemplatePackages("PDFPages");
4076 else if (t.cs() == "loadgame") {
4078 string name = normalize_filename(p.verbatim_item());
4079 string const path = getMasterFilePath();
4080 // We want to preserve relative / absolute filenames,
4081 // therefore path is only used for testing
4082 if (!makeAbsPath(name, path).exists()) {
4083 // The file extension is probably missing.
4084 // Now try to find it out.
4085 char const * const lyxskak_format[] = {"fen", 0};
4086 string const lyxskak_name =
4087 find_file(name, path, lyxskak_format);
4088 if (!lyxskak_name.empty())
4089 name = lyxskak_name;
4091 if (makeAbsPath(name, path).exists())
4092 fix_relative_filename(name);
4094 cerr << "Warning: Could not find file '"
4095 << name << "'." << endl;
4096 context.check_layout(os);
4097 begin_inset(os, "External\n\ttemplate ");
4098 os << "ChessDiagram\n\tfilename "
4101 context.check_layout(os);
4102 // after a \loadgame follows a \showboard
4103 if (p.get_token().asInput() == "showboard")
4105 registerExternalTemplatePackages("ChessDiagram");
4109 // try to see whether the string is in unicodesymbols
4110 // Only use text mode commands, since we are in text mode here,
4111 // and math commands may be invalid (bug 6797)
4115 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4116 Encodings::TEXT_CMD, termination, rem, &req);
4119 cerr << "When parsing " << t.cs()
4120 << ", result is " << to_utf8(s)
4121 << "+" << to_utf8(rem) << endl;
4122 context.check_layout(os);
4125 skip_spaces_braces(p);
4126 for (set<string>::const_iterator it = req.begin(); it != req.end(); it++)
4127 preamble.registerAutomaticallyLoadedPackage(*it);
4129 //cerr << "#: " << t << " mode: " << mode << endl;
4130 // heuristic: read up to next non-nested space
4132 string s = t.asInput();
4133 string z = p.verbatim_item();
4134 while (p.good() && z != " " && z.size()) {
4135 //cerr << "read: " << z << endl;
4137 z = p.verbatim_item();
4139 cerr << "found ERT: " << s << endl;
4140 handle_ert(os, s + ' ', context);
4143 string name = t.asInput();
4144 if (p.next_token().asInput() == "*") {
4145 // Starred commands like \vspace*{}
4146 p.get_token(); // Eat '*'
4149 if (!parse_command(name, p, os, outer, context))
4150 handle_ert(os, name, context);
4154 if (flags & FLAG_LEAVE) {
4155 flags &= ~FLAG_LEAVE;