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 };
189 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
191 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
192 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
193 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
194 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
195 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
197 // Whether we need to insert a bibtex inset in a comment
198 bool need_commentbib = false;
200 /// LaTeX names for quotes
201 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
202 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
203 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
204 "guilsinglleft", "frq", "guilsinglright", 0};
206 /// the same as known_quotes with .lyx names
207 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
208 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
209 "gld", "grd", "gls", "ers", "fls",
210 "fls", "frs", "frs", 0};
212 /// LaTeX names for font sizes
213 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
214 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
216 /// the same as known_sizes with .lyx names
217 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
218 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
220 /// LaTeX 2.09 names for font families
221 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
223 /// LaTeX names for font families
224 char const * const known_font_families[] = { "rmfamily", "sffamily",
227 /// LaTeX names for font family changing commands
228 char const * const known_text_font_families[] = { "textrm", "textsf",
231 /// The same as known_old_font_families, known_font_families and
232 /// known_text_font_families with .lyx names
233 char const * const known_coded_font_families[] = { "roman", "sans",
236 /// LaTeX 2.09 names for font series
237 char const * const known_old_font_series[] = { "bf", 0};
239 /// LaTeX names for font series
240 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
242 /// LaTeX names for font series changing commands
243 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
245 /// The same as known_old_font_series, known_font_series and
246 /// known_text_font_series with .lyx names
247 char const * const known_coded_font_series[] = { "bold", "medium", 0};
249 /// LaTeX 2.09 names for font shapes
250 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
252 /// LaTeX names for font shapes
253 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
256 /// LaTeX names for font shape changing commands
257 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
260 /// The same as known_old_font_shapes, known_font_shapes and
261 /// known_text_font_shapes with .lyx names
262 char const * const known_coded_font_shapes[] = { "italic", "slanted",
263 "smallcaps", "up", 0};
265 /// Known special characters which need skip_spaces_braces() afterwards
266 char const * const known_special_chars[] = {"ldots",
267 "lyxarrow", "textcompwordmark",
268 "slash", "textasciitilde", "textasciicircum", "textbackslash",
269 "LyX", "TeX", "LaTeXe",
272 /// special characters from known_special_chars which may have a \\protect before
273 char const * const known_special_protect_chars[] = {"LyX", "TeX",
274 "LaTeXe", "LaTeX", 0};
276 /// the same as known_special_chars with .lyx names
277 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
278 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
279 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
280 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
281 "\\SpecialChar LaTeX\n", 0};
284 * Graphics file extensions known by the dvips driver of the graphics package.
285 * These extensions are used to complete the filename of an included
286 * graphics file if it does not contain an extension.
287 * The order must be the same that latex uses to find a file, because we
288 * will use the first extension that matches.
289 * This is only an approximation for the common cases. If we would want to
290 * do it right in all cases, we would need to know which graphics driver is
291 * used and know the extensions of every driver of the graphics package.
293 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
294 "ps.gz", "eps.Z", "ps.Z", 0};
297 * Graphics file extensions known by the pdftex driver of the graphics package.
298 * \sa known_dvips_graphics_formats
300 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
304 * Known file extensions for TeX files as used by \\include.
306 char const * const known_tex_extensions[] = {"tex", 0};
308 /// spaces known by InsetSpace
309 char const * const known_spaces[] = { " ", "space", ",",
310 "thinspace", "quad", "qquad", "enspace", "enskip",
311 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
312 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
313 "upbracefill", "downbracefill", 0};
315 /// the same as known_spaces with .lyx names
316 char const * const known_coded_spaces[] = { "space{}", "space{}",
317 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
318 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
319 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
320 "upbracefill{}", "downbracefill{}", 0};
322 /// known TIPA combining diacritical marks
323 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
324 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
325 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
326 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
327 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
328 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
329 "textsubring", "textsubbar", 0};
331 /// TIPA tones that need special handling
332 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
334 // string to store the float type to be able to determine the type of subfloats
335 string float_type = "";
337 // string to store the float status of minted listings
338 string minted_float = "";
340 // whether a caption has been parsed for a floating minted listing
341 bool minted_float_has_caption = false;
343 // The caption for non-floating minted listings
344 string minted_nonfloat_caption = "";
347 /// splits "x=z, y=b" into a map and an ordered keyword vector
348 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
353 keys.resize(v.size());
354 for (size_t i = 0; i < v.size(); ++i) {
355 size_t const pos = v[i].find('=');
356 string const index = trimSpaceAndEol(v[i].substr(0, pos));
357 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
365 * Split a LaTeX length into value and unit.
366 * The latter can be a real unit like "pt", or a latex length variable
367 * like "\textwidth". The unit may contain additional stuff like glue
368 * lengths, but we don't care, because such lengths are ERT anyway.
369 * \returns true if \p value and \p unit are valid.
371 bool splitLatexLength(string const & len, string & value, string & unit)
375 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
376 //'4,5' is a valid LaTeX length number. Change it to '4.5'
377 string const length = subst(len, ',', '.');
378 if (i == string::npos)
381 if (len[0] == '\\') {
382 // We had something like \textwidth without a factor
388 value = trimSpaceAndEol(string(length, 0, i));
392 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
393 if (contains(len, '\\'))
394 unit = trimSpaceAndEol(string(len, i));
396 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
401 /// A simple function to translate a latex length to something LyX can
402 /// understand. Not perfect, but rather best-effort.
403 bool translate_len(string const & length, string & valstring, string & unit)
405 if (!splitLatexLength(length, valstring, unit))
407 // LyX uses percent values
409 istringstream iss(valstring);
414 string const percentval = oss.str();
416 if (unit.empty() || unit[0] != '\\')
418 string::size_type const i = unit.find(' ');
419 string const endlen = (i == string::npos) ? string() : string(unit, i);
420 if (unit == "\\textwidth") {
421 valstring = percentval;
422 unit = "text%" + endlen;
423 } else if (unit == "\\columnwidth") {
424 valstring = percentval;
425 unit = "col%" + endlen;
426 } else if (unit == "\\paperwidth") {
427 valstring = percentval;
428 unit = "page%" + endlen;
429 } else if (unit == "\\linewidth") {
430 valstring = percentval;
431 unit = "line%" + endlen;
432 } else if (unit == "\\paperheight") {
433 valstring = percentval;
434 unit = "pheight%" + endlen;
435 } else if (unit == "\\textheight") {
436 valstring = percentval;
437 unit = "theight%" + endlen;
438 } else if (unit == "\\baselineskip") {
439 valstring = percentval;
440 unit = "baselineskip%" + endlen;
448 string translate_len(string const & length)
452 if (translate_len(length, value, unit))
454 // If the input is invalid, return what we have.
462 * Translates a LaTeX length into \p value, \p unit and
463 * \p special parts suitable for a box inset.
464 * The difference from translate_len() is that a box inset knows about
465 * some special "units" that are stored in \p special.
467 void translate_box_len(string const & length, string & value, string & unit, string & special)
469 if (translate_len(length, value, unit)) {
470 if (unit == "\\height" || unit == "\\depth" ||
471 unit == "\\totalheight" || unit == "\\width") {
472 special = unit.substr(1);
473 // The unit is not used, but LyX requires a dummy setting
486 * Find a file with basename \p name in path \p path and an extension
489 string find_file(string const & name, string const & path,
490 char const * const * extensions)
492 for (char const * const * what = extensions; *what; ++what) {
493 string const trial = addExtension(name, *what);
494 if (makeAbsPath(trial, path).exists())
501 void begin_inset(ostream & os, string const & name)
503 os << "\n\\begin_inset " << name;
507 void begin_command_inset(ostream & os, string const & name,
508 string const & latexname)
510 begin_inset(os, "CommandInset ");
511 os << name << "\nLatexCommand " << latexname << '\n';
515 void end_inset(ostream & os)
517 os << "\n\\end_inset\n\n";
521 bool skip_braces(Parser & p)
523 if (p.next_token().cat() != catBegin)
526 if (p.next_token().cat() == catEnd) {
535 /// replace LaTeX commands in \p s from the unicodesymbols file with their
537 docstring convert_unicodesymbols(docstring s)
540 for (size_t i = 0; i < s.size();) {
549 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
550 Encodings::TEXT_CMD, termination, rem, &req));
551 set<string>::const_iterator it = req.begin();
552 set<string>::const_iterator en = req.end();
553 for (; it != en; ++it)
554 preamble.registerAutomaticallyLoadedPackage(*it);
557 if (s.empty() || s[0] != '\\')
566 /// try to convert \p s to a valid InsetCommand argument
567 string convert_command_inset_arg(string s)
570 // since we don't know the input encoding we can't use from_utf8
571 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
572 // LyX cannot handle newlines in a latex command
573 return subst(s, "\n", " ");
577 void output_ert(ostream & os, string const & s, Context & context)
579 context.check_layout(os);
580 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
582 os << "\n\\backslash\n";
583 else if (*it == '\n') {
584 context.new_paragraph(os);
585 context.check_layout(os);
589 context.check_end_layout(os);
593 void output_ert_inset(ostream & os, string const & s, Context & context)
595 // We must have a valid layout before outputting the ERT inset.
596 context.check_layout(os);
597 Context newcontext(true, context.textclass);
598 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
599 if (layout.forcePlainLayout())
600 newcontext.layout = &context.textclass.plainLayout();
601 begin_inset(os, "ERT");
602 os << "\nstatus collapsed\n";
603 output_ert(os, s, newcontext);
608 void output_comment(Parser & p, ostream & os, string const & s,
611 if (p.next_token().cat() == catNewline)
612 output_ert_inset(os, '%' + s, context);
614 output_ert_inset(os, '%' + s + '\n', context);
618 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
620 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
623 if (checkModule(name, command))
624 return findLayoutWithoutModule(textclass, name, command);
629 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
631 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
634 if (checkModule(name, command))
635 return findInsetLayoutWithoutModule(textclass, name, command);
640 void eat_whitespace(Parser &, ostream &, Context &, bool);
644 * Skips whitespace and braces.
645 * This should be called after a command has been parsed that is not put into
646 * ERT, and where LyX adds "{}" if needed.
648 void skip_spaces_braces(Parser & p, bool keepws = false)
650 /* The following four examples produce the same typeset output and
651 should be handled by this function:
659 // Unfortunately we need to skip comments, too.
660 // We can't use eat_whitespace since writing them after the {}
661 // results in different output in some cases.
662 bool const skipped_spaces = p.skip_spaces(true);
663 bool const skipped_braces = skip_braces(p);
664 if (keepws && skipped_spaces && !skipped_braces)
665 // put back the space (it is better handled by check_space)
666 p.unskip_spaces(true);
670 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
671 Context & context, Layout::LaTeXArgMap const & latexargs)
674 context.check_layout(os);
679 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
680 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
681 for (; lait != laend; ++lait) {
683 eat_whitespace(p, os, context, false);
684 if (lait->second.mandatory) {
685 if (p.next_token().cat() != catBegin)
687 p.get_token(); // eat '{'
689 context.check_layout(os);
692 begin_inset(os, "Argument ");
695 os << i << "\nstatus collapsed\n\n";
696 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
699 if (p.next_token().cat() == catEscape ||
700 p.next_token().character() != '[')
702 p.get_token(); // eat '['
704 context.check_layout(os);
707 begin_inset(os, "Argument ");
710 os << i << "\nstatus collapsed\n\n";
711 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
714 eat_whitespace(p, os, context, false);
719 void output_command_layout(ostream & os, Parser & p, bool outer,
720 Context & parent_context,
721 Layout const * newlayout)
723 TeXFont const oldFont = parent_context.font;
724 // save the current font size
725 string const size = oldFont.size;
726 // reset the font size to default, because the font size switches
727 // don't affect section headings and the like
728 parent_context.font.size = Context::normalfont.size;
729 // we only need to write the font change if we have an open layout
730 if (!parent_context.atParagraphStart())
731 output_font_change(os, oldFont, parent_context.font);
732 parent_context.check_end_layout(os);
733 Context context(true, parent_context.textclass, newlayout,
734 parent_context.layout, parent_context.font);
735 if (parent_context.deeper_paragraph) {
736 // We are beginning a nested environment after a
737 // deeper paragraph inside the outer list environment.
738 // Therefore we don't need to output a "begin deeper".
739 context.need_end_deeper = true;
741 context.check_deeper(os);
742 output_arguments(os, p, outer, true, false, context,
743 context.layout->latexargs());
744 parse_text(p, os, FLAG_ITEM, outer, context);
745 output_arguments(os, p, outer, false, true, context,
746 context.layout->postcommandargs());
747 context.check_end_layout(os);
748 if (parent_context.deeper_paragraph) {
749 // We must suppress the "end deeper" because we
750 // suppressed the "begin deeper" above.
751 context.need_end_deeper = false;
753 context.check_end_deeper(os);
754 // We don't need really a new paragraph, but
755 // we must make sure that the next item gets a \begin_layout.
756 parent_context.new_paragraph(os);
757 // Set the font size to the original value. No need to output it here
758 // (Context::begin_layout() will do that if needed)
759 parent_context.font.size = size;
764 * Output a space if necessary.
765 * This function gets called for every whitespace token.
767 * We have three cases here:
768 * 1. A space must be suppressed. Example: The lyxcode case below
769 * 2. A space may be suppressed. Example: Spaces before "\par"
770 * 3. A space must not be suppressed. Example: A space between two words
772 * We currently handle only 1. and 3 and from 2. only the case of
773 * spaces before newlines as a side effect.
775 * 2. could be used to suppress as many spaces as possible. This has two effects:
776 * - Reimporting LyX generated LaTeX files changes almost no whitespace
777 * - Superflous whitespace from non LyX generated LaTeX files is removed.
778 * The drawback is that the logic inside the function becomes
779 * complicated, and that is the reason why it is not implemented.
781 void check_space(Parser & p, ostream & os, Context & context)
783 Token const next = p.next_token();
784 Token const curr = p.curr_token();
785 // A space before a single newline and vice versa must be ignored
786 // LyX emits a newline before \end{lyxcode}.
787 // This newline must be ignored,
788 // otherwise LyX will add an additional protected space.
789 if (next.cat() == catSpace ||
790 next.cat() == catNewline ||
791 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
794 context.check_layout(os);
800 * Parse all arguments of \p command
802 void parse_arguments(string const & command,
803 vector<ArgumentType> const & template_arguments,
804 Parser & p, ostream & os, bool outer, Context & context)
806 string ert = command;
807 size_t no_arguments = template_arguments.size();
808 for (size_t i = 0; i < no_arguments; ++i) {
809 switch (template_arguments[i]) {
812 // This argument contains regular LaTeX
813 output_ert_inset(os, ert + '{', context);
814 eat_whitespace(p, os, context, false);
815 if (template_arguments[i] == required)
816 parse_text(p, os, FLAG_ITEM, outer, context);
818 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
822 // This argument consists only of a single item.
823 // The presence of '{' or not must be preserved.
825 if (p.next_token().cat() == catBegin)
826 ert += '{' + p.verbatim_item() + '}';
828 ert += p.verbatim_item();
832 // This argument may contain special characters
833 ert += '{' + p.verbatim_item() + '}';
837 // true because we must not eat whitespace
838 // if an optional arg follows we must not strip the
839 // brackets from this one
840 if (i < no_arguments - 1 &&
841 template_arguments[i+1] == optional)
842 ert += p.getFullOpt(true);
844 ert += p.getOpt(true);
848 output_ert_inset(os, ert, context);
853 * Check whether \p command is a known command. If yes,
854 * handle the command with all arguments.
855 * \return true if the command was parsed, false otherwise.
857 bool parse_command(string const & command, Parser & p, ostream & os,
858 bool outer, Context & context)
860 if (known_commands.find(command) != known_commands.end()) {
861 parse_arguments(command, known_commands[command], p, os,
869 /// Parses a minipage or parbox
870 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
871 unsigned inner_flags, bool outer, Context & parent_context,
872 string const & outer_type, string const & special,
873 string inner_type, string const & frame_color,
874 string const & background_color)
878 string hor_pos = "l";
879 // We need to set the height to the LaTeX default of 1\\totalheight
880 // for the case when no height argument is given
881 string height_value = "1";
882 string height_unit = "in";
883 string height_special = "totalheight";
888 string width_special = "none";
889 string thickness = "0.4pt";
890 if (!fboxrule.empty())
891 thickness = fboxrule;
895 if (!fboxsep.empty())
896 separation = fboxsep;
900 if (!shadow_size.empty())
901 shadowsize = shadow_size;
904 string framecolor = "black";
905 string backgroundcolor = "none";
906 if (!frame_color.empty())
907 framecolor = frame_color;
908 if (!background_color.empty())
909 backgroundcolor = background_color;
910 // if there is a color box around the \begin statements have not yet been parsed
912 if (!frame_color.empty() || !background_color.empty()) {
913 eat_whitespace(p, os, parent_context, false);
914 p.get_token().asInput(); // the '{'
916 if (p.next_token().asInput() == "\\begin") {
917 p.get_token().asInput();
919 inner_type = "minipage";
920 inner_flags = FLAG_END;
921 active_environments.push_back("minipage");
924 else if (p.next_token().asInput() == "\\parbox") {
925 p.get_token().asInput();
926 inner_type = "parbox";
927 inner_flags = FLAG_ITEM;
930 else if (p.next_token().asInput() == "\\makebox") {
931 p.get_token().asInput();
932 inner_type = "makebox";
933 inner_flags = FLAG_ITEM;
935 // in case there is just \colorbox{color}{text}
938 inner_type = "makebox";
939 inner_flags = FLAG_BRACE_LAST;
944 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
946 if (!inner_type.empty() && p.hasOpt()) {
947 if (inner_type != "makebox")
948 position = p.getArg('[', ']');
950 latex_width = p.getArg('[', ']');
951 translate_box_len(latex_width, width_value, width_unit, width_special);
954 if (position != "t" && position != "c" && position != "b") {
955 cerr << "invalid position " << position << " for "
956 << inner_type << endl;
960 if (inner_type != "makebox") {
961 latex_height = p.getArg('[', ']');
962 translate_box_len(latex_height, height_value, height_unit, height_special);
964 string const opt = p.getArg('[', ']');
967 if (hor_pos != "l" && hor_pos != "c" &&
968 hor_pos != "r" && hor_pos != "s") {
969 cerr << "invalid hor_pos " << hor_pos
970 << " for " << inner_type << endl;
977 inner_pos = p.getArg('[', ']');
978 if (inner_pos != "c" && inner_pos != "t" &&
979 inner_pos != "b" && inner_pos != "s") {
980 cerr << "invalid inner_pos "
981 << inner_pos << " for "
982 << inner_type << endl;
983 inner_pos = position;
987 if (inner_type == "makebox")
991 if (inner_type.empty()) {
992 if (special.empty() && outer_type != "framebox")
993 latex_width = "1\\columnwidth";
996 latex_width = p2.getArg('[', ']');
997 string const opt = p2.getArg('[', ']');
1000 if (hor_pos != "l" && hor_pos != "c" &&
1001 hor_pos != "r" && hor_pos != "s") {
1002 cerr << "invalid hor_pos " << hor_pos
1003 << " for " << outer_type << endl;
1007 if (outer_type == "framebox")
1011 } else if (inner_type != "makebox")
1012 latex_width = p.verbatim_item();
1013 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1014 // as this is LyX's standard for such cases (except for makebox)
1015 // \framebox is more special and handled below
1016 if (latex_width.empty() && inner_type != "makebox"
1017 && outer_type != "framebox")
1018 latex_width = "1\\columnwidth";
1020 translate_len(latex_width, width_value, width_unit);
1022 bool shadedparbox = false;
1023 if (inner_type == "shaded") {
1024 eat_whitespace(p, os, parent_context, false);
1025 if (outer_type == "parbox") {
1027 if (p.next_token().cat() == catBegin)
1029 eat_whitespace(p, os, parent_context, false);
1030 shadedparbox = true;
1035 // If we already read the inner box we have to push the inner env
1036 if (!outer_type.empty() && !inner_type.empty() &&
1037 (inner_flags & FLAG_END))
1038 active_environments.push_back(inner_type);
1039 bool use_ert = false;
1040 if (!outer_type.empty() && !inner_type.empty()) {
1041 // Look whether there is some content after the end of the
1042 // inner box, but before the end of the outer box.
1043 // If yes, we need to output ERT.
1045 if (inner_flags & FLAG_END)
1046 p.ertEnvironment(inner_type);
1049 p.skip_spaces(true);
1050 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1051 if ((outer_env && p.next_token().asInput() != "\\end") ||
1052 (!outer_env && p.next_token().cat() != catEnd)) {
1053 // something is between the end of the inner box and
1054 // the end of the outer box, so we need to use ERT.
1062 if (!outer_type.empty()) {
1063 if (outer_flags & FLAG_END)
1064 ss << "\\begin{" << outer_type << '}';
1066 ss << '\\' << outer_type << '{';
1067 if (!special.empty())
1071 if (!inner_type.empty()) {
1072 if (inner_type != "shaded") {
1073 if (inner_flags & FLAG_END)
1074 ss << "\\begin{" << inner_type << '}';
1076 ss << '\\' << inner_type;
1078 if (!position.empty())
1079 ss << '[' << position << ']';
1080 if (!latex_height.empty())
1081 ss << '[' << latex_height << ']';
1082 if (!inner_pos.empty())
1083 ss << '[' << inner_pos << ']';
1084 ss << '{' << latex_width << '}';
1085 if (!(inner_flags & FLAG_END))
1088 if (inner_type == "shaded")
1089 ss << "\\begin{shaded}";
1090 output_ert_inset(os, ss.str(), parent_context);
1091 if (!inner_type.empty()) {
1092 parse_text(p, os, inner_flags, outer, parent_context);
1093 if (inner_flags & FLAG_END)
1094 output_ert_inset(os, "\\end{" + inner_type + '}',
1097 output_ert_inset(os, "}", parent_context);
1099 if (!outer_type.empty()) {
1100 // If we already read the inner box we have to pop
1102 if (!inner_type.empty() && (inner_flags & FLAG_END))
1103 active_environments.pop_back();
1105 // Ensure that the end of the outer box is parsed correctly:
1106 // The opening brace has been eaten by parse_outer_box()
1107 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1108 outer_flags &= ~FLAG_ITEM;
1109 outer_flags |= FLAG_BRACE_LAST;
1111 parse_text(p, os, outer_flags, outer, parent_context);
1112 if (outer_flags & FLAG_END)
1113 output_ert_inset(os, "\\end{" + outer_type + '}',
1116 output_ert_inset(os, "}", parent_context);
1119 // LyX does not like empty positions, so we have
1120 // to set them to the LaTeX default values here.
1121 if (position.empty())
1123 if (inner_pos.empty())
1124 inner_pos = position;
1125 parent_context.check_layout(os);
1126 begin_inset(os, "Box ");
1127 if (outer_type == "framed")
1129 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1131 else if (outer_type == "shadowbox")
1132 os << "Shadowbox\n";
1133 else if ((outer_type == "shaded" && inner_type.empty()) ||
1134 (outer_type == "minipage" && inner_type == "shaded") ||
1135 (outer_type == "parbox" && inner_type == "shaded")) {
1137 preamble.registerAutomaticallyLoadedPackage("color");
1138 } else if (outer_type == "doublebox")
1139 os << "Doublebox\n";
1140 else if (outer_type.empty() || outer_type == "mbox")
1141 os << "Frameless\n";
1143 os << outer_type << '\n';
1144 os << "position \"" << position << "\"\n";
1145 os << "hor_pos \"" << hor_pos << "\"\n";
1146 if (outer_type == "mbox")
1147 os << "has_inner_box 1\n";
1148 else if (!frame_color.empty() && inner_type == "makebox")
1149 os << "has_inner_box 0\n";
1151 os << "has_inner_box " << !inner_type.empty() << "\n";
1152 os << "inner_pos \"" << inner_pos << "\"\n";
1153 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1155 if (outer_type == "mbox")
1156 os << "use_makebox 1\n";
1157 else if (!frame_color.empty())
1158 os << "use_makebox 0\n";
1160 os << "use_makebox " << (inner_type == "makebox") << '\n';
1161 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1162 os << "width \"\"\n";
1163 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1164 else if (contains(width_unit, '\\'))
1165 os << "width \"" << width_value << "in" << "\"\n";
1167 os << "width \"" << width_value << width_unit << "\"\n";
1168 if (contains(width_unit, '\\')) {
1169 width_unit.erase (0,1); // remove the leading '\'
1170 os << "special \"" << width_unit << "\"\n";
1172 os << "special \"" << width_special << "\"\n";
1173 if (contains(height_unit, '\\'))
1174 os << "height \"" << height_value << "in" << "\"\n";
1176 os << "height \"" << height_value << height_unit << "\"\n";
1177 os << "height_special \"" << height_special << "\"\n";
1178 os << "thickness \"" << thickness << "\"\n";
1179 os << "separation \"" << separation << "\"\n";
1180 os << "shadowsize \"" << shadowsize << "\"\n";
1181 os << "framecolor \"" << framecolor << "\"\n";
1182 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1183 os << "status open\n\n";
1185 // Unfortunately we can't use parse_text_in_inset:
1186 // InsetBox::forcePlainLayout() is hard coded and does not
1187 // use the inset layout. Apart from that do we call parse_text
1188 // up to two times, but need only one check_end_layout.
1189 bool const forcePlainLayout =
1190 (!inner_type.empty() || inner_type == "makebox") &&
1191 outer_type != "shaded" && outer_type != "framed";
1192 Context context(true, parent_context.textclass);
1193 if (forcePlainLayout)
1194 context.layout = &context.textclass.plainLayout();
1196 context.font = parent_context.font;
1198 // If we have no inner box the contents will be read with the outer box
1199 if (!inner_type.empty())
1200 parse_text(p, os, inner_flags, outer, context);
1202 // Ensure that the end of the outer box is parsed correctly:
1203 // The opening brace has been eaten by parse_outer_box()
1204 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1205 outer_flags &= ~FLAG_ITEM;
1206 outer_flags |= FLAG_BRACE_LAST;
1209 // Find end of outer box, output contents if inner_type is
1210 // empty and output possible comments
1211 if (!outer_type.empty()) {
1212 // If we already read the inner box we have to pop
1214 if (!inner_type.empty() && (inner_flags & FLAG_END))
1215 active_environments.pop_back();
1216 // This does not output anything but comments if
1217 // inner_type is not empty (see use_ert)
1218 parse_text(p, os, outer_flags, outer, context);
1221 context.check_end_layout(os);
1223 #ifdef PRESERVE_LAYOUT
1224 // LyX puts a % after the end of the minipage
1225 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1227 //output_comment(p, os, "dummy", parent_context);
1230 parent_context.new_paragraph(os);
1232 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1233 //output_comment(p, os, "dummy", parent_context);
1236 // We add a protected space if something real follows
1237 if (p.good() && p.next_token().cat() != catComment) {
1238 begin_inset(os, "space ~\n");
1244 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1245 active_environments.pop_back();
1246 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1247 // in this case we have to eat the the closing brace of the color box
1248 p.get_token().asInput(); // the '}'
1250 if (p.next_token().asInput() == "}") {
1251 // in this case we assume that the closing brace is from the box settings
1252 // therefore reset these values for the next box
1258 // all boxes except of Frameless and Shaded require calc
1259 if (!(outer_type.empty() || outer_type == "mbox") &&
1260 !((outer_type == "shaded" && inner_type.empty()) ||
1261 (outer_type == "minipage" && inner_type == "shaded") ||
1262 (outer_type == "parbox" && inner_type == "shaded")))
1263 preamble.registerAutomaticallyLoadedPackage("calc");
1267 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1268 Context & parent_context, string const & outer_type,
1269 string const & special)
1271 eat_whitespace(p, os, parent_context, false);
1272 if (flags & FLAG_ITEM) {
1274 if (p.next_token().cat() == catBegin)
1277 cerr << "Warning: Ignoring missing '{' after \\"
1278 << outer_type << '.' << endl;
1279 eat_whitespace(p, os, parent_context, false);
1282 unsigned int inner_flags = 0;
1284 if (outer_type == "minipage" || outer_type == "parbox") {
1285 p.skip_spaces(true);
1286 while (p.hasOpt()) {
1288 p.skip_spaces(true);
1291 p.skip_spaces(true);
1292 if (outer_type == "parbox") {
1294 if (p.next_token().cat() == catBegin)
1296 p.skip_spaces(true);
1299 if (outer_type == "shaded" || outer_type == "mbox") {
1300 // These boxes never have an inner box
1302 } else if (p.next_token().asInput() == "\\parbox") {
1303 inner = p.get_token().cs();
1304 inner_flags = FLAG_ITEM;
1305 } else if (p.next_token().asInput() == "\\begin") {
1306 // Is this a minipage or shaded box?
1309 inner = p.getArg('{', '}');
1311 if (inner == "minipage" || inner == "shaded")
1312 inner_flags = FLAG_END;
1317 if (inner_flags == FLAG_END) {
1318 if (inner != "shaded")
1322 eat_whitespace(p, os, parent_context, false);
1324 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1325 outer_type, special, inner, "", "");
1327 if (inner_flags == FLAG_ITEM) {
1329 eat_whitespace(p, os, parent_context, false);
1331 parse_box(p, os, flags, inner_flags, outer, parent_context,
1332 outer_type, special, inner, "", "");
1337 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1338 bool in_line, bool use_minted)
1340 parent_context.check_layout(os);
1341 begin_inset(os, "listings\n");
1342 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1344 while ((i = arg.find(", ")) != string::npos
1345 || (i = arg.find(",\t")) != string::npos)
1346 arg.erase(i + 1, 1);
1349 string const language = p.getArg('{', '}');
1350 p.skip_spaces(true);
1351 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1352 if (!minted_float.empty()) {
1353 arg += string(arg.empty() ? "" : ",") + minted_float;
1354 minted_nonfloat_caption.clear();
1358 os << "lstparams " << '"' << arg << '"' << '\n';
1359 if (arg.find("\\color") != string::npos)
1360 preamble.registerAutomaticallyLoadedPackage("color");
1363 os << "inline true\n";
1365 os << "inline false\n";
1366 os << "status collapsed\n";
1367 Context context(true, parent_context.textclass);
1368 context.layout = &parent_context.textclass.plainLayout();
1369 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1370 minted_nonfloat_caption.erase(0,3);
1371 os << "\n\\begin_layout Plain Layout\n";
1372 begin_inset(os, "Caption Standard\n");
1373 Context newcontext(true, context.textclass,
1374 context.layout, 0, context.font);
1375 newcontext.check_layout(os);
1376 os << minted_nonfloat_caption << "\n";
1377 newcontext.check_end_layout(os);
1379 os << "\n\\end_layout\n";
1380 minted_nonfloat_caption.clear();
1384 // set catcodes to verbatim early, just in case.
1385 p.setCatcodes(VERBATIM_CATCODES);
1386 string delim = p.get_token().asInput();
1387 //FIXME: handler error condition
1388 s = p.verbatimStuff(delim).second;
1389 // context.new_paragraph(os);
1390 } else if (use_minted) {
1391 s = p.verbatimEnvironment("minted");
1393 s = p.verbatimEnvironment("lstlisting");
1395 output_ert(os, s, context);
1396 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1397 minted_nonfloat_caption.erase(0,3);
1398 os << "\n\\begin_layout Plain Layout\n";
1399 begin_inset(os, "Caption Standard\n");
1400 Context newcontext(true, context.textclass,
1401 context.layout, 0, context.font);
1402 newcontext.check_layout(os);
1403 os << minted_nonfloat_caption << "\n";
1404 newcontext.check_end_layout(os);
1406 os << "\n\\end_layout\n";
1407 minted_nonfloat_caption.clear();
1409 // Don't close the inset here for floating minted listings.
1410 // It will be closed at the end of the listing environment.
1411 if (!use_minted || minted_float.empty())
1414 eat_whitespace(p, os, parent_context, true);
1415 Token t = p.get_token();
1416 if (t.asInput() != "\\end") {
1417 // If anything follows, collect it into a caption.
1418 minted_float_has_caption = true;
1419 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1420 begin_inset(os, "Caption Standard\n");
1421 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1428 /// parse an unknown environment
1429 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1430 unsigned flags, bool outer,
1431 Context & parent_context)
1433 if (name == "tabbing")
1434 // We need to remember that we have to handle '\=' specially
1435 flags |= FLAG_TABBING;
1437 // We need to translate font changes and paragraphs inside the
1438 // environment to ERT if we have a non standard font.
1439 // Otherwise things like
1440 // \large\begin{foo}\huge bar\end{foo}
1442 bool const specialfont =
1443 (parent_context.font != parent_context.normalfont);
1444 bool const new_layout_allowed = parent_context.new_layout_allowed;
1446 parent_context.new_layout_allowed = false;
1447 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1448 parse_text_snippet(p, os, flags, outer, parent_context);
1449 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1451 parent_context.new_layout_allowed = new_layout_allowed;
1455 void parse_environment(Parser & p, ostream & os, bool outer,
1456 string & last_env, Context & parent_context)
1458 Layout const * newlayout;
1459 InsetLayout const * newinsetlayout = 0;
1460 string const name = p.getArg('{', '}');
1461 const bool is_starred = suffixIs(name, '*');
1462 string const unstarred_name = rtrim(name, "*");
1463 active_environments.push_back(name);
1465 if (is_math_env(name)) {
1466 parent_context.check_layout(os);
1467 begin_inset(os, "Formula ");
1468 os << "\\begin{" << name << "}";
1469 parse_math(p, os, FLAG_END, MATH_MODE);
1470 os << "\\end{" << name << "}";
1472 if (is_display_math_env(name)) {
1473 // Prevent the conversion of a line break to a space
1474 // (bug 7668). This does not change the output, but
1475 // looks ugly in LyX.
1476 eat_whitespace(p, os, parent_context, false);
1480 else if (is_known(name, preamble.polyglossia_languages)) {
1481 // We must begin a new paragraph if not already done
1482 if (! parent_context.atParagraphStart()) {
1483 parent_context.check_end_layout(os);
1484 parent_context.new_paragraph(os);
1486 // save the language in the context so that it is
1487 // handled by parse_text
1488 parent_context.font.language = preamble.polyglossia2lyx(name);
1489 parse_text(p, os, FLAG_END, outer, parent_context);
1490 // Just in case the environment is empty
1491 parent_context.extra_stuff.erase();
1492 // We must begin a new paragraph to reset the language
1493 parent_context.new_paragraph(os);
1497 else if (unstarred_name == "tabular" || name == "longtable") {
1498 eat_whitespace(p, os, parent_context, false);
1499 string width = "0pt";
1500 if (name == "tabular*") {
1501 width = lyx::translate_len(p.getArg('{', '}'));
1502 eat_whitespace(p, os, parent_context, false);
1504 parent_context.check_layout(os);
1505 begin_inset(os, "Tabular ");
1506 handle_tabular(p, os, name, width, parent_context);
1511 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1512 eat_whitespace(p, os, parent_context, false);
1513 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1514 eat_whitespace(p, os, parent_context, false);
1515 parent_context.check_layout(os);
1516 begin_inset(os, "Float " + unstarred_name + "\n");
1517 // store the float type for subfloats
1518 // subfloats only work with figures and tables
1519 if (unstarred_name == "figure")
1520 float_type = unstarred_name;
1521 else if (unstarred_name == "table")
1522 float_type = unstarred_name;
1526 os << "placement " << opt << '\n';
1527 if (contains(opt, "H"))
1528 preamble.registerAutomaticallyLoadedPackage("float");
1530 Floating const & fl = parent_context.textclass.floats()
1531 .getType(unstarred_name);
1532 if (!fl.floattype().empty() && fl.usesFloatPkg())
1533 preamble.registerAutomaticallyLoadedPackage("float");
1536 os << "wide " << convert<string>(is_starred)
1537 << "\nsideways false"
1538 << "\nstatus open\n\n";
1539 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1541 // We don't need really a new paragraph, but
1542 // we must make sure that the next item gets a \begin_layout.
1543 parent_context.new_paragraph(os);
1545 // the float is parsed thus delete the type
1549 else if (unstarred_name == "sidewaysfigure"
1550 || unstarred_name == "sidewaystable"
1551 || unstarred_name == "sidewaysalgorithm") {
1552 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1553 eat_whitespace(p, os, parent_context, false);
1554 parent_context.check_layout(os);
1555 if (unstarred_name == "sidewaysfigure")
1556 begin_inset(os, "Float figure\n");
1557 else if (unstarred_name == "sidewaystable")
1558 begin_inset(os, "Float table\n");
1559 else if (unstarred_name == "sidewaysalgorithm")
1560 begin_inset(os, "Float algorithm\n");
1562 os << "placement " << opt << '\n';
1563 if (contains(opt, "H"))
1564 preamble.registerAutomaticallyLoadedPackage("float");
1565 os << "wide " << convert<string>(is_starred)
1566 << "\nsideways true"
1567 << "\nstatus open\n\n";
1568 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1570 // We don't need really a new paragraph, but
1571 // we must make sure that the next item gets a \begin_layout.
1572 parent_context.new_paragraph(os);
1574 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1577 else if (name == "wrapfigure" || name == "wraptable") {
1578 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1579 eat_whitespace(p, os, parent_context, false);
1580 parent_context.check_layout(os);
1583 string overhang = "0col%";
1586 lines = p.getArg('[', ']');
1587 string const placement = p.getArg('{', '}');
1589 overhang = p.getArg('[', ']');
1590 string const width = p.getArg('{', '}');
1592 if (name == "wrapfigure")
1593 begin_inset(os, "Wrap figure\n");
1595 begin_inset(os, "Wrap table\n");
1596 os << "lines " << lines
1597 << "\nplacement " << placement
1598 << "\noverhang " << lyx::translate_len(overhang)
1599 << "\nwidth " << lyx::translate_len(width)
1600 << "\nstatus open\n\n";
1601 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1603 // We don't need really a new paragraph, but
1604 // we must make sure that the next item gets a \begin_layout.
1605 parent_context.new_paragraph(os);
1607 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1610 else if (name == "minipage") {
1611 eat_whitespace(p, os, parent_context, false);
1612 // Test whether this is an outer box of a shaded box
1614 // swallow arguments
1615 while (p.hasOpt()) {
1617 p.skip_spaces(true);
1620 p.skip_spaces(true);
1621 Token t = p.get_token();
1622 bool shaded = false;
1623 if (t.asInput() == "\\begin") {
1624 p.skip_spaces(true);
1625 if (p.getArg('{', '}') == "shaded")
1630 parse_outer_box(p, os, FLAG_END, outer,
1631 parent_context, name, "shaded");
1633 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1634 "", "", name, "", "");
1638 else if (name == "comment") {
1639 eat_whitespace(p, os, parent_context, false);
1640 parent_context.check_layout(os);
1641 begin_inset(os, "Note Comment\n");
1642 os << "status open\n";
1643 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1646 skip_braces(p); // eat {} that might by set by LyX behind comments
1647 preamble.registerAutomaticallyLoadedPackage("verbatim");
1650 else if (unstarred_name == "verbatim") {
1651 // FIXME: this should go in the generic code that
1652 // handles environments defined in layout file that
1653 // have "PassThru 1". However, the code over there is
1654 // already too complicated for my taste.
1655 string const ascii_name =
1656 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1657 parent_context.new_paragraph(os);
1658 Context context(true, parent_context.textclass,
1659 &parent_context.textclass[from_ascii(ascii_name)]);
1660 string s = p.verbatimEnvironment(name);
1661 output_ert(os, s, context);
1665 else if (name == "IPA") {
1666 eat_whitespace(p, os, parent_context, false);
1667 parent_context.check_layout(os);
1668 begin_inset(os, "IPA\n");
1669 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1672 preamble.registerAutomaticallyLoadedPackage("tipa");
1673 preamble.registerAutomaticallyLoadedPackage("tipx");
1676 else if (name == "CJK") {
1677 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1678 // It is impossible to decide if a CJK environment was in its own paragraph or within
1679 // a line. We therefore always assume a paragraph since the latter is a rare case.
1680 eat_whitespace(p, os, parent_context, false);
1681 parent_context.check_end_layout(os);
1682 // store the encoding to be able to reset it
1683 string const encoding_old = p.getEncoding();
1684 string const encoding = p.getArg('{', '}');
1685 // FIXME: For some reason JIS does not work. Although the text
1686 // in tests/CJK.tex is identical with the SJIS version if you
1687 // convert both snippets using the recode command line utility,
1688 // the resulting .lyx file contains some extra characters if
1689 // you set buggy_encoding to false for JIS.
1690 bool const buggy_encoding = encoding == "JIS";
1691 if (!buggy_encoding)
1692 p.setEncoding(encoding, Encoding::CJK);
1694 // FIXME: This will read garbage, since the data is not encoded in utf8.
1695 p.setEncoding("UTF-8");
1697 // LyX only supports the same mapping for all CJK
1698 // environments, so we might need to output everything as ERT
1699 string const mapping = trim(p.getArg('{', '}'));
1700 char const * const * const where =
1701 is_known(encoding, supported_CJK_encodings);
1702 if (!buggy_encoding && !preamble.fontCJKSet())
1703 preamble.fontCJK(mapping);
1704 bool knownMapping = mapping == preamble.fontCJK();
1705 if (buggy_encoding || !knownMapping || !where) {
1706 parent_context.check_layout(os);
1707 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1709 // we must parse the content as verbatim because e.g. JIS can contain
1710 // normally invalid characters
1711 // FIXME: This works only for the most simple cases.
1712 // Since TeX control characters are not parsed,
1713 // things like comments are completely wrong.
1714 string const s = p.plainEnvironment("CJK");
1715 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1717 output_ert_inset(os, "\\", parent_context);
1718 else if (*it == '$')
1719 output_ert_inset(os, "$", parent_context);
1720 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1725 output_ert_inset(os, "\\end{" + name + "}",
1729 supported_CJK_languages[where - supported_CJK_encodings];
1730 // store the language because we must reset it at the end
1731 string const lang_old = parent_context.font.language;
1732 parent_context.font.language = lang;
1733 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1734 parent_context.font.language = lang_old;
1735 parent_context.new_paragraph(os);
1737 p.setEncoding(encoding_old);
1741 else if (name == "lyxgreyedout") {
1742 eat_whitespace(p, os, parent_context, false);
1743 parent_context.check_layout(os);
1744 begin_inset(os, "Note Greyedout\n");
1745 os << "status open\n";
1746 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1749 if (!preamble.notefontcolor().empty())
1750 preamble.registerAutomaticallyLoadedPackage("color");
1753 else if (name == "btSect") {
1754 eat_whitespace(p, os, parent_context, false);
1755 parent_context.check_layout(os);
1756 begin_command_inset(os, "bibtex", "bibtex");
1757 string bibstyle = "plain";
1759 bibstyle = p.getArg('[', ']');
1760 p.skip_spaces(true);
1762 string const bibfile = p.getArg('{', '}');
1763 eat_whitespace(p, os, parent_context, false);
1764 Token t = p.get_token();
1765 if (t.asInput() == "\\btPrintCited") {
1766 p.skip_spaces(true);
1767 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1769 if (t.asInput() == "\\btPrintNotCited") {
1770 p.skip_spaces(true);
1771 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1773 if (t.asInput() == "\\btPrintAll") {
1774 p.skip_spaces(true);
1775 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1777 os << "bibfiles " << '"' << bibfile << "\"\n"
1778 << "options " << '"' << bibstyle << "\"\n";
1779 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1784 else if (name == "framed" || name == "shaded") {
1785 eat_whitespace(p, os, parent_context, false);
1786 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1788 preamble.registerAutomaticallyLoadedPackage("framed");
1791 else if (name == "listing") {
1792 minted_float = "float";
1793 eat_whitespace(p, os, parent_context, false);
1794 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1796 minted_float += "=" + opt;
1797 // If something precedes \begin{minted}, we output it at the end
1798 // as a caption, in order to keep it inside the listings inset.
1799 eat_whitespace(p, os, parent_context, true);
1801 Token const & t = p.get_token();
1802 p.skip_spaces(true);
1803 string const envname = p.next_token().cat() == catBegin
1804 ? p.getArg('{', '}') : string();
1805 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1807 minted_float_has_caption = false;
1808 string content = parse_text_snippet(p, FLAG_END, outer,
1810 size_t i = content.find("\\begin_inset listings");
1811 bool minted_env = i != string::npos;
1814 caption = content.substr(0, i);
1815 content.erase(0, i);
1817 parent_context.check_layout(os);
1818 if (minted_env && minted_float_has_caption) {
1819 eat_whitespace(p, os, parent_context, true);
1820 os << content << "\n";
1821 if (!caption.empty())
1822 os << caption << "\n";
1823 os << "\n\\end_layout\n"; // close inner layout
1824 end_inset(os); // close caption inset
1825 os << "\n\\end_layout\n"; // close outer layout
1826 } else if (!caption.empty()) {
1828 begin_inset(os, "listings\n");
1829 os << "lstparams " << '"' << minted_float << '"' << '\n';
1830 os << "inline false\n";
1831 os << "status collapsed\n";
1833 os << "\n\\begin_layout Plain Layout\n";
1834 begin_inset(os, "Caption Standard\n");
1835 Context newcontext(true, parent_context.textclass,
1836 0, 0, parent_context.font);
1837 newcontext.check_layout(os);
1838 os << caption << "\n";
1839 newcontext.check_end_layout(os);
1841 os << "\n\\end_layout\n";
1842 } else if (content.empty()) {
1843 begin_inset(os, "listings\n");
1844 os << "lstparams " << '"' << minted_float << '"' << '\n';
1845 os << "inline false\n";
1846 os << "status collapsed\n";
1848 os << content << "\n";
1850 end_inset(os); // close listings inset
1851 parent_context.check_end_layout(os);
1852 parent_context.new_paragraph(os);
1854 minted_float.clear();
1855 minted_float_has_caption = false;
1858 else if (name == "lstlisting" || name == "minted") {
1859 bool use_minted = name == "minted";
1860 eat_whitespace(p, os, parent_context, false);
1861 if (use_minted && minted_float.empty()) {
1862 // look ahead for a bottom caption
1864 bool found_end_minted = false;
1865 while (!found_end_minted && p.good()) {
1866 Token const & t = p.get_token();
1868 string const envname =
1869 p.next_token().cat() == catBegin
1870 ? p.getArg('{', '}') : string();
1871 found_end_minted = t.asInput() == "\\end"
1872 && envname == "minted";
1874 eat_whitespace(p, os, parent_context, true);
1875 Token const & t = p.get_token();
1876 p.skip_spaces(true);
1877 if (t.asInput() == "\\lyxmintcaption") {
1878 string const pos = p.getArg('[', ']');
1880 string const caption =
1881 parse_text_snippet(p, FLAG_ITEM,
1882 false, parent_context);
1883 minted_nonfloat_caption = "[b]" + caption;
1888 parse_listings(p, os, parent_context, false, use_minted);
1892 else if (!parent_context.new_layout_allowed)
1893 parse_unknown_environment(p, name, os, FLAG_END, outer,
1896 // Alignment and spacing settings
1897 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1898 // therefore are totally broken!
1899 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1900 // they are commands not environments. They are furthermore switches that
1901 // can be ended by another switches, but also by commands like \footnote or
1902 // \parbox. So the only safe way is to leave them untouched.
1903 // However, we support the pseudo-environments
1904 // \begin{centering} ... \end{centering}
1905 // \begin{raggedright} ... \end{raggedright}
1906 // \begin{raggedleft} ... \end{raggedleft}
1907 // since they are used by LyX in floats (for spacing reasons)
1908 else if (name == "center" || name == "centering" ||
1909 name == "flushleft" || name == "raggedright" ||
1910 name == "flushright" || name == "raggedleft" ||
1911 name == "singlespace" || name == "onehalfspace" ||
1912 name == "doublespace" || name == "spacing") {
1913 eat_whitespace(p, os, parent_context, false);
1914 // We must begin a new paragraph if not already done
1915 if (! parent_context.atParagraphStart()) {
1916 parent_context.check_end_layout(os);
1917 parent_context.new_paragraph(os);
1919 if (name == "flushleft" || name == "raggedright")
1920 parent_context.add_extra_stuff("\\align left\n");
1921 else if (name == "flushright" || name == "raggedleft")
1922 parent_context.add_extra_stuff("\\align right\n");
1923 else if (name == "center" || name == "centering")
1924 parent_context.add_extra_stuff("\\align center\n");
1925 else if (name == "singlespace")
1926 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1927 else if (name == "onehalfspace") {
1928 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1929 preamble.registerAutomaticallyLoadedPackage("setspace");
1930 } else if (name == "doublespace") {
1931 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1932 preamble.registerAutomaticallyLoadedPackage("setspace");
1933 } else if (name == "spacing") {
1934 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1935 preamble.registerAutomaticallyLoadedPackage("setspace");
1937 parse_text(p, os, FLAG_END, outer, parent_context);
1938 // Just in case the environment is empty
1939 parent_context.extra_stuff.erase();
1940 // We must begin a new paragraph to reset the alignment
1941 parent_context.new_paragraph(os);
1945 // The single '=' is meant here.
1946 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1947 eat_whitespace(p, os, parent_context, false);
1948 Context context(true, parent_context.textclass, newlayout,
1949 parent_context.layout, parent_context.font);
1950 if (parent_context.deeper_paragraph) {
1951 // We are beginning a nested environment after a
1952 // deeper paragraph inside the outer list environment.
1953 // Therefore we don't need to output a "begin deeper".
1954 context.need_end_deeper = true;
1956 parent_context.check_end_layout(os);
1957 if (last_env == name) {
1958 // we need to output a separator since LyX would export
1959 // the two environments as one otherwise (bug 5716)
1960 TeX2LyXDocClass const & textclass(parent_context.textclass);
1961 Context newcontext(true, textclass,
1962 &(textclass.defaultLayout()));
1963 newcontext.check_layout(os);
1964 begin_inset(os, "Separator plain\n");
1966 newcontext.check_end_layout(os);
1968 switch (context.layout->latextype) {
1969 case LATEX_LIST_ENVIRONMENT:
1970 context.add_par_extra_stuff("\\labelwidthstring "
1971 + p.verbatim_item() + '\n');
1974 case LATEX_BIB_ENVIRONMENT:
1975 p.verbatim_item(); // swallow next arg
1981 context.check_deeper(os);
1982 // handle known optional and required arguments
1983 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1984 // It is impossible to place anything after the environment name,
1985 // but before the first \\item.
1986 if (context.layout->latextype == LATEX_ENVIRONMENT)
1987 output_arguments(os, p, outer, false, false, context,
1988 context.layout->latexargs());
1989 parse_text(p, os, FLAG_END, outer, context);
1990 if (context.layout->latextype == LATEX_ENVIRONMENT)
1991 output_arguments(os, p, outer, false, true, context,
1992 context.layout->postcommandargs());
1993 context.check_end_layout(os);
1994 if (parent_context.deeper_paragraph) {
1995 // We must suppress the "end deeper" because we
1996 // suppressed the "begin deeper" above.
1997 context.need_end_deeper = false;
1999 context.check_end_deeper(os);
2000 parent_context.new_paragraph(os);
2002 if (!preamble.titleLayoutFound())
2003 preamble.titleLayoutFound(newlayout->intitle);
2004 set<string> const & req = newlayout->requires();
2005 set<string>::const_iterator it = req.begin();
2006 set<string>::const_iterator en = req.end();
2007 for (; it != en; ++it)
2008 preamble.registerAutomaticallyLoadedPackage(*it);
2011 // The single '=' is meant here.
2012 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2013 eat_whitespace(p, os, parent_context, false);
2014 parent_context.check_layout(os);
2015 begin_inset(os, "Flex ");
2016 docstring flex_name = newinsetlayout->name();
2017 // FIXME: what do we do if the prefix is not Flex: ?
2018 if (prefixIs(flex_name, from_ascii("Flex:")))
2019 flex_name.erase(0, 5);
2020 os << to_utf8(flex_name) << '\n'
2021 << "status collapsed\n";
2022 if (newinsetlayout->isPassThru()) {
2023 string const arg = p.verbatimEnvironment(name);
2024 Context context(true, parent_context.textclass,
2025 &parent_context.textclass.plainLayout(),
2026 parent_context.layout);
2027 output_ert(os, arg, parent_context);
2029 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2033 else if (name == "appendix") {
2034 // This is no good latex style, but it works and is used in some documents...
2035 eat_whitespace(p, os, parent_context, false);
2036 parent_context.check_end_layout(os);
2037 Context context(true, parent_context.textclass, parent_context.layout,
2038 parent_context.layout, parent_context.font);
2039 context.check_layout(os);
2040 os << "\\start_of_appendix\n";
2041 parse_text(p, os, FLAG_END, outer, context);
2042 context.check_end_layout(os);
2046 else if (known_environments.find(name) != known_environments.end()) {
2047 vector<ArgumentType> arguments = known_environments[name];
2048 // The last "argument" denotes wether we may translate the
2049 // environment contents to LyX
2050 // The default required if no argument is given makes us
2051 // compatible with the reLyXre environment.
2052 ArgumentType contents = arguments.empty() ?
2055 if (!arguments.empty())
2056 arguments.pop_back();
2057 // See comment in parse_unknown_environment()
2058 bool const specialfont =
2059 (parent_context.font != parent_context.normalfont);
2060 bool const new_layout_allowed =
2061 parent_context.new_layout_allowed;
2063 parent_context.new_layout_allowed = false;
2064 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2065 outer, parent_context);
2066 if (contents == verbatim)
2067 output_ert_inset(os, p.ertEnvironment(name),
2070 parse_text_snippet(p, os, FLAG_END, outer,
2072 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2074 parent_context.new_layout_allowed = new_layout_allowed;
2078 parse_unknown_environment(p, name, os, FLAG_END, outer,
2082 active_environments.pop_back();
2086 /// parses a comment and outputs it to \p os.
2087 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2089 LASSERT(t.cat() == catComment, return);
2090 if (!t.cs().empty()) {
2091 context.check_layout(os);
2092 output_comment(p, os, t.cs(), context);
2093 if (p.next_token().cat() == catNewline) {
2094 // A newline after a comment line starts a new
2096 if (context.new_layout_allowed) {
2097 if(!context.atParagraphStart())
2098 // Only start a new paragraph if not already
2099 // done (we might get called recursively)
2100 context.new_paragraph(os);
2102 output_ert_inset(os, "\n", context);
2103 eat_whitespace(p, os, context, true);
2106 // "%\n" combination
2113 * Reads spaces and comments until the first non-space, non-comment token.
2114 * New paragraphs (double newlines or \\par) are handled like simple spaces
2115 * if \p eatParagraph is true.
2116 * Spaces are skipped, but comments are written to \p os.
2118 void eat_whitespace(Parser & p, ostream & os, Context & context,
2122 Token const & t = p.get_token();
2123 if (t.cat() == catComment)
2124 parse_comment(p, os, t, context);
2125 else if ((! eatParagraph && p.isParagraph()) ||
2126 (t.cat() != catSpace && t.cat() != catNewline)) {
2135 * Set a font attribute, parse text and reset the font attribute.
2136 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2137 * \param currentvalue Current value of the attribute. Is set to the new
2138 * value during parsing.
2139 * \param newvalue New value of the attribute
2141 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2142 Context & context, string const & attribute,
2143 string & currentvalue, string const & newvalue)
2145 context.check_layout(os);
2146 string const oldvalue = currentvalue;
2147 currentvalue = newvalue;
2148 os << '\n' << attribute << ' ' << newvalue << "\n";
2149 parse_text_snippet(p, os, flags, outer, context);
2150 context.check_layout(os);
2151 os << '\n' << attribute << ' ' << oldvalue << "\n";
2152 currentvalue = oldvalue;
2156 /// get the arguments of a natbib or jurabib citation command
2157 void get_cite_arguments(Parser & p, bool natbibOrder,
2158 string & before, string & after, bool const qualified = false)
2160 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2162 // text before the citation
2164 // text after the citation
2165 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2167 if (!after.empty()) {
2168 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2169 if (natbibOrder && !before.empty())
2170 swap(before, after);
2175 /// Convert filenames with TeX macros and/or quotes to something LyX
2177 string const normalize_filename(string const & name)
2182 Token const & t = p.get_token();
2183 if (t.cat() != catEscape)
2185 else if (t.cs() == "lyxdot") {
2186 // This is used by LyX for simple dots in relative
2190 } else if (t.cs() == "space") {
2193 } else if (t.cs() == "string") {
2194 // Convert \string" to " and \string~ to ~
2195 Token const & n = p.next_token();
2196 if (n.asInput() != "\"" && n.asInput() != "~")
2201 // Strip quotes. This is a bit complicated (see latex_path()).
2202 string full = os.str();
2203 if (!full.empty() && full[0] == '"') {
2204 string base = removeExtension(full);
2205 string ext = getExtension(full);
2206 if (!base.empty() && base[base.length()-1] == '"')
2209 return addExtension(trim(base, "\""), ext);
2210 if (full[full.length()-1] == '"')
2213 return trim(full, "\"");
2219 /// Convert \p name from TeX convention (relative to master file) to LyX
2220 /// convention (relative to .lyx file) if it is relative
2221 void fix_child_filename(string & name)
2223 string const absMasterTeX = getMasterFilePath(true);
2224 bool const isabs = FileName::isAbsolute(name);
2225 // convert from "relative to .tex master" to absolute original path
2227 name = makeAbsPath(name, absMasterTeX).absFileName();
2228 bool copyfile = copyFiles();
2229 string const absParentLyX = getParentFilePath(false);
2232 // convert from absolute original path to "relative to master file"
2233 string const rel = to_utf8(makeRelPath(from_utf8(name),
2234 from_utf8(absMasterTeX)));
2235 // re-interpret "relative to .tex file" as "relative to .lyx file"
2236 // (is different if the master .lyx file resides in a
2237 // different path than the master .tex file)
2238 string const absMasterLyX = getMasterFilePath(false);
2239 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2240 // Do not copy if the new path is impossible to create. Example:
2241 // absMasterTeX = "/foo/bar/"
2242 // absMasterLyX = "/bar/"
2243 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2244 if (contains(name, "/../"))
2251 // convert from absolute original path to
2252 // "relative to .lyx file"
2253 name = to_utf8(makeRelPath(from_utf8(abs),
2254 from_utf8(absParentLyX)));
2258 // convert from absolute original path to "relative to .lyx file"
2259 name = to_utf8(makeRelPath(from_utf8(name),
2260 from_utf8(absParentLyX)));
2265 void copy_file(FileName const & src, string dstname)
2269 string const absParent = getParentFilePath(false);
2271 if (FileName::isAbsolute(dstname))
2272 dst = FileName(dstname);
2274 dst = makeAbsPath(dstname, absParent);
2275 FileName const srcpath = src.onlyPath();
2276 FileName const dstpath = dst.onlyPath();
2277 if (equivalent(srcpath, dstpath))
2279 if (!dstpath.isDirectory()) {
2280 if (!dstpath.createPath()) {
2281 cerr << "Warning: Could not create directory for file `"
2282 << dst.absFileName() << "´." << endl;
2286 if (dst.isReadableFile()) {
2287 if (overwriteFiles())
2288 cerr << "Warning: Overwriting existing file `"
2289 << dst.absFileName() << "´." << endl;
2291 cerr << "Warning: Not overwriting existing file `"
2292 << dst.absFileName() << "´." << endl;
2296 if (!src.copyTo(dst))
2297 cerr << "Warning: Could not copy file `" << src.absFileName()
2298 << "´ to `" << dst.absFileName() << "´." << endl;
2302 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2303 bool parse_chunk(Parser & p, ostream & os, Context & context)
2305 // check whether a chunk is possible here.
2306 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2312 // read the parameters
2313 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2314 if (!params.first) {
2319 Parser::Arg const code = p.verbatimStuff("\n@");
2324 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2325 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2329 // The last newline read is important for paragraph handling
2333 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2334 // We must have a valid layout before outputting the Chunk inset.
2335 context.check_layout(os);
2336 Context chunkcontext(true, context.textclass);
2337 chunkcontext.layout = &context.textclass.plainLayout();
2338 begin_inset(os, "Flex Chunk");
2339 os << "\nstatus open\n";
2340 if (!params.second.empty()) {
2341 chunkcontext.check_layout(os);
2342 Context paramscontext(true, context.textclass);
2343 paramscontext.layout = &context.textclass.plainLayout();
2344 begin_inset(os, "Argument 1");
2345 os << "\nstatus open\n";
2346 output_ert(os, params.second, paramscontext);
2349 output_ert(os, code.second, chunkcontext);
2357 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2358 bool is_macro(Parser & p)
2360 Token first = p.curr_token();
2361 if (first.cat() != catEscape || !p.good())
2363 if (first.cs() == "def")
2365 if (first.cs() != "global" && first.cs() != "long")
2367 Token second = p.get_token();
2369 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2370 second.cat() == catNewline || second.cat() == catComment)) {
2371 second = p.get_token();
2374 bool secondvalid = second.cat() == catEscape;
2376 bool thirdvalid = false;
2377 if (p.good() && first.cs() == "global" && secondvalid &&
2378 second.cs() == "long") {
2379 third = p.get_token();
2381 while (p.good() && !p.isParagraph() &&
2382 (third.cat() == catSpace ||
2383 third.cat() == catNewline ||
2384 third.cat() == catComment)) {
2385 third = p.get_token();
2388 thirdvalid = third.cat() == catEscape;
2390 for (int i = 0; i < pos; ++i)
2395 return (first.cs() == "global" || first.cs() == "long") &&
2396 second.cs() == "def";
2397 return first.cs() == "global" && second.cs() == "long" &&
2398 third.cs() == "def";
2402 /// Parse a macro definition (assumes that is_macro() returned true)
2403 void parse_macro(Parser & p, ostream & os, Context & context)
2405 context.check_layout(os);
2406 Token first = p.curr_token();
2409 string command = first.asInput();
2410 if (first.cs() != "def") {
2412 eat_whitespace(p, os, context, false);
2413 second = p.curr_token();
2414 command += second.asInput();
2415 if (second.cs() != "def") {
2417 eat_whitespace(p, os, context, false);
2418 third = p.curr_token();
2419 command += third.asInput();
2422 eat_whitespace(p, os, context, false);
2423 string const name = p.get_token().cs();
2424 eat_whitespace(p, os, context, false);
2430 while (p.next_token().cat() != catBegin) {
2431 if (p.next_token().cat() == catParameter) {
2436 // followed by number?
2437 if (p.next_token().cat() == catOther) {
2438 string s = p.get_token().asInput();
2440 // number = current arity + 1?
2441 if (s.size() == 1 && s[0] == arity + '0' + 1)
2446 paramtext += p.get_token().cs();
2448 paramtext += p.get_token().cs();
2453 // only output simple (i.e. compatible) macro as FormulaMacros
2454 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2456 context.check_layout(os);
2457 begin_inset(os, "FormulaMacro");
2458 os << "\n\\def" << ert;
2461 output_ert_inset(os, command + ert, context);
2465 void registerExternalTemplatePackages(string const & name)
2467 external::TemplateManager const & etm = external::TemplateManager::get();
2468 external::Template const * const et = etm.getTemplateByName(name);
2471 external::Template::Formats::const_iterator cit = et->formats.end();
2473 cit = et->formats.find("PDFLaTeX");
2474 if (cit == et->formats.end())
2475 // If the template has not specified a PDFLaTeX output,
2476 // we try the LaTeX format.
2477 cit = et->formats.find("LaTeX");
2478 if (cit == et->formats.end())
2480 vector<string>::const_iterator qit = cit->second.requirements.begin();
2481 vector<string>::const_iterator qend = cit->second.requirements.end();
2482 for (; qit != qend; ++qit)
2483 preamble.registerAutomaticallyLoadedPackage(*qit);
2486 } // anonymous namespace
2489 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2492 Layout const * newlayout = 0;
2493 InsetLayout const * newinsetlayout = 0;
2494 char const * const * where = 0;
2495 // Store the latest bibliographystyle, addcontentslineContent and
2496 // nocite{*} option (needed for bibtex inset)
2498 string contentslineContent;
2499 // Some classes provide a \bibliographystyle, so do not output
2500 // any if none is explicitly set.
2501 string bibliographystyle;
2502 bool const use_natbib = isProvided("natbib");
2503 bool const use_jurabib = isProvided("jurabib");
2504 bool const use_biblatex = isProvided("biblatex")
2505 && preamble.citeEngine() != "biblatex-natbib";
2506 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2507 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2508 need_commentbib = use_biblatex || use_biblatex_natbib;
2511 // it is impossible to determine the correct encoding for non-CJK Japanese.
2512 // Therefore write a note at the beginning of the document
2513 if (is_nonCJKJapanese) {
2514 context.check_layout(os);
2515 begin_inset(os, "Note Note\n");
2516 os << "status open\n\\begin_layout Plain Layout\n"
2517 << "\\series bold\n"
2518 << "Important information:\n"
2519 << "\\end_layout\n\n"
2520 << "\\begin_layout Plain Layout\n"
2521 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2522 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2523 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2524 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2525 << " and specify the encoding using the -e command-line switch.\n"
2526 << " In addition, you might want to double check that the desired output encoding\n"
2527 << " is correctly selected in Document > Settings > Language.\n"
2528 << "\\end_layout\n";
2530 is_nonCJKJapanese = false;
2533 bool have_cycled = false;
2535 // Leave here only after at least one cycle
2536 if (have_cycled && flags & FLAG_LEAVE) {
2537 flags &= ~FLAG_LEAVE;
2541 Token const & t = p.get_token();
2543 debugToken(cerr, t, flags);
2546 if (flags & FLAG_ITEM) {
2547 if (t.cat() == catSpace)
2550 flags &= ~FLAG_ITEM;
2551 if (t.cat() == catBegin) {
2552 // skip the brace and collect everything to the next matching
2554 flags |= FLAG_BRACE_LAST;
2558 // handle only this single token, leave the loop if done
2559 flags |= FLAG_LEAVE;
2562 if (t.cat() != catEscape && t.character() == ']' &&
2563 (flags & FLAG_BRACK_LAST))
2565 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2568 // If there is anything between \end{env} and \begin{env} we
2569 // don't need to output a separator.
2570 if (t.cat() != catSpace && t.cat() != catNewline &&
2571 t.asInput() != "\\begin")
2578 bool const starred = p.next_token().asInput() == "*";
2579 string const starredname(starred ? (t.cs() + '*') : t.cs());
2580 if (t.cat() == catMath) {
2581 // we are inside some text mode thingy, so opening new math is allowed
2582 context.check_layout(os);
2583 begin_inset(os, "Formula ");
2584 Token const & n = p.get_token();
2585 bool const display(n.cat() == catMath && outer);
2587 // TeX's $$...$$ syntax for displayed math
2589 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2591 p.get_token(); // skip the second '$' token
2593 // simple $...$ stuff
2596 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2601 // Prevent the conversion of a line break to a
2602 // space (bug 7668). This does not change the
2603 // output, but looks ugly in LyX.
2604 eat_whitespace(p, os, context, false);
2609 if (t.cat() == catSuper || t.cat() == catSub) {
2610 cerr << "catcode " << t << " illegal in text mode\n";
2614 // Basic support for english quotes. This should be
2615 // extended to other quotes, but is not so easy (a
2616 // left english quote is the same as a right german
2618 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2619 context.check_layout(os);
2620 begin_inset(os, "Quotes ");
2627 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2628 context.check_layout(os);
2629 begin_inset(os, "Quotes ");
2637 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2638 context.check_layout(os);
2639 begin_inset(os, "Quotes ");
2647 if (t.asInput() == "<"
2648 && p.next_token().asInput() == "<") {
2649 bool has_chunk = false;
2653 has_chunk = parse_chunk(p, os, context);
2659 context.check_layout(os);
2660 begin_inset(os, "Quotes ");
2661 //FIXME: this is a right danish quote;
2662 // why not a left french quote?
2671 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2672 check_space(p, os, context);
2676 // babel shorthands (also used by polyglossia)
2677 // Since these can have different meanings for different languages
2678 // we import them as ERT (but they must be put in ERT to get output
2680 if (t.asInput() == "\"") {
2682 // These are known pairs. We put them together in
2683 // one ERT inset. In other cases (such as "a), only
2684 // the quotation mark is ERTed.
2685 if (p.next_token().asInput() == "\""
2686 || p.next_token().asInput() == "|"
2687 || p.next_token().asInput() == "-"
2688 || p.next_token().asInput() == "~"
2689 || p.next_token().asInput() == "="
2690 || p.next_token().asInput() == "/"
2691 || p.next_token().asInput() == "~"
2692 || p.next_token().asInput() == "'"
2693 || p.next_token().asInput() == "`"
2694 || p.next_token().asInput() == "<"
2695 || p.next_token().asInput() == ">") {
2696 s += p.next_token().asInput();
2699 output_ert_inset(os, s, context);
2703 if (t.character() == '[' && noweb_mode &&
2704 p.next_token().character() == '[') {
2705 // These can contain underscores
2707 string const s = p.getFullOpt() + ']';
2708 if (p.next_token().character() == ']')
2711 cerr << "Warning: Inserting missing ']' in '"
2712 << s << "'." << endl;
2713 output_ert_inset(os, s, context);
2717 if (t.cat() == catLetter) {
2718 context.check_layout(os);
2723 if (t.cat() == catOther ||
2724 t.cat() == catAlign ||
2725 t.cat() == catParameter) {
2726 context.check_layout(os);
2727 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2728 context.merging_hyphens_allowed &&
2729 context.font.family != "ttfamily" &&
2730 !context.layout->pass_thru) {
2731 if (p.next_next_token().asInput() == "-") {
2733 os << to_utf8(docstring(1, 0x2014));
2737 os << to_utf8(docstring(1, 0x2013));
2740 // This translates "&" to "\\&" which may be wrong...
2745 if (p.isParagraph()) {
2746 // In minted floating listings we will collect
2747 // everything into the caption, where multiple
2748 // paragraphs are forbidden.
2749 if (minted_float.empty()) {
2750 if (context.new_layout_allowed)
2751 context.new_paragraph(os);
2753 output_ert_inset(os, "\\par ", context);
2756 eat_whitespace(p, os, context, true);
2760 if (t.cat() == catActive) {
2761 context.check_layout(os);
2762 if (t.character() == '~') {
2763 if (context.layout->free_spacing)
2766 begin_inset(os, "space ~\n");
2774 if (t.cat() == catBegin) {
2775 Token const next = p.next_token();
2776 Token const end = p.next_next_token();
2777 if (next.cat() == catEnd) {
2779 Token const prev = p.prev_token();
2781 if (p.next_token().character() == '`')
2782 ; // ignore it in {}``
2784 output_ert_inset(os, "{}", context);
2785 } else if (next.cat() == catEscape &&
2786 is_known(next.cs(), known_quotes) &&
2787 end.cat() == catEnd) {
2788 // Something like {\textquoteright} (e.g.
2789 // from writer2latex). LyX writes
2790 // \textquoteright{}, so we may skip the
2791 // braces here for better readability.
2792 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2794 } else if (p.next_token().asInput() == "\\ascii") {
2795 // handle the \ascii characters
2796 // (the case without braces is handled later)
2797 // the code is "{\ascii\xxx}"
2798 p.get_token(); // eat \ascii
2799 string name2 = p.get_token().asInput();
2800 p.get_token(); // eat the final '}'
2801 string const name = "{\\ascii" + name2 + "}";
2805 // get the character from unicodesymbols
2806 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2807 Encodings::TEXT_CMD, termination, rem, &req);
2809 context.check_layout(os);
2812 output_ert_inset(os,
2813 to_utf8(rem), context);
2814 for (set<string>::const_iterator it = req.begin();
2815 it != req.end(); ++it)
2816 preamble.registerAutomaticallyLoadedPackage(*it);
2818 // we did not find a non-ert version
2819 output_ert_inset(os, name, context);
2821 context.check_layout(os);
2822 // special handling of font attribute changes
2823 Token const prev = p.prev_token();
2824 TeXFont const oldFont = context.font;
2825 if (next.character() == '[' ||
2826 next.character() == ']' ||
2827 next.character() == '*') {
2829 if (p.next_token().cat() == catEnd) {
2834 output_ert_inset(os, "{", context);
2835 parse_text_snippet(p, os,
2838 output_ert_inset(os, "}", context);
2840 } else if (! context.new_layout_allowed) {
2841 output_ert_inset(os, "{", context);
2842 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2844 output_ert_inset(os, "}", context);
2845 } else if (is_known(next.cs(), known_sizes)) {
2846 // next will change the size, so we must
2848 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2850 if (!context.atParagraphStart())
2852 << context.font.size << "\n";
2853 } else if (is_known(next.cs(), known_font_families)) {
2854 // next will change the font family, so we
2855 // must reset it here
2856 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2858 if (!context.atParagraphStart())
2860 << context.font.family << "\n";
2861 } else if (is_known(next.cs(), known_font_series)) {
2862 // next will change the font series, so we
2863 // must reset it here
2864 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2866 if (!context.atParagraphStart())
2868 << context.font.series << "\n";
2869 } else if (is_known(next.cs(), known_font_shapes)) {
2870 // next will change the font shape, so we
2871 // must reset it here
2872 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2874 if (!context.atParagraphStart())
2876 << context.font.shape << "\n";
2877 } else if (is_known(next.cs(), known_old_font_families) ||
2878 is_known(next.cs(), known_old_font_series) ||
2879 is_known(next.cs(), known_old_font_shapes)) {
2880 // next will change the font family, series
2881 // and shape, so we must reset it here
2882 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2884 if (!context.atParagraphStart())
2886 << context.font.family
2888 << context.font.series
2890 << context.font.shape << "\n";
2892 output_ert_inset(os, "{", context);
2893 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2895 output_ert_inset(os, "}", context);
2901 if (t.cat() == catEnd) {
2902 if (flags & FLAG_BRACE_LAST) {
2905 cerr << "stray '}' in text\n";
2906 output_ert_inset(os, "}", context);
2910 if (t.cat() == catComment) {
2911 parse_comment(p, os, t, context);
2916 // control sequences
2919 if (t.cs() == "(" || t.cs() == "[") {
2920 bool const simple = t.cs() == "(";
2921 context.check_layout(os);
2922 begin_inset(os, "Formula");
2923 os << " \\" << t.cs();
2924 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2925 os << '\\' << (simple ? ')' : ']');
2928 // Prevent the conversion of a line break to a
2929 // space (bug 7668). This does not change the
2930 // output, but looks ugly in LyX.
2931 eat_whitespace(p, os, context, false);
2936 if (t.cs() == "begin") {
2937 parse_environment(p, os, outer, last_env,
2942 if (t.cs() == "end") {
2943 if (flags & FLAG_END) {
2944 // eat environment name
2945 string const name = p.getArg('{', '}');
2946 if (name != active_environment())
2947 cerr << "\\end{" + name + "} does not match \\begin{"
2948 + active_environment() + "}\n";
2951 p.error("found 'end' unexpectedly");
2955 if (t.cs() == "item") {
2957 bool const optarg = p.hasOpt();
2959 // FIXME: This swallows comments, but we cannot use
2960 // eat_whitespace() since we must not output
2961 // anything before the item.
2962 p.skip_spaces(true);
2963 s = p.verbatimOption();
2965 p.skip_spaces(false);
2967 context.check_layout(os);
2968 if (context.has_item) {
2969 // An item in an unknown list-like environment
2970 // FIXME: Do this in check_layout()!
2971 context.has_item = false;
2973 output_ert_inset(os, "\\item", context);
2975 output_ert_inset(os, "\\item ", context);
2978 if (context.layout->labeltype != LABEL_MANUAL) {
2979 // handle option of itemize item
2980 begin_inset(os, "Argument item:1\n");
2981 os << "status open\n";
2982 os << "\n\\begin_layout Plain Layout\n";
2984 os << parse_text_snippet(p2,
2985 FLAG_BRACK_LAST, outer, context);
2986 // we must not use context.check_end_layout(os)
2987 // because that would close the outer itemize layout
2988 os << "\n\\end_layout\n";
2990 eat_whitespace(p, os, context, false);
2991 } else if (!s.empty()) {
2992 // LyX adds braces around the argument,
2993 // so we need to remove them here.
2994 if (s.size() > 2 && s[0] == '{' &&
2995 s[s.size()-1] == '}')
2996 s = s.substr(1, s.size()-2);
2997 // If the argument contains a space we
2998 // must put it into ERT: Otherwise LyX
2999 // would misinterpret the space as
3000 // item delimiter (bug 7663)
3001 if (contains(s, ' ')) {
3002 output_ert_inset(os, s, context);
3005 os << parse_text_snippet(p2,
3006 FLAG_BRACK_LAST, outer, context);
3008 // The space is needed to separate the
3009 // item from the rest of the sentence.
3011 eat_whitespace(p, os, context, false);
3017 if (t.cs() == "bibitem") {
3019 context.check_layout(os);
3020 eat_whitespace(p, os, context, false);
3021 string label = convert_command_inset_arg(p.verbatimOption());
3022 string key = convert_command_inset_arg(p.verbatim_item());
3023 if (contains(label, '\\') || contains(key, '\\')) {
3024 // LyX can't handle LaTeX commands in labels or keys
3025 output_ert_inset(os, t.asInput() + '[' + label +
3026 "]{" + p.verbatim_item() + '}',
3029 begin_command_inset(os, "bibitem", "bibitem");
3030 os << "label \"" << label << "\"\n"
3031 << "key \"" << key << "\"\n"
3032 << "literal \"true\"\n";
3039 // catch the case of \def\inputGnumericTable
3041 if (t.cs() == "def") {
3042 Token second = p.next_token();
3043 if (second.cs() == "inputGnumericTable") {
3047 Token third = p.get_token();
3049 if (third.cs() == "input") {
3053 string name = normalize_filename(p.verbatim_item());
3054 string const path = getMasterFilePath(true);
3055 // We want to preserve relative / absolute filenames,
3056 // therefore path is only used for testing
3057 // The file extension is in every case ".tex".
3058 // So we need to remove this extension and check for
3059 // the original one.
3060 name = removeExtension(name);
3061 if (!makeAbsPath(name, path).exists()) {
3062 char const * const Gnumeric_formats[] = {"gnumeric",
3064 string const Gnumeric_name =
3065 find_file(name, path, Gnumeric_formats);
3066 if (!Gnumeric_name.empty())
3067 name = Gnumeric_name;
3069 FileName const absname = makeAbsPath(name, path);
3070 if (absname.exists()) {
3071 fix_child_filename(name);
3072 copy_file(absname, name);
3074 cerr << "Warning: Could not find file '"
3075 << name << "'." << endl;
3076 context.check_layout(os);
3077 begin_inset(os, "External\n\ttemplate ");
3078 os << "GnumericSpreadsheet\n\tfilename "
3081 context.check_layout(os);
3083 // register the packages that are automatically loaded
3084 // by the Gnumeric template
3085 registerExternalTemplatePackages("GnumericSpreadsheet");
3090 parse_macro(p, os, context);
3094 if (t.cs() == "noindent") {
3096 context.add_par_extra_stuff("\\noindent\n");
3100 if (t.cs() == "appendix") {
3101 context.add_par_extra_stuff("\\start_of_appendix\n");
3102 // We need to start a new paragraph. Otherwise the
3103 // appendix in 'bla\appendix\chapter{' would start
3105 context.new_paragraph(os);
3106 // We need to make sure that the paragraph is
3107 // generated even if it is empty. Otherwise the
3108 // appendix in '\par\appendix\par\chapter{' would
3110 context.check_layout(os);
3111 // FIXME: This is a hack to prevent paragraph
3112 // deletion if it is empty. Handle this better!
3113 output_comment(p, os,
3114 "dummy comment inserted by tex2lyx to "
3115 "ensure that this paragraph is not empty",
3117 // Both measures above may generate an additional
3118 // empty paragraph, but that does not hurt, because
3119 // whitespace does not matter here.
3120 eat_whitespace(p, os, context, true);
3124 // Must catch empty dates before findLayout is called below
3125 if (t.cs() == "date") {
3126 eat_whitespace(p, os, context, false);
3128 string const date = p.verbatim_item();
3131 preamble.suppressDate(true);
3134 preamble.suppressDate(false);
3135 if (context.new_layout_allowed &&
3136 (newlayout = findLayout(context.textclass,
3139 output_command_layout(os, p, outer,
3140 context, newlayout);
3141 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3142 if (!preamble.titleLayoutFound())
3143 preamble.titleLayoutFound(newlayout->intitle);
3144 set<string> const & req = newlayout->requires();
3145 set<string>::const_iterator it = req.begin();
3146 set<string>::const_iterator en = req.end();
3147 for (; it != en; ++it)
3148 preamble.registerAutomaticallyLoadedPackage(*it);
3150 output_ert_inset(os,
3151 "\\date{" + p.verbatim_item() + '}',
3157 // Starred section headings
3158 // Must attempt to parse "Section*" before "Section".
3159 if ((p.next_token().asInput() == "*") &&
3160 context.new_layout_allowed &&
3161 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3164 output_command_layout(os, p, outer, context, newlayout);
3166 if (!preamble.titleLayoutFound())
3167 preamble.titleLayoutFound(newlayout->intitle);
3168 set<string> const & req = newlayout->requires();
3169 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3170 preamble.registerAutomaticallyLoadedPackage(*it);
3174 // Section headings and the like
3175 if (context.new_layout_allowed &&
3176 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3178 output_command_layout(os, p, outer, context, newlayout);
3180 if (!preamble.titleLayoutFound())
3181 preamble.titleLayoutFound(newlayout->intitle);
3182 set<string> const & req = newlayout->requires();
3183 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3184 preamble.registerAutomaticallyLoadedPackage(*it);
3188 if (t.cs() == "subfloat") {
3189 // the syntax is \subfloat[list entry][sub caption]{content}
3190 // if it is a table of figure depends on the surrounding float
3192 // do nothing if there is no outer float
3193 if (!float_type.empty()) {
3194 context.check_layout(os);
3196 begin_inset(os, "Float " + float_type + "\n");
3198 << "\nsideways false"
3199 << "\nstatus collapsed\n\n";
3202 bool has_caption = false;
3203 if (p.next_token().cat() != catEscape &&
3204 p.next_token().character() == '[') {
3205 p.get_token(); // eat '['
3206 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3209 // In case we have two optional args, the second is the caption.
3210 if (p.next_token().cat() != catEscape &&
3211 p.next_token().character() == '[') {
3212 p.get_token(); // eat '['
3213 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3216 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3217 // the caption comes always as the last
3219 // we must make sure that the caption gets a \begin_layout
3220 os << "\n\\begin_layout Plain Layout";
3222 begin_inset(os, "Caption Standard\n");
3223 Context newcontext(true, context.textclass,
3224 0, 0, context.font);
3225 newcontext.check_layout(os);
3226 os << caption << "\n";
3227 newcontext.check_end_layout(os);
3230 // close the layout we opened
3231 os << "\n\\end_layout";
3236 // if the float type is not supported or there is no surrounding float
3241 opt_arg1 = convert_command_inset_arg(p.getFullOpt());
3243 opt_arg2 = convert_command_inset_arg(p.getFullOpt());
3245 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3246 + "{" + p.verbatim_item() + '}', context);
3251 if (t.cs() == "xymatrix") {
3252 // we must open a new math because LyX's xy support is in math
3253 context.check_layout(os);
3254 begin_inset(os, "Formula ");
3256 os << "\\" << t.cs() << '{';
3257 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3260 preamble.registerAutomaticallyLoadedPackage("xy");
3264 if (t.cs() == "includegraphics") {
3265 bool const clip = p.next_token().asInput() == "*";
3268 string const arg = p.getArg('[', ']');
3269 map<string, string> opts;
3270 vector<string> keys;
3271 split_map(arg, opts, keys);
3273 opts["clip"] = string();
3274 string name = normalize_filename(p.verbatim_item());
3276 string const path = getMasterFilePath(true);
3277 // We want to preserve relative / absolute filenames,
3278 // therefore path is only used for testing
3279 if (!makeAbsPath(name, path).exists()) {
3280 // The file extension is probably missing.
3281 // Now try to find it out.
3282 string const dvips_name =
3283 find_file(name, path,
3284 known_dvips_graphics_formats);
3285 string const pdftex_name =
3286 find_file(name, path,
3287 known_pdftex_graphics_formats);
3288 if (!dvips_name.empty()) {
3289 if (!pdftex_name.empty()) {
3290 cerr << "This file contains the "
3292 "\"\\includegraphics{"
3294 "However, files\n\""
3295 << dvips_name << "\" and\n\""
3296 << pdftex_name << "\"\n"
3297 "both exist, so I had to make a "
3298 "choice and took the first one.\n"
3299 "Please move the unwanted one "
3300 "someplace else and try again\n"
3301 "if my choice was wrong."
3305 } else if (!pdftex_name.empty()) {
3311 FileName const absname = makeAbsPath(name, path);
3312 if (absname.exists()) {
3313 fix_child_filename(name);
3314 copy_file(absname, name);
3316 cerr << "Warning: Could not find graphics file '"
3317 << name << "'." << endl;
3319 context.check_layout(os);
3320 begin_inset(os, "Graphics ");
3321 os << "\n\tfilename " << name << '\n';
3322 if (opts.find("width") != opts.end())
3324 << translate_len(opts["width"]) << '\n';
3325 if (opts.find("height") != opts.end())
3327 << translate_len(opts["height"]) << '\n';
3328 if (opts.find("scale") != opts.end()) {
3329 istringstream iss(opts["scale"]);
3333 os << "\tscale " << val << '\n';
3335 if (opts.find("angle") != opts.end()) {
3336 os << "\trotateAngle "
3337 << opts["angle"] << '\n';
3338 vector<string>::const_iterator a =
3339 find(keys.begin(), keys.end(), "angle");
3340 vector<string>::const_iterator s =
3341 find(keys.begin(), keys.end(), "width");
3342 if (s == keys.end())
3343 s = find(keys.begin(), keys.end(), "height");
3344 if (s == keys.end())
3345 s = find(keys.begin(), keys.end(), "scale");
3346 if (s != keys.end() && distance(s, a) > 0)
3347 os << "\tscaleBeforeRotation\n";
3349 if (opts.find("origin") != opts.end()) {
3351 string const opt = opts["origin"];
3352 if (opt.find('l') != string::npos) ss << "left";
3353 if (opt.find('r') != string::npos) ss << "right";
3354 if (opt.find('c') != string::npos) ss << "center";
3355 if (opt.find('t') != string::npos) ss << "Top";
3356 if (opt.find('b') != string::npos) ss << "Bottom";
3357 if (opt.find('B') != string::npos) ss << "Baseline";
3358 if (!ss.str().empty())
3359 os << "\trotateOrigin " << ss.str() << '\n';
3361 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3363 if (opts.find("keepaspectratio") != opts.end())
3364 os << "\tkeepAspectRatio\n";
3365 if (opts.find("clip") != opts.end())
3367 if (opts.find("draft") != opts.end())
3369 if (opts.find("bb") != opts.end())
3370 os << "\tBoundingBox "
3371 << opts["bb"] << '\n';
3372 int numberOfbbOptions = 0;
3373 if (opts.find("bbllx") != opts.end())
3374 numberOfbbOptions++;
3375 if (opts.find("bblly") != opts.end())
3376 numberOfbbOptions++;
3377 if (opts.find("bburx") != opts.end())
3378 numberOfbbOptions++;
3379 if (opts.find("bbury") != opts.end())
3380 numberOfbbOptions++;
3381 if (numberOfbbOptions == 4)
3382 os << "\tBoundingBox "
3383 << opts["bbllx"] << " " << opts["bblly"] << " "
3384 << opts["bburx"] << " " << opts["bbury"] << '\n';
3385 else if (numberOfbbOptions > 0)
3386 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3387 numberOfbbOptions = 0;
3388 if (opts.find("natwidth") != opts.end())
3389 numberOfbbOptions++;
3390 if (opts.find("natheight") != opts.end())
3391 numberOfbbOptions++;
3392 if (numberOfbbOptions == 2)
3393 os << "\tBoundingBox 0bp 0bp "
3394 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3395 else if (numberOfbbOptions > 0)
3396 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3397 ostringstream special;
3398 if (opts.find("hiresbb") != opts.end())
3399 special << "hiresbb,";
3400 if (opts.find("trim") != opts.end())
3402 if (opts.find("viewport") != opts.end())
3403 special << "viewport=" << opts["viewport"] << ',';
3404 if (opts.find("totalheight") != opts.end())
3405 special << "totalheight=" << opts["totalheight"] << ',';
3406 if (opts.find("type") != opts.end())
3407 special << "type=" << opts["type"] << ',';
3408 if (opts.find("ext") != opts.end())
3409 special << "ext=" << opts["ext"] << ',';
3410 if (opts.find("read") != opts.end())
3411 special << "read=" << opts["read"] << ',';
3412 if (opts.find("command") != opts.end())
3413 special << "command=" << opts["command"] << ',';
3414 string s_special = special.str();
3415 if (!s_special.empty()) {
3416 // We had special arguments. Remove the trailing ','.
3417 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3419 // TODO: Handle the unknown settings better.
3420 // Warn about invalid options.
3421 // Check whether some option was given twice.
3423 preamble.registerAutomaticallyLoadedPackage("graphicx");
3427 if (t.cs() == "footnote" ||
3428 (t.cs() == "thanks" && context.layout->intitle)) {
3430 context.check_layout(os);
3431 begin_inset(os, "Foot\n");
3432 os << "status collapsed\n\n";
3433 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3438 if (t.cs() == "marginpar") {
3440 context.check_layout(os);
3441 begin_inset(os, "Marginal\n");
3442 os << "status collapsed\n\n";
3443 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3448 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3449 bool const use_minted = t.cs() == "mintinline";
3451 parse_listings(p, os, context, true, use_minted);
3455 if (t.cs() == "ensuremath") {
3457 context.check_layout(os);
3458 string const s = p.verbatim_item();
3459 //FIXME: this never triggers in UTF8
3460 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3463 output_ert_inset(os, "\\ensuremath{" + s + "}",
3468 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3469 if (preamble.titleLayoutFound()) {
3471 skip_spaces_braces(p);
3473 output_ert_inset(os, t.asInput(), context);
3477 if (t.cs() == "tableofcontents"
3478 || t.cs() == "lstlistoflistings"
3479 || t.cs() == "listoflistings") {
3480 string name = t.cs();
3481 if (preamble.minted() && name == "listoflistings")
3482 name.insert(0, "lst");
3483 context.check_layout(os);
3484 begin_command_inset(os, "toc", name);
3486 skip_spaces_braces(p);
3487 if (name == "lstlistoflistings") {
3488 if (preamble.minted())
3489 preamble.registerAutomaticallyLoadedPackage("minted");
3491 preamble.registerAutomaticallyLoadedPackage("listings");
3496 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3497 context.check_layout(os);
3498 if (t.cs() == "listoffigures")
3499 begin_inset(os, "FloatList figure\n");
3501 begin_inset(os, "FloatList table\n");
3503 skip_spaces_braces(p);
3507 if (t.cs() == "listof") {
3508 p.skip_spaces(true);
3509 string const name = p.get_token().cs();
3510 if (context.textclass.floats().typeExist(name)) {
3511 context.check_layout(os);
3512 begin_inset(os, "FloatList ");
3515 p.get_token(); // swallow second arg
3517 output_ert_inset(os, "\\listof{" + name + "}", context);
3521 if ((where = is_known(t.cs(), known_text_font_families))) {
3522 parse_text_attributes(p, os, FLAG_ITEM, outer,
3523 context, "\\family", context.font.family,
3524 known_coded_font_families[where - known_text_font_families]);
3528 if ((where = is_known(t.cs(), known_text_font_series))) {
3529 parse_text_attributes(p, os, FLAG_ITEM, outer,
3530 context, "\\series", context.font.series,
3531 known_coded_font_series[where - known_text_font_series]);
3535 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3536 parse_text_attributes(p, os, FLAG_ITEM, outer,
3537 context, "\\shape", context.font.shape,
3538 known_coded_font_shapes[where - known_text_font_shapes]);
3542 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3543 context.check_layout(os);
3544 TeXFont oldFont = context.font;
3545 context.font.init();
3546 context.font.size = oldFont.size;
3547 os << "\n\\family " << context.font.family << "\n";
3548 os << "\n\\series " << context.font.series << "\n";
3549 os << "\n\\shape " << context.font.shape << "\n";
3550 if (t.cs() == "textnormal") {
3551 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3552 output_font_change(os, context.font, oldFont);
3553 context.font = oldFont;
3555 eat_whitespace(p, os, context, false);
3559 if (t.cs() == "textcolor") {
3560 // scheme is \textcolor{color name}{text}
3561 string const color = p.verbatim_item();
3562 // we support the predefined colors of the color and the xcolor package
3563 if (color == "black" || color == "blue" || color == "cyan"
3564 || color == "green" || color == "magenta" || color == "red"
3565 || color == "white" || color == "yellow") {
3566 context.check_layout(os);
3567 os << "\n\\color " << color << "\n";
3568 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3569 context.check_layout(os);
3570 os << "\n\\color inherit\n";
3571 preamble.registerAutomaticallyLoadedPackage("color");
3572 } else if (color == "brown" || color == "darkgray" || color == "gray"
3573 || color == "lightgray" || color == "lime" || color == "olive"
3574 || color == "orange" || color == "pink" || color == "purple"
3575 || color == "teal" || color == "violet") {
3576 context.check_layout(os);
3577 os << "\n\\color " << color << "\n";
3578 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3579 context.check_layout(os);
3580 os << "\n\\color inherit\n";
3581 preamble.registerAutomaticallyLoadedPackage("xcolor");
3583 // for custom defined colors
3584 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3588 if (t.cs() == "underbar" || t.cs() == "uline") {
3589 // \underbar is not 100% correct (LyX outputs \uline
3590 // of ulem.sty). The difference is that \ulem allows
3591 // line breaks, and \underbar does not.
3592 // Do NOT handle \underline.
3593 // \underbar cuts through y, g, q, p etc.,
3594 // \underline does not.
3595 context.check_layout(os);
3596 os << "\n\\bar under\n";
3597 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3598 context.check_layout(os);
3599 os << "\n\\bar default\n";
3600 preamble.registerAutomaticallyLoadedPackage("ulem");
3604 if (t.cs() == "sout") {
3605 context.check_layout(os);
3606 os << "\n\\strikeout on\n";
3607 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3608 context.check_layout(os);
3609 os << "\n\\strikeout default\n";
3610 preamble.registerAutomaticallyLoadedPackage("ulem");
3614 if (t.cs() == "uuline" || t.cs() == "uwave"
3615 || t.cs() == "emph" || t.cs() == "noun"
3616 || t.cs() == "xout") {
3617 context.check_layout(os);
3618 os << "\n\\" << t.cs() << " on\n";
3619 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3620 context.check_layout(os);
3621 os << "\n\\" << t.cs() << " default\n";
3622 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3623 preamble.registerAutomaticallyLoadedPackage("ulem");
3627 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3628 context.check_layout(os);
3629 string name = p.getArg('{', '}');
3630 string localtime = p.getArg('{', '}');
3631 preamble.registerAuthor(name);
3632 Author const & author = preamble.getAuthor(name);
3633 // from_asctime_utc() will fail if LyX decides to output the
3634 // time in the text language.
3635 time_t ptime = from_asctime_utc(localtime);
3636 if (ptime == static_cast<time_t>(-1)) {
3637 cerr << "Warning: Could not parse time `" << localtime
3638 << "´ for change tracking, using current time instead.\n";
3639 ptime = current_time();
3641 if (t.cs() == "lyxadded")
3642 os << "\n\\change_inserted ";
3644 os << "\n\\change_deleted ";
3645 os << author.bufferId() << ' ' << ptime << '\n';
3646 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3647 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3648 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3649 LaTeXPackages::isAvailable("xcolor");
3650 // No need to test for luatex, since luatex comes in
3651 // two flavours (dvi and pdf), like latex, and those
3652 // are detected by pdflatex.
3653 if (pdflatex || xetex) {
3655 preamble.registerAutomaticallyLoadedPackage("ulem");
3656 preamble.registerAutomaticallyLoadedPackage("xcolor");
3657 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3661 preamble.registerAutomaticallyLoadedPackage("dvipost");
3662 } else if (xcolorulem) {
3663 preamble.registerAutomaticallyLoadedPackage("ulem");
3664 preamble.registerAutomaticallyLoadedPackage("xcolor");
3670 if (t.cs() == "textipa") {
3671 context.check_layout(os);
3672 begin_inset(os, "IPA\n");
3673 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3674 context.merging_hyphens_allowed = false;
3675 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3676 context.merging_hyphens_allowed = merging_hyphens_allowed;
3678 preamble.registerAutomaticallyLoadedPackage("tipa");
3679 preamble.registerAutomaticallyLoadedPackage("tipx");
3683 if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3684 context.check_layout(os);
3685 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3686 os << "status open\n";
3687 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3693 if (t.cs() == "textvertline") {
3694 // FIXME: This is not correct, \textvertline is higher than |
3700 if (t.cs() == "tone" ) {
3701 context.check_layout(os);
3702 // register the tone package
3703 preamble.registerAutomaticallyLoadedPackage("tone");
3704 string content = trimSpaceAndEol(p.verbatim_item());
3705 string command = t.asInput() + "{" + content + "}";
3706 // some tones can be detected by unicodesymbols, some need special code
3707 if (is_known(content, known_tones)) {
3708 os << "\\IPAChar " << command << "\n";
3711 // try to see whether the string is in unicodesymbols
3715 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3716 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3717 termination, rem, &req);
3721 output_ert_inset(os, to_utf8(rem), context);
3722 for (set<string>::const_iterator it = req.begin();
3723 it != req.end(); ++it)
3724 preamble.registerAutomaticallyLoadedPackage(*it);
3726 // we did not find a non-ert version
3727 output_ert_inset(os, command, context);
3731 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3732 t.cs() == "vphantom") {
3733 context.check_layout(os);
3734 if (t.cs() == "phantom")
3735 begin_inset(os, "Phantom Phantom\n");
3736 if (t.cs() == "hphantom")
3737 begin_inset(os, "Phantom HPhantom\n");
3738 if (t.cs() == "vphantom")
3739 begin_inset(os, "Phantom VPhantom\n");
3740 os << "status open\n";
3741 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3747 if (t.cs() == "href") {
3748 context.check_layout(os);
3749 string target = convert_command_inset_arg(p.verbatim_item());
3750 string name = convert_command_inset_arg(p.verbatim_item());
3752 size_t i = target.find(':');
3753 if (i != string::npos) {
3754 type = target.substr(0, i + 1);
3755 if (type == "mailto:" || type == "file:")
3756 target = target.substr(i + 1);
3757 // handle the case that name is equal to target, except of "http(s)://"
3758 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3761 begin_command_inset(os, "href", "href");
3763 os << "name \"" << name << "\"\n";
3764 os << "target \"" << target << "\"\n";
3765 if (type == "mailto:" || type == "file:")
3766 os << "type \"" << type << "\"\n";
3767 os << "literal \"true\"\n";
3769 skip_spaces_braces(p);
3773 if (t.cs() == "lyxline") {
3774 // swallow size argument (it is not used anyway)
3776 if (!context.atParagraphStart()) {
3777 // so our line is in the middle of a paragraph
3778 // we need to add a new line, lest this line
3779 // follow the other content on that line and
3780 // run off the side of the page
3781 // FIXME: This may create an empty paragraph,
3782 // but without that it would not be
3783 // possible to set noindent below.
3784 // Fortunately LaTeX does not care
3785 // about the empty paragraph.
3786 context.new_paragraph(os);
3788 if (preamble.indentParagraphs()) {
3789 // we need to unindent, lest the line be too long
3790 context.add_par_extra_stuff("\\noindent\n");
3792 context.check_layout(os);
3793 begin_command_inset(os, "line", "rule");
3794 os << "offset \"0.5ex\"\n"
3795 "width \"100line%\"\n"
3801 if (t.cs() == "rule") {
3802 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3803 string const width = p.getArg('{', '}');
3804 string const thickness = p.getArg('{', '}');
3805 context.check_layout(os);
3806 begin_command_inset(os, "line", "rule");
3807 if (!offset.empty())
3808 os << "offset \"" << translate_len(offset) << "\"\n";
3809 os << "width \"" << translate_len(width) << "\"\n"
3810 "height \"" << translate_len(thickness) << "\"\n";
3815 // handle refstyle first to catch \eqref which can also occur
3816 // without refstyle. Only recognize these commands if
3817 // refstyle.sty was found in the preamble (otherwise \eqref
3818 // and user defined ref commands could be misdetected).
3819 if ((where = is_known(t.cs(), known_refstyle_commands))
3820 && preamble.refstyle()) {
3821 context.check_layout(os);
3822 begin_command_inset(os, "ref", "formatted");
3823 os << "reference \"";
3824 os << known_refstyle_prefixes[where - known_refstyle_commands]
3826 os << convert_command_inset_arg(p.verbatim_item())
3828 os << "plural \"false\"\n";
3829 os << "caps \"false\"\n";
3830 os << "noprefix \"false\"\n";
3832 preamble.registerAutomaticallyLoadedPackage("refstyle");
3836 // if refstyle is used, we must not convert \prettyref to a
3837 // formatted reference, since that would result in a refstyle command.
3838 if ((where = is_known(t.cs(), known_ref_commands)) &&
3839 (t.cs() != "prettyref" || !preamble.refstyle())) {
3840 string const opt = p.getOpt();
3842 context.check_layout(os);
3843 begin_command_inset(os, "ref",
3844 known_coded_ref_commands[where - known_ref_commands]);
3845 os << "reference \""
3846 << convert_command_inset_arg(p.verbatim_item())
3848 os << "plural \"false\"\n";
3849 os << "caps \"false\"\n";
3850 os << "noprefix \"false\"\n";
3852 if (t.cs() == "vref" || t.cs() == "vpageref")
3853 preamble.registerAutomaticallyLoadedPackage("varioref");
3854 else if (t.cs() == "prettyref")
3855 preamble.registerAutomaticallyLoadedPackage("prettyref");
3857 // LyX does not yet support optional arguments of ref commands
3858 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3859 p.verbatim_item() + '}', context);
3865 is_known(t.cs(), known_natbib_commands) &&
3866 ((t.cs() != "citefullauthor" &&
3867 t.cs() != "citeyear" &&
3868 t.cs() != "citeyearpar") ||
3869 p.next_token().asInput() != "*")) {
3870 context.check_layout(os);
3871 string command = t.cs();
3872 if (p.next_token().asInput() == "*") {
3876 if (command == "citefullauthor")
3877 // alternative name for "\\citeauthor*"
3878 command = "citeauthor*";
3880 // text before the citation
3882 // text after the citation
3884 get_cite_arguments(p, true, before, after);
3886 if (command == "cite") {
3887 // \cite without optional argument means
3888 // \citet, \cite with at least one optional
3889 // argument means \citep.
3890 if (before.empty() && after.empty())
3895 if (before.empty() && after == "[]")
3896 // avoid \citet[]{a}
3898 else if (before == "[]" && after == "[]") {
3899 // avoid \citet[][]{a}
3903 // remove the brackets around after and before
3904 if (!after.empty()) {
3906 after.erase(after.length() - 1, 1);
3907 after = convert_command_inset_arg(after);
3909 if (!before.empty()) {
3911 before.erase(before.length() - 1, 1);
3912 before = convert_command_inset_arg(before);
3914 begin_command_inset(os, "citation", command);
3915 os << "after " << '"' << after << '"' << "\n";
3916 os << "before " << '"' << before << '"' << "\n";
3918 << convert_command_inset_arg(p.verbatim_item())
3920 << "literal \"true\"\n";
3922 // Need to set the cite engine if natbib is loaded by
3923 // the document class directly
3924 if (preamble.citeEngine() == "basic")
3925 preamble.citeEngine("natbib");
3930 && is_known(t.cs(), known_biblatex_commands)
3931 && ((t.cs() == "cite"
3932 || t.cs() == "citeauthor"
3933 || t.cs() == "Citeauthor"
3934 || t.cs() == "parencite"
3935 || t.cs() == "citetitle")
3936 || p.next_token().asInput() != "*"))
3937 || (use_biblatex_natbib
3938 && (is_known(t.cs(), known_biblatex_commands)
3939 || is_known(t.cs(), known_natbib_commands))
3940 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3941 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3942 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3943 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3944 || t.cs() == "parencite" || t.cs() == "citetitle")
3945 || p.next_token().asInput() != "*"))){
3946 context.check_layout(os);
3947 string command = t.cs();
3948 if (p.next_token().asInput() == "*") {
3953 bool const qualified = suffixIs(command, "s");
3955 command = rtrim(command, "s");
3957 // text before the citation
3959 // text after the citation
3961 get_cite_arguments(p, true, before, after, qualified);
3963 // These use natbib cmd names in LyX
3964 // for inter-citeengine compativility
3965 if (command == "citeyear")
3966 command = "citebyear";
3967 else if (command == "cite*")
3968 command = "citeyear";
3969 else if (command == "textcite")
3971 else if (command == "Textcite")
3973 else if (command == "parencite")
3975 else if (command == "Parencite")
3977 else if (command == "parencite*")
3978 command = "citeyearpar";
3979 else if (command == "smartcite")
3980 command = "footcite";
3981 else if (command == "Smartcite")
3982 command = "Footcite";
3984 string const emptyarg = qualified ? "()" : "[]";
3985 if (before.empty() && after == emptyarg)
3988 else if (before == emptyarg && after == emptyarg) {
3989 // avoid \cite[][]{a}
3993 // remove the brackets around after and before
3994 if (!after.empty()) {
3996 after.erase(after.length() - 1, 1);
3997 after = convert_command_inset_arg(after);
3999 if (!before.empty()) {
4001 before.erase(before.length() - 1, 1);
4002 before = convert_command_inset_arg(before);
4004 string keys, pretextlist, posttextlist;
4006 map<string, string> pres;
4007 map<string, string> posts;
4008 vector<string> lkeys;
4009 // text before the citation
4011 // text after the citation
4015 get_cite_arguments(p, true, lbefore, lafter);
4016 // remove the brackets around after and before
4017 if (!lafter.empty()) {
4019 lafter.erase(lafter.length() - 1, 1);
4020 lafter = convert_command_inset_arg(lafter);
4022 if (!lbefore.empty()) {
4023 lbefore.erase(0, 1);
4024 lbefore.erase(lbefore.length() - 1, 1);
4025 lbefore = convert_command_inset_arg(lbefore);
4027 if (lbefore.empty() && lafter == "[]")
4030 else if (lbefore == "[]" && lafter == "[]") {
4031 // avoid \cite[][]{a}
4035 lkey = p.getArg('{', '}');
4038 if (!lbefore.empty())
4039 pres.insert(make_pair(lkey, lbefore));
4040 if (!lafter.empty())
4041 posts.insert(make_pair(lkey, lafter));
4042 lkeys.push_back(lkey);
4044 keys = convert_command_inset_arg(getStringFromVector(lkeys));
4045 for (auto const & ptl : pres) {
4046 if (!pretextlist.empty())
4047 pretextlist += '\t';
4048 pretextlist += ptl.first + " " + ptl.second;
4050 for (auto const & potl : posts) {
4051 if (!posttextlist.empty())
4052 posttextlist += '\t';
4053 posttextlist += potl.first + " " + potl.second;
4056 keys = convert_command_inset_arg(p.verbatim_item());
4057 begin_command_inset(os, "citation", command);
4058 os << "after " << '"' << after << '"' << "\n";
4059 os << "before " << '"' << before << '"' << "\n";
4063 if (!pretextlist.empty())
4064 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4065 if (!posttextlist.empty())
4066 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4067 os << "literal \"true\"\n";
4069 // Need to set the cite engine if biblatex is loaded by
4070 // the document class directly
4071 if (preamble.citeEngine() == "basic")
4072 use_biblatex_natbib ?
4073 preamble.citeEngine("biblatex-natbib")
4074 : preamble.citeEngine("biblatex");
4079 is_known(t.cs(), known_jurabib_commands) &&
4080 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4081 context.check_layout(os);
4082 string command = t.cs();
4083 if (p.next_token().asInput() == "*") {
4087 char argumentOrder = '\0';
4088 vector<string> const options =
4089 preamble.getPackageOptions("jurabib");
4090 if (find(options.begin(), options.end(),
4091 "natbiborder") != options.end())
4092 argumentOrder = 'n';
4093 else if (find(options.begin(), options.end(),
4094 "jurabiborder") != options.end())
4095 argumentOrder = 'j';
4097 // text before the citation
4099 // text after the citation
4101 get_cite_arguments(p, argumentOrder != 'j', before, after);
4103 string const citation = p.verbatim_item();
4104 if (!before.empty() && argumentOrder == '\0') {
4105 cerr << "Warning: Assuming argument order "
4106 "of jurabib version 0.6 for\n'"
4107 << command << before << after << '{'
4108 << citation << "}'.\n"
4109 "Add 'jurabiborder' to the jurabib "
4110 "package options if you used an\n"
4111 "earlier jurabib version." << endl;
4113 if (!after.empty()) {
4115 after.erase(after.length() - 1, 1);
4117 if (!before.empty()) {
4119 before.erase(before.length() - 1, 1);
4121 begin_command_inset(os, "citation", command);
4122 os << "after " << '"' << after << "\"\n"
4123 << "before " << '"' << before << "\"\n"
4124 << "key " << '"' << citation << "\"\n"
4125 << "literal \"true\"\n";
4127 // Need to set the cite engine if jurabib is loaded by
4128 // the document class directly
4129 if (preamble.citeEngine() == "basic")
4130 preamble.citeEngine("jurabib");
4134 if (t.cs() == "cite"
4135 || t.cs() == "nocite") {
4136 context.check_layout(os);
4137 string after = convert_command_inset_arg(p.getArg('[', ']'));
4138 string key = convert_command_inset_arg(p.verbatim_item());
4139 // store the case that it is "\nocite{*}" to use it later for
4142 begin_command_inset(os, "citation", t.cs());
4143 os << "after " << '"' << after << "\"\n"
4144 << "key " << '"' << key << "\"\n"
4145 << "literal \"true\"\n";
4147 } else if (t.cs() == "nocite")
4152 if (t.cs() == "index" ||
4153 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4154 context.check_layout(os);
4155 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4156 p.getArg('[', ']') : "";
4157 string const kind = arg.empty() ? "idx" : arg;
4158 begin_inset(os, "Index ");
4159 os << kind << "\nstatus collapsed\n";
4160 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4163 preamble.registerAutomaticallyLoadedPackage("splitidx");
4167 if (t.cs() == "nomenclature") {
4168 context.check_layout(os);
4169 begin_command_inset(os, "nomenclature", "nomenclature");
4170 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
4171 if (!prefix.empty())
4172 os << "prefix " << '"' << prefix << '"' << "\n";
4173 os << "symbol " << '"'
4174 << convert_command_inset_arg(p.verbatim_item());
4175 os << "\"\ndescription \""
4176 << convert_command_inset_arg(p.verbatim_item())
4178 << "literal \"true\"\n";
4180 preamble.registerAutomaticallyLoadedPackage("nomencl");
4184 if (t.cs() == "label") {
4185 context.check_layout(os);
4186 begin_command_inset(os, "label", "label");
4188 << convert_command_inset_arg(p.verbatim_item())
4194 if (t.cs() == "lyxmintcaption") {
4195 string const pos = p.getArg('[', ']');
4197 string const caption =
4198 parse_text_snippet(p, FLAG_ITEM, false,
4200 minted_nonfloat_caption = "[t]" + caption;
4202 // We already got the caption at the bottom,
4203 // so simply skip it.
4204 parse_text_snippet(p, FLAG_ITEM, false, context);
4209 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4210 context.check_layout(os);
4211 string commandname = t.cs();
4213 if (p.next_token().asInput() == "*") {
4218 begin_command_inset(os, "index_print", commandname);
4219 string const indexname = p.getArg('[', ']');
4221 if (indexname.empty())
4222 os << "type \"idx\"\n";
4224 os << "type \"" << indexname << "\"\n";
4225 os << "literal \"true\"\n";
4228 skip_spaces_braces(p);
4229 preamble.registerAutomaticallyLoadedPackage("makeidx");
4230 if (preamble.use_indices() == "true")
4231 preamble.registerAutomaticallyLoadedPackage("splitidx");
4235 if (t.cs() == "printnomenclature") {
4237 string width_type = "";
4238 context.check_layout(os);
4239 begin_command_inset(os, "nomencl_print", "printnomenclature");
4240 // case of a custom width
4242 width = p.getArg('[', ']');
4243 width = translate_len(width);
4244 width_type = "custom";
4246 // case of no custom width
4247 // the case of no custom width but the width set
4248 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4249 // because the user could have set anything, not only the width
4250 // of the longest label (which would be width_type = "auto")
4251 string label = convert_command_inset_arg(p.getArg('{', '}'));
4252 if (label.empty() && width_type.empty())
4253 width_type = "none";
4254 os << "set_width \"" << width_type << "\"\n";
4255 if (width_type == "custom")
4256 os << "width \"" << width << '\"';
4258 skip_spaces_braces(p);
4259 preamble.registerAutomaticallyLoadedPackage("nomencl");
4263 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4264 context.check_layout(os);
4265 begin_inset(os, "script ");
4266 os << t.cs().substr(4) << '\n';
4267 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4268 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4270 if (t.cs() == "textsubscript")
4271 preamble.registerAutomaticallyLoadedPackage("subscript");
4275 if ((where = is_known(t.cs(), known_quotes))) {
4276 context.check_layout(os);
4277 begin_inset(os, "Quotes ");
4278 os << known_coded_quotes[where - known_quotes];
4280 // LyX adds {} after the quote, so we have to eat
4281 // spaces here if there are any before a possible
4283 eat_whitespace(p, os, context, false);
4288 if ((where = is_known(t.cs(), known_sizes)) &&
4289 context.new_layout_allowed) {
4290 context.check_layout(os);
4291 TeXFont const oldFont = context.font;
4292 context.font.size = known_coded_sizes[where - known_sizes];
4293 output_font_change(os, oldFont, context.font);
4294 eat_whitespace(p, os, context, false);
4298 if ((where = is_known(t.cs(), known_font_families)) &&
4299 context.new_layout_allowed) {
4300 context.check_layout(os);
4301 TeXFont const oldFont = context.font;
4302 context.font.family =
4303 known_coded_font_families[where - known_font_families];
4304 output_font_change(os, oldFont, context.font);
4305 eat_whitespace(p, os, context, false);
4309 if ((where = is_known(t.cs(), known_font_series)) &&
4310 context.new_layout_allowed) {
4311 context.check_layout(os);
4312 TeXFont const oldFont = context.font;
4313 context.font.series =
4314 known_coded_font_series[where - known_font_series];
4315 output_font_change(os, oldFont, context.font);
4316 eat_whitespace(p, os, context, false);
4320 if ((where = is_known(t.cs(), known_font_shapes)) &&
4321 context.new_layout_allowed) {
4322 context.check_layout(os);
4323 TeXFont const oldFont = context.font;
4324 context.font.shape =
4325 known_coded_font_shapes[where - known_font_shapes];
4326 output_font_change(os, oldFont, context.font);
4327 eat_whitespace(p, os, context, false);
4330 if ((where = is_known(t.cs(), known_old_font_families)) &&
4331 context.new_layout_allowed) {
4332 context.check_layout(os);
4333 TeXFont const oldFont = context.font;
4334 context.font.init();
4335 context.font.size = oldFont.size;
4336 context.font.family =
4337 known_coded_font_families[where - known_old_font_families];
4338 output_font_change(os, oldFont, context.font);
4339 eat_whitespace(p, os, context, false);
4343 if ((where = is_known(t.cs(), known_old_font_series)) &&
4344 context.new_layout_allowed) {
4345 context.check_layout(os);
4346 TeXFont const oldFont = context.font;
4347 context.font.init();
4348 context.font.size = oldFont.size;
4349 context.font.series =
4350 known_coded_font_series[where - known_old_font_series];
4351 output_font_change(os, oldFont, context.font);
4352 eat_whitespace(p, os, context, false);
4356 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4357 context.new_layout_allowed) {
4358 context.check_layout(os);
4359 TeXFont const oldFont = context.font;
4360 context.font.init();
4361 context.font.size = oldFont.size;
4362 context.font.shape =
4363 known_coded_font_shapes[where - known_old_font_shapes];
4364 output_font_change(os, oldFont, context.font);
4365 eat_whitespace(p, os, context, false);
4369 if (t.cs() == "selectlanguage") {
4370 context.check_layout(os);
4371 // save the language for the case that a
4372 // \foreignlanguage is used
4373 context.font.language = babel2lyx(p.verbatim_item());
4374 os << "\n\\lang " << context.font.language << "\n";
4378 if (t.cs() == "foreignlanguage") {
4379 string const lang = babel2lyx(p.verbatim_item());
4380 parse_text_attributes(p, os, FLAG_ITEM, outer,
4382 context.font.language, lang);
4386 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4387 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4388 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4390 // We have to output the whole command if it has an option
4391 // because LyX doesn't support this yet, see bug #8214,
4392 // only if there is a single option specifying a variant, we can handle it.
4394 string langopts = p.getOpt();
4395 // check if the option contains a variant, if yes, extract it
4396 string::size_type pos_var = langopts.find("variant");
4397 string::size_type i = langopts.find(',');
4398 string::size_type k = langopts.find('=', pos_var);
4399 if (pos_var != string::npos && i == string::npos) {
4401 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4402 lang = preamble.polyglossia2lyx(variant);
4403 parse_text_attributes(p, os, FLAG_ITEM, outer,
4405 context.font.language, lang);
4407 output_ert_inset(os, t.asInput() + langopts, context);
4409 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4410 parse_text_attributes(p, os, FLAG_ITEM, outer,
4412 context.font.language, lang);
4417 if (t.cs() == "inputencoding") {
4418 // nothing to write here
4419 string const enc = subst(p.verbatim_item(), "\n", " ");
4420 p.setEncoding(enc, Encoding::inputenc);
4424 if (is_known(t.cs(), known_special_chars) ||
4425 (t.cs() == "protect" &&
4426 p.next_token().cat() == catEscape &&
4427 is_known(p.next_token().cs(), known_special_protect_chars))) {
4428 // LyX sometimes puts a \protect in front, so we have to ignore it
4430 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4431 known_special_chars);
4432 context.check_layout(os);
4433 os << known_coded_special_chars[where - known_special_chars];
4434 skip_spaces_braces(p);
4438 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4439 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4440 p.next_next_token().asInput() == "-") ||
4441 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4442 // LyX sometimes puts a \protect in front, so we have to ignore it
4443 if (t.cs() == "protect")
4445 context.check_layout(os);
4446 if (t.cs() == "nobreakdash")
4447 os << "\\SpecialChar nobreakdash\n";
4449 os << "\\SpecialChar endofsentence\n";
4454 if (t.cs() == "textquotedbl") {
4455 context.check_layout(os);
4461 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4462 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4463 || t.cs() == "%" || t.cs() == "-") {
4464 context.check_layout(os);
4466 os << "\\SpecialChar softhyphen\n";
4472 if (t.cs() == "char") {
4473 context.check_layout(os);
4474 if (p.next_token().character() == '`') {
4476 if (p.next_token().cs() == "\"") {
4481 output_ert_inset(os, "\\char`", context);
4484 output_ert_inset(os, "\\char", context);
4489 if (t.cs() == "verb") {
4490 context.check_layout(os);
4491 // set catcodes to verbatim early, just in case.
4492 p.setCatcodes(VERBATIM_CATCODES);
4493 string delim = p.get_token().asInput();
4494 Parser::Arg arg = p.verbatimStuff(delim);
4496 output_ert_inset(os, "\\verb" + delim
4497 + arg.second + delim, context);
4499 cerr << "invalid \\verb command. Skipping" << endl;
4503 // Problem: \= creates a tabstop inside the tabbing environment
4504 // and else an accent. In the latter case we really would want
4505 // \={o} instead of \= o.
4506 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4507 output_ert_inset(os, t.asInput(), context);
4511 if (t.cs() == "\\") {
4512 context.check_layout(os);
4514 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4515 else if (p.next_token().asInput() == "*") {
4517 // getOpt() eats the following space if there
4518 // is no optional argument, but that is OK
4519 // here since it has no effect in the output.
4520 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4523 begin_inset(os, "Newline newline");
4529 if (t.cs() == "newline" ||
4530 (t.cs() == "linebreak" && !p.hasOpt())) {
4531 context.check_layout(os);
4532 begin_inset(os, "Newline ");
4535 skip_spaces_braces(p);
4539 if (t.cs() == "input" || t.cs() == "include"
4540 || t.cs() == "verbatiminput") {
4541 string name = t.cs();
4542 if (t.cs() == "verbatiminput"
4543 && p.next_token().asInput() == "*")
4544 name += p.get_token().asInput();
4545 context.check_layout(os);
4546 string filename(normalize_filename(p.getArg('{', '}')));
4547 string const path = getMasterFilePath(true);
4548 // We want to preserve relative / absolute filenames,
4549 // therefore path is only used for testing
4550 if ((t.cs() == "include" || t.cs() == "input") &&
4551 !makeAbsPath(filename, path).exists()) {
4552 // The file extension is probably missing.
4553 // Now try to find it out.
4554 string const tex_name =
4555 find_file(filename, path,
4556 known_tex_extensions);
4557 if (!tex_name.empty())
4558 filename = tex_name;
4560 bool external = false;
4562 if (makeAbsPath(filename, path).exists()) {
4563 string const abstexname =
4564 makeAbsPath(filename, path).absFileName();
4565 string const absfigname =
4566 changeExtension(abstexname, ".fig");
4567 fix_child_filename(filename);
4568 string const lyxname = changeExtension(filename,
4569 roundtripMode() ? ".lyx.lyx" : ".lyx");
4570 string const abslyxname = makeAbsPath(
4571 lyxname, getParentFilePath(false)).absFileName();
4573 if (!skipChildren())
4574 external = FileName(absfigname).exists();
4575 if (t.cs() == "input" && !skipChildren()) {
4576 string const ext = getExtension(abstexname);
4578 // Combined PS/LaTeX:
4579 // x.eps, x.pstex_t (old xfig)
4580 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4581 FileName const absepsname(
4582 changeExtension(abstexname, ".eps"));
4583 FileName const abspstexname(
4584 changeExtension(abstexname, ".pstex"));
4585 bool const xfigeps =
4586 (absepsname.exists() ||
4587 abspstexname.exists()) &&
4590 // Combined PDF/LaTeX:
4591 // x.pdf, x.pdftex_t (old xfig)
4592 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4593 FileName const abspdfname(
4594 changeExtension(abstexname, ".pdf"));
4595 bool const xfigpdf =
4596 abspdfname.exists() &&
4597 (ext == "pdftex_t" || ext == "pdf_t");
4601 // Combined PS/PDF/LaTeX:
4602 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4603 string const absbase2(
4604 removeExtension(abstexname) + "_pspdftex");
4605 FileName const abseps2name(
4606 addExtension(absbase2, ".eps"));
4607 FileName const abspdf2name(
4608 addExtension(absbase2, ".pdf"));
4609 bool const xfigboth =
4610 abspdf2name.exists() &&
4611 abseps2name.exists() && ext == "pspdftex";
4613 xfig = xfigpdf || xfigeps || xfigboth;
4614 external = external && xfig;
4617 outname = changeExtension(filename, ".fig");
4618 FileName abssrc(changeExtension(abstexname, ".fig"));
4619 copy_file(abssrc, outname);
4621 // Don't try to convert, the result
4622 // would be full of ERT.
4624 FileName abssrc(abstexname);
4625 copy_file(abssrc, outname);
4626 } else if (t.cs() != "verbatiminput" &&
4628 tex2lyx(abstexname, FileName(abslyxname),
4631 // no need to call copy_file
4632 // tex2lyx creates the file
4635 FileName abssrc(abstexname);
4636 copy_file(abssrc, outname);
4639 cerr << "Warning: Could not find included file '"
4640 << filename << "'." << endl;
4644 begin_inset(os, "External\n");
4645 os << "\ttemplate XFig\n"
4646 << "\tfilename " << outname << '\n';
4647 registerExternalTemplatePackages("XFig");
4649 begin_command_inset(os, "include", name);
4650 outname = subst(outname, "\"", "\\\"");
4651 os << "preview false\n"
4652 "filename \"" << outname << "\"\n";
4653 if (t.cs() == "verbatiminput")
4654 preamble.registerAutomaticallyLoadedPackage("verbatim");
4660 if (t.cs() == "bibliographystyle") {
4661 // store new bibliographystyle
4662 bibliographystyle = p.verbatim_item();
4663 // If any other command than \bibliography, \addcontentsline
4664 // and \nocite{*} follows, we need to output the style
4665 // (because it might be used by that command).
4666 // Otherwise, it will automatically be output by LyX.
4669 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4670 if (t2.cat() == catBegin)
4672 if (t2.cat() != catEscape)
4674 if (t2.cs() == "nocite") {
4675 if (p.getArg('{', '}') == "*")
4677 } else if (t2.cs() == "bibliography")
4679 else if (t2.cs() == "phantomsection") {
4683 else if (t2.cs() == "addcontentsline") {
4684 // get the 3 arguments of \addcontentsline
4687 contentslineContent = p.getArg('{', '}');
4688 // if the last argument is not \refname we must output
4689 if (contentslineContent == "\\refname")
4696 output_ert_inset(os,
4697 "\\bibliographystyle{" + bibliographystyle + '}',
4703 if (t.cs() == "phantomsection") {
4704 // we only support this if it occurs between
4705 // \bibliographystyle and \bibliography
4706 if (bibliographystyle.empty())
4707 output_ert_inset(os, "\\phantomsection", context);
4711 if (t.cs() == "addcontentsline") {
4712 context.check_layout(os);
4713 // get the 3 arguments of \addcontentsline
4714 string const one = p.getArg('{', '}');
4715 string const two = p.getArg('{', '}');
4716 string const three = p.getArg('{', '}');
4717 // only if it is a \refname, we support if for the bibtex inset
4718 if (contentslineContent != "\\refname") {
4719 output_ert_inset(os,
4720 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4726 else if (t.cs() == "bibliography") {
4727 context.check_layout(os);
4729 begin_command_inset(os, "bibtex", "bibtex");
4730 if (!btprint.empty()) {
4731 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4732 // clear the string because the next BibTeX inset can be without the
4733 // \nocite{*} option
4736 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4737 // Do we have addcontentsline?
4738 if (contentslineContent == "\\refname") {
4739 BibOpts = "bibtotoc";
4740 // clear string because next BibTeX inset can be without addcontentsline
4741 contentslineContent.clear();
4743 // Do we have a bibliographystyle set?
4744 if (!bibliographystyle.empty()) {
4745 if (BibOpts.empty())
4746 BibOpts = normalize_filename(bibliographystyle);
4748 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4749 // clear it because each bibtex entry has its style
4750 // and we need an empty string to handle \phantomsection
4751 bibliographystyle.clear();
4753 os << "options " << '"' << BibOpts << '"' << "\n";
4758 if (t.cs() == "printbibliography") {
4759 context.check_layout(os);
4761 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4762 vector<string> opts = getVectorFromString(bbloptions);
4763 vector<string>::iterator it =
4764 find(opts.begin(), opts.end(), "heading=bibintoc");
4765 if (it != opts.end()) {
4767 BibOpts = "bibtotoc";
4769 bbloptions = getStringFromVector(opts);
4770 begin_command_inset(os, "bibtex", "bibtex");
4771 if (!btprint.empty()) {
4772 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4773 // clear the string because the next BibTeX inset can be without the
4774 // \nocite{*} option
4778 for (auto const & bf : preamble.biblatex_bibliographies) {
4779 if (!bibfiles.empty())
4781 bibfiles += normalize_filename(bf);
4783 if (!bibfiles.empty())
4784 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4785 // Do we have addcontentsline?
4786 if (contentslineContent == "\\refname") {
4787 BibOpts = "bibtotoc";
4788 // clear string because next BibTeX inset can be without addcontentsline
4789 contentslineContent.clear();
4791 os << "options " << '"' << BibOpts << '"' << "\n";
4792 if (!bbloptions.empty())
4793 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4795 need_commentbib = false;
4799 if (t.cs() == "bibbysection") {
4800 context.check_layout(os);
4802 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4803 vector<string> opts = getVectorFromString(bbloptions);
4804 vector<string>::iterator it =
4805 find(opts.begin(), opts.end(), "heading=bibintoc");
4806 if (it != opts.end()) {
4808 BibOpts = "bibtotoc";
4810 bbloptions = getStringFromVector(opts);
4811 begin_command_inset(os, "bibtex", "bibtex");
4812 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4814 for (auto const & bf : preamble.biblatex_bibliographies) {
4815 if (!bibfiles.empty())
4817 bibfiles += normalize_filename(bf);
4819 if (!bibfiles.empty())
4820 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4821 os << "options " << '"' << BibOpts << '"' << "\n";
4822 if (!bbloptions.empty())
4823 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4825 need_commentbib = false;
4829 if (t.cs() == "parbox") {
4830 // Test whether this is an outer box of a shaded box
4832 // swallow arguments
4833 while (p.hasOpt()) {
4835 p.skip_spaces(true);
4838 p.skip_spaces(true);
4840 if (p.next_token().cat() == catBegin)
4842 p.skip_spaces(true);
4843 Token to = p.get_token();
4844 bool shaded = false;
4845 if (to.asInput() == "\\begin") {
4846 p.skip_spaces(true);
4847 if (p.getArg('{', '}') == "shaded")
4852 parse_outer_box(p, os, FLAG_ITEM, outer,
4853 context, "parbox", "shaded");
4855 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4856 "", "", t.cs(), "", "");
4860 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4861 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4862 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4863 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4867 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4868 string backgroundcolor;
4869 preamble.registerAutomaticallyLoadedPackage("xcolor");
4870 if (t.cs() == "fcolorbox") {
4871 string const framecolor = p.getArg('{', '}');
4872 backgroundcolor = p.getArg('{', '}');
4873 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4875 backgroundcolor = p.getArg('{', '}');
4876 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4881 // FIXME: due to the compiler limit of "if" nestings
4882 // the code for the alignment was put here
4883 // put them in their own if if this is fixed
4884 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4885 || t.cs() == "shadowsize"
4886 || t.cs() == "raggedleft" || t.cs() == "centering"
4887 || t.cs() == "raggedright") {
4888 if (t.cs() == "fboxrule")
4890 if (t.cs() == "fboxsep")
4892 if (t.cs() == "shadowsize")
4894 if (t.cs() != "raggedleft" && t.cs() != "centering"
4895 && t.cs() != "raggedright") {
4896 p.skip_spaces(true);
4897 while (p.good() && p.next_token().cat() != catSpace
4898 && p.next_token().cat() != catNewline
4899 && p.next_token().cat() != catEscape) {
4900 if (t.cs() == "fboxrule")
4901 fboxrule = fboxrule + p.get_token().asInput();
4902 if (t.cs() == "fboxsep")
4903 fboxsep = fboxsep + p.get_token().asInput();
4904 if (t.cs() == "shadowsize")
4905 shadow_size = shadow_size + p.get_token().asInput();
4908 output_ert_inset(os, t.asInput(), context);
4913 //\framebox() is part of the picture environment and different from \framebox{}
4914 //\framebox{} will be parsed by parse_outer_box
4915 if (t.cs() == "framebox") {
4916 if (p.next_token().character() == '(') {
4917 //the syntax is: \framebox(x,y)[position]{content}
4918 string arg = t.asInput();
4919 arg += p.getFullParentheseArg();
4920 arg += p.getFullOpt();
4921 eat_whitespace(p, os, context, false);
4922 output_ert_inset(os, arg + '{', context);
4923 parse_text(p, os, FLAG_ITEM, outer, context);
4924 output_ert_inset(os, "}", context);
4926 //the syntax is: \framebox[width][position]{content}
4927 string special = p.getFullOpt();
4928 special += p.getOpt();
4929 parse_outer_box(p, os, FLAG_ITEM, outer,
4930 context, t.cs(), special);
4935 //\makebox() is part of the picture environment and different from \makebox{}
4936 //\makebox{} will be parsed by parse_box
4937 if (t.cs() == "makebox") {
4938 if (p.next_token().character() == '(') {
4939 //the syntax is: \makebox(x,y)[position]{content}
4940 string arg = t.asInput();
4941 arg += p.getFullParentheseArg();
4942 arg += p.getFullOpt();
4943 eat_whitespace(p, os, context, false);
4944 output_ert_inset(os, arg + '{', context);
4945 parse_text(p, os, FLAG_ITEM, outer, context);
4946 output_ert_inset(os, "}", context);
4948 //the syntax is: \makebox[width][position]{content}
4949 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4950 "", "", t.cs(), "", "");
4954 if (t.cs() == "smallskip" ||
4955 t.cs() == "medskip" ||
4956 t.cs() == "bigskip" ||
4957 t.cs() == "vfill") {
4958 context.check_layout(os);
4959 begin_inset(os, "VSpace ");
4962 skip_spaces_braces(p);
4966 if ((where = is_known(t.cs(), known_spaces))) {
4967 context.check_layout(os);
4968 begin_inset(os, "space ");
4969 os << '\\' << known_coded_spaces[where - known_spaces]
4972 // LaTeX swallows whitespace after all spaces except
4973 // "\\,". We have to do that here, too, because LyX
4974 // adds "{}" which would make the spaces significant.
4976 eat_whitespace(p, os, context, false);
4977 // LyX adds "{}" after all spaces except "\\ " and
4978 // "\\,", so we have to remove "{}".
4979 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4980 // remove the braces after "\\,", too.
4986 if (t.cs() == "newpage" ||
4987 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4988 t.cs() == "clearpage" ||
4989 t.cs() == "cleardoublepage") {
4990 context.check_layout(os);
4991 begin_inset(os, "Newpage ");
4994 skip_spaces_braces(p);
4998 if (t.cs() == "DeclareRobustCommand" ||
4999 t.cs() == "DeclareRobustCommandx" ||
5000 t.cs() == "newcommand" ||
5001 t.cs() == "newcommandx" ||
5002 t.cs() == "providecommand" ||
5003 t.cs() == "providecommandx" ||
5004 t.cs() == "renewcommand" ||
5005 t.cs() == "renewcommandx") {
5006 // DeclareRobustCommand, DeclareRobustCommandx,
5007 // providecommand and providecommandx could be handled
5008 // by parse_command(), but we need to call
5009 // add_known_command() here.
5010 string name = t.asInput();
5011 if (p.next_token().asInput() == "*") {
5012 // Starred form. Eat '*'
5016 string const command = p.verbatim_item();
5017 string const opt1 = p.getFullOpt();
5018 string const opt2 = p.getFullOpt();
5019 add_known_command(command, opt1, !opt2.empty());
5020 string const ert = name + '{' + command + '}' +
5022 '{' + p.verbatim_item() + '}';
5024 if (t.cs() == "DeclareRobustCommand" ||
5025 t.cs() == "DeclareRobustCommandx" ||
5026 t.cs() == "providecommand" ||
5027 t.cs() == "providecommandx" ||
5028 name[name.length()-1] == '*')
5029 output_ert_inset(os, ert, context);
5031 context.check_layout(os);
5032 begin_inset(os, "FormulaMacro");
5039 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5040 // let could be handled by parse_command(),
5041 // but we need to call add_known_command() here.
5042 string ert = t.asInput();
5045 if (p.next_token().cat() == catBegin) {
5046 name = p.verbatim_item();
5047 ert += '{' + name + '}';
5049 name = p.verbatim_item();
5054 if (p.next_token().cat() == catBegin) {
5055 command = p.verbatim_item();
5056 ert += '{' + command + '}';
5058 command = p.verbatim_item();
5061 // If command is known, make name known too, to parse
5062 // its arguments correctly. For this reason we also
5063 // have commands in syntax.default that are hardcoded.
5064 CommandMap::iterator it = known_commands.find(command);
5065 if (it != known_commands.end())
5066 known_commands[t.asInput()] = it->second;
5067 output_ert_inset(os, ert, context);
5071 if (t.cs() == "hspace" || t.cs() == "vspace") {
5074 string name = t.asInput();
5075 string const length = p.verbatim_item();
5078 bool valid = splitLatexLength(length, valstring, unit);
5079 bool known_hspace = false;
5080 bool known_vspace = false;
5081 bool known_unit = false;
5084 istringstream iss(valstring);
5087 if (t.cs()[0] == 'h') {
5088 if (unit == "\\fill") {
5093 known_hspace = true;
5096 if (unit == "\\smallskipamount") {
5098 known_vspace = true;
5099 } else if (unit == "\\medskipamount") {
5101 known_vspace = true;
5102 } else if (unit == "\\bigskipamount") {
5104 known_vspace = true;
5105 } else if (unit == "\\fill") {
5107 known_vspace = true;
5111 if (!known_hspace && !known_vspace) {
5112 switch (unitFromString(unit)) {
5128 //unitFromString(unit) fails for relative units like Length::PCW
5129 // therefore handle them separately
5130 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5131 || unit == "\\textwidth" || unit == "\\linewidth"
5132 || unit == "\\textheight" || unit == "\\paperheight"
5133 || unit == "\\baselineskip")
5141 // check for glue lengths
5142 bool is_gluelength = false;
5143 string gluelength = length;
5144 string::size_type i = length.find(" minus");
5145 if (i == string::npos) {
5146 i = length.find(" plus");
5147 if (i != string::npos)
5148 is_gluelength = true;
5150 is_gluelength = true;
5151 // if yes transform "9xx minus 8yy plus 7zz"
5153 if (is_gluelength) {
5154 i = gluelength.find(" minus");
5155 if (i != string::npos)
5156 gluelength.replace(i, 7, "-");
5157 i = gluelength.find(" plus");
5158 if (i != string::npos)
5159 gluelength.replace(i, 6, "+");
5162 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5163 // Literal horizontal length or known variable
5164 context.check_layout(os);
5165 begin_inset(os, "space ");
5173 if (known_unit && !known_hspace)
5174 os << "\n\\length " << translate_len(length);
5176 os << "\n\\length " << gluelength;
5178 } else if (known_unit || known_vspace || is_gluelength) {
5179 // Literal vertical length or known variable
5180 context.check_layout(os);
5181 begin_inset(os, "VSpace ");
5184 if (known_unit && !known_vspace)
5185 os << translate_len(length);
5192 // LyX can't handle other length variables in Inset VSpace/space
5197 output_ert_inset(os, name + '{' + unit + '}', context);
5198 else if (value == -1.0)
5199 output_ert_inset(os, name + "{-" + unit + '}', context);
5201 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5203 output_ert_inset(os, name + '{' + length + '}', context);
5208 // The single '=' is meant here.
5209 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5213 context.check_layout(os);
5214 docstring name = newinsetlayout->name();
5215 bool const caption = name.find(from_ascii("Caption:")) == 0;
5217 // Already done for floating minted listings.
5218 if (minted_float.empty()) {
5219 begin_inset(os, "Caption ");
5220 os << to_utf8(name.substr(8)) << '\n';
5223 // FIXME: what do we do if the prefix is not Flex: ?
5224 if (prefixIs(name, from_ascii("Flex:")))
5226 begin_inset(os, "Flex ");
5227 os << to_utf8(name) << '\n'
5228 << "status collapsed\n";
5230 if (!minted_float.empty()) {
5231 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5232 } else if (newinsetlayout->isPassThru()) {
5233 // set catcodes to verbatim early, just in case.
5234 p.setCatcodes(VERBATIM_CATCODES);
5235 string delim = p.get_token().asInput();
5237 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5238 //FIXME: handle error condition
5239 string const arg = p.verbatimStuff("}").second;
5240 Context newcontext(true, context.textclass);
5241 if (newinsetlayout->forcePlainLayout())
5242 newcontext.layout = &context.textclass.plainLayout();
5243 output_ert(os, arg, newcontext);
5245 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5248 // Minted caption insets are not closed here because
5249 // we collect everything into the caption.
5250 if (minted_float.empty())
5255 if (t.cs() == "includepdf") {
5257 string const arg = p.getArg('[', ']');
5258 map<string, string> opts;
5259 vector<string> keys;
5260 split_map(arg, opts, keys);
5261 string name = normalize_filename(p.verbatim_item());
5262 string const path = getMasterFilePath(true);
5263 // We want to preserve relative / absolute filenames,
5264 // therefore path is only used for testing
5265 if (!makeAbsPath(name, path).exists()) {
5266 // The file extension is probably missing.
5267 // Now try to find it out.
5268 char const * const pdfpages_format[] = {"pdf", 0};
5269 string const pdftex_name =
5270 find_file(name, path, pdfpages_format);
5271 if (!pdftex_name.empty()) {
5276 FileName const absname = makeAbsPath(name, path);
5277 if (absname.exists())
5279 fix_child_filename(name);
5280 copy_file(absname, name);
5282 cerr << "Warning: Could not find file '"
5283 << name << "'." << endl;
5285 context.check_layout(os);
5286 begin_inset(os, "External\n\ttemplate ");
5287 os << "PDFPages\n\tfilename "
5289 // parse the options
5290 if (opts.find("pages") != opts.end())
5291 os << "\textra LaTeX \"pages="
5292 << opts["pages"] << "\"\n";
5293 if (opts.find("angle") != opts.end())
5294 os << "\trotateAngle "
5295 << opts["angle"] << '\n';
5296 if (opts.find("origin") != opts.end()) {
5298 string const opt = opts["origin"];
5299 if (opt == "tl") ss << "topleft";
5300 if (opt == "bl") ss << "bottomleft";
5301 if (opt == "Bl") ss << "baselineleft";
5302 if (opt == "c") ss << "center";
5303 if (opt == "tc") ss << "topcenter";
5304 if (opt == "bc") ss << "bottomcenter";
5305 if (opt == "Bc") ss << "baselinecenter";
5306 if (opt == "tr") ss << "topright";
5307 if (opt == "br") ss << "bottomright";
5308 if (opt == "Br") ss << "baselineright";
5309 if (!ss.str().empty())
5310 os << "\trotateOrigin " << ss.str() << '\n';
5312 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5314 if (opts.find("width") != opts.end())
5316 << translate_len(opts["width"]) << '\n';
5317 if (opts.find("height") != opts.end())
5319 << translate_len(opts["height"]) << '\n';
5320 if (opts.find("keepaspectratio") != opts.end())
5321 os << "\tkeepAspectRatio\n";
5323 context.check_layout(os);
5324 registerExternalTemplatePackages("PDFPages");
5328 if (t.cs() == "loadgame") {
5330 string name = normalize_filename(p.verbatim_item());
5331 string const path = getMasterFilePath(true);
5332 // We want to preserve relative / absolute filenames,
5333 // therefore path is only used for testing
5334 if (!makeAbsPath(name, path).exists()) {
5335 // The file extension is probably missing.
5336 // Now try to find it out.
5337 char const * const lyxskak_format[] = {"fen", 0};
5338 string const lyxskak_name =
5339 find_file(name, path, lyxskak_format);
5340 if (!lyxskak_name.empty())
5341 name = lyxskak_name;
5343 FileName const absname = makeAbsPath(name, path);
5344 if (absname.exists())
5346 fix_child_filename(name);
5347 copy_file(absname, name);
5349 cerr << "Warning: Could not find file '"
5350 << name << "'." << endl;
5351 context.check_layout(os);
5352 begin_inset(os, "External\n\ttemplate ");
5353 os << "ChessDiagram\n\tfilename "
5356 context.check_layout(os);
5357 // after a \loadgame follows a \showboard
5358 if (p.get_token().asInput() == "showboard")
5360 registerExternalTemplatePackages("ChessDiagram");
5364 // try to see whether the string is in unicodesymbols
5365 // Only use text mode commands, since we are in text mode here,
5366 // and math commands may be invalid (bug 6797)
5367 string name = t.asInput();
5368 // handle the dingbats, cyrillic and greek
5369 if (name == "\\ding" || name == "\\textcyr" ||
5370 (name == "\\textgreek" && !preamble.usePolyglossia()))
5371 name = name + '{' + p.getArg('{', '}') + '}';
5372 // handle the ifsym characters
5373 else if (name == "\\textifsymbol") {
5374 string const optif = p.getFullOpt();
5375 string const argif = p.getArg('{', '}');
5376 name = name + optif + '{' + argif + '}';
5378 // handle the \ascii characters
5379 // the case of \ascii within braces, as LyX outputs it, is already
5380 // handled for t.cat() == catBegin
5381 else if (name == "\\ascii") {
5382 // the code is "\asci\xxx"
5383 name = "{" + name + p.get_token().asInput() + "}";
5386 // handle some TIPA special characters
5387 else if (preamble.isPackageUsed("tipa")) {
5388 if (name == "\\s") {
5389 // fromLaTeXCommand() does not yet
5390 // recognize tipa short cuts
5391 name = "\\textsyllabic";
5392 } else if (name == "\\=" &&
5393 p.next_token().asInput() == "*") {
5394 // fromLaTeXCommand() does not yet
5395 // recognize tipa short cuts
5397 name = "\\textsubbar";
5398 } else if (name == "\\textdoublevertline") {
5399 // FIXME: This is not correct,
5400 // \textvertline is higher than \textbardbl
5401 name = "\\textbardbl";
5403 } else if (name == "\\!" ) {
5404 if (p.next_token().asInput() == "b") {
5405 p.get_token(); // eat 'b'
5408 } else if (p.next_token().asInput() == "d") {
5412 } else if (p.next_token().asInput() == "g") {
5416 } else if (p.next_token().asInput() == "G") {
5418 name = "\\texthtscg";
5420 } else if (p.next_token().asInput() == "j") {
5422 name = "\\texthtbardotlessj";
5424 } else if (p.next_token().asInput() == "o") {
5426 name = "\\textbullseye";
5429 } else if (name == "\\*" ) {
5430 if (p.next_token().asInput() == "k") {
5432 name = "\\textturnk";
5434 } else if (p.next_token().asInput() == "r") {
5435 p.get_token(); // eat 'b'
5436 name = "\\textturnr";
5438 } else if (p.next_token().asInput() == "t") {
5440 name = "\\textturnt";
5442 } else if (p.next_token().asInput() == "w") {
5444 name = "\\textturnw";
5449 if ((name.size() == 2 &&
5450 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5451 p.next_token().asInput() != "*") ||
5452 is_known(name.substr(1), known_tipa_marks)) {
5453 // name is a command that corresponds to a
5454 // combining character in unicodesymbols.
5455 // Append the argument, fromLaTeXCommand()
5456 // will either convert it to a single
5457 // character or a combining sequence.
5458 name += '{' + p.verbatim_item() + '}';
5460 // now get the character from unicodesymbols
5464 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5465 Encodings::TEXT_CMD, termination, rem, &req));
5467 context.check_layout(os);
5470 output_ert_inset(os, to_utf8(rem), context);
5472 skip_spaces_braces(p);
5473 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5474 preamble.registerAutomaticallyLoadedPackage(*it);
5476 //cerr << "#: " << t << " mode: " << mode << endl;
5477 // heuristic: read up to next non-nested space
5479 string s = t.asInput();
5480 string z = p.verbatim_item();
5481 while (p.good() && z != " " && !z.empty()) {
5482 //cerr << "read: " << z << endl;
5484 z = p.verbatim_item();
5486 cerr << "found ERT: " << s << endl;
5487 output_ert_inset(os, s + ' ', context);
5490 if (t.asInput() == name &&
5491 p.next_token().asInput() == "*") {
5492 // Starred commands like \vspace*{}
5493 p.get_token(); // Eat '*'
5496 if (!parse_command(name, p, os, outer, context))
5497 output_ert_inset(os, name, context);
5503 string guessLanguage(Parser & p, string const & lang)
5505 typedef std::map<std::string, size_t> LangMap;
5506 // map from language names to number of characters
5509 for (char const * const * i = supported_CJK_languages; *i; i++)
5510 used[string(*i)] = 0;
5513 Token const t = p.get_token();
5514 // comments are not counted for any language
5515 if (t.cat() == catComment)
5517 // commands are not counted as well, but we need to detect
5518 // \begin{CJK} and switch encoding if needed
5519 if (t.cat() == catEscape) {
5520 if (t.cs() == "inputencoding") {
5521 string const enc = subst(p.verbatim_item(), "\n", " ");
5522 p.setEncoding(enc, Encoding::inputenc);
5525 if (t.cs() != "begin")
5528 // Non-CJK content is counted for lang.
5529 // We do not care about the real language here:
5530 // If we have more non-CJK contents than CJK contents,
5531 // we simply use the language that was specified as
5532 // babel main language.
5533 used[lang] += t.asInput().length();
5536 // Now we are starting an environment
5538 string const name = p.getArg('{', '}');
5539 if (name != "CJK") {
5543 // It is a CJK environment
5545 /* name = */ p.getArg('{', '}');
5546 string const encoding = p.getArg('{', '}');
5547 /* mapping = */ p.getArg('{', '}');
5548 string const encoding_old = p.getEncoding();
5549 char const * const * const where =
5550 is_known(encoding, supported_CJK_encodings);
5552 p.setEncoding(encoding, Encoding::CJK);
5554 p.setEncoding("UTF-8");
5555 string const text = p.ertEnvironment("CJK");
5556 p.setEncoding(encoding_old);
5559 // ignore contents in unknown CJK encoding
5562 // the language of the text
5564 supported_CJK_languages[where - supported_CJK_encodings];
5565 used[cjk] += text.length();
5567 LangMap::const_iterator use = used.begin();
5568 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5569 if (it->second > use->second)
5576 void check_comment_bib(ostream & os, Context & context)
5578 if (!need_commentbib)
5580 // We have a bibliography database, but no bibliography with biblatex
5581 // which is completely valid. Insert a bibtex inset in a note.
5582 context.check_layout(os);
5583 begin_inset(os, "Note Note\n");
5584 os << "status open\n";
5585 os << "\\begin_layout Plain Layout\n";
5586 begin_command_inset(os, "bibtex", "bibtex");
5588 for (auto const & bf : preamble.biblatex_bibliographies) {
5589 if (!bibfiles.empty())
5591 bibfiles += normalize_filename(bf);
5593 if (!bibfiles.empty())
5594 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5595 end_inset(os);// Bibtex
5596 os << "\\end_layout\n";
5597 end_inset(os);// Note