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";
857 thickness = fboxrule;
862 separation = fboxsep;
866 if (shadow_size != "")
867 shadowsize = shadow_size;
870 string framecolor = "black";
871 string backgroundcolor = "none";
872 if (frame_color != "")
873 framecolor = frame_color;
874 if (background_color != "")
875 backgroundcolor = background_color;
876 // if there is a color box around the \begin statements have not yet been parsed
878 if (frame_color != "" || background_color != "") {
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 == "") {
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 != "")
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 != "")
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 != "")
1165 os << "use_makebox 0\n";
1167 os << "use_makebox " << (inner_type == "makebox") << '\n';
1168 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type == ""))
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 != "" || background_color != "")) {
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 && (fboxrule != "" || fboxsep != "" || shadow_size != "")) {
1257 // in this case we assume that the closing brace is from the box settings
1258 // therefore reset these values for the next box
1264 // all boxes except of Frameless and Shaded require calc
1265 if (!(outer_type.empty() || outer_type == "mbox") &&
1266 !((outer_type == "shaded" && inner_type.empty()) ||
1267 (outer_type == "minipage" && inner_type == "shaded") ||
1268 (outer_type == "parbox" && inner_type == "shaded")))
1269 preamble.registerAutomaticallyLoadedPackage("calc");
1273 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1274 Context & parent_context, string const & outer_type,
1275 string const & special)
1277 eat_whitespace(p, os, parent_context, false);
1278 if (flags & FLAG_ITEM) {
1280 if (p.next_token().cat() == catBegin)
1283 cerr << "Warning: Ignoring missing '{' after \\"
1284 << outer_type << '.' << endl;
1285 eat_whitespace(p, os, parent_context, false);
1288 unsigned int inner_flags = 0;
1290 if (outer_type == "minipage" || outer_type == "parbox") {
1291 p.skip_spaces(true);
1292 while (p.hasOpt()) {
1294 p.skip_spaces(true);
1297 p.skip_spaces(true);
1298 if (outer_type == "parbox") {
1300 if (p.next_token().cat() == catBegin)
1302 p.skip_spaces(true);
1305 if (outer_type == "shaded" || outer_type == "mbox") {
1306 // These boxes never have an inner box
1308 } else if (p.next_token().asInput() == "\\parbox") {
1309 inner = p.get_token().cs();
1310 inner_flags = FLAG_ITEM;
1311 } else if (p.next_token().asInput() == "\\begin") {
1312 // Is this a minipage or shaded box?
1315 inner = p.getArg('{', '}');
1317 if (inner == "minipage" || inner == "shaded")
1318 inner_flags = FLAG_END;
1323 if (inner_flags == FLAG_END) {
1324 if (inner != "shaded")
1328 eat_whitespace(p, os, parent_context, false);
1330 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1331 outer_type, special, inner, "", "");
1333 if (inner_flags == FLAG_ITEM) {
1335 eat_whitespace(p, os, parent_context, false);
1337 parse_box(p, os, flags, inner_flags, outer, parent_context,
1338 outer_type, special, inner, "", "");
1343 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1345 parent_context.check_layout(os);
1346 begin_inset(os, "listings\n");
1348 string arg = p.verbatimOption();
1349 os << "lstparams " << '"' << arg << '"' << '\n';
1350 if (arg.find("\\color") != string::npos)
1351 preamble.registerAutomaticallyLoadedPackage("color");
1354 os << "inline true\n";
1356 os << "inline false\n";
1357 os << "status collapsed\n";
1358 Context context(true, parent_context.textclass);
1359 context.layout = &parent_context.textclass.plainLayout();
1362 // set catcodes to verbatim early, just in case.
1363 p.setCatcodes(VERBATIM_CATCODES);
1364 string delim = p.get_token().asInput();
1365 //FIXME: handler error condition
1366 s = p.verbatimStuff(delim).second;
1367 // context.new_paragraph(os);
1369 s = p.verbatimEnvironment("lstlisting");
1370 output_ert(os, s, context);
1375 /// parse an unknown environment
1376 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1377 unsigned flags, bool outer,
1378 Context & parent_context)
1380 if (name == "tabbing")
1381 // We need to remember that we have to handle '\=' specially
1382 flags |= FLAG_TABBING;
1384 // We need to translate font changes and paragraphs inside the
1385 // environment to ERT if we have a non standard font.
1386 // Otherwise things like
1387 // \large\begin{foo}\huge bar\end{foo}
1389 bool const specialfont =
1390 (parent_context.font != parent_context.normalfont);
1391 bool const new_layout_allowed = parent_context.new_layout_allowed;
1393 parent_context.new_layout_allowed = false;
1394 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1395 parse_text_snippet(p, os, flags, outer, parent_context);
1396 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1398 parent_context.new_layout_allowed = new_layout_allowed;
1402 void parse_environment(Parser & p, ostream & os, bool outer,
1403 string & last_env, Context & parent_context)
1405 Layout const * newlayout;
1406 InsetLayout const * newinsetlayout = 0;
1407 string const name = p.getArg('{', '}');
1408 const bool is_starred = suffixIs(name, '*');
1409 string const unstarred_name = rtrim(name, "*");
1410 active_environments.push_back(name);
1412 if (is_math_env(name)) {
1413 parent_context.check_layout(os);
1414 begin_inset(os, "Formula ");
1415 os << "\\begin{" << name << "}";
1416 parse_math(p, os, FLAG_END, MATH_MODE);
1417 os << "\\end{" << name << "}";
1419 if (is_display_math_env(name)) {
1420 // Prevent the conversion of a line break to a space
1421 // (bug 7668). This does not change the output, but
1422 // looks ugly in LyX.
1423 eat_whitespace(p, os, parent_context, false);
1427 else if (is_known(name, preamble.polyglossia_languages)) {
1428 // We must begin a new paragraph if not already done
1429 if (! parent_context.atParagraphStart()) {
1430 parent_context.check_end_layout(os);
1431 parent_context.new_paragraph(os);
1433 // save the language in the context so that it is
1434 // handled by parse_text
1435 parent_context.font.language = preamble.polyglossia2lyx(name);
1436 parse_text(p, os, FLAG_END, outer, parent_context);
1437 // Just in case the environment is empty
1438 parent_context.extra_stuff.erase();
1439 // We must begin a new paragraph to reset the language
1440 parent_context.new_paragraph(os);
1444 else if (unstarred_name == "tabular" || name == "longtable") {
1445 eat_whitespace(p, os, parent_context, false);
1446 string width = "0pt";
1447 if (name == "tabular*") {
1448 width = lyx::translate_len(p.getArg('{', '}'));
1449 eat_whitespace(p, os, parent_context, false);
1451 parent_context.check_layout(os);
1452 begin_inset(os, "Tabular ");
1453 handle_tabular(p, os, name, width, parent_context);
1458 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1459 eat_whitespace(p, os, parent_context, false);
1460 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1461 eat_whitespace(p, os, parent_context, false);
1462 parent_context.check_layout(os);
1463 begin_inset(os, "Float " + unstarred_name + "\n");
1464 // store the float type for subfloats
1465 // subfloats only work with figures and tables
1466 if (unstarred_name == "figure")
1467 float_type = unstarred_name;
1468 else if (unstarred_name == "table")
1469 float_type = unstarred_name;
1473 os << "placement " << opt << '\n';
1474 if (contains(opt, "H"))
1475 preamble.registerAutomaticallyLoadedPackage("float");
1477 Floating const & fl = parent_context.textclass.floats()
1478 .getType(unstarred_name);
1479 if (!fl.floattype().empty() && fl.usesFloatPkg())
1480 preamble.registerAutomaticallyLoadedPackage("float");
1483 os << "wide " << convert<string>(is_starred)
1484 << "\nsideways false"
1485 << "\nstatus open\n\n";
1486 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1488 // We don't need really a new paragraph, but
1489 // we must make sure that the next item gets a \begin_layout.
1490 parent_context.new_paragraph(os);
1492 // the float is parsed thus delete the type
1496 else if (unstarred_name == "sidewaysfigure"
1497 || unstarred_name == "sidewaystable") {
1498 eat_whitespace(p, os, parent_context, false);
1499 parent_context.check_layout(os);
1500 if (unstarred_name == "sidewaysfigure")
1501 begin_inset(os, "Float figure\n");
1503 begin_inset(os, "Float table\n");
1504 os << "wide " << convert<string>(is_starred)
1505 << "\nsideways true"
1506 << "\nstatus open\n\n";
1507 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1509 // We don't need really a new paragraph, but
1510 // we must make sure that the next item gets a \begin_layout.
1511 parent_context.new_paragraph(os);
1513 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1516 else if (name == "wrapfigure" || name == "wraptable") {
1517 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1518 eat_whitespace(p, os, parent_context, false);
1519 parent_context.check_layout(os);
1522 string overhang = "0col%";
1525 lines = p.getArg('[', ']');
1526 string const placement = p.getArg('{', '}');
1528 overhang = p.getArg('[', ']');
1529 string const width = p.getArg('{', '}');
1531 if (name == "wrapfigure")
1532 begin_inset(os, "Wrap figure\n");
1534 begin_inset(os, "Wrap table\n");
1535 os << "lines " << lines
1536 << "\nplacement " << placement
1537 << "\noverhang " << lyx::translate_len(overhang)
1538 << "\nwidth " << lyx::translate_len(width)
1539 << "\nstatus open\n\n";
1540 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1542 // We don't need really a new paragraph, but
1543 // we must make sure that the next item gets a \begin_layout.
1544 parent_context.new_paragraph(os);
1546 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1549 else if (name == "minipage") {
1550 eat_whitespace(p, os, parent_context, false);
1551 // Test whether this is an outer box of a shaded box
1553 // swallow arguments
1554 while (p.hasOpt()) {
1556 p.skip_spaces(true);
1559 p.skip_spaces(true);
1560 Token t = p.get_token();
1561 bool shaded = false;
1562 if (t.asInput() == "\\begin") {
1563 p.skip_spaces(true);
1564 if (p.getArg('{', '}') == "shaded")
1569 parse_outer_box(p, os, FLAG_END, outer,
1570 parent_context, name, "shaded");
1572 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1573 "", "", name, "", "");
1577 else if (name == "comment") {
1578 eat_whitespace(p, os, parent_context, false);
1579 parent_context.check_layout(os);
1580 begin_inset(os, "Note Comment\n");
1581 os << "status open\n";
1582 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1585 skip_braces(p); // eat {} that might by set by LyX behind comments
1586 preamble.registerAutomaticallyLoadedPackage("verbatim");
1589 else if (name == "verbatim") {
1590 // FIXME: this should go in the generic code that
1591 // handles environments defined in layout file that
1592 // have "PassThru 1". However, the code over there is
1593 // already too complicated for my taste.
1594 parent_context.new_paragraph(os);
1595 Context context(true, parent_context.textclass,
1596 &parent_context.textclass[from_ascii("Verbatim")]);
1597 string s = p.verbatimEnvironment("verbatim");
1598 output_ert(os, s, context);
1602 else if (name == "IPA") {
1603 eat_whitespace(p, os, parent_context, false);
1604 parent_context.check_layout(os);
1605 begin_inset(os, "IPA\n");
1606 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1609 preamble.registerAutomaticallyLoadedPackage("tipa");
1610 preamble.registerAutomaticallyLoadedPackage("tipx");
1613 else if (name == "CJK") {
1614 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1615 // It is impossible to decide if a CJK environment was in its own paragraph or within
1616 // a line. We therefore always assume a paragraph since the latter is a rare case.
1617 eat_whitespace(p, os, parent_context, false);
1618 parent_context.check_end_layout(os);
1619 // store the encoding to be able to reset it
1620 string const encoding_old = p.getEncoding();
1621 string const encoding = p.getArg('{', '}');
1622 // FIXME: For some reason JIS does not work. Although the text
1623 // in tests/CJK.tex is identical with the SJIS version if you
1624 // convert both snippets using the recode command line utility,
1625 // the resulting .lyx file contains some extra characters if
1626 // you set buggy_encoding to false for JIS.
1627 bool const buggy_encoding = encoding == "JIS";
1628 if (!buggy_encoding)
1629 p.setEncoding(encoding, Encoding::CJK);
1631 // FIXME: This will read garbage, since the data is not encoded in utf8.
1632 p.setEncoding("UTF-8");
1634 // LyX only supports the same mapping for all CJK
1635 // environments, so we might need to output everything as ERT
1636 string const mapping = trim(p.getArg('{', '}'));
1637 char const * const * const where =
1638 is_known(encoding, supported_CJK_encodings);
1639 if (!buggy_encoding && !preamble.fontCJKSet())
1640 preamble.fontCJK(mapping);
1641 bool knownMapping = mapping == preamble.fontCJK();
1642 if (buggy_encoding || !knownMapping || !where) {
1643 parent_context.check_layout(os);
1644 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1646 // we must parse the content as verbatim because e.g. JIS can contain
1647 // normally invalid characters
1648 // FIXME: This works only for the most simple cases.
1649 // Since TeX control characters are not parsed,
1650 // things like comments are completely wrong.
1651 string const s = p.plainEnvironment("CJK");
1652 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1654 output_ert_inset(os, "\\", parent_context);
1655 else if (*it == '$')
1656 output_ert_inset(os, "$", parent_context);
1657 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1662 output_ert_inset(os, "\\end{" + name + "}",
1666 supported_CJK_languages[where - supported_CJK_encodings];
1667 // store the language because we must reset it at the end
1668 string const lang_old = parent_context.font.language;
1669 parent_context.font.language = lang;
1670 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1671 parent_context.font.language = lang_old;
1672 parent_context.new_paragraph(os);
1674 p.setEncoding(encoding_old);
1678 else if (name == "lyxgreyedout") {
1679 eat_whitespace(p, os, parent_context, false);
1680 parent_context.check_layout(os);
1681 begin_inset(os, "Note Greyedout\n");
1682 os << "status open\n";
1683 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1686 if (!preamble.notefontcolor().empty())
1687 preamble.registerAutomaticallyLoadedPackage("color");
1690 else if (name == "btSect") {
1691 eat_whitespace(p, os, parent_context, false);
1692 parent_context.check_layout(os);
1693 begin_command_inset(os, "bibtex", "bibtex");
1694 string bibstyle = "plain";
1696 bibstyle = p.getArg('[', ']');
1697 p.skip_spaces(true);
1699 string const bibfile = p.getArg('{', '}');
1700 eat_whitespace(p, os, parent_context, false);
1701 Token t = p.get_token();
1702 if (t.asInput() == "\\btPrintCited") {
1703 p.skip_spaces(true);
1704 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1706 if (t.asInput() == "\\btPrintNotCited") {
1707 p.skip_spaces(true);
1708 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1710 if (t.asInput() == "\\btPrintAll") {
1711 p.skip_spaces(true);
1712 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1714 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1715 os << "options " << '"' << bibstyle << '"' << "\n";
1716 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1721 else if (name == "framed" || name == "shaded") {
1722 eat_whitespace(p, os, parent_context, false);
1723 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1725 preamble.registerAutomaticallyLoadedPackage("framed");
1728 else if (name == "lstlisting") {
1729 eat_whitespace(p, os, parent_context, false);
1730 parse_listings(p, os, parent_context, false);
1734 else if (!parent_context.new_layout_allowed)
1735 parse_unknown_environment(p, name, os, FLAG_END, outer,
1738 // Alignment and spacing settings
1739 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1740 // therefore are totally broken!
1741 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1742 // they are commands not environments. They are furthermore switches that
1743 // can be ended by another switches, but also by commands like \footnote or
1744 // \parbox. So the only safe way is to leave them untouched.
1745 else if (name == "center" || name == "centering" ||
1746 name == "flushleft" || name == "flushright" ||
1747 name == "singlespace" || name == "onehalfspace" ||
1748 name == "doublespace" || name == "spacing") {
1749 eat_whitespace(p, os, parent_context, false);
1750 // We must begin a new paragraph if not already done
1751 if (! parent_context.atParagraphStart()) {
1752 parent_context.check_end_layout(os);
1753 parent_context.new_paragraph(os);
1755 if (name == "flushleft")
1756 parent_context.add_extra_stuff("\\align left\n");
1757 else if (name == "flushright")
1758 parent_context.add_extra_stuff("\\align right\n");
1759 else if (name == "center" || name == "centering")
1760 parent_context.add_extra_stuff("\\align center\n");
1761 else if (name == "singlespace")
1762 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1763 else if (name == "onehalfspace") {
1764 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1765 preamble.registerAutomaticallyLoadedPackage("setspace");
1766 } else if (name == "doublespace") {
1767 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1768 preamble.registerAutomaticallyLoadedPackage("setspace");
1769 } else if (name == "spacing") {
1770 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1771 preamble.registerAutomaticallyLoadedPackage("setspace");
1773 parse_text(p, os, FLAG_END, outer, parent_context);
1774 // Just in case the environment is empty
1775 parent_context.extra_stuff.erase();
1776 // We must begin a new paragraph to reset the alignment
1777 parent_context.new_paragraph(os);
1781 // The single '=' is meant here.
1782 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1783 eat_whitespace(p, os, parent_context, false);
1784 Context context(true, parent_context.textclass, newlayout,
1785 parent_context.layout, parent_context.font);
1786 if (parent_context.deeper_paragraph) {
1787 // We are beginning a nested environment after a
1788 // deeper paragraph inside the outer list environment.
1789 // Therefore we don't need to output a "begin deeper".
1790 context.need_end_deeper = true;
1792 parent_context.check_end_layout(os);
1793 if (last_env == name) {
1794 // we need to output a separator since LyX would export
1795 // the two environments as one otherwise (bug 5716)
1796 TeX2LyXDocClass const & textclass(parent_context.textclass);
1797 Context newcontext(true, textclass,
1798 &(textclass.defaultLayout()));
1799 newcontext.check_layout(os);
1800 begin_inset(os, "Separator plain\n");
1802 newcontext.check_end_layout(os);
1804 switch (context.layout->latextype) {
1805 case LATEX_LIST_ENVIRONMENT:
1806 context.add_par_extra_stuff("\\labelwidthstring "
1807 + p.verbatim_item() + '\n');
1810 case LATEX_BIB_ENVIRONMENT:
1811 p.verbatim_item(); // swallow next arg
1817 context.check_deeper(os);
1818 // handle known optional and required arguments
1819 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1820 // It is impossible to place anything after the environment name,
1821 // but before the first \\item.
1822 if (context.layout->latextype == LATEX_ENVIRONMENT)
1823 output_arguments(os, p, outer, false, false, context,
1824 context.layout->latexargs());
1825 parse_text(p, os, FLAG_END, outer, context);
1826 if (context.layout->latextype == LATEX_ENVIRONMENT)
1827 output_arguments(os, p, outer, false, true, context,
1828 context.layout->postcommandargs());
1829 context.check_end_layout(os);
1830 if (parent_context.deeper_paragraph) {
1831 // We must suppress the "end deeper" because we
1832 // suppressed the "begin deeper" above.
1833 context.need_end_deeper = false;
1835 context.check_end_deeper(os);
1836 parent_context.new_paragraph(os);
1838 if (!preamble.titleLayoutFound())
1839 preamble.titleLayoutFound(newlayout->intitle);
1840 set<string> const & req = newlayout->requires();
1841 set<string>::const_iterator it = req.begin();
1842 set<string>::const_iterator en = req.end();
1843 for (; it != en; ++it)
1844 preamble.registerAutomaticallyLoadedPackage(*it);
1847 // The single '=' is meant here.
1848 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1849 eat_whitespace(p, os, parent_context, false);
1850 parent_context.check_layout(os);
1851 begin_inset(os, "Flex ");
1852 os << to_utf8(newinsetlayout->name()) << '\n'
1853 << "status collapsed\n";
1854 if (newinsetlayout->isPassThru()) {
1855 string const arg = p.verbatimEnvironment(name);
1856 Context context(true, parent_context.textclass,
1857 &parent_context.textclass.plainLayout(),
1858 parent_context.layout);
1859 output_ert(os, arg, parent_context);
1861 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1865 else if (name == "appendix") {
1866 // This is no good latex style, but it works and is used in some documents...
1867 eat_whitespace(p, os, parent_context, false);
1868 parent_context.check_end_layout(os);
1869 Context context(true, parent_context.textclass, parent_context.layout,
1870 parent_context.layout, parent_context.font);
1871 context.check_layout(os);
1872 os << "\\start_of_appendix\n";
1873 parse_text(p, os, FLAG_END, outer, context);
1874 context.check_end_layout(os);
1878 else if (known_environments.find(name) != known_environments.end()) {
1879 vector<ArgumentType> arguments = known_environments[name];
1880 // The last "argument" denotes wether we may translate the
1881 // environment contents to LyX
1882 // The default required if no argument is given makes us
1883 // compatible with the reLyXre environment.
1884 ArgumentType contents = arguments.empty() ?
1887 if (!arguments.empty())
1888 arguments.pop_back();
1889 // See comment in parse_unknown_environment()
1890 bool const specialfont =
1891 (parent_context.font != parent_context.normalfont);
1892 bool const new_layout_allowed =
1893 parent_context.new_layout_allowed;
1895 parent_context.new_layout_allowed = false;
1896 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1897 outer, parent_context);
1898 if (contents == verbatim)
1899 output_ert_inset(os, p.ertEnvironment(name),
1902 parse_text_snippet(p, os, FLAG_END, outer,
1904 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1906 parent_context.new_layout_allowed = new_layout_allowed;
1910 parse_unknown_environment(p, name, os, FLAG_END, outer,
1914 active_environments.pop_back();
1918 /// parses a comment and outputs it to \p os.
1919 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1921 LASSERT(t.cat() == catComment, return);
1922 if (!t.cs().empty()) {
1923 context.check_layout(os);
1924 output_ert_inset(os, '%' + t.cs(), context);
1925 if (p.next_token().cat() == catNewline) {
1926 // A newline after a comment line starts a new
1928 if (context.new_layout_allowed) {
1929 if(!context.atParagraphStart())
1930 // Only start a new paragraph if not already
1931 // done (we might get called recursively)
1932 context.new_paragraph(os);
1934 output_ert_inset(os, "\n", context);
1935 eat_whitespace(p, os, context, true);
1938 // "%\n" combination
1945 * Reads spaces and comments until the first non-space, non-comment token.
1946 * New paragraphs (double newlines or \\par) are handled like simple spaces
1947 * if \p eatParagraph is true.
1948 * Spaces are skipped, but comments are written to \p os.
1950 void eat_whitespace(Parser & p, ostream & os, Context & context,
1954 Token const & t = p.get_token();
1955 if (t.cat() == catComment)
1956 parse_comment(p, os, t, context);
1957 else if ((! eatParagraph && p.isParagraph()) ||
1958 (t.cat() != catSpace && t.cat() != catNewline)) {
1967 * Set a font attribute, parse text and reset the font attribute.
1968 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1969 * \param currentvalue Current value of the attribute. Is set to the new
1970 * value during parsing.
1971 * \param newvalue New value of the attribute
1973 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1974 Context & context, string const & attribute,
1975 string & currentvalue, string const & newvalue)
1977 context.check_layout(os);
1978 string const oldvalue = currentvalue;
1979 currentvalue = newvalue;
1980 os << '\n' << attribute << ' ' << newvalue << "\n";
1981 parse_text_snippet(p, os, flags, outer, context);
1982 context.check_layout(os);
1983 os << '\n' << attribute << ' ' << oldvalue << "\n";
1984 currentvalue = oldvalue;
1988 /// get the arguments of a natbib or jurabib citation command
1989 void get_cite_arguments(Parser & p, bool natbibOrder,
1990 string & before, string & after)
1992 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1994 // text before the citation
1996 // text after the citation
1997 after = p.getFullOpt();
1999 if (!after.empty()) {
2000 before = p.getFullOpt();
2001 if (natbibOrder && !before.empty())
2002 swap(before, after);
2007 /// Convert filenames with TeX macros and/or quotes to something LyX
2009 string const normalize_filename(string const & name)
2014 Token const & t = p.get_token();
2015 if (t.cat() != catEscape)
2017 else if (t.cs() == "lyxdot") {
2018 // This is used by LyX for simple dots in relative
2022 } else if (t.cs() == "space") {
2025 } else if (t.cs() == "string") {
2026 // Convert \string" to " and \string~ to ~
2027 Token const & n = p.next_token();
2028 if (n.asInput() != "\"" && n.asInput() != "~")
2033 // Strip quotes. This is a bit complicated (see latex_path()).
2034 string full = os.str();
2035 if (!full.empty() && full[0] == '"') {
2036 string base = removeExtension(full);
2037 string ext = getExtension(full);
2038 if (!base.empty() && base[base.length()-1] == '"')
2041 return addExtension(trim(base, "\""), ext);
2042 if (full[full.length()-1] == '"')
2045 return trim(full, "\"");
2051 /// Convert \p name from TeX convention (relative to master file) to LyX
2052 /// convention (relative to .lyx file) if it is relative
2053 void fix_child_filename(string & name)
2055 string const absMasterTeX = getMasterFilePath(true);
2056 bool const isabs = FileName::isAbsolute(name);
2057 // convert from "relative to .tex master" to absolute original path
2059 name = makeAbsPath(name, absMasterTeX).absFileName();
2060 bool copyfile = copyFiles();
2061 string const absParentLyX = getParentFilePath(false);
2064 // convert from absolute original path to "relative to master file"
2065 string const rel = to_utf8(makeRelPath(from_utf8(name),
2066 from_utf8(absMasterTeX)));
2067 // re-interpret "relative to .tex file" as "relative to .lyx file"
2068 // (is different if the master .lyx file resides in a
2069 // different path than the master .tex file)
2070 string const absMasterLyX = getMasterFilePath(false);
2071 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2072 // Do not copy if the new path is impossible to create. Example:
2073 // absMasterTeX = "/foo/bar/"
2074 // absMasterLyX = "/bar/"
2075 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2076 if (contains(name, "/../"))
2083 // convert from absolute original path to
2084 // "relative to .lyx file"
2085 name = to_utf8(makeRelPath(from_utf8(abs),
2086 from_utf8(absParentLyX)));
2090 // convert from absolute original path to "relative to .lyx file"
2091 name = to_utf8(makeRelPath(from_utf8(name),
2092 from_utf8(absParentLyX)));
2097 void copy_file(FileName const & src, string dstname)
2101 string const absParent = getParentFilePath(false);
2103 if (FileName::isAbsolute(dstname))
2104 dst = FileName(dstname);
2106 dst = makeAbsPath(dstname, absParent);
2107 string const absMaster = getMasterFilePath(false);
2108 FileName const srcpath = src.onlyPath();
2109 FileName const dstpath = dst.onlyPath();
2110 if (equivalent(srcpath, dstpath))
2112 if (!dstpath.isDirectory()) {
2113 if (!dstpath.createPath()) {
2114 cerr << "Warning: Could not create directory for file `"
2115 << dst.absFileName() << "´." << endl;
2119 if (dst.isReadableFile()) {
2120 if (overwriteFiles())
2121 cerr << "Warning: Overwriting existing file `"
2122 << dst.absFileName() << "´." << endl;
2124 cerr << "Warning: Not overwriting existing file `"
2125 << dst.absFileName() << "´." << endl;
2129 if (!src.copyTo(dst))
2130 cerr << "Warning: Could not copy file `" << src.absFileName()
2131 << "´ to `" << dst.absFileName() << "´." << endl;
2135 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2136 bool parse_chunk(Parser & p, ostream & os, Context & context)
2138 // check whether a chunk is possible here.
2139 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2145 // read the parameters
2146 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2147 if (!params.first) {
2152 Parser::Arg const code = p.verbatimStuff("\n@");
2157 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2158 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2162 // The last newline read is important for paragraph handling
2166 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2167 // We must have a valid layout before outputting the Chunk inset.
2168 context.check_layout(os);
2169 Context chunkcontext(true, context.textclass);
2170 chunkcontext.layout = &context.textclass.plainLayout();
2171 begin_inset(os, "Flex Chunk");
2172 os << "\nstatus open\n";
2173 if (!params.second.empty()) {
2174 chunkcontext.check_layout(os);
2175 Context paramscontext(true, context.textclass);
2176 paramscontext.layout = &context.textclass.plainLayout();
2177 begin_inset(os, "Argument 1");
2178 os << "\nstatus open\n";
2179 output_ert(os, params.second, paramscontext);
2182 output_ert(os, code.second, chunkcontext);
2190 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2191 bool is_macro(Parser & p)
2193 Token first = p.curr_token();
2194 if (first.cat() != catEscape || !p.good())
2196 if (first.cs() == "def")
2198 if (first.cs() != "global" && first.cs() != "long")
2200 Token second = p.get_token();
2202 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2203 second.cat() == catNewline || second.cat() == catComment)) {
2204 second = p.get_token();
2207 bool secondvalid = second.cat() == catEscape;
2209 bool thirdvalid = false;
2210 if (p.good() && first.cs() == "global" && secondvalid &&
2211 second.cs() == "long") {
2212 third = p.get_token();
2214 while (p.good() && !p.isParagraph() &&
2215 (third.cat() == catSpace ||
2216 third.cat() == catNewline ||
2217 third.cat() == catComment)) {
2218 third = p.get_token();
2221 thirdvalid = third.cat() == catEscape;
2223 for (int i = 0; i < pos; ++i)
2228 return (first.cs() == "global" || first.cs() == "long") &&
2229 second.cs() == "def";
2230 return first.cs() == "global" && second.cs() == "long" &&
2231 third.cs() == "def";
2235 /// Parse a macro definition (assumes that is_macro() returned true)
2236 void parse_macro(Parser & p, ostream & os, Context & context)
2238 context.check_layout(os);
2239 Token first = p.curr_token();
2242 string command = first.asInput();
2243 if (first.cs() != "def") {
2245 eat_whitespace(p, os, context, false);
2246 second = p.curr_token();
2247 command += second.asInput();
2248 if (second.cs() != "def") {
2250 eat_whitespace(p, os, context, false);
2251 third = p.curr_token();
2252 command += third.asInput();
2255 eat_whitespace(p, os, context, false);
2256 string const name = p.get_token().cs();
2257 eat_whitespace(p, os, context, false);
2263 while (p.next_token().cat() != catBegin) {
2264 if (p.next_token().cat() == catParameter) {
2269 // followed by number?
2270 if (p.next_token().cat() == catOther) {
2271 string s = p.get_token().asInput();
2273 // number = current arity + 1?
2274 if (s.size() == 1 && s[0] == arity + '0' + 1)
2279 paramtext += p.get_token().cs();
2281 paramtext += p.get_token().cs();
2286 // only output simple (i.e. compatible) macro as FormulaMacros
2287 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2289 context.check_layout(os);
2290 begin_inset(os, "FormulaMacro");
2291 os << "\n\\def" << ert;
2294 output_ert_inset(os, command + ert, context);
2298 void registerExternalTemplatePackages(string const & name)
2300 external::TemplateManager const & etm = external::TemplateManager::get();
2301 external::Template const * const et = etm.getTemplateByName(name);
2304 external::Template::Formats::const_iterator cit = et->formats.end();
2306 cit = et->formats.find("PDFLaTeX");
2307 if (cit == et->formats.end())
2308 // If the template has not specified a PDFLaTeX output,
2309 // we try the LaTeX format.
2310 cit = et->formats.find("LaTeX");
2311 if (cit == et->formats.end())
2313 vector<string>::const_iterator qit = cit->second.requirements.begin();
2314 vector<string>::const_iterator qend = cit->second.requirements.end();
2315 for (; qit != qend; ++qit)
2316 preamble.registerAutomaticallyLoadedPackage(*qit);
2319 } // anonymous namespace
2322 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2325 Layout const * newlayout = 0;
2326 InsetLayout const * newinsetlayout = 0;
2327 char const * const * where = 0;
2328 // Store the latest bibliographystyle, addcontentslineContent and
2329 // nocite{*} option (needed for bibtex inset)
2331 string contentslineContent;
2332 string bibliographystyle = "default";
2333 bool const use_natbib = isProvided("natbib");
2334 bool const use_jurabib = isProvided("jurabib");
2337 // it is impossible to determine the correct encoding for non-CJK Japanese.
2338 // Therefore write a note at the beginning of the document
2339 if (is_nonCJKJapanese) {
2340 context.check_layout(os);
2341 begin_inset(os, "Note Note\n");
2342 os << "status open\n\\begin_layout Plain Layout\n"
2343 << "\\series bold\n"
2344 << "Important information:\n"
2345 << "\\end_layout\n\n"
2346 << "\\begin_layout Plain Layout\n"
2347 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2348 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2349 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2350 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2351 << " and specify the encoding using the -e command-line switch.\n"
2352 << " In addition, you might want to double check that the desired output encoding\n"
2353 << " is correctly selected in Document > Settings > Language.\n"
2354 << "\\end_layout\n";
2356 is_nonCJKJapanese = false;
2360 Token const & t = p.get_token();
2362 debugToken(cerr, t, flags);
2365 if (flags & FLAG_ITEM) {
2366 if (t.cat() == catSpace)
2369 flags &= ~FLAG_ITEM;
2370 if (t.cat() == catBegin) {
2371 // skip the brace and collect everything to the next matching
2373 flags |= FLAG_BRACE_LAST;
2377 // handle only this single token, leave the loop if done
2378 flags |= FLAG_LEAVE;
2381 if (t.cat() != catEscape && t.character() == ']' &&
2382 (flags & FLAG_BRACK_LAST))
2384 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2387 // If there is anything between \end{env} and \begin{env} we
2388 // don't need to output a separator.
2389 if (t.cat() != catSpace && t.cat() != catNewline &&
2390 t.asInput() != "\\begin")
2396 bool const starred = p.next_token().asInput() == "*";
2397 string const starredname(starred ? (t.cs() + '*') : t.cs());
2398 if (t.cat() == catMath) {
2399 // we are inside some text mode thingy, so opening new math is allowed
2400 context.check_layout(os);
2401 begin_inset(os, "Formula ");
2402 Token const & n = p.get_token();
2403 bool const display(n.cat() == catMath && outer);
2405 // TeX's $$...$$ syntax for displayed math
2407 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2409 p.get_token(); // skip the second '$' token
2411 // simple $...$ stuff
2414 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2419 // Prevent the conversion of a line break to a
2420 // space (bug 7668). This does not change the
2421 // output, but looks ugly in LyX.
2422 eat_whitespace(p, os, context, false);
2426 else if (t.cat() == catSuper || t.cat() == catSub)
2427 cerr << "catcode " << t << " illegal in text mode\n";
2429 // Basic support for english quotes. This should be
2430 // extended to other quotes, but is not so easy (a
2431 // left english quote is the same as a right german
2433 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2434 context.check_layout(os);
2435 begin_inset(os, "Quotes ");
2441 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2442 context.check_layout(os);
2443 begin_inset(os, "Quotes ");
2450 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2451 context.check_layout(os);
2452 begin_inset(os, "Quotes ");
2459 else if (t.asInput() == "<"
2460 && p.next_token().asInput() == "<") {
2461 bool has_chunk = false;
2465 has_chunk = parse_chunk(p, os, context);
2471 context.check_layout(os);
2472 begin_inset(os, "Quotes ");
2473 //FIXME: this is a right danish quote;
2474 // why not a left french quote?
2482 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2483 check_space(p, os, context);
2485 else if (t.character() == '[' && noweb_mode &&
2486 p.next_token().character() == '[') {
2487 // These can contain underscores
2489 string const s = p.getFullOpt() + ']';
2490 if (p.next_token().character() == ']')
2493 cerr << "Warning: Inserting missing ']' in '"
2494 << s << "'." << endl;
2495 output_ert_inset(os, s, context);
2498 else if (t.cat() == catLetter) {
2499 context.check_layout(os);
2503 else if (t.cat() == catOther ||
2504 t.cat() == catAlign ||
2505 t.cat() == catParameter) {
2506 context.check_layout(os);
2507 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2508 context.merging_hyphens_allowed &&
2509 context.font.family != "ttfamily" &&
2510 !context.layout->pass_thru) {
2511 if (p.next_next_token().asInput() == "-") {
2513 os << to_utf8(docstring(1, 0x2014));
2517 os << to_utf8(docstring(1, 0x2013));
2520 // This translates "&" to "\\&" which may be wrong...
2524 else if (p.isParagraph()) {
2525 if (context.new_layout_allowed)
2526 context.new_paragraph(os);
2528 output_ert_inset(os, "\\par ", context);
2529 eat_whitespace(p, os, context, true);
2532 else if (t.cat() == catActive) {
2533 context.check_layout(os);
2534 if (t.character() == '~') {
2535 if (context.layout->free_spacing)
2538 begin_inset(os, "space ~\n");
2545 else if (t.cat() == catBegin) {
2546 Token const next = p.next_token();
2547 Token const end = p.next_next_token();
2548 if (next.cat() == catEnd) {
2550 Token const prev = p.prev_token();
2552 if (p.next_token().character() == '`')
2553 ; // ignore it in {}``
2555 output_ert_inset(os, "{}", context);
2556 } else if (next.cat() == catEscape &&
2557 is_known(next.cs(), known_quotes) &&
2558 end.cat() == catEnd) {
2559 // Something like {\textquoteright} (e.g.
2560 // from writer2latex). LyX writes
2561 // \textquoteright{}, so we may skip the
2562 // braces here for better readability.
2563 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2565 } else if (p.next_token().asInput() == "\\ascii") {
2566 // handle the \ascii characters
2567 // (the case without braces is handled later)
2568 // the code is "{\ascii\xxx}"
2569 p.get_token(); // eat \ascii
2570 string name2 = p.get_token().asInput();
2571 p.get_token(); // eat the final '}'
2572 string const name = "{\\ascii" + name2 + "}";
2576 // get the character from unicodesymbols
2577 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2578 Encodings::TEXT_CMD, termination, rem, &req);
2580 context.check_layout(os);
2583 output_ert_inset(os,
2584 to_utf8(rem), context);
2585 for (set<string>::const_iterator it = req.begin();
2586 it != req.end(); ++it)
2587 preamble.registerAutomaticallyLoadedPackage(*it);
2589 // we did not find a non-ert version
2590 output_ert_inset(os, name, context);
2592 context.check_layout(os);
2593 // special handling of font attribute changes
2594 Token const prev = p.prev_token();
2595 TeXFont const oldFont = context.font;
2596 if (next.character() == '[' ||
2597 next.character() == ']' ||
2598 next.character() == '*') {
2600 if (p.next_token().cat() == catEnd) {
2605 output_ert_inset(os, "{", context);
2606 parse_text_snippet(p, os,
2609 output_ert_inset(os, "}", context);
2611 } else if (! context.new_layout_allowed) {
2612 output_ert_inset(os, "{", context);
2613 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2615 output_ert_inset(os, "}", context);
2616 } else if (is_known(next.cs(), known_sizes)) {
2617 // next will change the size, so we must
2619 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2621 if (!context.atParagraphStart())
2623 << context.font.size << "\n";
2624 } else if (is_known(next.cs(), known_font_families)) {
2625 // next will change the font family, so we
2626 // must reset it here
2627 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2629 if (!context.atParagraphStart())
2631 << context.font.family << "\n";
2632 } else if (is_known(next.cs(), known_font_series)) {
2633 // next will change the font series, so we
2634 // must reset it here
2635 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2637 if (!context.atParagraphStart())
2639 << context.font.series << "\n";
2640 } else if (is_known(next.cs(), known_font_shapes)) {
2641 // next will change the font shape, so we
2642 // must reset it here
2643 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2645 if (!context.atParagraphStart())
2647 << context.font.shape << "\n";
2648 } else if (is_known(next.cs(), known_old_font_families) ||
2649 is_known(next.cs(), known_old_font_series) ||
2650 is_known(next.cs(), known_old_font_shapes)) {
2651 // next will change the font family, series
2652 // and shape, so we must reset it here
2653 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2655 if (!context.atParagraphStart())
2657 << context.font.family
2659 << context.font.series
2661 << context.font.shape << "\n";
2663 output_ert_inset(os, "{", context);
2664 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2666 output_ert_inset(os, "}", context);
2671 else if (t.cat() == catEnd) {
2672 if (flags & FLAG_BRACE_LAST) {
2675 cerr << "stray '}' in text\n";
2676 output_ert_inset(os, "}", context);
2679 else if (t.cat() == catComment)
2680 parse_comment(p, os, t, context);
2683 // control sequences
2686 else if (t.cs() == "(" || t.cs() == "[") {
2687 bool const simple = t.cs() == "(";
2688 context.check_layout(os);
2689 begin_inset(os, "Formula");
2690 os << " \\" << t.cs();
2691 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2692 os << '\\' << (simple ? ')' : ']');
2695 // Prevent the conversion of a line break to a
2696 // space (bug 7668). This does not change the
2697 // output, but looks ugly in LyX.
2698 eat_whitespace(p, os, context, false);
2702 else if (t.cs() == "begin")
2703 parse_environment(p, os, outer, last_env,
2706 else if (t.cs() == "end") {
2707 if (flags & FLAG_END) {
2708 // eat environment name
2709 string const name = p.getArg('{', '}');
2710 if (name != active_environment())
2711 cerr << "\\end{" + name + "} does not match \\begin{"
2712 + active_environment() + "}\n";
2715 p.error("found 'end' unexpectedly");
2718 else if (t.cs() == "item") {
2720 bool const optarg = p.hasOpt();
2722 // FIXME: This swallows comments, but we cannot use
2723 // eat_whitespace() since we must not output
2724 // anything before the item.
2725 p.skip_spaces(true);
2726 s = p.verbatimOption();
2728 p.skip_spaces(false);
2730 context.check_layout(os);
2731 if (context.has_item) {
2732 // An item in an unknown list-like environment
2733 // FIXME: Do this in check_layout()!
2734 context.has_item = false;
2736 output_ert_inset(os, "\\item", context);
2738 output_ert_inset(os, "\\item ", context);
2741 if (context.layout->labeltype != LABEL_MANUAL) {
2742 // handle option of itemize item
2743 begin_inset(os, "Argument item:1\n");
2744 os << "status open\n";
2745 os << "\n\\begin_layout Plain Layout\n";
2747 os << parse_text_snippet(p2,
2748 FLAG_BRACK_LAST, outer, context);
2749 // we must not use context.check_end_layout(os)
2750 // because that would close the outer itemize layout
2751 os << "\n\\end_layout\n";
2753 eat_whitespace(p, os, context, false);
2754 } else if (!s.empty()) {
2755 // LyX adds braces around the argument,
2756 // so we need to remove them here.
2757 if (s.size() > 2 && s[0] == '{' &&
2758 s[s.size()-1] == '}')
2759 s = s.substr(1, s.size()-2);
2760 // If the argument contains a space we
2761 // must put it into ERT: Otherwise LyX
2762 // would misinterpret the space as
2763 // item delimiter (bug 7663)
2764 if (contains(s, ' ')) {
2765 output_ert_inset(os, s, context);
2768 os << parse_text_snippet(p2,
2769 FLAG_BRACK_LAST, outer, context);
2771 // The space is needed to separate the
2772 // item from the rest of the sentence.
2774 eat_whitespace(p, os, context, false);
2779 else if (t.cs() == "bibitem") {
2781 context.check_layout(os);
2782 eat_whitespace(p, os, context, false);
2783 string label = convert_command_inset_arg(p.verbatimOption());
2784 string key = convert_command_inset_arg(p.verbatim_item());
2785 if (contains(label, '\\') || contains(key, '\\')) {
2786 // LyX can't handle LaTeX commands in labels or keys
2787 output_ert_inset(os, t.asInput() + '[' + label +
2788 "]{" + p.verbatim_item() + '}',
2791 begin_command_inset(os, "bibitem", "bibitem");
2792 os << "label \"" << label << "\"\n"
2793 "key \"" << key << "\"\n";
2798 else if (is_macro(p)) {
2799 // catch the case of \def\inputGnumericTable
2801 if (t.cs() == "def") {
2802 Token second = p.next_token();
2803 if (second.cs() == "inputGnumericTable") {
2807 Token third = p.get_token();
2809 if (third.cs() == "input") {
2813 string name = normalize_filename(p.verbatim_item());
2814 string const path = getMasterFilePath(true);
2815 // We want to preserve relative / absolute filenames,
2816 // therefore path is only used for testing
2817 // The file extension is in every case ".tex".
2818 // So we need to remove this extension and check for
2819 // the original one.
2820 name = removeExtension(name);
2821 if (!makeAbsPath(name, path).exists()) {
2822 char const * const Gnumeric_formats[] = {"gnumeric",
2824 string const Gnumeric_name =
2825 find_file(name, path, Gnumeric_formats);
2826 if (!Gnumeric_name.empty())
2827 name = Gnumeric_name;
2829 FileName const absname = makeAbsPath(name, path);
2830 if (absname.exists()) {
2831 fix_child_filename(name);
2832 copy_file(absname, name);
2834 cerr << "Warning: Could not find file '"
2835 << name << "'." << endl;
2836 context.check_layout(os);
2837 begin_inset(os, "External\n\ttemplate ");
2838 os << "GnumericSpreadsheet\n\tfilename "
2841 context.check_layout(os);
2843 // register the packages that are automatically loaded
2844 // by the Gnumeric template
2845 registerExternalTemplatePackages("GnumericSpreadsheet");
2850 parse_macro(p, os, context);
2853 else if (t.cs() == "noindent") {
2855 context.add_par_extra_stuff("\\noindent\n");
2858 else if (t.cs() == "appendix") {
2859 context.add_par_extra_stuff("\\start_of_appendix\n");
2860 // We need to start a new paragraph. Otherwise the
2861 // appendix in 'bla\appendix\chapter{' would start
2863 context.new_paragraph(os);
2864 // We need to make sure that the paragraph is
2865 // generated even if it is empty. Otherwise the
2866 // appendix in '\par\appendix\par\chapter{' would
2868 context.check_layout(os);
2869 // FIXME: This is a hack to prevent paragraph
2870 // deletion if it is empty. Handle this better!
2871 output_ert_inset(os,
2872 "%dummy comment inserted by tex2lyx to "
2873 "ensure that this paragraph is not empty",
2875 // Both measures above may generate an additional
2876 // empty paragraph, but that does not hurt, because
2877 // whitespace does not matter here.
2878 eat_whitespace(p, os, context, true);
2881 // Must catch empty dates before findLayout is called below
2882 else if (t.cs() == "date") {
2883 eat_whitespace(p, os, context, false);
2885 string const date = p.verbatim_item();
2888 preamble.suppressDate(true);
2891 preamble.suppressDate(false);
2892 if (context.new_layout_allowed &&
2893 (newlayout = findLayout(context.textclass,
2896 output_command_layout(os, p, outer,
2897 context, newlayout);
2898 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2899 if (!preamble.titleLayoutFound())
2900 preamble.titleLayoutFound(newlayout->intitle);
2901 set<string> const & req = newlayout->requires();
2902 set<string>::const_iterator it = req.begin();
2903 set<string>::const_iterator en = req.end();
2904 for (; it != en; ++it)
2905 preamble.registerAutomaticallyLoadedPackage(*it);
2907 output_ert_inset(os,
2908 "\\date{" + p.verbatim_item() + '}',
2913 // Starred section headings
2914 // Must attempt to parse "Section*" before "Section".
2915 else if ((p.next_token().asInput() == "*") &&
2916 context.new_layout_allowed &&
2917 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2920 output_command_layout(os, p, outer, context, newlayout);
2922 if (!preamble.titleLayoutFound())
2923 preamble.titleLayoutFound(newlayout->intitle);
2924 set<string> const & req = newlayout->requires();
2925 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2926 preamble.registerAutomaticallyLoadedPackage(*it);
2929 // Section headings and the like
2930 else if (context.new_layout_allowed &&
2931 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2933 output_command_layout(os, p, outer, context, newlayout);
2935 if (!preamble.titleLayoutFound())
2936 preamble.titleLayoutFound(newlayout->intitle);
2937 set<string> const & req = newlayout->requires();
2938 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2939 preamble.registerAutomaticallyLoadedPackage(*it);
2942 else if (t.cs() == "subfloat") {
2943 // the syntax is \subfloat[list entry][sub caption]{content}
2944 // if it is a table of figure depends on the surrounding float
2945 // FIXME: second optional argument is not parsed
2946 bool has_caption = false;
2948 // do nothing if there is no outer float
2949 if (!float_type.empty()) {
2950 context.check_layout(os);
2952 begin_inset(os, "Float " + float_type + "\n");
2954 << "\nsideways false"
2955 << "\nstatus collapsed\n\n";
2958 if (p.next_token().cat() != catEscape &&
2959 p.next_token().character() == '[') {
2960 p.get_token(); // eat '['
2961 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2965 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2966 // the caption comes always as the last
2968 // we must make sure that the caption gets a \begin_layout
2969 os << "\n\\begin_layout Plain Layout";
2971 begin_inset(os, "Caption Standard\n");
2972 Context newcontext(true, context.textclass,
2973 0, 0, context.font);
2974 newcontext.check_layout(os);
2975 os << caption << "\n";
2976 newcontext.check_end_layout(os);
2977 // We don't need really a new paragraph, but
2978 // we must make sure that the next item gets a \begin_layout.
2979 //newcontext.new_paragraph(os);
2983 // We don't need really a new paragraph, but
2984 // we must make sure that the next item gets a \begin_layout.
2986 context.new_paragraph(os);
2989 context.check_end_layout(os);
2990 // close the layout we opened
2992 os << "\n\\end_layout\n";
2994 // if the float type is not supported or there is no surrounding float
2997 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2998 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2999 "]{" + p.verbatim_item() + '}', context);
3001 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3005 else if (t.cs() == "includegraphics") {
3006 bool const clip = p.next_token().asInput() == "*";
3009 string const arg = p.getArg('[', ']');
3010 map<string, string> opts;
3011 vector<string> keys;
3012 split_map(arg, opts, keys);
3014 opts["clip"] = string();
3015 string name = normalize_filename(p.verbatim_item());
3017 string const path = getMasterFilePath(true);
3018 // We want to preserve relative / absolute filenames,
3019 // therefore path is only used for testing
3020 if (!makeAbsPath(name, path).exists()) {
3021 // The file extension is probably missing.
3022 // Now try to find it out.
3023 string const dvips_name =
3024 find_file(name, path,
3025 known_dvips_graphics_formats);
3026 string const pdftex_name =
3027 find_file(name, path,
3028 known_pdftex_graphics_formats);
3029 if (!dvips_name.empty()) {
3030 if (!pdftex_name.empty()) {
3031 cerr << "This file contains the "
3033 "\"\\includegraphics{"
3035 "However, files\n\""
3036 << dvips_name << "\" and\n\""
3037 << pdftex_name << "\"\n"
3038 "both exist, so I had to make a "
3039 "choice and took the first one.\n"
3040 "Please move the unwanted one "
3041 "someplace else and try again\n"
3042 "if my choice was wrong."
3046 } else if (!pdftex_name.empty()) {
3052 FileName const absname = makeAbsPath(name, path);
3053 if (absname.exists()) {
3054 fix_child_filename(name);
3055 copy_file(absname, name);
3057 cerr << "Warning: Could not find graphics file '"
3058 << name << "'." << endl;
3060 context.check_layout(os);
3061 begin_inset(os, "Graphics ");
3062 os << "\n\tfilename " << name << '\n';
3063 if (opts.find("width") != opts.end())
3065 << translate_len(opts["width"]) << '\n';
3066 if (opts.find("height") != opts.end())
3068 << translate_len(opts["height"]) << '\n';
3069 if (opts.find("scale") != opts.end()) {
3070 istringstream iss(opts["scale"]);
3074 os << "\tscale " << val << '\n';
3076 if (opts.find("angle") != opts.end()) {
3077 os << "\trotateAngle "
3078 << opts["angle"] << '\n';
3079 vector<string>::const_iterator a =
3080 find(keys.begin(), keys.end(), "angle");
3081 vector<string>::const_iterator s =
3082 find(keys.begin(), keys.end(), "width");
3083 if (s == keys.end())
3084 s = find(keys.begin(), keys.end(), "height");
3085 if (s == keys.end())
3086 s = find(keys.begin(), keys.end(), "scale");
3087 if (s != keys.end() && distance(s, a) > 0)
3088 os << "\tscaleBeforeRotation\n";
3090 if (opts.find("origin") != opts.end()) {
3092 string const opt = opts["origin"];
3093 if (opt.find('l') != string::npos) ss << "left";
3094 if (opt.find('r') != string::npos) ss << "right";
3095 if (opt.find('c') != string::npos) ss << "center";
3096 if (opt.find('t') != string::npos) ss << "Top";
3097 if (opt.find('b') != string::npos) ss << "Bottom";
3098 if (opt.find('B') != string::npos) ss << "Baseline";
3099 if (!ss.str().empty())
3100 os << "\trotateOrigin " << ss.str() << '\n';
3102 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3104 if (opts.find("keepaspectratio") != opts.end())
3105 os << "\tkeepAspectRatio\n";
3106 if (opts.find("clip") != opts.end())
3108 if (opts.find("draft") != opts.end())
3110 if (opts.find("bb") != opts.end())
3111 os << "\tBoundingBox "
3112 << opts["bb"] << '\n';
3113 int numberOfbbOptions = 0;
3114 if (opts.find("bbllx") != opts.end())
3115 numberOfbbOptions++;
3116 if (opts.find("bblly") != opts.end())
3117 numberOfbbOptions++;
3118 if (opts.find("bburx") != opts.end())
3119 numberOfbbOptions++;
3120 if (opts.find("bbury") != opts.end())
3121 numberOfbbOptions++;
3122 if (numberOfbbOptions == 4)
3123 os << "\tBoundingBox "
3124 << opts["bbllx"] << " " << opts["bblly"] << " "
3125 << opts["bburx"] << " " << opts["bbury"] << '\n';
3126 else if (numberOfbbOptions > 0)
3127 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3128 numberOfbbOptions = 0;
3129 if (opts.find("natwidth") != opts.end())
3130 numberOfbbOptions++;
3131 if (opts.find("natheight") != opts.end())
3132 numberOfbbOptions++;
3133 if (numberOfbbOptions == 2)
3134 os << "\tBoundingBox 0bp 0bp "
3135 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3136 else if (numberOfbbOptions > 0)
3137 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3138 ostringstream special;
3139 if (opts.find("hiresbb") != opts.end())
3140 special << "hiresbb,";
3141 if (opts.find("trim") != opts.end())
3143 if (opts.find("viewport") != opts.end())
3144 special << "viewport=" << opts["viewport"] << ',';
3145 if (opts.find("totalheight") != opts.end())
3146 special << "totalheight=" << opts["totalheight"] << ',';
3147 if (opts.find("type") != opts.end())
3148 special << "type=" << opts["type"] << ',';
3149 if (opts.find("ext") != opts.end())
3150 special << "ext=" << opts["ext"] << ',';
3151 if (opts.find("read") != opts.end())
3152 special << "read=" << opts["read"] << ',';
3153 if (opts.find("command") != opts.end())
3154 special << "command=" << opts["command"] << ',';
3155 string s_special = special.str();
3156 if (!s_special.empty()) {
3157 // We had special arguments. Remove the trailing ','.
3158 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3160 // TODO: Handle the unknown settings better.
3161 // Warn about invalid options.
3162 // Check whether some option was given twice.
3164 preamble.registerAutomaticallyLoadedPackage("graphicx");
3167 else if (t.cs() == "footnote" ||
3168 (t.cs() == "thanks" && context.layout->intitle)) {
3170 context.check_layout(os);
3171 begin_inset(os, "Foot\n");
3172 os << "status collapsed\n\n";
3173 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3177 else if (t.cs() == "marginpar") {
3179 context.check_layout(os);
3180 begin_inset(os, "Marginal\n");
3181 os << "status collapsed\n\n";
3182 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3186 else if (t.cs() == "lstinline") {
3188 parse_listings(p, os, context, true);
3191 else if (t.cs() == "ensuremath") {
3193 context.check_layout(os);
3194 string const s = p.verbatim_item();
3195 //FIXME: this never triggers in UTF8
3196 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3199 output_ert_inset(os, "\\ensuremath{" + s + "}",
3203 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3204 if (preamble.titleLayoutFound()) {
3206 skip_spaces_braces(p);
3208 output_ert_inset(os, t.asInput(), context);
3211 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3212 context.check_layout(os);
3213 begin_command_inset(os, "toc", t.cs());
3215 skip_spaces_braces(p);
3216 if (t.cs() == "lstlistoflistings")
3217 preamble.registerAutomaticallyLoadedPackage("listings");
3220 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3221 context.check_layout(os);
3222 if (t.cs() == "listoffigures")
3223 begin_inset(os, "FloatList figure\n");
3225 begin_inset(os, "FloatList table\n");
3227 skip_spaces_braces(p);
3230 else if (t.cs() == "listof") {
3231 p.skip_spaces(true);
3232 string const name = p.get_token().cs();
3233 if (context.textclass.floats().typeExist(name)) {
3234 context.check_layout(os);
3235 begin_inset(os, "FloatList ");
3238 p.get_token(); // swallow second arg
3240 output_ert_inset(os, "\\listof{" + name + "}", context);
3243 else if ((where = is_known(t.cs(), known_text_font_families)))
3244 parse_text_attributes(p, os, FLAG_ITEM, outer,
3245 context, "\\family", context.font.family,
3246 known_coded_font_families[where - known_text_font_families]);
3248 else if ((where = is_known(t.cs(), known_text_font_series)))
3249 parse_text_attributes(p, os, FLAG_ITEM, outer,
3250 context, "\\series", context.font.series,
3251 known_coded_font_series[where - known_text_font_series]);
3253 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3254 parse_text_attributes(p, os, FLAG_ITEM, outer,
3255 context, "\\shape", context.font.shape,
3256 known_coded_font_shapes[where - known_text_font_shapes]);
3258 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3259 context.check_layout(os);
3260 TeXFont oldFont = context.font;
3261 context.font.init();
3262 context.font.size = oldFont.size;
3263 os << "\n\\family " << context.font.family << "\n";
3264 os << "\n\\series " << context.font.series << "\n";
3265 os << "\n\\shape " << context.font.shape << "\n";
3266 if (t.cs() == "textnormal") {
3267 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3268 output_font_change(os, context.font, oldFont);
3269 context.font = oldFont;
3271 eat_whitespace(p, os, context, false);
3274 else if (t.cs() == "textcolor") {
3275 // scheme is \textcolor{color name}{text}
3276 string const color = p.verbatim_item();
3277 // we support the predefined colors of the color and the xcolor package
3278 if (color == "black" || color == "blue" || color == "cyan"
3279 || color == "green" || color == "magenta" || color == "red"
3280 || color == "white" || color == "yellow") {
3281 context.check_layout(os);
3282 os << "\n\\color " << color << "\n";
3283 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3284 context.check_layout(os);
3285 os << "\n\\color inherit\n";
3286 preamble.registerAutomaticallyLoadedPackage("color");
3287 } else if (color == "brown" || color == "darkgray" || color == "gray"
3288 || color == "lightgray" || color == "lime" || color == "olive"
3289 || color == "orange" || color == "pink" || color == "purple"
3290 || color == "teal" || color == "violet") {
3291 context.check_layout(os);
3292 os << "\n\\color " << color << "\n";
3293 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3294 context.check_layout(os);
3295 os << "\n\\color inherit\n";
3296 preamble.registerAutomaticallyLoadedPackage("xcolor");
3298 // for custom defined colors
3299 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3302 else if (t.cs() == "underbar" || t.cs() == "uline") {
3303 // \underbar is not 100% correct (LyX outputs \uline
3304 // of ulem.sty). The difference is that \ulem allows
3305 // line breaks, and \underbar does not.
3306 // Do NOT handle \underline.
3307 // \underbar cuts through y, g, q, p etc.,
3308 // \underline does not.
3309 context.check_layout(os);
3310 os << "\n\\bar under\n";
3311 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3312 context.check_layout(os);
3313 os << "\n\\bar default\n";
3314 preamble.registerAutomaticallyLoadedPackage("ulem");
3317 else if (t.cs() == "sout") {
3318 context.check_layout(os);
3319 os << "\n\\strikeout on\n";
3320 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3321 context.check_layout(os);
3322 os << "\n\\strikeout default\n";
3323 preamble.registerAutomaticallyLoadedPackage("ulem");
3326 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3327 t.cs() == "emph" || t.cs() == "noun") {
3328 context.check_layout(os);
3329 os << "\n\\" << t.cs() << " on\n";
3330 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3331 context.check_layout(os);
3332 os << "\n\\" << t.cs() << " default\n";
3333 if (t.cs() == "uuline" || t.cs() == "uwave")
3334 preamble.registerAutomaticallyLoadedPackage("ulem");
3337 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3338 context.check_layout(os);
3339 string name = p.getArg('{', '}');
3340 string localtime = p.getArg('{', '}');
3341 preamble.registerAuthor(name);
3342 Author const & author = preamble.getAuthor(name);
3343 // from_asctime_utc() will fail if LyX decides to output the
3344 // time in the text language.
3345 time_t ptime = from_asctime_utc(localtime);
3346 if (ptime == static_cast<time_t>(-1)) {
3347 cerr << "Warning: Could not parse time `" << localtime
3348 << "´ for change tracking, using current time instead.\n";
3349 ptime = current_time();
3351 if (t.cs() == "lyxadded")
3352 os << "\n\\change_inserted ";
3354 os << "\n\\change_deleted ";
3355 os << author.bufferId() << ' ' << ptime << '\n';
3356 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3357 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3358 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3359 LaTeXPackages::isAvailable("xcolor");
3360 // No need to test for luatex, since luatex comes in
3361 // two flavours (dvi and pdf), like latex, and those
3362 // are detected by pdflatex.
3363 if (pdflatex || xetex) {
3365 preamble.registerAutomaticallyLoadedPackage("ulem");
3366 preamble.registerAutomaticallyLoadedPackage("xcolor");
3367 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3371 preamble.registerAutomaticallyLoadedPackage("dvipost");
3372 } else if (xcolorulem) {
3373 preamble.registerAutomaticallyLoadedPackage("ulem");
3374 preamble.registerAutomaticallyLoadedPackage("xcolor");
3379 else if (t.cs() == "textipa") {
3380 context.check_layout(os);
3381 begin_inset(os, "IPA\n");
3382 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3383 context.merging_hyphens_allowed = false;
3384 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3385 context.merging_hyphens_allowed = merging_hyphens_allowed;
3387 preamble.registerAutomaticallyLoadedPackage("tipa");
3388 preamble.registerAutomaticallyLoadedPackage("tipx");
3391 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3392 context.check_layout(os);
3393 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3394 os << "status open\n";
3395 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3400 else if (t.cs() == "textvertline") {
3401 // FIXME: This is not correct, \textvertline is higher than |
3407 else if (t.cs() == "tone" ) {
3408 context.check_layout(os);
3409 // register the tone package
3410 preamble.registerAutomaticallyLoadedPackage("tone");
3411 string content = trimSpaceAndEol(p.verbatim_item());
3412 string command = t.asInput() + "{" + content + "}";
3413 // some tones can be detected by unicodesymbols, some need special code
3414 if (is_known(content, known_tones)) {
3415 os << "\\IPAChar " << command << "\n";
3418 // try to see whether the string is in unicodesymbols
3422 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3423 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3424 termination, rem, &req);
3428 output_ert_inset(os, to_utf8(rem), context);
3429 for (set<string>::const_iterator it = req.begin();
3430 it != req.end(); ++it)
3431 preamble.registerAutomaticallyLoadedPackage(*it);
3433 // we did not find a non-ert version
3434 output_ert_inset(os, command, context);
3437 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3438 t.cs() == "vphantom") {
3439 context.check_layout(os);
3440 if (t.cs() == "phantom")
3441 begin_inset(os, "Phantom Phantom\n");
3442 if (t.cs() == "hphantom")
3443 begin_inset(os, "Phantom HPhantom\n");
3444 if (t.cs() == "vphantom")
3445 begin_inset(os, "Phantom VPhantom\n");
3446 os << "status open\n";
3447 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3452 else if (t.cs() == "href") {
3453 context.check_layout(os);
3454 string target = convert_command_inset_arg(p.verbatim_item());
3455 string name = convert_command_inset_arg(p.verbatim_item());
3457 size_t i = target.find(':');
3458 if (i != string::npos) {
3459 type = target.substr(0, i + 1);
3460 if (type == "mailto:" || type == "file:")
3461 target = target.substr(i + 1);
3462 // handle the case that name is equal to target, except of "http://"
3463 else if (target.substr(i + 3) == name && type == "http:")
3466 begin_command_inset(os, "href", "href");
3468 os << "name \"" << name << "\"\n";
3469 os << "target \"" << target << "\"\n";
3470 if (type == "mailto:" || type == "file:")
3471 os << "type \"" << type << "\"\n";
3473 skip_spaces_braces(p);
3476 else if (t.cs() == "lyxline") {
3477 // swallow size argument (it is not used anyway)
3479 if (!context.atParagraphStart()) {
3480 // so our line is in the middle of a paragraph
3481 // we need to add a new line, lest this line
3482 // follow the other content on that line and
3483 // run off the side of the page
3484 // FIXME: This may create an empty paragraph,
3485 // but without that it would not be
3486 // possible to set noindent below.
3487 // Fortunately LaTeX does not care
3488 // about the empty paragraph.
3489 context.new_paragraph(os);
3491 if (preamble.indentParagraphs()) {
3492 // we need to unindent, lest the line be too long
3493 context.add_par_extra_stuff("\\noindent\n");
3495 context.check_layout(os);
3496 begin_command_inset(os, "line", "rule");
3497 os << "offset \"0.5ex\"\n"
3498 "width \"100line%\"\n"
3503 else if (t.cs() == "rule") {
3504 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3505 string const width = p.getArg('{', '}');
3506 string const thickness = p.getArg('{', '}');
3507 context.check_layout(os);
3508 begin_command_inset(os, "line", "rule");
3509 if (!offset.empty())
3510 os << "offset \"" << translate_len(offset) << "\"\n";
3511 os << "width \"" << translate_len(width) << "\"\n"
3512 "height \"" << translate_len(thickness) << "\"\n";
3516 // handle refstyle first to catch \eqref which can also occur
3517 // without refstyle. Only recognize these commands if
3518 // refstyle.sty was found in the preamble (otherwise \eqref
3519 // and user defined ref commands could be misdetected).
3520 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3521 preamble.refstyle()) {
3522 context.check_layout(os);
3523 begin_command_inset(os, "ref", "formatted");
3524 os << "reference \"";
3525 os << known_refstyle_prefixes[where - known_refstyle_commands]
3527 os << convert_command_inset_arg(p.verbatim_item())
3530 preamble.registerAutomaticallyLoadedPackage("refstyle");
3533 // if refstyle is used, we must not convert \prettyref to a
3534 // formatted reference, since that would result in a refstyle command.
3535 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3536 (t.cs() != "prettyref" || !preamble.refstyle())) {
3537 string const opt = p.getOpt();
3539 context.check_layout(os);
3540 begin_command_inset(os, "ref",
3541 known_coded_ref_commands[where - known_ref_commands]);
3542 os << "reference \""
3543 << convert_command_inset_arg(p.verbatim_item())
3546 if (t.cs() == "vref" || t.cs() == "vpageref")
3547 preamble.registerAutomaticallyLoadedPackage("varioref");
3548 else if (t.cs() == "prettyref")
3549 preamble.registerAutomaticallyLoadedPackage("prettyref");
3551 // LyX does not yet support optional arguments of ref commands
3552 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3553 p.verbatim_item() + '}', context);
3557 else if (use_natbib &&
3558 is_known(t.cs(), known_natbib_commands) &&
3559 ((t.cs() != "citefullauthor" &&
3560 t.cs() != "citeyear" &&
3561 t.cs() != "citeyearpar") ||
3562 p.next_token().asInput() != "*")) {
3563 context.check_layout(os);
3564 string command = t.cs();
3565 if (p.next_token().asInput() == "*") {
3569 if (command == "citefullauthor")
3570 // alternative name for "\\citeauthor*"
3571 command = "citeauthor*";
3573 // text before the citation
3575 // text after the citation
3577 get_cite_arguments(p, true, before, after);
3579 if (command == "cite") {
3580 // \cite without optional argument means
3581 // \citet, \cite with at least one optional
3582 // argument means \citep.
3583 if (before.empty() && after.empty())
3588 if (before.empty() && after == "[]")
3589 // avoid \citet[]{a}
3591 else if (before == "[]" && after == "[]") {
3592 // avoid \citet[][]{a}
3596 // remove the brackets around after and before
3597 if (!after.empty()) {
3599 after.erase(after.length() - 1, 1);
3600 after = convert_command_inset_arg(after);
3602 if (!before.empty()) {
3604 before.erase(before.length() - 1, 1);
3605 before = convert_command_inset_arg(before);
3607 begin_command_inset(os, "citation", command);
3608 os << "after " << '"' << after << '"' << "\n";
3609 os << "before " << '"' << before << '"' << "\n";
3611 << convert_command_inset_arg(p.verbatim_item())
3614 // Need to set the cite engine if natbib is loaded by
3615 // the document class directly
3616 if (preamble.citeEngine() == "basic")
3617 preamble.citeEngine("natbib");
3620 else if (use_jurabib &&
3621 is_known(t.cs(), known_jurabib_commands) &&
3622 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3623 context.check_layout(os);
3624 string command = t.cs();
3625 if (p.next_token().asInput() == "*") {
3629 char argumentOrder = '\0';
3630 vector<string> const options =
3631 preamble.getPackageOptions("jurabib");
3632 if (find(options.begin(), options.end(),
3633 "natbiborder") != options.end())
3634 argumentOrder = 'n';
3635 else if (find(options.begin(), options.end(),
3636 "jurabiborder") != options.end())
3637 argumentOrder = 'j';
3639 // text before the citation
3641 // text after the citation
3643 get_cite_arguments(p, argumentOrder != 'j', before, after);
3645 string const citation = p.verbatim_item();
3646 if (!before.empty() && argumentOrder == '\0') {
3647 cerr << "Warning: Assuming argument order "
3648 "of jurabib version 0.6 for\n'"
3649 << command << before << after << '{'
3650 << citation << "}'.\n"
3651 "Add 'jurabiborder' to the jurabib "
3652 "package options if you used an\n"
3653 "earlier jurabib version." << endl;
3655 if (!after.empty()) {
3657 after.erase(after.length() - 1, 1);
3659 if (!before.empty()) {
3661 before.erase(before.length() - 1, 1);
3663 begin_command_inset(os, "citation", command);
3664 os << "after " << '"' << after << '"' << "\n";
3665 os << "before " << '"' << before << '"' << "\n";
3666 os << "key " << '"' << citation << '"' << "\n";
3668 // Need to set the cite engine if jurabib is loaded by
3669 // the document class directly
3670 if (preamble.citeEngine() == "basic")
3671 preamble.citeEngine("jurabib");
3674 else if (t.cs() == "cite"
3675 || t.cs() == "nocite") {
3676 context.check_layout(os);
3677 string after = convert_command_inset_arg(p.getArg('[', ']'));
3678 string key = convert_command_inset_arg(p.verbatim_item());
3679 // store the case that it is "\nocite{*}" to use it later for
3682 begin_command_inset(os, "citation", t.cs());
3683 os << "after " << '"' << after << '"' << "\n";
3684 os << "key " << '"' << key << '"' << "\n";
3686 } else if (t.cs() == "nocite")
3690 else if (t.cs() == "index" ||
3691 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3692 context.check_layout(os);
3693 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3694 p.getArg('[', ']') : "";
3695 string const kind = arg.empty() ? "idx" : arg;
3696 begin_inset(os, "Index ");
3697 os << kind << "\nstatus collapsed\n";
3698 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3701 preamble.registerAutomaticallyLoadedPackage("splitidx");
3704 else if (t.cs() == "nomenclature") {
3705 context.check_layout(os);
3706 begin_command_inset(os, "nomenclature", "nomenclature");
3707 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3708 if (!prefix.empty())
3709 os << "prefix " << '"' << prefix << '"' << "\n";
3710 os << "symbol " << '"'
3711 << convert_command_inset_arg(p.verbatim_item());
3712 os << "\"\ndescription \""
3713 << convert_command_inset_arg(p.verbatim_item())
3716 preamble.registerAutomaticallyLoadedPackage("nomencl");
3719 else if (t.cs() == "label") {
3720 context.check_layout(os);
3721 begin_command_inset(os, "label", "label");
3723 << convert_command_inset_arg(p.verbatim_item())
3728 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3729 context.check_layout(os);
3730 string commandname = t.cs();
3732 if (p.next_token().asInput() == "*") {
3737 begin_command_inset(os, "index_print", commandname);
3738 string const indexname = p.getArg('[', ']');
3740 if (indexname.empty())
3741 os << "type \"idx\"\n";
3743 os << "type \"" << indexname << "\"\n";
3746 skip_spaces_braces(p);
3747 preamble.registerAutomaticallyLoadedPackage("makeidx");
3748 if (preamble.use_indices() == "true")
3749 preamble.registerAutomaticallyLoadedPackage("splitidx");
3752 else if (t.cs() == "printnomenclature") {
3754 string width_type = "";
3755 context.check_layout(os);
3756 begin_command_inset(os, "nomencl_print", "printnomenclature");
3757 // case of a custom width
3759 width = p.getArg('[', ']');
3760 width = translate_len(width);
3761 width_type = "custom";
3763 // case of no custom width
3764 // the case of no custom width but the width set
3765 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3766 // because the user could have set anything, not only the width
3767 // of the longest label (which would be width_type = "auto")
3768 string label = convert_command_inset_arg(p.getArg('{', '}'));
3769 if (label.empty() && width_type.empty())
3770 width_type = "none";
3771 os << "set_width \"" << width_type << "\"\n";
3772 if (width_type == "custom")
3773 os << "width \"" << width << '\"';
3775 skip_spaces_braces(p);
3776 preamble.registerAutomaticallyLoadedPackage("nomencl");
3779 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3780 context.check_layout(os);
3781 begin_inset(os, "script ");
3782 os << t.cs().substr(4) << '\n';
3783 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3784 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3786 if (t.cs() == "textsubscript")
3787 preamble.registerAutomaticallyLoadedPackage("subscript");
3790 else if ((where = is_known(t.cs(), known_quotes))) {
3791 context.check_layout(os);
3792 begin_inset(os, "Quotes ");
3793 os << known_coded_quotes[where - known_quotes];
3795 // LyX adds {} after the quote, so we have to eat
3796 // spaces here if there are any before a possible
3798 eat_whitespace(p, os, context, false);
3802 else if ((where = is_known(t.cs(), known_sizes)) &&
3803 context.new_layout_allowed) {
3804 context.check_layout(os);
3805 TeXFont const oldFont = context.font;
3806 context.font.size = known_coded_sizes[where - known_sizes];
3807 output_font_change(os, oldFont, context.font);
3808 eat_whitespace(p, os, context, false);
3811 else if ((where = is_known(t.cs(), known_font_families)) &&
3812 context.new_layout_allowed) {
3813 context.check_layout(os);
3814 TeXFont const oldFont = context.font;
3815 context.font.family =
3816 known_coded_font_families[where - known_font_families];
3817 output_font_change(os, oldFont, context.font);
3818 eat_whitespace(p, os, context, false);
3821 else if ((where = is_known(t.cs(), known_font_series)) &&
3822 context.new_layout_allowed) {
3823 context.check_layout(os);
3824 TeXFont const oldFont = context.font;
3825 context.font.series =
3826 known_coded_font_series[where - known_font_series];
3827 output_font_change(os, oldFont, context.font);
3828 eat_whitespace(p, os, context, false);
3831 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3832 context.new_layout_allowed) {
3833 context.check_layout(os);
3834 TeXFont const oldFont = context.font;
3835 context.font.shape =
3836 known_coded_font_shapes[where - known_font_shapes];
3837 output_font_change(os, oldFont, context.font);
3838 eat_whitespace(p, os, context, false);
3840 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3841 context.new_layout_allowed) {
3842 context.check_layout(os);
3843 TeXFont const oldFont = context.font;
3844 context.font.init();
3845 context.font.size = oldFont.size;
3846 context.font.family =
3847 known_coded_font_families[where - known_old_font_families];
3848 output_font_change(os, oldFont, context.font);
3849 eat_whitespace(p, os, context, false);
3852 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3853 context.new_layout_allowed) {
3854 context.check_layout(os);
3855 TeXFont const oldFont = context.font;
3856 context.font.init();
3857 context.font.size = oldFont.size;
3858 context.font.series =
3859 known_coded_font_series[where - known_old_font_series];
3860 output_font_change(os, oldFont, context.font);
3861 eat_whitespace(p, os, context, false);
3864 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3865 context.new_layout_allowed) {
3866 context.check_layout(os);
3867 TeXFont const oldFont = context.font;
3868 context.font.init();
3869 context.font.size = oldFont.size;
3870 context.font.shape =
3871 known_coded_font_shapes[where - known_old_font_shapes];
3872 output_font_change(os, oldFont, context.font);
3873 eat_whitespace(p, os, context, false);
3876 else if (t.cs() == "selectlanguage") {
3877 context.check_layout(os);
3878 // save the language for the case that a
3879 // \foreignlanguage is used
3880 context.font.language = babel2lyx(p.verbatim_item());
3881 os << "\n\\lang " << context.font.language << "\n";
3884 else if (t.cs() == "foreignlanguage") {
3885 string const lang = babel2lyx(p.verbatim_item());
3886 parse_text_attributes(p, os, FLAG_ITEM, outer,
3888 context.font.language, lang);
3891 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3892 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3893 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3895 // We have to output the whole command if it has an option
3896 // because LyX doesn't support this yet, see bug #8214,
3897 // only if there is a single option specifying a variant, we can handle it.
3899 string langopts = p.getOpt();
3900 // check if the option contains a variant, if yes, extract it
3901 string::size_type pos_var = langopts.find("variant");
3902 string::size_type i = langopts.find(',');
3903 string::size_type k = langopts.find('=', pos_var);
3904 if (pos_var != string::npos && i == string::npos) {
3906 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3907 lang = preamble.polyglossia2lyx(variant);
3908 parse_text_attributes(p, os, FLAG_ITEM, outer,
3910 context.font.language, lang);
3912 output_ert_inset(os, t.asInput() + langopts, context);
3914 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3915 parse_text_attributes(p, os, FLAG_ITEM, outer,
3917 context.font.language, lang);
3921 else if (t.cs() == "inputencoding") {
3922 // nothing to write here
3923 string const enc = subst(p.verbatim_item(), "\n", " ");
3924 p.setEncoding(enc, Encoding::inputenc);
3927 else if (is_known(t.cs(), known_special_chars) ||
3928 (t.cs() == "protect" &&
3929 p.next_token().cat() == catEscape &&
3930 is_known(p.next_token().cs(), known_special_protect_chars))) {
3931 // LyX sometimes puts a \protect in front, so we have to ignore it
3933 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3934 known_special_chars);
3935 context.check_layout(os);
3936 os << known_coded_special_chars[where - known_special_chars];
3937 skip_spaces_braces(p);
3940 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3941 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3942 p.next_next_token().asInput() == "-") ||
3943 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3944 // LyX sometimes puts a \protect in front, so we have to ignore it
3945 if (t.cs() == "protect")
3947 context.check_layout(os);
3948 if (t.cs() == "nobreakdash")
3949 os << "\\SpecialChar nobreakdash\n";
3951 os << "\\SpecialChar endofsentence\n";
3955 else if (t.cs() == "textquotedbl") {
3956 context.check_layout(os);
3961 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3962 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3963 || t.cs() == "%" || t.cs() == "-") {
3964 context.check_layout(os);
3966 os << "\\SpecialChar softhyphen\n";
3971 else if (t.cs() == "char") {
3972 context.check_layout(os);
3973 if (p.next_token().character() == '`') {
3975 if (p.next_token().cs() == "\"") {
3980 output_ert_inset(os, "\\char`", context);
3983 output_ert_inset(os, "\\char", context);
3987 else if (t.cs() == "verb") {
3988 context.check_layout(os);
3989 // set catcodes to verbatim early, just in case.
3990 p.setCatcodes(VERBATIM_CATCODES);
3991 string delim = p.get_token().asInput();
3992 Parser::Arg arg = p.verbatimStuff(delim);
3994 output_ert_inset(os, "\\verb" + delim
3995 + arg.second + delim, context);
3997 cerr << "invalid \\verb command. Skipping" << endl;
4000 // Problem: \= creates a tabstop inside the tabbing environment
4001 // and else an accent. In the latter case we really would want
4002 // \={o} instead of \= o.
4003 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4004 output_ert_inset(os, t.asInput(), context);
4006 else if (t.cs() == "\\") {
4007 context.check_layout(os);
4009 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4010 else if (p.next_token().asInput() == "*") {
4012 // getOpt() eats the following space if there
4013 // is no optional argument, but that is OK
4014 // here since it has no effect in the output.
4015 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4018 begin_inset(os, "Newline newline");
4023 else if (t.cs() == "newline" ||
4024 (t.cs() == "linebreak" && !p.hasOpt())) {
4025 context.check_layout(os);
4026 begin_inset(os, "Newline ");
4029 skip_spaces_braces(p);
4032 else if (t.cs() == "input" || t.cs() == "include"
4033 || t.cs() == "verbatiminput") {
4034 string name = t.cs();
4035 if (t.cs() == "verbatiminput"
4036 && p.next_token().asInput() == "*")
4037 name += p.get_token().asInput();
4038 context.check_layout(os);
4039 string filename(normalize_filename(p.getArg('{', '}')));
4040 string const path = getMasterFilePath(true);
4041 // We want to preserve relative / absolute filenames,
4042 // therefore path is only used for testing
4043 if ((t.cs() == "include" || t.cs() == "input") &&
4044 !makeAbsPath(filename, path).exists()) {
4045 // The file extension is probably missing.
4046 // Now try to find it out.
4047 string const tex_name =
4048 find_file(filename, path,
4049 known_tex_extensions);
4050 if (!tex_name.empty())
4051 filename = tex_name;
4053 bool external = false;
4055 if (makeAbsPath(filename, path).exists()) {
4056 string const abstexname =
4057 makeAbsPath(filename, path).absFileName();
4058 string const absfigname =
4059 changeExtension(abstexname, ".fig");
4060 fix_child_filename(filename);
4061 string const lyxname = changeExtension(filename,
4062 roundtripMode() ? ".lyx.lyx" : ".lyx");
4063 string const abslyxname = makeAbsPath(
4064 lyxname, getParentFilePath(false)).absFileName();
4066 if (!skipChildren())
4067 external = FileName(absfigname).exists();
4068 if (t.cs() == "input" && !skipChildren()) {
4069 string const ext = getExtension(abstexname);
4071 // Combined PS/LaTeX:
4072 // x.eps, x.pstex_t (old xfig)
4073 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4074 FileName const absepsname(
4075 changeExtension(abstexname, ".eps"));
4076 FileName const abspstexname(
4077 changeExtension(abstexname, ".pstex"));
4078 bool const xfigeps =
4079 (absepsname.exists() ||
4080 abspstexname.exists()) &&
4083 // Combined PDF/LaTeX:
4084 // x.pdf, x.pdftex_t (old xfig)
4085 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4086 FileName const abspdfname(
4087 changeExtension(abstexname, ".pdf"));
4088 bool const xfigpdf =
4089 abspdfname.exists() &&
4090 (ext == "pdftex_t" || ext == "pdf_t");
4094 // Combined PS/PDF/LaTeX:
4095 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4096 string const absbase2(
4097 removeExtension(abstexname) + "_pspdftex");
4098 FileName const abseps2name(
4099 addExtension(absbase2, ".eps"));
4100 FileName const abspdf2name(
4101 addExtension(absbase2, ".pdf"));
4102 bool const xfigboth =
4103 abspdf2name.exists() &&
4104 abseps2name.exists() && ext == "pspdftex";
4106 xfig = xfigpdf || xfigeps || xfigboth;
4107 external = external && xfig;
4110 outname = changeExtension(filename, ".fig");
4111 FileName abssrc(changeExtension(abstexname, ".fig"));
4112 copy_file(abssrc, outname);
4114 // Don't try to convert, the result
4115 // would be full of ERT.
4117 FileName abssrc(abstexname);
4118 copy_file(abssrc, outname);
4119 } else if (t.cs() != "verbatiminput" &&
4121 tex2lyx(abstexname, FileName(abslyxname),
4124 // no need to call copy_file
4125 // tex2lyx creates the file
4128 FileName abssrc(abstexname);
4129 copy_file(abssrc, outname);
4132 cerr << "Warning: Could not find included file '"
4133 << filename << "'." << endl;
4137 begin_inset(os, "External\n");
4138 os << "\ttemplate XFig\n"
4139 << "\tfilename " << outname << '\n';
4140 registerExternalTemplatePackages("XFig");
4142 begin_command_inset(os, "include", name);
4143 outname = subst(outname, "\"", "\\\"");
4144 os << "preview false\n"
4145 "filename \"" << outname << "\"\n";
4146 if (t.cs() == "verbatiminput")
4147 preamble.registerAutomaticallyLoadedPackage("verbatim");
4152 else if (t.cs() == "bibliographystyle") {
4153 // store new bibliographystyle
4154 bibliographystyle = p.verbatim_item();
4155 // If any other command than \bibliography, \addcontentsline
4156 // and \nocite{*} follows, we need to output the style
4157 // (because it might be used by that command).
4158 // Otherwise, it will automatically be output by LyX.
4161 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4162 if (t2.cat() == catBegin)
4164 if (t2.cat() != catEscape)
4166 if (t2.cs() == "nocite") {
4167 if (p.getArg('{', '}') == "*")
4169 } else if (t2.cs() == "bibliography")
4171 else if (t2.cs() == "phantomsection") {
4175 else if (t2.cs() == "addcontentsline") {
4176 // get the 3 arguments of \addcontentsline
4179 contentslineContent = p.getArg('{', '}');
4180 // if the last argument is not \refname we must output
4181 if (contentslineContent == "\\refname")
4188 output_ert_inset(os,
4189 "\\bibliographystyle{" + bibliographystyle + '}',
4194 else if (t.cs() == "phantomsection") {
4195 // we only support this if it occurs between
4196 // \bibliographystyle and \bibliography
4197 if (bibliographystyle.empty())
4198 output_ert_inset(os, "\\phantomsection", context);
4201 else if (t.cs() == "addcontentsline") {
4202 context.check_layout(os);
4203 // get the 3 arguments of \addcontentsline
4204 string const one = p.getArg('{', '}');
4205 string const two = p.getArg('{', '}');
4206 string const three = p.getArg('{', '}');
4207 // only if it is a \refname, we support if for the bibtex inset
4208 if (contentslineContent != "\\refname") {
4209 output_ert_inset(os,
4210 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4215 else if (t.cs() == "bibliography") {
4216 context.check_layout(os);
4218 begin_command_inset(os, "bibtex", "bibtex");
4219 if (!btprint.empty()) {
4220 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4221 // clear the string because the next BibTeX inset can be without the
4222 // \nocite{*} option
4225 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4226 // Do we have addcontentsline?
4227 if (contentslineContent == "\\refname") {
4228 BibOpts = "bibtotoc";
4229 // clear string because next BibTeX inset can be without addcontentsline
4230 contentslineContent.clear();
4232 // Do we have a bibliographystyle set?
4233 if (!bibliographystyle.empty()) {
4234 if (BibOpts.empty())
4235 BibOpts = bibliographystyle;
4237 BibOpts = BibOpts + ',' + bibliographystyle;
4238 // clear it because each bibtex entry has its style
4239 // and we need an empty string to handle \phantomsection
4240 bibliographystyle.clear();
4242 os << "options " << '"' << BibOpts << '"' << "\n";
4246 else if (t.cs() == "parbox") {
4247 // Test whether this is an outer box of a shaded box
4249 // swallow arguments
4250 while (p.hasOpt()) {
4252 p.skip_spaces(true);
4255 p.skip_spaces(true);
4257 if (p.next_token().cat() == catBegin)
4259 p.skip_spaces(true);
4260 Token to = p.get_token();
4261 bool shaded = false;
4262 if (to.asInput() == "\\begin") {
4263 p.skip_spaces(true);
4264 if (p.getArg('{', '}') == "shaded")
4269 parse_outer_box(p, os, FLAG_ITEM, outer,
4270 context, "parbox", "shaded");
4272 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4273 "", "", t.cs(), "", "");
4276 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4277 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4278 t.cs() == "shadowbox" || t.cs() == "doublebox")
4279 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4281 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4282 string backgroundcolor;
4283 preamble.registerAutomaticallyLoadedPackage("xcolor");
4284 if (t.cs() == "fcolorbox") {
4285 string const framecolor = p.getArg('{', '}');
4286 backgroundcolor = p.getArg('{', '}');
4287 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4289 backgroundcolor = p.getArg('{', '}');
4290 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4294 // FIXME: due to the compiler limit of "if" nestings
4295 // the code for the alignment was put here
4296 // put them in their own if if this is fixed
4297 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4298 || t.cs() == "shadowsize"
4299 || t.cs() == "raggedleft" || t.cs() == "centering"
4300 || t.cs() == "raggedright") {
4301 p.skip_spaces(true);
4302 if (t.cs() == "fboxrule")
4304 if (t.cs() == "fboxsep")
4306 if (t.cs() == "shadowsize")
4308 if (t.cs() != "raggedleft" && t.cs() != "centering"
4309 && t.cs() != "raggedright") {
4310 while (p.good() && p.next_token().cat() != catSpace
4311 && p.next_token().cat() != catNewline
4312 && p.next_token().cat() != catEscape) {
4313 if (t.cs() == "fboxrule")
4314 fboxrule = fboxrule + p.get_token().asInput();
4315 if (t.cs() == "fboxsep")
4316 fboxsep = fboxsep + p.get_token().asInput();
4317 if (t.cs() == "shadowsize")
4318 shadow_size = shadow_size + p.get_token().asInput();
4321 // we only handle them if they are in a box
4323 output_ert_inset(os, '\\' + t.cs() + ' ', context);
4325 wasBoxAlign = false;
4328 //\framebox() is part of the picture environment and different from \framebox{}
4329 //\framebox{} will be parsed by parse_outer_box
4330 else if (t.cs() == "framebox") {
4331 if (p.next_token().character() == '(') {
4332 //the syntax is: \framebox(x,y)[position]{content}
4333 string arg = t.asInput();
4334 arg += p.getFullParentheseArg();
4335 arg += p.getFullOpt();
4336 eat_whitespace(p, os, context, false);
4337 output_ert_inset(os, arg + '{', context);
4338 parse_text(p, os, FLAG_ITEM, outer, context);
4339 output_ert_inset(os, "}", context);
4341 //the syntax is: \framebox[width][position]{content}
4342 string special = p.getFullOpt();
4343 special += p.getOpt();
4344 parse_outer_box(p, os, FLAG_ITEM, outer,
4345 context, t.cs(), special);
4349 //\makebox() is part of the picture environment and different from \makebox{}
4350 //\makebox{} will be parsed by parse_box
4351 else if (t.cs() == "makebox") {
4352 if (p.next_token().character() == '(') {
4353 //the syntax is: \makebox(x,y)[position]{content}
4354 string arg = t.asInput();
4355 arg += p.getFullParentheseArg();
4356 arg += p.getFullOpt();
4357 eat_whitespace(p, os, context, false);
4358 output_ert_inset(os, arg + '{', context);
4359 parse_text(p, os, FLAG_ITEM, outer, context);
4360 output_ert_inset(os, "}", context);
4362 //the syntax is: \makebox[width][position]{content}
4363 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4364 "", "", t.cs(), "", "");
4367 else if (t.cs() == "smallskip" ||
4368 t.cs() == "medskip" ||
4369 t.cs() == "bigskip" ||
4370 t.cs() == "vfill") {
4371 context.check_layout(os);
4372 begin_inset(os, "VSpace ");
4375 skip_spaces_braces(p);
4378 else if ((where = is_known(t.cs(), known_spaces))) {
4379 context.check_layout(os);
4380 begin_inset(os, "space ");
4381 os << '\\' << known_coded_spaces[where - known_spaces]
4384 // LaTeX swallows whitespace after all spaces except
4385 // "\\,". We have to do that here, too, because LyX
4386 // adds "{}" which would make the spaces significant.
4388 eat_whitespace(p, os, context, false);
4389 // LyX adds "{}" after all spaces except "\\ " and
4390 // "\\,", so we have to remove "{}".
4391 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4392 // remove the braces after "\\,", too.
4397 else if (t.cs() == "newpage" ||
4398 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4399 t.cs() == "clearpage" ||
4400 t.cs() == "cleardoublepage") {
4401 context.check_layout(os);
4402 begin_inset(os, "Newpage ");
4405 skip_spaces_braces(p);
4408 else if (t.cs() == "DeclareRobustCommand" ||
4409 t.cs() == "DeclareRobustCommandx" ||
4410 t.cs() == "newcommand" ||
4411 t.cs() == "newcommandx" ||
4412 t.cs() == "providecommand" ||
4413 t.cs() == "providecommandx" ||
4414 t.cs() == "renewcommand" ||
4415 t.cs() == "renewcommandx") {
4416 // DeclareRobustCommand, DeclareRobustCommandx,
4417 // providecommand and providecommandx could be handled
4418 // by parse_command(), but we need to call
4419 // add_known_command() here.
4420 string name = t.asInput();
4421 if (p.next_token().asInput() == "*") {
4422 // Starred form. Eat '*'
4426 string const command = p.verbatim_item();
4427 string const opt1 = p.getFullOpt();
4428 string const opt2 = p.getFullOpt();
4429 add_known_command(command, opt1, !opt2.empty());
4430 string const ert = name + '{' + command + '}' +
4432 '{' + p.verbatim_item() + '}';
4434 if (t.cs() == "DeclareRobustCommand" ||
4435 t.cs() == "DeclareRobustCommandx" ||
4436 t.cs() == "providecommand" ||
4437 t.cs() == "providecommandx" ||
4438 name[name.length()-1] == '*')
4439 output_ert_inset(os, ert, context);
4441 context.check_layout(os);
4442 begin_inset(os, "FormulaMacro");
4448 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4449 // let could be handled by parse_command(),
4450 // but we need to call add_known_command() here.
4451 string ert = t.asInput();
4454 if (p.next_token().cat() == catBegin) {
4455 name = p.verbatim_item();
4456 ert += '{' + name + '}';
4458 name = p.verbatim_item();
4463 if (p.next_token().cat() == catBegin) {
4464 command = p.verbatim_item();
4465 ert += '{' + command + '}';
4467 command = p.verbatim_item();
4470 // If command is known, make name known too, to parse
4471 // its arguments correctly. For this reason we also
4472 // have commands in syntax.default that are hardcoded.
4473 CommandMap::iterator it = known_commands.find(command);
4474 if (it != known_commands.end())
4475 known_commands[t.asInput()] = it->second;
4476 output_ert_inset(os, ert, context);
4479 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4482 string name = t.asInput();
4483 string const length = p.verbatim_item();
4486 bool valid = splitLatexLength(length, valstring, unit);
4487 bool known_hspace = false;
4488 bool known_vspace = false;
4489 bool known_unit = false;
4492 istringstream iss(valstring);
4495 if (t.cs()[0] == 'h') {
4496 if (unit == "\\fill") {
4501 known_hspace = true;
4504 if (unit == "\\smallskipamount") {
4506 known_vspace = true;
4507 } else if (unit == "\\medskipamount") {
4509 known_vspace = true;
4510 } else if (unit == "\\bigskipamount") {
4512 known_vspace = true;
4513 } else if (unit == "\\fill") {
4515 known_vspace = true;
4519 if (!known_hspace && !known_vspace) {
4520 switch (unitFromString(unit)) {
4536 //unitFromString(unit) fails for relative units like Length::PCW
4537 // therefore handle them separately
4538 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4539 || unit == "\\textwidth" || unit == "\\linewidth"
4540 || unit == "\\textheight" || unit == "\\paperheight")
4548 // check for glue lengths
4549 bool is_gluelength = false;
4550 string gluelength = length;
4551 string::size_type i = length.find(" minus");
4552 if (i == string::npos) {
4553 i = length.find(" plus");
4554 if (i != string::npos)
4555 is_gluelength = true;
4557 is_gluelength = true;
4558 // if yes transform "9xx minus 8yy plus 7zz"
4560 if (is_gluelength) {
4561 i = gluelength.find(" minus");
4562 if (i != string::npos)
4563 gluelength.replace(i, 7, "-");
4564 i = gluelength.find(" plus");
4565 if (i != string::npos)
4566 gluelength.replace(i, 6, "+");
4569 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4570 // Literal horizontal length or known variable
4571 context.check_layout(os);
4572 begin_inset(os, "space ");
4580 if (known_unit && !known_hspace)
4581 os << "\n\\length " << translate_len(length);
4583 os << "\n\\length " << gluelength;
4585 } else if (known_unit || known_vspace || is_gluelength) {
4586 // Literal vertical length or known variable
4587 context.check_layout(os);
4588 begin_inset(os, "VSpace ");
4591 if (known_unit && !known_vspace)
4592 os << translate_len(length);
4599 // LyX can't handle other length variables in Inset VSpace/space
4604 output_ert_inset(os, name + '{' + unit + '}', context);
4605 else if (value == -1.0)
4606 output_ert_inset(os, name + "{-" + unit + '}', context);
4608 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4610 output_ert_inset(os, name + '{' + length + '}', context);
4614 // The single '=' is meant here.
4615 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4619 context.check_layout(os);
4620 docstring const name = newinsetlayout->name();
4621 bool const caption = name.find(from_ascii("Caption:")) == 0;
4623 begin_inset(os, "Caption ");
4624 os << to_utf8(name.substr(8)) << '\n';
4626 begin_inset(os, "Flex ");
4627 os << to_utf8(name) << '\n'
4628 << "status collapsed\n";
4630 if (newinsetlayout->isPassThru()) {
4631 // set catcodes to verbatim early, just in case.
4632 p.setCatcodes(VERBATIM_CATCODES);
4633 string delim = p.get_token().asInput();
4635 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4636 //FIXME: handle error condition
4637 string const arg = p.verbatimStuff("}").second;
4638 Context newcontext(true, context.textclass);
4639 if (newinsetlayout->forcePlainLayout())
4640 newcontext.layout = &context.textclass.plainLayout();
4641 output_ert(os, arg, newcontext);
4643 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4649 else if (t.cs() == "includepdf") {
4651 string const arg = p.getArg('[', ']');
4652 map<string, string> opts;
4653 vector<string> keys;
4654 split_map(arg, opts, keys);
4655 string name = normalize_filename(p.verbatim_item());
4656 string const path = getMasterFilePath(true);
4657 // We want to preserve relative / absolute filenames,
4658 // therefore path is only used for testing
4659 if (!makeAbsPath(name, path).exists()) {
4660 // The file extension is probably missing.
4661 // Now try to find it out.
4662 char const * const pdfpages_format[] = {"pdf", 0};
4663 string const pdftex_name =
4664 find_file(name, path, pdfpages_format);
4665 if (!pdftex_name.empty()) {
4670 FileName const absname = makeAbsPath(name, path);
4671 if (absname.exists())
4673 fix_child_filename(name);
4674 copy_file(absname, name);
4676 cerr << "Warning: Could not find file '"
4677 << name << "'." << endl;
4679 context.check_layout(os);
4680 begin_inset(os, "External\n\ttemplate ");
4681 os << "PDFPages\n\tfilename "
4683 // parse the options
4684 if (opts.find("pages") != opts.end())
4685 os << "\textra LaTeX \"pages="
4686 << opts["pages"] << "\"\n";
4687 if (opts.find("angle") != opts.end())
4688 os << "\trotateAngle "
4689 << opts["angle"] << '\n';
4690 if (opts.find("origin") != opts.end()) {
4692 string const opt = opts["origin"];
4693 if (opt == "tl") ss << "topleft";
4694 if (opt == "bl") ss << "bottomleft";
4695 if (opt == "Bl") ss << "baselineleft";
4696 if (opt == "c") ss << "center";
4697 if (opt == "tc") ss << "topcenter";
4698 if (opt == "bc") ss << "bottomcenter";
4699 if (opt == "Bc") ss << "baselinecenter";
4700 if (opt == "tr") ss << "topright";
4701 if (opt == "br") ss << "bottomright";
4702 if (opt == "Br") ss << "baselineright";
4703 if (!ss.str().empty())
4704 os << "\trotateOrigin " << ss.str() << '\n';
4706 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4708 if (opts.find("width") != opts.end())
4710 << translate_len(opts["width"]) << '\n';
4711 if (opts.find("height") != opts.end())
4713 << translate_len(opts["height"]) << '\n';
4714 if (opts.find("keepaspectratio") != opts.end())
4715 os << "\tkeepAspectRatio\n";
4717 context.check_layout(os);
4718 registerExternalTemplatePackages("PDFPages");
4721 else if (t.cs() == "loadgame") {
4723 string name = normalize_filename(p.verbatim_item());
4724 string const path = getMasterFilePath(true);
4725 // We want to preserve relative / absolute filenames,
4726 // therefore path is only used for testing
4727 if (!makeAbsPath(name, path).exists()) {
4728 // The file extension is probably missing.
4729 // Now try to find it out.
4730 char const * const lyxskak_format[] = {"fen", 0};
4731 string const lyxskak_name =
4732 find_file(name, path, lyxskak_format);
4733 if (!lyxskak_name.empty())
4734 name = lyxskak_name;
4736 FileName const absname = makeAbsPath(name, path);
4737 if (absname.exists())
4739 fix_child_filename(name);
4740 copy_file(absname, name);
4742 cerr << "Warning: Could not find file '"
4743 << name << "'." << endl;
4744 context.check_layout(os);
4745 begin_inset(os, "External\n\ttemplate ");
4746 os << "ChessDiagram\n\tfilename "
4749 context.check_layout(os);
4750 // after a \loadgame follows a \showboard
4751 if (p.get_token().asInput() == "showboard")
4753 registerExternalTemplatePackages("ChessDiagram");
4757 // try to see whether the string is in unicodesymbols
4758 // Only use text mode commands, since we are in text mode here,
4759 // and math commands may be invalid (bug 6797)
4760 string name = t.asInput();
4761 // handle the dingbats, cyrillic and greek
4762 if (name == "\\ding" || name == "\\textcyr" ||
4763 (name == "\\textgreek" && !preamble.usePolyglossia()))
4764 name = name + '{' + p.getArg('{', '}') + '}';
4765 // handle the ifsym characters
4766 else if (name == "\\textifsymbol") {
4767 string const optif = p.getFullOpt();
4768 string const argif = p.getArg('{', '}');
4769 name = name + optif + '{' + argif + '}';
4771 // handle the \ascii characters
4772 // the case of \ascii within braces, as LyX outputs it, is already
4773 // handled for t.cat() == catBegin
4774 else if (name == "\\ascii") {
4775 // the code is "\asci\xxx"
4776 name = "{" + name + p.get_token().asInput() + "}";
4779 // handle some TIPA special characters
4780 else if (preamble.isPackageUsed("tipa")) {
4781 if (name == "\\textglobfall") {
4784 } else if (name == "\\s") {
4785 // fromLaTeXCommand() does not yet
4786 // recognize tipa short cuts
4787 name = "\\textsyllabic";
4788 } else if (name == "\\=" &&
4789 p.next_token().asInput() == "*") {
4790 // fromLaTeXCommand() does not yet
4791 // recognize tipa short cuts
4794 } else if (name == "\\textdoublevertline") {
4795 // FIXME: This is not correct,
4796 // \textvertline is higher than \textbardbl
4797 name = "\\textbardbl";
4799 } else if (name == "\\!" ) {
4800 if (p.next_token().asInput() == "b") {
4801 p.get_token(); // eat 'b'
4804 } else if (p.next_token().asInput() == "d") {
4808 } else if (p.next_token().asInput() == "g") {
4812 } else if (p.next_token().asInput() == "G") {
4814 name = "\\texthtscg";
4816 } else if (p.next_token().asInput() == "j") {
4818 name = "\\texthtbardotlessj";
4820 } else if (p.next_token().asInput() == "o") {
4822 name = "\\textbullseye";
4825 } else if (name == "\\*" ) {
4826 if (p.next_token().asInput() == "k") {
4828 name = "\\textturnk";
4830 } else if (p.next_token().asInput() == "r") {
4831 p.get_token(); // eat 'b'
4832 name = "\\textturnr";
4834 } else if (p.next_token().asInput() == "t") {
4836 name = "\\textturnt";
4838 } else if (p.next_token().asInput() == "w") {
4840 name = "\\textturnw";
4845 if ((name.size() == 2 &&
4846 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4847 p.next_token().asInput() != "*") ||
4848 is_known(name.substr(1), known_tipa_marks)) {
4849 // name is a command that corresponds to a
4850 // combining character in unicodesymbols.
4851 // Append the argument, fromLaTeXCommand()
4852 // will either convert it to a single
4853 // character or a combining sequence.
4854 name += '{' + p.verbatim_item() + '}';
4856 // now get the character from unicodesymbols
4860 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4861 Encodings::TEXT_CMD, termination, rem, &req);
4863 context.check_layout(os);
4866 output_ert_inset(os, to_utf8(rem), context);
4868 skip_spaces_braces(p);
4869 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4870 preamble.registerAutomaticallyLoadedPackage(*it);
4872 //cerr << "#: " << t << " mode: " << mode << endl;
4873 // heuristic: read up to next non-nested space
4875 string s = t.asInput();
4876 string z = p.verbatim_item();
4877 while (p.good() && z != " " && !z.empty()) {
4878 //cerr << "read: " << z << endl;
4880 z = p.verbatim_item();
4882 cerr << "found ERT: " << s << endl;
4883 output_ert_inset(os, s + ' ', context);
4886 if (t.asInput() == name &&
4887 p.next_token().asInput() == "*") {
4888 // Starred commands like \vspace*{}
4889 p.get_token(); // Eat '*'
4892 if (!parse_command(name, p, os, outer, context))
4893 output_ert_inset(os, name, context);
4897 if (flags & FLAG_LEAVE) {
4898 flags &= ~FLAG_LEAVE;
4905 string guessLanguage(Parser & p, string const & lang)
4907 typedef std::map<std::string, size_t> LangMap;
4908 // map from language names to number of characters
4911 for (char const * const * i = supported_CJK_languages; *i; i++)
4912 used[string(*i)] = 0;
4915 Token const t = p.get_token();
4916 // comments are not counted for any language
4917 if (t.cat() == catComment)
4919 // commands are not counted as well, but we need to detect
4920 // \begin{CJK} and switch encoding if needed
4921 if (t.cat() == catEscape) {
4922 if (t.cs() == "inputencoding") {
4923 string const enc = subst(p.verbatim_item(), "\n", " ");
4924 p.setEncoding(enc, Encoding::inputenc);
4927 if (t.cs() != "begin")
4930 // Non-CJK content is counted for lang.
4931 // We do not care about the real language here:
4932 // If we have more non-CJK contents than CJK contents,
4933 // we simply use the language that was specified as
4934 // babel main language.
4935 used[lang] += t.asInput().length();
4938 // Now we are starting an environment
4940 string const name = p.getArg('{', '}');
4941 if (name != "CJK") {
4945 // It is a CJK environment
4947 /* name = */ p.getArg('{', '}');
4948 string const encoding = p.getArg('{', '}');
4949 /* mapping = */ p.getArg('{', '}');
4950 string const encoding_old = p.getEncoding();
4951 char const * const * const where =
4952 is_known(encoding, supported_CJK_encodings);
4954 p.setEncoding(encoding, Encoding::CJK);
4956 p.setEncoding("UTF-8");
4957 string const text = p.ertEnvironment("CJK");
4958 p.setEncoding(encoding_old);
4961 // ignore contents in unknown CJK encoding
4964 // the language of the text
4966 supported_CJK_languages[where - supported_CJK_encodings];
4967 used[cjk] += text.length();
4969 LangMap::const_iterator use = used.begin();
4970 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4971 if (it->second > use->second)