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")
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";
1122 os << "has_inner_box " << !inner_type.empty() << "\n";
1123 os << "inner_pos \"" << inner_pos << "\"\n";
1124 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1126 if (outer_type == "mbox")
1127 os << "use_makebox 1\n";
1129 os << "use_makebox " << (inner_type == "makebox") << '\n';
1130 if (outer_type == "mbox")
1131 os << "width \"\"\n";
1132 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1133 else if (contains(width_unit, '\\'))
1134 os << "width \"" << width_value << "in" << "\"\n";
1136 os << "width \"" << width_value << width_unit << "\"\n";
1137 if (contains(width_unit, '\\')) {
1138 width_unit.erase (0,1); // remove the leading '\'
1139 os << "special \"" << width_unit << "\"\n";
1141 os << "special \"" << width_special << "\"\n";
1142 if (contains(height_unit, '\\'))
1143 os << "height \"" << height_value << "in" << "\"\n";
1145 os << "height \"" << height_value << height_unit << "\"\n";
1146 os << "height_special \"" << height_special << "\"\n";
1147 os << "thickness \"" << thickness << "\"\n";
1148 os << "separation \"" << separation << "\"\n";
1149 os << "shadowsize \"" << shadowsize << "\"\n";
1150 os << "framecolor \"" << framecolor << "\"\n";
1151 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1152 os << "status open\n\n";
1154 // Unfortunately we can't use parse_text_in_inset:
1155 // InsetBox::forcePlainLayout() is hard coded and does not
1156 // use the inset layout. Apart from that do we call parse_text
1157 // up to two times, but need only one check_end_layout.
1158 bool const forcePlainLayout =
1159 (!inner_type.empty() || inner_type == "makebox") &&
1160 outer_type != "shaded" && outer_type != "framed";
1161 Context context(true, parent_context.textclass);
1162 if (forcePlainLayout)
1163 context.layout = &context.textclass.plainLayout();
1165 context.font = parent_context.font;
1167 // If we have no inner box the contents will be read with the outer box
1168 if (!inner_type.empty())
1169 parse_text(p, os, inner_flags, outer, context);
1171 // Ensure that the end of the outer box is parsed correctly:
1172 // The opening brace has been eaten by parse_outer_box()
1173 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1174 outer_flags &= ~FLAG_ITEM;
1175 outer_flags |= FLAG_BRACE_LAST;
1178 // Find end of outer box, output contents if inner_type is
1179 // empty and output possible comments
1180 if (!outer_type.empty()) {
1181 // If we already read the inner box we have to pop
1183 if (!inner_type.empty() && (inner_flags & FLAG_END))
1184 active_environments.pop_back();
1185 // This does not output anything but comments if
1186 // inner_type is not empty (see use_ert)
1187 parse_text(p, os, outer_flags, outer, context);
1190 context.check_end_layout(os);
1192 #ifdef PRESERVE_LAYOUT
1193 // LyX puts a % after the end of the minipage
1194 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1196 //output_ert_inset(os, "%dummy", parent_context);
1199 parent_context.new_paragraph(os);
1201 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1202 //output_ert_inset(os, "%dummy", parent_context);
1205 // We add a protected space if something real follows
1206 if (p.good() && p.next_token().cat() != catComment) {
1207 begin_inset(os, "space ~\n");
1213 if (background_color != "") {
1214 // in this case we have to eat the the closing brace of the color box
1215 p.get_token().asInput(); // the '}'
1217 if (p.next_token().asInput() == "}"
1218 && (fboxrule != "" || fboxsep != "" || shadow_size != "")) {
1219 // in this case we assume that the closing brace is from the box settings
1220 // therefore reset these values for the next box
1225 if (shadow_size != "")
1231 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1232 Context & parent_context, string const & outer_type,
1233 string const & special)
1235 eat_whitespace(p, os, parent_context, false);
1236 if (flags & FLAG_ITEM) {
1238 if (p.next_token().cat() == catBegin)
1241 cerr << "Warning: Ignoring missing '{' after \\"
1242 << outer_type << '.' << endl;
1243 eat_whitespace(p, os, parent_context, false);
1246 unsigned int inner_flags = 0;
1248 if (outer_type == "minipage" || outer_type == "parbox") {
1249 p.skip_spaces(true);
1250 while (p.hasOpt()) {
1252 p.skip_spaces(true);
1255 p.skip_spaces(true);
1256 if (outer_type == "parbox") {
1258 if (p.next_token().cat() == catBegin)
1260 p.skip_spaces(true);
1263 if (outer_type == "shaded" || outer_type == "mbox") {
1264 // These boxes never have an inner box
1266 } else if (p.next_token().asInput() == "\\parbox") {
1267 inner = p.get_token().cs();
1268 inner_flags = FLAG_ITEM;
1269 } else if (p.next_token().asInput() == "\\begin") {
1270 // Is this a minipage or shaded box?
1273 inner = p.getArg('{', '}');
1275 if (inner == "minipage" || inner == "shaded")
1276 inner_flags = FLAG_END;
1281 if (inner_flags == FLAG_END) {
1282 if (inner != "shaded")
1286 eat_whitespace(p, os, parent_context, false);
1288 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1289 outer_type, special, inner, "", "");
1291 if (inner_flags == FLAG_ITEM) {
1293 eat_whitespace(p, os, parent_context, false);
1295 parse_box(p, os, flags, inner_flags, outer, parent_context,
1296 outer_type, special, inner, "", "");
1301 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1303 parent_context.check_layout(os);
1304 begin_inset(os, "listings\n");
1306 string arg = p.verbatimOption();
1307 os << "lstparams " << '"' << arg << '"' << '\n';
1308 if (arg.find("\\color") != string::npos)
1309 preamble.registerAutomaticallyLoadedPackage("color");
1312 os << "inline true\n";
1314 os << "inline false\n";
1315 os << "status collapsed\n";
1316 Context context(true, parent_context.textclass);
1317 context.layout = &parent_context.textclass.plainLayout();
1320 // set catcodes to verbatim early, just in case.
1321 p.setCatcodes(VERBATIM_CATCODES);
1322 string delim = p.get_token().asInput();
1323 //FIXME: handler error condition
1324 s = p.verbatimStuff(delim).second;
1325 // context.new_paragraph(os);
1327 s = p.verbatimEnvironment("lstlisting");
1328 output_ert(os, s, context);
1333 /// parse an unknown environment
1334 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1335 unsigned flags, bool outer,
1336 Context & parent_context)
1338 if (name == "tabbing")
1339 // We need to remember that we have to handle '\=' specially
1340 flags |= FLAG_TABBING;
1342 // We need to translate font changes and paragraphs inside the
1343 // environment to ERT if we have a non standard font.
1344 // Otherwise things like
1345 // \large\begin{foo}\huge bar\end{foo}
1347 bool const specialfont =
1348 (parent_context.font != parent_context.normalfont);
1349 bool const new_layout_allowed = parent_context.new_layout_allowed;
1351 parent_context.new_layout_allowed = false;
1352 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1353 parse_text_snippet(p, os, flags, outer, parent_context);
1354 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1356 parent_context.new_layout_allowed = new_layout_allowed;
1360 void parse_environment(Parser & p, ostream & os, bool outer,
1361 string & last_env, Context & parent_context)
1363 Layout const * newlayout;
1364 InsetLayout const * newinsetlayout = 0;
1365 string const name = p.getArg('{', '}');
1366 const bool is_starred = suffixIs(name, '*');
1367 string const unstarred_name = rtrim(name, "*");
1368 active_environments.push_back(name);
1370 if (is_math_env(name)) {
1371 parent_context.check_layout(os);
1372 begin_inset(os, "Formula ");
1373 os << "\\begin{" << name << "}";
1374 parse_math(p, os, FLAG_END, MATH_MODE);
1375 os << "\\end{" << name << "}";
1377 if (is_display_math_env(name)) {
1378 // Prevent the conversion of a line break to a space
1379 // (bug 7668). This does not change the output, but
1380 // looks ugly in LyX.
1381 eat_whitespace(p, os, parent_context, false);
1385 else if (is_known(name, preamble.polyglossia_languages)) {
1386 // We must begin a new paragraph if not already done
1387 if (! parent_context.atParagraphStart()) {
1388 parent_context.check_end_layout(os);
1389 parent_context.new_paragraph(os);
1391 // save the language in the context so that it is
1392 // handled by parse_text
1393 parent_context.font.language = preamble.polyglossia2lyx(name);
1394 parse_text(p, os, FLAG_END, outer, parent_context);
1395 // Just in case the environment is empty
1396 parent_context.extra_stuff.erase();
1397 // We must begin a new paragraph to reset the language
1398 parent_context.new_paragraph(os);
1402 else if (unstarred_name == "tabular" || name == "longtable") {
1403 eat_whitespace(p, os, parent_context, false);
1404 string width = "0pt";
1405 if (name == "tabular*") {
1406 width = lyx::translate_len(p.getArg('{', '}'));
1407 eat_whitespace(p, os, parent_context, false);
1409 parent_context.check_layout(os);
1410 begin_inset(os, "Tabular ");
1411 handle_tabular(p, os, name, width, parent_context);
1416 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1417 eat_whitespace(p, os, parent_context, false);
1418 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1419 eat_whitespace(p, os, parent_context, false);
1420 parent_context.check_layout(os);
1421 begin_inset(os, "Float " + unstarred_name + "\n");
1422 // store the float type for subfloats
1423 // subfloats only work with figures and tables
1424 if (unstarred_name == "figure")
1425 float_type = unstarred_name;
1426 else if (unstarred_name == "table")
1427 float_type = unstarred_name;
1431 os << "placement " << opt << '\n';
1432 if (contains(opt, "H"))
1433 preamble.registerAutomaticallyLoadedPackage("float");
1435 Floating const & fl = parent_context.textclass.floats()
1436 .getType(unstarred_name);
1437 if (!fl.floattype().empty() && fl.usesFloatPkg())
1438 preamble.registerAutomaticallyLoadedPackage("float");
1441 os << "wide " << convert<string>(is_starred)
1442 << "\nsideways false"
1443 << "\nstatus open\n\n";
1444 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1446 // We don't need really a new paragraph, but
1447 // we must make sure that the next item gets a \begin_layout.
1448 parent_context.new_paragraph(os);
1450 // the float is parsed thus delete the type
1454 else if (unstarred_name == "sidewaysfigure"
1455 || unstarred_name == "sidewaystable") {
1456 eat_whitespace(p, os, parent_context, false);
1457 parent_context.check_layout(os);
1458 if (unstarred_name == "sidewaysfigure")
1459 begin_inset(os, "Float figure\n");
1461 begin_inset(os, "Float table\n");
1462 os << "wide " << convert<string>(is_starred)
1463 << "\nsideways true"
1464 << "\nstatus open\n\n";
1465 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1467 // We don't need really a new paragraph, but
1468 // we must make sure that the next item gets a \begin_layout.
1469 parent_context.new_paragraph(os);
1471 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1474 else if (name == "wrapfigure" || name == "wraptable") {
1475 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1476 eat_whitespace(p, os, parent_context, false);
1477 parent_context.check_layout(os);
1480 string overhang = "0col%";
1483 lines = p.getArg('[', ']');
1484 string const placement = p.getArg('{', '}');
1486 overhang = p.getArg('[', ']');
1487 string const width = p.getArg('{', '}');
1489 if (name == "wrapfigure")
1490 begin_inset(os, "Wrap figure\n");
1492 begin_inset(os, "Wrap table\n");
1493 os << "lines " << lines
1494 << "\nplacement " << placement
1495 << "\noverhang " << lyx::translate_len(overhang)
1496 << "\nwidth " << lyx::translate_len(width)
1497 << "\nstatus open\n\n";
1498 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1500 // We don't need really a new paragraph, but
1501 // we must make sure that the next item gets a \begin_layout.
1502 parent_context.new_paragraph(os);
1504 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1507 else if (name == "minipage") {
1508 eat_whitespace(p, os, parent_context, false);
1509 // Test whether this is an outer box of a shaded box
1511 // swallow arguments
1512 while (p.hasOpt()) {
1514 p.skip_spaces(true);
1517 p.skip_spaces(true);
1518 Token t = p.get_token();
1519 bool shaded = false;
1520 if (t.asInput() == "\\begin") {
1521 p.skip_spaces(true);
1522 if (p.getArg('{', '}') == "shaded")
1527 parse_outer_box(p, os, FLAG_END, outer,
1528 parent_context, name, "shaded");
1530 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1531 "", "", name, "", "");
1535 else if (name == "comment") {
1536 eat_whitespace(p, os, parent_context, false);
1537 parent_context.check_layout(os);
1538 begin_inset(os, "Note Comment\n");
1539 os << "status open\n";
1540 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1543 skip_braces(p); // eat {} that might by set by LyX behind comments
1544 preamble.registerAutomaticallyLoadedPackage("verbatim");
1547 else if (name == "verbatim") {
1548 // FIXME: this should go in the generic code that
1549 // handles environments defined in layout file that
1550 // have "PassThru 1". However, the code over there is
1551 // already too complicated for my taste.
1552 parent_context.new_paragraph(os);
1553 Context context(true, parent_context.textclass,
1554 &parent_context.textclass[from_ascii("Verbatim")]);
1555 string s = p.verbatimEnvironment("verbatim");
1556 output_ert(os, s, context);
1560 else if (name == "IPA") {
1561 eat_whitespace(p, os, parent_context, false);
1562 parent_context.check_layout(os);
1563 begin_inset(os, "IPA\n");
1564 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1567 preamble.registerAutomaticallyLoadedPackage("tipa");
1568 preamble.registerAutomaticallyLoadedPackage("tipx");
1571 else if (name == "CJK") {
1572 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1573 // It is impossible to decide if a CJK environment was in its own paragraph or within
1574 // a line. We therefore always assume a paragraph since the latter is a rare case.
1575 eat_whitespace(p, os, parent_context, false);
1576 parent_context.check_end_layout(os);
1577 // store the encoding to be able to reset it
1578 string const encoding_old = p.getEncoding();
1579 string const encoding = p.getArg('{', '}');
1580 // FIXME: For some reason JIS does not work. Although the text
1581 // in tests/CJK.tex is identical with the SJIS version if you
1582 // convert both snippets using the recode command line utility,
1583 // the resulting .lyx file contains some extra characters if
1584 // you set buggy_encoding to false for JIS.
1585 bool const buggy_encoding = encoding == "JIS";
1586 if (!buggy_encoding)
1587 p.setEncoding(encoding, Encoding::CJK);
1589 // FIXME: This will read garbage, since the data is not encoded in utf8.
1590 p.setEncoding("UTF-8");
1592 // LyX only supports the same mapping for all CJK
1593 // environments, so we might need to output everything as ERT
1594 string const mapping = trim(p.getArg('{', '}'));
1595 char const * const * const where =
1596 is_known(encoding, supported_CJK_encodings);
1597 if (!buggy_encoding && !preamble.fontCJKSet())
1598 preamble.fontCJK(mapping);
1599 bool knownMapping = mapping == preamble.fontCJK();
1600 if (buggy_encoding || !knownMapping || !where) {
1601 parent_context.check_layout(os);
1602 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1604 // we must parse the content as verbatim because e.g. JIS can contain
1605 // normally invalid characters
1606 // FIXME: This works only for the most simple cases.
1607 // Since TeX control characters are not parsed,
1608 // things like comments are completely wrong.
1609 string const s = p.plainEnvironment("CJK");
1610 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1612 output_ert_inset(os, "\\", parent_context);
1613 else if (*it == '$')
1614 output_ert_inset(os, "$", parent_context);
1615 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1620 output_ert_inset(os, "\\end{" + name + "}",
1624 supported_CJK_languages[where - supported_CJK_encodings];
1625 // store the language because we must reset it at the end
1626 string const lang_old = parent_context.font.language;
1627 parent_context.font.language = lang;
1628 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1629 parent_context.font.language = lang_old;
1630 parent_context.new_paragraph(os);
1632 p.setEncoding(encoding_old);
1636 else if (name == "lyxgreyedout") {
1637 eat_whitespace(p, os, parent_context, false);
1638 parent_context.check_layout(os);
1639 begin_inset(os, "Note Greyedout\n");
1640 os << "status open\n";
1641 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1644 if (!preamble.notefontcolor().empty())
1645 preamble.registerAutomaticallyLoadedPackage("color");
1648 else if (name == "btSect") {
1649 eat_whitespace(p, os, parent_context, false);
1650 parent_context.check_layout(os);
1651 begin_command_inset(os, "bibtex", "bibtex");
1652 string bibstyle = "plain";
1654 bibstyle = p.getArg('[', ']');
1655 p.skip_spaces(true);
1657 string const bibfile = p.getArg('{', '}');
1658 eat_whitespace(p, os, parent_context, false);
1659 Token t = p.get_token();
1660 if (t.asInput() == "\\btPrintCited") {
1661 p.skip_spaces(true);
1662 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1664 if (t.asInput() == "\\btPrintNotCited") {
1665 p.skip_spaces(true);
1666 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1668 if (t.asInput() == "\\btPrintAll") {
1669 p.skip_spaces(true);
1670 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1672 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1673 os << "options " << '"' << bibstyle << '"' << "\n";
1674 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1679 else if (name == "framed" || name == "shaded") {
1680 eat_whitespace(p, os, parent_context, false);
1681 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1685 else if (name == "lstlisting") {
1686 eat_whitespace(p, os, parent_context, false);
1687 parse_listings(p, os, parent_context, false);
1691 else if (!parent_context.new_layout_allowed)
1692 parse_unknown_environment(p, name, os, FLAG_END, outer,
1695 // Alignment and spacing settings
1696 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1697 // therefore are totally broken!
1698 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1699 // they are commands not environments. They are furthermore switches that
1700 // can be ended by another switches, but also by commands like \footnote or
1701 // \parbox. So the only safe way is to leave them untouched.
1702 else if (name == "center" || name == "centering" ||
1703 name == "flushleft" || name == "flushright" ||
1704 name == "singlespace" || name == "onehalfspace" ||
1705 name == "doublespace" || name == "spacing") {
1706 eat_whitespace(p, os, parent_context, false);
1707 // We must begin a new paragraph if not already done
1708 if (! parent_context.atParagraphStart()) {
1709 parent_context.check_end_layout(os);
1710 parent_context.new_paragraph(os);
1712 if (name == "flushleft")
1713 parent_context.add_extra_stuff("\\align left\n");
1714 else if (name == "flushright")
1715 parent_context.add_extra_stuff("\\align right\n");
1716 else if (name == "center" || name == "centering")
1717 parent_context.add_extra_stuff("\\align center\n");
1718 else if (name == "singlespace")
1719 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1720 else if (name == "onehalfspace") {
1721 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1722 preamble.registerAutomaticallyLoadedPackage("setspace");
1723 } else if (name == "doublespace") {
1724 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1725 preamble.registerAutomaticallyLoadedPackage("setspace");
1726 } else if (name == "spacing") {
1727 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1728 preamble.registerAutomaticallyLoadedPackage("setspace");
1730 parse_text(p, os, FLAG_END, outer, parent_context);
1731 // Just in case the environment is empty
1732 parent_context.extra_stuff.erase();
1733 // We must begin a new paragraph to reset the alignment
1734 parent_context.new_paragraph(os);
1738 // The single '=' is meant here.
1739 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1740 eat_whitespace(p, os, parent_context, false);
1741 Context context(true, parent_context.textclass, newlayout,
1742 parent_context.layout, parent_context.font);
1743 if (parent_context.deeper_paragraph) {
1744 // We are beginning a nested environment after a
1745 // deeper paragraph inside the outer list environment.
1746 // Therefore we don't need to output a "begin deeper".
1747 context.need_end_deeper = true;
1749 parent_context.check_end_layout(os);
1750 if (last_env == name) {
1751 // we need to output a separator since LyX would export
1752 // the two environments as one otherwise (bug 5716)
1753 TeX2LyXDocClass const & textclass(parent_context.textclass);
1754 Context newcontext(true, textclass,
1755 &(textclass.defaultLayout()));
1756 newcontext.check_layout(os);
1757 begin_inset(os, "Separator plain\n");
1759 newcontext.check_end_layout(os);
1761 switch (context.layout->latextype) {
1762 case LATEX_LIST_ENVIRONMENT:
1763 context.add_par_extra_stuff("\\labelwidthstring "
1764 + p.verbatim_item() + '\n');
1767 case LATEX_BIB_ENVIRONMENT:
1768 p.verbatim_item(); // swallow next arg
1774 context.check_deeper(os);
1775 // handle known optional and required arguments
1776 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1777 // It is impossible to place anything after the environment name,
1778 // but before the first \\item.
1779 if (context.layout->latextype == LATEX_ENVIRONMENT)
1780 output_arguments(os, p, outer, false, false, context,
1781 context.layout->latexargs());
1782 parse_text(p, os, FLAG_END, outer, context);
1783 if (context.layout->latextype == LATEX_ENVIRONMENT)
1784 output_arguments(os, p, outer, false, true, context,
1785 context.layout->postcommandargs());
1786 context.check_end_layout(os);
1787 if (parent_context.deeper_paragraph) {
1788 // We must suppress the "end deeper" because we
1789 // suppressed the "begin deeper" above.
1790 context.need_end_deeper = false;
1792 context.check_end_deeper(os);
1793 parent_context.new_paragraph(os);
1795 if (!preamble.titleLayoutFound())
1796 preamble.titleLayoutFound(newlayout->intitle);
1797 set<string> const & req = newlayout->requires();
1798 set<string>::const_iterator it = req.begin();
1799 set<string>::const_iterator en = req.end();
1800 for (; it != en; ++it)
1801 preamble.registerAutomaticallyLoadedPackage(*it);
1804 // The single '=' is meant here.
1805 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1806 eat_whitespace(p, os, parent_context, false);
1807 parent_context.check_layout(os);
1808 begin_inset(os, "Flex ");
1809 os << to_utf8(newinsetlayout->name()) << '\n'
1810 << "status collapsed\n";
1811 if (newinsetlayout->isPassThru()) {
1812 string const arg = p.verbatimEnvironment(name);
1813 Context context(true, parent_context.textclass,
1814 &parent_context.textclass.plainLayout(),
1815 parent_context.layout);
1816 output_ert(os, arg, parent_context);
1818 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1822 else if (name == "appendix") {
1823 // This is no good latex style, but it works and is used in some documents...
1824 eat_whitespace(p, os, parent_context, false);
1825 parent_context.check_end_layout(os);
1826 Context context(true, parent_context.textclass, parent_context.layout,
1827 parent_context.layout, parent_context.font);
1828 context.check_layout(os);
1829 os << "\\start_of_appendix\n";
1830 parse_text(p, os, FLAG_END, outer, context);
1831 context.check_end_layout(os);
1835 else if (known_environments.find(name) != known_environments.end()) {
1836 vector<ArgumentType> arguments = known_environments[name];
1837 // The last "argument" denotes wether we may translate the
1838 // environment contents to LyX
1839 // The default required if no argument is given makes us
1840 // compatible with the reLyXre environment.
1841 ArgumentType contents = arguments.empty() ?
1844 if (!arguments.empty())
1845 arguments.pop_back();
1846 // See comment in parse_unknown_environment()
1847 bool const specialfont =
1848 (parent_context.font != parent_context.normalfont);
1849 bool const new_layout_allowed =
1850 parent_context.new_layout_allowed;
1852 parent_context.new_layout_allowed = false;
1853 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1854 outer, parent_context);
1855 if (contents == verbatim)
1856 output_ert_inset(os, p.ertEnvironment(name),
1859 parse_text_snippet(p, os, FLAG_END, outer,
1861 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1863 parent_context.new_layout_allowed = new_layout_allowed;
1867 parse_unknown_environment(p, name, os, FLAG_END, outer,
1871 active_environments.pop_back();
1875 /// parses a comment and outputs it to \p os.
1876 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1878 LASSERT(t.cat() == catComment, return);
1879 if (!t.cs().empty()) {
1880 context.check_layout(os);
1881 output_ert_inset(os, '%' + t.cs(), context);
1882 if (p.next_token().cat() == catNewline) {
1883 // A newline after a comment line starts a new
1885 if (context.new_layout_allowed) {
1886 if(!context.atParagraphStart())
1887 // Only start a new paragraph if not already
1888 // done (we might get called recursively)
1889 context.new_paragraph(os);
1891 output_ert_inset(os, "\n", context);
1892 eat_whitespace(p, os, context, true);
1895 // "%\n" combination
1902 * Reads spaces and comments until the first non-space, non-comment token.
1903 * New paragraphs (double newlines or \\par) are handled like simple spaces
1904 * if \p eatParagraph is true.
1905 * Spaces are skipped, but comments are written to \p os.
1907 void eat_whitespace(Parser & p, ostream & os, Context & context,
1911 Token const & t = p.get_token();
1912 if (t.cat() == catComment)
1913 parse_comment(p, os, t, context);
1914 else if ((! eatParagraph && p.isParagraph()) ||
1915 (t.cat() != catSpace && t.cat() != catNewline)) {
1924 * Set a font attribute, parse text and reset the font attribute.
1925 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1926 * \param currentvalue Current value of the attribute. Is set to the new
1927 * value during parsing.
1928 * \param newvalue New value of the attribute
1930 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1931 Context & context, string const & attribute,
1932 string & currentvalue, string const & newvalue)
1934 context.check_layout(os);
1935 string const oldvalue = currentvalue;
1936 currentvalue = newvalue;
1937 os << '\n' << attribute << ' ' << newvalue << "\n";
1938 parse_text_snippet(p, os, flags, outer, context);
1939 context.check_layout(os);
1940 os << '\n' << attribute << ' ' << oldvalue << "\n";
1941 currentvalue = oldvalue;
1945 /// get the arguments of a natbib or jurabib citation command
1946 void get_cite_arguments(Parser & p, bool natbibOrder,
1947 string & before, string & after)
1949 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1951 // text before the citation
1953 // text after the citation
1954 after = p.getFullOpt();
1956 if (!after.empty()) {
1957 before = p.getFullOpt();
1958 if (natbibOrder && !before.empty())
1959 swap(before, after);
1964 /// Convert filenames with TeX macros and/or quotes to something LyX
1966 string const normalize_filename(string const & name)
1971 Token const & t = p.get_token();
1972 if (t.cat() != catEscape)
1974 else if (t.cs() == "lyxdot") {
1975 // This is used by LyX for simple dots in relative
1979 } else if (t.cs() == "space") {
1982 } else if (t.cs() == "string") {
1983 // Convert \string" to " and \string~ to ~
1984 Token const & n = p.next_token();
1985 if (n.asInput() != "\"" && n.asInput() != "~")
1990 // Strip quotes. This is a bit complicated (see latex_path()).
1991 string full = os.str();
1992 if (!full.empty() && full[0] == '"') {
1993 string base = removeExtension(full);
1994 string ext = getExtension(full);
1995 if (!base.empty() && base[base.length()-1] == '"')
1998 return addExtension(trim(base, "\""), ext);
1999 if (full[full.length()-1] == '"')
2002 return trim(full, "\"");
2008 /// Convert \p name from TeX convention (relative to master file) to LyX
2009 /// convention (relative to .lyx file) if it is relative
2010 void fix_child_filename(string & name)
2012 string const absMasterTeX = getMasterFilePath(true);
2013 bool const isabs = FileName::isAbsolute(name);
2014 // convert from "relative to .tex master" to absolute original path
2016 name = makeAbsPath(name, absMasterTeX).absFileName();
2017 bool copyfile = copyFiles();
2018 string const absParentLyX = getParentFilePath(false);
2021 // convert from absolute original path to "relative to master file"
2022 string const rel = to_utf8(makeRelPath(from_utf8(name),
2023 from_utf8(absMasterTeX)));
2024 // re-interpret "relative to .tex file" as "relative to .lyx file"
2025 // (is different if the master .lyx file resides in a
2026 // different path than the master .tex file)
2027 string const absMasterLyX = getMasterFilePath(false);
2028 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2029 // Do not copy if the new path is impossible to create. Example:
2030 // absMasterTeX = "/foo/bar/"
2031 // absMasterLyX = "/bar/"
2032 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2033 if (contains(name, "/../"))
2040 // convert from absolute original path to
2041 // "relative to .lyx file"
2042 name = to_utf8(makeRelPath(from_utf8(abs),
2043 from_utf8(absParentLyX)));
2047 // convert from absolute original path to "relative to .lyx file"
2048 name = to_utf8(makeRelPath(from_utf8(name),
2049 from_utf8(absParentLyX)));
2054 void copy_file(FileName const & src, string dstname)
2058 string const absParent = getParentFilePath(false);
2060 if (FileName::isAbsolute(dstname))
2061 dst = FileName(dstname);
2063 dst = makeAbsPath(dstname, absParent);
2064 string const absMaster = getMasterFilePath(false);
2065 FileName const srcpath = src.onlyPath();
2066 FileName const dstpath = dst.onlyPath();
2067 if (equivalent(srcpath, dstpath))
2069 if (!dstpath.isDirectory()) {
2070 if (!dstpath.createPath()) {
2071 cerr << "Warning: Could not create directory for file `"
2072 << dst.absFileName() << "´." << endl;
2076 if (dst.isReadableFile()) {
2077 if (overwriteFiles())
2078 cerr << "Warning: Overwriting existing file `"
2079 << dst.absFileName() << "´." << endl;
2081 cerr << "Warning: Not overwriting existing file `"
2082 << dst.absFileName() << "´." << endl;
2086 if (!src.copyTo(dst))
2087 cerr << "Warning: Could not copy file `" << src.absFileName()
2088 << "´ to `" << dst.absFileName() << "´." << endl;
2092 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2093 bool parse_chunk(Parser & p, ostream & os, Context & context)
2095 // check whether a chunk is possible here.
2096 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2102 // read the parameters
2103 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2104 if (!params.first) {
2109 Parser::Arg const code = p.verbatimStuff("\n@");
2114 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2115 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2119 // The last newline read is important for paragraph handling
2123 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2124 // We must have a valid layout before outputting the Chunk inset.
2125 context.check_layout(os);
2126 Context chunkcontext(true, context.textclass);
2127 chunkcontext.layout = &context.textclass.plainLayout();
2128 begin_inset(os, "Flex Chunk");
2129 os << "\nstatus open\n";
2130 if (!params.second.empty()) {
2131 chunkcontext.check_layout(os);
2132 Context paramscontext(true, context.textclass);
2133 paramscontext.layout = &context.textclass.plainLayout();
2134 begin_inset(os, "Argument 1");
2135 os << "\nstatus open\n";
2136 output_ert(os, params.second, paramscontext);
2139 output_ert(os, code.second, chunkcontext);
2147 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2148 bool is_macro(Parser & p)
2150 Token first = p.curr_token();
2151 if (first.cat() != catEscape || !p.good())
2153 if (first.cs() == "def")
2155 if (first.cs() != "global" && first.cs() != "long")
2157 Token second = p.get_token();
2159 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2160 second.cat() == catNewline || second.cat() == catComment)) {
2161 second = p.get_token();
2164 bool secondvalid = second.cat() == catEscape;
2166 bool thirdvalid = false;
2167 if (p.good() && first.cs() == "global" && secondvalid &&
2168 second.cs() == "long") {
2169 third = p.get_token();
2171 while (p.good() && !p.isParagraph() &&
2172 (third.cat() == catSpace ||
2173 third.cat() == catNewline ||
2174 third.cat() == catComment)) {
2175 third = p.get_token();
2178 thirdvalid = third.cat() == catEscape;
2180 for (int i = 0; i < pos; ++i)
2185 return (first.cs() == "global" || first.cs() == "long") &&
2186 second.cs() == "def";
2187 return first.cs() == "global" && second.cs() == "long" &&
2188 third.cs() == "def";
2192 /// Parse a macro definition (assumes that is_macro() returned true)
2193 void parse_macro(Parser & p, ostream & os, Context & context)
2195 context.check_layout(os);
2196 Token first = p.curr_token();
2199 string command = first.asInput();
2200 if (first.cs() != "def") {
2202 eat_whitespace(p, os, context, false);
2203 second = p.curr_token();
2204 command += second.asInput();
2205 if (second.cs() != "def") {
2207 eat_whitespace(p, os, context, false);
2208 third = p.curr_token();
2209 command += third.asInput();
2212 eat_whitespace(p, os, context, false);
2213 string const name = p.get_token().cs();
2214 eat_whitespace(p, os, context, false);
2220 while (p.next_token().cat() != catBegin) {
2221 if (p.next_token().cat() == catParameter) {
2226 // followed by number?
2227 if (p.next_token().cat() == catOther) {
2228 string s = p.get_token().asInput();
2230 // number = current arity + 1?
2231 if (s.size() == 1 && s[0] == arity + '0' + 1)
2236 paramtext += p.get_token().cs();
2238 paramtext += p.get_token().cs();
2243 // only output simple (i.e. compatible) macro as FormulaMacros
2244 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2246 context.check_layout(os);
2247 begin_inset(os, "FormulaMacro");
2248 os << "\n\\def" << ert;
2251 output_ert_inset(os, command + ert, context);
2255 void registerExternalTemplatePackages(string const & name)
2257 external::TemplateManager const & etm = external::TemplateManager::get();
2258 external::Template const * const et = etm.getTemplateByName(name);
2261 external::Template::Formats::const_iterator cit = et->formats.end();
2263 cit = et->formats.find("PDFLaTeX");
2264 if (cit == et->formats.end())
2265 // If the template has not specified a PDFLaTeX output,
2266 // we try the LaTeX format.
2267 cit = et->formats.find("LaTeX");
2268 if (cit == et->formats.end())
2270 vector<string>::const_iterator qit = cit->second.requirements.begin();
2271 vector<string>::const_iterator qend = cit->second.requirements.end();
2272 for (; qit != qend; ++qit)
2273 preamble.registerAutomaticallyLoadedPackage(*qit);
2276 } // anonymous namespace
2279 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2282 Layout const * newlayout = 0;
2283 InsetLayout const * newinsetlayout = 0;
2284 char const * const * where = 0;
2285 // Store the latest bibliographystyle, addcontentslineContent and
2286 // nocite{*} option (needed for bibtex inset)
2288 string contentslineContent;
2289 string bibliographystyle = "default";
2290 bool const use_natbib = isProvided("natbib");
2291 bool const use_jurabib = isProvided("jurabib");
2294 // it is impossible to determine the correct encoding for non-CJK Japanese.
2295 // Therefore write a note at the beginning of the document
2296 if (is_nonCJKJapanese) {
2297 context.check_layout(os);
2298 begin_inset(os, "Note Note\n");
2299 os << "status open\n\\begin_layout Plain Layout\n"
2300 << "\\series bold\n"
2301 << "Important information:\n"
2302 << "\\end_layout\n\n"
2303 << "\\begin_layout Plain Layout\n"
2304 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2305 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2306 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2307 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2308 << " and specify the encoding using the -e command-line switch.\n"
2309 << " In addition, you might want to double check that the desired output encoding\n"
2310 << " is correctly selected in Document > Settings > Language.\n"
2311 << "\\end_layout\n";
2313 is_nonCJKJapanese = false;
2317 Token const & t = p.get_token();
2319 debugToken(cerr, t, flags);
2322 if (flags & FLAG_ITEM) {
2323 if (t.cat() == catSpace)
2326 flags &= ~FLAG_ITEM;
2327 if (t.cat() == catBegin) {
2328 // skip the brace and collect everything to the next matching
2330 flags |= FLAG_BRACE_LAST;
2334 // handle only this single token, leave the loop if done
2335 flags |= FLAG_LEAVE;
2338 if (t.cat() != catEscape && t.character() == ']' &&
2339 (flags & FLAG_BRACK_LAST))
2341 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2344 // If there is anything between \end{env} and \begin{env} we
2345 // don't need to output a separator.
2346 if (t.cat() != catSpace && t.cat() != catNewline &&
2347 t.asInput() != "\\begin")
2353 bool const starred = p.next_token().asInput() == "*";
2354 string const starredname(starred ? (t.cs() + '*') : t.cs());
2355 if (t.cat() == catMath) {
2356 // we are inside some text mode thingy, so opening new math is allowed
2357 context.check_layout(os);
2358 begin_inset(os, "Formula ");
2359 Token const & n = p.get_token();
2360 bool const display(n.cat() == catMath && outer);
2362 // TeX's $$...$$ syntax for displayed math
2364 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2366 p.get_token(); // skip the second '$' token
2368 // simple $...$ stuff
2371 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2376 // Prevent the conversion of a line break to a
2377 // space (bug 7668). This does not change the
2378 // output, but looks ugly in LyX.
2379 eat_whitespace(p, os, context, false);
2383 else if (t.cat() == catSuper || t.cat() == catSub)
2384 cerr << "catcode " << t << " illegal in text mode\n";
2386 // Basic support for english quotes. This should be
2387 // extended to other quotes, but is not so easy (a
2388 // left english quote is the same as a right german
2390 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2391 context.check_layout(os);
2392 begin_inset(os, "Quotes ");
2398 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2399 context.check_layout(os);
2400 begin_inset(os, "Quotes ");
2407 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2408 context.check_layout(os);
2409 begin_inset(os, "Quotes ");
2416 else if (t.asInput() == "<"
2417 && p.next_token().asInput() == "<") {
2418 bool has_chunk = false;
2422 has_chunk = parse_chunk(p, os, context);
2428 context.check_layout(os);
2429 begin_inset(os, "Quotes ");
2430 //FIXME: this is a right danish quote;
2431 // why not a left french quote?
2439 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2440 check_space(p, os, context);
2442 else if (t.character() == '[' && noweb_mode &&
2443 p.next_token().character() == '[') {
2444 // These can contain underscores
2446 string const s = p.getFullOpt() + ']';
2447 if (p.next_token().character() == ']')
2450 cerr << "Warning: Inserting missing ']' in '"
2451 << s << "'." << endl;
2452 output_ert_inset(os, s, context);
2455 else if (t.cat() == catLetter) {
2456 context.check_layout(os);
2460 else if (t.cat() == catOther ||
2461 t.cat() == catAlign ||
2462 t.cat() == catParameter) {
2463 context.check_layout(os);
2464 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2465 context.merging_hyphens_allowed &&
2466 context.font.family != "ttfamily" &&
2467 !context.layout->pass_thru) {
2468 if (p.next_next_token().asInput() == "-") {
2470 os << to_utf8(docstring(1, 0x2014));
2474 os << to_utf8(docstring(1, 0x2013));
2477 // This translates "&" to "\\&" which may be wrong...
2481 else if (p.isParagraph()) {
2482 if (context.new_layout_allowed)
2483 context.new_paragraph(os);
2485 output_ert_inset(os, "\\par ", context);
2486 eat_whitespace(p, os, context, true);
2489 else if (t.cat() == catActive) {
2490 context.check_layout(os);
2491 if (t.character() == '~') {
2492 if (context.layout->free_spacing)
2495 begin_inset(os, "space ~\n");
2502 else if (t.cat() == catBegin) {
2503 Token const next = p.next_token();
2504 Token const end = p.next_next_token();
2505 if (next.cat() == catEnd) {
2507 Token const prev = p.prev_token();
2509 if (p.next_token().character() == '`')
2510 ; // ignore it in {}``
2512 output_ert_inset(os, "{}", context);
2513 } else if (next.cat() == catEscape &&
2514 is_known(next.cs(), known_quotes) &&
2515 end.cat() == catEnd) {
2516 // Something like {\textquoteright} (e.g.
2517 // from writer2latex). LyX writes
2518 // \textquoteright{}, so we may skip the
2519 // braces here for better readability.
2520 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2522 } else if (p.next_token().asInput() == "\\ascii") {
2523 // handle the \ascii characters
2524 // (the case without braces is handled later)
2525 // the code is "{\ascii\xxx}"
2526 p.get_token(); // eat \ascii
2527 string name2 = p.get_token().asInput();
2528 p.get_token(); // eat the final '}'
2529 string const name = "{\\ascii" + name2 + "}";
2533 // get the character from unicodesymbols
2534 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2535 Encodings::TEXT_CMD, termination, rem, &req);
2537 context.check_layout(os);
2540 output_ert_inset(os,
2541 to_utf8(rem), context);
2542 for (set<string>::const_iterator it = req.begin();
2543 it != req.end(); ++it)
2544 preamble.registerAutomaticallyLoadedPackage(*it);
2546 // we did not find a non-ert version
2547 output_ert_inset(os, name, context);
2549 context.check_layout(os);
2550 // special handling of font attribute changes
2551 Token const prev = p.prev_token();
2552 TeXFont const oldFont = context.font;
2553 if (next.character() == '[' ||
2554 next.character() == ']' ||
2555 next.character() == '*') {
2557 if (p.next_token().cat() == catEnd) {
2562 output_ert_inset(os, "{", context);
2563 parse_text_snippet(p, os,
2566 output_ert_inset(os, "}", context);
2568 } else if (! context.new_layout_allowed) {
2569 output_ert_inset(os, "{", context);
2570 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2572 output_ert_inset(os, "}", context);
2573 } else if (is_known(next.cs(), known_sizes)) {
2574 // next will change the size, so we must
2576 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2578 if (!context.atParagraphStart())
2580 << context.font.size << "\n";
2581 } else if (is_known(next.cs(), known_font_families)) {
2582 // next will change the font family, so we
2583 // must reset it here
2584 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2586 if (!context.atParagraphStart())
2588 << context.font.family << "\n";
2589 } else if (is_known(next.cs(), known_font_series)) {
2590 // next will change the font series, so we
2591 // must reset it here
2592 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2594 if (!context.atParagraphStart())
2596 << context.font.series << "\n";
2597 } else if (is_known(next.cs(), known_font_shapes)) {
2598 // next will change the font shape, so we
2599 // must reset it here
2600 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2602 if (!context.atParagraphStart())
2604 << context.font.shape << "\n";
2605 } else if (is_known(next.cs(), known_old_font_families) ||
2606 is_known(next.cs(), known_old_font_series) ||
2607 is_known(next.cs(), known_old_font_shapes)) {
2608 // next will change the font family, series
2609 // and shape, so we must reset it here
2610 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2612 if (!context.atParagraphStart())
2614 << context.font.family
2616 << context.font.series
2618 << context.font.shape << "\n";
2620 output_ert_inset(os, "{", context);
2621 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2623 output_ert_inset(os, "}", context);
2628 else if (t.cat() == catEnd) {
2629 if (flags & FLAG_BRACE_LAST) {
2632 cerr << "stray '}' in text\n";
2633 output_ert_inset(os, "}", context);
2636 else if (t.cat() == catComment)
2637 parse_comment(p, os, t, context);
2640 // control sequences
2643 else if (t.cs() == "(" || t.cs() == "[") {
2644 bool const simple = t.cs() == "(";
2645 context.check_layout(os);
2646 begin_inset(os, "Formula");
2647 os << " \\" << t.cs();
2648 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2649 os << '\\' << (simple ? ')' : ']');
2652 // Prevent the conversion of a line break to a
2653 // space (bug 7668). This does not change the
2654 // output, but looks ugly in LyX.
2655 eat_whitespace(p, os, context, false);
2659 else if (t.cs() == "begin")
2660 parse_environment(p, os, outer, last_env,
2663 else if (t.cs() == "end") {
2664 if (flags & FLAG_END) {
2665 // eat environment name
2666 string const name = p.getArg('{', '}');
2667 if (name != active_environment())
2668 cerr << "\\end{" + name + "} does not match \\begin{"
2669 + active_environment() + "}\n";
2672 p.error("found 'end' unexpectedly");
2675 else if (t.cs() == "item") {
2677 bool const optarg = p.hasOpt();
2679 // FIXME: This swallows comments, but we cannot use
2680 // eat_whitespace() since we must not output
2681 // anything before the item.
2682 p.skip_spaces(true);
2683 s = p.verbatimOption();
2685 p.skip_spaces(false);
2687 context.check_layout(os);
2688 if (context.has_item) {
2689 // An item in an unknown list-like environment
2690 // FIXME: Do this in check_layout()!
2691 context.has_item = false;
2693 output_ert_inset(os, "\\item", context);
2695 output_ert_inset(os, "\\item ", context);
2698 if (context.layout->labeltype != LABEL_MANUAL) {
2699 // handle option of itemize item
2700 begin_inset(os, "Argument item:1\n");
2701 os << "status open\n";
2702 os << "\n\\begin_layout Plain Layout\n";
2704 os << parse_text_snippet(p2,
2705 FLAG_BRACK_LAST, outer, context);
2706 // we must not use context.check_end_layout(os)
2707 // because that would close the outer itemize layout
2708 os << "\n\\end_layout\n";
2710 eat_whitespace(p, os, context, false);
2711 } else if (!s.empty()) {
2712 // LyX adds braces around the argument,
2713 // so we need to remove them here.
2714 if (s.size() > 2 && s[0] == '{' &&
2715 s[s.size()-1] == '}')
2716 s = s.substr(1, s.size()-2);
2717 // If the argument contains a space we
2718 // must put it into ERT: Otherwise LyX
2719 // would misinterpret the space as
2720 // item delimiter (bug 7663)
2721 if (contains(s, ' ')) {
2722 output_ert_inset(os, s, context);
2725 os << parse_text_snippet(p2,
2726 FLAG_BRACK_LAST, outer, context);
2728 // The space is needed to separate the
2729 // item from the rest of the sentence.
2731 eat_whitespace(p, os, context, false);
2736 else if (t.cs() == "bibitem") {
2738 context.check_layout(os);
2739 eat_whitespace(p, os, context, false);
2740 string label = convert_command_inset_arg(p.verbatimOption());
2741 string key = convert_command_inset_arg(p.verbatim_item());
2742 if (contains(label, '\\') || contains(key, '\\')) {
2743 // LyX can't handle LaTeX commands in labels or keys
2744 output_ert_inset(os, t.asInput() + '[' + label +
2745 "]{" + p.verbatim_item() + '}',
2748 begin_command_inset(os, "bibitem", "bibitem");
2749 os << "label \"" << label << "\"\n"
2750 "key \"" << key << "\"\n";
2755 else if (is_macro(p)) {
2756 // catch the case of \def\inputGnumericTable
2758 if (t.cs() == "def") {
2759 Token second = p.next_token();
2760 if (second.cs() == "inputGnumericTable") {
2764 Token third = p.get_token();
2766 if (third.cs() == "input") {
2770 string name = normalize_filename(p.verbatim_item());
2771 string const path = getMasterFilePath(true);
2772 // We want to preserve relative / absolute filenames,
2773 // therefore path is only used for testing
2774 // The file extension is in every case ".tex".
2775 // So we need to remove this extension and check for
2776 // the original one.
2777 name = removeExtension(name);
2778 if (!makeAbsPath(name, path).exists()) {
2779 char const * const Gnumeric_formats[] = {"gnumeric",
2781 string const Gnumeric_name =
2782 find_file(name, path, Gnumeric_formats);
2783 if (!Gnumeric_name.empty())
2784 name = Gnumeric_name;
2786 FileName const absname = makeAbsPath(name, path);
2787 if (absname.exists()) {
2788 fix_child_filename(name);
2789 copy_file(absname, name);
2791 cerr << "Warning: Could not find file '"
2792 << name << "'." << endl;
2793 context.check_layout(os);
2794 begin_inset(os, "External\n\ttemplate ");
2795 os << "GnumericSpreadsheet\n\tfilename "
2798 context.check_layout(os);
2800 // register the packages that are automatically loaded
2801 // by the Gnumeric template
2802 registerExternalTemplatePackages("GnumericSpreadsheet");
2807 parse_macro(p, os, context);
2810 else if (t.cs() == "noindent") {
2812 context.add_par_extra_stuff("\\noindent\n");
2815 else if (t.cs() == "appendix") {
2816 context.add_par_extra_stuff("\\start_of_appendix\n");
2817 // We need to start a new paragraph. Otherwise the
2818 // appendix in 'bla\appendix\chapter{' would start
2820 context.new_paragraph(os);
2821 // We need to make sure that the paragraph is
2822 // generated even if it is empty. Otherwise the
2823 // appendix in '\par\appendix\par\chapter{' would
2825 context.check_layout(os);
2826 // FIXME: This is a hack to prevent paragraph
2827 // deletion if it is empty. Handle this better!
2828 output_ert_inset(os,
2829 "%dummy comment inserted by tex2lyx to "
2830 "ensure that this paragraph is not empty",
2832 // Both measures above may generate an additional
2833 // empty paragraph, but that does not hurt, because
2834 // whitespace does not matter here.
2835 eat_whitespace(p, os, context, true);
2838 // Must catch empty dates before findLayout is called below
2839 else if (t.cs() == "date") {
2840 eat_whitespace(p, os, context, false);
2842 string const date = p.verbatim_item();
2845 preamble.suppressDate(true);
2848 preamble.suppressDate(false);
2849 if (context.new_layout_allowed &&
2850 (newlayout = findLayout(context.textclass,
2853 output_command_layout(os, p, outer,
2854 context, newlayout);
2855 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2856 if (!preamble.titleLayoutFound())
2857 preamble.titleLayoutFound(newlayout->intitle);
2858 set<string> const & req = newlayout->requires();
2859 set<string>::const_iterator it = req.begin();
2860 set<string>::const_iterator en = req.end();
2861 for (; it != en; ++it)
2862 preamble.registerAutomaticallyLoadedPackage(*it);
2864 output_ert_inset(os,
2865 "\\date{" + p.verbatim_item() + '}',
2870 // Starred section headings
2871 // Must attempt to parse "Section*" before "Section".
2872 else if ((p.next_token().asInput() == "*") &&
2873 context.new_layout_allowed &&
2874 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2877 output_command_layout(os, p, outer, context, newlayout);
2879 if (!preamble.titleLayoutFound())
2880 preamble.titleLayoutFound(newlayout->intitle);
2881 set<string> const & req = newlayout->requires();
2882 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2883 preamble.registerAutomaticallyLoadedPackage(*it);
2886 // Section headings and the like
2887 else if (context.new_layout_allowed &&
2888 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2890 output_command_layout(os, p, outer, context, newlayout);
2892 if (!preamble.titleLayoutFound())
2893 preamble.titleLayoutFound(newlayout->intitle);
2894 set<string> const & req = newlayout->requires();
2895 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2896 preamble.registerAutomaticallyLoadedPackage(*it);
2899 else if (t.cs() == "subfloat") {
2900 // the syntax is \subfloat[list entry][sub caption]{content}
2901 // if it is a table of figure depends on the surrounding float
2902 // FIXME: second optional argument is not parsed
2903 bool has_caption = false;
2905 // do nothing if there is no outer float
2906 if (!float_type.empty()) {
2907 context.check_layout(os);
2909 begin_inset(os, "Float " + float_type + "\n");
2911 << "\nsideways false"
2912 << "\nstatus collapsed\n\n";
2915 if (p.next_token().cat() != catEscape &&
2916 p.next_token().character() == '[') {
2917 p.get_token(); // eat '['
2918 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2922 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2923 // the caption comes always as the last
2925 // we must make sure that the caption gets a \begin_layout
2926 os << "\n\\begin_layout Plain Layout";
2928 begin_inset(os, "Caption Standard\n");
2929 Context newcontext(true, context.textclass,
2930 0, 0, context.font);
2931 newcontext.check_layout(os);
2932 os << caption << "\n";
2933 newcontext.check_end_layout(os);
2934 // We don't need really a new paragraph, but
2935 // we must make sure that the next item gets a \begin_layout.
2936 //newcontext.new_paragraph(os);
2940 // We don't need really a new paragraph, but
2941 // we must make sure that the next item gets a \begin_layout.
2943 context.new_paragraph(os);
2946 context.check_end_layout(os);
2947 // close the layout we opened
2949 os << "\n\\end_layout\n";
2951 // if the float type is not supported or there is no surrounding float
2954 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2955 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2956 "]{" + p.verbatim_item() + '}', context);
2958 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2962 else if (t.cs() == "includegraphics") {
2963 bool const clip = p.next_token().asInput() == "*";
2966 string const arg = p.getArg('[', ']');
2967 map<string, string> opts;
2968 vector<string> keys;
2969 split_map(arg, opts, keys);
2971 opts["clip"] = string();
2972 string name = normalize_filename(p.verbatim_item());
2974 string const path = getMasterFilePath(true);
2975 // We want to preserve relative / absolute filenames,
2976 // therefore path is only used for testing
2977 if (!makeAbsPath(name, path).exists()) {
2978 // The file extension is probably missing.
2979 // Now try to find it out.
2980 string const dvips_name =
2981 find_file(name, path,
2982 known_dvips_graphics_formats);
2983 string const pdftex_name =
2984 find_file(name, path,
2985 known_pdftex_graphics_formats);
2986 if (!dvips_name.empty()) {
2987 if (!pdftex_name.empty()) {
2988 cerr << "This file contains the "
2990 "\"\\includegraphics{"
2992 "However, files\n\""
2993 << dvips_name << "\" and\n\""
2994 << pdftex_name << "\"\n"
2995 "both exist, so I had to make a "
2996 "choice and took the first one.\n"
2997 "Please move the unwanted one "
2998 "someplace else and try again\n"
2999 "if my choice was wrong."
3003 } else if (!pdftex_name.empty()) {
3009 FileName const absname = makeAbsPath(name, path);
3010 if (absname.exists()) {
3011 fix_child_filename(name);
3012 copy_file(absname, name);
3014 cerr << "Warning: Could not find graphics file '"
3015 << name << "'." << endl;
3017 context.check_layout(os);
3018 begin_inset(os, "Graphics ");
3019 os << "\n\tfilename " << name << '\n';
3020 if (opts.find("width") != opts.end())
3022 << translate_len(opts["width"]) << '\n';
3023 if (opts.find("height") != opts.end())
3025 << translate_len(opts["height"]) << '\n';
3026 if (opts.find("scale") != opts.end()) {
3027 istringstream iss(opts["scale"]);
3031 os << "\tscale " << val << '\n';
3033 if (opts.find("angle") != opts.end()) {
3034 os << "\trotateAngle "
3035 << opts["angle"] << '\n';
3036 vector<string>::const_iterator a =
3037 find(keys.begin(), keys.end(), "angle");
3038 vector<string>::const_iterator s =
3039 find(keys.begin(), keys.end(), "width");
3040 if (s == keys.end())
3041 s = find(keys.begin(), keys.end(), "height");
3042 if (s == keys.end())
3043 s = find(keys.begin(), keys.end(), "scale");
3044 if (s != keys.end() && distance(s, a) > 0)
3045 os << "\tscaleBeforeRotation\n";
3047 if (opts.find("origin") != opts.end()) {
3049 string const opt = opts["origin"];
3050 if (opt.find('l') != string::npos) ss << "left";
3051 if (opt.find('r') != string::npos) ss << "right";
3052 if (opt.find('c') != string::npos) ss << "center";
3053 if (opt.find('t') != string::npos) ss << "Top";
3054 if (opt.find('b') != string::npos) ss << "Bottom";
3055 if (opt.find('B') != string::npos) ss << "Baseline";
3056 if (!ss.str().empty())
3057 os << "\trotateOrigin " << ss.str() << '\n';
3059 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3061 if (opts.find("keepaspectratio") != opts.end())
3062 os << "\tkeepAspectRatio\n";
3063 if (opts.find("clip") != opts.end())
3065 if (opts.find("draft") != opts.end())
3067 if (opts.find("bb") != opts.end())
3068 os << "\tBoundingBox "
3069 << opts["bb"] << '\n';
3070 int numberOfbbOptions = 0;
3071 if (opts.find("bbllx") != opts.end())
3072 numberOfbbOptions++;
3073 if (opts.find("bblly") != opts.end())
3074 numberOfbbOptions++;
3075 if (opts.find("bburx") != opts.end())
3076 numberOfbbOptions++;
3077 if (opts.find("bbury") != opts.end())
3078 numberOfbbOptions++;
3079 if (numberOfbbOptions == 4)
3080 os << "\tBoundingBox "
3081 << opts["bbllx"] << " " << opts["bblly"] << " "
3082 << opts["bburx"] << " " << opts["bbury"] << '\n';
3083 else if (numberOfbbOptions > 0)
3084 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3085 numberOfbbOptions = 0;
3086 if (opts.find("natwidth") != opts.end())
3087 numberOfbbOptions++;
3088 if (opts.find("natheight") != opts.end())
3089 numberOfbbOptions++;
3090 if (numberOfbbOptions == 2)
3091 os << "\tBoundingBox 0bp 0bp "
3092 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3093 else if (numberOfbbOptions > 0)
3094 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3095 ostringstream special;
3096 if (opts.find("hiresbb") != opts.end())
3097 special << "hiresbb,";
3098 if (opts.find("trim") != opts.end())
3100 if (opts.find("viewport") != opts.end())
3101 special << "viewport=" << opts["viewport"] << ',';
3102 if (opts.find("totalheight") != opts.end())
3103 special << "totalheight=" << opts["totalheight"] << ',';
3104 if (opts.find("type") != opts.end())
3105 special << "type=" << opts["type"] << ',';
3106 if (opts.find("ext") != opts.end())
3107 special << "ext=" << opts["ext"] << ',';
3108 if (opts.find("read") != opts.end())
3109 special << "read=" << opts["read"] << ',';
3110 if (opts.find("command") != opts.end())
3111 special << "command=" << opts["command"] << ',';
3112 string s_special = special.str();
3113 if (!s_special.empty()) {
3114 // We had special arguments. Remove the trailing ','.
3115 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3117 // TODO: Handle the unknown settings better.
3118 // Warn about invalid options.
3119 // Check whether some option was given twice.
3121 preamble.registerAutomaticallyLoadedPackage("graphicx");
3124 else if (t.cs() == "footnote" ||
3125 (t.cs() == "thanks" && context.layout->intitle)) {
3127 context.check_layout(os);
3128 begin_inset(os, "Foot\n");
3129 os << "status collapsed\n\n";
3130 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3134 else if (t.cs() == "marginpar") {
3136 context.check_layout(os);
3137 begin_inset(os, "Marginal\n");
3138 os << "status collapsed\n\n";
3139 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3143 else if (t.cs() == "lstinline") {
3145 parse_listings(p, os, context, true);
3148 else if (t.cs() == "ensuremath") {
3150 context.check_layout(os);
3151 string const s = p.verbatim_item();
3152 //FIXME: this never triggers in UTF8
3153 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3156 output_ert_inset(os, "\\ensuremath{" + s + "}",
3160 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3161 if (preamble.titleLayoutFound()) {
3163 skip_spaces_braces(p);
3165 output_ert_inset(os, t.asInput(), context);
3168 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3169 context.check_layout(os);
3170 begin_command_inset(os, "toc", t.cs());
3172 skip_spaces_braces(p);
3173 if (t.cs() == "lstlistoflistings")
3174 preamble.registerAutomaticallyLoadedPackage("listings");
3177 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3178 context.check_layout(os);
3179 if (t.cs() == "listoffigures")
3180 begin_inset(os, "FloatList figure\n");
3182 begin_inset(os, "FloatList table\n");
3184 skip_spaces_braces(p);
3187 else if (t.cs() == "listof") {
3188 p.skip_spaces(true);
3189 string const name = p.get_token().cs();
3190 if (context.textclass.floats().typeExist(name)) {
3191 context.check_layout(os);
3192 begin_inset(os, "FloatList ");
3195 p.get_token(); // swallow second arg
3197 output_ert_inset(os, "\\listof{" + name + "}", context);
3200 else if ((where = is_known(t.cs(), known_text_font_families)))
3201 parse_text_attributes(p, os, FLAG_ITEM, outer,
3202 context, "\\family", context.font.family,
3203 known_coded_font_families[where - known_text_font_families]);
3205 else if ((where = is_known(t.cs(), known_text_font_series)))
3206 parse_text_attributes(p, os, FLAG_ITEM, outer,
3207 context, "\\series", context.font.series,
3208 known_coded_font_series[where - known_text_font_series]);
3210 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3211 parse_text_attributes(p, os, FLAG_ITEM, outer,
3212 context, "\\shape", context.font.shape,
3213 known_coded_font_shapes[where - known_text_font_shapes]);
3215 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3216 context.check_layout(os);
3217 TeXFont oldFont = context.font;
3218 context.font.init();
3219 context.font.size = oldFont.size;
3220 os << "\n\\family " << context.font.family << "\n";
3221 os << "\n\\series " << context.font.series << "\n";
3222 os << "\n\\shape " << context.font.shape << "\n";
3223 if (t.cs() == "textnormal") {
3224 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3225 output_font_change(os, context.font, oldFont);
3226 context.font = oldFont;
3228 eat_whitespace(p, os, context, false);
3231 else if (t.cs() == "textcolor") {
3232 // scheme is \textcolor{color name}{text}
3233 string const color = p.verbatim_item();
3234 // we support the predefined colors of the color and the xcolor package
3235 if (color == "black" || color == "blue" || color == "cyan"
3236 || color == "green" || color == "magenta" || color == "red"
3237 || color == "white" || color == "yellow") {
3238 context.check_layout(os);
3239 os << "\n\\color " << color << "\n";
3240 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3241 context.check_layout(os);
3242 os << "\n\\color inherit\n";
3243 preamble.registerAutomaticallyLoadedPackage("color");
3244 } else if (color == "brown" || color == "darkgray" || color == "gray"
3245 || color == "lightgray" || color == "lime" || color == "olive"
3246 || color == "orange" || color == "pink" || color == "purple"
3247 || color == "teal" || color == "violet") {
3248 context.check_layout(os);
3249 os << "\n\\color " << color << "\n";
3250 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3251 context.check_layout(os);
3252 os << "\n\\color inherit\n";
3253 preamble.registerAutomaticallyLoadedPackage("xcolor");
3255 // for custom defined colors
3256 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3259 else if (t.cs() == "underbar" || t.cs() == "uline") {
3260 // \underbar is not 100% correct (LyX outputs \uline
3261 // of ulem.sty). The difference is that \ulem allows
3262 // line breaks, and \underbar does not.
3263 // Do NOT handle \underline.
3264 // \underbar cuts through y, g, q, p etc.,
3265 // \underline does not.
3266 context.check_layout(os);
3267 os << "\n\\bar under\n";
3268 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3269 context.check_layout(os);
3270 os << "\n\\bar default\n";
3271 preamble.registerAutomaticallyLoadedPackage("ulem");
3274 else if (t.cs() == "sout") {
3275 context.check_layout(os);
3276 os << "\n\\strikeout on\n";
3277 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3278 context.check_layout(os);
3279 os << "\n\\strikeout default\n";
3280 preamble.registerAutomaticallyLoadedPackage("ulem");
3283 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3284 t.cs() == "emph" || t.cs() == "noun") {
3285 context.check_layout(os);
3286 os << "\n\\" << t.cs() << " on\n";
3287 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3288 context.check_layout(os);
3289 os << "\n\\" << t.cs() << " default\n";
3290 if (t.cs() == "uuline" || t.cs() == "uwave")
3291 preamble.registerAutomaticallyLoadedPackage("ulem");
3294 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3295 context.check_layout(os);
3296 string name = p.getArg('{', '}');
3297 string localtime = p.getArg('{', '}');
3298 preamble.registerAuthor(name);
3299 Author const & author = preamble.getAuthor(name);
3300 // from_asctime_utc() will fail if LyX decides to output the
3301 // time in the text language.
3302 time_t ptime = from_asctime_utc(localtime);
3303 if (ptime == static_cast<time_t>(-1)) {
3304 cerr << "Warning: Could not parse time `" << localtime
3305 << "´ for change tracking, using current time instead.\n";
3306 ptime = current_time();
3308 if (t.cs() == "lyxadded")
3309 os << "\n\\change_inserted ";
3311 os << "\n\\change_deleted ";
3312 os << author.bufferId() << ' ' << ptime << '\n';
3313 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3314 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3315 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3316 LaTeXPackages::isAvailable("xcolor");
3317 // No need to test for luatex, since luatex comes in
3318 // two flavours (dvi and pdf), like latex, and those
3319 // are detected by pdflatex.
3320 if (pdflatex || xetex) {
3322 preamble.registerAutomaticallyLoadedPackage("ulem");
3323 preamble.registerAutomaticallyLoadedPackage("xcolor");
3324 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3328 preamble.registerAutomaticallyLoadedPackage("dvipost");
3329 } else if (xcolorulem) {
3330 preamble.registerAutomaticallyLoadedPackage("ulem");
3331 preamble.registerAutomaticallyLoadedPackage("xcolor");
3336 else if (t.cs() == "textipa") {
3337 context.check_layout(os);
3338 begin_inset(os, "IPA\n");
3339 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3340 context.merging_hyphens_allowed = false;
3341 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3342 context.merging_hyphens_allowed = merging_hyphens_allowed;
3344 preamble.registerAutomaticallyLoadedPackage("tipa");
3345 preamble.registerAutomaticallyLoadedPackage("tipx");
3348 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3349 context.check_layout(os);
3350 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3351 os << "status open\n";
3352 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3357 else if (t.cs() == "textvertline") {
3358 // FIXME: This is not correct, \textvertline is higher than |
3364 else if (t.cs() == "tone" ) {
3365 context.check_layout(os);
3366 // register the tone package
3367 preamble.registerAutomaticallyLoadedPackage("tone");
3368 string content = trimSpaceAndEol(p.verbatim_item());
3369 string command = t.asInput() + "{" + content + "}";
3370 // some tones can be detected by unicodesymbols, some need special code
3371 if (is_known(content, known_tones)) {
3372 os << "\\IPAChar " << command << "\n";
3375 // try to see whether the string is in unicodesymbols
3379 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3380 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3381 termination, rem, &req);
3385 output_ert_inset(os, to_utf8(rem), context);
3386 for (set<string>::const_iterator it = req.begin();
3387 it != req.end(); ++it)
3388 preamble.registerAutomaticallyLoadedPackage(*it);
3390 // we did not find a non-ert version
3391 output_ert_inset(os, command, context);
3394 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3395 t.cs() == "vphantom") {
3396 context.check_layout(os);
3397 if (t.cs() == "phantom")
3398 begin_inset(os, "Phantom Phantom\n");
3399 if (t.cs() == "hphantom")
3400 begin_inset(os, "Phantom HPhantom\n");
3401 if (t.cs() == "vphantom")
3402 begin_inset(os, "Phantom VPhantom\n");
3403 os << "status open\n";
3404 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3409 else if (t.cs() == "href") {
3410 context.check_layout(os);
3411 string target = convert_command_inset_arg(p.verbatim_item());
3412 string name = convert_command_inset_arg(p.verbatim_item());
3414 size_t i = target.find(':');
3415 if (i != string::npos) {
3416 type = target.substr(0, i + 1);
3417 if (type == "mailto:" || type == "file:")
3418 target = target.substr(i + 1);
3419 // handle the case that name is equal to target, except of "http://"
3420 else if (target.substr(i + 3) == name && type == "http:")
3423 begin_command_inset(os, "href", "href");
3425 os << "name \"" << name << "\"\n";
3426 os << "target \"" << target << "\"\n";
3427 if (type == "mailto:" || type == "file:")
3428 os << "type \"" << type << "\"\n";
3430 skip_spaces_braces(p);
3433 else if (t.cs() == "lyxline") {
3434 // swallow size argument (it is not used anyway)
3436 if (!context.atParagraphStart()) {
3437 // so our line is in the middle of a paragraph
3438 // we need to add a new line, lest this line
3439 // follow the other content on that line and
3440 // run off the side of the page
3441 // FIXME: This may create an empty paragraph,
3442 // but without that it would not be
3443 // possible to set noindent below.
3444 // Fortunately LaTeX does not care
3445 // about the empty paragraph.
3446 context.new_paragraph(os);
3448 if (preamble.indentParagraphs()) {
3449 // we need to unindent, lest the line be too long
3450 context.add_par_extra_stuff("\\noindent\n");
3452 context.check_layout(os);
3453 begin_command_inset(os, "line", "rule");
3454 os << "offset \"0.5ex\"\n"
3455 "width \"100line%\"\n"
3460 else if (t.cs() == "rule") {
3461 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3462 string const width = p.getArg('{', '}');
3463 string const thickness = p.getArg('{', '}');
3464 context.check_layout(os);
3465 begin_command_inset(os, "line", "rule");
3466 if (!offset.empty())
3467 os << "offset \"" << translate_len(offset) << "\"\n";
3468 os << "width \"" << translate_len(width) << "\"\n"
3469 "height \"" << translate_len(thickness) << "\"\n";
3473 // handle refstyle first to catch \eqref which can also occur
3474 // without refstyle. Only recognize these commands if
3475 // refstyle.sty was found in the preamble (otherwise \eqref
3476 // and user defined ref commands could be misdetected).
3477 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3478 preamble.refstyle()) {
3479 context.check_layout(os);
3480 begin_command_inset(os, "ref", "formatted");
3481 os << "reference \"";
3482 os << known_refstyle_prefixes[where - known_refstyle_commands]
3484 os << convert_command_inset_arg(p.verbatim_item())
3487 preamble.registerAutomaticallyLoadedPackage("refstyle");
3490 // if refstyle is used, we must not convert \prettyref to a
3491 // formatted reference, since that would result in a refstyle command.
3492 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3493 (t.cs() != "prettyref" || !preamble.refstyle())) {
3494 string const opt = p.getOpt();
3496 context.check_layout(os);
3497 begin_command_inset(os, "ref",
3498 known_coded_ref_commands[where - known_ref_commands]);
3499 os << "reference \""
3500 << convert_command_inset_arg(p.verbatim_item())
3503 if (t.cs() == "vref" || t.cs() == "vpageref")
3504 preamble.registerAutomaticallyLoadedPackage("varioref");
3505 else if (t.cs() == "prettyref")
3506 preamble.registerAutomaticallyLoadedPackage("prettyref");
3508 // LyX does not yet support optional arguments of ref commands
3509 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3510 p.verbatim_item() + '}', context);
3514 else if (use_natbib &&
3515 is_known(t.cs(), known_natbib_commands) &&
3516 ((t.cs() != "citefullauthor" &&
3517 t.cs() != "citeyear" &&
3518 t.cs() != "citeyearpar") ||
3519 p.next_token().asInput() != "*")) {
3520 context.check_layout(os);
3521 string command = t.cs();
3522 if (p.next_token().asInput() == "*") {
3526 if (command == "citefullauthor")
3527 // alternative name for "\\citeauthor*"
3528 command = "citeauthor*";
3530 // text before the citation
3532 // text after the citation
3534 get_cite_arguments(p, true, before, after);
3536 if (command == "cite") {
3537 // \cite without optional argument means
3538 // \citet, \cite with at least one optional
3539 // argument means \citep.
3540 if (before.empty() && after.empty())
3545 if (before.empty() && after == "[]")
3546 // avoid \citet[]{a}
3548 else if (before == "[]" && after == "[]") {
3549 // avoid \citet[][]{a}
3553 // remove the brackets around after and before
3554 if (!after.empty()) {
3556 after.erase(after.length() - 1, 1);
3557 after = convert_command_inset_arg(after);
3559 if (!before.empty()) {
3561 before.erase(before.length() - 1, 1);
3562 before = convert_command_inset_arg(before);
3564 begin_command_inset(os, "citation", command);
3565 os << "after " << '"' << after << '"' << "\n";
3566 os << "before " << '"' << before << '"' << "\n";
3568 << convert_command_inset_arg(p.verbatim_item())
3571 // Need to set the cite engine if natbib is loaded by
3572 // the document class directly
3573 if (preamble.citeEngine() == "basic")
3574 preamble.citeEngine("natbib");
3577 else if (use_jurabib &&
3578 is_known(t.cs(), known_jurabib_commands) &&
3579 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3580 context.check_layout(os);
3581 string command = t.cs();
3582 if (p.next_token().asInput() == "*") {
3586 char argumentOrder = '\0';
3587 vector<string> const options =
3588 preamble.getPackageOptions("jurabib");
3589 if (find(options.begin(), options.end(),
3590 "natbiborder") != options.end())
3591 argumentOrder = 'n';
3592 else if (find(options.begin(), options.end(),
3593 "jurabiborder") != options.end())
3594 argumentOrder = 'j';
3596 // text before the citation
3598 // text after the citation
3600 get_cite_arguments(p, argumentOrder != 'j', before, after);
3602 string const citation = p.verbatim_item();
3603 if (!before.empty() && argumentOrder == '\0') {
3604 cerr << "Warning: Assuming argument order "
3605 "of jurabib version 0.6 for\n'"
3606 << command << before << after << '{'
3607 << citation << "}'.\n"
3608 "Add 'jurabiborder' to the jurabib "
3609 "package options if you used an\n"
3610 "earlier jurabib version." << endl;
3612 if (!after.empty()) {
3614 after.erase(after.length() - 1, 1);
3616 if (!before.empty()) {
3618 before.erase(before.length() - 1, 1);
3620 begin_command_inset(os, "citation", command);
3621 os << "after " << '"' << after << '"' << "\n";
3622 os << "before " << '"' << before << '"' << "\n";
3623 os << "key " << '"' << citation << '"' << "\n";
3625 // Need to set the cite engine if jurabib is loaded by
3626 // the document class directly
3627 if (preamble.citeEngine() == "basic")
3628 preamble.citeEngine("jurabib");
3631 else if (t.cs() == "cite"
3632 || t.cs() == "nocite") {
3633 context.check_layout(os);
3634 string after = convert_command_inset_arg(p.getArg('[', ']'));
3635 string key = convert_command_inset_arg(p.verbatim_item());
3636 // store the case that it is "\nocite{*}" to use it later for
3639 begin_command_inset(os, "citation", t.cs());
3640 os << "after " << '"' << after << '"' << "\n";
3641 os << "key " << '"' << key << '"' << "\n";
3643 } else if (t.cs() == "nocite")
3647 else if (t.cs() == "index" ||
3648 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3649 context.check_layout(os);
3650 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3651 p.getArg('[', ']') : "";
3652 string const kind = arg.empty() ? "idx" : arg;
3653 begin_inset(os, "Index ");
3654 os << kind << "\nstatus collapsed\n";
3655 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3658 preamble.registerAutomaticallyLoadedPackage("splitidx");
3661 else if (t.cs() == "nomenclature") {
3662 context.check_layout(os);
3663 begin_command_inset(os, "nomenclature", "nomenclature");
3664 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3665 if (!prefix.empty())
3666 os << "prefix " << '"' << prefix << '"' << "\n";
3667 os << "symbol " << '"'
3668 << convert_command_inset_arg(p.verbatim_item());
3669 os << "\"\ndescription \""
3670 << convert_command_inset_arg(p.verbatim_item())
3673 preamble.registerAutomaticallyLoadedPackage("nomencl");
3676 else if (t.cs() == "label") {
3677 context.check_layout(os);
3678 begin_command_inset(os, "label", "label");
3680 << convert_command_inset_arg(p.verbatim_item())
3685 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3686 context.check_layout(os);
3687 string commandname = t.cs();
3689 if (p.next_token().asInput() == "*") {
3694 begin_command_inset(os, "index_print", commandname);
3695 string const indexname = p.getArg('[', ']');
3697 if (indexname.empty())
3698 os << "type \"idx\"\n";
3700 os << "type \"" << indexname << "\"\n";
3703 skip_spaces_braces(p);
3704 preamble.registerAutomaticallyLoadedPackage("makeidx");
3705 if (preamble.use_indices() == "true")
3706 preamble.registerAutomaticallyLoadedPackage("splitidx");
3709 else if (t.cs() == "printnomenclature") {
3711 string width_type = "";
3712 context.check_layout(os);
3713 begin_command_inset(os, "nomencl_print", "printnomenclature");
3714 // case of a custom width
3716 width = p.getArg('[', ']');
3717 width = translate_len(width);
3718 width_type = "custom";
3720 // case of no custom width
3721 // the case of no custom width but the width set
3722 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3723 // because the user could have set anything, not only the width
3724 // of the longest label (which would be width_type = "auto")
3725 string label = convert_command_inset_arg(p.getArg('{', '}'));
3726 if (label.empty() && width_type.empty())
3727 width_type = "none";
3728 os << "set_width \"" << width_type << "\"\n";
3729 if (width_type == "custom")
3730 os << "width \"" << width << '\"';
3732 skip_spaces_braces(p);
3733 preamble.registerAutomaticallyLoadedPackage("nomencl");
3736 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3737 context.check_layout(os);
3738 begin_inset(os, "script ");
3739 os << t.cs().substr(4) << '\n';
3740 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3741 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3743 if (t.cs() == "textsubscript")
3744 preamble.registerAutomaticallyLoadedPackage("subscript");
3747 else if ((where = is_known(t.cs(), known_quotes))) {
3748 context.check_layout(os);
3749 begin_inset(os, "Quotes ");
3750 os << known_coded_quotes[where - known_quotes];
3752 // LyX adds {} after the quote, so we have to eat
3753 // spaces here if there are any before a possible
3755 eat_whitespace(p, os, context, false);
3759 else if ((where = is_known(t.cs(), known_sizes)) &&
3760 context.new_layout_allowed) {
3761 context.check_layout(os);
3762 TeXFont const oldFont = context.font;
3763 context.font.size = known_coded_sizes[where - known_sizes];
3764 output_font_change(os, oldFont, context.font);
3765 eat_whitespace(p, os, context, false);
3768 else if ((where = is_known(t.cs(), known_font_families)) &&
3769 context.new_layout_allowed) {
3770 context.check_layout(os);
3771 TeXFont const oldFont = context.font;
3772 context.font.family =
3773 known_coded_font_families[where - known_font_families];
3774 output_font_change(os, oldFont, context.font);
3775 eat_whitespace(p, os, context, false);
3778 else if ((where = is_known(t.cs(), known_font_series)) &&
3779 context.new_layout_allowed) {
3780 context.check_layout(os);
3781 TeXFont const oldFont = context.font;
3782 context.font.series =
3783 known_coded_font_series[where - known_font_series];
3784 output_font_change(os, oldFont, context.font);
3785 eat_whitespace(p, os, context, false);
3788 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3789 context.new_layout_allowed) {
3790 context.check_layout(os);
3791 TeXFont const oldFont = context.font;
3792 context.font.shape =
3793 known_coded_font_shapes[where - known_font_shapes];
3794 output_font_change(os, oldFont, context.font);
3795 eat_whitespace(p, os, context, false);
3797 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3798 context.new_layout_allowed) {
3799 context.check_layout(os);
3800 TeXFont const oldFont = context.font;
3801 context.font.init();
3802 context.font.size = oldFont.size;
3803 context.font.family =
3804 known_coded_font_families[where - known_old_font_families];
3805 output_font_change(os, oldFont, context.font);
3806 eat_whitespace(p, os, context, false);
3809 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3810 context.new_layout_allowed) {
3811 context.check_layout(os);
3812 TeXFont const oldFont = context.font;
3813 context.font.init();
3814 context.font.size = oldFont.size;
3815 context.font.series =
3816 known_coded_font_series[where - known_old_font_series];
3817 output_font_change(os, oldFont, context.font);
3818 eat_whitespace(p, os, context, false);
3821 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3822 context.new_layout_allowed) {
3823 context.check_layout(os);
3824 TeXFont const oldFont = context.font;
3825 context.font.init();
3826 context.font.size = oldFont.size;
3827 context.font.shape =
3828 known_coded_font_shapes[where - known_old_font_shapes];
3829 output_font_change(os, oldFont, context.font);
3830 eat_whitespace(p, os, context, false);
3833 else if (t.cs() == "selectlanguage") {
3834 context.check_layout(os);
3835 // save the language for the case that a
3836 // \foreignlanguage is used
3837 context.font.language = babel2lyx(p.verbatim_item());
3838 os << "\n\\lang " << context.font.language << "\n";
3841 else if (t.cs() == "foreignlanguage") {
3842 string const lang = babel2lyx(p.verbatim_item());
3843 parse_text_attributes(p, os, FLAG_ITEM, outer,
3845 context.font.language, lang);
3848 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3849 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3850 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3852 // We have to output the whole command if it has an option
3853 // because LyX doesn't support this yet, see bug #8214,
3854 // only if there is a single option specifying a variant, we can handle it.
3856 string langopts = p.getOpt();
3857 // check if the option contains a variant, if yes, extract it
3858 string::size_type pos_var = langopts.find("variant");
3859 string::size_type i = langopts.find(',');
3860 string::size_type k = langopts.find('=', pos_var);
3861 if (pos_var != string::npos && i == string::npos) {
3863 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3864 lang = preamble.polyglossia2lyx(variant);
3865 parse_text_attributes(p, os, FLAG_ITEM, outer,
3867 context.font.language, lang);
3869 output_ert_inset(os, t.asInput() + langopts, context);
3871 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3872 parse_text_attributes(p, os, FLAG_ITEM, outer,
3874 context.font.language, lang);
3878 else if (t.cs() == "inputencoding") {
3879 // nothing to write here
3880 string const enc = subst(p.verbatim_item(), "\n", " ");
3881 p.setEncoding(enc, Encoding::inputenc);
3884 else if (is_known(t.cs(), known_special_chars) ||
3885 (t.cs() == "protect" &&
3886 p.next_token().cat() == catEscape &&
3887 is_known(p.next_token().cs(), known_special_protect_chars))) {
3888 // LyX sometimes puts a \protect in front, so we have to ignore it
3890 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3891 known_special_chars);
3892 context.check_layout(os);
3893 os << known_coded_special_chars[where - known_special_chars];
3894 skip_spaces_braces(p);
3897 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3898 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3899 p.next_next_token().asInput() == "-") ||
3900 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3901 // LyX sometimes puts a \protect in front, so we have to ignore it
3902 if (t.cs() == "protect")
3904 context.check_layout(os);
3905 if (t.cs() == "nobreakdash")
3906 os << "\\SpecialChar nobreakdash\n";
3908 os << "\\SpecialChar endofsentence\n";
3912 else if (t.cs() == "textquotedbl") {
3913 context.check_layout(os);
3918 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3919 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3920 || t.cs() == "%" || t.cs() == "-") {
3921 context.check_layout(os);
3923 os << "\\SpecialChar softhyphen\n";
3928 else if (t.cs() == "char") {
3929 context.check_layout(os);
3930 if (p.next_token().character() == '`') {
3932 if (p.next_token().cs() == "\"") {
3937 output_ert_inset(os, "\\char`", context);
3940 output_ert_inset(os, "\\char", context);
3944 else if (t.cs() == "verb") {
3945 context.check_layout(os);
3946 // set catcodes to verbatim early, just in case.
3947 p.setCatcodes(VERBATIM_CATCODES);
3948 string delim = p.get_token().asInput();
3949 Parser::Arg arg = p.verbatimStuff(delim);
3951 output_ert_inset(os, "\\verb" + delim
3952 + arg.second + delim, context);
3954 cerr << "invalid \\verb command. Skipping" << endl;
3957 // Problem: \= creates a tabstop inside the tabbing environment
3958 // and else an accent. In the latter case we really would want
3959 // \={o} instead of \= o.
3960 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3961 output_ert_inset(os, t.asInput(), context);
3963 else if (t.cs() == "\\") {
3964 context.check_layout(os);
3966 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3967 else if (p.next_token().asInput() == "*") {
3969 // getOpt() eats the following space if there
3970 // is no optional argument, but that is OK
3971 // here since it has no effect in the output.
3972 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3975 begin_inset(os, "Newline newline");
3980 else if (t.cs() == "newline" ||
3981 (t.cs() == "linebreak" && !p.hasOpt())) {
3982 context.check_layout(os);
3983 begin_inset(os, "Newline ");
3986 skip_spaces_braces(p);
3989 else if (t.cs() == "input" || t.cs() == "include"
3990 || t.cs() == "verbatiminput") {
3991 string name = t.cs();
3992 if (t.cs() == "verbatiminput"
3993 && p.next_token().asInput() == "*")
3994 name += p.get_token().asInput();
3995 context.check_layout(os);
3996 string filename(normalize_filename(p.getArg('{', '}')));
3997 string const path = getMasterFilePath(true);
3998 // We want to preserve relative / absolute filenames,
3999 // therefore path is only used for testing
4000 if ((t.cs() == "include" || t.cs() == "input") &&
4001 !makeAbsPath(filename, path).exists()) {
4002 // The file extension is probably missing.
4003 // Now try to find it out.
4004 string const tex_name =
4005 find_file(filename, path,
4006 known_tex_extensions);
4007 if (!tex_name.empty())
4008 filename = tex_name;
4010 bool external = false;
4012 if (makeAbsPath(filename, path).exists()) {
4013 string const abstexname =
4014 makeAbsPath(filename, path).absFileName();
4015 string const absfigname =
4016 changeExtension(abstexname, ".fig");
4017 fix_child_filename(filename);
4018 string const lyxname = changeExtension(filename,
4019 roundtripMode() ? ".lyx.lyx" : ".lyx");
4020 string const abslyxname = makeAbsPath(
4021 lyxname, getParentFilePath(false)).absFileName();
4023 if (!skipChildren())
4024 external = FileName(absfigname).exists();
4025 if (t.cs() == "input" && !skipChildren()) {
4026 string const ext = getExtension(abstexname);
4028 // Combined PS/LaTeX:
4029 // x.eps, x.pstex_t (old xfig)
4030 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4031 FileName const absepsname(
4032 changeExtension(abstexname, ".eps"));
4033 FileName const abspstexname(
4034 changeExtension(abstexname, ".pstex"));
4035 bool const xfigeps =
4036 (absepsname.exists() ||
4037 abspstexname.exists()) &&
4040 // Combined PDF/LaTeX:
4041 // x.pdf, x.pdftex_t (old xfig)
4042 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4043 FileName const abspdfname(
4044 changeExtension(abstexname, ".pdf"));
4045 bool const xfigpdf =
4046 abspdfname.exists() &&
4047 (ext == "pdftex_t" || ext == "pdf_t");
4051 // Combined PS/PDF/LaTeX:
4052 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4053 string const absbase2(
4054 removeExtension(abstexname) + "_pspdftex");
4055 FileName const abseps2name(
4056 addExtension(absbase2, ".eps"));
4057 FileName const abspdf2name(
4058 addExtension(absbase2, ".pdf"));
4059 bool const xfigboth =
4060 abspdf2name.exists() &&
4061 abseps2name.exists() && ext == "pspdftex";
4063 xfig = xfigpdf || xfigeps || xfigboth;
4064 external = external && xfig;
4067 outname = changeExtension(filename, ".fig");
4068 FileName abssrc(changeExtension(abstexname, ".fig"));
4069 copy_file(abssrc, outname);
4071 // Don't try to convert, the result
4072 // would be full of ERT.
4074 FileName abssrc(abstexname);
4075 copy_file(abssrc, outname);
4076 } else if (t.cs() != "verbatiminput" &&
4078 tex2lyx(abstexname, FileName(abslyxname),
4081 // no need to call copy_file
4082 // tex2lyx creates the file
4085 FileName abssrc(abstexname);
4086 copy_file(abssrc, outname);
4089 cerr << "Warning: Could not find included file '"
4090 << filename << "'." << endl;
4094 begin_inset(os, "External\n");
4095 os << "\ttemplate XFig\n"
4096 << "\tfilename " << outname << '\n';
4097 registerExternalTemplatePackages("XFig");
4099 begin_command_inset(os, "include", name);
4100 outname = subst(outname, "\"", "\\\"");
4101 os << "preview false\n"
4102 "filename \"" << outname << "\"\n";
4103 if (t.cs() == "verbatiminput")
4104 preamble.registerAutomaticallyLoadedPackage("verbatim");
4109 else if (t.cs() == "bibliographystyle") {
4110 // store new bibliographystyle
4111 bibliographystyle = p.verbatim_item();
4112 // If any other command than \bibliography, \addcontentsline
4113 // and \nocite{*} follows, we need to output the style
4114 // (because it might be used by that command).
4115 // Otherwise, it will automatically be output by LyX.
4118 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4119 if (t2.cat() == catBegin)
4121 if (t2.cat() != catEscape)
4123 if (t2.cs() == "nocite") {
4124 if (p.getArg('{', '}') == "*")
4126 } else if (t2.cs() == "bibliography")
4128 else if (t2.cs() == "phantomsection") {
4132 else if (t2.cs() == "addcontentsline") {
4133 // get the 3 arguments of \addcontentsline
4136 contentslineContent = p.getArg('{', '}');
4137 // if the last argument is not \refname we must output
4138 if (contentslineContent == "\\refname")
4145 output_ert_inset(os,
4146 "\\bibliographystyle{" + bibliographystyle + '}',
4151 else if (t.cs() == "phantomsection") {
4152 // we only support this if it occurs between
4153 // \bibliographystyle and \bibliography
4154 if (bibliographystyle.empty())
4155 output_ert_inset(os, "\\phantomsection", context);
4158 else if (t.cs() == "addcontentsline") {
4159 context.check_layout(os);
4160 // get the 3 arguments of \addcontentsline
4161 string const one = p.getArg('{', '}');
4162 string const two = p.getArg('{', '}');
4163 string const three = p.getArg('{', '}');
4164 // only if it is a \refname, we support if for the bibtex inset
4165 if (contentslineContent != "\\refname") {
4166 output_ert_inset(os,
4167 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4172 else if (t.cs() == "bibliography") {
4173 context.check_layout(os);
4175 begin_command_inset(os, "bibtex", "bibtex");
4176 if (!btprint.empty()) {
4177 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4178 // clear the string because the next BibTeX inset can be without the
4179 // \nocite{*} option
4182 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4183 // Do we have addcontentsline?
4184 if (contentslineContent == "\\refname") {
4185 BibOpts = "bibtotoc";
4186 // clear string because next BibTeX inset can be without addcontentsline
4187 contentslineContent.clear();
4189 // Do we have a bibliographystyle set?
4190 if (!bibliographystyle.empty()) {
4191 if (BibOpts.empty())
4192 BibOpts = bibliographystyle;
4194 BibOpts = BibOpts + ',' + bibliographystyle;
4195 // clear it because each bibtex entry has its style
4196 // and we need an empty string to handle \phantomsection
4197 bibliographystyle.clear();
4199 os << "options " << '"' << BibOpts << '"' << "\n";
4203 else if (t.cs() == "parbox") {
4204 // Test whether this is an outer box of a shaded box
4206 // swallow arguments
4207 while (p.hasOpt()) {
4209 p.skip_spaces(true);
4212 p.skip_spaces(true);
4214 if (p.next_token().cat() == catBegin)
4216 p.skip_spaces(true);
4217 Token to = p.get_token();
4218 bool shaded = false;
4219 if (to.asInput() == "\\begin") {
4220 p.skip_spaces(true);
4221 if (p.getArg('{', '}') == "shaded")
4226 parse_outer_box(p, os, FLAG_ITEM, outer,
4227 context, "parbox", "shaded");
4229 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4230 "", "", t.cs(), "", "");
4233 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4234 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4235 t.cs() == "shadowbox" || t.cs() == "doublebox")
4236 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4238 else if (t.cs() == "colorbox") {
4239 string const backgroundcolor = p.getArg('{', '}');
4240 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4243 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4244 || t.cs() == "shadowsize") {
4245 p.skip_spaces(true);
4246 if (t.cs() == "fboxrule")
4248 if (t.cs() == "fboxsep")
4250 if (t.cs() == "shadowsize")
4252 while (p.good() && p.next_token().cat() != catSpace
4253 && p.next_token().cat() != catNewline
4254 && p.next_token().cat() != catEscape) {
4255 if (t.cs() == "fboxrule")
4256 fboxrule = fboxrule + p.get_token().asInput();
4257 if (t.cs() == "fboxsep")
4258 fboxsep = fboxsep + p.get_token().asInput();
4259 if (t.cs() == "shadowsize")
4260 shadow_size = shadow_size + p.get_token().asInput();
4264 //\framebox() is part of the picture environment and different from \framebox{}
4265 //\framebox{} will be parsed by parse_outer_box
4266 else if (t.cs() == "framebox") {
4267 if (p.next_token().character() == '(') {
4268 //the syntax is: \framebox(x,y)[position]{content}
4269 string arg = t.asInput();
4270 arg += p.getFullParentheseArg();
4271 arg += p.getFullOpt();
4272 eat_whitespace(p, os, context, false);
4273 output_ert_inset(os, arg + '{', context);
4274 parse_text(p, os, FLAG_ITEM, outer, context);
4275 output_ert_inset(os, "}", context);
4277 //the syntax is: \framebox[width][position]{content}
4278 string special = p.getFullOpt();
4279 special += p.getOpt();
4280 parse_outer_box(p, os, FLAG_ITEM, outer,
4281 context, t.cs(), special);
4285 //\makebox() is part of the picture environment and different from \makebox{}
4286 //\makebox{} will be parsed by parse_box
4287 else if (t.cs() == "makebox") {
4288 if (p.next_token().character() == '(') {
4289 //the syntax is: \makebox(x,y)[position]{content}
4290 string arg = t.asInput();
4291 arg += p.getFullParentheseArg();
4292 arg += p.getFullOpt();
4293 eat_whitespace(p, os, context, false);
4294 output_ert_inset(os, arg + '{', context);
4295 parse_text(p, os, FLAG_ITEM, outer, context);
4296 output_ert_inset(os, "}", context);
4298 //the syntax is: \makebox[width][position]{content}
4299 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4300 "", "", t.cs(), "", "");
4303 else if (t.cs() == "smallskip" ||
4304 t.cs() == "medskip" ||
4305 t.cs() == "bigskip" ||
4306 t.cs() == "vfill") {
4307 context.check_layout(os);
4308 begin_inset(os, "VSpace ");
4311 skip_spaces_braces(p);
4314 else if ((where = is_known(t.cs(), known_spaces))) {
4315 context.check_layout(os);
4316 begin_inset(os, "space ");
4317 os << '\\' << known_coded_spaces[where - known_spaces]
4320 // LaTeX swallows whitespace after all spaces except
4321 // "\\,". We have to do that here, too, because LyX
4322 // adds "{}" which would make the spaces significant.
4324 eat_whitespace(p, os, context, false);
4325 // LyX adds "{}" after all spaces except "\\ " and
4326 // "\\,", so we have to remove "{}".
4327 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4328 // remove the braces after "\\,", too.
4333 else if (t.cs() == "newpage" ||
4334 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4335 t.cs() == "clearpage" ||
4336 t.cs() == "cleardoublepage") {
4337 context.check_layout(os);
4338 begin_inset(os, "Newpage ");
4341 skip_spaces_braces(p);
4344 else if (t.cs() == "DeclareRobustCommand" ||
4345 t.cs() == "DeclareRobustCommandx" ||
4346 t.cs() == "newcommand" ||
4347 t.cs() == "newcommandx" ||
4348 t.cs() == "providecommand" ||
4349 t.cs() == "providecommandx" ||
4350 t.cs() == "renewcommand" ||
4351 t.cs() == "renewcommandx") {
4352 // DeclareRobustCommand, DeclareRobustCommandx,
4353 // providecommand and providecommandx could be handled
4354 // by parse_command(), but we need to call
4355 // add_known_command() here.
4356 string name = t.asInput();
4357 if (p.next_token().asInput() == "*") {
4358 // Starred form. Eat '*'
4362 string const command = p.verbatim_item();
4363 string const opt1 = p.getFullOpt();
4364 string const opt2 = p.getFullOpt();
4365 add_known_command(command, opt1, !opt2.empty());
4366 string const ert = name + '{' + command + '}' +
4368 '{' + p.verbatim_item() + '}';
4370 if (t.cs() == "DeclareRobustCommand" ||
4371 t.cs() == "DeclareRobustCommandx" ||
4372 t.cs() == "providecommand" ||
4373 t.cs() == "providecommandx" ||
4374 name[name.length()-1] == '*')
4375 output_ert_inset(os, ert, context);
4377 context.check_layout(os);
4378 begin_inset(os, "FormulaMacro");
4384 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4385 // let could be handled by parse_command(),
4386 // but we need to call add_known_command() here.
4387 string ert = t.asInput();
4390 if (p.next_token().cat() == catBegin) {
4391 name = p.verbatim_item();
4392 ert += '{' + name + '}';
4394 name = p.verbatim_item();
4399 if (p.next_token().cat() == catBegin) {
4400 command = p.verbatim_item();
4401 ert += '{' + command + '}';
4403 command = p.verbatim_item();
4406 // If command is known, make name known too, to parse
4407 // its arguments correctly. For this reason we also
4408 // have commands in syntax.default that are hardcoded.
4409 CommandMap::iterator it = known_commands.find(command);
4410 if (it != known_commands.end())
4411 known_commands[t.asInput()] = it->second;
4412 output_ert_inset(os, ert, context);
4415 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4418 string name = t.asInput();
4419 string const length = p.verbatim_item();
4422 bool valid = splitLatexLength(length, valstring, unit);
4423 bool known_hspace = false;
4424 bool known_vspace = false;
4425 bool known_unit = false;
4428 istringstream iss(valstring);
4431 if (t.cs()[0] == 'h') {
4432 if (unit == "\\fill") {
4437 known_hspace = true;
4440 if (unit == "\\smallskipamount") {
4442 known_vspace = true;
4443 } else if (unit == "\\medskipamount") {
4445 known_vspace = true;
4446 } else if (unit == "\\bigskipamount") {
4448 known_vspace = true;
4449 } else if (unit == "\\fill") {
4451 known_vspace = true;
4455 if (!known_hspace && !known_vspace) {
4456 switch (unitFromString(unit)) {
4472 //unitFromString(unit) fails for relative units like Length::PCW
4473 // therefore handle them separately
4474 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4475 || unit == "\\textwidth" || unit == "\\linewidth"
4476 || unit == "\\textheight" || unit == "\\paperheight")
4484 // check for glue lengths
4485 bool is_gluelength = false;
4486 string gluelength = length;
4487 string::size_type i = length.find(" minus");
4488 if (i == string::npos) {
4489 i = length.find(" plus");
4490 if (i != string::npos)
4491 is_gluelength = true;
4493 is_gluelength = true;
4494 // if yes transform "9xx minus 8yy plus 7zz"
4496 if (is_gluelength) {
4497 i = gluelength.find(" minus");
4498 if (i != string::npos)
4499 gluelength.replace(i, 7, "-");
4500 i = gluelength.find(" plus");
4501 if (i != string::npos)
4502 gluelength.replace(i, 6, "+");
4505 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4506 // Literal horizontal length or known variable
4507 context.check_layout(os);
4508 begin_inset(os, "space ");
4516 if (known_unit && !known_hspace)
4517 os << "\n\\length " << translate_len(length);
4519 os << "\n\\length " << gluelength;
4521 } else if (known_unit || known_vspace || is_gluelength) {
4522 // Literal vertical length or known variable
4523 context.check_layout(os);
4524 begin_inset(os, "VSpace ");
4527 if (known_unit && !known_vspace)
4528 os << translate_len(length);
4535 // LyX can't handle other length variables in Inset VSpace/space
4540 output_ert_inset(os, name + '{' + unit + '}', context);
4541 else if (value == -1.0)
4542 output_ert_inset(os, name + "{-" + unit + '}', context);
4544 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4546 output_ert_inset(os, name + '{' + length + '}', context);
4550 // The single '=' is meant here.
4551 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4555 context.check_layout(os);
4556 docstring const name = newinsetlayout->name();
4557 bool const caption = name.find(from_ascii("Caption:")) == 0;
4559 begin_inset(os, "Caption ");
4560 os << to_utf8(name.substr(8)) << '\n';
4562 begin_inset(os, "Flex ");
4563 os << to_utf8(name) << '\n'
4564 << "status collapsed\n";
4566 if (newinsetlayout->isPassThru()) {
4567 // set catcodes to verbatim early, just in case.
4568 p.setCatcodes(VERBATIM_CATCODES);
4569 string delim = p.get_token().asInput();
4571 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4572 //FIXME: handle error condition
4573 string const arg = p.verbatimStuff("}").second;
4574 Context newcontext(true, context.textclass);
4575 if (newinsetlayout->forcePlainLayout())
4576 newcontext.layout = &context.textclass.plainLayout();
4577 output_ert(os, arg, newcontext);
4579 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4585 else if (t.cs() == "includepdf") {
4587 string const arg = p.getArg('[', ']');
4588 map<string, string> opts;
4589 vector<string> keys;
4590 split_map(arg, opts, keys);
4591 string name = normalize_filename(p.verbatim_item());
4592 string const path = getMasterFilePath(true);
4593 // We want to preserve relative / absolute filenames,
4594 // therefore path is only used for testing
4595 if (!makeAbsPath(name, path).exists()) {
4596 // The file extension is probably missing.
4597 // Now try to find it out.
4598 char const * const pdfpages_format[] = {"pdf", 0};
4599 string const pdftex_name =
4600 find_file(name, path, pdfpages_format);
4601 if (!pdftex_name.empty()) {
4606 FileName const absname = makeAbsPath(name, path);
4607 if (absname.exists())
4609 fix_child_filename(name);
4610 copy_file(absname, name);
4612 cerr << "Warning: Could not find file '"
4613 << name << "'." << endl;
4615 context.check_layout(os);
4616 begin_inset(os, "External\n\ttemplate ");
4617 os << "PDFPages\n\tfilename "
4619 // parse the options
4620 if (opts.find("pages") != opts.end())
4621 os << "\textra LaTeX \"pages="
4622 << opts["pages"] << "\"\n";
4623 if (opts.find("angle") != opts.end())
4624 os << "\trotateAngle "
4625 << opts["angle"] << '\n';
4626 if (opts.find("origin") != opts.end()) {
4628 string const opt = opts["origin"];
4629 if (opt == "tl") ss << "topleft";
4630 if (opt == "bl") ss << "bottomleft";
4631 if (opt == "Bl") ss << "baselineleft";
4632 if (opt == "c") ss << "center";
4633 if (opt == "tc") ss << "topcenter";
4634 if (opt == "bc") ss << "bottomcenter";
4635 if (opt == "Bc") ss << "baselinecenter";
4636 if (opt == "tr") ss << "topright";
4637 if (opt == "br") ss << "bottomright";
4638 if (opt == "Br") ss << "baselineright";
4639 if (!ss.str().empty())
4640 os << "\trotateOrigin " << ss.str() << '\n';
4642 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4644 if (opts.find("width") != opts.end())
4646 << translate_len(opts["width"]) << '\n';
4647 if (opts.find("height") != opts.end())
4649 << translate_len(opts["height"]) << '\n';
4650 if (opts.find("keepaspectratio") != opts.end())
4651 os << "\tkeepAspectRatio\n";
4653 context.check_layout(os);
4654 registerExternalTemplatePackages("PDFPages");
4657 else if (t.cs() == "loadgame") {
4659 string name = normalize_filename(p.verbatim_item());
4660 string const path = getMasterFilePath(true);
4661 // We want to preserve relative / absolute filenames,
4662 // therefore path is only used for testing
4663 if (!makeAbsPath(name, path).exists()) {
4664 // The file extension is probably missing.
4665 // Now try to find it out.
4666 char const * const lyxskak_format[] = {"fen", 0};
4667 string const lyxskak_name =
4668 find_file(name, path, lyxskak_format);
4669 if (!lyxskak_name.empty())
4670 name = lyxskak_name;
4672 FileName const absname = makeAbsPath(name, path);
4673 if (absname.exists())
4675 fix_child_filename(name);
4676 copy_file(absname, name);
4678 cerr << "Warning: Could not find file '"
4679 << name << "'." << endl;
4680 context.check_layout(os);
4681 begin_inset(os, "External\n\ttemplate ");
4682 os << "ChessDiagram\n\tfilename "
4685 context.check_layout(os);
4686 // after a \loadgame follows a \showboard
4687 if (p.get_token().asInput() == "showboard")
4689 registerExternalTemplatePackages("ChessDiagram");
4693 // try to see whether the string is in unicodesymbols
4694 // Only use text mode commands, since we are in text mode here,
4695 // and math commands may be invalid (bug 6797)
4696 string name = t.asInput();
4697 // handle the dingbats, cyrillic and greek
4698 if (name == "\\ding" || name == "\\textcyr" ||
4699 (name == "\\textgreek" && !preamble.usePolyglossia()))
4700 name = name + '{' + p.getArg('{', '}') + '}';
4701 // handle the ifsym characters
4702 else if (name == "\\textifsymbol") {
4703 string const optif = p.getFullOpt();
4704 string const argif = p.getArg('{', '}');
4705 name = name + optif + '{' + argif + '}';
4707 // handle the \ascii characters
4708 // the case of \ascii within braces, as LyX outputs it, is already
4709 // handled for t.cat() == catBegin
4710 else if (name == "\\ascii") {
4711 // the code is "\asci\xxx"
4712 name = "{" + name + p.get_token().asInput() + "}";
4715 // handle some TIPA special characters
4716 else if (preamble.isPackageUsed("tipa")) {
4717 if (name == "\\textglobfall") {
4720 } else if (name == "\\s") {
4721 // fromLaTeXCommand() does not yet
4722 // recognize tipa short cuts
4723 name = "\\textsyllabic";
4724 } else if (name == "\\=" &&
4725 p.next_token().asInput() == "*") {
4726 // fromLaTeXCommand() does not yet
4727 // recognize tipa short cuts
4730 } else if (name == "\\textdoublevertline") {
4731 // FIXME: This is not correct,
4732 // \textvertline is higher than \textbardbl
4733 name = "\\textbardbl";
4735 } else if (name == "\\!" ) {
4736 if (p.next_token().asInput() == "b") {
4737 p.get_token(); // eat 'b'
4740 } else if (p.next_token().asInput() == "d") {
4744 } else if (p.next_token().asInput() == "g") {
4748 } else if (p.next_token().asInput() == "G") {
4750 name = "\\texthtscg";
4752 } else if (p.next_token().asInput() == "j") {
4754 name = "\\texthtbardotlessj";
4756 } else if (p.next_token().asInput() == "o") {
4758 name = "\\textbullseye";
4761 } else if (name == "\\*" ) {
4762 if (p.next_token().asInput() == "k") {
4764 name = "\\textturnk";
4766 } else if (p.next_token().asInput() == "r") {
4767 p.get_token(); // eat 'b'
4768 name = "\\textturnr";
4770 } else if (p.next_token().asInput() == "t") {
4772 name = "\\textturnt";
4774 } else if (p.next_token().asInput() == "w") {
4776 name = "\\textturnw";
4781 if ((name.size() == 2 &&
4782 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4783 p.next_token().asInput() != "*") ||
4784 is_known(name.substr(1), known_tipa_marks)) {
4785 // name is a command that corresponds to a
4786 // combining character in unicodesymbols.
4787 // Append the argument, fromLaTeXCommand()
4788 // will either convert it to a single
4789 // character or a combining sequence.
4790 name += '{' + p.verbatim_item() + '}';
4792 // now get the character from unicodesymbols
4796 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4797 Encodings::TEXT_CMD, termination, rem, &req);
4799 context.check_layout(os);
4802 output_ert_inset(os, to_utf8(rem), context);
4804 skip_spaces_braces(p);
4805 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4806 preamble.registerAutomaticallyLoadedPackage(*it);
4808 //cerr << "#: " << t << " mode: " << mode << endl;
4809 // heuristic: read up to next non-nested space
4811 string s = t.asInput();
4812 string z = p.verbatim_item();
4813 while (p.good() && z != " " && !z.empty()) {
4814 //cerr << "read: " << z << endl;
4816 z = p.verbatim_item();
4818 cerr << "found ERT: " << s << endl;
4819 output_ert_inset(os, s + ' ', context);
4822 if (t.asInput() == name &&
4823 p.next_token().asInput() == "*") {
4824 // Starred commands like \vspace*{}
4825 p.get_token(); // Eat '*'
4828 if (!parse_command(name, p, os, outer, context))
4829 output_ert_inset(os, name, context);
4833 if (flags & FLAG_LEAVE) {
4834 flags &= ~FLAG_LEAVE;
4841 string guessLanguage(Parser & p, string const & lang)
4843 typedef std::map<std::string, size_t> LangMap;
4844 // map from language names to number of characters
4847 for (char const * const * i = supported_CJK_languages; *i; i++)
4848 used[string(*i)] = 0;
4851 Token const t = p.get_token();
4852 // comments are not counted for any language
4853 if (t.cat() == catComment)
4855 // commands are not counted as well, but we need to detect
4856 // \begin{CJK} and switch encoding if needed
4857 if (t.cat() == catEscape) {
4858 if (t.cs() == "inputencoding") {
4859 string const enc = subst(p.verbatim_item(), "\n", " ");
4860 p.setEncoding(enc, Encoding::inputenc);
4863 if (t.cs() != "begin")
4866 // Non-CJK content is counted for lang.
4867 // We do not care about the real language here:
4868 // If we have more non-CJK contents than CJK contents,
4869 // we simply use the language that was specified as
4870 // babel main language.
4871 used[lang] += t.asInput().length();
4874 // Now we are starting an environment
4876 string const name = p.getArg('{', '}');
4877 if (name != "CJK") {
4881 // It is a CJK environment
4883 /* name = */ p.getArg('{', '}');
4884 string const encoding = p.getArg('{', '}');
4885 /* mapping = */ p.getArg('{', '}');
4886 string const encoding_old = p.getEncoding();
4887 char const * const * const where =
4888 is_known(encoding, supported_CJK_encodings);
4890 p.setEncoding(encoding, Encoding::CJK);
4892 p.setEncoding("UTF-8");
4893 string const text = p.ertEnvironment("CJK");
4894 p.setEncoding(encoding_old);
4897 // ignore contents in unknown CJK encoding
4900 // the language of the text
4902 supported_CJK_languages[where - supported_CJK_encodings];
4903 used[cjk] += text.length();
4905 LangMap::const_iterator use = used.begin();
4906 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4907 if (it->second > use->second)