2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subsecref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "subsec", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
187 /// LaTeX names for quotes
188 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
189 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
190 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
191 "guilsinglleft", "frq", "guilsinglright", 0};
193 /// the same as known_quotes with .lyx names
194 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
195 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
196 "gld", "grd", "gls", "ers", "fls",
197 "fls", "frs", "frs", 0};
199 /// LaTeX names for font sizes
200 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
201 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
203 /// the same as known_sizes with .lyx names
204 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
205 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
207 /// LaTeX 2.09 names for font families
208 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
210 /// LaTeX names for font families
211 char const * const known_font_families[] = { "rmfamily", "sffamily",
214 /// LaTeX names for font family changing commands
215 char const * const known_text_font_families[] = { "textrm", "textsf",
218 /// The same as known_old_font_families, known_font_families and
219 /// known_text_font_families with .lyx names
220 char const * const known_coded_font_families[] = { "roman", "sans",
223 /// LaTeX 2.09 names for font series
224 char const * const known_old_font_series[] = { "bf", 0};
226 /// LaTeX names for font series
227 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
229 /// LaTeX names for font series changing commands
230 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
232 /// The same as known_old_font_series, known_font_series and
233 /// known_text_font_series with .lyx names
234 char const * const known_coded_font_series[] = { "bold", "medium", 0};
236 /// LaTeX 2.09 names for font shapes
237 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
239 /// LaTeX names for font shapes
240 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
243 /// LaTeX names for font shape changing commands
244 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
247 /// The same as known_old_font_shapes, known_font_shapes and
248 /// known_text_font_shapes with .lyx names
249 char const * const known_coded_font_shapes[] = { "italic", "slanted",
250 "smallcaps", "up", 0};
252 /// Known special characters which need skip_spaces_braces() afterwards
253 char const * const known_special_chars[] = {"ldots",
254 "lyxarrow", "textcompwordmark",
255 "slash", "textasciitilde", "textasciicircum", "textbackslash",
256 "LyX", "TeX", "LaTeXe",
259 /// special characters from known_special_chars which may have a \\protect before
260 char const * const known_special_protect_chars[] = {"LyX", "TeX",
261 "LaTeXe", "LaTeX", 0};
263 /// the same as known_special_chars with .lyx names
264 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
265 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
266 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
267 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
268 "\\SpecialChar LaTeX\n", 0};
271 * Graphics file extensions known by the dvips driver of the graphics package.
272 * These extensions are used to complete the filename of an included
273 * graphics file if it does not contain an extension.
274 * The order must be the same that latex uses to find a file, because we
275 * will use the first extension that matches.
276 * This is only an approximation for the common cases. If we would want to
277 * do it right in all cases, we would need to know which graphics driver is
278 * used and know the extensions of every driver of the graphics package.
280 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
281 "ps.gz", "eps.Z", "ps.Z", 0};
284 * Graphics file extensions known by the pdftex driver of the graphics package.
285 * \sa known_dvips_graphics_formats
287 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
291 * Known file extensions for TeX files as used by \\include.
293 char const * const known_tex_extensions[] = {"tex", 0};
295 /// spaces known by InsetSpace
296 char const * const known_spaces[] = { " ", "space", ",",
297 "thinspace", "quad", "qquad", "enspace", "enskip",
298 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
299 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
300 "upbracefill", "downbracefill", 0};
302 /// the same as known_spaces with .lyx names
303 char const * const known_coded_spaces[] = { "space{}", "space{}",
304 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
305 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
306 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
307 "upbracefill{}", "downbracefill{}", 0};
309 /// known TIPA combining diacritical marks
310 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
311 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
312 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
313 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
314 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
315 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
316 "textsubring", "textsubbar", 0};
318 /// TIPA tones that need special handling
319 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
321 // string to store the float type to be able to determine the type of subfloats
322 string float_type = "";
324 // string to store the float status of minted listings
325 string minted_float = "";
327 // whether a caption has been parsed for a floating minted listing
328 bool minted_float_has_caption = false;
330 // The caption for non-floating minted listings
331 string minted_nonfloat_caption = "";
334 /// splits "x=z, y=b" into a map and an ordered keyword vector
335 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
340 keys.resize(v.size());
341 for (size_t i = 0; i < v.size(); ++i) {
342 size_t const pos = v[i].find('=');
343 string const index = trimSpaceAndEol(v[i].substr(0, pos));
344 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
352 * Split a LaTeX length into value and unit.
353 * The latter can be a real unit like "pt", or a latex length variable
354 * like "\textwidth". The unit may contain additional stuff like glue
355 * lengths, but we don't care, because such lengths are ERT anyway.
356 * \returns true if \p value and \p unit are valid.
358 bool splitLatexLength(string const & len, string & value, string & unit)
362 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
363 //'4,5' is a valid LaTeX length number. Change it to '4.5'
364 string const length = subst(len, ',', '.');
365 if (i == string::npos)
368 if (len[0] == '\\') {
369 // We had something like \textwidth without a factor
375 value = trimSpaceAndEol(string(length, 0, i));
379 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
380 if (contains(len, '\\'))
381 unit = trimSpaceAndEol(string(len, i));
383 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
388 /// A simple function to translate a latex length to something LyX can
389 /// understand. Not perfect, but rather best-effort.
390 bool translate_len(string const & length, string & valstring, string & unit)
392 if (!splitLatexLength(length, valstring, unit))
394 // LyX uses percent values
396 istringstream iss(valstring);
401 string const percentval = oss.str();
403 if (unit.empty() || unit[0] != '\\')
405 string::size_type const i = unit.find(' ');
406 string const endlen = (i == string::npos) ? string() : string(unit, i);
407 if (unit == "\\textwidth") {
408 valstring = percentval;
409 unit = "text%" + endlen;
410 } else if (unit == "\\columnwidth") {
411 valstring = percentval;
412 unit = "col%" + endlen;
413 } else if (unit == "\\paperwidth") {
414 valstring = percentval;
415 unit = "page%" + endlen;
416 } else if (unit == "\\linewidth") {
417 valstring = percentval;
418 unit = "line%" + endlen;
419 } else if (unit == "\\paperheight") {
420 valstring = percentval;
421 unit = "pheight%" + endlen;
422 } else if (unit == "\\textheight") {
423 valstring = percentval;
424 unit = "theight%" + endlen;
425 } else if (unit == "\\baselineskip") {
426 valstring = percentval;
427 unit = "baselineskip%" + endlen;
435 string translate_len(string const & length)
439 if (translate_len(length, value, unit))
441 // If the input is invalid, return what we have.
449 * Translates a LaTeX length into \p value, \p unit and
450 * \p special parts suitable for a box inset.
451 * The difference from translate_len() is that a box inset knows about
452 * some special "units" that are stored in \p special.
454 void translate_box_len(string const & length, string & value, string & unit, string & special)
456 if (translate_len(length, value, unit)) {
457 if (unit == "\\height" || unit == "\\depth" ||
458 unit == "\\totalheight" || unit == "\\width") {
459 special = unit.substr(1);
460 // The unit is not used, but LyX requires a dummy setting
473 * Find a file with basename \p name in path \p path and an extension
476 string find_file(string const & name, string const & path,
477 char const * const * extensions)
479 for (char const * const * what = extensions; *what; ++what) {
480 string const trial = addExtension(name, *what);
481 if (makeAbsPath(trial, path).exists())
488 void begin_inset(ostream & os, string const & name)
490 os << "\n\\begin_inset " << name;
494 void begin_command_inset(ostream & os, string const & name,
495 string const & latexname)
497 begin_inset(os, "CommandInset ");
498 os << name << "\nLatexCommand " << latexname << '\n';
502 void end_inset(ostream & os)
504 os << "\n\\end_inset\n\n";
508 bool skip_braces(Parser & p)
510 if (p.next_token().cat() != catBegin)
513 if (p.next_token().cat() == catEnd) {
522 /// replace LaTeX commands in \p s from the unicodesymbols file with their
524 docstring convert_unicodesymbols(docstring s)
527 for (size_t i = 0; i < s.size();) {
536 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
537 Encodings::TEXT_CMD, termination, rem, &req));
538 set<string>::const_iterator it = req.begin();
539 set<string>::const_iterator en = req.end();
540 for (; it != en; ++it)
541 preamble.registerAutomaticallyLoadedPackage(*it);
544 if (s.empty() || s[0] != '\\')
553 /// try to convert \p s to a valid InsetCommand argument
554 string convert_command_inset_arg(string s)
557 // since we don't know the input encoding we can't use from_utf8
558 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
559 // LyX cannot handle newlines in a latex command
560 return subst(s, "\n", " ");
564 void output_ert(ostream & os, string const & s, Context & context)
566 context.check_layout(os);
567 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
569 os << "\n\\backslash\n";
570 else if (*it == '\n') {
571 context.new_paragraph(os);
572 context.check_layout(os);
576 context.check_end_layout(os);
580 void output_ert_inset(ostream & os, string const & s, Context & context)
582 // We must have a valid layout before outputting the ERT inset.
583 context.check_layout(os);
584 Context newcontext(true, context.textclass);
585 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
586 if (layout.forcePlainLayout())
587 newcontext.layout = &context.textclass.plainLayout();
588 begin_inset(os, "ERT");
589 os << "\nstatus collapsed\n";
590 output_ert(os, s, newcontext);
595 void output_comment(Parser & p, ostream & os, string const & s,
598 if (p.next_token().cat() == catNewline)
599 output_ert_inset(os, '%' + s, context);
601 output_ert_inset(os, '%' + s + '\n', context);
605 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
607 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
610 if (checkModule(name, command))
611 return findLayoutWithoutModule(textclass, name, command);
616 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
618 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
621 if (checkModule(name, command))
622 return findInsetLayoutWithoutModule(textclass, name, command);
627 void eat_whitespace(Parser &, ostream &, Context &, bool);
631 * Skips whitespace and braces.
632 * This should be called after a command has been parsed that is not put into
633 * ERT, and where LyX adds "{}" if needed.
635 void skip_spaces_braces(Parser & p, bool keepws = false)
637 /* The following four examples produce the same typeset output and
638 should be handled by this function:
646 // Unfortunately we need to skip comments, too.
647 // We can't use eat_whitespace since writing them after the {}
648 // results in different output in some cases.
649 bool const skipped_spaces = p.skip_spaces(true);
650 bool const skipped_braces = skip_braces(p);
651 if (keepws && skipped_spaces && !skipped_braces)
652 // put back the space (it is better handled by check_space)
653 p.unskip_spaces(true);
657 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
658 Context & context, Layout::LaTeXArgMap const & latexargs)
661 context.check_layout(os);
666 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
667 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
668 for (; lait != laend; ++lait) {
670 eat_whitespace(p, os, context, false);
671 if (lait->second.mandatory) {
672 if (p.next_token().cat() != catBegin)
674 p.get_token(); // eat '{'
676 context.check_layout(os);
679 begin_inset(os, "Argument ");
682 os << i << "\nstatus collapsed\n\n";
683 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
686 if (p.next_token().cat() == catEscape ||
687 p.next_token().character() != '[')
689 p.get_token(); // eat '['
691 context.check_layout(os);
694 begin_inset(os, "Argument ");
697 os << i << "\nstatus collapsed\n\n";
698 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
701 eat_whitespace(p, os, context, false);
706 void output_command_layout(ostream & os, Parser & p, bool outer,
707 Context & parent_context,
708 Layout const * newlayout)
710 TeXFont const oldFont = parent_context.font;
711 // save the current font size
712 string const size = oldFont.size;
713 // reset the font size to default, because the font size switches
714 // don't affect section headings and the like
715 parent_context.font.size = Context::normalfont.size;
716 // we only need to write the font change if we have an open layout
717 if (!parent_context.atParagraphStart())
718 output_font_change(os, oldFont, parent_context.font);
719 parent_context.check_end_layout(os);
720 Context context(true, parent_context.textclass, newlayout,
721 parent_context.layout, parent_context.font);
722 if (parent_context.deeper_paragraph) {
723 // We are beginning a nested environment after a
724 // deeper paragraph inside the outer list environment.
725 // Therefore we don't need to output a "begin deeper".
726 context.need_end_deeper = true;
728 context.check_deeper(os);
729 output_arguments(os, p, outer, true, false, context,
730 context.layout->latexargs());
731 parse_text(p, os, FLAG_ITEM, outer, context);
732 output_arguments(os, p, outer, false, true, context,
733 context.layout->postcommandargs());
734 context.check_end_layout(os);
735 if (parent_context.deeper_paragraph) {
736 // We must suppress the "end deeper" because we
737 // suppressed the "begin deeper" above.
738 context.need_end_deeper = false;
740 context.check_end_deeper(os);
741 // We don't need really a new paragraph, but
742 // we must make sure that the next item gets a \begin_layout.
743 parent_context.new_paragraph(os);
744 // Set the font size to the original value. No need to output it here
745 // (Context::begin_layout() will do that if needed)
746 parent_context.font.size = size;
751 * Output a space if necessary.
752 * This function gets called for every whitespace token.
754 * We have three cases here:
755 * 1. A space must be suppressed. Example: The lyxcode case below
756 * 2. A space may be suppressed. Example: Spaces before "\par"
757 * 3. A space must not be suppressed. Example: A space between two words
759 * We currently handle only 1. and 3 and from 2. only the case of
760 * spaces before newlines as a side effect.
762 * 2. could be used to suppress as many spaces as possible. This has two effects:
763 * - Reimporting LyX generated LaTeX files changes almost no whitespace
764 * - Superflous whitespace from non LyX generated LaTeX files is removed.
765 * The drawback is that the logic inside the function becomes
766 * complicated, and that is the reason why it is not implemented.
768 void check_space(Parser & p, ostream & os, Context & context)
770 Token const next = p.next_token();
771 Token const curr = p.curr_token();
772 // A space before a single newline and vice versa must be ignored
773 // LyX emits a newline before \end{lyxcode}.
774 // This newline must be ignored,
775 // otherwise LyX will add an additional protected space.
776 if (next.cat() == catSpace ||
777 next.cat() == catNewline ||
778 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
781 context.check_layout(os);
787 * Parse all arguments of \p command
789 void parse_arguments(string const & command,
790 vector<ArgumentType> const & template_arguments,
791 Parser & p, ostream & os, bool outer, Context & context)
793 string ert = command;
794 size_t no_arguments = template_arguments.size();
795 for (size_t i = 0; i < no_arguments; ++i) {
796 switch (template_arguments[i]) {
799 // This argument contains regular LaTeX
800 output_ert_inset(os, ert + '{', context);
801 eat_whitespace(p, os, context, false);
802 if (template_arguments[i] == required)
803 parse_text(p, os, FLAG_ITEM, outer, context);
805 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
809 // This argument consists only of a single item.
810 // The presence of '{' or not must be preserved.
812 if (p.next_token().cat() == catBegin)
813 ert += '{' + p.verbatim_item() + '}';
815 ert += p.verbatim_item();
819 // This argument may contain special characters
820 ert += '{' + p.verbatim_item() + '}';
824 // true because we must not eat whitespace
825 // if an optional arg follows we must not strip the
826 // brackets from this one
827 if (i < no_arguments - 1 &&
828 template_arguments[i+1] == optional)
829 ert += p.getFullOpt(true);
831 ert += p.getOpt(true);
835 output_ert_inset(os, ert, context);
840 * Check whether \p command is a known command. If yes,
841 * handle the command with all arguments.
842 * \return true if the command was parsed, false otherwise.
844 bool parse_command(string const & command, Parser & p, ostream & os,
845 bool outer, Context & context)
847 if (known_commands.find(command) != known_commands.end()) {
848 parse_arguments(command, known_commands[command], p, os,
856 /// Parses a minipage or parbox
857 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
858 unsigned inner_flags, bool outer, Context & parent_context,
859 string const & outer_type, string const & special,
860 string inner_type, string const & frame_color,
861 string const & background_color)
865 string hor_pos = "l";
866 // We need to set the height to the LaTeX default of 1\\totalheight
867 // for the case when no height argument is given
868 string height_value = "1";
869 string height_unit = "in";
870 string height_special = "totalheight";
875 string width_special = "none";
876 string thickness = "0.4pt";
877 if (!fboxrule.empty())
878 thickness = fboxrule;
882 if (!fboxsep.empty())
883 separation = fboxsep;
887 if (!shadow_size.empty())
888 shadowsize = shadow_size;
891 string framecolor = "black";
892 string backgroundcolor = "none";
893 if (!frame_color.empty())
894 framecolor = frame_color;
895 if (!background_color.empty())
896 backgroundcolor = background_color;
897 // if there is a color box around the \begin statements have not yet been parsed
899 if (!frame_color.empty() || !background_color.empty()) {
900 eat_whitespace(p, os, parent_context, false);
901 p.get_token().asInput(); // the '{'
903 if (p.next_token().asInput() == "\\begin") {
904 p.get_token().asInput();
906 inner_type = "minipage";
907 inner_flags = FLAG_END;
908 active_environments.push_back("minipage");
911 else if (p.next_token().asInput() == "\\parbox") {
912 p.get_token().asInput();
913 inner_type = "parbox";
914 inner_flags = FLAG_ITEM;
917 else if (p.next_token().asInput() == "\\makebox") {
918 p.get_token().asInput();
919 inner_type = "makebox";
920 inner_flags = FLAG_ITEM;
922 // in case there is just \colorbox{color}{text}
925 inner_type = "makebox";
926 inner_flags = FLAG_BRACE_LAST;
931 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
933 if (!inner_type.empty() && p.hasOpt()) {
934 if (inner_type != "makebox")
935 position = p.getArg('[', ']');
937 latex_width = p.getArg('[', ']');
938 translate_box_len(latex_width, width_value, width_unit, width_special);
941 if (position != "t" && position != "c" && position != "b") {
942 cerr << "invalid position " << position << " for "
943 << inner_type << endl;
947 if (inner_type != "makebox") {
948 latex_height = p.getArg('[', ']');
949 translate_box_len(latex_height, height_value, height_unit, height_special);
951 string const opt = p.getArg('[', ']');
954 if (hor_pos != "l" && hor_pos != "c" &&
955 hor_pos != "r" && hor_pos != "s") {
956 cerr << "invalid hor_pos " << hor_pos
957 << " for " << inner_type << endl;
964 inner_pos = p.getArg('[', ']');
965 if (inner_pos != "c" && inner_pos != "t" &&
966 inner_pos != "b" && inner_pos != "s") {
967 cerr << "invalid inner_pos "
968 << inner_pos << " for "
969 << inner_type << endl;
970 inner_pos = position;
974 if (inner_type == "makebox")
978 if (inner_type.empty()) {
979 if (special.empty() && outer_type != "framebox")
980 latex_width = "1\\columnwidth";
983 latex_width = p2.getArg('[', ']');
984 string const opt = p2.getArg('[', ']');
987 if (hor_pos != "l" && hor_pos != "c" &&
988 hor_pos != "r" && hor_pos != "s") {
989 cerr << "invalid hor_pos " << hor_pos
990 << " for " << outer_type << endl;
994 if (outer_type == "framebox")
998 } else if (inner_type != "makebox")
999 latex_width = p.verbatim_item();
1000 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1001 // as this is LyX's standard for such cases (except for makebox)
1002 // \framebox is more special and handled below
1003 if (latex_width.empty() && inner_type != "makebox"
1004 && outer_type != "framebox")
1005 latex_width = "1\\columnwidth";
1007 translate_len(latex_width, width_value, width_unit);
1009 bool shadedparbox = false;
1010 if (inner_type == "shaded") {
1011 eat_whitespace(p, os, parent_context, false);
1012 if (outer_type == "parbox") {
1014 if (p.next_token().cat() == catBegin)
1016 eat_whitespace(p, os, parent_context, false);
1017 shadedparbox = true;
1022 // If we already read the inner box we have to push the inner env
1023 if (!outer_type.empty() && !inner_type.empty() &&
1024 (inner_flags & FLAG_END))
1025 active_environments.push_back(inner_type);
1026 bool use_ert = false;
1027 if (!outer_type.empty() && !inner_type.empty()) {
1028 // Look whether there is some content after the end of the
1029 // inner box, but before the end of the outer box.
1030 // If yes, we need to output ERT.
1032 if (inner_flags & FLAG_END)
1033 p.ertEnvironment(inner_type);
1036 p.skip_spaces(true);
1037 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1038 if ((outer_env && p.next_token().asInput() != "\\end") ||
1039 (!outer_env && p.next_token().cat() != catEnd)) {
1040 // something is between the end of the inner box and
1041 // the end of the outer box, so we need to use ERT.
1049 if (!outer_type.empty()) {
1050 if (outer_flags & FLAG_END)
1051 ss << "\\begin{" << outer_type << '}';
1053 ss << '\\' << outer_type << '{';
1054 if (!special.empty())
1058 if (!inner_type.empty()) {
1059 if (inner_type != "shaded") {
1060 if (inner_flags & FLAG_END)
1061 ss << "\\begin{" << inner_type << '}';
1063 ss << '\\' << inner_type;
1065 if (!position.empty())
1066 ss << '[' << position << ']';
1067 if (!latex_height.empty())
1068 ss << '[' << latex_height << ']';
1069 if (!inner_pos.empty())
1070 ss << '[' << inner_pos << ']';
1071 ss << '{' << latex_width << '}';
1072 if (!(inner_flags & FLAG_END))
1075 if (inner_type == "shaded")
1076 ss << "\\begin{shaded}";
1077 output_ert_inset(os, ss.str(), parent_context);
1078 if (!inner_type.empty()) {
1079 parse_text(p, os, inner_flags, outer, parent_context);
1080 if (inner_flags & FLAG_END)
1081 output_ert_inset(os, "\\end{" + inner_type + '}',
1084 output_ert_inset(os, "}", parent_context);
1086 if (!outer_type.empty()) {
1087 // If we already read the inner box we have to pop
1089 if (!inner_type.empty() && (inner_flags & FLAG_END))
1090 active_environments.pop_back();
1092 // Ensure that the end of the outer box is parsed correctly:
1093 // The opening brace has been eaten by parse_outer_box()
1094 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1095 outer_flags &= ~FLAG_ITEM;
1096 outer_flags |= FLAG_BRACE_LAST;
1098 parse_text(p, os, outer_flags, outer, parent_context);
1099 if (outer_flags & FLAG_END)
1100 output_ert_inset(os, "\\end{" + outer_type + '}',
1103 output_ert_inset(os, "}", parent_context);
1106 // LyX does not like empty positions, so we have
1107 // to set them to the LaTeX default values here.
1108 if (position.empty())
1110 if (inner_pos.empty())
1111 inner_pos = position;
1112 parent_context.check_layout(os);
1113 begin_inset(os, "Box ");
1114 if (outer_type == "framed")
1116 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1118 else if (outer_type == "shadowbox")
1119 os << "Shadowbox\n";
1120 else if ((outer_type == "shaded" && inner_type.empty()) ||
1121 (outer_type == "minipage" && inner_type == "shaded") ||
1122 (outer_type == "parbox" && inner_type == "shaded")) {
1124 preamble.registerAutomaticallyLoadedPackage("color");
1125 } else if (outer_type == "doublebox")
1126 os << "Doublebox\n";
1127 else if (outer_type.empty() || outer_type == "mbox")
1128 os << "Frameless\n";
1130 os << outer_type << '\n';
1131 os << "position \"" << position << "\"\n";
1132 os << "hor_pos \"" << hor_pos << "\"\n";
1133 if (outer_type == "mbox")
1134 os << "has_inner_box 1\n";
1135 else if (!frame_color.empty() && inner_type == "makebox")
1136 os << "has_inner_box 0\n";
1138 os << "has_inner_box " << !inner_type.empty() << "\n";
1139 os << "inner_pos \"" << inner_pos << "\"\n";
1140 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1142 if (outer_type == "mbox")
1143 os << "use_makebox 1\n";
1144 else if (!frame_color.empty())
1145 os << "use_makebox 0\n";
1147 os << "use_makebox " << (inner_type == "makebox") << '\n';
1148 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1149 os << "width \"\"\n";
1150 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1151 else if (contains(width_unit, '\\'))
1152 os << "width \"" << width_value << "in" << "\"\n";
1154 os << "width \"" << width_value << width_unit << "\"\n";
1155 if (contains(width_unit, '\\')) {
1156 width_unit.erase (0,1); // remove the leading '\'
1157 os << "special \"" << width_unit << "\"\n";
1159 os << "special \"" << width_special << "\"\n";
1160 if (contains(height_unit, '\\'))
1161 os << "height \"" << height_value << "in" << "\"\n";
1163 os << "height \"" << height_value << height_unit << "\"\n";
1164 os << "height_special \"" << height_special << "\"\n";
1165 os << "thickness \"" << thickness << "\"\n";
1166 os << "separation \"" << separation << "\"\n";
1167 os << "shadowsize \"" << shadowsize << "\"\n";
1168 os << "framecolor \"" << framecolor << "\"\n";
1169 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1170 os << "status open\n\n";
1172 // Unfortunately we can't use parse_text_in_inset:
1173 // InsetBox::forcePlainLayout() is hard coded and does not
1174 // use the inset layout. Apart from that do we call parse_text
1175 // up to two times, but need only one check_end_layout.
1176 bool const forcePlainLayout =
1177 (!inner_type.empty() || inner_type == "makebox") &&
1178 outer_type != "shaded" && outer_type != "framed";
1179 Context context(true, parent_context.textclass);
1180 if (forcePlainLayout)
1181 context.layout = &context.textclass.plainLayout();
1183 context.font = parent_context.font;
1185 // If we have no inner box the contents will be read with the outer box
1186 if (!inner_type.empty())
1187 parse_text(p, os, inner_flags, outer, context);
1189 // Ensure that the end of the outer box is parsed correctly:
1190 // The opening brace has been eaten by parse_outer_box()
1191 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1192 outer_flags &= ~FLAG_ITEM;
1193 outer_flags |= FLAG_BRACE_LAST;
1196 // Find end of outer box, output contents if inner_type is
1197 // empty and output possible comments
1198 if (!outer_type.empty()) {
1199 // If we already read the inner box we have to pop
1201 if (!inner_type.empty() && (inner_flags & FLAG_END))
1202 active_environments.pop_back();
1203 // This does not output anything but comments if
1204 // inner_type is not empty (see use_ert)
1205 parse_text(p, os, outer_flags, outer, context);
1208 context.check_end_layout(os);
1210 #ifdef PRESERVE_LAYOUT
1211 // LyX puts a % after the end of the minipage
1212 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1214 //output_comment(p, os, "dummy", parent_context);
1217 parent_context.new_paragraph(os);
1219 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1220 //output_comment(p, os, "dummy", parent_context);
1223 // We add a protected space if something real follows
1224 if (p.good() && p.next_token().cat() != catComment) {
1225 begin_inset(os, "space ~\n");
1231 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1232 active_environments.pop_back();
1233 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1234 // in this case we have to eat the the closing brace of the color box
1235 p.get_token().asInput(); // the '}'
1237 if (p.next_token().asInput() == "}") {
1238 // in this case we assume that the closing brace is from the box settings
1239 // therefore reset these values for the next box
1245 // all boxes except of Frameless and Shaded require calc
1246 if (!(outer_type.empty() || outer_type == "mbox") &&
1247 !((outer_type == "shaded" && inner_type.empty()) ||
1248 (outer_type == "minipage" && inner_type == "shaded") ||
1249 (outer_type == "parbox" && inner_type == "shaded")))
1250 preamble.registerAutomaticallyLoadedPackage("calc");
1254 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1255 Context & parent_context, string const & outer_type,
1256 string const & special)
1258 eat_whitespace(p, os, parent_context, false);
1259 if (flags & FLAG_ITEM) {
1261 if (p.next_token().cat() == catBegin)
1264 cerr << "Warning: Ignoring missing '{' after \\"
1265 << outer_type << '.' << endl;
1266 eat_whitespace(p, os, parent_context, false);
1269 unsigned int inner_flags = 0;
1271 if (outer_type == "minipage" || outer_type == "parbox") {
1272 p.skip_spaces(true);
1273 while (p.hasOpt()) {
1275 p.skip_spaces(true);
1278 p.skip_spaces(true);
1279 if (outer_type == "parbox") {
1281 if (p.next_token().cat() == catBegin)
1283 p.skip_spaces(true);
1286 if (outer_type == "shaded" || outer_type == "mbox") {
1287 // These boxes never have an inner box
1289 } else if (p.next_token().asInput() == "\\parbox") {
1290 inner = p.get_token().cs();
1291 inner_flags = FLAG_ITEM;
1292 } else if (p.next_token().asInput() == "\\begin") {
1293 // Is this a minipage or shaded box?
1296 inner = p.getArg('{', '}');
1298 if (inner == "minipage" || inner == "shaded")
1299 inner_flags = FLAG_END;
1304 if (inner_flags == FLAG_END) {
1305 if (inner != "shaded")
1309 eat_whitespace(p, os, parent_context, false);
1311 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1312 outer_type, special, inner, "", "");
1314 if (inner_flags == FLAG_ITEM) {
1316 eat_whitespace(p, os, parent_context, false);
1318 parse_box(p, os, flags, inner_flags, outer, parent_context,
1319 outer_type, special, inner, "", "");
1324 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1325 bool in_line, bool use_minted)
1327 parent_context.check_layout(os);
1328 begin_inset(os, "listings\n");
1329 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1331 while ((i = arg.find(", ")) != string::npos
1332 || (i = arg.find(",\t")) != string::npos)
1333 arg.erase(i + 1, 1);
1336 string const language = p.getArg('{', '}');
1337 p.skip_spaces(true);
1338 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1339 if (!minted_float.empty()) {
1340 arg += string(arg.empty() ? "" : ",") + minted_float;
1341 minted_nonfloat_caption.clear();
1345 os << "lstparams " << '"' << arg << '"' << '\n';
1346 if (arg.find("\\color") != string::npos)
1347 preamble.registerAutomaticallyLoadedPackage("color");
1350 os << "inline true\n";
1352 os << "inline false\n";
1353 os << "status collapsed\n";
1354 Context context(true, parent_context.textclass);
1355 context.layout = &parent_context.textclass.plainLayout();
1356 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1357 minted_nonfloat_caption.erase(0,3);
1358 os << "\n\\begin_layout Plain Layout\n";
1359 begin_inset(os, "Caption Standard\n");
1360 Context newcontext(true, context.textclass,
1361 context.layout, 0, context.font);
1362 newcontext.check_layout(os);
1363 os << minted_nonfloat_caption << "\n";
1364 newcontext.check_end_layout(os);
1366 os << "\n\\end_layout\n";
1367 minted_nonfloat_caption.clear();
1371 // set catcodes to verbatim early, just in case.
1372 p.setCatcodes(VERBATIM_CATCODES);
1373 string delim = p.get_token().asInput();
1374 //FIXME: handler error condition
1375 s = p.verbatimStuff(delim).second;
1376 // context.new_paragraph(os);
1377 } else if (use_minted) {
1378 s = p.verbatimEnvironment("minted");
1380 s = p.verbatimEnvironment("lstlisting");
1382 output_ert(os, s, context);
1383 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1384 minted_nonfloat_caption.erase(0,3);
1385 os << "\n\\begin_layout Plain Layout\n";
1386 begin_inset(os, "Caption Standard\n");
1387 Context newcontext(true, context.textclass,
1388 context.layout, 0, context.font);
1389 newcontext.check_layout(os);
1390 os << minted_nonfloat_caption << "\n";
1391 newcontext.check_end_layout(os);
1393 os << "\n\\end_layout\n";
1394 minted_nonfloat_caption.clear();
1396 // Don't close the inset here for floating minted listings.
1397 // It will be closed at the end of the listing environment.
1398 if (!use_minted || minted_float.empty())
1401 eat_whitespace(p, os, parent_context, true);
1402 Token t = p.get_token();
1403 if (t.asInput() != "\\end") {
1404 // If anything follows, collect it into a caption.
1405 minted_float_has_caption = true;
1406 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1407 begin_inset(os, "Caption Standard\n");
1408 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1415 /// parse an unknown environment
1416 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1417 unsigned flags, bool outer,
1418 Context & parent_context)
1420 if (name == "tabbing")
1421 // We need to remember that we have to handle '\=' specially
1422 flags |= FLAG_TABBING;
1424 // We need to translate font changes and paragraphs inside the
1425 // environment to ERT if we have a non standard font.
1426 // Otherwise things like
1427 // \large\begin{foo}\huge bar\end{foo}
1429 bool const specialfont =
1430 (parent_context.font != parent_context.normalfont);
1431 bool const new_layout_allowed = parent_context.new_layout_allowed;
1433 parent_context.new_layout_allowed = false;
1434 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1435 parse_text_snippet(p, os, flags, outer, parent_context);
1436 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1438 parent_context.new_layout_allowed = new_layout_allowed;
1442 void parse_environment(Parser & p, ostream & os, bool outer,
1443 string & last_env, Context & parent_context)
1445 Layout const * newlayout;
1446 InsetLayout const * newinsetlayout = 0;
1447 string const name = p.getArg('{', '}');
1448 const bool is_starred = suffixIs(name, '*');
1449 string const unstarred_name = rtrim(name, "*");
1450 active_environments.push_back(name);
1452 if (is_math_env(name)) {
1453 parent_context.check_layout(os);
1454 begin_inset(os, "Formula ");
1455 os << "\\begin{" << name << "}";
1456 parse_math(p, os, FLAG_END, MATH_MODE);
1457 os << "\\end{" << name << "}";
1459 if (is_display_math_env(name)) {
1460 // Prevent the conversion of a line break to a space
1461 // (bug 7668). This does not change the output, but
1462 // looks ugly in LyX.
1463 eat_whitespace(p, os, parent_context, false);
1467 else if (is_known(name, preamble.polyglossia_languages)) {
1468 // We must begin a new paragraph if not already done
1469 if (! parent_context.atParagraphStart()) {
1470 parent_context.check_end_layout(os);
1471 parent_context.new_paragraph(os);
1473 // save the language in the context so that it is
1474 // handled by parse_text
1475 parent_context.font.language = preamble.polyglossia2lyx(name);
1476 parse_text(p, os, FLAG_END, outer, parent_context);
1477 // Just in case the environment is empty
1478 parent_context.extra_stuff.erase();
1479 // We must begin a new paragraph to reset the language
1480 parent_context.new_paragraph(os);
1484 else if (unstarred_name == "tabular" || name == "longtable") {
1485 eat_whitespace(p, os, parent_context, false);
1486 string width = "0pt";
1487 if (name == "tabular*") {
1488 width = lyx::translate_len(p.getArg('{', '}'));
1489 eat_whitespace(p, os, parent_context, false);
1491 parent_context.check_layout(os);
1492 begin_inset(os, "Tabular ");
1493 handle_tabular(p, os, name, width, parent_context);
1498 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1499 eat_whitespace(p, os, parent_context, false);
1500 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1501 eat_whitespace(p, os, parent_context, false);
1502 parent_context.check_layout(os);
1503 begin_inset(os, "Float " + unstarred_name + "\n");
1504 // store the float type for subfloats
1505 // subfloats only work with figures and tables
1506 if (unstarred_name == "figure")
1507 float_type = unstarred_name;
1508 else if (unstarred_name == "table")
1509 float_type = unstarred_name;
1513 os << "placement " << opt << '\n';
1514 if (contains(opt, "H"))
1515 preamble.registerAutomaticallyLoadedPackage("float");
1517 Floating const & fl = parent_context.textclass.floats()
1518 .getType(unstarred_name);
1519 if (!fl.floattype().empty() && fl.usesFloatPkg())
1520 preamble.registerAutomaticallyLoadedPackage("float");
1523 os << "wide " << convert<string>(is_starred)
1524 << "\nsideways false"
1525 << "\nstatus open\n\n";
1526 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1528 // We don't need really a new paragraph, but
1529 // we must make sure that the next item gets a \begin_layout.
1530 parent_context.new_paragraph(os);
1532 // the float is parsed thus delete the type
1536 else if (unstarred_name == "sidewaysfigure"
1537 || unstarred_name == "sidewaystable"
1538 || unstarred_name == "sidewaysalgorithm") {
1539 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1540 eat_whitespace(p, os, parent_context, false);
1541 parent_context.check_layout(os);
1542 if (unstarred_name == "sidewaysfigure")
1543 begin_inset(os, "Float figure\n");
1544 else if (unstarred_name == "sidewaystable")
1545 begin_inset(os, "Float table\n");
1546 else if (unstarred_name == "sidewaysalgorithm")
1547 begin_inset(os, "Float algorithm\n");
1549 os << "placement " << opt << '\n';
1550 if (contains(opt, "H"))
1551 preamble.registerAutomaticallyLoadedPackage("float");
1552 os << "wide " << convert<string>(is_starred)
1553 << "\nsideways true"
1554 << "\nstatus open\n\n";
1555 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1557 // We don't need really a new paragraph, but
1558 // we must make sure that the next item gets a \begin_layout.
1559 parent_context.new_paragraph(os);
1561 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1564 else if (name == "wrapfigure" || name == "wraptable") {
1565 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1566 eat_whitespace(p, os, parent_context, false);
1567 parent_context.check_layout(os);
1570 string overhang = "0col%";
1573 lines = p.getArg('[', ']');
1574 string const placement = p.getArg('{', '}');
1576 overhang = p.getArg('[', ']');
1577 string const width = p.getArg('{', '}');
1579 if (name == "wrapfigure")
1580 begin_inset(os, "Wrap figure\n");
1582 begin_inset(os, "Wrap table\n");
1583 os << "lines " << lines
1584 << "\nplacement " << placement
1585 << "\noverhang " << lyx::translate_len(overhang)
1586 << "\nwidth " << lyx::translate_len(width)
1587 << "\nstatus open\n\n";
1588 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1590 // We don't need really a new paragraph, but
1591 // we must make sure that the next item gets a \begin_layout.
1592 parent_context.new_paragraph(os);
1594 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1597 else if (name == "minipage") {
1598 eat_whitespace(p, os, parent_context, false);
1599 // Test whether this is an outer box of a shaded box
1601 // swallow arguments
1602 while (p.hasOpt()) {
1604 p.skip_spaces(true);
1607 p.skip_spaces(true);
1608 Token t = p.get_token();
1609 bool shaded = false;
1610 if (t.asInput() == "\\begin") {
1611 p.skip_spaces(true);
1612 if (p.getArg('{', '}') == "shaded")
1617 parse_outer_box(p, os, FLAG_END, outer,
1618 parent_context, name, "shaded");
1620 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1621 "", "", name, "", "");
1625 else if (name == "comment") {
1626 eat_whitespace(p, os, parent_context, false);
1627 parent_context.check_layout(os);
1628 begin_inset(os, "Note Comment\n");
1629 os << "status open\n";
1630 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1633 skip_braces(p); // eat {} that might by set by LyX behind comments
1634 preamble.registerAutomaticallyLoadedPackage("verbatim");
1637 else if (unstarred_name == "verbatim") {
1638 // FIXME: this should go in the generic code that
1639 // handles environments defined in layout file that
1640 // have "PassThru 1". However, the code over there is
1641 // already too complicated for my taste.
1642 string const ascii_name =
1643 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1644 parent_context.new_paragraph(os);
1645 Context context(true, parent_context.textclass,
1646 &parent_context.textclass[from_ascii(ascii_name)]);
1647 string s = p.verbatimEnvironment(name);
1648 output_ert(os, s, context);
1652 else if (name == "IPA") {
1653 eat_whitespace(p, os, parent_context, false);
1654 parent_context.check_layout(os);
1655 begin_inset(os, "IPA\n");
1656 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1659 preamble.registerAutomaticallyLoadedPackage("tipa");
1660 preamble.registerAutomaticallyLoadedPackage("tipx");
1663 else if (name == "CJK") {
1664 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1665 // It is impossible to decide if a CJK environment was in its own paragraph or within
1666 // a line. We therefore always assume a paragraph since the latter is a rare case.
1667 eat_whitespace(p, os, parent_context, false);
1668 parent_context.check_end_layout(os);
1669 // store the encoding to be able to reset it
1670 string const encoding_old = p.getEncoding();
1671 string const encoding = p.getArg('{', '}');
1672 // FIXME: For some reason JIS does not work. Although the text
1673 // in tests/CJK.tex is identical with the SJIS version if you
1674 // convert both snippets using the recode command line utility,
1675 // the resulting .lyx file contains some extra characters if
1676 // you set buggy_encoding to false for JIS.
1677 bool const buggy_encoding = encoding == "JIS";
1678 if (!buggy_encoding)
1679 p.setEncoding(encoding, Encoding::CJK);
1681 // FIXME: This will read garbage, since the data is not encoded in utf8.
1682 p.setEncoding("UTF-8");
1684 // LyX only supports the same mapping for all CJK
1685 // environments, so we might need to output everything as ERT
1686 string const mapping = trim(p.getArg('{', '}'));
1687 char const * const * const where =
1688 is_known(encoding, supported_CJK_encodings);
1689 if (!buggy_encoding && !preamble.fontCJKSet())
1690 preamble.fontCJK(mapping);
1691 bool knownMapping = mapping == preamble.fontCJK();
1692 if (buggy_encoding || !knownMapping || !where) {
1693 parent_context.check_layout(os);
1694 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1696 // we must parse the content as verbatim because e.g. JIS can contain
1697 // normally invalid characters
1698 // FIXME: This works only for the most simple cases.
1699 // Since TeX control characters are not parsed,
1700 // things like comments are completely wrong.
1701 string const s = p.plainEnvironment("CJK");
1702 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1704 output_ert_inset(os, "\\", parent_context);
1705 else if (*it == '$')
1706 output_ert_inset(os, "$", parent_context);
1707 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1712 output_ert_inset(os, "\\end{" + name + "}",
1716 supported_CJK_languages[where - supported_CJK_encodings];
1717 // store the language because we must reset it at the end
1718 string const lang_old = parent_context.font.language;
1719 parent_context.font.language = lang;
1720 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1721 parent_context.font.language = lang_old;
1722 parent_context.new_paragraph(os);
1724 p.setEncoding(encoding_old);
1728 else if (name == "lyxgreyedout") {
1729 eat_whitespace(p, os, parent_context, false);
1730 parent_context.check_layout(os);
1731 begin_inset(os, "Note Greyedout\n");
1732 os << "status open\n";
1733 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1736 if (!preamble.notefontcolor().empty())
1737 preamble.registerAutomaticallyLoadedPackage("color");
1740 else if (name == "btSect") {
1741 eat_whitespace(p, os, parent_context, false);
1742 parent_context.check_layout(os);
1743 begin_command_inset(os, "bibtex", "bibtex");
1744 string bibstyle = "plain";
1746 bibstyle = p.getArg('[', ']');
1747 p.skip_spaces(true);
1749 string const bibfile = p.getArg('{', '}');
1750 eat_whitespace(p, os, parent_context, false);
1751 Token t = p.get_token();
1752 if (t.asInput() == "\\btPrintCited") {
1753 p.skip_spaces(true);
1754 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1756 if (t.asInput() == "\\btPrintNotCited") {
1757 p.skip_spaces(true);
1758 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1760 if (t.asInput() == "\\btPrintAll") {
1761 p.skip_spaces(true);
1762 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1764 os << "bibfiles " << '"' << bibfile << "\"\n"
1765 << "options " << '"' << bibstyle << "\"\n";
1766 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1771 else if (name == "framed" || name == "shaded") {
1772 eat_whitespace(p, os, parent_context, false);
1773 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1775 preamble.registerAutomaticallyLoadedPackage("framed");
1778 else if (name == "listing") {
1779 minted_float = "float";
1780 eat_whitespace(p, os, parent_context, false);
1781 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1783 minted_float += "=" + opt;
1784 // If something precedes \begin{minted}, we output it at the end
1785 // as a caption, in order to keep it inside the listings inset.
1786 eat_whitespace(p, os, parent_context, true);
1788 Token const & t = p.get_token();
1789 p.skip_spaces(true);
1790 string const envname = p.next_token().cat() == catBegin
1791 ? p.getArg('{', '}') : string();
1792 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1794 minted_float_has_caption = false;
1795 string content = parse_text_snippet(p, FLAG_END, outer,
1797 size_t i = content.find("\\begin_inset listings");
1798 bool minted_env = i != string::npos;
1801 caption = content.substr(0, i);
1802 content.erase(0, i);
1804 parent_context.check_layout(os);
1805 if (minted_env && minted_float_has_caption) {
1806 eat_whitespace(p, os, parent_context, true);
1807 os << content << "\n";
1808 if (!caption.empty())
1809 os << caption << "\n";
1810 os << "\n\\end_layout\n"; // close inner layout
1811 end_inset(os); // close caption inset
1812 os << "\n\\end_layout\n"; // close outer layout
1813 } else if (!caption.empty()) {
1815 begin_inset(os, "listings\n");
1816 os << "lstparams " << '"' << minted_float << '"' << '\n';
1817 os << "inline false\n";
1818 os << "status collapsed\n";
1820 os << "\n\\begin_layout Plain Layout\n";
1821 begin_inset(os, "Caption Standard\n");
1822 Context newcontext(true, parent_context.textclass,
1823 0, 0, parent_context.font);
1824 newcontext.check_layout(os);
1825 os << caption << "\n";
1826 newcontext.check_end_layout(os);
1828 os << "\n\\end_layout\n";
1829 } else if (content.empty()) {
1830 begin_inset(os, "listings\n");
1831 os << "lstparams " << '"' << minted_float << '"' << '\n';
1832 os << "inline false\n";
1833 os << "status collapsed\n";
1835 os << content << "\n";
1837 end_inset(os); // close listings inset
1838 parent_context.check_end_layout(os);
1839 parent_context.new_paragraph(os);
1841 minted_float.clear();
1842 minted_float_has_caption = false;
1845 else if (name == "lstlisting" || name == "minted") {
1846 bool use_minted = name == "minted";
1847 eat_whitespace(p, os, parent_context, false);
1848 if (use_minted && minted_float.empty()) {
1849 // look ahead for a bottom caption
1851 bool found_end_minted = false;
1852 while (!found_end_minted && p.good()) {
1853 Token const & t = p.get_token();
1855 string const envname =
1856 p.next_token().cat() == catBegin
1857 ? p.getArg('{', '}') : string();
1858 found_end_minted = t.asInput() == "\\end"
1859 && envname == "minted";
1861 eat_whitespace(p, os, parent_context, true);
1862 Token const & t = p.get_token();
1863 p.skip_spaces(true);
1864 if (t.asInput() == "\\lyxmintcaption") {
1865 string const pos = p.getArg('[', ']');
1867 string const caption =
1868 parse_text_snippet(p, FLAG_ITEM,
1869 false, parent_context);
1870 minted_nonfloat_caption = "[b]" + caption;
1875 parse_listings(p, os, parent_context, false, use_minted);
1879 else if (!parent_context.new_layout_allowed)
1880 parse_unknown_environment(p, name, os, FLAG_END, outer,
1883 // Alignment and spacing settings
1884 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1885 // therefore are totally broken!
1886 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1887 // they are commands not environments. They are furthermore switches that
1888 // can be ended by another switches, but also by commands like \footnote or
1889 // \parbox. So the only safe way is to leave them untouched.
1890 else if (name == "center" || name == "centering" ||
1891 name == "flushleft" || name == "flushright" ||
1892 name == "singlespace" || name == "onehalfspace" ||
1893 name == "doublespace" || name == "spacing") {
1894 eat_whitespace(p, os, parent_context, false);
1895 // We must begin a new paragraph if not already done
1896 if (! parent_context.atParagraphStart()) {
1897 parent_context.check_end_layout(os);
1898 parent_context.new_paragraph(os);
1900 if (name == "flushleft")
1901 parent_context.add_extra_stuff("\\align left\n");
1902 else if (name == "flushright")
1903 parent_context.add_extra_stuff("\\align right\n");
1904 else if (name == "center" || name == "centering")
1905 parent_context.add_extra_stuff("\\align center\n");
1906 else if (name == "singlespace")
1907 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1908 else if (name == "onehalfspace") {
1909 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1910 preamble.registerAutomaticallyLoadedPackage("setspace");
1911 } else if (name == "doublespace") {
1912 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1913 preamble.registerAutomaticallyLoadedPackage("setspace");
1914 } else if (name == "spacing") {
1915 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1916 preamble.registerAutomaticallyLoadedPackage("setspace");
1918 parse_text(p, os, FLAG_END, outer, parent_context);
1919 // Just in case the environment is empty
1920 parent_context.extra_stuff.erase();
1921 // We must begin a new paragraph to reset the alignment
1922 parent_context.new_paragraph(os);
1926 // The single '=' is meant here.
1927 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1928 eat_whitespace(p, os, parent_context, false);
1929 Context context(true, parent_context.textclass, newlayout,
1930 parent_context.layout, parent_context.font);
1931 if (parent_context.deeper_paragraph) {
1932 // We are beginning a nested environment after a
1933 // deeper paragraph inside the outer list environment.
1934 // Therefore we don't need to output a "begin deeper".
1935 context.need_end_deeper = true;
1937 parent_context.check_end_layout(os);
1938 if (last_env == name) {
1939 // we need to output a separator since LyX would export
1940 // the two environments as one otherwise (bug 5716)
1941 TeX2LyXDocClass const & textclass(parent_context.textclass);
1942 Context newcontext(true, textclass,
1943 &(textclass.defaultLayout()));
1944 newcontext.check_layout(os);
1945 begin_inset(os, "Separator plain\n");
1947 newcontext.check_end_layout(os);
1949 switch (context.layout->latextype) {
1950 case LATEX_LIST_ENVIRONMENT:
1951 context.add_par_extra_stuff("\\labelwidthstring "
1952 + p.verbatim_item() + '\n');
1955 case LATEX_BIB_ENVIRONMENT:
1956 p.verbatim_item(); // swallow next arg
1962 context.check_deeper(os);
1963 // handle known optional and required arguments
1964 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1965 // It is impossible to place anything after the environment name,
1966 // but before the first \\item.
1967 if (context.layout->latextype == LATEX_ENVIRONMENT)
1968 output_arguments(os, p, outer, false, false, context,
1969 context.layout->latexargs());
1970 parse_text(p, os, FLAG_END, outer, context);
1971 if (context.layout->latextype == LATEX_ENVIRONMENT)
1972 output_arguments(os, p, outer, false, true, context,
1973 context.layout->postcommandargs());
1974 context.check_end_layout(os);
1975 if (parent_context.deeper_paragraph) {
1976 // We must suppress the "end deeper" because we
1977 // suppressed the "begin deeper" above.
1978 context.need_end_deeper = false;
1980 context.check_end_deeper(os);
1981 parent_context.new_paragraph(os);
1983 if (!preamble.titleLayoutFound())
1984 preamble.titleLayoutFound(newlayout->intitle);
1985 set<string> const & req = newlayout->requires();
1986 set<string>::const_iterator it = req.begin();
1987 set<string>::const_iterator en = req.end();
1988 for (; it != en; ++it)
1989 preamble.registerAutomaticallyLoadedPackage(*it);
1992 // The single '=' is meant here.
1993 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1994 eat_whitespace(p, os, parent_context, false);
1995 parent_context.check_layout(os);
1996 begin_inset(os, "Flex ");
1997 docstring flex_name = newinsetlayout->name();
1998 // FIXME: what do we do if the prefix is not Flex: ?
1999 if (prefixIs(flex_name, from_ascii("Flex:")))
2000 flex_name.erase(0, 5);
2001 os << to_utf8(flex_name) << '\n'
2002 << "status collapsed\n";
2003 if (newinsetlayout->isPassThru()) {
2004 string const arg = p.verbatimEnvironment(name);
2005 Context context(true, parent_context.textclass,
2006 &parent_context.textclass.plainLayout(),
2007 parent_context.layout);
2008 output_ert(os, arg, parent_context);
2010 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2014 else if (name == "appendix") {
2015 // This is no good latex style, but it works and is used in some documents...
2016 eat_whitespace(p, os, parent_context, false);
2017 parent_context.check_end_layout(os);
2018 Context context(true, parent_context.textclass, parent_context.layout,
2019 parent_context.layout, parent_context.font);
2020 context.check_layout(os);
2021 os << "\\start_of_appendix\n";
2022 parse_text(p, os, FLAG_END, outer, context);
2023 context.check_end_layout(os);
2027 else if (known_environments.find(name) != known_environments.end()) {
2028 vector<ArgumentType> arguments = known_environments[name];
2029 // The last "argument" denotes wether we may translate the
2030 // environment contents to LyX
2031 // The default required if no argument is given makes us
2032 // compatible with the reLyXre environment.
2033 ArgumentType contents = arguments.empty() ?
2036 if (!arguments.empty())
2037 arguments.pop_back();
2038 // See comment in parse_unknown_environment()
2039 bool const specialfont =
2040 (parent_context.font != parent_context.normalfont);
2041 bool const new_layout_allowed =
2042 parent_context.new_layout_allowed;
2044 parent_context.new_layout_allowed = false;
2045 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2046 outer, parent_context);
2047 if (contents == verbatim)
2048 output_ert_inset(os, p.ertEnvironment(name),
2051 parse_text_snippet(p, os, FLAG_END, outer,
2053 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2055 parent_context.new_layout_allowed = new_layout_allowed;
2059 parse_unknown_environment(p, name, os, FLAG_END, outer,
2063 active_environments.pop_back();
2067 /// parses a comment and outputs it to \p os.
2068 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2070 LASSERT(t.cat() == catComment, return);
2071 if (!t.cs().empty()) {
2072 context.check_layout(os);
2073 output_comment(p, os, t.cs(), context);
2074 if (p.next_token().cat() == catNewline) {
2075 // A newline after a comment line starts a new
2077 if (context.new_layout_allowed) {
2078 if(!context.atParagraphStart())
2079 // Only start a new paragraph if not already
2080 // done (we might get called recursively)
2081 context.new_paragraph(os);
2083 output_ert_inset(os, "\n", context);
2084 eat_whitespace(p, os, context, true);
2087 // "%\n" combination
2094 * Reads spaces and comments until the first non-space, non-comment token.
2095 * New paragraphs (double newlines or \\par) are handled like simple spaces
2096 * if \p eatParagraph is true.
2097 * Spaces are skipped, but comments are written to \p os.
2099 void eat_whitespace(Parser & p, ostream & os, Context & context,
2103 Token const & t = p.get_token();
2104 if (t.cat() == catComment)
2105 parse_comment(p, os, t, context);
2106 else if ((! eatParagraph && p.isParagraph()) ||
2107 (t.cat() != catSpace && t.cat() != catNewline)) {
2116 * Set a font attribute, parse text and reset the font attribute.
2117 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2118 * \param currentvalue Current value of the attribute. Is set to the new
2119 * value during parsing.
2120 * \param newvalue New value of the attribute
2122 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2123 Context & context, string const & attribute,
2124 string & currentvalue, string const & newvalue)
2126 context.check_layout(os);
2127 string const oldvalue = currentvalue;
2128 currentvalue = newvalue;
2129 os << '\n' << attribute << ' ' << newvalue << "\n";
2130 parse_text_snippet(p, os, flags, outer, context);
2131 context.check_layout(os);
2132 os << '\n' << attribute << ' ' << oldvalue << "\n";
2133 currentvalue = oldvalue;
2137 /// get the arguments of a natbib or jurabib citation command
2138 void get_cite_arguments(Parser & p, bool natbibOrder,
2139 string & before, string & after)
2141 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2143 // text before the citation
2145 // text after the citation
2146 after = p.getFullOpt();
2148 if (!after.empty()) {
2149 before = p.getFullOpt();
2150 if (natbibOrder && !before.empty())
2151 swap(before, after);
2156 /// Convert filenames with TeX macros and/or quotes to something LyX
2158 string const normalize_filename(string const & name)
2163 Token const & t = p.get_token();
2164 if (t.cat() != catEscape)
2166 else if (t.cs() == "lyxdot") {
2167 // This is used by LyX for simple dots in relative
2171 } else if (t.cs() == "space") {
2174 } else if (t.cs() == "string") {
2175 // Convert \string" to " and \string~ to ~
2176 Token const & n = p.next_token();
2177 if (n.asInput() != "\"" && n.asInput() != "~")
2182 // Strip quotes. This is a bit complicated (see latex_path()).
2183 string full = os.str();
2184 if (!full.empty() && full[0] == '"') {
2185 string base = removeExtension(full);
2186 string ext = getExtension(full);
2187 if (!base.empty() && base[base.length()-1] == '"')
2190 return addExtension(trim(base, "\""), ext);
2191 if (full[full.length()-1] == '"')
2194 return trim(full, "\"");
2200 /// Convert \p name from TeX convention (relative to master file) to LyX
2201 /// convention (relative to .lyx file) if it is relative
2202 void fix_child_filename(string & name)
2204 string const absMasterTeX = getMasterFilePath(true);
2205 bool const isabs = FileName::isAbsolute(name);
2206 // convert from "relative to .tex master" to absolute original path
2208 name = makeAbsPath(name, absMasterTeX).absFileName();
2209 bool copyfile = copyFiles();
2210 string const absParentLyX = getParentFilePath(false);
2213 // convert from absolute original path to "relative to master file"
2214 string const rel = to_utf8(makeRelPath(from_utf8(name),
2215 from_utf8(absMasterTeX)));
2216 // re-interpret "relative to .tex file" as "relative to .lyx file"
2217 // (is different if the master .lyx file resides in a
2218 // different path than the master .tex file)
2219 string const absMasterLyX = getMasterFilePath(false);
2220 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2221 // Do not copy if the new path is impossible to create. Example:
2222 // absMasterTeX = "/foo/bar/"
2223 // absMasterLyX = "/bar/"
2224 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2225 if (contains(name, "/../"))
2232 // convert from absolute original path to
2233 // "relative to .lyx file"
2234 name = to_utf8(makeRelPath(from_utf8(abs),
2235 from_utf8(absParentLyX)));
2239 // convert from absolute original path to "relative to .lyx file"
2240 name = to_utf8(makeRelPath(from_utf8(name),
2241 from_utf8(absParentLyX)));
2246 void copy_file(FileName const & src, string dstname)
2250 string const absParent = getParentFilePath(false);
2252 if (FileName::isAbsolute(dstname))
2253 dst = FileName(dstname);
2255 dst = makeAbsPath(dstname, absParent);
2256 FileName const srcpath = src.onlyPath();
2257 FileName const dstpath = dst.onlyPath();
2258 if (equivalent(srcpath, dstpath))
2260 if (!dstpath.isDirectory()) {
2261 if (!dstpath.createPath()) {
2262 cerr << "Warning: Could not create directory for file `"
2263 << dst.absFileName() << "´." << endl;
2267 if (dst.isReadableFile()) {
2268 if (overwriteFiles())
2269 cerr << "Warning: Overwriting existing file `"
2270 << dst.absFileName() << "´." << endl;
2272 cerr << "Warning: Not overwriting existing file `"
2273 << dst.absFileName() << "´." << endl;
2277 if (!src.copyTo(dst))
2278 cerr << "Warning: Could not copy file `" << src.absFileName()
2279 << "´ to `" << dst.absFileName() << "´." << endl;
2283 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2284 bool parse_chunk(Parser & p, ostream & os, Context & context)
2286 // check whether a chunk is possible here.
2287 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2293 // read the parameters
2294 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2295 if (!params.first) {
2300 Parser::Arg const code = p.verbatimStuff("\n@");
2305 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2306 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2310 // The last newline read is important for paragraph handling
2314 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2315 // We must have a valid layout before outputting the Chunk inset.
2316 context.check_layout(os);
2317 Context chunkcontext(true, context.textclass);
2318 chunkcontext.layout = &context.textclass.plainLayout();
2319 begin_inset(os, "Flex Chunk");
2320 os << "\nstatus open\n";
2321 if (!params.second.empty()) {
2322 chunkcontext.check_layout(os);
2323 Context paramscontext(true, context.textclass);
2324 paramscontext.layout = &context.textclass.plainLayout();
2325 begin_inset(os, "Argument 1");
2326 os << "\nstatus open\n";
2327 output_ert(os, params.second, paramscontext);
2330 output_ert(os, code.second, chunkcontext);
2338 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2339 bool is_macro(Parser & p)
2341 Token first = p.curr_token();
2342 if (first.cat() != catEscape || !p.good())
2344 if (first.cs() == "def")
2346 if (first.cs() != "global" && first.cs() != "long")
2348 Token second = p.get_token();
2350 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2351 second.cat() == catNewline || second.cat() == catComment)) {
2352 second = p.get_token();
2355 bool secondvalid = second.cat() == catEscape;
2357 bool thirdvalid = false;
2358 if (p.good() && first.cs() == "global" && secondvalid &&
2359 second.cs() == "long") {
2360 third = p.get_token();
2362 while (p.good() && !p.isParagraph() &&
2363 (third.cat() == catSpace ||
2364 third.cat() == catNewline ||
2365 third.cat() == catComment)) {
2366 third = p.get_token();
2369 thirdvalid = third.cat() == catEscape;
2371 for (int i = 0; i < pos; ++i)
2376 return (first.cs() == "global" || first.cs() == "long") &&
2377 second.cs() == "def";
2378 return first.cs() == "global" && second.cs() == "long" &&
2379 third.cs() == "def";
2383 /// Parse a macro definition (assumes that is_macro() returned true)
2384 void parse_macro(Parser & p, ostream & os, Context & context)
2386 context.check_layout(os);
2387 Token first = p.curr_token();
2390 string command = first.asInput();
2391 if (first.cs() != "def") {
2393 eat_whitespace(p, os, context, false);
2394 second = p.curr_token();
2395 command += second.asInput();
2396 if (second.cs() != "def") {
2398 eat_whitespace(p, os, context, false);
2399 third = p.curr_token();
2400 command += third.asInput();
2403 eat_whitespace(p, os, context, false);
2404 string const name = p.get_token().cs();
2405 eat_whitespace(p, os, context, false);
2411 while (p.next_token().cat() != catBegin) {
2412 if (p.next_token().cat() == catParameter) {
2417 // followed by number?
2418 if (p.next_token().cat() == catOther) {
2419 string s = p.get_token().asInput();
2421 // number = current arity + 1?
2422 if (s.size() == 1 && s[0] == arity + '0' + 1)
2427 paramtext += p.get_token().cs();
2429 paramtext += p.get_token().cs();
2434 // only output simple (i.e. compatible) macro as FormulaMacros
2435 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2437 context.check_layout(os);
2438 begin_inset(os, "FormulaMacro");
2439 os << "\n\\def" << ert;
2442 output_ert_inset(os, command + ert, context);
2446 void registerExternalTemplatePackages(string const & name)
2448 external::TemplateManager const & etm = external::TemplateManager::get();
2449 external::Template const * const et = etm.getTemplateByName(name);
2452 external::Template::Formats::const_iterator cit = et->formats.end();
2454 cit = et->formats.find("PDFLaTeX");
2455 if (cit == et->formats.end())
2456 // If the template has not specified a PDFLaTeX output,
2457 // we try the LaTeX format.
2458 cit = et->formats.find("LaTeX");
2459 if (cit == et->formats.end())
2461 vector<string>::const_iterator qit = cit->second.requirements.begin();
2462 vector<string>::const_iterator qend = cit->second.requirements.end();
2463 for (; qit != qend; ++qit)
2464 preamble.registerAutomaticallyLoadedPackage(*qit);
2467 } // anonymous namespace
2470 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2473 Layout const * newlayout = 0;
2474 InsetLayout const * newinsetlayout = 0;
2475 char const * const * where = 0;
2476 // Store the latest bibliographystyle, addcontentslineContent and
2477 // nocite{*} option (needed for bibtex inset)
2479 string contentslineContent;
2480 // Some classes provide a \bibliographystyle, so do not output
2481 // any if none is explicitly set.
2482 string bibliographystyle;
2483 bool const use_natbib = isProvided("natbib");
2484 bool const use_jurabib = isProvided("jurabib");
2487 // it is impossible to determine the correct encoding for non-CJK Japanese.
2488 // Therefore write a note at the beginning of the document
2489 if (is_nonCJKJapanese) {
2490 context.check_layout(os);
2491 begin_inset(os, "Note Note\n");
2492 os << "status open\n\\begin_layout Plain Layout\n"
2493 << "\\series bold\n"
2494 << "Important information:\n"
2495 << "\\end_layout\n\n"
2496 << "\\begin_layout Plain Layout\n"
2497 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2498 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2499 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2500 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2501 << " and specify the encoding using the -e command-line switch.\n"
2502 << " In addition, you might want to double check that the desired output encoding\n"
2503 << " is correctly selected in Document > Settings > Language.\n"
2504 << "\\end_layout\n";
2506 is_nonCJKJapanese = false;
2510 Token const & t = p.get_token();
2512 debugToken(cerr, t, flags);
2515 if (flags & FLAG_ITEM) {
2516 if (t.cat() == catSpace)
2519 flags &= ~FLAG_ITEM;
2520 if (t.cat() == catBegin) {
2521 // skip the brace and collect everything to the next matching
2523 flags |= FLAG_BRACE_LAST;
2527 // handle only this single token, leave the loop if done
2528 flags |= FLAG_LEAVE;
2531 if (t.cat() != catEscape && t.character() == ']' &&
2532 (flags & FLAG_BRACK_LAST))
2534 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2537 // If there is anything between \end{env} and \begin{env} we
2538 // don't need to output a separator.
2539 if (t.cat() != catSpace && t.cat() != catNewline &&
2540 t.asInput() != "\\begin")
2546 bool const starred = p.next_token().asInput() == "*";
2547 string const starredname(starred ? (t.cs() + '*') : t.cs());
2548 if (t.cat() == catMath) {
2549 // we are inside some text mode thingy, so opening new math is allowed
2550 context.check_layout(os);
2551 begin_inset(os, "Formula ");
2552 Token const & n = p.get_token();
2553 bool const display(n.cat() == catMath && outer);
2555 // TeX's $$...$$ syntax for displayed math
2557 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2559 p.get_token(); // skip the second '$' token
2561 // simple $...$ stuff
2564 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2569 // Prevent the conversion of a line break to a
2570 // space (bug 7668). This does not change the
2571 // output, but looks ugly in LyX.
2572 eat_whitespace(p, os, context, false);
2576 else if (t.cat() == catSuper || t.cat() == catSub)
2577 cerr << "catcode " << t << " illegal in text mode\n";
2579 // Basic support for english quotes. This should be
2580 // extended to other quotes, but is not so easy (a
2581 // left english quote is the same as a right german
2583 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2584 context.check_layout(os);
2585 begin_inset(os, "Quotes ");
2591 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2592 context.check_layout(os);
2593 begin_inset(os, "Quotes ");
2600 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2601 context.check_layout(os);
2602 begin_inset(os, "Quotes ");
2609 else if (t.asInput() == "<"
2610 && p.next_token().asInput() == "<") {
2611 bool has_chunk = false;
2615 has_chunk = parse_chunk(p, os, context);
2621 context.check_layout(os);
2622 begin_inset(os, "Quotes ");
2623 //FIXME: this is a right danish quote;
2624 // why not a left french quote?
2632 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2633 check_space(p, os, context);
2635 // babel shorthands (also used by polyglossia)
2636 // Since these can have different meanings for different languages
2637 // we import them as ERT (but they must be put in ERT to get output
2639 else if (t.asInput() == "\"") {
2641 // These are known pairs. We put them together in
2642 // one ERT inset. In other cases (such as "a), only
2643 // the quotation mark is ERTed.
2644 if (p.next_token().asInput() == "\""
2645 || p.next_token().asInput() == "|"
2646 || p.next_token().asInput() == "-"
2647 || p.next_token().asInput() == "~"
2648 || p.next_token().asInput() == "="
2649 || p.next_token().asInput() == "/"
2650 || p.next_token().asInput() == "~"
2651 || p.next_token().asInput() == "'"
2652 || p.next_token().asInput() == "`"
2653 || p.next_token().asInput() == "<"
2654 || p.next_token().asInput() == ">") {
2655 s += p.next_token().asInput();
2658 output_ert_inset(os, s, context);
2661 else if (t.character() == '[' && noweb_mode &&
2662 p.next_token().character() == '[') {
2663 // These can contain underscores
2665 string const s = p.getFullOpt() + ']';
2666 if (p.next_token().character() == ']')
2669 cerr << "Warning: Inserting missing ']' in '"
2670 << s << "'." << endl;
2671 output_ert_inset(os, s, context);
2674 else if (t.cat() == catLetter) {
2675 context.check_layout(os);
2679 else if (t.cat() == catOther ||
2680 t.cat() == catAlign ||
2681 t.cat() == catParameter) {
2682 context.check_layout(os);
2683 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2684 context.merging_hyphens_allowed &&
2685 context.font.family != "ttfamily" &&
2686 !context.layout->pass_thru) {
2687 if (p.next_next_token().asInput() == "-") {
2689 os << to_utf8(docstring(1, 0x2014));
2693 os << to_utf8(docstring(1, 0x2013));
2696 // This translates "&" to "\\&" which may be wrong...
2700 else if (p.isParagraph()) {
2701 // In minted floating listings we will collect
2702 // everything into the caption, where multiple
2703 // paragraphs are forbidden.
2704 if (minted_float.empty()) {
2705 if (context.new_layout_allowed)
2706 context.new_paragraph(os);
2708 output_ert_inset(os, "\\par ", context);
2711 eat_whitespace(p, os, context, true);
2714 else if (t.cat() == catActive) {
2715 context.check_layout(os);
2716 if (t.character() == '~') {
2717 if (context.layout->free_spacing)
2720 begin_inset(os, "space ~\n");
2727 else if (t.cat() == catBegin) {
2728 Token const next = p.next_token();
2729 Token const end = p.next_next_token();
2730 if (next.cat() == catEnd) {
2732 Token const prev = p.prev_token();
2734 if (p.next_token().character() == '`')
2735 ; // ignore it in {}``
2737 output_ert_inset(os, "{}", context);
2738 } else if (next.cat() == catEscape &&
2739 is_known(next.cs(), known_quotes) &&
2740 end.cat() == catEnd) {
2741 // Something like {\textquoteright} (e.g.
2742 // from writer2latex). LyX writes
2743 // \textquoteright{}, so we may skip the
2744 // braces here for better readability.
2745 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2747 } else if (p.next_token().asInput() == "\\ascii") {
2748 // handle the \ascii characters
2749 // (the case without braces is handled later)
2750 // the code is "{\ascii\xxx}"
2751 p.get_token(); // eat \ascii
2752 string name2 = p.get_token().asInput();
2753 p.get_token(); // eat the final '}'
2754 string const name = "{\\ascii" + name2 + "}";
2758 // get the character from unicodesymbols
2759 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2760 Encodings::TEXT_CMD, termination, rem, &req);
2762 context.check_layout(os);
2765 output_ert_inset(os,
2766 to_utf8(rem), context);
2767 for (set<string>::const_iterator it = req.begin();
2768 it != req.end(); ++it)
2769 preamble.registerAutomaticallyLoadedPackage(*it);
2771 // we did not find a non-ert version
2772 output_ert_inset(os, name, context);
2774 context.check_layout(os);
2775 // special handling of font attribute changes
2776 Token const prev = p.prev_token();
2777 TeXFont const oldFont = context.font;
2778 if (next.character() == '[' ||
2779 next.character() == ']' ||
2780 next.character() == '*') {
2782 if (p.next_token().cat() == catEnd) {
2787 output_ert_inset(os, "{", context);
2788 parse_text_snippet(p, os,
2791 output_ert_inset(os, "}", context);
2793 } else if (! context.new_layout_allowed) {
2794 output_ert_inset(os, "{", context);
2795 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2797 output_ert_inset(os, "}", context);
2798 } else if (is_known(next.cs(), known_sizes)) {
2799 // next will change the size, so we must
2801 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2803 if (!context.atParagraphStart())
2805 << context.font.size << "\n";
2806 } else if (is_known(next.cs(), known_font_families)) {
2807 // next will change the font family, so we
2808 // must reset it here
2809 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2811 if (!context.atParagraphStart())
2813 << context.font.family << "\n";
2814 } else if (is_known(next.cs(), known_font_series)) {
2815 // next will change the font series, so we
2816 // must reset it here
2817 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2819 if (!context.atParagraphStart())
2821 << context.font.series << "\n";
2822 } else if (is_known(next.cs(), known_font_shapes)) {
2823 // next will change the font shape, so we
2824 // must reset it here
2825 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2827 if (!context.atParagraphStart())
2829 << context.font.shape << "\n";
2830 } else if (is_known(next.cs(), known_old_font_families) ||
2831 is_known(next.cs(), known_old_font_series) ||
2832 is_known(next.cs(), known_old_font_shapes)) {
2833 // next will change the font family, series
2834 // and shape, so we must reset it here
2835 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2837 if (!context.atParagraphStart())
2839 << context.font.family
2841 << context.font.series
2843 << context.font.shape << "\n";
2845 output_ert_inset(os, "{", context);
2846 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2848 output_ert_inset(os, "}", context);
2853 else if (t.cat() == catEnd) {
2854 if (flags & FLAG_BRACE_LAST) {
2857 cerr << "stray '}' in text\n";
2858 output_ert_inset(os, "}", context);
2861 else if (t.cat() == catComment)
2862 parse_comment(p, os, t, context);
2865 // control sequences
2868 else if (t.cs() == "(" || t.cs() == "[") {
2869 bool const simple = t.cs() == "(";
2870 context.check_layout(os);
2871 begin_inset(os, "Formula");
2872 os << " \\" << t.cs();
2873 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2874 os << '\\' << (simple ? ')' : ']');
2877 // Prevent the conversion of a line break to a
2878 // space (bug 7668). This does not change the
2879 // output, but looks ugly in LyX.
2880 eat_whitespace(p, os, context, false);
2884 else if (t.cs() == "begin")
2885 parse_environment(p, os, outer, last_env,
2888 else if (t.cs() == "end") {
2889 if (flags & FLAG_END) {
2890 // eat environment name
2891 string const name = p.getArg('{', '}');
2892 if (name != active_environment())
2893 cerr << "\\end{" + name + "} does not match \\begin{"
2894 + active_environment() + "}\n";
2897 p.error("found 'end' unexpectedly");
2900 else if (t.cs() == "item") {
2902 bool const optarg = p.hasOpt();
2904 // FIXME: This swallows comments, but we cannot use
2905 // eat_whitespace() since we must not output
2906 // anything before the item.
2907 p.skip_spaces(true);
2908 s = p.verbatimOption();
2910 p.skip_spaces(false);
2912 context.check_layout(os);
2913 if (context.has_item) {
2914 // An item in an unknown list-like environment
2915 // FIXME: Do this in check_layout()!
2916 context.has_item = false;
2918 output_ert_inset(os, "\\item", context);
2920 output_ert_inset(os, "\\item ", context);
2923 if (context.layout->labeltype != LABEL_MANUAL) {
2924 // handle option of itemize item
2925 begin_inset(os, "Argument item:1\n");
2926 os << "status open\n";
2927 os << "\n\\begin_layout Plain Layout\n";
2929 os << parse_text_snippet(p2,
2930 FLAG_BRACK_LAST, outer, context);
2931 // we must not use context.check_end_layout(os)
2932 // because that would close the outer itemize layout
2933 os << "\n\\end_layout\n";
2935 eat_whitespace(p, os, context, false);
2936 } else if (!s.empty()) {
2937 // LyX adds braces around the argument,
2938 // so we need to remove them here.
2939 if (s.size() > 2 && s[0] == '{' &&
2940 s[s.size()-1] == '}')
2941 s = s.substr(1, s.size()-2);
2942 // If the argument contains a space we
2943 // must put it into ERT: Otherwise LyX
2944 // would misinterpret the space as
2945 // item delimiter (bug 7663)
2946 if (contains(s, ' ')) {
2947 output_ert_inset(os, s, context);
2950 os << parse_text_snippet(p2,
2951 FLAG_BRACK_LAST, outer, context);
2953 // The space is needed to separate the
2954 // item from the rest of the sentence.
2956 eat_whitespace(p, os, context, false);
2961 else if (t.cs() == "bibitem") {
2963 context.check_layout(os);
2964 eat_whitespace(p, os, context, false);
2965 string label = convert_command_inset_arg(p.verbatimOption());
2966 string key = convert_command_inset_arg(p.verbatim_item());
2967 if (contains(label, '\\') || contains(key, '\\')) {
2968 // LyX can't handle LaTeX commands in labels or keys
2969 output_ert_inset(os, t.asInput() + '[' + label +
2970 "]{" + p.verbatim_item() + '}',
2973 begin_command_inset(os, "bibitem", "bibitem");
2974 os << "label \"" << label << "\"\n"
2975 << "key \"" << key << "\"\n"
2976 << "literal \"true\"\n";
2981 else if (is_macro(p)) {
2982 // catch the case of \def\inputGnumericTable
2984 if (t.cs() == "def") {
2985 Token second = p.next_token();
2986 if (second.cs() == "inputGnumericTable") {
2990 Token third = p.get_token();
2992 if (third.cs() == "input") {
2996 string name = normalize_filename(p.verbatim_item());
2997 string const path = getMasterFilePath(true);
2998 // We want to preserve relative / absolute filenames,
2999 // therefore path is only used for testing
3000 // The file extension is in every case ".tex".
3001 // So we need to remove this extension and check for
3002 // the original one.
3003 name = removeExtension(name);
3004 if (!makeAbsPath(name, path).exists()) {
3005 char const * const Gnumeric_formats[] = {"gnumeric",
3007 string const Gnumeric_name =
3008 find_file(name, path, Gnumeric_formats);
3009 if (!Gnumeric_name.empty())
3010 name = Gnumeric_name;
3012 FileName const absname = makeAbsPath(name, path);
3013 if (absname.exists()) {
3014 fix_child_filename(name);
3015 copy_file(absname, name);
3017 cerr << "Warning: Could not find file '"
3018 << name << "'." << endl;
3019 context.check_layout(os);
3020 begin_inset(os, "External\n\ttemplate ");
3021 os << "GnumericSpreadsheet\n\tfilename "
3024 context.check_layout(os);
3026 // register the packages that are automatically loaded
3027 // by the Gnumeric template
3028 registerExternalTemplatePackages("GnumericSpreadsheet");
3033 parse_macro(p, os, context);
3036 else if (t.cs() == "noindent") {
3038 context.add_par_extra_stuff("\\noindent\n");
3041 else if (t.cs() == "appendix") {
3042 context.add_par_extra_stuff("\\start_of_appendix\n");
3043 // We need to start a new paragraph. Otherwise the
3044 // appendix in 'bla\appendix\chapter{' would start
3046 context.new_paragraph(os);
3047 // We need to make sure that the paragraph is
3048 // generated even if it is empty. Otherwise the
3049 // appendix in '\par\appendix\par\chapter{' would
3051 context.check_layout(os);
3052 // FIXME: This is a hack to prevent paragraph
3053 // deletion if it is empty. Handle this better!
3054 output_comment(p, os,
3055 "dummy comment inserted by tex2lyx to "
3056 "ensure that this paragraph is not empty",
3058 // Both measures above may generate an additional
3059 // empty paragraph, but that does not hurt, because
3060 // whitespace does not matter here.
3061 eat_whitespace(p, os, context, true);
3064 // Must catch empty dates before findLayout is called below
3065 else if (t.cs() == "date") {
3066 eat_whitespace(p, os, context, false);
3068 string const date = p.verbatim_item();
3071 preamble.suppressDate(true);
3074 preamble.suppressDate(false);
3075 if (context.new_layout_allowed &&
3076 (newlayout = findLayout(context.textclass,
3079 output_command_layout(os, p, outer,
3080 context, newlayout);
3081 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3082 if (!preamble.titleLayoutFound())
3083 preamble.titleLayoutFound(newlayout->intitle);
3084 set<string> const & req = newlayout->requires();
3085 set<string>::const_iterator it = req.begin();
3086 set<string>::const_iterator en = req.end();
3087 for (; it != en; ++it)
3088 preamble.registerAutomaticallyLoadedPackage(*it);
3090 output_ert_inset(os,
3091 "\\date{" + p.verbatim_item() + '}',
3096 // Starred section headings
3097 // Must attempt to parse "Section*" before "Section".
3098 else if ((p.next_token().asInput() == "*") &&
3099 context.new_layout_allowed &&
3100 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3103 output_command_layout(os, p, outer, context, newlayout);
3105 if (!preamble.titleLayoutFound())
3106 preamble.titleLayoutFound(newlayout->intitle);
3107 set<string> const & req = newlayout->requires();
3108 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3109 preamble.registerAutomaticallyLoadedPackage(*it);
3112 // Section headings and the like
3113 else if (context.new_layout_allowed &&
3114 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3116 output_command_layout(os, p, outer, context, newlayout);
3118 if (!preamble.titleLayoutFound())
3119 preamble.titleLayoutFound(newlayout->intitle);
3120 set<string> const & req = newlayout->requires();
3121 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3122 preamble.registerAutomaticallyLoadedPackage(*it);
3125 else if (t.cs() == "subfloat") {
3126 // the syntax is \subfloat[list entry][sub caption]{content}
3127 // if it is a table of figure depends on the surrounding float
3128 // FIXME: second optional argument is not parsed
3130 // do nothing if there is no outer float
3131 if (!float_type.empty()) {
3132 context.check_layout(os);
3134 begin_inset(os, "Float " + float_type + "\n");
3136 << "\nsideways false"
3137 << "\nstatus collapsed\n\n";
3140 bool has_caption = false;
3141 if (p.next_token().cat() != catEscape &&
3142 p.next_token().character() == '[') {
3143 p.get_token(); // eat '['
3144 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3148 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3149 // the caption comes always as the last
3151 // we must make sure that the caption gets a \begin_layout
3152 os << "\n\\begin_layout Plain Layout";
3154 begin_inset(os, "Caption Standard\n");
3155 Context newcontext(true, context.textclass,
3156 0, 0, context.font);
3157 newcontext.check_layout(os);
3158 os << caption << "\n";
3159 newcontext.check_end_layout(os);
3160 // We don't need really a new paragraph, but
3161 // we must make sure that the next item gets a \begin_layout.
3162 //newcontext.new_paragraph(os);
3166 // We don't need really a new paragraph, but
3167 // we must make sure that the next item gets a \begin_layout.
3169 context.new_paragraph(os);
3172 context.check_end_layout(os);
3173 // close the layout we opened
3175 os << "\n\\end_layout\n";
3177 // if the float type is not supported or there is no surrounding float
3180 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
3181 output_ert_inset(os, t.asInput() + '[' + opt_arg +
3182 "]{" + p.verbatim_item() + '}', context);
3184 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3188 else if (t.cs() == "includegraphics") {
3189 bool const clip = p.next_token().asInput() == "*";
3192 string const arg = p.getArg('[', ']');
3193 map<string, string> opts;
3194 vector<string> keys;
3195 split_map(arg, opts, keys);
3197 opts["clip"] = string();
3198 string name = normalize_filename(p.verbatim_item());
3200 string const path = getMasterFilePath(true);
3201 // We want to preserve relative / absolute filenames,
3202 // therefore path is only used for testing
3203 if (!makeAbsPath(name, path).exists()) {
3204 // The file extension is probably missing.
3205 // Now try to find it out.
3206 string const dvips_name =
3207 find_file(name, path,
3208 known_dvips_graphics_formats);
3209 string const pdftex_name =
3210 find_file(name, path,
3211 known_pdftex_graphics_formats);
3212 if (!dvips_name.empty()) {
3213 if (!pdftex_name.empty()) {
3214 cerr << "This file contains the "
3216 "\"\\includegraphics{"
3218 "However, files\n\""
3219 << dvips_name << "\" and\n\""
3220 << pdftex_name << "\"\n"
3221 "both exist, so I had to make a "
3222 "choice and took the first one.\n"
3223 "Please move the unwanted one "
3224 "someplace else and try again\n"
3225 "if my choice was wrong."
3229 } else if (!pdftex_name.empty()) {
3235 FileName const absname = makeAbsPath(name, path);
3236 if (absname.exists()) {
3237 fix_child_filename(name);
3238 copy_file(absname, name);
3240 cerr << "Warning: Could not find graphics file '"
3241 << name << "'." << endl;
3243 context.check_layout(os);
3244 begin_inset(os, "Graphics ");
3245 os << "\n\tfilename " << name << '\n';
3246 if (opts.find("width") != opts.end())
3248 << translate_len(opts["width"]) << '\n';
3249 if (opts.find("height") != opts.end())
3251 << translate_len(opts["height"]) << '\n';
3252 if (opts.find("scale") != opts.end()) {
3253 istringstream iss(opts["scale"]);
3257 os << "\tscale " << val << '\n';
3259 if (opts.find("angle") != opts.end()) {
3260 os << "\trotateAngle "
3261 << opts["angle"] << '\n';
3262 vector<string>::const_iterator a =
3263 find(keys.begin(), keys.end(), "angle");
3264 vector<string>::const_iterator s =
3265 find(keys.begin(), keys.end(), "width");
3266 if (s == keys.end())
3267 s = find(keys.begin(), keys.end(), "height");
3268 if (s == keys.end())
3269 s = find(keys.begin(), keys.end(), "scale");
3270 if (s != keys.end() && distance(s, a) > 0)
3271 os << "\tscaleBeforeRotation\n";
3273 if (opts.find("origin") != opts.end()) {
3275 string const opt = opts["origin"];
3276 if (opt.find('l') != string::npos) ss << "left";
3277 if (opt.find('r') != string::npos) ss << "right";
3278 if (opt.find('c') != string::npos) ss << "center";
3279 if (opt.find('t') != string::npos) ss << "Top";
3280 if (opt.find('b') != string::npos) ss << "Bottom";
3281 if (opt.find('B') != string::npos) ss << "Baseline";
3282 if (!ss.str().empty())
3283 os << "\trotateOrigin " << ss.str() << '\n';
3285 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3287 if (opts.find("keepaspectratio") != opts.end())
3288 os << "\tkeepAspectRatio\n";
3289 if (opts.find("clip") != opts.end())
3291 if (opts.find("draft") != opts.end())
3293 if (opts.find("bb") != opts.end())
3294 os << "\tBoundingBox "
3295 << opts["bb"] << '\n';
3296 int numberOfbbOptions = 0;
3297 if (opts.find("bbllx") != opts.end())
3298 numberOfbbOptions++;
3299 if (opts.find("bblly") != opts.end())
3300 numberOfbbOptions++;
3301 if (opts.find("bburx") != opts.end())
3302 numberOfbbOptions++;
3303 if (opts.find("bbury") != opts.end())
3304 numberOfbbOptions++;
3305 if (numberOfbbOptions == 4)
3306 os << "\tBoundingBox "
3307 << opts["bbllx"] << " " << opts["bblly"] << " "
3308 << opts["bburx"] << " " << opts["bbury"] << '\n';
3309 else if (numberOfbbOptions > 0)
3310 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3311 numberOfbbOptions = 0;
3312 if (opts.find("natwidth") != opts.end())
3313 numberOfbbOptions++;
3314 if (opts.find("natheight") != opts.end())
3315 numberOfbbOptions++;
3316 if (numberOfbbOptions == 2)
3317 os << "\tBoundingBox 0bp 0bp "
3318 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3319 else if (numberOfbbOptions > 0)
3320 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3321 ostringstream special;
3322 if (opts.find("hiresbb") != opts.end())
3323 special << "hiresbb,";
3324 if (opts.find("trim") != opts.end())
3326 if (opts.find("viewport") != opts.end())
3327 special << "viewport=" << opts["viewport"] << ',';
3328 if (opts.find("totalheight") != opts.end())
3329 special << "totalheight=" << opts["totalheight"] << ',';
3330 if (opts.find("type") != opts.end())
3331 special << "type=" << opts["type"] << ',';
3332 if (opts.find("ext") != opts.end())
3333 special << "ext=" << opts["ext"] << ',';
3334 if (opts.find("read") != opts.end())
3335 special << "read=" << opts["read"] << ',';
3336 if (opts.find("command") != opts.end())
3337 special << "command=" << opts["command"] << ',';
3338 string s_special = special.str();
3339 if (!s_special.empty()) {
3340 // We had special arguments. Remove the trailing ','.
3341 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3343 // TODO: Handle the unknown settings better.
3344 // Warn about invalid options.
3345 // Check whether some option was given twice.
3347 preamble.registerAutomaticallyLoadedPackage("graphicx");
3350 else if (t.cs() == "footnote" ||
3351 (t.cs() == "thanks" && context.layout->intitle)) {
3353 context.check_layout(os);
3354 begin_inset(os, "Foot\n");
3355 os << "status collapsed\n\n";
3356 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3360 else if (t.cs() == "marginpar") {
3362 context.check_layout(os);
3363 begin_inset(os, "Marginal\n");
3364 os << "status collapsed\n\n";
3365 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3369 else if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3370 bool const use_minted = t.cs() == "mintinline";
3372 parse_listings(p, os, context, true, use_minted);
3375 else if (t.cs() == "ensuremath") {
3377 context.check_layout(os);
3378 string const s = p.verbatim_item();
3379 //FIXME: this never triggers in UTF8
3380 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3383 output_ert_inset(os, "\\ensuremath{" + s + "}",
3387 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3388 if (preamble.titleLayoutFound()) {
3390 skip_spaces_braces(p);
3392 output_ert_inset(os, t.asInput(), context);
3395 else if (t.cs() == "tableofcontents"
3396 || t.cs() == "lstlistoflistings"
3397 || t.cs() == "listoflistings") {
3398 string name = t.cs();
3399 if (preamble.minted() && name == "listoflistings")
3400 name.insert(0, "lst");
3401 context.check_layout(os);
3402 begin_command_inset(os, "toc", name);
3404 skip_spaces_braces(p);
3405 if (name == "lstlistoflistings") {
3406 if (preamble.minted())
3407 preamble.registerAutomaticallyLoadedPackage("minted");
3409 preamble.registerAutomaticallyLoadedPackage("listings");
3413 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3414 context.check_layout(os);
3415 if (t.cs() == "listoffigures")
3416 begin_inset(os, "FloatList figure\n");
3418 begin_inset(os, "FloatList table\n");
3420 skip_spaces_braces(p);
3423 else if (t.cs() == "listof") {
3424 p.skip_spaces(true);
3425 string const name = p.get_token().cs();
3426 if (context.textclass.floats().typeExist(name)) {
3427 context.check_layout(os);
3428 begin_inset(os, "FloatList ");
3431 p.get_token(); // swallow second arg
3433 output_ert_inset(os, "\\listof{" + name + "}", context);
3436 else if ((where = is_known(t.cs(), known_text_font_families)))
3437 parse_text_attributes(p, os, FLAG_ITEM, outer,
3438 context, "\\family", context.font.family,
3439 known_coded_font_families[where - known_text_font_families]);
3441 else if ((where = is_known(t.cs(), known_text_font_series)))
3442 parse_text_attributes(p, os, FLAG_ITEM, outer,
3443 context, "\\series", context.font.series,
3444 known_coded_font_series[where - known_text_font_series]);
3446 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3447 parse_text_attributes(p, os, FLAG_ITEM, outer,
3448 context, "\\shape", context.font.shape,
3449 known_coded_font_shapes[where - known_text_font_shapes]);
3451 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3452 context.check_layout(os);
3453 TeXFont oldFont = context.font;
3454 context.font.init();
3455 context.font.size = oldFont.size;
3456 os << "\n\\family " << context.font.family << "\n";
3457 os << "\n\\series " << context.font.series << "\n";
3458 os << "\n\\shape " << context.font.shape << "\n";
3459 if (t.cs() == "textnormal") {
3460 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3461 output_font_change(os, context.font, oldFont);
3462 context.font = oldFont;
3464 eat_whitespace(p, os, context, false);
3467 else if (t.cs() == "textcolor") {
3468 // scheme is \textcolor{color name}{text}
3469 string const color = p.verbatim_item();
3470 // we support the predefined colors of the color and the xcolor package
3471 if (color == "black" || color == "blue" || color == "cyan"
3472 || color == "green" || color == "magenta" || color == "red"
3473 || color == "white" || color == "yellow") {
3474 context.check_layout(os);
3475 os << "\n\\color " << color << "\n";
3476 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3477 context.check_layout(os);
3478 os << "\n\\color inherit\n";
3479 preamble.registerAutomaticallyLoadedPackage("color");
3480 } else if (color == "brown" || color == "darkgray" || color == "gray"
3481 || color == "lightgray" || color == "lime" || color == "olive"
3482 || color == "orange" || color == "pink" || color == "purple"
3483 || color == "teal" || color == "violet") {
3484 context.check_layout(os);
3485 os << "\n\\color " << color << "\n";
3486 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3487 context.check_layout(os);
3488 os << "\n\\color inherit\n";
3489 preamble.registerAutomaticallyLoadedPackage("xcolor");
3491 // for custom defined colors
3492 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3495 else if (t.cs() == "underbar" || t.cs() == "uline") {
3496 // \underbar is not 100% correct (LyX outputs \uline
3497 // of ulem.sty). The difference is that \ulem allows
3498 // line breaks, and \underbar does not.
3499 // Do NOT handle \underline.
3500 // \underbar cuts through y, g, q, p etc.,
3501 // \underline does not.
3502 context.check_layout(os);
3503 os << "\n\\bar under\n";
3504 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3505 context.check_layout(os);
3506 os << "\n\\bar default\n";
3507 preamble.registerAutomaticallyLoadedPackage("ulem");
3510 else if (t.cs() == "sout") {
3511 context.check_layout(os);
3512 os << "\n\\strikeout on\n";
3513 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3514 context.check_layout(os);
3515 os << "\n\\strikeout default\n";
3516 preamble.registerAutomaticallyLoadedPackage("ulem");
3519 else if (t.cs() == "uuline" || t.cs() == "uwave"
3520 || t.cs() == "emph" || t.cs() == "noun"
3521 || t.cs() == "xout") {
3522 context.check_layout(os);
3523 os << "\n\\" << t.cs() << " on\n";
3524 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3525 context.check_layout(os);
3526 os << "\n\\" << t.cs() << " default\n";
3527 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3528 preamble.registerAutomaticallyLoadedPackage("ulem");
3531 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3532 context.check_layout(os);
3533 string name = p.getArg('{', '}');
3534 string localtime = p.getArg('{', '}');
3535 preamble.registerAuthor(name);
3536 Author const & author = preamble.getAuthor(name);
3537 // from_asctime_utc() will fail if LyX decides to output the
3538 // time in the text language.
3539 time_t ptime = from_asctime_utc(localtime);
3540 if (ptime == static_cast<time_t>(-1)) {
3541 cerr << "Warning: Could not parse time `" << localtime
3542 << "´ for change tracking, using current time instead.\n";
3543 ptime = current_time();
3545 if (t.cs() == "lyxadded")
3546 os << "\n\\change_inserted ";
3548 os << "\n\\change_deleted ";
3549 os << author.bufferId() << ' ' << ptime << '\n';
3550 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3551 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3552 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3553 LaTeXPackages::isAvailable("xcolor");
3554 // No need to test for luatex, since luatex comes in
3555 // two flavours (dvi and pdf), like latex, and those
3556 // are detected by pdflatex.
3557 if (pdflatex || xetex) {
3559 preamble.registerAutomaticallyLoadedPackage("ulem");
3560 preamble.registerAutomaticallyLoadedPackage("xcolor");
3561 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3565 preamble.registerAutomaticallyLoadedPackage("dvipost");
3566 } else if (xcolorulem) {
3567 preamble.registerAutomaticallyLoadedPackage("ulem");
3568 preamble.registerAutomaticallyLoadedPackage("xcolor");
3573 else if (t.cs() == "textipa") {
3574 context.check_layout(os);
3575 begin_inset(os, "IPA\n");
3576 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3577 context.merging_hyphens_allowed = false;
3578 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3579 context.merging_hyphens_allowed = merging_hyphens_allowed;
3581 preamble.registerAutomaticallyLoadedPackage("tipa");
3582 preamble.registerAutomaticallyLoadedPackage("tipx");
3585 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3586 context.check_layout(os);
3587 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3588 os << "status open\n";
3589 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3594 else if (t.cs() == "textvertline") {
3595 // FIXME: This is not correct, \textvertline is higher than |
3601 else if (t.cs() == "tone" ) {
3602 context.check_layout(os);
3603 // register the tone package
3604 preamble.registerAutomaticallyLoadedPackage("tone");
3605 string content = trimSpaceAndEol(p.verbatim_item());
3606 string command = t.asInput() + "{" + content + "}";
3607 // some tones can be detected by unicodesymbols, some need special code
3608 if (is_known(content, known_tones)) {
3609 os << "\\IPAChar " << command << "\n";
3612 // try to see whether the string is in unicodesymbols
3616 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3617 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3618 termination, rem, &req);
3622 output_ert_inset(os, to_utf8(rem), context);
3623 for (set<string>::const_iterator it = req.begin();
3624 it != req.end(); ++it)
3625 preamble.registerAutomaticallyLoadedPackage(*it);
3627 // we did not find a non-ert version
3628 output_ert_inset(os, command, context);
3631 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3632 t.cs() == "vphantom") {
3633 context.check_layout(os);
3634 if (t.cs() == "phantom")
3635 begin_inset(os, "Phantom Phantom\n");
3636 if (t.cs() == "hphantom")
3637 begin_inset(os, "Phantom HPhantom\n");
3638 if (t.cs() == "vphantom")
3639 begin_inset(os, "Phantom VPhantom\n");
3640 os << "status open\n";
3641 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3646 else if (t.cs() == "href") {
3647 context.check_layout(os);
3648 string target = convert_command_inset_arg(p.verbatim_item());
3649 string name = convert_command_inset_arg(p.verbatim_item());
3651 size_t i = target.find(':');
3652 if (i != string::npos) {
3653 type = target.substr(0, i + 1);
3654 if (type == "mailto:" || type == "file:")
3655 target = target.substr(i + 1);
3656 // handle the case that name is equal to target, except of "http(s)://"
3657 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3660 begin_command_inset(os, "href", "href");
3662 os << "name \"" << name << "\"\n";
3663 os << "target \"" << target << "\"\n";
3664 if (type == "mailto:" || type == "file:")
3665 os << "type \"" << type << "\"\n";
3666 os << "literal \"true\"\n";
3668 skip_spaces_braces(p);
3671 else if (t.cs() == "lyxline") {
3672 // swallow size argument (it is not used anyway)
3674 if (!context.atParagraphStart()) {
3675 // so our line is in the middle of a paragraph
3676 // we need to add a new line, lest this line
3677 // follow the other content on that line and
3678 // run off the side of the page
3679 // FIXME: This may create an empty paragraph,
3680 // but without that it would not be
3681 // possible to set noindent below.
3682 // Fortunately LaTeX does not care
3683 // about the empty paragraph.
3684 context.new_paragraph(os);
3686 if (preamble.indentParagraphs()) {
3687 // we need to unindent, lest the line be too long
3688 context.add_par_extra_stuff("\\noindent\n");
3690 context.check_layout(os);
3691 begin_command_inset(os, "line", "rule");
3692 os << "offset \"0.5ex\"\n"
3693 "width \"100line%\"\n"
3698 else if (t.cs() == "rule") {
3699 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3700 string const width = p.getArg('{', '}');
3701 string const thickness = p.getArg('{', '}');
3702 context.check_layout(os);
3703 begin_command_inset(os, "line", "rule");
3704 if (!offset.empty())
3705 os << "offset \"" << translate_len(offset) << "\"\n";
3706 os << "width \"" << translate_len(width) << "\"\n"
3707 "height \"" << translate_len(thickness) << "\"\n";
3711 // handle refstyle first to catch \eqref which can also occur
3712 // without refstyle. Only recognize these commands if
3713 // refstyle.sty was found in the preamble (otherwise \eqref
3714 // and user defined ref commands could be misdetected).
3715 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3716 preamble.refstyle()) {
3717 context.check_layout(os);
3718 begin_command_inset(os, "ref", "formatted");
3719 os << "reference \"";
3720 os << known_refstyle_prefixes[where - known_refstyle_commands]
3722 os << convert_command_inset_arg(p.verbatim_item())
3724 os << "plural \"false\"\n";
3725 os << "caps \"false\"\n";
3726 os << "noprefix \"false\"\n";
3728 preamble.registerAutomaticallyLoadedPackage("refstyle");
3731 // if refstyle is used, we must not convert \prettyref to a
3732 // formatted reference, since that would result in a refstyle command.
3733 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3734 (t.cs() != "prettyref" || !preamble.refstyle())) {
3735 string const opt = p.getOpt();
3737 context.check_layout(os);
3738 begin_command_inset(os, "ref",
3739 known_coded_ref_commands[where - known_ref_commands]);
3740 os << "reference \""
3741 << convert_command_inset_arg(p.verbatim_item())
3743 os << "plural \"false\"\n";
3744 os << "caps \"false\"\n";
3745 os << "noprefix \"false\"\n";
3747 if (t.cs() == "vref" || t.cs() == "vpageref")
3748 preamble.registerAutomaticallyLoadedPackage("varioref");
3749 else if (t.cs() == "prettyref")
3750 preamble.registerAutomaticallyLoadedPackage("prettyref");
3752 // LyX does not yet support optional arguments of ref commands
3753 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3754 p.verbatim_item() + '}', context);
3758 else if (use_natbib &&
3759 is_known(t.cs(), known_natbib_commands) &&
3760 ((t.cs() != "citefullauthor" &&
3761 t.cs() != "citeyear" &&
3762 t.cs() != "citeyearpar") ||
3763 p.next_token().asInput() != "*")) {
3764 context.check_layout(os);
3765 string command = t.cs();
3766 if (p.next_token().asInput() == "*") {
3770 if (command == "citefullauthor")
3771 // alternative name for "\\citeauthor*"
3772 command = "citeauthor*";
3774 // text before the citation
3776 // text after the citation
3778 get_cite_arguments(p, true, before, after);
3780 if (command == "cite") {
3781 // \cite without optional argument means
3782 // \citet, \cite with at least one optional
3783 // argument means \citep.
3784 if (before.empty() && after.empty())
3789 if (before.empty() && after == "[]")
3790 // avoid \citet[]{a}
3792 else if (before == "[]" && after == "[]") {
3793 // avoid \citet[][]{a}
3797 // remove the brackets around after and before
3798 if (!after.empty()) {
3800 after.erase(after.length() - 1, 1);
3801 after = convert_command_inset_arg(after);
3803 if (!before.empty()) {
3805 before.erase(before.length() - 1, 1);
3806 before = convert_command_inset_arg(before);
3808 begin_command_inset(os, "citation", command);
3809 os << "after " << '"' << after << '"' << "\n";
3810 os << "before " << '"' << before << '"' << "\n";
3812 << convert_command_inset_arg(p.verbatim_item())
3814 << "literal \"true\"\n";
3816 // Need to set the cite engine if natbib is loaded by
3817 // the document class directly
3818 if (preamble.citeEngine() == "basic")
3819 preamble.citeEngine("natbib");
3822 else if (use_jurabib &&
3823 is_known(t.cs(), known_jurabib_commands) &&
3824 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3825 context.check_layout(os);
3826 string command = t.cs();
3827 if (p.next_token().asInput() == "*") {
3831 char argumentOrder = '\0';
3832 vector<string> const options =
3833 preamble.getPackageOptions("jurabib");
3834 if (find(options.begin(), options.end(),
3835 "natbiborder") != options.end())
3836 argumentOrder = 'n';
3837 else if (find(options.begin(), options.end(),
3838 "jurabiborder") != options.end())
3839 argumentOrder = 'j';
3841 // text before the citation
3843 // text after the citation
3845 get_cite_arguments(p, argumentOrder != 'j', before, after);
3847 string const citation = p.verbatim_item();
3848 if (!before.empty() && argumentOrder == '\0') {
3849 cerr << "Warning: Assuming argument order "
3850 "of jurabib version 0.6 for\n'"
3851 << command << before << after << '{'
3852 << citation << "}'.\n"
3853 "Add 'jurabiborder' to the jurabib "
3854 "package options if you used an\n"
3855 "earlier jurabib version." << endl;
3857 if (!after.empty()) {
3859 after.erase(after.length() - 1, 1);
3861 if (!before.empty()) {
3863 before.erase(before.length() - 1, 1);
3865 begin_command_inset(os, "citation", command);
3866 os << "after " << '"' << after << "\"\n"
3867 << "before " << '"' << before << "\"\n"
3868 << "key " << '"' << citation << "\"\n"
3869 << "literal \"true\"\n";
3871 // Need to set the cite engine if jurabib is loaded by
3872 // the document class directly
3873 if (preamble.citeEngine() == "basic")
3874 preamble.citeEngine("jurabib");
3877 else if (t.cs() == "cite"
3878 || t.cs() == "nocite") {
3879 context.check_layout(os);
3880 string after = convert_command_inset_arg(p.getArg('[', ']'));
3881 string key = convert_command_inset_arg(p.verbatim_item());
3882 // store the case that it is "\nocite{*}" to use it later for
3885 begin_command_inset(os, "citation", t.cs());
3886 os << "after " << '"' << after << "\"\n"
3887 << "key " << '"' << key << "\"\n"
3888 << "literal \"true\"\n";
3890 } else if (t.cs() == "nocite")
3894 else if (t.cs() == "index" ||
3895 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
3896 context.check_layout(os);
3897 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
3898 p.getArg('[', ']') : "";
3899 string const kind = arg.empty() ? "idx" : arg;
3900 begin_inset(os, "Index ");
3901 os << kind << "\nstatus collapsed\n";
3902 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
3905 preamble.registerAutomaticallyLoadedPackage("splitidx");
3908 else if (t.cs() == "nomenclature") {
3909 context.check_layout(os);
3910 begin_command_inset(os, "nomenclature", "nomenclature");
3911 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
3912 if (!prefix.empty())
3913 os << "prefix " << '"' << prefix << '"' << "\n";
3914 os << "symbol " << '"'
3915 << convert_command_inset_arg(p.verbatim_item());
3916 os << "\"\ndescription \""
3917 << convert_command_inset_arg(p.verbatim_item())
3919 << "literal \"true\"\n";
3921 preamble.registerAutomaticallyLoadedPackage("nomencl");
3924 else if (t.cs() == "label") {
3925 context.check_layout(os);
3926 begin_command_inset(os, "label", "label");
3928 << convert_command_inset_arg(p.verbatim_item())
3933 else if (t.cs() == "lyxmintcaption") {
3934 string const pos = p.getArg('[', ']');
3936 string const caption =
3937 parse_text_snippet(p, FLAG_ITEM, false,
3939 minted_nonfloat_caption = "[t]" + caption;
3941 // We already got the caption at the bottom,
3942 // so simply skip it.
3943 parse_text_snippet(p, FLAG_ITEM, false, context);
3947 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
3948 context.check_layout(os);
3949 string commandname = t.cs();
3951 if (p.next_token().asInput() == "*") {
3956 begin_command_inset(os, "index_print", commandname);
3957 string const indexname = p.getArg('[', ']');
3959 if (indexname.empty())
3960 os << "type \"idx\"\n";
3962 os << "type \"" << indexname << "\"\n";
3963 os << "literal \"true\"\n";
3966 skip_spaces_braces(p);
3967 preamble.registerAutomaticallyLoadedPackage("makeidx");
3968 if (preamble.use_indices() == "true")
3969 preamble.registerAutomaticallyLoadedPackage("splitidx");
3972 else if (t.cs() == "printnomenclature") {
3974 string width_type = "";
3975 context.check_layout(os);
3976 begin_command_inset(os, "nomencl_print", "printnomenclature");
3977 // case of a custom width
3979 width = p.getArg('[', ']');
3980 width = translate_len(width);
3981 width_type = "custom";
3983 // case of no custom width
3984 // the case of no custom width but the width set
3985 // via \settowidth{\nomlabelwidth}{***} cannot be supported
3986 // because the user could have set anything, not only the width
3987 // of the longest label (which would be width_type = "auto")
3988 string label = convert_command_inset_arg(p.getArg('{', '}'));
3989 if (label.empty() && width_type.empty())
3990 width_type = "none";
3991 os << "set_width \"" << width_type << "\"\n";
3992 if (width_type == "custom")
3993 os << "width \"" << width << '\"';
3995 skip_spaces_braces(p);
3996 preamble.registerAutomaticallyLoadedPackage("nomencl");
3999 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4000 context.check_layout(os);
4001 begin_inset(os, "script ");
4002 os << t.cs().substr(4) << '\n';
4003 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4004 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4006 if (t.cs() == "textsubscript")
4007 preamble.registerAutomaticallyLoadedPackage("subscript");
4010 else if ((where = is_known(t.cs(), known_quotes))) {
4011 context.check_layout(os);
4012 begin_inset(os, "Quotes ");
4013 os << known_coded_quotes[where - known_quotes];
4015 // LyX adds {} after the quote, so we have to eat
4016 // spaces here if there are any before a possible
4018 eat_whitespace(p, os, context, false);
4022 else if ((where = is_known(t.cs(), known_sizes)) &&
4023 context.new_layout_allowed) {
4024 context.check_layout(os);
4025 TeXFont const oldFont = context.font;
4026 context.font.size = known_coded_sizes[where - known_sizes];
4027 output_font_change(os, oldFont, context.font);
4028 eat_whitespace(p, os, context, false);
4031 else if ((where = is_known(t.cs(), known_font_families)) &&
4032 context.new_layout_allowed) {
4033 context.check_layout(os);
4034 TeXFont const oldFont = context.font;
4035 context.font.family =
4036 known_coded_font_families[where - known_font_families];
4037 output_font_change(os, oldFont, context.font);
4038 eat_whitespace(p, os, context, false);
4041 else if ((where = is_known(t.cs(), known_font_series)) &&
4042 context.new_layout_allowed) {
4043 context.check_layout(os);
4044 TeXFont const oldFont = context.font;
4045 context.font.series =
4046 known_coded_font_series[where - known_font_series];
4047 output_font_change(os, oldFont, context.font);
4048 eat_whitespace(p, os, context, false);
4051 else if ((where = is_known(t.cs(), known_font_shapes)) &&
4052 context.new_layout_allowed) {
4053 context.check_layout(os);
4054 TeXFont const oldFont = context.font;
4055 context.font.shape =
4056 known_coded_font_shapes[where - known_font_shapes];
4057 output_font_change(os, oldFont, context.font);
4058 eat_whitespace(p, os, context, false);
4060 else if ((where = is_known(t.cs(), known_old_font_families)) &&
4061 context.new_layout_allowed) {
4062 context.check_layout(os);
4063 TeXFont const oldFont = context.font;
4064 context.font.init();
4065 context.font.size = oldFont.size;
4066 context.font.family =
4067 known_coded_font_families[where - known_old_font_families];
4068 output_font_change(os, oldFont, context.font);
4069 eat_whitespace(p, os, context, false);
4072 else if ((where = is_known(t.cs(), known_old_font_series)) &&
4073 context.new_layout_allowed) {
4074 context.check_layout(os);
4075 TeXFont const oldFont = context.font;
4076 context.font.init();
4077 context.font.size = oldFont.size;
4078 context.font.series =
4079 known_coded_font_series[where - known_old_font_series];
4080 output_font_change(os, oldFont, context.font);
4081 eat_whitespace(p, os, context, false);
4084 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4085 context.new_layout_allowed) {
4086 context.check_layout(os);
4087 TeXFont const oldFont = context.font;
4088 context.font.init();
4089 context.font.size = oldFont.size;
4090 context.font.shape =
4091 known_coded_font_shapes[where - known_old_font_shapes];
4092 output_font_change(os, oldFont, context.font);
4093 eat_whitespace(p, os, context, false);
4096 else if (t.cs() == "selectlanguage") {
4097 context.check_layout(os);
4098 // save the language for the case that a
4099 // \foreignlanguage is used
4100 context.font.language = babel2lyx(p.verbatim_item());
4101 os << "\n\\lang " << context.font.language << "\n";
4104 else if (t.cs() == "foreignlanguage") {
4105 string const lang = babel2lyx(p.verbatim_item());
4106 parse_text_attributes(p, os, FLAG_ITEM, outer,
4108 context.font.language, lang);
4111 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4112 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4113 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4115 // We have to output the whole command if it has an option
4116 // because LyX doesn't support this yet, see bug #8214,
4117 // only if there is a single option specifying a variant, we can handle it.
4119 string langopts = p.getOpt();
4120 // check if the option contains a variant, if yes, extract it
4121 string::size_type pos_var = langopts.find("variant");
4122 string::size_type i = langopts.find(',');
4123 string::size_type k = langopts.find('=', pos_var);
4124 if (pos_var != string::npos && i == string::npos) {
4126 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4127 lang = preamble.polyglossia2lyx(variant);
4128 parse_text_attributes(p, os, FLAG_ITEM, outer,
4130 context.font.language, lang);
4132 output_ert_inset(os, t.asInput() + langopts, context);
4134 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4135 parse_text_attributes(p, os, FLAG_ITEM, outer,
4137 context.font.language, lang);
4141 else if (t.cs() == "inputencoding") {
4142 // nothing to write here
4143 string const enc = subst(p.verbatim_item(), "\n", " ");
4144 p.setEncoding(enc, Encoding::inputenc);
4147 else if (is_known(t.cs(), known_special_chars) ||
4148 (t.cs() == "protect" &&
4149 p.next_token().cat() == catEscape &&
4150 is_known(p.next_token().cs(), known_special_protect_chars))) {
4151 // LyX sometimes puts a \protect in front, so we have to ignore it
4153 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4154 known_special_chars);
4155 context.check_layout(os);
4156 os << known_coded_special_chars[where - known_special_chars];
4157 skip_spaces_braces(p);
4160 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4161 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4162 p.next_next_token().asInput() == "-") ||
4163 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4164 // LyX sometimes puts a \protect in front, so we have to ignore it
4165 if (t.cs() == "protect")
4167 context.check_layout(os);
4168 if (t.cs() == "nobreakdash")
4169 os << "\\SpecialChar nobreakdash\n";
4171 os << "\\SpecialChar endofsentence\n";
4175 else if (t.cs() == "textquotedbl") {
4176 context.check_layout(os);
4181 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4182 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4183 || t.cs() == "%" || t.cs() == "-") {
4184 context.check_layout(os);
4186 os << "\\SpecialChar softhyphen\n";
4191 else if (t.cs() == "char") {
4192 context.check_layout(os);
4193 if (p.next_token().character() == '`') {
4195 if (p.next_token().cs() == "\"") {
4200 output_ert_inset(os, "\\char`", context);
4203 output_ert_inset(os, "\\char", context);
4207 else if (t.cs() == "verb") {
4208 context.check_layout(os);
4209 // set catcodes to verbatim early, just in case.
4210 p.setCatcodes(VERBATIM_CATCODES);
4211 string delim = p.get_token().asInput();
4212 Parser::Arg arg = p.verbatimStuff(delim);
4214 output_ert_inset(os, "\\verb" + delim
4215 + arg.second + delim, context);
4217 cerr << "invalid \\verb command. Skipping" << endl;
4220 // Problem: \= creates a tabstop inside the tabbing environment
4221 // and else an accent. In the latter case we really would want
4222 // \={o} instead of \= o.
4223 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4224 output_ert_inset(os, t.asInput(), context);
4226 else if (t.cs() == "\\") {
4227 context.check_layout(os);
4229 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4230 else if (p.next_token().asInput() == "*") {
4232 // getOpt() eats the following space if there
4233 // is no optional argument, but that is OK
4234 // here since it has no effect in the output.
4235 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4238 begin_inset(os, "Newline newline");
4243 else if (t.cs() == "newline" ||
4244 (t.cs() == "linebreak" && !p.hasOpt())) {
4245 context.check_layout(os);
4246 begin_inset(os, "Newline ");
4249 skip_spaces_braces(p);
4252 else if (t.cs() == "input" || t.cs() == "include"
4253 || t.cs() == "verbatiminput") {
4254 string name = t.cs();
4255 if (t.cs() == "verbatiminput"
4256 && p.next_token().asInput() == "*")
4257 name += p.get_token().asInput();
4258 context.check_layout(os);
4259 string filename(normalize_filename(p.getArg('{', '}')));
4260 string const path = getMasterFilePath(true);
4261 // We want to preserve relative / absolute filenames,
4262 // therefore path is only used for testing
4263 if ((t.cs() == "include" || t.cs() == "input") &&
4264 !makeAbsPath(filename, path).exists()) {
4265 // The file extension is probably missing.
4266 // Now try to find it out.
4267 string const tex_name =
4268 find_file(filename, path,
4269 known_tex_extensions);
4270 if (!tex_name.empty())
4271 filename = tex_name;
4273 bool external = false;
4275 if (makeAbsPath(filename, path).exists()) {
4276 string const abstexname =
4277 makeAbsPath(filename, path).absFileName();
4278 string const absfigname =
4279 changeExtension(abstexname, ".fig");
4280 fix_child_filename(filename);
4281 string const lyxname = changeExtension(filename,
4282 roundtripMode() ? ".lyx.lyx" : ".lyx");
4283 string const abslyxname = makeAbsPath(
4284 lyxname, getParentFilePath(false)).absFileName();
4286 if (!skipChildren())
4287 external = FileName(absfigname).exists();
4288 if (t.cs() == "input" && !skipChildren()) {
4289 string const ext = getExtension(abstexname);
4291 // Combined PS/LaTeX:
4292 // x.eps, x.pstex_t (old xfig)
4293 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4294 FileName const absepsname(
4295 changeExtension(abstexname, ".eps"));
4296 FileName const abspstexname(
4297 changeExtension(abstexname, ".pstex"));
4298 bool const xfigeps =
4299 (absepsname.exists() ||
4300 abspstexname.exists()) &&
4303 // Combined PDF/LaTeX:
4304 // x.pdf, x.pdftex_t (old xfig)
4305 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4306 FileName const abspdfname(
4307 changeExtension(abstexname, ".pdf"));
4308 bool const xfigpdf =
4309 abspdfname.exists() &&
4310 (ext == "pdftex_t" || ext == "pdf_t");
4314 // Combined PS/PDF/LaTeX:
4315 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4316 string const absbase2(
4317 removeExtension(abstexname) + "_pspdftex");
4318 FileName const abseps2name(
4319 addExtension(absbase2, ".eps"));
4320 FileName const abspdf2name(
4321 addExtension(absbase2, ".pdf"));
4322 bool const xfigboth =
4323 abspdf2name.exists() &&
4324 abseps2name.exists() && ext == "pspdftex";
4326 xfig = xfigpdf || xfigeps || xfigboth;
4327 external = external && xfig;
4330 outname = changeExtension(filename, ".fig");
4331 FileName abssrc(changeExtension(abstexname, ".fig"));
4332 copy_file(abssrc, outname);
4334 // Don't try to convert, the result
4335 // would be full of ERT.
4337 FileName abssrc(abstexname);
4338 copy_file(abssrc, outname);
4339 } else if (t.cs() != "verbatiminput" &&
4341 tex2lyx(abstexname, FileName(abslyxname),
4344 // no need to call copy_file
4345 // tex2lyx creates the file
4348 FileName abssrc(abstexname);
4349 copy_file(abssrc, outname);
4352 cerr << "Warning: Could not find included file '"
4353 << filename << "'." << endl;
4357 begin_inset(os, "External\n");
4358 os << "\ttemplate XFig\n"
4359 << "\tfilename " << outname << '\n';
4360 registerExternalTemplatePackages("XFig");
4362 begin_command_inset(os, "include", name);
4363 outname = subst(outname, "\"", "\\\"");
4364 os << "preview false\n"
4365 "filename \"" << outname << "\"\n";
4366 if (t.cs() == "verbatiminput")
4367 preamble.registerAutomaticallyLoadedPackage("verbatim");
4372 else if (t.cs() == "bibliographystyle") {
4373 // store new bibliographystyle
4374 bibliographystyle = p.verbatim_item();
4375 // If any other command than \bibliography, \addcontentsline
4376 // and \nocite{*} follows, we need to output the style
4377 // (because it might be used by that command).
4378 // Otherwise, it will automatically be output by LyX.
4381 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4382 if (t2.cat() == catBegin)
4384 if (t2.cat() != catEscape)
4386 if (t2.cs() == "nocite") {
4387 if (p.getArg('{', '}') == "*")
4389 } else if (t2.cs() == "bibliography")
4391 else if (t2.cs() == "phantomsection") {
4395 else if (t2.cs() == "addcontentsline") {
4396 // get the 3 arguments of \addcontentsline
4399 contentslineContent = p.getArg('{', '}');
4400 // if the last argument is not \refname we must output
4401 if (contentslineContent == "\\refname")
4408 output_ert_inset(os,
4409 "\\bibliographystyle{" + bibliographystyle + '}',
4414 else if (t.cs() == "phantomsection") {
4415 // we only support this if it occurs between
4416 // \bibliographystyle and \bibliography
4417 if (bibliographystyle.empty())
4418 output_ert_inset(os, "\\phantomsection", context);
4421 else if (t.cs() == "addcontentsline") {
4422 context.check_layout(os);
4423 // get the 3 arguments of \addcontentsline
4424 string const one = p.getArg('{', '}');
4425 string const two = p.getArg('{', '}');
4426 string const three = p.getArg('{', '}');
4427 // only if it is a \refname, we support if for the bibtex inset
4428 if (contentslineContent != "\\refname") {
4429 output_ert_inset(os,
4430 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4435 else if (t.cs() == "bibliography") {
4436 context.check_layout(os);
4438 begin_command_inset(os, "bibtex", "bibtex");
4439 if (!btprint.empty()) {
4440 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4441 // clear the string because the next BibTeX inset can be without the
4442 // \nocite{*} option
4445 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4446 // Do we have addcontentsline?
4447 if (contentslineContent == "\\refname") {
4448 BibOpts = "bibtotoc";
4449 // clear string because next BibTeX inset can be without addcontentsline
4450 contentslineContent.clear();
4452 // Do we have a bibliographystyle set?
4453 if (!bibliographystyle.empty()) {
4454 if (BibOpts.empty())
4455 BibOpts = normalize_filename(bibliographystyle);
4457 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4458 // clear it because each bibtex entry has its style
4459 // and we need an empty string to handle \phantomsection
4460 bibliographystyle.clear();
4462 os << "options " << '"' << BibOpts << '"' << "\n";
4466 else if (t.cs() == "parbox") {
4467 // Test whether this is an outer box of a shaded box
4469 // swallow arguments
4470 while (p.hasOpt()) {
4472 p.skip_spaces(true);
4475 p.skip_spaces(true);
4477 if (p.next_token().cat() == catBegin)
4479 p.skip_spaces(true);
4480 Token to = p.get_token();
4481 bool shaded = false;
4482 if (to.asInput() == "\\begin") {
4483 p.skip_spaces(true);
4484 if (p.getArg('{', '}') == "shaded")
4489 parse_outer_box(p, os, FLAG_ITEM, outer,
4490 context, "parbox", "shaded");
4492 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4493 "", "", t.cs(), "", "");
4496 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4497 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4498 t.cs() == "shadowbox" || t.cs() == "doublebox")
4499 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4501 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4502 string backgroundcolor;
4503 preamble.registerAutomaticallyLoadedPackage("xcolor");
4504 if (t.cs() == "fcolorbox") {
4505 string const framecolor = p.getArg('{', '}');
4506 backgroundcolor = p.getArg('{', '}');
4507 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4509 backgroundcolor = p.getArg('{', '}');
4510 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4514 // FIXME: due to the compiler limit of "if" nestings
4515 // the code for the alignment was put here
4516 // put them in their own if if this is fixed
4517 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4518 || t.cs() == "shadowsize"
4519 || t.cs() == "raggedleft" || t.cs() == "centering"
4520 || t.cs() == "raggedright") {
4521 if (t.cs() == "fboxrule")
4523 if (t.cs() == "fboxsep")
4525 if (t.cs() == "shadowsize")
4527 if (t.cs() != "raggedleft" && t.cs() != "centering"
4528 && t.cs() != "raggedright") {
4529 p.skip_spaces(true);
4530 while (p.good() && p.next_token().cat() != catSpace
4531 && p.next_token().cat() != catNewline
4532 && p.next_token().cat() != catEscape) {
4533 if (t.cs() == "fboxrule")
4534 fboxrule = fboxrule + p.get_token().asInput();
4535 if (t.cs() == "fboxsep")
4536 fboxsep = fboxsep + p.get_token().asInput();
4537 if (t.cs() == "shadowsize")
4538 shadow_size = shadow_size + p.get_token().asInput();
4541 output_ert_inset(os, t.asInput(), context);
4545 //\framebox() is part of the picture environment and different from \framebox{}
4546 //\framebox{} will be parsed by parse_outer_box
4547 else if (t.cs() == "framebox") {
4548 if (p.next_token().character() == '(') {
4549 //the syntax is: \framebox(x,y)[position]{content}
4550 string arg = t.asInput();
4551 arg += p.getFullParentheseArg();
4552 arg += p.getFullOpt();
4553 eat_whitespace(p, os, context, false);
4554 output_ert_inset(os, arg + '{', context);
4555 parse_text(p, os, FLAG_ITEM, outer, context);
4556 output_ert_inset(os, "}", context);
4558 //the syntax is: \framebox[width][position]{content}
4559 string special = p.getFullOpt();
4560 special += p.getOpt();
4561 parse_outer_box(p, os, FLAG_ITEM, outer,
4562 context, t.cs(), special);
4566 //\makebox() is part of the picture environment and different from \makebox{}
4567 //\makebox{} will be parsed by parse_box
4568 else if (t.cs() == "makebox") {
4569 if (p.next_token().character() == '(') {
4570 //the syntax is: \makebox(x,y)[position]{content}
4571 string arg = t.asInput();
4572 arg += p.getFullParentheseArg();
4573 arg += p.getFullOpt();
4574 eat_whitespace(p, os, context, false);
4575 output_ert_inset(os, arg + '{', context);
4576 parse_text(p, os, FLAG_ITEM, outer, context);
4577 output_ert_inset(os, "}", context);
4579 //the syntax is: \makebox[width][position]{content}
4580 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4581 "", "", t.cs(), "", "");
4584 else if (t.cs() == "smallskip" ||
4585 t.cs() == "medskip" ||
4586 t.cs() == "bigskip" ||
4587 t.cs() == "vfill") {
4588 context.check_layout(os);
4589 begin_inset(os, "VSpace ");
4592 skip_spaces_braces(p);
4595 else if ((where = is_known(t.cs(), known_spaces))) {
4596 context.check_layout(os);
4597 begin_inset(os, "space ");
4598 os << '\\' << known_coded_spaces[where - known_spaces]
4601 // LaTeX swallows whitespace after all spaces except
4602 // "\\,". We have to do that here, too, because LyX
4603 // adds "{}" which would make the spaces significant.
4605 eat_whitespace(p, os, context, false);
4606 // LyX adds "{}" after all spaces except "\\ " and
4607 // "\\,", so we have to remove "{}".
4608 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4609 // remove the braces after "\\,", too.
4614 else if (t.cs() == "newpage" ||
4615 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4616 t.cs() == "clearpage" ||
4617 t.cs() == "cleardoublepage") {
4618 context.check_layout(os);
4619 begin_inset(os, "Newpage ");
4622 skip_spaces_braces(p);
4625 else if (t.cs() == "DeclareRobustCommand" ||
4626 t.cs() == "DeclareRobustCommandx" ||
4627 t.cs() == "newcommand" ||
4628 t.cs() == "newcommandx" ||
4629 t.cs() == "providecommand" ||
4630 t.cs() == "providecommandx" ||
4631 t.cs() == "renewcommand" ||
4632 t.cs() == "renewcommandx") {
4633 // DeclareRobustCommand, DeclareRobustCommandx,
4634 // providecommand and providecommandx could be handled
4635 // by parse_command(), but we need to call
4636 // add_known_command() here.
4637 string name = t.asInput();
4638 if (p.next_token().asInput() == "*") {
4639 // Starred form. Eat '*'
4643 string const command = p.verbatim_item();
4644 string const opt1 = p.getFullOpt();
4645 string const opt2 = p.getFullOpt();
4646 add_known_command(command, opt1, !opt2.empty());
4647 string const ert = name + '{' + command + '}' +
4649 '{' + p.verbatim_item() + '}';
4651 if (t.cs() == "DeclareRobustCommand" ||
4652 t.cs() == "DeclareRobustCommandx" ||
4653 t.cs() == "providecommand" ||
4654 t.cs() == "providecommandx" ||
4655 name[name.length()-1] == '*')
4656 output_ert_inset(os, ert, context);
4658 context.check_layout(os);
4659 begin_inset(os, "FormulaMacro");
4665 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4666 // let could be handled by parse_command(),
4667 // but we need to call add_known_command() here.
4668 string ert = t.asInput();
4671 if (p.next_token().cat() == catBegin) {
4672 name = p.verbatim_item();
4673 ert += '{' + name + '}';
4675 name = p.verbatim_item();
4680 if (p.next_token().cat() == catBegin) {
4681 command = p.verbatim_item();
4682 ert += '{' + command + '}';
4684 command = p.verbatim_item();
4687 // If command is known, make name known too, to parse
4688 // its arguments correctly. For this reason we also
4689 // have commands in syntax.default that are hardcoded.
4690 CommandMap::iterator it = known_commands.find(command);
4691 if (it != known_commands.end())
4692 known_commands[t.asInput()] = it->second;
4693 output_ert_inset(os, ert, context);
4696 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4699 string name = t.asInput();
4700 string const length = p.verbatim_item();
4703 bool valid = splitLatexLength(length, valstring, unit);
4704 bool known_hspace = false;
4705 bool known_vspace = false;
4706 bool known_unit = false;
4709 istringstream iss(valstring);
4712 if (t.cs()[0] == 'h') {
4713 if (unit == "\\fill") {
4718 known_hspace = true;
4721 if (unit == "\\smallskipamount") {
4723 known_vspace = true;
4724 } else if (unit == "\\medskipamount") {
4726 known_vspace = true;
4727 } else if (unit == "\\bigskipamount") {
4729 known_vspace = true;
4730 } else if (unit == "\\fill") {
4732 known_vspace = true;
4736 if (!known_hspace && !known_vspace) {
4737 switch (unitFromString(unit)) {
4753 //unitFromString(unit) fails for relative units like Length::PCW
4754 // therefore handle them separately
4755 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4756 || unit == "\\textwidth" || unit == "\\linewidth"
4757 || unit == "\\textheight" || unit == "\\paperheight"
4758 || unit == "\\baselineskip")
4766 // check for glue lengths
4767 bool is_gluelength = false;
4768 string gluelength = length;
4769 string::size_type i = length.find(" minus");
4770 if (i == string::npos) {
4771 i = length.find(" plus");
4772 if (i != string::npos)
4773 is_gluelength = true;
4775 is_gluelength = true;
4776 // if yes transform "9xx minus 8yy plus 7zz"
4778 if (is_gluelength) {
4779 i = gluelength.find(" minus");
4780 if (i != string::npos)
4781 gluelength.replace(i, 7, "-");
4782 i = gluelength.find(" plus");
4783 if (i != string::npos)
4784 gluelength.replace(i, 6, "+");
4787 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4788 // Literal horizontal length or known variable
4789 context.check_layout(os);
4790 begin_inset(os, "space ");
4798 if (known_unit && !known_hspace)
4799 os << "\n\\length " << translate_len(length);
4801 os << "\n\\length " << gluelength;
4803 } else if (known_unit || known_vspace || is_gluelength) {
4804 // Literal vertical length or known variable
4805 context.check_layout(os);
4806 begin_inset(os, "VSpace ");
4809 if (known_unit && !known_vspace)
4810 os << translate_len(length);
4817 // LyX can't handle other length variables in Inset VSpace/space
4822 output_ert_inset(os, name + '{' + unit + '}', context);
4823 else if (value == -1.0)
4824 output_ert_inset(os, name + "{-" + unit + '}', context);
4826 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
4828 output_ert_inset(os, name + '{' + length + '}', context);
4832 // The single '=' is meant here.
4833 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
4837 context.check_layout(os);
4838 docstring name = newinsetlayout->name();
4839 bool const caption = name.find(from_ascii("Caption:")) == 0;
4841 // Already done for floating minted listings.
4842 if (minted_float.empty()) {
4843 begin_inset(os, "Caption ");
4844 os << to_utf8(name.substr(8)) << '\n';
4847 // FIXME: what do we do if the prefix is not Flex: ?
4848 if (prefixIs(name, from_ascii("Flex:")))
4850 begin_inset(os, "Flex ");
4851 os << to_utf8(name) << '\n'
4852 << "status collapsed\n";
4854 if (!minted_float.empty()) {
4855 parse_text_snippet(p, os, FLAG_ITEM, false, context);
4856 } else if (newinsetlayout->isPassThru()) {
4857 // set catcodes to verbatim early, just in case.
4858 p.setCatcodes(VERBATIM_CATCODES);
4859 string delim = p.get_token().asInput();
4861 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
4862 //FIXME: handle error condition
4863 string const arg = p.verbatimStuff("}").second;
4864 Context newcontext(true, context.textclass);
4865 if (newinsetlayout->forcePlainLayout())
4866 newcontext.layout = &context.textclass.plainLayout();
4867 output_ert(os, arg, newcontext);
4869 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4872 // Minted caption insets are not closed here because
4873 // we collect everything into the caption.
4874 if (minted_float.empty())
4878 else if (t.cs() == "includepdf") {
4880 string const arg = p.getArg('[', ']');
4881 map<string, string> opts;
4882 vector<string> keys;
4883 split_map(arg, opts, keys);
4884 string name = normalize_filename(p.verbatim_item());
4885 string const path = getMasterFilePath(true);
4886 // We want to preserve relative / absolute filenames,
4887 // therefore path is only used for testing
4888 if (!makeAbsPath(name, path).exists()) {
4889 // The file extension is probably missing.
4890 // Now try to find it out.
4891 char const * const pdfpages_format[] = {"pdf", 0};
4892 string const pdftex_name =
4893 find_file(name, path, pdfpages_format);
4894 if (!pdftex_name.empty()) {
4899 FileName const absname = makeAbsPath(name, path);
4900 if (absname.exists())
4902 fix_child_filename(name);
4903 copy_file(absname, name);
4905 cerr << "Warning: Could not find file '"
4906 << name << "'." << endl;
4908 context.check_layout(os);
4909 begin_inset(os, "External\n\ttemplate ");
4910 os << "PDFPages\n\tfilename "
4912 // parse the options
4913 if (opts.find("pages") != opts.end())
4914 os << "\textra LaTeX \"pages="
4915 << opts["pages"] << "\"\n";
4916 if (opts.find("angle") != opts.end())
4917 os << "\trotateAngle "
4918 << opts["angle"] << '\n';
4919 if (opts.find("origin") != opts.end()) {
4921 string const opt = opts["origin"];
4922 if (opt == "tl") ss << "topleft";
4923 if (opt == "bl") ss << "bottomleft";
4924 if (opt == "Bl") ss << "baselineleft";
4925 if (opt == "c") ss << "center";
4926 if (opt == "tc") ss << "topcenter";
4927 if (opt == "bc") ss << "bottomcenter";
4928 if (opt == "Bc") ss << "baselinecenter";
4929 if (opt == "tr") ss << "topright";
4930 if (opt == "br") ss << "bottomright";
4931 if (opt == "Br") ss << "baselineright";
4932 if (!ss.str().empty())
4933 os << "\trotateOrigin " << ss.str() << '\n';
4935 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4937 if (opts.find("width") != opts.end())
4939 << translate_len(opts["width"]) << '\n';
4940 if (opts.find("height") != opts.end())
4942 << translate_len(opts["height"]) << '\n';
4943 if (opts.find("keepaspectratio") != opts.end())
4944 os << "\tkeepAspectRatio\n";
4946 context.check_layout(os);
4947 registerExternalTemplatePackages("PDFPages");
4950 else if (t.cs() == "loadgame") {
4952 string name = normalize_filename(p.verbatim_item());
4953 string const path = getMasterFilePath(true);
4954 // We want to preserve relative / absolute filenames,
4955 // therefore path is only used for testing
4956 if (!makeAbsPath(name, path).exists()) {
4957 // The file extension is probably missing.
4958 // Now try to find it out.
4959 char const * const lyxskak_format[] = {"fen", 0};
4960 string const lyxskak_name =
4961 find_file(name, path, lyxskak_format);
4962 if (!lyxskak_name.empty())
4963 name = lyxskak_name;
4965 FileName const absname = makeAbsPath(name, path);
4966 if (absname.exists())
4968 fix_child_filename(name);
4969 copy_file(absname, name);
4971 cerr << "Warning: Could not find file '"
4972 << name << "'." << endl;
4973 context.check_layout(os);
4974 begin_inset(os, "External\n\ttemplate ");
4975 os << "ChessDiagram\n\tfilename "
4978 context.check_layout(os);
4979 // after a \loadgame follows a \showboard
4980 if (p.get_token().asInput() == "showboard")
4982 registerExternalTemplatePackages("ChessDiagram");
4986 // try to see whether the string is in unicodesymbols
4987 // Only use text mode commands, since we are in text mode here,
4988 // and math commands may be invalid (bug 6797)
4989 string name = t.asInput();
4990 // handle the dingbats, cyrillic and greek
4991 if (name == "\\ding" || name == "\\textcyr" ||
4992 (name == "\\textgreek" && !preamble.usePolyglossia()))
4993 name = name + '{' + p.getArg('{', '}') + '}';
4994 // handle the ifsym characters
4995 else if (name == "\\textifsymbol") {
4996 string const optif = p.getFullOpt();
4997 string const argif = p.getArg('{', '}');
4998 name = name + optif + '{' + argif + '}';
5000 // handle the \ascii characters
5001 // the case of \ascii within braces, as LyX outputs it, is already
5002 // handled for t.cat() == catBegin
5003 else if (name == "\\ascii") {
5004 // the code is "\asci\xxx"
5005 name = "{" + name + p.get_token().asInput() + "}";
5008 // handle some TIPA special characters
5009 else if (preamble.isPackageUsed("tipa")) {
5010 if (name == "\\s") {
5011 // fromLaTeXCommand() does not yet
5012 // recognize tipa short cuts
5013 name = "\\textsyllabic";
5014 } else if (name == "\\=" &&
5015 p.next_token().asInput() == "*") {
5016 // fromLaTeXCommand() does not yet
5017 // recognize tipa short cuts
5019 name = "\\textsubbar";
5020 } else if (name == "\\textdoublevertline") {
5021 // FIXME: This is not correct,
5022 // \textvertline is higher than \textbardbl
5023 name = "\\textbardbl";
5025 } else if (name == "\\!" ) {
5026 if (p.next_token().asInput() == "b") {
5027 p.get_token(); // eat 'b'
5030 } else if (p.next_token().asInput() == "d") {
5034 } else if (p.next_token().asInput() == "g") {
5038 } else if (p.next_token().asInput() == "G") {
5040 name = "\\texthtscg";
5042 } else if (p.next_token().asInput() == "j") {
5044 name = "\\texthtbardotlessj";
5046 } else if (p.next_token().asInput() == "o") {
5048 name = "\\textbullseye";
5051 } else if (name == "\\*" ) {
5052 if (p.next_token().asInput() == "k") {
5054 name = "\\textturnk";
5056 } else if (p.next_token().asInput() == "r") {
5057 p.get_token(); // eat 'b'
5058 name = "\\textturnr";
5060 } else if (p.next_token().asInput() == "t") {
5062 name = "\\textturnt";
5064 } else if (p.next_token().asInput() == "w") {
5066 name = "\\textturnw";
5071 if ((name.size() == 2 &&
5072 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5073 p.next_token().asInput() != "*") ||
5074 is_known(name.substr(1), known_tipa_marks)) {
5075 // name is a command that corresponds to a
5076 // combining character in unicodesymbols.
5077 // Append the argument, fromLaTeXCommand()
5078 // will either convert it to a single
5079 // character or a combining sequence.
5080 name += '{' + p.verbatim_item() + '}';
5082 // now get the character from unicodesymbols
5086 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5087 Encodings::TEXT_CMD, termination, rem, &req));
5089 context.check_layout(os);
5092 output_ert_inset(os, to_utf8(rem), context);
5094 skip_spaces_braces(p);
5095 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5096 preamble.registerAutomaticallyLoadedPackage(*it);
5098 //cerr << "#: " << t << " mode: " << mode << endl;
5099 // heuristic: read up to next non-nested space
5101 string s = t.asInput();
5102 string z = p.verbatim_item();
5103 while (p.good() && z != " " && !z.empty()) {
5104 //cerr << "read: " << z << endl;
5106 z = p.verbatim_item();
5108 cerr << "found ERT: " << s << endl;
5109 output_ert_inset(os, s + ' ', context);
5112 if (t.asInput() == name &&
5113 p.next_token().asInput() == "*") {
5114 // Starred commands like \vspace*{}
5115 p.get_token(); // Eat '*'
5118 if (!parse_command(name, p, os, outer, context))
5119 output_ert_inset(os, name, context);
5123 if (flags & FLAG_LEAVE) {
5124 flags &= ~FLAG_LEAVE;
5131 string guessLanguage(Parser & p, string const & lang)
5133 typedef std::map<std::string, size_t> LangMap;
5134 // map from language names to number of characters
5137 for (char const * const * i = supported_CJK_languages; *i; i++)
5138 used[string(*i)] = 0;
5141 Token const t = p.get_token();
5142 // comments are not counted for any language
5143 if (t.cat() == catComment)
5145 // commands are not counted as well, but we need to detect
5146 // \begin{CJK} and switch encoding if needed
5147 if (t.cat() == catEscape) {
5148 if (t.cs() == "inputencoding") {
5149 string const enc = subst(p.verbatim_item(), "\n", " ");
5150 p.setEncoding(enc, Encoding::inputenc);
5153 if (t.cs() != "begin")
5156 // Non-CJK content is counted for lang.
5157 // We do not care about the real language here:
5158 // If we have more non-CJK contents than CJK contents,
5159 // we simply use the language that was specified as
5160 // babel main language.
5161 used[lang] += t.asInput().length();
5164 // Now we are starting an environment
5166 string const name = p.getArg('{', '}');
5167 if (name != "CJK") {
5171 // It is a CJK environment
5173 /* name = */ p.getArg('{', '}');
5174 string const encoding = p.getArg('{', '}');
5175 /* mapping = */ p.getArg('{', '}');
5176 string const encoding_old = p.getEncoding();
5177 char const * const * const where =
5178 is_known(encoding, supported_CJK_encodings);
5180 p.setEncoding(encoding, Encoding::CJK);
5182 p.setEncoding("UTF-8");
5183 string const text = p.ertEnvironment("CJK");
5184 p.setEncoding(encoding_old);
5187 // ignore contents in unknown CJK encoding
5190 // the language of the text
5192 supported_CJK_languages[where - supported_CJK_encodings];
5193 used[cjk] += text.length();
5195 LangMap::const_iterator use = used.begin();
5196 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5197 if (it->second > use->second)