2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
130 bool wasBoxAlign = false;
132 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
133 "vpageref", "prettyref", "nameref", "eqref", 0 };
135 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
136 "vpageref", "formatted", "nameref", "eqref", 0 };
138 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
139 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
140 "secref", "subref", "tabref", "thmref", 0 };
142 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
143 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
144 "sec", "sub", "tab", "thm", 0 };
148 * supported CJK encodings
149 * JIS does not work with LyX's encoding conversion
151 const char * const supported_CJK_encodings[] = {
152 "EUC-JP", "KS", "GB", "UTF8",
153 "Bg5", /*"JIS",*/ "SJIS", 0};
156 * the same as supported_CJK_encodings with their corresponding LyX language name
157 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
159 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
160 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
161 * please keep this in sync with supported_CJK_encodings line by line!
163 const char * const supported_CJK_languages[] = {
164 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
165 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
169 * The starred forms are also known except for "citefullauthor",
170 * "citeyear" and "citeyearpar".
172 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
173 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
174 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
178 * No starred form other than "cite*" known.
180 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 // jurabib commands not (yet) supported by LyX:
184 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
185 // "footciteauthor", "footciteyear", "footciteyearpar",
186 "citefield", "citetitle", 0 };
188 /// LaTeX names for quotes
189 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
190 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
191 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
192 "guilsinglleft", "frq", "guilsinglright", 0};
194 /// the same as known_quotes with .lyx names
195 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
196 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
197 "gld", "grd", "gls", "ers", "fls",
198 "fls", "frs", "frs", 0};
200 /// LaTeX names for font sizes
201 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
202 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
204 /// the same as known_sizes with .lyx names
205 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
206 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
208 /// LaTeX 2.09 names for font families
209 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
211 /// LaTeX names for font families
212 char const * const known_font_families[] = { "rmfamily", "sffamily",
215 /// LaTeX names for font family changing commands
216 char const * const known_text_font_families[] = { "textrm", "textsf",
219 /// The same as known_old_font_families, known_font_families and
220 /// known_text_font_families with .lyx names
221 char const * const known_coded_font_families[] = { "roman", "sans",
224 /// LaTeX 2.09 names for font series
225 char const * const known_old_font_series[] = { "bf", 0};
227 /// LaTeX names for font series
228 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
230 /// LaTeX names for font series changing commands
231 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
233 /// The same as known_old_font_series, known_font_series and
234 /// known_text_font_series with .lyx names
235 char const * const known_coded_font_series[] = { "bold", "medium", 0};
237 /// LaTeX 2.09 names for font shapes
238 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
240 /// LaTeX names for font shapes
241 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
244 /// LaTeX names for font shape changing commands
245 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
248 /// The same as known_old_font_shapes, known_font_shapes and
249 /// known_text_font_shapes with .lyx names
250 char const * const known_coded_font_shapes[] = { "italic", "slanted",
251 "smallcaps", "up", 0};
253 /// Known special characters which need skip_spaces_braces() afterwards
254 char const * const known_special_chars[] = {"ldots",
255 "lyxarrow", "textcompwordmark",
256 "slash", "textasciitilde", "textasciicircum", "textbackslash",
257 "LyX", "TeX", "LaTeXe",
260 /// special characters from known_special_chars which may have a \\protect before
261 char const * const known_special_protect_chars[] = {"LyX", "TeX",
262 "LaTeXe", "LaTeX", 0};
264 /// the same as known_special_chars with .lyx names
265 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
266 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
267 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
268 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
269 "\\SpecialChar LaTeX\n", 0};
272 * Graphics file extensions known by the dvips driver of the graphics package.
273 * These extensions are used to complete the filename of an included
274 * graphics file if it does not contain an extension.
275 * The order must be the same that latex uses to find a file, because we
276 * will use the first extension that matches.
277 * This is only an approximation for the common cases. If we would want to
278 * do it right in all cases, we would need to know which graphics driver is
279 * used and know the extensions of every driver of the graphics package.
281 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
282 "ps.gz", "eps.Z", "ps.Z", 0};
285 * Graphics file extensions known by the pdftex driver of the graphics package.
286 * \sa known_dvips_graphics_formats
288 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
292 * Known file extensions for TeX files as used by \\include.
294 char const * const known_tex_extensions[] = {"tex", 0};
296 /// spaces known by InsetSpace
297 char const * const known_spaces[] = { " ", "space", ",",
298 "thinspace", "quad", "qquad", "enspace", "enskip",
299 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
300 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
301 "upbracefill", "downbracefill", 0};
303 /// the same as known_spaces with .lyx names
304 char const * const known_coded_spaces[] = { "space{}", "space{}",
305 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
306 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
307 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
308 "upbracefill{}", "downbracefill{}", 0};
310 /// known TIPA combining diacritical marks
311 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
312 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
313 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
314 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
315 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
316 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
319 /// TIPA tones that need special handling
320 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
322 // string to store the float type to be able to determine the type of subfloats
323 string float_type = "";
326 /// splits "x=z, y=b" into a map and an ordered keyword vector
327 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
332 keys.resize(v.size());
333 for (size_t i = 0; i < v.size(); ++i) {
334 size_t const pos = v[i].find('=');
335 string const index = trimSpaceAndEol(v[i].substr(0, pos));
336 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
344 * Split a LaTeX length into value and unit.
345 * The latter can be a real unit like "pt", or a latex length variable
346 * like "\textwidth". The unit may contain additional stuff like glue
347 * lengths, but we don't care, because such lengths are ERT anyway.
348 * \returns true if \p value and \p unit are valid.
350 bool splitLatexLength(string const & len, string & value, string & unit)
354 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
355 //'4,5' is a valid LaTeX length number. Change it to '4.5'
356 string const length = subst(len, ',', '.');
357 if (i == string::npos)
360 if (len[0] == '\\') {
361 // We had something like \textwidth without a factor
367 value = trimSpaceAndEol(string(length, 0, i));
371 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
372 if (contains(len, '\\'))
373 unit = trimSpaceAndEol(string(len, i));
375 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
380 /// A simple function to translate a latex length to something LyX can
381 /// understand. Not perfect, but rather best-effort.
382 bool translate_len(string const & length, string & valstring, string & unit)
384 if (!splitLatexLength(length, valstring, unit))
386 // LyX uses percent values
388 istringstream iss(valstring);
393 string const percentval = oss.str();
395 if (unit.empty() || unit[0] != '\\')
397 string::size_type const i = unit.find(' ');
398 string const endlen = (i == string::npos) ? string() : string(unit, i);
399 if (unit == "\\textwidth") {
400 valstring = percentval;
401 unit = "text%" + endlen;
402 } else if (unit == "\\columnwidth") {
403 valstring = percentval;
404 unit = "col%" + endlen;
405 } else if (unit == "\\paperwidth") {
406 valstring = percentval;
407 unit = "page%" + endlen;
408 } else if (unit == "\\linewidth") {
409 valstring = percentval;
410 unit = "line%" + endlen;
411 } else if (unit == "\\paperheight") {
412 valstring = percentval;
413 unit = "pheight%" + endlen;
414 } else if (unit == "\\textheight") {
415 valstring = percentval;
416 unit = "theight%" + endlen;
424 string translate_len(string const & length)
428 if (translate_len(length, value, unit))
430 // If the input is invalid, return what we have.
438 * Translates a LaTeX length into \p value, \p unit and
439 * \p special parts suitable for a box inset.
440 * The difference from translate_len() is that a box inset knows about
441 * some special "units" that are stored in \p special.
443 void translate_box_len(string const & length, string & value, string & unit, string & special)
445 if (translate_len(length, value, unit)) {
446 if (unit == "\\height" || unit == "\\depth" ||
447 unit == "\\totalheight" || unit == "\\width") {
448 special = unit.substr(1);
449 // The unit is not used, but LyX requires a dummy setting
462 * Find a file with basename \p name in path \p path and an extension
465 string find_file(string const & name, string const & path,
466 char const * const * extensions)
468 for (char const * const * what = extensions; *what; ++what) {
469 string const trial = addExtension(name, *what);
470 if (makeAbsPath(trial, path).exists())
477 void begin_inset(ostream & os, string const & name)
479 os << "\n\\begin_inset " << name;
483 void begin_command_inset(ostream & os, string const & name,
484 string const & latexname)
486 begin_inset(os, "CommandInset ");
487 os << name << "\nLatexCommand " << latexname << '\n';
491 void end_inset(ostream & os)
493 os << "\n\\end_inset\n\n";
497 bool skip_braces(Parser & p)
499 if (p.next_token().cat() != catBegin)
502 if (p.next_token().cat() == catEnd) {
511 /// replace LaTeX commands in \p s from the unicodesymbols file with their
513 docstring convert_unicodesymbols(docstring s)
516 for (size_t i = 0; i < s.size();) {
525 docstring parsed = encodings.fromLaTeXCommand(s,
526 Encodings::TEXT_CMD, termination, rem, &req);
527 set<string>::const_iterator it = req.begin();
528 set<string>::const_iterator en = req.end();
529 for (; it != en; ++it)
530 preamble.registerAutomaticallyLoadedPackage(*it);
533 if (s.empty() || s[0] != '\\')
542 /// try to convert \p s to a valid InsetCommand argument
543 string convert_command_inset_arg(string s)
546 // since we don't know the input encoding we can't use from_utf8
547 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
548 // LyX cannot handle newlines in a latex command
549 return subst(s, "\n", " ");
553 void output_ert(ostream & os, string const & s, Context & context)
555 context.check_layout(os);
556 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
558 os << "\n\\backslash\n";
559 else if (*it == '\n') {
560 context.new_paragraph(os);
561 context.check_layout(os);
565 context.check_end_layout(os);
569 void output_ert_inset(ostream & os, string const & s, Context & context)
571 // We must have a valid layout before outputting the ERT inset.
572 context.check_layout(os);
573 Context newcontext(true, context.textclass);
574 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
575 if (layout.forcePlainLayout())
576 newcontext.layout = &context.textclass.plainLayout();
577 begin_inset(os, "ERT");
578 os << "\nstatus collapsed\n";
579 output_ert(os, s, newcontext);
584 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
586 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
589 if (checkModule(name, command))
590 return findLayoutWithoutModule(textclass, name, command);
595 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
597 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
600 if (checkModule(name, command))
601 return findInsetLayoutWithoutModule(textclass, name, command);
606 void eat_whitespace(Parser &, ostream &, Context &, bool);
610 * Skips whitespace and braces.
611 * This should be called after a command has been parsed that is not put into
612 * ERT, and where LyX adds "{}" if needed.
614 void skip_spaces_braces(Parser & p, bool keepws = false)
616 /* The following four examples produce the same typeset output and
617 should be handled by this function:
625 // Unfortunately we need to skip comments, too.
626 // We can't use eat_whitespace since writing them after the {}
627 // results in different output in some cases.
628 bool const skipped_spaces = p.skip_spaces(true);
629 bool const skipped_braces = skip_braces(p);
630 if (keepws && skipped_spaces && !skipped_braces)
631 // put back the space (it is better handled by check_space)
632 p.unskip_spaces(true);
636 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
637 Context & context, Layout::LaTeXArgMap const & latexargs)
640 context.check_layout(os);
645 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
646 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
647 for (; lait != laend; ++lait) {
649 eat_whitespace(p, os, context, false);
650 if (lait->second.mandatory) {
651 if (p.next_token().cat() != catBegin)
653 p.get_token(); // eat '{'
655 context.check_layout(os);
658 begin_inset(os, "Argument ");
661 os << i << "\nstatus collapsed\n\n";
662 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
665 if (p.next_token().cat() == catEscape ||
666 p.next_token().character() != '[')
668 p.get_token(); // eat '['
670 context.check_layout(os);
673 begin_inset(os, "Argument ");
676 os << i << "\nstatus collapsed\n\n";
677 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
680 eat_whitespace(p, os, context, false);
685 void output_command_layout(ostream & os, Parser & p, bool outer,
686 Context & parent_context,
687 Layout const * newlayout)
689 TeXFont const oldFont = parent_context.font;
690 // save the current font size
691 string const size = oldFont.size;
692 // reset the font size to default, because the font size switches
693 // don't affect section headings and the like
694 parent_context.font.size = Context::normalfont.size;
695 // we only need to write the font change if we have an open layout
696 if (!parent_context.atParagraphStart())
697 output_font_change(os, oldFont, parent_context.font);
698 parent_context.check_end_layout(os);
699 Context context(true, parent_context.textclass, newlayout,
700 parent_context.layout, parent_context.font);
701 if (parent_context.deeper_paragraph) {
702 // We are beginning a nested environment after a
703 // deeper paragraph inside the outer list environment.
704 // Therefore we don't need to output a "begin deeper".
705 context.need_end_deeper = true;
707 context.check_deeper(os);
708 output_arguments(os, p, outer, true, false, context,
709 context.layout->latexargs());
710 parse_text(p, os, FLAG_ITEM, outer, context);
711 output_arguments(os, p, outer, false, true, context,
712 context.layout->postcommandargs());
713 context.check_end_layout(os);
714 if (parent_context.deeper_paragraph) {
715 // We must suppress the "end deeper" because we
716 // suppressed the "begin deeper" above.
717 context.need_end_deeper = false;
719 context.check_end_deeper(os);
720 // We don't need really a new paragraph, but
721 // we must make sure that the next item gets a \begin_layout.
722 parent_context.new_paragraph(os);
723 // Set the font size to the original value. No need to output it here
724 // (Context::begin_layout() will do that if needed)
725 parent_context.font.size = size;
730 * Output a space if necessary.
731 * This function gets called for every whitespace token.
733 * We have three cases here:
734 * 1. A space must be suppressed. Example: The lyxcode case below
735 * 2. A space may be suppressed. Example: Spaces before "\par"
736 * 3. A space must not be suppressed. Example: A space between two words
738 * We currently handle only 1. and 3 and from 2. only the case of
739 * spaces before newlines as a side effect.
741 * 2. could be used to suppress as many spaces as possible. This has two effects:
742 * - Reimporting LyX generated LaTeX files changes almost no whitespace
743 * - Superflous whitespace from non LyX generated LaTeX files is removed.
744 * The drawback is that the logic inside the function becomes
745 * complicated, and that is the reason why it is not implemented.
747 void check_space(Parser & p, ostream & os, Context & context)
749 Token const next = p.next_token();
750 Token const curr = p.curr_token();
751 // A space before a single newline and vice versa must be ignored
752 // LyX emits a newline before \end{lyxcode}.
753 // This newline must be ignored,
754 // otherwise LyX will add an additional protected space.
755 if (next.cat() == catSpace ||
756 next.cat() == catNewline ||
757 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
760 context.check_layout(os);
766 * Parse all arguments of \p command
768 void parse_arguments(string const & command,
769 vector<ArgumentType> const & template_arguments,
770 Parser & p, ostream & os, bool outer, Context & context)
772 string ert = command;
773 size_t no_arguments = template_arguments.size();
774 for (size_t i = 0; i < no_arguments; ++i) {
775 switch (template_arguments[i]) {
778 // This argument contains regular LaTeX
779 output_ert_inset(os, ert + '{', context);
780 eat_whitespace(p, os, context, false);
781 if (template_arguments[i] == required)
782 parse_text(p, os, FLAG_ITEM, outer, context);
784 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
788 // This argument consists only of a single item.
789 // The presence of '{' or not must be preserved.
791 if (p.next_token().cat() == catBegin)
792 ert += '{' + p.verbatim_item() + '}';
794 ert += p.verbatim_item();
798 // This argument may contain special characters
799 ert += '{' + p.verbatim_item() + '}';
803 // true because we must not eat whitespace
804 // if an optional arg follows we must not strip the
805 // brackets from this one
806 if (i < no_arguments - 1 &&
807 template_arguments[i+1] == optional)
808 ert += p.getFullOpt(true);
810 ert += p.getOpt(true);
814 output_ert_inset(os, ert, context);
819 * Check whether \p command is a known command. If yes,
820 * handle the command with all arguments.
821 * \return true if the command was parsed, false otherwise.
823 bool parse_command(string const & command, Parser & p, ostream & os,
824 bool outer, Context & context)
826 if (known_commands.find(command) != known_commands.end()) {
827 parse_arguments(command, known_commands[command], p, os,
835 /// Parses a minipage or parbox
836 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
837 unsigned inner_flags, bool outer, Context & parent_context,
838 string const & outer_type, string const & special,
839 string inner_type, string const & frame_color,
840 string const & background_color)
844 string hor_pos = "l";
845 // We need to set the height to the LaTeX default of 1\\totalheight
846 // for the case when no height argument is given
847 string height_value = "1";
848 string height_unit = "in";
849 string height_special = "totalheight";
854 string width_special = "none";
855 string thickness = "0.4pt";
856 if (!fboxrule.empty())
857 thickness = fboxrule;
861 if (!fboxsep.empty())
862 separation = fboxsep;
866 if (!shadow_size.empty())
867 shadowsize = shadow_size;
870 string framecolor = "black";
871 string backgroundcolor = "none";
872 if (!frame_color.empty())
873 framecolor = frame_color;
874 if (!background_color.empty())
875 backgroundcolor = background_color;
876 // if there is a color box around the \begin statements have not yet been parsed
878 if (!frame_color.empty() || !background_color.empty()) {
879 eat_whitespace(p, os, parent_context, false);
880 p.get_token().asInput(); // the '{'
882 if (p.next_token().asInput() == "\\begin") {
883 p.get_token().asInput();
885 inner_type = "minipage";
886 inner_flags = FLAG_END;
887 active_environments.push_back("minipage");
890 else if (p.next_token().asInput() == "\\parbox") {
891 p.get_token().asInput();
892 inner_type = "parbox";
893 inner_flags = FLAG_ITEM;
896 else if (p.next_token().asInput() == "\\makebox") {
897 p.get_token().asInput();
898 inner_type = "makebox";
899 inner_flags = FLAG_ITEM;
901 // in case there is just \colorbox{color}{text}
904 inner_type = "makebox";
905 inner_flags = FLAG_BRACE_LAST;
910 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
912 if (!inner_type.empty() && p.hasOpt()) {
913 if (inner_type != "makebox")
914 position = p.getArg('[', ']');
916 latex_width = p.getArg('[', ']');
917 translate_box_len(latex_width, width_value, width_unit, width_special);
920 if (position != "t" && position != "c" && position != "b") {
921 cerr << "invalid position " << position << " for "
922 << inner_type << endl;
926 if (inner_type != "makebox") {
927 latex_height = p.getArg('[', ']');
928 translate_box_len(latex_height, height_value, height_unit, height_special);
930 string const opt = p.getArg('[', ']');
933 if (hor_pos != "l" && hor_pos != "c" &&
934 hor_pos != "r" && hor_pos != "s") {
935 cerr << "invalid hor_pos " << hor_pos
936 << " for " << inner_type << endl;
943 inner_pos = p.getArg('[', ']');
944 if (inner_pos != "c" && inner_pos != "t" &&
945 inner_pos != "b" && inner_pos != "s") {
946 cerr << "invalid inner_pos "
947 << inner_pos << " for "
948 << inner_type << endl;
949 inner_pos = position;
953 if (inner_type == "makebox")
957 if (inner_type.empty()) {
958 if (special.empty() && outer_type != "framebox")
959 latex_width = "1\\columnwidth";
962 latex_width = p2.getArg('[', ']');
963 string const opt = p2.getArg('[', ']');
966 if (hor_pos != "l" && hor_pos != "c" &&
967 hor_pos != "r" && hor_pos != "s") {
968 cerr << "invalid hor_pos " << hor_pos
969 << " for " << outer_type << endl;
973 if (outer_type == "framebox")
977 } else if (inner_type != "makebox")
978 latex_width = p.verbatim_item();
979 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
980 // as this is LyX's standard for such cases (except for makebox)
981 // \framebox is more special and handled below
982 if (latex_width.empty() && inner_type != "makebox"
983 && outer_type != "framebox")
984 latex_width = "1\\columnwidth";
986 translate_len(latex_width, width_value, width_unit);
988 bool shadedparbox = false;
989 if (inner_type == "shaded") {
990 eat_whitespace(p, os, parent_context, false);
991 if (outer_type == "parbox") {
993 if (p.next_token().cat() == catBegin)
995 eat_whitespace(p, os, parent_context, false);
1001 // If we already read the inner box we have to push the inner env
1002 if (!outer_type.empty() && !inner_type.empty() &&
1003 (inner_flags & FLAG_END))
1004 active_environments.push_back(inner_type);
1005 bool use_ert = false;
1006 if (!outer_type.empty() && !inner_type.empty()) {
1007 // Look whether there is some content after the end of the
1008 // inner box, but before the end of the outer box.
1009 // If yes, we need to output ERT.
1011 if (inner_flags & FLAG_END)
1012 p.ertEnvironment(inner_type);
1015 p.skip_spaces(true);
1016 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1017 if ((outer_env && p.next_token().asInput() != "\\end") ||
1018 (!outer_env && p.next_token().cat() != catEnd)) {
1019 // something is between the end of the inner box and
1020 // the end of the outer box, so we need to use ERT.
1026 // try to determine the box content alignment
1027 // first handle the simple case of "{\centering..."
1028 if (p.next_token().asInput() == "\\raggedright") {
1031 } else if (p.next_token().asInput() == "\\centering") {
1034 } else if (p.next_token().asInput() == "\\raggedleft") {
1038 // now handle the cases "{%catNewline\centering..."
1039 // and "{catNewline\centering..."
1041 p.get_token().asInput();
1042 if (p.next_token().cat() == catComment || p.next_token().cat() == catNewline)
1043 p.get_token().asInput();
1044 if (p.next_token().asInput() == "\\raggedright") {
1047 } else if (p.next_token().asInput() == "\\centering") {
1050 } else if (p.next_token().asInput() == "\\raggedleft") {
1059 if (!outer_type.empty()) {
1060 if (outer_flags & FLAG_END)
1061 ss << "\\begin{" << outer_type << '}';
1063 ss << '\\' << outer_type << '{';
1064 if (!special.empty())
1068 if (!inner_type.empty()) {
1069 if (inner_type != "shaded") {
1070 if (inner_flags & FLAG_END)
1071 ss << "\\begin{" << inner_type << '}';
1073 ss << '\\' << inner_type;
1075 if (!position.empty())
1076 ss << '[' << position << ']';
1077 if (!latex_height.empty())
1078 ss << '[' << latex_height << ']';
1079 if (!inner_pos.empty())
1080 ss << '[' << inner_pos << ']';
1081 ss << '{' << latex_width << '}';
1082 if (!(inner_flags & FLAG_END))
1085 if (inner_type == "shaded")
1086 ss << "\\begin{shaded}";
1087 output_ert_inset(os, ss.str(), parent_context);
1088 if (!inner_type.empty()) {
1089 parse_text(p, os, inner_flags, outer, parent_context);
1090 if (inner_flags & FLAG_END)
1091 output_ert_inset(os, "\\end{" + inner_type + '}',
1094 output_ert_inset(os, "}", parent_context);
1096 if (!outer_type.empty()) {
1097 // If we already read the inner box we have to pop
1099 if (!inner_type.empty() && (inner_flags & FLAG_END))
1100 active_environments.pop_back();
1102 // Ensure that the end of the outer box is parsed correctly:
1103 // The opening brace has been eaten by parse_outer_box()
1104 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1105 outer_flags &= ~FLAG_ITEM;
1106 outer_flags |= FLAG_BRACE_LAST;
1108 parse_text(p, os, outer_flags, outer, parent_context);
1109 if (outer_flags & FLAG_END)
1110 output_ert_inset(os, "\\end{" + outer_type + '}',
1113 output_ert_inset(os, "}", parent_context);
1116 // LyX does not like empty positions, so we have
1117 // to set them to the LaTeX default values here.
1118 if (position.empty())
1120 if (inner_pos.empty())
1121 inner_pos = position;
1122 parent_context.check_layout(os);
1123 begin_inset(os, "Box ");
1124 if (outer_type == "framed")
1126 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1128 else if (outer_type == "shadowbox")
1129 os << "Shadowbox\n";
1130 else if ((outer_type == "shaded" && inner_type.empty()) ||
1131 (outer_type == "minipage" && inner_type == "shaded") ||
1132 (outer_type == "parbox" && inner_type == "shaded")) {
1134 preamble.registerAutomaticallyLoadedPackage("color");
1135 } else if (outer_type == "doublebox")
1136 os << "Doublebox\n";
1137 else if (outer_type.empty() || outer_type == "mbox")
1138 os << "Frameless\n";
1140 os << outer_type << '\n';
1141 os << "position \"" << position << "\"\n";
1142 os << "hor_pos \"" << hor_pos << "\"\n";
1143 if (outer_type == "mbox")
1144 os << "has_inner_box 1\n";
1145 else if (!frame_color.empty() && inner_type == "makebox")
1146 os << "has_inner_box 0\n";
1148 os << "has_inner_box " << !inner_type.empty() << "\n";
1149 os << "inner_pos \"" << inner_pos << "\"\n";
1150 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1152 if (outer_type == "mbox")
1153 os << "use_makebox 1\n";
1154 else if (!frame_color.empty())
1155 os << "use_makebox 0\n";
1157 os << "use_makebox " << (inner_type == "makebox") << '\n';
1158 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1159 os << "width \"\"\n";
1160 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1161 else if (contains(width_unit, '\\'))
1162 os << "width \"" << width_value << "in" << "\"\n";
1164 os << "width \"" << width_value << width_unit << "\"\n";
1165 if (contains(width_unit, '\\')) {
1166 width_unit.erase (0,1); // remove the leading '\'
1167 os << "special \"" << width_unit << "\"\n";
1169 os << "special \"" << width_special << "\"\n";
1170 if (contains(height_unit, '\\'))
1171 os << "height \"" << height_value << "in" << "\"\n";
1173 os << "height \"" << height_value << height_unit << "\"\n";
1174 os << "height_special \"" << height_special << "\"\n";
1175 os << "thickness \"" << thickness << "\"\n";
1176 os << "separation \"" << separation << "\"\n";
1177 os << "shadowsize \"" << shadowsize << "\"\n";
1178 os << "framecolor \"" << framecolor << "\"\n";
1179 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1180 os << "status open\n\n";
1182 // Unfortunately we can't use parse_text_in_inset:
1183 // InsetBox::forcePlainLayout() is hard coded and does not
1184 // use the inset layout. Apart from that do we call parse_text
1185 // up to two times, but need only one check_end_layout.
1186 bool const forcePlainLayout =
1187 (!inner_type.empty() || inner_type == "makebox") &&
1188 outer_type != "shaded" && outer_type != "framed";
1189 Context context(true, parent_context.textclass);
1190 if (forcePlainLayout)
1191 context.layout = &context.textclass.plainLayout();
1193 context.font = parent_context.font;
1195 // If we have no inner box the contents will be read with the outer box
1196 if (!inner_type.empty())
1197 parse_text(p, os, inner_flags, outer, context);
1199 // Ensure that the end of the outer box is parsed correctly:
1200 // The opening brace has been eaten by parse_outer_box()
1201 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1202 outer_flags &= ~FLAG_ITEM;
1203 outer_flags |= FLAG_BRACE_LAST;
1206 // Find end of outer box, output contents if inner_type is
1207 // empty and output possible comments
1208 if (!outer_type.empty()) {
1209 // If we already read the inner box we have to pop
1211 if (!inner_type.empty() && (inner_flags & FLAG_END))
1212 active_environments.pop_back();
1213 // This does not output anything but comments if
1214 // inner_type is not empty (see use_ert)
1215 parse_text(p, os, outer_flags, outer, context);
1218 context.check_end_layout(os);
1220 #ifdef PRESERVE_LAYOUT
1221 // LyX puts a % after the end of the minipage
1222 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1224 //output_ert_inset(os, "%dummy", parent_context);
1227 parent_context.new_paragraph(os);
1229 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1230 //output_ert_inset(os, "%dummy", parent_context);
1233 // We add a protected space if something real follows
1234 if (p.good() && p.next_token().cat() != catComment) {
1235 begin_inset(os, "space ~\n");
1241 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1242 active_environments.pop_back();
1243 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1244 // in this case we have to eat the the closing brace of the color box
1245 p.get_token().asInput(); // the '}'
1247 if (p.next_token().asInput() == "}") {
1248 // in this case we assume that the closing brace is from the box settings
1249 // therefore reset these values for the next box
1255 // all boxes except of Frameless and Shaded require calc
1256 if (!(outer_type.empty() || outer_type == "mbox") &&
1257 !((outer_type == "shaded" && inner_type.empty()) ||
1258 (outer_type == "minipage" && inner_type == "shaded") ||
1259 (outer_type == "parbox" && inner_type == "shaded")))
1260 preamble.registerAutomaticallyLoadedPackage("calc");
1264 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1265 Context & parent_context, string const & outer_type,
1266 string const & special)
1268 eat_whitespace(p, os, parent_context, false);
1269 if (flags & FLAG_ITEM) {
1271 if (p.next_token().cat() == catBegin)
1274 cerr << "Warning: Ignoring missing '{' after \\"
1275 << outer_type << '.' << endl;
1276 eat_whitespace(p, os, parent_context, false);
1279 unsigned int inner_flags = 0;
1281 if (outer_type == "minipage" || outer_type == "parbox") {
1282 p.skip_spaces(true);
1283 while (p.hasOpt()) {
1285 p.skip_spaces(true);
1288 p.skip_spaces(true);
1289 if (outer_type == "parbox") {
1291 if (p.next_token().cat() == catBegin)
1293 p.skip_spaces(true);
1296 if (outer_type == "shaded" || outer_type == "mbox") {
1297 // These boxes never have an inner box
1299 } else if (p.next_token().asInput() == "\\parbox") {
1300 inner = p.get_token().cs();
1301 inner_flags = FLAG_ITEM;
1302 } else if (p.next_token().asInput() == "\\begin") {
1303 // Is this a minipage or shaded box?
1306 inner = p.getArg('{', '}');
1308 if (inner == "minipage" || inner == "shaded")
1309 inner_flags = FLAG_END;
1314 if (inner_flags == FLAG_END) {
1315 if (inner != "shaded")
1319 eat_whitespace(p, os, parent_context, false);
1321 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1322 outer_type, special, inner, "", "");
1324 if (inner_flags == FLAG_ITEM) {
1326 eat_whitespace(p, os, parent_context, false);
1328 parse_box(p, os, flags, inner_flags, outer, parent_context,
1329 outer_type, special, inner, "", "");
1334 void parse_listings(Parser & p, ostream & os, Context & parent_context, bool in_line)
1336 parent_context.check_layout(os);
1337 begin_inset(os, "listings\n");
1339 string arg = p.verbatimOption();
1340 os << "lstparams " << '"' << arg << '"' << '\n';
1341 if (arg.find("\\color") != string::npos)
1342 preamble.registerAutomaticallyLoadedPackage("color");
1345 os << "inline true\n";
1347 os << "inline false\n";
1348 os << "status collapsed\n";
1349 Context context(true, parent_context.textclass);
1350 context.layout = &parent_context.textclass.plainLayout();
1353 // set catcodes to verbatim early, just in case.
1354 p.setCatcodes(VERBATIM_CATCODES);
1355 string delim = p.get_token().asInput();
1356 //FIXME: handler error condition
1357 s = p.verbatimStuff(delim).second;
1358 // context.new_paragraph(os);
1360 s = p.verbatimEnvironment("lstlisting");
1361 output_ert(os, s, context);
1366 /// parse an unknown environment
1367 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1368 unsigned flags, bool outer,
1369 Context & parent_context)
1371 if (name == "tabbing")
1372 // We need to remember that we have to handle '\=' specially
1373 flags |= FLAG_TABBING;
1375 // We need to translate font changes and paragraphs inside the
1376 // environment to ERT if we have a non standard font.
1377 // Otherwise things like
1378 // \large\begin{foo}\huge bar\end{foo}
1380 bool const specialfont =
1381 (parent_context.font != parent_context.normalfont);
1382 bool const new_layout_allowed = parent_context.new_layout_allowed;
1384 parent_context.new_layout_allowed = false;
1385 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1386 parse_text_snippet(p, os, flags, outer, parent_context);
1387 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1389 parent_context.new_layout_allowed = new_layout_allowed;
1393 void parse_environment(Parser & p, ostream & os, bool outer,
1394 string & last_env, Context & parent_context)
1396 Layout const * newlayout;
1397 InsetLayout const * newinsetlayout = 0;
1398 string const name = p.getArg('{', '}');
1399 const bool is_starred = suffixIs(name, '*');
1400 string const unstarred_name = rtrim(name, "*");
1401 active_environments.push_back(name);
1403 if (is_math_env(name)) {
1404 parent_context.check_layout(os);
1405 begin_inset(os, "Formula ");
1406 os << "\\begin{" << name << "}";
1407 parse_math(p, os, FLAG_END, MATH_MODE);
1408 os << "\\end{" << name << "}";
1410 if (is_display_math_env(name)) {
1411 // Prevent the conversion of a line break to a space
1412 // (bug 7668). This does not change the output, but
1413 // looks ugly in LyX.
1414 eat_whitespace(p, os, parent_context, false);
1418 else if (is_known(name, preamble.polyglossia_languages)) {
1419 // We must begin a new paragraph if not already done
1420 if (! parent_context.atParagraphStart()) {
1421 parent_context.check_end_layout(os);
1422 parent_context.new_paragraph(os);
1424 // save the language in the context so that it is
1425 // handled by parse_text
1426 parent_context.font.language = preamble.polyglossia2lyx(name);
1427 parse_text(p, os, FLAG_END, outer, parent_context);
1428 // Just in case the environment is empty
1429 parent_context.extra_stuff.erase();
1430 // We must begin a new paragraph to reset the language
1431 parent_context.new_paragraph(os);
1435 else if (unstarred_name == "tabular" || name == "longtable") {
1436 eat_whitespace(p, os, parent_context, false);
1437 string width = "0pt";
1438 if (name == "tabular*") {
1439 width = lyx::translate_len(p.getArg('{', '}'));
1440 eat_whitespace(p, os, parent_context, false);
1442 parent_context.check_layout(os);
1443 begin_inset(os, "Tabular ");
1444 handle_tabular(p, os, name, width, parent_context);
1449 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1450 eat_whitespace(p, os, parent_context, false);
1451 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1452 eat_whitespace(p, os, parent_context, false);
1453 parent_context.check_layout(os);
1454 begin_inset(os, "Float " + unstarred_name + "\n");
1455 // store the float type for subfloats
1456 // subfloats only work with figures and tables
1457 if (unstarred_name == "figure")
1458 float_type = unstarred_name;
1459 else if (unstarred_name == "table")
1460 float_type = unstarred_name;
1464 os << "placement " << opt << '\n';
1465 if (contains(opt, "H"))
1466 preamble.registerAutomaticallyLoadedPackage("float");
1468 Floating const & fl = parent_context.textclass.floats()
1469 .getType(unstarred_name);
1470 if (!fl.floattype().empty() && fl.usesFloatPkg())
1471 preamble.registerAutomaticallyLoadedPackage("float");
1474 os << "wide " << convert<string>(is_starred)
1475 << "\nsideways false"
1476 << "\nstatus open\n\n";
1477 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1479 // We don't need really a new paragraph, but
1480 // we must make sure that the next item gets a \begin_layout.
1481 parent_context.new_paragraph(os);
1483 // the float is parsed thus delete the type
1487 else if (unstarred_name == "sidewaysfigure"
1488 || unstarred_name == "sidewaystable") {
1489 eat_whitespace(p, os, parent_context, false);
1490 parent_context.check_layout(os);
1491 if (unstarred_name == "sidewaysfigure")
1492 begin_inset(os, "Float figure\n");
1494 begin_inset(os, "Float table\n");
1495 os << "wide " << convert<string>(is_starred)
1496 << "\nsideways true"
1497 << "\nstatus open\n\n";
1498 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1500 // We don't need really a new paragraph, but
1501 // we must make sure that the next item gets a \begin_layout.
1502 parent_context.new_paragraph(os);
1504 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1507 else if (name == "wrapfigure" || name == "wraptable") {
1508 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1509 eat_whitespace(p, os, parent_context, false);
1510 parent_context.check_layout(os);
1513 string overhang = "0col%";
1516 lines = p.getArg('[', ']');
1517 string const placement = p.getArg('{', '}');
1519 overhang = p.getArg('[', ']');
1520 string const width = p.getArg('{', '}');
1522 if (name == "wrapfigure")
1523 begin_inset(os, "Wrap figure\n");
1525 begin_inset(os, "Wrap table\n");
1526 os << "lines " << lines
1527 << "\nplacement " << placement
1528 << "\noverhang " << lyx::translate_len(overhang)
1529 << "\nwidth " << lyx::translate_len(width)
1530 << "\nstatus open\n\n";
1531 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1533 // We don't need really a new paragraph, but
1534 // we must make sure that the next item gets a \begin_layout.
1535 parent_context.new_paragraph(os);
1537 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1540 else if (name == "minipage") {
1541 eat_whitespace(p, os, parent_context, false);
1542 // Test whether this is an outer box of a shaded box
1544 // swallow arguments
1545 while (p.hasOpt()) {
1547 p.skip_spaces(true);
1550 p.skip_spaces(true);
1551 Token t = p.get_token();
1552 bool shaded = false;
1553 if (t.asInput() == "\\begin") {
1554 p.skip_spaces(true);
1555 if (p.getArg('{', '}') == "shaded")
1560 parse_outer_box(p, os, FLAG_END, outer,
1561 parent_context, name, "shaded");
1563 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1564 "", "", name, "", "");
1568 else if (name == "comment") {
1569 eat_whitespace(p, os, parent_context, false);
1570 parent_context.check_layout(os);
1571 begin_inset(os, "Note Comment\n");
1572 os << "status open\n";
1573 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1576 skip_braces(p); // eat {} that might by set by LyX behind comments
1577 preamble.registerAutomaticallyLoadedPackage("verbatim");
1580 else if (name == "verbatim") {
1581 // FIXME: this should go in the generic code that
1582 // handles environments defined in layout file that
1583 // have "PassThru 1". However, the code over there is
1584 // already too complicated for my taste.
1585 parent_context.new_paragraph(os);
1586 Context context(true, parent_context.textclass,
1587 &parent_context.textclass[from_ascii("Verbatim")]);
1588 string s = p.verbatimEnvironment("verbatim");
1589 output_ert(os, s, context);
1593 else if (name == "IPA") {
1594 eat_whitespace(p, os, parent_context, false);
1595 parent_context.check_layout(os);
1596 begin_inset(os, "IPA\n");
1597 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1600 preamble.registerAutomaticallyLoadedPackage("tipa");
1601 preamble.registerAutomaticallyLoadedPackage("tipx");
1604 else if (name == "CJK") {
1605 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1606 // It is impossible to decide if a CJK environment was in its own paragraph or within
1607 // a line. We therefore always assume a paragraph since the latter is a rare case.
1608 eat_whitespace(p, os, parent_context, false);
1609 parent_context.check_end_layout(os);
1610 // store the encoding to be able to reset it
1611 string const encoding_old = p.getEncoding();
1612 string const encoding = p.getArg('{', '}');
1613 // FIXME: For some reason JIS does not work. Although the text
1614 // in tests/CJK.tex is identical with the SJIS version if you
1615 // convert both snippets using the recode command line utility,
1616 // the resulting .lyx file contains some extra characters if
1617 // you set buggy_encoding to false for JIS.
1618 bool const buggy_encoding = encoding == "JIS";
1619 if (!buggy_encoding)
1620 p.setEncoding(encoding, Encoding::CJK);
1622 // FIXME: This will read garbage, since the data is not encoded in utf8.
1623 p.setEncoding("UTF-8");
1625 // LyX only supports the same mapping for all CJK
1626 // environments, so we might need to output everything as ERT
1627 string const mapping = trim(p.getArg('{', '}'));
1628 char const * const * const where =
1629 is_known(encoding, supported_CJK_encodings);
1630 if (!buggy_encoding && !preamble.fontCJKSet())
1631 preamble.fontCJK(mapping);
1632 bool knownMapping = mapping == preamble.fontCJK();
1633 if (buggy_encoding || !knownMapping || !where) {
1634 parent_context.check_layout(os);
1635 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1637 // we must parse the content as verbatim because e.g. JIS can contain
1638 // normally invalid characters
1639 // FIXME: This works only for the most simple cases.
1640 // Since TeX control characters are not parsed,
1641 // things like comments are completely wrong.
1642 string const s = p.plainEnvironment("CJK");
1643 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1645 output_ert_inset(os, "\\", parent_context);
1646 else if (*it == '$')
1647 output_ert_inset(os, "$", parent_context);
1648 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1653 output_ert_inset(os, "\\end{" + name + "}",
1657 supported_CJK_languages[where - supported_CJK_encodings];
1658 // store the language because we must reset it at the end
1659 string const lang_old = parent_context.font.language;
1660 parent_context.font.language = lang;
1661 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1662 parent_context.font.language = lang_old;
1663 parent_context.new_paragraph(os);
1665 p.setEncoding(encoding_old);
1669 else if (name == "lyxgreyedout") {
1670 eat_whitespace(p, os, parent_context, false);
1671 parent_context.check_layout(os);
1672 begin_inset(os, "Note Greyedout\n");
1673 os << "status open\n";
1674 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1677 if (!preamble.notefontcolor().empty())
1678 preamble.registerAutomaticallyLoadedPackage("color");
1681 else if (name == "btSect") {
1682 eat_whitespace(p, os, parent_context, false);
1683 parent_context.check_layout(os);
1684 begin_command_inset(os, "bibtex", "bibtex");
1685 string bibstyle = "plain";
1687 bibstyle = p.getArg('[', ']');
1688 p.skip_spaces(true);
1690 string const bibfile = p.getArg('{', '}');
1691 eat_whitespace(p, os, parent_context, false);
1692 Token t = p.get_token();
1693 if (t.asInput() == "\\btPrintCited") {
1694 p.skip_spaces(true);
1695 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1697 if (t.asInput() == "\\btPrintNotCited") {
1698 p.skip_spaces(true);
1699 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1701 if (t.asInput() == "\\btPrintAll") {
1702 p.skip_spaces(true);
1703 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1705 os << "bibfiles " << '"' << bibfile << '"' << "\n";
1706 os << "options " << '"' << bibstyle << '"' << "\n";
1707 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1712 else if (name == "framed" || name == "shaded") {
1713 eat_whitespace(p, os, parent_context, false);
1714 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1716 preamble.registerAutomaticallyLoadedPackage("framed");
1719 else if (name == "lstlisting") {
1720 eat_whitespace(p, os, parent_context, false);
1721 parse_listings(p, os, parent_context, false);
1725 else if (!parent_context.new_layout_allowed)
1726 parse_unknown_environment(p, name, os, FLAG_END, outer,
1729 // Alignment and spacing settings
1730 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1731 // therefore are totally broken!
1732 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1733 // they are commands not environments. They are furthermore switches that
1734 // can be ended by another switches, but also by commands like \footnote or
1735 // \parbox. So the only safe way is to leave them untouched.
1736 else if (name == "center" || name == "centering" ||
1737 name == "flushleft" || name == "flushright" ||
1738 name == "singlespace" || name == "onehalfspace" ||
1739 name == "doublespace" || name == "spacing") {
1740 eat_whitespace(p, os, parent_context, false);
1741 // We must begin a new paragraph if not already done
1742 if (! parent_context.atParagraphStart()) {
1743 parent_context.check_end_layout(os);
1744 parent_context.new_paragraph(os);
1746 if (name == "flushleft")
1747 parent_context.add_extra_stuff("\\align left\n");
1748 else if (name == "flushright")
1749 parent_context.add_extra_stuff("\\align right\n");
1750 else if (name == "center" || name == "centering")
1751 parent_context.add_extra_stuff("\\align center\n");
1752 else if (name == "singlespace")
1753 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1754 else if (name == "onehalfspace") {
1755 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1756 preamble.registerAutomaticallyLoadedPackage("setspace");
1757 } else if (name == "doublespace") {
1758 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1759 preamble.registerAutomaticallyLoadedPackage("setspace");
1760 } else if (name == "spacing") {
1761 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1762 preamble.registerAutomaticallyLoadedPackage("setspace");
1764 parse_text(p, os, FLAG_END, outer, parent_context);
1765 // Just in case the environment is empty
1766 parent_context.extra_stuff.erase();
1767 // We must begin a new paragraph to reset the alignment
1768 parent_context.new_paragraph(os);
1772 // The single '=' is meant here.
1773 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1774 eat_whitespace(p, os, parent_context, false);
1775 Context context(true, parent_context.textclass, newlayout,
1776 parent_context.layout, parent_context.font);
1777 if (parent_context.deeper_paragraph) {
1778 // We are beginning a nested environment after a
1779 // deeper paragraph inside the outer list environment.
1780 // Therefore we don't need to output a "begin deeper".
1781 context.need_end_deeper = true;
1783 parent_context.check_end_layout(os);
1784 if (last_env == name) {
1785 // we need to output a separator since LyX would export
1786 // the two environments as one otherwise (bug 5716)
1787 TeX2LyXDocClass const & textclass(parent_context.textclass);
1788 Context newcontext(true, textclass,
1789 &(textclass.defaultLayout()));
1790 newcontext.check_layout(os);
1791 begin_inset(os, "Separator plain\n");
1793 newcontext.check_end_layout(os);
1795 switch (context.layout->latextype) {
1796 case LATEX_LIST_ENVIRONMENT:
1797 context.add_par_extra_stuff("\\labelwidthstring "
1798 + p.verbatim_item() + '\n');
1801 case LATEX_BIB_ENVIRONMENT:
1802 p.verbatim_item(); // swallow next arg
1808 context.check_deeper(os);
1809 // handle known optional and required arguments
1810 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1811 // It is impossible to place anything after the environment name,
1812 // but before the first \\item.
1813 if (context.layout->latextype == LATEX_ENVIRONMENT)
1814 output_arguments(os, p, outer, false, false, context,
1815 context.layout->latexargs());
1816 parse_text(p, os, FLAG_END, outer, context);
1817 if (context.layout->latextype == LATEX_ENVIRONMENT)
1818 output_arguments(os, p, outer, false, true, context,
1819 context.layout->postcommandargs());
1820 context.check_end_layout(os);
1821 if (parent_context.deeper_paragraph) {
1822 // We must suppress the "end deeper" because we
1823 // suppressed the "begin deeper" above.
1824 context.need_end_deeper = false;
1826 context.check_end_deeper(os);
1827 parent_context.new_paragraph(os);
1829 if (!preamble.titleLayoutFound())
1830 preamble.titleLayoutFound(newlayout->intitle);
1831 set<string> const & req = newlayout->requires();
1832 set<string>::const_iterator it = req.begin();
1833 set<string>::const_iterator en = req.end();
1834 for (; it != en; ++it)
1835 preamble.registerAutomaticallyLoadedPackage(*it);
1838 // The single '=' is meant here.
1839 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1840 eat_whitespace(p, os, parent_context, false);
1841 parent_context.check_layout(os);
1842 begin_inset(os, "Flex ");
1843 os << to_utf8(newinsetlayout->name()) << '\n'
1844 << "status collapsed\n";
1845 if (newinsetlayout->isPassThru()) {
1846 string const arg = p.verbatimEnvironment(name);
1847 Context context(true, parent_context.textclass,
1848 &parent_context.textclass.plainLayout(),
1849 parent_context.layout);
1850 output_ert(os, arg, parent_context);
1852 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1856 else if (name == "appendix") {
1857 // This is no good latex style, but it works and is used in some documents...
1858 eat_whitespace(p, os, parent_context, false);
1859 parent_context.check_end_layout(os);
1860 Context context(true, parent_context.textclass, parent_context.layout,
1861 parent_context.layout, parent_context.font);
1862 context.check_layout(os);
1863 os << "\\start_of_appendix\n";
1864 parse_text(p, os, FLAG_END, outer, context);
1865 context.check_end_layout(os);
1869 else if (known_environments.find(name) != known_environments.end()) {
1870 vector<ArgumentType> arguments = known_environments[name];
1871 // The last "argument" denotes wether we may translate the
1872 // environment contents to LyX
1873 // The default required if no argument is given makes us
1874 // compatible with the reLyXre environment.
1875 ArgumentType contents = arguments.empty() ?
1878 if (!arguments.empty())
1879 arguments.pop_back();
1880 // See comment in parse_unknown_environment()
1881 bool const specialfont =
1882 (parent_context.font != parent_context.normalfont);
1883 bool const new_layout_allowed =
1884 parent_context.new_layout_allowed;
1886 parent_context.new_layout_allowed = false;
1887 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1888 outer, parent_context);
1889 if (contents == verbatim)
1890 output_ert_inset(os, p.ertEnvironment(name),
1893 parse_text_snippet(p, os, FLAG_END, outer,
1895 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1897 parent_context.new_layout_allowed = new_layout_allowed;
1901 parse_unknown_environment(p, name, os, FLAG_END, outer,
1905 active_environments.pop_back();
1909 /// parses a comment and outputs it to \p os.
1910 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1912 LASSERT(t.cat() == catComment, return);
1913 if (!t.cs().empty()) {
1914 context.check_layout(os);
1915 output_ert_inset(os, '%' + t.cs(), context);
1916 if (p.next_token().cat() == catNewline) {
1917 // A newline after a comment line starts a new
1919 if (context.new_layout_allowed) {
1920 if(!context.atParagraphStart())
1921 // Only start a new paragraph if not already
1922 // done (we might get called recursively)
1923 context.new_paragraph(os);
1925 output_ert_inset(os, "\n", context);
1926 eat_whitespace(p, os, context, true);
1929 // "%\n" combination
1936 * Reads spaces and comments until the first non-space, non-comment token.
1937 * New paragraphs (double newlines or \\par) are handled like simple spaces
1938 * if \p eatParagraph is true.
1939 * Spaces are skipped, but comments are written to \p os.
1941 void eat_whitespace(Parser & p, ostream & os, Context & context,
1945 Token const & t = p.get_token();
1946 if (t.cat() == catComment)
1947 parse_comment(p, os, t, context);
1948 else if ((! eatParagraph && p.isParagraph()) ||
1949 (t.cat() != catSpace && t.cat() != catNewline)) {
1958 * Set a font attribute, parse text and reset the font attribute.
1959 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1960 * \param currentvalue Current value of the attribute. Is set to the new
1961 * value during parsing.
1962 * \param newvalue New value of the attribute
1964 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1965 Context & context, string const & attribute,
1966 string & currentvalue, string const & newvalue)
1968 context.check_layout(os);
1969 string const oldvalue = currentvalue;
1970 currentvalue = newvalue;
1971 os << '\n' << attribute << ' ' << newvalue << "\n";
1972 parse_text_snippet(p, os, flags, outer, context);
1973 context.check_layout(os);
1974 os << '\n' << attribute << ' ' << oldvalue << "\n";
1975 currentvalue = oldvalue;
1979 /// get the arguments of a natbib or jurabib citation command
1980 void get_cite_arguments(Parser & p, bool natbibOrder,
1981 string & before, string & after)
1983 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1985 // text before the citation
1987 // text after the citation
1988 after = p.getFullOpt();
1990 if (!after.empty()) {
1991 before = p.getFullOpt();
1992 if (natbibOrder && !before.empty())
1993 swap(before, after);
1998 /// Convert filenames with TeX macros and/or quotes to something LyX
2000 string const normalize_filename(string const & name)
2005 Token const & t = p.get_token();
2006 if (t.cat() != catEscape)
2008 else if (t.cs() == "lyxdot") {
2009 // This is used by LyX for simple dots in relative
2013 } else if (t.cs() == "space") {
2016 } else if (t.cs() == "string") {
2017 // Convert \string" to " and \string~ to ~
2018 Token const & n = p.next_token();
2019 if (n.asInput() != "\"" && n.asInput() != "~")
2024 // Strip quotes. This is a bit complicated (see latex_path()).
2025 string full = os.str();
2026 if (!full.empty() && full[0] == '"') {
2027 string base = removeExtension(full);
2028 string ext = getExtension(full);
2029 if (!base.empty() && base[base.length()-1] == '"')
2032 return addExtension(trim(base, "\""), ext);
2033 if (full[full.length()-1] == '"')
2036 return trim(full, "\"");
2042 /// Convert \p name from TeX convention (relative to master file) to LyX
2043 /// convention (relative to .lyx file) if it is relative
2044 void fix_child_filename(string & name)
2046 string const absMasterTeX = getMasterFilePath(true);
2047 bool const isabs = FileName::isAbsolute(name);
2048 // convert from "relative to .tex master" to absolute original path
2050 name = makeAbsPath(name, absMasterTeX).absFileName();
2051 bool copyfile = copyFiles();
2052 string const absParentLyX = getParentFilePath(false);
2055 // convert from absolute original path to "relative to master file"
2056 string const rel = to_utf8(makeRelPath(from_utf8(name),
2057 from_utf8(absMasterTeX)));
2058 // re-interpret "relative to .tex file" as "relative to .lyx file"
2059 // (is different if the master .lyx file resides in a
2060 // different path than the master .tex file)
2061 string const absMasterLyX = getMasterFilePath(false);
2062 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2063 // Do not copy if the new path is impossible to create. Example:
2064 // absMasterTeX = "/foo/bar/"
2065 // absMasterLyX = "/bar/"
2066 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2067 if (contains(name, "/../"))
2074 // convert from absolute original path to
2075 // "relative to .lyx file"
2076 name = to_utf8(makeRelPath(from_utf8(abs),
2077 from_utf8(absParentLyX)));
2081 // convert from absolute original path to "relative to .lyx file"
2082 name = to_utf8(makeRelPath(from_utf8(name),
2083 from_utf8(absParentLyX)));
2088 void copy_file(FileName const & src, string dstname)
2092 string const absParent = getParentFilePath(false);
2094 if (FileName::isAbsolute(dstname))
2095 dst = FileName(dstname);
2097 dst = makeAbsPath(dstname, absParent);
2098 string const absMaster = getMasterFilePath(false);
2099 FileName const srcpath = src.onlyPath();
2100 FileName const dstpath = dst.onlyPath();
2101 if (equivalent(srcpath, dstpath))
2103 if (!dstpath.isDirectory()) {
2104 if (!dstpath.createPath()) {
2105 cerr << "Warning: Could not create directory for file `"
2106 << dst.absFileName() << "´." << endl;
2110 if (dst.isReadableFile()) {
2111 if (overwriteFiles())
2112 cerr << "Warning: Overwriting existing file `"
2113 << dst.absFileName() << "´." << endl;
2115 cerr << "Warning: Not overwriting existing file `"
2116 << dst.absFileName() << "´." << endl;
2120 if (!src.copyTo(dst))
2121 cerr << "Warning: Could not copy file `" << src.absFileName()
2122 << "´ to `" << dst.absFileName() << "´." << endl;
2126 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2127 bool parse_chunk(Parser & p, ostream & os, Context & context)
2129 // check whether a chunk is possible here.
2130 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2136 // read the parameters
2137 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2138 if (!params.first) {
2143 Parser::Arg const code = p.verbatimStuff("\n@");
2148 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2149 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2153 // The last newline read is important for paragraph handling
2157 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2158 // We must have a valid layout before outputting the Chunk inset.
2159 context.check_layout(os);
2160 Context chunkcontext(true, context.textclass);
2161 chunkcontext.layout = &context.textclass.plainLayout();
2162 begin_inset(os, "Flex Chunk");
2163 os << "\nstatus open\n";
2164 if (!params.second.empty()) {
2165 chunkcontext.check_layout(os);
2166 Context paramscontext(true, context.textclass);
2167 paramscontext.layout = &context.textclass.plainLayout();
2168 begin_inset(os, "Argument 1");
2169 os << "\nstatus open\n";
2170 output_ert(os, params.second, paramscontext);
2173 output_ert(os, code.second, chunkcontext);
2181 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2182 bool is_macro(Parser & p)
2184 Token first = p.curr_token();
2185 if (first.cat() != catEscape || !p.good())
2187 if (first.cs() == "def")
2189 if (first.cs() != "global" && first.cs() != "long")
2191 Token second = p.get_token();
2193 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2194 second.cat() == catNewline || second.cat() == catComment)) {
2195 second = p.get_token();
2198 bool secondvalid = second.cat() == catEscape;
2200 bool thirdvalid = false;
2201 if (p.good() && first.cs() == "global" && secondvalid &&
2202 second.cs() == "long") {
2203 third = p.get_token();
2205 while (p.good() && !p.isParagraph() &&
2206 (third.cat() == catSpace ||
2207 third.cat() == catNewline ||
2208 third.cat() == catComment)) {
2209 third = p.get_token();
2212 thirdvalid = third.cat() == catEscape;
2214 for (int i = 0; i < pos; ++i)
2219 return (first.cs() == "global" || first.cs() == "long") &&
2220 second.cs() == "def";
2221 return first.cs() == "global" && second.cs() == "long" &&
2222 third.cs() == "def";
2226 /// Parse a macro definition (assumes that is_macro() returned true)
2227 void parse_macro(Parser & p, ostream & os, Context & context)
2229 context.check_layout(os);
2230 Token first = p.curr_token();
2233 string command = first.asInput();
2234 if (first.cs() != "def") {
2236 eat_whitespace(p, os, context, false);
2237 second = p.curr_token();
2238 command += second.asInput();
2239 if (second.cs() != "def") {
2241 eat_whitespace(p, os, context, false);
2242 third = p.curr_token();
2243 command += third.asInput();
2246 eat_whitespace(p, os, context, false);
2247 string const name = p.get_token().cs();
2248 eat_whitespace(p, os, context, false);
2254 while (p.next_token().cat() != catBegin) {
2255 if (p.next_token().cat() == catParameter) {
2260 // followed by number?
2261 if (p.next_token().cat() == catOther) {
2262 string s = p.get_token().asInput();
2264 // number = current arity + 1?
2265 if (s.size() == 1 && s[0] == arity + '0' + 1)
2270 paramtext += p.get_token().cs();
2272 paramtext += p.get_token().cs();
2277 // only output simple (i.e. compatible) macro as FormulaMacros
2278 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2280 context.check_layout(os);
2281 begin_inset(os, "FormulaMacro");
2282 os << "\n\\def" << ert;
2285 output_ert_inset(os, command + ert, context);
2289 void registerExternalTemplatePackages(string const & name)
2291 external::TemplateManager const & etm = external::TemplateManager::get();
2292 external::Template const * const et = etm.getTemplateByName(name);
2295 external::Template::Formats::const_iterator cit = et->formats.end();
2297 cit = et->formats.find("PDFLaTeX");
2298 if (cit == et->formats.end())
2299 // If the template has not specified a PDFLaTeX output,
2300 // we try the LaTeX format.
2301 cit = et->formats.find("LaTeX");
2302 if (cit == et->formats.end())
2304 vector<string>::const_iterator qit = cit->second.requirements.begin();
2305 vector<string>::const_iterator qend = cit->second.requirements.end();
2306 for (; qit != qend; ++qit)
2307 preamble.registerAutomaticallyLoadedPackage(*qit);
2310 } // anonymous namespace
2313 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2316 Layout const * newlayout = 0;
2317 InsetLayout const * newinsetlayout = 0;
2318 char const * const * where = 0;
2319 // Store the latest bibliographystyle, addcontentslineContent and
2320 // nocite{*} option (needed for bibtex inset)
2322 string contentslineContent;
2323 string bibliographystyle = "default";
2324 bool const use_natbib = isProvided("natbib");
2325 bool const use_jurabib = isProvided("jurabib");
2328 // it is impossible to determine the correct encoding for non-CJK Japanese.
2329 // Therefore write a note at the beginning of the document
2330 if (is_nonCJKJapanese) {
2331 context.check_layout(os);
2332 begin_inset(os, "Note Note\n");
2333 os << "status open\n\\begin_layout Plain Layout\n"
2334 << "\\series bold\n"
2335 << "Important information:\n"
2336 << "\\end_layout\n\n"
2337 << "\\begin_layout Plain Layout\n"
2338 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2339 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2340 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2341 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2342 << " and specify the encoding using the -e command-line switch.\n"
2343 << " In addition, you might want to double check that the desired output encoding\n"
2344 << " is correctly selected in Document > Settings > Language.\n"
2345 << "\\end_layout\n";
2347 is_nonCJKJapanese = false;
2351 Token const & t = p.get_token();
2353 debugToken(cerr, t, flags);
2356 if (flags & FLAG_ITEM) {
2357 if (t.cat() == catSpace)
2360 flags &= ~FLAG_ITEM;
2361 if (t.cat() == catBegin) {
2362 // skip the brace and collect everything to the next matching
2364 flags |= FLAG_BRACE_LAST;
2368 // handle only this single token, leave the loop if done
2369 flags |= FLAG_LEAVE;
2372 if (t.cat() != catEscape && t.character() == ']' &&
2373 (flags & FLAG_BRACK_LAST))
2375 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2378 // If there is anything between \end{env} and \begin{env} we
2379 // don't need to output a separator.
2380 if (t.cat() != catSpace && t.cat() != catNewline &&
2381 t.asInput() != "\\begin")
2387 bool const starred = p.next_token().asInput() == "*";
2388 string const starredname(starred ? (t.cs() + '*') : t.cs());
2389 if (t.cat() == catMath) {
2390 // we are inside some text mode thingy, so opening new math is allowed
2391 context.check_layout(os);
2392 begin_inset(os, "Formula ");
2393 Token const & n = p.get_token();
2394 bool const display(n.cat() == catMath && outer);
2396 // TeX's $$...$$ syntax for displayed math
2398 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2400 p.get_token(); // skip the second '$' token
2402 // simple $...$ stuff
2405 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2410 // Prevent the conversion of a line break to a
2411 // space (bug 7668). This does not change the
2412 // output, but looks ugly in LyX.
2413 eat_whitespace(p, os, context, false);
2417 else if (t.cat() == catSuper || t.cat() == catSub)
2418 cerr << "catcode " << t << " illegal in text mode\n";
2420 // Basic support for english quotes. This should be
2421 // extended to other quotes, but is not so easy (a
2422 // left english quote is the same as a right german
2424 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2425 context.check_layout(os);
2426 begin_inset(os, "Quotes ");
2432 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2433 context.check_layout(os);
2434 begin_inset(os, "Quotes ");
2441 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2442 context.check_layout(os);
2443 begin_inset(os, "Quotes ");
2450 else if (t.asInput() == "<"
2451 && p.next_token().asInput() == "<") {
2452 bool has_chunk = false;
2456 has_chunk = parse_chunk(p, os, context);
2462 context.check_layout(os);
2463 begin_inset(os, "Quotes ");
2464 //FIXME: this is a right danish quote;
2465 // why not a left french quote?
2473 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2474 check_space(p, os, context);
2476 else if (t.character() == '[' && noweb_mode &&
2477 p.next_token().character() == '[') {
2478 // These can contain underscores
2480 string const s = p.getFullOpt() + ']';
2481 if (p.next_token().character() == ']')
2484 cerr << "Warning: Inserting missing ']' in '"
2485 << s << "'." << endl;
2486 output_ert_inset(os, s, context);
2489 else if (t.cat() == catLetter) {
2490 context.check_layout(os);
2494 else if (t.cat() == catOther ||
2495 t.cat() == catAlign ||
2496 t.cat() == catParameter) {
2497 context.check_layout(os);
2498 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2499 context.merging_hyphens_allowed &&
2500 context.font.family != "ttfamily" &&
2501 !context.layout->pass_thru) {
2502 if (p.next_next_token().asInput() == "-") {
2504 os << to_utf8(docstring(1, 0x2014));
2508 os << to_utf8(docstring(1, 0x2013));
2511 // This translates "&" to "\\&" which may be wrong...
2515 else if (p.isParagraph()) {
2516 if (context.new_layout_allowed)
2517 context.new_paragraph(os);
2519 output_ert_inset(os, "\\par ", context);
2520 eat_whitespace(p, os, context, true);
2523 else if (t.cat() == catActive) {
2524 context.check_layout(os);
2525 if (t.character() == '~') {
2526 if (context.layout->free_spacing)
2529 begin_inset(os, "space ~\n");
2536 else if (t.cat() == catBegin) {
2537 Token const next = p.next_token();
2538 Token const end = p.next_next_token();
2539 if (next.cat() == catEnd) {
2541 Token const prev = p.prev_token();
2543 if (p.next_token().character() == '`')
2544 ; // ignore it in {}``
2546 output_ert_inset(os, "{}", context);
2547 } else if (next.cat() == catEscape &&
2548 is_known(next.cs(), known_quotes) &&
2549 end.cat() == catEnd) {
2550 // Something like {\textquoteright} (e.g.
2551 // from writer2latex). LyX writes
2552 // \textquoteright{}, so we may skip the
2553 // braces here for better readability.
2554 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2556 } else if (p.next_token().asInput() == "\\ascii") {
2557 // handle the \ascii characters
2558 // (the case without braces is handled later)
2559 // the code is "{\ascii\xxx}"
2560 p.get_token(); // eat \ascii
2561 string name2 = p.get_token().asInput();
2562 p.get_token(); // eat the final '}'
2563 string const name = "{\\ascii" + name2 + "}";
2567 // get the character from unicodesymbols
2568 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2569 Encodings::TEXT_CMD, termination, rem, &req);
2571 context.check_layout(os);
2574 output_ert_inset(os,
2575 to_utf8(rem), context);
2576 for (set<string>::const_iterator it = req.begin();
2577 it != req.end(); ++it)
2578 preamble.registerAutomaticallyLoadedPackage(*it);
2580 // we did not find a non-ert version
2581 output_ert_inset(os, name, context);
2583 context.check_layout(os);
2584 // special handling of font attribute changes
2585 Token const prev = p.prev_token();
2586 TeXFont const oldFont = context.font;
2587 if (next.character() == '[' ||
2588 next.character() == ']' ||
2589 next.character() == '*') {
2591 if (p.next_token().cat() == catEnd) {
2596 output_ert_inset(os, "{", context);
2597 parse_text_snippet(p, os,
2600 output_ert_inset(os, "}", context);
2602 } else if (! context.new_layout_allowed) {
2603 output_ert_inset(os, "{", context);
2604 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2606 output_ert_inset(os, "}", context);
2607 } else if (is_known(next.cs(), known_sizes)) {
2608 // next will change the size, so we must
2610 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2612 if (!context.atParagraphStart())
2614 << context.font.size << "\n";
2615 } else if (is_known(next.cs(), known_font_families)) {
2616 // next will change the font family, so we
2617 // must reset it here
2618 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2620 if (!context.atParagraphStart())
2622 << context.font.family << "\n";
2623 } else if (is_known(next.cs(), known_font_series)) {
2624 // next will change the font series, so we
2625 // must reset it here
2626 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2628 if (!context.atParagraphStart())
2630 << context.font.series << "\n";
2631 } else if (is_known(next.cs(), known_font_shapes)) {
2632 // next will change the font shape, so we
2633 // must reset it here
2634 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2636 if (!context.atParagraphStart())
2638 << context.font.shape << "\n";
2639 } else if (is_known(next.cs(), known_old_font_families) ||
2640 is_known(next.cs(), known_old_font_series) ||
2641 is_known(next.cs(), known_old_font_shapes)) {
2642 // next will change the font family, series
2643 // and shape, so we must reset it here
2644 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2646 if (!context.atParagraphStart())
2648 << context.font.family
2650 << context.font.series
2652 << context.font.shape << "\n";
2654 output_ert_inset(os, "{", context);
2655 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2657 output_ert_inset(os, "}", context);
2662 else if (t.cat() == catEnd) {
2663 if (flags & FLAG_BRACE_LAST) {
2666 cerr << "stray '}' in text\n";
2667 output_ert_inset(os, "}", context);
2670 else if (t.cat() == catComment)
2671 parse_comment(p, os, t, context);
2674 // control sequences
2677 else if (t.cs() == "(" || t.cs() == "[") {
2678 bool const simple = t.cs() == "(";
2679 context.check_layout(os);
2680 begin_inset(os, "Formula");
2681 os << " \\" << t.cs();
2682 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2683 os << '\\' << (simple ? ')' : ']');
2686 // Prevent the conversion of a line break to a
2687 // space (bug 7668). This does not change the
2688 // output, but looks ugly in LyX.
2689 eat_whitespace(p, os, context, false);
2693 else if (t.cs() == "begin")
2694 parse_environment(p, os, outer, last_env,
2697 else if (t.cs() == "end") {
2698 if (flags & FLAG_END) {
2699 // eat environment name
2700 string const name = p.getArg('{', '}');
2701 if (name != active_environment())
2702 cerr << "\\end{" + name + "} does not match \\begin{"
2703 + active_environment() + "}\n";
2706 p.error("found 'end' unexpectedly");
2709 else if (t.cs() == "item") {
2711 bool const optarg = p.hasOpt();
2713 // FIXME: This swallows comments, but we cannot use
2714 // eat_whitespace() since we must not output
2715 // anything before the item.
2716 p.skip_spaces(true);
2717 s = p.verbatimOption();
2719 p.skip_spaces(false);
2721 context.check_layout(os);
2722 if (context.has_item) {
2723 // An item in an unknown list-like environment
2724 // FIXME: Do this in check_layout()!
2725 context.has_item = false;
2727 output_ert_inset(os, "\\item", context);
2729 output_ert_inset(os, "\\item ", context);
2732 if (context.layout->labeltype != LABEL_MANUAL) {
2733 // handle option of itemize item
2734 begin_inset(os, "Argument item:1\n");
2735 os << "status open\n";
2736 os << "\n\\begin_layout Plain Layout\n";
2738 os << parse_text_snippet(p2,
2739 FLAG_BRACK_LAST, outer, context);
2740 // we must not use context.check_end_layout(os)
2741 // because that would close the outer itemize layout
2742 os << "\n\\end_layout\n";
2744 eat_whitespace(p, os, context, false);
2745 } else if (!s.empty()) {
2746 // LyX adds braces around the argument,
2747 // so we need to remove them here.
2748 if (s.size() > 2 && s[0] == '{' &&
2749 s[s.size()-1] == '}')
2750 s = s.substr(1, s.size()-2);
2751 // If the argument contains a space we
2752 // must put it into ERT: Otherwise LyX
2753 // would misinterpret the space as
2754 // item delimiter (bug 7663)
2755 if (contains(s, ' ')) {
2756 output_ert_inset(os, s, context);
2759 os << parse_text_snippet(p2,
2760 FLAG_BRACK_LAST, outer, context);
2762 // The space is needed to separate the
2763 // item from the rest of the sentence.
2765 eat_whitespace(p, os, context, false);
2770 else if (t.cs() == "bibitem") {
2772 context.check_layout(os);
2773 eat_whitespace(p, os, context, false);
2774 string label = convert_command_inset_arg(p.verbatimOption());
2775 string key = convert_command_inset_arg(p.verbatim_item());
2776 if (contains(label, '\\') || contains(key, '\\')) {
2777 // LyX can't handle LaTeX commands in labels or keys
2778 output_ert_inset(os, t.asInput() + '[' + label +
2779 "]{" + p.verbatim_item() + '}',
2782 begin_command_inset(os, "bibitem", "bibitem");
2783 os << "label \"" << label << "\"\n"
2784 "key \"" << key << "\"\n";
2789 else if (is_macro(p)) {
2790 // catch the case of \def\inputGnumericTable
2792 if (t.cs() == "def") {
2793 Token second = p.next_token();
2794 if (second.cs() == "inputGnumericTable") {
2798 Token third = p.get_token();
2800 if (third.cs() == "input") {
2804 string name = normalize_filename(p.verbatim_item());
2805 string const path = getMasterFilePath(true);
2806 // We want to preserve relative / absolute filenames,
2807 // therefore path is only used for testing
2808 // The file extension is in every case ".tex".
2809 // So we need to remove this extension and check for
2810 // the original one.
2811 name = removeExtension(name);
2812 if (!makeAbsPath(name, path).exists()) {
2813 char const * const Gnumeric_formats[] = {"gnumeric",
2815 string const Gnumeric_name =
2816 find_file(name, path, Gnumeric_formats);
2817 if (!Gnumeric_name.empty())
2818 name = Gnumeric_name;
2820 FileName const absname = makeAbsPath(name, path);
2821 if (absname.exists()) {
2822 fix_child_filename(name);
2823 copy_file(absname, name);
2825 cerr << "Warning: Could not find file '"
2826 << name << "'." << endl;
2827 context.check_layout(os);
2828 begin_inset(os, "External\n\ttemplate ");
2829 os << "GnumericSpreadsheet\n\tfilename "
2832 context.check_layout(os);
2834 // register the packages that are automatically loaded
2835 // by the Gnumeric template
2836 registerExternalTemplatePackages("GnumericSpreadsheet");
2841 parse_macro(p, os, context);
2844 else if (t.cs() == "noindent") {
2846 context.add_par_extra_stuff("\\noindent\n");
2849 else if (t.cs() == "appendix") {
2850 context.add_par_extra_stuff("\\start_of_appendix\n");
2851 // We need to start a new paragraph. Otherwise the
2852 // appendix in 'bla\appendix\chapter{' would start
2854 context.new_paragraph(os);
2855 // We need to make sure that the paragraph is
2856 // generated even if it is empty. Otherwise the
2857 // appendix in '\par\appendix\par\chapter{' would
2859 context.check_layout(os);
2860 // FIXME: This is a hack to prevent paragraph
2861 // deletion if it is empty. Handle this better!
2862 output_ert_inset(os,
2863 "%dummy comment inserted by tex2lyx to "
2864 "ensure that this paragraph is not empty",
2866 // Both measures above may generate an additional
2867 // empty paragraph, but that does not hurt, because
2868 // whitespace does not matter here.
2869 eat_whitespace(p, os, context, true);
2872 // Must catch empty dates before findLayout is called below
2873 else if (t.cs() == "date") {
2874 eat_whitespace(p, os, context, false);
2876 string const date = p.verbatim_item();
2879 preamble.suppressDate(true);
2882 preamble.suppressDate(false);
2883 if (context.new_layout_allowed &&
2884 (newlayout = findLayout(context.textclass,
2887 output_command_layout(os, p, outer,
2888 context, newlayout);
2889 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2890 if (!preamble.titleLayoutFound())
2891 preamble.titleLayoutFound(newlayout->intitle);
2892 set<string> const & req = newlayout->requires();
2893 set<string>::const_iterator it = req.begin();
2894 set<string>::const_iterator en = req.end();
2895 for (; it != en; ++it)
2896 preamble.registerAutomaticallyLoadedPackage(*it);
2898 output_ert_inset(os,
2899 "\\date{" + p.verbatim_item() + '}',
2904 // Starred section headings
2905 // Must attempt to parse "Section*" before "Section".
2906 else if ((p.next_token().asInput() == "*") &&
2907 context.new_layout_allowed &&
2908 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2911 output_command_layout(os, p, outer, context, newlayout);
2913 if (!preamble.titleLayoutFound())
2914 preamble.titleLayoutFound(newlayout->intitle);
2915 set<string> const & req = newlayout->requires();
2916 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2917 preamble.registerAutomaticallyLoadedPackage(*it);
2920 // Section headings and the like
2921 else if (context.new_layout_allowed &&
2922 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2924 output_command_layout(os, p, outer, context, newlayout);
2926 if (!preamble.titleLayoutFound())
2927 preamble.titleLayoutFound(newlayout->intitle);
2928 set<string> const & req = newlayout->requires();
2929 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2930 preamble.registerAutomaticallyLoadedPackage(*it);
2933 else if (t.cs() == "subfloat") {
2934 // the syntax is \subfloat[list entry][sub caption]{content}
2935 // if it is a table of figure depends on the surrounding float
2936 // FIXME: second optional argument is not parsed
2937 bool has_caption = false;
2939 // do nothing if there is no outer float
2940 if (!float_type.empty()) {
2941 context.check_layout(os);
2943 begin_inset(os, "Float " + float_type + "\n");
2945 << "\nsideways false"
2946 << "\nstatus collapsed\n\n";
2949 if (p.next_token().cat() != catEscape &&
2950 p.next_token().character() == '[') {
2951 p.get_token(); // eat '['
2952 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2956 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2957 // the caption comes always as the last
2959 // we must make sure that the caption gets a \begin_layout
2960 os << "\n\\begin_layout Plain Layout";
2962 begin_inset(os, "Caption Standard\n");
2963 Context newcontext(true, context.textclass,
2964 0, 0, context.font);
2965 newcontext.check_layout(os);
2966 os << caption << "\n";
2967 newcontext.check_end_layout(os);
2968 // We don't need really a new paragraph, but
2969 // we must make sure that the next item gets a \begin_layout.
2970 //newcontext.new_paragraph(os);
2974 // We don't need really a new paragraph, but
2975 // we must make sure that the next item gets a \begin_layout.
2977 context.new_paragraph(os);
2980 context.check_end_layout(os);
2981 // close the layout we opened
2983 os << "\n\\end_layout\n";
2985 // if the float type is not supported or there is no surrounding float
2988 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2989 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2990 "]{" + p.verbatim_item() + '}', context);
2992 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2996 else if (t.cs() == "includegraphics") {
2997 bool const clip = p.next_token().asInput() == "*";
3000 string const arg = p.getArg('[', ']');
3001 map<string, string> opts;
3002 vector<string> keys;
3003 split_map(arg, opts, keys);
3005 opts["clip"] = string();
3006 string name = normalize_filename(p.verbatim_item());
3008 string const path = getMasterFilePath(true);
3009 // We want to preserve relative / absolute filenames,
3010 // therefore path is only used for testing
3011 if (!makeAbsPath(name, path).exists()) {
3012 // The file extension is probably missing.
3013 // Now try to find it out.
3014 string const dvips_name =
3015 find_file(name, path,
3016 known_dvips_graphics_formats);
3017 string const pdftex_name =
3018 find_file(name, path,
3019 known_pdftex_graphics_formats);
3020 if (!dvips_name.empty()) {
3021 if (!pdftex_name.empty()) {
3022 cerr << "This file contains the "
3024 "\"\\includegraphics{"
3026 "However, files\n\""
3027 << dvips_name << "\" and\n\""
3028 << pdftex_name << "\"\n"
3029 "both exist, so I had to make a "
3030 "choice and took the first one.\n"
3031 "Please move the unwanted one "
3032 "someplace else and try again\n"
3033 "if my choice was wrong."
3037 } else if (!pdftex_name.empty()) {
3043 FileName const absname = makeAbsPath(name, path);
3044 if (absname.exists()) {
3045 fix_child_filename(name);
3046 copy_file(absname, name);
3048 cerr << "Warning: Could not find graphics file '"
3049 << name << "'." << endl;
3051 context.check_layout(os);
3052 begin_inset(os, "Graphics ");
3053 os << "\n\tfilename " << name << '\n';
3054 if (opts.find("width") != opts.end())
3056 << translate_len(opts["width"]) << '\n';
3057 if (opts.find("height") != opts.end())
3059 << translate_len(opts["height"]) << '\n';
3060 if (opts.find("scale") != opts.end()) {
3061 istringstream iss(opts["scale"]);
3065 os << "\tscale " << val << '\n';
3067 if (opts.find("angle") != opts.end()) {
3068 os << "\trotateAngle "
3069 << opts["angle"] << '\n';
3070 vector<string>::const_iterator a =
3071 find(keys.begin(), keys.end(), "angle");
3072 vector<string>::const_iterator s =
3073 find(keys.begin(), keys.end(), "width");
3074 if (s == keys.end())
3075 s = find(keys.begin(), keys.end(), "height");
3076 if (s == keys.end())
3077 s = find(keys.begin(), keys.end(), "scale");
3078 if (s != keys.end() && distance(s, a) > 0)
3079 os << "\tscaleBeforeRotation\n";
3081 if (opts.find("origin") != opts.end()) {
3083 string const opt = opts["origin"];
3084 if (opt.find('l') != string::npos) ss << "left";
3085 if (opt.find('r') != string::npos) ss << "right";
3086 if (opt.find('c') != string::npos) ss << "center";
3087 if (opt.find('t') != string::npos) ss << "Top";
3088 if (opt.find('b') != string::npos) ss << "Bottom";
3089 if (opt.find('B') != string::npos) ss << "Baseline";
3090 if (!ss.str().empty())
3091 os << "\trotateOrigin " << ss.str() << '\n';
3093 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3095 if (opts.find("keepaspectratio") != opts.end())
3096 os << "\tkeepAspectRatio\n";
3097 if (opts.find("clip") != opts.end())
3099 if (opts.find("draft") != opts.end())
3101 if (opts.find("bb") != opts.end())
3102 os << "\tBoundingBox "
3103 << opts["bb"] << '\n';
3104 int numberOfbbOptions = 0;
3105 if (opts.find("bbllx") != opts.end())
3106 numberOfbbOptions++;
3107 if (opts.find("bblly") != opts.end())
3108 numberOfbbOptions++;
3109 if (opts.find("bburx") != opts.end())
3110 numberOfbbOptions++;
3111 if (opts.find("bbury") != opts.end())
3112 numberOfbbOptions++;
3113 if (numberOfbbOptions == 4)
3114 os << "\tBoundingBox "
3115 << opts["bbllx"] << " " << opts["bblly"] << " "
3116 << opts["bburx"] << " " << opts["bbury"] << '\n';
3117 else if (numberOfbbOptions > 0)
3118 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3119 numberOfbbOptions = 0;
3120 if (opts.find("natwidth") != opts.end())
3121 numberOfbbOptions++;
3122 if (opts.find("natheight") != opts.end())
3123 numberOfbbOptions++;
3124 if (numberOfbbOptions == 2)
3125 os << "\tBoundingBox 0bp 0bp "
3126 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3127 else if (numberOfbbOptions > 0)
3128 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3129 ostringstream special;
3130 if (opts.find("hiresbb") != opts.end())
3131 special << "hiresbb,";
3132 if (opts.find("trim") != opts.end())
3134 if (opts.find("viewport") != opts.end())
3135 special << "viewport=" << opts["viewport"] << ',';
3136 if (opts.find("totalheight") != opts.end())
3137 special << "totalheight=" << opts["totalheight"] << ',';
3138 if (opts.find("type") != opts.end())
3139 special << "type=" << opts["type"] << ',';
3140 if (opts.find("ext") != opts.end())
3141 special << "ext=" << opts["ext"] << ',';
3142 if (opts.find("read") != opts.end())
3143 special << "read=" << opts["read"] << ',';
3144 if (opts.find("command") != opts.end())
3145 special << "command=" << opts["command"] << ',';
3146 string s_special = special.str();
3147 if (!s_special.empty()) {
3148 // We had special arguments. Remove the trailing ','.
3149 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3151 // TODO: Handle the unknown settings better.
3152 // Warn about invalid options.
3153 // Check whether some option was given twice.
3155 preamble.registerAutomaticallyLoadedPackage("graphicx");
3158 else if (t.cs() == "footnote" ||
3159 (t.cs() == "thanks" && context.layout->intitle)) {
3161 context.check_layout(os);
3162 begin_inset(os, "Foot\n");
3163 os << "status collapsed\n\n";
3164 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3168 else if (t.cs() == "marginpar") {
3170 context.check_layout(os);
3171 begin_inset(os, "Marginal\n");
3172 os << "status collapsed\n\n";
3173 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3177 else if (t.cs() == "lstinline") {
3179 parse_listings(p, os, context, true);
3182 else if (t.cs() == "ensuremath") {
3184 context.check_layout(os);
3185 string const s = p.verbatim_item();
3186 //FIXME: this never triggers in UTF8
3187 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3190 output_ert_inset(os, "\\ensuremath{" + s + "}",
3194 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3195 if (preamble.titleLayoutFound()) {
3197 skip_spaces_braces(p);
3199 output_ert_inset(os, t.asInput(), context);
3202 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3203 context.check_layout(os);
3204 begin_command_inset(os, "toc", t.cs());
3206 skip_spaces_braces(p);
3207 if (t.cs() == "lstlistoflistings")
3208 preamble.registerAutomaticallyLoadedPackage("listings");
3211 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3212 context.check_layout(os);
3213 if (t.cs() == "listoffigures")
3214 begin_inset(os, "FloatList figure\n");
3216 begin_inset(os, "FloatList table\n");
3218 skip_spaces_braces(p);
3221 else if (t.cs() == "listof") {
3222 p.skip_spaces(true);
3223 string const name = p.get_token().cs();
3224 if (context.textclass.floats().typeExist(name)) {
3225 context.check_layout(os);
3226 begin_inset(os, "FloatList ");
3229 p.get_token(); // swallow second arg
3231 output_ert_inset(os, "\\listof{" + name + "}", context);
3234 else if ((where = is_known(t.cs(), known_text_font_families)))
3235 parse_text_attributes(p, os, FLAG_ITEM, outer,
3236 context, "\\family", context.font.family,
3237 known_coded_font_families[where - known_text_font_families]);
3239 else if ((where = is_known(t.cs(), known_text_font_series)))
3240 parse_text_attributes(p, os, FLAG_ITEM, outer,
3241 context, "\\series", context.font.series,
3242 known_coded_font_series[where - known_text_font_series]);
3244 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3245 parse_text_attributes(p, os, FLAG_ITEM, outer,
3246 context, "\\shape", context.font.shape,
3247 known_coded_font_shapes[where - known_text_font_shapes]);
3249 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3250 context.check_layout(os);
3251 TeXFont oldFont = context.font;
3252 context.font.init();
3253 context.font.size = oldFont.size;
3254 os << "\n\\family " << context.font.family << "\n";
3255 os << "\n\\series " << context.font.series << "\n";
3256 os << "\n\\shape " << context.font.shape << "\n";
3257 if (t.cs() == "textnormal") {
3258 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3259 output_font_change(os, context.font, oldFont);
3260 context.font = oldFont;
3262 eat_whitespace(p, os, context, false);
3265 else if (t.cs() == "textcolor") {
3266 // scheme is \textcolor{color name}{text}
3267 string const color = p.verbatim_item();
3268 // we support the predefined colors of the color and the xcolor package
3269 if (color == "black" || color == "blue" || color == "cyan"
3270 || color == "green" || color == "magenta" || color == "red"
3271 || color == "white" || color == "yellow") {
3272 context.check_layout(os);
3273 os << "\n\\color " << color << "\n";
3274 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3275 context.check_layout(os);
3276 os << "\n\\color inherit\n";
3277 preamble.registerAutomaticallyLoadedPackage("color");
3278 } else if (color == "brown" || color == "darkgray" || color == "gray"
3279 || color == "lightgray" || color == "lime" || color == "olive"
3280 || color == "orange" || color == "pink" || color == "purple"
3281 || color == "teal" || color == "violet") {
3282 context.check_layout(os);
3283 os << "\n\\color " << color << "\n";
3284 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3285 context.check_layout(os);
3286 os << "\n\\color inherit\n";
3287 preamble.registerAutomaticallyLoadedPackage("xcolor");
3289 // for custom defined colors
3290 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3293 else if (t.cs() == "underbar" || t.cs() == "uline") {
3294 // \underbar is not 100% correct (LyX outputs \uline
3295 // of ulem.sty). The difference is that \ulem allows
3296 // line breaks, and \underbar does not.
3297 // Do NOT handle \underline.
3298 // \underbar cuts through y, g, q, p etc.,
3299 // \underline does not.
3300 context.check_layout(os);
3301 os << "\n\\bar under\n";
3302 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3303 context.check_layout(os);
3304 os << "\n\\bar default\n";
3305 preamble.registerAutomaticallyLoadedPackage("ulem");
3308 else if (t.cs() == "sout") {
3309 context.check_layout(os);
3310 os << "\n\\strikeout on\n";
3311 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3312 context.check_layout(os);
3313 os << "\n\\strikeout default\n";
3314 preamble.registerAutomaticallyLoadedPackage("ulem");
3317 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3318 t.cs() == "emph" || t.cs() == "noun") {
3319 context.check_layout(os);
3320 os << "\n\\" << t.cs() << " on\n";
3321 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3322 context.check_layout(os);
3323 os << "\n\\" << t.cs() << " default\n";
3324 if (t.cs() == "uuline" || t.cs() == "uwave")
3325 preamble.registerAutomaticallyLoadedPackage("ulem");
3328 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3329 context.check_layout(os);
3330 string name = p.getArg('{', '}');
3331 string localtime = p.getArg('{', '}');
3332 preamble.registerAuthor(name);
3333 Author const & author = preamble.getAuthor(name);
3334 // from_asctime_utc() will fail if LyX decides to output the
3335 // time in the text language.
3336 time_t ptime = from_asctime_utc(localtime);
3337 if (ptime == static_cast<time_t>(-1)) {
3338 cerr << "Warning: Could not parse time `" << localtime
3339 << "´ for change tracking, using current time instead.\n";
3340 ptime = current_time();
3342 if (t.cs() == "lyxadded")
3343 os << "\n\\change_inserted ";
3345 os << "\n\\change_deleted ";
3346 os << author.bufferId() << ' ' << ptime << '\n';
3347 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3348 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3349 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3350 LaTeXPackages::isAvailable("xcolor");
3351 // No need to test for luatex, since luatex comes in
3352 // two flavours (dvi and pdf), like latex, and those
3353 // are detected by pdflatex.
3354 if (pdflatex || xetex) {
3356 preamble.registerAutomaticallyLoadedPackage("ulem");
3357 preamble.registerAutomaticallyLoadedPackage("xcolor");
3358 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3362 preamble.registerAutomaticallyLoadedPackage("dvipost");
3363 } else if (xcolorulem) {
3364 preamble.registerAutomaticallyLoadedPackage("ulem");
3365 preamble.registerAutomaticallyLoadedPackage("xcolor");
3370 else if (t.cs() == "textipa") {
3371 context.check_layout(os);
3372 begin_inset(os, "IPA\n");
3373 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3374 context.merging_hyphens_allowed = false;
3375 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3376 context.merging_hyphens_allowed = merging_hyphens_allowed;
3378 preamble.registerAutomaticallyLoadedPackage("tipa");
3379 preamble.registerAutomaticallyLoadedPackage("tipx");
3382 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3383 context.check_layout(os);
3384 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3385 os << "status open\n";
3386 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3391 else if (t.cs() == "textvertline") {
3392 // FIXME: This is not correct, \textvertline is higher than |
3398 else if (t.cs() == "tone" ) {
3399 context.check_layout(os);
3400 // register the tone package
3401 preamble.registerAutomaticallyLoadedPackage("tone");
3402 string content = trimSpaceAndEol(p.verbatim_item());
3403 string command = t.asInput() + "{" + content + "}";
3404 // some tones can be detected by unicodesymbols, some need special code
3405 if (is_known(content, known_tones)) {
3406 os << "\\IPAChar " << command << "\n";
3409 // try to see whether the string is in unicodesymbols
3413 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3414 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3415 termination, rem, &req);
3419 output_ert_inset(os, to_utf8(rem), context);
3420 for (set<string>::const_iterator it = req.begin();
3421 it != req.end(); ++it)
3422 preamble.registerAutomaticallyLoadedPackage(*it);
3424 // we did not find a non-ert version
3425 output_ert_inset(os, command, context);
3428 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3429 t.cs() == "vphantom") {
3430 context.check_layout(os);
3431 if (t.cs() == "phantom")
3432 begin_inset(os, "Phantom Phantom\n");
3433 if (t.cs() == "hphantom")
3434 begin_inset(os, "Phantom HPhantom\n");
3435 if (t.cs() == "vphantom")
3436 begin_inset(os, "Phantom VPhantom\n");
3437 os << "status open\n";
3438 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3443 else if (t.cs() == "href") {
3444 context.check_layout(os);
3445 string target = convert_command_inset_arg(p.verbatim_item());
3446 string name = convert_command_inset_arg(p.verbatim_item());
3448 size_t i = target.find(':');
3449 if (i != string::npos) {
3450 type = target.substr(0, i + 1);
3451 if (type == "mailto:" || type == "file:")
3452 target = target.substr(i + 1);
3453 // handle the case that name is equal to target, except of "http://"
3454 else if (target.substr(i + 3) == name && type == "http:")
3457 begin_command_inset(os, "href", "href");
3459 os << "name \"" << name << "\"\n";
3460 os << "target \"" << target << "\"\n";
3461 if (type == "mailto:" || type == "file:")
3462 os << "type \"" << type << "\"\n";
3464 skip_spaces_braces(p);
3467 else if (t.cs() == "lyxline") {
3468 // swallow size argument (it is not used anyway)
3470 if (!context.atParagraphStart()) {
3471 // so our line is in the middle of a paragraph
3472 // we need to add a new line, lest this line
3473 // follow the other content on that line and
3474 // run off the side of the page
3475 // FIXME: This may create an empty paragraph,
3476 // but without that it would not be
3477 // possible to set noindent below.
3478 // Fortunately LaTeX does not care
3479 // about the empty paragraph.
3480 context.new_paragraph(os);
3482 if (preamble.indentParagraphs()) {
3483 // we need to unindent, lest the line be too long
3484 context.add_par_extra_stuff("\\noindent\n");
3486 context.check_layout(os);
3487 begin_command_inset(os, "line", "rule");
3488 os << "offset \"0.5ex\"\n"
3489 "width \"100line%\"\n"
3494 else if (t.cs() == "rule") {
3495 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3496 string const width = p.getArg('{', '}');
3497 string const thickness = p.getArg('{', '}');
3498 context.check_layout(os);
3499 begin_command_inset(os, "line", "rule");
3500 if (!offset.empty())
3501 os << "offset \"" << translate_len(offset) << "\"\n";
3502 os << "width \"" << translate_len(width) << "\"\n"
3503 "height \"" << translate_len(thickness) << "\"\n";
3507 // handle refstyle first to catch \eqref which can also occur
3508 // without refstyle. Only recognize these commands if
3509 // refstyle.sty was found in the preamble (otherwise \eqref
3510 // and user defined ref commands could be misdetected).
3511 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3512 preamble.refstyle()) {
3513 context.check_layout(os);
3514 begin_command_inset(os, "ref", "formatted");
3515 os << "reference \"";
3516 os << known_refstyle_prefixes[where - known_refstyle_commands]
3518 os << convert_command_inset_arg(p.verbatim_item())
3521 preamble.registerAutomaticallyLoadedPackage("refstyle");
3524 // if refstyle is used, we must not convert \prettyref to a
3525 // formatted reference, since that would result in a refstyle command.
3526 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3527 (t.cs() != "prettyref" || !preamble.refstyle())) {
3528 string const opt = p.getOpt();
3530 context.check_layout(os);
3531 begin_command_inset(os, "ref",
3532 known_coded_ref_commands[where - known_ref_commands]);
3533 os << "reference \""
3534 << convert_command_inset_arg(p.verbatim_item())
3537 if (t.cs() == "vref" || t.cs() == "vpageref")
3538 preamble.registerAutomaticallyLoadedPackage("varioref");
3539 else if (t.cs() == "prettyref")
3540 preamble.registerAutomaticallyLoadedPackage("prettyref");
3542 // LyX does not yet support optional arguments of ref commands
3543 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3544 p.verbatim_item() + '}', context);
3548 else if (use_natbib &&
3549 is_known(t.cs(), known_natbib_commands) &&
3550 ((t.cs() != "citefullauthor" &&
3551 t.cs() != "citeyear" &&
3552 t.cs() != "citeyearpar") ||
3553 p.next_token().asInput() != "*")) {
3554 context.check_layout(os);
3555 string command = t.cs();
3556 if (p.next_token().asInput() == "*") {
3560 if (command == "citefullauthor")
3561 // alternative name for "\\citeauthor*"
3562 command = "citeauthor*";
3564 // text before the citation
3566 // text after the citation
3568 get_cite_arguments(p, true, before, after);
3570 if (command == "cite") {
3571 // \cite without optional argument means
3572 // \citet, \cite with at least one optional
3573 // argument means \citep.
3574 if (before.empty() && after.empty())
3579 if (before.empty() && after == "[]")
3580 // avoid \citet[]{a}
3582 else if (before == "[]" && after == "[]") {
3583 // avoid \citet[][]{a}
3587 // remove the brackets around after and before
3588 if (!after.empty()) {
3590 after.erase(after.length() - 1, 1);
3591 after = convert_command_inset_arg(after);
3593 if (!before.empty()) {
3595 before.erase(before.length() - 1, 1);
3596 before = convert_command_inset_arg(before);
3598 begin_command_inset(os, "citation", command);
3599 os << "after " << '"' << after << '"' << "\n";
3600 os << "before " << '"' << before << '"' << "\n";
3602 << convert_command_inset_arg(p.verbatim_item())
3605 // Need to set the cite engine if natbib is loaded by
3606 // the document class directly
3607 if (preamble.citeEngine() == "basic")
3608 preamble.citeEngine("natbib");
3611 else if (use_jurabib &&
3612 is_known(t.cs(), known_jurabib_commands) &&
3613 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3614 context.check_layout(os);
3615 string command = t.cs();
3616 if (p.next_token().asInput() == "*") {
3620 char argumentOrder = '\0';
3621 vector<string> const options =
3622 preamble.getPackageOptions("jurabib");
3623 if (find(options.begin(), options.end(),
3624 "natbiborder") != options.end())
3625 argumentOrder = 'n';
3626 else if (find(options.begin(), options.end(),
3627 "jurabiborder") != options.end())
3628 argumentOrder = 'j';
3630 // text before the citation
3632 // text after the citation
3634 get_cite_arguments(p, argumentOrder != 'j', before, after);
3636 string const citation = p.verbatim_item();
3637 if (!before.empty() && argumentOrder == '\0') {
3638 cerr << "Warning: Assuming argument order "
3639 "of jurabib version 0.6 for\n'"
3640 << command << before << after << '{'
3641 << citation << "}'.\n"
3642 "Add 'jurabiborder' to the jurabib "
3643 "package options if you used an\n"
3644 "earlier jurabib version." << endl;
3646 if (!after.empty()) {
3648 after.erase(after.length() - 1, 1);
3650 if (!before.empty()) {
3652 before.erase(before.length() - 1, 1);
3654 begin_command_inset(os, "citation", command);
3655 os << "after " << '"' << after << '"' << "\n";
3656 os << "before " << '"' << before << '"' << "\n";
3657 os << "key " << '"' << citation << '"' << "\n";
3659 // Need to set the cite engine if jurabib is loaded by
3660 // the document class directly
3661 if (preamble.citeEngine() == "basic")
3662 preamble.citeEngine("jurabib");
3665 else if (t.cs() == "cite"
3666 || t.cs() == "nocite") {
3667 context.check_layout(os);
3668 string after = convert_command_inset_arg(p.getArg('[', ']'));
3669 string key = convert_command_inset_arg(p.verbatim_item());
3670 // store the case that it is "\nocite{*}" to use it later for
3673 begin_command_inset(os, "citation", t.cs());
3674 os << "after " << '"' << after << '"' << "\n";
3675 os << "key " << '"' << key << '"' << "\n";
3677 } else if (t.cs() == "nocite")
3681 else if (t.cs() == "index" ||
3682 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3683 context.check_layout(os);
3684 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3685 p.getArg('[', ']') : "";
3686 string const kind = arg.empty() ? "idx" : arg;
3687 begin_inset(os, "Index ");
3688 os << kind << "\nstatus collapsed\n";
3689 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3692 preamble.registerAutomaticallyLoadedPackage("splitidx");
3695 else if (t.cs() == "nomenclature") {
3696 context.check_layout(os);
3697 begin_command_inset(os, "nomenclature", "nomenclature");
3698 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3699 if (!prefix.empty())
3700 os << "prefix " << '"' << prefix << '"' << "\n";
3701 os << "symbol " << '"'
3702 << convert_command_inset_arg(p.verbatim_item());
3703 os << "\"\ndescription \""
3704 << convert_command_inset_arg(p.verbatim_item())
3707 preamble.registerAutomaticallyLoadedPackage("nomencl");
3710 else if (t.cs() == "label") {
3711 context.check_layout(os);
3712 begin_command_inset(os, "label", "label");
3714 << convert_command_inset_arg(p.verbatim_item())
3719 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3720 context.check_layout(os);
3721 string commandname = t.cs();
3723 if (p.next_token().asInput() == "*") {
3728 begin_command_inset(os, "index_print", commandname);
3729 string const indexname = p.getArg('[', ']');
3731 if (indexname.empty())
3732 os << "type \"idx\"\n";
3734 os << "type \"" << indexname << "\"\n";
3737 skip_spaces_braces(p);
3738 preamble.registerAutomaticallyLoadedPackage("makeidx");
3739 if (preamble.use_indices() == "true")
3740 preamble.registerAutomaticallyLoadedPackage("splitidx");
3743 else if (t.cs() == "printnomenclature") {
3745 string width_type = "";
3746 context.check_layout(os);
3747 begin_command_inset(os, "nomencl_print", "printnomenclature");
3748 // case of a custom width
3750 width = p.getArg('[', ']');
3751 width = translate_len(width);
3752 width_type = "custom";
3754 // case of no custom width
3755 // the case of no custom width but the width set
3756 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3757 // because the user could have set anything, not only the width
3758 // of the longest label (which would be width_type = "auto")
3759 string label = convert_command_inset_arg(p.getArg('{', '}'));
3760 if (label.empty() && width_type.empty())
3761 width_type = "none";
3762 os << "set_width \"" << width_type << "\"\n";
3763 if (width_type == "custom")
3764 os << "width \"" << width << '\"';
3766 skip_spaces_braces(p);
3767 preamble.registerAutomaticallyLoadedPackage("nomencl");
3770 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3771 context.check_layout(os);
3772 begin_inset(os, "script ");
3773 os << t.cs().substr(4) << '\n';
3774 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3775 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3777 if (t.cs() == "textsubscript")
3778 preamble.registerAutomaticallyLoadedPackage("subscript");
3781 else if ((where = is_known(t.cs(), known_quotes))) {
3782 context.check_layout(os);
3783 begin_inset(os, "Quotes ");
3784 os << known_coded_quotes[where - known_quotes];
3786 // LyX adds {} after the quote, so we have to eat
3787 // spaces here if there are any before a possible
3789 eat_whitespace(p, os, context, false);
3793 else if ((where = is_known(t.cs(), known_sizes)) &&
3794 context.new_layout_allowed) {
3795 context.check_layout(os);
3796 TeXFont const oldFont = context.font;
3797 context.font.size = known_coded_sizes[where - known_sizes];
3798 output_font_change(os, oldFont, context.font);
3799 eat_whitespace(p, os, context, false);
3802 else if ((where = is_known(t.cs(), known_font_families)) &&
3803 context.new_layout_allowed) {
3804 context.check_layout(os);
3805 TeXFont const oldFont = context.font;
3806 context.font.family =
3807 known_coded_font_families[where - known_font_families];
3808 output_font_change(os, oldFont, context.font);
3809 eat_whitespace(p, os, context, false);
3812 else if ((where = is_known(t.cs(), known_font_series)) &&
3813 context.new_layout_allowed) {
3814 context.check_layout(os);
3815 TeXFont const oldFont = context.font;
3816 context.font.series =
3817 known_coded_font_series[where - known_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_font_shapes)) &&
3823 context.new_layout_allowed) {
3824 context.check_layout(os);
3825 TeXFont const oldFont = context.font;
3826 context.font.shape =
3827 known_coded_font_shapes[where - known_font_shapes];
3828 output_font_change(os, oldFont, context.font);
3829 eat_whitespace(p, os, context, false);
3831 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3832 context.new_layout_allowed) {
3833 context.check_layout(os);
3834 TeXFont const oldFont = context.font;
3835 context.font.init();
3836 context.font.size = oldFont.size;
3837 context.font.family =
3838 known_coded_font_families[where - known_old_font_families];
3839 output_font_change(os, oldFont, context.font);
3840 eat_whitespace(p, os, context, false);
3843 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3844 context.new_layout_allowed) {
3845 context.check_layout(os);
3846 TeXFont const oldFont = context.font;
3847 context.font.init();
3848 context.font.size = oldFont.size;
3849 context.font.series =
3850 known_coded_font_series[where - known_old_font_series];
3851 output_font_change(os, oldFont, context.font);
3852 eat_whitespace(p, os, context, false);
3855 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3856 context.new_layout_allowed) {
3857 context.check_layout(os);
3858 TeXFont const oldFont = context.font;
3859 context.font.init();
3860 context.font.size = oldFont.size;
3861 context.font.shape =
3862 known_coded_font_shapes[where - known_old_font_shapes];
3863 output_font_change(os, oldFont, context.font);
3864 eat_whitespace(p, os, context, false);
3867 else if (t.cs() == "selectlanguage") {
3868 context.check_layout(os);
3869 // save the language for the case that a
3870 // \foreignlanguage is used
3871 context.font.language = babel2lyx(p.verbatim_item());
3872 os << "\n\\lang " << context.font.language << "\n";
3875 else if (t.cs() == "foreignlanguage") {
3876 string const lang = babel2lyx(p.verbatim_item());
3877 parse_text_attributes(p, os, FLAG_ITEM, outer,
3879 context.font.language, lang);
3882 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3883 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3884 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3886 // We have to output the whole command if it has an option
3887 // because LyX doesn't support this yet, see bug #8214,
3888 // only if there is a single option specifying a variant, we can handle it.
3890 string langopts = p.getOpt();
3891 // check if the option contains a variant, if yes, extract it
3892 string::size_type pos_var = langopts.find("variant");
3893 string::size_type i = langopts.find(',');
3894 string::size_type k = langopts.find('=', pos_var);
3895 if (pos_var != string::npos && i == string::npos) {
3897 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3898 lang = preamble.polyglossia2lyx(variant);
3899 parse_text_attributes(p, os, FLAG_ITEM, outer,
3901 context.font.language, lang);
3903 output_ert_inset(os, t.asInput() + langopts, context);
3905 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3906 parse_text_attributes(p, os, FLAG_ITEM, outer,
3908 context.font.language, lang);
3912 else if (t.cs() == "inputencoding") {
3913 // nothing to write here
3914 string const enc = subst(p.verbatim_item(), "\n", " ");
3915 p.setEncoding(enc, Encoding::inputenc);
3918 else if (is_known(t.cs(), known_special_chars) ||
3919 (t.cs() == "protect" &&
3920 p.next_token().cat() == catEscape &&
3921 is_known(p.next_token().cs(), known_special_protect_chars))) {
3922 // LyX sometimes puts a \protect in front, so we have to ignore it
3924 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3925 known_special_chars);
3926 context.check_layout(os);
3927 os << known_coded_special_chars[where - known_special_chars];
3928 skip_spaces_braces(p);
3931 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3932 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3933 p.next_next_token().asInput() == "-") ||
3934 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3935 // LyX sometimes puts a \protect in front, so we have to ignore it
3936 if (t.cs() == "protect")
3938 context.check_layout(os);
3939 if (t.cs() == "nobreakdash")
3940 os << "\\SpecialChar nobreakdash\n";
3942 os << "\\SpecialChar endofsentence\n";
3946 else if (t.cs() == "textquotedbl") {
3947 context.check_layout(os);
3952 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3953 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3954 || t.cs() == "%" || t.cs() == "-") {
3955 context.check_layout(os);
3957 os << "\\SpecialChar softhyphen\n";
3962 else if (t.cs() == "char") {
3963 context.check_layout(os);
3964 if (p.next_token().character() == '`') {
3966 if (p.next_token().cs() == "\"") {
3971 output_ert_inset(os, "\\char`", context);
3974 output_ert_inset(os, "\\char", context);
3978 else if (t.cs() == "verb") {
3979 context.check_layout(os);
3980 // set catcodes to verbatim early, just in case.
3981 p.setCatcodes(VERBATIM_CATCODES);
3982 string delim = p.get_token().asInput();
3983 Parser::Arg arg = p.verbatimStuff(delim);
3985 output_ert_inset(os, "\\verb" + delim
3986 + arg.second + delim, context);
3988 cerr << "invalid \\verb command. Skipping" << endl;
3991 // Problem: \= creates a tabstop inside the tabbing environment
3992 // and else an accent. In the latter case we really would want
3993 // \={o} instead of \= o.
3994 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3995 output_ert_inset(os, t.asInput(), context);
3997 else if (t.cs() == "\\") {
3998 context.check_layout(os);
4000 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4001 else if (p.next_token().asInput() == "*") {
4003 // getOpt() eats the following space if there
4004 // is no optional argument, but that is OK
4005 // here since it has no effect in the output.
4006 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4009 begin_inset(os, "Newline newline");
4014 else if (t.cs() == "newline" ||
4015 (t.cs() == "linebreak" && !p.hasOpt())) {
4016 context.check_layout(os);
4017 begin_inset(os, "Newline ");
4020 skip_spaces_braces(p);
4023 else if (t.cs() == "input" || t.cs() == "include"
4024 || t.cs() == "verbatiminput") {
4025 string name = t.cs();
4026 if (t.cs() == "verbatiminput"
4027 && p.next_token().asInput() == "*")
4028 name += p.get_token().asInput();
4029 context.check_layout(os);
4030 string filename(normalize_filename(p.getArg('{', '}')));
4031 string const path = getMasterFilePath(true);
4032 // We want to preserve relative / absolute filenames,
4033 // therefore path is only used for testing
4034 if ((t.cs() == "include" || t.cs() == "input") &&
4035 !makeAbsPath(filename, path).exists()) {
4036 // The file extension is probably missing.
4037 // Now try to find it out.
4038 string const tex_name =
4039 find_file(filename, path,
4040 known_tex_extensions);
4041 if (!tex_name.empty())
4042 filename = tex_name;
4044 bool external = false;
4046 if (makeAbsPath(filename, path).exists()) {
4047 string const abstexname =
4048 makeAbsPath(filename, path).absFileName();
4049 string const absfigname =
4050 changeExtension(abstexname, ".fig");
4051 fix_child_filename(filename);
4052 string const lyxname = changeExtension(filename,
4053 roundtripMode() ? ".lyx.lyx" : ".lyx");
4054 string const abslyxname = makeAbsPath(
4055 lyxname, getParentFilePath(false)).absFileName();
4057 if (!skipChildren())
4058 external = FileName(absfigname).exists();
4059 if (t.cs() == "input" && !skipChildren()) {
4060 string const ext = getExtension(abstexname);
4062 // Combined PS/LaTeX:
4063 // x.eps, x.pstex_t (old xfig)
4064 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4065 FileName const absepsname(
4066 changeExtension(abstexname, ".eps"));
4067 FileName const abspstexname(
4068 changeExtension(abstexname, ".pstex"));
4069 bool const xfigeps =
4070 (absepsname.exists() ||
4071 abspstexname.exists()) &&
4074 // Combined PDF/LaTeX:
4075 // x.pdf, x.pdftex_t (old xfig)
4076 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4077 FileName const abspdfname(
4078 changeExtension(abstexname, ".pdf"));
4079 bool const xfigpdf =
4080 abspdfname.exists() &&
4081 (ext == "pdftex_t" || ext == "pdf_t");
4085 // Combined PS/PDF/LaTeX:
4086 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4087 string const absbase2(
4088 removeExtension(abstexname) + "_pspdftex");
4089 FileName const abseps2name(
4090 addExtension(absbase2, ".eps"));
4091 FileName const abspdf2name(
4092 addExtension(absbase2, ".pdf"));
4093 bool const xfigboth =
4094 abspdf2name.exists() &&
4095 abseps2name.exists() && ext == "pspdftex";
4097 xfig = xfigpdf || xfigeps || xfigboth;
4098 external = external && xfig;
4101 outname = changeExtension(filename, ".fig");
4102 FileName abssrc(changeExtension(abstexname, ".fig"));
4103 copy_file(abssrc, outname);
4105 // Don't try to convert, the result
4106 // would be full of ERT.
4108 FileName abssrc(abstexname);
4109 copy_file(abssrc, outname);
4110 } else if (t.cs() != "verbatiminput" &&
4112 tex2lyx(abstexname, FileName(abslyxname),
4115 // no need to call copy_file
4116 // tex2lyx creates the file
4119 FileName abssrc(abstexname);
4120 copy_file(abssrc, outname);
4123 cerr << "Warning: Could not find included file '"
4124 << filename << "'." << endl;
4128 begin_inset(os, "External\n");
4129 os << "\ttemplate XFig\n"
4130 << "\tfilename " << outname << '\n';
4131 registerExternalTemplatePackages("XFig");
4133 begin_command_inset(os, "include", name);
4134 outname = subst(outname, "\"", "\\\"");
4135 os << "preview false\n"
4136 "filename \"" << outname << "\"\n";
4137 if (t.cs() == "verbatiminput")
4138 preamble.registerAutomaticallyLoadedPackage("verbatim");
4143 else if (t.cs() == "bibliographystyle") {
4144 // store new bibliographystyle
4145 bibliographystyle = p.verbatim_item();
4146 // If any other command than \bibliography, \addcontentsline
4147 // and \nocite{*} follows, we need to output the style
4148 // (because it might be used by that command).
4149 // Otherwise, it will automatically be output by LyX.
4152 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4153 if (t2.cat() == catBegin)
4155 if (t2.cat() != catEscape)
4157 if (t2.cs() == "nocite") {
4158 if (p.getArg('{', '}') == "*")
4160 } else if (t2.cs() == "bibliography")
4162 else if (t2.cs() == "phantomsection") {
4166 else if (t2.cs() == "addcontentsline") {
4167 // get the 3 arguments of \addcontentsline
4170 contentslineContent = p.getArg('{', '}');
4171 // if the last argument is not \refname we must output
4172 if (contentslineContent == "\\refname")
4179 output_ert_inset(os,
4180 "\\bibliographystyle{" + bibliographystyle + '}',
4185 else if (t.cs() == "phantomsection") {
4186 // we only support this if it occurs between
4187 // \bibliographystyle and \bibliography
4188 if (bibliographystyle.empty())
4189 output_ert_inset(os, "\\phantomsection", context);
4192 else if (t.cs() == "addcontentsline") {
4193 context.check_layout(os);
4194 // get the 3 arguments of \addcontentsline
4195 string const one = p.getArg('{', '}');
4196 string const two = p.getArg('{', '}');
4197 string const three = p.getArg('{', '}');
4198 // only if it is a \refname, we support if for the bibtex inset
4199 if (contentslineContent != "\\refname") {
4200 output_ert_inset(os,
4201 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4206 else if (t.cs() == "bibliography") {
4207 context.check_layout(os);
4209 begin_command_inset(os, "bibtex", "bibtex");
4210 if (!btprint.empty()) {
4211 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4212 // clear the string because the next BibTeX inset can be without the
4213 // \nocite{*} option
4216 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4217 // Do we have addcontentsline?
4218 if (contentslineContent == "\\refname") {
4219 BibOpts = "bibtotoc";
4220 // clear string because next BibTeX inset can be without addcontentsline
4221 contentslineContent.clear();
4223 // Do we have a bibliographystyle set?
4224 if (!bibliographystyle.empty()) {
4225 if (BibOpts.empty())
4226 BibOpts = bibliographystyle;
4228 BibOpts = BibOpts + ',' + bibliographystyle;
4229 // clear it because each bibtex entry has its style
4230 // and we need an empty string to handle \phantomsection
4231 bibliographystyle.clear();
4233 os << "options " << '"' << BibOpts << '"' << "\n";
4237 else if (t.cs() == "parbox") {
4238 // Test whether this is an outer box of a shaded box
4240 // swallow arguments
4241 while (p.hasOpt()) {
4243 p.skip_spaces(true);
4246 p.skip_spaces(true);
4248 if (p.next_token().cat() == catBegin)
4250 p.skip_spaces(true);
4251 Token to = p.get_token();
4252 bool shaded = false;
4253 if (to.asInput() == "\\begin") {
4254 p.skip_spaces(true);
4255 if (p.getArg('{', '}') == "shaded")
4260 parse_outer_box(p, os, FLAG_ITEM, outer,
4261 context, "parbox", "shaded");
4263 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4264 "", "", t.cs(), "", "");
4267 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4268 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4269 t.cs() == "shadowbox" || t.cs() == "doublebox")
4270 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4272 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4273 string backgroundcolor;
4274 preamble.registerAutomaticallyLoadedPackage("xcolor");
4275 if (t.cs() == "fcolorbox") {
4276 string const framecolor = p.getArg('{', '}');
4277 backgroundcolor = p.getArg('{', '}');
4278 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4280 backgroundcolor = p.getArg('{', '}');
4281 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4285 // FIXME: due to the compiler limit of "if" nestings
4286 // the code for the alignment was put here
4287 // put them in their own if if this is fixed
4288 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4289 || t.cs() == "shadowsize"
4290 || t.cs() == "raggedleft" || t.cs() == "centering"
4291 || t.cs() == "raggedright") {
4292 p.skip_spaces(true);
4293 if (t.cs() == "fboxrule")
4295 if (t.cs() == "fboxsep")
4297 if (t.cs() == "shadowsize")
4299 if (t.cs() != "raggedleft" && t.cs() != "centering"
4300 && t.cs() != "raggedright") {
4301 while (p.good() && p.next_token().cat() != catSpace
4302 && p.next_token().cat() != catNewline
4303 && p.next_token().cat() != catEscape) {
4304 if (t.cs() == "fboxrule")
4305 fboxrule = fboxrule + p.get_token().asInput();
4306 if (t.cs() == "fboxsep")
4307 fboxsep = fboxsep + p.get_token().asInput();
4308 if (t.cs() == "shadowsize")
4309 shadow_size = shadow_size + p.get_token().asInput();
4312 // we only handle them if they are in a box
4314 output_ert_inset(os, '\\' + t.cs() + ' ', context);
4316 wasBoxAlign = false;
4319 //\framebox() is part of the picture environment and different from \framebox{}
4320 //\framebox{} will be parsed by parse_outer_box
4321 else if (t.cs() == "framebox") {
4322 if (p.next_token().character() == '(') {
4323 //the syntax is: \framebox(x,y)[position]{content}
4324 string arg = t.asInput();
4325 arg += p.getFullParentheseArg();
4326 arg += p.getFullOpt();
4327 eat_whitespace(p, os, context, false);
4328 output_ert_inset(os, arg + '{', context);
4329 parse_text(p, os, FLAG_ITEM, outer, context);
4330 output_ert_inset(os, "}", context);
4332 //the syntax is: \framebox[width][position]{content}
4333 string special = p.getFullOpt();
4334 special += p.getOpt();
4335 parse_outer_box(p, os, FLAG_ITEM, outer,
4336 context, t.cs(), special);
4340 //\makebox() is part of the picture environment and different from \makebox{}
4341 //\makebox{} will be parsed by parse_box
4342 else if (t.cs() == "makebox") {
4343 if (p.next_token().character() == '(') {
4344 //the syntax is: \makebox(x,y)[position]{content}
4345 string arg = t.asInput();
4346 arg += p.getFullParentheseArg();
4347 arg += p.getFullOpt();
4348 eat_whitespace(p, os, context, false);
4349 output_ert_inset(os, arg + '{', context);
4350 parse_text(p, os, FLAG_ITEM, outer, context);
4351 output_ert_inset(os, "}", context);
4353 //the syntax is: \makebox[width][position]{content}
4354 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4355 "", "", t.cs(), "", "");
4358 else if (t.cs() == "smallskip" ||
4359 t.cs() == "medskip" ||
4360 t.cs() == "bigskip" ||
4361 t.cs() == "vfill") {
4362 context.check_layout(os);
4363 begin_inset(os, "VSpace ");
4366 skip_spaces_braces(p);
4369 else if ((where = is_known(t.cs(), known_spaces))) {
4370 context.check_layout(os);
4371 begin_inset(os, "space ");
4372 os << '\\' << known_coded_spaces[where - known_spaces]
4375 // LaTeX swallows whitespace after all spaces except
4376 // "\\,". We have to do that here, too, because LyX
4377 // adds "{}" which would make the spaces significant.
4379 eat_whitespace(p, os, context, false);
4380 // LyX adds "{}" after all spaces except "\\ " and
4381 // "\\,", so we have to remove "{}".
4382 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4383 // remove the braces after "\\,", too.
4388 else if (t.cs() == "newpage" ||
4389 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4390 t.cs() == "clearpage" ||
4391 t.cs() == "cleardoublepage") {
4392 context.check_layout(os);
4393 begin_inset(os, "Newpage ");
4396 skip_spaces_braces(p);
4399 else if (t.cs() == "DeclareRobustCommand" ||
4400 t.cs() == "DeclareRobustCommandx" ||
4401 t.cs() == "newcommand" ||
4402 t.cs() == "newcommandx" ||
4403 t.cs() == "providecommand" ||
4404 t.cs() == "providecommandx" ||
4405 t.cs() == "renewcommand" ||
4406 t.cs() == "renewcommandx") {
4407 // DeclareRobustCommand, DeclareRobustCommandx,
4408 // providecommand and providecommandx could be handled
4409 // by parse_command(), but we need to call
4410 // add_known_command() here.
4411 string name = t.asInput();
4412 if (p.next_token().asInput() == "*") {
4413 // Starred form. Eat '*'
4417 string const command = p.verbatim_item();
4418 string const opt1 = p.getFullOpt();
4419 string const opt2 = p.getFullOpt();
4420 add_known_command(command, opt1, !opt2.empty());
4421 string const ert = name + '{' + command + '}' +
4423 '{' + p.verbatim_item() + '}';
4425 if (t.cs() == "DeclareRobustCommand" ||
4426 t.cs() == "DeclareRobustCommandx" ||
4427 t.cs() == "providecommand" ||
4428 t.cs() == "providecommandx" ||
4429 name[name.length()-1] == '*')
4430 output_ert_inset(os, ert, context);
4432 context.check_layout(os);
4433 begin_inset(os, "FormulaMacro");
4439 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4440 // let could be handled by parse_command(),
4441 // but we need to call add_known_command() here.
4442 string ert = t.asInput();
4445 if (p.next_token().cat() == catBegin) {
4446 name = p.verbatim_item();
4447 ert += '{' + name + '}';
4449 name = p.verbatim_item();
4454 if (p.next_token().cat() == catBegin) {
4455 command = p.verbatim_item();
4456 ert += '{' + command + '}';
4458 command = p.verbatim_item();
4461 // If command is known, make name known too, to parse
4462 // its arguments correctly. For this reason we also
4463 // have commands in syntax.default that are hardcoded.
4464 CommandMap::iterator it = known_commands.find(command);
4465 if (it != known_commands.end())
4466 known_commands[t.asInput()] = it->second;
4467 output_ert_inset(os, ert, context);
4470 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4473 string name = t.asInput();
4474 string const length = p.verbatim_item();
4477 bool valid = splitLatexLength(length, valstring, unit);
4478 bool known_hspace = false;
4479 bool known_vspace = false;
4480 bool known_unit = false;
4483 istringstream iss(valstring);
4486 if (t.cs()[0] == 'h') {
4487 if (unit == "\\fill") {
4492 known_hspace = true;
4495 if (unit == "\\smallskipamount") {
4497 known_vspace = true;
4498 } else if (unit == "\\medskipamount") {
4500 known_vspace = true;
4501 } else if (unit == "\\bigskipamount") {
4503 known_vspace = true;
4504 } else if (unit == "\\fill") {
4506 known_vspace = true;
4510 if (!known_hspace && !known_vspace) {
4511 switch (unitFromString(unit)) {
4527 //unitFromString(unit) fails for relative units like Length::PCW
4528 // therefore handle them separately
4529 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4530 || unit == "\\textwidth" || unit == "\\linewidth"
4531 || unit == "\\textheight" || unit == "\\paperheight")
4539 // check for glue lengths
4540 bool is_gluelength = false;
4541 string gluelength = length;
4542 string::size_type i = length.find(" minus");
4543 if (i == string::npos) {
4544 i = length.find(" plus");
4545 if (i != string::npos)
4546 is_gluelength = true;
4548 is_gluelength = true;
4549 // if yes transform "9xx minus 8yy plus 7zz"
4551 if (is_gluelength) {
4552 i = gluelength.find(" minus");
4553 if (i != string::npos)
4554 gluelength.replace(i, 7, "-");
4555 i = gluelength.find(" plus");
4556 if (i != string::npos)
4557 gluelength.replace(i, 6, "+");
4560 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4561 // Literal horizontal length or known variable
4562 context.check_layout(os);
4563 begin_inset(os, "space ");
4571 if (known_unit && !known_hspace)
4572 os << "\n\\length " << translate_len(length);
4574 os << "\n\\length " << gluelength;
4576 } else if (known_unit || known_vspace || is_gluelength) {
4577 // Literal vertical length or known variable
4578 context.check_layout(os);
4579 begin_inset(os, "VSpace ");
4582 if (known_unit && !known_vspace)
4583 os << translate_len(length);
4590 // LyX can't handle other length variables in Inset VSpace/space
4595 output_ert_inset(os, name + '{' + unit + '}', context);
4596 else if (value == -1.0)
4597 output_ert_inset(os, name + "{-" + unit + '}', context);
4599 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4601 output_ert_inset(os, name + '{' + length + '}', context);
4605 // The single '=' is meant here.
4606 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4610 context.check_layout(os);
4611 docstring const name = newinsetlayout->name();
4612 bool const caption = name.find(from_ascii("Caption:")) == 0;
4614 begin_inset(os, "Caption ");
4615 os << to_utf8(name.substr(8)) << '\n';
4617 begin_inset(os, "Flex ");
4618 os << to_utf8(name) << '\n'
4619 << "status collapsed\n";
4621 if (newinsetlayout->isPassThru()) {
4622 // set catcodes to verbatim early, just in case.
4623 p.setCatcodes(VERBATIM_CATCODES);
4624 string delim = p.get_token().asInput();
4626 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4627 //FIXME: handle error condition
4628 string const arg = p.verbatimStuff("}").second;
4629 Context newcontext(true, context.textclass);
4630 if (newinsetlayout->forcePlainLayout())
4631 newcontext.layout = &context.textclass.plainLayout();
4632 output_ert(os, arg, newcontext);
4634 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4640 else if (t.cs() == "includepdf") {
4642 string const arg = p.getArg('[', ']');
4643 map<string, string> opts;
4644 vector<string> keys;
4645 split_map(arg, opts, keys);
4646 string name = normalize_filename(p.verbatim_item());
4647 string const path = getMasterFilePath(true);
4648 // We want to preserve relative / absolute filenames,
4649 // therefore path is only used for testing
4650 if (!makeAbsPath(name, path).exists()) {
4651 // The file extension is probably missing.
4652 // Now try to find it out.
4653 char const * const pdfpages_format[] = {"pdf", 0};
4654 string const pdftex_name =
4655 find_file(name, path, pdfpages_format);
4656 if (!pdftex_name.empty()) {
4661 FileName const absname = makeAbsPath(name, path);
4662 if (absname.exists())
4664 fix_child_filename(name);
4665 copy_file(absname, name);
4667 cerr << "Warning: Could not find file '"
4668 << name << "'." << endl;
4670 context.check_layout(os);
4671 begin_inset(os, "External\n\ttemplate ");
4672 os << "PDFPages\n\tfilename "
4674 // parse the options
4675 if (opts.find("pages") != opts.end())
4676 os << "\textra LaTeX \"pages="
4677 << opts["pages"] << "\"\n";
4678 if (opts.find("angle") != opts.end())
4679 os << "\trotateAngle "
4680 << opts["angle"] << '\n';
4681 if (opts.find("origin") != opts.end()) {
4683 string const opt = opts["origin"];
4684 if (opt == "tl") ss << "topleft";
4685 if (opt == "bl") ss << "bottomleft";
4686 if (opt == "Bl") ss << "baselineleft";
4687 if (opt == "c") ss << "center";
4688 if (opt == "tc") ss << "topcenter";
4689 if (opt == "bc") ss << "bottomcenter";
4690 if (opt == "Bc") ss << "baselinecenter";
4691 if (opt == "tr") ss << "topright";
4692 if (opt == "br") ss << "bottomright";
4693 if (opt == "Br") ss << "baselineright";
4694 if (!ss.str().empty())
4695 os << "\trotateOrigin " << ss.str() << '\n';
4697 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4699 if (opts.find("width") != opts.end())
4701 << translate_len(opts["width"]) << '\n';
4702 if (opts.find("height") != opts.end())
4704 << translate_len(opts["height"]) << '\n';
4705 if (opts.find("keepaspectratio") != opts.end())
4706 os << "\tkeepAspectRatio\n";
4708 context.check_layout(os);
4709 registerExternalTemplatePackages("PDFPages");
4712 else if (t.cs() == "loadgame") {
4714 string name = normalize_filename(p.verbatim_item());
4715 string const path = getMasterFilePath(true);
4716 // We want to preserve relative / absolute filenames,
4717 // therefore path is only used for testing
4718 if (!makeAbsPath(name, path).exists()) {
4719 // The file extension is probably missing.
4720 // Now try to find it out.
4721 char const * const lyxskak_format[] = {"fen", 0};
4722 string const lyxskak_name =
4723 find_file(name, path, lyxskak_format);
4724 if (!lyxskak_name.empty())
4725 name = lyxskak_name;
4727 FileName const absname = makeAbsPath(name, path);
4728 if (absname.exists())
4730 fix_child_filename(name);
4731 copy_file(absname, name);
4733 cerr << "Warning: Could not find file '"
4734 << name << "'." << endl;
4735 context.check_layout(os);
4736 begin_inset(os, "External\n\ttemplate ");
4737 os << "ChessDiagram\n\tfilename "
4740 context.check_layout(os);
4741 // after a \loadgame follows a \showboard
4742 if (p.get_token().asInput() == "showboard")
4744 registerExternalTemplatePackages("ChessDiagram");
4748 // try to see whether the string is in unicodesymbols
4749 // Only use text mode commands, since we are in text mode here,
4750 // and math commands may be invalid (bug 6797)
4751 string name = t.asInput();
4752 // handle the dingbats, cyrillic and greek
4753 if (name == "\\ding" || name == "\\textcyr" ||
4754 (name == "\\textgreek" && !preamble.usePolyglossia()))
4755 name = name + '{' + p.getArg('{', '}') + '}';
4756 // handle the ifsym characters
4757 else if (name == "\\textifsymbol") {
4758 string const optif = p.getFullOpt();
4759 string const argif = p.getArg('{', '}');
4760 name = name + optif + '{' + argif + '}';
4762 // handle the \ascii characters
4763 // the case of \ascii within braces, as LyX outputs it, is already
4764 // handled for t.cat() == catBegin
4765 else if (name == "\\ascii") {
4766 // the code is "\asci\xxx"
4767 name = "{" + name + p.get_token().asInput() + "}";
4770 // handle some TIPA special characters
4771 else if (preamble.isPackageUsed("tipa")) {
4772 if (name == "\\textglobfall") {
4775 } else if (name == "\\s") {
4776 // fromLaTeXCommand() does not yet
4777 // recognize tipa short cuts
4778 name = "\\textsyllabic";
4779 } else if (name == "\\=" &&
4780 p.next_token().asInput() == "*") {
4781 // fromLaTeXCommand() does not yet
4782 // recognize tipa short cuts
4785 } else if (name == "\\textdoublevertline") {
4786 // FIXME: This is not correct,
4787 // \textvertline is higher than \textbardbl
4788 name = "\\textbardbl";
4790 } else if (name == "\\!" ) {
4791 if (p.next_token().asInput() == "b") {
4792 p.get_token(); // eat 'b'
4795 } else if (p.next_token().asInput() == "d") {
4799 } else if (p.next_token().asInput() == "g") {
4803 } else if (p.next_token().asInput() == "G") {
4805 name = "\\texthtscg";
4807 } else if (p.next_token().asInput() == "j") {
4809 name = "\\texthtbardotlessj";
4811 } else if (p.next_token().asInput() == "o") {
4813 name = "\\textbullseye";
4816 } else if (name == "\\*" ) {
4817 if (p.next_token().asInput() == "k") {
4819 name = "\\textturnk";
4821 } else if (p.next_token().asInput() == "r") {
4822 p.get_token(); // eat 'b'
4823 name = "\\textturnr";
4825 } else if (p.next_token().asInput() == "t") {
4827 name = "\\textturnt";
4829 } else if (p.next_token().asInput() == "w") {
4831 name = "\\textturnw";
4836 if ((name.size() == 2 &&
4837 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4838 p.next_token().asInput() != "*") ||
4839 is_known(name.substr(1), known_tipa_marks)) {
4840 // name is a command that corresponds to a
4841 // combining character in unicodesymbols.
4842 // Append the argument, fromLaTeXCommand()
4843 // will either convert it to a single
4844 // character or a combining sequence.
4845 name += '{' + p.verbatim_item() + '}';
4847 // now get the character from unicodesymbols
4851 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4852 Encodings::TEXT_CMD, termination, rem, &req);
4854 context.check_layout(os);
4857 output_ert_inset(os, to_utf8(rem), context);
4859 skip_spaces_braces(p);
4860 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4861 preamble.registerAutomaticallyLoadedPackage(*it);
4863 //cerr << "#: " << t << " mode: " << mode << endl;
4864 // heuristic: read up to next non-nested space
4866 string s = t.asInput();
4867 string z = p.verbatim_item();
4868 while (p.good() && z != " " && !z.empty()) {
4869 //cerr << "read: " << z << endl;
4871 z = p.verbatim_item();
4873 cerr << "found ERT: " << s << endl;
4874 output_ert_inset(os, s + ' ', context);
4877 if (t.asInput() == name &&
4878 p.next_token().asInput() == "*") {
4879 // Starred commands like \vspace*{}
4880 p.get_token(); // Eat '*'
4883 if (!parse_command(name, p, os, outer, context))
4884 output_ert_inset(os, name, context);
4888 if (flags & FLAG_LEAVE) {
4889 flags &= ~FLAG_LEAVE;
4896 string guessLanguage(Parser & p, string const & lang)
4898 typedef std::map<std::string, size_t> LangMap;
4899 // map from language names to number of characters
4902 for (char const * const * i = supported_CJK_languages; *i; i++)
4903 used[string(*i)] = 0;
4906 Token const t = p.get_token();
4907 // comments are not counted for any language
4908 if (t.cat() == catComment)
4910 // commands are not counted as well, but we need to detect
4911 // \begin{CJK} and switch encoding if needed
4912 if (t.cat() == catEscape) {
4913 if (t.cs() == "inputencoding") {
4914 string const enc = subst(p.verbatim_item(), "\n", " ");
4915 p.setEncoding(enc, Encoding::inputenc);
4918 if (t.cs() != "begin")
4921 // Non-CJK content is counted for lang.
4922 // We do not care about the real language here:
4923 // If we have more non-CJK contents than CJK contents,
4924 // we simply use the language that was specified as
4925 // babel main language.
4926 used[lang] += t.asInput().length();
4929 // Now we are starting an environment
4931 string const name = p.getArg('{', '}');
4932 if (name != "CJK") {
4936 // It is a CJK environment
4938 /* name = */ p.getArg('{', '}');
4939 string const encoding = p.getArg('{', '}');
4940 /* mapping = */ p.getArg('{', '}');
4941 string const encoding_old = p.getEncoding();
4942 char const * const * const where =
4943 is_known(encoding, supported_CJK_encodings);
4945 p.setEncoding(encoding, Encoding::CJK);
4947 p.setEncoding("UTF-8");
4948 string const text = p.ertEnvironment("CJK");
4949 p.setEncoding(encoding_old);
4952 // ignore contents in unknown CJK encoding
4955 // the language of the text
4957 supported_CJK_languages[where - supported_CJK_encodings];
4958 used[cjk] += text.length();
4960 LangMap::const_iterator use = used.begin();
4961 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4962 if (it->second > use->second)