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;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
130 bool wasBoxAlign = false;
132 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
133 "vpageref", "prettyref", "nameref", "eqref", 0 };
135 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
136 "vpageref", "formatted", "nameref", "eqref", 0 };
138 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
139 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
140 "secref", "subref", "tabref", "thmref", 0 };
142 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
143 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
144 "sec", "sub", "tab", "thm", 0 };
148 * supported CJK encodings
149 * JIS does not work with LyX's encoding conversion
151 const char * const supported_CJK_encodings[] = {
152 "EUC-JP", "KS", "GB", "UTF8",
153 "Bg5", /*"JIS",*/ "SJIS", 0};
156 * the same as supported_CJK_encodings with their corresponding LyX language name
157 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
159 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
160 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
161 * please keep this in sync with supported_CJK_encodings line by line!
163 const char * const supported_CJK_languages[] = {
164 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
165 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
169 * The starred forms are also known except for "citefullauthor",
170 * "citeyear" and "citeyearpar".
172 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
173 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
174 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
178 * No starred form other than "cite*" known.
180 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 // jurabib commands not (yet) supported by LyX:
184 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
185 // "footciteauthor", "footciteyear", "footciteyearpar",
186 "citefield", "citetitle", 0 };
188 /// LaTeX names for quotes
189 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
190 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
191 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
192 "guilsinglleft", "frq", "guilsinglright", 0};
194 /// the same as known_quotes with .lyx names
195 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
196 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
197 "gld", "grd", "gls", "ers", "fls",
198 "fls", "frs", "frs", 0};
200 /// LaTeX names for font sizes
201 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
202 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
204 /// the same as known_sizes with .lyx names
205 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
206 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
208 /// LaTeX 2.09 names for font families
209 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
211 /// LaTeX names for font families
212 char const * const known_font_families[] = { "rmfamily", "sffamily",
215 /// LaTeX names for font family changing commands
216 char const * const known_text_font_families[] = { "textrm", "textsf",
219 /// The same as known_old_font_families, known_font_families and
220 /// known_text_font_families with .lyx names
221 char const * const known_coded_font_families[] = { "roman", "sans",
224 /// LaTeX 2.09 names for font series
225 char const * const known_old_font_series[] = { "bf", 0};
227 /// LaTeX names for font series
228 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
230 /// LaTeX names for font series changing commands
231 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
233 /// The same as known_old_font_series, known_font_series and
234 /// known_text_font_series with .lyx names
235 char const * const known_coded_font_series[] = { "bold", "medium", 0};
237 /// LaTeX 2.09 names for font shapes
238 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
240 /// LaTeX names for font shapes
241 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
244 /// LaTeX names for font shape changing commands
245 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
248 /// The same as known_old_font_shapes, known_font_shapes and
249 /// known_text_font_shapes with .lyx names
250 char const * const known_coded_font_shapes[] = { "italic", "slanted",
251 "smallcaps", "up", 0};
253 /// Known special characters which need skip_spaces_braces() afterwards
254 char const * const known_special_chars[] = {"ldots",
255 "lyxarrow", "textcompwordmark",
256 "slash", "textasciitilde", "textasciicircum", "textbackslash",
257 "LyX", "TeX", "LaTeXe",
260 /// special characters from known_special_chars which may have a \\protect before
261 char const * const known_special_protect_chars[] = {"LyX", "TeX",
262 "LaTeXe", "LaTeX", 0};
264 /// the same as known_special_chars with .lyx names
265 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
266 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
267 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
268 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
269 "\\SpecialChar LaTeX\n", 0};
272 * Graphics file extensions known by the dvips driver of the graphics package.
273 * These extensions are used to complete the filename of an included
274 * graphics file if it does not contain an extension.
275 * The order must be the same that latex uses to find a file, because we
276 * will use the first extension that matches.
277 * This is only an approximation for the common cases. If we would want to
278 * do it right in all cases, we would need to know which graphics driver is
279 * used and know the extensions of every driver of the graphics package.
281 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
282 "ps.gz", "eps.Z", "ps.Z", 0};
285 * Graphics file extensions known by the pdftex driver of the graphics package.
286 * \sa known_dvips_graphics_formats
288 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
292 * Known file extensions for TeX files as used by \\include.
294 char const * const known_tex_extensions[] = {"tex", 0};
296 /// spaces known by InsetSpace
297 char const * const known_spaces[] = { " ", "space", ",",
298 "thinspace", "quad", "qquad", "enspace", "enskip",
299 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
300 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
301 "upbracefill", "downbracefill", 0};
303 /// the same as known_spaces with .lyx names
304 char const * const known_coded_spaces[] = { "space{}", "space{}",
305 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
306 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
307 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
308 "upbracefill{}", "downbracefill{}", 0};
310 /// known TIPA combining diacritical marks
311 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
312 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
313 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
314 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
315 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
316 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
319 /// TIPA tones that need special handling
320 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
322 // string to store the float type to be able to determine the type of subfloats
323 string float_type = "";
326 /// splits "x=z, y=b" into a map and an ordered keyword vector
327 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
332 keys.resize(v.size());
333 for (size_t i = 0; i < v.size(); ++i) {
334 size_t const pos = v[i].find('=');
335 string const index = trimSpaceAndEol(v[i].substr(0, pos));
336 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
344 * Split a LaTeX length into value and unit.
345 * The latter can be a real unit like "pt", or a latex length variable
346 * like "\textwidth". The unit may contain additional stuff like glue
347 * lengths, but we don't care, because such lengths are ERT anyway.
348 * \returns true if \p value and \p unit are valid.
350 bool splitLatexLength(string const & len, string & value, string & unit)
354 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
355 //'4,5' is a valid LaTeX length number. Change it to '4.5'
356 string const length = subst(len, ',', '.');
357 if (i == string::npos)
360 if (len[0] == '\\') {
361 // We had something like \textwidth without a factor
367 value = trimSpaceAndEol(string(length, 0, i));
371 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
372 if (contains(len, '\\'))
373 unit = trimSpaceAndEol(string(len, i));
375 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
380 /// A simple function to translate a latex length to something LyX can
381 /// understand. Not perfect, but rather best-effort.
382 bool translate_len(string const & length, string & valstring, string & unit)
384 if (!splitLatexLength(length, valstring, unit))
386 // LyX uses percent values
388 istringstream iss(valstring);
393 string const percentval = oss.str();
395 if (unit.empty() || unit[0] != '\\')
397 string::size_type const i = unit.find(' ');
398 string const endlen = (i == string::npos) ? string() : string(unit, i);
399 if (unit == "\\textwidth") {
400 valstring = percentval;
401 unit = "text%" + endlen;
402 } else if (unit == "\\columnwidth") {
403 valstring = percentval;
404 unit = "col%" + endlen;
405 } else if (unit == "\\paperwidth") {
406 valstring = percentval;
407 unit = "page%" + endlen;
408 } else if (unit == "\\linewidth") {
409 valstring = percentval;
410 unit = "line%" + endlen;
411 } else if (unit == "\\paperheight") {
412 valstring = percentval;
413 unit = "pheight%" + endlen;
414 } else if (unit == "\\textheight") {
415 valstring = percentval;
416 unit = "theight%" + endlen;
424 string translate_len(string const & length)
428 if (translate_len(length, value, unit))
430 // If the input is invalid, return what we have.
438 * Translates a LaTeX length into \p value, \p unit and
439 * \p special parts suitable for a box inset.
440 * The difference from translate_len() is that a box inset knows about
441 * some special "units" that are stored in \p special.
443 void translate_box_len(string const & length, string & value, string & unit, string & special)
445 if (translate_len(length, value, unit)) {
446 if (unit == "\\height" || unit == "\\depth" ||
447 unit == "\\totalheight" || unit == "\\width") {
448 special = unit.substr(1);
449 // The unit is not used, but LyX requires a dummy setting
462 * Find a file with basename \p name in path \p path and an extension
465 string find_file(string const & name, string const & path,
466 char const * const * extensions)
468 for (char const * const * what = extensions; *what; ++what) {
469 string const trial = addExtension(name, *what);
470 if (makeAbsPath(trial, path).exists())
477 void begin_inset(ostream & os, string const & name)
479 os << "\n\\begin_inset " << name;
483 void begin_command_inset(ostream & os, string const & name,
484 string const & latexname)
486 begin_inset(os, "CommandInset ");
487 os << name << "\nLatexCommand " << latexname << '\n';
491 void end_inset(ostream & os)
493 os << "\n\\end_inset\n\n";
497 bool skip_braces(Parser & p)
499 if (p.next_token().cat() != catBegin)
502 if (p.next_token().cat() == catEnd) {
511 /// replace LaTeX commands in \p s from the unicodesymbols file with their
513 docstring convert_unicodesymbols(docstring s)
516 for (size_t i = 0; i < s.size();) {
525 docstring parsed = encodings.fromLaTeXCommand(s,
526 Encodings::TEXT_CMD, termination, rem, &req);
527 set<string>::const_iterator it = req.begin();
528 set<string>::const_iterator en = req.end();
529 for (; it != en; ++it)
530 preamble.registerAutomaticallyLoadedPackage(*it);
533 if (s.empty() || s[0] != '\\')
542 /// try to convert \p s to a valid InsetCommand argument
543 string convert_command_inset_arg(string s)
546 // since we don't know the input encoding we can't use from_utf8
547 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
548 // LyX cannot handle newlines in a latex command
549 return subst(s, "\n", " ");
553 void output_ert(ostream & os, string const & s, Context & context)
555 context.check_layout(os);
556 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
558 os << "\n\\backslash\n";
559 else if (*it == '\n') {
560 context.new_paragraph(os);
561 context.check_layout(os);
565 context.check_end_layout(os);
569 void output_ert_inset(ostream & os, string const & s, Context & context)
571 // We must have a valid layout before outputting the ERT inset.
572 context.check_layout(os);
573 Context newcontext(true, context.textclass);
574 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
575 if (layout.forcePlainLayout())
576 newcontext.layout = &context.textclass.plainLayout();
577 begin_inset(os, "ERT");
578 os << "\nstatus collapsed\n";
579 output_ert(os, s, newcontext);
584 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
586 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
589 if (checkModule(name, command))
590 return findLayoutWithoutModule(textclass, name, command);
595 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
597 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
600 if (checkModule(name, command))
601 return findInsetLayoutWithoutModule(textclass, name, command);
606 void eat_whitespace(Parser &, ostream &, Context &, bool);
610 * Skips whitespace and braces.
611 * This should be called after a command has been parsed that is not put into
612 * ERT, and where LyX adds "{}" if needed.
614 void skip_spaces_braces(Parser & p, bool keepws = false)
616 /* The following four examples produce the same typeset output and
617 should be handled by this function:
625 // Unfortunately we need to skip comments, too.
626 // We can't use eat_whitespace since writing them after the {}
627 // results in different output in some cases.
628 bool const skipped_spaces = p.skip_spaces(true);
629 bool const skipped_braces = skip_braces(p);
630 if (keepws && skipped_spaces && !skipped_braces)
631 // put back the space (it is better handled by check_space)
632 p.unskip_spaces(true);
636 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
637 Context & context, Layout::LaTeXArgMap const & latexargs)
640 context.check_layout(os);
645 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
646 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
647 for (; lait != laend; ++lait) {
649 eat_whitespace(p, os, context, false);
650 if (lait->second.mandatory) {
651 if (p.next_token().cat() != catBegin)
653 p.get_token(); // eat '{'
655 context.check_layout(os);
658 begin_inset(os, "Argument ");
661 os << i << "\nstatus collapsed\n\n";
662 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
665 if (p.next_token().cat() == catEscape ||
666 p.next_token().character() != '[')
668 p.get_token(); // eat '['
670 context.check_layout(os);
673 begin_inset(os, "Argument ");
676 os << i << "\nstatus collapsed\n\n";
677 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
680 eat_whitespace(p, os, context, false);
685 void output_command_layout(ostream & os, Parser & p, bool outer,
686 Context & parent_context,
687 Layout const * newlayout)
689 TeXFont const oldFont = parent_context.font;
690 // save the current font size
691 string const size = oldFont.size;
692 // reset the font size to default, because the font size switches
693 // don't affect section headings and the like
694 parent_context.font.size = Context::normalfont.size;
695 // we only need to write the font change if we have an open layout
696 if (!parent_context.atParagraphStart())
697 output_font_change(os, oldFont, parent_context.font);
698 parent_context.check_end_layout(os);
699 Context context(true, parent_context.textclass, newlayout,
700 parent_context.layout, parent_context.font);
701 if (parent_context.deeper_paragraph) {
702 // We are beginning a nested environment after a
703 // deeper paragraph inside the outer list environment.
704 // Therefore we don't need to output a "begin deeper".
705 context.need_end_deeper = true;
707 context.check_deeper(os);
708 output_arguments(os, p, outer, true, false, context,
709 context.layout->latexargs());
710 parse_text(p, os, FLAG_ITEM, outer, context);
711 output_arguments(os, p, outer, false, true, context,
712 context.layout->postcommandargs());
713 context.check_end_layout(os);
714 if (parent_context.deeper_paragraph) {
715 // We must suppress the "end deeper" because we
716 // suppressed the "begin deeper" above.
717 context.need_end_deeper = false;
719 context.check_end_deeper(os);
720 // We don't need really a new paragraph, but
721 // we must make sure that the next item gets a \begin_layout.
722 parent_context.new_paragraph(os);
723 // Set the font size to the original value. No need to output it here
724 // (Context::begin_layout() will do that if needed)
725 parent_context.font.size = size;
730 * Output a space if necessary.
731 * This function gets called for every whitespace token.
733 * We have three cases here:
734 * 1. A space must be suppressed. Example: The lyxcode case below
735 * 2. A space may be suppressed. Example: Spaces before "\par"
736 * 3. A space must not be suppressed. Example: A space between two words
738 * We currently handle only 1. and 3 and from 2. only the case of
739 * spaces before newlines as a side effect.
741 * 2. could be used to suppress as many spaces as possible. This has two effects:
742 * - Reimporting LyX generated LaTeX files changes almost no whitespace
743 * - Superflous whitespace from non LyX generated LaTeX files is removed.
744 * The drawback is that the logic inside the function becomes
745 * complicated, and that is the reason why it is not implemented.
747 void check_space(Parser & p, ostream & os, Context & context)
749 Token const next = p.next_token();
750 Token const curr = p.curr_token();
751 // A space before a single newline and vice versa must be ignored
752 // LyX emits a newline before \end{lyxcode}.
753 // This newline must be ignored,
754 // otherwise LyX will add an additional protected space.
755 if (next.cat() == catSpace ||
756 next.cat() == catNewline ||
757 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
760 context.check_layout(os);
766 * Parse all arguments of \p command
768 void parse_arguments(string const & command,
769 vector<ArgumentType> const & template_arguments,
770 Parser & p, ostream & os, bool outer, Context & context)
772 string ert = command;
773 size_t no_arguments = template_arguments.size();
774 for (size_t i = 0; i < no_arguments; ++i) {
775 switch (template_arguments[i]) {
778 // This argument contains regular LaTeX
779 output_ert_inset(os, ert + '{', context);
780 eat_whitespace(p, os, context, false);
781 if (template_arguments[i] == required)
782 parse_text(p, os, FLAG_ITEM, outer, context);
784 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
788 // This argument consists only of a single item.
789 // The presence of '{' or not must be preserved.
791 if (p.next_token().cat() == catBegin)
792 ert += '{' + p.verbatim_item() + '}';
794 ert += p.verbatim_item();
798 // This argument may contain special characters
799 ert += '{' + p.verbatim_item() + '}';
803 // true because we must not eat whitespace
804 // if an optional arg follows we must not strip the
805 // brackets from this one
806 if (i < no_arguments - 1 &&
807 template_arguments[i+1] == optional)
808 ert += p.getFullOpt(true);
810 ert += p.getOpt(true);
814 output_ert_inset(os, ert, context);
819 * Check whether \p command is a known command. If yes,
820 * handle the command with all arguments.
821 * \return true if the command was parsed, false otherwise.
823 bool parse_command(string const & command, Parser & p, ostream & os,
824 bool outer, Context & context)
826 if (known_commands.find(command) != known_commands.end()) {
827 parse_arguments(command, known_commands[command], p, os,
835 /// Parses a minipage or parbox
836 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
837 unsigned inner_flags, bool outer, Context & parent_context,
838 string const & outer_type, string const & special,
839 string inner_type, string const & frame_color,
840 string const & background_color)
844 string hor_pos = "l";
845 // We need to set the height to the LaTeX default of 1\\totalheight
846 // for the case when no height argument is given
847 string height_value = "1";
848 string height_unit = "in";
849 string height_special = "totalheight";
854 string width_special = "none";
855 string thickness = "0.4pt";
856 if (!fboxrule.empty())
857 thickness = fboxrule;
861 if (!fboxsep.empty())
862 separation = fboxsep;
866 if (!shadow_size.empty())
867 shadowsize = shadow_size;
870 string framecolor = "black";
871 string backgroundcolor = "none";
872 if (!frame_color.empty())
873 framecolor = frame_color;
874 if (!background_color.empty())
875 backgroundcolor = background_color;
876 // if there is a color box around the \begin statements have not yet been parsed
878 if (!frame_color.empty() || !background_color.empty()) {
879 eat_whitespace(p, os, parent_context, false);
880 p.get_token().asInput(); // the '{'
882 if (p.next_token().asInput() == "\\begin") {
883 p.get_token().asInput();
885 inner_type = "minipage";
886 inner_flags = FLAG_END;
889 else if (p.next_token().asInput() == "\\parbox") {
890 p.get_token().asInput();
891 inner_type = "parbox";
892 inner_flags = FLAG_ITEM;
895 else if (p.next_token().asInput() == "\\makebox") {
896 p.get_token().asInput();
897 inner_type = "makebox";
898 inner_flags = FLAG_ITEM;
900 // in case there is just \colorbox{color}{text}
903 inner_type = "makebox";
904 inner_flags = FLAG_BRACE_LAST;
909 if (!inner_type.empty() && p.hasOpt()) {
910 if (inner_type != "makebox")
911 position = p.getArg('[', ']');
913 latex_width = p.getArg('[', ']');
914 translate_box_len(latex_width, width_value, width_unit, width_special);
917 if (position != "t" && position != "c" && position != "b") {
918 cerr << "invalid position " << position << " for "
919 << inner_type << endl;
923 if (inner_type != "makebox") {
924 latex_height = p.getArg('[', ']');
925 translate_box_len(latex_height, height_value, height_unit, height_special);
927 string const opt = p.getArg('[', ']');
930 if (hor_pos != "l" && hor_pos != "c" &&
931 hor_pos != "r" && hor_pos != "s") {
932 cerr << "invalid hor_pos " << hor_pos
933 << " for " << inner_type << endl;
940 inner_pos = p.getArg('[', ']');
941 if (inner_pos != "c" && inner_pos != "t" &&
942 inner_pos != "b" && inner_pos != "s") {
943 cerr << "invalid inner_pos "
944 << inner_pos << " for "
945 << inner_type << endl;
946 inner_pos = position;
950 if (inner_type == "makebox")
954 if (inner_type.empty()) {
955 if (special.empty() && outer_type != "framebox")
956 latex_width = "1\\columnwidth";
959 latex_width = p2.getArg('[', ']');
960 string const opt = p2.getArg('[', ']');
963 if (hor_pos != "l" && hor_pos != "c" &&
964 hor_pos != "r" && hor_pos != "s") {
965 cerr << "invalid hor_pos " << hor_pos
966 << " for " << outer_type << endl;
970 if (outer_type == "framebox")
974 } else if (inner_type != "makebox")
975 latex_width = p.verbatim_item();
976 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
977 // as this is LyX's standard for such cases (except for makebox)
978 // \framebox is more special and handled below
979 if (latex_width.empty() && inner_type != "makebox"
980 && outer_type != "framebox")
981 latex_width = "1\\columnwidth";
983 translate_len(latex_width, width_value, width_unit);
985 bool shadedparbox = false;
986 if (inner_type == "shaded") {
987 eat_whitespace(p, os, parent_context, false);
988 if (outer_type == "parbox") {
990 if (p.next_token().cat() == catBegin)
992 eat_whitespace(p, os, parent_context, false);
998 // If we already read the inner box we have to push the inner env
999 if (!outer_type.empty() && !inner_type.empty() &&
1000 (inner_flags & FLAG_END))
1001 active_environments.push_back(inner_type);
1002 bool use_ert = false;
1003 if (!outer_type.empty() && !inner_type.empty()) {
1004 // Look whether there is some content after the end of the
1005 // inner box, but before the end of the outer box.
1006 // If yes, we need to output ERT.
1008 if (inner_flags & FLAG_END)
1009 p.ertEnvironment(inner_type);
1012 p.skip_spaces(true);
1013 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1014 if ((outer_env && p.next_token().asInput() != "\\end") ||
1015 (!outer_env && p.next_token().cat() != catEnd)) {
1016 // something is between the end of the inner box and
1017 // the end of the outer box, so we need to use ERT.
1022 // if only \makebox{content} was used we can set its width to 1\width
1023 // because this identic and also identic to \mbox
1024 // this doesn't work for \framebox{content}, thus we have to use ERT for this
1025 if (latex_width.empty() && inner_type == "makebox" && background_color.empty()) {
1028 width_special = "width";
1029 } else if (latex_width.empty() && outer_type == "framebox") {
1030 width_value.clear();
1032 width_special = "none";
1035 // try to determine the box content alignment
1036 // first handle the simple case of "{\centering..."
1037 if (p.next_token().asInput() == "\\raggedright") {
1040 } else if (p.next_token().asInput() == "\\centering") {
1043 } else if (p.next_token().asInput() == "\\raggedleft") {
1047 // now handle the cases "{%catNewline\centering..."
1048 // and "{catNewline\centering..."
1050 p.get_token().asInput();
1051 if (p.next_token().cat() == catComment || p.next_token().cat() == catNewline)
1052 p.get_token().asInput();
1053 if (p.next_token().asInput() == "\\raggedright") {
1056 } else if (p.next_token().asInput() == "\\centering") {
1060 } else if (p.next_token().asInput() == "\\raggedleft") {
1069 if (!outer_type.empty()) {
1070 if (outer_flags & FLAG_END)
1071 ss << "\\begin{" << outer_type << '}';
1073 ss << '\\' << outer_type << '{';
1074 if (!special.empty())
1078 if (!inner_type.empty()) {
1079 if (inner_type != "shaded") {
1080 if (inner_flags & FLAG_END)
1081 ss << "\\begin{" << inner_type << '}';
1083 ss << '\\' << inner_type;
1085 if (!position.empty())
1086 ss << '[' << position << ']';
1087 if (!latex_height.empty())
1088 ss << '[' << latex_height << ']';
1089 if (!inner_pos.empty())
1090 ss << '[' << inner_pos << ']';
1091 ss << '{' << latex_width << '}';
1092 if (!(inner_flags & FLAG_END))
1095 if (inner_type == "shaded")
1096 ss << "\\begin{shaded}";
1097 output_ert_inset(os, ss.str(), parent_context);
1098 if (!inner_type.empty()) {
1099 parse_text(p, os, inner_flags, outer, parent_context);
1100 if (inner_flags & FLAG_END)
1101 output_ert_inset(os, "\\end{" + inner_type + '}',
1104 output_ert_inset(os, "}", parent_context);
1106 if (!outer_type.empty()) {
1107 // If we already read the inner box we have to pop
1109 if (!inner_type.empty() && (inner_flags & FLAG_END))
1110 active_environments.pop_back();
1112 // Ensure that the end of the outer box is parsed correctly:
1113 // The opening brace has been eaten by parse_outer_box()
1114 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1115 outer_flags &= ~FLAG_ITEM;
1116 outer_flags |= FLAG_BRACE_LAST;
1118 parse_text(p, os, outer_flags, outer, parent_context);
1119 if (outer_flags & FLAG_END)
1120 output_ert_inset(os, "\\end{" + outer_type + '}',
1123 output_ert_inset(os, "}", parent_context);
1126 // LyX does not like empty positions, so we have
1127 // to set them to the LaTeX default values here.
1128 if (position.empty())
1130 if (inner_pos.empty())
1131 inner_pos = position;
1132 parent_context.check_layout(os);
1133 begin_inset(os, "Box ");
1134 if (outer_type == "framed")
1136 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1138 else if (outer_type == "shadowbox")
1139 os << "Shadowbox\n";
1140 else if ((outer_type == "shaded" && inner_type.empty()) ||
1141 (outer_type == "minipage" && inner_type == "shaded") ||
1142 (outer_type == "parbox" && inner_type == "shaded")) {
1144 preamble.registerAutomaticallyLoadedPackage("color");
1145 } else if (outer_type == "doublebox")
1146 os << "Doublebox\n";
1147 else if (outer_type.empty() || outer_type == "mbox")
1148 os << "Frameless\n";
1150 os << outer_type << '\n';
1151 os << "position \"" << position << "\"\n";
1152 os << "hor_pos \"" << hor_pos << "\"\n";
1153 if (outer_type == "mbox")
1154 os << "has_inner_box 1\n";
1155 if (!frame_color.empty())
1156 os << "has_inner_box 0\n";
1158 os << "has_inner_box " << !inner_type.empty() << "\n";
1159 os << "inner_pos \"" << inner_pos << "\"\n";
1160 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1162 if (outer_type == "mbox")
1163 os << "use_makebox 1\n";
1164 if (!frame_color.empty())
1165 os << "use_makebox 0\n";
1167 os << "use_makebox " << (inner_type == "makebox") << '\n';
1168 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1169 os << "width \"\"\n";
1170 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1171 else if (contains(width_unit, '\\'))
1172 os << "width \"" << width_value << "in" << "\"\n";
1174 os << "width \"" << width_value << width_unit << "\"\n";
1175 if (contains(width_unit, '\\')) {
1176 width_unit.erase (0,1); // remove the leading '\'
1177 os << "special \"" << width_unit << "\"\n";
1179 os << "special \"" << width_special << "\"\n";
1180 if (contains(height_unit, '\\'))
1181 os << "height \"" << height_value << "in" << "\"\n";
1183 os << "height \"" << height_value << height_unit << "\"\n";
1184 os << "height_special \"" << height_special << "\"\n";
1185 os << "thickness \"" << thickness << "\"\n";
1186 os << "separation \"" << separation << "\"\n";
1187 os << "shadowsize \"" << shadowsize << "\"\n";
1188 os << "framecolor \"" << framecolor << "\"\n";
1189 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1190 os << "status open\n\n";
1192 // Unfortunately we can't use parse_text_in_inset:
1193 // InsetBox::forcePlainLayout() is hard coded and does not
1194 // use the inset layout. Apart from that do we call parse_text
1195 // up to two times, but need only one check_end_layout.
1196 bool const forcePlainLayout =
1197 (!inner_type.empty() || inner_type == "makebox") &&
1198 outer_type != "shaded" && outer_type != "framed";
1199 Context context(true, parent_context.textclass);
1200 if (forcePlainLayout)
1201 context.layout = &context.textclass.plainLayout();
1203 context.font = parent_context.font;
1205 // If we have no inner box the contents will be read with the outer box
1206 if (!inner_type.empty())
1207 parse_text(p, os, inner_flags, outer, context);
1209 // Ensure that the end of the outer box is parsed correctly:
1210 // The opening brace has been eaten by parse_outer_box()
1211 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1212 outer_flags &= ~FLAG_ITEM;
1213 outer_flags |= FLAG_BRACE_LAST;
1216 // Find end of outer box, output contents if inner_type is
1217 // empty and output possible comments
1218 if (!outer_type.empty()) {
1219 // If we already read the inner box we have to pop
1221 if (!inner_type.empty() && (inner_flags & FLAG_END))
1222 active_environments.pop_back();
1223 // This does not output anything but comments if
1224 // inner_type is not empty (see use_ert)
1225 parse_text(p, os, outer_flags, outer, context);
1228 context.check_end_layout(os);
1230 #ifdef PRESERVE_LAYOUT
1231 // LyX puts a % after the end of the minipage
1232 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1234 //output_ert_inset(os, "%dummy", parent_context);
1237 parent_context.new_paragraph(os);
1239 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1240 //output_ert_inset(os, "%dummy", parent_context);
1243 // We add a protected space if something real follows
1244 if (p.good() && p.next_token().cat() != catComment) {
1245 begin_inset(os, "space ~\n");
1251 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1252 // in this case we have to eat the the closing brace of the color box
1253 p.get_token().asInput(); // the '}'
1255 if (p.next_token().asInput() == "}") {
1256 // in this case we assume that the closing brace is from the box settings
1257 // therefore reset these values for the next box
1263 // all boxes except of Frameless and Shaded require calc
1264 if (!(outer_type.empty() || outer_type == "mbox") &&
1265 !((outer_type == "shaded" && inner_type.empty()) ||
1266 (outer_type == "minipage" && inner_type == "shaded") ||
1267 (outer_type == "parbox" && inner_type == "shaded")))
1268 preamble.registerAutomaticallyLoadedPackage("calc");
1272 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1273 Context & parent_context, string const & outer_type,
1274 string const & special)
1276 eat_whitespace(p, os, parent_context, false);
1277 if (flags & FLAG_ITEM) {
1279 if (p.next_token().cat() == catBegin)
1282 cerr << "Warning: Ignoring missing '{' after \\"
1283 << outer_type << '.' << endl;
1284 eat_whitespace(p, os, parent_context, false);
1287 unsigned int inner_flags = 0;
1289 if (outer_type == "minipage" || outer_type == "parbox") {
1290 p.skip_spaces(true);
1291 while (p.hasOpt()) {
1293 p.skip_spaces(true);
1296 p.skip_spaces(true);
1297 if (outer_type == "parbox") {
1299 if (p.next_token().cat() == catBegin)
1301 p.skip_spaces(true);
1304 if (outer_type == "shaded" || outer_type == "mbox") {
1305 // These boxes never have an inner box
1307 } else if (p.next_token().asInput() == "\\parbox") {
1308 inner = p.get_token().cs();
1309 inner_flags = FLAG_ITEM;
1310 } else if (p.next_token().asInput() == "\\begin") {
1311 // Is this a minipage or shaded box?
1314 inner = p.getArg('{', '}');
1316 if (inner == "minipage" || inner == "shaded")
1317 inner_flags = FLAG_END;
1322 if (inner_flags == FLAG_END) {
1323 if (inner != "shaded")
1327 eat_whitespace(p, os, parent_context, false);
1329 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1330 outer_type, special, inner, "", "");
1332 if (inner_flags == FLAG_ITEM) {
1334 eat_whitespace(p, os, parent_context, false);
1336 parse_box(p, os, flags, inner_flags, outer, parent_context,
1337 outer_type, special, inner, "", "");
1342 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1344 parent_context.check_layout(os);
1345 begin_inset(os, "listings\n");
1347 string arg = p.verbatimOption();
1348 os << "lstparams " << '"' << arg << '"' << '\n';
1349 if (arg.find("\\color") != string::npos)
1350 preamble.registerAutomaticallyLoadedPackage("color");
1353 os << "inline true\n";
1355 os << "inline false\n";
1356 os << "status collapsed\n";
1357 Context context(true, parent_context.textclass);
1358 context.layout = &parent_context.textclass.plainLayout();
1361 // set catcodes to verbatim early, just in case.
1362 p.setCatcodes(VERBATIM_CATCODES);
1363 string delim = p.get_token().asInput();
1364 //FIXME: handler error condition
1365 s = p.verbatimStuff(delim).second;
1366 // context.new_paragraph(os);
1368 s = p.verbatimEnvironment("lstlisting");
1369 output_ert(os, s, context);
1374 /// parse an unknown environment
1375 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1376 unsigned flags, bool outer,
1377 Context & parent_context)
1379 if (name == "tabbing")
1380 // We need to remember that we have to handle '\=' specially
1381 flags |= FLAG_TABBING;
1383 // We need to translate font changes and paragraphs inside the
1384 // environment to ERT if we have a non standard font.
1385 // Otherwise things like
1386 // \large\begin{foo}\huge bar\end{foo}
1388 bool const specialfont =
1389 (parent_context.font != parent_context.normalfont);
1390 bool const new_layout_allowed = parent_context.new_layout_allowed;
1392 parent_context.new_layout_allowed = false;
1393 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1394 parse_text_snippet(p, os, flags, outer, parent_context);
1395 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1397 parent_context.new_layout_allowed = new_layout_allowed;
1401 void parse_environment(Parser & p, ostream & os, bool outer,
1402 string & last_env, Context & parent_context)
1404 Layout const * newlayout;
1405 InsetLayout const * newinsetlayout = 0;
1406 string const name = p.getArg('{', '}');
1407 const bool is_starred = suffixIs(name, '*');
1408 string const unstarred_name = rtrim(name, "*");
1409 active_environments.push_back(name);
1411 if (is_math_env(name)) {
1412 parent_context.check_layout(os);
1413 begin_inset(os, "Formula ");
1414 os << "\\begin{" << name << "}";
1415 parse_math(p, os, FLAG_END, MATH_MODE);
1416 os << "\\end{" << name << "}";
1418 if (is_display_math_env(name)) {
1419 // Prevent the conversion of a line break to a space
1420 // (bug 7668). This does not change the output, but
1421 // looks ugly in LyX.
1422 eat_whitespace(p, os, parent_context, false);
1426 else if (is_known(name, preamble.polyglossia_languages)) {
1427 // We must begin a new paragraph if not already done
1428 if (! parent_context.atParagraphStart()) {
1429 parent_context.check_end_layout(os);
1430 parent_context.new_paragraph(os);
1432 // save the language in the context so that it is
1433 // handled by parse_text
1434 parent_context.font.language = preamble.polyglossia2lyx(name);
1435 parse_text(p, os, FLAG_END, outer, parent_context);
1436 // Just in case the environment is empty
1437 parent_context.extra_stuff.erase();
1438 // We must begin a new paragraph to reset the language
1439 parent_context.new_paragraph(os);
1443 else if (unstarred_name == "tabular" || name == "longtable") {
1444 eat_whitespace(p, os, parent_context, false);
1445 string width = "0pt";
1446 if (name == "tabular*") {
1447 width = lyx::translate_len(p.getArg('{', '}'));
1448 eat_whitespace(p, os, parent_context, false);
1450 parent_context.check_layout(os);
1451 begin_inset(os, "Tabular ");
1452 handle_tabular(p, os, name, width, parent_context);
1457 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1458 eat_whitespace(p, os, parent_context, false);
1459 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1460 eat_whitespace(p, os, parent_context, false);
1461 parent_context.check_layout(os);
1462 begin_inset(os, "Float " + unstarred_name + "\n");
1463 // store the float type for subfloats
1464 // subfloats only work with figures and tables
1465 if (unstarred_name == "figure")
1466 float_type = unstarred_name;
1467 else if (unstarred_name == "table")
1468 float_type = unstarred_name;
1472 os << "placement " << opt << '\n';
1473 if (contains(opt, "H"))
1474 preamble.registerAutomaticallyLoadedPackage("float");
1476 Floating const & fl = parent_context.textclass.floats()
1477 .getType(unstarred_name);
1478 if (!fl.floattype().empty() && fl.usesFloatPkg())
1479 preamble.registerAutomaticallyLoadedPackage("float");
1482 os << "wide " << convert<string>(is_starred)
1483 << "\nsideways false"
1484 << "\nstatus open\n\n";
1485 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1487 // We don't need really a new paragraph, but
1488 // we must make sure that the next item gets a \begin_layout.
1489 parent_context.new_paragraph(os);
1491 // the float is parsed thus delete the type
1495 else if (unstarred_name == "sidewaysfigure"
1496 || unstarred_name == "sidewaystable") {
1497 eat_whitespace(p, os, parent_context, false);
1498 parent_context.check_layout(os);
1499 if (unstarred_name == "sidewaysfigure")
1500 begin_inset(os, "Float figure\n");
1502 begin_inset(os, "Float table\n");
1503 os << "wide " << convert<string>(is_starred)
1504 << "\nsideways true"
1505 << "\nstatus open\n\n";
1506 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1508 // We don't need really a new paragraph, but
1509 // we must make sure that the next item gets a \begin_layout.
1510 parent_context.new_paragraph(os);
1512 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1515 else if (name == "wrapfigure" || name == "wraptable") {
1516 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1517 eat_whitespace(p, os, parent_context, false);
1518 parent_context.check_layout(os);
1521 string overhang = "0col%";
1524 lines = p.getArg('[', ']');
1525 string const placement = p.getArg('{', '}');
1527 overhang = p.getArg('[', ']');
1528 string const width = p.getArg('{', '}');
1530 if (name == "wrapfigure")
1531 begin_inset(os, "Wrap figure\n");
1533 begin_inset(os, "Wrap table\n");
1534 os << "lines " << lines
1535 << "\nplacement " << placement
1536 << "\noverhang " << lyx::translate_len(overhang)
1537 << "\nwidth " << lyx::translate_len(width)
1538 << "\nstatus open\n\n";
1539 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1541 // We don't need really a new paragraph, but
1542 // we must make sure that the next item gets a \begin_layout.
1543 parent_context.new_paragraph(os);
1545 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1548 else if (name == "minipage") {
1549 eat_whitespace(p, os, parent_context, false);
1550 // Test whether this is an outer box of a shaded box
1552 // swallow arguments
1553 while (p.hasOpt()) {
1555 p.skip_spaces(true);
1558 p.skip_spaces(true);
1559 Token t = p.get_token();
1560 bool shaded = false;
1561 if (t.asInput() == "\\begin") {
1562 p.skip_spaces(true);
1563 if (p.getArg('{', '}') == "shaded")
1568 parse_outer_box(p, os, FLAG_END, outer,
1569 parent_context, name, "shaded");
1571 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1572 "", "", name, "", "");
1576 else if (name == "comment") {
1577 eat_whitespace(p, os, parent_context, false);
1578 parent_context.check_layout(os);
1579 begin_inset(os, "Note Comment\n");
1580 os << "status open\n";
1581 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1584 skip_braces(p); // eat {} that might by set by LyX behind comments
1585 preamble.registerAutomaticallyLoadedPackage("verbatim");
1588 else if (name == "verbatim") {
1589 // FIXME: this should go in the generic code that
1590 // handles environments defined in layout file that
1591 // have "PassThru 1". However, the code over there is
1592 // already too complicated for my taste.
1593 parent_context.new_paragraph(os);
1594 Context context(true, parent_context.textclass,
1595 &parent_context.textclass[from_ascii("Verbatim")]);
1596 string s = p.verbatimEnvironment("verbatim");
1597 output_ert(os, s, context);
1601 else if (name == "IPA") {
1602 eat_whitespace(p, os, parent_context, false);
1603 parent_context.check_layout(os);
1604 begin_inset(os, "IPA\n");
1605 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1608 preamble.registerAutomaticallyLoadedPackage("tipa");
1609 preamble.registerAutomaticallyLoadedPackage("tipx");
1612 else if (name == "CJK") {
1613 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1614 // It is impossible to decide if a CJK environment was in its own paragraph or within
1615 // a line. We therefore always assume a paragraph since the latter is a rare case.
1616 eat_whitespace(p, os, parent_context, false);
1617 parent_context.check_end_layout(os);
1618 // store the encoding to be able to reset it
1619 string const encoding_old = p.getEncoding();
1620 string const encoding = p.getArg('{', '}');
1621 // FIXME: For some reason JIS does not work. Although the text
1622 // in tests/CJK.tex is identical with the SJIS version if you
1623 // convert both snippets using the recode command line utility,
1624 // the resulting .lyx file contains some extra characters if
1625 // you set buggy_encoding to false for JIS.
1626 bool const buggy_encoding = encoding == "JIS";
1627 if (!buggy_encoding)
1628 p.setEncoding(encoding, Encoding::CJK);
1630 // FIXME: This will read garbage, since the data is not encoded in utf8.
1631 p.setEncoding("UTF-8");
1633 // LyX only supports the same mapping for all CJK
1634 // environments, so we might need to output everything as ERT
1635 string const mapping = trim(p.getArg('{', '}'));
1636 char const * const * const where =
1637 is_known(encoding, supported_CJK_encodings);
1638 if (!buggy_encoding && !preamble.fontCJKSet())
1639 preamble.fontCJK(mapping);
1640 bool knownMapping = mapping == preamble.fontCJK();
1641 if (buggy_encoding || !knownMapping || !where) {
1642 parent_context.check_layout(os);
1643 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1645 // we must parse the content as verbatim because e.g. JIS can contain
1646 // normally invalid characters
1647 // FIXME: This works only for the most simple cases.
1648 // Since TeX control characters are not parsed,
1649 // things like comments are completely wrong.
1650 string const s = p.plainEnvironment("CJK");
1651 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1653 output_ert_inset(os, "\\", parent_context);
1654 else if (*it == '$')
1655 output_ert_inset(os, "$", parent_context);
1656 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1661 output_ert_inset(os, "\\end{" + name + "}",
1665 supported_CJK_languages[where - supported_CJK_encodings];
1666 // store the language because we must reset it at the end
1667 string const lang_old = parent_context.font.language;
1668 parent_context.font.language = lang;
1669 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1670 parent_context.font.language = lang_old;
1671 parent_context.new_paragraph(os);
1673 p.setEncoding(encoding_old);
1677 else if (name == "lyxgreyedout") {
1678 eat_whitespace(p, os, parent_context, false);
1679 parent_context.check_layout(os);
1680 begin_inset(os, "Note Greyedout\n");
1681 os << "status open\n";
1682 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1685 if (!preamble.notefontcolor().empty())
1686 preamble.registerAutomaticallyLoadedPackage("color");
1689 else if (name == "btSect") {
1690 eat_whitespace(p, os, parent_context, false);
1691 parent_context.check_layout(os);
1692 begin_command_inset(os, "bibtex", "bibtex");
1693 string bibstyle = "plain";
1695 bibstyle = p.getArg('[', ']');
1696 p.skip_spaces(true);
1698 string const bibfile = p.getArg('{', '}');
1699 eat_whitespace(p, os, parent_context, false);
1700 Token t = p.get_token();
1701 if (t.asInput() == "\\btPrintCited") {
1702 p.skip_spaces(true);
1703 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1705 if (t.asInput() == "\\btPrintNotCited") {
1706 p.skip_spaces(true);
1707 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1709 if (t.asInput() == "\\btPrintAll") {
1710 p.skip_spaces(true);
1711 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1713 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1714 os << "options " << '"' << bibstyle << '"' << "\n";
1715 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1720 else if (name == "framed" || name == "shaded") {
1721 eat_whitespace(p, os, parent_context, false);
1722 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1724 preamble.registerAutomaticallyLoadedPackage("framed");
1727 else if (name == "lstlisting") {
1728 eat_whitespace(p, os, parent_context, false);
1729 parse_listings(p, os, parent_context, false);
1733 else if (!parent_context.new_layout_allowed)
1734 parse_unknown_environment(p, name, os, FLAG_END, outer,
1737 // Alignment and spacing settings
1738 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1739 // therefore are totally broken!
1740 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1741 // they are commands not environments. They are furthermore switches that
1742 // can be ended by another switches, but also by commands like \footnote or
1743 // \parbox. So the only safe way is to leave them untouched.
1744 else if (name == "center" || name == "centering" ||
1745 name == "flushleft" || name == "flushright" ||
1746 name == "singlespace" || name == "onehalfspace" ||
1747 name == "doublespace" || name == "spacing") {
1748 eat_whitespace(p, os, parent_context, false);
1749 // We must begin a new paragraph if not already done
1750 if (! parent_context.atParagraphStart()) {
1751 parent_context.check_end_layout(os);
1752 parent_context.new_paragraph(os);
1754 if (name == "flushleft")
1755 parent_context.add_extra_stuff("\\align left\n");
1756 else if (name == "flushright")
1757 parent_context.add_extra_stuff("\\align right\n");
1758 else if (name == "center" || name == "centering")
1759 parent_context.add_extra_stuff("\\align center\n");
1760 else if (name == "singlespace")
1761 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1762 else if (name == "onehalfspace") {
1763 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1764 preamble.registerAutomaticallyLoadedPackage("setspace");
1765 } else if (name == "doublespace") {
1766 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1767 preamble.registerAutomaticallyLoadedPackage("setspace");
1768 } else if (name == "spacing") {
1769 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1770 preamble.registerAutomaticallyLoadedPackage("setspace");
1772 parse_text(p, os, FLAG_END, outer, parent_context);
1773 // Just in case the environment is empty
1774 parent_context.extra_stuff.erase();
1775 // We must begin a new paragraph to reset the alignment
1776 parent_context.new_paragraph(os);
1780 // The single '=' is meant here.
1781 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1782 eat_whitespace(p, os, parent_context, false);
1783 Context context(true, parent_context.textclass, newlayout,
1784 parent_context.layout, parent_context.font);
1785 if (parent_context.deeper_paragraph) {
1786 // We are beginning a nested environment after a
1787 // deeper paragraph inside the outer list environment.
1788 // Therefore we don't need to output a "begin deeper".
1789 context.need_end_deeper = true;
1791 parent_context.check_end_layout(os);
1792 if (last_env == name) {
1793 // we need to output a separator since LyX would export
1794 // the two environments as one otherwise (bug 5716)
1795 TeX2LyXDocClass const & textclass(parent_context.textclass);
1796 Context newcontext(true, textclass,
1797 &(textclass.defaultLayout()));
1798 newcontext.check_layout(os);
1799 begin_inset(os, "Separator plain\n");
1801 newcontext.check_end_layout(os);
1803 switch (context.layout->latextype) {
1804 case LATEX_LIST_ENVIRONMENT:
1805 context.add_par_extra_stuff("\\labelwidthstring "
1806 + p.verbatim_item() + '\n');
1809 case LATEX_BIB_ENVIRONMENT:
1810 p.verbatim_item(); // swallow next arg
1816 context.check_deeper(os);
1817 // handle known optional and required arguments
1818 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1819 // It is impossible to place anything after the environment name,
1820 // but before the first \\item.
1821 if (context.layout->latextype == LATEX_ENVIRONMENT)
1822 output_arguments(os, p, outer, false, false, context,
1823 context.layout->latexargs());
1824 parse_text(p, os, FLAG_END, outer, context);
1825 if (context.layout->latextype == LATEX_ENVIRONMENT)
1826 output_arguments(os, p, outer, false, true, context,
1827 context.layout->postcommandargs());
1828 context.check_end_layout(os);
1829 if (parent_context.deeper_paragraph) {
1830 // We must suppress the "end deeper" because we
1831 // suppressed the "begin deeper" above.
1832 context.need_end_deeper = false;
1834 context.check_end_deeper(os);
1835 parent_context.new_paragraph(os);
1837 if (!preamble.titleLayoutFound())
1838 preamble.titleLayoutFound(newlayout->intitle);
1839 set<string> const & req = newlayout->requires();
1840 set<string>::const_iterator it = req.begin();
1841 set<string>::const_iterator en = req.end();
1842 for (; it != en; ++it)
1843 preamble.registerAutomaticallyLoadedPackage(*it);
1846 // The single '=' is meant here.
1847 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1848 eat_whitespace(p, os, parent_context, false);
1849 parent_context.check_layout(os);
1850 begin_inset(os, "Flex ");
1851 os << to_utf8(newinsetlayout->name()) << '\n'
1852 << "status collapsed\n";
1853 if (newinsetlayout->isPassThru()) {
1854 string const arg = p.verbatimEnvironment(name);
1855 Context context(true, parent_context.textclass,
1856 &parent_context.textclass.plainLayout(),
1857 parent_context.layout);
1858 output_ert(os, arg, parent_context);
1860 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1864 else if (name == "appendix") {
1865 // This is no good latex style, but it works and is used in some documents...
1866 eat_whitespace(p, os, parent_context, false);
1867 parent_context.check_end_layout(os);
1868 Context context(true, parent_context.textclass, parent_context.layout,
1869 parent_context.layout, parent_context.font);
1870 context.check_layout(os);
1871 os << "\\start_of_appendix\n";
1872 parse_text(p, os, FLAG_END, outer, context);
1873 context.check_end_layout(os);
1877 else if (known_environments.find(name) != known_environments.end()) {
1878 vector<ArgumentType> arguments = known_environments[name];
1879 // The last "argument" denotes wether we may translate the
1880 // environment contents to LyX
1881 // The default required if no argument is given makes us
1882 // compatible with the reLyXre environment.
1883 ArgumentType contents = arguments.empty() ?
1886 if (!arguments.empty())
1887 arguments.pop_back();
1888 // See comment in parse_unknown_environment()
1889 bool const specialfont =
1890 (parent_context.font != parent_context.normalfont);
1891 bool const new_layout_allowed =
1892 parent_context.new_layout_allowed;
1894 parent_context.new_layout_allowed = false;
1895 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1896 outer, parent_context);
1897 if (contents == verbatim)
1898 output_ert_inset(os, p.ertEnvironment(name),
1901 parse_text_snippet(p, os, FLAG_END, outer,
1903 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1905 parent_context.new_layout_allowed = new_layout_allowed;
1909 parse_unknown_environment(p, name, os, FLAG_END, outer,
1913 active_environments.pop_back();
1917 /// parses a comment and outputs it to \p os.
1918 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1920 LASSERT(t.cat() == catComment, return);
1921 if (!t.cs().empty()) {
1922 context.check_layout(os);
1923 output_ert_inset(os, '%' + t.cs(), context);
1924 if (p.next_token().cat() == catNewline) {
1925 // A newline after a comment line starts a new
1927 if (context.new_layout_allowed) {
1928 if(!context.atParagraphStart())
1929 // Only start a new paragraph if not already
1930 // done (we might get called recursively)
1931 context.new_paragraph(os);
1933 output_ert_inset(os, "\n", context);
1934 eat_whitespace(p, os, context, true);
1937 // "%\n" combination
1944 * Reads spaces and comments until the first non-space, non-comment token.
1945 * New paragraphs (double newlines or \\par) are handled like simple spaces
1946 * if \p eatParagraph is true.
1947 * Spaces are skipped, but comments are written to \p os.
1949 void eat_whitespace(Parser & p, ostream & os, Context & context,
1953 Token const & t = p.get_token();
1954 if (t.cat() == catComment)
1955 parse_comment(p, os, t, context);
1956 else if ((! eatParagraph && p.isParagraph()) ||
1957 (t.cat() != catSpace && t.cat() != catNewline)) {
1966 * Set a font attribute, parse text and reset the font attribute.
1967 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1968 * \param currentvalue Current value of the attribute. Is set to the new
1969 * value during parsing.
1970 * \param newvalue New value of the attribute
1972 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1973 Context & context, string const & attribute,
1974 string & currentvalue, string const & newvalue)
1976 context.check_layout(os);
1977 string const oldvalue = currentvalue;
1978 currentvalue = newvalue;
1979 os << '\n' << attribute << ' ' << newvalue << "\n";
1980 parse_text_snippet(p, os, flags, outer, context);
1981 context.check_layout(os);
1982 os << '\n' << attribute << ' ' << oldvalue << "\n";
1983 currentvalue = oldvalue;
1987 /// get the arguments of a natbib or jurabib citation command
1988 void get_cite_arguments(Parser & p, bool natbibOrder,
1989 string & before, string & after)
1991 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1993 // text before the citation
1995 // text after the citation
1996 after = p.getFullOpt();
1998 if (!after.empty()) {
1999 before = p.getFullOpt();
2000 if (natbibOrder && !before.empty())
2001 swap(before, after);
2006 /// Convert filenames with TeX macros and/or quotes to something LyX
2008 string const normalize_filename(string const & name)
2013 Token const & t = p.get_token();
2014 if (t.cat() != catEscape)
2016 else if (t.cs() == "lyxdot") {
2017 // This is used by LyX for simple dots in relative
2021 } else if (t.cs() == "space") {
2024 } else if (t.cs() == "string") {
2025 // Convert \string" to " and \string~ to ~
2026 Token const & n = p.next_token();
2027 if (n.asInput() != "\"" && n.asInput() != "~")
2032 // Strip quotes. This is a bit complicated (see latex_path()).
2033 string full = os.str();
2034 if (!full.empty() && full[0] == '"') {
2035 string base = removeExtension(full);
2036 string ext = getExtension(full);
2037 if (!base.empty() && base[base.length()-1] == '"')
2040 return addExtension(trim(base, "\""), ext);
2041 if (full[full.length()-1] == '"')
2044 return trim(full, "\"");
2050 /// Convert \p name from TeX convention (relative to master file) to LyX
2051 /// convention (relative to .lyx file) if it is relative
2052 void fix_child_filename(string & name)
2054 string const absMasterTeX = getMasterFilePath(true);
2055 bool const isabs = FileName::isAbsolute(name);
2056 // convert from "relative to .tex master" to absolute original path
2058 name = makeAbsPath(name, absMasterTeX).absFileName();
2059 bool copyfile = copyFiles();
2060 string const absParentLyX = getParentFilePath(false);
2063 // convert from absolute original path to "relative to master file"
2064 string const rel = to_utf8(makeRelPath(from_utf8(name),
2065 from_utf8(absMasterTeX)));
2066 // re-interpret "relative to .tex file" as "relative to .lyx file"
2067 // (is different if the master .lyx file resides in a
2068 // different path than the master .tex file)
2069 string const absMasterLyX = getMasterFilePath(false);
2070 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2071 // Do not copy if the new path is impossible to create. Example:
2072 // absMasterTeX = "/foo/bar/"
2073 // absMasterLyX = "/bar/"
2074 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2075 if (contains(name, "/../"))
2082 // convert from absolute original path to
2083 // "relative to .lyx file"
2084 name = to_utf8(makeRelPath(from_utf8(abs),
2085 from_utf8(absParentLyX)));
2089 // convert from absolute original path to "relative to .lyx file"
2090 name = to_utf8(makeRelPath(from_utf8(name),
2091 from_utf8(absParentLyX)));
2096 void copy_file(FileName const & src, string dstname)
2100 string const absParent = getParentFilePath(false);
2102 if (FileName::isAbsolute(dstname))
2103 dst = FileName(dstname);
2105 dst = makeAbsPath(dstname, absParent);
2106 string const absMaster = getMasterFilePath(false);
2107 FileName const srcpath = src.onlyPath();
2108 FileName const dstpath = dst.onlyPath();
2109 if (equivalent(srcpath, dstpath))
2111 if (!dstpath.isDirectory()) {
2112 if (!dstpath.createPath()) {
2113 cerr << "Warning: Could not create directory for file `"
2114 << dst.absFileName() << "´." << endl;
2118 if (dst.isReadableFile()) {
2119 if (overwriteFiles())
2120 cerr << "Warning: Overwriting existing file `"
2121 << dst.absFileName() << "´." << endl;
2123 cerr << "Warning: Not overwriting existing file `"
2124 << dst.absFileName() << "´." << endl;
2128 if (!src.copyTo(dst))
2129 cerr << "Warning: Could not copy file `" << src.absFileName()
2130 << "´ to `" << dst.absFileName() << "´." << endl;
2134 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2135 bool parse_chunk(Parser & p, ostream & os, Context & context)
2137 // check whether a chunk is possible here.
2138 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2144 // read the parameters
2145 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2146 if (!params.first) {
2151 Parser::Arg const code = p.verbatimStuff("\n@");
2156 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2157 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2161 // The last newline read is important for paragraph handling
2165 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2166 // We must have a valid layout before outputting the Chunk inset.
2167 context.check_layout(os);
2168 Context chunkcontext(true, context.textclass);
2169 chunkcontext.layout = &context.textclass.plainLayout();
2170 begin_inset(os, "Flex Chunk");
2171 os << "\nstatus open\n";
2172 if (!params.second.empty()) {
2173 chunkcontext.check_layout(os);
2174 Context paramscontext(true, context.textclass);
2175 paramscontext.layout = &context.textclass.plainLayout();
2176 begin_inset(os, "Argument 1");
2177 os << "\nstatus open\n";
2178 output_ert(os, params.second, paramscontext);
2181 output_ert(os, code.second, chunkcontext);
2189 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2190 bool is_macro(Parser & p)
2192 Token first = p.curr_token();
2193 if (first.cat() != catEscape || !p.good())
2195 if (first.cs() == "def")
2197 if (first.cs() != "global" && first.cs() != "long")
2199 Token second = p.get_token();
2201 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2202 second.cat() == catNewline || second.cat() == catComment)) {
2203 second = p.get_token();
2206 bool secondvalid = second.cat() == catEscape;
2208 bool thirdvalid = false;
2209 if (p.good() && first.cs() == "global" && secondvalid &&
2210 second.cs() == "long") {
2211 third = p.get_token();
2213 while (p.good() && !p.isParagraph() &&
2214 (third.cat() == catSpace ||
2215 third.cat() == catNewline ||
2216 third.cat() == catComment)) {
2217 third = p.get_token();
2220 thirdvalid = third.cat() == catEscape;
2222 for (int i = 0; i < pos; ++i)
2227 return (first.cs() == "global" || first.cs() == "long") &&
2228 second.cs() == "def";
2229 return first.cs() == "global" && second.cs() == "long" &&
2230 third.cs() == "def";
2234 /// Parse a macro definition (assumes that is_macro() returned true)
2235 void parse_macro(Parser & p, ostream & os, Context & context)
2237 context.check_layout(os);
2238 Token first = p.curr_token();
2241 string command = first.asInput();
2242 if (first.cs() != "def") {
2244 eat_whitespace(p, os, context, false);
2245 second = p.curr_token();
2246 command += second.asInput();
2247 if (second.cs() != "def") {
2249 eat_whitespace(p, os, context, false);
2250 third = p.curr_token();
2251 command += third.asInput();
2254 eat_whitespace(p, os, context, false);
2255 string const name = p.get_token().cs();
2256 eat_whitespace(p, os, context, false);
2262 while (p.next_token().cat() != catBegin) {
2263 if (p.next_token().cat() == catParameter) {
2268 // followed by number?
2269 if (p.next_token().cat() == catOther) {
2270 string s = p.get_token().asInput();
2272 // number = current arity + 1?
2273 if (s.size() == 1 && s[0] == arity + '0' + 1)
2278 paramtext += p.get_token().cs();
2280 paramtext += p.get_token().cs();
2285 // only output simple (i.e. compatible) macro as FormulaMacros
2286 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2288 context.check_layout(os);
2289 begin_inset(os, "FormulaMacro");
2290 os << "\n\\def" << ert;
2293 output_ert_inset(os, command + ert, context);
2297 void registerExternalTemplatePackages(string const & name)
2299 external::TemplateManager const & etm = external::TemplateManager::get();
2300 external::Template const * const et = etm.getTemplateByName(name);
2303 external::Template::Formats::const_iterator cit = et->formats.end();
2305 cit = et->formats.find("PDFLaTeX");
2306 if (cit == et->formats.end())
2307 // If the template has not specified a PDFLaTeX output,
2308 // we try the LaTeX format.
2309 cit = et->formats.find("LaTeX");
2310 if (cit == et->formats.end())
2312 vector<string>::const_iterator qit = cit->second.requirements.begin();
2313 vector<string>::const_iterator qend = cit->second.requirements.end();
2314 for (; qit != qend; ++qit)
2315 preamble.registerAutomaticallyLoadedPackage(*qit);
2318 } // anonymous namespace
2321 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2324 Layout const * newlayout = 0;
2325 InsetLayout const * newinsetlayout = 0;
2326 char const * const * where = 0;
2327 // Store the latest bibliographystyle, addcontentslineContent and
2328 // nocite{*} option (needed for bibtex inset)
2330 string contentslineContent;
2331 string bibliographystyle = "default";
2332 bool const use_natbib = isProvided("natbib");
2333 bool const use_jurabib = isProvided("jurabib");
2336 // it is impossible to determine the correct encoding for non-CJK Japanese.
2337 // Therefore write a note at the beginning of the document
2338 if (is_nonCJKJapanese) {
2339 context.check_layout(os);
2340 begin_inset(os, "Note Note\n");
2341 os << "status open\n\\begin_layout Plain Layout\n"
2342 << "\\series bold\n"
2343 << "Important information:\n"
2344 << "\\end_layout\n\n"
2345 << "\\begin_layout Plain Layout\n"
2346 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2347 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2348 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2349 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2350 << " and specify the encoding using the -e command-line switch.\n"
2351 << " In addition, you might want to double check that the desired output encoding\n"
2352 << " is correctly selected in Document > Settings > Language.\n"
2353 << "\\end_layout\n";
2355 is_nonCJKJapanese = false;
2359 Token const & t = p.get_token();
2361 debugToken(cerr, t, flags);
2364 if (flags & FLAG_ITEM) {
2365 if (t.cat() == catSpace)
2368 flags &= ~FLAG_ITEM;
2369 if (t.cat() == catBegin) {
2370 // skip the brace and collect everything to the next matching
2372 flags |= FLAG_BRACE_LAST;
2376 // handle only this single token, leave the loop if done
2377 flags |= FLAG_LEAVE;
2380 if (t.cat() != catEscape && t.character() == ']' &&
2381 (flags & FLAG_BRACK_LAST))
2383 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2386 // If there is anything between \end{env} and \begin{env} we
2387 // don't need to output a separator.
2388 if (t.cat() != catSpace && t.cat() != catNewline &&
2389 t.asInput() != "\\begin")
2395 bool const starred = p.next_token().asInput() == "*";
2396 string const starredname(starred ? (t.cs() + '*') : t.cs());
2397 if (t.cat() == catMath) {
2398 // we are inside some text mode thingy, so opening new math is allowed
2399 context.check_layout(os);
2400 begin_inset(os, "Formula ");
2401 Token const & n = p.get_token();
2402 bool const display(n.cat() == catMath && outer);
2404 // TeX's $$...$$ syntax for displayed math
2406 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2408 p.get_token(); // skip the second '$' token
2410 // simple $...$ stuff
2413 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2418 // Prevent the conversion of a line break to a
2419 // space (bug 7668). This does not change the
2420 // output, but looks ugly in LyX.
2421 eat_whitespace(p, os, context, false);
2425 else if (t.cat() == catSuper || t.cat() == catSub)
2426 cerr << "catcode " << t << " illegal in text mode\n";
2428 // Basic support for english quotes. This should be
2429 // extended to other quotes, but is not so easy (a
2430 // left english quote is the same as a right german
2432 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2433 context.check_layout(os);
2434 begin_inset(os, "Quotes ");
2440 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2441 context.check_layout(os);
2442 begin_inset(os, "Quotes ");
2449 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2450 context.check_layout(os);
2451 begin_inset(os, "Quotes ");
2458 else if (t.asInput() == "<"
2459 && p.next_token().asInput() == "<") {
2460 bool has_chunk = false;
2464 has_chunk = parse_chunk(p, os, context);
2470 context.check_layout(os);
2471 begin_inset(os, "Quotes ");
2472 //FIXME: this is a right danish quote;
2473 // why not a left french quote?
2481 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2482 check_space(p, os, context);
2484 else if (t.character() == '[' && noweb_mode &&
2485 p.next_token().character() == '[') {
2486 // These can contain underscores
2488 string const s = p.getFullOpt() + ']';
2489 if (p.next_token().character() == ']')
2492 cerr << "Warning: Inserting missing ']' in '"
2493 << s << "'." << endl;
2494 output_ert_inset(os, s, context);
2497 else if (t.cat() == catLetter) {
2498 context.check_layout(os);
2502 else if (t.cat() == catOther ||
2503 t.cat() == catAlign ||
2504 t.cat() == catParameter) {
2505 context.check_layout(os);
2506 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2507 context.merging_hyphens_allowed &&
2508 context.font.family != "ttfamily" &&
2509 !context.layout->pass_thru) {
2510 if (p.next_next_token().asInput() == "-") {
2512 os << to_utf8(docstring(1, 0x2014));
2516 os << to_utf8(docstring(1, 0x2013));
2519 // This translates "&" to "\\&" which may be wrong...
2523 else if (p.isParagraph()) {
2524 if (context.new_layout_allowed)
2525 context.new_paragraph(os);
2527 output_ert_inset(os, "\\par ", context);
2528 eat_whitespace(p, os, context, true);
2531 else if (t.cat() == catActive) {
2532 context.check_layout(os);
2533 if (t.character() == '~') {
2534 if (context.layout->free_spacing)
2537 begin_inset(os, "space ~\n");
2544 else if (t.cat() == catBegin) {
2545 Token const next = p.next_token();
2546 Token const end = p.next_next_token();
2547 if (next.cat() == catEnd) {
2549 Token const prev = p.prev_token();
2551 if (p.next_token().character() == '`')
2552 ; // ignore it in {}``
2554 output_ert_inset(os, "{}", context);
2555 } else if (next.cat() == catEscape &&
2556 is_known(next.cs(), known_quotes) &&
2557 end.cat() == catEnd) {
2558 // Something like {\textquoteright} (e.g.
2559 // from writer2latex). LyX writes
2560 // \textquoteright{}, so we may skip the
2561 // braces here for better readability.
2562 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2564 } else if (p.next_token().asInput() == "\\ascii") {
2565 // handle the \ascii characters
2566 // (the case without braces is handled later)
2567 // the code is "{\ascii\xxx}"
2568 p.get_token(); // eat \ascii
2569 string name2 = p.get_token().asInput();
2570 p.get_token(); // eat the final '}'
2571 string const name = "{\\ascii" + name2 + "}";
2575 // get the character from unicodesymbols
2576 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2577 Encodings::TEXT_CMD, termination, rem, &req);
2579 context.check_layout(os);
2582 output_ert_inset(os,
2583 to_utf8(rem), context);
2584 for (set<string>::const_iterator it = req.begin();
2585 it != req.end(); ++it)
2586 preamble.registerAutomaticallyLoadedPackage(*it);
2588 // we did not find a non-ert version
2589 output_ert_inset(os, name, context);
2591 context.check_layout(os);
2592 // special handling of font attribute changes
2593 Token const prev = p.prev_token();
2594 TeXFont const oldFont = context.font;
2595 if (next.character() == '[' ||
2596 next.character() == ']' ||
2597 next.character() == '*') {
2599 if (p.next_token().cat() == catEnd) {
2604 output_ert_inset(os, "{", context);
2605 parse_text_snippet(p, os,
2608 output_ert_inset(os, "}", context);
2610 } else if (! context.new_layout_allowed) {
2611 output_ert_inset(os, "{", context);
2612 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2614 output_ert_inset(os, "}", context);
2615 } else if (is_known(next.cs(), known_sizes)) {
2616 // next will change the size, so we must
2618 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2620 if (!context.atParagraphStart())
2622 << context.font.size << "\n";
2623 } else if (is_known(next.cs(), known_font_families)) {
2624 // next will change the font family, so we
2625 // must reset it here
2626 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2628 if (!context.atParagraphStart())
2630 << context.font.family << "\n";
2631 } else if (is_known(next.cs(), known_font_series)) {
2632 // next will change the font series, so we
2633 // must reset it here
2634 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2636 if (!context.atParagraphStart())
2638 << context.font.series << "\n";
2639 } else if (is_known(next.cs(), known_font_shapes)) {
2640 // next will change the font shape, so we
2641 // must reset it here
2642 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2644 if (!context.atParagraphStart())
2646 << context.font.shape << "\n";
2647 } else if (is_known(next.cs(), known_old_font_families) ||
2648 is_known(next.cs(), known_old_font_series) ||
2649 is_known(next.cs(), known_old_font_shapes)) {
2650 // next will change the font family, series
2651 // and shape, so we must reset it here
2652 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2654 if (!context.atParagraphStart())
2656 << context.font.family
2658 << context.font.series
2660 << context.font.shape << "\n";
2662 output_ert_inset(os, "{", context);
2663 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2665 output_ert_inset(os, "}", context);
2670 else if (t.cat() == catEnd) {
2671 if (flags & FLAG_BRACE_LAST) {
2674 cerr << "stray '}' in text\n";
2675 output_ert_inset(os, "}", context);
2678 else if (t.cat() == catComment)
2679 parse_comment(p, os, t, context);
2682 // control sequences
2685 else if (t.cs() == "(" || t.cs() == "[") {
2686 bool const simple = t.cs() == "(";
2687 context.check_layout(os);
2688 begin_inset(os, "Formula");
2689 os << " \\" << t.cs();
2690 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2691 os << '\\' << (simple ? ')' : ']');
2694 // Prevent the conversion of a line break to a
2695 // space (bug 7668). This does not change the
2696 // output, but looks ugly in LyX.
2697 eat_whitespace(p, os, context, false);
2701 else if (t.cs() == "begin")
2702 parse_environment(p, os, outer, last_env,
2705 else if (t.cs() == "end") {
2706 if (flags & FLAG_END) {
2707 // eat environment name
2708 string const name = p.getArg('{', '}');
2709 if (name != active_environment())
2710 cerr << "\\end{" + name + "} does not match \\begin{"
2711 + active_environment() + "}\n";
2714 p.error("found 'end' unexpectedly");
2717 else if (t.cs() == "item") {
2719 bool const optarg = p.hasOpt();
2721 // FIXME: This swallows comments, but we cannot use
2722 // eat_whitespace() since we must not output
2723 // anything before the item.
2724 p.skip_spaces(true);
2725 s = p.verbatimOption();
2727 p.skip_spaces(false);
2729 context.check_layout(os);
2730 if (context.has_item) {
2731 // An item in an unknown list-like environment
2732 // FIXME: Do this in check_layout()!
2733 context.has_item = false;
2735 output_ert_inset(os, "\\item", context);
2737 output_ert_inset(os, "\\item ", context);
2740 if (context.layout->labeltype != LABEL_MANUAL) {
2741 // handle option of itemize item
2742 begin_inset(os, "Argument item:1\n");
2743 os << "status open\n";
2744 os << "\n\\begin_layout Plain Layout\n";
2746 os << parse_text_snippet(p2,
2747 FLAG_BRACK_LAST, outer, context);
2748 // we must not use context.check_end_layout(os)
2749 // because that would close the outer itemize layout
2750 os << "\n\\end_layout\n";
2752 eat_whitespace(p, os, context, false);
2753 } else if (!s.empty()) {
2754 // LyX adds braces around the argument,
2755 // so we need to remove them here.
2756 if (s.size() > 2 && s[0] == '{' &&
2757 s[s.size()-1] == '}')
2758 s = s.substr(1, s.size()-2);
2759 // If the argument contains a space we
2760 // must put it into ERT: Otherwise LyX
2761 // would misinterpret the space as
2762 // item delimiter (bug 7663)
2763 if (contains(s, ' ')) {
2764 output_ert_inset(os, s, context);
2767 os << parse_text_snippet(p2,
2768 FLAG_BRACK_LAST, outer, context);
2770 // The space is needed to separate the
2771 // item from the rest of the sentence.
2773 eat_whitespace(p, os, context, false);
2778 else if (t.cs() == "bibitem") {
2780 context.check_layout(os);
2781 eat_whitespace(p, os, context, false);
2782 string label = convert_command_inset_arg(p.verbatimOption());
2783 string key = convert_command_inset_arg(p.verbatim_item());
2784 if (contains(label, '\\') || contains(key, '\\')) {
2785 // LyX can't handle LaTeX commands in labels or keys
2786 output_ert_inset(os, t.asInput() + '[' + label +
2787 "]{" + p.verbatim_item() + '}',
2790 begin_command_inset(os, "bibitem", "bibitem");
2791 os << "label \"" << label << "\"\n"
2792 "key \"" << key << "\"\n";
2797 else if (is_macro(p)) {
2798 // catch the case of \def\inputGnumericTable
2800 if (t.cs() == "def") {
2801 Token second = p.next_token();
2802 if (second.cs() == "inputGnumericTable") {
2806 Token third = p.get_token();
2808 if (third.cs() == "input") {
2812 string name = normalize_filename(p.verbatim_item());
2813 string const path = getMasterFilePath(true);
2814 // We want to preserve relative / absolute filenames,
2815 // therefore path is only used for testing
2816 // The file extension is in every case ".tex".
2817 // So we need to remove this extension and check for
2818 // the original one.
2819 name = removeExtension(name);
2820 if (!makeAbsPath(name, path).exists()) {
2821 char const * const Gnumeric_formats[] = {"gnumeric",
2823 string const Gnumeric_name =
2824 find_file(name, path, Gnumeric_formats);
2825 if (!Gnumeric_name.empty())
2826 name = Gnumeric_name;
2828 FileName const absname = makeAbsPath(name, path);
2829 if (absname.exists()) {
2830 fix_child_filename(name);
2831 copy_file(absname, name);
2833 cerr << "Warning: Could not find file '"
2834 << name << "'." << endl;
2835 context.check_layout(os);
2836 begin_inset(os, "External\n\ttemplate ");
2837 os << "GnumericSpreadsheet\n\tfilename "
2840 context.check_layout(os);
2842 // register the packages that are automatically loaded
2843 // by the Gnumeric template
2844 registerExternalTemplatePackages("GnumericSpreadsheet");
2849 parse_macro(p, os, context);
2852 else if (t.cs() == "noindent") {
2854 context.add_par_extra_stuff("\\noindent\n");
2857 else if (t.cs() == "appendix") {
2858 context.add_par_extra_stuff("\\start_of_appendix\n");
2859 // We need to start a new paragraph. Otherwise the
2860 // appendix in 'bla\appendix\chapter{' would start
2862 context.new_paragraph(os);
2863 // We need to make sure that the paragraph is
2864 // generated even if it is empty. Otherwise the
2865 // appendix in '\par\appendix\par\chapter{' would
2867 context.check_layout(os);
2868 // FIXME: This is a hack to prevent paragraph
2869 // deletion if it is empty. Handle this better!
2870 output_ert_inset(os,
2871 "%dummy comment inserted by tex2lyx to "
2872 "ensure that this paragraph is not empty",
2874 // Both measures above may generate an additional
2875 // empty paragraph, but that does not hurt, because
2876 // whitespace does not matter here.
2877 eat_whitespace(p, os, context, true);
2880 // Must catch empty dates before findLayout is called below
2881 else if (t.cs() == "date") {
2882 eat_whitespace(p, os, context, false);
2884 string const date = p.verbatim_item();
2887 preamble.suppressDate(true);
2890 preamble.suppressDate(false);
2891 if (context.new_layout_allowed &&
2892 (newlayout = findLayout(context.textclass,
2895 output_command_layout(os, p, outer,
2896 context, newlayout);
2897 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2898 if (!preamble.titleLayoutFound())
2899 preamble.titleLayoutFound(newlayout->intitle);
2900 set<string> const & req = newlayout->requires();
2901 set<string>::const_iterator it = req.begin();
2902 set<string>::const_iterator en = req.end();
2903 for (; it != en; ++it)
2904 preamble.registerAutomaticallyLoadedPackage(*it);
2906 output_ert_inset(os,
2907 "\\date{" + p.verbatim_item() + '}',
2912 // Starred section headings
2913 // Must attempt to parse "Section*" before "Section".
2914 else if ((p.next_token().asInput() == "*") &&
2915 context.new_layout_allowed &&
2916 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2919 output_command_layout(os, p, outer, context, newlayout);
2921 if (!preamble.titleLayoutFound())
2922 preamble.titleLayoutFound(newlayout->intitle);
2923 set<string> const & req = newlayout->requires();
2924 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2925 preamble.registerAutomaticallyLoadedPackage(*it);
2928 // Section headings and the like
2929 else if (context.new_layout_allowed &&
2930 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2932 output_command_layout(os, p, outer, context, newlayout);
2934 if (!preamble.titleLayoutFound())
2935 preamble.titleLayoutFound(newlayout->intitle);
2936 set<string> const & req = newlayout->requires();
2937 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2938 preamble.registerAutomaticallyLoadedPackage(*it);
2941 else if (t.cs() == "subfloat") {
2942 // the syntax is \subfloat[list entry][sub caption]{content}
2943 // if it is a table of figure depends on the surrounding float
2944 // FIXME: second optional argument is not parsed
2945 bool has_caption = false;
2947 // do nothing if there is no outer float
2948 if (!float_type.empty()) {
2949 context.check_layout(os);
2951 begin_inset(os, "Float " + float_type + "\n");
2953 << "\nsideways false"
2954 << "\nstatus collapsed\n\n";
2957 if (p.next_token().cat() != catEscape &&
2958 p.next_token().character() == '[') {
2959 p.get_token(); // eat '['
2960 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2964 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2965 // the caption comes always as the last
2967 // we must make sure that the caption gets a \begin_layout
2968 os << "\n\\begin_layout Plain Layout";
2970 begin_inset(os, "Caption Standard\n");
2971 Context newcontext(true, context.textclass,
2972 0, 0, context.font);
2973 newcontext.check_layout(os);
2974 os << caption << "\n";
2975 newcontext.check_end_layout(os);
2976 // We don't need really a new paragraph, but
2977 // we must make sure that the next item gets a \begin_layout.
2978 //newcontext.new_paragraph(os);
2982 // We don't need really a new paragraph, but
2983 // we must make sure that the next item gets a \begin_layout.
2985 context.new_paragraph(os);
2988 context.check_end_layout(os);
2989 // close the layout we opened
2991 os << "\n\\end_layout\n";
2993 // if the float type is not supported or there is no surrounding float
2996 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2997 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2998 "]{" + p.verbatim_item() + '}', context);
3000 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3004 else if (t.cs() == "includegraphics") {
3005 bool const clip = p.next_token().asInput() == "*";
3008 string const arg = p.getArg('[', ']');
3009 map<string, string> opts;
3010 vector<string> keys;
3011 split_map(arg, opts, keys);
3013 opts["clip"] = string();
3014 string name = normalize_filename(p.verbatim_item());
3016 string const path = getMasterFilePath(true);
3017 // We want to preserve relative / absolute filenames,
3018 // therefore path is only used for testing
3019 if (!makeAbsPath(name, path).exists()) {
3020 // The file extension is probably missing.
3021 // Now try to find it out.
3022 string const dvips_name =
3023 find_file(name, path,
3024 known_dvips_graphics_formats);
3025 string const pdftex_name =
3026 find_file(name, path,
3027 known_pdftex_graphics_formats);
3028 if (!dvips_name.empty()) {
3029 if (!pdftex_name.empty()) {
3030 cerr << "This file contains the "
3032 "\"\\includegraphics{"
3034 "However, files\n\""
3035 << dvips_name << "\" and\n\""
3036 << pdftex_name << "\"\n"
3037 "both exist, so I had to make a "
3038 "choice and took the first one.\n"
3039 "Please move the unwanted one "
3040 "someplace else and try again\n"
3041 "if my choice was wrong."
3045 } else if (!pdftex_name.empty()) {
3051 FileName const absname = makeAbsPath(name, path);
3052 if (absname.exists()) {
3053 fix_child_filename(name);
3054 copy_file(absname, name);
3056 cerr << "Warning: Could not find graphics file '"
3057 << name << "'." << endl;
3059 context.check_layout(os);
3060 begin_inset(os, "Graphics ");
3061 os << "\n\tfilename " << name << '\n';
3062 if (opts.find("width") != opts.end())
3064 << translate_len(opts["width"]) << '\n';
3065 if (opts.find("height") != opts.end())
3067 << translate_len(opts["height"]) << '\n';
3068 if (opts.find("scale") != opts.end()) {
3069 istringstream iss(opts["scale"]);
3073 os << "\tscale " << val << '\n';
3075 if (opts.find("angle") != opts.end()) {
3076 os << "\trotateAngle "
3077 << opts["angle"] << '\n';
3078 vector<string>::const_iterator a =
3079 find(keys.begin(), keys.end(), "angle");
3080 vector<string>::const_iterator s =
3081 find(keys.begin(), keys.end(), "width");
3082 if (s == keys.end())
3083 s = find(keys.begin(), keys.end(), "height");
3084 if (s == keys.end())
3085 s = find(keys.begin(), keys.end(), "scale");
3086 if (s != keys.end() && distance(s, a) > 0)
3087 os << "\tscaleBeforeRotation\n";
3089 if (opts.find("origin") != opts.end()) {
3091 string const opt = opts["origin"];
3092 if (opt.find('l') != string::npos) ss << "left";
3093 if (opt.find('r') != string::npos) ss << "right";
3094 if (opt.find('c') != string::npos) ss << "center";
3095 if (opt.find('t') != string::npos) ss << "Top";
3096 if (opt.find('b') != string::npos) ss << "Bottom";
3097 if (opt.find('B') != string::npos) ss << "Baseline";
3098 if (!ss.str().empty())
3099 os << "\trotateOrigin " << ss.str() << '\n';
3101 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3103 if (opts.find("keepaspectratio") != opts.end())
3104 os << "\tkeepAspectRatio\n";
3105 if (opts.find("clip") != opts.end())
3107 if (opts.find("draft") != opts.end())
3109 if (opts.find("bb") != opts.end())
3110 os << "\tBoundingBox "
3111 << opts["bb"] << '\n';
3112 int numberOfbbOptions = 0;
3113 if (opts.find("bbllx") != opts.end())
3114 numberOfbbOptions++;
3115 if (opts.find("bblly") != opts.end())
3116 numberOfbbOptions++;
3117 if (opts.find("bburx") != opts.end())
3118 numberOfbbOptions++;
3119 if (opts.find("bbury") != opts.end())
3120 numberOfbbOptions++;
3121 if (numberOfbbOptions == 4)
3122 os << "\tBoundingBox "
3123 << opts["bbllx"] << " " << opts["bblly"] << " "
3124 << opts["bburx"] << " " << opts["bbury"] << '\n';
3125 else if (numberOfbbOptions > 0)
3126 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3127 numberOfbbOptions = 0;
3128 if (opts.find("natwidth") != opts.end())
3129 numberOfbbOptions++;
3130 if (opts.find("natheight") != opts.end())
3131 numberOfbbOptions++;
3132 if (numberOfbbOptions == 2)
3133 os << "\tBoundingBox 0bp 0bp "
3134 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3135 else if (numberOfbbOptions > 0)
3136 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3137 ostringstream special;
3138 if (opts.find("hiresbb") != opts.end())
3139 special << "hiresbb,";
3140 if (opts.find("trim") != opts.end())
3142 if (opts.find("viewport") != opts.end())
3143 special << "viewport=" << opts["viewport"] << ',';
3144 if (opts.find("totalheight") != opts.end())
3145 special << "totalheight=" << opts["totalheight"] << ',';
3146 if (opts.find("type") != opts.end())
3147 special << "type=" << opts["type"] << ',';
3148 if (opts.find("ext") != opts.end())
3149 special << "ext=" << opts["ext"] << ',';
3150 if (opts.find("read") != opts.end())
3151 special << "read=" << opts["read"] << ',';
3152 if (opts.find("command") != opts.end())
3153 special << "command=" << opts["command"] << ',';
3154 string s_special = special.str();
3155 if (!s_special.empty()) {
3156 // We had special arguments. Remove the trailing ','.
3157 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3159 // TODO: Handle the unknown settings better.
3160 // Warn about invalid options.
3161 // Check whether some option was given twice.
3163 preamble.registerAutomaticallyLoadedPackage("graphicx");
3166 else if (t.cs() == "footnote" ||
3167 (t.cs() == "thanks" && context.layout->intitle)) {
3169 context.check_layout(os);
3170 begin_inset(os, "Foot\n");
3171 os << "status collapsed\n\n";
3172 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3176 else if (t.cs() == "marginpar") {
3178 context.check_layout(os);
3179 begin_inset(os, "Marginal\n");
3180 os << "status collapsed\n\n";
3181 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3185 else if (t.cs() == "lstinline") {
3187 parse_listings(p, os, context, true);
3190 else if (t.cs() == "ensuremath") {
3192 context.check_layout(os);
3193 string const s = p.verbatim_item();
3194 //FIXME: this never triggers in UTF8
3195 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3198 output_ert_inset(os, "\\ensuremath{" + s + "}",
3202 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3203 if (preamble.titleLayoutFound()) {
3205 skip_spaces_braces(p);
3207 output_ert_inset(os, t.asInput(), context);
3210 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3211 context.check_layout(os);
3212 begin_command_inset(os, "toc", t.cs());
3214 skip_spaces_braces(p);
3215 if (t.cs() == "lstlistoflistings")
3216 preamble.registerAutomaticallyLoadedPackage("listings");
3219 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3220 context.check_layout(os);
3221 if (t.cs() == "listoffigures")
3222 begin_inset(os, "FloatList figure\n");
3224 begin_inset(os, "FloatList table\n");
3226 skip_spaces_braces(p);
3229 else if (t.cs() == "listof") {
3230 p.skip_spaces(true);
3231 string const name = p.get_token().cs();
3232 if (context.textclass.floats().typeExist(name)) {
3233 context.check_layout(os);
3234 begin_inset(os, "FloatList ");
3237 p.get_token(); // swallow second arg
3239 output_ert_inset(os, "\\listof{" + name + "}", context);
3242 else if ((where = is_known(t.cs(), known_text_font_families)))
3243 parse_text_attributes(p, os, FLAG_ITEM, outer,
3244 context, "\\family", context.font.family,
3245 known_coded_font_families[where - known_text_font_families]);
3247 else if ((where = is_known(t.cs(), known_text_font_series)))
3248 parse_text_attributes(p, os, FLAG_ITEM, outer,
3249 context, "\\series", context.font.series,
3250 known_coded_font_series[where - known_text_font_series]);
3252 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3253 parse_text_attributes(p, os, FLAG_ITEM, outer,
3254 context, "\\shape", context.font.shape,
3255 known_coded_font_shapes[where - known_text_font_shapes]);
3257 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3258 context.check_layout(os);
3259 TeXFont oldFont = context.font;
3260 context.font.init();
3261 context.font.size = oldFont.size;
3262 os << "\n\\family " << context.font.family << "\n";
3263 os << "\n\\series " << context.font.series << "\n";
3264 os << "\n\\shape " << context.font.shape << "\n";
3265 if (t.cs() == "textnormal") {
3266 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3267 output_font_change(os, context.font, oldFont);
3268 context.font = oldFont;
3270 eat_whitespace(p, os, context, false);
3273 else if (t.cs() == "textcolor") {
3274 // scheme is \textcolor{color name}{text}
3275 string const color = p.verbatim_item();
3276 // we support the predefined colors of the color and the xcolor package
3277 if (color == "black" || color == "blue" || color == "cyan"
3278 || color == "green" || color == "magenta" || color == "red"
3279 || color == "white" || color == "yellow") {
3280 context.check_layout(os);
3281 os << "\n\\color " << color << "\n";
3282 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3283 context.check_layout(os);
3284 os << "\n\\color inherit\n";
3285 preamble.registerAutomaticallyLoadedPackage("color");
3286 } else if (color == "brown" || color == "darkgray" || color == "gray"
3287 || color == "lightgray" || color == "lime" || color == "olive"
3288 || color == "orange" || color == "pink" || color == "purple"
3289 || color == "teal" || color == "violet") {
3290 context.check_layout(os);
3291 os << "\n\\color " << color << "\n";
3292 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3293 context.check_layout(os);
3294 os << "\n\\color inherit\n";
3295 preamble.registerAutomaticallyLoadedPackage("xcolor");
3297 // for custom defined colors
3298 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3301 else if (t.cs() == "underbar" || t.cs() == "uline") {
3302 // \underbar is not 100% correct (LyX outputs \uline
3303 // of ulem.sty). The difference is that \ulem allows
3304 // line breaks, and \underbar does not.
3305 // Do NOT handle \underline.
3306 // \underbar cuts through y, g, q, p etc.,
3307 // \underline does not.
3308 context.check_layout(os);
3309 os << "\n\\bar under\n";
3310 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3311 context.check_layout(os);
3312 os << "\n\\bar default\n";
3313 preamble.registerAutomaticallyLoadedPackage("ulem");
3316 else if (t.cs() == "sout") {
3317 context.check_layout(os);
3318 os << "\n\\strikeout on\n";
3319 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3320 context.check_layout(os);
3321 os << "\n\\strikeout default\n";
3322 preamble.registerAutomaticallyLoadedPackage("ulem");
3325 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3326 t.cs() == "emph" || t.cs() == "noun") {
3327 context.check_layout(os);
3328 os << "\n\\" << t.cs() << " on\n";
3329 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3330 context.check_layout(os);
3331 os << "\n\\" << t.cs() << " default\n";
3332 if (t.cs() == "uuline" || t.cs() == "uwave")
3333 preamble.registerAutomaticallyLoadedPackage("ulem");
3336 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3337 context.check_layout(os);
3338 string name = p.getArg('{', '}');
3339 string localtime = p.getArg('{', '}');
3340 preamble.registerAuthor(name);
3341 Author const & author = preamble.getAuthor(name);
3342 // from_asctime_utc() will fail if LyX decides to output the
3343 // time in the text language.
3344 time_t ptime = from_asctime_utc(localtime);
3345 if (ptime == static_cast<time_t>(-1)) {
3346 cerr << "Warning: Could not parse time `" << localtime
3347 << "´ for change tracking, using current time instead.\n";
3348 ptime = current_time();
3350 if (t.cs() == "lyxadded")
3351 os << "\n\\change_inserted ";
3353 os << "\n\\change_deleted ";
3354 os << author.bufferId() << ' ' << ptime << '\n';
3355 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3356 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3357 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3358 LaTeXPackages::isAvailable("xcolor");
3359 // No need to test for luatex, since luatex comes in
3360 // two flavours (dvi and pdf), like latex, and those
3361 // are detected by pdflatex.
3362 if (pdflatex || xetex) {
3364 preamble.registerAutomaticallyLoadedPackage("ulem");
3365 preamble.registerAutomaticallyLoadedPackage("xcolor");
3366 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3370 preamble.registerAutomaticallyLoadedPackage("dvipost");
3371 } else if (xcolorulem) {
3372 preamble.registerAutomaticallyLoadedPackage("ulem");
3373 preamble.registerAutomaticallyLoadedPackage("xcolor");
3378 else if (t.cs() == "textipa") {
3379 context.check_layout(os);
3380 begin_inset(os, "IPA\n");
3381 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3382 context.merging_hyphens_allowed = false;
3383 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3384 context.merging_hyphens_allowed = merging_hyphens_allowed;
3386 preamble.registerAutomaticallyLoadedPackage("tipa");
3387 preamble.registerAutomaticallyLoadedPackage("tipx");
3390 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3391 context.check_layout(os);
3392 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3393 os << "status open\n";
3394 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3399 else if (t.cs() == "textvertline") {
3400 // FIXME: This is not correct, \textvertline is higher than |
3406 else if (t.cs() == "tone" ) {
3407 context.check_layout(os);
3408 // register the tone package
3409 preamble.registerAutomaticallyLoadedPackage("tone");
3410 string content = trimSpaceAndEol(p.verbatim_item());
3411 string command = t.asInput() + "{" + content + "}";
3412 // some tones can be detected by unicodesymbols, some need special code
3413 if (is_known(content, known_tones)) {
3414 os << "\\IPAChar " << command << "\n";
3417 // try to see whether the string is in unicodesymbols
3421 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3422 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3423 termination, rem, &req);
3427 output_ert_inset(os, to_utf8(rem), context);
3428 for (set<string>::const_iterator it = req.begin();
3429 it != req.end(); ++it)
3430 preamble.registerAutomaticallyLoadedPackage(*it);
3432 // we did not find a non-ert version
3433 output_ert_inset(os, command, context);
3436 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3437 t.cs() == "vphantom") {
3438 context.check_layout(os);
3439 if (t.cs() == "phantom")
3440 begin_inset(os, "Phantom Phantom\n");
3441 if (t.cs() == "hphantom")
3442 begin_inset(os, "Phantom HPhantom\n");
3443 if (t.cs() == "vphantom")
3444 begin_inset(os, "Phantom VPhantom\n");
3445 os << "status open\n";
3446 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3451 else if (t.cs() == "href") {
3452 context.check_layout(os);
3453 string target = convert_command_inset_arg(p.verbatim_item());
3454 string name = convert_command_inset_arg(p.verbatim_item());
3456 size_t i = target.find(':');
3457 if (i != string::npos) {
3458 type = target.substr(0, i + 1);
3459 if (type == "mailto:" || type == "file:")
3460 target = target.substr(i + 1);
3461 // handle the case that name is equal to target, except of "http://"
3462 else if (target.substr(i + 3) == name && type == "http:")
3465 begin_command_inset(os, "href", "href");
3467 os << "name \"" << name << "\"\n";
3468 os << "target \"" << target << "\"\n";
3469 if (type == "mailto:" || type == "file:")
3470 os << "type \"" << type << "\"\n";
3472 skip_spaces_braces(p);
3475 else if (t.cs() == "lyxline") {
3476 // swallow size argument (it is not used anyway)
3478 if (!context.atParagraphStart()) {
3479 // so our line is in the middle of a paragraph
3480 // we need to add a new line, lest this line
3481 // follow the other content on that line and
3482 // run off the side of the page
3483 // FIXME: This may create an empty paragraph,
3484 // but without that it would not be
3485 // possible to set noindent below.
3486 // Fortunately LaTeX does not care
3487 // about the empty paragraph.
3488 context.new_paragraph(os);
3490 if (preamble.indentParagraphs()) {
3491 // we need to unindent, lest the line be too long
3492 context.add_par_extra_stuff("\\noindent\n");
3494 context.check_layout(os);
3495 begin_command_inset(os, "line", "rule");
3496 os << "offset \"0.5ex\"\n"
3497 "width \"100line%\"\n"
3502 else if (t.cs() == "rule") {
3503 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3504 string const width = p.getArg('{', '}');
3505 string const thickness = p.getArg('{', '}');
3506 context.check_layout(os);
3507 begin_command_inset(os, "line", "rule");
3508 if (!offset.empty())
3509 os << "offset \"" << translate_len(offset) << "\"\n";
3510 os << "width \"" << translate_len(width) << "\"\n"
3511 "height \"" << translate_len(thickness) << "\"\n";
3515 // handle refstyle first to catch \eqref which can also occur
3516 // without refstyle. Only recognize these commands if
3517 // refstyle.sty was found in the preamble (otherwise \eqref
3518 // and user defined ref commands could be misdetected).
3519 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3520 preamble.refstyle()) {
3521 context.check_layout(os);
3522 begin_command_inset(os, "ref", "formatted");
3523 os << "reference \"";
3524 os << known_refstyle_prefixes[where - known_refstyle_commands]
3526 os << convert_command_inset_arg(p.verbatim_item())
3529 preamble.registerAutomaticallyLoadedPackage("refstyle");
3532 // if refstyle is used, we must not convert \prettyref to a
3533 // formatted reference, since that would result in a refstyle command.
3534 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3535 (t.cs() != "prettyref" || !preamble.refstyle())) {
3536 string const opt = p.getOpt();
3538 context.check_layout(os);
3539 begin_command_inset(os, "ref",
3540 known_coded_ref_commands[where - known_ref_commands]);
3541 os << "reference \""
3542 << convert_command_inset_arg(p.verbatim_item())
3545 if (t.cs() == "vref" || t.cs() == "vpageref")
3546 preamble.registerAutomaticallyLoadedPackage("varioref");
3547 else if (t.cs() == "prettyref")
3548 preamble.registerAutomaticallyLoadedPackage("prettyref");
3550 // LyX does not yet support optional arguments of ref commands
3551 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3552 p.verbatim_item() + '}', context);
3556 else if (use_natbib &&
3557 is_known(t.cs(), known_natbib_commands) &&
3558 ((t.cs() != "citefullauthor" &&
3559 t.cs() != "citeyear" &&
3560 t.cs() != "citeyearpar") ||
3561 p.next_token().asInput() != "*")) {
3562 context.check_layout(os);
3563 string command = t.cs();
3564 if (p.next_token().asInput() == "*") {
3568 if (command == "citefullauthor")
3569 // alternative name for "\\citeauthor*"
3570 command = "citeauthor*";
3572 // text before the citation
3574 // text after the citation
3576 get_cite_arguments(p, true, before, after);
3578 if (command == "cite") {
3579 // \cite without optional argument means
3580 // \citet, \cite with at least one optional
3581 // argument means \citep.
3582 if (before.empty() && after.empty())
3587 if (before.empty() && after == "[]")
3588 // avoid \citet[]{a}
3590 else if (before == "[]" && after == "[]") {
3591 // avoid \citet[][]{a}
3595 // remove the brackets around after and before
3596 if (!after.empty()) {
3598 after.erase(after.length() - 1, 1);
3599 after = convert_command_inset_arg(after);
3601 if (!before.empty()) {
3603 before.erase(before.length() - 1, 1);
3604 before = convert_command_inset_arg(before);
3606 begin_command_inset(os, "citation", command);
3607 os << "after " << '"' << after << '"' << "\n";
3608 os << "before " << '"' << before << '"' << "\n";
3610 << convert_command_inset_arg(p.verbatim_item())
3613 // Need to set the cite engine if natbib is loaded by
3614 // the document class directly
3615 if (preamble.citeEngine() == "basic")
3616 preamble.citeEngine("natbib");
3619 else if (use_jurabib &&
3620 is_known(t.cs(), known_jurabib_commands) &&
3621 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3622 context.check_layout(os);
3623 string command = t.cs();
3624 if (p.next_token().asInput() == "*") {
3628 char argumentOrder = '\0';
3629 vector<string> const options =
3630 preamble.getPackageOptions("jurabib");
3631 if (find(options.begin(), options.end(),
3632 "natbiborder") != options.end())
3633 argumentOrder = 'n';
3634 else if (find(options.begin(), options.end(),
3635 "jurabiborder") != options.end())
3636 argumentOrder = 'j';
3638 // text before the citation
3640 // text after the citation
3642 get_cite_arguments(p, argumentOrder != 'j', before, after);
3644 string const citation = p.verbatim_item();
3645 if (!before.empty() && argumentOrder == '\0') {
3646 cerr << "Warning: Assuming argument order "
3647 "of jurabib version 0.6 for\n'"
3648 << command << before << after << '{'
3649 << citation << "}'.\n"
3650 "Add 'jurabiborder' to the jurabib "
3651 "package options if you used an\n"
3652 "earlier jurabib version." << endl;
3654 if (!after.empty()) {
3656 after.erase(after.length() - 1, 1);
3658 if (!before.empty()) {
3660 before.erase(before.length() - 1, 1);
3662 begin_command_inset(os, "citation", command);
3663 os << "after " << '"' << after << '"' << "\n";
3664 os << "before " << '"' << before << '"' << "\n";
3665 os << "key " << '"' << citation << '"' << "\n";
3667 // Need to set the cite engine if jurabib is loaded by
3668 // the document class directly
3669 if (preamble.citeEngine() == "basic")
3670 preamble.citeEngine("jurabib");
3673 else if (t.cs() == "cite"
3674 || t.cs() == "nocite") {
3675 context.check_layout(os);
3676 string after = convert_command_inset_arg(p.getArg('[', ']'));
3677 string key = convert_command_inset_arg(p.verbatim_item());
3678 // store the case that it is "\nocite{*}" to use it later for
3681 begin_command_inset(os, "citation", t.cs());
3682 os << "after " << '"' << after << '"' << "\n";
3683 os << "key " << '"' << key << '"' << "\n";
3685 } else if (t.cs() == "nocite")
3689 else if (t.cs() == "index" ||
3690 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3691 context.check_layout(os);
3692 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3693 p.getArg('[', ']') : "";
3694 string const kind = arg.empty() ? "idx" : arg;
3695 begin_inset(os, "Index ");
3696 os << kind << "\nstatus collapsed\n";
3697 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3700 preamble.registerAutomaticallyLoadedPackage("splitidx");
3703 else if (t.cs() == "nomenclature") {
3704 context.check_layout(os);
3705 begin_command_inset(os, "nomenclature", "nomenclature");
3706 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3707 if (!prefix.empty())
3708 os << "prefix " << '"' << prefix << '"' << "\n";
3709 os << "symbol " << '"'
3710 << convert_command_inset_arg(p.verbatim_item());
3711 os << "\"\ndescription \""
3712 << convert_command_inset_arg(p.verbatim_item())
3715 preamble.registerAutomaticallyLoadedPackage("nomencl");
3718 else if (t.cs() == "label") {
3719 context.check_layout(os);
3720 begin_command_inset(os, "label", "label");
3722 << convert_command_inset_arg(p.verbatim_item())
3727 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3728 context.check_layout(os);
3729 string commandname = t.cs();
3731 if (p.next_token().asInput() == "*") {
3736 begin_command_inset(os, "index_print", commandname);
3737 string const indexname = p.getArg('[', ']');
3739 if (indexname.empty())
3740 os << "type \"idx\"\n";
3742 os << "type \"" << indexname << "\"\n";
3745 skip_spaces_braces(p);
3746 preamble.registerAutomaticallyLoadedPackage("makeidx");
3747 if (preamble.use_indices() == "true")
3748 preamble.registerAutomaticallyLoadedPackage("splitidx");
3751 else if (t.cs() == "printnomenclature") {
3753 string width_type = "";
3754 context.check_layout(os);
3755 begin_command_inset(os, "nomencl_print", "printnomenclature");
3756 // case of a custom width
3758 width = p.getArg('[', ']');
3759 width = translate_len(width);
3760 width_type = "custom";
3762 // case of no custom width
3763 // the case of no custom width but the width set
3764 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3765 // because the user could have set anything, not only the width
3766 // of the longest label (which would be width_type = "auto")
3767 string label = convert_command_inset_arg(p.getArg('{', '}'));
3768 if (label.empty() && width_type.empty())
3769 width_type = "none";
3770 os << "set_width \"" << width_type << "\"\n";
3771 if (width_type == "custom")
3772 os << "width \"" << width << '\"';
3774 skip_spaces_braces(p);
3775 preamble.registerAutomaticallyLoadedPackage("nomencl");
3778 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3779 context.check_layout(os);
3780 begin_inset(os, "script ");
3781 os << t.cs().substr(4) << '\n';
3782 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3783 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3785 if (t.cs() == "textsubscript")
3786 preamble.registerAutomaticallyLoadedPackage("subscript");
3789 else if ((where = is_known(t.cs(), known_quotes))) {
3790 context.check_layout(os);
3791 begin_inset(os, "Quotes ");
3792 os << known_coded_quotes[where - known_quotes];
3794 // LyX adds {} after the quote, so we have to eat
3795 // spaces here if there are any before a possible
3797 eat_whitespace(p, os, context, false);
3801 else if ((where = is_known(t.cs(), known_sizes)) &&
3802 context.new_layout_allowed) {
3803 context.check_layout(os);
3804 TeXFont const oldFont = context.font;
3805 context.font.size = known_coded_sizes[where - known_sizes];
3806 output_font_change(os, oldFont, context.font);
3807 eat_whitespace(p, os, context, false);
3810 else if ((where = is_known(t.cs(), known_font_families)) &&
3811 context.new_layout_allowed) {
3812 context.check_layout(os);
3813 TeXFont const oldFont = context.font;
3814 context.font.family =
3815 known_coded_font_families[where - known_font_families];
3816 output_font_change(os, oldFont, context.font);
3817 eat_whitespace(p, os, context, false);
3820 else if ((where = is_known(t.cs(), known_font_series)) &&
3821 context.new_layout_allowed) {
3822 context.check_layout(os);
3823 TeXFont const oldFont = context.font;
3824 context.font.series =
3825 known_coded_font_series[where - known_font_series];
3826 output_font_change(os, oldFont, context.font);
3827 eat_whitespace(p, os, context, false);
3830 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3831 context.new_layout_allowed) {
3832 context.check_layout(os);
3833 TeXFont const oldFont = context.font;
3834 context.font.shape =
3835 known_coded_font_shapes[where - known_font_shapes];
3836 output_font_change(os, oldFont, context.font);
3837 eat_whitespace(p, os, context, false);
3839 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3840 context.new_layout_allowed) {
3841 context.check_layout(os);
3842 TeXFont const oldFont = context.font;
3843 context.font.init();
3844 context.font.size = oldFont.size;
3845 context.font.family =
3846 known_coded_font_families[where - known_old_font_families];
3847 output_font_change(os, oldFont, context.font);
3848 eat_whitespace(p, os, context, false);
3851 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3852 context.new_layout_allowed) {
3853 context.check_layout(os);
3854 TeXFont const oldFont = context.font;
3855 context.font.init();
3856 context.font.size = oldFont.size;
3857 context.font.series =
3858 known_coded_font_series[where - known_old_font_series];
3859 output_font_change(os, oldFont, context.font);
3860 eat_whitespace(p, os, context, false);
3863 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3864 context.new_layout_allowed) {
3865 context.check_layout(os);
3866 TeXFont const oldFont = context.font;
3867 context.font.init();
3868 context.font.size = oldFont.size;
3869 context.font.shape =
3870 known_coded_font_shapes[where - known_old_font_shapes];
3871 output_font_change(os, oldFont, context.font);
3872 eat_whitespace(p, os, context, false);
3875 else if (t.cs() == "selectlanguage") {
3876 context.check_layout(os);
3877 // save the language for the case that a
3878 // \foreignlanguage is used
3879 context.font.language = babel2lyx(p.verbatim_item());
3880 os << "\n\\lang " << context.font.language << "\n";
3883 else if (t.cs() == "foreignlanguage") {
3884 string const lang = babel2lyx(p.verbatim_item());
3885 parse_text_attributes(p, os, FLAG_ITEM, outer,
3887 context.font.language, lang);
3890 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3891 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3892 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3894 // We have to output the whole command if it has an option
3895 // because LyX doesn't support this yet, see bug #8214,
3896 // only if there is a single option specifying a variant, we can handle it.
3898 string langopts = p.getOpt();
3899 // check if the option contains a variant, if yes, extract it
3900 string::size_type pos_var = langopts.find("variant");
3901 string::size_type i = langopts.find(',');
3902 string::size_type k = langopts.find('=', pos_var);
3903 if (pos_var != string::npos && i == string::npos) {
3905 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3906 lang = preamble.polyglossia2lyx(variant);
3907 parse_text_attributes(p, os, FLAG_ITEM, outer,
3909 context.font.language, lang);
3911 output_ert_inset(os, t.asInput() + langopts, context);
3913 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3914 parse_text_attributes(p, os, FLAG_ITEM, outer,
3916 context.font.language, lang);
3920 else if (t.cs() == "inputencoding") {
3921 // nothing to write here
3922 string const enc = subst(p.verbatim_item(), "\n", " ");
3923 p.setEncoding(enc, Encoding::inputenc);
3926 else if (is_known(t.cs(), known_special_chars) ||
3927 (t.cs() == "protect" &&
3928 p.next_token().cat() == catEscape &&
3929 is_known(p.next_token().cs(), known_special_protect_chars))) {
3930 // LyX sometimes puts a \protect in front, so we have to ignore it
3932 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3933 known_special_chars);
3934 context.check_layout(os);
3935 os << known_coded_special_chars[where - known_special_chars];
3936 skip_spaces_braces(p);
3939 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3940 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3941 p.next_next_token().asInput() == "-") ||
3942 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3943 // LyX sometimes puts a \protect in front, so we have to ignore it
3944 if (t.cs() == "protect")
3946 context.check_layout(os);
3947 if (t.cs() == "nobreakdash")
3948 os << "\\SpecialChar nobreakdash\n";
3950 os << "\\SpecialChar endofsentence\n";
3954 else if (t.cs() == "textquotedbl") {
3955 context.check_layout(os);
3960 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3961 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3962 || t.cs() == "%" || t.cs() == "-") {
3963 context.check_layout(os);
3965 os << "\\SpecialChar softhyphen\n";
3970 else if (t.cs() == "char") {
3971 context.check_layout(os);
3972 if (p.next_token().character() == '`') {
3974 if (p.next_token().cs() == "\"") {
3979 output_ert_inset(os, "\\char`", context);
3982 output_ert_inset(os, "\\char", context);
3986 else if (t.cs() == "verb") {
3987 context.check_layout(os);
3988 // set catcodes to verbatim early, just in case.
3989 p.setCatcodes(VERBATIM_CATCODES);
3990 string delim = p.get_token().asInput();
3991 Parser::Arg arg = p.verbatimStuff(delim);
3993 output_ert_inset(os, "\\verb" + delim
3994 + arg.second + delim, context);
3996 cerr << "invalid \\verb command. Skipping" << endl;
3999 // Problem: \= creates a tabstop inside the tabbing environment
4000 // and else an accent. In the latter case we really would want
4001 // \={o} instead of \= o.
4002 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4003 output_ert_inset(os, t.asInput(), context);
4005 else if (t.cs() == "\\") {
4006 context.check_layout(os);
4008 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4009 else if (p.next_token().asInput() == "*") {
4011 // getOpt() eats the following space if there
4012 // is no optional argument, but that is OK
4013 // here since it has no effect in the output.
4014 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4017 begin_inset(os, "Newline newline");
4022 else if (t.cs() == "newline" ||
4023 (t.cs() == "linebreak" && !p.hasOpt())) {
4024 context.check_layout(os);
4025 begin_inset(os, "Newline ");
4028 skip_spaces_braces(p);
4031 else if (t.cs() == "input" || t.cs() == "include"
4032 || t.cs() == "verbatiminput") {
4033 string name = t.cs();
4034 if (t.cs() == "verbatiminput"
4035 && p.next_token().asInput() == "*")
4036 name += p.get_token().asInput();
4037 context.check_layout(os);
4038 string filename(normalize_filename(p.getArg('{', '}')));
4039 string const path = getMasterFilePath(true);
4040 // We want to preserve relative / absolute filenames,
4041 // therefore path is only used for testing
4042 if ((t.cs() == "include" || t.cs() == "input") &&
4043 !makeAbsPath(filename, path).exists()) {
4044 // The file extension is probably missing.
4045 // Now try to find it out.
4046 string const tex_name =
4047 find_file(filename, path,
4048 known_tex_extensions);
4049 if (!tex_name.empty())
4050 filename = tex_name;
4052 bool external = false;
4054 if (makeAbsPath(filename, path).exists()) {
4055 string const abstexname =
4056 makeAbsPath(filename, path).absFileName();
4057 string const absfigname =
4058 changeExtension(abstexname, ".fig");
4059 fix_child_filename(filename);
4060 string const lyxname = changeExtension(filename,
4061 roundtripMode() ? ".lyx.lyx" : ".lyx");
4062 string const abslyxname = makeAbsPath(
4063 lyxname, getParentFilePath(false)).absFileName();
4065 if (!skipChildren())
4066 external = FileName(absfigname).exists();
4067 if (t.cs() == "input" && !skipChildren()) {
4068 string const ext = getExtension(abstexname);
4070 // Combined PS/LaTeX:
4071 // x.eps, x.pstex_t (old xfig)
4072 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4073 FileName const absepsname(
4074 changeExtension(abstexname, ".eps"));
4075 FileName const abspstexname(
4076 changeExtension(abstexname, ".pstex"));
4077 bool const xfigeps =
4078 (absepsname.exists() ||
4079 abspstexname.exists()) &&
4082 // Combined PDF/LaTeX:
4083 // x.pdf, x.pdftex_t (old xfig)
4084 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4085 FileName const abspdfname(
4086 changeExtension(abstexname, ".pdf"));
4087 bool const xfigpdf =
4088 abspdfname.exists() &&
4089 (ext == "pdftex_t" || ext == "pdf_t");
4093 // Combined PS/PDF/LaTeX:
4094 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4095 string const absbase2(
4096 removeExtension(abstexname) + "_pspdftex");
4097 FileName const abseps2name(
4098 addExtension(absbase2, ".eps"));
4099 FileName const abspdf2name(
4100 addExtension(absbase2, ".pdf"));
4101 bool const xfigboth =
4102 abspdf2name.exists() &&
4103 abseps2name.exists() && ext == "pspdftex";
4105 xfig = xfigpdf || xfigeps || xfigboth;
4106 external = external && xfig;
4109 outname = changeExtension(filename, ".fig");
4110 FileName abssrc(changeExtension(abstexname, ".fig"));
4111 copy_file(abssrc, outname);
4113 // Don't try to convert, the result
4114 // would be full of ERT.
4116 FileName abssrc(abstexname);
4117 copy_file(abssrc, outname);
4118 } else if (t.cs() != "verbatiminput" &&
4120 tex2lyx(abstexname, FileName(abslyxname),
4123 // no need to call copy_file
4124 // tex2lyx creates the file
4127 FileName abssrc(abstexname);
4128 copy_file(abssrc, outname);
4131 cerr << "Warning: Could not find included file '"
4132 << filename << "'." << endl;
4136 begin_inset(os, "External\n");
4137 os << "\ttemplate XFig\n"
4138 << "\tfilename " << outname << '\n';
4139 registerExternalTemplatePackages("XFig");
4141 begin_command_inset(os, "include", name);
4142 outname = subst(outname, "\"", "\\\"");
4143 os << "preview false\n"
4144 "filename \"" << outname << "\"\n";
4145 if (t.cs() == "verbatiminput")
4146 preamble.registerAutomaticallyLoadedPackage("verbatim");
4151 else if (t.cs() == "bibliographystyle") {
4152 // store new bibliographystyle
4153 bibliographystyle = p.verbatim_item();
4154 // If any other command than \bibliography, \addcontentsline
4155 // and \nocite{*} follows, we need to output the style
4156 // (because it might be used by that command).
4157 // Otherwise, it will automatically be output by LyX.
4160 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4161 if (t2.cat() == catBegin)
4163 if (t2.cat() != catEscape)
4165 if (t2.cs() == "nocite") {
4166 if (p.getArg('{', '}') == "*")
4168 } else if (t2.cs() == "bibliography")
4170 else if (t2.cs() == "phantomsection") {
4174 else if (t2.cs() == "addcontentsline") {
4175 // get the 3 arguments of \addcontentsline
4178 contentslineContent = p.getArg('{', '}');
4179 // if the last argument is not \refname we must output
4180 if (contentslineContent == "\\refname")
4187 output_ert_inset(os,
4188 "\\bibliographystyle{" + bibliographystyle + '}',
4193 else if (t.cs() == "phantomsection") {
4194 // we only support this if it occurs between
4195 // \bibliographystyle and \bibliography
4196 if (bibliographystyle.empty())
4197 output_ert_inset(os, "\\phantomsection", context);
4200 else if (t.cs() == "addcontentsline") {
4201 context.check_layout(os);
4202 // get the 3 arguments of \addcontentsline
4203 string const one = p.getArg('{', '}');
4204 string const two = p.getArg('{', '}');
4205 string const three = p.getArg('{', '}');
4206 // only if it is a \refname, we support if for the bibtex inset
4207 if (contentslineContent != "\\refname") {
4208 output_ert_inset(os,
4209 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4214 else if (t.cs() == "bibliography") {
4215 context.check_layout(os);
4217 begin_command_inset(os, "bibtex", "bibtex");
4218 if (!btprint.empty()) {
4219 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4220 // clear the string because the next BibTeX inset can be without the
4221 // \nocite{*} option
4224 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4225 // Do we have addcontentsline?
4226 if (contentslineContent == "\\refname") {
4227 BibOpts = "bibtotoc";
4228 // clear string because next BibTeX inset can be without addcontentsline
4229 contentslineContent.clear();
4231 // Do we have a bibliographystyle set?
4232 if (!bibliographystyle.empty()) {
4233 if (BibOpts.empty())
4234 BibOpts = bibliographystyle;
4236 BibOpts = BibOpts + ',' + bibliographystyle;
4237 // clear it because each bibtex entry has its style
4238 // and we need an empty string to handle \phantomsection
4239 bibliographystyle.clear();
4241 os << "options " << '"' << BibOpts << '"' << "\n";
4245 else if (t.cs() == "parbox") {
4246 // Test whether this is an outer box of a shaded box
4248 // swallow arguments
4249 while (p.hasOpt()) {
4251 p.skip_spaces(true);
4254 p.skip_spaces(true);
4256 if (p.next_token().cat() == catBegin)
4258 p.skip_spaces(true);
4259 Token to = p.get_token();
4260 bool shaded = false;
4261 if (to.asInput() == "\\begin") {
4262 p.skip_spaces(true);
4263 if (p.getArg('{', '}') == "shaded")
4268 parse_outer_box(p, os, FLAG_ITEM, outer,
4269 context, "parbox", "shaded");
4271 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4272 "", "", t.cs(), "", "");
4275 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4276 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4277 t.cs() == "shadowbox" || t.cs() == "doublebox")
4278 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4280 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4281 string backgroundcolor;
4282 preamble.registerAutomaticallyLoadedPackage("xcolor");
4283 if (t.cs() == "fcolorbox") {
4284 string const framecolor = p.getArg('{', '}');
4285 backgroundcolor = p.getArg('{', '}');
4286 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4288 backgroundcolor = p.getArg('{', '}');
4289 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4293 // FIXME: due to the compiler limit of "if" nestings
4294 // the code for the alignment was put here
4295 // put them in their own if if this is fixed
4296 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4297 || t.cs() == "shadowsize"
4298 || t.cs() == "raggedleft" || t.cs() == "centering"
4299 || t.cs() == "raggedright") {
4300 p.skip_spaces(true);
4301 if (t.cs() == "fboxrule")
4303 if (t.cs() == "fboxsep")
4305 if (t.cs() == "shadowsize")
4307 if (t.cs() != "raggedleft" && t.cs() != "centering"
4308 && t.cs() != "raggedright") {
4309 while (p.good() && p.next_token().cat() != catSpace
4310 && p.next_token().cat() != catNewline
4311 && p.next_token().cat() != catEscape) {
4312 if (t.cs() == "fboxrule")
4313 fboxrule = fboxrule + p.get_token().asInput();
4314 if (t.cs() == "fboxsep")
4315 fboxsep = fboxsep + p.get_token().asInput();
4316 if (t.cs() == "shadowsize")
4317 shadow_size = shadow_size + p.get_token().asInput();
4320 // we only handle them if they are in a box
4322 output_ert_inset(os, '\\' + t.cs() + ' ', context);
4324 wasBoxAlign = false;
4327 //\framebox() is part of the picture environment and different from \framebox{}
4328 //\framebox{} will be parsed by parse_outer_box
4329 else if (t.cs() == "framebox") {
4330 if (p.next_token().character() == '(') {
4331 //the syntax is: \framebox(x,y)[position]{content}
4332 string arg = t.asInput();
4333 arg += p.getFullParentheseArg();
4334 arg += p.getFullOpt();
4335 eat_whitespace(p, os, context, false);
4336 output_ert_inset(os, arg + '{', context);
4337 parse_text(p, os, FLAG_ITEM, outer, context);
4338 output_ert_inset(os, "}", context);
4340 //the syntax is: \framebox[width][position]{content}
4341 string special = p.getFullOpt();
4342 special += p.getOpt();
4343 parse_outer_box(p, os, FLAG_ITEM, outer,
4344 context, t.cs(), special);
4348 //\makebox() is part of the picture environment and different from \makebox{}
4349 //\makebox{} will be parsed by parse_box
4350 else if (t.cs() == "makebox") {
4351 if (p.next_token().character() == '(') {
4352 //the syntax is: \makebox(x,y)[position]{content}
4353 string arg = t.asInput();
4354 arg += p.getFullParentheseArg();
4355 arg += p.getFullOpt();
4356 eat_whitespace(p, os, context, false);
4357 output_ert_inset(os, arg + '{', context);
4358 parse_text(p, os, FLAG_ITEM, outer, context);
4359 output_ert_inset(os, "}", context);
4361 //the syntax is: \makebox[width][position]{content}
4362 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4363 "", "", t.cs(), "", "");
4366 else if (t.cs() == "smallskip" ||
4367 t.cs() == "medskip" ||
4368 t.cs() == "bigskip" ||
4369 t.cs() == "vfill") {
4370 context.check_layout(os);
4371 begin_inset(os, "VSpace ");
4374 skip_spaces_braces(p);
4377 else if ((where = is_known(t.cs(), known_spaces))) {
4378 context.check_layout(os);
4379 begin_inset(os, "space ");
4380 os << '\\' << known_coded_spaces[where - known_spaces]
4383 // LaTeX swallows whitespace after all spaces except
4384 // "\\,". We have to do that here, too, because LyX
4385 // adds "{}" which would make the spaces significant.
4387 eat_whitespace(p, os, context, false);
4388 // LyX adds "{}" after all spaces except "\\ " and
4389 // "\\,", so we have to remove "{}".
4390 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4391 // remove the braces after "\\,", too.
4396 else if (t.cs() == "newpage" ||
4397 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4398 t.cs() == "clearpage" ||
4399 t.cs() == "cleardoublepage") {
4400 context.check_layout(os);
4401 begin_inset(os, "Newpage ");
4404 skip_spaces_braces(p);
4407 else if (t.cs() == "DeclareRobustCommand" ||
4408 t.cs() == "DeclareRobustCommandx" ||
4409 t.cs() == "newcommand" ||
4410 t.cs() == "newcommandx" ||
4411 t.cs() == "providecommand" ||
4412 t.cs() == "providecommandx" ||
4413 t.cs() == "renewcommand" ||
4414 t.cs() == "renewcommandx") {
4415 // DeclareRobustCommand, DeclareRobustCommandx,
4416 // providecommand and providecommandx could be handled
4417 // by parse_command(), but we need to call
4418 // add_known_command() here.
4419 string name = t.asInput();
4420 if (p.next_token().asInput() == "*") {
4421 // Starred form. Eat '*'
4425 string const command = p.verbatim_item();
4426 string const opt1 = p.getFullOpt();
4427 string const opt2 = p.getFullOpt();
4428 add_known_command(command, opt1, !opt2.empty());
4429 string const ert = name + '{' + command + '}' +
4431 '{' + p.verbatim_item() + '}';
4433 if (t.cs() == "DeclareRobustCommand" ||
4434 t.cs() == "DeclareRobustCommandx" ||
4435 t.cs() == "providecommand" ||
4436 t.cs() == "providecommandx" ||
4437 name[name.length()-1] == '*')
4438 output_ert_inset(os, ert, context);
4440 context.check_layout(os);
4441 begin_inset(os, "FormulaMacro");
4447 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4448 // let could be handled by parse_command(),
4449 // but we need to call add_known_command() here.
4450 string ert = t.asInput();
4453 if (p.next_token().cat() == catBegin) {
4454 name = p.verbatim_item();
4455 ert += '{' + name + '}';
4457 name = p.verbatim_item();
4462 if (p.next_token().cat() == catBegin) {
4463 command = p.verbatim_item();
4464 ert += '{' + command + '}';
4466 command = p.verbatim_item();
4469 // If command is known, make name known too, to parse
4470 // its arguments correctly. For this reason we also
4471 // have commands in syntax.default that are hardcoded.
4472 CommandMap::iterator it = known_commands.find(command);
4473 if (it != known_commands.end())
4474 known_commands[t.asInput()] = it->second;
4475 output_ert_inset(os, ert, context);
4478 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4481 string name = t.asInput();
4482 string const length = p.verbatim_item();
4485 bool valid = splitLatexLength(length, valstring, unit);
4486 bool known_hspace = false;
4487 bool known_vspace = false;
4488 bool known_unit = false;
4491 istringstream iss(valstring);
4494 if (t.cs()[0] == 'h') {
4495 if (unit == "\\fill") {
4500 known_hspace = true;
4503 if (unit == "\\smallskipamount") {
4505 known_vspace = true;
4506 } else if (unit == "\\medskipamount") {
4508 known_vspace = true;
4509 } else if (unit == "\\bigskipamount") {
4511 known_vspace = true;
4512 } else if (unit == "\\fill") {
4514 known_vspace = true;
4518 if (!known_hspace && !known_vspace) {
4519 switch (unitFromString(unit)) {
4535 //unitFromString(unit) fails for relative units like Length::PCW
4536 // therefore handle them separately
4537 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4538 || unit == "\\textwidth" || unit == "\\linewidth"
4539 || unit == "\\textheight" || unit == "\\paperheight")
4547 // check for glue lengths
4548 bool is_gluelength = false;
4549 string gluelength = length;
4550 string::size_type i = length.find(" minus");
4551 if (i == string::npos) {
4552 i = length.find(" plus");
4553 if (i != string::npos)
4554 is_gluelength = true;
4556 is_gluelength = true;
4557 // if yes transform "9xx minus 8yy plus 7zz"
4559 if (is_gluelength) {
4560 i = gluelength.find(" minus");
4561 if (i != string::npos)
4562 gluelength.replace(i, 7, "-");
4563 i = gluelength.find(" plus");
4564 if (i != string::npos)
4565 gluelength.replace(i, 6, "+");
4568 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4569 // Literal horizontal length or known variable
4570 context.check_layout(os);
4571 begin_inset(os, "space ");
4579 if (known_unit && !known_hspace)
4580 os << "\n\\length " << translate_len(length);
4582 os << "\n\\length " << gluelength;
4584 } else if (known_unit || known_vspace || is_gluelength) {
4585 // Literal vertical length or known variable
4586 context.check_layout(os);
4587 begin_inset(os, "VSpace ");
4590 if (known_unit && !known_vspace)
4591 os << translate_len(length);
4598 // LyX can't handle other length variables in Inset VSpace/space
4603 output_ert_inset(os, name + '{' + unit + '}', context);
4604 else if (value == -1.0)
4605 output_ert_inset(os, name + "{-" + unit + '}', context);
4607 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4609 output_ert_inset(os, name + '{' + length + '}', context);
4613 // The single '=' is meant here.
4614 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4618 context.check_layout(os);
4619 docstring const name = newinsetlayout->name();
4620 bool const caption = name.find(from_ascii("Caption:")) == 0;
4622 begin_inset(os, "Caption ");
4623 os << to_utf8(name.substr(8)) << '\n';
4625 begin_inset(os, "Flex ");
4626 os << to_utf8(name) << '\n'
4627 << "status collapsed\n";
4629 if (newinsetlayout->isPassThru()) {
4630 // set catcodes to verbatim early, just in case.
4631 p.setCatcodes(VERBATIM_CATCODES);
4632 string delim = p.get_token().asInput();
4634 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4635 //FIXME: handle error condition
4636 string const arg = p.verbatimStuff("}").second;
4637 Context newcontext(true, context.textclass);
4638 if (newinsetlayout->forcePlainLayout())
4639 newcontext.layout = &context.textclass.plainLayout();
4640 output_ert(os, arg, newcontext);
4642 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4648 else if (t.cs() == "includepdf") {
4650 string const arg = p.getArg('[', ']');
4651 map<string, string> opts;
4652 vector<string> keys;
4653 split_map(arg, opts, keys);
4654 string name = normalize_filename(p.verbatim_item());
4655 string const path = getMasterFilePath(true);
4656 // We want to preserve relative / absolute filenames,
4657 // therefore path is only used for testing
4658 if (!makeAbsPath(name, path).exists()) {
4659 // The file extension is probably missing.
4660 // Now try to find it out.
4661 char const * const pdfpages_format[] = {"pdf", 0};
4662 string const pdftex_name =
4663 find_file(name, path, pdfpages_format);
4664 if (!pdftex_name.empty()) {
4669 FileName const absname = makeAbsPath(name, path);
4670 if (absname.exists())
4672 fix_child_filename(name);
4673 copy_file(absname, name);
4675 cerr << "Warning: Could not find file '"
4676 << name << "'." << endl;
4678 context.check_layout(os);
4679 begin_inset(os, "External\n\ttemplate ");
4680 os << "PDFPages\n\tfilename "
4682 // parse the options
4683 if (opts.find("pages") != opts.end())
4684 os << "\textra LaTeX \"pages="
4685 << opts["pages"] << "\"\n";
4686 if (opts.find("angle") != opts.end())
4687 os << "\trotateAngle "
4688 << opts["angle"] << '\n';
4689 if (opts.find("origin") != opts.end()) {
4691 string const opt = opts["origin"];
4692 if (opt == "tl") ss << "topleft";
4693 if (opt == "bl") ss << "bottomleft";
4694 if (opt == "Bl") ss << "baselineleft";
4695 if (opt == "c") ss << "center";
4696 if (opt == "tc") ss << "topcenter";
4697 if (opt == "bc") ss << "bottomcenter";
4698 if (opt == "Bc") ss << "baselinecenter";
4699 if (opt == "tr") ss << "topright";
4700 if (opt == "br") ss << "bottomright";
4701 if (opt == "Br") ss << "baselineright";
4702 if (!ss.str().empty())
4703 os << "\trotateOrigin " << ss.str() << '\n';
4705 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4707 if (opts.find("width") != opts.end())
4709 << translate_len(opts["width"]) << '\n';
4710 if (opts.find("height") != opts.end())
4712 << translate_len(opts["height"]) << '\n';
4713 if (opts.find("keepaspectratio") != opts.end())
4714 os << "\tkeepAspectRatio\n";
4716 context.check_layout(os);
4717 registerExternalTemplatePackages("PDFPages");
4720 else if (t.cs() == "loadgame") {
4722 string name = normalize_filename(p.verbatim_item());
4723 string const path = getMasterFilePath(true);
4724 // We want to preserve relative / absolute filenames,
4725 // therefore path is only used for testing
4726 if (!makeAbsPath(name, path).exists()) {
4727 // The file extension is probably missing.
4728 // Now try to find it out.
4729 char const * const lyxskak_format[] = {"fen", 0};
4730 string const lyxskak_name =
4731 find_file(name, path, lyxskak_format);
4732 if (!lyxskak_name.empty())
4733 name = lyxskak_name;
4735 FileName const absname = makeAbsPath(name, path);
4736 if (absname.exists())
4738 fix_child_filename(name);
4739 copy_file(absname, name);
4741 cerr << "Warning: Could not find file '"
4742 << name << "'." << endl;
4743 context.check_layout(os);
4744 begin_inset(os, "External\n\ttemplate ");
4745 os << "ChessDiagram\n\tfilename "
4748 context.check_layout(os);
4749 // after a \loadgame follows a \showboard
4750 if (p.get_token().asInput() == "showboard")
4752 registerExternalTemplatePackages("ChessDiagram");
4756 // try to see whether the string is in unicodesymbols
4757 // Only use text mode commands, since we are in text mode here,
4758 // and math commands may be invalid (bug 6797)
4759 string name = t.asInput();
4760 // handle the dingbats, cyrillic and greek
4761 if (name == "\\ding" || name == "\\textcyr" ||
4762 (name == "\\textgreek" && !preamble.usePolyglossia()))
4763 name = name + '{' + p.getArg('{', '}') + '}';
4764 // handle the ifsym characters
4765 else if (name == "\\textifsymbol") {
4766 string const optif = p.getFullOpt();
4767 string const argif = p.getArg('{', '}');
4768 name = name + optif + '{' + argif + '}';
4770 // handle the \ascii characters
4771 // the case of \ascii within braces, as LyX outputs it, is already
4772 // handled for t.cat() == catBegin
4773 else if (name == "\\ascii") {
4774 // the code is "\asci\xxx"
4775 name = "{" + name + p.get_token().asInput() + "}";
4778 // handle some TIPA special characters
4779 else if (preamble.isPackageUsed("tipa")) {
4780 if (name == "\\textglobfall") {
4783 } else if (name == "\\s") {
4784 // fromLaTeXCommand() does not yet
4785 // recognize tipa short cuts
4786 name = "\\textsyllabic";
4787 } else if (name == "\\=" &&
4788 p.next_token().asInput() == "*") {
4789 // fromLaTeXCommand() does not yet
4790 // recognize tipa short cuts
4793 } else if (name == "\\textdoublevertline") {
4794 // FIXME: This is not correct,
4795 // \textvertline is higher than \textbardbl
4796 name = "\\textbardbl";
4798 } else if (name == "\\!" ) {
4799 if (p.next_token().asInput() == "b") {
4800 p.get_token(); // eat 'b'
4803 } else if (p.next_token().asInput() == "d") {
4807 } else if (p.next_token().asInput() == "g") {
4811 } else if (p.next_token().asInput() == "G") {
4813 name = "\\texthtscg";
4815 } else if (p.next_token().asInput() == "j") {
4817 name = "\\texthtbardotlessj";
4819 } else if (p.next_token().asInput() == "o") {
4821 name = "\\textbullseye";
4824 } else if (name == "\\*" ) {
4825 if (p.next_token().asInput() == "k") {
4827 name = "\\textturnk";
4829 } else if (p.next_token().asInput() == "r") {
4830 p.get_token(); // eat 'b'
4831 name = "\\textturnr";
4833 } else if (p.next_token().asInput() == "t") {
4835 name = "\\textturnt";
4837 } else if (p.next_token().asInput() == "w") {
4839 name = "\\textturnw";
4844 if ((name.size() == 2 &&
4845 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4846 p.next_token().asInput() != "*") ||
4847 is_known(name.substr(1), known_tipa_marks)) {
4848 // name is a command that corresponds to a
4849 // combining character in unicodesymbols.
4850 // Append the argument, fromLaTeXCommand()
4851 // will either convert it to a single
4852 // character or a combining sequence.
4853 name += '{' + p.verbatim_item() + '}';
4855 // now get the character from unicodesymbols
4859 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4860 Encodings::TEXT_CMD, termination, rem, &req);
4862 context.check_layout(os);
4865 output_ert_inset(os, to_utf8(rem), context);
4867 skip_spaces_braces(p);
4868 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4869 preamble.registerAutomaticallyLoadedPackage(*it);
4871 //cerr << "#: " << t << " mode: " << mode << endl;
4872 // heuristic: read up to next non-nested space
4874 string s = t.asInput();
4875 string z = p.verbatim_item();
4876 while (p.good() && z != " " && !z.empty()) {
4877 //cerr << "read: " << z << endl;
4879 z = p.verbatim_item();
4881 cerr << "found ERT: " << s << endl;
4882 output_ert_inset(os, s + ' ', context);
4885 if (t.asInput() == name &&
4886 p.next_token().asInput() == "*") {
4887 // Starred commands like \vspace*{}
4888 p.get_token(); // Eat '*'
4891 if (!parse_command(name, p, os, outer, context))
4892 output_ert_inset(os, name, context);
4896 if (flags & FLAG_LEAVE) {
4897 flags &= ~FLAG_LEAVE;
4904 string guessLanguage(Parser & p, string const & lang)
4906 typedef std::map<std::string, size_t> LangMap;
4907 // map from language names to number of characters
4910 for (char const * const * i = supported_CJK_languages; *i; i++)
4911 used[string(*i)] = 0;
4914 Token const t = p.get_token();
4915 // comments are not counted for any language
4916 if (t.cat() == catComment)
4918 // commands are not counted as well, but we need to detect
4919 // \begin{CJK} and switch encoding if needed
4920 if (t.cat() == catEscape) {
4921 if (t.cs() == "inputencoding") {
4922 string const enc = subst(p.verbatim_item(), "\n", " ");
4923 p.setEncoding(enc, Encoding::inputenc);
4926 if (t.cs() != "begin")
4929 // Non-CJK content is counted for lang.
4930 // We do not care about the real language here:
4931 // If we have more non-CJK contents than CJK contents,
4932 // we simply use the language that was specified as
4933 // babel main language.
4934 used[lang] += t.asInput().length();
4937 // Now we are starting an environment
4939 string const name = p.getArg('{', '}');
4940 if (name != "CJK") {
4944 // It is a CJK environment
4946 /* name = */ p.getArg('{', '}');
4947 string const encoding = p.getArg('{', '}');
4948 /* mapping = */ p.getArg('{', '}');
4949 string const encoding_old = p.getEncoding();
4950 char const * const * const where =
4951 is_known(encoding, supported_CJK_encodings);
4953 p.setEncoding(encoding, Encoding::CJK);
4955 p.setEncoding("UTF-8");
4956 string const text = p.ertEnvironment("CJK");
4957 p.setEncoding(encoding_old);
4960 // ignore contents in unknown CJK encoding
4963 // the language of the text
4965 supported_CJK_languages[where - supported_CJK_encodings];
4966 used[cjk] += text.length();
4968 LangMap::const_iterator use = used.begin();
4969 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4970 if (it->second > use->second)