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", "subsecref", "tabref", "thmref", 0 };
142 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
143 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
144 "sec", "subsec", "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 FileName const srcpath = src.onlyPath();
2099 FileName const dstpath = dst.onlyPath();
2100 if (equivalent(srcpath, dstpath))
2102 if (!dstpath.isDirectory()) {
2103 if (!dstpath.createPath()) {
2104 cerr << "Warning: Could not create directory for file `"
2105 << dst.absFileName() << "´." << endl;
2109 if (dst.isReadableFile()) {
2110 if (overwriteFiles())
2111 cerr << "Warning: Overwriting existing file `"
2112 << dst.absFileName() << "´." << endl;
2114 cerr << "Warning: Not overwriting existing file `"
2115 << dst.absFileName() << "´." << endl;
2119 if (!src.copyTo(dst))
2120 cerr << "Warning: Could not copy file `" << src.absFileName()
2121 << "´ to `" << dst.absFileName() << "´." << endl;
2125 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2126 bool parse_chunk(Parser & p, ostream & os, Context & context)
2128 // check whether a chunk is possible here.
2129 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2135 // read the parameters
2136 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2137 if (!params.first) {
2142 Parser::Arg const code = p.verbatimStuff("\n@");
2147 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2148 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2152 // The last newline read is important for paragraph handling
2156 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2157 // We must have a valid layout before outputting the Chunk inset.
2158 context.check_layout(os);
2159 Context chunkcontext(true, context.textclass);
2160 chunkcontext.layout = &context.textclass.plainLayout();
2161 begin_inset(os, "Flex Chunk");
2162 os << "\nstatus open\n";
2163 if (!params.second.empty()) {
2164 chunkcontext.check_layout(os);
2165 Context paramscontext(true, context.textclass);
2166 paramscontext.layout = &context.textclass.plainLayout();
2167 begin_inset(os, "Argument 1");
2168 os << "\nstatus open\n";
2169 output_ert(os, params.second, paramscontext);
2172 output_ert(os, code.second, chunkcontext);
2180 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2181 bool is_macro(Parser & p)
2183 Token first = p.curr_token();
2184 if (first.cat() != catEscape || !p.good())
2186 if (first.cs() == "def")
2188 if (first.cs() != "global" && first.cs() != "long")
2190 Token second = p.get_token();
2192 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2193 second.cat() == catNewline || second.cat() == catComment)) {
2194 second = p.get_token();
2197 bool secondvalid = second.cat() == catEscape;
2199 bool thirdvalid = false;
2200 if (p.good() && first.cs() == "global" && secondvalid &&
2201 second.cs() == "long") {
2202 third = p.get_token();
2204 while (p.good() && !p.isParagraph() &&
2205 (third.cat() == catSpace ||
2206 third.cat() == catNewline ||
2207 third.cat() == catComment)) {
2208 third = p.get_token();
2211 thirdvalid = third.cat() == catEscape;
2213 for (int i = 0; i < pos; ++i)
2218 return (first.cs() == "global" || first.cs() == "long") &&
2219 second.cs() == "def";
2220 return first.cs() == "global" && second.cs() == "long" &&
2221 third.cs() == "def";
2225 /// Parse a macro definition (assumes that is_macro() returned true)
2226 void parse_macro(Parser & p, ostream & os, Context & context)
2228 context.check_layout(os);
2229 Token first = p.curr_token();
2232 string command = first.asInput();
2233 if (first.cs() != "def") {
2235 eat_whitespace(p, os, context, false);
2236 second = p.curr_token();
2237 command += second.asInput();
2238 if (second.cs() != "def") {
2240 eat_whitespace(p, os, context, false);
2241 third = p.curr_token();
2242 command += third.asInput();
2245 eat_whitespace(p, os, context, false);
2246 string const name = p.get_token().cs();
2247 eat_whitespace(p, os, context, false);
2253 while (p.next_token().cat() != catBegin) {
2254 if (p.next_token().cat() == catParameter) {
2259 // followed by number?
2260 if (p.next_token().cat() == catOther) {
2261 string s = p.get_token().asInput();
2263 // number = current arity + 1?
2264 if (s.size() == 1 && s[0] == arity + '0' + 1)
2269 paramtext += p.get_token().cs();
2271 paramtext += p.get_token().cs();
2276 // only output simple (i.e. compatible) macro as FormulaMacros
2277 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2279 context.check_layout(os);
2280 begin_inset(os, "FormulaMacro");
2281 os << "\n\\def" << ert;
2284 output_ert_inset(os, command + ert, context);
2288 void registerExternalTemplatePackages(string const & name)
2290 external::TemplateManager const & etm = external::TemplateManager::get();
2291 external::Template const * const et = etm.getTemplateByName(name);
2294 external::Template::Formats::const_iterator cit = et->formats.end();
2296 cit = et->formats.find("PDFLaTeX");
2297 if (cit == et->formats.end())
2298 // If the template has not specified a PDFLaTeX output,
2299 // we try the LaTeX format.
2300 cit = et->formats.find("LaTeX");
2301 if (cit == et->formats.end())
2303 vector<string>::const_iterator qit = cit->second.requirements.begin();
2304 vector<string>::const_iterator qend = cit->second.requirements.end();
2305 for (; qit != qend; ++qit)
2306 preamble.registerAutomaticallyLoadedPackage(*qit);
2309 } // anonymous namespace
2312 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2315 Layout const * newlayout = 0;
2316 InsetLayout const * newinsetlayout = 0;
2317 char const * const * where = 0;
2318 // Store the latest bibliographystyle, addcontentslineContent and
2319 // nocite{*} option (needed for bibtex inset)
2321 string contentslineContent;
2322 string bibliographystyle = "default";
2323 bool const use_natbib = isProvided("natbib");
2324 bool const use_jurabib = isProvided("jurabib");
2327 // it is impossible to determine the correct encoding for non-CJK Japanese.
2328 // Therefore write a note at the beginning of the document
2329 if (is_nonCJKJapanese) {
2330 context.check_layout(os);
2331 begin_inset(os, "Note Note\n");
2332 os << "status open\n\\begin_layout Plain Layout\n"
2333 << "\\series bold\n"
2334 << "Important information:\n"
2335 << "\\end_layout\n\n"
2336 << "\\begin_layout Plain Layout\n"
2337 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2338 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2339 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2340 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2341 << " and specify the encoding using the -e command-line switch.\n"
2342 << " In addition, you might want to double check that the desired output encoding\n"
2343 << " is correctly selected in Document > Settings > Language.\n"
2344 << "\\end_layout\n";
2346 is_nonCJKJapanese = false;
2350 Token const & t = p.get_token();
2352 debugToken(cerr, t, flags);
2355 if (flags & FLAG_ITEM) {
2356 if (t.cat() == catSpace)
2359 flags &= ~FLAG_ITEM;
2360 if (t.cat() == catBegin) {
2361 // skip the brace and collect everything to the next matching
2363 flags |= FLAG_BRACE_LAST;
2367 // handle only this single token, leave the loop if done
2368 flags |= FLAG_LEAVE;
2371 if (t.cat() != catEscape && t.character() == ']' &&
2372 (flags & FLAG_BRACK_LAST))
2374 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2377 // If there is anything between \end{env} and \begin{env} we
2378 // don't need to output a separator.
2379 if (t.cat() != catSpace && t.cat() != catNewline &&
2380 t.asInput() != "\\begin")
2386 bool const starred = p.next_token().asInput() == "*";
2387 string const starredname(starred ? (t.cs() + '*') : t.cs());
2388 if (t.cat() == catMath) {
2389 // we are inside some text mode thingy, so opening new math is allowed
2390 context.check_layout(os);
2391 begin_inset(os, "Formula ");
2392 Token const & n = p.get_token();
2393 bool const display(n.cat() == catMath && outer);
2395 // TeX's $$...$$ syntax for displayed math
2397 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2399 p.get_token(); // skip the second '$' token
2401 // simple $...$ stuff
2404 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2409 // Prevent the conversion of a line break to a
2410 // space (bug 7668). This does not change the
2411 // output, but looks ugly in LyX.
2412 eat_whitespace(p, os, context, false);
2416 else if (t.cat() == catSuper || t.cat() == catSub)
2417 cerr << "catcode " << t << " illegal in text mode\n";
2419 // Basic support for english quotes. This should be
2420 // extended to other quotes, but is not so easy (a
2421 // left english quote is the same as a right german
2423 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2424 context.check_layout(os);
2425 begin_inset(os, "Quotes ");
2431 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2432 context.check_layout(os);
2433 begin_inset(os, "Quotes ");
2440 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2441 context.check_layout(os);
2442 begin_inset(os, "Quotes ");
2449 else if (t.asInput() == "<"
2450 && p.next_token().asInput() == "<") {
2451 bool has_chunk = false;
2455 has_chunk = parse_chunk(p, os, context);
2461 context.check_layout(os);
2462 begin_inset(os, "Quotes ");
2463 //FIXME: this is a right danish quote;
2464 // why not a left french quote?
2472 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2473 check_space(p, os, context);
2475 else if (t.character() == '[' && noweb_mode &&
2476 p.next_token().character() == '[') {
2477 // These can contain underscores
2479 string const s = p.getFullOpt() + ']';
2480 if (p.next_token().character() == ']')
2483 cerr << "Warning: Inserting missing ']' in '"
2484 << s << "'." << endl;
2485 output_ert_inset(os, s, context);
2488 else if (t.cat() == catLetter) {
2489 context.check_layout(os);
2493 else if (t.cat() == catOther ||
2494 t.cat() == catAlign ||
2495 t.cat() == catParameter) {
2496 context.check_layout(os);
2497 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2498 context.merging_hyphens_allowed &&
2499 context.font.family != "ttfamily" &&
2500 !context.layout->pass_thru) {
2501 if (p.next_next_token().asInput() == "-") {
2503 os << to_utf8(docstring(1, 0x2014));
2507 os << to_utf8(docstring(1, 0x2013));
2510 // This translates "&" to "\\&" which may be wrong...
2514 else if (p.isParagraph()) {
2515 if (context.new_layout_allowed)
2516 context.new_paragraph(os);
2518 output_ert_inset(os, "\\par ", context);
2519 eat_whitespace(p, os, context, true);
2522 else if (t.cat() == catActive) {
2523 context.check_layout(os);
2524 if (t.character() == '~') {
2525 if (context.layout->free_spacing)
2528 begin_inset(os, "space ~\n");
2535 else if (t.cat() == catBegin) {
2536 Token const next = p.next_token();
2537 Token const end = p.next_next_token();
2538 if (next.cat() == catEnd) {
2540 Token const prev = p.prev_token();
2542 if (p.next_token().character() == '`')
2543 ; // ignore it in {}``
2545 output_ert_inset(os, "{}", context);
2546 } else if (next.cat() == catEscape &&
2547 is_known(next.cs(), known_quotes) &&
2548 end.cat() == catEnd) {
2549 // Something like {\textquoteright} (e.g.
2550 // from writer2latex). LyX writes
2551 // \textquoteright{}, so we may skip the
2552 // braces here for better readability.
2553 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2555 } else if (p.next_token().asInput() == "\\ascii") {
2556 // handle the \ascii characters
2557 // (the case without braces is handled later)
2558 // the code is "{\ascii\xxx}"
2559 p.get_token(); // eat \ascii
2560 string name2 = p.get_token().asInput();
2561 p.get_token(); // eat the final '}'
2562 string const name = "{\\ascii" + name2 + "}";
2566 // get the character from unicodesymbols
2567 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2568 Encodings::TEXT_CMD, termination, rem, &req);
2570 context.check_layout(os);
2573 output_ert_inset(os,
2574 to_utf8(rem), context);
2575 for (set<string>::const_iterator it = req.begin();
2576 it != req.end(); ++it)
2577 preamble.registerAutomaticallyLoadedPackage(*it);
2579 // we did not find a non-ert version
2580 output_ert_inset(os, name, context);
2582 context.check_layout(os);
2583 // special handling of font attribute changes
2584 Token const prev = p.prev_token();
2585 TeXFont const oldFont = context.font;
2586 if (next.character() == '[' ||
2587 next.character() == ']' ||
2588 next.character() == '*') {
2590 if (p.next_token().cat() == catEnd) {
2595 output_ert_inset(os, "{", context);
2596 parse_text_snippet(p, os,
2599 output_ert_inset(os, "}", context);
2601 } else if (! context.new_layout_allowed) {
2602 output_ert_inset(os, "{", context);
2603 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2605 output_ert_inset(os, "}", context);
2606 } else if (is_known(next.cs(), known_sizes)) {
2607 // next will change the size, so we must
2609 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2611 if (!context.atParagraphStart())
2613 << context.font.size << "\n";
2614 } else if (is_known(next.cs(), known_font_families)) {
2615 // next will change the font family, so we
2616 // must reset it here
2617 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2619 if (!context.atParagraphStart())
2621 << context.font.family << "\n";
2622 } else if (is_known(next.cs(), known_font_series)) {
2623 // next will change the font series, so we
2624 // must reset it here
2625 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2627 if (!context.atParagraphStart())
2629 << context.font.series << "\n";
2630 } else if (is_known(next.cs(), known_font_shapes)) {
2631 // next will change the font shape, so we
2632 // must reset it here
2633 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2635 if (!context.atParagraphStart())
2637 << context.font.shape << "\n";
2638 } else if (is_known(next.cs(), known_old_font_families) ||
2639 is_known(next.cs(), known_old_font_series) ||
2640 is_known(next.cs(), known_old_font_shapes)) {
2641 // next will change the font family, series
2642 // and shape, so we must reset it here
2643 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2645 if (!context.atParagraphStart())
2647 << context.font.family
2649 << context.font.series
2651 << context.font.shape << "\n";
2653 output_ert_inset(os, "{", context);
2654 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2656 output_ert_inset(os, "}", context);
2661 else if (t.cat() == catEnd) {
2662 if (flags & FLAG_BRACE_LAST) {
2665 cerr << "stray '}' in text\n";
2666 output_ert_inset(os, "}", context);
2669 else if (t.cat() == catComment)
2670 parse_comment(p, os, t, context);
2673 // control sequences
2676 else if (t.cs() == "(" || t.cs() == "[") {
2677 bool const simple = t.cs() == "(";
2678 context.check_layout(os);
2679 begin_inset(os, "Formula");
2680 os << " \\" << t.cs();
2681 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2682 os << '\\' << (simple ? ')' : ']');
2685 // Prevent the conversion of a line break to a
2686 // space (bug 7668). This does not change the
2687 // output, but looks ugly in LyX.
2688 eat_whitespace(p, os, context, false);
2692 else if (t.cs() == "begin")
2693 parse_environment(p, os, outer, last_env,
2696 else if (t.cs() == "end") {
2697 if (flags & FLAG_END) {
2698 // eat environment name
2699 string const name = p.getArg('{', '}');
2700 if (name != active_environment())
2701 cerr << "\\end{" + name + "} does not match \\begin{"
2702 + active_environment() + "}\n";
2705 p.error("found 'end' unexpectedly");
2708 else if (t.cs() == "item") {
2710 bool const optarg = p.hasOpt();
2712 // FIXME: This swallows comments, but we cannot use
2713 // eat_whitespace() since we must not output
2714 // anything before the item.
2715 p.skip_spaces(true);
2716 s = p.verbatimOption();
2718 p.skip_spaces(false);
2720 context.check_layout(os);
2721 if (context.has_item) {
2722 // An item in an unknown list-like environment
2723 // FIXME: Do this in check_layout()!
2724 context.has_item = false;
2726 output_ert_inset(os, "\\item", context);
2728 output_ert_inset(os, "\\item ", context);
2731 if (context.layout->labeltype != LABEL_MANUAL) {
2732 // handle option of itemize item
2733 begin_inset(os, "Argument item:1\n");
2734 os << "status open\n";
2735 os << "\n\\begin_layout Plain Layout\n";
2737 os << parse_text_snippet(p2,
2738 FLAG_BRACK_LAST, outer, context);
2739 // we must not use context.check_end_layout(os)
2740 // because that would close the outer itemize layout
2741 os << "\n\\end_layout\n";
2743 eat_whitespace(p, os, context, false);
2744 } else if (!s.empty()) {
2745 // LyX adds braces around the argument,
2746 // so we need to remove them here.
2747 if (s.size() > 2 && s[0] == '{' &&
2748 s[s.size()-1] == '}')
2749 s = s.substr(1, s.size()-2);
2750 // If the argument contains a space we
2751 // must put it into ERT: Otherwise LyX
2752 // would misinterpret the space as
2753 // item delimiter (bug 7663)
2754 if (contains(s, ' ')) {
2755 output_ert_inset(os, s, context);
2758 os << parse_text_snippet(p2,
2759 FLAG_BRACK_LAST, outer, context);
2761 // The space is needed to separate the
2762 // item from the rest of the sentence.
2764 eat_whitespace(p, os, context, false);
2769 else if (t.cs() == "bibitem") {
2771 context.check_layout(os);
2772 eat_whitespace(p, os, context, false);
2773 string label = convert_command_inset_arg(p.verbatimOption());
2774 string key = convert_command_inset_arg(p.verbatim_item());
2775 if (contains(label, '\\') || contains(key, '\\')) {
2776 // LyX can't handle LaTeX commands in labels or keys
2777 output_ert_inset(os, t.asInput() + '[' + label +
2778 "]{" + p.verbatim_item() + '}',
2781 begin_command_inset(os, "bibitem", "bibitem");
2782 os << "label \"" << label << "\"\n"
2783 "key \"" << key << "\"\n";
2788 else if (is_macro(p)) {
2789 // catch the case of \def\inputGnumericTable
2791 if (t.cs() == "def") {
2792 Token second = p.next_token();
2793 if (second.cs() == "inputGnumericTable") {
2797 Token third = p.get_token();
2799 if (third.cs() == "input") {
2803 string name = normalize_filename(p.verbatim_item());
2804 string const path = getMasterFilePath(true);
2805 // We want to preserve relative / absolute filenames,
2806 // therefore path is only used for testing
2807 // The file extension is in every case ".tex".
2808 // So we need to remove this extension and check for
2809 // the original one.
2810 name = removeExtension(name);
2811 if (!makeAbsPath(name, path).exists()) {
2812 char const * const Gnumeric_formats[] = {"gnumeric",
2814 string const Gnumeric_name =
2815 find_file(name, path, Gnumeric_formats);
2816 if (!Gnumeric_name.empty())
2817 name = Gnumeric_name;
2819 FileName const absname = makeAbsPath(name, path);
2820 if (absname.exists()) {
2821 fix_child_filename(name);
2822 copy_file(absname, name);
2824 cerr << "Warning: Could not find file '"
2825 << name << "'." << endl;
2826 context.check_layout(os);
2827 begin_inset(os, "External\n\ttemplate ");
2828 os << "GnumericSpreadsheet\n\tfilename "
2831 context.check_layout(os);
2833 // register the packages that are automatically loaded
2834 // by the Gnumeric template
2835 registerExternalTemplatePackages("GnumericSpreadsheet");
2840 parse_macro(p, os, context);
2843 else if (t.cs() == "noindent") {
2845 context.add_par_extra_stuff("\\noindent\n");
2848 else if (t.cs() == "appendix") {
2849 context.add_par_extra_stuff("\\start_of_appendix\n");
2850 // We need to start a new paragraph. Otherwise the
2851 // appendix in 'bla\appendix\chapter{' would start
2853 context.new_paragraph(os);
2854 // We need to make sure that the paragraph is
2855 // generated even if it is empty. Otherwise the
2856 // appendix in '\par\appendix\par\chapter{' would
2858 context.check_layout(os);
2859 // FIXME: This is a hack to prevent paragraph
2860 // deletion if it is empty. Handle this better!
2861 output_ert_inset(os,
2862 "%dummy comment inserted by tex2lyx to "
2863 "ensure that this paragraph is not empty",
2865 // Both measures above may generate an additional
2866 // empty paragraph, but that does not hurt, because
2867 // whitespace does not matter here.
2868 eat_whitespace(p, os, context, true);
2871 // Must catch empty dates before findLayout is called below
2872 else if (t.cs() == "date") {
2873 eat_whitespace(p, os, context, false);
2875 string const date = p.verbatim_item();
2878 preamble.suppressDate(true);
2881 preamble.suppressDate(false);
2882 if (context.new_layout_allowed &&
2883 (newlayout = findLayout(context.textclass,
2886 output_command_layout(os, p, outer,
2887 context, newlayout);
2888 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2889 if (!preamble.titleLayoutFound())
2890 preamble.titleLayoutFound(newlayout->intitle);
2891 set<string> const & req = newlayout->requires();
2892 set<string>::const_iterator it = req.begin();
2893 set<string>::const_iterator en = req.end();
2894 for (; it != en; ++it)
2895 preamble.registerAutomaticallyLoadedPackage(*it);
2897 output_ert_inset(os,
2898 "\\date{" + p.verbatim_item() + '}',
2903 // Starred section headings
2904 // Must attempt to parse "Section*" before "Section".
2905 else if ((p.next_token().asInput() == "*") &&
2906 context.new_layout_allowed &&
2907 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2910 output_command_layout(os, p, outer, context, newlayout);
2912 if (!preamble.titleLayoutFound())
2913 preamble.titleLayoutFound(newlayout->intitle);
2914 set<string> const & req = newlayout->requires();
2915 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2916 preamble.registerAutomaticallyLoadedPackage(*it);
2919 // Section headings and the like
2920 else if (context.new_layout_allowed &&
2921 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2923 output_command_layout(os, p, outer, context, newlayout);
2925 if (!preamble.titleLayoutFound())
2926 preamble.titleLayoutFound(newlayout->intitle);
2927 set<string> const & req = newlayout->requires();
2928 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
2929 preamble.registerAutomaticallyLoadedPackage(*it);
2932 else if (t.cs() == "subfloat") {
2933 // the syntax is \subfloat[list entry][sub caption]{content}
2934 // if it is a table of figure depends on the surrounding float
2935 // FIXME: second optional argument is not parsed
2937 // do nothing if there is no outer float
2938 if (!float_type.empty()) {
2939 context.check_layout(os);
2941 begin_inset(os, "Float " + float_type + "\n");
2943 << "\nsideways false"
2944 << "\nstatus collapsed\n\n";
2947 bool has_caption = false;
2948 if (p.next_token().cat() != catEscape &&
2949 p.next_token().character() == '[') {
2950 p.get_token(); // eat '['
2951 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2955 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2956 // the caption comes always as the last
2958 // we must make sure that the caption gets a \begin_layout
2959 os << "\n\\begin_layout Plain Layout";
2961 begin_inset(os, "Caption Standard\n");
2962 Context newcontext(true, context.textclass,
2963 0, 0, context.font);
2964 newcontext.check_layout(os);
2965 os << caption << "\n";
2966 newcontext.check_end_layout(os);
2967 // We don't need really a new paragraph, but
2968 // we must make sure that the next item gets a \begin_layout.
2969 //newcontext.new_paragraph(os);
2973 // We don't need really a new paragraph, but
2974 // we must make sure that the next item gets a \begin_layout.
2976 context.new_paragraph(os);
2979 context.check_end_layout(os);
2980 // close the layout we opened
2982 os << "\n\\end_layout\n";
2984 // if the float type is not supported or there is no surrounding float
2987 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2988 output_ert_inset(os, t.asInput() + '[' + opt_arg +
2989 "]{" + p.verbatim_item() + '}', context);
2991 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2995 else if (t.cs() == "includegraphics") {
2996 bool const clip = p.next_token().asInput() == "*";
2999 string const arg = p.getArg('[', ']');
3000 map<string, string> opts;
3001 vector<string> keys;
3002 split_map(arg, opts, keys);
3004 opts["clip"] = string();
3005 string name = normalize_filename(p.verbatim_item());
3007 string const path = getMasterFilePath(true);
3008 // We want to preserve relative / absolute filenames,
3009 // therefore path is only used for testing
3010 if (!makeAbsPath(name, path).exists()) {
3011 // The file extension is probably missing.
3012 // Now try to find it out.
3013 string const dvips_name =
3014 find_file(name, path,
3015 known_dvips_graphics_formats);
3016 string const pdftex_name =
3017 find_file(name, path,
3018 known_pdftex_graphics_formats);
3019 if (!dvips_name.empty()) {
3020 if (!pdftex_name.empty()) {
3021 cerr << "This file contains the "
3023 "\"\\includegraphics{"
3025 "However, files\n\""
3026 << dvips_name << "\" and\n\""
3027 << pdftex_name << "\"\n"
3028 "both exist, so I had to make a "
3029 "choice and took the first one.\n"
3030 "Please move the unwanted one "
3031 "someplace else and try again\n"
3032 "if my choice was wrong."
3036 } else if (!pdftex_name.empty()) {
3042 FileName const absname = makeAbsPath(name, path);
3043 if (absname.exists()) {
3044 fix_child_filename(name);
3045 copy_file(absname, name);
3047 cerr << "Warning: Could not find graphics file '"
3048 << name << "'." << endl;
3050 context.check_layout(os);
3051 begin_inset(os, "Graphics ");
3052 os << "\n\tfilename " << name << '\n';
3053 if (opts.find("width") != opts.end())
3055 << translate_len(opts["width"]) << '\n';
3056 if (opts.find("height") != opts.end())
3058 << translate_len(opts["height"]) << '\n';
3059 if (opts.find("scale") != opts.end()) {
3060 istringstream iss(opts["scale"]);
3064 os << "\tscale " << val << '\n';
3066 if (opts.find("angle") != opts.end()) {
3067 os << "\trotateAngle "
3068 << opts["angle"] << '\n';
3069 vector<string>::const_iterator a =
3070 find(keys.begin(), keys.end(), "angle");
3071 vector<string>::const_iterator s =
3072 find(keys.begin(), keys.end(), "width");
3073 if (s == keys.end())
3074 s = find(keys.begin(), keys.end(), "height");
3075 if (s == keys.end())
3076 s = find(keys.begin(), keys.end(), "scale");
3077 if (s != keys.end() && distance(s, a) > 0)
3078 os << "\tscaleBeforeRotation\n";
3080 if (opts.find("origin") != opts.end()) {
3082 string const opt = opts["origin"];
3083 if (opt.find('l') != string::npos) ss << "left";
3084 if (opt.find('r') != string::npos) ss << "right";
3085 if (opt.find('c') != string::npos) ss << "center";
3086 if (opt.find('t') != string::npos) ss << "Top";
3087 if (opt.find('b') != string::npos) ss << "Bottom";
3088 if (opt.find('B') != string::npos) ss << "Baseline";
3089 if (!ss.str().empty())
3090 os << "\trotateOrigin " << ss.str() << '\n';
3092 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3094 if (opts.find("keepaspectratio") != opts.end())
3095 os << "\tkeepAspectRatio\n";
3096 if (opts.find("clip") != opts.end())
3098 if (opts.find("draft") != opts.end())
3100 if (opts.find("bb") != opts.end())
3101 os << "\tBoundingBox "
3102 << opts["bb"] << '\n';
3103 int numberOfbbOptions = 0;
3104 if (opts.find("bbllx") != opts.end())
3105 numberOfbbOptions++;
3106 if (opts.find("bblly") != opts.end())
3107 numberOfbbOptions++;
3108 if (opts.find("bburx") != opts.end())
3109 numberOfbbOptions++;
3110 if (opts.find("bbury") != opts.end())
3111 numberOfbbOptions++;
3112 if (numberOfbbOptions == 4)
3113 os << "\tBoundingBox "
3114 << opts["bbllx"] << " " << opts["bblly"] << " "
3115 << opts["bburx"] << " " << opts["bbury"] << '\n';
3116 else if (numberOfbbOptions > 0)
3117 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3118 numberOfbbOptions = 0;
3119 if (opts.find("natwidth") != opts.end())
3120 numberOfbbOptions++;
3121 if (opts.find("natheight") != opts.end())
3122 numberOfbbOptions++;
3123 if (numberOfbbOptions == 2)
3124 os << "\tBoundingBox 0bp 0bp "
3125 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3126 else if (numberOfbbOptions > 0)
3127 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3128 ostringstream special;
3129 if (opts.find("hiresbb") != opts.end())
3130 special << "hiresbb,";
3131 if (opts.find("trim") != opts.end())
3133 if (opts.find("viewport") != opts.end())
3134 special << "viewport=" << opts["viewport"] << ',';
3135 if (opts.find("totalheight") != opts.end())
3136 special << "totalheight=" << opts["totalheight"] << ',';
3137 if (opts.find("type") != opts.end())
3138 special << "type=" << opts["type"] << ',';
3139 if (opts.find("ext") != opts.end())
3140 special << "ext=" << opts["ext"] << ',';
3141 if (opts.find("read") != opts.end())
3142 special << "read=" << opts["read"] << ',';
3143 if (opts.find("command") != opts.end())
3144 special << "command=" << opts["command"] << ',';
3145 string s_special = special.str();
3146 if (!s_special.empty()) {
3147 // We had special arguments. Remove the trailing ','.
3148 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3150 // TODO: Handle the unknown settings better.
3151 // Warn about invalid options.
3152 // Check whether some option was given twice.
3154 preamble.registerAutomaticallyLoadedPackage("graphicx");
3157 else if (t.cs() == "footnote" ||
3158 (t.cs() == "thanks" && context.layout->intitle)) {
3160 context.check_layout(os);
3161 begin_inset(os, "Foot\n");
3162 os << "status collapsed\n\n";
3163 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3167 else if (t.cs() == "marginpar") {
3169 context.check_layout(os);
3170 begin_inset(os, "Marginal\n");
3171 os << "status collapsed\n\n";
3172 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3176 else if (t.cs() == "lstinline") {
3178 parse_listings(p, os, context, true);
3181 else if (t.cs() == "ensuremath") {
3183 context.check_layout(os);
3184 string const s = p.verbatim_item();
3185 //FIXME: this never triggers in UTF8
3186 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3189 output_ert_inset(os, "\\ensuremath{" + s + "}",
3193 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3194 if (preamble.titleLayoutFound()) {
3196 skip_spaces_braces(p);
3198 output_ert_inset(os, t.asInput(), context);
3201 else if (t.cs() == "tableofcontents" || t.cs() == "lstlistoflistings") {
3202 context.check_layout(os);
3203 begin_command_inset(os, "toc", t.cs());
3205 skip_spaces_braces(p);
3206 if (t.cs() == "lstlistoflistings")
3207 preamble.registerAutomaticallyLoadedPackage("listings");
3210 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3211 context.check_layout(os);
3212 if (t.cs() == "listoffigures")
3213 begin_inset(os, "FloatList figure\n");
3215 begin_inset(os, "FloatList table\n");
3217 skip_spaces_braces(p);
3220 else if (t.cs() == "listof") {
3221 p.skip_spaces(true);
3222 string const name = p.get_token().cs();
3223 if (context.textclass.floats().typeExist(name)) {
3224 context.check_layout(os);
3225 begin_inset(os, "FloatList ");
3228 p.get_token(); // swallow second arg
3230 output_ert_inset(os, "\\listof{" + name + "}", context);
3233 else if ((where = is_known(t.cs(), known_text_font_families)))
3234 parse_text_attributes(p, os, FLAG_ITEM, outer,
3235 context, "\\family", context.font.family,
3236 known_coded_font_families[where - known_text_font_families]);
3238 else if ((where = is_known(t.cs(), known_text_font_series)))
3239 parse_text_attributes(p, os, FLAG_ITEM, outer,
3240 context, "\\series", context.font.series,
3241 known_coded_font_series[where - known_text_font_series]);
3243 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3244 parse_text_attributes(p, os, FLAG_ITEM, outer,
3245 context, "\\shape", context.font.shape,
3246 known_coded_font_shapes[where - known_text_font_shapes]);
3248 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3249 context.check_layout(os);
3250 TeXFont oldFont = context.font;
3251 context.font.init();
3252 context.font.size = oldFont.size;
3253 os << "\n\\family " << context.font.family << "\n";
3254 os << "\n\\series " << context.font.series << "\n";
3255 os << "\n\\shape " << context.font.shape << "\n";
3256 if (t.cs() == "textnormal") {
3257 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3258 output_font_change(os, context.font, oldFont);
3259 context.font = oldFont;
3261 eat_whitespace(p, os, context, false);
3264 else if (t.cs() == "textcolor") {
3265 // scheme is \textcolor{color name}{text}
3266 string const color = p.verbatim_item();
3267 // we support the predefined colors of the color and the xcolor package
3268 if (color == "black" || color == "blue" || color == "cyan"
3269 || color == "green" || color == "magenta" || color == "red"
3270 || color == "white" || color == "yellow") {
3271 context.check_layout(os);
3272 os << "\n\\color " << color << "\n";
3273 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3274 context.check_layout(os);
3275 os << "\n\\color inherit\n";
3276 preamble.registerAutomaticallyLoadedPackage("color");
3277 } else if (color == "brown" || color == "darkgray" || color == "gray"
3278 || color == "lightgray" || color == "lime" || color == "olive"
3279 || color == "orange" || color == "pink" || color == "purple"
3280 || color == "teal" || color == "violet") {
3281 context.check_layout(os);
3282 os << "\n\\color " << color << "\n";
3283 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3284 context.check_layout(os);
3285 os << "\n\\color inherit\n";
3286 preamble.registerAutomaticallyLoadedPackage("xcolor");
3288 // for custom defined colors
3289 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3292 else if (t.cs() == "underbar" || t.cs() == "uline") {
3293 // \underbar is not 100% correct (LyX outputs \uline
3294 // of ulem.sty). The difference is that \ulem allows
3295 // line breaks, and \underbar does not.
3296 // Do NOT handle \underline.
3297 // \underbar cuts through y, g, q, p etc.,
3298 // \underline does not.
3299 context.check_layout(os);
3300 os << "\n\\bar under\n";
3301 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3302 context.check_layout(os);
3303 os << "\n\\bar default\n";
3304 preamble.registerAutomaticallyLoadedPackage("ulem");
3307 else if (t.cs() == "sout") {
3308 context.check_layout(os);
3309 os << "\n\\strikeout on\n";
3310 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3311 context.check_layout(os);
3312 os << "\n\\strikeout default\n";
3313 preamble.registerAutomaticallyLoadedPackage("ulem");
3316 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
3317 t.cs() == "emph" || t.cs() == "noun") {
3318 context.check_layout(os);
3319 os << "\n\\" << t.cs() << " on\n";
3320 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3321 context.check_layout(os);
3322 os << "\n\\" << t.cs() << " default\n";
3323 if (t.cs() == "uuline" || t.cs() == "uwave")
3324 preamble.registerAutomaticallyLoadedPackage("ulem");
3327 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3328 context.check_layout(os);
3329 string name = p.getArg('{', '}');
3330 string localtime = p.getArg('{', '}');
3331 preamble.registerAuthor(name);
3332 Author const & author = preamble.getAuthor(name);
3333 // from_asctime_utc() will fail if LyX decides to output the
3334 // time in the text language.
3335 time_t ptime = from_asctime_utc(localtime);
3336 if (ptime == static_cast<time_t>(-1)) {
3337 cerr << "Warning: Could not parse time `" << localtime
3338 << "´ for change tracking, using current time instead.\n";
3339 ptime = current_time();
3341 if (t.cs() == "lyxadded")
3342 os << "\n\\change_inserted ";
3344 os << "\n\\change_deleted ";
3345 os << author.bufferId() << ' ' << ptime << '\n';
3346 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3347 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3348 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3349 LaTeXPackages::isAvailable("xcolor");
3350 // No need to test for luatex, since luatex comes in
3351 // two flavours (dvi and pdf), like latex, and those
3352 // are detected by pdflatex.
3353 if (pdflatex || xetex) {
3355 preamble.registerAutomaticallyLoadedPackage("ulem");
3356 preamble.registerAutomaticallyLoadedPackage("xcolor");
3357 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3361 preamble.registerAutomaticallyLoadedPackage("dvipost");
3362 } else if (xcolorulem) {
3363 preamble.registerAutomaticallyLoadedPackage("ulem");
3364 preamble.registerAutomaticallyLoadedPackage("xcolor");
3369 else if (t.cs() == "textipa") {
3370 context.check_layout(os);
3371 begin_inset(os, "IPA\n");
3372 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3373 context.merging_hyphens_allowed = false;
3374 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3375 context.merging_hyphens_allowed = merging_hyphens_allowed;
3377 preamble.registerAutomaticallyLoadedPackage("tipa");
3378 preamble.registerAutomaticallyLoadedPackage("tipx");
3381 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3382 context.check_layout(os);
3383 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3384 os << "status open\n";
3385 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3390 else if (t.cs() == "textvertline") {
3391 // FIXME: This is not correct, \textvertline is higher than |
3397 else if (t.cs() == "tone" ) {
3398 context.check_layout(os);
3399 // register the tone package
3400 preamble.registerAutomaticallyLoadedPackage("tone");
3401 string content = trimSpaceAndEol(p.verbatim_item());
3402 string command = t.asInput() + "{" + content + "}";
3403 // some tones can be detected by unicodesymbols, some need special code
3404 if (is_known(content, known_tones)) {
3405 os << "\\IPAChar " << command << "\n";
3408 // try to see whether the string is in unicodesymbols
3412 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3413 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3414 termination, rem, &req);
3418 output_ert_inset(os, to_utf8(rem), context);
3419 for (set<string>::const_iterator it = req.begin();
3420 it != req.end(); ++it)
3421 preamble.registerAutomaticallyLoadedPackage(*it);
3423 // we did not find a non-ert version
3424 output_ert_inset(os, command, context);
3427 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3428 t.cs() == "vphantom") {
3429 context.check_layout(os);
3430 if (t.cs() == "phantom")
3431 begin_inset(os, "Phantom Phantom\n");
3432 if (t.cs() == "hphantom")
3433 begin_inset(os, "Phantom HPhantom\n");
3434 if (t.cs() == "vphantom")
3435 begin_inset(os, "Phantom VPhantom\n");
3436 os << "status open\n";
3437 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3442 else if (t.cs() == "href") {
3443 context.check_layout(os);
3444 string target = convert_command_inset_arg(p.verbatim_item());
3445 string name = convert_command_inset_arg(p.verbatim_item());
3447 size_t i = target.find(':');
3448 if (i != string::npos) {
3449 type = target.substr(0, i + 1);
3450 if (type == "mailto:" || type == "file:")
3451 target = target.substr(i + 1);
3452 // handle the case that name is equal to target, except of "http://"
3453 else if (target.substr(i + 3) == name && type == "http:")
3456 begin_command_inset(os, "href", "href");
3458 os << "name \"" << name << "\"\n";
3459 os << "target \"" << target << "\"\n";
3460 if (type == "mailto:" || type == "file:")
3461 os << "type \"" << type << "\"\n";
3463 skip_spaces_braces(p);
3466 else if (t.cs() == "lyxline") {
3467 // swallow size argument (it is not used anyway)
3469 if (!context.atParagraphStart()) {
3470 // so our line is in the middle of a paragraph
3471 // we need to add a new line, lest this line
3472 // follow the other content on that line and
3473 // run off the side of the page
3474 // FIXME: This may create an empty paragraph,
3475 // but without that it would not be
3476 // possible to set noindent below.
3477 // Fortunately LaTeX does not care
3478 // about the empty paragraph.
3479 context.new_paragraph(os);
3481 if (preamble.indentParagraphs()) {
3482 // we need to unindent, lest the line be too long
3483 context.add_par_extra_stuff("\\noindent\n");
3485 context.check_layout(os);
3486 begin_command_inset(os, "line", "rule");
3487 os << "offset \"0.5ex\"\n"
3488 "width \"100line%\"\n"
3493 else if (t.cs() == "rule") {
3494 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3495 string const width = p.getArg('{', '}');
3496 string const thickness = p.getArg('{', '}');
3497 context.check_layout(os);
3498 begin_command_inset(os, "line", "rule");
3499 if (!offset.empty())
3500 os << "offset \"" << translate_len(offset) << "\"\n";
3501 os << "width \"" << translate_len(width) << "\"\n"
3502 "height \"" << translate_len(thickness) << "\"\n";
3506 // handle refstyle first to catch \eqref which can also occur
3507 // without refstyle. Only recognize these commands if
3508 // refstyle.sty was found in the preamble (otherwise \eqref
3509 // and user defined ref commands could be misdetected).
3510 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3511 preamble.refstyle()) {
3512 context.check_layout(os);
3513 begin_command_inset(os, "ref", "formatted");
3514 os << "reference \"";
3515 os << known_refstyle_prefixes[where - known_refstyle_commands]
3517 os << convert_command_inset_arg(p.verbatim_item())
3520 preamble.registerAutomaticallyLoadedPackage("refstyle");
3523 // if refstyle is used, we must not convert \prettyref to a
3524 // formatted reference, since that would result in a refstyle command.
3525 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3526 (t.cs() != "prettyref" || !preamble.refstyle())) {
3527 string const opt = p.getOpt();
3529 context.check_layout(os);
3530 begin_command_inset(os, "ref",
3531 known_coded_ref_commands[where - known_ref_commands]);
3532 os << "reference \""
3533 << convert_command_inset_arg(p.verbatim_item())
3536 if (t.cs() == "vref" || t.cs() == "vpageref")
3537 preamble.registerAutomaticallyLoadedPackage("varioref");
3538 else if (t.cs() == "prettyref")
3539 preamble.registerAutomaticallyLoadedPackage("prettyref");
3541 // LyX does not yet support optional arguments of ref commands
3542 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3543 p.verbatim_item() + '}', context);
3547 else if (use_natbib &&
3548 is_known(t.cs(), known_natbib_commands) &&
3549 ((t.cs() != "citefullauthor" &&
3550 t.cs() != "citeyear" &&
3551 t.cs() != "citeyearpar") ||
3552 p.next_token().asInput() != "*")) {
3553 context.check_layout(os);
3554 string command = t.cs();
3555 if (p.next_token().asInput() == "*") {
3559 if (command == "citefullauthor")
3560 // alternative name for "\\citeauthor*"
3561 command = "citeauthor*";
3563 // text before the citation
3565 // text after the citation
3567 get_cite_arguments(p, true, before, after);
3569 if (command == "cite") {
3570 // \cite without optional argument means
3571 // \citet, \cite with at least one optional
3572 // argument means \citep.
3573 if (before.empty() && after.empty())
3578 if (before.empty() && after == "[]")
3579 // avoid \citet[]{a}
3581 else if (before == "[]" && after == "[]") {
3582 // avoid \citet[][]{a}
3586 // remove the brackets around after and before
3587 if (!after.empty()) {
3589 after.erase(after.length() - 1, 1);
3590 after = convert_command_inset_arg(after);
3592 if (!before.empty()) {
3594 before.erase(before.length() - 1, 1);
3595 before = convert_command_inset_arg(before);
3597 begin_command_inset(os, "citation", command);
3598 os << "after " << '"' << after << '"' << "\n";
3599 os << "before " << '"' << before << '"' << "\n";
3601 << convert_command_inset_arg(p.verbatim_item())
3604 // Need to set the cite engine if natbib is loaded by
3605 // the document class directly
3606 if (preamble.citeEngine() == "basic")
3607 preamble.citeEngine("natbib");
3610 else if (use_jurabib &&
3611 is_known(t.cs(), known_jurabib_commands) &&
3612 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3613 context.check_layout(os);
3614 string command = t.cs();
3615 if (p.next_token().asInput() == "*") {
3619 char argumentOrder = '\0';
3620 vector<string> const options =
3621 preamble.getPackageOptions("jurabib");
3622 if (find(options.begin(), options.end(),
3623 "natbiborder") != options.end())
3624 argumentOrder = 'n';
3625 else if (find(options.begin(), options.end(),
3626 "jurabiborder") != options.end())
3627 argumentOrder = 'j';
3629 // text before the citation
3631 // text after the citation
3633 get_cite_arguments(p, argumentOrder != 'j', before, after);
3635 string const citation = p.verbatim_item();
3636 if (!before.empty() && argumentOrder == '\0') {
3637 cerr << "Warning: Assuming argument order "
3638 "of jurabib version 0.6 for\n'"
3639 << command << before << after << '{'
3640 << citation << "}'.\n"
3641 "Add 'jurabiborder' to the jurabib "
3642 "package options if you used an\n"
3643 "earlier jurabib version." << endl;
3645 if (!after.empty()) {
3647 after.erase(after.length() - 1, 1);
3649 if (!before.empty()) {
3651 before.erase(before.length() - 1, 1);
3653 begin_command_inset(os, "citation", command);
3654 os << "after " << '"' << after << '"' << "\n";
3655 os << "before " << '"' << before << '"' << "\n";
3656 os << "key " << '"' << citation << '"' << "\n";
3658 // Need to set the cite engine if jurabib is loaded by
3659 // the document class directly
3660 if (preamble.citeEngine() == "basic")
3661 preamble.citeEngine("jurabib");
3664 else if (t.cs() == "cite"
3665 || t.cs() == "nocite") {
3666 context.check_layout(os);
3667 string after = convert_command_inset_arg(p.getArg('[', ']'));
3668 string key = convert_command_inset_arg(p.verbatim_item());
3669 // store the case that it is "\nocite{*}" to use it later for
3672 begin_command_inset(os, "citation", t.cs());
3673 os << "after " << '"' << after << '"' << "\n";
3674 os << "key " << '"' << key << '"' << "\n";
3676 } else if (t.cs() == "nocite")
3680 else if (t.cs() == "index" ||
3681 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3682 context.check_layout(os);
3683 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3684 p.getArg('[', ']') : "";
3685 string const kind = arg.empty() ? "idx" : arg;
3686 begin_inset(os, "Index ");
3687 os << kind << "\nstatus collapsed\n";
3688 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3691 preamble.registerAutomaticallyLoadedPackage("splitidx");
3694 else if (t.cs() == "nomenclature") {
3695 context.check_layout(os);
3696 begin_command_inset(os, "nomenclature", "nomenclature");
3697 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3698 if (!prefix.empty())
3699 os << "prefix " << '"' << prefix << '"' << "\n";
3700 os << "symbol " << '"'
3701 << convert_command_inset_arg(p.verbatim_item());
3702 os << "\"\ndescription \""
3703 << convert_command_inset_arg(p.verbatim_item())
3706 preamble.registerAutomaticallyLoadedPackage("nomencl");
3709 else if (t.cs() == "label") {
3710 context.check_layout(os);
3711 begin_command_inset(os, "label", "label");
3713 << convert_command_inset_arg(p.verbatim_item())
3718 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3719 context.check_layout(os);
3720 string commandname = t.cs();
3722 if (p.next_token().asInput() == "*") {
3727 begin_command_inset(os, "index_print", commandname);
3728 string const indexname = p.getArg('[', ']');
3730 if (indexname.empty())
3731 os << "type \"idx\"\n";
3733 os << "type \"" << indexname << "\"\n";
3736 skip_spaces_braces(p);
3737 preamble.registerAutomaticallyLoadedPackage("makeidx");
3738 if (preamble.use_indices() == "true")
3739 preamble.registerAutomaticallyLoadedPackage("splitidx");
3742 else if (t.cs() == "printnomenclature") {
3744 string width_type = "";
3745 context.check_layout(os);
3746 begin_command_inset(os, "nomencl_print", "printnomenclature");
3747 // case of a custom width
3749 width = p.getArg('[', ']');
3750 width = translate_len(width);
3751 width_type = "custom";
3753 // case of no custom width
3754 // the case of no custom width but the width set
3755 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3756 // because the user could have set anything, not only the width
3757 // of the longest label (which would be width_type = "auto")
3758 string label = convert_command_inset_arg(p.getArg('{', '}'));
3759 if (label.empty() && width_type.empty())
3760 width_type = "none";
3761 os << "set_width \"" << width_type << "\"\n";
3762 if (width_type == "custom")
3763 os << "width \"" << width << '\"';
3765 skip_spaces_braces(p);
3766 preamble.registerAutomaticallyLoadedPackage("nomencl");
3769 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
3770 context.check_layout(os);
3771 begin_inset(os, "script ");
3772 os << t.cs().substr(4) << '\n';
3773 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
3774 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3776 if (t.cs() == "textsubscript")
3777 preamble.registerAutomaticallyLoadedPackage("subscript");
3780 else if ((where = is_known(t.cs(), known_quotes))) {
3781 context.check_layout(os);
3782 begin_inset(os, "Quotes ");
3783 os << known_coded_quotes[where - known_quotes];
3785 // LyX adds {} after the quote, so we have to eat
3786 // spaces here if there are any before a possible
3788 eat_whitespace(p, os, context, false);
3792 else if ((where = is_known(t.cs(), known_sizes)) &&
3793 context.new_layout_allowed) {
3794 context.check_layout(os);
3795 TeXFont const oldFont = context.font;
3796 context.font.size = known_coded_sizes[where - known_sizes];
3797 output_font_change(os, oldFont, context.font);
3798 eat_whitespace(p, os, context, false);
3801 else if ((where = is_known(t.cs(), known_font_families)) &&
3802 context.new_layout_allowed) {
3803 context.check_layout(os);
3804 TeXFont const oldFont = context.font;
3805 context.font.family =
3806 known_coded_font_families[where - known_font_families];
3807 output_font_change(os, oldFont, context.font);
3808 eat_whitespace(p, os, context, false);
3811 else if ((where = is_known(t.cs(), known_font_series)) &&
3812 context.new_layout_allowed) {
3813 context.check_layout(os);
3814 TeXFont const oldFont = context.font;
3815 context.font.series =
3816 known_coded_font_series[where - known_font_series];
3817 output_font_change(os, oldFont, context.font);
3818 eat_whitespace(p, os, context, false);
3821 else if ((where = is_known(t.cs(), known_font_shapes)) &&
3822 context.new_layout_allowed) {
3823 context.check_layout(os);
3824 TeXFont const oldFont = context.font;
3825 context.font.shape =
3826 known_coded_font_shapes[where - known_font_shapes];
3827 output_font_change(os, oldFont, context.font);
3828 eat_whitespace(p, os, context, false);
3830 else if ((where = is_known(t.cs(), known_old_font_families)) &&
3831 context.new_layout_allowed) {
3832 context.check_layout(os);
3833 TeXFont const oldFont = context.font;
3834 context.font.init();
3835 context.font.size = oldFont.size;
3836 context.font.family =
3837 known_coded_font_families[where - known_old_font_families];
3838 output_font_change(os, oldFont, context.font);
3839 eat_whitespace(p, os, context, false);
3842 else if ((where = is_known(t.cs(), known_old_font_series)) &&
3843 context.new_layout_allowed) {
3844 context.check_layout(os);
3845 TeXFont const oldFont = context.font;
3846 context.font.init();
3847 context.font.size = oldFont.size;
3848 context.font.series =
3849 known_coded_font_series[where - known_old_font_series];
3850 output_font_change(os, oldFont, context.font);
3851 eat_whitespace(p, os, context, false);
3854 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
3855 context.new_layout_allowed) {
3856 context.check_layout(os);
3857 TeXFont const oldFont = context.font;
3858 context.font.init();
3859 context.font.size = oldFont.size;
3860 context.font.shape =
3861 known_coded_font_shapes[where - known_old_font_shapes];
3862 output_font_change(os, oldFont, context.font);
3863 eat_whitespace(p, os, context, false);
3866 else if (t.cs() == "selectlanguage") {
3867 context.check_layout(os);
3868 // save the language for the case that a
3869 // \foreignlanguage is used
3870 context.font.language = babel2lyx(p.verbatim_item());
3871 os << "\n\\lang " << context.font.language << "\n";
3874 else if (t.cs() == "foreignlanguage") {
3875 string const lang = babel2lyx(p.verbatim_item());
3876 parse_text_attributes(p, os, FLAG_ITEM, outer,
3878 context.font.language, lang);
3881 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
3882 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
3883 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
3885 // We have to output the whole command if it has an option
3886 // because LyX doesn't support this yet, see bug #8214,
3887 // only if there is a single option specifying a variant, we can handle it.
3889 string langopts = p.getOpt();
3890 // check if the option contains a variant, if yes, extract it
3891 string::size_type pos_var = langopts.find("variant");
3892 string::size_type i = langopts.find(',');
3893 string::size_type k = langopts.find('=', pos_var);
3894 if (pos_var != string::npos && i == string::npos) {
3896 variant = langopts.substr(k + 1, langopts.length() - k - 2);
3897 lang = preamble.polyglossia2lyx(variant);
3898 parse_text_attributes(p, os, FLAG_ITEM, outer,
3900 context.font.language, lang);
3902 output_ert_inset(os, t.asInput() + langopts, context);
3904 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
3905 parse_text_attributes(p, os, FLAG_ITEM, outer,
3907 context.font.language, lang);
3911 else if (t.cs() == "inputencoding") {
3912 // nothing to write here
3913 string const enc = subst(p.verbatim_item(), "\n", " ");
3914 p.setEncoding(enc, Encoding::inputenc);
3917 else if (is_known(t.cs(), known_special_chars) ||
3918 (t.cs() == "protect" &&
3919 p.next_token().cat() == catEscape &&
3920 is_known(p.next_token().cs(), known_special_protect_chars))) {
3921 // LyX sometimes puts a \protect in front, so we have to ignore it
3923 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
3924 known_special_chars);
3925 context.check_layout(os);
3926 os << known_coded_special_chars[where - known_special_chars];
3927 skip_spaces_braces(p);
3930 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
3931 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
3932 p.next_next_token().asInput() == "-") ||
3933 (t.cs() == "@" && p.next_token().asInput() == ".")) {
3934 // LyX sometimes puts a \protect in front, so we have to ignore it
3935 if (t.cs() == "protect")
3937 context.check_layout(os);
3938 if (t.cs() == "nobreakdash")
3939 os << "\\SpecialChar nobreakdash\n";
3941 os << "\\SpecialChar endofsentence\n";
3945 else if (t.cs() == "textquotedbl") {
3946 context.check_layout(os);
3951 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3952 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3953 || t.cs() == "%" || t.cs() == "-") {
3954 context.check_layout(os);
3956 os << "\\SpecialChar softhyphen\n";
3961 else if (t.cs() == "char") {
3962 context.check_layout(os);
3963 if (p.next_token().character() == '`') {
3965 if (p.next_token().cs() == "\"") {
3970 output_ert_inset(os, "\\char`", context);
3973 output_ert_inset(os, "\\char", context);
3977 else if (t.cs() == "verb") {
3978 context.check_layout(os);
3979 // set catcodes to verbatim early, just in case.
3980 p.setCatcodes(VERBATIM_CATCODES);
3981 string delim = p.get_token().asInput();
3982 Parser::Arg arg = p.verbatimStuff(delim);
3984 output_ert_inset(os, "\\verb" + delim
3985 + arg.second + delim, context);
3987 cerr << "invalid \\verb command. Skipping" << endl;
3990 // Problem: \= creates a tabstop inside the tabbing environment
3991 // and else an accent. In the latter case we really would want
3992 // \={o} instead of \= o.
3993 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3994 output_ert_inset(os, t.asInput(), context);
3996 else if (t.cs() == "\\") {
3997 context.check_layout(os);
3999 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4000 else if (p.next_token().asInput() == "*") {
4002 // getOpt() eats the following space if there
4003 // is no optional argument, but that is OK
4004 // here since it has no effect in the output.
4005 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4008 begin_inset(os, "Newline newline");
4013 else if (t.cs() == "newline" ||
4014 (t.cs() == "linebreak" && !p.hasOpt())) {
4015 context.check_layout(os);
4016 begin_inset(os, "Newline ");
4019 skip_spaces_braces(p);
4022 else if (t.cs() == "input" || t.cs() == "include"
4023 || t.cs() == "verbatiminput") {
4024 string name = t.cs();
4025 if (t.cs() == "verbatiminput"
4026 && p.next_token().asInput() == "*")
4027 name += p.get_token().asInput();
4028 context.check_layout(os);
4029 string filename(normalize_filename(p.getArg('{', '}')));
4030 string const path = getMasterFilePath(true);
4031 // We want to preserve relative / absolute filenames,
4032 // therefore path is only used for testing
4033 if ((t.cs() == "include" || t.cs() == "input") &&
4034 !makeAbsPath(filename, path).exists()) {
4035 // The file extension is probably missing.
4036 // Now try to find it out.
4037 string const tex_name =
4038 find_file(filename, path,
4039 known_tex_extensions);
4040 if (!tex_name.empty())
4041 filename = tex_name;
4043 bool external = false;
4045 if (makeAbsPath(filename, path).exists()) {
4046 string const abstexname =
4047 makeAbsPath(filename, path).absFileName();
4048 string const absfigname =
4049 changeExtension(abstexname, ".fig");
4050 fix_child_filename(filename);
4051 string const lyxname = changeExtension(filename,
4052 roundtripMode() ? ".lyx.lyx" : ".lyx");
4053 string const abslyxname = makeAbsPath(
4054 lyxname, getParentFilePath(false)).absFileName();
4056 if (!skipChildren())
4057 external = FileName(absfigname).exists();
4058 if (t.cs() == "input" && !skipChildren()) {
4059 string const ext = getExtension(abstexname);
4061 // Combined PS/LaTeX:
4062 // x.eps, x.pstex_t (old xfig)
4063 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4064 FileName const absepsname(
4065 changeExtension(abstexname, ".eps"));
4066 FileName const abspstexname(
4067 changeExtension(abstexname, ".pstex"));
4068 bool const xfigeps =
4069 (absepsname.exists() ||
4070 abspstexname.exists()) &&
4073 // Combined PDF/LaTeX:
4074 // x.pdf, x.pdftex_t (old xfig)
4075 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4076 FileName const abspdfname(
4077 changeExtension(abstexname, ".pdf"));
4078 bool const xfigpdf =
4079 abspdfname.exists() &&
4080 (ext == "pdftex_t" || ext == "pdf_t");
4084 // Combined PS/PDF/LaTeX:
4085 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4086 string const absbase2(
4087 removeExtension(abstexname) + "_pspdftex");
4088 FileName const abseps2name(
4089 addExtension(absbase2, ".eps"));
4090 FileName const abspdf2name(
4091 addExtension(absbase2, ".pdf"));
4092 bool const xfigboth =
4093 abspdf2name.exists() &&
4094 abseps2name.exists() && ext == "pspdftex";
4096 xfig = xfigpdf || xfigeps || xfigboth;
4097 external = external && xfig;
4100 outname = changeExtension(filename, ".fig");
4101 FileName abssrc(changeExtension(abstexname, ".fig"));
4102 copy_file(abssrc, outname);
4104 // Don't try to convert, the result
4105 // would be full of ERT.
4107 FileName abssrc(abstexname);
4108 copy_file(abssrc, outname);
4109 } else if (t.cs() != "verbatiminput" &&
4111 tex2lyx(abstexname, FileName(abslyxname),
4114 // no need to call copy_file
4115 // tex2lyx creates the file
4118 FileName abssrc(abstexname);
4119 copy_file(abssrc, outname);
4122 cerr << "Warning: Could not find included file '"
4123 << filename << "'." << endl;
4127 begin_inset(os, "External\n");
4128 os << "\ttemplate XFig\n"
4129 << "\tfilename " << outname << '\n';
4130 registerExternalTemplatePackages("XFig");
4132 begin_command_inset(os, "include", name);
4133 outname = subst(outname, "\"", "\\\"");
4134 os << "preview false\n"
4135 "filename \"" << outname << "\"\n";
4136 if (t.cs() == "verbatiminput")
4137 preamble.registerAutomaticallyLoadedPackage("verbatim");
4142 else if (t.cs() == "bibliographystyle") {
4143 // store new bibliographystyle
4144 bibliographystyle = p.verbatim_item();
4145 // If any other command than \bibliography, \addcontentsline
4146 // and \nocite{*} follows, we need to output the style
4147 // (because it might be used by that command).
4148 // Otherwise, it will automatically be output by LyX.
4151 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4152 if (t2.cat() == catBegin)
4154 if (t2.cat() != catEscape)
4156 if (t2.cs() == "nocite") {
4157 if (p.getArg('{', '}') == "*")
4159 } else if (t2.cs() == "bibliography")
4161 else if (t2.cs() == "phantomsection") {
4165 else if (t2.cs() == "addcontentsline") {
4166 // get the 3 arguments of \addcontentsline
4169 contentslineContent = p.getArg('{', '}');
4170 // if the last argument is not \refname we must output
4171 if (contentslineContent == "\\refname")
4178 output_ert_inset(os,
4179 "\\bibliographystyle{" + bibliographystyle + '}',
4184 else if (t.cs() == "phantomsection") {
4185 // we only support this if it occurs between
4186 // \bibliographystyle and \bibliography
4187 if (bibliographystyle.empty())
4188 output_ert_inset(os, "\\phantomsection", context);
4191 else if (t.cs() == "addcontentsline") {
4192 context.check_layout(os);
4193 // get the 3 arguments of \addcontentsline
4194 string const one = p.getArg('{', '}');
4195 string const two = p.getArg('{', '}');
4196 string const three = p.getArg('{', '}');
4197 // only if it is a \refname, we support if for the bibtex inset
4198 if (contentslineContent != "\\refname") {
4199 output_ert_inset(os,
4200 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4205 else if (t.cs() == "bibliography") {
4206 context.check_layout(os);
4208 begin_command_inset(os, "bibtex", "bibtex");
4209 if (!btprint.empty()) {
4210 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4211 // clear the string because the next BibTeX inset can be without the
4212 // \nocite{*} option
4215 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
4216 // Do we have addcontentsline?
4217 if (contentslineContent == "\\refname") {
4218 BibOpts = "bibtotoc";
4219 // clear string because next BibTeX inset can be without addcontentsline
4220 contentslineContent.clear();
4222 // Do we have a bibliographystyle set?
4223 if (!bibliographystyle.empty()) {
4224 if (BibOpts.empty())
4225 BibOpts = bibliographystyle;
4227 BibOpts = BibOpts + ',' + bibliographystyle;
4228 // clear it because each bibtex entry has its style
4229 // and we need an empty string to handle \phantomsection
4230 bibliographystyle.clear();
4232 os << "options " << '"' << BibOpts << '"' << "\n";
4236 else if (t.cs() == "parbox") {
4237 // Test whether this is an outer box of a shaded box
4239 // swallow arguments
4240 while (p.hasOpt()) {
4242 p.skip_spaces(true);
4245 p.skip_spaces(true);
4247 if (p.next_token().cat() == catBegin)
4249 p.skip_spaces(true);
4250 Token to = p.get_token();
4251 bool shaded = false;
4252 if (to.asInput() == "\\begin") {
4253 p.skip_spaces(true);
4254 if (p.getArg('{', '}') == "shaded")
4259 parse_outer_box(p, os, FLAG_ITEM, outer,
4260 context, "parbox", "shaded");
4262 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4263 "", "", t.cs(), "", "");
4266 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4267 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4268 t.cs() == "shadowbox" || t.cs() == "doublebox")
4269 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4271 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4272 string backgroundcolor;
4273 preamble.registerAutomaticallyLoadedPackage("xcolor");
4274 if (t.cs() == "fcolorbox") {
4275 string const framecolor = p.getArg('{', '}');
4276 backgroundcolor = p.getArg('{', '}');
4277 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4279 backgroundcolor = p.getArg('{', '}');
4280 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4284 // FIXME: due to the compiler limit of "if" nestings
4285 // the code for the alignment was put here
4286 // put them in their own if if this is fixed
4287 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4288 || t.cs() == "shadowsize"
4289 || t.cs() == "raggedleft" || t.cs() == "centering"
4290 || t.cs() == "raggedright") {
4291 if (t.cs() == "fboxrule")
4293 if (t.cs() == "fboxsep")
4295 if (t.cs() == "shadowsize")
4297 if (t.cs() != "raggedleft" && t.cs() != "centering"
4298 && t.cs() != "raggedright") {
4299 p.skip_spaces(true);
4300 while (p.good() && p.next_token().cat() != catSpace
4301 && p.next_token().cat() != catNewline
4302 && p.next_token().cat() != catEscape) {
4303 if (t.cs() == "fboxrule")
4304 fboxrule = fboxrule + p.get_token().asInput();
4305 if (t.cs() == "fboxsep")
4306 fboxsep = fboxsep + p.get_token().asInput();
4307 if (t.cs() == "shadowsize")
4308 shadow_size = shadow_size + p.get_token().asInput();
4311 // we only handle them if they are in a box
4313 // LyX will add a space after outputting the
4314 // alignment command, so eat any space which
4315 // might follow. Otherwise the paragraph
4316 // might start with an unneeded space.
4317 p.skip_spaces(true);
4319 output_ert_inset(os, t.asInput(), context);
4321 wasBoxAlign = false;
4324 //\framebox() is part of the picture environment and different from \framebox{}
4325 //\framebox{} will be parsed by parse_outer_box
4326 else if (t.cs() == "framebox") {
4327 if (p.next_token().character() == '(') {
4328 //the syntax is: \framebox(x,y)[position]{content}
4329 string arg = t.asInput();
4330 arg += p.getFullParentheseArg();
4331 arg += p.getFullOpt();
4332 eat_whitespace(p, os, context, false);
4333 output_ert_inset(os, arg + '{', context);
4334 parse_text(p, os, FLAG_ITEM, outer, context);
4335 output_ert_inset(os, "}", context);
4337 //the syntax is: \framebox[width][position]{content}
4338 string special = p.getFullOpt();
4339 special += p.getOpt();
4340 parse_outer_box(p, os, FLAG_ITEM, outer,
4341 context, t.cs(), special);
4345 //\makebox() is part of the picture environment and different from \makebox{}
4346 //\makebox{} will be parsed by parse_box
4347 else if (t.cs() == "makebox") {
4348 if (p.next_token().character() == '(') {
4349 //the syntax is: \makebox(x,y)[position]{content}
4350 string arg = t.asInput();
4351 arg += p.getFullParentheseArg();
4352 arg += p.getFullOpt();
4353 eat_whitespace(p, os, context, false);
4354 output_ert_inset(os, arg + '{', context);
4355 parse_text(p, os, FLAG_ITEM, outer, context);
4356 output_ert_inset(os, "}", context);
4358 //the syntax is: \makebox[width][position]{content}
4359 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4360 "", "", t.cs(), "", "");
4363 else if (t.cs() == "smallskip" ||
4364 t.cs() == "medskip" ||
4365 t.cs() == "bigskip" ||
4366 t.cs() == "vfill") {
4367 context.check_layout(os);
4368 begin_inset(os, "VSpace ");
4371 skip_spaces_braces(p);
4374 else if ((where = is_known(t.cs(), known_spaces))) {
4375 context.check_layout(os);
4376 begin_inset(os, "space ");
4377 os << '\\' << known_coded_spaces[where - known_spaces]
4380 // LaTeX swallows whitespace after all spaces except
4381 // "\\,". We have to do that here, too, because LyX
4382 // adds "{}" which would make the spaces significant.
4384 eat_whitespace(p, os, context, false);
4385 // LyX adds "{}" after all spaces except "\\ " and
4386 // "\\,", so we have to remove "{}".
4387 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4388 // remove the braces after "\\,", too.
4393 else if (t.cs() == "newpage" ||
4394 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4395 t.cs() == "clearpage" ||
4396 t.cs() == "cleardoublepage") {
4397 context.check_layout(os);
4398 begin_inset(os, "Newpage ");
4401 skip_spaces_braces(p);
4404 else if (t.cs() == "DeclareRobustCommand" ||
4405 t.cs() == "DeclareRobustCommandx" ||
4406 t.cs() == "newcommand" ||
4407 t.cs() == "newcommandx" ||
4408 t.cs() == "providecommand" ||
4409 t.cs() == "providecommandx" ||
4410 t.cs() == "renewcommand" ||
4411 t.cs() == "renewcommandx") {
4412 // DeclareRobustCommand, DeclareRobustCommandx,
4413 // providecommand and providecommandx could be handled
4414 // by parse_command(), but we need to call
4415 // add_known_command() here.
4416 string name = t.asInput();
4417 if (p.next_token().asInput() == "*") {
4418 // Starred form. Eat '*'
4422 string const command = p.verbatim_item();
4423 string const opt1 = p.getFullOpt();
4424 string const opt2 = p.getFullOpt();
4425 add_known_command(command, opt1, !opt2.empty());
4426 string const ert = name + '{' + command + '}' +
4428 '{' + p.verbatim_item() + '}';
4430 if (t.cs() == "DeclareRobustCommand" ||
4431 t.cs() == "DeclareRobustCommandx" ||
4432 t.cs() == "providecommand" ||
4433 t.cs() == "providecommandx" ||
4434 name[name.length()-1] == '*')
4435 output_ert_inset(os, ert, context);
4437 context.check_layout(os);
4438 begin_inset(os, "FormulaMacro");
4444 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4445 // let could be handled by parse_command(),
4446 // but we need to call add_known_command() here.
4447 string ert = t.asInput();
4450 if (p.next_token().cat() == catBegin) {
4451 name = p.verbatim_item();
4452 ert += '{' + name + '}';
4454 name = p.verbatim_item();
4459 if (p.next_token().cat() == catBegin) {
4460 command = p.verbatim_item();
4461 ert += '{' + command + '}';
4463 command = p.verbatim_item();
4466 // If command is known, make name known too, to parse
4467 // its arguments correctly. For this reason we also
4468 // have commands in syntax.default that are hardcoded.
4469 CommandMap::iterator it = known_commands.find(command);
4470 if (it != known_commands.end())
4471 known_commands[t.asInput()] = it->second;
4472 output_ert_inset(os, ert, context);
4475 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4478 string name = t.asInput();
4479 string const length = p.verbatim_item();
4482 bool valid = splitLatexLength(length, valstring, unit);
4483 bool known_hspace = false;
4484 bool known_vspace = false;
4485 bool known_unit = false;
4488 istringstream iss(valstring);
4491 if (t.cs()[0] == 'h') {
4492 if (unit == "\\fill") {
4497 known_hspace = true;
4500 if (unit == "\\smallskipamount") {
4502 known_vspace = true;
4503 } else if (unit == "\\medskipamount") {
4505 known_vspace = true;
4506 } else if (unit == "\\bigskipamount") {
4508 known_vspace = true;
4509 } else if (unit == "\\fill") {
4511 known_vspace = true;
4515 if (!known_hspace && !known_vspace) {
4516 switch (unitFromString(unit)) {
4532 //unitFromString(unit) fails for relative units like Length::PCW
4533 // therefore handle them separately
4534 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4535 || unit == "\\textwidth" || unit == "\\linewidth"
4536 || unit == "\\textheight" || unit == "\\paperheight")
4544 // check for glue lengths
4545 bool is_gluelength = false;
4546 string gluelength = length;
4547 string::size_type i = length.find(" minus");
4548 if (i == string::npos) {
4549 i = length.find(" plus");
4550 if (i != string::npos)
4551 is_gluelength = true;
4553 is_gluelength = true;
4554 // if yes transform "9xx minus 8yy plus 7zz"
4556 if (is_gluelength) {
4557 i = gluelength.find(" minus");
4558 if (i != string::npos)
4559 gluelength.replace(i, 7, "-");
4560 i = gluelength.find(" plus");
4561 if (i != string::npos)
4562 gluelength.replace(i, 6, "+");
4565 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4566 // Literal horizontal length or known variable
4567 context.check_layout(os);
4568 begin_inset(os, "space ");
4576 if (known_unit && !known_hspace)
4577 os << "\n\\length " << translate_len(length);
4579 os << "\n\\length " << gluelength;
4581 } else if (known_unit || known_vspace || is_gluelength) {
4582 // Literal vertical length or known variable
4583 context.check_layout(os);
4584 begin_inset(os, "VSpace ");
4587 if (known_unit && !known_vspace)
4588 os << translate_len(length);
4595 // LyX can't handle other length variables in Inset VSpace/space
4600 output_ert_inset(os, name + '{' + unit + '}', context);
4601 else if (value == -1.0)
4602 output_ert_inset(os, name + "{-" + unit + '}', context);
4604 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4606 output_ert_inset(os, name + '{' + length + '}', context);
4610 // The single '=' is meant here.
4611 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4615 context.check_layout(os);
4616 docstring const name = newinsetlayout->name();
4617 bool const caption = name.find(from_ascii("Caption:")) == 0;
4619 begin_inset(os, "Caption ");
4620 os << to_utf8(name.substr(8)) << '\n';
4622 begin_inset(os, "Flex ");
4623 os << to_utf8(name) << '\n'
4624 << "status collapsed\n";
4626 if (newinsetlayout->isPassThru()) {
4627 // set catcodes to verbatim early, just in case.
4628 p.setCatcodes(VERBATIM_CATCODES);
4629 string delim = p.get_token().asInput();
4631 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4632 //FIXME: handle error condition
4633 string const arg = p.verbatimStuff("}").second;
4634 Context newcontext(true, context.textclass);
4635 if (newinsetlayout->forcePlainLayout())
4636 newcontext.layout = &context.textclass.plainLayout();
4637 output_ert(os, arg, newcontext);
4639 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4645 else if (t.cs() == "includepdf") {
4647 string const arg = p.getArg('[', ']');
4648 map<string, string> opts;
4649 vector<string> keys;
4650 split_map(arg, opts, keys);
4651 string name = normalize_filename(p.verbatim_item());
4652 string const path = getMasterFilePath(true);
4653 // We want to preserve relative / absolute filenames,
4654 // therefore path is only used for testing
4655 if (!makeAbsPath(name, path).exists()) {
4656 // The file extension is probably missing.
4657 // Now try to find it out.
4658 char const * const pdfpages_format[] = {"pdf", 0};
4659 string const pdftex_name =
4660 find_file(name, path, pdfpages_format);
4661 if (!pdftex_name.empty()) {
4666 FileName const absname = makeAbsPath(name, path);
4667 if (absname.exists())
4669 fix_child_filename(name);
4670 copy_file(absname, name);
4672 cerr << "Warning: Could not find file '"
4673 << name << "'." << endl;
4675 context.check_layout(os);
4676 begin_inset(os, "External\n\ttemplate ");
4677 os << "PDFPages\n\tfilename "
4679 // parse the options
4680 if (opts.find("pages") != opts.end())
4681 os << "\textra LaTeX \"pages="
4682 << opts["pages"] << "\"\n";
4683 if (opts.find("angle") != opts.end())
4684 os << "\trotateAngle "
4685 << opts["angle"] << '\n';
4686 if (opts.find("origin") != opts.end()) {
4688 string const opt = opts["origin"];
4689 if (opt == "tl") ss << "topleft";
4690 if (opt == "bl") ss << "bottomleft";
4691 if (opt == "Bl") ss << "baselineleft";
4692 if (opt == "c") ss << "center";
4693 if (opt == "tc") ss << "topcenter";
4694 if (opt == "bc") ss << "bottomcenter";
4695 if (opt == "Bc") ss << "baselinecenter";
4696 if (opt == "tr") ss << "topright";
4697 if (opt == "br") ss << "bottomright";
4698 if (opt == "Br") ss << "baselineright";
4699 if (!ss.str().empty())
4700 os << "\trotateOrigin " << ss.str() << '\n';
4702 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4704 if (opts.find("width") != opts.end())
4706 << translate_len(opts["width"]) << '\n';
4707 if (opts.find("height") != opts.end())
4709 << translate_len(opts["height"]) << '\n';
4710 if (opts.find("keepaspectratio") != opts.end())
4711 os << "\tkeepAspectRatio\n";
4713 context.check_layout(os);
4714 registerExternalTemplatePackages("PDFPages");
4717 else if (t.cs() == "loadgame") {
4719 string name = normalize_filename(p.verbatim_item());
4720 string const path = getMasterFilePath(true);
4721 // We want to preserve relative / absolute filenames,
4722 // therefore path is only used for testing
4723 if (!makeAbsPath(name, path).exists()) {
4724 // The file extension is probably missing.
4725 // Now try to find it out.
4726 char const * const lyxskak_format[] = {"fen", 0};
4727 string const lyxskak_name =
4728 find_file(name, path, lyxskak_format);
4729 if (!lyxskak_name.empty())
4730 name = lyxskak_name;
4732 FileName const absname = makeAbsPath(name, path);
4733 if (absname.exists())
4735 fix_child_filename(name);
4736 copy_file(absname, name);
4738 cerr << "Warning: Could not find file '"
4739 << name << "'." << endl;
4740 context.check_layout(os);
4741 begin_inset(os, "External\n\ttemplate ");
4742 os << "ChessDiagram\n\tfilename "
4745 context.check_layout(os);
4746 // after a \loadgame follows a \showboard
4747 if (p.get_token().asInput() == "showboard")
4749 registerExternalTemplatePackages("ChessDiagram");
4753 // try to see whether the string is in unicodesymbols
4754 // Only use text mode commands, since we are in text mode here,
4755 // and math commands may be invalid (bug 6797)
4756 string name = t.asInput();
4757 // handle the dingbats, cyrillic and greek
4758 if (name == "\\ding" || name == "\\textcyr" ||
4759 (name == "\\textgreek" && !preamble.usePolyglossia()))
4760 name = name + '{' + p.getArg('{', '}') + '}';
4761 // handle the ifsym characters
4762 else if (name == "\\textifsymbol") {
4763 string const optif = p.getFullOpt();
4764 string const argif = p.getArg('{', '}');
4765 name = name + optif + '{' + argif + '}';
4767 // handle the \ascii characters
4768 // the case of \ascii within braces, as LyX outputs it, is already
4769 // handled for t.cat() == catBegin
4770 else if (name == "\\ascii") {
4771 // the code is "\asci\xxx"
4772 name = "{" + name + p.get_token().asInput() + "}";
4775 // handle some TIPA special characters
4776 else if (preamble.isPackageUsed("tipa")) {
4777 if (name == "\\textglobfall") {
4780 } else if (name == "\\s") {
4781 // fromLaTeXCommand() does not yet
4782 // recognize tipa short cuts
4783 name = "\\textsyllabic";
4784 } else if (name == "\\=" &&
4785 p.next_token().asInput() == "*") {
4786 // fromLaTeXCommand() does not yet
4787 // recognize tipa short cuts
4790 } else if (name == "\\textdoublevertline") {
4791 // FIXME: This is not correct,
4792 // \textvertline is higher than \textbardbl
4793 name = "\\textbardbl";
4795 } else if (name == "\\!" ) {
4796 if (p.next_token().asInput() == "b") {
4797 p.get_token(); // eat 'b'
4800 } else if (p.next_token().asInput() == "d") {
4804 } else if (p.next_token().asInput() == "g") {
4808 } else if (p.next_token().asInput() == "G") {
4810 name = "\\texthtscg";
4812 } else if (p.next_token().asInput() == "j") {
4814 name = "\\texthtbardotlessj";
4816 } else if (p.next_token().asInput() == "o") {
4818 name = "\\textbullseye";
4821 } else if (name == "\\*" ) {
4822 if (p.next_token().asInput() == "k") {
4824 name = "\\textturnk";
4826 } else if (p.next_token().asInput() == "r") {
4827 p.get_token(); // eat 'b'
4828 name = "\\textturnr";
4830 } else if (p.next_token().asInput() == "t") {
4832 name = "\\textturnt";
4834 } else if (p.next_token().asInput() == "w") {
4836 name = "\\textturnw";
4841 if ((name.size() == 2 &&
4842 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
4843 p.next_token().asInput() != "*") ||
4844 is_known(name.substr(1), known_tipa_marks)) {
4845 // name is a command that corresponds to a
4846 // combining character in unicodesymbols.
4847 // Append the argument, fromLaTeXCommand()
4848 // will either convert it to a single
4849 // character or a combining sequence.
4850 name += '{' + p.verbatim_item() + '}';
4852 // now get the character from unicodesymbols
4856 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
4857 Encodings::TEXT_CMD, termination, rem, &req);
4859 context.check_layout(os);
4862 output_ert_inset(os, to_utf8(rem), context);
4864 skip_spaces_braces(p);
4865 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
4866 preamble.registerAutomaticallyLoadedPackage(*it);
4868 //cerr << "#: " << t << " mode: " << mode << endl;
4869 // heuristic: read up to next non-nested space
4871 string s = t.asInput();
4872 string z = p.verbatim_item();
4873 while (p.good() && z != " " && !z.empty()) {
4874 //cerr << "read: " << z << endl;
4876 z = p.verbatim_item();
4878 cerr << "found ERT: " << s << endl;
4879 output_ert_inset(os, s + ' ', context);
4882 if (t.asInput() == name &&
4883 p.next_token().asInput() == "*") {
4884 // Starred commands like \vspace*{}
4885 p.get_token(); // Eat '*'
4888 if (!parse_command(name, p, os, outer, context))
4889 output_ert_inset(os, name, context);
4893 if (flags & FLAG_LEAVE) {
4894 flags &= ~FLAG_LEAVE;
4901 string guessLanguage(Parser & p, string const & lang)
4903 typedef std::map<std::string, size_t> LangMap;
4904 // map from language names to number of characters
4907 for (char const * const * i = supported_CJK_languages; *i; i++)
4908 used[string(*i)] = 0;
4911 Token const t = p.get_token();
4912 // comments are not counted for any language
4913 if (t.cat() == catComment)
4915 // commands are not counted as well, but we need to detect
4916 // \begin{CJK} and switch encoding if needed
4917 if (t.cat() == catEscape) {
4918 if (t.cs() == "inputencoding") {
4919 string const enc = subst(p.verbatim_item(), "\n", " ");
4920 p.setEncoding(enc, Encoding::inputenc);
4923 if (t.cs() != "begin")
4926 // Non-CJK content is counted for lang.
4927 // We do not care about the real language here:
4928 // If we have more non-CJK contents than CJK contents,
4929 // we simply use the language that was specified as
4930 // babel main language.
4931 used[lang] += t.asInput().length();
4934 // Now we are starting an environment
4936 string const name = p.getArg('{', '}');
4937 if (name != "CJK") {
4941 // It is a CJK environment
4943 /* name = */ p.getArg('{', '}');
4944 string const encoding = p.getArg('{', '}');
4945 /* mapping = */ p.getArg('{', '}');
4946 string const encoding_old = p.getEncoding();
4947 char const * const * const where =
4948 is_known(encoding, supported_CJK_encodings);
4950 p.setEncoding(encoding, Encoding::CJK);
4952 p.setEncoding("UTF-8");
4953 string const text = p.ertEnvironment("CJK");
4954 p.setEncoding(encoding_old);
4957 // ignore contents in unknown CJK encoding
4960 // the language of the text
4962 supported_CJK_languages[where - supported_CJK_encodings];
4963 used[cjk] += text.length();
4965 LangMap::const_iterator use = used.begin();
4966 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
4967 if (it->second > use->second)