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 = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "sub", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
187 /// LaTeX names for quotes
188 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
189 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
190 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
191 "guilsinglleft", "frq", "guilsinglright", 0};
193 /// the same as known_quotes with .lyx names
194 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
195 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
196 "gld", "grd", "gls", "ers", "fls",
197 "fls", "frs", "frs", 0};
199 /// LaTeX names for font sizes
200 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
201 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
203 /// the same as known_sizes with .lyx names
204 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
205 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
207 /// LaTeX 2.09 names for font families
208 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
210 /// LaTeX names for font families
211 char const * const known_font_families[] = { "rmfamily", "sffamily",
214 /// LaTeX names for font family changing commands
215 char const * const known_text_font_families[] = { "textrm", "textsf",
218 /// The same as known_old_font_families, known_font_families and
219 /// known_text_font_families with .lyx names
220 char const * const known_coded_font_families[] = { "roman", "sans",
223 /// LaTeX 2.09 names for font series
224 char const * const known_old_font_series[] = { "bf", 0};
226 /// LaTeX names for font series
227 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
229 /// LaTeX names for font series changing commands
230 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
232 /// The same as known_old_font_series, known_font_series and
233 /// known_text_font_series with .lyx names
234 char const * const known_coded_font_series[] = { "bold", "medium", 0};
236 /// LaTeX 2.09 names for font shapes
237 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
239 /// LaTeX names for font shapes
240 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
243 /// LaTeX names for font shape changing commands
244 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
247 /// The same as known_old_font_shapes, known_font_shapes and
248 /// known_text_font_shapes with .lyx names
249 char const * const known_coded_font_shapes[] = { "italic", "slanted",
250 "smallcaps", "up", 0};
252 /// Known special characters which need skip_spaces_braces() afterwards
253 char const * const known_special_chars[] = {"ldots",
254 "lyxarrow", "textcompwordmark",
255 "slash", "textasciitilde", "textasciicircum", "textbackslash",
256 "LyX", "TeX", "LaTeXe",
259 /// special characters from known_special_chars which may have a \\protect before
260 char const * const known_special_protect_chars[] = {"LyX", "TeX",
261 "LaTeXe", "LaTeX", 0};
263 /// the same as known_special_chars with .lyx names
264 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
265 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
266 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
267 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
268 "\\SpecialChar LaTeX\n", 0};
271 * Graphics file extensions known by the dvips driver of the graphics package.
272 * These extensions are used to complete the filename of an included
273 * graphics file if it does not contain an extension.
274 * The order must be the same that latex uses to find a file, because we
275 * will use the first extension that matches.
276 * This is only an approximation for the common cases. If we would want to
277 * do it right in all cases, we would need to know which graphics driver is
278 * used and know the extensions of every driver of the graphics package.
280 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
281 "ps.gz", "eps.Z", "ps.Z", 0};
284 * Graphics file extensions known by the pdftex driver of the graphics package.
285 * \sa known_dvips_graphics_formats
287 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
291 * Known file extensions for TeX files as used by \\include.
293 char const * const known_tex_extensions[] = {"tex", 0};
295 /// spaces known by InsetSpace
296 char const * const known_spaces[] = { " ", "space", ",",
297 "thinspace", "quad", "qquad", "enspace", "enskip",
298 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
299 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
300 "upbracefill", "downbracefill", 0};
302 /// the same as known_spaces with .lyx names
303 char const * const known_coded_spaces[] = { "space{}", "space{}",
304 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
305 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
306 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
307 "upbracefill{}", "downbracefill{}", 0};
309 /// known TIPA combining diacritical marks
310 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
311 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
312 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
313 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
314 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
315 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
318 /// TIPA tones that need special handling
319 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
321 // string to store the float type to be able to determine the type of subfloats
322 string float_type = "";
325 /// splits "x=z, y=b" into a map and an ordered keyword vector
326 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
331 keys.resize(v.size());
332 for (size_t i = 0; i < v.size(); ++i) {
333 size_t const pos = v[i].find('=');
334 string const index = trimSpaceAndEol(v[i].substr(0, pos));
335 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
343 * Split a LaTeX length into value and unit.
344 * The latter can be a real unit like "pt", or a latex length variable
345 * like "\textwidth". The unit may contain additional stuff like glue
346 * lengths, but we don't care, because such lengths are ERT anyway.
347 * \returns true if \p value and \p unit are valid.
349 bool splitLatexLength(string const & len, string & value, string & unit)
353 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
354 //'4,5' is a valid LaTeX length number. Change it to '4.5'
355 string const length = subst(len, ',', '.');
356 if (i == string::npos)
359 if (len[0] == '\\') {
360 // We had something like \textwidth without a factor
366 value = trimSpaceAndEol(string(length, 0, i));
370 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
371 if (contains(len, '\\'))
372 unit = trimSpaceAndEol(string(len, i));
374 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
379 /// A simple function to translate a latex length to something LyX can
380 /// understand. Not perfect, but rather best-effort.
381 bool translate_len(string const & length, string & valstring, string & unit)
383 if (!splitLatexLength(length, valstring, unit))
385 // LyX uses percent values
387 istringstream iss(valstring);
392 string const percentval = oss.str();
394 if (unit.empty() || unit[0] != '\\')
396 string::size_type const i = unit.find(' ');
397 string const endlen = (i == string::npos) ? string() : string(unit, i);
398 if (unit == "\\textwidth") {
399 valstring = percentval;
400 unit = "text%" + endlen;
401 } else if (unit == "\\columnwidth") {
402 valstring = percentval;
403 unit = "col%" + endlen;
404 } else if (unit == "\\paperwidth") {
405 valstring = percentval;
406 unit = "page%" + endlen;
407 } else if (unit == "\\linewidth") {
408 valstring = percentval;
409 unit = "line%" + endlen;
410 } else if (unit == "\\paperheight") {
411 valstring = percentval;
412 unit = "pheight%" + endlen;
413 } else if (unit == "\\textheight") {
414 valstring = percentval;
415 unit = "theight%" + endlen;
423 string translate_len(string const & length)
427 if (translate_len(length, value, unit))
429 // If the input is invalid, return what we have.
437 * Translates a LaTeX length into \p value, \p unit and
438 * \p special parts suitable for a box inset.
439 * The difference from translate_len() is that a box inset knows about
440 * some special "units" that are stored in \p special.
442 void translate_box_len(string const & length, string & value, string & unit, string & special)
444 if (translate_len(length, value, unit)) {
445 if (unit == "\\height" || unit == "\\depth" ||
446 unit == "\\totalheight" || unit == "\\width") {
447 special = unit.substr(1);
448 // The unit is not used, but LyX requires a dummy setting
461 * Find a file with basename \p name in path \p path and an extension
464 string find_file(string const & name, string const & path,
465 char const * const * extensions)
467 for (char const * const * what = extensions; *what; ++what) {
468 string const trial = addExtension(name, *what);
469 if (makeAbsPath(trial, path).exists())
476 void begin_inset(ostream & os, string const & name)
478 os << "\n\\begin_inset " << name;
482 void begin_command_inset(ostream & os, string const & name,
483 string const & latexname)
485 begin_inset(os, "CommandInset ");
486 os << name << "\nLatexCommand " << latexname << '\n';
490 void end_inset(ostream & os)
492 os << "\n\\end_inset\n\n";
496 bool skip_braces(Parser & p)
498 if (p.next_token().cat() != catBegin)
501 if (p.next_token().cat() == catEnd) {
510 /// replace LaTeX commands in \p s from the unicodesymbols file with their
512 docstring convert_unicodesymbols(docstring s)
515 for (size_t i = 0; i < s.size();) {
524 docstring parsed = encodings.fromLaTeXCommand(s,
525 Encodings::TEXT_CMD, termination, rem, &req);
526 set<string>::const_iterator it = req.begin();
527 set<string>::const_iterator en = req.end();
528 for (; it != en; ++it)
529 preamble.registerAutomaticallyLoadedPackage(*it);
532 if (s.empty() || s[0] != '\\')
541 /// try to convert \p s to a valid InsetCommand argument
542 string convert_command_inset_arg(string s)
545 // since we don't know the input encoding we can't use from_utf8
546 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
547 // LyX cannot handle newlines in a latex command
548 return subst(s, "\n", " ");
552 void output_ert(ostream & os, string const & s, Context & context)
554 context.check_layout(os);
555 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
557 os << "\n\\backslash\n";
558 else if (*it == '\n') {
559 context.new_paragraph(os);
560 context.check_layout(os);
564 context.check_end_layout(os);
568 void output_ert_inset(ostream & os, string const & s, Context & context)
570 // We must have a valid layout before outputting the ERT inset.
571 context.check_layout(os);
572 Context newcontext(true, context.textclass);
573 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
574 if (layout.forcePlainLayout())
575 newcontext.layout = &context.textclass.plainLayout();
576 begin_inset(os, "ERT");
577 os << "\nstatus collapsed\n";
578 output_ert(os, s, newcontext);
583 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
585 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
588 if (checkModule(name, command))
589 return findLayoutWithoutModule(textclass, name, command);
594 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
596 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
599 if (checkModule(name, command))
600 return findInsetLayoutWithoutModule(textclass, name, command);
605 void eat_whitespace(Parser &, ostream &, Context &, bool);
609 * Skips whitespace and braces.
610 * This should be called after a command has been parsed that is not put into
611 * ERT, and where LyX adds "{}" if needed.
613 void skip_spaces_braces(Parser & p, bool keepws = false)
615 /* The following four examples produce the same typeset output and
616 should be handled by this function:
624 // Unfortunately we need to skip comments, too.
625 // We can't use eat_whitespace since writing them after the {}
626 // results in different output in some cases.
627 bool const skipped_spaces = p.skip_spaces(true);
628 bool const skipped_braces = skip_braces(p);
629 if (keepws && skipped_spaces && !skipped_braces)
630 // put back the space (it is better handled by check_space)
631 p.unskip_spaces(true);
635 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
636 Context & context, Layout::LaTeXArgMap const & latexargs)
639 context.check_layout(os);
644 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
645 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
646 for (; lait != laend; ++lait) {
648 eat_whitespace(p, os, context, false);
649 if (lait->second.mandatory) {
650 if (p.next_token().cat() != catBegin)
652 p.get_token(); // eat '{'
654 context.check_layout(os);
657 begin_inset(os, "Argument ");
660 os << i << "\nstatus collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
664 if (p.next_token().cat() == catEscape ||
665 p.next_token().character() != '[')
667 p.get_token(); // eat '['
669 context.check_layout(os);
672 begin_inset(os, "Argument ");
675 os << i << "\nstatus collapsed\n\n";
676 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
679 eat_whitespace(p, os, context, false);
684 void output_command_layout(ostream & os, Parser & p, bool outer,
685 Context & parent_context,
686 Layout const * newlayout)
688 TeXFont const oldFont = parent_context.font;
689 // save the current font size
690 string const size = oldFont.size;
691 // reset the font size to default, because the font size switches
692 // don't affect section headings and the like
693 parent_context.font.size = Context::normalfont.size;
694 // we only need to write the font change if we have an open layout
695 if (!parent_context.atParagraphStart())
696 output_font_change(os, oldFont, parent_context.font);
697 parent_context.check_end_layout(os);
698 Context context(true, parent_context.textclass, newlayout,
699 parent_context.layout, parent_context.font);
700 if (parent_context.deeper_paragraph) {
701 // We are beginning a nested environment after a
702 // deeper paragraph inside the outer list environment.
703 // Therefore we don't need to output a "begin deeper".
704 context.need_end_deeper = true;
706 context.check_deeper(os);
707 output_arguments(os, p, outer, true, false, context,
708 context.layout->latexargs());
709 parse_text(p, os, FLAG_ITEM, outer, context);
710 output_arguments(os, p, outer, false, true, context,
711 context.layout->postcommandargs());
712 context.check_end_layout(os);
713 if (parent_context.deeper_paragraph) {
714 // We must suppress the "end deeper" because we
715 // suppressed the "begin deeper" above.
716 context.need_end_deeper = false;
718 context.check_end_deeper(os);
719 // We don't need really a new paragraph, but
720 // we must make sure that the next item gets a \begin_layout.
721 parent_context.new_paragraph(os);
722 // Set the font size to the original value. No need to output it here
723 // (Context::begin_layout() will do that if needed)
724 parent_context.font.size = size;
729 * Output a space if necessary.
730 * This function gets called for every whitespace token.
732 * We have three cases here:
733 * 1. A space must be suppressed. Example: The lyxcode case below
734 * 2. A space may be suppressed. Example: Spaces before "\par"
735 * 3. A space must not be suppressed. Example: A space between two words
737 * We currently handle only 1. and 3 and from 2. only the case of
738 * spaces before newlines as a side effect.
740 * 2. could be used to suppress as many spaces as possible. This has two effects:
741 * - Reimporting LyX generated LaTeX files changes almost no whitespace
742 * - Superflous whitespace from non LyX generated LaTeX files is removed.
743 * The drawback is that the logic inside the function becomes
744 * complicated, and that is the reason why it is not implemented.
746 void check_space(Parser & p, ostream & os, Context & context)
748 Token const next = p.next_token();
749 Token const curr = p.curr_token();
750 // A space before a single newline and vice versa must be ignored
751 // LyX emits a newline before \end{lyxcode}.
752 // This newline must be ignored,
753 // otherwise LyX will add an additional protected space.
754 if (next.cat() == catSpace ||
755 next.cat() == catNewline ||
756 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
759 context.check_layout(os);
765 * Parse all arguments of \p command
767 void parse_arguments(string const & command,
768 vector<ArgumentType> const & template_arguments,
769 Parser & p, ostream & os, bool outer, Context & context)
771 string ert = command;
772 size_t no_arguments = template_arguments.size();
773 for (size_t i = 0; i < no_arguments; ++i) {
774 switch (template_arguments[i]) {
777 // This argument contains regular LaTeX
778 output_ert_inset(os, ert + '{', context);
779 eat_whitespace(p, os, context, false);
780 if (template_arguments[i] == required)
781 parse_text(p, os, FLAG_ITEM, outer, context);
783 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
787 // This argument consists only of a single item.
788 // The presence of '{' or not must be preserved.
790 if (p.next_token().cat() == catBegin)
791 ert += '{' + p.verbatim_item() + '}';
793 ert += p.verbatim_item();
797 // This argument may contain special characters
798 ert += '{' + p.verbatim_item() + '}';
802 // true because we must not eat whitespace
803 // if an optional arg follows we must not strip the
804 // brackets from this one
805 if (i < no_arguments - 1 &&
806 template_arguments[i+1] == optional)
807 ert += p.getFullOpt(true);
809 ert += p.getOpt(true);
813 output_ert_inset(os, ert, context);
818 * Check whether \p command is a known command. If yes,
819 * handle the command with all arguments.
820 * \return true if the command was parsed, false otherwise.
822 bool parse_command(string const & command, Parser & p, ostream & os,
823 bool outer, Context & context)
825 if (known_commands.find(command) != known_commands.end()) {
826 parse_arguments(command, known_commands[command], p, os,
834 /// Parses a minipage or parbox
835 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
836 unsigned inner_flags, bool outer, Context & parent_context,
837 string const & outer_type, string const & special,
838 string inner_type, string const & frame_color,
839 string const & background_color)
843 string hor_pos = "l";
844 // We need to set the height to the LaTeX default of 1\\totalheight
845 // for the case when no height argument is given
846 string height_value = "1";
847 string height_unit = "in";
848 string height_special = "totalheight";
853 string width_special = "none";
854 string thickness = "0.4pt";
856 thickness = fboxrule;
861 separation = fboxsep;
865 if (shadow_size != "")
866 shadowsize = shadow_size;
869 string framecolor = "black";
870 string backgroundcolor = "none";
871 if (frame_color != "")
872 framecolor = frame_color;
873 if (background_color != "")
874 backgroundcolor = background_color;
875 // if there is a color box around the \begin statements have not yet been parsed
877 if (frame_color != "" || background_color != "") {
878 eat_whitespace(p, os, parent_context, false);
879 p.get_token().asInput(); // the '{'
881 if (p.next_token().asInput() == "\\begin") {
882 p.get_token().asInput();
884 inner_type = "minipage";
885 inner_flags = FLAG_END;
888 else if (p.next_token().asInput() == "\\parbox") {
889 p.get_token().asInput();
890 inner_type = "parbox";
891 inner_flags = FLAG_ITEM;
894 else if (p.next_token().asInput() == "\\makebox") {
895 p.get_token().asInput();
896 inner_type = "makebox";
897 inner_flags = FLAG_ITEM;
899 // in case there is just \colorbox{color}{text}
902 inner_type = "makebox";
903 inner_flags = FLAG_BRACE_LAST;
908 if (!inner_type.empty() && p.hasOpt()) {
909 if (inner_type != "makebox")
910 position = p.getArg('[', ']');
912 latex_width = p.getArg('[', ']');
913 translate_box_len(latex_width, width_value, width_unit, width_special);
916 if (position != "t" && position != "c" && position != "b") {
917 cerr << "invalid position " << position << " for "
918 << inner_type << endl;
922 if (inner_type != "makebox") {
923 latex_height = p.getArg('[', ']');
924 translate_box_len(latex_height, height_value, height_unit, height_special);
926 string const opt = p.getArg('[', ']');
929 if (hor_pos != "l" && hor_pos != "c" &&
930 hor_pos != "r" && hor_pos != "s") {
931 cerr << "invalid hor_pos " << hor_pos
932 << " for " << inner_type << endl;
939 inner_pos = p.getArg('[', ']');
940 if (inner_pos != "c" && inner_pos != "t" &&
941 inner_pos != "b" && inner_pos != "s") {
942 cerr << "invalid inner_pos "
943 << inner_pos << " for "
944 << inner_type << endl;
945 inner_pos = position;
949 if (inner_type == "makebox")
953 if (inner_type.empty()) {
954 if (special.empty() && outer_type != "framebox")
955 latex_width = "1\\columnwidth";
958 latex_width = p2.getArg('[', ']');
959 string const opt = p2.getArg('[', ']');
962 if (hor_pos != "l" && hor_pos != "c" &&
963 hor_pos != "r" && hor_pos != "s") {
964 cerr << "invalid hor_pos " << hor_pos
965 << " for " << outer_type << endl;
969 if (outer_type == "framebox")
973 } else if (inner_type != "makebox")
974 latex_width = p.verbatim_item();
975 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
976 // as this is LyX's standard for such cases (except for makebox)
977 // \framebox is more special and handled below
978 if (latex_width.empty() && inner_type != "makebox"
979 && outer_type != "framebox")
980 latex_width = "1\\columnwidth";
982 translate_len(latex_width, width_value, width_unit);
984 bool shadedparbox = false;
985 if (inner_type == "shaded") {
986 eat_whitespace(p, os, parent_context, false);
987 if (outer_type == "parbox") {
989 if (p.next_token().cat() == catBegin)
991 eat_whitespace(p, os, parent_context, false);
997 // If we already read the inner box we have to push the inner env
998 if (!outer_type.empty() && !inner_type.empty() &&
999 (inner_flags & FLAG_END))
1000 active_environments.push_back(inner_type);
1001 bool use_ert = false;
1002 if (!outer_type.empty() && !inner_type.empty()) {
1003 // Look whether there is some content after the end of the
1004 // inner box, but before the end of the outer box.
1005 // If yes, we need to output ERT.
1007 if (inner_flags & FLAG_END)
1008 p.ertEnvironment(inner_type);
1011 p.skip_spaces(true);
1012 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1013 if ((outer_env && p.next_token().asInput() != "\\end") ||
1014 (!outer_env && p.next_token().cat() != catEnd)) {
1015 // something is between the end of the inner box and
1016 // the end of the outer box, so we need to use ERT.
1021 // if only \makebox{content} was used we can set its width to 1\width
1022 // because this identic and also identic to \mbox
1023 // this doesn't work for \framebox{content}, thus we have to use ERT for this
1024 if (latex_width.empty() && inner_type == "makebox" && background_color == "") {
1027 width_special = "width";
1028 } else if (latex_width.empty() && outer_type == "framebox") {
1029 width_value.clear();
1031 width_special = "none";
1035 if (!outer_type.empty()) {
1036 if (outer_flags & FLAG_END)
1037 ss << "\\begin{" << outer_type << '}';
1039 ss << '\\' << outer_type << '{';
1040 if (!special.empty())
1044 if (!inner_type.empty()) {
1045 if (inner_type != "shaded") {
1046 if (inner_flags & FLAG_END)
1047 ss << "\\begin{" << inner_type << '}';
1049 ss << '\\' << inner_type;
1051 if (!position.empty())
1052 ss << '[' << position << ']';
1053 if (!latex_height.empty())
1054 ss << '[' << latex_height << ']';
1055 if (!inner_pos.empty())
1056 ss << '[' << inner_pos << ']';
1057 ss << '{' << latex_width << '}';
1058 if (!(inner_flags & FLAG_END))
1061 if (inner_type == "shaded")
1062 ss << "\\begin{shaded}";
1063 output_ert_inset(os, ss.str(), parent_context);
1064 if (!inner_type.empty()) {
1065 parse_text(p, os, inner_flags, outer, parent_context);
1066 if (inner_flags & FLAG_END)
1067 output_ert_inset(os, "\\end{" + inner_type + '}',
1070 output_ert_inset(os, "}", parent_context);
1072 if (!outer_type.empty()) {
1073 // If we already read the inner box we have to pop
1075 if (!inner_type.empty() && (inner_flags & FLAG_END))
1076 active_environments.pop_back();
1078 // Ensure that the end of the outer box is parsed correctly:
1079 // The opening brace has been eaten by parse_outer_box()
1080 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1081 outer_flags &= ~FLAG_ITEM;
1082 outer_flags |= FLAG_BRACE_LAST;
1084 parse_text(p, os, outer_flags, outer, parent_context);
1085 if (outer_flags & FLAG_END)
1086 output_ert_inset(os, "\\end{" + outer_type + '}',
1089 output_ert_inset(os, "}", parent_context);
1092 // LyX does not like empty positions, so we have
1093 // to set them to the LaTeX default values here.
1094 if (position.empty())
1096 if (inner_pos.empty())
1097 inner_pos = position;
1098 parent_context.check_layout(os);
1099 begin_inset(os, "Box ");
1100 if (outer_type == "framed")
1102 else if (outer_type == "framebox" || outer_type == "fbox" || frame_color != "")
1104 else if (outer_type == "shadowbox")
1105 os << "Shadowbox\n";
1106 else if ((outer_type == "shaded" && inner_type.empty()) ||
1107 (outer_type == "minipage" && inner_type == "shaded") ||
1108 (outer_type == "parbox" && inner_type == "shaded")) {
1110 preamble.registerAutomaticallyLoadedPackage("color");
1111 } else if (outer_type == "doublebox")
1112 os << "Doublebox\n";
1113 else if (outer_type.empty() || outer_type == "mbox")
1114 os << "Frameless\n";
1116 os << outer_type << '\n';
1117 os << "position \"" << position << "\"\n";
1118 os << "hor_pos \"" << hor_pos << "\"\n";
1119 if (outer_type == "mbox")
1120 os << "has_inner_box 1\n";
1121 if (frame_color != "")
1122 os << "has_inner_box 0\n";
1124 os << "has_inner_box " << !inner_type.empty() << "\n";
1125 os << "inner_pos \"" << inner_pos << "\"\n";
1126 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1128 if (outer_type == "mbox")
1129 os << "use_makebox 1\n";
1130 if (frame_color != "")
1131 os << "use_makebox 0\n";
1133 os << "use_makebox " << (inner_type == "makebox") << '\n';
1134 if (outer_type == "mbox")
1135 os << "width \"\"\n";
1136 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1137 else if (contains(width_unit, '\\'))
1138 os << "width \"" << width_value << "in" << "\"\n";
1140 os << "width \"" << width_value << width_unit << "\"\n";
1141 if (contains(width_unit, '\\')) {
1142 width_unit.erase (0,1); // remove the leading '\'
1143 os << "special \"" << width_unit << "\"\n";
1145 os << "special \"" << width_special << "\"\n";
1146 if (contains(height_unit, '\\'))
1147 os << "height \"" << height_value << "in" << "\"\n";
1149 os << "height \"" << height_value << height_unit << "\"\n";
1150 os << "height_special \"" << height_special << "\"\n";
1151 os << "thickness \"" << thickness << "\"\n";
1152 os << "separation \"" << separation << "\"\n";
1153 os << "shadowsize \"" << shadowsize << "\"\n";
1154 os << "framecolor \"" << framecolor << "\"\n";
1155 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1156 os << "status open\n\n";
1158 // Unfortunately we can't use parse_text_in_inset:
1159 // InsetBox::forcePlainLayout() is hard coded and does not
1160 // use the inset layout. Apart from that do we call parse_text
1161 // up to two times, but need only one check_end_layout.
1162 bool const forcePlainLayout =
1163 (!inner_type.empty() || inner_type == "makebox") &&
1164 outer_type != "shaded" && outer_type != "framed";
1165 Context context(true, parent_context.textclass);
1166 if (forcePlainLayout)
1167 context.layout = &context.textclass.plainLayout();
1169 context.font = parent_context.font;
1171 // If we have no inner box the contents will be read with the outer box
1172 if (!inner_type.empty())
1173 parse_text(p, os, inner_flags, outer, context);
1175 // Ensure that the end of the outer box is parsed correctly:
1176 // The opening brace has been eaten by parse_outer_box()
1177 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1178 outer_flags &= ~FLAG_ITEM;
1179 outer_flags |= FLAG_BRACE_LAST;
1182 // Find end of outer box, output contents if inner_type is
1183 // empty and output possible comments
1184 if (!outer_type.empty()) {
1185 // If we already read the inner box we have to pop
1187 if (!inner_type.empty() && (inner_flags & FLAG_END))
1188 active_environments.pop_back();
1189 // This does not output anything but comments if
1190 // inner_type is not empty (see use_ert)
1191 parse_text(p, os, outer_flags, outer, context);
1194 context.check_end_layout(os);
1196 #ifdef PRESERVE_LAYOUT
1197 // LyX puts a % after the end of the minipage
1198 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1200 //output_ert_inset(os, "%dummy", parent_context);
1203 parent_context.new_paragraph(os);
1205 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1206 //output_ert_inset(os, "%dummy", parent_context);
1209 // We add a protected space if something real follows
1210 if (p.good() && p.next_token().cat() != catComment) {
1211 begin_inset(os, "space ~\n");
1217 if (inner_flags != FLAG_BRACE_LAST && (frame_color != "" || background_color != "")) {
1218 // in this case we have to eat the the closing brace of the color box
1219 p.get_token().asInput(); // the '}'
1221 if (p.next_token().asInput() == "}"
1222 && (fboxrule != "" || fboxsep != "" || shadow_size != "")) {
1223 // in this case we assume that the closing brace is from the box settings
1224 // therefore reset these values for the next box
1229 if (shadow_size != "")
1235 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1236 Context & parent_context, string const & outer_type,
1237 string const & special)
1239 eat_whitespace(p, os, parent_context, false);
1240 if (flags & FLAG_ITEM) {
1242 if (p.next_token().cat() == catBegin)
1245 cerr << "Warning: Ignoring missing '{' after \\"
1246 << outer_type << '.' << endl;
1247 eat_whitespace(p, os, parent_context, false);
1250 unsigned int inner_flags = 0;
1252 if (outer_type == "minipage" || outer_type == "parbox") {
1253 p.skip_spaces(true);
1254 while (p.hasOpt()) {
1256 p.skip_spaces(true);
1259 p.skip_spaces(true);
1260 if (outer_type == "parbox") {
1262 if (p.next_token().cat() == catBegin)
1264 p.skip_spaces(true);
1267 if (outer_type == "shaded" || outer_type == "mbox") {
1268 // These boxes never have an inner box
1270 } else if (p.next_token().asInput() == "\\parbox") {
1271 inner = p.get_token().cs();
1272 inner_flags = FLAG_ITEM;
1273 } else if (p.next_token().asInput() == "\\begin") {
1274 // Is this a minipage or shaded box?
1277 inner = p.getArg('{', '}');
1279 if (inner == "minipage" || inner == "shaded")
1280 inner_flags = FLAG_END;
1285 if (inner_flags == FLAG_END) {
1286 if (inner != "shaded")
1290 eat_whitespace(p, os, parent_context, false);
1292 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1293 outer_type, special, inner, "", "");
1295 if (inner_flags == FLAG_ITEM) {
1297 eat_whitespace(p, os, parent_context, false);
1299 parse_box(p, os, flags, inner_flags, outer, parent_context,
1300 outer_type, special, inner, "", "");
1305 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1307 parent_context.check_layout(os);
1308 begin_inset(os, "listings\n");
1310 string arg = p.verbatimOption();
1311 os << "lstparams " << '"' << arg << '"' << '\n';
1312 if (arg.find("\\color") != string::npos)
1313 preamble.registerAutomaticallyLoadedPackage("color");
1316 os << "inline true\n";
1318 os << "inline false\n";
1319 os << "status collapsed\n";
1320 Context context(true, parent_context.textclass);
1321 context.layout = &parent_context.textclass.plainLayout();
1324 // set catcodes to verbatim early, just in case.
1325 p.setCatcodes(VERBATIM_CATCODES);
1326 string delim = p.get_token().asInput();
1327 //FIXME: handler error condition
1328 s = p.verbatimStuff(delim).second;
1329 // context.new_paragraph(os);
1331 s = p.verbatimEnvironment("lstlisting");
1332 output_ert(os, s, context);
1337 /// parse an unknown environment
1338 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1339 unsigned flags, bool outer,
1340 Context & parent_context)
1342 if (name == "tabbing")
1343 // We need to remember that we have to handle '\=' specially
1344 flags |= FLAG_TABBING;
1346 // We need to translate font changes and paragraphs inside the
1347 // environment to ERT if we have a non standard font.
1348 // Otherwise things like
1349 // \large\begin{foo}\huge bar\end{foo}
1351 bool const specialfont =
1352 (parent_context.font != parent_context.normalfont);
1353 bool const new_layout_allowed = parent_context.new_layout_allowed;
1355 parent_context.new_layout_allowed = false;
1356 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1357 parse_text_snippet(p, os, flags, outer, parent_context);
1358 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1360 parent_context.new_layout_allowed = new_layout_allowed;
1364 void parse_environment(Parser & p, ostream & os, bool outer,
1365 string & last_env, Context & parent_context)
1367 Layout const * newlayout;
1368 InsetLayout const * newinsetlayout = 0;
1369 string const name = p.getArg('{', '}');
1370 const bool is_starred = suffixIs(name, '*');
1371 string const unstarred_name = rtrim(name, "*");
1372 active_environments.push_back(name);
1374 if (is_math_env(name)) {
1375 parent_context.check_layout(os);
1376 begin_inset(os, "Formula ");
1377 os << "\\begin{" << name << "}";
1378 parse_math(p, os, FLAG_END, MATH_MODE);
1379 os << "\\end{" << name << "}";
1381 if (is_display_math_env(name)) {
1382 // Prevent the conversion of a line break to a space
1383 // (bug 7668). This does not change the output, but
1384 // looks ugly in LyX.
1385 eat_whitespace(p, os, parent_context, false);
1389 else if (is_known(name, preamble.polyglossia_languages)) {
1390 // We must begin a new paragraph if not already done
1391 if (! parent_context.atParagraphStart()) {
1392 parent_context.check_end_layout(os);
1393 parent_context.new_paragraph(os);
1395 // save the language in the context so that it is
1396 // handled by parse_text
1397 parent_context.font.language = preamble.polyglossia2lyx(name);
1398 parse_text(p, os, FLAG_END, outer, parent_context);
1399 // Just in case the environment is empty
1400 parent_context.extra_stuff.erase();
1401 // We must begin a new paragraph to reset the language
1402 parent_context.new_paragraph(os);
1406 else if (unstarred_name == "tabular" || name == "longtable") {
1407 eat_whitespace(p, os, parent_context, false);
1408 string width = "0pt";
1409 if (name == "tabular*") {
1410 width = lyx::translate_len(p.getArg('{', '}'));
1411 eat_whitespace(p, os, parent_context, false);
1413 parent_context.check_layout(os);
1414 begin_inset(os, "Tabular ");
1415 handle_tabular(p, os, name, width, parent_context);
1420 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1421 eat_whitespace(p, os, parent_context, false);
1422 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1423 eat_whitespace(p, os, parent_context, false);
1424 parent_context.check_layout(os);
1425 begin_inset(os, "Float " + unstarred_name + "\n");
1426 // store the float type for subfloats
1427 // subfloats only work with figures and tables
1428 if (unstarred_name == "figure")
1429 float_type = unstarred_name;
1430 else if (unstarred_name == "table")
1431 float_type = unstarred_name;
1435 os << "placement " << opt << '\n';
1436 if (contains(opt, "H"))
1437 preamble.registerAutomaticallyLoadedPackage("float");
1439 Floating const & fl = parent_context.textclass.floats()
1440 .getType(unstarred_name);
1441 if (!fl.floattype().empty() && fl.usesFloatPkg())
1442 preamble.registerAutomaticallyLoadedPackage("float");
1445 os << "wide " << convert<string>(is_starred)
1446 << "\nsideways false"
1447 << "\nstatus open\n\n";
1448 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1450 // We don't need really a new paragraph, but
1451 // we must make sure that the next item gets a \begin_layout.
1452 parent_context.new_paragraph(os);
1454 // the float is parsed thus delete the type
1458 else if (unstarred_name == "sidewaysfigure"
1459 || unstarred_name == "sidewaystable") {
1460 eat_whitespace(p, os, parent_context, false);
1461 parent_context.check_layout(os);
1462 if (unstarred_name == "sidewaysfigure")
1463 begin_inset(os, "Float figure\n");
1465 begin_inset(os, "Float table\n");
1466 os << "wide " << convert<string>(is_starred)
1467 << "\nsideways true"
1468 << "\nstatus open\n\n";
1469 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1471 // We don't need really a new paragraph, but
1472 // we must make sure that the next item gets a \begin_layout.
1473 parent_context.new_paragraph(os);
1475 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1478 else if (name == "wrapfigure" || name == "wraptable") {
1479 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1480 eat_whitespace(p, os, parent_context, false);
1481 parent_context.check_layout(os);
1484 string overhang = "0col%";
1487 lines = p.getArg('[', ']');
1488 string const placement = p.getArg('{', '}');
1490 overhang = p.getArg('[', ']');
1491 string const width = p.getArg('{', '}');
1493 if (name == "wrapfigure")
1494 begin_inset(os, "Wrap figure\n");
1496 begin_inset(os, "Wrap table\n");
1497 os << "lines " << lines
1498 << "\nplacement " << placement
1499 << "\noverhang " << lyx::translate_len(overhang)
1500 << "\nwidth " << lyx::translate_len(width)
1501 << "\nstatus open\n\n";
1502 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1504 // We don't need really a new paragraph, but
1505 // we must make sure that the next item gets a \begin_layout.
1506 parent_context.new_paragraph(os);
1508 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1511 else if (name == "minipage") {
1512 eat_whitespace(p, os, parent_context, false);
1513 // Test whether this is an outer box of a shaded box
1515 // swallow arguments
1516 while (p.hasOpt()) {
1518 p.skip_spaces(true);
1521 p.skip_spaces(true);
1522 Token t = p.get_token();
1523 bool shaded = false;
1524 if (t.asInput() == "\\begin") {
1525 p.skip_spaces(true);
1526 if (p.getArg('{', '}') == "shaded")
1531 parse_outer_box(p, os, FLAG_END, outer,
1532 parent_context, name, "shaded");
1534 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1535 "", "", name, "", "");
1539 else if (name == "comment") {
1540 eat_whitespace(p, os, parent_context, false);
1541 parent_context.check_layout(os);
1542 begin_inset(os, "Note Comment\n");
1543 os << "status open\n";
1544 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1547 skip_braces(p); // eat {} that might by set by LyX behind comments
1548 preamble.registerAutomaticallyLoadedPackage("verbatim");
1551 else if (name == "verbatim") {
1552 // FIXME: this should go in the generic code that
1553 // handles environments defined in layout file that
1554 // have "PassThru 1". However, the code over there is
1555 // already too complicated for my taste.
1556 parent_context.new_paragraph(os);
1557 Context context(true, parent_context.textclass,
1558 &parent_context.textclass[from_ascii("Verbatim")]);
1559 string s = p.verbatimEnvironment("verbatim");
1560 output_ert(os, s, context);
1564 else if (name == "IPA") {
1565 eat_whitespace(p, os, parent_context, false);
1566 parent_context.check_layout(os);
1567 begin_inset(os, "IPA\n");
1568 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1571 preamble.registerAutomaticallyLoadedPackage("tipa");
1572 preamble.registerAutomaticallyLoadedPackage("tipx");
1575 else if (name == "CJK") {
1576 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1577 // It is impossible to decide if a CJK environment was in its own paragraph or within
1578 // a line. We therefore always assume a paragraph since the latter is a rare case.
1579 eat_whitespace(p, os, parent_context, false);
1580 parent_context.check_end_layout(os);
1581 // store the encoding to be able to reset it
1582 string const encoding_old = p.getEncoding();
1583 string const encoding = p.getArg('{', '}');
1584 // FIXME: For some reason JIS does not work. Although the text
1585 // in tests/CJK.tex is identical with the SJIS version if you
1586 // convert both snippets using the recode command line utility,
1587 // the resulting .lyx file contains some extra characters if
1588 // you set buggy_encoding to false for JIS.
1589 bool const buggy_encoding = encoding == "JIS";
1590 if (!buggy_encoding)
1591 p.setEncoding(encoding, Encoding::CJK);
1593 // FIXME: This will read garbage, since the data is not encoded in utf8.
1594 p.setEncoding("UTF-8");
1596 // LyX only supports the same mapping for all CJK
1597 // environments, so we might need to output everything as ERT
1598 string const mapping = trim(p.getArg('{', '}'));
1599 char const * const * const where =
1600 is_known(encoding, supported_CJK_encodings);
1601 if (!buggy_encoding && !preamble.fontCJKSet())
1602 preamble.fontCJK(mapping);
1603 bool knownMapping = mapping == preamble.fontCJK();
1604 if (buggy_encoding || !knownMapping || !where) {
1605 parent_context.check_layout(os);
1606 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1608 // we must parse the content as verbatim because e.g. JIS can contain
1609 // normally invalid characters
1610 // FIXME: This works only for the most simple cases.
1611 // Since TeX control characters are not parsed,
1612 // things like comments are completely wrong.
1613 string const s = p.plainEnvironment("CJK");
1614 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1616 output_ert_inset(os, "\\", parent_context);
1617 else if (*it == '$')
1618 output_ert_inset(os, "$", parent_context);
1619 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1624 output_ert_inset(os, "\\end{" + name + "}",
1628 supported_CJK_languages[where - supported_CJK_encodings];
1629 // store the language because we must reset it at the end
1630 string const lang_old = parent_context.font.language;
1631 parent_context.font.language = lang;
1632 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1633 parent_context.font.language = lang_old;
1634 parent_context.new_paragraph(os);
1636 p.setEncoding(encoding_old);
1640 else if (name == "lyxgreyedout") {
1641 eat_whitespace(p, os, parent_context, false);
1642 parent_context.check_layout(os);
1643 begin_inset(os, "Note Greyedout\n");
1644 os << "status open\n";
1645 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1648 if (!preamble.notefontcolor().empty())
1649 preamble.registerAutomaticallyLoadedPackage("color");
1652 else if (name == "btSect") {
1653 eat_whitespace(p, os, parent_context, false);
1654 parent_context.check_layout(os);
1655 begin_command_inset(os, "bibtex", "bibtex");
1656 string bibstyle = "plain";
1658 bibstyle = p.getArg('[', ']');
1659 p.skip_spaces(true);
1661 string const bibfile = p.getArg('{', '}');
1662 eat_whitespace(p, os, parent_context, false);
1663 Token t = p.get_token();
1664 if (t.asInput() == "\\btPrintCited") {
1665 p.skip_spaces(true);
1666 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1668 if (t.asInput() == "\\btPrintNotCited") {
1669 p.skip_spaces(true);
1670 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1672 if (t.asInput() == "\\btPrintAll") {
1673 p.skip_spaces(true);
1674 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1676 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1677 os << "options " << '"' << bibstyle << '"' << "\n";
1678 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1683 else if (name == "framed" || name == "shaded") {
1684 eat_whitespace(p, os, parent_context, false);
1685 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1689 else if (name == "lstlisting") {
1690 eat_whitespace(p, os, parent_context, false);
1691 parse_listings(p, os, parent_context, false);
1695 else if (!parent_context.new_layout_allowed)
1696 parse_unknown_environment(p, name, os, FLAG_END, outer,
1699 // Alignment and spacing settings
1700 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1701 // therefore are totally broken!
1702 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1703 // they are commands not environments. They are furthermore switches that
1704 // can be ended by another switches, but also by commands like \footnote or
1705 // \parbox. So the only safe way is to leave them untouched.
1706 else if (name == "center" || name == "centering" ||
1707 name == "flushleft" || name == "flushright" ||
1708 name == "singlespace" || name == "onehalfspace" ||
1709 name == "doublespace" || name == "spacing") {
1710 eat_whitespace(p, os, parent_context, false);
1711 // We must begin a new paragraph if not already done
1712 if (! parent_context.atParagraphStart()) {
1713 parent_context.check_end_layout(os);
1714 parent_context.new_paragraph(os);
1716 if (name == "flushleft")
1717 parent_context.add_extra_stuff("\\align left\n");
1718 else if (name == "flushright")
1719 parent_context.add_extra_stuff("\\align right\n");
1720 else if (name == "center" || name == "centering")
1721 parent_context.add_extra_stuff("\\align center\n");
1722 else if (name == "singlespace")
1723 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1724 else if (name == "onehalfspace") {
1725 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1726 preamble.registerAutomaticallyLoadedPackage("setspace");
1727 } else if (name == "doublespace") {
1728 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1729 preamble.registerAutomaticallyLoadedPackage("setspace");
1730 } else if (name == "spacing") {
1731 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1732 preamble.registerAutomaticallyLoadedPackage("setspace");
1734 parse_text(p, os, FLAG_END, outer, parent_context);
1735 // Just in case the environment is empty
1736 parent_context.extra_stuff.erase();
1737 // We must begin a new paragraph to reset the alignment
1738 parent_context.new_paragraph(os);
1742 // The single '=' is meant here.
1743 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1744 eat_whitespace(p, os, parent_context, false);
1745 Context context(true, parent_context.textclass, newlayout,
1746 parent_context.layout, parent_context.font);
1747 if (parent_context.deeper_paragraph) {
1748 // We are beginning a nested environment after a
1749 // deeper paragraph inside the outer list environment.
1750 // Therefore we don't need to output a "begin deeper".
1751 context.need_end_deeper = true;
1753 parent_context.check_end_layout(os);
1754 if (last_env == name) {
1755 // we need to output a separator since LyX would export
1756 // the two environments as one otherwise (bug 5716)
1757 TeX2LyXDocClass const & textclass(parent_context.textclass);
1758 Context newcontext(true, textclass,
1759 &(textclass.defaultLayout()));
1760 newcontext.check_layout(os);
1761 begin_inset(os, "Separator plain\n");
1763 newcontext.check_end_layout(os);
1765 switch (context.layout->latextype) {
1766 case LATEX_LIST_ENVIRONMENT:
1767 context.add_par_extra_stuff("\\labelwidthstring "
1768 + p.verbatim_item() + '\n');
1771 case LATEX_BIB_ENVIRONMENT:
1772 p.verbatim_item(); // swallow next arg
1778 context.check_deeper(os);
1779 // handle known optional and required arguments
1780 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1781 // It is impossible to place anything after the environment name,
1782 // but before the first \\item.
1783 if (context.layout->latextype == LATEX_ENVIRONMENT)
1784 output_arguments(os, p, outer, false, false, context,
1785 context.layout->latexargs());
1786 parse_text(p, os, FLAG_END, outer, context);
1787 if (context.layout->latextype == LATEX_ENVIRONMENT)
1788 output_arguments(os, p, outer, false, true, context,
1789 context.layout->postcommandargs());
1790 context.check_end_layout(os);
1791 if (parent_context.deeper_paragraph) {
1792 // We must suppress the "end deeper" because we
1793 // suppressed the "begin deeper" above.
1794 context.need_end_deeper = false;
1796 context.check_end_deeper(os);
1797 parent_context.new_paragraph(os);
1799 if (!preamble.titleLayoutFound())
1800 preamble.titleLayoutFound(newlayout->intitle);
1801 set<string> const & req = newlayout->requires();
1802 set<string>::const_iterator it = req.begin();
1803 set<string>::const_iterator en = req.end();
1804 for (; it != en; ++it)
1805 preamble.registerAutomaticallyLoadedPackage(*it);
1808 // The single '=' is meant here.
1809 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1810 eat_whitespace(p, os, parent_context, false);
1811 parent_context.check_layout(os);
1812 begin_inset(os, "Flex ");
1813 os << to_utf8(newinsetlayout->name()) << '\n'
1814 << "status collapsed\n";
1815 if (newinsetlayout->isPassThru()) {
1816 string const arg = p.verbatimEnvironment(name);
1817 Context context(true, parent_context.textclass,
1818 &parent_context.textclass.plainLayout(),
1819 parent_context.layout);
1820 output_ert(os, arg, parent_context);
1822 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1826 else if (name == "appendix") {
1827 // This is no good latex style, but it works and is used in some documents...
1828 eat_whitespace(p, os, parent_context, false);
1829 parent_context.check_end_layout(os);
1830 Context context(true, parent_context.textclass, parent_context.layout,
1831 parent_context.layout, parent_context.font);
1832 context.check_layout(os);
1833 os << "\\start_of_appendix\n";
1834 parse_text(p, os, FLAG_END, outer, context);
1835 context.check_end_layout(os);
1839 else if (known_environments.find(name) != known_environments.end()) {
1840 vector<ArgumentType> arguments = known_environments[name];
1841 // The last "argument" denotes wether we may translate the
1842 // environment contents to LyX
1843 // The default required if no argument is given makes us
1844 // compatible with the reLyXre environment.
1845 ArgumentType contents = arguments.empty() ?
1848 if (!arguments.empty())
1849 arguments.pop_back();
1850 // See comment in parse_unknown_environment()
1851 bool const specialfont =
1852 (parent_context.font != parent_context.normalfont);
1853 bool const new_layout_allowed =
1854 parent_context.new_layout_allowed;
1856 parent_context.new_layout_allowed = false;
1857 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1858 outer, parent_context);
1859 if (contents == verbatim)
1860 output_ert_inset(os, p.ertEnvironment(name),
1863 parse_text_snippet(p, os, FLAG_END, outer,
1865 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1867 parent_context.new_layout_allowed = new_layout_allowed;
1871 parse_unknown_environment(p, name, os, FLAG_END, outer,
1875 active_environments.pop_back();
1879 /// parses a comment and outputs it to \p os.
1880 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1882 LASSERT(t.cat() == catComment, return);
1883 if (!t.cs().empty()) {
1884 context.check_layout(os);
1885 output_ert_inset(os, '%' + t.cs(), context);
1886 if (p.next_token().cat() == catNewline) {
1887 // A newline after a comment line starts a new
1889 if (context.new_layout_allowed) {
1890 if(!context.atParagraphStart())
1891 // Only start a new paragraph if not already
1892 // done (we might get called recursively)
1893 context.new_paragraph(os);
1895 output_ert_inset(os, "\n", context);
1896 eat_whitespace(p, os, context, true);
1899 // "%\n" combination
1906 * Reads spaces and comments until the first non-space, non-comment token.
1907 * New paragraphs (double newlines or \\par) are handled like simple spaces
1908 * if \p eatParagraph is true.
1909 * Spaces are skipped, but comments are written to \p os.
1911 void eat_whitespace(Parser & p, ostream & os, Context & context,
1915 Token const & t = p.get_token();
1916 if (t.cat() == catComment)
1917 parse_comment(p, os, t, context);
1918 else if ((! eatParagraph && p.isParagraph()) ||
1919 (t.cat() != catSpace && t.cat() != catNewline)) {
1928 * Set a font attribute, parse text and reset the font attribute.
1929 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1930 * \param currentvalue Current value of the attribute. Is set to the new
1931 * value during parsing.
1932 * \param newvalue New value of the attribute
1934 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1935 Context & context, string const & attribute,
1936 string & currentvalue, string const & newvalue)
1938 context.check_layout(os);
1939 string const oldvalue = currentvalue;
1940 currentvalue = newvalue;
1941 os << '\n' << attribute << ' ' << newvalue << "\n";
1942 parse_text_snippet(p, os, flags, outer, context);
1943 context.check_layout(os);
1944 os << '\n' << attribute << ' ' << oldvalue << "\n";
1945 currentvalue = oldvalue;
1949 /// get the arguments of a natbib or jurabib citation command
1950 void get_cite_arguments(Parser & p, bool natbibOrder,
1951 string & before, string & after)
1953 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1955 // text before the citation
1957 // text after the citation
1958 after = p.getFullOpt();
1960 if (!after.empty()) {
1961 before = p.getFullOpt();
1962 if (natbibOrder && !before.empty())
1963 swap(before, after);
1968 /// Convert filenames with TeX macros and/or quotes to something LyX
1970 string const normalize_filename(string const & name)
1975 Token const & t = p.get_token();
1976 if (t.cat() != catEscape)
1978 else if (t.cs() == "lyxdot") {
1979 // This is used by LyX for simple dots in relative
1983 } else if (t.cs() == "space") {
1986 } else if (t.cs() == "string") {
1987 // Convert \string" to " and \string~ to ~
1988 Token const & n = p.next_token();
1989 if (n.asInput() != "\"" && n.asInput() != "~")
1994 // Strip quotes. This is a bit complicated (see latex_path()).
1995 string full = os.str();
1996 if (!full.empty() && full[0] == '"') {
1997 string base = removeExtension(full);
1998 string ext = getExtension(full);
1999 if (!base.empty() && base[base.length()-1] == '"')
2002 return addExtension(trim(base, "\""), ext);
2003 if (full[full.length()-1] == '"')
2006 return trim(full, "\"");
2012 /// Convert \p name from TeX convention (relative to master file) to LyX
2013 /// convention (relative to .lyx file) if it is relative
2014 void fix_child_filename(string & name)
2016 string const absMasterTeX = getMasterFilePath(true);
2017 bool const isabs = FileName::isAbsolute(name);
2018 // convert from "relative to .tex master" to absolute original path
2020 name = makeAbsPath(name, absMasterTeX).absFileName();
2021 bool copyfile = copyFiles();
2022 string const absParentLyX = getParentFilePath(false);
2025 // convert from absolute original path to "relative to master file"
2026 string const rel = to_utf8(makeRelPath(from_utf8(name),
2027 from_utf8(absMasterTeX)));
2028 // re-interpret "relative to .tex file" as "relative to .lyx file"
2029 // (is different if the master .lyx file resides in a
2030 // different path than the master .tex file)
2031 string const absMasterLyX = getMasterFilePath(false);
2032 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2033 // Do not copy if the new path is impossible to create. Example:
2034 // absMasterTeX = "/foo/bar/"
2035 // absMasterLyX = "/bar/"
2036 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2037 if (contains(name, "/../"))
2044 // convert from absolute original path to
2045 // "relative to .lyx file"
2046 name = to_utf8(makeRelPath(from_utf8(abs),
2047 from_utf8(absParentLyX)));
2051 // convert from absolute original path to "relative to .lyx file"
2052 name = to_utf8(makeRelPath(from_utf8(name),
2053 from_utf8(absParentLyX)));
2058 void copy_file(FileName const & src, string dstname)
2062 string const absParent = getParentFilePath(false);
2064 if (FileName::isAbsolute(dstname))
2065 dst = FileName(dstname);
2067 dst = makeAbsPath(dstname, absParent);
2068 string const absMaster = getMasterFilePath(false);
2069 FileName const srcpath = src.onlyPath();
2070 FileName const dstpath = dst.onlyPath();
2071 if (equivalent(srcpath, dstpath))
2073 if (!dstpath.isDirectory()) {
2074 if (!dstpath.createPath()) {
2075 cerr << "Warning: Could not create directory for file `"
2076 << dst.absFileName() << "´." << endl;
2080 if (dst.isReadableFile()) {
2081 if (overwriteFiles())
2082 cerr << "Warning: Overwriting existing file `"
2083 << dst.absFileName() << "´." << endl;
2085 cerr << "Warning: Not overwriting existing file `"
2086 << dst.absFileName() << "´." << endl;
2090 if (!src.copyTo(dst))
2091 cerr << "Warning: Could not copy file `" << src.absFileName()
2092 << "´ to `" << dst.absFileName() << "´." << endl;
2096 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2097 bool parse_chunk(Parser & p, ostream & os, Context & context)
2099 // check whether a chunk is possible here.
2100 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2106 // read the parameters
2107 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2108 if (!params.first) {
2113 Parser::Arg const code = p.verbatimStuff("\n@");
2118 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2119 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2123 // The last newline read is important for paragraph handling
2127 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2128 // We must have a valid layout before outputting the Chunk inset.
2129 context.check_layout(os);
2130 Context chunkcontext(true, context.textclass);
2131 chunkcontext.layout = &context.textclass.plainLayout();
2132 begin_inset(os, "Flex Chunk");
2133 os << "\nstatus open\n";
2134 if (!params.second.empty()) {
2135 chunkcontext.check_layout(os);
2136 Context paramscontext(true, context.textclass);
2137 paramscontext.layout = &context.textclass.plainLayout();
2138 begin_inset(os, "Argument 1");
2139 os << "\nstatus open\n";
2140 output_ert(os, params.second, paramscontext);
2143 output_ert(os, code.second, chunkcontext);
2151 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2152 bool is_macro(Parser & p)
2154 Token first = p.curr_token();
2155 if (first.cat() != catEscape || !p.good())
2157 if (first.cs() == "def")
2159 if (first.cs() != "global" && first.cs() != "long")
2161 Token second = p.get_token();
2163 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2164 second.cat() == catNewline || second.cat() == catComment)) {
2165 second = p.get_token();
2168 bool secondvalid = second.cat() == catEscape;
2170 bool thirdvalid = false;
2171 if (p.good() && first.cs() == "global" && secondvalid &&
2172 second.cs() == "long") {
2173 third = p.get_token();
2175 while (p.good() && !p.isParagraph() &&
2176 (third.cat() == catSpace ||
2177 third.cat() == catNewline ||
2178 third.cat() == catComment)) {
2179 third = p.get_token();
2182 thirdvalid = third.cat() == catEscape;
2184 for (int i = 0; i < pos; ++i)
2189 return (first.cs() == "global" || first.cs() == "long") &&
2190 second.cs() == "def";
2191 return first.cs() == "global" && second.cs() == "long" &&
2192 third.cs() == "def";
2196 /// Parse a macro definition (assumes that is_macro() returned true)
2197 void parse_macro(Parser & p, ostream & os, Context & context)
2199 context.check_layout(os);
2200 Token first = p.curr_token();
2203 string command = first.asInput();
2204 if (first.cs() != "def") {
2206 eat_whitespace(p, os, context, false);
2207 second = p.curr_token();
2208 command += second.asInput();
2209 if (second.cs() != "def") {
2211 eat_whitespace(p, os, context, false);
2212 third = p.curr_token();
2213 command += third.asInput();
2216 eat_whitespace(p, os, context, false);
2217 string const name = p.get_token().cs();
2218 eat_whitespace(p, os, context, false);
2224 while (p.next_token().cat() != catBegin) {
2225 if (p.next_token().cat() == catParameter) {
2230 // followed by number?
2231 if (p.next_token().cat() == catOther) {
2232 string s = p.get_token().asInput();
2234 // number = current arity + 1?
2235 if (s.size() == 1 && s[0] == arity + '0' + 1)
2240 paramtext += p.get_token().cs();
2242 paramtext += p.get_token().cs();
2247 // only output simple (i.e. compatible) macro as FormulaMacros
2248 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2250 context.check_layout(os);
2251 begin_inset(os, "FormulaMacro");
2252 os << "\n\\def" << ert;
2255 output_ert_inset(os, command + ert, context);
2259 void registerExternalTemplatePackages(string const & name)
2261 external::TemplateManager const & etm = external::TemplateManager::get();
2262 external::Template const * const et = etm.getTemplateByName(name);
2265 external::Template::Formats::const_iterator cit = et->formats.end();
2267 cit = et->formats.find("PDFLaTeX");
2268 if (cit == et->formats.end())
2269 // If the template has not specified a PDFLaTeX output,
2270 // we try the LaTeX format.
2271 cit = et->formats.find("LaTeX");
2272 if (cit == et->formats.end())
2274 vector<string>::const_iterator qit = cit->second.requirements.begin();
2275 vector<string>::const_iterator qend = cit->second.requirements.end();
2276 for (; qit != qend; ++qit)
2277 preamble.registerAutomaticallyLoadedPackage(*qit);
2280 } // anonymous namespace
2283 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2286 Layout const * newlayout = 0;
2287 InsetLayout const * newinsetlayout = 0;
2288 char const * const * where = 0;
2289 // Store the latest bibliographystyle, addcontentslineContent and
2290 // nocite{*} option (needed for bibtex inset)
2292 string contentslineContent;
2293 string bibliographystyle = "default";
2294 bool const use_natbib = isProvided("natbib");
2295 bool const use_jurabib = isProvided("jurabib");
2298 // it is impossible to determine the correct encoding for non-CJK Japanese.
2299 // Therefore write a note at the beginning of the document
2300 if (is_nonCJKJapanese) {
2301 context.check_layout(os);
2302 begin_inset(os, "Note Note\n");
2303 os << "status open\n\\begin_layout Plain Layout\n"
2304 << "\\series bold\n"
2305 << "Important information:\n"
2306 << "\\end_layout\n\n"
2307 << "\\begin_layout Plain Layout\n"
2308 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2309 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2310 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2311 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2312 << " and specify the encoding using the -e command-line switch.\n"
2313 << " In addition, you might want to double check that the desired output encoding\n"
2314 << " is correctly selected in Document > Settings > Language.\n"
2315 << "\\end_layout\n";
2317 is_nonCJKJapanese = false;
2321 Token const & t = p.get_token();
2323 debugToken(cerr, t, flags);
2326 if (flags & FLAG_ITEM) {
2327 if (t.cat() == catSpace)
2330 flags &= ~FLAG_ITEM;
2331 if (t.cat() == catBegin) {
2332 // skip the brace and collect everything to the next matching
2334 flags |= FLAG_BRACE_LAST;
2338 // handle only this single token, leave the loop if done
2339 flags |= FLAG_LEAVE;
2342 if (t.cat() != catEscape && t.character() == ']' &&
2343 (flags & FLAG_BRACK_LAST))
2345 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2348 // If there is anything between \end{env} and \begin{env} we
2349 // don't need to output a separator.
2350 if (t.cat() != catSpace && t.cat() != catNewline &&
2351 t.asInput() != "\\begin")
2357 bool const starred = p.next_token().asInput() == "*";
2358 string const starredname(starred ? (t.cs() + '*') : t.cs());
2359 if (t.cat() == catMath) {
2360 // we are inside some text mode thingy, so opening new math is allowed
2361 context.check_layout(os);
2362 begin_inset(os, "Formula ");
2363 Token const & n = p.get_token();
2364 bool const display(n.cat() == catMath && outer);
2366 // TeX's $$...$$ syntax for displayed math
2368 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2370 p.get_token(); // skip the second '$' token
2372 // simple $...$ stuff
2375 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2380 // Prevent the conversion of a line break to a
2381 // space (bug 7668). This does not change the
2382 // output, but looks ugly in LyX.
2383 eat_whitespace(p, os, context, false);
2387 else if (t.cat() == catSuper || t.cat() == catSub)
2388 cerr << "catcode " << t << " illegal in text mode\n";
2390 // Basic support for english quotes. This should be
2391 // extended to other quotes, but is not so easy (a
2392 // left english quote is the same as a right german
2394 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2395 context.check_layout(os);
2396 begin_inset(os, "Quotes ");
2402 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2403 context.check_layout(os);
2404 begin_inset(os, "Quotes ");
2411 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2412 context.check_layout(os);
2413 begin_inset(os, "Quotes ");
2420 else if (t.asInput() == "<"
2421 && p.next_token().asInput() == "<") {
2422 bool has_chunk = false;
2426 has_chunk = parse_chunk(p, os, context);
2432 context.check_layout(os);
2433 begin_inset(os, "Quotes ");
2434 //FIXME: this is a right danish quote;
2435 // why not a left french quote?
2443 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2444 check_space(p, os, context);
2446 else if (t.character() == '[' && noweb_mode &&
2447 p.next_token().character() == '[') {
2448 // These can contain underscores
2450 string const s = p.getFullOpt() + ']';
2451 if (p.next_token().character() == ']')
2454 cerr << "Warning: Inserting missing ']' in '"
2455 << s << "'." << endl;
2456 output_ert_inset(os, s, context);
2459 else if (t.cat() == catLetter) {
2460 context.check_layout(os);
2464 else if (t.cat() == catOther ||
2465 t.cat() == catAlign ||
2466 t.cat() == catParameter) {
2467 context.check_layout(os);
2468 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2469 context.merging_hyphens_allowed &&
2470 context.font.family != "ttfamily" &&
2471 !context.layout->pass_thru) {
2472 if (p.next_next_token().asInput() == "-") {
2474 os << to_utf8(docstring(1, 0x2014));
2478 os << to_utf8(docstring(1, 0x2013));
2481 // This translates "&" to "\\&" which may be wrong...
2485 else if (p.isParagraph()) {
2486 if (context.new_layout_allowed)
2487 context.new_paragraph(os);
2489 output_ert_inset(os, "\\par ", context);
2490 eat_whitespace(p, os, context, true);
2493 else if (t.cat() == catActive) {
2494 context.check_layout(os);
2495 if (t.character() == '~') {
2496 if (context.layout->free_spacing)
2499 begin_inset(os, "space ~\n");
2506 else if (t.cat() == catBegin) {
2507 Token const next = p.next_token();
2508 Token const end = p.next_next_token();
2509 if (next.cat() == catEnd) {
2511 Token const prev = p.prev_token();
2513 if (p.next_token().character() == '`')
2514 ; // ignore it in {}``
2516 output_ert_inset(os, "{}", context);
2517 } else if (next.cat() == catEscape &&
2518 is_known(next.cs(), known_quotes) &&
2519 end.cat() == catEnd) {
2520 // Something like {\textquoteright} (e.g.
2521 // from writer2latex). LyX writes
2522 // \textquoteright{}, so we may skip the
2523 // braces here for better readability.
2524 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2526 } else if (p.next_token().asInput() == "\\ascii") {
2527 // handle the \ascii characters
2528 // (the case without braces is handled later)
2529 // the code is "{\ascii\xxx}"
2530 p.get_token(); // eat \ascii
2531 string name2 = p.get_token().asInput();
2532 p.get_token(); // eat the final '}'
2533 string const name = "{\\ascii" + name2 + "}";
2537 // get the character from unicodesymbols
2538 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2539 Encodings::TEXT_CMD, termination, rem, &req);
2541 context.check_layout(os);
2544 output_ert_inset(os,
2545 to_utf8(rem), context);
2546 for (set<string>::const_iterator it = req.begin();
2547 it != req.end(); ++it)
2548 preamble.registerAutomaticallyLoadedPackage(*it);
2550 // we did not find a non-ert version
2551 output_ert_inset(os, name, context);
2553 context.check_layout(os);
2554 // special handling of font attribute changes
2555 Token const prev = p.prev_token();
2556 TeXFont const oldFont = context.font;
2557 if (next.character() == '[' ||
2558 next.character() == ']' ||
2559 next.character() == '*') {
2561 if (p.next_token().cat() == catEnd) {
2566 output_ert_inset(os, "{", context);
2567 parse_text_snippet(p, os,
2570 output_ert_inset(os, "}", context);
2572 } else if (! context.new_layout_allowed) {
2573 output_ert_inset(os, "{", context);
2574 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2576 output_ert_inset(os, "}", context);
2577 } else if (is_known(next.cs(), known_sizes)) {
2578 // next will change the size, so we must
2580 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2582 if (!context.atParagraphStart())
2584 << context.font.size << "\n";
2585 } else if (is_known(next.cs(), known_font_families)) {
2586 // next will change the font family, so we
2587 // must reset it here
2588 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2590 if (!context.atParagraphStart())
2592 << context.font.family << "\n";
2593 } else if (is_known(next.cs(), known_font_series)) {
2594 // next will change the font series, so we
2595 // must reset it here
2596 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2598 if (!context.atParagraphStart())
2600 << context.font.series << "\n";
2601 } else if (is_known(next.cs(), known_font_shapes)) {
2602 // next will change the font shape, so we
2603 // must reset it here
2604 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2606 if (!context.atParagraphStart())
2608 << context.font.shape << "\n";
2609 } else if (is_known(next.cs(), known_old_font_families) ||
2610 is_known(next.cs(), known_old_font_series) ||
2611 is_known(next.cs(), known_old_font_shapes)) {
2612 // next will change the font family, series
2613 // and shape, so we must reset it here
2614 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2616 if (!context.atParagraphStart())
2618 << context.font.family
2620 << context.font.series
2622 << context.font.shape << "\n";
2624 output_ert_inset(os, "{", context);
2625 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2627 output_ert_inset(os, "}", context);
2632 else if (t.cat() == catEnd) {
2633 if (flags & FLAG_BRACE_LAST) {
2636 cerr << "stray '}' in text\n";
2637 output_ert_inset(os, "}", context);
2640 else if (t.cat() == catComment)
2641 parse_comment(p, os, t, context);
2644 // control sequences
2647 else if (t.cs() == "(" || t.cs() == "[") {
2648 bool const simple = t.cs() == "(";
2649 context.check_layout(os);
2650 begin_inset(os, "Formula");
2651 os << " \\" << t.cs();
2652 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2653 os << '\\' << (simple ? ')' : ']');
2656 // Prevent the conversion of a line break to a
2657 // space (bug 7668). This does not change the
2658 // output, but looks ugly in LyX.
2659 eat_whitespace(p, os, context, false);
2663 else if (t.cs() == "begin")
2664 parse_environment(p, os, outer, last_env,
2667 else if (t.cs() == "end") {
2668 if (flags & FLAG_END) {
2669 // eat environment name
2670 string const name = p.getArg('{', '}');
2671 if (name != active_environment())
2672 cerr << "\\end{" + name + "} does not match \\begin{"
2673 + active_environment() + "}\n";
2676 p.error("found 'end' unexpectedly");
2679 else if (t.cs() == "item") {
2681 bool const optarg = p.hasOpt();
2683 // FIXME: This swallows comments, but we cannot use
2684 // eat_whitespace() since we must not output
2685 // anything before the item.
2686 p.skip_spaces(true);
2687 s = p.verbatimOption();
2689 p.skip_spaces(false);
2691 context.check_layout(os);
2692 if (context.has_item) {
2693 // An item in an unknown list-like environment
2694 // FIXME: Do this in check_layout()!
2695 context.has_item = false;
2697 output_ert_inset(os, "\\item", context);
2699 output_ert_inset(os, "\\item ", context);
2702 if (context.layout->labeltype != LABEL_MANUAL) {
2703 // handle option of itemize item
2704 begin_inset(os, "Argument item:1\n");
2705 os << "status open\n";
2706 os << "\n\\begin_layout Plain Layout\n";
2708 os << parse_text_snippet(p2,
2709 FLAG_BRACK_LAST, outer, context);
2710 // we must not use context.check_end_layout(os)
2711 // because that would close the outer itemize layout
2712 os << "\n\\end_layout\n";
2714 eat_whitespace(p, os, context, false);
2715 } else if (!s.empty()) {
2716 // LyX adds braces around the argument,
2717 // so we need to remove them here.
2718 if (s.size() > 2 && s[0] == '{' &&
2719 s[s.size()-1] == '}')
2720 s = s.substr(1, s.size()-2);
2721 // If the argument contains a space we
2722 // must put it into ERT: Otherwise LyX
2723 // would misinterpret the space as
2724 // item delimiter (bug 7663)
2725 if (contains(s, ' ')) {
2726 output_ert_inset(os, s, context);
2729 os << parse_text_snippet(p2,
2730 FLAG_BRACK_LAST, outer, context);
2732 // The space is needed to separate the
2733 // item from the rest of the sentence.
2735 eat_whitespace(p, os, context, false);
2740 else if (t.cs() == "bibitem") {
2742 context.check_layout(os);
2743 eat_whitespace(p, os, context, false);
2744 string label = convert_command_inset_arg(p.verbatimOption());
2745 string key = convert_command_inset_arg(p.verbatim_item());
2746 if (contains(label, '\\') || contains(key, '\\')) {
2747 // LyX can't handle LaTeX commands in labels or keys
2748 output_ert_inset(os, t.asInput() + '[' + label +
2749 "]{" + p.verbatim_item() + '}',
2752 begin_command_inset(os, "bibitem", "bibitem");
2753 os << "label \"" << label << "\"\n"
2754 "key \"" << key << "\"\n";
2759 else if (is_macro(p)) {
2760 // catch the case of \def\inputGnumericTable
2762 if (t.cs() == "def") {
2763 Token second = p.next_token();
2764 if (second.cs() == "inputGnumericTable") {
2768 Token third = p.get_token();
2770 if (third.cs() == "input") {
2774 string name = normalize_filename(p.verbatim_item());
2775 string const path = getMasterFilePath(true);
2776 // We want to preserve relative / absolute filenames,
2777 // therefore path is only used for testing
2778 // The file extension is in every case ".tex".
2779 // So we need to remove this extension and check for
2780 // the original one.
2781 name = removeExtension(name);
2782 if (!makeAbsPath(name, path).exists()) {
2783 char const * const Gnumeric_formats[] = {"gnumeric",
2785 string const Gnumeric_name =
2786 find_file(name, path, Gnumeric_formats);
2787 if (!Gnumeric_name.empty())
2788 name = Gnumeric_name;
2790 FileName const absname = makeAbsPath(name, path);
2791 if (absname.exists()) {
2792 fix_child_filename(name);
2793 copy_file(absname, name);
2795 cerr << "Warning: Could not find file '"
2796 << name << "'." << endl;
2797 context.check_layout(os);
2798 begin_inset(os, "External\n\ttemplate ");
2799 os << "GnumericSpreadsheet\n\tfilename "
2802 context.check_layout(os);
2804 // register the packages that are automatically loaded
2805 // by the Gnumeric template
2806 registerExternalTemplatePackages("GnumericSpreadsheet");
2811 parse_macro(p, os, context);
2814 else if (t.cs() == "noindent") {
2816 context.add_par_extra_stuff("\\noindent\n");
2819 else if (t.cs() == "appendix") {
2820 context.add_par_extra_stuff("\\start_of_appendix\n");
2821 // We need to start a new paragraph. Otherwise the
2822 // appendix in 'bla\appendix\chapter{' would start
2824 context.new_paragraph(os);
2825 // We need to make sure that the paragraph is
2826 // generated even if it is empty. Otherwise the
2827 // appendix in '\par\appendix\par\chapter{' would
2829 context.check_layout(os);
2830 // FIXME: This is a hack to prevent paragraph
2831 // deletion if it is empty. Handle this better!
2832 output_ert_inset(os,
2833 "%dummy comment inserted by tex2lyx to "
2834 "ensure that this paragraph is not empty",
2836 // Both measures above may generate an additional
2837 // empty paragraph, but that does not hurt, because
2838 // whitespace does not matter here.
2839 eat_whitespace(p, os, context, true);
2842 // Must catch empty dates before findLayout is called below
2843 else if (t.cs() == "date") {
2844 eat_whitespace(p, os, context, false);
2846 string const date = p.verbatim_item();
2849 preamble.suppressDate(true);
2852 preamble.suppressDate(false);
2853 if (context.new_layout_allowed &&
2854 (newlayout = findLayout(context.textclass,
2857 output_command_layout(os, p, outer,
2858 context, newlayout);
2859 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2860 if (!preamble.titleLayoutFound())
2861 preamble.titleLayoutFound(newlayout->intitle);
2862 set<string> const & req = newlayout->requires();
2863 set<string>::const_iterator it = req.begin();
2864 set<string>::const_iterator en = req.end();
2865 for (; it != en; ++it)
2866 preamble.registerAutomaticallyLoadedPackage(*it);
2868 output_ert_inset(os,
2869 "\\date{" + p.verbatim_item() + '}',
2874 // Starred section headings
2875 // Must attempt to parse "Section*" before "Section".
2876 else if ((p.next_token().asInput() == "*") &&
2877 context.new_layout_allowed &&
2878 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2881 output_command_layout(os, p, outer, context, newlayout);
2883 if (!preamble.titleLayoutFound())
2884 preamble.titleLayoutFound(newlayout->intitle);
2885 set<string> const & req = newlayout->requires();
2886 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2887 preamble.registerAutomaticallyLoadedPackage(*it);
2890 // Section headings and the like
2891 else if (context.new_layout_allowed &&
2892 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2894 output_command_layout(os, p, outer, context, newlayout);
2896 if (!preamble.titleLayoutFound())
2897 preamble.titleLayoutFound(newlayout->intitle);
2898 set<string> const & req = newlayout->requires();
2899 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2900 preamble.registerAutomaticallyLoadedPackage(*it);
2903 else if (t.cs() == "subfloat") {
2904 // the syntax is \subfloat[list entry][sub caption]{content}
2905 // if it is a table of figure depends on the surrounding float
2906 // FIXME: second optional argument is not parsed
2907 bool has_caption = false;
2909 // do nothing if there is no outer float
2910 if (!float_type.empty()) {
2911 context.check_layout(os);
2913 begin_inset(os, "Float " + float_type + "\n");
2915 << "\nsideways false"
2916 << "\nstatus collapsed\n\n";
2919 if (p.next_token().cat() != catEscape &&
2920 p.next_token().character() == '[') {
2921 p.get_token(); // eat '['
2922 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2926 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2927 // the caption comes always as the last
2929 // we must make sure that the caption gets a \begin_layout
2930 os << "\n\\begin_layout Plain Layout";
2932 begin_inset(os, "Caption Standard\n");
2933 Context newcontext(true, context.textclass,
2934 0, 0, context.font);
2935 newcontext.check_layout(os);
2936 os << caption << "\n";
2937 newcontext.check_end_layout(os);
2938 // We don't need really a new paragraph, but
2939 // we must make sure that the next item gets a \begin_layout.
2940 //newcontext.new_paragraph(os);
2944 // We don't need really a new paragraph, but
2945 // we must make sure that the next item gets a \begin_layout.
2947 context.new_paragraph(os);
2950 context.check_end_layout(os);
2951 // close the layout we opened
2953 os << "\n\\end_layout\n";
2955 // if the float type is not supported or there is no surrounding float
2958 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2959 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2960 "]{" + p.verbatim_item() + '}', context);
2962 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2966 else if (t.cs() == "includegraphics") {
2967 bool const clip = p.next_token().asInput() == "*";
2970 string const arg = p.getArg('[', ']');
2971 map<string, string> opts;
2972 vector<string> keys;
2973 split_map(arg, opts, keys);
2975 opts["clip"] = string();
2976 string name = normalize_filename(p.verbatim_item());
2978 string const path = getMasterFilePath(true);
2979 // We want to preserve relative / absolute filenames,
2980 // therefore path is only used for testing
2981 if (!makeAbsPath(name, path).exists()) {
2982 // The file extension is probably missing.
2983 // Now try to find it out.
2984 string const dvips_name =
2985 find_file(name, path,
2986 known_dvips_graphics_formats);
2987 string const pdftex_name =
2988 find_file(name, path,
2989 known_pdftex_graphics_formats);
2990 if (!dvips_name.empty()) {
2991 if (!pdftex_name.empty()) {
2992 cerr << "This file contains the "
2994 "\"\\includegraphics{"
2996 "However, files\n\""
2997 << dvips_name << "\" and\n\""
2998 << pdftex_name << "\"\n"
2999 "both exist, so I had to make a "
3000 "choice and took the first one.\n"
3001 "Please move the unwanted one "
3002 "someplace else and try again\n"
3003 "if my choice was wrong."
3007 } else if (!pdftex_name.empty()) {
3013 FileName const absname = makeAbsPath(name, path);
3014 if (absname.exists()) {
3015 fix_child_filename(name);
3016 copy_file(absname, name);
3018 cerr << "Warning: Could not find graphics file '"
3019 << name << "'." << endl;
3021 context.check_layout(os);
3022 begin_inset(os, "Graphics ");
3023 os << "\n\tfilename " << name << '\n';
3024 if (opts.find("width") != opts.end())
3026 << translate_len(opts["width"]) << '\n';
3027 if (opts.find("height") != opts.end())
3029 << translate_len(opts["height"]) << '\n';
3030 if (opts.find("scale") != opts.end()) {
3031 istringstream iss(opts["scale"]);
3035 os << "\tscale " << val << '\n';
3037 if (opts.find("angle") != opts.end()) {
3038 os << "\trotateAngle "
3039 << opts["angle"] << '\n';
3040 vector<string>::const_iterator a =
3041 find(keys.begin(), keys.end(), "angle");
3042 vector<string>::const_iterator s =
3043 find(keys.begin(), keys.end(), "width");
3044 if (s == keys.end())
3045 s = find(keys.begin(), keys.end(), "height");
3046 if (s == keys.end())
3047 s = find(keys.begin(), keys.end(), "scale");
3048 if (s != keys.end() && distance(s, a) > 0)
3049 os << "\tscaleBeforeRotation\n";
3051 if (opts.find("origin") != opts.end()) {
3053 string const opt = opts["origin"];
3054 if (opt.find('l') != string::npos) ss << "left";
3055 if (opt.find('r') != string::npos) ss << "right";
3056 if (opt.find('c') != string::npos) ss << "center";
3057 if (opt.find('t') != string::npos) ss << "Top";
3058 if (opt.find('b') != string::npos) ss << "Bottom";
3059 if (opt.find('B') != string::npos) ss << "Baseline";
3060 if (!ss.str().empty())
3061 os << "\trotateOrigin " << ss.str() << '\n';
3063 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3065 if (opts.find("keepaspectratio") != opts.end())
3066 os << "\tkeepAspectRatio\n";
3067 if (opts.find("clip") != opts.end())
3069 if (opts.find("draft") != opts.end())
3071 if (opts.find("bb") != opts.end())
3072 os << "\tBoundingBox "
3073 << opts["bb"] << '\n';
3074 int numberOfbbOptions = 0;
3075 if (opts.find("bbllx") != opts.end())
3076 numberOfbbOptions++;
3077 if (opts.find("bblly") != opts.end())
3078 numberOfbbOptions++;
3079 if (opts.find("bburx") != opts.end())
3080 numberOfbbOptions++;
3081 if (opts.find("bbury") != opts.end())
3082 numberOfbbOptions++;
3083 if (numberOfbbOptions == 4)
3084 os << "\tBoundingBox "
3085 << opts["bbllx"] << " " << opts["bblly"] << " "
3086 << opts["bburx"] << " " << opts["bbury"] << '\n';
3087 else if (numberOfbbOptions > 0)
3088 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3089 numberOfbbOptions = 0;
3090 if (opts.find("natwidth") != opts.end())
3091 numberOfbbOptions++;
3092 if (opts.find("natheight") != opts.end())
3093 numberOfbbOptions++;
3094 if (numberOfbbOptions == 2)
3095 os << "\tBoundingBox 0bp 0bp "
3096 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3097 else if (numberOfbbOptions > 0)
3098 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3099 ostringstream special;
3100 if (opts.find("hiresbb") != opts.end())
3101 special << "hiresbb,";
3102 if (opts.find("trim") != opts.end())
3104 if (opts.find("viewport") != opts.end())
3105 special << "viewport=" << opts["viewport"] << ',';
3106 if (opts.find("totalheight") != opts.end())
3107 special << "totalheight=" << opts["totalheight"] << ',';
3108 if (opts.find("type") != opts.end())
3109 special << "type=" << opts["type"] << ',';
3110 if (opts.find("ext") != opts.end())
3111 special << "ext=" << opts["ext"] << ',';
3112 if (opts.find("read") != opts.end())
3113 special << "read=" << opts["read"] << ',';
3114 if (opts.find("command") != opts.end())
3115 special << "command=" << opts["command"] << ',';
3116 string s_special = special.str();
3117 if (!s_special.empty()) {
3118 // We had special arguments. Remove the trailing ','.
3119 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3121 // TODO: Handle the unknown settings better.
3122 // Warn about invalid options.
3123 // Check whether some option was given twice.
3125 preamble.registerAutomaticallyLoadedPackage("graphicx");
3128 else if (t.cs() == "footnote" ||
3129 (t.cs() == "thanks" && context.layout->intitle)) {
3131 context.check_layout(os);
3132 begin_inset(os, "Foot\n");
3133 os << "status collapsed\n\n";
3134 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3138 else if (t.cs() == "marginpar") {
3140 context.check_layout(os);
3141 begin_inset(os, "Marginal\n");
3142 os << "status collapsed\n\n";
3143 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3147 else if (t.cs() == "lstinline") {
3149 parse_listings(p, os, context, true);
3152 else if (t.cs() == "ensuremath") {
3154 context.check_layout(os);
3155 string const s = p.verbatim_item();
3156 //FIXME: this never triggers in UTF8
3157 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3160 output_ert_inset(os, "\\ensuremath{" + s + "}",
3164 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3165 if (preamble.titleLayoutFound()) {
3167 skip_spaces_braces(p);
3169 output_ert_inset(os, t.asInput(), context);
3172 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3173 context.check_layout(os);
3174 begin_command_inset(os, "toc", t.cs());
3176 skip_spaces_braces(p);
3177 if (t.cs() == "lstlistoflistings")
3178 preamble.registerAutomaticallyLoadedPackage("listings");
3181 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3182 context.check_layout(os);
3183 if (t.cs() == "listoffigures")
3184 begin_inset(os, "FloatList figure\n");
3186 begin_inset(os, "FloatList table\n");
3188 skip_spaces_braces(p);
3191 else if (t.cs() == "listof") {
3192 p.skip_spaces(true);
3193 string const name = p.get_token().cs();
3194 if (context.textclass.floats().typeExist(name)) {
3195 context.check_layout(os);
3196 begin_inset(os, "FloatList ");
3199 p.get_token(); // swallow second arg
3201 output_ert_inset(os, "\\listof{" + name + "}", context);
3204 else if ((where = is_known(t.cs(), known_text_font_families)))
3205 parse_text_attributes(p, os, FLAG_ITEM, outer,
3206 context, "\\family", context.font.family,
3207 known_coded_font_families[where - known_text_font_families]);
3209 else if ((where = is_known(t.cs(), known_text_font_series)))
3210 parse_text_attributes(p, os, FLAG_ITEM, outer,
3211 context, "\\series", context.font.series,
3212 known_coded_font_series[where - known_text_font_series]);
3214 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3215 parse_text_attributes(p, os, FLAG_ITEM, outer,
3216 context, "\\shape", context.font.shape,
3217 known_coded_font_shapes[where - known_text_font_shapes]);
3219 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3220 context.check_layout(os);
3221 TeXFont oldFont = context.font;
3222 context.font.init();
3223 context.font.size = oldFont.size;
3224 os << "\n\\family " << context.font.family << "\n";
3225 os << "\n\\series " << context.font.series << "\n";
3226 os << "\n\\shape " << context.font.shape << "\n";
3227 if (t.cs() == "textnormal") {
3228 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3229 output_font_change(os, context.font, oldFont);
3230 context.font = oldFont;
3232 eat_whitespace(p, os, context, false);
3235 else if (t.cs() == "textcolor") {
3236 // scheme is \textcolor{color name}{text}
3237 string const color = p.verbatim_item();
3238 // we support the predefined colors of the color and the xcolor package
3239 if (color == "black" || color == "blue" || color == "cyan"
3240 || color == "green" || color == "magenta" || color == "red"
3241 || color == "white" || color == "yellow") {
3242 context.check_layout(os);
3243 os << "\n\\color " << color << "\n";
3244 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3245 context.check_layout(os);
3246 os << "\n\\color inherit\n";
3247 preamble.registerAutomaticallyLoadedPackage("color");
3248 } else if (color == "brown" || color == "darkgray" || color == "gray"
3249 || color == "lightgray" || color == "lime" || color == "olive"
3250 || color == "orange" || color == "pink" || color == "purple"
3251 || color == "teal" || color == "violet") {
3252 context.check_layout(os);
3253 os << "\n\\color " << color << "\n";
3254 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3255 context.check_layout(os);
3256 os << "\n\\color inherit\n";
3257 preamble.registerAutomaticallyLoadedPackage("xcolor");
3259 // for custom defined colors
3260 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3263 else if (t.cs() == "underbar" || t.cs() == "uline") {
3264 // \underbar is not 100% correct (LyX outputs \uline
3265 // of ulem.sty). The difference is that \ulem allows
3266 // line breaks, and \underbar does not.
3267 // Do NOT handle \underline.
3268 // \underbar cuts through y, g, q, p etc.,
3269 // \underline does not.
3270 context.check_layout(os);
3271 os << "\n\\bar under\n";
3272 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3273 context.check_layout(os);
3274 os << "\n\\bar default\n";
3275 preamble.registerAutomaticallyLoadedPackage("ulem");
3278 else if (t.cs() == "sout") {
3279 context.check_layout(os);
3280 os << "\n\\strikeout on\n";
3281 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3282 context.check_layout(os);
3283 os << "\n\\strikeout default\n";
3284 preamble.registerAutomaticallyLoadedPackage("ulem");
3287 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3288 t.cs() == "emph" || t.cs() == "noun") {
3289 context.check_layout(os);
3290 os << "\n\\" << t.cs() << " on\n";
3291 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3292 context.check_layout(os);
3293 os << "\n\\" << t.cs() << " default\n";
3294 if (t.cs() == "uuline" || t.cs() == "uwave")
3295 preamble.registerAutomaticallyLoadedPackage("ulem");
3298 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3299 context.check_layout(os);
3300 string name = p.getArg('{', '}');
3301 string localtime = p.getArg('{', '}');
3302 preamble.registerAuthor(name);
3303 Author const & author = preamble.getAuthor(name);
3304 // from_asctime_utc() will fail if LyX decides to output the
3305 // time in the text language.
3306 time_t ptime = from_asctime_utc(localtime);
3307 if (ptime == static_cast<time_t>(-1)) {
3308 cerr << "Warning: Could not parse time `" << localtime
3309 << "´ for change tracking, using current time instead.\n";
3310 ptime = current_time();
3312 if (t.cs() == "lyxadded")
3313 os << "\n\\change_inserted ";
3315 os << "\n\\change_deleted ";
3316 os << author.bufferId() << ' ' << ptime << '\n';
3317 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3318 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3319 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3320 LaTeXPackages::isAvailable("xcolor");
3321 // No need to test for luatex, since luatex comes in
3322 // two flavours (dvi and pdf), like latex, and those
3323 // are detected by pdflatex.
3324 if (pdflatex || xetex) {
3326 preamble.registerAutomaticallyLoadedPackage("ulem");
3327 preamble.registerAutomaticallyLoadedPackage("xcolor");
3328 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3332 preamble.registerAutomaticallyLoadedPackage("dvipost");
3333 } else if (xcolorulem) {
3334 preamble.registerAutomaticallyLoadedPackage("ulem");
3335 preamble.registerAutomaticallyLoadedPackage("xcolor");
3340 else if (t.cs() == "textipa") {
3341 context.check_layout(os);
3342 begin_inset(os, "IPA\n");
3343 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3344 context.merging_hyphens_allowed = false;
3345 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3346 context.merging_hyphens_allowed = merging_hyphens_allowed;
3348 preamble.registerAutomaticallyLoadedPackage("tipa");
3349 preamble.registerAutomaticallyLoadedPackage("tipx");
3352 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3353 context.check_layout(os);
3354 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3355 os << "status open\n";
3356 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3361 else if (t.cs() == "textvertline") {
3362 // FIXME: This is not correct, \textvertline is higher than |
3368 else if (t.cs() == "tone" ) {
3369 context.check_layout(os);
3370 // register the tone package
3371 preamble.registerAutomaticallyLoadedPackage("tone");
3372 string content = trimSpaceAndEol(p.verbatim_item());
3373 string command = t.asInput() + "{" + content + "}";
3374 // some tones can be detected by unicodesymbols, some need special code
3375 if (is_known(content, known_tones)) {
3376 os << "\\IPAChar " << command << "\n";
3379 // try to see whether the string is in unicodesymbols
3383 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3384 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3385 termination, rem, &req);
3389 output_ert_inset(os, to_utf8(rem), context);
3390 for (set<string>::const_iterator it = req.begin();
3391 it != req.end(); ++it)
3392 preamble.registerAutomaticallyLoadedPackage(*it);
3394 // we did not find a non-ert version
3395 output_ert_inset(os, command, context);
3398 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3399 t.cs() == "vphantom") {
3400 context.check_layout(os);
3401 if (t.cs() == "phantom")
3402 begin_inset(os, "Phantom Phantom\n");
3403 if (t.cs() == "hphantom")
3404 begin_inset(os, "Phantom HPhantom\n");
3405 if (t.cs() == "vphantom")
3406 begin_inset(os, "Phantom VPhantom\n");
3407 os << "status open\n";
3408 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3413 else if (t.cs() == "href") {
3414 context.check_layout(os);
3415 string target = convert_command_inset_arg(p.verbatim_item());
3416 string name = convert_command_inset_arg(p.verbatim_item());
3418 size_t i = target.find(':');
3419 if (i != string::npos) {
3420 type = target.substr(0, i + 1);
3421 if (type == "mailto:" || type == "file:")
3422 target = target.substr(i + 1);
3423 // handle the case that name is equal to target, except of "http://"
3424 else if (target.substr(i + 3) == name && type == "http:")
3427 begin_command_inset(os, "href", "href");
3429 os << "name \"" << name << "\"\n";
3430 os << "target \"" << target << "\"\n";
3431 if (type == "mailto:" || type == "file:")
3432 os << "type \"" << type << "\"\n";
3434 skip_spaces_braces(p);
3437 else if (t.cs() == "lyxline") {
3438 // swallow size argument (it is not used anyway)
3440 if (!context.atParagraphStart()) {
3441 // so our line is in the middle of a paragraph
3442 // we need to add a new line, lest this line
3443 // follow the other content on that line and
3444 // run off the side of the page
3445 // FIXME: This may create an empty paragraph,
3446 // but without that it would not be
3447 // possible to set noindent below.
3448 // Fortunately LaTeX does not care
3449 // about the empty paragraph.
3450 context.new_paragraph(os);
3452 if (preamble.indentParagraphs()) {
3453 // we need to unindent, lest the line be too long
3454 context.add_par_extra_stuff("\\noindent\n");
3456 context.check_layout(os);
3457 begin_command_inset(os, "line", "rule");
3458 os << "offset \"0.5ex\"\n"
3459 "width \"100line%\"\n"
3464 else if (t.cs() == "rule") {
3465 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3466 string const width = p.getArg('{', '}');
3467 string const thickness = p.getArg('{', '}');
3468 context.check_layout(os);
3469 begin_command_inset(os, "line", "rule");
3470 if (!offset.empty())
3471 os << "offset \"" << translate_len(offset) << "\"\n";
3472 os << "width \"" << translate_len(width) << "\"\n"
3473 "height \"" << translate_len(thickness) << "\"\n";
3477 // handle refstyle first to catch \eqref which can also occur
3478 // without refstyle. Only recognize these commands if
3479 // refstyle.sty was found in the preamble (otherwise \eqref
3480 // and user defined ref commands could be misdetected).
3481 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3482 preamble.refstyle()) {
3483 context.check_layout(os);
3484 begin_command_inset(os, "ref", "formatted");
3485 os << "reference \"";
3486 os << known_refstyle_prefixes[where - known_refstyle_commands]
3488 os << convert_command_inset_arg(p.verbatim_item())
3491 preamble.registerAutomaticallyLoadedPackage("refstyle");
3494 // if refstyle is used, we must not convert \prettyref to a
3495 // formatted reference, since that would result in a refstyle command.
3496 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3497 (t.cs() != "prettyref" || !preamble.refstyle())) {
3498 string const opt = p.getOpt();
3500 context.check_layout(os);
3501 begin_command_inset(os, "ref",
3502 known_coded_ref_commands[where - known_ref_commands]);
3503 os << "reference \""
3504 << convert_command_inset_arg(p.verbatim_item())
3507 if (t.cs() == "vref" || t.cs() == "vpageref")
3508 preamble.registerAutomaticallyLoadedPackage("varioref");
3509 else if (t.cs() == "prettyref")
3510 preamble.registerAutomaticallyLoadedPackage("prettyref");
3512 // LyX does not yet support optional arguments of ref commands
3513 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3514 p.verbatim_item() + '}', context);
3518 else if (use_natbib &&
3519 is_known(t.cs(), known_natbib_commands) &&
3520 ((t.cs() != "citefullauthor" &&
3521 t.cs() != "citeyear" &&
3522 t.cs() != "citeyearpar") ||
3523 p.next_token().asInput() != "*")) {
3524 context.check_layout(os);
3525 string command = t.cs();
3526 if (p.next_token().asInput() == "*") {
3530 if (command == "citefullauthor")
3531 // alternative name for "\\citeauthor*"
3532 command = "citeauthor*";
3534 // text before the citation
3536 // text after the citation
3538 get_cite_arguments(p, true, before, after);
3540 if (command == "cite") {
3541 // \cite without optional argument means
3542 // \citet, \cite with at least one optional
3543 // argument means \citep.
3544 if (before.empty() && after.empty())
3549 if (before.empty() && after == "[]")
3550 // avoid \citet[]{a}
3552 else if (before == "[]" && after == "[]") {
3553 // avoid \citet[][]{a}
3557 // remove the brackets around after and before
3558 if (!after.empty()) {
3560 after.erase(after.length() - 1, 1);
3561 after = convert_command_inset_arg(after);
3563 if (!before.empty()) {
3565 before.erase(before.length() - 1, 1);
3566 before = convert_command_inset_arg(before);
3568 begin_command_inset(os, "citation", command);
3569 os << "after " << '"' << after << '"' << "\n";
3570 os << "before " << '"' << before << '"' << "\n";
3572 << convert_command_inset_arg(p.verbatim_item())
3575 // Need to set the cite engine if natbib is loaded by
3576 // the document class directly
3577 if (preamble.citeEngine() == "basic")
3578 preamble.citeEngine("natbib");
3581 else if (use_jurabib &&
3582 is_known(t.cs(), known_jurabib_commands) &&
3583 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3584 context.check_layout(os);
3585 string command = t.cs();
3586 if (p.next_token().asInput() == "*") {
3590 char argumentOrder = '\0';
3591 vector<string> const options =
3592 preamble.getPackageOptions("jurabib");
3593 if (find(options.begin(), options.end(),
3594 "natbiborder") != options.end())
3595 argumentOrder = 'n';
3596 else if (find(options.begin(), options.end(),
3597 "jurabiborder") != options.end())
3598 argumentOrder = 'j';
3600 // text before the citation
3602 // text after the citation
3604 get_cite_arguments(p, argumentOrder != 'j', before, after);
3606 string const citation = p.verbatim_item();
3607 if (!before.empty() && argumentOrder == '\0') {
3608 cerr << "Warning: Assuming argument order "
3609 "of jurabib version 0.6 for\n'"
3610 << command << before << after << '{'
3611 << citation << "}'.\n"
3612 "Add 'jurabiborder' to the jurabib "
3613 "package options if you used an\n"
3614 "earlier jurabib version." << endl;
3616 if (!after.empty()) {
3618 after.erase(after.length() - 1, 1);
3620 if (!before.empty()) {
3622 before.erase(before.length() - 1, 1);
3624 begin_command_inset(os, "citation", command);
3625 os << "after " << '"' << after << '"' << "\n";
3626 os << "before " << '"' << before << '"' << "\n";
3627 os << "key " << '"' << citation << '"' << "\n";
3629 // Need to set the cite engine if jurabib is loaded by
3630 // the document class directly
3631 if (preamble.citeEngine() == "basic")
3632 preamble.citeEngine("jurabib");
3635 else if (t.cs() == "cite"
3636 || t.cs() == "nocite") {
3637 context.check_layout(os);
3638 string after = convert_command_inset_arg(p.getArg('[', ']'));
3639 string key = convert_command_inset_arg(p.verbatim_item());
3640 // store the case that it is "\nocite{*}" to use it later for
3643 begin_command_inset(os, "citation", t.cs());
3644 os << "after " << '"' << after << '"' << "\n";
3645 os << "key " << '"' << key << '"' << "\n";
3647 } else if (t.cs() == "nocite")
3651 else if (t.cs() == "index" ||
3652 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3653 context.check_layout(os);
3654 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3655 p.getArg('[', ']') : "";
3656 string const kind = arg.empty() ? "idx" : arg;
3657 begin_inset(os, "Index ");
3658 os << kind << "\nstatus collapsed\n";
3659 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3662 preamble.registerAutomaticallyLoadedPackage("splitidx");
3665 else if (t.cs() == "nomenclature") {
3666 context.check_layout(os);
3667 begin_command_inset(os, "nomenclature", "nomenclature");
3668 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3669 if (!prefix.empty())
3670 os << "prefix " << '"' << prefix << '"' << "\n";
3671 os << "symbol " << '"'
3672 << convert_command_inset_arg(p.verbatim_item());
3673 os << "\"\ndescription \""
3674 << convert_command_inset_arg(p.verbatim_item())
3677 preamble.registerAutomaticallyLoadedPackage("nomencl");
3680 else if (t.cs() == "label") {
3681 context.check_layout(os);
3682 begin_command_inset(os, "label", "label");
3684 << convert_command_inset_arg(p.verbatim_item())
3689 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3690 context.check_layout(os);
3691 string commandname = t.cs();
3693 if (p.next_token().asInput() == "*") {
3698 begin_command_inset(os, "index_print", commandname);
3699 string const indexname = p.getArg('[', ']');
3701 if (indexname.empty())
3702 os << "type \"idx\"\n";
3704 os << "type \"" << indexname << "\"\n";
3707 skip_spaces_braces(p);
3708 preamble.registerAutomaticallyLoadedPackage("makeidx");
3709 if (preamble.use_indices() == "true")
3710 preamble.registerAutomaticallyLoadedPackage("splitidx");
3713 else if (t.cs() == "printnomenclature") {
3715 string width_type = "";
3716 context.check_layout(os);
3717 begin_command_inset(os, "nomencl_print", "printnomenclature");
3718 // case of a custom width
3720 width = p.getArg('[', ']');
3721 width = translate_len(width);
3722 width_type = "custom";
3724 // case of no custom width
3725 // the case of no custom width but the width set
3726 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3727 // because the user could have set anything, not only the width
3728 // of the longest label (which would be width_type = "auto")
3729 string label = convert_command_inset_arg(p.getArg('{', '}'));
3730 if (label.empty() && width_type.empty())
3731 width_type = "none";
3732 os << "set_width \"" << width_type << "\"\n";
3733 if (width_type == "custom")
3734 os << "width \"" << width << '\"';
3736 skip_spaces_braces(p);
3737 preamble.registerAutomaticallyLoadedPackage("nomencl");
3740 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3741 context.check_layout(os);
3742 begin_inset(os, "script ");
3743 os << t.cs().substr(4) << '\n';
3744 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3745 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3747 if (t.cs() == "textsubscript")
3748 preamble.registerAutomaticallyLoadedPackage("subscript");
3751 else if ((where = is_known(t.cs(), known_quotes))) {
3752 context.check_layout(os);
3753 begin_inset(os, "Quotes ");
3754 os << known_coded_quotes[where - known_quotes];
3756 // LyX adds {} after the quote, so we have to eat
3757 // spaces here if there are any before a possible
3759 eat_whitespace(p, os, context, false);
3763 else if ((where = is_known(t.cs(), known_sizes)) &&
3764 context.new_layout_allowed) {
3765 context.check_layout(os);
3766 TeXFont const oldFont = context.font;
3767 context.font.size = known_coded_sizes[where - known_sizes];
3768 output_font_change(os, oldFont, context.font);
3769 eat_whitespace(p, os, context, false);
3772 else if ((where = is_known(t.cs(), known_font_families)) &&
3773 context.new_layout_allowed) {
3774 context.check_layout(os);
3775 TeXFont const oldFont = context.font;
3776 context.font.family =
3777 known_coded_font_families[where - known_font_families];
3778 output_font_change(os, oldFont, context.font);
3779 eat_whitespace(p, os, context, false);
3782 else if ((where = is_known(t.cs(), known_font_series)) &&
3783 context.new_layout_allowed) {
3784 context.check_layout(os);
3785 TeXFont const oldFont = context.font;
3786 context.font.series =
3787 known_coded_font_series[where - known_font_series];
3788 output_font_change(os, oldFont, context.font);
3789 eat_whitespace(p, os, context, false);
3792 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3793 context.new_layout_allowed) {
3794 context.check_layout(os);
3795 TeXFont const oldFont = context.font;
3796 context.font.shape =
3797 known_coded_font_shapes[where - known_font_shapes];
3798 output_font_change(os, oldFont, context.font);
3799 eat_whitespace(p, os, context, false);
3801 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3802 context.new_layout_allowed) {
3803 context.check_layout(os);
3804 TeXFont const oldFont = context.font;
3805 context.font.init();
3806 context.font.size = oldFont.size;
3807 context.font.family =
3808 known_coded_font_families[where - known_old_font_families];
3809 output_font_change(os, oldFont, context.font);
3810 eat_whitespace(p, os, context, false);
3813 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3814 context.new_layout_allowed) {
3815 context.check_layout(os);
3816 TeXFont const oldFont = context.font;
3817 context.font.init();
3818 context.font.size = oldFont.size;
3819 context.font.series =
3820 known_coded_font_series[where - known_old_font_series];
3821 output_font_change(os, oldFont, context.font);
3822 eat_whitespace(p, os, context, false);
3825 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3826 context.new_layout_allowed) {
3827 context.check_layout(os);
3828 TeXFont const oldFont = context.font;
3829 context.font.init();
3830 context.font.size = oldFont.size;
3831 context.font.shape =
3832 known_coded_font_shapes[where - known_old_font_shapes];
3833 output_font_change(os, oldFont, context.font);
3834 eat_whitespace(p, os, context, false);
3837 else if (t.cs() == "selectlanguage") {
3838 context.check_layout(os);
3839 // save the language for the case that a
3840 // \foreignlanguage is used
3841 context.font.language = babel2lyx(p.verbatim_item());
3842 os << "\n\\lang " << context.font.language << "\n";
3845 else if (t.cs() == "foreignlanguage") {
3846 string const lang = babel2lyx(p.verbatim_item());
3847 parse_text_attributes(p, os, FLAG_ITEM, outer,
3849 context.font.language, lang);
3852 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3853 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3854 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3856 // We have to output the whole command if it has an option
3857 // because LyX doesn't support this yet, see bug #8214,
3858 // only if there is a single option specifying a variant, we can handle it.
3860 string langopts = p.getOpt();
3861 // check if the option contains a variant, if yes, extract it
3862 string::size_type pos_var = langopts.find("variant");
3863 string::size_type i = langopts.find(',');
3864 string::size_type k = langopts.find('=', pos_var);
3865 if (pos_var != string::npos && i == string::npos) {
3867 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3868 lang = preamble.polyglossia2lyx(variant);
3869 parse_text_attributes(p, os, FLAG_ITEM, outer,
3871 context.font.language, lang);
3873 output_ert_inset(os, t.asInput() + langopts, context);
3875 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3876 parse_text_attributes(p, os, FLAG_ITEM, outer,
3878 context.font.language, lang);
3882 else if (t.cs() == "inputencoding") {
3883 // nothing to write here
3884 string const enc = subst(p.verbatim_item(), "\n", " ");
3885 p.setEncoding(enc, Encoding::inputenc);
3888 else if (is_known(t.cs(), known_special_chars) ||
3889 (t.cs() == "protect" &&
3890 p.next_token().cat() == catEscape &&
3891 is_known(p.next_token().cs(), known_special_protect_chars))) {
3892 // LyX sometimes puts a \protect in front, so we have to ignore it
3894 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3895 known_special_chars);
3896 context.check_layout(os);
3897 os << known_coded_special_chars[where - known_special_chars];
3898 skip_spaces_braces(p);
3901 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3902 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3903 p.next_next_token().asInput() == "-") ||
3904 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3905 // LyX sometimes puts a \protect in front, so we have to ignore it
3906 if (t.cs() == "protect")
3908 context.check_layout(os);
3909 if (t.cs() == "nobreakdash")
3910 os << "\\SpecialChar nobreakdash\n";
3912 os << "\\SpecialChar endofsentence\n";
3916 else if (t.cs() == "textquotedbl") {
3917 context.check_layout(os);
3922 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3923 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3924 || t.cs() == "%" || t.cs() == "-") {
3925 context.check_layout(os);
3927 os << "\\SpecialChar softhyphen\n";
3932 else if (t.cs() == "char") {
3933 context.check_layout(os);
3934 if (p.next_token().character() == '`') {
3936 if (p.next_token().cs() == "\"") {
3941 output_ert_inset(os, "\\char`", context);
3944 output_ert_inset(os, "\\char", context);
3948 else if (t.cs() == "verb") {
3949 context.check_layout(os);
3950 // set catcodes to verbatim early, just in case.
3951 p.setCatcodes(VERBATIM_CATCODES);
3952 string delim = p.get_token().asInput();
3953 Parser::Arg arg = p.verbatimStuff(delim);
3955 output_ert_inset(os, "\\verb" + delim
3956 + arg.second + delim, context);
3958 cerr << "invalid \\verb command. Skipping" << endl;
3961 // Problem: \= creates a tabstop inside the tabbing environment
3962 // and else an accent. In the latter case we really would want
3963 // \={o} instead of \= o.
3964 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3965 output_ert_inset(os, t.asInput(), context);
3967 else if (t.cs() == "\\") {
3968 context.check_layout(os);
3970 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3971 else if (p.next_token().asInput() == "*") {
3973 // getOpt() eats the following space if there
3974 // is no optional argument, but that is OK
3975 // here since it has no effect in the output.
3976 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3979 begin_inset(os, "Newline newline");
3984 else if (t.cs() == "newline" ||
3985 (t.cs() == "linebreak" && !p.hasOpt())) {
3986 context.check_layout(os);
3987 begin_inset(os, "Newline ");
3990 skip_spaces_braces(p);
3993 else if (t.cs() == "input" || t.cs() == "include"
3994 || t.cs() == "verbatiminput") {
3995 string name = t.cs();
3996 if (t.cs() == "verbatiminput"
3997 && p.next_token().asInput() == "*")
3998 name += p.get_token().asInput();
3999 context.check_layout(os);
4000 string filename(normalize_filename(p.getArg('{', '}')));
4001 string const path = getMasterFilePath(true);
4002 // We want to preserve relative / absolute filenames,
4003 // therefore path is only used for testing
4004 if ((t.cs() == "include" || t.cs() == "input") &&
4005 !makeAbsPath(filename, path).exists()) {
4006 // The file extension is probably missing.
4007 // Now try to find it out.
4008 string const tex_name =
4009 find_file(filename, path,
4010 known_tex_extensions);
4011 if (!tex_name.empty())
4012 filename = tex_name;
4014 bool external = false;
4016 if (makeAbsPath(filename, path).exists()) {
4017 string const abstexname =
4018 makeAbsPath(filename, path).absFileName();
4019 string const absfigname =
4020 changeExtension(abstexname, ".fig");
4021 fix_child_filename(filename);
4022 string const lyxname = changeExtension(filename,
4023 roundtripMode() ? ".lyx.lyx" : ".lyx");
4024 string const abslyxname = makeAbsPath(
4025 lyxname, getParentFilePath(false)).absFileName();
4027 if (!skipChildren())
4028 external = FileName(absfigname).exists();
4029 if (t.cs() == "input" && !skipChildren()) {
4030 string const ext = getExtension(abstexname);
4032 // Combined PS/LaTeX:
4033 // x.eps, x.pstex_t (old xfig)
4034 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4035 FileName const absepsname(
4036 changeExtension(abstexname, ".eps"));
4037 FileName const abspstexname(
4038 changeExtension(abstexname, ".pstex"));
4039 bool const xfigeps =
4040 (absepsname.exists() ||
4041 abspstexname.exists()) &&
4044 // Combined PDF/LaTeX:
4045 // x.pdf, x.pdftex_t (old xfig)
4046 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4047 FileName const abspdfname(
4048 changeExtension(abstexname, ".pdf"));
4049 bool const xfigpdf =
4050 abspdfname.exists() &&
4051 (ext == "pdftex_t" || ext == "pdf_t");
4055 // Combined PS/PDF/LaTeX:
4056 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4057 string const absbase2(
4058 removeExtension(abstexname) + "_pspdftex");
4059 FileName const abseps2name(
4060 addExtension(absbase2, ".eps"));
4061 FileName const abspdf2name(
4062 addExtension(absbase2, ".pdf"));
4063 bool const xfigboth =
4064 abspdf2name.exists() &&
4065 abseps2name.exists() && ext == "pspdftex";
4067 xfig = xfigpdf || xfigeps || xfigboth;
4068 external = external && xfig;
4071 outname = changeExtension(filename, ".fig");
4072 FileName abssrc(changeExtension(abstexname, ".fig"));
4073 copy_file(abssrc, outname);
4075 // Don't try to convert, the result
4076 // would be full of ERT.
4078 FileName abssrc(abstexname);
4079 copy_file(abssrc, outname);
4080 } else if (t.cs() != "verbatiminput" &&
4082 tex2lyx(abstexname, FileName(abslyxname),
4085 // no need to call copy_file
4086 // tex2lyx creates the file
4089 FileName abssrc(abstexname);
4090 copy_file(abssrc, outname);
4093 cerr << "Warning: Could not find included file '"
4094 << filename << "'." << endl;
4098 begin_inset(os, "External\n");
4099 os << "\ttemplate XFig\n"
4100 << "\tfilename " << outname << '\n';
4101 registerExternalTemplatePackages("XFig");
4103 begin_command_inset(os, "include", name);
4104 outname = subst(outname, "\"", "\\\"");
4105 os << "preview false\n"
4106 "filename \"" << outname << "\"\n";
4107 if (t.cs() == "verbatiminput")
4108 preamble.registerAutomaticallyLoadedPackage("verbatim");
4113 else if (t.cs() == "bibliographystyle") {
4114 // store new bibliographystyle
4115 bibliographystyle = p.verbatim_item();
4116 // If any other command than \bibliography, \addcontentsline
4117 // and \nocite{*} follows, we need to output the style
4118 // (because it might be used by that command).
4119 // Otherwise, it will automatically be output by LyX.
4122 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4123 if (t2.cat() == catBegin)
4125 if (t2.cat() != catEscape)
4127 if (t2.cs() == "nocite") {
4128 if (p.getArg('{', '}') == "*")
4130 } else if (t2.cs() == "bibliography")
4132 else if (t2.cs() == "phantomsection") {
4136 else if (t2.cs() == "addcontentsline") {
4137 // get the 3 arguments of \addcontentsline
4140 contentslineContent = p.getArg('{', '}');
4141 // if the last argument is not \refname we must output
4142 if (contentslineContent == "\\refname")
4149 output_ert_inset(os,
4150 "\\bibliographystyle{" + bibliographystyle + '}',
4155 else if (t.cs() == "phantomsection") {
4156 // we only support this if it occurs between
4157 // \bibliographystyle and \bibliography
4158 if (bibliographystyle.empty())
4159 output_ert_inset(os, "\\phantomsection", context);
4162 else if (t.cs() == "addcontentsline") {
4163 context.check_layout(os);
4164 // get the 3 arguments of \addcontentsline
4165 string const one = p.getArg('{', '}');
4166 string const two = p.getArg('{', '}');
4167 string const three = p.getArg('{', '}');
4168 // only if it is a \refname, we support if for the bibtex inset
4169 if (contentslineContent != "\\refname") {
4170 output_ert_inset(os,
4171 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4176 else if (t.cs() == "bibliography") {
4177 context.check_layout(os);
4179 begin_command_inset(os, "bibtex", "bibtex");
4180 if (!btprint.empty()) {
4181 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4182 // clear the string because the next BibTeX inset can be without the
4183 // \nocite{*} option
4186 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4187 // Do we have addcontentsline?
4188 if (contentslineContent == "\\refname") {
4189 BibOpts = "bibtotoc";
4190 // clear string because next BibTeX inset can be without addcontentsline
4191 contentslineContent.clear();
4193 // Do we have a bibliographystyle set?
4194 if (!bibliographystyle.empty()) {
4195 if (BibOpts.empty())
4196 BibOpts = bibliographystyle;
4198 BibOpts = BibOpts + ',' + bibliographystyle;
4199 // clear it because each bibtex entry has its style
4200 // and we need an empty string to handle \phantomsection
4201 bibliographystyle.clear();
4203 os << "options " << '"' << BibOpts << '"' << "\n";
4207 else if (t.cs() == "parbox") {
4208 // Test whether this is an outer box of a shaded box
4210 // swallow arguments
4211 while (p.hasOpt()) {
4213 p.skip_spaces(true);
4216 p.skip_spaces(true);
4218 if (p.next_token().cat() == catBegin)
4220 p.skip_spaces(true);
4221 Token to = p.get_token();
4222 bool shaded = false;
4223 if (to.asInput() == "\\begin") {
4224 p.skip_spaces(true);
4225 if (p.getArg('{', '}') == "shaded")
4230 parse_outer_box(p, os, FLAG_ITEM, outer,
4231 context, "parbox", "shaded");
4233 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4234 "", "", t.cs(), "", "");
4237 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4238 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4239 t.cs() == "shadowbox" || t.cs() == "doublebox")
4240 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4242 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4243 string backgroundcolor;
4244 preamble.registerAutomaticallyLoadedPackage("xcolor");
4245 if (t.cs() == "fcolorbox") {
4246 string const framecolor = p.getArg('{', '}');
4247 backgroundcolor = p.getArg('{', '}');
4248 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4250 backgroundcolor = p.getArg('{', '}');
4251 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4255 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4256 || t.cs() == "shadowsize") {
4257 p.skip_spaces(true);
4258 if (t.cs() == "fboxrule")
4260 if (t.cs() == "fboxsep")
4262 if (t.cs() == "shadowsize")
4264 while (p.good() && p.next_token().cat() != catSpace
4265 && p.next_token().cat() != catNewline
4266 && p.next_token().cat() != catEscape) {
4267 if (t.cs() == "fboxrule")
4268 fboxrule = fboxrule + p.get_token().asInput();
4269 if (t.cs() == "fboxsep")
4270 fboxsep = fboxsep + p.get_token().asInput();
4271 if (t.cs() == "shadowsize")
4272 shadow_size = shadow_size + p.get_token().asInput();
4276 //\framebox() is part of the picture environment and different from \framebox{}
4277 //\framebox{} will be parsed by parse_outer_box
4278 else if (t.cs() == "framebox") {
4279 if (p.next_token().character() == '(') {
4280 //the syntax is: \framebox(x,y)[position]{content}
4281 string arg = t.asInput();
4282 arg += p.getFullParentheseArg();
4283 arg += p.getFullOpt();
4284 eat_whitespace(p, os, context, false);
4285 output_ert_inset(os, arg + '{', context);
4286 parse_text(p, os, FLAG_ITEM, outer, context);
4287 output_ert_inset(os, "}", context);
4289 //the syntax is: \framebox[width][position]{content}
4290 string special = p.getFullOpt();
4291 special += p.getOpt();
4292 parse_outer_box(p, os, FLAG_ITEM, outer,
4293 context, t.cs(), special);
4297 //\makebox() is part of the picture environment and different from \makebox{}
4298 //\makebox{} will be parsed by parse_box
4299 else if (t.cs() == "makebox") {
4300 if (p.next_token().character() == '(') {
4301 //the syntax is: \makebox(x,y)[position]{content}
4302 string arg = t.asInput();
4303 arg += p.getFullParentheseArg();
4304 arg += p.getFullOpt();
4305 eat_whitespace(p, os, context, false);
4306 output_ert_inset(os, arg + '{', context);
4307 parse_text(p, os, FLAG_ITEM, outer, context);
4308 output_ert_inset(os, "}", context);
4310 //the syntax is: \makebox[width][position]{content}
4311 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4312 "", "", t.cs(), "", "");
4315 else if (t.cs() == "smallskip" ||
4316 t.cs() == "medskip" ||
4317 t.cs() == "bigskip" ||
4318 t.cs() == "vfill") {
4319 context.check_layout(os);
4320 begin_inset(os, "VSpace ");
4323 skip_spaces_braces(p);
4326 else if ((where = is_known(t.cs(), known_spaces))) {
4327 context.check_layout(os);
4328 begin_inset(os, "space ");
4329 os << '\\' << known_coded_spaces[where - known_spaces]
4332 // LaTeX swallows whitespace after all spaces except
4333 // "\\,". We have to do that here, too, because LyX
4334 // adds "{}" which would make the spaces significant.
4336 eat_whitespace(p, os, context, false);
4337 // LyX adds "{}" after all spaces except "\\ " and
4338 // "\\,", so we have to remove "{}".
4339 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4340 // remove the braces after "\\,", too.
4345 else if (t.cs() == "newpage" ||
4346 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4347 t.cs() == "clearpage" ||
4348 t.cs() == "cleardoublepage") {
4349 context.check_layout(os);
4350 begin_inset(os, "Newpage ");
4353 skip_spaces_braces(p);
4356 else if (t.cs() == "DeclareRobustCommand" ||
4357 t.cs() == "DeclareRobustCommandx" ||
4358 t.cs() == "newcommand" ||
4359 t.cs() == "newcommandx" ||
4360 t.cs() == "providecommand" ||
4361 t.cs() == "providecommandx" ||
4362 t.cs() == "renewcommand" ||
4363 t.cs() == "renewcommandx") {
4364 // DeclareRobustCommand, DeclareRobustCommandx,
4365 // providecommand and providecommandx could be handled
4366 // by parse_command(), but we need to call
4367 // add_known_command() here.
4368 string name = t.asInput();
4369 if (p.next_token().asInput() == "*") {
4370 // Starred form. Eat '*'
4374 string const command = p.verbatim_item();
4375 string const opt1 = p.getFullOpt();
4376 string const opt2 = p.getFullOpt();
4377 add_known_command(command, opt1, !opt2.empty());
4378 string const ert = name + '{' + command + '}' +
4380 '{' + p.verbatim_item() + '}';
4382 if (t.cs() == "DeclareRobustCommand" ||
4383 t.cs() == "DeclareRobustCommandx" ||
4384 t.cs() == "providecommand" ||
4385 t.cs() == "providecommandx" ||
4386 name[name.length()-1] == '*')
4387 output_ert_inset(os, ert, context);
4389 context.check_layout(os);
4390 begin_inset(os, "FormulaMacro");
4396 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4397 // let could be handled by parse_command(),
4398 // but we need to call add_known_command() here.
4399 string ert = t.asInput();
4402 if (p.next_token().cat() == catBegin) {
4403 name = p.verbatim_item();
4404 ert += '{' + name + '}';
4406 name = p.verbatim_item();
4411 if (p.next_token().cat() == catBegin) {
4412 command = p.verbatim_item();
4413 ert += '{' + command + '}';
4415 command = p.verbatim_item();
4418 // If command is known, make name known too, to parse
4419 // its arguments correctly. For this reason we also
4420 // have commands in syntax.default that are hardcoded.
4421 CommandMap::iterator it = known_commands.find(command);
4422 if (it != known_commands.end())
4423 known_commands[t.asInput()] = it->second;
4424 output_ert_inset(os, ert, context);
4427 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4430 string name = t.asInput();
4431 string const length = p.verbatim_item();
4434 bool valid = splitLatexLength(length, valstring, unit);
4435 bool known_hspace = false;
4436 bool known_vspace = false;
4437 bool known_unit = false;
4440 istringstream iss(valstring);
4443 if (t.cs()[0] == 'h') {
4444 if (unit == "\\fill") {
4449 known_hspace = true;
4452 if (unit == "\\smallskipamount") {
4454 known_vspace = true;
4455 } else if (unit == "\\medskipamount") {
4457 known_vspace = true;
4458 } else if (unit == "\\bigskipamount") {
4460 known_vspace = true;
4461 } else if (unit == "\\fill") {
4463 known_vspace = true;
4467 if (!known_hspace && !known_vspace) {
4468 switch (unitFromString(unit)) {
4484 //unitFromString(unit) fails for relative units like Length::PCW
4485 // therefore handle them separately
4486 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4487 || unit == "\\textwidth" || unit == "\\linewidth"
4488 || unit == "\\textheight" || unit == "\\paperheight")
4496 // check for glue lengths
4497 bool is_gluelength = false;
4498 string gluelength = length;
4499 string::size_type i = length.find(" minus");
4500 if (i == string::npos) {
4501 i = length.find(" plus");
4502 if (i != string::npos)
4503 is_gluelength = true;
4505 is_gluelength = true;
4506 // if yes transform "9xx minus 8yy plus 7zz"
4508 if (is_gluelength) {
4509 i = gluelength.find(" minus");
4510 if (i != string::npos)
4511 gluelength.replace(i, 7, "-");
4512 i = gluelength.find(" plus");
4513 if (i != string::npos)
4514 gluelength.replace(i, 6, "+");
4517 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4518 // Literal horizontal length or known variable
4519 context.check_layout(os);
4520 begin_inset(os, "space ");
4528 if (known_unit && !known_hspace)
4529 os << "\n\\length " << translate_len(length);
4531 os << "\n\\length " << gluelength;
4533 } else if (known_unit || known_vspace || is_gluelength) {
4534 // Literal vertical length or known variable
4535 context.check_layout(os);
4536 begin_inset(os, "VSpace ");
4539 if (known_unit && !known_vspace)
4540 os << translate_len(length);
4547 // LyX can't handle other length variables in Inset VSpace/space
4552 output_ert_inset(os, name + '{' + unit + '}', context);
4553 else if (value == -1.0)
4554 output_ert_inset(os, name + "{-" + unit + '}', context);
4556 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4558 output_ert_inset(os, name + '{' + length + '}', context);
4562 // The single '=' is meant here.
4563 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4567 context.check_layout(os);
4568 docstring const name = newinsetlayout->name();
4569 bool const caption = name.find(from_ascii("Caption:")) == 0;
4571 begin_inset(os, "Caption ");
4572 os << to_utf8(name.substr(8)) << '\n';
4574 begin_inset(os, "Flex ");
4575 os << to_utf8(name) << '\n'
4576 << "status collapsed\n";
4578 if (newinsetlayout->isPassThru()) {
4579 // set catcodes to verbatim early, just in case.
4580 p.setCatcodes(VERBATIM_CATCODES);
4581 string delim = p.get_token().asInput();
4583 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4584 //FIXME: handle error condition
4585 string const arg = p.verbatimStuff("}").second;
4586 Context newcontext(true, context.textclass);
4587 if (newinsetlayout->forcePlainLayout())
4588 newcontext.layout = &context.textclass.plainLayout();
4589 output_ert(os, arg, newcontext);
4591 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4597 else if (t.cs() == "includepdf") {
4599 string const arg = p.getArg('[', ']');
4600 map<string, string> opts;
4601 vector<string> keys;
4602 split_map(arg, opts, keys);
4603 string name = normalize_filename(p.verbatim_item());
4604 string const path = getMasterFilePath(true);
4605 // We want to preserve relative / absolute filenames,
4606 // therefore path is only used for testing
4607 if (!makeAbsPath(name, path).exists()) {
4608 // The file extension is probably missing.
4609 // Now try to find it out.
4610 char const * const pdfpages_format[] = {"pdf", 0};
4611 string const pdftex_name =
4612 find_file(name, path, pdfpages_format);
4613 if (!pdftex_name.empty()) {
4618 FileName const absname = makeAbsPath(name, path);
4619 if (absname.exists())
4621 fix_child_filename(name);
4622 copy_file(absname, name);
4624 cerr << "Warning: Could not find file '"
4625 << name << "'." << endl;
4627 context.check_layout(os);
4628 begin_inset(os, "External\n\ttemplate ");
4629 os << "PDFPages\n\tfilename "
4631 // parse the options
4632 if (opts.find("pages") != opts.end())
4633 os << "\textra LaTeX \"pages="
4634 << opts["pages"] << "\"\n";
4635 if (opts.find("angle") != opts.end())
4636 os << "\trotateAngle "
4637 << opts["angle"] << '\n';
4638 if (opts.find("origin") != opts.end()) {
4640 string const opt = opts["origin"];
4641 if (opt == "tl") ss << "topleft";
4642 if (opt == "bl") ss << "bottomleft";
4643 if (opt == "Bl") ss << "baselineleft";
4644 if (opt == "c") ss << "center";
4645 if (opt == "tc") ss << "topcenter";
4646 if (opt == "bc") ss << "bottomcenter";
4647 if (opt == "Bc") ss << "baselinecenter";
4648 if (opt == "tr") ss << "topright";
4649 if (opt == "br") ss << "bottomright";
4650 if (opt == "Br") ss << "baselineright";
4651 if (!ss.str().empty())
4652 os << "\trotateOrigin " << ss.str() << '\n';
4654 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4656 if (opts.find("width") != opts.end())
4658 << translate_len(opts["width"]) << '\n';
4659 if (opts.find("height") != opts.end())
4661 << translate_len(opts["height"]) << '\n';
4662 if (opts.find("keepaspectratio") != opts.end())
4663 os << "\tkeepAspectRatio\n";
4665 context.check_layout(os);
4666 registerExternalTemplatePackages("PDFPages");
4669 else if (t.cs() == "loadgame") {
4671 string name = normalize_filename(p.verbatim_item());
4672 string const path = getMasterFilePath(true);
4673 // We want to preserve relative / absolute filenames,
4674 // therefore path is only used for testing
4675 if (!makeAbsPath(name, path).exists()) {
4676 // The file extension is probably missing.
4677 // Now try to find it out.
4678 char const * const lyxskak_format[] = {"fen", 0};
4679 string const lyxskak_name =
4680 find_file(name, path, lyxskak_format);
4681 if (!lyxskak_name.empty())
4682 name = lyxskak_name;
4684 FileName const absname = makeAbsPath(name, path);
4685 if (absname.exists())
4687 fix_child_filename(name);
4688 copy_file(absname, name);
4690 cerr << "Warning: Could not find file '"
4691 << name << "'." << endl;
4692 context.check_layout(os);
4693 begin_inset(os, "External\n\ttemplate ");
4694 os << "ChessDiagram\n\tfilename "
4697 context.check_layout(os);
4698 // after a \loadgame follows a \showboard
4699 if (p.get_token().asInput() == "showboard")
4701 registerExternalTemplatePackages("ChessDiagram");
4705 // try to see whether the string is in unicodesymbols
4706 // Only use text mode commands, since we are in text mode here,
4707 // and math commands may be invalid (bug 6797)
4708 string name = t.asInput();
4709 // handle the dingbats, cyrillic and greek
4710 if (name == "\\ding" || name == "\\textcyr" ||
4711 (name == "\\textgreek" && !preamble.usePolyglossia()))
4712 name = name + '{' + p.getArg('{', '}') + '}';
4713 // handle the ifsym characters
4714 else if (name == "\\textifsymbol") {
4715 string const optif = p.getFullOpt();
4716 string const argif = p.getArg('{', '}');
4717 name = name + optif + '{' + argif + '}';
4719 // handle the \ascii characters
4720 // the case of \ascii within braces, as LyX outputs it, is already
4721 // handled for t.cat() == catBegin
4722 else if (name == "\\ascii") {
4723 // the code is "\asci\xxx"
4724 name = "{" + name + p.get_token().asInput() + "}";
4727 // handle some TIPA special characters
4728 else if (preamble.isPackageUsed("tipa")) {
4729 if (name == "\\textglobfall") {
4732 } else if (name == "\\s") {
4733 // fromLaTeXCommand() does not yet
4734 // recognize tipa short cuts
4735 name = "\\textsyllabic";
4736 } else if (name == "\\=" &&
4737 p.next_token().asInput() == "*") {
4738 // fromLaTeXCommand() does not yet
4739 // recognize tipa short cuts
4742 } else if (name == "\\textdoublevertline") {
4743 // FIXME: This is not correct,
4744 // \textvertline is higher than \textbardbl
4745 name = "\\textbardbl";
4747 } else if (name == "\\!" ) {
4748 if (p.next_token().asInput() == "b") {
4749 p.get_token(); // eat 'b'
4752 } else if (p.next_token().asInput() == "d") {
4756 } else if (p.next_token().asInput() == "g") {
4760 } else if (p.next_token().asInput() == "G") {
4762 name = "\\texthtscg";
4764 } else if (p.next_token().asInput() == "j") {
4766 name = "\\texthtbardotlessj";
4768 } else if (p.next_token().asInput() == "o") {
4770 name = "\\textbullseye";
4773 } else if (name == "\\*" ) {
4774 if (p.next_token().asInput() == "k") {
4776 name = "\\textturnk";
4778 } else if (p.next_token().asInput() == "r") {
4779 p.get_token(); // eat 'b'
4780 name = "\\textturnr";
4782 } else if (p.next_token().asInput() == "t") {
4784 name = "\\textturnt";
4786 } else if (p.next_token().asInput() == "w") {
4788 name = "\\textturnw";
4793 if ((name.size() == 2 &&
4794 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4795 p.next_token().asInput() != "*") ||
4796 is_known(name.substr(1), known_tipa_marks)) {
4797 // name is a command that corresponds to a
4798 // combining character in unicodesymbols.
4799 // Append the argument, fromLaTeXCommand()
4800 // will either convert it to a single
4801 // character or a combining sequence.
4802 name += '{' + p.verbatim_item() + '}';
4804 // now get the character from unicodesymbols
4808 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4809 Encodings::TEXT_CMD, termination, rem, &req);
4811 context.check_layout(os);
4814 output_ert_inset(os, to_utf8(rem), context);
4816 skip_spaces_braces(p);
4817 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4818 preamble.registerAutomaticallyLoadedPackage(*it);
4820 //cerr << "#: " << t << " mode: " << mode << endl;
4821 // heuristic: read up to next non-nested space
4823 string s = t.asInput();
4824 string z = p.verbatim_item();
4825 while (p.good() && z != " " && !z.empty()) {
4826 //cerr << "read: " << z << endl;
4828 z = p.verbatim_item();
4830 cerr << "found ERT: " << s << endl;
4831 output_ert_inset(os, s + ' ', context);
4834 if (t.asInput() == name &&
4835 p.next_token().asInput() == "*") {
4836 // Starred commands like \vspace*{}
4837 p.get_token(); // Eat '*'
4840 if (!parse_command(name, p, os, outer, context))
4841 output_ert_inset(os, name, context);
4845 if (flags & FLAG_LEAVE) {
4846 flags &= ~FLAG_LEAVE;
4853 string guessLanguage(Parser & p, string const & lang)
4855 typedef std::map<std::string, size_t> LangMap;
4856 // map from language names to number of characters
4859 for (char const * const * i = supported_CJK_languages; *i; i++)
4860 used[string(*i)] = 0;
4863 Token const t = p.get_token();
4864 // comments are not counted for any language
4865 if (t.cat() == catComment)
4867 // commands are not counted as well, but we need to detect
4868 // \begin{CJK} and switch encoding if needed
4869 if (t.cat() == catEscape) {
4870 if (t.cs() == "inputencoding") {
4871 string const enc = subst(p.verbatim_item(), "\n", " ");
4872 p.setEncoding(enc, Encoding::inputenc);
4875 if (t.cs() != "begin")
4878 // Non-CJK content is counted for lang.
4879 // We do not care about the real language here:
4880 // If we have more non-CJK contents than CJK contents,
4881 // we simply use the language that was specified as
4882 // babel main language.
4883 used[lang] += t.asInput().length();
4886 // Now we are starting an environment
4888 string const name = p.getArg('{', '}');
4889 if (name != "CJK") {
4893 // It is a CJK environment
4895 /* name = */ p.getArg('{', '}');
4896 string const encoding = p.getArg('{', '}');
4897 /* mapping = */ p.getArg('{', '}');
4898 string const encoding_old = p.getEncoding();
4899 char const * const * const where =
4900 is_known(encoding, supported_CJK_encodings);
4902 p.setEncoding(encoding, Encoding::CJK);
4904 p.setEncoding("UTF-8");
4905 string const text = p.ertEnvironment("CJK");
4906 p.setEncoding(encoding_old);
4909 // ignore contents in unknown CJK encoding
4912 // the language of the text
4914 supported_CJK_languages[where - supported_CJK_encodings];
4915 used[cjk] += text.length();
4917 LangMap::const_iterator use = used.begin();
4918 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4919 if (it->second > use->second)