2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "sub", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
187 /// LaTeX names for quotes
188 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
189 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
190 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
191 "guilsinglleft", "frq", "guilsinglright", 0};
193 /// the same as known_quotes with .lyx names
194 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
195 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
196 "gld", "grd", "gls", "ers", "fls",
197 "fls", "frs", "frs", 0};
199 /// LaTeX names for font sizes
200 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
201 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
203 /// the same as known_sizes with .lyx names
204 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
205 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
207 /// LaTeX 2.09 names for font families
208 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
210 /// LaTeX names for font families
211 char const * const known_font_families[] = { "rmfamily", "sffamily",
214 /// LaTeX names for font family changing commands
215 char const * const known_text_font_families[] = { "textrm", "textsf",
218 /// The same as known_old_font_families, known_font_families and
219 /// known_text_font_families with .lyx names
220 char const * const known_coded_font_families[] = { "roman", "sans",
223 /// LaTeX 2.09 names for font series
224 char const * const known_old_font_series[] = { "bf", 0};
226 /// LaTeX names for font series
227 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
229 /// LaTeX names for font series changing commands
230 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
232 /// The same as known_old_font_series, known_font_series and
233 /// known_text_font_series with .lyx names
234 char const * const known_coded_font_series[] = { "bold", "medium", 0};
236 /// LaTeX 2.09 names for font shapes
237 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
239 /// LaTeX names for font shapes
240 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
243 /// LaTeX names for font shape changing commands
244 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
247 /// The same as known_old_font_shapes, known_font_shapes and
248 /// known_text_font_shapes with .lyx names
249 char const * const known_coded_font_shapes[] = { "italic", "slanted",
250 "smallcaps", "up", 0};
252 /// Known special characters which need skip_spaces_braces() afterwards
253 char const * const known_special_chars[] = {"ldots",
254 "lyxarrow", "textcompwordmark",
255 "slash", "textasciitilde", "textasciicircum", "textbackslash",
256 "LyX", "TeX", "LaTeXe",
259 /// special characters from known_special_chars which may have a \\protect before
260 char const * const known_special_protect_chars[] = {"LyX", "TeX",
261 "LaTeXe", "LaTeX", 0};
263 /// the same as known_special_chars with .lyx names
264 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
265 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
266 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
267 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
268 "\\SpecialChar LaTeX\n", 0};
271 * Graphics file extensions known by the dvips driver of the graphics package.
272 * These extensions are used to complete the filename of an included
273 * graphics file if it does not contain an extension.
274 * The order must be the same that latex uses to find a file, because we
275 * will use the first extension that matches.
276 * This is only an approximation for the common cases. If we would want to
277 * do it right in all cases, we would need to know which graphics driver is
278 * used and know the extensions of every driver of the graphics package.
280 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
281 "ps.gz", "eps.Z", "ps.Z", 0};
284 * Graphics file extensions known by the pdftex driver of the graphics package.
285 * \sa known_dvips_graphics_formats
287 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
291 * Known file extensions for TeX files as used by \\include.
293 char const * const known_tex_extensions[] = {"tex", 0};
295 /// spaces known by InsetSpace
296 char const * const known_spaces[] = { " ", "space", ",",
297 "thinspace", "quad", "qquad", "enspace", "enskip",
298 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
299 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
300 "upbracefill", "downbracefill", 0};
302 /// the same as known_spaces with .lyx names
303 char const * const known_coded_spaces[] = { "space{}", "space{}",
304 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
305 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
306 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
307 "upbracefill{}", "downbracefill{}", 0};
309 /// known TIPA combining diacritical marks
310 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
311 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
312 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
313 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
314 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
315 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
318 /// TIPA tones that need special handling
319 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
321 // string to store the float type to be able to determine the type of subfloats
322 string float_type = "";
325 /// splits "x=z, y=b" into a map and an ordered keyword vector
326 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
331 keys.resize(v.size());
332 for (size_t i = 0; i < v.size(); ++i) {
333 size_t const pos = v[i].find('=');
334 string const index = trimSpaceAndEol(v[i].substr(0, pos));
335 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
343 * Split a LaTeX length into value and unit.
344 * The latter can be a real unit like "pt", or a latex length variable
345 * like "\textwidth". The unit may contain additional stuff like glue
346 * lengths, but we don't care, because such lengths are ERT anyway.
347 * \returns true if \p value and \p unit are valid.
349 bool splitLatexLength(string const & len, string & value, string & unit)
353 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
354 //'4,5' is a valid LaTeX length number. Change it to '4.5'
355 string const length = subst(len, ',', '.');
356 if (i == string::npos)
359 if (len[0] == '\\') {
360 // We had something like \textwidth without a factor
366 value = trimSpaceAndEol(string(length, 0, i));
370 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
371 if (contains(len, '\\'))
372 unit = trimSpaceAndEol(string(len, i));
374 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
379 /// A simple function to translate a latex length to something LyX can
380 /// understand. Not perfect, but rather best-effort.
381 bool translate_len(string const & length, string & valstring, string & unit)
383 if (!splitLatexLength(length, valstring, unit))
385 // LyX uses percent values
387 istringstream iss(valstring);
392 string const percentval = oss.str();
394 if (unit.empty() || unit[0] != '\\')
396 string::size_type const i = unit.find(' ');
397 string const endlen = (i == string::npos) ? string() : string(unit, i);
398 if (unit == "\\textwidth") {
399 valstring = percentval;
400 unit = "text%" + endlen;
401 } else if (unit == "\\columnwidth") {
402 valstring = percentval;
403 unit = "col%" + endlen;
404 } else if (unit == "\\paperwidth") {
405 valstring = percentval;
406 unit = "page%" + endlen;
407 } else if (unit == "\\linewidth") {
408 valstring = percentval;
409 unit = "line%" + endlen;
410 } else if (unit == "\\paperheight") {
411 valstring = percentval;
412 unit = "pheight%" + endlen;
413 } else if (unit == "\\textheight") {
414 valstring = percentval;
415 unit = "theight%" + endlen;
423 string translate_len(string const & length)
427 if (translate_len(length, value, unit))
429 // If the input is invalid, return what we have.
437 * Translates a LaTeX length into \p value, \p unit and
438 * \p special parts suitable for a box inset.
439 * The difference from translate_len() is that a box inset knows about
440 * some special "units" that are stored in \p special.
442 void translate_box_len(string const & length, string & value, string & unit, string & special)
444 if (translate_len(length, value, unit)) {
445 if (unit == "\\height" || unit == "\\depth" ||
446 unit == "\\totalheight" || unit == "\\width") {
447 special = unit.substr(1);
448 // The unit is not used, but LyX requires a dummy setting
461 * Find a file with basename \p name in path \p path and an extension
464 string find_file(string const & name, string const & path,
465 char const * const * extensions)
467 for (char const * const * what = extensions; *what; ++what) {
468 string const trial = addExtension(name, *what);
469 if (makeAbsPath(trial, path).exists())
476 void begin_inset(ostream & os, string const & name)
478 os << "\n\\begin_inset " << name;
482 void begin_command_inset(ostream & os, string const & name,
483 string const & latexname)
485 begin_inset(os, "CommandInset ");
486 os << name << "\nLatexCommand " << latexname << '\n';
490 void end_inset(ostream & os)
492 os << "\n\\end_inset\n\n";
496 bool skip_braces(Parser & p)
498 if (p.next_token().cat() != catBegin)
501 if (p.next_token().cat() == catEnd) {
510 /// replace LaTeX commands in \p s from the unicodesymbols file with their
512 docstring convert_unicodesymbols(docstring s)
515 for (size_t i = 0; i < s.size();) {
524 docstring parsed = encodings.fromLaTeXCommand(s,
525 Encodings::TEXT_CMD, termination, rem, &req);
526 set<string>::const_iterator it = req.begin();
527 set<string>::const_iterator en = req.end();
528 for (; it != en; ++it)
529 preamble.registerAutomaticallyLoadedPackage(*it);
532 if (s.empty() || s[0] != '\\')
541 /// try to convert \p s to a valid InsetCommand argument
542 string convert_command_inset_arg(string s)
545 // since we don't know the input encoding we can't use from_utf8
546 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
547 // LyX cannot handle newlines in a latex command
548 return subst(s, "\n", " ");
552 void output_ert(ostream & os, string const & s, Context & context)
554 context.check_layout(os);
555 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
557 os << "\n\\backslash\n";
558 else if (*it == '\n') {
559 context.new_paragraph(os);
560 context.check_layout(os);
564 context.check_end_layout(os);
568 void output_ert_inset(ostream & os, string const & s, Context & context)
570 // We must have a valid layout before outputting the ERT inset.
571 context.check_layout(os);
572 Context newcontext(true, context.textclass);
573 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
574 if (layout.forcePlainLayout())
575 newcontext.layout = &context.textclass.plainLayout();
576 begin_inset(os, "ERT");
577 os << "\nstatus collapsed\n";
578 output_ert(os, s, newcontext);
583 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
585 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
588 if (checkModule(name, command))
589 return findLayoutWithoutModule(textclass, name, command);
594 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
596 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
599 if (checkModule(name, command))
600 return findInsetLayoutWithoutModule(textclass, name, command);
605 void eat_whitespace(Parser &, ostream &, Context &, bool);
609 * Skips whitespace and braces.
610 * This should be called after a command has been parsed that is not put into
611 * ERT, and where LyX adds "{}" if needed.
613 void skip_spaces_braces(Parser & p, bool keepws = false)
615 /* The following four examples produce the same typeset output and
616 should be handled by this function:
624 // Unfortunately we need to skip comments, too.
625 // We can't use eat_whitespace since writing them after the {}
626 // results in different output in some cases.
627 bool const skipped_spaces = p.skip_spaces(true);
628 bool const skipped_braces = skip_braces(p);
629 if (keepws && skipped_spaces && !skipped_braces)
630 // put back the space (it is better handled by check_space)
631 p.unskip_spaces(true);
635 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
636 Context & context, Layout::LaTeXArgMap const & latexargs)
639 context.check_layout(os);
644 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
645 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
646 for (; lait != laend; ++lait) {
648 eat_whitespace(p, os, context, false);
649 if (lait->second.mandatory) {
650 if (p.next_token().cat() != catBegin)
652 p.get_token(); // eat '{'
654 context.check_layout(os);
657 begin_inset(os, "Argument ");
660 os << i << "\nstatus collapsed\n\n";
661 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
664 if (p.next_token().cat() == catEscape ||
665 p.next_token().character() != '[')
667 p.get_token(); // eat '['
669 context.check_layout(os);
672 begin_inset(os, "Argument ");
675 os << i << "\nstatus collapsed\n\n";
676 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
679 eat_whitespace(p, os, context, false);
684 void output_command_layout(ostream & os, Parser & p, bool outer,
685 Context & parent_context,
686 Layout const * newlayout)
688 TeXFont const oldFont = parent_context.font;
689 // save the current font size
690 string const size = oldFont.size;
691 // reset the font size to default, because the font size switches
692 // don't affect section headings and the like
693 parent_context.font.size = Context::normalfont.size;
694 // we only need to write the font change if we have an open layout
695 if (!parent_context.atParagraphStart())
696 output_font_change(os, oldFont, parent_context.font);
697 parent_context.check_end_layout(os);
698 Context context(true, parent_context.textclass, newlayout,
699 parent_context.layout, parent_context.font);
700 if (parent_context.deeper_paragraph) {
701 // We are beginning a nested environment after a
702 // deeper paragraph inside the outer list environment.
703 // Therefore we don't need to output a "begin deeper".
704 context.need_end_deeper = true;
706 context.check_deeper(os);
707 output_arguments(os, p, outer, true, false, context,
708 context.layout->latexargs());
709 parse_text(p, os, FLAG_ITEM, outer, context);
710 output_arguments(os, p, outer, false, true, context,
711 context.layout->postcommandargs());
712 context.check_end_layout(os);
713 if (parent_context.deeper_paragraph) {
714 // We must suppress the "end deeper" because we
715 // suppressed the "begin deeper" above.
716 context.need_end_deeper = false;
718 context.check_end_deeper(os);
719 // We don't need really a new paragraph, but
720 // we must make sure that the next item gets a \begin_layout.
721 parent_context.new_paragraph(os);
722 // Set the font size to the original value. No need to output it here
723 // (Context::begin_layout() will do that if needed)
724 parent_context.font.size = size;
729 * Output a space if necessary.
730 * This function gets called for every whitespace token.
732 * We have three cases here:
733 * 1. A space must be suppressed. Example: The lyxcode case below
734 * 2. A space may be suppressed. Example: Spaces before "\par"
735 * 3. A space must not be suppressed. Example: A space between two words
737 * We currently handle only 1. and 3 and from 2. only the case of
738 * spaces before newlines as a side effect.
740 * 2. could be used to suppress as many spaces as possible. This has two effects:
741 * - Reimporting LyX generated LaTeX files changes almost no whitespace
742 * - Superflous whitespace from non LyX generated LaTeX files is removed.
743 * The drawback is that the logic inside the function becomes
744 * complicated, and that is the reason why it is not implemented.
746 void check_space(Parser & p, ostream & os, Context & context)
748 Token const next = p.next_token();
749 Token const curr = p.curr_token();
750 // A space before a single newline and vice versa must be ignored
751 // LyX emits a newline before \end{lyxcode}.
752 // This newline must be ignored,
753 // otherwise LyX will add an additional protected space.
754 if (next.cat() == catSpace ||
755 next.cat() == catNewline ||
756 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
759 context.check_layout(os);
765 * Parse all arguments of \p command
767 void parse_arguments(string const & command,
768 vector<ArgumentType> const & template_arguments,
769 Parser & p, ostream & os, bool outer, Context & context)
771 string ert = command;
772 size_t no_arguments = template_arguments.size();
773 for (size_t i = 0; i < no_arguments; ++i) {
774 switch (template_arguments[i]) {
777 // This argument contains regular LaTeX
778 output_ert_inset(os, ert + '{', context);
779 eat_whitespace(p, os, context, false);
780 if (template_arguments[i] == required)
781 parse_text(p, os, FLAG_ITEM, outer, context);
783 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
787 // This argument consists only of a single item.
788 // The presence of '{' or not must be preserved.
790 if (p.next_token().cat() == catBegin)
791 ert += '{' + p.verbatim_item() + '}';
793 ert += p.verbatim_item();
797 // This argument may contain special characters
798 ert += '{' + p.verbatim_item() + '}';
802 // true because we must not eat whitespace
803 // if an optional arg follows we must not strip the
804 // brackets from this one
805 if (i < no_arguments - 1 &&
806 template_arguments[i+1] == optional)
807 ert += p.getFullOpt(true);
809 ert += p.getOpt(true);
813 output_ert_inset(os, ert, context);
818 * Check whether \p command is a known command. If yes,
819 * handle the command with all arguments.
820 * \return true if the command was parsed, false otherwise.
822 bool parse_command(string const & command, Parser & p, ostream & os,
823 bool outer, Context & context)
825 if (known_commands.find(command) != known_commands.end()) {
826 parse_arguments(command, known_commands[command], p, os,
834 /// Parses a minipage or parbox
835 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
836 unsigned inner_flags, bool outer, Context & parent_context,
837 string const & outer_type, string const & special,
838 string inner_type, string const & frame_color,
839 string const & background_color)
843 string hor_pos = "l";
844 // We need to set the height to the LaTeX default of 1\\totalheight
845 // for the case when no height argument is given
846 string height_value = "1";
847 string height_unit = "in";
848 string height_special = "totalheight";
853 string width_special = "none";
854 string thickness = "0.4pt";
856 thickness = fboxrule;
861 separation = fboxsep;
865 if (shadow_size != "")
866 shadowsize = shadow_size;
869 string framecolor = "black";
870 string backgroundcolor = "none";
871 if (frame_color != "")
872 framecolor = frame_color;
873 if (background_color != "")
874 backgroundcolor = background_color;
875 // if there is a color box around the \begin statements have not yet been parsed
877 if (frame_color != "" || background_color != "") {
878 eat_whitespace(p, os, parent_context, false);
879 p.get_token().asInput(); // the '{'
881 if (p.next_token().asInput() == "\\begin") {
882 p.get_token().asInput();
884 inner_type = "minipage";
885 inner_flags = FLAG_END;
888 else if (p.next_token().asInput() == "\\parbox") {
889 p.get_token().asInput();
890 inner_type = "parbox";
891 inner_flags = FLAG_ITEM;
894 else if (p.next_token().asInput() == "\\makebox") {
895 p.get_token().asInput();
896 inner_type = "makebox";
897 inner_flags = FLAG_ITEM;
899 // in case there is just \colorbox{color}{text}
902 inner_type = "makebox";
903 inner_flags = FLAG_BRACE_LAST;
908 if (!inner_type.empty() && p.hasOpt()) {
909 if (inner_type != "makebox")
910 position = p.getArg('[', ']');
912 latex_width = p.getArg('[', ']');
913 translate_box_len(latex_width, width_value, width_unit, width_special);
916 if (position != "t" && position != "c" && position != "b") {
917 cerr << "invalid position " << position << " for "
918 << inner_type << endl;
922 if (inner_type != "makebox") {
923 latex_height = p.getArg('[', ']');
924 translate_box_len(latex_height, height_value, height_unit, height_special);
926 string const opt = p.getArg('[', ']');
929 if (hor_pos != "l" && hor_pos != "c" &&
930 hor_pos != "r" && hor_pos != "s") {
931 cerr << "invalid hor_pos " << hor_pos
932 << " for " << inner_type << endl;
939 inner_pos = p.getArg('[', ']');
940 if (inner_pos != "c" && inner_pos != "t" &&
941 inner_pos != "b" && inner_pos != "s") {
942 cerr << "invalid inner_pos "
943 << inner_pos << " for "
944 << inner_type << endl;
945 inner_pos = position;
949 if (inner_type == "makebox")
953 if (inner_type.empty()) {
954 if (special.empty() && outer_type != "framebox")
955 latex_width = "1\\columnwidth";
958 latex_width = p2.getArg('[', ']');
959 string const opt = p2.getArg('[', ']');
962 if (hor_pos != "l" && hor_pos != "c" &&
963 hor_pos != "r" && hor_pos != "s") {
964 cerr << "invalid hor_pos " << hor_pos
965 << " for " << outer_type << endl;
969 if (outer_type == "framebox")
973 } else if (inner_type != "makebox")
974 latex_width = p.verbatim_item();
975 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
976 // as this is LyX's standard for such cases (except for makebox)
977 // \framebox is more special and handled below
978 if (latex_width.empty() && inner_type != "makebox"
979 && outer_type != "framebox")
980 latex_width = "1\\columnwidth";
982 translate_len(latex_width, width_value, width_unit);
984 bool shadedparbox = false;
985 if (inner_type == "shaded") {
986 eat_whitespace(p, os, parent_context, false);
987 if (outer_type == "parbox") {
989 if (p.next_token().cat() == catBegin)
991 eat_whitespace(p, os, parent_context, false);
997 // If we already read the inner box we have to push the inner env
998 if (!outer_type.empty() && !inner_type.empty() &&
999 (inner_flags & FLAG_END))
1000 active_environments.push_back(inner_type);
1001 bool use_ert = false;
1002 if (!outer_type.empty() && !inner_type.empty()) {
1003 // Look whether there is some content after the end of the
1004 // inner box, but before the end of the outer box.
1005 // If yes, we need to output ERT.
1007 if (inner_flags & FLAG_END)
1008 p.ertEnvironment(inner_type);
1011 p.skip_spaces(true);
1012 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1013 if ((outer_env && p.next_token().asInput() != "\\end") ||
1014 (!outer_env && p.next_token().cat() != catEnd)) {
1015 // something is between the end of the inner box and
1016 // the end of the outer box, so we need to use ERT.
1021 // if only \makebox{content} was used we can set its width to 1\width
1022 // because this identic and also identic to \mbox
1023 // this doesn't work for \framebox{content}, thus we have to use ERT for this
1024 if (latex_width.empty() && inner_type == "makebox" && background_color == "") {
1027 width_special = "width";
1028 } else if (latex_width.empty() && outer_type == "framebox") {
1029 width_value.clear();
1031 width_special = "none";
1035 if (!outer_type.empty()) {
1036 if (outer_flags & FLAG_END)
1037 ss << "\\begin{" << outer_type << '}';
1039 ss << '\\' << outer_type << '{';
1040 if (!special.empty())
1044 if (!inner_type.empty()) {
1045 if (inner_type != "shaded") {
1046 if (inner_flags & FLAG_END)
1047 ss << "\\begin{" << inner_type << '}';
1049 ss << '\\' << inner_type;
1051 if (!position.empty())
1052 ss << '[' << position << ']';
1053 if (!latex_height.empty())
1054 ss << '[' << latex_height << ']';
1055 if (!inner_pos.empty())
1056 ss << '[' << inner_pos << ']';
1057 ss << '{' << latex_width << '}';
1058 if (!(inner_flags & FLAG_END))
1061 if (inner_type == "shaded")
1062 ss << "\\begin{shaded}";
1063 output_ert_inset(os, ss.str(), parent_context);
1064 if (!inner_type.empty()) {
1065 parse_text(p, os, inner_flags, outer, parent_context);
1066 if (inner_flags & FLAG_END)
1067 output_ert_inset(os, "\\end{" + inner_type + '}',
1070 output_ert_inset(os, "}", parent_context);
1072 if (!outer_type.empty()) {
1073 // If we already read the inner box we have to pop
1075 if (!inner_type.empty() && (inner_flags & FLAG_END))
1076 active_environments.pop_back();
1078 // Ensure that the end of the outer box is parsed correctly:
1079 // The opening brace has been eaten by parse_outer_box()
1080 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1081 outer_flags &= ~FLAG_ITEM;
1082 outer_flags |= FLAG_BRACE_LAST;
1084 parse_text(p, os, outer_flags, outer, parent_context);
1085 if (outer_flags & FLAG_END)
1086 output_ert_inset(os, "\\end{" + outer_type + '}',
1089 output_ert_inset(os, "}", parent_context);
1092 // LyX does not like empty positions, so we have
1093 // to set them to the LaTeX default values here.
1094 if (position.empty())
1096 if (inner_pos.empty())
1097 inner_pos = position;
1098 parent_context.check_layout(os);
1099 begin_inset(os, "Box ");
1100 if (outer_type == "framed")
1102 else if (outer_type == "framebox" || outer_type == "fbox" || frame_color != "")
1104 else if (outer_type == "shadowbox")
1105 os << "Shadowbox\n";
1106 else if ((outer_type == "shaded" && inner_type.empty()) ||
1107 (outer_type == "minipage" && inner_type == "shaded") ||
1108 (outer_type == "parbox" && inner_type == "shaded")) {
1110 preamble.registerAutomaticallyLoadedPackage("color");
1111 } else if (outer_type == "doublebox")
1112 os << "Doublebox\n";
1113 else if (outer_type.empty() || outer_type == "mbox")
1114 os << "Frameless\n";
1116 os << outer_type << '\n';
1117 os << "position \"" << position << "\"\n";
1118 os << "hor_pos \"" << hor_pos << "\"\n";
1119 if (outer_type == "mbox")
1120 os << "has_inner_box 1\n";
1121 if (frame_color != "")
1122 os << "has_inner_box 0\n";
1124 os << "has_inner_box " << !inner_type.empty() << "\n";
1125 os << "inner_pos \"" << inner_pos << "\"\n";
1126 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1128 if (outer_type == "mbox")
1129 os << "use_makebox 1\n";
1130 if (frame_color != "")
1131 os << "use_makebox 0\n";
1133 os << "use_makebox " << (inner_type == "makebox") << '\n';
1134 if (outer_type == "mbox")
1135 os << "width \"\"\n";
1136 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1137 else if (contains(width_unit, '\\'))
1138 os << "width \"" << width_value << "in" << "\"\n";
1140 os << "width \"" << width_value << width_unit << "\"\n";
1141 if (contains(width_unit, '\\')) {
1142 width_unit.erase (0,1); // remove the leading '\'
1143 os << "special \"" << width_unit << "\"\n";
1145 os << "special \"" << width_special << "\"\n";
1146 if (contains(height_unit, '\\'))
1147 os << "height \"" << height_value << "in" << "\"\n";
1149 os << "height \"" << height_value << height_unit << "\"\n";
1150 os << "height_special \"" << height_special << "\"\n";
1151 os << "thickness \"" << thickness << "\"\n";
1152 os << "separation \"" << separation << "\"\n";
1153 os << "shadowsize \"" << shadowsize << "\"\n";
1154 os << "framecolor \"" << framecolor << "\"\n";
1155 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1156 os << "status open\n\n";
1158 // Unfortunately we can't use parse_text_in_inset:
1159 // InsetBox::forcePlainLayout() is hard coded and does not
1160 // use the inset layout. Apart from that do we call parse_text
1161 // up to two times, but need only one check_end_layout.
1162 bool const forcePlainLayout =
1163 (!inner_type.empty() || inner_type == "makebox") &&
1164 outer_type != "shaded" && outer_type != "framed";
1165 Context context(true, parent_context.textclass);
1166 if (forcePlainLayout)
1167 context.layout = &context.textclass.plainLayout();
1169 context.font = parent_context.font;
1171 // If we have no inner box the contents will be read with the outer box
1172 if (!inner_type.empty())
1173 parse_text(p, os, inner_flags, outer, context);
1175 // Ensure that the end of the outer box is parsed correctly:
1176 // The opening brace has been eaten by parse_outer_box()
1177 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1178 outer_flags &= ~FLAG_ITEM;
1179 outer_flags |= FLAG_BRACE_LAST;
1182 // Find end of outer box, output contents if inner_type is
1183 // empty and output possible comments
1184 if (!outer_type.empty()) {
1185 // If we already read the inner box we have to pop
1187 if (!inner_type.empty() && (inner_flags & FLAG_END))
1188 active_environments.pop_back();
1189 // This does not output anything but comments if
1190 // inner_type is not empty (see use_ert)
1191 parse_text(p, os, outer_flags, outer, context);
1194 context.check_end_layout(os);
1196 #ifdef PRESERVE_LAYOUT
1197 // LyX puts a % after the end of the minipage
1198 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1200 //output_ert_inset(os, "%dummy", parent_context);
1203 parent_context.new_paragraph(os);
1205 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1206 //output_ert_inset(os, "%dummy", parent_context);
1209 // We add a protected space if something real follows
1210 if (p.good() && p.next_token().cat() != catComment) {
1211 begin_inset(os, "space ~\n");
1217 if (inner_flags != FLAG_BRACE_LAST && (frame_color != "" || background_color != "")) {
1218 // in this case we have to eat the the closing brace of the color box
1219 p.get_token().asInput(); // the '}'
1221 if (p.next_token().asInput() == "}"
1222 && (fboxrule != "" || fboxsep != "" || shadow_size != "")) {
1223 // in this case we assume that the closing brace is from the box settings
1224 // therefore reset these values for the next box
1229 if (shadow_size != "")
1233 // all boxes except of Frameless and Shaded require calc
1234 if (!(outer_type.empty() || outer_type == "mbox") &&
1235 !((outer_type == "shaded" && inner_type.empty()) ||
1236 (outer_type == "minipage" && inner_type == "shaded") ||
1237 (outer_type == "parbox" && inner_type == "shaded")))
1238 preamble.registerAutomaticallyLoadedPackage("calc");
1242 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1243 Context & parent_context, string const & outer_type,
1244 string const & special)
1246 eat_whitespace(p, os, parent_context, false);
1247 if (flags & FLAG_ITEM) {
1249 if (p.next_token().cat() == catBegin)
1252 cerr << "Warning: Ignoring missing '{' after \\"
1253 << outer_type << '.' << endl;
1254 eat_whitespace(p, os, parent_context, false);
1257 unsigned int inner_flags = 0;
1259 if (outer_type == "minipage" || outer_type == "parbox") {
1260 p.skip_spaces(true);
1261 while (p.hasOpt()) {
1263 p.skip_spaces(true);
1266 p.skip_spaces(true);
1267 if (outer_type == "parbox") {
1269 if (p.next_token().cat() == catBegin)
1271 p.skip_spaces(true);
1274 if (outer_type == "shaded" || outer_type == "mbox") {
1275 // These boxes never have an inner box
1277 } else if (p.next_token().asInput() == "\\parbox") {
1278 inner = p.get_token().cs();
1279 inner_flags = FLAG_ITEM;
1280 } else if (p.next_token().asInput() == "\\begin") {
1281 // Is this a minipage or shaded box?
1284 inner = p.getArg('{', '}');
1286 if (inner == "minipage" || inner == "shaded")
1287 inner_flags = FLAG_END;
1292 if (inner_flags == FLAG_END) {
1293 if (inner != "shaded")
1297 eat_whitespace(p, os, parent_context, false);
1299 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1300 outer_type, special, inner, "", "");
1302 if (inner_flags == FLAG_ITEM) {
1304 eat_whitespace(p, os, parent_context, false);
1306 parse_box(p, os, flags, inner_flags, outer, parent_context,
1307 outer_type, special, inner, "", "");
1312 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1314 parent_context.check_layout(os);
1315 begin_inset(os, "listings\n");
1317 string arg = p.verbatimOption();
1318 os << "lstparams " << '"' << arg << '"' << '\n';
1319 if (arg.find("\\color") != string::npos)
1320 preamble.registerAutomaticallyLoadedPackage("color");
1323 os << "inline true\n";
1325 os << "inline false\n";
1326 os << "status collapsed\n";
1327 Context context(true, parent_context.textclass);
1328 context.layout = &parent_context.textclass.plainLayout();
1331 // set catcodes to verbatim early, just in case.
1332 p.setCatcodes(VERBATIM_CATCODES);
1333 string delim = p.get_token().asInput();
1334 //FIXME: handler error condition
1335 s = p.verbatimStuff(delim).second;
1336 // context.new_paragraph(os);
1338 s = p.verbatimEnvironment("lstlisting");
1339 output_ert(os, s, context);
1344 /// parse an unknown environment
1345 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1346 unsigned flags, bool outer,
1347 Context & parent_context)
1349 if (name == "tabbing")
1350 // We need to remember that we have to handle '\=' specially
1351 flags |= FLAG_TABBING;
1353 // We need to translate font changes and paragraphs inside the
1354 // environment to ERT if we have a non standard font.
1355 // Otherwise things like
1356 // \large\begin{foo}\huge bar\end{foo}
1358 bool const specialfont =
1359 (parent_context.font != parent_context.normalfont);
1360 bool const new_layout_allowed = parent_context.new_layout_allowed;
1362 parent_context.new_layout_allowed = false;
1363 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1364 parse_text_snippet(p, os, flags, outer, parent_context);
1365 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1367 parent_context.new_layout_allowed = new_layout_allowed;
1371 void parse_environment(Parser & p, ostream & os, bool outer,
1372 string & last_env, Context & parent_context)
1374 Layout const * newlayout;
1375 InsetLayout const * newinsetlayout = 0;
1376 string const name = p.getArg('{', '}');
1377 const bool is_starred = suffixIs(name, '*');
1378 string const unstarred_name = rtrim(name, "*");
1379 active_environments.push_back(name);
1381 if (is_math_env(name)) {
1382 parent_context.check_layout(os);
1383 begin_inset(os, "Formula ");
1384 os << "\\begin{" << name << "}";
1385 parse_math(p, os, FLAG_END, MATH_MODE);
1386 os << "\\end{" << name << "}";
1388 if (is_display_math_env(name)) {
1389 // Prevent the conversion of a line break to a space
1390 // (bug 7668). This does not change the output, but
1391 // looks ugly in LyX.
1392 eat_whitespace(p, os, parent_context, false);
1396 else if (is_known(name, preamble.polyglossia_languages)) {
1397 // We must begin a new paragraph if not already done
1398 if (! parent_context.atParagraphStart()) {
1399 parent_context.check_end_layout(os);
1400 parent_context.new_paragraph(os);
1402 // save the language in the context so that it is
1403 // handled by parse_text
1404 parent_context.font.language = preamble.polyglossia2lyx(name);
1405 parse_text(p, os, FLAG_END, outer, parent_context);
1406 // Just in case the environment is empty
1407 parent_context.extra_stuff.erase();
1408 // We must begin a new paragraph to reset the language
1409 parent_context.new_paragraph(os);
1413 else if (unstarred_name == "tabular" || name == "longtable") {
1414 eat_whitespace(p, os, parent_context, false);
1415 string width = "0pt";
1416 if (name == "tabular*") {
1417 width = lyx::translate_len(p.getArg('{', '}'));
1418 eat_whitespace(p, os, parent_context, false);
1420 parent_context.check_layout(os);
1421 begin_inset(os, "Tabular ");
1422 handle_tabular(p, os, name, width, parent_context);
1427 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1428 eat_whitespace(p, os, parent_context, false);
1429 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1430 eat_whitespace(p, os, parent_context, false);
1431 parent_context.check_layout(os);
1432 begin_inset(os, "Float " + unstarred_name + "\n");
1433 // store the float type for subfloats
1434 // subfloats only work with figures and tables
1435 if (unstarred_name == "figure")
1436 float_type = unstarred_name;
1437 else if (unstarred_name == "table")
1438 float_type = unstarred_name;
1442 os << "placement " << opt << '\n';
1443 if (contains(opt, "H"))
1444 preamble.registerAutomaticallyLoadedPackage("float");
1446 Floating const & fl = parent_context.textclass.floats()
1447 .getType(unstarred_name);
1448 if (!fl.floattype().empty() && fl.usesFloatPkg())
1449 preamble.registerAutomaticallyLoadedPackage("float");
1452 os << "wide " << convert<string>(is_starred)
1453 << "\nsideways false"
1454 << "\nstatus open\n\n";
1455 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1457 // We don't need really a new paragraph, but
1458 // we must make sure that the next item gets a \begin_layout.
1459 parent_context.new_paragraph(os);
1461 // the float is parsed thus delete the type
1465 else if (unstarred_name == "sidewaysfigure"
1466 || unstarred_name == "sidewaystable") {
1467 eat_whitespace(p, os, parent_context, false);
1468 parent_context.check_layout(os);
1469 if (unstarred_name == "sidewaysfigure")
1470 begin_inset(os, "Float figure\n");
1472 begin_inset(os, "Float table\n");
1473 os << "wide " << convert<string>(is_starred)
1474 << "\nsideways true"
1475 << "\nstatus open\n\n";
1476 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1478 // We don't need really a new paragraph, but
1479 // we must make sure that the next item gets a \begin_layout.
1480 parent_context.new_paragraph(os);
1482 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1485 else if (name == "wrapfigure" || name == "wraptable") {
1486 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1487 eat_whitespace(p, os, parent_context, false);
1488 parent_context.check_layout(os);
1491 string overhang = "0col%";
1494 lines = p.getArg('[', ']');
1495 string const placement = p.getArg('{', '}');
1497 overhang = p.getArg('[', ']');
1498 string const width = p.getArg('{', '}');
1500 if (name == "wrapfigure")
1501 begin_inset(os, "Wrap figure\n");
1503 begin_inset(os, "Wrap table\n");
1504 os << "lines " << lines
1505 << "\nplacement " << placement
1506 << "\noverhang " << lyx::translate_len(overhang)
1507 << "\nwidth " << lyx::translate_len(width)
1508 << "\nstatus open\n\n";
1509 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1511 // We don't need really a new paragraph, but
1512 // we must make sure that the next item gets a \begin_layout.
1513 parent_context.new_paragraph(os);
1515 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1518 else if (name == "minipage") {
1519 eat_whitespace(p, os, parent_context, false);
1520 // Test whether this is an outer box of a shaded box
1522 // swallow arguments
1523 while (p.hasOpt()) {
1525 p.skip_spaces(true);
1528 p.skip_spaces(true);
1529 Token t = p.get_token();
1530 bool shaded = false;
1531 if (t.asInput() == "\\begin") {
1532 p.skip_spaces(true);
1533 if (p.getArg('{', '}') == "shaded")
1538 parse_outer_box(p, os, FLAG_END, outer,
1539 parent_context, name, "shaded");
1541 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1542 "", "", name, "", "");
1546 else if (name == "comment") {
1547 eat_whitespace(p, os, parent_context, false);
1548 parent_context.check_layout(os);
1549 begin_inset(os, "Note Comment\n");
1550 os << "status open\n";
1551 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1554 skip_braces(p); // eat {} that might by set by LyX behind comments
1555 preamble.registerAutomaticallyLoadedPackage("verbatim");
1558 else if (name == "verbatim") {
1559 // FIXME: this should go in the generic code that
1560 // handles environments defined in layout file that
1561 // have "PassThru 1". However, the code over there is
1562 // already too complicated for my taste.
1563 parent_context.new_paragraph(os);
1564 Context context(true, parent_context.textclass,
1565 &parent_context.textclass[from_ascii("Verbatim")]);
1566 string s = p.verbatimEnvironment("verbatim");
1567 output_ert(os, s, context);
1571 else if (name == "IPA") {
1572 eat_whitespace(p, os, parent_context, false);
1573 parent_context.check_layout(os);
1574 begin_inset(os, "IPA\n");
1575 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1578 preamble.registerAutomaticallyLoadedPackage("tipa");
1579 preamble.registerAutomaticallyLoadedPackage("tipx");
1582 else if (name == "CJK") {
1583 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1584 // It is impossible to decide if a CJK environment was in its own paragraph or within
1585 // a line. We therefore always assume a paragraph since the latter is a rare case.
1586 eat_whitespace(p, os, parent_context, false);
1587 parent_context.check_end_layout(os);
1588 // store the encoding to be able to reset it
1589 string const encoding_old = p.getEncoding();
1590 string const encoding = p.getArg('{', '}');
1591 // FIXME: For some reason JIS does not work. Although the text
1592 // in tests/CJK.tex is identical with the SJIS version if you
1593 // convert both snippets using the recode command line utility,
1594 // the resulting .lyx file contains some extra characters if
1595 // you set buggy_encoding to false for JIS.
1596 bool const buggy_encoding = encoding == "JIS";
1597 if (!buggy_encoding)
1598 p.setEncoding(encoding, Encoding::CJK);
1600 // FIXME: This will read garbage, since the data is not encoded in utf8.
1601 p.setEncoding("UTF-8");
1603 // LyX only supports the same mapping for all CJK
1604 // environments, so we might need to output everything as ERT
1605 string const mapping = trim(p.getArg('{', '}'));
1606 char const * const * const where =
1607 is_known(encoding, supported_CJK_encodings);
1608 if (!buggy_encoding && !preamble.fontCJKSet())
1609 preamble.fontCJK(mapping);
1610 bool knownMapping = mapping == preamble.fontCJK();
1611 if (buggy_encoding || !knownMapping || !where) {
1612 parent_context.check_layout(os);
1613 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1615 // we must parse the content as verbatim because e.g. JIS can contain
1616 // normally invalid characters
1617 // FIXME: This works only for the most simple cases.
1618 // Since TeX control characters are not parsed,
1619 // things like comments are completely wrong.
1620 string const s = p.plainEnvironment("CJK");
1621 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1623 output_ert_inset(os, "\\", parent_context);
1624 else if (*it == '$')
1625 output_ert_inset(os, "$", parent_context);
1626 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1631 output_ert_inset(os, "\\end{" + name + "}",
1635 supported_CJK_languages[where - supported_CJK_encodings];
1636 // store the language because we must reset it at the end
1637 string const lang_old = parent_context.font.language;
1638 parent_context.font.language = lang;
1639 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1640 parent_context.font.language = lang_old;
1641 parent_context.new_paragraph(os);
1643 p.setEncoding(encoding_old);
1647 else if (name == "lyxgreyedout") {
1648 eat_whitespace(p, os, parent_context, false);
1649 parent_context.check_layout(os);
1650 begin_inset(os, "Note Greyedout\n");
1651 os << "status open\n";
1652 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1655 if (!preamble.notefontcolor().empty())
1656 preamble.registerAutomaticallyLoadedPackage("color");
1659 else if (name == "btSect") {
1660 eat_whitespace(p, os, parent_context, false);
1661 parent_context.check_layout(os);
1662 begin_command_inset(os, "bibtex", "bibtex");
1663 string bibstyle = "plain";
1665 bibstyle = p.getArg('[', ']');
1666 p.skip_spaces(true);
1668 string const bibfile = p.getArg('{', '}');
1669 eat_whitespace(p, os, parent_context, false);
1670 Token t = p.get_token();
1671 if (t.asInput() == "\\btPrintCited") {
1672 p.skip_spaces(true);
1673 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1675 if (t.asInput() == "\\btPrintNotCited") {
1676 p.skip_spaces(true);
1677 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1679 if (t.asInput() == "\\btPrintAll") {
1680 p.skip_spaces(true);
1681 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1683 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1684 os << "options " << '"' << bibstyle << '"' << "\n";
1685 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1690 else if (name == "framed" || name == "shaded") {
1691 eat_whitespace(p, os, parent_context, false);
1692 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1694 preamble.registerAutomaticallyLoadedPackage("framed");
1697 else if (name == "lstlisting") {
1698 eat_whitespace(p, os, parent_context, false);
1699 parse_listings(p, os, parent_context, false);
1703 else if (!parent_context.new_layout_allowed)
1704 parse_unknown_environment(p, name, os, FLAG_END, outer,
1707 // Alignment and spacing settings
1708 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1709 // therefore are totally broken!
1710 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1711 // they are commands not environments. They are furthermore switches that
1712 // can be ended by another switches, but also by commands like \footnote or
1713 // \parbox. So the only safe way is to leave them untouched.
1714 else if (name == "center" || name == "centering" ||
1715 name == "flushleft" || name == "flushright" ||
1716 name == "singlespace" || name == "onehalfspace" ||
1717 name == "doublespace" || name == "spacing") {
1718 eat_whitespace(p, os, parent_context, false);
1719 // We must begin a new paragraph if not already done
1720 if (! parent_context.atParagraphStart()) {
1721 parent_context.check_end_layout(os);
1722 parent_context.new_paragraph(os);
1724 if (name == "flushleft")
1725 parent_context.add_extra_stuff("\\align left\n");
1726 else if (name == "flushright")
1727 parent_context.add_extra_stuff("\\align right\n");
1728 else if (name == "center" || name == "centering")
1729 parent_context.add_extra_stuff("\\align center\n");
1730 else if (name == "singlespace")
1731 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1732 else if (name == "onehalfspace") {
1733 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1734 preamble.registerAutomaticallyLoadedPackage("setspace");
1735 } else if (name == "doublespace") {
1736 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1737 preamble.registerAutomaticallyLoadedPackage("setspace");
1738 } else if (name == "spacing") {
1739 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1740 preamble.registerAutomaticallyLoadedPackage("setspace");
1742 parse_text(p, os, FLAG_END, outer, parent_context);
1743 // Just in case the environment is empty
1744 parent_context.extra_stuff.erase();
1745 // We must begin a new paragraph to reset the alignment
1746 parent_context.new_paragraph(os);
1750 // The single '=' is meant here.
1751 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1752 eat_whitespace(p, os, parent_context, false);
1753 Context context(true, parent_context.textclass, newlayout,
1754 parent_context.layout, parent_context.font);
1755 if (parent_context.deeper_paragraph) {
1756 // We are beginning a nested environment after a
1757 // deeper paragraph inside the outer list environment.
1758 // Therefore we don't need to output a "begin deeper".
1759 context.need_end_deeper = true;
1761 parent_context.check_end_layout(os);
1762 if (last_env == name) {
1763 // we need to output a separator since LyX would export
1764 // the two environments as one otherwise (bug 5716)
1765 TeX2LyXDocClass const & textclass(parent_context.textclass);
1766 Context newcontext(true, textclass,
1767 &(textclass.defaultLayout()));
1768 newcontext.check_layout(os);
1769 begin_inset(os, "Separator plain\n");
1771 newcontext.check_end_layout(os);
1773 switch (context.layout->latextype) {
1774 case LATEX_LIST_ENVIRONMENT:
1775 context.add_par_extra_stuff("\\labelwidthstring "
1776 + p.verbatim_item() + '\n');
1779 case LATEX_BIB_ENVIRONMENT:
1780 p.verbatim_item(); // swallow next arg
1786 context.check_deeper(os);
1787 // handle known optional and required arguments
1788 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1789 // It is impossible to place anything after the environment name,
1790 // but before the first \\item.
1791 if (context.layout->latextype == LATEX_ENVIRONMENT)
1792 output_arguments(os, p, outer, false, false, context,
1793 context.layout->latexargs());
1794 parse_text(p, os, FLAG_END, outer, context);
1795 if (context.layout->latextype == LATEX_ENVIRONMENT)
1796 output_arguments(os, p, outer, false, true, context,
1797 context.layout->postcommandargs());
1798 context.check_end_layout(os);
1799 if (parent_context.deeper_paragraph) {
1800 // We must suppress the "end deeper" because we
1801 // suppressed the "begin deeper" above.
1802 context.need_end_deeper = false;
1804 context.check_end_deeper(os);
1805 parent_context.new_paragraph(os);
1807 if (!preamble.titleLayoutFound())
1808 preamble.titleLayoutFound(newlayout->intitle);
1809 set<string> const & req = newlayout->requires();
1810 set<string>::const_iterator it = req.begin();
1811 set<string>::const_iterator en = req.end();
1812 for (; it != en; ++it)
1813 preamble.registerAutomaticallyLoadedPackage(*it);
1816 // The single '=' is meant here.
1817 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1818 eat_whitespace(p, os, parent_context, false);
1819 parent_context.check_layout(os);
1820 begin_inset(os, "Flex ");
1821 os << to_utf8(newinsetlayout->name()) << '\n'
1822 << "status collapsed\n";
1823 if (newinsetlayout->isPassThru()) {
1824 string const arg = p.verbatimEnvironment(name);
1825 Context context(true, parent_context.textclass,
1826 &parent_context.textclass.plainLayout(),
1827 parent_context.layout);
1828 output_ert(os, arg, parent_context);
1830 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1834 else if (name == "appendix") {
1835 // This is no good latex style, but it works and is used in some documents...
1836 eat_whitespace(p, os, parent_context, false);
1837 parent_context.check_end_layout(os);
1838 Context context(true, parent_context.textclass, parent_context.layout,
1839 parent_context.layout, parent_context.font);
1840 context.check_layout(os);
1841 os << "\\start_of_appendix\n";
1842 parse_text(p, os, FLAG_END, outer, context);
1843 context.check_end_layout(os);
1847 else if (known_environments.find(name) != known_environments.end()) {
1848 vector<ArgumentType> arguments = known_environments[name];
1849 // The last "argument" denotes wether we may translate the
1850 // environment contents to LyX
1851 // The default required if no argument is given makes us
1852 // compatible with the reLyXre environment.
1853 ArgumentType contents = arguments.empty() ?
1856 if (!arguments.empty())
1857 arguments.pop_back();
1858 // See comment in parse_unknown_environment()
1859 bool const specialfont =
1860 (parent_context.font != parent_context.normalfont);
1861 bool const new_layout_allowed =
1862 parent_context.new_layout_allowed;
1864 parent_context.new_layout_allowed = false;
1865 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1866 outer, parent_context);
1867 if (contents == verbatim)
1868 output_ert_inset(os, p.ertEnvironment(name),
1871 parse_text_snippet(p, os, FLAG_END, outer,
1873 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1875 parent_context.new_layout_allowed = new_layout_allowed;
1879 parse_unknown_environment(p, name, os, FLAG_END, outer,
1883 active_environments.pop_back();
1887 /// parses a comment and outputs it to \p os.
1888 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1890 LASSERT(t.cat() == catComment, return);
1891 if (!t.cs().empty()) {
1892 context.check_layout(os);
1893 output_ert_inset(os, '%' + t.cs(), context);
1894 if (p.next_token().cat() == catNewline) {
1895 // A newline after a comment line starts a new
1897 if (context.new_layout_allowed) {
1898 if(!context.atParagraphStart())
1899 // Only start a new paragraph if not already
1900 // done (we might get called recursively)
1901 context.new_paragraph(os);
1903 output_ert_inset(os, "\n", context);
1904 eat_whitespace(p, os, context, true);
1907 // "%\n" combination
1914 * Reads spaces and comments until the first non-space, non-comment token.
1915 * New paragraphs (double newlines or \\par) are handled like simple spaces
1916 * if \p eatParagraph is true.
1917 * Spaces are skipped, but comments are written to \p os.
1919 void eat_whitespace(Parser & p, ostream & os, Context & context,
1923 Token const & t = p.get_token();
1924 if (t.cat() == catComment)
1925 parse_comment(p, os, t, context);
1926 else if ((! eatParagraph && p.isParagraph()) ||
1927 (t.cat() != catSpace && t.cat() != catNewline)) {
1936 * Set a font attribute, parse text and reset the font attribute.
1937 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1938 * \param currentvalue Current value of the attribute. Is set to the new
1939 * value during parsing.
1940 * \param newvalue New value of the attribute
1942 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1943 Context & context, string const & attribute,
1944 string & currentvalue, string const & newvalue)
1946 context.check_layout(os);
1947 string const oldvalue = currentvalue;
1948 currentvalue = newvalue;
1949 os << '\n' << attribute << ' ' << newvalue << "\n";
1950 parse_text_snippet(p, os, flags, outer, context);
1951 context.check_layout(os);
1952 os << '\n' << attribute << ' ' << oldvalue << "\n";
1953 currentvalue = oldvalue;
1957 /// get the arguments of a natbib or jurabib citation command
1958 void get_cite_arguments(Parser & p, bool natbibOrder,
1959 string & before, string & after)
1961 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1963 // text before the citation
1965 // text after the citation
1966 after = p.getFullOpt();
1968 if (!after.empty()) {
1969 before = p.getFullOpt();
1970 if (natbibOrder && !before.empty())
1971 swap(before, after);
1976 /// Convert filenames with TeX macros and/or quotes to something LyX
1978 string const normalize_filename(string const & name)
1983 Token const & t = p.get_token();
1984 if (t.cat() != catEscape)
1986 else if (t.cs() == "lyxdot") {
1987 // This is used by LyX for simple dots in relative
1991 } else if (t.cs() == "space") {
1994 } else if (t.cs() == "string") {
1995 // Convert \string" to " and \string~ to ~
1996 Token const & n = p.next_token();
1997 if (n.asInput() != "\"" && n.asInput() != "~")
2002 // Strip quotes. This is a bit complicated (see latex_path()).
2003 string full = os.str();
2004 if (!full.empty() && full[0] == '"') {
2005 string base = removeExtension(full);
2006 string ext = getExtension(full);
2007 if (!base.empty() && base[base.length()-1] == '"')
2010 return addExtension(trim(base, "\""), ext);
2011 if (full[full.length()-1] == '"')
2014 return trim(full, "\"");
2020 /// Convert \p name from TeX convention (relative to master file) to LyX
2021 /// convention (relative to .lyx file) if it is relative
2022 void fix_child_filename(string & name)
2024 string const absMasterTeX = getMasterFilePath(true);
2025 bool const isabs = FileName::isAbsolute(name);
2026 // convert from "relative to .tex master" to absolute original path
2028 name = makeAbsPath(name, absMasterTeX).absFileName();
2029 bool copyfile = copyFiles();
2030 string const absParentLyX = getParentFilePath(false);
2033 // convert from absolute original path to "relative to master file"
2034 string const rel = to_utf8(makeRelPath(from_utf8(name),
2035 from_utf8(absMasterTeX)));
2036 // re-interpret "relative to .tex file" as "relative to .lyx file"
2037 // (is different if the master .lyx file resides in a
2038 // different path than the master .tex file)
2039 string const absMasterLyX = getMasterFilePath(false);
2040 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2041 // Do not copy if the new path is impossible to create. Example:
2042 // absMasterTeX = "/foo/bar/"
2043 // absMasterLyX = "/bar/"
2044 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2045 if (contains(name, "/../"))
2052 // convert from absolute original path to
2053 // "relative to .lyx file"
2054 name = to_utf8(makeRelPath(from_utf8(abs),
2055 from_utf8(absParentLyX)));
2059 // convert from absolute original path to "relative to .lyx file"
2060 name = to_utf8(makeRelPath(from_utf8(name),
2061 from_utf8(absParentLyX)));
2066 void copy_file(FileName const & src, string dstname)
2070 string const absParent = getParentFilePath(false);
2072 if (FileName::isAbsolute(dstname))
2073 dst = FileName(dstname);
2075 dst = makeAbsPath(dstname, absParent);
2076 string const absMaster = getMasterFilePath(false);
2077 FileName const srcpath = src.onlyPath();
2078 FileName const dstpath = dst.onlyPath();
2079 if (equivalent(srcpath, dstpath))
2081 if (!dstpath.isDirectory()) {
2082 if (!dstpath.createPath()) {
2083 cerr << "Warning: Could not create directory for file `"
2084 << dst.absFileName() << "´." << endl;
2088 if (dst.isReadableFile()) {
2089 if (overwriteFiles())
2090 cerr << "Warning: Overwriting existing file `"
2091 << dst.absFileName() << "´." << endl;
2093 cerr << "Warning: Not overwriting existing file `"
2094 << dst.absFileName() << "´." << endl;
2098 if (!src.copyTo(dst))
2099 cerr << "Warning: Could not copy file `" << src.absFileName()
2100 << "´ to `" << dst.absFileName() << "´." << endl;
2104 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2105 bool parse_chunk(Parser & p, ostream & os, Context & context)
2107 // check whether a chunk is possible here.
2108 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2114 // read the parameters
2115 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2116 if (!params.first) {
2121 Parser::Arg const code = p.verbatimStuff("\n@");
2126 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2127 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2131 // The last newline read is important for paragraph handling
2135 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2136 // We must have a valid layout before outputting the Chunk inset.
2137 context.check_layout(os);
2138 Context chunkcontext(true, context.textclass);
2139 chunkcontext.layout = &context.textclass.plainLayout();
2140 begin_inset(os, "Flex Chunk");
2141 os << "\nstatus open\n";
2142 if (!params.second.empty()) {
2143 chunkcontext.check_layout(os);
2144 Context paramscontext(true, context.textclass);
2145 paramscontext.layout = &context.textclass.plainLayout();
2146 begin_inset(os, "Argument 1");
2147 os << "\nstatus open\n";
2148 output_ert(os, params.second, paramscontext);
2151 output_ert(os, code.second, chunkcontext);
2159 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2160 bool is_macro(Parser & p)
2162 Token first = p.curr_token();
2163 if (first.cat() != catEscape || !p.good())
2165 if (first.cs() == "def")
2167 if (first.cs() != "global" && first.cs() != "long")
2169 Token second = p.get_token();
2171 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2172 second.cat() == catNewline || second.cat() == catComment)) {
2173 second = p.get_token();
2176 bool secondvalid = second.cat() == catEscape;
2178 bool thirdvalid = false;
2179 if (p.good() && first.cs() == "global" && secondvalid &&
2180 second.cs() == "long") {
2181 third = p.get_token();
2183 while (p.good() && !p.isParagraph() &&
2184 (third.cat() == catSpace ||
2185 third.cat() == catNewline ||
2186 third.cat() == catComment)) {
2187 third = p.get_token();
2190 thirdvalid = third.cat() == catEscape;
2192 for (int i = 0; i < pos; ++i)
2197 return (first.cs() == "global" || first.cs() == "long") &&
2198 second.cs() == "def";
2199 return first.cs() == "global" && second.cs() == "long" &&
2200 third.cs() == "def";
2204 /// Parse a macro definition (assumes that is_macro() returned true)
2205 void parse_macro(Parser & p, ostream & os, Context & context)
2207 context.check_layout(os);
2208 Token first = p.curr_token();
2211 string command = first.asInput();
2212 if (first.cs() != "def") {
2214 eat_whitespace(p, os, context, false);
2215 second = p.curr_token();
2216 command += second.asInput();
2217 if (second.cs() != "def") {
2219 eat_whitespace(p, os, context, false);
2220 third = p.curr_token();
2221 command += third.asInput();
2224 eat_whitespace(p, os, context, false);
2225 string const name = p.get_token().cs();
2226 eat_whitespace(p, os, context, false);
2232 while (p.next_token().cat() != catBegin) {
2233 if (p.next_token().cat() == catParameter) {
2238 // followed by number?
2239 if (p.next_token().cat() == catOther) {
2240 string s = p.get_token().asInput();
2242 // number = current arity + 1?
2243 if (s.size() == 1 && s[0] == arity + '0' + 1)
2248 paramtext += p.get_token().cs();
2250 paramtext += p.get_token().cs();
2255 // only output simple (i.e. compatible) macro as FormulaMacros
2256 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2258 context.check_layout(os);
2259 begin_inset(os, "FormulaMacro");
2260 os << "\n\\def" << ert;
2263 output_ert_inset(os, command + ert, context);
2267 void registerExternalTemplatePackages(string const & name)
2269 external::TemplateManager const & etm = external::TemplateManager::get();
2270 external::Template const * const et = etm.getTemplateByName(name);
2273 external::Template::Formats::const_iterator cit = et->formats.end();
2275 cit = et->formats.find("PDFLaTeX");
2276 if (cit == et->formats.end())
2277 // If the template has not specified a PDFLaTeX output,
2278 // we try the LaTeX format.
2279 cit = et->formats.find("LaTeX");
2280 if (cit == et->formats.end())
2282 vector<string>::const_iterator qit = cit->second.requirements.begin();
2283 vector<string>::const_iterator qend = cit->second.requirements.end();
2284 for (; qit != qend; ++qit)
2285 preamble.registerAutomaticallyLoadedPackage(*qit);
2288 } // anonymous namespace
2291 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2294 Layout const * newlayout = 0;
2295 InsetLayout const * newinsetlayout = 0;
2296 char const * const * where = 0;
2297 // Store the latest bibliographystyle, addcontentslineContent and
2298 // nocite{*} option (needed for bibtex inset)
2300 string contentslineContent;
2301 string bibliographystyle = "default";
2302 bool const use_natbib = isProvided("natbib");
2303 bool const use_jurabib = isProvided("jurabib");
2306 // it is impossible to determine the correct encoding for non-CJK Japanese.
2307 // Therefore write a note at the beginning of the document
2308 if (is_nonCJKJapanese) {
2309 context.check_layout(os);
2310 begin_inset(os, "Note Note\n");
2311 os << "status open\n\\begin_layout Plain Layout\n"
2312 << "\\series bold\n"
2313 << "Important information:\n"
2314 << "\\end_layout\n\n"
2315 << "\\begin_layout Plain Layout\n"
2316 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2317 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2318 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2319 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2320 << " and specify the encoding using the -e command-line switch.\n"
2321 << " In addition, you might want to double check that the desired output encoding\n"
2322 << " is correctly selected in Document > Settings > Language.\n"
2323 << "\\end_layout\n";
2325 is_nonCJKJapanese = false;
2329 Token const & t = p.get_token();
2331 debugToken(cerr, t, flags);
2334 if (flags & FLAG_ITEM) {
2335 if (t.cat() == catSpace)
2338 flags &= ~FLAG_ITEM;
2339 if (t.cat() == catBegin) {
2340 // skip the brace and collect everything to the next matching
2342 flags |= FLAG_BRACE_LAST;
2346 // handle only this single token, leave the loop if done
2347 flags |= FLAG_LEAVE;
2350 if (t.cat() != catEscape && t.character() == ']' &&
2351 (flags & FLAG_BRACK_LAST))
2353 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2356 // If there is anything between \end{env} and \begin{env} we
2357 // don't need to output a separator.
2358 if (t.cat() != catSpace && t.cat() != catNewline &&
2359 t.asInput() != "\\begin")
2365 bool const starred = p.next_token().asInput() == "*";
2366 string const starredname(starred ? (t.cs() + '*') : t.cs());
2367 if (t.cat() == catMath) {
2368 // we are inside some text mode thingy, so opening new math is allowed
2369 context.check_layout(os);
2370 begin_inset(os, "Formula ");
2371 Token const & n = p.get_token();
2372 bool const display(n.cat() == catMath && outer);
2374 // TeX's $$...$$ syntax for displayed math
2376 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2378 p.get_token(); // skip the second '$' token
2380 // simple $...$ stuff
2383 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2388 // Prevent the conversion of a line break to a
2389 // space (bug 7668). This does not change the
2390 // output, but looks ugly in LyX.
2391 eat_whitespace(p, os, context, false);
2395 else if (t.cat() == catSuper || t.cat() == catSub)
2396 cerr << "catcode " << t << " illegal in text mode\n";
2398 // Basic support for english quotes. This should be
2399 // extended to other quotes, but is not so easy (a
2400 // left english quote is the same as a right german
2402 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2403 context.check_layout(os);
2404 begin_inset(os, "Quotes ");
2410 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2411 context.check_layout(os);
2412 begin_inset(os, "Quotes ");
2419 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2420 context.check_layout(os);
2421 begin_inset(os, "Quotes ");
2428 else if (t.asInput() == "<"
2429 && p.next_token().asInput() == "<") {
2430 bool has_chunk = false;
2434 has_chunk = parse_chunk(p, os, context);
2440 context.check_layout(os);
2441 begin_inset(os, "Quotes ");
2442 //FIXME: this is a right danish quote;
2443 // why not a left french quote?
2451 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2452 check_space(p, os, context);
2454 else if (t.character() == '[' && noweb_mode &&
2455 p.next_token().character() == '[') {
2456 // These can contain underscores
2458 string const s = p.getFullOpt() + ']';
2459 if (p.next_token().character() == ']')
2462 cerr << "Warning: Inserting missing ']' in '"
2463 << s << "'." << endl;
2464 output_ert_inset(os, s, context);
2467 else if (t.cat() == catLetter) {
2468 context.check_layout(os);
2472 else if (t.cat() == catOther ||
2473 t.cat() == catAlign ||
2474 t.cat() == catParameter) {
2475 context.check_layout(os);
2476 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2477 context.merging_hyphens_allowed &&
2478 context.font.family != "ttfamily" &&
2479 !context.layout->pass_thru) {
2480 if (p.next_next_token().asInput() == "-") {
2482 os << to_utf8(docstring(1, 0x2014));
2486 os << to_utf8(docstring(1, 0x2013));
2489 // This translates "&" to "\\&" which may be wrong...
2493 else if (p.isParagraph()) {
2494 if (context.new_layout_allowed)
2495 context.new_paragraph(os);
2497 output_ert_inset(os, "\\par ", context);
2498 eat_whitespace(p, os, context, true);
2501 else if (t.cat() == catActive) {
2502 context.check_layout(os);
2503 if (t.character() == '~') {
2504 if (context.layout->free_spacing)
2507 begin_inset(os, "space ~\n");
2514 else if (t.cat() == catBegin) {
2515 Token const next = p.next_token();
2516 Token const end = p.next_next_token();
2517 if (next.cat() == catEnd) {
2519 Token const prev = p.prev_token();
2521 if (p.next_token().character() == '`')
2522 ; // ignore it in {}``
2524 output_ert_inset(os, "{}", context);
2525 } else if (next.cat() == catEscape &&
2526 is_known(next.cs(), known_quotes) &&
2527 end.cat() == catEnd) {
2528 // Something like {\textquoteright} (e.g.
2529 // from writer2latex). LyX writes
2530 // \textquoteright{}, so we may skip the
2531 // braces here for better readability.
2532 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2534 } else if (p.next_token().asInput() == "\\ascii") {
2535 // handle the \ascii characters
2536 // (the case without braces is handled later)
2537 // the code is "{\ascii\xxx}"
2538 p.get_token(); // eat \ascii
2539 string name2 = p.get_token().asInput();
2540 p.get_token(); // eat the final '}'
2541 string const name = "{\\ascii" + name2 + "}";
2545 // get the character from unicodesymbols
2546 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2547 Encodings::TEXT_CMD, termination, rem, &req);
2549 context.check_layout(os);
2552 output_ert_inset(os,
2553 to_utf8(rem), context);
2554 for (set<string>::const_iterator it = req.begin();
2555 it != req.end(); ++it)
2556 preamble.registerAutomaticallyLoadedPackage(*it);
2558 // we did not find a non-ert version
2559 output_ert_inset(os, name, context);
2561 context.check_layout(os);
2562 // special handling of font attribute changes
2563 Token const prev = p.prev_token();
2564 TeXFont const oldFont = context.font;
2565 if (next.character() == '[' ||
2566 next.character() == ']' ||
2567 next.character() == '*') {
2569 if (p.next_token().cat() == catEnd) {
2574 output_ert_inset(os, "{", context);
2575 parse_text_snippet(p, os,
2578 output_ert_inset(os, "}", context);
2580 } else if (! context.new_layout_allowed) {
2581 output_ert_inset(os, "{", context);
2582 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2584 output_ert_inset(os, "}", context);
2585 } else if (is_known(next.cs(), known_sizes)) {
2586 // next will change the size, so we must
2588 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2590 if (!context.atParagraphStart())
2592 << context.font.size << "\n";
2593 } else if (is_known(next.cs(), known_font_families)) {
2594 // next will change the font family, so we
2595 // must reset it here
2596 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2598 if (!context.atParagraphStart())
2600 << context.font.family << "\n";
2601 } else if (is_known(next.cs(), known_font_series)) {
2602 // next will change the font series, so we
2603 // must reset it here
2604 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2606 if (!context.atParagraphStart())
2608 << context.font.series << "\n";
2609 } else if (is_known(next.cs(), known_font_shapes)) {
2610 // next will change the font shape, so we
2611 // must reset it here
2612 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2614 if (!context.atParagraphStart())
2616 << context.font.shape << "\n";
2617 } else if (is_known(next.cs(), known_old_font_families) ||
2618 is_known(next.cs(), known_old_font_series) ||
2619 is_known(next.cs(), known_old_font_shapes)) {
2620 // next will change the font family, series
2621 // and shape, so we must reset it here
2622 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2624 if (!context.atParagraphStart())
2626 << context.font.family
2628 << context.font.series
2630 << context.font.shape << "\n";
2632 output_ert_inset(os, "{", context);
2633 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2635 output_ert_inset(os, "}", context);
2640 else if (t.cat() == catEnd) {
2641 if (flags & FLAG_BRACE_LAST) {
2644 cerr << "stray '}' in text\n";
2645 output_ert_inset(os, "}", context);
2648 else if (t.cat() == catComment)
2649 parse_comment(p, os, t, context);
2652 // control sequences
2655 else if (t.cs() == "(" || t.cs() == "[") {
2656 bool const simple = t.cs() == "(";
2657 context.check_layout(os);
2658 begin_inset(os, "Formula");
2659 os << " \\" << t.cs();
2660 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2661 os << '\\' << (simple ? ')' : ']');
2664 // Prevent the conversion of a line break to a
2665 // space (bug 7668). This does not change the
2666 // output, but looks ugly in LyX.
2667 eat_whitespace(p, os, context, false);
2671 else if (t.cs() == "begin")
2672 parse_environment(p, os, outer, last_env,
2675 else if (t.cs() == "end") {
2676 if (flags & FLAG_END) {
2677 // eat environment name
2678 string const name = p.getArg('{', '}');
2679 if (name != active_environment())
2680 cerr << "\\end{" + name + "} does not match \\begin{"
2681 + active_environment() + "}\n";
2684 p.error("found 'end' unexpectedly");
2687 else if (t.cs() == "item") {
2689 bool const optarg = p.hasOpt();
2691 // FIXME: This swallows comments, but we cannot use
2692 // eat_whitespace() since we must not output
2693 // anything before the item.
2694 p.skip_spaces(true);
2695 s = p.verbatimOption();
2697 p.skip_spaces(false);
2699 context.check_layout(os);
2700 if (context.has_item) {
2701 // An item in an unknown list-like environment
2702 // FIXME: Do this in check_layout()!
2703 context.has_item = false;
2705 output_ert_inset(os, "\\item", context);
2707 output_ert_inset(os, "\\item ", context);
2710 if (context.layout->labeltype != LABEL_MANUAL) {
2711 // handle option of itemize item
2712 begin_inset(os, "Argument item:1\n");
2713 os << "status open\n";
2714 os << "\n\\begin_layout Plain Layout\n";
2716 os << parse_text_snippet(p2,
2717 FLAG_BRACK_LAST, outer, context);
2718 // we must not use context.check_end_layout(os)
2719 // because that would close the outer itemize layout
2720 os << "\n\\end_layout\n";
2722 eat_whitespace(p, os, context, false);
2723 } else if (!s.empty()) {
2724 // LyX adds braces around the argument,
2725 // so we need to remove them here.
2726 if (s.size() > 2 && s[0] == '{' &&
2727 s[s.size()-1] == '}')
2728 s = s.substr(1, s.size()-2);
2729 // If the argument contains a space we
2730 // must put it into ERT: Otherwise LyX
2731 // would misinterpret the space as
2732 // item delimiter (bug 7663)
2733 if (contains(s, ' ')) {
2734 output_ert_inset(os, s, context);
2737 os << parse_text_snippet(p2,
2738 FLAG_BRACK_LAST, outer, context);
2740 // The space is needed to separate the
2741 // item from the rest of the sentence.
2743 eat_whitespace(p, os, context, false);
2748 else if (t.cs() == "bibitem") {
2750 context.check_layout(os);
2751 eat_whitespace(p, os, context, false);
2752 string label = convert_command_inset_arg(p.verbatimOption());
2753 string key = convert_command_inset_arg(p.verbatim_item());
2754 if (contains(label, '\\') || contains(key, '\\')) {
2755 // LyX can't handle LaTeX commands in labels or keys
2756 output_ert_inset(os, t.asInput() + '[' + label +
2757 "]{" + p.verbatim_item() + '}',
2760 begin_command_inset(os, "bibitem", "bibitem");
2761 os << "label \"" << label << "\"\n"
2762 "key \"" << key << "\"\n";
2767 else if (is_macro(p)) {
2768 // catch the case of \def\inputGnumericTable
2770 if (t.cs() == "def") {
2771 Token second = p.next_token();
2772 if (second.cs() == "inputGnumericTable") {
2776 Token third = p.get_token();
2778 if (third.cs() == "input") {
2782 string name = normalize_filename(p.verbatim_item());
2783 string const path = getMasterFilePath(true);
2784 // We want to preserve relative / absolute filenames,
2785 // therefore path is only used for testing
2786 // The file extension is in every case ".tex".
2787 // So we need to remove this extension and check for
2788 // the original one.
2789 name = removeExtension(name);
2790 if (!makeAbsPath(name, path).exists()) {
2791 char const * const Gnumeric_formats[] = {"gnumeric",
2793 string const Gnumeric_name =
2794 find_file(name, path, Gnumeric_formats);
2795 if (!Gnumeric_name.empty())
2796 name = Gnumeric_name;
2798 FileName const absname = makeAbsPath(name, path);
2799 if (absname.exists()) {
2800 fix_child_filename(name);
2801 copy_file(absname, name);
2803 cerr << "Warning: Could not find file '"
2804 << name << "'." << endl;
2805 context.check_layout(os);
2806 begin_inset(os, "External\n\ttemplate ");
2807 os << "GnumericSpreadsheet\n\tfilename "
2810 context.check_layout(os);
2812 // register the packages that are automatically loaded
2813 // by the Gnumeric template
2814 registerExternalTemplatePackages("GnumericSpreadsheet");
2819 parse_macro(p, os, context);
2822 else if (t.cs() == "noindent") {
2824 context.add_par_extra_stuff("\\noindent\n");
2827 else if (t.cs() == "appendix") {
2828 context.add_par_extra_stuff("\\start_of_appendix\n");
2829 // We need to start a new paragraph. Otherwise the
2830 // appendix in 'bla\appendix\chapter{' would start
2832 context.new_paragraph(os);
2833 // We need to make sure that the paragraph is
2834 // generated even if it is empty. Otherwise the
2835 // appendix in '\par\appendix\par\chapter{' would
2837 context.check_layout(os);
2838 // FIXME: This is a hack to prevent paragraph
2839 // deletion if it is empty. Handle this better!
2840 output_ert_inset(os,
2841 "%dummy comment inserted by tex2lyx to "
2842 "ensure that this paragraph is not empty",
2844 // Both measures above may generate an additional
2845 // empty paragraph, but that does not hurt, because
2846 // whitespace does not matter here.
2847 eat_whitespace(p, os, context, true);
2850 // Must catch empty dates before findLayout is called below
2851 else if (t.cs() == "date") {
2852 eat_whitespace(p, os, context, false);
2854 string const date = p.verbatim_item();
2857 preamble.suppressDate(true);
2860 preamble.suppressDate(false);
2861 if (context.new_layout_allowed &&
2862 (newlayout = findLayout(context.textclass,
2865 output_command_layout(os, p, outer,
2866 context, newlayout);
2867 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2868 if (!preamble.titleLayoutFound())
2869 preamble.titleLayoutFound(newlayout->intitle);
2870 set<string> const & req = newlayout->requires();
2871 set<string>::const_iterator it = req.begin();
2872 set<string>::const_iterator en = req.end();
2873 for (; it != en; ++it)
2874 preamble.registerAutomaticallyLoadedPackage(*it);
2876 output_ert_inset(os,
2877 "\\date{" + p.verbatim_item() + '}',
2882 // Starred section headings
2883 // Must attempt to parse "Section*" before "Section".
2884 else if ((p.next_token().asInput() == "*") &&
2885 context.new_layout_allowed &&
2886 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2889 output_command_layout(os, p, outer, context, newlayout);
2891 if (!preamble.titleLayoutFound())
2892 preamble.titleLayoutFound(newlayout->intitle);
2893 set<string> const & req = newlayout->requires();
2894 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2895 preamble.registerAutomaticallyLoadedPackage(*it);
2898 // Section headings and the like
2899 else if (context.new_layout_allowed &&
2900 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2902 output_command_layout(os, p, outer, context, newlayout);
2904 if (!preamble.titleLayoutFound())
2905 preamble.titleLayoutFound(newlayout->intitle);
2906 set<string> const & req = newlayout->requires();
2907 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2908 preamble.registerAutomaticallyLoadedPackage(*it);
2911 else if (t.cs() == "subfloat") {
2912 // the syntax is \subfloat[list entry][sub caption]{content}
2913 // if it is a table of figure depends on the surrounding float
2914 // FIXME: second optional argument is not parsed
2915 bool has_caption = false;
2917 // do nothing if there is no outer float
2918 if (!float_type.empty()) {
2919 context.check_layout(os);
2921 begin_inset(os, "Float " + float_type + "\n");
2923 << "\nsideways false"
2924 << "\nstatus collapsed\n\n";
2927 if (p.next_token().cat() != catEscape &&
2928 p.next_token().character() == '[') {
2929 p.get_token(); // eat '['
2930 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2934 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2935 // the caption comes always as the last
2937 // we must make sure that the caption gets a \begin_layout
2938 os << "\n\\begin_layout Plain Layout";
2940 begin_inset(os, "Caption Standard\n");
2941 Context newcontext(true, context.textclass,
2942 0, 0, context.font);
2943 newcontext.check_layout(os);
2944 os << caption << "\n";
2945 newcontext.check_end_layout(os);
2946 // We don't need really a new paragraph, but
2947 // we must make sure that the next item gets a \begin_layout.
2948 //newcontext.new_paragraph(os);
2952 // We don't need really a new paragraph, but
2953 // we must make sure that the next item gets a \begin_layout.
2955 context.new_paragraph(os);
2958 context.check_end_layout(os);
2959 // close the layout we opened
2961 os << "\n\\end_layout\n";
2963 // if the float type is not supported or there is no surrounding float
2966 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2967 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2968 "]{" + p.verbatim_item() + '}', context);
2970 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2974 else if (t.cs() == "includegraphics") {
2975 bool const clip = p.next_token().asInput() == "*";
2978 string const arg = p.getArg('[', ']');
2979 map<string, string> opts;
2980 vector<string> keys;
2981 split_map(arg, opts, keys);
2983 opts["clip"] = string();
2984 string name = normalize_filename(p.verbatim_item());
2986 string const path = getMasterFilePath(true);
2987 // We want to preserve relative / absolute filenames,
2988 // therefore path is only used for testing
2989 if (!makeAbsPath(name, path).exists()) {
2990 // The file extension is probably missing.
2991 // Now try to find it out.
2992 string const dvips_name =
2993 find_file(name, path,
2994 known_dvips_graphics_formats);
2995 string const pdftex_name =
2996 find_file(name, path,
2997 known_pdftex_graphics_formats);
2998 if (!dvips_name.empty()) {
2999 if (!pdftex_name.empty()) {
3000 cerr << "This file contains the "
3002 "\"\\includegraphics{"
3004 "However, files\n\""
3005 << dvips_name << "\" and\n\""
3006 << pdftex_name << "\"\n"
3007 "both exist, so I had to make a "
3008 "choice and took the first one.\n"
3009 "Please move the unwanted one "
3010 "someplace else and try again\n"
3011 "if my choice was wrong."
3015 } else if (!pdftex_name.empty()) {
3021 FileName const absname = makeAbsPath(name, path);
3022 if (absname.exists()) {
3023 fix_child_filename(name);
3024 copy_file(absname, name);
3026 cerr << "Warning: Could not find graphics file '"
3027 << name << "'." << endl;
3029 context.check_layout(os);
3030 begin_inset(os, "Graphics ");
3031 os << "\n\tfilename " << name << '\n';
3032 if (opts.find("width") != opts.end())
3034 << translate_len(opts["width"]) << '\n';
3035 if (opts.find("height") != opts.end())
3037 << translate_len(opts["height"]) << '\n';
3038 if (opts.find("scale") != opts.end()) {
3039 istringstream iss(opts["scale"]);
3043 os << "\tscale " << val << '\n';
3045 if (opts.find("angle") != opts.end()) {
3046 os << "\trotateAngle "
3047 << opts["angle"] << '\n';
3048 vector<string>::const_iterator a =
3049 find(keys.begin(), keys.end(), "angle");
3050 vector<string>::const_iterator s =
3051 find(keys.begin(), keys.end(), "width");
3052 if (s == keys.end())
3053 s = find(keys.begin(), keys.end(), "height");
3054 if (s == keys.end())
3055 s = find(keys.begin(), keys.end(), "scale");
3056 if (s != keys.end() && distance(s, a) > 0)
3057 os << "\tscaleBeforeRotation\n";
3059 if (opts.find("origin") != opts.end()) {
3061 string const opt = opts["origin"];
3062 if (opt.find('l') != string::npos) ss << "left";
3063 if (opt.find('r') != string::npos) ss << "right";
3064 if (opt.find('c') != string::npos) ss << "center";
3065 if (opt.find('t') != string::npos) ss << "Top";
3066 if (opt.find('b') != string::npos) ss << "Bottom";
3067 if (opt.find('B') != string::npos) ss << "Baseline";
3068 if (!ss.str().empty())
3069 os << "\trotateOrigin " << ss.str() << '\n';
3071 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3073 if (opts.find("keepaspectratio") != opts.end())
3074 os << "\tkeepAspectRatio\n";
3075 if (opts.find("clip") != opts.end())
3077 if (opts.find("draft") != opts.end())
3079 if (opts.find("bb") != opts.end())
3080 os << "\tBoundingBox "
3081 << opts["bb"] << '\n';
3082 int numberOfbbOptions = 0;
3083 if (opts.find("bbllx") != opts.end())
3084 numberOfbbOptions++;
3085 if (opts.find("bblly") != opts.end())
3086 numberOfbbOptions++;
3087 if (opts.find("bburx") != opts.end())
3088 numberOfbbOptions++;
3089 if (opts.find("bbury") != opts.end())
3090 numberOfbbOptions++;
3091 if (numberOfbbOptions == 4)
3092 os << "\tBoundingBox "
3093 << opts["bbllx"] << " " << opts["bblly"] << " "
3094 << opts["bburx"] << " " << opts["bbury"] << '\n';
3095 else if (numberOfbbOptions > 0)
3096 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3097 numberOfbbOptions = 0;
3098 if (opts.find("natwidth") != opts.end())
3099 numberOfbbOptions++;
3100 if (opts.find("natheight") != opts.end())
3101 numberOfbbOptions++;
3102 if (numberOfbbOptions == 2)
3103 os << "\tBoundingBox 0bp 0bp "
3104 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3105 else if (numberOfbbOptions > 0)
3106 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3107 ostringstream special;
3108 if (opts.find("hiresbb") != opts.end())
3109 special << "hiresbb,";
3110 if (opts.find("trim") != opts.end())
3112 if (opts.find("viewport") != opts.end())
3113 special << "viewport=" << opts["viewport"] << ',';
3114 if (opts.find("totalheight") != opts.end())
3115 special << "totalheight=" << opts["totalheight"] << ',';
3116 if (opts.find("type") != opts.end())
3117 special << "type=" << opts["type"] << ',';
3118 if (opts.find("ext") != opts.end())
3119 special << "ext=" << opts["ext"] << ',';
3120 if (opts.find("read") != opts.end())
3121 special << "read=" << opts["read"] << ',';
3122 if (opts.find("command") != opts.end())
3123 special << "command=" << opts["command"] << ',';
3124 string s_special = special.str();
3125 if (!s_special.empty()) {
3126 // We had special arguments. Remove the trailing ','.
3127 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3129 // TODO: Handle the unknown settings better.
3130 // Warn about invalid options.
3131 // Check whether some option was given twice.
3133 preamble.registerAutomaticallyLoadedPackage("graphicx");
3136 else if (t.cs() == "footnote" ||
3137 (t.cs() == "thanks" && context.layout->intitle)) {
3139 context.check_layout(os);
3140 begin_inset(os, "Foot\n");
3141 os << "status collapsed\n\n";
3142 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3146 else if (t.cs() == "marginpar") {
3148 context.check_layout(os);
3149 begin_inset(os, "Marginal\n");
3150 os << "status collapsed\n\n";
3151 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3155 else if (t.cs() == "lstinline") {
3157 parse_listings(p, os, context, true);
3160 else if (t.cs() == "ensuremath") {
3162 context.check_layout(os);
3163 string const s = p.verbatim_item();
3164 //FIXME: this never triggers in UTF8
3165 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3168 output_ert_inset(os, "\\ensuremath{" + s + "}",
3172 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3173 if (preamble.titleLayoutFound()) {
3175 skip_spaces_braces(p);
3177 output_ert_inset(os, t.asInput(), context);
3180 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3181 context.check_layout(os);
3182 begin_command_inset(os, "toc", t.cs());
3184 skip_spaces_braces(p);
3185 if (t.cs() == "lstlistoflistings")
3186 preamble.registerAutomaticallyLoadedPackage("listings");
3189 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3190 context.check_layout(os);
3191 if (t.cs() == "listoffigures")
3192 begin_inset(os, "FloatList figure\n");
3194 begin_inset(os, "FloatList table\n");
3196 skip_spaces_braces(p);
3199 else if (t.cs() == "listof") {
3200 p.skip_spaces(true);
3201 string const name = p.get_token().cs();
3202 if (context.textclass.floats().typeExist(name)) {
3203 context.check_layout(os);
3204 begin_inset(os, "FloatList ");
3207 p.get_token(); // swallow second arg
3209 output_ert_inset(os, "\\listof{" + name + "}", context);
3212 else if ((where = is_known(t.cs(), known_text_font_families)))
3213 parse_text_attributes(p, os, FLAG_ITEM, outer,
3214 context, "\\family", context.font.family,
3215 known_coded_font_families[where - known_text_font_families]);
3217 else if ((where = is_known(t.cs(), known_text_font_series)))
3218 parse_text_attributes(p, os, FLAG_ITEM, outer,
3219 context, "\\series", context.font.series,
3220 known_coded_font_series[where - known_text_font_series]);
3222 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3223 parse_text_attributes(p, os, FLAG_ITEM, outer,
3224 context, "\\shape", context.font.shape,
3225 known_coded_font_shapes[where - known_text_font_shapes]);
3227 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3228 context.check_layout(os);
3229 TeXFont oldFont = context.font;
3230 context.font.init();
3231 context.font.size = oldFont.size;
3232 os << "\n\\family " << context.font.family << "\n";
3233 os << "\n\\series " << context.font.series << "\n";
3234 os << "\n\\shape " << context.font.shape << "\n";
3235 if (t.cs() == "textnormal") {
3236 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3237 output_font_change(os, context.font, oldFont);
3238 context.font = oldFont;
3240 eat_whitespace(p, os, context, false);
3243 else if (t.cs() == "textcolor") {
3244 // scheme is \textcolor{color name}{text}
3245 string const color = p.verbatim_item();
3246 // we support the predefined colors of the color and the xcolor package
3247 if (color == "black" || color == "blue" || color == "cyan"
3248 || color == "green" || color == "magenta" || color == "red"
3249 || color == "white" || color == "yellow") {
3250 context.check_layout(os);
3251 os << "\n\\color " << color << "\n";
3252 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3253 context.check_layout(os);
3254 os << "\n\\color inherit\n";
3255 preamble.registerAutomaticallyLoadedPackage("color");
3256 } else if (color == "brown" || color == "darkgray" || color == "gray"
3257 || color == "lightgray" || color == "lime" || color == "olive"
3258 || color == "orange" || color == "pink" || color == "purple"
3259 || color == "teal" || color == "violet") {
3260 context.check_layout(os);
3261 os << "\n\\color " << color << "\n";
3262 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3263 context.check_layout(os);
3264 os << "\n\\color inherit\n";
3265 preamble.registerAutomaticallyLoadedPackage("xcolor");
3267 // for custom defined colors
3268 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3271 else if (t.cs() == "underbar" || t.cs() == "uline") {
3272 // \underbar is not 100% correct (LyX outputs \uline
3273 // of ulem.sty). The difference is that \ulem allows
3274 // line breaks, and \underbar does not.
3275 // Do NOT handle \underline.
3276 // \underbar cuts through y, g, q, p etc.,
3277 // \underline does not.
3278 context.check_layout(os);
3279 os << "\n\\bar under\n";
3280 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3281 context.check_layout(os);
3282 os << "\n\\bar default\n";
3283 preamble.registerAutomaticallyLoadedPackage("ulem");
3286 else if (t.cs() == "sout") {
3287 context.check_layout(os);
3288 os << "\n\\strikeout on\n";
3289 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3290 context.check_layout(os);
3291 os << "\n\\strikeout default\n";
3292 preamble.registerAutomaticallyLoadedPackage("ulem");
3295 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3296 t.cs() == "emph" || t.cs() == "noun") {
3297 context.check_layout(os);
3298 os << "\n\\" << t.cs() << " on\n";
3299 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3300 context.check_layout(os);
3301 os << "\n\\" << t.cs() << " default\n";
3302 if (t.cs() == "uuline" || t.cs() == "uwave")
3303 preamble.registerAutomaticallyLoadedPackage("ulem");
3306 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3307 context.check_layout(os);
3308 string name = p.getArg('{', '}');
3309 string localtime = p.getArg('{', '}');
3310 preamble.registerAuthor(name);
3311 Author const & author = preamble.getAuthor(name);
3312 // from_asctime_utc() will fail if LyX decides to output the
3313 // time in the text language.
3314 time_t ptime = from_asctime_utc(localtime);
3315 if (ptime == static_cast<time_t>(-1)) {
3316 cerr << "Warning: Could not parse time `" << localtime
3317 << "´ for change tracking, using current time instead.\n";
3318 ptime = current_time();
3320 if (t.cs() == "lyxadded")
3321 os << "\n\\change_inserted ";
3323 os << "\n\\change_deleted ";
3324 os << author.bufferId() << ' ' << ptime << '\n';
3325 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3326 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3327 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3328 LaTeXPackages::isAvailable("xcolor");
3329 // No need to test for luatex, since luatex comes in
3330 // two flavours (dvi and pdf), like latex, and those
3331 // are detected by pdflatex.
3332 if (pdflatex || xetex) {
3334 preamble.registerAutomaticallyLoadedPackage("ulem");
3335 preamble.registerAutomaticallyLoadedPackage("xcolor");
3336 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3340 preamble.registerAutomaticallyLoadedPackage("dvipost");
3341 } else if (xcolorulem) {
3342 preamble.registerAutomaticallyLoadedPackage("ulem");
3343 preamble.registerAutomaticallyLoadedPackage("xcolor");
3348 else if (t.cs() == "textipa") {
3349 context.check_layout(os);
3350 begin_inset(os, "IPA\n");
3351 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3352 context.merging_hyphens_allowed = false;
3353 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3354 context.merging_hyphens_allowed = merging_hyphens_allowed;
3356 preamble.registerAutomaticallyLoadedPackage("tipa");
3357 preamble.registerAutomaticallyLoadedPackage("tipx");
3360 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3361 context.check_layout(os);
3362 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3363 os << "status open\n";
3364 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3369 else if (t.cs() == "textvertline") {
3370 // FIXME: This is not correct, \textvertline is higher than |
3376 else if (t.cs() == "tone" ) {
3377 context.check_layout(os);
3378 // register the tone package
3379 preamble.registerAutomaticallyLoadedPackage("tone");
3380 string content = trimSpaceAndEol(p.verbatim_item());
3381 string command = t.asInput() + "{" + content + "}";
3382 // some tones can be detected by unicodesymbols, some need special code
3383 if (is_known(content, known_tones)) {
3384 os << "\\IPAChar " << command << "\n";
3387 // try to see whether the string is in unicodesymbols
3391 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3392 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3393 termination, rem, &req);
3397 output_ert_inset(os, to_utf8(rem), context);
3398 for (set<string>::const_iterator it = req.begin();
3399 it != req.end(); ++it)
3400 preamble.registerAutomaticallyLoadedPackage(*it);
3402 // we did not find a non-ert version
3403 output_ert_inset(os, command, context);
3406 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3407 t.cs() == "vphantom") {
3408 context.check_layout(os);
3409 if (t.cs() == "phantom")
3410 begin_inset(os, "Phantom Phantom\n");
3411 if (t.cs() == "hphantom")
3412 begin_inset(os, "Phantom HPhantom\n");
3413 if (t.cs() == "vphantom")
3414 begin_inset(os, "Phantom VPhantom\n");
3415 os << "status open\n";
3416 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3421 else if (t.cs() == "href") {
3422 context.check_layout(os);
3423 string target = convert_command_inset_arg(p.verbatim_item());
3424 string name = convert_command_inset_arg(p.verbatim_item());
3426 size_t i = target.find(':');
3427 if (i != string::npos) {
3428 type = target.substr(0, i + 1);
3429 if (type == "mailto:" || type == "file:")
3430 target = target.substr(i + 1);
3431 // handle the case that name is equal to target, except of "http://"
3432 else if (target.substr(i + 3) == name && type == "http:")
3435 begin_command_inset(os, "href", "href");
3437 os << "name \"" << name << "\"\n";
3438 os << "target \"" << target << "\"\n";
3439 if (type == "mailto:" || type == "file:")
3440 os << "type \"" << type << "\"\n";
3442 skip_spaces_braces(p);
3445 else if (t.cs() == "lyxline") {
3446 // swallow size argument (it is not used anyway)
3448 if (!context.atParagraphStart()) {
3449 // so our line is in the middle of a paragraph
3450 // we need to add a new line, lest this line
3451 // follow the other content on that line and
3452 // run off the side of the page
3453 // FIXME: This may create an empty paragraph,
3454 // but without that it would not be
3455 // possible to set noindent below.
3456 // Fortunately LaTeX does not care
3457 // about the empty paragraph.
3458 context.new_paragraph(os);
3460 if (preamble.indentParagraphs()) {
3461 // we need to unindent, lest the line be too long
3462 context.add_par_extra_stuff("\\noindent\n");
3464 context.check_layout(os);
3465 begin_command_inset(os, "line", "rule");
3466 os << "offset \"0.5ex\"\n"
3467 "width \"100line%\"\n"
3472 else if (t.cs() == "rule") {
3473 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3474 string const width = p.getArg('{', '}');
3475 string const thickness = p.getArg('{', '}');
3476 context.check_layout(os);
3477 begin_command_inset(os, "line", "rule");
3478 if (!offset.empty())
3479 os << "offset \"" << translate_len(offset) << "\"\n";
3480 os << "width \"" << translate_len(width) << "\"\n"
3481 "height \"" << translate_len(thickness) << "\"\n";
3485 // handle refstyle first to catch \eqref which can also occur
3486 // without refstyle. Only recognize these commands if
3487 // refstyle.sty was found in the preamble (otherwise \eqref
3488 // and user defined ref commands could be misdetected).
3489 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3490 preamble.refstyle()) {
3491 context.check_layout(os);
3492 begin_command_inset(os, "ref", "formatted");
3493 os << "reference \"";
3494 os << known_refstyle_prefixes[where - known_refstyle_commands]
3496 os << convert_command_inset_arg(p.verbatim_item())
3499 preamble.registerAutomaticallyLoadedPackage("refstyle");
3502 // if refstyle is used, we must not convert \prettyref to a
3503 // formatted reference, since that would result in a refstyle command.
3504 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3505 (t.cs() != "prettyref" || !preamble.refstyle())) {
3506 string const opt = p.getOpt();
3508 context.check_layout(os);
3509 begin_command_inset(os, "ref",
3510 known_coded_ref_commands[where - known_ref_commands]);
3511 os << "reference \""
3512 << convert_command_inset_arg(p.verbatim_item())
3515 if (t.cs() == "vref" || t.cs() == "vpageref")
3516 preamble.registerAutomaticallyLoadedPackage("varioref");
3517 else if (t.cs() == "prettyref")
3518 preamble.registerAutomaticallyLoadedPackage("prettyref");
3520 // LyX does not yet support optional arguments of ref commands
3521 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3522 p.verbatim_item() + '}', context);
3526 else if (use_natbib &&
3527 is_known(t.cs(), known_natbib_commands) &&
3528 ((t.cs() != "citefullauthor" &&
3529 t.cs() != "citeyear" &&
3530 t.cs() != "citeyearpar") ||
3531 p.next_token().asInput() != "*")) {
3532 context.check_layout(os);
3533 string command = t.cs();
3534 if (p.next_token().asInput() == "*") {
3538 if (command == "citefullauthor")
3539 // alternative name for "\\citeauthor*"
3540 command = "citeauthor*";
3542 // text before the citation
3544 // text after the citation
3546 get_cite_arguments(p, true, before, after);
3548 if (command == "cite") {
3549 // \cite without optional argument means
3550 // \citet, \cite with at least one optional
3551 // argument means \citep.
3552 if (before.empty() && after.empty())
3557 if (before.empty() && after == "[]")
3558 // avoid \citet[]{a}
3560 else if (before == "[]" && after == "[]") {
3561 // avoid \citet[][]{a}
3565 // remove the brackets around after and before
3566 if (!after.empty()) {
3568 after.erase(after.length() - 1, 1);
3569 after = convert_command_inset_arg(after);
3571 if (!before.empty()) {
3573 before.erase(before.length() - 1, 1);
3574 before = convert_command_inset_arg(before);
3576 begin_command_inset(os, "citation", command);
3577 os << "after " << '"' << after << '"' << "\n";
3578 os << "before " << '"' << before << '"' << "\n";
3580 << convert_command_inset_arg(p.verbatim_item())
3583 // Need to set the cite engine if natbib is loaded by
3584 // the document class directly
3585 if (preamble.citeEngine() == "basic")
3586 preamble.citeEngine("natbib");
3589 else if (use_jurabib &&
3590 is_known(t.cs(), known_jurabib_commands) &&
3591 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3592 context.check_layout(os);
3593 string command = t.cs();
3594 if (p.next_token().asInput() == "*") {
3598 char argumentOrder = '\0';
3599 vector<string> const options =
3600 preamble.getPackageOptions("jurabib");
3601 if (find(options.begin(), options.end(),
3602 "natbiborder") != options.end())
3603 argumentOrder = 'n';
3604 else if (find(options.begin(), options.end(),
3605 "jurabiborder") != options.end())
3606 argumentOrder = 'j';
3608 // text before the citation
3610 // text after the citation
3612 get_cite_arguments(p, argumentOrder != 'j', before, after);
3614 string const citation = p.verbatim_item();
3615 if (!before.empty() && argumentOrder == '\0') {
3616 cerr << "Warning: Assuming argument order "
3617 "of jurabib version 0.6 for\n'"
3618 << command << before << after << '{'
3619 << citation << "}'.\n"
3620 "Add 'jurabiborder' to the jurabib "
3621 "package options if you used an\n"
3622 "earlier jurabib version." << endl;
3624 if (!after.empty()) {
3626 after.erase(after.length() - 1, 1);
3628 if (!before.empty()) {
3630 before.erase(before.length() - 1, 1);
3632 begin_command_inset(os, "citation", command);
3633 os << "after " << '"' << after << '"' << "\n";
3634 os << "before " << '"' << before << '"' << "\n";
3635 os << "key " << '"' << citation << '"' << "\n";
3637 // Need to set the cite engine if jurabib is loaded by
3638 // the document class directly
3639 if (preamble.citeEngine() == "basic")
3640 preamble.citeEngine("jurabib");
3643 else if (t.cs() == "cite"
3644 || t.cs() == "nocite") {
3645 context.check_layout(os);
3646 string after = convert_command_inset_arg(p.getArg('[', ']'));
3647 string key = convert_command_inset_arg(p.verbatim_item());
3648 // store the case that it is "\nocite{*}" to use it later for
3651 begin_command_inset(os, "citation", t.cs());
3652 os << "after " << '"' << after << '"' << "\n";
3653 os << "key " << '"' << key << '"' << "\n";
3655 } else if (t.cs() == "nocite")
3659 else if (t.cs() == "index" ||
3660 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3661 context.check_layout(os);
3662 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3663 p.getArg('[', ']') : "";
3664 string const kind = arg.empty() ? "idx" : arg;
3665 begin_inset(os, "Index ");
3666 os << kind << "\nstatus collapsed\n";
3667 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3670 preamble.registerAutomaticallyLoadedPackage("splitidx");
3673 else if (t.cs() == "nomenclature") {
3674 context.check_layout(os);
3675 begin_command_inset(os, "nomenclature", "nomenclature");
3676 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3677 if (!prefix.empty())
3678 os << "prefix " << '"' << prefix << '"' << "\n";
3679 os << "symbol " << '"'
3680 << convert_command_inset_arg(p.verbatim_item());
3681 os << "\"\ndescription \""
3682 << convert_command_inset_arg(p.verbatim_item())
3685 preamble.registerAutomaticallyLoadedPackage("nomencl");
3688 else if (t.cs() == "label") {
3689 context.check_layout(os);
3690 begin_command_inset(os, "label", "label");
3692 << convert_command_inset_arg(p.verbatim_item())
3697 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3698 context.check_layout(os);
3699 string commandname = t.cs();
3701 if (p.next_token().asInput() == "*") {
3706 begin_command_inset(os, "index_print", commandname);
3707 string const indexname = p.getArg('[', ']');
3709 if (indexname.empty())
3710 os << "type \"idx\"\n";
3712 os << "type \"" << indexname << "\"\n";
3715 skip_spaces_braces(p);
3716 preamble.registerAutomaticallyLoadedPackage("makeidx");
3717 if (preamble.use_indices() == "true")
3718 preamble.registerAutomaticallyLoadedPackage("splitidx");
3721 else if (t.cs() == "printnomenclature") {
3723 string width_type = "";
3724 context.check_layout(os);
3725 begin_command_inset(os, "nomencl_print", "printnomenclature");
3726 // case of a custom width
3728 width = p.getArg('[', ']');
3729 width = translate_len(width);
3730 width_type = "custom";
3732 // case of no custom width
3733 // the case of no custom width but the width set
3734 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3735 // because the user could have set anything, not only the width
3736 // of the longest label (which would be width_type = "auto")
3737 string label = convert_command_inset_arg(p.getArg('{', '}'));
3738 if (label.empty() && width_type.empty())
3739 width_type = "none";
3740 os << "set_width \"" << width_type << "\"\n";
3741 if (width_type == "custom")
3742 os << "width \"" << width << '\"';
3744 skip_spaces_braces(p);
3745 preamble.registerAutomaticallyLoadedPackage("nomencl");
3748 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3749 context.check_layout(os);
3750 begin_inset(os, "script ");
3751 os << t.cs().substr(4) << '\n';
3752 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3753 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3755 if (t.cs() == "textsubscript")
3756 preamble.registerAutomaticallyLoadedPackage("subscript");
3759 else if ((where = is_known(t.cs(), known_quotes))) {
3760 context.check_layout(os);
3761 begin_inset(os, "Quotes ");
3762 os << known_coded_quotes[where - known_quotes];
3764 // LyX adds {} after the quote, so we have to eat
3765 // spaces here if there are any before a possible
3767 eat_whitespace(p, os, context, false);
3771 else if ((where = is_known(t.cs(), known_sizes)) &&
3772 context.new_layout_allowed) {
3773 context.check_layout(os);
3774 TeXFont const oldFont = context.font;
3775 context.font.size = known_coded_sizes[where - known_sizes];
3776 output_font_change(os, oldFont, context.font);
3777 eat_whitespace(p, os, context, false);
3780 else if ((where = is_known(t.cs(), known_font_families)) &&
3781 context.new_layout_allowed) {
3782 context.check_layout(os);
3783 TeXFont const oldFont = context.font;
3784 context.font.family =
3785 known_coded_font_families[where - known_font_families];
3786 output_font_change(os, oldFont, context.font);
3787 eat_whitespace(p, os, context, false);
3790 else if ((where = is_known(t.cs(), known_font_series)) &&
3791 context.new_layout_allowed) {
3792 context.check_layout(os);
3793 TeXFont const oldFont = context.font;
3794 context.font.series =
3795 known_coded_font_series[where - known_font_series];
3796 output_font_change(os, oldFont, context.font);
3797 eat_whitespace(p, os, context, false);
3800 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3801 context.new_layout_allowed) {
3802 context.check_layout(os);
3803 TeXFont const oldFont = context.font;
3804 context.font.shape =
3805 known_coded_font_shapes[where - known_font_shapes];
3806 output_font_change(os, oldFont, context.font);
3807 eat_whitespace(p, os, context, false);
3809 else if ((where = is_known(t.cs(), known_old_font_families)) &&
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.family =
3816 known_coded_font_families[where - known_old_font_families];
3817 output_font_change(os, oldFont, context.font);
3818 eat_whitespace(p, os, context, false);
3821 else if ((where = is_known(t.cs(), known_old_font_series)) &&
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.series =
3828 known_coded_font_series[where - known_old_font_series];
3829 output_font_change(os, oldFont, context.font);
3830 eat_whitespace(p, os, context, false);
3833 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3834 context.new_layout_allowed) {
3835 context.check_layout(os);
3836 TeXFont const oldFont = context.font;
3837 context.font.init();
3838 context.font.size = oldFont.size;
3839 context.font.shape =
3840 known_coded_font_shapes[where - known_old_font_shapes];
3841 output_font_change(os, oldFont, context.font);
3842 eat_whitespace(p, os, context, false);
3845 else if (t.cs() == "selectlanguage") {
3846 context.check_layout(os);
3847 // save the language for the case that a
3848 // \foreignlanguage is used
3849 context.font.language = babel2lyx(p.verbatim_item());
3850 os << "\n\\lang " << context.font.language << "\n";
3853 else if (t.cs() == "foreignlanguage") {
3854 string const lang = babel2lyx(p.verbatim_item());
3855 parse_text_attributes(p, os, FLAG_ITEM, outer,
3857 context.font.language, lang);
3860 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3861 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3862 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3864 // We have to output the whole command if it has an option
3865 // because LyX doesn't support this yet, see bug #8214,
3866 // only if there is a single option specifying a variant, we can handle it.
3868 string langopts = p.getOpt();
3869 // check if the option contains a variant, if yes, extract it
3870 string::size_type pos_var = langopts.find("variant");
3871 string::size_type i = langopts.find(',');
3872 string::size_type k = langopts.find('=', pos_var);
3873 if (pos_var != string::npos && i == string::npos) {
3875 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3876 lang = preamble.polyglossia2lyx(variant);
3877 parse_text_attributes(p, os, FLAG_ITEM, outer,
3879 context.font.language, lang);
3881 output_ert_inset(os, t.asInput() + langopts, context);
3883 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3884 parse_text_attributes(p, os, FLAG_ITEM, outer,
3886 context.font.language, lang);
3890 else if (t.cs() == "inputencoding") {
3891 // nothing to write here
3892 string const enc = subst(p.verbatim_item(), "\n", " ");
3893 p.setEncoding(enc, Encoding::inputenc);
3896 else if (is_known(t.cs(), known_special_chars) ||
3897 (t.cs() == "protect" &&
3898 p.next_token().cat() == catEscape &&
3899 is_known(p.next_token().cs(), known_special_protect_chars))) {
3900 // LyX sometimes puts a \protect in front, so we have to ignore it
3902 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3903 known_special_chars);
3904 context.check_layout(os);
3905 os << known_coded_special_chars[where - known_special_chars];
3906 skip_spaces_braces(p);
3909 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3910 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3911 p.next_next_token().asInput() == "-") ||
3912 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3913 // LyX sometimes puts a \protect in front, so we have to ignore it
3914 if (t.cs() == "protect")
3916 context.check_layout(os);
3917 if (t.cs() == "nobreakdash")
3918 os << "\\SpecialChar nobreakdash\n";
3920 os << "\\SpecialChar endofsentence\n";
3924 else if (t.cs() == "textquotedbl") {
3925 context.check_layout(os);
3930 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3931 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3932 || t.cs() == "%" || t.cs() == "-") {
3933 context.check_layout(os);
3935 os << "\\SpecialChar softhyphen\n";
3940 else if (t.cs() == "char") {
3941 context.check_layout(os);
3942 if (p.next_token().character() == '`') {
3944 if (p.next_token().cs() == "\"") {
3949 output_ert_inset(os, "\\char`", context);
3952 output_ert_inset(os, "\\char", context);
3956 else if (t.cs() == "verb") {
3957 context.check_layout(os);
3958 // set catcodes to verbatim early, just in case.
3959 p.setCatcodes(VERBATIM_CATCODES);
3960 string delim = p.get_token().asInput();
3961 Parser::Arg arg = p.verbatimStuff(delim);
3963 output_ert_inset(os, "\\verb" + delim
3964 + arg.second + delim, context);
3966 cerr << "invalid \\verb command. Skipping" << endl;
3969 // Problem: \= creates a tabstop inside the tabbing environment
3970 // and else an accent. In the latter case we really would want
3971 // \={o} instead of \= o.
3972 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3973 output_ert_inset(os, t.asInput(), context);
3975 else if (t.cs() == "\\") {
3976 context.check_layout(os);
3978 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3979 else if (p.next_token().asInput() == "*") {
3981 // getOpt() eats the following space if there
3982 // is no optional argument, but that is OK
3983 // here since it has no effect in the output.
3984 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3987 begin_inset(os, "Newline newline");
3992 else if (t.cs() == "newline" ||
3993 (t.cs() == "linebreak" && !p.hasOpt())) {
3994 context.check_layout(os);
3995 begin_inset(os, "Newline ");
3998 skip_spaces_braces(p);
4001 else if (t.cs() == "input" || t.cs() == "include"
4002 || t.cs() == "verbatiminput") {
4003 string name = t.cs();
4004 if (t.cs() == "verbatiminput"
4005 && p.next_token().asInput() == "*")
4006 name += p.get_token().asInput();
4007 context.check_layout(os);
4008 string filename(normalize_filename(p.getArg('{', '}')));
4009 string const path = getMasterFilePath(true);
4010 // We want to preserve relative / absolute filenames,
4011 // therefore path is only used for testing
4012 if ((t.cs() == "include" || t.cs() == "input") &&
4013 !makeAbsPath(filename, path).exists()) {
4014 // The file extension is probably missing.
4015 // Now try to find it out.
4016 string const tex_name =
4017 find_file(filename, path,
4018 known_tex_extensions);
4019 if (!tex_name.empty())
4020 filename = tex_name;
4022 bool external = false;
4024 if (makeAbsPath(filename, path).exists()) {
4025 string const abstexname =
4026 makeAbsPath(filename, path).absFileName();
4027 string const absfigname =
4028 changeExtension(abstexname, ".fig");
4029 fix_child_filename(filename);
4030 string const lyxname = changeExtension(filename,
4031 roundtripMode() ? ".lyx.lyx" : ".lyx");
4032 string const abslyxname = makeAbsPath(
4033 lyxname, getParentFilePath(false)).absFileName();
4035 if (!skipChildren())
4036 external = FileName(absfigname).exists();
4037 if (t.cs() == "input" && !skipChildren()) {
4038 string const ext = getExtension(abstexname);
4040 // Combined PS/LaTeX:
4041 // x.eps, x.pstex_t (old xfig)
4042 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4043 FileName const absepsname(
4044 changeExtension(abstexname, ".eps"));
4045 FileName const abspstexname(
4046 changeExtension(abstexname, ".pstex"));
4047 bool const xfigeps =
4048 (absepsname.exists() ||
4049 abspstexname.exists()) &&
4052 // Combined PDF/LaTeX:
4053 // x.pdf, x.pdftex_t (old xfig)
4054 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4055 FileName const abspdfname(
4056 changeExtension(abstexname, ".pdf"));
4057 bool const xfigpdf =
4058 abspdfname.exists() &&
4059 (ext == "pdftex_t" || ext == "pdf_t");
4063 // Combined PS/PDF/LaTeX:
4064 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4065 string const absbase2(
4066 removeExtension(abstexname) + "_pspdftex");
4067 FileName const abseps2name(
4068 addExtension(absbase2, ".eps"));
4069 FileName const abspdf2name(
4070 addExtension(absbase2, ".pdf"));
4071 bool const xfigboth =
4072 abspdf2name.exists() &&
4073 abseps2name.exists() && ext == "pspdftex";
4075 xfig = xfigpdf || xfigeps || xfigboth;
4076 external = external && xfig;
4079 outname = changeExtension(filename, ".fig");
4080 FileName abssrc(changeExtension(abstexname, ".fig"));
4081 copy_file(abssrc, outname);
4083 // Don't try to convert, the result
4084 // would be full of ERT.
4086 FileName abssrc(abstexname);
4087 copy_file(abssrc, outname);
4088 } else if (t.cs() != "verbatiminput" &&
4090 tex2lyx(abstexname, FileName(abslyxname),
4093 // no need to call copy_file
4094 // tex2lyx creates the file
4097 FileName abssrc(abstexname);
4098 copy_file(abssrc, outname);
4101 cerr << "Warning: Could not find included file '"
4102 << filename << "'." << endl;
4106 begin_inset(os, "External\n");
4107 os << "\ttemplate XFig\n"
4108 << "\tfilename " << outname << '\n';
4109 registerExternalTemplatePackages("XFig");
4111 begin_command_inset(os, "include", name);
4112 outname = subst(outname, "\"", "\\\"");
4113 os << "preview false\n"
4114 "filename \"" << outname << "\"\n";
4115 if (t.cs() == "verbatiminput")
4116 preamble.registerAutomaticallyLoadedPackage("verbatim");
4121 else if (t.cs() == "bibliographystyle") {
4122 // store new bibliographystyle
4123 bibliographystyle = p.verbatim_item();
4124 // If any other command than \bibliography, \addcontentsline
4125 // and \nocite{*} follows, we need to output the style
4126 // (because it might be used by that command).
4127 // Otherwise, it will automatically be output by LyX.
4130 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4131 if (t2.cat() == catBegin)
4133 if (t2.cat() != catEscape)
4135 if (t2.cs() == "nocite") {
4136 if (p.getArg('{', '}') == "*")
4138 } else if (t2.cs() == "bibliography")
4140 else if (t2.cs() == "phantomsection") {
4144 else if (t2.cs() == "addcontentsline") {
4145 // get the 3 arguments of \addcontentsline
4148 contentslineContent = p.getArg('{', '}');
4149 // if the last argument is not \refname we must output
4150 if (contentslineContent == "\\refname")
4157 output_ert_inset(os,
4158 "\\bibliographystyle{" + bibliographystyle + '}',
4163 else if (t.cs() == "phantomsection") {
4164 // we only support this if it occurs between
4165 // \bibliographystyle and \bibliography
4166 if (bibliographystyle.empty())
4167 output_ert_inset(os, "\\phantomsection", context);
4170 else if (t.cs() == "addcontentsline") {
4171 context.check_layout(os);
4172 // get the 3 arguments of \addcontentsline
4173 string const one = p.getArg('{', '}');
4174 string const two = p.getArg('{', '}');
4175 string const three = p.getArg('{', '}');
4176 // only if it is a \refname, we support if for the bibtex inset
4177 if (contentslineContent != "\\refname") {
4178 output_ert_inset(os,
4179 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4184 else if (t.cs() == "bibliography") {
4185 context.check_layout(os);
4187 begin_command_inset(os, "bibtex", "bibtex");
4188 if (!btprint.empty()) {
4189 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4190 // clear the string because the next BibTeX inset can be without the
4191 // \nocite{*} option
4194 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4195 // Do we have addcontentsline?
4196 if (contentslineContent == "\\refname") {
4197 BibOpts = "bibtotoc";
4198 // clear string because next BibTeX inset can be without addcontentsline
4199 contentslineContent.clear();
4201 // Do we have a bibliographystyle set?
4202 if (!bibliographystyle.empty()) {
4203 if (BibOpts.empty())
4204 BibOpts = bibliographystyle;
4206 BibOpts = BibOpts + ',' + bibliographystyle;
4207 // clear it because each bibtex entry has its style
4208 // and we need an empty string to handle \phantomsection
4209 bibliographystyle.clear();
4211 os << "options " << '"' << BibOpts << '"' << "\n";
4215 else if (t.cs() == "parbox") {
4216 // Test whether this is an outer box of a shaded box
4218 // swallow arguments
4219 while (p.hasOpt()) {
4221 p.skip_spaces(true);
4224 p.skip_spaces(true);
4226 if (p.next_token().cat() == catBegin)
4228 p.skip_spaces(true);
4229 Token to = p.get_token();
4230 bool shaded = false;
4231 if (to.asInput() == "\\begin") {
4232 p.skip_spaces(true);
4233 if (p.getArg('{', '}') == "shaded")
4238 parse_outer_box(p, os, FLAG_ITEM, outer,
4239 context, "parbox", "shaded");
4241 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4242 "", "", t.cs(), "", "");
4245 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4246 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4247 t.cs() == "shadowbox" || t.cs() == "doublebox")
4248 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4250 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4251 string backgroundcolor;
4252 preamble.registerAutomaticallyLoadedPackage("xcolor");
4253 if (t.cs() == "fcolorbox") {
4254 string const framecolor = p.getArg('{', '}');
4255 backgroundcolor = p.getArg('{', '}');
4256 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4258 backgroundcolor = p.getArg('{', '}');
4259 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4263 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4264 || t.cs() == "shadowsize") {
4265 p.skip_spaces(true);
4266 if (t.cs() == "fboxrule")
4268 if (t.cs() == "fboxsep")
4270 if (t.cs() == "shadowsize")
4272 while (p.good() && p.next_token().cat() != catSpace
4273 && p.next_token().cat() != catNewline
4274 && p.next_token().cat() != catEscape) {
4275 if (t.cs() == "fboxrule")
4276 fboxrule = fboxrule + p.get_token().asInput();
4277 if (t.cs() == "fboxsep")
4278 fboxsep = fboxsep + p.get_token().asInput();
4279 if (t.cs() == "shadowsize")
4280 shadow_size = shadow_size + p.get_token().asInput();
4284 //\framebox() is part of the picture environment and different from \framebox{}
4285 //\framebox{} will be parsed by parse_outer_box
4286 else if (t.cs() == "framebox") {
4287 if (p.next_token().character() == '(') {
4288 //the syntax is: \framebox(x,y)[position]{content}
4289 string arg = t.asInput();
4290 arg += p.getFullParentheseArg();
4291 arg += p.getFullOpt();
4292 eat_whitespace(p, os, context, false);
4293 output_ert_inset(os, arg + '{', context);
4294 parse_text(p, os, FLAG_ITEM, outer, context);
4295 output_ert_inset(os, "}", context);
4297 //the syntax is: \framebox[width][position]{content}
4298 string special = p.getFullOpt();
4299 special += p.getOpt();
4300 parse_outer_box(p, os, FLAG_ITEM, outer,
4301 context, t.cs(), special);
4305 //\makebox() is part of the picture environment and different from \makebox{}
4306 //\makebox{} will be parsed by parse_box
4307 else if (t.cs() == "makebox") {
4308 if (p.next_token().character() == '(') {
4309 //the syntax is: \makebox(x,y)[position]{content}
4310 string arg = t.asInput();
4311 arg += p.getFullParentheseArg();
4312 arg += p.getFullOpt();
4313 eat_whitespace(p, os, context, false);
4314 output_ert_inset(os, arg + '{', context);
4315 parse_text(p, os, FLAG_ITEM, outer, context);
4316 output_ert_inset(os, "}", context);
4318 //the syntax is: \makebox[width][position]{content}
4319 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4320 "", "", t.cs(), "", "");
4323 else if (t.cs() == "smallskip" ||
4324 t.cs() == "medskip" ||
4325 t.cs() == "bigskip" ||
4326 t.cs() == "vfill") {
4327 context.check_layout(os);
4328 begin_inset(os, "VSpace ");
4331 skip_spaces_braces(p);
4334 else if ((where = is_known(t.cs(), known_spaces))) {
4335 context.check_layout(os);
4336 begin_inset(os, "space ");
4337 os << '\\' << known_coded_spaces[where - known_spaces]
4340 // LaTeX swallows whitespace after all spaces except
4341 // "\\,". We have to do that here, too, because LyX
4342 // adds "{}" which would make the spaces significant.
4344 eat_whitespace(p, os, context, false);
4345 // LyX adds "{}" after all spaces except "\\ " and
4346 // "\\,", so we have to remove "{}".
4347 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4348 // remove the braces after "\\,", too.
4353 else if (t.cs() == "newpage" ||
4354 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4355 t.cs() == "clearpage" ||
4356 t.cs() == "cleardoublepage") {
4357 context.check_layout(os);
4358 begin_inset(os, "Newpage ");
4361 skip_spaces_braces(p);
4364 else if (t.cs() == "DeclareRobustCommand" ||
4365 t.cs() == "DeclareRobustCommandx" ||
4366 t.cs() == "newcommand" ||
4367 t.cs() == "newcommandx" ||
4368 t.cs() == "providecommand" ||
4369 t.cs() == "providecommandx" ||
4370 t.cs() == "renewcommand" ||
4371 t.cs() == "renewcommandx") {
4372 // DeclareRobustCommand, DeclareRobustCommandx,
4373 // providecommand and providecommandx could be handled
4374 // by parse_command(), but we need to call
4375 // add_known_command() here.
4376 string name = t.asInput();
4377 if (p.next_token().asInput() == "*") {
4378 // Starred form. Eat '*'
4382 string const command = p.verbatim_item();
4383 string const opt1 = p.getFullOpt();
4384 string const opt2 = p.getFullOpt();
4385 add_known_command(command, opt1, !opt2.empty());
4386 string const ert = name + '{' + command + '}' +
4388 '{' + p.verbatim_item() + '}';
4390 if (t.cs() == "DeclareRobustCommand" ||
4391 t.cs() == "DeclareRobustCommandx" ||
4392 t.cs() == "providecommand" ||
4393 t.cs() == "providecommandx" ||
4394 name[name.length()-1] == '*')
4395 output_ert_inset(os, ert, context);
4397 context.check_layout(os);
4398 begin_inset(os, "FormulaMacro");
4404 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4405 // let could be handled by parse_command(),
4406 // but we need to call add_known_command() here.
4407 string ert = t.asInput();
4410 if (p.next_token().cat() == catBegin) {
4411 name = p.verbatim_item();
4412 ert += '{' + name + '}';
4414 name = p.verbatim_item();
4419 if (p.next_token().cat() == catBegin) {
4420 command = p.verbatim_item();
4421 ert += '{' + command + '}';
4423 command = p.verbatim_item();
4426 // If command is known, make name known too, to parse
4427 // its arguments correctly. For this reason we also
4428 // have commands in syntax.default that are hardcoded.
4429 CommandMap::iterator it = known_commands.find(command);
4430 if (it != known_commands.end())
4431 known_commands[t.asInput()] = it->second;
4432 output_ert_inset(os, ert, context);
4435 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4438 string name = t.asInput();
4439 string const length = p.verbatim_item();
4442 bool valid = splitLatexLength(length, valstring, unit);
4443 bool known_hspace = false;
4444 bool known_vspace = false;
4445 bool known_unit = false;
4448 istringstream iss(valstring);
4451 if (t.cs()[0] == 'h') {
4452 if (unit == "\\fill") {
4457 known_hspace = true;
4460 if (unit == "\\smallskipamount") {
4462 known_vspace = true;
4463 } else if (unit == "\\medskipamount") {
4465 known_vspace = true;
4466 } else if (unit == "\\bigskipamount") {
4468 known_vspace = true;
4469 } else if (unit == "\\fill") {
4471 known_vspace = true;
4475 if (!known_hspace && !known_vspace) {
4476 switch (unitFromString(unit)) {
4492 //unitFromString(unit) fails for relative units like Length::PCW
4493 // therefore handle them separately
4494 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4495 || unit == "\\textwidth" || unit == "\\linewidth"
4496 || unit == "\\textheight" || unit == "\\paperheight")
4504 // check for glue lengths
4505 bool is_gluelength = false;
4506 string gluelength = length;
4507 string::size_type i = length.find(" minus");
4508 if (i == string::npos) {
4509 i = length.find(" plus");
4510 if (i != string::npos)
4511 is_gluelength = true;
4513 is_gluelength = true;
4514 // if yes transform "9xx minus 8yy plus 7zz"
4516 if (is_gluelength) {
4517 i = gluelength.find(" minus");
4518 if (i != string::npos)
4519 gluelength.replace(i, 7, "-");
4520 i = gluelength.find(" plus");
4521 if (i != string::npos)
4522 gluelength.replace(i, 6, "+");
4525 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4526 // Literal horizontal length or known variable
4527 context.check_layout(os);
4528 begin_inset(os, "space ");
4536 if (known_unit && !known_hspace)
4537 os << "\n\\length " << translate_len(length);
4539 os << "\n\\length " << gluelength;
4541 } else if (known_unit || known_vspace || is_gluelength) {
4542 // Literal vertical length or known variable
4543 context.check_layout(os);
4544 begin_inset(os, "VSpace ");
4547 if (known_unit && !known_vspace)
4548 os << translate_len(length);
4555 // LyX can't handle other length variables in Inset VSpace/space
4560 output_ert_inset(os, name + '{' + unit + '}', context);
4561 else if (value == -1.0)
4562 output_ert_inset(os, name + "{-" + unit + '}', context);
4564 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4566 output_ert_inset(os, name + '{' + length + '}', context);
4570 // The single '=' is meant here.
4571 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4575 context.check_layout(os);
4576 docstring const name = newinsetlayout->name();
4577 bool const caption = name.find(from_ascii("Caption:")) == 0;
4579 begin_inset(os, "Caption ");
4580 os << to_utf8(name.substr(8)) << '\n';
4582 begin_inset(os, "Flex ");
4583 os << to_utf8(name) << '\n'
4584 << "status collapsed\n";
4586 if (newinsetlayout->isPassThru()) {
4587 // set catcodes to verbatim early, just in case.
4588 p.setCatcodes(VERBATIM_CATCODES);
4589 string delim = p.get_token().asInput();
4591 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4592 //FIXME: handle error condition
4593 string const arg = p.verbatimStuff("}").second;
4594 Context newcontext(true, context.textclass);
4595 if (newinsetlayout->forcePlainLayout())
4596 newcontext.layout = &context.textclass.plainLayout();
4597 output_ert(os, arg, newcontext);
4599 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4605 else if (t.cs() == "includepdf") {
4607 string const arg = p.getArg('[', ']');
4608 map<string, string> opts;
4609 vector<string> keys;
4610 split_map(arg, opts, keys);
4611 string name = normalize_filename(p.verbatim_item());
4612 string const path = getMasterFilePath(true);
4613 // We want to preserve relative / absolute filenames,
4614 // therefore path is only used for testing
4615 if (!makeAbsPath(name, path).exists()) {
4616 // The file extension is probably missing.
4617 // Now try to find it out.
4618 char const * const pdfpages_format[] = {"pdf", 0};
4619 string const pdftex_name =
4620 find_file(name, path, pdfpages_format);
4621 if (!pdftex_name.empty()) {
4626 FileName const absname = makeAbsPath(name, path);
4627 if (absname.exists())
4629 fix_child_filename(name);
4630 copy_file(absname, name);
4632 cerr << "Warning: Could not find file '"
4633 << name << "'." << endl;
4635 context.check_layout(os);
4636 begin_inset(os, "External\n\ttemplate ");
4637 os << "PDFPages\n\tfilename "
4639 // parse the options
4640 if (opts.find("pages") != opts.end())
4641 os << "\textra LaTeX \"pages="
4642 << opts["pages"] << "\"\n";
4643 if (opts.find("angle") != opts.end())
4644 os << "\trotateAngle "
4645 << opts["angle"] << '\n';
4646 if (opts.find("origin") != opts.end()) {
4648 string const opt = opts["origin"];
4649 if (opt == "tl") ss << "topleft";
4650 if (opt == "bl") ss << "bottomleft";
4651 if (opt == "Bl") ss << "baselineleft";
4652 if (opt == "c") ss << "center";
4653 if (opt == "tc") ss << "topcenter";
4654 if (opt == "bc") ss << "bottomcenter";
4655 if (opt == "Bc") ss << "baselinecenter";
4656 if (opt == "tr") ss << "topright";
4657 if (opt == "br") ss << "bottomright";
4658 if (opt == "Br") ss << "baselineright";
4659 if (!ss.str().empty())
4660 os << "\trotateOrigin " << ss.str() << '\n';
4662 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4664 if (opts.find("width") != opts.end())
4666 << translate_len(opts["width"]) << '\n';
4667 if (opts.find("height") != opts.end())
4669 << translate_len(opts["height"]) << '\n';
4670 if (opts.find("keepaspectratio") != opts.end())
4671 os << "\tkeepAspectRatio\n";
4673 context.check_layout(os);
4674 registerExternalTemplatePackages("PDFPages");
4677 else if (t.cs() == "loadgame") {
4679 string name = normalize_filename(p.verbatim_item());
4680 string const path = getMasterFilePath(true);
4681 // We want to preserve relative / absolute filenames,
4682 // therefore path is only used for testing
4683 if (!makeAbsPath(name, path).exists()) {
4684 // The file extension is probably missing.
4685 // Now try to find it out.
4686 char const * const lyxskak_format[] = {"fen", 0};
4687 string const lyxskak_name =
4688 find_file(name, path, lyxskak_format);
4689 if (!lyxskak_name.empty())
4690 name = lyxskak_name;
4692 FileName const absname = makeAbsPath(name, path);
4693 if (absname.exists())
4695 fix_child_filename(name);
4696 copy_file(absname, name);
4698 cerr << "Warning: Could not find file '"
4699 << name << "'." << endl;
4700 context.check_layout(os);
4701 begin_inset(os, "External\n\ttemplate ");
4702 os << "ChessDiagram\n\tfilename "
4705 context.check_layout(os);
4706 // after a \loadgame follows a \showboard
4707 if (p.get_token().asInput() == "showboard")
4709 registerExternalTemplatePackages("ChessDiagram");
4713 // try to see whether the string is in unicodesymbols
4714 // Only use text mode commands, since we are in text mode here,
4715 // and math commands may be invalid (bug 6797)
4716 string name = t.asInput();
4717 // handle the dingbats, cyrillic and greek
4718 if (name == "\\ding" || name == "\\textcyr" ||
4719 (name == "\\textgreek" && !preamble.usePolyglossia()))
4720 name = name + '{' + p.getArg('{', '}') + '}';
4721 // handle the ifsym characters
4722 else if (name == "\\textifsymbol") {
4723 string const optif = p.getFullOpt();
4724 string const argif = p.getArg('{', '}');
4725 name = name + optif + '{' + argif + '}';
4727 // handle the \ascii characters
4728 // the case of \ascii within braces, as LyX outputs it, is already
4729 // handled for t.cat() == catBegin
4730 else if (name == "\\ascii") {
4731 // the code is "\asci\xxx"
4732 name = "{" + name + p.get_token().asInput() + "}";
4735 // handle some TIPA special characters
4736 else if (preamble.isPackageUsed("tipa")) {
4737 if (name == "\\textglobfall") {
4740 } else if (name == "\\s") {
4741 // fromLaTeXCommand() does not yet
4742 // recognize tipa short cuts
4743 name = "\\textsyllabic";
4744 } else if (name == "\\=" &&
4745 p.next_token().asInput() == "*") {
4746 // fromLaTeXCommand() does not yet
4747 // recognize tipa short cuts
4750 } else if (name == "\\textdoublevertline") {
4751 // FIXME: This is not correct,
4752 // \textvertline is higher than \textbardbl
4753 name = "\\textbardbl";
4755 } else if (name == "\\!" ) {
4756 if (p.next_token().asInput() == "b") {
4757 p.get_token(); // eat 'b'
4760 } else if (p.next_token().asInput() == "d") {
4764 } else if (p.next_token().asInput() == "g") {
4768 } else if (p.next_token().asInput() == "G") {
4770 name = "\\texthtscg";
4772 } else if (p.next_token().asInput() == "j") {
4774 name = "\\texthtbardotlessj";
4776 } else if (p.next_token().asInput() == "o") {
4778 name = "\\textbullseye";
4781 } else if (name == "\\*" ) {
4782 if (p.next_token().asInput() == "k") {
4784 name = "\\textturnk";
4786 } else if (p.next_token().asInput() == "r") {
4787 p.get_token(); // eat 'b'
4788 name = "\\textturnr";
4790 } else if (p.next_token().asInput() == "t") {
4792 name = "\\textturnt";
4794 } else if (p.next_token().asInput() == "w") {
4796 name = "\\textturnw";
4801 if ((name.size() == 2 &&
4802 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4803 p.next_token().asInput() != "*") ||
4804 is_known(name.substr(1), known_tipa_marks)) {
4805 // name is a command that corresponds to a
4806 // combining character in unicodesymbols.
4807 // Append the argument, fromLaTeXCommand()
4808 // will either convert it to a single
4809 // character or a combining sequence.
4810 name += '{' + p.verbatim_item() + '}';
4812 // now get the character from unicodesymbols
4816 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4817 Encodings::TEXT_CMD, termination, rem, &req);
4819 context.check_layout(os);
4822 output_ert_inset(os, to_utf8(rem), context);
4824 skip_spaces_braces(p);
4825 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4826 preamble.registerAutomaticallyLoadedPackage(*it);
4828 //cerr << "#: " << t << " mode: " << mode << endl;
4829 // heuristic: read up to next non-nested space
4831 string s = t.asInput();
4832 string z = p.verbatim_item();
4833 while (p.good() && z != " " && !z.empty()) {
4834 //cerr << "read: " << z << endl;
4836 z = p.verbatim_item();
4838 cerr << "found ERT: " << s << endl;
4839 output_ert_inset(os, s + ' ', context);
4842 if (t.asInput() == name &&
4843 p.next_token().asInput() == "*") {
4844 // Starred commands like \vspace*{}
4845 p.get_token(); // Eat '*'
4848 if (!parse_command(name, p, os, outer, context))
4849 output_ert_inset(os, name, context);
4853 if (flags & FLAG_LEAVE) {
4854 flags &= ~FLAG_LEAVE;
4861 string guessLanguage(Parser & p, string const & lang)
4863 typedef std::map<std::string, size_t> LangMap;
4864 // map from language names to number of characters
4867 for (char const * const * i = supported_CJK_languages; *i; i++)
4868 used[string(*i)] = 0;
4871 Token const t = p.get_token();
4872 // comments are not counted for any language
4873 if (t.cat() == catComment)
4875 // commands are not counted as well, but we need to detect
4876 // \begin{CJK} and switch encoding if needed
4877 if (t.cat() == catEscape) {
4878 if (t.cs() == "inputencoding") {
4879 string const enc = subst(p.verbatim_item(), "\n", " ");
4880 p.setEncoding(enc, Encoding::inputenc);
4883 if (t.cs() != "begin")
4886 // Non-CJK content is counted for lang.
4887 // We do not care about the real language here:
4888 // If we have more non-CJK contents than CJK contents,
4889 // we simply use the language that was specified as
4890 // babel main language.
4891 used[lang] += t.asInput().length();
4894 // Now we are starting an environment
4896 string const name = p.getArg('{', '}');
4897 if (name != "CJK") {
4901 // It is a CJK environment
4903 /* name = */ p.getArg('{', '}');
4904 string const encoding = p.getArg('{', '}');
4905 /* mapping = */ p.getArg('{', '}');
4906 string const encoding_old = p.getEncoding();
4907 char const * const * const where =
4908 is_known(encoding, supported_CJK_encodings);
4910 p.setEncoding(encoding, Encoding::CJK);
4912 p.setEncoding("UTF-8");
4913 string const text = p.ertEnvironment("CJK");
4914 p.setEncoding(encoding_old);
4917 // ignore contents in unknown CJK encoding
4920 // the language of the text
4922 supported_CJK_languages[where - supported_CJK_encodings];
4923 used[cjk] += text.length();
4925 LangMap::const_iterator use = used.begin();
4926 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4927 if (it->second > use->second)