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 set<string>::const_iterator it = req.begin();
465 set<string>::const_iterator en = req.end();
466 for (; it != en; ++it)
467 preamble.registerAutomaticallyLoadedPackage(*it);
470 if (s.empty() || s[0] != '\\')
479 /// try to convert \p s to a valid InsetCommand argument
480 string convert_command_inset_arg(string s)
483 // since we don't know the input encoding we can't use from_utf8
484 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
485 // LyX cannot handle newlines in a latex command
486 return subst(s, "\n", " ");
490 void handle_backslash(ostream & os, string const & s)
492 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
494 os << "\n\\backslash\n";
501 void handle_ert(ostream & os, string const & s, Context & context)
503 // We must have a valid layout before outputting the ERT inset.
504 context.check_layout(os);
505 Context newcontext(true, context.textclass);
506 begin_inset(os, "ERT");
507 os << "\nstatus collapsed\n";
508 newcontext.check_layout(os);
509 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
511 os << "\n\\backslash\n";
512 else if (*it == '\n') {
513 newcontext.new_paragraph(os);
514 newcontext.check_layout(os);
518 newcontext.check_end_layout(os);
523 void handle_comment(ostream & os, string const & s, Context & context)
525 // TODO: Handle this better
526 Context newcontext(true, context.textclass);
527 begin_inset(os, "ERT");
528 os << "\nstatus collapsed\n";
529 newcontext.check_layout(os);
530 handle_backslash(os, s);
531 // make sure that our comment is the last thing on the line
532 newcontext.new_paragraph(os);
533 newcontext.check_layout(os);
534 newcontext.check_end_layout(os);
539 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
541 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
544 if (checkModule(name, command))
545 return findLayoutWithoutModule(textclass, name, command);
550 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
552 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
555 if (checkModule(name, command))
556 return findInsetLayoutWithoutModule(textclass, name, command);
561 void eat_whitespace(Parser &, ostream &, Context &, bool);
565 * Skips whitespace and braces.
566 * This should be called after a command has been parsed that is not put into
567 * ERT, and where LyX adds "{}" if needed.
569 void skip_spaces_braces(Parser & p, bool keepws = false)
571 /* The following four examples produce the same typeset output and
572 should be handled by this function:
580 // Unfortunately we need to skip comments, too.
581 // We can't use eat_whitespace since writing them after the {}
582 // results in different output in some cases.
583 bool const skipped_spaces = p.skip_spaces(true);
584 bool const skipped_braces = skip_braces(p);
585 if (keepws && skipped_spaces && !skipped_braces)
586 // put back the space (it is better handled by check_space)
587 p.unskip_spaces(true);
591 void output_command_layout(ostream & os, Parser & p, bool outer,
592 Context & parent_context,
593 Layout const * newlayout)
595 TeXFont const oldFont = parent_context.font;
596 // save the current font size
597 string const size = oldFont.size;
598 // reset the font size to default, because the font size switches
599 // don't affect section headings and the like
600 parent_context.font.size = Context::normalfont.size;
601 // we only need to write the font change if we have an open layout
602 if (!parent_context.atParagraphStart())
603 output_font_change(os, oldFont, parent_context.font);
604 parent_context.check_end_layout(os);
605 Context context(true, parent_context.textclass, newlayout,
606 parent_context.layout, parent_context.font);
607 if (parent_context.deeper_paragraph) {
608 // We are beginning a nested environment after a
609 // deeper paragraph inside the outer list environment.
610 // Therefore we don't need to output a "begin deeper".
611 context.need_end_deeper = true;
613 context.check_deeper(os);
614 context.check_layout(os);
615 unsigned int optargs = 0;
616 while (optargs < context.layout->optargs) {
617 eat_whitespace(p, os, context, false);
618 if (p.next_token().cat() == catEscape ||
619 p.next_token().character() != '[')
621 p.get_token(); // eat '['
622 begin_inset(os, "Argument\n");
623 os << "status collapsed\n\n";
624 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
626 eat_whitespace(p, os, context, false);
629 unsigned int reqargs = 0;
630 while (reqargs < context.layout->reqargs) {
631 eat_whitespace(p, os, context, false);
632 if (p.next_token().cat() != catBegin)
634 p.get_token(); // eat '{'
635 begin_inset(os, "Argument\n");
636 os << "status collapsed\n\n";
637 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
639 eat_whitespace(p, os, context, false);
642 parse_text(p, os, FLAG_ITEM, outer, context);
643 context.check_end_layout(os);
644 if (parent_context.deeper_paragraph) {
645 // We must suppress the "end deeper" because we
646 // suppressed the "begin deeper" above.
647 context.need_end_deeper = false;
649 context.check_end_deeper(os);
650 // We don't need really a new paragraph, but
651 // we must make sure that the next item gets a \begin_layout.
652 parent_context.new_paragraph(os);
653 // Set the font size to the original value. No need to output it here
654 // (Context::begin_layout() will do that if needed)
655 parent_context.font.size = size;
660 * Output a space if necessary.
661 * This function gets called for every whitespace token.
663 * We have three cases here:
664 * 1. A space must be suppressed. Example: The lyxcode case below
665 * 2. A space may be suppressed. Example: Spaces before "\par"
666 * 3. A space must not be suppressed. Example: A space between two words
668 * We currently handle only 1. and 3 and from 2. only the case of
669 * spaces before newlines as a side effect.
671 * 2. could be used to suppress as many spaces as possible. This has two effects:
672 * - Reimporting LyX generated LaTeX files changes almost no whitespace
673 * - Superflous whitespace from non LyX generated LaTeX files is removed.
674 * The drawback is that the logic inside the function becomes
675 * complicated, and that is the reason why it is not implemented.
677 void check_space(Parser & p, ostream & os, Context & context)
679 Token const next = p.next_token();
680 Token const curr = p.curr_token();
681 // A space before a single newline and vice versa must be ignored
682 // LyX emits a newline before \end{lyxcode}.
683 // This newline must be ignored,
684 // otherwise LyX will add an additional protected space.
685 if (next.cat() == catSpace ||
686 next.cat() == catNewline ||
687 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
690 context.check_layout(os);
696 * Parse all arguments of \p command
698 void parse_arguments(string const & command,
699 vector<ArgumentType> const & template_arguments,
700 Parser & p, ostream & os, bool outer, Context & context)
702 string ert = command;
703 size_t no_arguments = template_arguments.size();
704 for (size_t i = 0; i < no_arguments; ++i) {
705 switch (template_arguments[i]) {
708 // This argument contains regular LaTeX
709 handle_ert(os, ert + '{', context);
710 eat_whitespace(p, os, context, false);
711 if (template_arguments[i] == required)
712 parse_text(p, os, FLAG_ITEM, outer, context);
714 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
718 // This argument consists only of a single item.
719 // The presence of '{' or not must be preserved.
721 if (p.next_token().cat() == catBegin)
722 ert += '{' + p.verbatim_item() + '}';
724 ert += p.verbatim_item();
728 // This argument may contain special characters
729 ert += '{' + p.verbatim_item() + '}';
733 // true because we must not eat whitespace
734 // if an optional arg follows we must not strip the
735 // brackets from this one
736 if (i < no_arguments - 1 &&
737 template_arguments[i+1] == optional)
738 ert += p.getFullOpt(true);
740 ert += p.getOpt(true);
744 handle_ert(os, ert, context);
749 * Check whether \p command is a known command. If yes,
750 * handle the command with all arguments.
751 * \return true if the command was parsed, false otherwise.
753 bool parse_command(string const & command, Parser & p, ostream & os,
754 bool outer, Context & context)
756 if (known_commands.find(command) != known_commands.end()) {
757 parse_arguments(command, known_commands[command], p, os,
765 /// Parses a minipage or parbox
766 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
767 unsigned inner_flags, bool outer, Context & parent_context,
768 string const & outer_type, string const & special,
769 string const & inner_type)
773 string hor_pos = "c";
774 // We need to set the height to the LaTeX default of 1\\totalheight
775 // for the case when no height argument is given
776 string height_value = "1";
777 string height_unit = "in";
778 string height_special = "totalheight";
783 string width_special = "none";
784 if (!inner_type.empty() && p.hasOpt()) {
785 if (inner_type != "makebox")
786 position = p.getArg('[', ']');
788 latex_width = p.getArg('[', ']');
789 translate_box_len(latex_width, width_value, width_unit, width_special);
792 if (position != "t" && position != "c" && position != "b") {
793 cerr << "invalid position " << position << " for "
794 << inner_type << endl;
798 if (inner_type != "makebox") {
799 latex_height = p.getArg('[', ']');
800 translate_box_len(latex_height, height_value, height_unit, height_special);
802 hor_pos = p.getArg('[', ']');
805 inner_pos = p.getArg('[', ']');
806 if (inner_pos != "c" && inner_pos != "t" &&
807 inner_pos != "b" && inner_pos != "s") {
808 cerr << "invalid inner_pos "
809 << inner_pos << " for "
810 << inner_type << endl;
811 inner_pos = position;
816 if (inner_type.empty()) {
817 if (special.empty() && outer_type != "framebox")
818 latex_width = "1\\columnwidth";
821 latex_width = p2.getArg('[', ']');
822 string const opt = p2.getArg('[', ']');
825 if (hor_pos != "l" && hor_pos != "c" &&
827 cerr << "invalid hor_pos " << hor_pos
828 << " for " << outer_type << endl;
833 } else if (inner_type != "makebox")
834 latex_width = p.verbatim_item();
835 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
836 // as this is LyX's standard for such cases (except for makebox)
837 // \framebox is more special and handled below
838 if (latex_width.empty() && inner_type != "makebox"
839 && outer_type != "framebox")
840 latex_width = "1\\columnwidth";
842 translate_len(latex_width, width_value, width_unit);
844 bool shadedparbox = false;
845 if (inner_type == "shaded") {
846 eat_whitespace(p, os, parent_context, false);
847 if (outer_type == "parbox") {
849 if (p.next_token().cat() == catBegin)
851 eat_whitespace(p, os, parent_context, false);
857 // If we already read the inner box we have to push the inner env
858 if (!outer_type.empty() && !inner_type.empty() &&
859 (inner_flags & FLAG_END))
860 active_environments.push_back(inner_type);
861 // LyX can't handle length variables
862 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
863 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
864 // Look whether there is some content after the end of the
865 // inner box, but before the end of the outer box.
866 // If yes, we need to output ERT.
868 if (inner_flags & FLAG_END)
869 p.verbatimEnvironment(inner_type);
873 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
874 if ((outer_env && p.next_token().asInput() != "\\end") ||
875 (!outer_env && p.next_token().cat() != catEnd)) {
876 // something is between the end of the inner box and
877 // the end of the outer box, so we need to use ERT.
882 // if only \makebox{content} was used we can set its width to 1\width
883 // because this identic and also identic to \mbox
884 // this doesn't work for \framebox{content}, thus we have to use ERT for this
885 if (latex_width.empty() && inner_type == "makebox") {
888 width_special = "width";
889 } else if (latex_width.empty() && outer_type == "framebox") {
894 if (!outer_type.empty()) {
895 if (outer_flags & FLAG_END)
896 ss << "\\begin{" << outer_type << '}';
898 ss << '\\' << outer_type << '{';
899 if (!special.empty())
903 if (!inner_type.empty()) {
904 if (inner_type != "shaded") {
905 if (inner_flags & FLAG_END)
906 ss << "\\begin{" << inner_type << '}';
908 ss << '\\' << inner_type;
910 if (!position.empty())
911 ss << '[' << position << ']';
912 if (!latex_height.empty())
913 ss << '[' << latex_height << ']';
914 if (!inner_pos.empty())
915 ss << '[' << inner_pos << ']';
916 ss << '{' << latex_width << '}';
917 if (!(inner_flags & FLAG_END))
920 if (inner_type == "shaded")
921 ss << "\\begin{shaded}";
922 handle_ert(os, ss.str(), parent_context);
923 if (!inner_type.empty()) {
924 parse_text(p, os, inner_flags, outer, parent_context);
925 if (inner_flags & FLAG_END)
926 handle_ert(os, "\\end{" + inner_type + '}',
929 handle_ert(os, "}", parent_context);
931 if (!outer_type.empty()) {
932 // If we already read the inner box we have to pop
934 if (!inner_type.empty() && (inner_flags & FLAG_END))
935 active_environments.pop_back();
937 // Ensure that the end of the outer box is parsed correctly:
938 // The opening brace has been eaten by parse_outer_box()
939 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
940 outer_flags &= ~FLAG_ITEM;
941 outer_flags |= FLAG_BRACE_LAST;
943 parse_text(p, os, outer_flags, outer, parent_context);
944 if (outer_flags & FLAG_END)
945 handle_ert(os, "\\end{" + outer_type + '}',
947 else if (inner_type.empty() && outer_type == "framebox")
948 // in this case it is already closed later
951 handle_ert(os, "}", parent_context);
954 // LyX does not like empty positions, so we have
955 // to set them to the LaTeX default values here.
956 if (position.empty())
958 if (inner_pos.empty())
959 inner_pos = position;
960 parent_context.check_layout(os);
961 begin_inset(os, "Box ");
962 if (outer_type == "framed")
964 else if (outer_type == "framebox")
966 else if (outer_type == "shadowbox")
968 else if ((outer_type == "shaded" && inner_type.empty()) ||
969 (outer_type == "minipage" && inner_type == "shaded") ||
970 (outer_type == "parbox" && inner_type == "shaded")) {
972 preamble.registerAutomaticallyLoadedPackage("color");
973 } else if (outer_type == "doublebox")
975 else if (outer_type.empty())
978 os << outer_type << '\n';
979 os << "position \"" << position << "\"\n";
980 os << "hor_pos \"" << hor_pos << "\"\n";
981 os << "has_inner_box " << !inner_type.empty() << "\n";
982 os << "inner_pos \"" << inner_pos << "\"\n";
983 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
985 os << "use_makebox " << (inner_type == "makebox") << '\n';
986 os << "width \"" << width_value << width_unit << "\"\n";
987 os << "special \"" << width_special << "\"\n";
988 os << "height \"" << height_value << height_unit << "\"\n";
989 os << "height_special \"" << height_special << "\"\n";
990 os << "status open\n\n";
992 // Unfortunately we can't use parse_text_in_inset:
993 // InsetBox::forcePlainLayout() is hard coded and does not
994 // use the inset layout. Apart from that do we call parse_text
995 // up to two times, but need only one check_end_layout.
996 bool const forcePlainLayout =
997 (!inner_type.empty() || inner_type == "makebox") &&
998 outer_type != "shaded" && outer_type != "framed";
999 Context context(true, parent_context.textclass);
1000 if (forcePlainLayout)
1001 context.layout = &context.textclass.plainLayout();
1003 context.font = parent_context.font;
1005 // If we have no inner box the contents will be read with the outer box
1006 if (!inner_type.empty())
1007 parse_text(p, os, inner_flags, outer, context);
1009 // Ensure that the end of the outer box is parsed correctly:
1010 // The opening brace has been eaten by parse_outer_box()
1011 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1012 outer_flags &= ~FLAG_ITEM;
1013 outer_flags |= FLAG_BRACE_LAST;
1016 // Find end of outer box, output contents if inner_type is
1017 // empty and output possible comments
1018 if (!outer_type.empty()) {
1019 // If we already read the inner box we have to pop
1021 if (!inner_type.empty() && (inner_flags & FLAG_END))
1022 active_environments.pop_back();
1023 // This does not output anything but comments if
1024 // inner_type is not empty (see use_ert)
1025 parse_text(p, os, outer_flags, outer, context);
1028 context.check_end_layout(os);
1030 #ifdef PRESERVE_LAYOUT
1031 // LyX puts a % after the end of the minipage
1032 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1034 //handle_comment(os, "%dummy", parent_context);
1037 parent_context.new_paragraph(os);
1039 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1040 //handle_comment(os, "%dummy", parent_context);
1043 // We add a protected space if something real follows
1044 if (p.good() && p.next_token().cat() != catComment) {
1045 begin_inset(os, "space ~\n");
1054 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1055 Context & parent_context, string const & outer_type,
1056 string const & special)
1058 eat_whitespace(p, os, parent_context, false);
1059 if (flags & FLAG_ITEM) {
1061 if (p.next_token().cat() == catBegin)
1064 cerr << "Warning: Ignoring missing '{' after \\"
1065 << outer_type << '.' << endl;
1066 eat_whitespace(p, os, parent_context, false);
1069 unsigned int inner_flags = 0;
1071 if (outer_type == "minipage" || outer_type == "parbox") {
1072 p.skip_spaces(true);
1073 while (p.hasOpt()) {
1075 p.skip_spaces(true);
1078 p.skip_spaces(true);
1079 if (outer_type == "parbox") {
1081 if (p.next_token().cat() == catBegin)
1083 p.skip_spaces(true);
1086 if (outer_type == "shaded") {
1087 // These boxes never have an inner box
1089 } else if (p.next_token().asInput() == "\\parbox") {
1090 inner = p.get_token().cs();
1091 inner_flags = FLAG_ITEM;
1092 } else if (p.next_token().asInput() == "\\begin") {
1093 // Is this a minipage or shaded box?
1096 inner = p.getArg('{', '}');
1098 if (inner == "minipage" || inner == "shaded")
1099 inner_flags = FLAG_END;
1104 if (inner_flags == FLAG_END) {
1105 if (inner != "shaded")
1109 eat_whitespace(p, os, parent_context, false);
1111 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1112 outer_type, special, inner);
1114 if (inner_flags == FLAG_ITEM) {
1116 eat_whitespace(p, os, parent_context, false);
1118 parse_box(p, os, flags, inner_flags, outer, parent_context,
1119 outer_type, special, inner);
1124 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1126 parent_context.check_layout(os);
1127 begin_inset(os, "listings\n");
1129 string arg = p.verbatimOption();
1130 os << "lstparams " << '"' << arg << '"' << '\n';
1133 os << "inline true\n";
1135 os << "inline false\n";
1136 os << "status collapsed\n";
1137 Context context(true, parent_context.textclass);
1138 context.layout = &parent_context.textclass.plainLayout();
1141 s = p.plainCommand('!', '!', "lstinline");
1142 context.new_paragraph(os);
1143 context.check_layout(os);
1145 s = p.plainEnvironment("lstlisting");
1146 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1148 os << "\n\\backslash\n";
1149 else if (*it == '\n') {
1150 // avoid adding an empty paragraph at the end
1152 context.new_paragraph(os);
1153 context.check_layout(os);
1158 context.check_end_layout(os);
1163 /// parse an unknown environment
1164 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1165 unsigned flags, bool outer,
1166 Context & parent_context)
1168 if (name == "tabbing")
1169 // We need to remember that we have to handle '\=' specially
1170 flags |= FLAG_TABBING;
1172 // We need to translate font changes and paragraphs inside the
1173 // environment to ERT if we have a non standard font.
1174 // Otherwise things like
1175 // \large\begin{foo}\huge bar\end{foo}
1177 bool const specialfont =
1178 (parent_context.font != parent_context.normalfont);
1179 bool const new_layout_allowed = parent_context.new_layout_allowed;
1181 parent_context.new_layout_allowed = false;
1182 handle_ert(os, "\\begin{" + name + "}", parent_context);
1183 parse_text_snippet(p, os, flags, outer, parent_context);
1184 handle_ert(os, "\\end{" + name + "}", parent_context);
1186 parent_context.new_layout_allowed = new_layout_allowed;
1190 void parse_environment(Parser & p, ostream & os, bool outer,
1191 string & last_env, Context & parent_context)
1193 Layout const * newlayout;
1194 InsetLayout const * newinsetlayout = 0;
1195 string const name = p.getArg('{', '}');
1196 const bool is_starred = suffixIs(name, '*');
1197 string const unstarred_name = rtrim(name, "*");
1198 active_environments.push_back(name);
1200 if (is_math_env(name)) {
1201 parent_context.check_layout(os);
1202 begin_inset(os, "Formula ");
1203 os << "\\begin{" << name << "}";
1204 parse_math(p, os, FLAG_END, MATH_MODE);
1205 os << "\\end{" << name << "}";
1207 if (is_display_math_env(name)) {
1208 // Prevent the conversion of a line break to a space
1209 // (bug 7668). This does not change the output, but
1210 // looks ugly in LyX.
1211 eat_whitespace(p, os, parent_context, false);
1215 else if (unstarred_name == "tabular" || name == "longtable") {
1216 eat_whitespace(p, os, parent_context, false);
1217 string width = "0pt";
1218 if (name == "tabular*") {
1219 width = lyx::translate_len(p.getArg('{', '}'));
1220 eat_whitespace(p, os, parent_context, false);
1222 parent_context.check_layout(os);
1223 begin_inset(os, "Tabular ");
1224 handle_tabular(p, os, name, width, parent_context);
1229 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1230 eat_whitespace(p, os, parent_context, false);
1231 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1232 eat_whitespace(p, os, parent_context, false);
1233 parent_context.check_layout(os);
1234 begin_inset(os, "Float " + unstarred_name + "\n");
1235 // store the float type for subfloats
1236 // subfloats only work with figures and tables
1237 if (unstarred_name == "figure")
1238 float_type = unstarred_name;
1239 else if (unstarred_name == "table")
1240 float_type = unstarred_name;
1244 os << "placement " << opt << '\n';
1245 if (contains(opt, "H"))
1246 preamble.registerAutomaticallyLoadedPackage("float");
1248 Floating const & fl = parent_context.textclass.floats()
1249 .getType(unstarred_name);
1250 if (!fl.floattype().empty() && fl.usesFloatPkg())
1251 preamble.registerAutomaticallyLoadedPackage("float");
1254 os << "wide " << convert<string>(is_starred)
1255 << "\nsideways false"
1256 << "\nstatus open\n\n";
1257 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1259 // We don't need really a new paragraph, but
1260 // we must make sure that the next item gets a \begin_layout.
1261 parent_context.new_paragraph(os);
1263 // the float is parsed thus delete the type
1267 else if (unstarred_name == "sidewaysfigure"
1268 || unstarred_name == "sidewaystable") {
1269 eat_whitespace(p, os, parent_context, false);
1270 parent_context.check_layout(os);
1271 if (unstarred_name == "sidewaysfigure")
1272 begin_inset(os, "Float figure\n");
1274 begin_inset(os, "Float table\n");
1275 os << "wide " << convert<string>(is_starred)
1276 << "\nsideways true"
1277 << "\nstatus open\n\n";
1278 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1280 // We don't need really a new paragraph, but
1281 // we must make sure that the next item gets a \begin_layout.
1282 parent_context.new_paragraph(os);
1284 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1287 else if (name == "wrapfigure" || name == "wraptable") {
1288 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1289 eat_whitespace(p, os, parent_context, false);
1290 parent_context.check_layout(os);
1293 string overhang = "0col%";
1296 lines = p.getArg('[', ']');
1297 string const placement = p.getArg('{', '}');
1299 overhang = p.getArg('[', ']');
1300 string const width = p.getArg('{', '}');
1302 if (name == "wrapfigure")
1303 begin_inset(os, "Wrap figure\n");
1305 begin_inset(os, "Wrap table\n");
1306 os << "lines " << lines
1307 << "\nplacement " << placement
1308 << "\noverhang " << lyx::translate_len(overhang)
1309 << "\nwidth " << lyx::translate_len(width)
1310 << "\nstatus open\n\n";
1311 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1313 // We don't need really a new paragraph, but
1314 // we must make sure that the next item gets a \begin_layout.
1315 parent_context.new_paragraph(os);
1317 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1320 else if (name == "minipage") {
1321 eat_whitespace(p, os, parent_context, false);
1322 // Test whether this is an outer box of a shaded box
1324 // swallow arguments
1325 while (p.hasOpt()) {
1327 p.skip_spaces(true);
1330 p.skip_spaces(true);
1331 Token t = p.get_token();
1332 bool shaded = false;
1333 if (t.asInput() == "\\begin") {
1334 p.skip_spaces(true);
1335 if (p.getArg('{', '}') == "shaded")
1340 parse_outer_box(p, os, FLAG_END, outer,
1341 parent_context, name, "shaded");
1343 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1348 else if (name == "comment") {
1349 eat_whitespace(p, os, parent_context, false);
1350 parent_context.check_layout(os);
1351 begin_inset(os, "Note Comment\n");
1352 os << "status open\n";
1353 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1356 skip_braces(p); // eat {} that might by set by LyX behind comments
1357 preamble.registerAutomaticallyLoadedPackage("verbatim");
1360 else if (name == "verbatim") {
1361 os << "\n\\end_layout\n\n\\begin_layout Verbatim\n";
1362 string const s = p.plainEnvironment("verbatim");
1363 string::const_iterator it2 = s.begin();
1364 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1366 os << "\\backslash ";
1367 else if (*it == '\n') {
1369 // avoid adding an empty paragraph at the end
1370 // FIXME: if there are 2 consecutive spaces at the end ignore it
1371 // because LyX will re-add a \n
1372 // This hack must be removed once bug 8049 is fixed!
1373 if ((it + 1 != et) && (it + 2 != et || *it2 != '\n'))
1374 os << "\n\\end_layout\n\\begin_layout Verbatim\n";
1378 os << "\n\\end_layout\n\n";
1380 // reset to Standard layout
1381 os << "\n\\begin_layout Standard\n";
1384 else if (name == "lyxgreyedout") {
1385 eat_whitespace(p, os, parent_context, false);
1386 parent_context.check_layout(os);
1387 begin_inset(os, "Note Greyedout\n");
1388 os << "status open\n";
1389 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1392 if (!preamble.notefontcolor().empty())
1393 preamble.registerAutomaticallyLoadedPackage("color");
1396 else if (name == "framed" || name == "shaded") {
1397 eat_whitespace(p, os, parent_context, false);
1398 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1402 else if (name == "lstlisting") {
1403 eat_whitespace(p, os, parent_context, false);
1404 // FIXME handle the automatic color package loading
1405 // uwestoehr asks: In what case color is loaded?
1406 parse_listings(p, os, parent_context, false);
1410 else if (!parent_context.new_layout_allowed)
1411 parse_unknown_environment(p, name, os, FLAG_END, outer,
1414 // Alignment and spacing settings
1415 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1416 // therefore are totally broken!
1417 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1418 // they are commands not environments. They are furthermore switches that
1419 // can be ended by another switches, but also by commands like \footnote or
1420 // \parbox. So the only safe way is to leave them untouched.
1421 else if (name == "center" || name == "centering" ||
1422 name == "flushleft" || name == "flushright" ||
1423 name == "singlespace" || name == "onehalfspace" ||
1424 name == "doublespace" || name == "spacing") {
1425 eat_whitespace(p, os, parent_context, false);
1426 // We must begin a new paragraph if not already done
1427 if (! parent_context.atParagraphStart()) {
1428 parent_context.check_end_layout(os);
1429 parent_context.new_paragraph(os);
1431 if (name == "flushleft")
1432 parent_context.add_extra_stuff("\\align left\n");
1433 else if (name == "flushright")
1434 parent_context.add_extra_stuff("\\align right\n");
1435 else if (name == "center" || name == "centering")
1436 parent_context.add_extra_stuff("\\align center\n");
1437 else if (name == "singlespace")
1438 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1439 else if (name == "onehalfspace") {
1440 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1441 preamble.registerAutomaticallyLoadedPackage("setspace");
1442 } else if (name == "doublespace") {
1443 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1444 preamble.registerAutomaticallyLoadedPackage("setspace");
1445 } else if (name == "spacing") {
1446 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1447 preamble.registerAutomaticallyLoadedPackage("setspace");
1449 parse_text(p, os, FLAG_END, outer, parent_context);
1450 // Just in case the environment is empty
1451 parent_context.extra_stuff.erase();
1452 // We must begin a new paragraph to reset the alignment
1453 parent_context.new_paragraph(os);
1457 // The single '=' is meant here.
1458 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1459 eat_whitespace(p, os, parent_context, false);
1460 Context context(true, parent_context.textclass, newlayout,
1461 parent_context.layout, parent_context.font);
1462 if (parent_context.deeper_paragraph) {
1463 // We are beginning a nested environment after a
1464 // deeper paragraph inside the outer list environment.
1465 // Therefore we don't need to output a "begin deeper".
1466 context.need_end_deeper = true;
1468 parent_context.check_end_layout(os);
1469 if (last_env == name) {
1470 // we need to output a separator since LyX would export
1471 // the two environments as one otherwise (bug 5716)
1472 docstring const sep = from_ascii("--Separator--");
1473 TeX2LyXDocClass const & textclass(parent_context.textclass);
1474 if (textclass.hasLayout(sep)) {
1475 Context newcontext(parent_context);
1476 newcontext.layout = &(textclass[sep]);
1477 newcontext.check_layout(os);
1478 newcontext.check_end_layout(os);
1480 parent_context.check_layout(os);
1481 begin_inset(os, "Note Note\n");
1482 os << "status closed\n";
1483 Context newcontext(true, textclass,
1484 &(textclass.defaultLayout()));
1485 newcontext.check_layout(os);
1486 newcontext.check_end_layout(os);
1488 parent_context.check_end_layout(os);
1491 switch (context.layout->latextype) {
1492 case LATEX_LIST_ENVIRONMENT:
1493 context.add_par_extra_stuff("\\labelwidthstring "
1494 + p.verbatim_item() + '\n');
1497 case LATEX_BIB_ENVIRONMENT:
1498 p.verbatim_item(); // swallow next arg
1504 context.check_deeper(os);
1505 // handle known optional and required arguments
1506 // layouts require all optional arguments before the required ones
1507 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1508 // It is impossible to place anything after the environment name,
1509 // but before the first \\item.
1510 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1511 bool need_layout = true;
1512 unsigned int optargs = 0;
1513 while (optargs < context.layout->optargs) {
1514 eat_whitespace(p, os, context, false);
1515 if (p.next_token().cat() == catEscape ||
1516 p.next_token().character() != '[')
1518 p.get_token(); // eat '['
1520 context.check_layout(os);
1521 need_layout = false;
1523 begin_inset(os, "Argument\n");
1524 os << "status collapsed\n\n";
1525 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1527 eat_whitespace(p, os, context, false);
1530 unsigned int reqargs = 0;
1531 while (reqargs < context.layout->reqargs) {
1532 eat_whitespace(p, os, context, false);
1533 if (p.next_token().cat() != catBegin)
1535 p.get_token(); // eat '{'
1537 context.check_layout(os);
1538 need_layout = false;
1540 begin_inset(os, "Argument\n");
1541 os << "status collapsed\n\n";
1542 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1544 eat_whitespace(p, os, context, false);
1548 parse_text(p, os, FLAG_END, outer, context);
1549 context.check_end_layout(os);
1550 if (parent_context.deeper_paragraph) {
1551 // We must suppress the "end deeper" because we
1552 // suppressed the "begin deeper" above.
1553 context.need_end_deeper = false;
1555 context.check_end_deeper(os);
1556 parent_context.new_paragraph(os);
1558 if (!preamble.titleLayoutFound())
1559 preamble.titleLayoutFound(newlayout->intitle);
1560 set<string> const & req = newlayout->requires();
1561 set<string>::const_iterator it = req.begin();
1562 set<string>::const_iterator en = req.end();
1563 for (; it != en; ++it)
1564 preamble.registerAutomaticallyLoadedPackage(*it);
1567 // The single '=' is meant here.
1568 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1569 eat_whitespace(p, os, parent_context, false);
1570 parent_context.check_layout(os);
1571 begin_inset(os, "Flex ");
1572 os << to_utf8(newinsetlayout->name()) << '\n'
1573 << "status collapsed\n";
1574 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1578 else if (name == "appendix") {
1579 // This is no good latex style, but it works and is used in some documents...
1580 eat_whitespace(p, os, parent_context, false);
1581 parent_context.check_end_layout(os);
1582 Context context(true, parent_context.textclass, parent_context.layout,
1583 parent_context.layout, parent_context.font);
1584 context.check_layout(os);
1585 os << "\\start_of_appendix\n";
1586 parse_text(p, os, FLAG_END, outer, context);
1587 context.check_end_layout(os);
1591 else if (known_environments.find(name) != known_environments.end()) {
1592 vector<ArgumentType> arguments = known_environments[name];
1593 // The last "argument" denotes wether we may translate the
1594 // environment contents to LyX
1595 // The default required if no argument is given makes us
1596 // compatible with the reLyXre environment.
1597 ArgumentType contents = arguments.empty() ?
1600 if (!arguments.empty())
1601 arguments.pop_back();
1602 // See comment in parse_unknown_environment()
1603 bool const specialfont =
1604 (parent_context.font != parent_context.normalfont);
1605 bool const new_layout_allowed =
1606 parent_context.new_layout_allowed;
1608 parent_context.new_layout_allowed = false;
1609 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1610 outer, parent_context);
1611 if (contents == verbatim)
1612 handle_ert(os, p.verbatimEnvironment(name),
1615 parse_text_snippet(p, os, FLAG_END, outer,
1617 handle_ert(os, "\\end{" + name + "}", parent_context);
1619 parent_context.new_layout_allowed = new_layout_allowed;
1623 parse_unknown_environment(p, name, os, FLAG_END, outer,
1627 active_environments.pop_back();
1631 /// parses a comment and outputs it to \p os.
1632 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1634 LASSERT(t.cat() == catComment, return);
1635 if (!t.cs().empty()) {
1636 context.check_layout(os);
1637 handle_comment(os, '%' + t.cs(), context);
1638 if (p.next_token().cat() == catNewline) {
1639 // A newline after a comment line starts a new
1641 if (context.new_layout_allowed) {
1642 if(!context.atParagraphStart())
1643 // Only start a new paragraph if not already
1644 // done (we might get called recursively)
1645 context.new_paragraph(os);
1647 handle_ert(os, "\n", context);
1648 eat_whitespace(p, os, context, true);
1651 // "%\n" combination
1658 * Reads spaces and comments until the first non-space, non-comment token.
1659 * New paragraphs (double newlines or \\par) are handled like simple spaces
1660 * if \p eatParagraph is true.
1661 * Spaces are skipped, but comments are written to \p os.
1663 void eat_whitespace(Parser & p, ostream & os, Context & context,
1667 Token const & t = p.get_token();
1668 if (t.cat() == catComment)
1669 parse_comment(p, os, t, context);
1670 else if ((! eatParagraph && p.isParagraph()) ||
1671 (t.cat() != catSpace && t.cat() != catNewline)) {
1680 * Set a font attribute, parse text and reset the font attribute.
1681 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1682 * \param currentvalue Current value of the attribute. Is set to the new
1683 * value during parsing.
1684 * \param newvalue New value of the attribute
1686 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1687 Context & context, string const & attribute,
1688 string & currentvalue, string const & newvalue)
1690 context.check_layout(os);
1691 string const oldvalue = currentvalue;
1692 currentvalue = newvalue;
1693 os << '\n' << attribute << ' ' << newvalue << "\n";
1694 parse_text_snippet(p, os, flags, outer, context);
1695 context.check_layout(os);
1696 os << '\n' << attribute << ' ' << oldvalue << "\n";
1697 currentvalue = oldvalue;
1701 /// get the arguments of a natbib or jurabib citation command
1702 void get_cite_arguments(Parser & p, bool natbibOrder,
1703 string & before, string & after)
1705 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1707 // text before the citation
1709 // text after the citation
1710 after = p.getFullOpt();
1712 if (!after.empty()) {
1713 before = p.getFullOpt();
1714 if (natbibOrder && !before.empty())
1715 swap(before, after);
1720 /// Convert filenames with TeX macros and/or quotes to something LyX
1722 string const normalize_filename(string const & name)
1724 Parser p(trim(name, "\""));
1727 Token const & t = p.get_token();
1728 if (t.cat() != catEscape)
1730 else if (t.cs() == "lyxdot") {
1731 // This is used by LyX for simple dots in relative
1735 } else if (t.cs() == "space") {
1745 /// Convert \p name from TeX convention (relative to master file) to LyX
1746 /// convention (relative to .lyx file) if it is relative
1747 void fix_relative_filename(string & name)
1749 if (FileName::isAbsolute(name))
1752 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1753 from_utf8(getParentFilePath())));
1757 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1758 void parse_noweb(Parser & p, ostream & os, Context & context)
1760 // assemble the rest of the keyword
1764 Token const & t = p.get_token();
1765 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1768 scrap = (p.good() && p.next_token().asInput() == "=");
1770 name += p.get_token().asInput();
1773 name += t.asInput();
1776 if (!scrap || !context.new_layout_allowed ||
1777 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1778 cerr << "Warning: Could not interpret '" << name
1779 << "'. Ignoring it." << endl;
1783 // We use new_paragraph instead of check_end_layout because the stuff
1784 // following the noweb chunk needs to start with a \begin_layout.
1785 // This may create a new paragraph even if there was none in the
1786 // noweb file, but the alternative is an invalid LyX file. Since
1787 // noweb code chunks are implemented with a layout style in LyX they
1788 // always must be in an own paragraph.
1789 context.new_paragraph(os);
1790 Context newcontext(true, context.textclass,
1791 &context.textclass[from_ascii("Scrap")]);
1792 newcontext.check_layout(os);
1795 Token const & t = p.get_token();
1796 // We abuse the parser a bit, because this is no TeX syntax
1798 if (t.cat() == catEscape)
1799 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1802 Context tmp(false, context.textclass,
1803 &context.textclass[from_ascii("Scrap")]);
1804 tmp.need_end_layout = true;
1805 tmp.check_layout(oss);
1806 os << subst(t.asInput(), "\n", oss.str());
1808 // The scrap chunk is ended by an @ at the beginning of a line.
1809 // After the @ the line may contain a comment and/or
1810 // whitespace, but nothing else.
1811 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1812 (p.next_token().cat() == catSpace ||
1813 p.next_token().cat() == catNewline ||
1814 p.next_token().cat() == catComment)) {
1815 while (p.good() && p.next_token().cat() == catSpace)
1816 os << p.get_token().asInput();
1817 if (p.next_token().cat() == catComment)
1818 // The comment includes a final '\n'
1819 os << p.get_token().asInput();
1821 if (p.next_token().cat() == catNewline)
1828 newcontext.check_end_layout(os);
1832 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1833 bool is_macro(Parser & p)
1835 Token first = p.curr_token();
1836 if (first.cat() != catEscape || !p.good())
1838 if (first.cs() == "def")
1840 if (first.cs() != "global" && first.cs() != "long")
1842 Token second = p.get_token();
1844 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1845 second.cat() == catNewline || second.cat() == catComment)) {
1846 second = p.get_token();
1849 bool secondvalid = second.cat() == catEscape;
1851 bool thirdvalid = false;
1852 if (p.good() && first.cs() == "global" && secondvalid &&
1853 second.cs() == "long") {
1854 third = p.get_token();
1856 while (p.good() && !p.isParagraph() &&
1857 (third.cat() == catSpace ||
1858 third.cat() == catNewline ||
1859 third.cat() == catComment)) {
1860 third = p.get_token();
1863 thirdvalid = third.cat() == catEscape;
1865 for (int i = 0; i < pos; ++i)
1870 return (first.cs() == "global" || first.cs() == "long") &&
1871 second.cs() == "def";
1872 return first.cs() == "global" && second.cs() == "long" &&
1873 third.cs() == "def";
1877 /// Parse a macro definition (assumes that is_macro() returned true)
1878 void parse_macro(Parser & p, ostream & os, Context & context)
1880 context.check_layout(os);
1881 Token first = p.curr_token();
1884 string command = first.asInput();
1885 if (first.cs() != "def") {
1887 eat_whitespace(p, os, context, false);
1888 second = p.curr_token();
1889 command += second.asInput();
1890 if (second.cs() != "def") {
1892 eat_whitespace(p, os, context, false);
1893 third = p.curr_token();
1894 command += third.asInput();
1897 eat_whitespace(p, os, context, false);
1898 string const name = p.get_token().cs();
1899 eat_whitespace(p, os, context, false);
1905 while (p.next_token().cat() != catBegin) {
1906 if (p.next_token().cat() == catParameter) {
1911 // followed by number?
1912 if (p.next_token().cat() == catOther) {
1913 char c = p.getChar();
1915 // number = current arity + 1?
1916 if (c == arity + '0' + 1)
1921 paramtext += p.get_token().cs();
1923 paramtext += p.get_token().cs();
1928 // only output simple (i.e. compatible) macro as FormulaMacros
1929 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1931 context.check_layout(os);
1932 begin_inset(os, "FormulaMacro");
1933 os << "\n\\def" << ert;
1936 handle_ert(os, command + ert, context);
1940 void registerExternalTemplatePackages(string const & name)
1942 external::TemplateManager const & etm = external::TemplateManager::get();
1943 external::Template const * const et = etm.getTemplateByName(name);
1946 external::Template::Formats::const_iterator cit = et->formats.end();
1948 cit = et->formats.find("PDFLaTeX");
1949 if (cit == et->formats.end())
1950 // If the template has not specified a PDFLaTeX output,
1951 // we try the LaTeX format.
1952 cit = et->formats.find("LaTeX");
1953 if (cit == et->formats.end())
1955 vector<string>::const_iterator qit = cit->second.requirements.begin();
1956 vector<string>::const_iterator qend = cit->second.requirements.end();
1957 for (; qit != qend; ++qit)
1958 preamble.registerAutomaticallyLoadedPackage(*qit);
1961 } // anonymous namespace
1964 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1967 Layout const * newlayout = 0;
1968 InsetLayout const * newinsetlayout = 0;
1969 char const * const * where = 0;
1970 // Store the latest bibliographystyle and nocite{*} option
1971 // (needed for bibtex inset)
1973 string bibliographystyle = "default";
1974 bool const use_natbib = preamble.isPackageUsed("natbib");
1975 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1978 Token const & t = p.get_token();
1981 debugToken(cerr, t, flags);
1984 if (flags & FLAG_ITEM) {
1985 if (t.cat() == catSpace)
1988 flags &= ~FLAG_ITEM;
1989 if (t.cat() == catBegin) {
1990 // skip the brace and collect everything to the next matching
1992 flags |= FLAG_BRACE_LAST;
1996 // handle only this single token, leave the loop if done
1997 flags |= FLAG_LEAVE;
2000 if (t.cat() != catEscape && t.character() == ']' &&
2001 (flags & FLAG_BRACK_LAST))
2003 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2006 // If there is anything between \end{env} and \begin{env} we
2007 // don't need to output a separator.
2008 if (t.cat() != catSpace && t.cat() != catNewline &&
2009 t.asInput() != "\\begin")
2015 if (t.cat() == catMath) {
2016 // we are inside some text mode thingy, so opening new math is allowed
2017 context.check_layout(os);
2018 begin_inset(os, "Formula ");
2019 Token const & n = p.get_token();
2020 bool const display(n.cat() == catMath && outer);
2022 // TeX's $$...$$ syntax for displayed math
2024 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2026 p.get_token(); // skip the second '$' token
2028 // simple $...$ stuff
2031 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2036 // Prevent the conversion of a line break to a
2037 // space (bug 7668). This does not change the
2038 // output, but looks ugly in LyX.
2039 eat_whitespace(p, os, context, false);
2043 else if (t.cat() == catSuper || t.cat() == catSub)
2044 cerr << "catcode " << t << " illegal in text mode\n";
2046 // Basic support for english quotes. This should be
2047 // extended to other quotes, but is not so easy (a
2048 // left english quote is the same as a right german
2050 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2051 context.check_layout(os);
2052 begin_inset(os, "Quotes ");
2058 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2059 context.check_layout(os);
2060 begin_inset(os, "Quotes ");
2067 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2068 context.check_layout(os);
2069 begin_inset(os, "Quotes ");
2076 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
2077 context.check_layout(os);
2078 begin_inset(os, "Quotes ");
2085 else if (t.asInput() == "<"
2086 && p.next_token().asInput() == "<" && noweb_mode) {
2088 parse_noweb(p, os, context);
2091 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2092 check_space(p, os, context);
2094 else if (t.character() == '[' && noweb_mode &&
2095 p.next_token().character() == '[') {
2096 // These can contain underscores
2098 string const s = p.getFullOpt() + ']';
2099 if (p.next_token().character() == ']')
2102 cerr << "Warning: Inserting missing ']' in '"
2103 << s << "'." << endl;
2104 handle_ert(os, s, context);
2107 else if (t.cat() == catLetter) {
2108 context.check_layout(os);
2109 // Workaround for bug 4752.
2110 // FIXME: This whole code block needs to be removed
2111 // when the bug is fixed and tex2lyx produces
2112 // the updated file format.
2113 // The replacement algorithm in LyX is so stupid that
2114 // it even translates a phrase if it is part of a word.
2115 bool handled = false;
2116 for (int const * l = known_phrase_lengths; *l; ++l) {
2117 string phrase = t.cs();
2118 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
2119 phrase += p.get_token().cs();
2120 if (is_known(phrase, known_coded_phrases)) {
2121 handle_ert(os, phrase, context);
2125 for (size_t i = 1; i < phrase.length(); ++i)
2133 else if (t.cat() == catOther ||
2134 t.cat() == catAlign ||
2135 t.cat() == catParameter) {
2136 // This translates "&" to "\\&" which may be wrong...
2137 context.check_layout(os);
2141 else if (p.isParagraph()) {
2142 if (context.new_layout_allowed)
2143 context.new_paragraph(os);
2145 handle_ert(os, "\\par ", context);
2146 eat_whitespace(p, os, context, true);
2149 else if (t.cat() == catActive) {
2150 context.check_layout(os);
2151 if (t.character() == '~') {
2152 if (context.layout->free_spacing)
2155 begin_inset(os, "space ~\n");
2162 else if (t.cat() == catBegin) {
2163 Token const next = p.next_token();
2164 Token const end = p.next_next_token();
2165 if (next.cat() == catEnd) {
2167 Token const prev = p.prev_token();
2169 if (p.next_token().character() == '`' ||
2170 (prev.character() == '-' &&
2171 p.next_token().character() == '-'))
2172 ; // ignore it in {}`` or -{}-
2174 handle_ert(os, "{}", context);
2175 } else if (next.cat() == catEscape &&
2176 is_known(next.cs(), known_quotes) &&
2177 end.cat() == catEnd) {
2178 // Something like {\textquoteright} (e.g.
2179 // from writer2latex). LyX writes
2180 // \textquoteright{}, so we may skip the
2181 // braces here for better readability.
2182 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2185 context.check_layout(os);
2186 // special handling of font attribute changes
2187 Token const prev = p.prev_token();
2188 TeXFont const oldFont = context.font;
2189 if (next.character() == '[' ||
2190 next.character() == ']' ||
2191 next.character() == '*') {
2193 if (p.next_token().cat() == catEnd) {
2198 handle_ert(os, "{", context);
2199 parse_text_snippet(p, os,
2202 handle_ert(os, "}", context);
2204 } else if (! context.new_layout_allowed) {
2205 handle_ert(os, "{", context);
2206 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2208 handle_ert(os, "}", context);
2209 } else if (is_known(next.cs(), known_sizes)) {
2210 // next will change the size, so we must
2212 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2214 if (!context.atParagraphStart())
2216 << context.font.size << "\n";
2217 } else if (is_known(next.cs(), known_font_families)) {
2218 // next will change the font family, so we
2219 // must reset it here
2220 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2222 if (!context.atParagraphStart())
2224 << context.font.family << "\n";
2225 } else if (is_known(next.cs(), known_font_series)) {
2226 // next will change the font series, so we
2227 // must reset it here
2228 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2230 if (!context.atParagraphStart())
2232 << context.font.series << "\n";
2233 } else if (is_known(next.cs(), known_font_shapes)) {
2234 // next will change the font shape, so we
2235 // must reset it here
2236 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2238 if (!context.atParagraphStart())
2240 << context.font.shape << "\n";
2241 } else if (is_known(next.cs(), known_old_font_families) ||
2242 is_known(next.cs(), known_old_font_series) ||
2243 is_known(next.cs(), known_old_font_shapes)) {
2244 // next will change the font family, series
2245 // and shape, so we must reset it here
2246 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2248 if (!context.atParagraphStart())
2250 << context.font.family
2252 << context.font.series
2254 << context.font.shape << "\n";
2256 handle_ert(os, "{", context);
2257 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2259 handle_ert(os, "}", context);
2264 else if (t.cat() == catEnd) {
2265 if (flags & FLAG_BRACE_LAST) {
2268 cerr << "stray '}' in text\n";
2269 handle_ert(os, "}", context);
2272 else if (t.cat() == catComment)
2273 parse_comment(p, os, t, context);
2276 // control sequences
2279 else if (t.cs() == "(") {
2280 context.check_layout(os);
2281 begin_inset(os, "Formula");
2283 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2288 else if (t.cs() == "[") {
2289 context.check_layout(os);
2290 begin_inset(os, "Formula");
2292 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2295 // Prevent the conversion of a line break to a space
2296 // (bug 7668). This does not change the output, but
2297 // looks ugly in LyX.
2298 eat_whitespace(p, os, context, false);
2301 else if (t.cs() == "begin")
2302 parse_environment(p, os, outer, last_env,
2305 else if (t.cs() == "end") {
2306 if (flags & FLAG_END) {
2307 // eat environment name
2308 string const name = p.getArg('{', '}');
2309 if (name != active_environment())
2310 cerr << "\\end{" + name + "} does not match \\begin{"
2311 + active_environment() + "}\n";
2314 p.error("found 'end' unexpectedly");
2317 else if (t.cs() == "item") {
2319 bool const optarg = p.hasOpt();
2321 // FIXME: This swallows comments, but we cannot use
2322 // eat_whitespace() since we must not output
2323 // anything before the item.
2324 p.skip_spaces(true);
2325 s = p.verbatimOption();
2327 p.skip_spaces(false);
2329 context.check_layout(os);
2330 if (context.has_item) {
2331 // An item in an unknown list-like environment
2332 // FIXME: Do this in check_layout()!
2333 context.has_item = false;
2335 handle_ert(os, "\\item", context);
2337 handle_ert(os, "\\item ", context);
2340 if (context.layout->labeltype != LABEL_MANUAL) {
2341 // LyX does not support \item[\mybullet]
2342 // in itemize environments
2344 os << parse_text_snippet(p2,
2345 FLAG_BRACK_LAST, outer, context);
2346 } else if (!s.empty()) {
2347 // LyX adds braces around the argument,
2348 // so we need to remove them here.
2349 if (s.size() > 2 && s[0] == '{' &&
2350 s[s.size()-1] == '}')
2351 s = s.substr(1, s.size()-2);
2352 // If the argument contains a space we
2353 // must put it into ERT: Otherwise LyX
2354 // would misinterpret the space as
2355 // item delimiter (bug 7663)
2356 if (contains(s, ' ')) {
2357 handle_ert(os, s, context);
2360 os << parse_text_snippet(p2,
2364 // The space is needed to separate the
2365 // item from the rest of the sentence.
2367 eat_whitespace(p, os, context, false);
2372 else if (t.cs() == "bibitem") {
2374 context.check_layout(os);
2375 eat_whitespace(p, os, context, false);
2376 string label = convert_command_inset_arg(p.verbatimOption());
2377 string key = convert_command_inset_arg(p.verbatim_item());
2378 if (contains(label, '\\') || contains(key, '\\')) {
2379 // LyX can't handle LaTeX commands in labels or keys
2380 handle_ert(os, t.asInput() + '[' + label +
2381 "]{" + p.verbatim_item() + '}',
2384 begin_command_inset(os, "bibitem", "bibitem");
2385 os << "label \"" << label << "\"\n"
2386 "key \"" << key << "\"\n";
2391 else if (is_macro(p)) {
2392 // catch the case of \def\inputGnumericTable
2394 if (t.cs() == "def") {
2395 Token second = p.next_token();
2396 if (second.cs() == "inputGnumericTable") {
2400 Token third = p.get_token();
2402 if (third.cs() == "input") {
2406 string name = normalize_filename(p.verbatim_item());
2407 string const path = getMasterFilePath();
2408 // We want to preserve relative / absolute filenames,
2409 // therefore path is only used for testing
2410 // The file extension is in every case ".tex".
2411 // So we need to remove this extension and check for
2412 // the original one.
2413 name = removeExtension(name);
2414 if (!makeAbsPath(name, path).exists()) {
2415 char const * const Gnumeric_formats[] = {"gnumeric",
2417 string const Gnumeric_name =
2418 find_file(name, path, Gnumeric_formats);
2419 if (!Gnumeric_name.empty())
2420 name = Gnumeric_name;
2422 if (makeAbsPath(name, path).exists())
2423 fix_relative_filename(name);
2425 cerr << "Warning: Could not find file '"
2426 << name << "'." << endl;
2427 context.check_layout(os);
2428 begin_inset(os, "External\n\ttemplate ");
2429 os << "GnumericSpreadsheet\n\tfilename "
2432 context.check_layout(os);
2434 // register the packages that are automatically reloaded
2435 // by the Gnumeric template
2436 registerExternalTemplatePackages("GnumericSpreadsheet");
2441 parse_macro(p, os, context);
2444 else if (t.cs() == "noindent") {
2446 context.add_par_extra_stuff("\\noindent\n");
2449 else if (t.cs() == "appendix") {
2450 context.add_par_extra_stuff("\\start_of_appendix\n");
2451 // We need to start a new paragraph. Otherwise the
2452 // appendix in 'bla\appendix\chapter{' would start
2454 context.new_paragraph(os);
2455 // We need to make sure that the paragraph is
2456 // generated even if it is empty. Otherwise the
2457 // appendix in '\par\appendix\par\chapter{' would
2459 context.check_layout(os);
2460 // FIXME: This is a hack to prevent paragraph
2461 // deletion if it is empty. Handle this better!
2463 "%dummy comment inserted by tex2lyx to "
2464 "ensure that this paragraph is not empty",
2466 // Both measures above may generate an additional
2467 // empty paragraph, but that does not hurt, because
2468 // whitespace does not matter here.
2469 eat_whitespace(p, os, context, true);
2472 // Must catch empty dates before findLayout is called below
2473 else if (t.cs() == "date") {
2474 eat_whitespace(p, os, context, false);
2476 string const date = p.verbatim_item();
2479 preamble.suppressDate(true);
2482 preamble.suppressDate(false);
2483 if (context.new_layout_allowed &&
2484 (newlayout = findLayout(context.textclass,
2487 output_command_layout(os, p, outer,
2488 context, newlayout);
2489 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2490 if (!preamble.titleLayoutFound())
2491 preamble.titleLayoutFound(newlayout->intitle);
2492 set<string> const & req = newlayout->requires();
2493 set<string>::const_iterator it = req.begin();
2494 set<string>::const_iterator en = req.end();
2495 for (; it != en; ++it)
2496 preamble.registerAutomaticallyLoadedPackage(*it);
2499 "\\date{" + p.verbatim_item() + '}',
2504 // Starred section headings
2505 // Must attempt to parse "Section*" before "Section".
2506 else if ((p.next_token().asInput() == "*") &&
2507 context.new_layout_allowed &&
2508 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2511 output_command_layout(os, p, outer, context, newlayout);
2513 if (!preamble.titleLayoutFound())
2514 preamble.titleLayoutFound(newlayout->intitle);
2515 set<string> const & req = newlayout->requires();
2516 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2517 preamble.registerAutomaticallyLoadedPackage(*it);
2520 // Section headings and the like
2521 else if (context.new_layout_allowed &&
2522 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2524 output_command_layout(os, p, outer, context, newlayout);
2526 if (!preamble.titleLayoutFound())
2527 preamble.titleLayoutFound(newlayout->intitle);
2528 set<string> const & req = newlayout->requires();
2529 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2530 preamble.registerAutomaticallyLoadedPackage(*it);
2533 else if (t.cs() == "caption") {
2535 context.check_layout(os);
2537 begin_inset(os, "Caption\n");
2538 Context newcontext(true, context.textclass);
2539 newcontext.font = context.font;
2540 newcontext.check_layout(os);
2541 if (p.next_token().cat() != catEscape &&
2542 p.next_token().character() == '[') {
2543 p.get_token(); // eat '['
2544 begin_inset(os, "Argument\n");
2545 os << "status collapsed\n";
2546 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2548 eat_whitespace(p, os, context, false);
2550 parse_text(p, os, FLAG_ITEM, outer, context);
2551 context.check_end_layout(os);
2552 // We don't need really a new paragraph, but
2553 // we must make sure that the next item gets a \begin_layout.
2554 context.new_paragraph(os);
2557 newcontext.check_end_layout(os);
2560 else if (t.cs() == "subfloat") {
2561 // the syntax is \subfloat[caption]{content}
2562 // if it is a table of figure depends on the surrounding float
2563 bool has_caption = false;
2565 // do nothing if there is no outer float
2566 if (!float_type.empty()) {
2567 context.check_layout(os);
2569 begin_inset(os, "Float " + float_type + "\n");
2571 << "\nsideways false"
2572 << "\nstatus collapsed\n\n";
2575 if (p.next_token().cat() != catEscape &&
2576 p.next_token().character() == '[') {
2577 p.get_token(); // eat '['
2578 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2582 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2583 // the caption comes always as the last
2585 // we must make sure that the caption gets a \begin_layout
2586 os << "\n\\begin_layout Plain Layout";
2588 begin_inset(os, "Caption\n");
2589 Context newcontext(true, context.textclass);
2590 newcontext.font = context.font;
2591 newcontext.check_layout(os);
2592 os << caption << "\n";
2593 newcontext.check_end_layout(os);
2594 // We don't need really a new paragraph, but
2595 // we must make sure that the next item gets a \begin_layout.
2596 //newcontext.new_paragraph(os);
2600 // We don't need really a new paragraph, but
2601 // we must make sure that the next item gets a \begin_layout.
2603 context.new_paragraph(os);
2606 context.check_end_layout(os);
2607 // close the layout we opened
2609 os << "\n\\end_layout\n";
2611 // if the float type is not supported or there is no surrounding float
2614 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2615 handle_ert(os, t.asInput() + '[' + opt_arg +
2616 "]{" + p.verbatim_item() + '}', context);
2618 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2622 else if (t.cs() == "includegraphics") {
2623 bool const clip = p.next_token().asInput() == "*";
2626 string const arg = p.getArg('[', ']');
2627 map<string, string> opts;
2628 vector<string> keys;
2629 split_map(arg, opts, keys);
2631 opts["clip"] = string();
2632 string name = normalize_filename(p.verbatim_item());
2634 string const path = getMasterFilePath();
2635 // We want to preserve relative / absolute filenames,
2636 // therefore path is only used for testing
2637 if (!makeAbsPath(name, path).exists()) {
2638 // The file extension is probably missing.
2639 // Now try to find it out.
2640 string const dvips_name =
2641 find_file(name, path,
2642 known_dvips_graphics_formats);
2643 string const pdftex_name =
2644 find_file(name, path,
2645 known_pdftex_graphics_formats);
2646 if (!dvips_name.empty()) {
2647 if (!pdftex_name.empty()) {
2648 cerr << "This file contains the "
2650 "\"\\includegraphics{"
2652 "However, files\n\""
2653 << dvips_name << "\" and\n\""
2654 << pdftex_name << "\"\n"
2655 "both exist, so I had to make a "
2656 "choice and took the first one.\n"
2657 "Please move the unwanted one "
2658 "someplace else and try again\n"
2659 "if my choice was wrong."
2663 } else if (!pdftex_name.empty()) {
2669 if (makeAbsPath(name, path).exists())
2670 fix_relative_filename(name);
2672 cerr << "Warning: Could not find graphics file '"
2673 << name << "'." << endl;
2675 context.check_layout(os);
2676 begin_inset(os, "Graphics ");
2677 os << "\n\tfilename " << name << '\n';
2678 if (opts.find("width") != opts.end())
2680 << translate_len(opts["width"]) << '\n';
2681 if (opts.find("height") != opts.end())
2683 << translate_len(opts["height"]) << '\n';
2684 if (opts.find("scale") != opts.end()) {
2685 istringstream iss(opts["scale"]);
2689 os << "\tscale " << val << '\n';
2691 if (opts.find("angle") != opts.end()) {
2692 os << "\trotateAngle "
2693 << opts["angle"] << '\n';
2694 vector<string>::const_iterator a =
2695 find(keys.begin(), keys.end(), "angle");
2696 vector<string>::const_iterator s =
2697 find(keys.begin(), keys.end(), "width");
2698 if (s == keys.end())
2699 s = find(keys.begin(), keys.end(), "height");
2700 if (s == keys.end())
2701 s = find(keys.begin(), keys.end(), "scale");
2702 if (s != keys.end() && distance(s, a) > 0)
2703 os << "\tscaleBeforeRotation\n";
2705 if (opts.find("origin") != opts.end()) {
2707 string const opt = opts["origin"];
2708 if (opt.find('l') != string::npos) ss << "left";
2709 if (opt.find('r') != string::npos) ss << "right";
2710 if (opt.find('c') != string::npos) ss << "center";
2711 if (opt.find('t') != string::npos) ss << "Top";
2712 if (opt.find('b') != string::npos) ss << "Bottom";
2713 if (opt.find('B') != string::npos) ss << "Baseline";
2714 if (!ss.str().empty())
2715 os << "\trotateOrigin " << ss.str() << '\n';
2717 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2719 if (opts.find("keepaspectratio") != opts.end())
2720 os << "\tkeepAspectRatio\n";
2721 if (opts.find("clip") != opts.end())
2723 if (opts.find("draft") != opts.end())
2725 if (opts.find("bb") != opts.end())
2726 os << "\tBoundingBox "
2727 << opts["bb"] << '\n';
2728 int numberOfbbOptions = 0;
2729 if (opts.find("bbllx") != opts.end())
2730 numberOfbbOptions++;
2731 if (opts.find("bblly") != opts.end())
2732 numberOfbbOptions++;
2733 if (opts.find("bburx") != opts.end())
2734 numberOfbbOptions++;
2735 if (opts.find("bbury") != opts.end())
2736 numberOfbbOptions++;
2737 if (numberOfbbOptions == 4)
2738 os << "\tBoundingBox "
2739 << opts["bbllx"] << " " << opts["bblly"] << " "
2740 << opts["bburx"] << " " << opts["bbury"] << '\n';
2741 else if (numberOfbbOptions > 0)
2742 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2743 numberOfbbOptions = 0;
2744 if (opts.find("natwidth") != opts.end())
2745 numberOfbbOptions++;
2746 if (opts.find("natheight") != opts.end())
2747 numberOfbbOptions++;
2748 if (numberOfbbOptions == 2)
2749 os << "\tBoundingBox 0bp 0bp "
2750 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2751 else if (numberOfbbOptions > 0)
2752 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2753 ostringstream special;
2754 if (opts.find("hiresbb") != opts.end())
2755 special << "hiresbb,";
2756 if (opts.find("trim") != opts.end())
2758 if (opts.find("viewport") != opts.end())
2759 special << "viewport=" << opts["viewport"] << ',';
2760 if (opts.find("totalheight") != opts.end())
2761 special << "totalheight=" << opts["totalheight"] << ',';
2762 if (opts.find("type") != opts.end())
2763 special << "type=" << opts["type"] << ',';
2764 if (opts.find("ext") != opts.end())
2765 special << "ext=" << opts["ext"] << ',';
2766 if (opts.find("read") != opts.end())
2767 special << "read=" << opts["read"] << ',';
2768 if (opts.find("command") != opts.end())
2769 special << "command=" << opts["command"] << ',';
2770 string s_special = special.str();
2771 if (!s_special.empty()) {
2772 // We had special arguments. Remove the trailing ','.
2773 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2775 // TODO: Handle the unknown settings better.
2776 // Warn about invalid options.
2777 // Check whether some option was given twice.
2779 preamble.registerAutomaticallyLoadedPackage("graphicx");
2782 else if (t.cs() == "footnote" ||
2783 (t.cs() == "thanks" && context.layout->intitle)) {
2785 context.check_layout(os);
2786 begin_inset(os, "Foot\n");
2787 os << "status collapsed\n\n";
2788 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2792 else if (t.cs() == "marginpar") {
2794 context.check_layout(os);
2795 begin_inset(os, "Marginal\n");
2796 os << "status collapsed\n\n";
2797 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2801 else if (t.cs() == "lstinline") {
2803 parse_listings(p, os, context, true);
2806 else if (t.cs() == "ensuremath") {
2808 context.check_layout(os);
2809 string const s = p.verbatim_item();
2810 //FIXME: this never triggers in UTF8
2811 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2814 handle_ert(os, "\\ensuremath{" + s + "}",
2818 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2819 if (preamble.titleLayoutFound()) {
2821 skip_spaces_braces(p);
2823 handle_ert(os, t.asInput(), context);
2826 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
2827 context.check_layout(os);
2828 begin_command_inset(os, "toc", t.cs());
2830 skip_spaces_braces(p);
2831 if (t.cs() == "lstlistoflistings")
2832 preamble.registerAutomaticallyLoadedPackage("listings");
2835 else if (t.cs() == "listoffigures") {
2836 context.check_layout(os);
2837 begin_inset(os, "FloatList figure\n");
2839 skip_spaces_braces(p);
2842 else if (t.cs() == "listoftables") {
2843 context.check_layout(os);
2844 begin_inset(os, "FloatList table\n");
2846 skip_spaces_braces(p);
2849 else if (t.cs() == "listof") {
2850 p.skip_spaces(true);
2851 string const name = p.get_token().cs();
2852 if (context.textclass.floats().typeExist(name)) {
2853 context.check_layout(os);
2854 begin_inset(os, "FloatList ");
2857 p.get_token(); // swallow second arg
2859 handle_ert(os, "\\listof{" + name + "}", context);
2862 else if ((where = is_known(t.cs(), known_text_font_families)))
2863 parse_text_attributes(p, os, FLAG_ITEM, outer,
2864 context, "\\family", context.font.family,
2865 known_coded_font_families[where - known_text_font_families]);
2867 else if ((where = is_known(t.cs(), known_text_font_series)))
2868 parse_text_attributes(p, os, FLAG_ITEM, outer,
2869 context, "\\series", context.font.series,
2870 known_coded_font_series[where - known_text_font_series]);
2872 else if ((where = is_known(t.cs(), known_text_font_shapes)))
2873 parse_text_attributes(p, os, FLAG_ITEM, outer,
2874 context, "\\shape", context.font.shape,
2875 known_coded_font_shapes[where - known_text_font_shapes]);
2877 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2878 context.check_layout(os);
2879 TeXFont oldFont = context.font;
2880 context.font.init();
2881 context.font.size = oldFont.size;
2882 os << "\n\\family " << context.font.family << "\n";
2883 os << "\n\\series " << context.font.series << "\n";
2884 os << "\n\\shape " << context.font.shape << "\n";
2885 if (t.cs() == "textnormal") {
2886 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2887 output_font_change(os, context.font, oldFont);
2888 context.font = oldFont;
2890 eat_whitespace(p, os, context, false);
2893 else if (t.cs() == "textcolor") {
2894 // scheme is \textcolor{color name}{text}
2895 string const color = p.verbatim_item();
2896 // we only support the predefined colors of the color package
2897 if (color == "black" || color == "blue" || color == "cyan"
2898 || color == "green" || color == "magenta" || color == "red"
2899 || color == "white" || color == "yellow") {
2900 context.check_layout(os);
2901 os << "\n\\color " << color << "\n";
2902 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2903 context.check_layout(os);
2904 os << "\n\\color inherit\n";
2905 preamble.registerAutomaticallyLoadedPackage("color");
2907 // for custom defined colors
2908 handle_ert(os, t.asInput() + "{" + color + "}", context);
2911 else if (t.cs() == "underbar" || t.cs() == "uline") {
2912 // \underbar is not 100% correct (LyX outputs \uline
2913 // of ulem.sty). The difference is that \ulem allows
2914 // line breaks, and \underbar does not.
2915 // Do NOT handle \underline.
2916 // \underbar cuts through y, g, q, p etc.,
2917 // \underline does not.
2918 context.check_layout(os);
2919 os << "\n\\bar under\n";
2920 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2921 context.check_layout(os);
2922 os << "\n\\bar default\n";
2923 preamble.registerAutomaticallyLoadedPackage("ulem");
2926 else if (t.cs() == "sout") {
2927 context.check_layout(os);
2928 os << "\n\\strikeout on\n";
2929 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2930 context.check_layout(os);
2931 os << "\n\\strikeout default\n";
2932 preamble.registerAutomaticallyLoadedPackage("ulem");
2935 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2936 t.cs() == "emph" || t.cs() == "noun") {
2937 context.check_layout(os);
2938 os << "\n\\" << t.cs() << " on\n";
2939 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2940 context.check_layout(os);
2941 os << "\n\\" << t.cs() << " default\n";
2942 if (t.cs() == "uuline" || t.cs() == "uwave")
2943 preamble.registerAutomaticallyLoadedPackage("ulem");
2946 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
2947 context.check_layout(os);
2948 string name = p.getArg('{', '}');
2949 string localtime = p.getArg('{', '}');
2950 preamble.registerAuthor(name);
2951 Author const & author = preamble.getAuthor(name);
2952 // from_ctime() will fail if LyX decides to output the
2953 // time in the text language. It might also use a wrong
2954 // time zone (if the original LyX document was exported
2955 // with a different time zone).
2956 time_t ptime = from_ctime(localtime);
2957 if (ptime == static_cast<time_t>(-1)) {
2958 cerr << "Warning: Could not parse time `" << localtime
2959 << "´ for change tracking, using current time instead.\n";
2960 ptime = current_time();
2962 if (t.cs() == "lyxadded")
2963 os << "\n\\change_inserted ";
2965 os << "\n\\change_deleted ";
2966 os << author.bufferId() << ' ' << ptime << '\n';
2967 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2968 bool dvipost = LaTeXPackages::isAvailable("dvipost");
2969 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
2970 LaTeXPackages::isAvailable("xcolor");
2971 // No need to test for luatex, since luatex comes in
2972 // two flavours (dvi and pdf), like latex, and those
2973 // are detected by pdflatex.
2974 if (pdflatex || xetex) {
2976 preamble.registerAutomaticallyLoadedPackage("ulem");
2977 preamble.registerAutomaticallyLoadedPackage("xcolor");
2978 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
2982 preamble.registerAutomaticallyLoadedPackage("dvipost");
2983 } else if (xcolorulem) {
2984 preamble.registerAutomaticallyLoadedPackage("ulem");
2985 preamble.registerAutomaticallyLoadedPackage("xcolor");
2990 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2991 t.cs() == "vphantom") {
2992 context.check_layout(os);
2993 if (t.cs() == "phantom")
2994 begin_inset(os, "Phantom Phantom\n");
2995 if (t.cs() == "hphantom")
2996 begin_inset(os, "Phantom HPhantom\n");
2997 if (t.cs() == "vphantom")
2998 begin_inset(os, "Phantom VPhantom\n");
2999 os << "status open\n";
3000 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3005 else if (t.cs() == "href") {
3006 context.check_layout(os);
3007 string target = p.getArg('{', '}');
3008 string name = p.getArg('{', '}');
3010 size_t i = target.find(':');
3011 if (i != string::npos) {
3012 type = target.substr(0, i + 1);
3013 if (type == "mailto:" || type == "file:")
3014 target = target.substr(i + 1);
3015 // handle the case that name is equal to target, except of "http://"
3016 else if (target.substr(i + 3) == name && type == "http:")
3019 begin_command_inset(os, "href", "href");
3021 os << "name \"" << name << "\"\n";
3022 os << "target \"" << target << "\"\n";
3023 if (type == "mailto:" || type == "file:")
3024 os << "type \"" << type << "\"\n";
3026 skip_spaces_braces(p);
3029 else if (t.cs() == "lyxline") {
3030 // swallow size argument (it is not used anyway)
3032 if (!context.atParagraphStart()) {
3033 // so our line is in the middle of a paragraph
3034 // we need to add a new line, lest this line
3035 // follow the other content on that line and
3036 // run off the side of the page
3037 // FIXME: This may create an empty paragraph,
3038 // but without that it would not be
3039 // possible to set noindent below.
3040 // Fortunately LaTeX does not care
3041 // about the empty paragraph.
3042 context.new_paragraph(os);
3044 if (preamble.indentParagraphs()) {
3045 // we need to unindent, lest the line be too long
3046 context.add_par_extra_stuff("\\noindent\n");
3048 context.check_layout(os);
3049 begin_command_inset(os, "line", "rule");
3050 os << "offset \"0.5ex\"\n"
3051 "width \"100line%\"\n"
3056 else if (t.cs() == "rule") {
3057 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3058 string const width = p.getArg('{', '}');
3059 string const thickness = p.getArg('{', '}');
3060 context.check_layout(os);
3061 begin_command_inset(os, "line", "rule");
3062 if (!offset.empty())
3063 os << "offset \"" << translate_len(offset) << "\"\n";
3064 os << "width \"" << translate_len(width) << "\"\n"
3065 "height \"" << translate_len(thickness) << "\"\n";
3069 else if (is_known(t.cs(), known_phrases) ||
3070 (t.cs() == "protect" &&
3071 p.next_token().cat() == catEscape &&
3072 is_known(p.next_token().cs(), known_phrases))) {
3073 // LyX sometimes puts a \protect in front, so we have to ignore it
3074 // FIXME: This needs to be changed when bug 4752 is fixed.
3076 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3078 context.check_layout(os);
3079 os << known_coded_phrases[where - known_phrases];
3080 skip_spaces_braces(p);
3083 else if ((where = is_known(t.cs(), known_ref_commands))) {
3084 string const opt = p.getOpt();
3086 context.check_layout(os);
3087 begin_command_inset(os, "ref",
3088 known_coded_ref_commands[where - known_ref_commands]);
3089 os << "reference \""
3090 << convert_command_inset_arg(p.verbatim_item())
3093 if (t.cs() == "vref" || t.cs() == "vpageref")
3094 preamble.registerAutomaticallyLoadedPackage("varioref");
3097 // LyX does not support optional arguments of ref commands
3098 handle_ert(os, t.asInput() + '[' + opt + "]{" +
3099 p.verbatim_item() + "}", context);
3103 else if (use_natbib &&
3104 is_known(t.cs(), known_natbib_commands) &&
3105 ((t.cs() != "citefullauthor" &&
3106 t.cs() != "citeyear" &&
3107 t.cs() != "citeyearpar") ||
3108 p.next_token().asInput() != "*")) {
3109 context.check_layout(os);
3110 string command = t.cs();
3111 if (p.next_token().asInput() == "*") {
3115 if (command == "citefullauthor")
3116 // alternative name for "\\citeauthor*"
3117 command = "citeauthor*";
3119 // text before the citation
3121 // text after the citation
3123 get_cite_arguments(p, true, before, after);
3125 if (command == "cite") {
3126 // \cite without optional argument means
3127 // \citet, \cite with at least one optional
3128 // argument means \citep.
3129 if (before.empty() && after.empty())
3134 if (before.empty() && after == "[]")
3135 // avoid \citet[]{a}
3137 else if (before == "[]" && after == "[]") {
3138 // avoid \citet[][]{a}
3142 // remove the brackets around after and before
3143 if (!after.empty()) {
3145 after.erase(after.length() - 1, 1);
3146 after = convert_command_inset_arg(after);
3148 if (!before.empty()) {
3150 before.erase(before.length() - 1, 1);
3151 before = convert_command_inset_arg(before);
3153 begin_command_inset(os, "citation", command);
3154 os << "after " << '"' << after << '"' << "\n";
3155 os << "before " << '"' << before << '"' << "\n";
3157 << convert_command_inset_arg(p.verbatim_item())
3162 else if (use_jurabib &&
3163 is_known(t.cs(), known_jurabib_commands) &&
3164 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3165 context.check_layout(os);
3166 string command = t.cs();
3167 if (p.next_token().asInput() == "*") {
3171 char argumentOrder = '\0';
3172 vector<string> const options =
3173 preamble.getPackageOptions("jurabib");
3174 if (find(options.begin(), options.end(),
3175 "natbiborder") != options.end())
3176 argumentOrder = 'n';
3177 else if (find(options.begin(), options.end(),
3178 "jurabiborder") != options.end())
3179 argumentOrder = 'j';
3181 // text before the citation
3183 // text after the citation
3185 get_cite_arguments(p, argumentOrder != 'j', before, after);
3187 string const citation = p.verbatim_item();
3188 if (!before.empty() && argumentOrder == '\0') {
3189 cerr << "Warning: Assuming argument order "
3190 "of jurabib version 0.6 for\n'"
3191 << command << before << after << '{'
3192 << citation << "}'.\n"
3193 "Add 'jurabiborder' to the jurabib "
3194 "package options if you used an\n"
3195 "earlier jurabib version." << endl;
3197 if (!after.empty()) {
3199 after.erase(after.length() - 1, 1);
3201 if (!before.empty()) {
3203 before.erase(before.length() - 1, 1);
3205 begin_command_inset(os, "citation", command);
3206 os << "after " << '"' << after << '"' << "\n";
3207 os << "before " << '"' << before << '"' << "\n";
3208 os << "key " << '"' << citation << '"' << "\n";
3212 else if (t.cs() == "cite"
3213 || t.cs() == "nocite") {
3214 context.check_layout(os);
3215 string after = convert_command_inset_arg(p.getArg('[', ']'));
3216 string key = convert_command_inset_arg(p.verbatim_item());
3217 // store the case that it is "\nocite{*}" to use it later for
3220 begin_command_inset(os, "citation", t.cs());
3221 os << "after " << '"' << after << '"' << "\n";
3222 os << "key " << '"' << key << '"' << "\n";
3224 } else if (t.cs() == "nocite")
3228 else if (t.cs() == "index" ||
3229 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3230 context.check_layout(os);
3231 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3232 p.getArg('[', ']') : "";
3233 string const kind = arg.empty() ? "idx" : arg;
3234 begin_inset(os, "Index ");
3235 os << kind << "\nstatus collapsed\n";
3236 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3239 preamble.registerAutomaticallyLoadedPackage("splitidx");
3242 else if (t.cs() == "nomenclature") {
3243 context.check_layout(os);
3244 begin_command_inset(os, "nomenclature", "nomenclature");
3245 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3246 if (!prefix.empty())
3247 os << "prefix " << '"' << prefix << '"' << "\n";
3248 os << "symbol " << '"'
3249 << convert_command_inset_arg(p.verbatim_item());
3250 os << "\"\ndescription \""
3251 << convert_command_inset_arg(p.verbatim_item())
3254 preamble.registerAutomaticallyLoadedPackage("nomencl");
3257 else if (t.cs() == "label") {
3258 context.check_layout(os);
3259 begin_command_inset(os, "label", "label");
3261 << convert_command_inset_arg(p.verbatim_item())
3266 else if (t.cs() == "printindex") {
3267 context.check_layout(os);
3268 begin_command_inset(os, "index_print", "printindex");
3269 os << "type \"idx\"\n";
3271 skip_spaces_braces(p);
3272 preamble.registerAutomaticallyLoadedPackage("makeidx");
3273 if (preamble.use_indices() == "true")
3274 preamble.registerAutomaticallyLoadedPackage("splitidx");
3277 else if (t.cs() == "printnomenclature") {
3279 string width_type = "";
3280 context.check_layout(os);
3281 begin_command_inset(os, "nomencl_print", "printnomenclature");
3282 // case of a custom width
3284 width = p.getArg('[', ']');
3285 width = translate_len(width);
3286 width_type = "custom";
3288 // case of no custom width
3289 // the case of no custom width but the width set
3290 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3291 // because the user could have set anything, not only the width
3292 // of the longest label (which would be width_type = "auto")
3293 string label = convert_command_inset_arg(p.getArg('{', '}'));
3294 if (label.empty() && width_type.empty())
3295 width_type = "none";
3296 os << "set_width \"" << width_type << "\"\n";
3297 if (width_type == "custom")
3298 os << "width \"" << width << '\"';
3300 skip_spaces_braces(p);
3301 preamble.registerAutomaticallyLoadedPackage("nomencl");
3304 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3305 context.check_layout(os);
3306 begin_inset(os, "script ");
3307 os << t.cs().substr(4) << '\n';
3308 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3310 if (t.cs() == "textsubscript")
3311 preamble.registerAutomaticallyLoadedPackage("subscript");
3314 else if ((where = is_known(t.cs(), known_quotes))) {
3315 context.check_layout(os);
3316 begin_inset(os, "Quotes ");
3317 os << known_coded_quotes[where - known_quotes];
3319 // LyX adds {} after the quote, so we have to eat
3320 // spaces here if there are any before a possible
3322 eat_whitespace(p, os, context, false);
3326 else if ((where = is_known(t.cs(), known_sizes)) &&
3327 context.new_layout_allowed) {
3328 context.check_layout(os);
3329 TeXFont const oldFont = context.font;
3330 context.font.size = known_coded_sizes[where - known_sizes];
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_families)) &&
3336 context.new_layout_allowed) {
3337 context.check_layout(os);
3338 TeXFont const oldFont = context.font;
3339 context.font.family =
3340 known_coded_font_families[where - known_font_families];
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_series)) &&
3346 context.new_layout_allowed) {
3347 context.check_layout(os);
3348 TeXFont const oldFont = context.font;
3349 context.font.series =
3350 known_coded_font_series[where - known_font_series];
3351 output_font_change(os, oldFont, context.font);
3352 eat_whitespace(p, os, context, false);
3355 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3356 context.new_layout_allowed) {
3357 context.check_layout(os);
3358 TeXFont const oldFont = context.font;
3359 context.font.shape =
3360 known_coded_font_shapes[where - known_font_shapes];
3361 output_font_change(os, oldFont, context.font);
3362 eat_whitespace(p, os, context, false);
3364 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3365 context.new_layout_allowed) {
3366 context.check_layout(os);
3367 TeXFont const oldFont = context.font;
3368 context.font.init();
3369 context.font.size = oldFont.size;
3370 context.font.family =
3371 known_coded_font_families[where - known_old_font_families];
3372 output_font_change(os, oldFont, context.font);
3373 eat_whitespace(p, os, context, false);
3376 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3377 context.new_layout_allowed) {
3378 context.check_layout(os);
3379 TeXFont const oldFont = context.font;
3380 context.font.init();
3381 context.font.size = oldFont.size;
3382 context.font.series =
3383 known_coded_font_series[where - known_old_font_series];
3384 output_font_change(os, oldFont, context.font);
3385 eat_whitespace(p, os, context, false);
3388 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3389 context.new_layout_allowed) {
3390 context.check_layout(os);
3391 TeXFont const oldFont = context.font;
3392 context.font.init();
3393 context.font.size = oldFont.size;
3394 context.font.shape =
3395 known_coded_font_shapes[where - known_old_font_shapes];
3396 output_font_change(os, oldFont, context.font);
3397 eat_whitespace(p, os, context, false);
3400 else if (t.cs() == "selectlanguage") {
3401 context.check_layout(os);
3402 // save the language for the case that a
3403 // \foreignlanguage is used
3405 context.font.language = babel2lyx(p.verbatim_item());
3406 os << "\n\\lang " << context.font.language << "\n";
3409 else if (t.cs() == "foreignlanguage") {
3410 string const lang = babel2lyx(p.verbatim_item());
3411 parse_text_attributes(p, os, FLAG_ITEM, outer,
3413 context.font.language, lang);
3416 else if (t.cs() == "inputencoding") {
3417 // nothing to write here
3418 string const enc = subst(p.verbatim_item(), "\n", " ");
3422 else if ((where = is_known(t.cs(), known_special_chars))) {
3423 context.check_layout(os);
3424 os << "\\SpecialChar \\"
3425 << known_coded_special_chars[where - known_special_chars]
3427 skip_spaces_braces(p);
3430 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3431 context.check_layout(os);
3432 os << "\\SpecialChar \\nobreakdash-\n";
3436 else if (t.cs() == "textquotedbl") {
3437 context.check_layout(os);
3442 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3443 context.check_layout(os);
3444 os << "\\SpecialChar \\@.\n";
3448 else if (t.cs() == "-") {
3449 context.check_layout(os);
3450 os << "\\SpecialChar \\-\n";
3453 else if (t.cs() == "textasciitilde") {
3454 context.check_layout(os);
3456 skip_spaces_braces(p);
3459 else if (t.cs() == "textasciicircum") {
3460 context.check_layout(os);
3462 skip_spaces_braces(p);
3465 else if (t.cs() == "textbackslash") {
3466 context.check_layout(os);
3467 os << "\n\\backslash\n";
3468 skip_spaces_braces(p);
3471 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3472 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3474 context.check_layout(os);
3478 else if (t.cs() == "char") {
3479 context.check_layout(os);
3480 if (p.next_token().character() == '`') {
3482 if (p.next_token().cs() == "\"") {
3487 handle_ert(os, "\\char`", context);
3490 handle_ert(os, "\\char", context);
3494 else if (t.cs() == "verb") {
3495 context.check_layout(os);
3496 char const delimiter = p.next_token().character();
3497 string const arg = p.getArg(delimiter, delimiter);
3499 oss << "\\verb" << delimiter << arg << delimiter;
3500 handle_ert(os, oss.str(), context);
3503 // Problem: \= creates a tabstop inside the tabbing environment
3504 // and else an accent. In the latter case we really would want
3505 // \={o} instead of \= o.
3506 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3507 handle_ert(os, t.asInput(), context);
3509 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3510 else if (t.cs().size() == 1
3511 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3512 context.check_layout(os);
3513 // try to see whether the string is in unicodesymbols
3516 string command = t.asInput() + "{"
3517 + trimSpaceAndEol(p.verbatim_item())
3520 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3521 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3522 termination, rem, &req);
3525 cerr << "When parsing " << command
3526 << ", result is " << to_utf8(s)
3527 << "+" << to_utf8(rem) << endl;
3529 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3530 preamble.registerAutomaticallyLoadedPackage(*it);
3532 // we did not find a non-ert version
3533 handle_ert(os, command, context);
3536 else if (t.cs() == "\\") {
3537 context.check_layout(os);
3539 handle_ert(os, "\\\\" + p.getOpt(), context);
3540 else if (p.next_token().asInput() == "*") {
3542 // getOpt() eats the following space if there
3543 // is no optional argument, but that is OK
3544 // here since it has no effect in the output.
3545 handle_ert(os, "\\\\*" + p.getOpt(), context);
3548 begin_inset(os, "Newline newline");
3553 else if (t.cs() == "newline" ||
3554 (t.cs() == "linebreak" && !p.hasOpt())) {
3555 context.check_layout(os);
3556 begin_inset(os, "Newline ");
3559 skip_spaces_braces(p);
3562 else if (t.cs() == "input" || t.cs() == "include"
3563 || t.cs() == "verbatiminput") {
3564 string name = t.cs();
3565 if (t.cs() == "verbatiminput"
3566 && p.next_token().asInput() == "*")
3567 name += p.get_token().asInput();
3568 context.check_layout(os);
3569 string filename(normalize_filename(p.getArg('{', '}')));
3570 string const path = getMasterFilePath();
3571 // We want to preserve relative / absolute filenames,
3572 // therefore path is only used for testing
3573 if ((t.cs() == "include" || t.cs() == "input") &&
3574 !makeAbsPath(filename, path).exists()) {
3575 // The file extension is probably missing.
3576 // Now try to find it out.
3577 string const tex_name =
3578 find_file(filename, path,
3579 known_tex_extensions);
3580 if (!tex_name.empty())
3581 filename = tex_name;
3583 bool external = false;
3585 if (makeAbsPath(filename, path).exists()) {
3586 string const abstexname =
3587 makeAbsPath(filename, path).absFileName();
3588 string const abslyxname =
3589 changeExtension(abstexname, ".lyx");
3590 string const absfigname =
3591 changeExtension(abstexname, ".fig");
3592 fix_relative_filename(filename);
3593 string const lyxname =
3594 changeExtension(filename, ".lyx");
3596 external = FileName(absfigname).exists();
3597 if (t.cs() == "input") {
3598 string const ext = getExtension(abstexname);
3600 // Combined PS/LaTeX:
3601 // x.eps, x.pstex_t (old xfig)
3602 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3603 FileName const absepsname(
3604 changeExtension(abstexname, ".eps"));
3605 FileName const abspstexname(
3606 changeExtension(abstexname, ".pstex"));
3607 bool const xfigeps =
3608 (absepsname.exists() ||
3609 abspstexname.exists()) &&
3612 // Combined PDF/LaTeX:
3613 // x.pdf, x.pdftex_t (old xfig)
3614 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3615 FileName const abspdfname(
3616 changeExtension(abstexname, ".pdf"));
3617 bool const xfigpdf =
3618 abspdfname.exists() &&
3619 (ext == "pdftex_t" || ext == "pdf_t");
3623 // Combined PS/PDF/LaTeX:
3624 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3625 string const absbase2(
3626 removeExtension(abstexname) + "_pspdftex");
3627 FileName const abseps2name(
3628 addExtension(absbase2, ".eps"));
3629 FileName const abspdf2name(
3630 addExtension(absbase2, ".pdf"));
3631 bool const xfigboth =
3632 abspdf2name.exists() &&
3633 abseps2name.exists() && ext == "pspdftex";
3635 xfig = xfigpdf || xfigeps || xfigboth;
3636 external = external && xfig;
3639 outname = changeExtension(filename, ".fig");
3641 // Don't try to convert, the result
3642 // would be full of ERT.
3644 } else if (t.cs() != "verbatiminput" &&
3645 tex2lyx(abstexname, FileName(abslyxname),
3652 cerr << "Warning: Could not find included file '"
3653 << filename << "'." << endl;
3657 begin_inset(os, "External\n");
3658 os << "\ttemplate XFig\n"
3659 << "\tfilename " << outname << '\n';
3660 registerExternalTemplatePackages("XFig");
3662 begin_command_inset(os, "include", name);
3663 os << "preview false\n"
3664 "filename \"" << outname << "\"\n";
3665 if (t.cs() == "verbatiminput")
3666 preamble.registerAutomaticallyLoadedPackage("verbatim");
3671 else if (t.cs() == "bibliographystyle") {
3672 // store new bibliographystyle
3673 bibliographystyle = p.verbatim_item();
3674 // If any other command than \bibliography and
3675 // \nocite{*} follows, we need to output the style
3676 // (because it might be used by that command).
3677 // Otherwise, it will automatically be output by LyX.
3680 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3681 if (t2.cat() == catBegin)
3683 if (t2.cat() != catEscape)
3685 if (t2.cs() == "nocite") {
3686 if (p.getArg('{', '}') == "*")
3688 } else if (t2.cs() == "bibliography")
3695 "\\bibliographystyle{" + bibliographystyle + '}',
3700 else if (t.cs() == "bibliography") {
3701 context.check_layout(os);
3702 begin_command_inset(os, "bibtex", "bibtex");
3703 if (!btprint.empty()) {
3704 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3705 // clear the string because the next BibTeX inset can be without the
3706 // \nocite{*} option
3709 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3710 // Do we have a bibliographystyle set?
3711 if (!bibliographystyle.empty())
3712 os << "options " << '"' << bibliographystyle << '"' << "\n";
3716 else if (t.cs() == "parbox") {
3717 // Test whether this is an outer box of a shaded box
3719 // swallow arguments
3720 while (p.hasOpt()) {
3722 p.skip_spaces(true);
3725 p.skip_spaces(true);
3727 if (p.next_token().cat() == catBegin)
3729 p.skip_spaces(true);
3730 Token to = p.get_token();
3731 bool shaded = false;
3732 if (to.asInput() == "\\begin") {
3733 p.skip_spaces(true);
3734 if (p.getArg('{', '}') == "shaded")
3739 parse_outer_box(p, os, FLAG_ITEM, outer,
3740 context, "parbox", "shaded");
3742 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3746 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3747 t.cs() == "shadowbox" || t.cs() == "doublebox")
3748 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3750 else if (t.cs() == "framebox") {
3751 if (p.next_token().character() == '(') {
3752 //the syntax is: \framebox(x,y)[position]{content}
3753 string arg = t.asInput();
3754 arg += p.getFullParentheseArg();
3755 arg += p.getFullOpt();
3756 eat_whitespace(p, os, context, false);
3757 handle_ert(os, arg + '{', context);
3758 eat_whitespace(p, os, context, false);
3759 parse_text(p, os, FLAG_ITEM, outer, context);
3760 handle_ert(os, "}", context);
3762 string special = p.getFullOpt();
3763 special += p.getOpt();
3764 parse_outer_box(p, os, FLAG_ITEM, outer,
3765 context, t.cs(), special);
3769 //\makebox() is part of the picture environment and different from \makebox{}
3770 //\makebox{} will be parsed by parse_box
3771 else if (t.cs() == "makebox") {
3772 if (p.next_token().character() == '(') {
3773 //the syntax is: \makebox(x,y)[position]{content}
3774 string arg = t.asInput();
3775 arg += p.getFullParentheseArg();
3776 arg += p.getFullOpt();
3777 eat_whitespace(p, os, context, false);
3778 handle_ert(os, arg + '{', context);
3779 eat_whitespace(p, os, context, false);
3780 parse_text(p, os, FLAG_ITEM, outer, context);
3781 handle_ert(os, "}", context);
3783 //the syntax is: \makebox[width][position]{content}
3784 parse_box(p, os, 0, FLAG_ITEM, outer, context,
3788 else if (t.cs() == "smallskip" ||
3789 t.cs() == "medskip" ||
3790 t.cs() == "bigskip" ||
3791 t.cs() == "vfill") {
3792 context.check_layout(os);
3793 begin_inset(os, "VSpace ");
3796 skip_spaces_braces(p);
3799 else if ((where = is_known(t.cs(), known_spaces))) {
3800 context.check_layout(os);
3801 begin_inset(os, "space ");
3802 os << '\\' << known_coded_spaces[where - known_spaces]
3805 // LaTeX swallows whitespace after all spaces except
3806 // "\\,". We have to do that here, too, because LyX
3807 // adds "{}" which would make the spaces significant.
3809 eat_whitespace(p, os, context, false);
3810 // LyX adds "{}" after all spaces except "\\ " and
3811 // "\\,", so we have to remove "{}".
3812 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3813 // remove the braces after "\\,", too.
3818 else if (t.cs() == "newpage" ||
3819 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3820 t.cs() == "clearpage" ||
3821 t.cs() == "cleardoublepage") {
3822 context.check_layout(os);
3823 begin_inset(os, "Newpage ");
3826 skip_spaces_braces(p);
3829 else if (t.cs() == "DeclareRobustCommand" ||
3830 t.cs() == "DeclareRobustCommandx" ||
3831 t.cs() == "newcommand" ||
3832 t.cs() == "newcommandx" ||
3833 t.cs() == "providecommand" ||
3834 t.cs() == "providecommandx" ||
3835 t.cs() == "renewcommand" ||
3836 t.cs() == "renewcommandx") {
3837 // DeclareRobustCommand, DeclareRobustCommandx,
3838 // providecommand and providecommandx could be handled
3839 // by parse_command(), but we need to call
3840 // add_known_command() here.
3841 string name = t.asInput();
3842 if (p.next_token().asInput() == "*") {
3843 // Starred form. Eat '*'
3847 string const command = p.verbatim_item();
3848 string const opt1 = p.getFullOpt();
3849 string const opt2 = p.getFullOpt();
3850 add_known_command(command, opt1, !opt2.empty());
3851 string const ert = name + '{' + command + '}' +
3853 '{' + p.verbatim_item() + '}';
3855 if (t.cs() == "DeclareRobustCommand" ||
3856 t.cs() == "DeclareRobustCommandx" ||
3857 t.cs() == "providecommand" ||
3858 t.cs() == "providecommandx" ||
3859 name[name.length()-1] == '*')
3860 handle_ert(os, ert, context);
3862 context.check_layout(os);
3863 begin_inset(os, "FormulaMacro");
3869 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3870 // let could be handled by parse_command(),
3871 // but we need to call add_known_command() here.
3872 string ert = t.asInput();
3875 if (p.next_token().cat() == catBegin) {
3876 name = p.verbatim_item();
3877 ert += '{' + name + '}';
3879 name = p.verbatim_item();
3884 if (p.next_token().cat() == catBegin) {
3885 command = p.verbatim_item();
3886 ert += '{' + command + '}';
3888 command = p.verbatim_item();
3891 // If command is known, make name known too, to parse
3892 // its arguments correctly. For this reason we also
3893 // have commands in syntax.default that are hardcoded.
3894 CommandMap::iterator it = known_commands.find(command);
3895 if (it != known_commands.end())
3896 known_commands[t.asInput()] = it->second;
3897 handle_ert(os, ert, context);
3900 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3901 bool starred = false;
3902 if (p.next_token().asInput() == "*") {
3906 string name = t.asInput();
3907 string const length = p.verbatim_item();
3910 bool valid = splitLatexLength(length, valstring, unit);
3911 bool known_hspace = false;
3912 bool known_vspace = false;
3913 bool known_unit = false;
3916 istringstream iss(valstring);
3919 if (t.cs()[0] == 'h') {
3920 if (unit == "\\fill") {
3925 known_hspace = true;
3928 if (unit == "\\smallskipamount") {
3930 known_vspace = true;
3931 } else if (unit == "\\medskipamount") {
3933 known_vspace = true;
3934 } else if (unit == "\\bigskipamount") {
3936 known_vspace = true;
3937 } else if (unit == "\\fill") {
3939 known_vspace = true;
3943 if (!known_hspace && !known_vspace) {
3944 switch (unitFromString(unit)) {
3965 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3966 // Literal horizontal length or known variable
3967 context.check_layout(os);
3968 begin_inset(os, "space ");
3976 if (known_unit && !known_hspace)
3978 << translate_len(length);
3980 } else if (known_unit || known_vspace) {
3981 // Literal vertical length or known variable
3982 context.check_layout(os);
3983 begin_inset(os, "VSpace ");
3991 // LyX can't handle other length variables in Inset VSpace/space
3996 handle_ert(os, name + '{' + unit + '}', context);
3997 else if (value == -1.0)
3998 handle_ert(os, name + "{-" + unit + '}', context);
4000 handle_ert(os, name + '{' + valstring + unit + '}', context);
4002 handle_ert(os, name + '{' + length + '}', context);
4006 // The single '=' is meant here.
4007 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
4009 context.check_layout(os);
4010 begin_inset(os, "Flex ");
4011 os << to_utf8(newinsetlayout->name()) << '\n'
4012 << "status collapsed\n";
4013 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4017 else if (t.cs() == "includepdf") {
4019 string const arg = p.getArg('[', ']');
4020 map<string, string> opts;
4021 vector<string> keys;
4022 split_map(arg, opts, keys);
4023 string name = normalize_filename(p.verbatim_item());
4024 string const path = getMasterFilePath();
4025 // We want to preserve relative / absolute filenames,
4026 // therefore path is only used for testing
4027 if (!makeAbsPath(name, path).exists()) {
4028 // The file extension is probably missing.
4029 // Now try to find it out.
4030 char const * const pdfpages_format[] = {"pdf", 0};
4031 string const pdftex_name =
4032 find_file(name, path, pdfpages_format);
4033 if (!pdftex_name.empty()) {
4038 if (makeAbsPath(name, path).exists())
4039 fix_relative_filename(name);
4041 cerr << "Warning: Could not find file '"
4042 << name << "'." << endl;
4044 context.check_layout(os);
4045 begin_inset(os, "External\n\ttemplate ");
4046 os << "PDFPages\n\tfilename "
4048 // parse the options
4049 if (opts.find("pages") != opts.end())
4050 os << "\textra LaTeX \"pages="
4051 << opts["pages"] << "\"\n";
4052 if (opts.find("angle") != opts.end())
4053 os << "\trotateAngle "
4054 << opts["angle"] << '\n';
4055 if (opts.find("origin") != opts.end()) {
4057 string const opt = opts["origin"];
4058 if (opt == "tl") ss << "topleft";
4059 if (opt == "bl") ss << "bottomleft";
4060 if (opt == "Bl") ss << "baselineleft";
4061 if (opt == "c") ss << "center";
4062 if (opt == "tc") ss << "topcenter";
4063 if (opt == "bc") ss << "bottomcenter";
4064 if (opt == "Bc") ss << "baselinecenter";
4065 if (opt == "tr") ss << "topright";
4066 if (opt == "br") ss << "bottomright";
4067 if (opt == "Br") ss << "baselineright";
4068 if (!ss.str().empty())
4069 os << "\trotateOrigin " << ss.str() << '\n';
4071 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4073 if (opts.find("width") != opts.end())
4075 << translate_len(opts["width"]) << '\n';
4076 if (opts.find("height") != opts.end())
4078 << translate_len(opts["height"]) << '\n';
4079 if (opts.find("keepaspectratio") != opts.end())
4080 os << "\tkeepAspectRatio\n";
4082 context.check_layout(os);
4083 registerExternalTemplatePackages("PDFPages");
4086 else if (t.cs() == "loadgame") {
4088 string name = normalize_filename(p.verbatim_item());
4089 string const path = getMasterFilePath();
4090 // We want to preserve relative / absolute filenames,
4091 // therefore path is only used for testing
4092 if (!makeAbsPath(name, path).exists()) {
4093 // The file extension is probably missing.
4094 // Now try to find it out.
4095 char const * const lyxskak_format[] = {"fen", 0};
4096 string const lyxskak_name =
4097 find_file(name, path, lyxskak_format);
4098 if (!lyxskak_name.empty())
4099 name = lyxskak_name;
4101 if (makeAbsPath(name, path).exists())
4102 fix_relative_filename(name);
4104 cerr << "Warning: Could not find file '"
4105 << name << "'." << endl;
4106 context.check_layout(os);
4107 begin_inset(os, "External\n\ttemplate ");
4108 os << "ChessDiagram\n\tfilename "
4111 context.check_layout(os);
4112 // after a \loadgame follows a \showboard
4113 if (p.get_token().asInput() == "showboard")
4115 registerExternalTemplatePackages("ChessDiagram");
4119 // try to see whether the string is in unicodesymbols
4120 // Only use text mode commands, since we are in text mode here,
4121 // and math commands may be invalid (bug 6797)
4125 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
4126 Encodings::TEXT_CMD, termination, rem, &req);
4129 cerr << "When parsing " << t.cs()
4130 << ", result is " << to_utf8(s)
4131 << "+" << to_utf8(rem) << endl;
4132 context.check_layout(os);
4135 skip_spaces_braces(p);
4136 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4137 preamble.registerAutomaticallyLoadedPackage(*it);
4139 //cerr << "#: " << t << " mode: " << mode << endl;
4140 // heuristic: read up to next non-nested space
4142 string s = t.asInput();
4143 string z = p.verbatim_item();
4144 while (p.good() && z != " " && z.size()) {
4145 //cerr << "read: " << z << endl;
4147 z = p.verbatim_item();
4149 cerr << "found ERT: " << s << endl;
4150 handle_ert(os, s + ' ', context);
4153 string name = t.asInput();
4154 if (p.next_token().asInput() == "*") {
4155 // Starred commands like \vspace*{}
4156 p.get_token(); // Eat '*'
4159 if (!parse_command(name, p, os, outer, context))
4160 handle_ert(os, name, context);
4164 if (flags & FLAG_LEAVE) {
4165 flags &= ~FLAG_LEAVE;