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", "subsecref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "subsec", "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",
316 "textsubring", "textsubbar", 0};
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";
855 if (!fboxrule.empty())
856 thickness = fboxrule;
860 if (!fboxsep.empty())
861 separation = fboxsep;
865 if (!shadow_size.empty())
866 shadowsize = shadow_size;
869 string framecolor = "black";
870 string backgroundcolor = "none";
871 if (!frame_color.empty())
872 framecolor = frame_color;
873 if (!background_color.empty())
874 backgroundcolor = background_color;
875 // if there is a color box around the \begin statements have not yet been parsed
877 if (!frame_color.empty() || !background_color.empty()) {
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;
886 active_environments.push_back("minipage");
889 else if (p.next_token().asInput() == "\\parbox") {
890 p.get_token().asInput();
891 inner_type = "parbox";
892 inner_flags = FLAG_ITEM;
895 else if (p.next_token().asInput() == "\\makebox") {
896 p.get_token().asInput();
897 inner_type = "makebox";
898 inner_flags = FLAG_ITEM;
900 // in case there is just \colorbox{color}{text}
903 inner_type = "makebox";
904 inner_flags = FLAG_BRACE_LAST;
909 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
911 if (!inner_type.empty() && p.hasOpt()) {
912 if (inner_type != "makebox")
913 position = p.getArg('[', ']');
915 latex_width = p.getArg('[', ']');
916 translate_box_len(latex_width, width_value, width_unit, width_special);
919 if (position != "t" && position != "c" && position != "b") {
920 cerr << "invalid position " << position << " for "
921 << inner_type << endl;
925 if (inner_type != "makebox") {
926 latex_height = p.getArg('[', ']');
927 translate_box_len(latex_height, height_value, height_unit, height_special);
929 string const opt = p.getArg('[', ']');
932 if (hor_pos != "l" && hor_pos != "c" &&
933 hor_pos != "r" && hor_pos != "s") {
934 cerr << "invalid hor_pos " << hor_pos
935 << " for " << inner_type << endl;
942 inner_pos = p.getArg('[', ']');
943 if (inner_pos != "c" && inner_pos != "t" &&
944 inner_pos != "b" && inner_pos != "s") {
945 cerr << "invalid inner_pos "
946 << inner_pos << " for "
947 << inner_type << endl;
948 inner_pos = position;
952 if (inner_type == "makebox")
956 if (inner_type.empty()) {
957 if (special.empty() && outer_type != "framebox")
958 latex_width = "1\\columnwidth";
961 latex_width = p2.getArg('[', ']');
962 string const opt = p2.getArg('[', ']');
965 if (hor_pos != "l" && hor_pos != "c" &&
966 hor_pos != "r" && hor_pos != "s") {
967 cerr << "invalid hor_pos " << hor_pos
968 << " for " << outer_type << endl;
972 if (outer_type == "framebox")
976 } else if (inner_type != "makebox")
977 latex_width = p.verbatim_item();
978 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
979 // as this is LyX's standard for such cases (except for makebox)
980 // \framebox is more special and handled below
981 if (latex_width.empty() && inner_type != "makebox"
982 && outer_type != "framebox")
983 latex_width = "1\\columnwidth";
985 translate_len(latex_width, width_value, width_unit);
987 bool shadedparbox = false;
988 if (inner_type == "shaded") {
989 eat_whitespace(p, os, parent_context, false);
990 if (outer_type == "parbox") {
992 if (p.next_token().cat() == catBegin)
994 eat_whitespace(p, os, parent_context, false);
1000 // If we already read the inner box we have to push the inner env
1001 if (!outer_type.empty() && !inner_type.empty() &&
1002 (inner_flags & FLAG_END))
1003 active_environments.push_back(inner_type);
1004 bool use_ert = false;
1005 if (!outer_type.empty() && !inner_type.empty()) {
1006 // Look whether there is some content after the end of the
1007 // inner box, but before the end of the outer box.
1008 // If yes, we need to output ERT.
1010 if (inner_flags & FLAG_END)
1011 p.ertEnvironment(inner_type);
1014 p.skip_spaces(true);
1015 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1016 if ((outer_env && p.next_token().asInput() != "\\end") ||
1017 (!outer_env && p.next_token().cat() != catEnd)) {
1018 // something is between the end of the inner box and
1019 // the end of the outer box, so we need to use ERT.
1027 if (!outer_type.empty()) {
1028 if (outer_flags & FLAG_END)
1029 ss << "\\begin{" << outer_type << '}';
1031 ss << '\\' << outer_type << '{';
1032 if (!special.empty())
1036 if (!inner_type.empty()) {
1037 if (inner_type != "shaded") {
1038 if (inner_flags & FLAG_END)
1039 ss << "\\begin{" << inner_type << '}';
1041 ss << '\\' << inner_type;
1043 if (!position.empty())
1044 ss << '[' << position << ']';
1045 if (!latex_height.empty())
1046 ss << '[' << latex_height << ']';
1047 if (!inner_pos.empty())
1048 ss << '[' << inner_pos << ']';
1049 ss << '{' << latex_width << '}';
1050 if (!(inner_flags & FLAG_END))
1053 if (inner_type == "shaded")
1054 ss << "\\begin{shaded}";
1055 output_ert_inset(os, ss.str(), parent_context);
1056 if (!inner_type.empty()) {
1057 parse_text(p, os, inner_flags, outer, parent_context);
1058 if (inner_flags & FLAG_END)
1059 output_ert_inset(os, "\\end{" + inner_type + '}',
1062 output_ert_inset(os, "}", parent_context);
1064 if (!outer_type.empty()) {
1065 // If we already read the inner box we have to pop
1067 if (!inner_type.empty() && (inner_flags & FLAG_END))
1068 active_environments.pop_back();
1070 // Ensure that the end of the outer box is parsed correctly:
1071 // The opening brace has been eaten by parse_outer_box()
1072 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1073 outer_flags &= ~FLAG_ITEM;
1074 outer_flags |= FLAG_BRACE_LAST;
1076 parse_text(p, os, outer_flags, outer, parent_context);
1077 if (outer_flags & FLAG_END)
1078 output_ert_inset(os, "\\end{" + outer_type + '}',
1081 output_ert_inset(os, "}", parent_context);
1084 // LyX does not like empty positions, so we have
1085 // to set them to the LaTeX default values here.
1086 if (position.empty())
1088 if (inner_pos.empty())
1089 inner_pos = position;
1090 parent_context.check_layout(os);
1091 begin_inset(os, "Box ");
1092 if (outer_type == "framed")
1094 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1096 else if (outer_type == "shadowbox")
1097 os << "Shadowbox\n";
1098 else if ((outer_type == "shaded" && inner_type.empty()) ||
1099 (outer_type == "minipage" && inner_type == "shaded") ||
1100 (outer_type == "parbox" && inner_type == "shaded")) {
1102 preamble.registerAutomaticallyLoadedPackage("color");
1103 } else if (outer_type == "doublebox")
1104 os << "Doublebox\n";
1105 else if (outer_type.empty() || outer_type == "mbox")
1106 os << "Frameless\n";
1108 os << outer_type << '\n';
1109 os << "position \"" << position << "\"\n";
1110 os << "hor_pos \"" << hor_pos << "\"\n";
1111 if (outer_type == "mbox")
1112 os << "has_inner_box 1\n";
1113 else if (!frame_color.empty() && inner_type == "makebox")
1114 os << "has_inner_box 0\n";
1116 os << "has_inner_box " << !inner_type.empty() << "\n";
1117 os << "inner_pos \"" << inner_pos << "\"\n";
1118 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1120 if (outer_type == "mbox")
1121 os << "use_makebox 1\n";
1122 else if (!frame_color.empty())
1123 os << "use_makebox 0\n";
1125 os << "use_makebox " << (inner_type == "makebox") << '\n';
1126 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1127 os << "width \"\"\n";
1128 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1129 else if (contains(width_unit, '\\'))
1130 os << "width \"" << width_value << "in" << "\"\n";
1132 os << "width \"" << width_value << width_unit << "\"\n";
1133 if (contains(width_unit, '\\')) {
1134 width_unit.erase (0,1); // remove the leading '\'
1135 os << "special \"" << width_unit << "\"\n";
1137 os << "special \"" << width_special << "\"\n";
1138 if (contains(height_unit, '\\'))
1139 os << "height \"" << height_value << "in" << "\"\n";
1141 os << "height \"" << height_value << height_unit << "\"\n";
1142 os << "height_special \"" << height_special << "\"\n";
1143 os << "thickness \"" << thickness << "\"\n";
1144 os << "separation \"" << separation << "\"\n";
1145 os << "shadowsize \"" << shadowsize << "\"\n";
1146 os << "framecolor \"" << framecolor << "\"\n";
1147 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1148 os << "status open\n\n";
1150 // Unfortunately we can't use parse_text_in_inset:
1151 // InsetBox::forcePlainLayout() is hard coded and does not
1152 // use the inset layout. Apart from that do we call parse_text
1153 // up to two times, but need only one check_end_layout.
1154 bool const forcePlainLayout =
1155 (!inner_type.empty() || inner_type == "makebox") &&
1156 outer_type != "shaded" && outer_type != "framed";
1157 Context context(true, parent_context.textclass);
1158 if (forcePlainLayout)
1159 context.layout = &context.textclass.plainLayout();
1161 context.font = parent_context.font;
1163 // If we have no inner box the contents will be read with the outer box
1164 if (!inner_type.empty())
1165 parse_text(p, os, inner_flags, outer, context);
1167 // Ensure that the end of the outer box is parsed correctly:
1168 // The opening brace has been eaten by parse_outer_box()
1169 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1170 outer_flags &= ~FLAG_ITEM;
1171 outer_flags |= FLAG_BRACE_LAST;
1174 // Find end of outer box, output contents if inner_type is
1175 // empty and output possible comments
1176 if (!outer_type.empty()) {
1177 // If we already read the inner box we have to pop
1179 if (!inner_type.empty() && (inner_flags & FLAG_END))
1180 active_environments.pop_back();
1181 // This does not output anything but comments if
1182 // inner_type is not empty (see use_ert)
1183 parse_text(p, os, outer_flags, outer, context);
1186 context.check_end_layout(os);
1188 #ifdef PRESERVE_LAYOUT
1189 // LyX puts a % after the end of the minipage
1190 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1192 //output_ert_inset(os, "%dummy", parent_context);
1195 parent_context.new_paragraph(os);
1197 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1198 //output_ert_inset(os, "%dummy", parent_context);
1201 // We add a protected space if something real follows
1202 if (p.good() && p.next_token().cat() != catComment) {
1203 begin_inset(os, "space ~\n");
1209 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1210 active_environments.pop_back();
1211 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1212 // in this case we have to eat the the closing brace of the color box
1213 p.get_token().asInput(); // the '}'
1215 if (p.next_token().asInput() == "}") {
1216 // in this case we assume that the closing brace is from the box settings
1217 // therefore reset these values for the next box
1223 // all boxes except of Frameless and Shaded require calc
1224 if (!(outer_type.empty() || outer_type == "mbox") &&
1225 !((outer_type == "shaded" && inner_type.empty()) ||
1226 (outer_type == "minipage" && inner_type == "shaded") ||
1227 (outer_type == "parbox" && inner_type == "shaded")))
1228 preamble.registerAutomaticallyLoadedPackage("calc");
1232 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1233 Context & parent_context, string const & outer_type,
1234 string const & special)
1236 eat_whitespace(p, os, parent_context, false);
1237 if (flags & FLAG_ITEM) {
1239 if (p.next_token().cat() == catBegin)
1242 cerr << "Warning: Ignoring missing '{' after \\"
1243 << outer_type << '.' << endl;
1244 eat_whitespace(p, os, parent_context, false);
1247 unsigned int inner_flags = 0;
1249 if (outer_type == "minipage" || outer_type == "parbox") {
1250 p.skip_spaces(true);
1251 while (p.hasOpt()) {
1253 p.skip_spaces(true);
1256 p.skip_spaces(true);
1257 if (outer_type == "parbox") {
1259 if (p.next_token().cat() == catBegin)
1261 p.skip_spaces(true);
1264 if (outer_type == "shaded" || outer_type == "mbox") {
1265 // These boxes never have an inner box
1267 } else if (p.next_token().asInput() == "\\parbox") {
1268 inner = p.get_token().cs();
1269 inner_flags = FLAG_ITEM;
1270 } else if (p.next_token().asInput() == "\\begin") {
1271 // Is this a minipage or shaded box?
1274 inner = p.getArg('{', '}');
1276 if (inner == "minipage" || inner == "shaded")
1277 inner_flags = FLAG_END;
1282 if (inner_flags == FLAG_END) {
1283 if (inner != "shaded")
1287 eat_whitespace(p, os, parent_context, false);
1289 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1290 outer_type, special, inner, "", "");
1292 if (inner_flags == FLAG_ITEM) {
1294 eat_whitespace(p, os, parent_context, false);
1296 parse_box(p, os, flags, inner_flags, outer, parent_context,
1297 outer_type, special, inner, "", "");
1302 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1304 parent_context.check_layout(os);
1305 begin_inset(os, "listings\n");
1307 string arg = p.verbatimOption();
1308 os << "lstparams " << '"' << arg << '"' << '\n';
1309 if (arg.find("\\color") != string::npos)
1310 preamble.registerAutomaticallyLoadedPackage("color");
1313 os << "inline true\n";
1315 os << "inline false\n";
1316 os << "status collapsed\n";
1317 Context context(true, parent_context.textclass);
1318 context.layout = &parent_context.textclass.plainLayout();
1321 // set catcodes to verbatim early, just in case.
1322 p.setCatcodes(VERBATIM_CATCODES);
1323 string delim = p.get_token().asInput();
1324 //FIXME: handler error condition
1325 s = p.verbatimStuff(delim).second;
1326 // context.new_paragraph(os);
1328 s = p.verbatimEnvironment("lstlisting");
1329 output_ert(os, s, context);
1334 /// parse an unknown environment
1335 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1336 unsigned flags, bool outer,
1337 Context & parent_context)
1339 if (name == "tabbing")
1340 // We need to remember that we have to handle '\=' specially
1341 flags |= FLAG_TABBING;
1343 // We need to translate font changes and paragraphs inside the
1344 // environment to ERT if we have a non standard font.
1345 // Otherwise things like
1346 // \large\begin{foo}\huge bar\end{foo}
1348 bool const specialfont =
1349 (parent_context.font != parent_context.normalfont);
1350 bool const new_layout_allowed = parent_context.new_layout_allowed;
1352 parent_context.new_layout_allowed = false;
1353 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1354 parse_text_snippet(p, os, flags, outer, parent_context);
1355 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1357 parent_context.new_layout_allowed = new_layout_allowed;
1361 void parse_environment(Parser & p, ostream & os, bool outer,
1362 string & last_env, Context & parent_context)
1364 Layout const * newlayout;
1365 InsetLayout const * newinsetlayout = 0;
1366 string const name = p.getArg('{', '}');
1367 const bool is_starred = suffixIs(name, '*');
1368 string const unstarred_name = rtrim(name, "*");
1369 active_environments.push_back(name);
1371 if (is_math_env(name)) {
1372 parent_context.check_layout(os);
1373 begin_inset(os, "Formula ");
1374 os << "\\begin{" << name << "}";
1375 parse_math(p, os, FLAG_END, MATH_MODE);
1376 os << "\\end{" << name << "}";
1378 if (is_display_math_env(name)) {
1379 // Prevent the conversion of a line break to a space
1380 // (bug 7668). This does not change the output, but
1381 // looks ugly in LyX.
1382 eat_whitespace(p, os, parent_context, false);
1386 else if (is_known(name, preamble.polyglossia_languages)) {
1387 // We must begin a new paragraph if not already done
1388 if (! parent_context.atParagraphStart()) {
1389 parent_context.check_end_layout(os);
1390 parent_context.new_paragraph(os);
1392 // save the language in the context so that it is
1393 // handled by parse_text
1394 parent_context.font.language = preamble.polyglossia2lyx(name);
1395 parse_text(p, os, FLAG_END, outer, parent_context);
1396 // Just in case the environment is empty
1397 parent_context.extra_stuff.erase();
1398 // We must begin a new paragraph to reset the language
1399 parent_context.new_paragraph(os);
1403 else if (unstarred_name == "tabular" || name == "longtable") {
1404 eat_whitespace(p, os, parent_context, false);
1405 string width = "0pt";
1406 if (name == "tabular*") {
1407 width = lyx::translate_len(p.getArg('{', '}'));
1408 eat_whitespace(p, os, parent_context, false);
1410 parent_context.check_layout(os);
1411 begin_inset(os, "Tabular ");
1412 handle_tabular(p, os, name, width, parent_context);
1417 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1418 eat_whitespace(p, os, parent_context, false);
1419 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1420 eat_whitespace(p, os, parent_context, false);
1421 parent_context.check_layout(os);
1422 begin_inset(os, "Float " + unstarred_name + "\n");
1423 // store the float type for subfloats
1424 // subfloats only work with figures and tables
1425 if (unstarred_name == "figure")
1426 float_type = unstarred_name;
1427 else if (unstarred_name == "table")
1428 float_type = unstarred_name;
1432 os << "placement " << opt << '\n';
1433 if (contains(opt, "H"))
1434 preamble.registerAutomaticallyLoadedPackage("float");
1436 Floating const & fl = parent_context.textclass.floats()
1437 .getType(unstarred_name);
1438 if (!fl.floattype().empty() && fl.usesFloatPkg())
1439 preamble.registerAutomaticallyLoadedPackage("float");
1442 os << "wide " << convert<string>(is_starred)
1443 << "\nsideways false"
1444 << "\nstatus open\n\n";
1445 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1447 // We don't need really a new paragraph, but
1448 // we must make sure that the next item gets a \begin_layout.
1449 parent_context.new_paragraph(os);
1451 // the float is parsed thus delete the type
1455 else if (unstarred_name == "sidewaysfigure"
1456 || unstarred_name == "sidewaystable") {
1457 eat_whitespace(p, os, parent_context, false);
1458 parent_context.check_layout(os);
1459 if (unstarred_name == "sidewaysfigure")
1460 begin_inset(os, "Float figure\n");
1462 begin_inset(os, "Float table\n");
1463 os << "wide " << convert<string>(is_starred)
1464 << "\nsideways true"
1465 << "\nstatus open\n\n";
1466 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1468 // We don't need really a new paragraph, but
1469 // we must make sure that the next item gets a \begin_layout.
1470 parent_context.new_paragraph(os);
1472 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1475 else if (name == "wrapfigure" || name == "wraptable") {
1476 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1477 eat_whitespace(p, os, parent_context, false);
1478 parent_context.check_layout(os);
1481 string overhang = "0col%";
1484 lines = p.getArg('[', ']');
1485 string const placement = p.getArg('{', '}');
1487 overhang = p.getArg('[', ']');
1488 string const width = p.getArg('{', '}');
1490 if (name == "wrapfigure")
1491 begin_inset(os, "Wrap figure\n");
1493 begin_inset(os, "Wrap table\n");
1494 os << "lines " << lines
1495 << "\nplacement " << placement
1496 << "\noverhang " << lyx::translate_len(overhang)
1497 << "\nwidth " << lyx::translate_len(width)
1498 << "\nstatus open\n\n";
1499 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1501 // We don't need really a new paragraph, but
1502 // we must make sure that the next item gets a \begin_layout.
1503 parent_context.new_paragraph(os);
1505 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1508 else if (name == "minipage") {
1509 eat_whitespace(p, os, parent_context, false);
1510 // Test whether this is an outer box of a shaded box
1512 // swallow arguments
1513 while (p.hasOpt()) {
1515 p.skip_spaces(true);
1518 p.skip_spaces(true);
1519 Token t = p.get_token();
1520 bool shaded = false;
1521 if (t.asInput() == "\\begin") {
1522 p.skip_spaces(true);
1523 if (p.getArg('{', '}') == "shaded")
1528 parse_outer_box(p, os, FLAG_END, outer,
1529 parent_context, name, "shaded");
1531 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1532 "", "", name, "", "");
1536 else if (name == "comment") {
1537 eat_whitespace(p, os, parent_context, false);
1538 parent_context.check_layout(os);
1539 begin_inset(os, "Note Comment\n");
1540 os << "status open\n";
1541 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1544 skip_braces(p); // eat {} that might by set by LyX behind comments
1545 preamble.registerAutomaticallyLoadedPackage("verbatim");
1548 else if (name == "verbatim") {
1549 // FIXME: this should go in the generic code that
1550 // handles environments defined in layout file that
1551 // have "PassThru 1". However, the code over there is
1552 // already too complicated for my taste.
1553 parent_context.new_paragraph(os);
1554 Context context(true, parent_context.textclass,
1555 &parent_context.textclass[from_ascii("Verbatim")]);
1556 string s = p.verbatimEnvironment("verbatim");
1557 output_ert(os, s, context);
1561 else if (name == "IPA") {
1562 eat_whitespace(p, os, parent_context, false);
1563 parent_context.check_layout(os);
1564 begin_inset(os, "IPA\n");
1565 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1568 preamble.registerAutomaticallyLoadedPackage("tipa");
1569 preamble.registerAutomaticallyLoadedPackage("tipx");
1572 else if (name == "CJK") {
1573 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1574 // It is impossible to decide if a CJK environment was in its own paragraph or within
1575 // a line. We therefore always assume a paragraph since the latter is a rare case.
1576 eat_whitespace(p, os, parent_context, false);
1577 parent_context.check_end_layout(os);
1578 // store the encoding to be able to reset it
1579 string const encoding_old = p.getEncoding();
1580 string const encoding = p.getArg('{', '}');
1581 // FIXME: For some reason JIS does not work. Although the text
1582 // in tests/CJK.tex is identical with the SJIS version if you
1583 // convert both snippets using the recode command line utility,
1584 // the resulting .lyx file contains some extra characters if
1585 // you set buggy_encoding to false for JIS.
1586 bool const buggy_encoding = encoding == "JIS";
1587 if (!buggy_encoding)
1588 p.setEncoding(encoding, Encoding::CJK);
1590 // FIXME: This will read garbage, since the data is not encoded in utf8.
1591 p.setEncoding("UTF-8");
1593 // LyX only supports the same mapping for all CJK
1594 // environments, so we might need to output everything as ERT
1595 string const mapping = trim(p.getArg('{', '}'));
1596 char const * const * const where =
1597 is_known(encoding, supported_CJK_encodings);
1598 if (!buggy_encoding && !preamble.fontCJKSet())
1599 preamble.fontCJK(mapping);
1600 bool knownMapping = mapping == preamble.fontCJK();
1601 if (buggy_encoding || !knownMapping || !where) {
1602 parent_context.check_layout(os);
1603 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1605 // we must parse the content as verbatim because e.g. JIS can contain
1606 // normally invalid characters
1607 // FIXME: This works only for the most simple cases.
1608 // Since TeX control characters are not parsed,
1609 // things like comments are completely wrong.
1610 string const s = p.plainEnvironment("CJK");
1611 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1613 output_ert_inset(os, "\\", parent_context);
1614 else if (*it == '$')
1615 output_ert_inset(os, "$", parent_context);
1616 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1621 output_ert_inset(os, "\\end{" + name + "}",
1625 supported_CJK_languages[where - supported_CJK_encodings];
1626 // store the language because we must reset it at the end
1627 string const lang_old = parent_context.font.language;
1628 parent_context.font.language = lang;
1629 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1630 parent_context.font.language = lang_old;
1631 parent_context.new_paragraph(os);
1633 p.setEncoding(encoding_old);
1637 else if (name == "lyxgreyedout") {
1638 eat_whitespace(p, os, parent_context, false);
1639 parent_context.check_layout(os);
1640 begin_inset(os, "Note Greyedout\n");
1641 os << "status open\n";
1642 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1645 if (!preamble.notefontcolor().empty())
1646 preamble.registerAutomaticallyLoadedPackage("color");
1649 else if (name == "btSect") {
1650 eat_whitespace(p, os, parent_context, false);
1651 parent_context.check_layout(os);
1652 begin_command_inset(os, "bibtex", "bibtex");
1653 string bibstyle = "plain";
1655 bibstyle = p.getArg('[', ']');
1656 p.skip_spaces(true);
1658 string const bibfile = p.getArg('{', '}');
1659 eat_whitespace(p, os, parent_context, false);
1660 Token t = p.get_token();
1661 if (t.asInput() == "\\btPrintCited") {
1662 p.skip_spaces(true);
1663 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1665 if (t.asInput() == "\\btPrintNotCited") {
1666 p.skip_spaces(true);
1667 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1669 if (t.asInput() == "\\btPrintAll") {
1670 p.skip_spaces(true);
1671 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1673 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1674 os << "options " << '"' << bibstyle << '"' << "\n";
1675 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1680 else if (name == "framed" || name == "shaded") {
1681 eat_whitespace(p, os, parent_context, false);
1682 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1684 preamble.registerAutomaticallyLoadedPackage("framed");
1687 else if (name == "lstlisting") {
1688 eat_whitespace(p, os, parent_context, false);
1689 parse_listings(p, os, parent_context, false);
1693 else if (!parent_context.new_layout_allowed)
1694 parse_unknown_environment(p, name, os, FLAG_END, outer,
1697 // Alignment and spacing settings
1698 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1699 // therefore are totally broken!
1700 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1701 // they are commands not environments. They are furthermore switches that
1702 // can be ended by another switches, but also by commands like \footnote or
1703 // \parbox. So the only safe way is to leave them untouched.
1704 else if (name == "center" || name == "centering" ||
1705 name == "flushleft" || name == "flushright" ||
1706 name == "singlespace" || name == "onehalfspace" ||
1707 name == "doublespace" || name == "spacing") {
1708 eat_whitespace(p, os, parent_context, false);
1709 // We must begin a new paragraph if not already done
1710 if (! parent_context.atParagraphStart()) {
1711 parent_context.check_end_layout(os);
1712 parent_context.new_paragraph(os);
1714 if (name == "flushleft")
1715 parent_context.add_extra_stuff("\\align left\n");
1716 else if (name == "flushright")
1717 parent_context.add_extra_stuff("\\align right\n");
1718 else if (name == "center" || name == "centering")
1719 parent_context.add_extra_stuff("\\align center\n");
1720 else if (name == "singlespace")
1721 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1722 else if (name == "onehalfspace") {
1723 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1724 preamble.registerAutomaticallyLoadedPackage("setspace");
1725 } else if (name == "doublespace") {
1726 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1727 preamble.registerAutomaticallyLoadedPackage("setspace");
1728 } else if (name == "spacing") {
1729 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1730 preamble.registerAutomaticallyLoadedPackage("setspace");
1732 parse_text(p, os, FLAG_END, outer, parent_context);
1733 // Just in case the environment is empty
1734 parent_context.extra_stuff.erase();
1735 // We must begin a new paragraph to reset the alignment
1736 parent_context.new_paragraph(os);
1740 // The single '=' is meant here.
1741 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1742 eat_whitespace(p, os, parent_context, false);
1743 Context context(true, parent_context.textclass, newlayout,
1744 parent_context.layout, parent_context.font);
1745 if (parent_context.deeper_paragraph) {
1746 // We are beginning a nested environment after a
1747 // deeper paragraph inside the outer list environment.
1748 // Therefore we don't need to output a "begin deeper".
1749 context.need_end_deeper = true;
1751 parent_context.check_end_layout(os);
1752 if (last_env == name) {
1753 // we need to output a separator since LyX would export
1754 // the two environments as one otherwise (bug 5716)
1755 TeX2LyXDocClass const & textclass(parent_context.textclass);
1756 Context newcontext(true, textclass,
1757 &(textclass.defaultLayout()));
1758 newcontext.check_layout(os);
1759 begin_inset(os, "Separator plain\n");
1761 newcontext.check_end_layout(os);
1763 switch (context.layout->latextype) {
1764 case LATEX_LIST_ENVIRONMENT:
1765 context.add_par_extra_stuff("\\labelwidthstring "
1766 + p.verbatim_item() + '\n');
1769 case LATEX_BIB_ENVIRONMENT:
1770 p.verbatim_item(); // swallow next arg
1776 context.check_deeper(os);
1777 // handle known optional and required arguments
1778 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1779 // It is impossible to place anything after the environment name,
1780 // but before the first \\item.
1781 if (context.layout->latextype == LATEX_ENVIRONMENT)
1782 output_arguments(os, p, outer, false, false, context,
1783 context.layout->latexargs());
1784 parse_text(p, os, FLAG_END, outer, context);
1785 if (context.layout->latextype == LATEX_ENVIRONMENT)
1786 output_arguments(os, p, outer, false, true, context,
1787 context.layout->postcommandargs());
1788 context.check_end_layout(os);
1789 if (parent_context.deeper_paragraph) {
1790 // We must suppress the "end deeper" because we
1791 // suppressed the "begin deeper" above.
1792 context.need_end_deeper = false;
1794 context.check_end_deeper(os);
1795 parent_context.new_paragraph(os);
1797 if (!preamble.titleLayoutFound())
1798 preamble.titleLayoutFound(newlayout->intitle);
1799 set<string> const & req = newlayout->requires();
1800 set<string>::const_iterator it = req.begin();
1801 set<string>::const_iterator en = req.end();
1802 for (; it != en; ++it)
1803 preamble.registerAutomaticallyLoadedPackage(*it);
1806 // The single '=' is meant here.
1807 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1808 eat_whitespace(p, os, parent_context, false);
1809 parent_context.check_layout(os);
1810 begin_inset(os, "Flex ");
1811 os << to_utf8(newinsetlayout->name()) << '\n'
1812 << "status collapsed\n";
1813 if (newinsetlayout->isPassThru()) {
1814 string const arg = p.verbatimEnvironment(name);
1815 Context context(true, parent_context.textclass,
1816 &parent_context.textclass.plainLayout(),
1817 parent_context.layout);
1818 output_ert(os, arg, parent_context);
1820 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1824 else if (name == "appendix") {
1825 // This is no good latex style, but it works and is used in some documents...
1826 eat_whitespace(p, os, parent_context, false);
1827 parent_context.check_end_layout(os);
1828 Context context(true, parent_context.textclass, parent_context.layout,
1829 parent_context.layout, parent_context.font);
1830 context.check_layout(os);
1831 os << "\\start_of_appendix\n";
1832 parse_text(p, os, FLAG_END, outer, context);
1833 context.check_end_layout(os);
1837 else if (known_environments.find(name) != known_environments.end()) {
1838 vector<ArgumentType> arguments = known_environments[name];
1839 // The last "argument" denotes wether we may translate the
1840 // environment contents to LyX
1841 // The default required if no argument is given makes us
1842 // compatible with the reLyXre environment.
1843 ArgumentType contents = arguments.empty() ?
1846 if (!arguments.empty())
1847 arguments.pop_back();
1848 // See comment in parse_unknown_environment()
1849 bool const specialfont =
1850 (parent_context.font != parent_context.normalfont);
1851 bool const new_layout_allowed =
1852 parent_context.new_layout_allowed;
1854 parent_context.new_layout_allowed = false;
1855 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1856 outer, parent_context);
1857 if (contents == verbatim)
1858 output_ert_inset(os, p.ertEnvironment(name),
1861 parse_text_snippet(p, os, FLAG_END, outer,
1863 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1865 parent_context.new_layout_allowed = new_layout_allowed;
1869 parse_unknown_environment(p, name, os, FLAG_END, outer,
1873 active_environments.pop_back();
1877 /// parses a comment and outputs it to \p os.
1878 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1880 LASSERT(t.cat() == catComment, return);
1881 if (!t.cs().empty()) {
1882 context.check_layout(os);
1883 output_ert_inset(os, '%' + t.cs(), context);
1884 if (p.next_token().cat() == catNewline) {
1885 // A newline after a comment line starts a new
1887 if (context.new_layout_allowed) {
1888 if(!context.atParagraphStart())
1889 // Only start a new paragraph if not already
1890 // done (we might get called recursively)
1891 context.new_paragraph(os);
1893 output_ert_inset(os, "\n", context);
1894 eat_whitespace(p, os, context, true);
1897 // "%\n" combination
1904 * Reads spaces and comments until the first non-space, non-comment token.
1905 * New paragraphs (double newlines or \\par) are handled like simple spaces
1906 * if \p eatParagraph is true.
1907 * Spaces are skipped, but comments are written to \p os.
1909 void eat_whitespace(Parser & p, ostream & os, Context & context,
1913 Token const & t = p.get_token();
1914 if (t.cat() == catComment)
1915 parse_comment(p, os, t, context);
1916 else if ((! eatParagraph && p.isParagraph()) ||
1917 (t.cat() != catSpace && t.cat() != catNewline)) {
1926 * Set a font attribute, parse text and reset the font attribute.
1927 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1928 * \param currentvalue Current value of the attribute. Is set to the new
1929 * value during parsing.
1930 * \param newvalue New value of the attribute
1932 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1933 Context & context, string const & attribute,
1934 string & currentvalue, string const & newvalue)
1936 context.check_layout(os);
1937 string const oldvalue = currentvalue;
1938 currentvalue = newvalue;
1939 os << '\n' << attribute << ' ' << newvalue << "\n";
1940 parse_text_snippet(p, os, flags, outer, context);
1941 context.check_layout(os);
1942 os << '\n' << attribute << ' ' << oldvalue << "\n";
1943 currentvalue = oldvalue;
1947 /// get the arguments of a natbib or jurabib citation command
1948 void get_cite_arguments(Parser & p, bool natbibOrder,
1949 string & before, string & after)
1951 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1953 // text before the citation
1955 // text after the citation
1956 after = p.getFullOpt();
1958 if (!after.empty()) {
1959 before = p.getFullOpt();
1960 if (natbibOrder && !before.empty())
1961 swap(before, after);
1966 /// Convert filenames with TeX macros and/or quotes to something LyX
1968 string const normalize_filename(string const & name)
1973 Token const & t = p.get_token();
1974 if (t.cat() != catEscape)
1976 else if (t.cs() == "lyxdot") {
1977 // This is used by LyX for simple dots in relative
1981 } else if (t.cs() == "space") {
1984 } else if (t.cs() == "string") {
1985 // Convert \string" to " and \string~ to ~
1986 Token const & n = p.next_token();
1987 if (n.asInput() != "\"" && n.asInput() != "~")
1992 // Strip quotes. This is a bit complicated (see latex_path()).
1993 string full = os.str();
1994 if (!full.empty() && full[0] == '"') {
1995 string base = removeExtension(full);
1996 string ext = getExtension(full);
1997 if (!base.empty() && base[base.length()-1] == '"')
2000 return addExtension(trim(base, "\""), ext);
2001 if (full[full.length()-1] == '"')
2004 return trim(full, "\"");
2010 /// Convert \p name from TeX convention (relative to master file) to LyX
2011 /// convention (relative to .lyx file) if it is relative
2012 void fix_child_filename(string & name)
2014 string const absMasterTeX = getMasterFilePath(true);
2015 bool const isabs = FileName::isAbsolute(name);
2016 // convert from "relative to .tex master" to absolute original path
2018 name = makeAbsPath(name, absMasterTeX).absFileName();
2019 bool copyfile = copyFiles();
2020 string const absParentLyX = getParentFilePath(false);
2023 // convert from absolute original path to "relative to master file"
2024 string const rel = to_utf8(makeRelPath(from_utf8(name),
2025 from_utf8(absMasterTeX)));
2026 // re-interpret "relative to .tex file" as "relative to .lyx file"
2027 // (is different if the master .lyx file resides in a
2028 // different path than the master .tex file)
2029 string const absMasterLyX = getMasterFilePath(false);
2030 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2031 // Do not copy if the new path is impossible to create. Example:
2032 // absMasterTeX = "/foo/bar/"
2033 // absMasterLyX = "/bar/"
2034 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2035 if (contains(name, "/../"))
2042 // convert from absolute original path to
2043 // "relative to .lyx file"
2044 name = to_utf8(makeRelPath(from_utf8(abs),
2045 from_utf8(absParentLyX)));
2049 // convert from absolute original path to "relative to .lyx file"
2050 name = to_utf8(makeRelPath(from_utf8(name),
2051 from_utf8(absParentLyX)));
2056 void copy_file(FileName const & src, string dstname)
2060 string const absParent = getParentFilePath(false);
2062 if (FileName::isAbsolute(dstname))
2063 dst = FileName(dstname);
2065 dst = makeAbsPath(dstname, absParent);
2066 FileName const srcpath = src.onlyPath();
2067 FileName const dstpath = dst.onlyPath();
2068 if (equivalent(srcpath, dstpath))
2070 if (!dstpath.isDirectory()) {
2071 if (!dstpath.createPath()) {
2072 cerr << "Warning: Could not create directory for file `"
2073 << dst.absFileName() << "´." << endl;
2077 if (dst.isReadableFile()) {
2078 if (overwriteFiles())
2079 cerr << "Warning: Overwriting existing file `"
2080 << dst.absFileName() << "´." << endl;
2082 cerr << "Warning: Not overwriting existing file `"
2083 << dst.absFileName() << "´." << endl;
2087 if (!src.copyTo(dst))
2088 cerr << "Warning: Could not copy file `" << src.absFileName()
2089 << "´ to `" << dst.absFileName() << "´." << endl;
2093 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2094 bool parse_chunk(Parser & p, ostream & os, Context & context)
2096 // check whether a chunk is possible here.
2097 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2103 // read the parameters
2104 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2105 if (!params.first) {
2110 Parser::Arg const code = p.verbatimStuff("\n@");
2115 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2116 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2120 // The last newline read is important for paragraph handling
2124 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2125 // We must have a valid layout before outputting the Chunk inset.
2126 context.check_layout(os);
2127 Context chunkcontext(true, context.textclass);
2128 chunkcontext.layout = &context.textclass.plainLayout();
2129 begin_inset(os, "Flex Chunk");
2130 os << "\nstatus open\n";
2131 if (!params.second.empty()) {
2132 chunkcontext.check_layout(os);
2133 Context paramscontext(true, context.textclass);
2134 paramscontext.layout = &context.textclass.plainLayout();
2135 begin_inset(os, "Argument 1");
2136 os << "\nstatus open\n";
2137 output_ert(os, params.second, paramscontext);
2140 output_ert(os, code.second, chunkcontext);
2148 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2149 bool is_macro(Parser & p)
2151 Token first = p.curr_token();
2152 if (first.cat() != catEscape || !p.good())
2154 if (first.cs() == "def")
2156 if (first.cs() != "global" && first.cs() != "long")
2158 Token second = p.get_token();
2160 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2161 second.cat() == catNewline || second.cat() == catComment)) {
2162 second = p.get_token();
2165 bool secondvalid = second.cat() == catEscape;
2167 bool thirdvalid = false;
2168 if (p.good() && first.cs() == "global" && secondvalid &&
2169 second.cs() == "long") {
2170 third = p.get_token();
2172 while (p.good() && !p.isParagraph() &&
2173 (third.cat() == catSpace ||
2174 third.cat() == catNewline ||
2175 third.cat() == catComment)) {
2176 third = p.get_token();
2179 thirdvalid = third.cat() == catEscape;
2181 for (int i = 0; i < pos; ++i)
2186 return (first.cs() == "global" || first.cs() == "long") &&
2187 second.cs() == "def";
2188 return first.cs() == "global" && second.cs() == "long" &&
2189 third.cs() == "def";
2193 /// Parse a macro definition (assumes that is_macro() returned true)
2194 void parse_macro(Parser & p, ostream & os, Context & context)
2196 context.check_layout(os);
2197 Token first = p.curr_token();
2200 string command = first.asInput();
2201 if (first.cs() != "def") {
2203 eat_whitespace(p, os, context, false);
2204 second = p.curr_token();
2205 command += second.asInput();
2206 if (second.cs() != "def") {
2208 eat_whitespace(p, os, context, false);
2209 third = p.curr_token();
2210 command += third.asInput();
2213 eat_whitespace(p, os, context, false);
2214 string const name = p.get_token().cs();
2215 eat_whitespace(p, os, context, false);
2221 while (p.next_token().cat() != catBegin) {
2222 if (p.next_token().cat() == catParameter) {
2227 // followed by number?
2228 if (p.next_token().cat() == catOther) {
2229 string s = p.get_token().asInput();
2231 // number = current arity + 1?
2232 if (s.size() == 1 && s[0] == arity + '0' + 1)
2237 paramtext += p.get_token().cs();
2239 paramtext += p.get_token().cs();
2244 // only output simple (i.e. compatible) macro as FormulaMacros
2245 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2247 context.check_layout(os);
2248 begin_inset(os, "FormulaMacro");
2249 os << "\n\\def" << ert;
2252 output_ert_inset(os, command + ert, context);
2256 void registerExternalTemplatePackages(string const & name)
2258 external::TemplateManager const & etm = external::TemplateManager::get();
2259 external::Template const * const et = etm.getTemplateByName(name);
2262 external::Template::Formats::const_iterator cit = et->formats.end();
2264 cit = et->formats.find("PDFLaTeX");
2265 if (cit == et->formats.end())
2266 // If the template has not specified a PDFLaTeX output,
2267 // we try the LaTeX format.
2268 cit = et->formats.find("LaTeX");
2269 if (cit == et->formats.end())
2271 vector<string>::const_iterator qit = cit->second.requirements.begin();
2272 vector<string>::const_iterator qend = cit->second.requirements.end();
2273 for (; qit != qend; ++qit)
2274 preamble.registerAutomaticallyLoadedPackage(*qit);
2277 } // anonymous namespace
2280 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2283 Layout const * newlayout = 0;
2284 InsetLayout const * newinsetlayout = 0;
2285 char const * const * where = 0;
2286 // Store the latest bibliographystyle, addcontentslineContent and
2287 // nocite{*} option (needed for bibtex inset)
2289 string contentslineContent;
2290 string bibliographystyle = "default";
2291 bool const use_natbib = isProvided("natbib");
2292 bool const use_jurabib = isProvided("jurabib");
2295 // it is impossible to determine the correct encoding for non-CJK Japanese.
2296 // Therefore write a note at the beginning of the document
2297 if (is_nonCJKJapanese) {
2298 context.check_layout(os);
2299 begin_inset(os, "Note Note\n");
2300 os << "status open\n\\begin_layout Plain Layout\n"
2301 << "\\series bold\n"
2302 << "Important information:\n"
2303 << "\\end_layout\n\n"
2304 << "\\begin_layout Plain Layout\n"
2305 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2306 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2307 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2308 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2309 << " and specify the encoding using the -e command-line switch.\n"
2310 << " In addition, you might want to double check that the desired output encoding\n"
2311 << " is correctly selected in Document > Settings > Language.\n"
2312 << "\\end_layout\n";
2314 is_nonCJKJapanese = false;
2318 Token const & t = p.get_token();
2320 debugToken(cerr, t, flags);
2323 if (flags & FLAG_ITEM) {
2324 if (t.cat() == catSpace)
2327 flags &= ~FLAG_ITEM;
2328 if (t.cat() == catBegin) {
2329 // skip the brace and collect everything to the next matching
2331 flags |= FLAG_BRACE_LAST;
2335 // handle only this single token, leave the loop if done
2336 flags |= FLAG_LEAVE;
2339 if (t.cat() != catEscape && t.character() == ']' &&
2340 (flags & FLAG_BRACK_LAST))
2342 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2345 // If there is anything between \end{env} and \begin{env} we
2346 // don't need to output a separator.
2347 if (t.cat() != catSpace && t.cat() != catNewline &&
2348 t.asInput() != "\\begin")
2354 bool const starred = p.next_token().asInput() == "*";
2355 string const starredname(starred ? (t.cs() + '*') : t.cs());
2356 if (t.cat() == catMath) {
2357 // we are inside some text mode thingy, so opening new math is allowed
2358 context.check_layout(os);
2359 begin_inset(os, "Formula ");
2360 Token const & n = p.get_token();
2361 bool const display(n.cat() == catMath && outer);
2363 // TeX's $$...$$ syntax for displayed math
2365 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2367 p.get_token(); // skip the second '$' token
2369 // simple $...$ stuff
2372 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2377 // Prevent the conversion of a line break to a
2378 // space (bug 7668). This does not change the
2379 // output, but looks ugly in LyX.
2380 eat_whitespace(p, os, context, false);
2384 else if (t.cat() == catSuper || t.cat() == catSub)
2385 cerr << "catcode " << t << " illegal in text mode\n";
2387 // Basic support for english quotes. This should be
2388 // extended to other quotes, but is not so easy (a
2389 // left english quote is the same as a right german
2391 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2392 context.check_layout(os);
2393 begin_inset(os, "Quotes ");
2399 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2400 context.check_layout(os);
2401 begin_inset(os, "Quotes ");
2408 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2409 context.check_layout(os);
2410 begin_inset(os, "Quotes ");
2417 else if (t.asInput() == "<"
2418 && p.next_token().asInput() == "<") {
2419 bool has_chunk = false;
2423 has_chunk = parse_chunk(p, os, context);
2429 context.check_layout(os);
2430 begin_inset(os, "Quotes ");
2431 //FIXME: this is a right danish quote;
2432 // why not a left french quote?
2440 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2441 check_space(p, os, context);
2443 else if (t.character() == '[' && noweb_mode &&
2444 p.next_token().character() == '[') {
2445 // These can contain underscores
2447 string const s = p.getFullOpt() + ']';
2448 if (p.next_token().character() == ']')
2451 cerr << "Warning: Inserting missing ']' in '"
2452 << s << "'." << endl;
2453 output_ert_inset(os, s, context);
2456 else if (t.cat() == catLetter) {
2457 context.check_layout(os);
2461 else if (t.cat() == catOther ||
2462 t.cat() == catAlign ||
2463 t.cat() == catParameter) {
2464 context.check_layout(os);
2465 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2466 context.merging_hyphens_allowed &&
2467 context.font.family != "ttfamily" &&
2468 !context.layout->pass_thru) {
2469 if (p.next_next_token().asInput() == "-") {
2471 os << to_utf8(docstring(1, 0x2014));
2475 os << to_utf8(docstring(1, 0x2013));
2478 // This translates "&" to "\\&" which may be wrong...
2482 else if (p.isParagraph()) {
2483 if (context.new_layout_allowed)
2484 context.new_paragraph(os);
2486 output_ert_inset(os, "\\par ", context);
2487 eat_whitespace(p, os, context, true);
2490 else if (t.cat() == catActive) {
2491 context.check_layout(os);
2492 if (t.character() == '~') {
2493 if (context.layout->free_spacing)
2496 begin_inset(os, "space ~\n");
2503 else if (t.cat() == catBegin) {
2504 Token const next = p.next_token();
2505 Token const end = p.next_next_token();
2506 if (next.cat() == catEnd) {
2508 Token const prev = p.prev_token();
2510 if (p.next_token().character() == '`')
2511 ; // ignore it in {}``
2513 output_ert_inset(os, "{}", context);
2514 } else if (next.cat() == catEscape &&
2515 is_known(next.cs(), known_quotes) &&
2516 end.cat() == catEnd) {
2517 // Something like {\textquoteright} (e.g.
2518 // from writer2latex). LyX writes
2519 // \textquoteright{}, so we may skip the
2520 // braces here for better readability.
2521 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2523 } else if (p.next_token().asInput() == "\\ascii") {
2524 // handle the \ascii characters
2525 // (the case without braces is handled later)
2526 // the code is "{\ascii\xxx}"
2527 p.get_token(); // eat \ascii
2528 string name2 = p.get_token().asInput();
2529 p.get_token(); // eat the final '}'
2530 string const name = "{\\ascii" + name2 + "}";
2534 // get the character from unicodesymbols
2535 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2536 Encodings::TEXT_CMD, termination, rem, &req);
2538 context.check_layout(os);
2541 output_ert_inset(os,
2542 to_utf8(rem), context);
2543 for (set<string>::const_iterator it = req.begin();
2544 it != req.end(); ++it)
2545 preamble.registerAutomaticallyLoadedPackage(*it);
2547 // we did not find a non-ert version
2548 output_ert_inset(os, name, context);
2550 context.check_layout(os);
2551 // special handling of font attribute changes
2552 Token const prev = p.prev_token();
2553 TeXFont const oldFont = context.font;
2554 if (next.character() == '[' ||
2555 next.character() == ']' ||
2556 next.character() == '*') {
2558 if (p.next_token().cat() == catEnd) {
2563 output_ert_inset(os, "{", context);
2564 parse_text_snippet(p, os,
2567 output_ert_inset(os, "}", context);
2569 } else if (! context.new_layout_allowed) {
2570 output_ert_inset(os, "{", context);
2571 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2573 output_ert_inset(os, "}", context);
2574 } else if (is_known(next.cs(), known_sizes)) {
2575 // next will change the size, so we must
2577 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2579 if (!context.atParagraphStart())
2581 << context.font.size << "\n";
2582 } else if (is_known(next.cs(), known_font_families)) {
2583 // next will change the font family, so we
2584 // must reset it here
2585 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2587 if (!context.atParagraphStart())
2589 << context.font.family << "\n";
2590 } else if (is_known(next.cs(), known_font_series)) {
2591 // next will change the font series, so we
2592 // must reset it here
2593 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2595 if (!context.atParagraphStart())
2597 << context.font.series << "\n";
2598 } else if (is_known(next.cs(), known_font_shapes)) {
2599 // next will change the font shape, so we
2600 // must reset it here
2601 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2603 if (!context.atParagraphStart())
2605 << context.font.shape << "\n";
2606 } else if (is_known(next.cs(), known_old_font_families) ||
2607 is_known(next.cs(), known_old_font_series) ||
2608 is_known(next.cs(), known_old_font_shapes)) {
2609 // next will change the font family, series
2610 // and shape, so we must reset it here
2611 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2613 if (!context.atParagraphStart())
2615 << context.font.family
2617 << context.font.series
2619 << context.font.shape << "\n";
2621 output_ert_inset(os, "{", context);
2622 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2624 output_ert_inset(os, "}", context);
2629 else if (t.cat() == catEnd) {
2630 if (flags & FLAG_BRACE_LAST) {
2633 cerr << "stray '}' in text\n";
2634 output_ert_inset(os, "}", context);
2637 else if (t.cat() == catComment)
2638 parse_comment(p, os, t, context);
2641 // control sequences
2644 else if (t.cs() == "(" || t.cs() == "[") {
2645 bool const simple = t.cs() == "(";
2646 context.check_layout(os);
2647 begin_inset(os, "Formula");
2648 os << " \\" << t.cs();
2649 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2650 os << '\\' << (simple ? ')' : ']');
2653 // Prevent the conversion of a line break to a
2654 // space (bug 7668). This does not change the
2655 // output, but looks ugly in LyX.
2656 eat_whitespace(p, os, context, false);
2660 else if (t.cs() == "begin")
2661 parse_environment(p, os, outer, last_env,
2664 else if (t.cs() == "end") {
2665 if (flags & FLAG_END) {
2666 // eat environment name
2667 string const name = p.getArg('{', '}');
2668 if (name != active_environment())
2669 cerr << "\\end{" + name + "} does not match \\begin{"
2670 + active_environment() + "}\n";
2673 p.error("found 'end' unexpectedly");
2676 else if (t.cs() == "item") {
2678 bool const optarg = p.hasOpt();
2680 // FIXME: This swallows comments, but we cannot use
2681 // eat_whitespace() since we must not output
2682 // anything before the item.
2683 p.skip_spaces(true);
2684 s = p.verbatimOption();
2686 p.skip_spaces(false);
2688 context.check_layout(os);
2689 if (context.has_item) {
2690 // An item in an unknown list-like environment
2691 // FIXME: Do this in check_layout()!
2692 context.has_item = false;
2694 output_ert_inset(os, "\\item", context);
2696 output_ert_inset(os, "\\item ", context);
2699 if (context.layout->labeltype != LABEL_MANUAL) {
2700 // handle option of itemize item
2701 begin_inset(os, "Argument item:1\n");
2702 os << "status open\n";
2703 os << "\n\\begin_layout Plain Layout\n";
2705 os << parse_text_snippet(p2,
2706 FLAG_BRACK_LAST, outer, context);
2707 // we must not use context.check_end_layout(os)
2708 // because that would close the outer itemize layout
2709 os << "\n\\end_layout\n";
2711 eat_whitespace(p, os, context, false);
2712 } else if (!s.empty()) {
2713 // LyX adds braces around the argument,
2714 // so we need to remove them here.
2715 if (s.size() > 2 && s[0] == '{' &&
2716 s[s.size()-1] == '}')
2717 s = s.substr(1, s.size()-2);
2718 // If the argument contains a space we
2719 // must put it into ERT: Otherwise LyX
2720 // would misinterpret the space as
2721 // item delimiter (bug 7663)
2722 if (contains(s, ' ')) {
2723 output_ert_inset(os, s, context);
2726 os << parse_text_snippet(p2,
2727 FLAG_BRACK_LAST, outer, context);
2729 // The space is needed to separate the
2730 // item from the rest of the sentence.
2732 eat_whitespace(p, os, context, false);
2737 else if (t.cs() == "bibitem") {
2739 context.check_layout(os);
2740 eat_whitespace(p, os, context, false);
2741 string label = convert_command_inset_arg(p.verbatimOption());
2742 string key = convert_command_inset_arg(p.verbatim_item());
2743 if (contains(label, '\\') || contains(key, '\\')) {
2744 // LyX can't handle LaTeX commands in labels or keys
2745 output_ert_inset(os, t.asInput() + '[' + label +
2746 "]{" + p.verbatim_item() + '}',
2749 begin_command_inset(os, "bibitem", "bibitem");
2750 os << "label \"" << label << "\"\n"
2751 "key \"" << key << "\"\n";
2756 else if (is_macro(p)) {
2757 // catch the case of \def\inputGnumericTable
2759 if (t.cs() == "def") {
2760 Token second = p.next_token();
2761 if (second.cs() == "inputGnumericTable") {
2765 Token third = p.get_token();
2767 if (third.cs() == "input") {
2771 string name = normalize_filename(p.verbatim_item());
2772 string const path = getMasterFilePath(true);
2773 // We want to preserve relative / absolute filenames,
2774 // therefore path is only used for testing
2775 // The file extension is in every case ".tex".
2776 // So we need to remove this extension and check for
2777 // the original one.
2778 name = removeExtension(name);
2779 if (!makeAbsPath(name, path).exists()) {
2780 char const * const Gnumeric_formats[] = {"gnumeric",
2782 string const Gnumeric_name =
2783 find_file(name, path, Gnumeric_formats);
2784 if (!Gnumeric_name.empty())
2785 name = Gnumeric_name;
2787 FileName const absname = makeAbsPath(name, path);
2788 if (absname.exists()) {
2789 fix_child_filename(name);
2790 copy_file(absname, name);
2792 cerr << "Warning: Could not find file '"
2793 << name << "'." << endl;
2794 context.check_layout(os);
2795 begin_inset(os, "External\n\ttemplate ");
2796 os << "GnumericSpreadsheet\n\tfilename "
2799 context.check_layout(os);
2801 // register the packages that are automatically loaded
2802 // by the Gnumeric template
2803 registerExternalTemplatePackages("GnumericSpreadsheet");
2808 parse_macro(p, os, context);
2811 else if (t.cs() == "noindent") {
2813 context.add_par_extra_stuff("\\noindent\n");
2816 else if (t.cs() == "appendix") {
2817 context.add_par_extra_stuff("\\start_of_appendix\n");
2818 // We need to start a new paragraph. Otherwise the
2819 // appendix in 'bla\appendix\chapter{' would start
2821 context.new_paragraph(os);
2822 // We need to make sure that the paragraph is
2823 // generated even if it is empty. Otherwise the
2824 // appendix in '\par\appendix\par\chapter{' would
2826 context.check_layout(os);
2827 // FIXME: This is a hack to prevent paragraph
2828 // deletion if it is empty. Handle this better!
2829 output_ert_inset(os,
2830 "%dummy comment inserted by tex2lyx to "
2831 "ensure that this paragraph is not empty",
2833 // Both measures above may generate an additional
2834 // empty paragraph, but that does not hurt, because
2835 // whitespace does not matter here.
2836 eat_whitespace(p, os, context, true);
2839 // Must catch empty dates before findLayout is called below
2840 else if (t.cs() == "date") {
2841 eat_whitespace(p, os, context, false);
2843 string const date = p.verbatim_item();
2846 preamble.suppressDate(true);
2849 preamble.suppressDate(false);
2850 if (context.new_layout_allowed &&
2851 (newlayout = findLayout(context.textclass,
2854 output_command_layout(os, p, outer,
2855 context, newlayout);
2856 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2857 if (!preamble.titleLayoutFound())
2858 preamble.titleLayoutFound(newlayout->intitle);
2859 set<string> const & req = newlayout->requires();
2860 set<string>::const_iterator it = req.begin();
2861 set<string>::const_iterator en = req.end();
2862 for (; it != en; ++it)
2863 preamble.registerAutomaticallyLoadedPackage(*it);
2865 output_ert_inset(os,
2866 "\\date{" + p.verbatim_item() + '}',
2871 // Starred section headings
2872 // Must attempt to parse "Section*" before "Section".
2873 else if ((p.next_token().asInput() == "*") &&
2874 context.new_layout_allowed &&
2875 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2878 output_command_layout(os, p, outer, context, newlayout);
2880 if (!preamble.titleLayoutFound())
2881 preamble.titleLayoutFound(newlayout->intitle);
2882 set<string> const & req = newlayout->requires();
2883 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2884 preamble.registerAutomaticallyLoadedPackage(*it);
2887 // Section headings and the like
2888 else if (context.new_layout_allowed &&
2889 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2891 output_command_layout(os, p, outer, context, newlayout);
2893 if (!preamble.titleLayoutFound())
2894 preamble.titleLayoutFound(newlayout->intitle);
2895 set<string> const & req = newlayout->requires();
2896 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2897 preamble.registerAutomaticallyLoadedPackage(*it);
2900 else if (t.cs() == "subfloat") {
2901 // the syntax is \subfloat[list entry][sub caption]{content}
2902 // if it is a table of figure depends on the surrounding float
2903 // FIXME: second optional argument is not parsed
2905 // do nothing if there is no outer float
2906 if (!float_type.empty()) {
2907 context.check_layout(os);
2909 begin_inset(os, "Float " + float_type + "\n");
2911 << "\nsideways false"
2912 << "\nstatus collapsed\n\n";
2915 bool has_caption = false;
2916 if (p.next_token().cat() != catEscape &&
2917 p.next_token().character() == '[') {
2918 p.get_token(); // eat '['
2919 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2923 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2924 // the caption comes always as the last
2926 // we must make sure that the caption gets a \begin_layout
2927 os << "\n\\begin_layout Plain Layout";
2929 begin_inset(os, "Caption Standard\n");
2930 Context newcontext(true, context.textclass,
2931 0, 0, context.font);
2932 newcontext.check_layout(os);
2933 os << caption << "\n";
2934 newcontext.check_end_layout(os);
2935 // We don't need really a new paragraph, but
2936 // we must make sure that the next item gets a \begin_layout.
2937 //newcontext.new_paragraph(os);
2941 // We don't need really a new paragraph, but
2942 // we must make sure that the next item gets a \begin_layout.
2944 context.new_paragraph(os);
2947 context.check_end_layout(os);
2948 // close the layout we opened
2950 os << "\n\\end_layout\n";
2952 // if the float type is not supported or there is no surrounding float
2955 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2956 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2957 "]{" + p.verbatim_item() + '}', context);
2959 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2963 else if (t.cs() == "includegraphics") {
2964 bool const clip = p.next_token().asInput() == "*";
2967 string const arg = p.getArg('[', ']');
2968 map<string, string> opts;
2969 vector<string> keys;
2970 split_map(arg, opts, keys);
2972 opts["clip"] = string();
2973 string name = normalize_filename(p.verbatim_item());
2975 string const path = getMasterFilePath(true);
2976 // We want to preserve relative / absolute filenames,
2977 // therefore path is only used for testing
2978 if (!makeAbsPath(name, path).exists()) {
2979 // The file extension is probably missing.
2980 // Now try to find it out.
2981 string const dvips_name =
2982 find_file(name, path,
2983 known_dvips_graphics_formats);
2984 string const pdftex_name =
2985 find_file(name, path,
2986 known_pdftex_graphics_formats);
2987 if (!dvips_name.empty()) {
2988 if (!pdftex_name.empty()) {
2989 cerr << "This file contains the "
2991 "\"\\includegraphics{"
2993 "However, files\n\""
2994 << dvips_name << "\" and\n\""
2995 << pdftex_name << "\"\n"
2996 "both exist, so I had to make a "
2997 "choice and took the first one.\n"
2998 "Please move the unwanted one "
2999 "someplace else and try again\n"
3000 "if my choice was wrong."
3004 } else if (!pdftex_name.empty()) {
3010 FileName const absname = makeAbsPath(name, path);
3011 if (absname.exists()) {
3012 fix_child_filename(name);
3013 copy_file(absname, name);
3015 cerr << "Warning: Could not find graphics file '"
3016 << name << "'." << endl;
3018 context.check_layout(os);
3019 begin_inset(os, "Graphics ");
3020 os << "\n\tfilename " << name << '\n';
3021 if (opts.find("width") != opts.end())
3023 << translate_len(opts["width"]) << '\n';
3024 if (opts.find("height") != opts.end())
3026 << translate_len(opts["height"]) << '\n';
3027 if (opts.find("scale") != opts.end()) {
3028 istringstream iss(opts["scale"]);
3032 os << "\tscale " << val << '\n';
3034 if (opts.find("angle") != opts.end()) {
3035 os << "\trotateAngle "
3036 << opts["angle"] << '\n';
3037 vector<string>::const_iterator a =
3038 find(keys.begin(), keys.end(), "angle");
3039 vector<string>::const_iterator s =
3040 find(keys.begin(), keys.end(), "width");
3041 if (s == keys.end())
3042 s = find(keys.begin(), keys.end(), "height");
3043 if (s == keys.end())
3044 s = find(keys.begin(), keys.end(), "scale");
3045 if (s != keys.end() && distance(s, a) > 0)
3046 os << "\tscaleBeforeRotation\n";
3048 if (opts.find("origin") != opts.end()) {
3050 string const opt = opts["origin"];
3051 if (opt.find('l') != string::npos) ss << "left";
3052 if (opt.find('r') != string::npos) ss << "right";
3053 if (opt.find('c') != string::npos) ss << "center";
3054 if (opt.find('t') != string::npos) ss << "Top";
3055 if (opt.find('b') != string::npos) ss << "Bottom";
3056 if (opt.find('B') != string::npos) ss << "Baseline";
3057 if (!ss.str().empty())
3058 os << "\trotateOrigin " << ss.str() << '\n';
3060 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3062 if (opts.find("keepaspectratio") != opts.end())
3063 os << "\tkeepAspectRatio\n";
3064 if (opts.find("clip") != opts.end())
3066 if (opts.find("draft") != opts.end())
3068 if (opts.find("bb") != opts.end())
3069 os << "\tBoundingBox "
3070 << opts["bb"] << '\n';
3071 int numberOfbbOptions = 0;
3072 if (opts.find("bbllx") != opts.end())
3073 numberOfbbOptions++;
3074 if (opts.find("bblly") != opts.end())
3075 numberOfbbOptions++;
3076 if (opts.find("bburx") != opts.end())
3077 numberOfbbOptions++;
3078 if (opts.find("bbury") != opts.end())
3079 numberOfbbOptions++;
3080 if (numberOfbbOptions == 4)
3081 os << "\tBoundingBox "
3082 << opts["bbllx"] << " " << opts["bblly"] << " "
3083 << opts["bburx"] << " " << opts["bbury"] << '\n';
3084 else if (numberOfbbOptions > 0)
3085 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3086 numberOfbbOptions = 0;
3087 if (opts.find("natwidth") != opts.end())
3088 numberOfbbOptions++;
3089 if (opts.find("natheight") != opts.end())
3090 numberOfbbOptions++;
3091 if (numberOfbbOptions == 2)
3092 os << "\tBoundingBox 0bp 0bp "
3093 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3094 else if (numberOfbbOptions > 0)
3095 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3096 ostringstream special;
3097 if (opts.find("hiresbb") != opts.end())
3098 special << "hiresbb,";
3099 if (opts.find("trim") != opts.end())
3101 if (opts.find("viewport") != opts.end())
3102 special << "viewport=" << opts["viewport"] << ',';
3103 if (opts.find("totalheight") != opts.end())
3104 special << "totalheight=" << opts["totalheight"] << ',';
3105 if (opts.find("type") != opts.end())
3106 special << "type=" << opts["type"] << ',';
3107 if (opts.find("ext") != opts.end())
3108 special << "ext=" << opts["ext"] << ',';
3109 if (opts.find("read") != opts.end())
3110 special << "read=" << opts["read"] << ',';
3111 if (opts.find("command") != opts.end())
3112 special << "command=" << opts["command"] << ',';
3113 string s_special = special.str();
3114 if (!s_special.empty()) {
3115 // We had special arguments. Remove the trailing ','.
3116 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3118 // TODO: Handle the unknown settings better.
3119 // Warn about invalid options.
3120 // Check whether some option was given twice.
3122 preamble.registerAutomaticallyLoadedPackage("graphicx");
3125 else if (t.cs() == "footnote" ||
3126 (t.cs() == "thanks" && context.layout->intitle)) {
3128 context.check_layout(os);
3129 begin_inset(os, "Foot\n");
3130 os << "status collapsed\n\n";
3131 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3135 else if (t.cs() == "marginpar") {
3137 context.check_layout(os);
3138 begin_inset(os, "Marginal\n");
3139 os << "status collapsed\n\n";
3140 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3144 else if (t.cs() == "lstinline") {
3146 parse_listings(p, os, context, true);
3149 else if (t.cs() == "ensuremath") {
3151 context.check_layout(os);
3152 string const s = p.verbatim_item();
3153 //FIXME: this never triggers in UTF8
3154 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3157 output_ert_inset(os, "\\ensuremath{" + s + "}",
3161 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3162 if (preamble.titleLayoutFound()) {
3164 skip_spaces_braces(p);
3166 output_ert_inset(os, t.asInput(), context);
3169 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3170 context.check_layout(os);
3171 begin_command_inset(os, "toc", t.cs());
3173 skip_spaces_braces(p);
3174 if (t.cs() == "lstlistoflistings")
3175 preamble.registerAutomaticallyLoadedPackage("listings");
3178 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3179 context.check_layout(os);
3180 if (t.cs() == "listoffigures")
3181 begin_inset(os, "FloatList figure\n");
3183 begin_inset(os, "FloatList table\n");
3185 skip_spaces_braces(p);
3188 else if (t.cs() == "listof") {
3189 p.skip_spaces(true);
3190 string const name = p.get_token().cs();
3191 if (context.textclass.floats().typeExist(name)) {
3192 context.check_layout(os);
3193 begin_inset(os, "FloatList ");
3196 p.get_token(); // swallow second arg
3198 output_ert_inset(os, "\\listof{" + name + "}", context);
3201 else if ((where = is_known(t.cs(), known_text_font_families)))
3202 parse_text_attributes(p, os, FLAG_ITEM, outer,
3203 context, "\\family", context.font.family,
3204 known_coded_font_families[where - known_text_font_families]);
3206 else if ((where = is_known(t.cs(), known_text_font_series)))
3207 parse_text_attributes(p, os, FLAG_ITEM, outer,
3208 context, "\\series", context.font.series,
3209 known_coded_font_series[where - known_text_font_series]);
3211 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3212 parse_text_attributes(p, os, FLAG_ITEM, outer,
3213 context, "\\shape", context.font.shape,
3214 known_coded_font_shapes[where - known_text_font_shapes]);
3216 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3217 context.check_layout(os);
3218 TeXFont oldFont = context.font;
3219 context.font.init();
3220 context.font.size = oldFont.size;
3221 os << "\n\\family " << context.font.family << "\n";
3222 os << "\n\\series " << context.font.series << "\n";
3223 os << "\n\\shape " << context.font.shape << "\n";
3224 if (t.cs() == "textnormal") {
3225 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3226 output_font_change(os, context.font, oldFont);
3227 context.font = oldFont;
3229 eat_whitespace(p, os, context, false);
3232 else if (t.cs() == "textcolor") {
3233 // scheme is \textcolor{color name}{text}
3234 string const color = p.verbatim_item();
3235 // we support the predefined colors of the color and the xcolor package
3236 if (color == "black" || color == "blue" || color == "cyan"
3237 || color == "green" || color == "magenta" || color == "red"
3238 || color == "white" || color == "yellow") {
3239 context.check_layout(os);
3240 os << "\n\\color " << color << "\n";
3241 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3242 context.check_layout(os);
3243 os << "\n\\color inherit\n";
3244 preamble.registerAutomaticallyLoadedPackage("color");
3245 } else if (color == "brown" || color == "darkgray" || color == "gray"
3246 || color == "lightgray" || color == "lime" || color == "olive"
3247 || color == "orange" || color == "pink" || color == "purple"
3248 || color == "teal" || color == "violet") {
3249 context.check_layout(os);
3250 os << "\n\\color " << color << "\n";
3251 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3252 context.check_layout(os);
3253 os << "\n\\color inherit\n";
3254 preamble.registerAutomaticallyLoadedPackage("xcolor");
3256 // for custom defined colors
3257 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3260 else if (t.cs() == "underbar" || t.cs() == "uline") {
3261 // \underbar is not 100% correct (LyX outputs \uline
3262 // of ulem.sty). The difference is that \ulem allows
3263 // line breaks, and \underbar does not.
3264 // Do NOT handle \underline.
3265 // \underbar cuts through y, g, q, p etc.,
3266 // \underline does not.
3267 context.check_layout(os);
3268 os << "\n\\bar under\n";
3269 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3270 context.check_layout(os);
3271 os << "\n\\bar default\n";
3272 preamble.registerAutomaticallyLoadedPackage("ulem");
3275 else if (t.cs() == "sout") {
3276 context.check_layout(os);
3277 os << "\n\\strikeout on\n";
3278 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3279 context.check_layout(os);
3280 os << "\n\\strikeout default\n";
3281 preamble.registerAutomaticallyLoadedPackage("ulem");
3284 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3285 t.cs() == "emph" || t.cs() == "noun") {
3286 context.check_layout(os);
3287 os << "\n\\" << t.cs() << " on\n";
3288 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3289 context.check_layout(os);
3290 os << "\n\\" << t.cs() << " default\n";
3291 if (t.cs() == "uuline" || t.cs() == "uwave")
3292 preamble.registerAutomaticallyLoadedPackage("ulem");
3295 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3296 context.check_layout(os);
3297 string name = p.getArg('{', '}');
3298 string localtime = p.getArg('{', '}');
3299 preamble.registerAuthor(name);
3300 Author const & author = preamble.getAuthor(name);
3301 // from_asctime_utc() will fail if LyX decides to output the
3302 // time in the text language.
3303 time_t ptime = from_asctime_utc(localtime);
3304 if (ptime == static_cast<time_t>(-1)) {
3305 cerr << "Warning: Could not parse time `" << localtime
3306 << "´ for change tracking, using current time instead.\n";
3307 ptime = current_time();
3309 if (t.cs() == "lyxadded")
3310 os << "\n\\change_inserted ";
3312 os << "\n\\change_deleted ";
3313 os << author.bufferId() << ' ' << ptime << '\n';
3314 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3315 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3316 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3317 LaTeXPackages::isAvailable("xcolor");
3318 // No need to test for luatex, since luatex comes in
3319 // two flavours (dvi and pdf), like latex, and those
3320 // are detected by pdflatex.
3321 if (pdflatex || xetex) {
3323 preamble.registerAutomaticallyLoadedPackage("ulem");
3324 preamble.registerAutomaticallyLoadedPackage("xcolor");
3325 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3329 preamble.registerAutomaticallyLoadedPackage("dvipost");
3330 } else if (xcolorulem) {
3331 preamble.registerAutomaticallyLoadedPackage("ulem");
3332 preamble.registerAutomaticallyLoadedPackage("xcolor");
3337 else if (t.cs() == "textipa") {
3338 context.check_layout(os);
3339 begin_inset(os, "IPA\n");
3340 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3341 context.merging_hyphens_allowed = false;
3342 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3343 context.merging_hyphens_allowed = merging_hyphens_allowed;
3345 preamble.registerAutomaticallyLoadedPackage("tipa");
3346 preamble.registerAutomaticallyLoadedPackage("tipx");
3349 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3350 context.check_layout(os);
3351 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3352 os << "status open\n";
3353 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3358 else if (t.cs() == "textvertline") {
3359 // FIXME: This is not correct, \textvertline is higher than |
3365 else if (t.cs() == "tone" ) {
3366 context.check_layout(os);
3367 // register the tone package
3368 preamble.registerAutomaticallyLoadedPackage("tone");
3369 string content = trimSpaceAndEol(p.verbatim_item());
3370 string command = t.asInput() + "{" + content + "}";
3371 // some tones can be detected by unicodesymbols, some need special code
3372 if (is_known(content, known_tones)) {
3373 os << "\\IPAChar " << command << "\n";
3376 // try to see whether the string is in unicodesymbols
3380 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3381 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3382 termination, rem, &req);
3386 output_ert_inset(os, to_utf8(rem), context);
3387 for (set<string>::const_iterator it = req.begin();
3388 it != req.end(); ++it)
3389 preamble.registerAutomaticallyLoadedPackage(*it);
3391 // we did not find a non-ert version
3392 output_ert_inset(os, command, context);
3395 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3396 t.cs() == "vphantom") {
3397 context.check_layout(os);
3398 if (t.cs() == "phantom")
3399 begin_inset(os, "Phantom Phantom\n");
3400 if (t.cs() == "hphantom")
3401 begin_inset(os, "Phantom HPhantom\n");
3402 if (t.cs() == "vphantom")
3403 begin_inset(os, "Phantom VPhantom\n");
3404 os << "status open\n";
3405 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3410 else if (t.cs() == "href") {
3411 context.check_layout(os);
3412 string target = convert_command_inset_arg(p.verbatim_item());
3413 string name = convert_command_inset_arg(p.verbatim_item());
3415 size_t i = target.find(':');
3416 if (i != string::npos) {
3417 type = target.substr(0, i + 1);
3418 if (type == "mailto:" || type == "file:")
3419 target = target.substr(i + 1);
3420 // handle the case that name is equal to target, except of "http://"
3421 else if (target.substr(i + 3) == name && type == "http:")
3424 begin_command_inset(os, "href", "href");
3426 os << "name \"" << name << "\"\n";
3427 os << "target \"" << target << "\"\n";
3428 if (type == "mailto:" || type == "file:")
3429 os << "type \"" << type << "\"\n";
3431 skip_spaces_braces(p);
3434 else if (t.cs() == "lyxline") {
3435 // swallow size argument (it is not used anyway)
3437 if (!context.atParagraphStart()) {
3438 // so our line is in the middle of a paragraph
3439 // we need to add a new line, lest this line
3440 // follow the other content on that line and
3441 // run off the side of the page
3442 // FIXME: This may create an empty paragraph,
3443 // but without that it would not be
3444 // possible to set noindent below.
3445 // Fortunately LaTeX does not care
3446 // about the empty paragraph.
3447 context.new_paragraph(os);
3449 if (preamble.indentParagraphs()) {
3450 // we need to unindent, lest the line be too long
3451 context.add_par_extra_stuff("\\noindent\n");
3453 context.check_layout(os);
3454 begin_command_inset(os, "line", "rule");
3455 os << "offset \"0.5ex\"\n"
3456 "width \"100line%\"\n"
3461 else if (t.cs() == "rule") {
3462 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3463 string const width = p.getArg('{', '}');
3464 string const thickness = p.getArg('{', '}');
3465 context.check_layout(os);
3466 begin_command_inset(os, "line", "rule");
3467 if (!offset.empty())
3468 os << "offset \"" << translate_len(offset) << "\"\n";
3469 os << "width \"" << translate_len(width) << "\"\n"
3470 "height \"" << translate_len(thickness) << "\"\n";
3474 // handle refstyle first to catch \eqref which can also occur
3475 // without refstyle. Only recognize these commands if
3476 // refstyle.sty was found in the preamble (otherwise \eqref
3477 // and user defined ref commands could be misdetected).
3478 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3479 preamble.refstyle()) {
3480 context.check_layout(os);
3481 begin_command_inset(os, "ref", "formatted");
3482 os << "reference \"";
3483 os << known_refstyle_prefixes[where - known_refstyle_commands]
3485 os << convert_command_inset_arg(p.verbatim_item())
3488 preamble.registerAutomaticallyLoadedPackage("refstyle");
3491 // if refstyle is used, we must not convert \prettyref to a
3492 // formatted reference, since that would result in a refstyle command.
3493 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3494 (t.cs() != "prettyref" || !preamble.refstyle())) {
3495 string const opt = p.getOpt();
3497 context.check_layout(os);
3498 begin_command_inset(os, "ref",
3499 known_coded_ref_commands[where - known_ref_commands]);
3500 os << "reference \""
3501 << convert_command_inset_arg(p.verbatim_item())
3504 if (t.cs() == "vref" || t.cs() == "vpageref")
3505 preamble.registerAutomaticallyLoadedPackage("varioref");
3506 else if (t.cs() == "prettyref")
3507 preamble.registerAutomaticallyLoadedPackage("prettyref");
3509 // LyX does not yet support optional arguments of ref commands
3510 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3511 p.verbatim_item() + '}', context);
3515 else if (use_natbib &&
3516 is_known(t.cs(), known_natbib_commands) &&
3517 ((t.cs() != "citefullauthor" &&
3518 t.cs() != "citeyear" &&
3519 t.cs() != "citeyearpar") ||
3520 p.next_token().asInput() != "*")) {
3521 context.check_layout(os);
3522 string command = t.cs();
3523 if (p.next_token().asInput() == "*") {
3527 if (command == "citefullauthor")
3528 // alternative name for "\\citeauthor*"
3529 command = "citeauthor*";
3531 // text before the citation
3533 // text after the citation
3535 get_cite_arguments(p, true, before, after);
3537 if (command == "cite") {
3538 // \cite without optional argument means
3539 // \citet, \cite with at least one optional
3540 // argument means \citep.
3541 if (before.empty() && after.empty())
3546 if (before.empty() && after == "[]")
3547 // avoid \citet[]{a}
3549 else if (before == "[]" && after == "[]") {
3550 // avoid \citet[][]{a}
3554 // remove the brackets around after and before
3555 if (!after.empty()) {
3557 after.erase(after.length() - 1, 1);
3558 after = convert_command_inset_arg(after);
3560 if (!before.empty()) {
3562 before.erase(before.length() - 1, 1);
3563 before = convert_command_inset_arg(before);
3565 begin_command_inset(os, "citation", command);
3566 os << "after " << '"' << after << '"' << "\n";
3567 os << "before " << '"' << before << '"' << "\n";
3569 << convert_command_inset_arg(p.verbatim_item())
3572 // Need to set the cite engine if natbib is loaded by
3573 // the document class directly
3574 if (preamble.citeEngine() == "basic")
3575 preamble.citeEngine("natbib");
3578 else if (use_jurabib &&
3579 is_known(t.cs(), known_jurabib_commands) &&
3580 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3581 context.check_layout(os);
3582 string command = t.cs();
3583 if (p.next_token().asInput() == "*") {
3587 char argumentOrder = '\0';
3588 vector<string> const options =
3589 preamble.getPackageOptions("jurabib");
3590 if (find(options.begin(), options.end(),
3591 "natbiborder") != options.end())
3592 argumentOrder = 'n';
3593 else if (find(options.begin(), options.end(),
3594 "jurabiborder") != options.end())
3595 argumentOrder = 'j';
3597 // text before the citation
3599 // text after the citation
3601 get_cite_arguments(p, argumentOrder != 'j', before, after);
3603 string const citation = p.verbatim_item();
3604 if (!before.empty() && argumentOrder == '\0') {
3605 cerr << "Warning: Assuming argument order "
3606 "of jurabib version 0.6 for\n'"
3607 << command << before << after << '{'
3608 << citation << "}'.\n"
3609 "Add 'jurabiborder' to the jurabib "
3610 "package options if you used an\n"
3611 "earlier jurabib version." << endl;
3613 if (!after.empty()) {
3615 after.erase(after.length() - 1, 1);
3617 if (!before.empty()) {
3619 before.erase(before.length() - 1, 1);
3621 begin_command_inset(os, "citation", command);
3622 os << "after " << '"' << after << '"' << "\n";
3623 os << "before " << '"' << before << '"' << "\n";
3624 os << "key " << '"' << citation << '"' << "\n";
3626 // Need to set the cite engine if jurabib is loaded by
3627 // the document class directly
3628 if (preamble.citeEngine() == "basic")
3629 preamble.citeEngine("jurabib");
3632 else if (t.cs() == "cite"
3633 || t.cs() == "nocite") {
3634 context.check_layout(os);
3635 string after = convert_command_inset_arg(p.getArg('[', ']'));
3636 string key = convert_command_inset_arg(p.verbatim_item());
3637 // store the case that it is "\nocite{*}" to use it later for
3640 begin_command_inset(os, "citation", t.cs());
3641 os << "after " << '"' << after << '"' << "\n";
3642 os << "key " << '"' << key << '"' << "\n";
3644 } else if (t.cs() == "nocite")
3648 else if (t.cs() == "index" ||
3649 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3650 context.check_layout(os);
3651 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3652 p.getArg('[', ']') : "";
3653 string const kind = arg.empty() ? "idx" : arg;
3654 begin_inset(os, "Index ");
3655 os << kind << "\nstatus collapsed\n";
3656 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3659 preamble.registerAutomaticallyLoadedPackage("splitidx");
3662 else if (t.cs() == "nomenclature") {
3663 context.check_layout(os);
3664 begin_command_inset(os, "nomenclature", "nomenclature");
3665 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3666 if (!prefix.empty())
3667 os << "prefix " << '"' << prefix << '"' << "\n";
3668 os << "symbol " << '"'
3669 << convert_command_inset_arg(p.verbatim_item());
3670 os << "\"\ndescription \""
3671 << convert_command_inset_arg(p.verbatim_item())
3674 preamble.registerAutomaticallyLoadedPackage("nomencl");
3677 else if (t.cs() == "label") {
3678 context.check_layout(os);
3679 begin_command_inset(os, "label", "label");
3681 << convert_command_inset_arg(p.verbatim_item())
3686 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3687 context.check_layout(os);
3688 string commandname = t.cs();
3690 if (p.next_token().asInput() == "*") {
3695 begin_command_inset(os, "index_print", commandname);
3696 string const indexname = p.getArg('[', ']');
3698 if (indexname.empty())
3699 os << "type \"idx\"\n";
3701 os << "type \"" << indexname << "\"\n";
3704 skip_spaces_braces(p);
3705 preamble.registerAutomaticallyLoadedPackage("makeidx");
3706 if (preamble.use_indices() == "true")
3707 preamble.registerAutomaticallyLoadedPackage("splitidx");
3710 else if (t.cs() == "printnomenclature") {
3712 string width_type = "";
3713 context.check_layout(os);
3714 begin_command_inset(os, "nomencl_print", "printnomenclature");
3715 // case of a custom width
3717 width = p.getArg('[', ']');
3718 width = translate_len(width);
3719 width_type = "custom";
3721 // case of no custom width
3722 // the case of no custom width but the width set
3723 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3724 // because the user could have set anything, not only the width
3725 // of the longest label (which would be width_type = "auto")
3726 string label = convert_command_inset_arg(p.getArg('{', '}'));
3727 if (label.empty() && width_type.empty())
3728 width_type = "none";
3729 os << "set_width \"" << width_type << "\"\n";
3730 if (width_type == "custom")
3731 os << "width \"" << width << '\"';
3733 skip_spaces_braces(p);
3734 preamble.registerAutomaticallyLoadedPackage("nomencl");
3737 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3738 context.check_layout(os);
3739 begin_inset(os, "script ");
3740 os << t.cs().substr(4) << '\n';
3741 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3742 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3744 if (t.cs() == "textsubscript")
3745 preamble.registerAutomaticallyLoadedPackage("subscript");
3748 else if ((where = is_known(t.cs(), known_quotes))) {
3749 context.check_layout(os);
3750 begin_inset(os, "Quotes ");
3751 os << known_coded_quotes[where - known_quotes];
3753 // LyX adds {} after the quote, so we have to eat
3754 // spaces here if there are any before a possible
3756 eat_whitespace(p, os, context, false);
3760 else if ((where = is_known(t.cs(), known_sizes)) &&
3761 context.new_layout_allowed) {
3762 context.check_layout(os);
3763 TeXFont const oldFont = context.font;
3764 context.font.size = known_coded_sizes[where - known_sizes];
3765 output_font_change(os, oldFont, context.font);
3766 eat_whitespace(p, os, context, false);
3769 else if ((where = is_known(t.cs(), known_font_families)) &&
3770 context.new_layout_allowed) {
3771 context.check_layout(os);
3772 TeXFont const oldFont = context.font;
3773 context.font.family =
3774 known_coded_font_families[where - known_font_families];
3775 output_font_change(os, oldFont, context.font);
3776 eat_whitespace(p, os, context, false);
3779 else if ((where = is_known(t.cs(), known_font_series)) &&
3780 context.new_layout_allowed) {
3781 context.check_layout(os);
3782 TeXFont const oldFont = context.font;
3783 context.font.series =
3784 known_coded_font_series[where - known_font_series];
3785 output_font_change(os, oldFont, context.font);
3786 eat_whitespace(p, os, context, false);
3789 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3790 context.new_layout_allowed) {
3791 context.check_layout(os);
3792 TeXFont const oldFont = context.font;
3793 context.font.shape =
3794 known_coded_font_shapes[where - known_font_shapes];
3795 output_font_change(os, oldFont, context.font);
3796 eat_whitespace(p, os, context, false);
3798 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3799 context.new_layout_allowed) {
3800 context.check_layout(os);
3801 TeXFont const oldFont = context.font;
3802 context.font.init();
3803 context.font.size = oldFont.size;
3804 context.font.family =
3805 known_coded_font_families[where - known_old_font_families];
3806 output_font_change(os, oldFont, context.font);
3807 eat_whitespace(p, os, context, false);
3810 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3811 context.new_layout_allowed) {
3812 context.check_layout(os);
3813 TeXFont const oldFont = context.font;
3814 context.font.init();
3815 context.font.size = oldFont.size;
3816 context.font.series =
3817 known_coded_font_series[where - known_old_font_series];
3818 output_font_change(os, oldFont, context.font);
3819 eat_whitespace(p, os, context, false);
3822 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3823 context.new_layout_allowed) {
3824 context.check_layout(os);
3825 TeXFont const oldFont = context.font;
3826 context.font.init();
3827 context.font.size = oldFont.size;
3828 context.font.shape =
3829 known_coded_font_shapes[where - known_old_font_shapes];
3830 output_font_change(os, oldFont, context.font);
3831 eat_whitespace(p, os, context, false);
3834 else if (t.cs() == "selectlanguage") {
3835 context.check_layout(os);
3836 // save the language for the case that a
3837 // \foreignlanguage is used
3838 context.font.language = babel2lyx(p.verbatim_item());
3839 os << "\n\\lang " << context.font.language << "\n";
3842 else if (t.cs() == "foreignlanguage") {
3843 string const lang = babel2lyx(p.verbatim_item());
3844 parse_text_attributes(p, os, FLAG_ITEM, outer,
3846 context.font.language, lang);
3849 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3850 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3851 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3853 // We have to output the whole command if it has an option
3854 // because LyX doesn't support this yet, see bug #8214,
3855 // only if there is a single option specifying a variant, we can handle it.
3857 string langopts = p.getOpt();
3858 // check if the option contains a variant, if yes, extract it
3859 string::size_type pos_var = langopts.find("variant");
3860 string::size_type i = langopts.find(',');
3861 string::size_type k = langopts.find('=', pos_var);
3862 if (pos_var != string::npos && i == string::npos) {
3864 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3865 lang = preamble.polyglossia2lyx(variant);
3866 parse_text_attributes(p, os, FLAG_ITEM, outer,
3868 context.font.language, lang);
3870 output_ert_inset(os, t.asInput() + langopts, context);
3872 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3873 parse_text_attributes(p, os, FLAG_ITEM, outer,
3875 context.font.language, lang);
3879 else if (t.cs() == "inputencoding") {
3880 // nothing to write here
3881 string const enc = subst(p.verbatim_item(), "\n", " ");
3882 p.setEncoding(enc, Encoding::inputenc);
3885 else if (is_known(t.cs(), known_special_chars) ||
3886 (t.cs() == "protect" &&
3887 p.next_token().cat() == catEscape &&
3888 is_known(p.next_token().cs(), known_special_protect_chars))) {
3889 // LyX sometimes puts a \protect in front, so we have to ignore it
3891 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3892 known_special_chars);
3893 context.check_layout(os);
3894 os << known_coded_special_chars[where - known_special_chars];
3895 skip_spaces_braces(p);
3898 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3899 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3900 p.next_next_token().asInput() == "-") ||
3901 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3902 // LyX sometimes puts a \protect in front, so we have to ignore it
3903 if (t.cs() == "protect")
3905 context.check_layout(os);
3906 if (t.cs() == "nobreakdash")
3907 os << "\\SpecialChar nobreakdash\n";
3909 os << "\\SpecialChar endofsentence\n";
3913 else if (t.cs() == "textquotedbl") {
3914 context.check_layout(os);
3919 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3920 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3921 || t.cs() == "%" || t.cs() == "-") {
3922 context.check_layout(os);
3924 os << "\\SpecialChar softhyphen\n";
3929 else if (t.cs() == "char") {
3930 context.check_layout(os);
3931 if (p.next_token().character() == '`') {
3933 if (p.next_token().cs() == "\"") {
3938 output_ert_inset(os, "\\char`", context);
3941 output_ert_inset(os, "\\char", context);
3945 else if (t.cs() == "verb") {
3946 context.check_layout(os);
3947 // set catcodes to verbatim early, just in case.
3948 p.setCatcodes(VERBATIM_CATCODES);
3949 string delim = p.get_token().asInput();
3950 Parser::Arg arg = p.verbatimStuff(delim);
3952 output_ert_inset(os, "\\verb" + delim
3953 + arg.second + delim, context);
3955 cerr << "invalid \\verb command. Skipping" << endl;
3958 // Problem: \= creates a tabstop inside the tabbing environment
3959 // and else an accent. In the latter case we really would want
3960 // \={o} instead of \= o.
3961 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3962 output_ert_inset(os, t.asInput(), context);
3964 else if (t.cs() == "\\") {
3965 context.check_layout(os);
3967 output_ert_inset(os, "\\\\" + p.getOpt(), context);
3968 else if (p.next_token().asInput() == "*") {
3970 // getOpt() eats the following space if there
3971 // is no optional argument, but that is OK
3972 // here since it has no effect in the output.
3973 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
3976 begin_inset(os, "Newline newline");
3981 else if (t.cs() == "newline" ||
3982 (t.cs() == "linebreak" && !p.hasOpt())) {
3983 context.check_layout(os);
3984 begin_inset(os, "Newline ");
3987 skip_spaces_braces(p);
3990 else if (t.cs() == "input" || t.cs() == "include"
3991 || t.cs() == "verbatiminput") {
3992 string name = t.cs();
3993 if (t.cs() == "verbatiminput"
3994 && p.next_token().asInput() == "*")
3995 name += p.get_token().asInput();
3996 context.check_layout(os);
3997 string filename(normalize_filename(p.getArg('{', '}')));
3998 string const path = getMasterFilePath(true);
3999 // We want to preserve relative / absolute filenames,
4000 // therefore path is only used for testing
4001 if ((t.cs() == "include" || t.cs() == "input") &&
4002 !makeAbsPath(filename, path).exists()) {
4003 // The file extension is probably missing.
4004 // Now try to find it out.
4005 string const tex_name =
4006 find_file(filename, path,
4007 known_tex_extensions);
4008 if (!tex_name.empty())
4009 filename = tex_name;
4011 bool external = false;
4013 if (makeAbsPath(filename, path).exists()) {
4014 string const abstexname =
4015 makeAbsPath(filename, path).absFileName();
4016 string const absfigname =
4017 changeExtension(abstexname, ".fig");
4018 fix_child_filename(filename);
4019 string const lyxname = changeExtension(filename,
4020 roundtripMode() ? ".lyx.lyx" : ".lyx");
4021 string const abslyxname = makeAbsPath(
4022 lyxname, getParentFilePath(false)).absFileName();
4024 if (!skipChildren())
4025 external = FileName(absfigname).exists();
4026 if (t.cs() == "input" && !skipChildren()) {
4027 string const ext = getExtension(abstexname);
4029 // Combined PS/LaTeX:
4030 // x.eps, x.pstex_t (old xfig)
4031 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4032 FileName const absepsname(
4033 changeExtension(abstexname, ".eps"));
4034 FileName const abspstexname(
4035 changeExtension(abstexname, ".pstex"));
4036 bool const xfigeps =
4037 (absepsname.exists() ||
4038 abspstexname.exists()) &&
4041 // Combined PDF/LaTeX:
4042 // x.pdf, x.pdftex_t (old xfig)
4043 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4044 FileName const abspdfname(
4045 changeExtension(abstexname, ".pdf"));
4046 bool const xfigpdf =
4047 abspdfname.exists() &&
4048 (ext == "pdftex_t" || ext == "pdf_t");
4052 // Combined PS/PDF/LaTeX:
4053 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4054 string const absbase2(
4055 removeExtension(abstexname) + "_pspdftex");
4056 FileName const abseps2name(
4057 addExtension(absbase2, ".eps"));
4058 FileName const abspdf2name(
4059 addExtension(absbase2, ".pdf"));
4060 bool const xfigboth =
4061 abspdf2name.exists() &&
4062 abseps2name.exists() && ext == "pspdftex";
4064 xfig = xfigpdf || xfigeps || xfigboth;
4065 external = external && xfig;
4068 outname = changeExtension(filename, ".fig");
4069 FileName abssrc(changeExtension(abstexname, ".fig"));
4070 copy_file(abssrc, outname);
4072 // Don't try to convert, the result
4073 // would be full of ERT.
4075 FileName abssrc(abstexname);
4076 copy_file(abssrc, outname);
4077 } else if (t.cs() != "verbatiminput" &&
4079 tex2lyx(abstexname, FileName(abslyxname),
4082 // no need to call copy_file
4083 // tex2lyx creates the file
4086 FileName abssrc(abstexname);
4087 copy_file(abssrc, outname);
4090 cerr << "Warning: Could not find included file '"
4091 << filename << "'." << endl;
4095 begin_inset(os, "External\n");
4096 os << "\ttemplate XFig\n"
4097 << "\tfilename " << outname << '\n';
4098 registerExternalTemplatePackages("XFig");
4100 begin_command_inset(os, "include", name);
4101 outname = subst(outname, "\"", "\\\"");
4102 os << "preview false\n"
4103 "filename \"" << outname << "\"\n";
4104 if (t.cs() == "verbatiminput")
4105 preamble.registerAutomaticallyLoadedPackage("verbatim");
4110 else if (t.cs() == "bibliographystyle") {
4111 // store new bibliographystyle
4112 bibliographystyle = p.verbatim_item();
4113 // If any other command than \bibliography, \addcontentsline
4114 // and \nocite{*} follows, we need to output the style
4115 // (because it might be used by that command).
4116 // Otherwise, it will automatically be output by LyX.
4119 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4120 if (t2.cat() == catBegin)
4122 if (t2.cat() != catEscape)
4124 if (t2.cs() == "nocite") {
4125 if (p.getArg('{', '}') == "*")
4127 } else if (t2.cs() == "bibliography")
4129 else if (t2.cs() == "phantomsection") {
4133 else if (t2.cs() == "addcontentsline") {
4134 // get the 3 arguments of \addcontentsline
4137 contentslineContent = p.getArg('{', '}');
4138 // if the last argument is not \refname we must output
4139 if (contentslineContent == "\\refname")
4146 output_ert_inset(os,
4147 "\\bibliographystyle{" + bibliographystyle + '}',
4152 else if (t.cs() == "phantomsection") {
4153 // we only support this if it occurs between
4154 // \bibliographystyle and \bibliography
4155 if (bibliographystyle.empty())
4156 output_ert_inset(os, "\\phantomsection", context);
4159 else if (t.cs() == "addcontentsline") {
4160 context.check_layout(os);
4161 // get the 3 arguments of \addcontentsline
4162 string const one = p.getArg('{', '}');
4163 string const two = p.getArg('{', '}');
4164 string const three = p.getArg('{', '}');
4165 // only if it is a \refname, we support if for the bibtex inset
4166 if (contentslineContent != "\\refname") {
4167 output_ert_inset(os,
4168 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4173 else if (t.cs() == "bibliography") {
4174 context.check_layout(os);
4176 begin_command_inset(os, "bibtex", "bibtex");
4177 if (!btprint.empty()) {
4178 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4179 // clear the string because the next BibTeX inset can be without the
4180 // \nocite{*} option
4183 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4184 // Do we have addcontentsline?
4185 if (contentslineContent == "\\refname") {
4186 BibOpts = "bibtotoc";
4187 // clear string because next BibTeX inset can be without addcontentsline
4188 contentslineContent.clear();
4190 // Do we have a bibliographystyle set?
4191 if (!bibliographystyle.empty()) {
4192 if (BibOpts.empty())
4193 BibOpts = bibliographystyle;
4195 BibOpts = BibOpts + ',' + bibliographystyle;
4196 // clear it because each bibtex entry has its style
4197 // and we need an empty string to handle \phantomsection
4198 bibliographystyle.clear();
4200 os << "options " << '"' << BibOpts << '"' << "\n";
4204 else if (t.cs() == "parbox") {
4205 // Test whether this is an outer box of a shaded box
4207 // swallow arguments
4208 while (p.hasOpt()) {
4210 p.skip_spaces(true);
4213 p.skip_spaces(true);
4215 if (p.next_token().cat() == catBegin)
4217 p.skip_spaces(true);
4218 Token to = p.get_token();
4219 bool shaded = false;
4220 if (to.asInput() == "\\begin") {
4221 p.skip_spaces(true);
4222 if (p.getArg('{', '}') == "shaded")
4227 parse_outer_box(p, os, FLAG_ITEM, outer,
4228 context, "parbox", "shaded");
4230 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4231 "", "", t.cs(), "", "");
4234 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4235 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4236 t.cs() == "shadowbox" || t.cs() == "doublebox")
4237 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4239 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4240 string backgroundcolor;
4241 preamble.registerAutomaticallyLoadedPackage("xcolor");
4242 if (t.cs() == "fcolorbox") {
4243 string const framecolor = p.getArg('{', '}');
4244 backgroundcolor = p.getArg('{', '}');
4245 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4247 backgroundcolor = p.getArg('{', '}');
4248 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4252 // FIXME: due to the compiler limit of "if" nestings
4253 // the code for the alignment was put here
4254 // put them in their own if if this is fixed
4255 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4256 || t.cs() == "shadowsize"
4257 || t.cs() == "raggedleft" || t.cs() == "centering"
4258 || t.cs() == "raggedright") {
4259 if (t.cs() == "fboxrule")
4261 if (t.cs() == "fboxsep")
4263 if (t.cs() == "shadowsize")
4265 if (t.cs() != "raggedleft" && t.cs() != "centering"
4266 && t.cs() != "raggedright") {
4267 p.skip_spaces(true);
4268 while (p.good() && p.next_token().cat() != catSpace
4269 && p.next_token().cat() != catNewline
4270 && p.next_token().cat() != catEscape) {
4271 if (t.cs() == "fboxrule")
4272 fboxrule = fboxrule + p.get_token().asInput();
4273 if (t.cs() == "fboxsep")
4274 fboxsep = fboxsep + p.get_token().asInput();
4275 if (t.cs() == "shadowsize")
4276 shadow_size = shadow_size + p.get_token().asInput();
4279 output_ert_inset(os, t.asInput(), context);
4283 //\framebox() is part of the picture environment and different from \framebox{}
4284 //\framebox{} will be parsed by parse_outer_box
4285 else if (t.cs() == "framebox") {
4286 if (p.next_token().character() == '(') {
4287 //the syntax is: \framebox(x,y)[position]{content}
4288 string arg = t.asInput();
4289 arg += p.getFullParentheseArg();
4290 arg += p.getFullOpt();
4291 eat_whitespace(p, os, context, false);
4292 output_ert_inset(os, arg + '{', context);
4293 parse_text(p, os, FLAG_ITEM, outer, context);
4294 output_ert_inset(os, "}", context);
4296 //the syntax is: \framebox[width][position]{content}
4297 string special = p.getFullOpt();
4298 special += p.getOpt();
4299 parse_outer_box(p, os, FLAG_ITEM, outer,
4300 context, t.cs(), special);
4304 //\makebox() is part of the picture environment and different from \makebox{}
4305 //\makebox{} will be parsed by parse_box
4306 else if (t.cs() == "makebox") {
4307 if (p.next_token().character() == '(') {
4308 //the syntax is: \makebox(x,y)[position]{content}
4309 string arg = t.asInput();
4310 arg += p.getFullParentheseArg();
4311 arg += p.getFullOpt();
4312 eat_whitespace(p, os, context, false);
4313 output_ert_inset(os, arg + '{', context);
4314 parse_text(p, os, FLAG_ITEM, outer, context);
4315 output_ert_inset(os, "}", context);
4317 //the syntax is: \makebox[width][position]{content}
4318 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4319 "", "", t.cs(), "", "");
4322 else if (t.cs() == "smallskip" ||
4323 t.cs() == "medskip" ||
4324 t.cs() == "bigskip" ||
4325 t.cs() == "vfill") {
4326 context.check_layout(os);
4327 begin_inset(os, "VSpace ");
4330 skip_spaces_braces(p);
4333 else if ((where = is_known(t.cs(), known_spaces))) {
4334 context.check_layout(os);
4335 begin_inset(os, "space ");
4336 os << '\\' << known_coded_spaces[where - known_spaces]
4339 // LaTeX swallows whitespace after all spaces except
4340 // "\\,". We have to do that here, too, because LyX
4341 // adds "{}" which would make the spaces significant.
4343 eat_whitespace(p, os, context, false);
4344 // LyX adds "{}" after all spaces except "\\ " and
4345 // "\\,", so we have to remove "{}".
4346 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4347 // remove the braces after "\\,", too.
4352 else if (t.cs() == "newpage" ||
4353 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4354 t.cs() == "clearpage" ||
4355 t.cs() == "cleardoublepage") {
4356 context.check_layout(os);
4357 begin_inset(os, "Newpage ");
4360 skip_spaces_braces(p);
4363 else if (t.cs() == "DeclareRobustCommand" ||
4364 t.cs() == "DeclareRobustCommandx" ||
4365 t.cs() == "newcommand" ||
4366 t.cs() == "newcommandx" ||
4367 t.cs() == "providecommand" ||
4368 t.cs() == "providecommandx" ||
4369 t.cs() == "renewcommand" ||
4370 t.cs() == "renewcommandx") {
4371 // DeclareRobustCommand, DeclareRobustCommandx,
4372 // providecommand and providecommandx could be handled
4373 // by parse_command(), but we need to call
4374 // add_known_command() here.
4375 string name = t.asInput();
4376 if (p.next_token().asInput() == "*") {
4377 // Starred form. Eat '*'
4381 string const command = p.verbatim_item();
4382 string const opt1 = p.getFullOpt();
4383 string const opt2 = p.getFullOpt();
4384 add_known_command(command, opt1, !opt2.empty());
4385 string const ert = name + '{' + command + '}' +
4387 '{' + p.verbatim_item() + '}';
4389 if (t.cs() == "DeclareRobustCommand" ||
4390 t.cs() == "DeclareRobustCommandx" ||
4391 t.cs() == "providecommand" ||
4392 t.cs() == "providecommandx" ||
4393 name[name.length()-1] == '*')
4394 output_ert_inset(os, ert, context);
4396 context.check_layout(os);
4397 begin_inset(os, "FormulaMacro");
4403 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4404 // let could be handled by parse_command(),
4405 // but we need to call add_known_command() here.
4406 string ert = t.asInput();
4409 if (p.next_token().cat() == catBegin) {
4410 name = p.verbatim_item();
4411 ert += '{' + name + '}';
4413 name = p.verbatim_item();
4418 if (p.next_token().cat() == catBegin) {
4419 command = p.verbatim_item();
4420 ert += '{' + command + '}';
4422 command = p.verbatim_item();
4425 // If command is known, make name known too, to parse
4426 // its arguments correctly. For this reason we also
4427 // have commands in syntax.default that are hardcoded.
4428 CommandMap::iterator it = known_commands.find(command);
4429 if (it != known_commands.end())
4430 known_commands[t.asInput()] = it->second;
4431 output_ert_inset(os, ert, context);
4434 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4437 string name = t.asInput();
4438 string const length = p.verbatim_item();
4441 bool valid = splitLatexLength(length, valstring, unit);
4442 bool known_hspace = false;
4443 bool known_vspace = false;
4444 bool known_unit = false;
4447 istringstream iss(valstring);
4450 if (t.cs()[0] == 'h') {
4451 if (unit == "\\fill") {
4456 known_hspace = true;
4459 if (unit == "\\smallskipamount") {
4461 known_vspace = true;
4462 } else if (unit == "\\medskipamount") {
4464 known_vspace = true;
4465 } else if (unit == "\\bigskipamount") {
4467 known_vspace = true;
4468 } else if (unit == "\\fill") {
4470 known_vspace = true;
4474 if (!known_hspace && !known_vspace) {
4475 switch (unitFromString(unit)) {
4491 //unitFromString(unit) fails for relative units like Length::PCW
4492 // therefore handle them separately
4493 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4494 || unit == "\\textwidth" || unit == "\\linewidth"
4495 || unit == "\\textheight" || unit == "\\paperheight")
4503 // check for glue lengths
4504 bool is_gluelength = false;
4505 string gluelength = length;
4506 string::size_type i = length.find(" minus");
4507 if (i == string::npos) {
4508 i = length.find(" plus");
4509 if (i != string::npos)
4510 is_gluelength = true;
4512 is_gluelength = true;
4513 // if yes transform "9xx minus 8yy plus 7zz"
4515 if (is_gluelength) {
4516 i = gluelength.find(" minus");
4517 if (i != string::npos)
4518 gluelength.replace(i, 7, "-");
4519 i = gluelength.find(" plus");
4520 if (i != string::npos)
4521 gluelength.replace(i, 6, "+");
4524 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4525 // Literal horizontal length or known variable
4526 context.check_layout(os);
4527 begin_inset(os, "space ");
4535 if (known_unit && !known_hspace)
4536 os << "\n\\length " << translate_len(length);
4538 os << "\n\\length " << gluelength;
4540 } else if (known_unit || known_vspace || is_gluelength) {
4541 // Literal vertical length or known variable
4542 context.check_layout(os);
4543 begin_inset(os, "VSpace ");
4546 if (known_unit && !known_vspace)
4547 os << translate_len(length);
4554 // LyX can't handle other length variables in Inset VSpace/space
4559 output_ert_inset(os, name + '{' + unit + '}', context);
4560 else if (value == -1.0)
4561 output_ert_inset(os, name + "{-" + unit + '}', context);
4563 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4565 output_ert_inset(os, name + '{' + length + '}', context);
4569 // The single '=' is meant here.
4570 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4574 context.check_layout(os);
4575 docstring const name = newinsetlayout->name();
4576 bool const caption = name.find(from_ascii("Caption:")) == 0;
4578 begin_inset(os, "Caption ");
4579 os << to_utf8(name.substr(8)) << '\n';
4581 begin_inset(os, "Flex ");
4582 os << to_utf8(name) << '\n'
4583 << "status collapsed\n";
4585 if (newinsetlayout->isPassThru()) {
4586 // set catcodes to verbatim early, just in case.
4587 p.setCatcodes(VERBATIM_CATCODES);
4588 string delim = p.get_token().asInput();
4590 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4591 //FIXME: handle error condition
4592 string const arg = p.verbatimStuff("}").second;
4593 Context newcontext(true, context.textclass);
4594 if (newinsetlayout->forcePlainLayout())
4595 newcontext.layout = &context.textclass.plainLayout();
4596 output_ert(os, arg, newcontext);
4598 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4604 else if (t.cs() == "includepdf") {
4606 string const arg = p.getArg('[', ']');
4607 map<string, string> opts;
4608 vector<string> keys;
4609 split_map(arg, opts, keys);
4610 string name = normalize_filename(p.verbatim_item());
4611 string const path = getMasterFilePath(true);
4612 // We want to preserve relative / absolute filenames,
4613 // therefore path is only used for testing
4614 if (!makeAbsPath(name, path).exists()) {
4615 // The file extension is probably missing.
4616 // Now try to find it out.
4617 char const * const pdfpages_format[] = {"pdf", 0};
4618 string const pdftex_name =
4619 find_file(name, path, pdfpages_format);
4620 if (!pdftex_name.empty()) {
4625 FileName const absname = makeAbsPath(name, path);
4626 if (absname.exists())
4628 fix_child_filename(name);
4629 copy_file(absname, name);
4631 cerr << "Warning: Could not find file '"
4632 << name << "'." << endl;
4634 context.check_layout(os);
4635 begin_inset(os, "External\n\ttemplate ");
4636 os << "PDFPages\n\tfilename "
4638 // parse the options
4639 if (opts.find("pages") != opts.end())
4640 os << "\textra LaTeX \"pages="
4641 << opts["pages"] << "\"\n";
4642 if (opts.find("angle") != opts.end())
4643 os << "\trotateAngle "
4644 << opts["angle"] << '\n';
4645 if (opts.find("origin") != opts.end()) {
4647 string const opt = opts["origin"];
4648 if (opt == "tl") ss << "topleft";
4649 if (opt == "bl") ss << "bottomleft";
4650 if (opt == "Bl") ss << "baselineleft";
4651 if (opt == "c") ss << "center";
4652 if (opt == "tc") ss << "topcenter";
4653 if (opt == "bc") ss << "bottomcenter";
4654 if (opt == "Bc") ss << "baselinecenter";
4655 if (opt == "tr") ss << "topright";
4656 if (opt == "br") ss << "bottomright";
4657 if (opt == "Br") ss << "baselineright";
4658 if (!ss.str().empty())
4659 os << "\trotateOrigin " << ss.str() << '\n';
4661 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4663 if (opts.find("width") != opts.end())
4665 << translate_len(opts["width"]) << '\n';
4666 if (opts.find("height") != opts.end())
4668 << translate_len(opts["height"]) << '\n';
4669 if (opts.find("keepaspectratio") != opts.end())
4670 os << "\tkeepAspectRatio\n";
4672 context.check_layout(os);
4673 registerExternalTemplatePackages("PDFPages");
4676 else if (t.cs() == "loadgame") {
4678 string name = normalize_filename(p.verbatim_item());
4679 string const path = getMasterFilePath(true);
4680 // We want to preserve relative / absolute filenames,
4681 // therefore path is only used for testing
4682 if (!makeAbsPath(name, path).exists()) {
4683 // The file extension is probably missing.
4684 // Now try to find it out.
4685 char const * const lyxskak_format[] = {"fen", 0};
4686 string const lyxskak_name =
4687 find_file(name, path, lyxskak_format);
4688 if (!lyxskak_name.empty())
4689 name = lyxskak_name;
4691 FileName const absname = makeAbsPath(name, path);
4692 if (absname.exists())
4694 fix_child_filename(name);
4695 copy_file(absname, name);
4697 cerr << "Warning: Could not find file '"
4698 << name << "'." << endl;
4699 context.check_layout(os);
4700 begin_inset(os, "External\n\ttemplate ");
4701 os << "ChessDiagram\n\tfilename "
4704 context.check_layout(os);
4705 // after a \loadgame follows a \showboard
4706 if (p.get_token().asInput() == "showboard")
4708 registerExternalTemplatePackages("ChessDiagram");
4712 // try to see whether the string is in unicodesymbols
4713 // Only use text mode commands, since we are in text mode here,
4714 // and math commands may be invalid (bug 6797)
4715 string name = t.asInput();
4716 // handle the dingbats, cyrillic and greek
4717 if (name == "\\ding" || name == "\\textcyr" ||
4718 (name == "\\textgreek" && !preamble.usePolyglossia()))
4719 name = name + '{' + p.getArg('{', '}') + '}';
4720 // handle the ifsym characters
4721 else if (name == "\\textifsymbol") {
4722 string const optif = p.getFullOpt();
4723 string const argif = p.getArg('{', '}');
4724 name = name + optif + '{' + argif + '}';
4726 // handle the \ascii characters
4727 // the case of \ascii within braces, as LyX outputs it, is already
4728 // handled for t.cat() == catBegin
4729 else if (name == "\\ascii") {
4730 // the code is "\asci\xxx"
4731 name = "{" + name + p.get_token().asInput() + "}";
4734 // handle some TIPA special characters
4735 else if (preamble.isPackageUsed("tipa")) {
4736 if (name == "\\textglobfall") {
4739 } else if (name == "\\s") {
4740 // fromLaTeXCommand() does not yet
4741 // recognize tipa short cuts
4742 name = "\\textsyllabic";
4743 } else if (name == "\\=" &&
4744 p.next_token().asInput() == "*") {
4745 // fromLaTeXCommand() does not yet
4746 // recognize tipa short cuts
4748 name = "\\textsubbar";
4749 } else if (name == "\\textdoublevertline") {
4750 // FIXME: This is not correct,
4751 // \textvertline is higher than \textbardbl
4752 name = "\\textbardbl";
4754 } else if (name == "\\!" ) {
4755 if (p.next_token().asInput() == "b") {
4756 p.get_token(); // eat 'b'
4759 } else if (p.next_token().asInput() == "d") {
4763 } else if (p.next_token().asInput() == "g") {
4767 } else if (p.next_token().asInput() == "G") {
4769 name = "\\texthtscg";
4771 } else if (p.next_token().asInput() == "j") {
4773 name = "\\texthtbardotlessj";
4775 } else if (p.next_token().asInput() == "o") {
4777 name = "\\textbullseye";
4780 } else if (name == "\\*" ) {
4781 if (p.next_token().asInput() == "k") {
4783 name = "\\textturnk";
4785 } else if (p.next_token().asInput() == "r") {
4786 p.get_token(); // eat 'b'
4787 name = "\\textturnr";
4789 } else if (p.next_token().asInput() == "t") {
4791 name = "\\textturnt";
4793 } else if (p.next_token().asInput() == "w") {
4795 name = "\\textturnw";
4800 if ((name.size() == 2 &&
4801 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4802 p.next_token().asInput() != "*") ||
4803 is_known(name.substr(1), known_tipa_marks)) {
4804 // name is a command that corresponds to a
4805 // combining character in unicodesymbols.
4806 // Append the argument, fromLaTeXCommand()
4807 // will either convert it to a single
4808 // character or a combining sequence.
4809 name += '{' + p.verbatim_item() + '}';
4811 // now get the character from unicodesymbols
4815 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4816 Encodings::TEXT_CMD, termination, rem, &req);
4818 context.check_layout(os);
4821 output_ert_inset(os, to_utf8(rem), context);
4823 skip_spaces_braces(p);
4824 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4825 preamble.registerAutomaticallyLoadedPackage(*it);
4827 //cerr << "#: " << t << " mode: " << mode << endl;
4828 // heuristic: read up to next non-nested space
4830 string s = t.asInput();
4831 string z = p.verbatim_item();
4832 while (p.good() && z != " " && !z.empty()) {
4833 //cerr << "read: " << z << endl;
4835 z = p.verbatim_item();
4837 cerr << "found ERT: " << s << endl;
4838 output_ert_inset(os, s + ' ', context);
4841 if (t.asInput() == name &&
4842 p.next_token().asInput() == "*") {
4843 // Starred commands like \vspace*{}
4844 p.get_token(); // Eat '*'
4847 if (!parse_command(name, p, os, outer, context))
4848 output_ert_inset(os, name, context);
4852 if (flags & FLAG_LEAVE) {
4853 flags &= ~FLAG_LEAVE;
4860 string guessLanguage(Parser & p, string const & lang)
4862 typedef std::map<std::string, size_t> LangMap;
4863 // map from language names to number of characters
4866 for (char const * const * i = supported_CJK_languages; *i; i++)
4867 used[string(*i)] = 0;
4870 Token const t = p.get_token();
4871 // comments are not counted for any language
4872 if (t.cat() == catComment)
4874 // commands are not counted as well, but we need to detect
4875 // \begin{CJK} and switch encoding if needed
4876 if (t.cat() == catEscape) {
4877 if (t.cs() == "inputencoding") {
4878 string const enc = subst(p.verbatim_item(), "\n", " ");
4879 p.setEncoding(enc, Encoding::inputenc);
4882 if (t.cs() != "begin")
4885 // Non-CJK content is counted for lang.
4886 // We do not care about the real language here:
4887 // If we have more non-CJK contents than CJK contents,
4888 // we simply use the language that was specified as
4889 // babel main language.
4890 used[lang] += t.asInput().length();
4893 // Now we are starting an environment
4895 string const name = p.getArg('{', '}');
4896 if (name != "CJK") {
4900 // It is a CJK environment
4902 /* name = */ p.getArg('{', '}');
4903 string const encoding = p.getArg('{', '}');
4904 /* mapping = */ p.getArg('{', '}');
4905 string const encoding_old = p.getEncoding();
4906 char const * const * const where =
4907 is_known(encoding, supported_CJK_encodings);
4909 p.setEncoding(encoding, Encoding::CJK);
4911 p.setEncoding("UTF-8");
4912 string const text = p.ertEnvironment("CJK");
4913 p.setEncoding(encoding_old);
4916 // ignore contents in unknown CJK encoding
4919 // the language of the text
4921 supported_CJK_languages[where - supported_CJK_encodings];
4922 used[cjk] += text.length();
4924 LangMap::const_iterator use = used.begin();
4925 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4926 if (it->second > use->second)