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, string, 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,
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
68 output_arguments(os, p, outer, false, string(), newcontext,
70 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space", ",",
320 "thinspace", "quad", "qquad", "enspace", "enskip",
321 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
322 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
323 "upbracefill", "downbracefill", 0};
325 /// the same as known_spaces with .lyx names
326 char const * const known_coded_spaces[] = { "space{}", "space{}",
327 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
328 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
329 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
330 "upbracefill{}", "downbracefill{}", 0};
332 /// known TIPA combining diacritical marks
333 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
334 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
335 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
336 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
337 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
338 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
339 "textsubring", "textsubbar", 0};
341 /// TIPA tones that need special handling
342 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
344 // string to store the float type to be able to determine the type of subfloats
345 string float_type = "";
347 // string to store the float status of minted listings
348 string minted_float = "";
350 // whether a caption has been parsed for a floating minted listing
351 bool minted_float_has_caption = false;
353 // The caption for non-floating minted listings
354 string minted_nonfloat_caption = "";
356 // Characters that have to be escaped by \\ in LaTeX
357 char const * const known_escaped_chars[] = {
358 "&", "_", "$", "%", "#", "^", "{", "}", 0};
361 /// splits "x=z, y=b" into a map and an ordered keyword vector
362 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
367 keys.resize(v.size());
368 for (size_t i = 0; i < v.size(); ++i) {
369 size_t const pos = v[i].find('=');
370 string const index = trimSpaceAndEol(v[i].substr(0, pos));
371 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
379 * Split a LaTeX length into value and unit.
380 * The latter can be a real unit like "pt", or a latex length variable
381 * like "\textwidth". The unit may contain additional stuff like glue
382 * lengths, but we don't care, because such lengths are ERT anyway.
383 * \returns true if \p value and \p unit are valid.
385 bool splitLatexLength(string const & len, string & value, string & unit)
389 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
390 //'4,5' is a valid LaTeX length number. Change it to '4.5'
391 string const length = subst(len, ',', '.');
392 if (i == string::npos)
395 if (len[0] == '\\') {
396 // We had something like \textwidth without a factor
402 value = trimSpaceAndEol(string(length, 0, i));
406 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
407 if (contains(len, '\\'))
408 unit = trimSpaceAndEol(string(len, i));
410 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
415 /// A simple function to translate a latex length to something LyX can
416 /// understand. Not perfect, but rather best-effort.
417 bool translate_len(string const & length, string & valstring, string & unit)
419 if (!splitLatexLength(length, valstring, unit))
421 // LyX uses percent values
423 istringstream iss(valstring);
428 string const percentval = oss.str();
430 if (unit.empty() || unit[0] != '\\')
432 string::size_type const i = unit.find(' ');
433 string const endlen = (i == string::npos) ? string() : string(unit, i);
434 if (unit == "\\textwidth") {
435 valstring = percentval;
436 unit = "text%" + endlen;
437 } else if (unit == "\\columnwidth") {
438 valstring = percentval;
439 unit = "col%" + endlen;
440 } else if (unit == "\\paperwidth") {
441 valstring = percentval;
442 unit = "page%" + endlen;
443 } else if (unit == "\\linewidth") {
444 valstring = percentval;
445 unit = "line%" + endlen;
446 } else if (unit == "\\paperheight") {
447 valstring = percentval;
448 unit = "pheight%" + endlen;
449 } else if (unit == "\\textheight") {
450 valstring = percentval;
451 unit = "theight%" + endlen;
452 } else if (unit == "\\baselineskip") {
453 valstring = percentval;
454 unit = "baselineskip%" + endlen;
460 /// If we have ambiguous quotation marks, make a smart guess
461 /// based on main quote style
462 string guessQuoteStyle(string in, bool const opening)
465 if (prefixIs(in, "qr")) {// straight quote
467 res = subst(res, "r", "l");
468 } else if (in == "eld") {// ``
469 if (preamble.quotesStyle() == "german")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "russian")
477 } else if (in == "erd") {// ''
478 if (preamble.quotesStyle() == "polish")
480 else if (preamble.quotesStyle() == "british")
482 else if (preamble.quotesStyle() == "french")
484 else if (preamble.quotesStyle() == "swedish")
485 res = opening ? "sld" : "srd";
486 } else if (in == "els") {// `
487 if (preamble.quotesStyle() == "german")
489 else if (preamble.quotesStyle() == "british")
491 } else if (in == "ers") {// '
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sls" : "srs";
498 } else if (in == "ard") {// >>
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ald") {// <<
506 if (preamble.quotesStyle() == "swiss")
508 else if (preamble.quotesStyle() == "french")
510 else if (preamble.quotesStyle() == "russian")
512 } else if (in == "ars") {// >
513 if (preamble.quotesStyle() == "swiss")
515 } else if (in == "als") {// <
516 if (preamble.quotesStyle() == "swiss")
518 } else if (in == "gld") {// ,,
519 if (preamble.quotesStyle() == "polish")
521 else if (preamble.quotesStyle() == "russian")
523 } else if (in == "gls") {// ,
524 if (preamble.quotesStyle() == "polish")
531 string const fromPolyglossiaEnvironment(string const s)
533 // Since \arabic is taken by the LaTeX kernel,
534 // the Arabic polyglossia environment is upcased
542 string uncapitalize(string const s)
544 docstring in = from_ascii(s);
545 char_type t = lowercase(s[0]);
551 bool isCapitalized(string const s)
553 docstring in = from_ascii(s);
554 char_type t = uppercase(s[0]);
556 return to_ascii(in) == s;
563 string translate_len(string const & length)
567 if (translate_len(length, value, unit))
569 // If the input is invalid, return what we have.
577 * Translates a LaTeX length into \p value, \p unit and
578 * \p special parts suitable for a box inset.
579 * The difference from translate_len() is that a box inset knows about
580 * some special "units" that are stored in \p special.
582 void translate_box_len(string const & length, string & value, string & unit, string & special)
584 if (translate_len(length, value, unit)) {
585 if (unit == "\\height" || unit == "\\depth" ||
586 unit == "\\totalheight" || unit == "\\width") {
587 special = unit.substr(1);
588 // The unit is not used, but LyX requires a dummy setting
600 void begin_inset(ostream & os, string const & name)
602 os << "\n\\begin_inset " << name;
606 void begin_command_inset(ostream & os, string const & name,
607 string const & latexname)
609 begin_inset(os, "CommandInset ");
610 os << name << "\nLatexCommand " << latexname << '\n';
614 void end_inset(ostream & os)
616 os << "\n\\end_inset\n\n";
620 bool skip_braces(Parser & p)
622 if (p.next_token().cat() != catBegin)
625 if (p.next_token().cat() == catEnd) {
634 /// replace LaTeX commands in \p s from the unicodesymbols file with their
636 pair<bool, docstring> convert_unicodesymbols(docstring s)
640 for (size_t i = 0; i < s.size();) {
649 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
650 Encodings::TEXT_CMD, termination, rem, &req));
651 set<string>::const_iterator it = req.begin();
652 set<string>::const_iterator en = req.end();
653 for (; it != en; ++it)
654 preamble.registerAutomaticallyLoadedPackage(*it);
657 if (s.empty() || s[0] != '\\')
661 for (auto const & c : known_escaped_chars)
662 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
667 return make_pair(res, os.str());
671 /// try to convert \p s to a valid InsetCommand argument
672 /// return whether this succeeded. If not, these command insets
673 /// get the "literate" flag.
674 pair<bool, string> convert_latexed_command_inset_arg(string s)
676 bool success = false;
678 // since we don't know the input encoding we can't use from_utf8
679 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
681 s = to_utf8(res.second);
683 // LyX cannot handle newlines in a latex command
684 return make_pair(success, subst(s, "\n", " "));
687 /// try to convert \p s to a valid InsetCommand argument
688 /// without trying to recode macros.
689 string convert_literate_command_inset_arg(string s)
691 // LyX cannot handle newlines in a latex command
692 return subst(s, "\n", " ");
695 void output_ert(ostream & os, string const & s, Context & context)
697 context.check_layout(os);
698 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
700 os << "\n\\backslash\n";
701 else if (*it == '\n') {
702 context.new_paragraph(os);
703 context.check_layout(os);
707 context.check_end_layout(os);
711 void output_ert_inset(ostream & os, string const & s, Context & context)
713 // We must have a valid layout before outputting the ERT inset.
714 context.check_layout(os);
715 Context newcontext(true, context.textclass);
716 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
717 if (layout.forcePlainLayout())
718 newcontext.layout = &context.textclass.plainLayout();
719 begin_inset(os, "ERT");
720 os << "\nstatus collapsed\n";
721 output_ert(os, s, newcontext);
726 void output_comment(Parser & p, ostream & os, string const & s,
729 if (p.next_token().cat() == catNewline)
730 output_ert_inset(os, '%' + s, context);
732 output_ert_inset(os, '%' + s + '\n', context);
736 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
737 string const & latexparam = string())
739 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
742 if (checkModule(name, command))
743 return findLayoutWithoutModule(textclass, name, command, latexparam);
748 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
749 string const & latexparam = string())
751 InsetLayout const * insetlayout =
752 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
755 if (checkModule(name, command))
756 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
761 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
762 bool eatNewline = true);
766 * Skips whitespace and braces.
767 * This should be called after a command has been parsed that is not put into
768 * ERT, and where LyX adds "{}" if needed.
770 void skip_spaces_braces(Parser & p, bool keepws = false)
772 /* The following four examples produce the same typeset output and
773 should be handled by this function:
781 // Unfortunately we need to skip comments, too.
782 // We can't use eat_whitespace since writing them after the {}
783 // results in different output in some cases.
784 bool const skipped_spaces = p.skip_spaces(true);
785 bool const skipped_braces = skip_braces(p);
786 if (keepws && skipped_spaces && !skipped_braces)
787 // put back the space (it is better handled by check_space)
788 p.unskip_spaces(true);
792 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
793 Context & context, Layout::LaTeXArgMap const & latexargs)
795 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
797 context.check_layout(os);
803 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
804 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
805 for (; lait != laend; ++lait) {
807 eat_whitespace(p, os, context, false);
808 if (lait->second.mandatory) {
809 if (p.next_token().cat() != catBegin)
811 string ldelim = to_utf8(lait->second.ldelim);
812 string rdelim = to_utf8(lait->second.rdelim);
817 p.get_token(); // eat ldelim
818 if (ldelim.size() > 1)
819 p.get_token(); // eat ldelim
821 context.check_layout(os);
824 begin_inset(os, "Argument ");
827 os << i << "\nstatus collapsed\n\n";
828 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
831 string ldelim = to_utf8(lait->second.ldelim);
832 string rdelim = to_utf8(lait->second.rdelim);
837 string tok = p.next_token().asInput();
838 // we only support delimiters with max 2 chars for now.
839 if (ldelim.size() > 1)
840 tok += p.next_next_token().asInput();
841 if (p.next_token().cat() == catEscape || tok != ldelim)
843 p.get_token(); // eat ldelim
844 if (ldelim.size() > 1)
845 p.get_token(); // eat ldelim
847 context.check_layout(os);
850 begin_inset(os, "Argument ");
853 os << i << "\nstatus collapsed\n\n";
854 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
857 eat_whitespace(p, os, context, false);
862 void output_command_layout(ostream & os, Parser & p, bool outer,
863 Context & parent_context,
864 Layout const * newlayout)
866 TeXFont const oldFont = parent_context.font;
867 // save the current font size
868 string const size = oldFont.size;
869 // reset the font size to default, because the font size switches
870 // don't affect section headings and the like
871 parent_context.font.size = Context::normalfont.size;
872 // we only need to write the font change if we have an open layout
873 if (!parent_context.atParagraphStart())
874 output_font_change(os, oldFont, parent_context.font);
875 parent_context.check_end_layout(os);
876 Context context(true, parent_context.textclass, newlayout,
877 parent_context.layout, parent_context.font);
878 if (parent_context.deeper_paragraph) {
879 // We are beginning a nested environment after a
880 // deeper paragraph inside the outer list environment.
881 // Therefore we don't need to output a "begin deeper".
882 context.need_end_deeper = true;
884 context.check_deeper(os);
885 output_arguments(os, p, outer, true, string(), context,
886 context.layout->latexargs());
887 // If we have a latex param, we eat it here.
888 if (!parent_context.latexparam.empty()) {
890 Context dummy(true, parent_context.textclass);
891 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
892 string(1, parent_context.latexparam.back()));
894 parse_text(p, os, FLAG_ITEM, outer, context);
895 output_arguments(os, p, outer, false, "post", context,
896 context.layout->postcommandargs());
897 context.check_end_layout(os);
898 if (parent_context.deeper_paragraph) {
899 // We must suppress the "end deeper" because we
900 // suppressed the "begin deeper" above.
901 context.need_end_deeper = false;
903 context.check_end_deeper(os);
904 // We don't need really a new paragraph, but
905 // we must make sure that the next item gets a \begin_layout.
906 parent_context.new_paragraph(os);
907 // Set the font size to the original value. No need to output it here
908 // (Context::begin_layout() will do that if needed)
909 parent_context.font.size = size;
914 * Output a space if necessary.
915 * This function gets called for every whitespace token.
917 * We have three cases here:
918 * 1. A space must be suppressed. Example: The lyxcode case below
919 * 2. A space may be suppressed. Example: Spaces before "\par"
920 * 3. A space must not be suppressed. Example: A space between two words
922 * We currently handle only 1. and 3 and from 2. only the case of
923 * spaces before newlines as a side effect.
925 * 2. could be used to suppress as many spaces as possible. This has two effects:
926 * - Reimporting LyX generated LaTeX files changes almost no whitespace
927 * - Superflous whitespace from non LyX generated LaTeX files is removed.
928 * The drawback is that the logic inside the function becomes
929 * complicated, and that is the reason why it is not implemented.
931 void check_space(Parser & p, ostream & os, Context & context)
933 Token const next = p.next_token();
934 Token const curr = p.curr_token();
935 // A space before a single newline and vice versa must be ignored
936 // LyX emits a newline before \end{lyxcode}.
937 // This newline must be ignored,
938 // otherwise LyX will add an additional protected space.
939 if (next.cat() == catSpace ||
940 next.cat() == catNewline ||
941 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
944 context.check_layout(os);
950 * Parse all arguments of \p command
952 void parse_arguments(string const & command,
953 vector<ArgumentType> const & template_arguments,
954 Parser & p, ostream & os, bool outer, Context & context)
956 string ert = command;
957 size_t no_arguments = template_arguments.size();
958 for (size_t i = 0; i < no_arguments; ++i) {
959 switch (template_arguments[i]) {
962 // This argument contains regular LaTeX
963 output_ert_inset(os, ert + '{', context);
964 eat_whitespace(p, os, context, false);
965 if (template_arguments[i] == required)
966 parse_text(p, os, FLAG_ITEM, outer, context);
968 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
972 // This argument consists only of a single item.
973 // The presence of '{' or not must be preserved.
975 if (p.next_token().cat() == catBegin)
976 ert += '{' + p.verbatim_item() + '}';
978 ert += p.verbatim_item();
982 // This argument may contain special characters
983 ert += '{' + p.verbatim_item() + '}';
987 // true because we must not eat whitespace
988 // if an optional arg follows we must not strip the
989 // brackets from this one
990 if (i < no_arguments - 1 &&
991 template_arguments[i+1] == optional)
992 ert += p.getFullOpt(true);
994 ert += p.getOpt(true);
998 output_ert_inset(os, ert, context);
1003 * Check whether \p command is a known command. If yes,
1004 * handle the command with all arguments.
1005 * \return true if the command was parsed, false otherwise.
1007 bool parse_command(string const & command, Parser & p, ostream & os,
1008 bool outer, Context & context)
1010 if (known_commands.find(command) != known_commands.end()) {
1011 parse_arguments(command, known_commands[command], p, os,
1019 /// Parses a minipage or parbox
1020 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1021 unsigned inner_flags, bool outer, Context & parent_context,
1022 string const & outer_type, string const & special,
1023 string inner_type, string const & frame_color,
1024 string const & background_color)
1028 string hor_pos = "l";
1029 // We need to set the height to the LaTeX default of 1\\totalheight
1030 // for the case when no height argument is given
1031 string height_value = "1";
1032 string height_unit = "in";
1033 string height_special = "totalheight";
1034 string latex_height;
1038 string width_special = "none";
1039 string thickness = "0.4pt";
1040 if (!fboxrule.empty())
1041 thickness = fboxrule;
1043 thickness = "0.4pt";
1045 if (!fboxsep.empty())
1046 separation = fboxsep;
1050 if (!shadow_size.empty())
1051 shadowsize = shadow_size;
1054 string framecolor = "black";
1055 string backgroundcolor = "none";
1056 if (!frame_color.empty())
1057 framecolor = frame_color;
1058 if (!background_color.empty())
1059 backgroundcolor = background_color;
1060 // if there is a color box around the \begin statements have not yet been parsed
1062 if (!frame_color.empty() || !background_color.empty()) {
1063 eat_whitespace(p, os, parent_context, false);
1064 p.get_token().asInput(); // the '{'
1066 if (p.next_token().asInput() == "\\begin") {
1067 p.get_token().asInput();
1069 inner_type = "minipage";
1070 inner_flags = FLAG_END;
1071 active_environments.push_back("minipage");
1074 else if (p.next_token().asInput() == "\\parbox") {
1075 p.get_token().asInput();
1076 inner_type = "parbox";
1077 inner_flags = FLAG_ITEM;
1080 else if (p.next_token().asInput() == "\\makebox") {
1081 p.get_token().asInput();
1082 inner_type = "makebox";
1083 inner_flags = FLAG_ITEM;
1085 // in case there is just \colorbox{color}{text}
1088 inner_type = "makebox";
1089 inner_flags = FLAG_BRACE_LAST;
1094 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1096 if (!inner_type.empty() && p.hasOpt()) {
1097 if (inner_type != "makebox")
1098 position = p.getArg('[', ']');
1100 latex_width = p.getArg('[', ']');
1101 translate_box_len(latex_width, width_value, width_unit, width_special);
1104 if (position != "t" && position != "c" && position != "b") {
1105 cerr << "invalid position " << position << " for "
1106 << inner_type << endl;
1110 if (inner_type != "makebox") {
1111 latex_height = p.getArg('[', ']');
1112 translate_box_len(latex_height, height_value, height_unit, height_special);
1114 string const opt = p.getArg('[', ']');
1117 if (hor_pos != "l" && hor_pos != "c" &&
1118 hor_pos != "r" && hor_pos != "s") {
1119 cerr << "invalid hor_pos " << hor_pos
1120 << " for " << inner_type << endl;
1127 inner_pos = p.getArg('[', ']');
1128 if (inner_pos != "c" && inner_pos != "t" &&
1129 inner_pos != "b" && inner_pos != "s") {
1130 cerr << "invalid inner_pos "
1131 << inner_pos << " for "
1132 << inner_type << endl;
1133 inner_pos = position;
1137 if (inner_type == "makebox")
1141 if (inner_type.empty()) {
1142 if (special.empty() && outer_type != "framebox")
1143 latex_width = "1\\columnwidth";
1146 latex_width = p2.getArg('[', ']');
1147 string const opt = p2.getArg('[', ']');
1150 if (hor_pos != "l" && hor_pos != "c" &&
1151 hor_pos != "r" && hor_pos != "s") {
1152 cerr << "invalid hor_pos " << hor_pos
1153 << " for " << outer_type << endl;
1157 if (outer_type == "framebox")
1161 } else if (inner_type != "makebox")
1162 latex_width = p.verbatim_item();
1163 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1164 // as this is LyX's standard for such cases (except for makebox)
1165 // \framebox is more special and handled below
1166 if (latex_width.empty() && inner_type != "makebox"
1167 && outer_type != "framebox")
1168 latex_width = "1\\columnwidth";
1170 translate_len(latex_width, width_value, width_unit);
1172 bool shadedparbox = false;
1173 if (inner_type == "shaded") {
1174 eat_whitespace(p, os, parent_context, false);
1175 if (outer_type == "parbox") {
1177 if (p.next_token().cat() == catBegin)
1179 eat_whitespace(p, os, parent_context, false);
1180 shadedparbox = true;
1185 // If we already read the inner box we have to push the inner env
1186 if (!outer_type.empty() && !inner_type.empty() &&
1187 (inner_flags & FLAG_END))
1188 active_environments.push_back(inner_type);
1189 bool use_ert = false;
1190 if (!outer_type.empty() && !inner_type.empty()) {
1191 // Look whether there is some content after the end of the
1192 // inner box, but before the end of the outer box.
1193 // If yes, we need to output ERT.
1195 if (inner_flags & FLAG_END)
1196 p.ertEnvironment(inner_type);
1199 p.skip_spaces(true);
1200 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1201 if ((outer_env && p.next_token().asInput() != "\\end") ||
1202 (!outer_env && p.next_token().cat() != catEnd)) {
1203 // something is between the end of the inner box and
1204 // the end of the outer box, so we need to use ERT.
1212 if (!outer_type.empty()) {
1213 if (outer_flags & FLAG_END)
1214 ss << "\\begin{" << outer_type << '}';
1216 ss << '\\' << outer_type << '{';
1217 if (!special.empty())
1221 if (!inner_type.empty()) {
1222 if (inner_type != "shaded") {
1223 if (inner_flags & FLAG_END)
1224 ss << "\\begin{" << inner_type << '}';
1226 ss << '\\' << inner_type;
1228 if (!position.empty())
1229 ss << '[' << position << ']';
1230 if (!latex_height.empty())
1231 ss << '[' << latex_height << ']';
1232 if (!inner_pos.empty())
1233 ss << '[' << inner_pos << ']';
1234 ss << '{' << latex_width << '}';
1235 if (!(inner_flags & FLAG_END))
1238 if (inner_type == "shaded")
1239 ss << "\\begin{shaded}";
1240 output_ert_inset(os, ss.str(), parent_context);
1241 if (!inner_type.empty()) {
1242 parse_text(p, os, inner_flags, outer, parent_context);
1243 if (inner_flags & FLAG_END)
1244 output_ert_inset(os, "\\end{" + inner_type + '}',
1247 output_ert_inset(os, "}", parent_context);
1249 if (!outer_type.empty()) {
1250 // If we already read the inner box we have to pop
1252 if (!inner_type.empty() && (inner_flags & FLAG_END))
1253 active_environments.pop_back();
1255 // Ensure that the end of the outer box is parsed correctly:
1256 // The opening brace has been eaten by parse_outer_box()
1257 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1258 outer_flags &= ~FLAG_ITEM;
1259 outer_flags |= FLAG_BRACE_LAST;
1261 parse_text(p, os, outer_flags, outer, parent_context);
1262 if (outer_flags & FLAG_END)
1263 output_ert_inset(os, "\\end{" + outer_type + '}',
1266 output_ert_inset(os, "}", parent_context);
1269 // LyX does not like empty positions, so we have
1270 // to set them to the LaTeX default values here.
1271 if (position.empty())
1273 if (inner_pos.empty())
1274 inner_pos = position;
1275 parent_context.check_layout(os);
1276 begin_inset(os, "Box ");
1277 if (outer_type == "framed")
1279 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1281 else if (outer_type == "shadowbox")
1282 os << "Shadowbox\n";
1283 else if ((outer_type == "shaded" && inner_type.empty()) ||
1284 (outer_type == "minipage" && inner_type == "shaded") ||
1285 (outer_type == "parbox" && inner_type == "shaded")) {
1287 preamble.registerAutomaticallyLoadedPackage("color");
1288 } else if (outer_type == "doublebox")
1289 os << "Doublebox\n";
1290 else if (outer_type.empty() || outer_type == "mbox")
1291 os << "Frameless\n";
1293 os << outer_type << '\n';
1294 os << "position \"" << position << "\"\n";
1295 os << "hor_pos \"" << hor_pos << "\"\n";
1296 if (outer_type == "mbox")
1297 os << "has_inner_box 1\n";
1298 else if (!frame_color.empty() && inner_type == "makebox")
1299 os << "has_inner_box 0\n";
1301 os << "has_inner_box " << !inner_type.empty() << "\n";
1302 os << "inner_pos \"" << inner_pos << "\"\n";
1303 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1305 if (outer_type == "mbox")
1306 os << "use_makebox 1\n";
1307 else if (!frame_color.empty())
1308 os << "use_makebox 0\n";
1310 os << "use_makebox " << (inner_type == "makebox") << '\n';
1311 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1312 os << "width \"\"\n";
1313 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1314 else if (contains(width_unit, '\\'))
1315 os << "width \"" << width_value << "in" << "\"\n";
1317 os << "width \"" << width_value << width_unit << "\"\n";
1318 if (contains(width_unit, '\\')) {
1319 width_unit.erase (0,1); // remove the leading '\'
1320 os << "special \"" << width_unit << "\"\n";
1322 os << "special \"" << width_special << "\"\n";
1323 if (contains(height_unit, '\\'))
1324 os << "height \"" << height_value << "in" << "\"\n";
1326 os << "height \"" << height_value << height_unit << "\"\n";
1327 os << "height_special \"" << height_special << "\"\n";
1328 os << "thickness \"" << thickness << "\"\n";
1329 os << "separation \"" << separation << "\"\n";
1330 os << "shadowsize \"" << shadowsize << "\"\n";
1331 os << "framecolor \"" << framecolor << "\"\n";
1332 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1333 os << "status open\n\n";
1335 // Unfortunately we can't use parse_text_in_inset:
1336 // InsetBox::forcePlainLayout() is hard coded and does not
1337 // use the inset layout. Apart from that do we call parse_text
1338 // up to two times, but need only one check_end_layout.
1339 bool const forcePlainLayout =
1340 (!inner_type.empty() || inner_type == "makebox") &&
1341 outer_type != "shaded" && outer_type != "framed";
1342 Context context(true, parent_context.textclass);
1343 if (forcePlainLayout)
1344 context.layout = &context.textclass.plainLayout();
1346 context.font = parent_context.font;
1348 // If we have no inner box the contents will be read with the outer box
1349 if (!inner_type.empty())
1350 parse_text(p, os, inner_flags, outer, context);
1352 // Ensure that the end of the outer box is parsed correctly:
1353 // The opening brace has been eaten by parse_outer_box()
1354 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1355 outer_flags &= ~FLAG_ITEM;
1356 outer_flags |= FLAG_BRACE_LAST;
1359 // Find end of outer box, output contents if inner_type is
1360 // empty and output possible comments
1361 if (!outer_type.empty()) {
1362 // If we already read the inner box we have to pop
1364 if (!inner_type.empty() && (inner_flags & FLAG_END))
1365 active_environments.pop_back();
1366 // This does not output anything but comments if
1367 // inner_type is not empty (see use_ert)
1368 parse_text(p, os, outer_flags, outer, context);
1371 context.check_end_layout(os);
1373 #ifdef PRESERVE_LAYOUT
1374 // LyX puts a % after the end of the minipage
1375 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1377 //output_comment(p, os, "dummy", parent_context);
1380 parent_context.new_paragraph(os);
1382 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1383 //output_comment(p, os, "dummy", parent_context);
1386 // We add a protected space if something real follows
1387 if (p.good() && p.next_token().cat() != catComment) {
1388 begin_inset(os, "space ~\n");
1394 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1395 active_environments.pop_back();
1396 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1397 // in this case we have to eat the the closing brace of the color box
1398 p.get_token().asInput(); // the '}'
1400 if (p.next_token().asInput() == "}") {
1401 // in this case we assume that the closing brace is from the box settings
1402 // therefore reset these values for the next box
1408 // all boxes except of Frameless and Shaded require calc
1409 if (!(outer_type.empty() || outer_type == "mbox") &&
1410 !((outer_type == "shaded" && inner_type.empty()) ||
1411 (outer_type == "minipage" && inner_type == "shaded") ||
1412 (outer_type == "parbox" && inner_type == "shaded")))
1413 preamble.registerAutomaticallyLoadedPackage("calc");
1417 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1418 Context & parent_context, string const & outer_type,
1419 string const & special)
1421 eat_whitespace(p, os, parent_context, false);
1422 if (flags & FLAG_ITEM) {
1424 if (p.next_token().cat() == catBegin)
1427 cerr << "Warning: Ignoring missing '{' after \\"
1428 << outer_type << '.' << endl;
1429 eat_whitespace(p, os, parent_context, false);
1432 unsigned int inner_flags = 0;
1434 if (outer_type == "minipage" || outer_type == "parbox") {
1435 p.skip_spaces(true);
1436 while (p.hasOpt()) {
1438 p.skip_spaces(true);
1441 p.skip_spaces(true);
1442 if (outer_type == "parbox") {
1444 if (p.next_token().cat() == catBegin)
1446 p.skip_spaces(true);
1449 if (outer_type == "shaded" || outer_type == "mbox") {
1450 // These boxes never have an inner box
1452 } else if (p.next_token().asInput() == "\\parbox") {
1453 inner = p.get_token().cs();
1454 inner_flags = FLAG_ITEM;
1455 } else if (p.next_token().asInput() == "\\begin") {
1456 // Is this a minipage or shaded box?
1459 inner = p.getArg('{', '}');
1461 if (inner == "minipage" || inner == "shaded")
1462 inner_flags = FLAG_END;
1467 if (inner_flags == FLAG_END) {
1468 if (inner != "shaded")
1472 eat_whitespace(p, os, parent_context, false);
1474 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1475 outer_type, special, inner, "", "");
1477 if (inner_flags == FLAG_ITEM) {
1479 eat_whitespace(p, os, parent_context, false);
1481 parse_box(p, os, flags, inner_flags, outer, parent_context,
1482 outer_type, special, inner, "", "");
1487 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1488 bool in_line, bool use_minted)
1490 parent_context.check_layout(os);
1491 begin_inset(os, "listings\n");
1492 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1494 while ((i = arg.find(", ")) != string::npos
1495 || (i = arg.find(",\t")) != string::npos)
1496 arg.erase(i + 1, 1);
1499 string const language = p.getArg('{', '}');
1500 p.skip_spaces(true);
1501 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1502 if (!minted_float.empty()) {
1503 arg += string(arg.empty() ? "" : ",") + minted_float;
1504 minted_nonfloat_caption.clear();
1508 os << "lstparams " << '"' << arg << '"' << '\n';
1509 if (arg.find("\\color") != string::npos)
1510 preamble.registerAutomaticallyLoadedPackage("color");
1513 os << "inline true\n";
1515 os << "inline false\n";
1516 os << "status open\n";
1517 Context context(true, parent_context.textclass);
1518 context.layout = &parent_context.textclass.plainLayout();
1519 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1520 minted_nonfloat_caption.erase(0,3);
1521 os << "\n\\begin_layout Plain Layout\n";
1522 begin_inset(os, "Caption Standard\n");
1523 Context newcontext(true, context.textclass,
1524 context.layout, 0, context.font);
1525 newcontext.check_layout(os);
1526 os << minted_nonfloat_caption << "\n";
1527 newcontext.check_end_layout(os);
1529 os << "\n\\end_layout\n";
1530 minted_nonfloat_caption.clear();
1534 // set catcodes to verbatim early, just in case.
1535 p.setCatcodes(VERBATIM_CATCODES);
1536 string delim = p.get_token().asInput();
1537 //FIXME: handler error condition
1538 s = p.verbatimStuff(delim).second;
1539 // context.new_paragraph(os);
1540 } else if (use_minted) {
1541 s = p.verbatimEnvironment("minted");
1543 s = p.verbatimEnvironment("lstlisting");
1545 output_ert(os, s, context);
1546 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1547 minted_nonfloat_caption.erase(0,3);
1548 os << "\n\\begin_layout Plain Layout\n";
1549 begin_inset(os, "Caption Standard\n");
1550 Context newcontext(true, context.textclass,
1551 context.layout, 0, context.font);
1552 newcontext.check_layout(os);
1553 os << minted_nonfloat_caption << "\n";
1554 newcontext.check_end_layout(os);
1556 os << "\n\\end_layout\n";
1557 minted_nonfloat_caption.clear();
1559 // Don't close the inset here for floating minted listings.
1560 // It will be closed at the end of the listing environment.
1561 if (!use_minted || minted_float.empty())
1564 eat_whitespace(p, os, parent_context, true);
1565 Token t = p.get_token();
1566 if (t.asInput() != "\\end") {
1567 // If anything follows, collect it into a caption.
1568 minted_float_has_caption = true;
1569 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1570 begin_inset(os, "Caption Standard\n");
1571 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1578 /// parse an unknown environment
1579 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1580 unsigned flags, bool outer,
1581 Context & parent_context)
1583 if (name == "tabbing")
1584 // We need to remember that we have to handle '\=' specially
1585 flags |= FLAG_TABBING;
1587 // We need to translate font changes and paragraphs inside the
1588 // environment to ERT if we have a non standard font.
1589 // Otherwise things like
1590 // \large\begin{foo}\huge bar\end{foo}
1592 bool const specialfont =
1593 (parent_context.font != parent_context.normalfont);
1594 bool const new_layout_allowed = parent_context.new_layout_allowed;
1596 parent_context.new_layout_allowed = false;
1597 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1598 // Try to handle options: Look if we have optional arguments,
1599 // and if so, put the brackets in ERT.
1600 while (p.hasOpt()) {
1601 p.get_token(); // eat '['
1602 output_ert_inset(os, "[", parent_context);
1603 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1604 output_ert_inset(os, "]", parent_context);
1606 parse_text_snippet(p, os, flags, outer, parent_context);
1607 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1609 parent_context.new_layout_allowed = new_layout_allowed;
1613 void parse_environment(Parser & p, ostream & os, bool outer,
1614 string & last_env, Context & parent_context)
1616 Layout const * newlayout;
1617 InsetLayout const * newinsetlayout = 0;
1618 string const name = p.getArg('{', '}');
1619 const bool is_starred = suffixIs(name, '*');
1620 string const unstarred_name = rtrim(name, "*");
1621 active_environments.push_back(name);
1623 // We use this loop and break out after a condition is met
1624 // rather than a huge else-if-chain.
1626 if (is_math_env(name)) {
1627 parent_context.check_layout(os);
1628 begin_inset(os, "Formula ");
1629 os << "\\begin{" << name << "}";
1630 parse_math(p, os, FLAG_END, MATH_MODE);
1631 os << "\\end{" << name << "}";
1633 if (is_display_math_env(name)) {
1634 // Prevent the conversion of a line break to a space
1635 // (bug 7668). This does not change the output, but
1636 // looks ugly in LyX.
1637 eat_whitespace(p, os, parent_context, false);
1642 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1643 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1644 // We must begin a new paragraph if not already done
1645 if (! parent_context.atParagraphStart()) {
1646 parent_context.check_end_layout(os);
1647 parent_context.new_paragraph(os);
1649 // save the language in the context so that it is
1650 // handled by parse_text
1651 parent_context.font.language =
1652 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1653 parse_text(p, os, FLAG_END, outer, parent_context);
1654 // Just in case the environment is empty
1655 parent_context.extra_stuff.erase();
1656 // We must begin a new paragraph to reset the language
1657 parent_context.new_paragraph(os);
1662 if (unstarred_name == "tabular" || name == "longtable"
1663 || name == "tabularx" || name == "xltabular") {
1664 eat_whitespace(p, os, parent_context, false);
1665 string width = "0pt";
1667 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1668 string const opt = p.getArg('[', ']');
1671 else if (opt == "l")
1673 else if (opt == "r")
1676 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1677 width = lyx::translate_len(p.getArg('{', '}'));
1678 eat_whitespace(p, os, parent_context, false);
1680 parent_context.check_layout(os);
1681 begin_inset(os, "Tabular ");
1682 handle_tabular(p, os, name, width, halign, parent_context);
1688 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1689 eat_whitespace(p, os, parent_context, false);
1690 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1691 eat_whitespace(p, os, parent_context, false);
1692 parent_context.check_layout(os);
1693 begin_inset(os, "Float " + unstarred_name + "\n");
1694 // store the float type for subfloats
1695 // subfloats only work with figures and tables
1696 if (unstarred_name == "figure")
1697 float_type = unstarred_name;
1698 else if (unstarred_name == "table")
1699 float_type = unstarred_name;
1703 os << "placement " << opt << '\n';
1704 if (contains(opt, "H"))
1705 preamble.registerAutomaticallyLoadedPackage("float");
1707 Floating const & fl = parent_context.textclass.floats()
1708 .getType(unstarred_name);
1709 if (!fl.floattype().empty() && fl.usesFloatPkg())
1710 preamble.registerAutomaticallyLoadedPackage("float");
1713 os << "wide " << convert<string>(is_starred)
1714 << "\nsideways false"
1715 << "\nstatus open\n\n";
1716 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1718 // We don't need really a new paragraph, but
1719 // we must make sure that the next item gets a \begin_layout.
1720 parent_context.new_paragraph(os);
1722 // the float is parsed thus delete the type
1727 if (unstarred_name == "sidewaysfigure"
1728 || unstarred_name == "sidewaystable"
1729 || unstarred_name == "sidewaysalgorithm") {
1730 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1731 eat_whitespace(p, os, parent_context, false);
1732 parent_context.check_layout(os);
1733 if (unstarred_name == "sidewaysfigure")
1734 begin_inset(os, "Float figure\n");
1735 else if (unstarred_name == "sidewaystable")
1736 begin_inset(os, "Float table\n");
1737 else if (unstarred_name == "sidewaysalgorithm")
1738 begin_inset(os, "Float algorithm\n");
1740 os << "placement " << opt << '\n';
1741 if (contains(opt, "H"))
1742 preamble.registerAutomaticallyLoadedPackage("float");
1743 os << "wide " << convert<string>(is_starred)
1744 << "\nsideways true"
1745 << "\nstatus open\n\n";
1746 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1748 // We don't need really a new paragraph, but
1749 // we must make sure that the next item gets a \begin_layout.
1750 parent_context.new_paragraph(os);
1752 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1756 if (name == "wrapfigure" || name == "wraptable") {
1757 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1758 eat_whitespace(p, os, parent_context, false);
1759 parent_context.check_layout(os);
1762 string overhang = "0col%";
1765 lines = p.getArg('[', ']');
1766 string const placement = p.getArg('{', '}');
1768 overhang = p.getArg('[', ']');
1769 string const width = p.getArg('{', '}');
1771 if (name == "wrapfigure")
1772 begin_inset(os, "Wrap figure\n");
1774 begin_inset(os, "Wrap table\n");
1775 os << "lines " << lines
1776 << "\nplacement " << placement
1777 << "\noverhang " << lyx::translate_len(overhang)
1778 << "\nwidth " << lyx::translate_len(width)
1779 << "\nstatus open\n\n";
1780 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1782 // We don't need really a new paragraph, but
1783 // we must make sure that the next item gets a \begin_layout.
1784 parent_context.new_paragraph(os);
1786 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1790 if (name == "minipage") {
1791 eat_whitespace(p, os, parent_context, false);
1792 // Test whether this is an outer box of a shaded box
1794 // swallow arguments
1795 while (p.hasOpt()) {
1797 p.skip_spaces(true);
1800 p.skip_spaces(true);
1801 Token t = p.get_token();
1802 bool shaded = false;
1803 if (t.asInput() == "\\begin") {
1804 p.skip_spaces(true);
1805 if (p.getArg('{', '}') == "shaded")
1810 parse_outer_box(p, os, FLAG_END, outer,
1811 parent_context, name, "shaded");
1813 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1814 "", "", name, "", "");
1819 if (name == "comment") {
1820 eat_whitespace(p, os, parent_context, false);
1821 parent_context.check_layout(os);
1822 begin_inset(os, "Note Comment\n");
1823 os << "status open\n";
1824 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1827 skip_braces(p); // eat {} that might by set by LyX behind comments
1828 preamble.registerAutomaticallyLoadedPackage("verbatim");
1832 if (unstarred_name == "verbatim") {
1833 // FIXME: this should go in the generic code that
1834 // handles environments defined in layout file that
1835 // have "PassThru 1". However, the code over there is
1836 // already too complicated for my taste.
1837 string const ascii_name =
1838 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1839 parent_context.new_paragraph(os);
1840 Context context(true, parent_context.textclass,
1841 &parent_context.textclass[from_ascii(ascii_name)]);
1842 string s = p.verbatimEnvironment(name);
1843 output_ert(os, s, context);
1848 if (name == "IPA") {
1849 eat_whitespace(p, os, parent_context, false);
1850 parent_context.check_layout(os);
1851 begin_inset(os, "IPA\n");
1852 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1855 preamble.registerAutomaticallyLoadedPackage("tipa");
1856 preamble.registerAutomaticallyLoadedPackage("tipx");
1860 if (name == parent_context.textclass.titlename()
1861 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1862 parse_text(p, os, FLAG_END, outer, parent_context);
1863 // Just in case the environment is empty
1864 parent_context.extra_stuff.erase();
1865 // We must begin a new paragraph
1866 parent_context.new_paragraph(os);
1871 if (name == "CJK") {
1872 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1873 // It is impossible to decide if a CJK environment was in its own paragraph or within
1874 // a line. We therefore always assume a paragraph since the latter is a rare case.
1875 eat_whitespace(p, os, parent_context, false);
1876 parent_context.check_end_layout(os);
1877 // store the encoding to be able to reset it
1878 string const encoding_old = p.getEncoding();
1879 string const encoding = p.getArg('{', '}');
1880 // FIXME: For some reason JIS does not work. Although the text
1881 // in tests/CJK.tex is identical with the SJIS version if you
1882 // convert both snippets using the recode command line utility,
1883 // the resulting .lyx file contains some extra characters if
1884 // you set buggy_encoding to false for JIS.
1885 bool const buggy_encoding = encoding == "JIS";
1886 if (!buggy_encoding)
1887 p.setEncoding(encoding, Encoding::CJK);
1889 // FIXME: This will read garbage, since the data is not encoded in utf8.
1890 p.setEncoding("UTF-8");
1892 // LyX only supports the same mapping for all CJK
1893 // environments, so we might need to output everything as ERT
1894 string const mapping = trim(p.getArg('{', '}'));
1895 char const * const * const where =
1896 is_known(encoding, supported_CJK_encodings);
1897 if (!buggy_encoding && !preamble.fontCJKSet())
1898 preamble.fontCJK(mapping);
1899 bool knownMapping = mapping == preamble.fontCJK();
1900 if (buggy_encoding || !knownMapping || !where) {
1901 parent_context.check_layout(os);
1902 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1904 // we must parse the content as verbatim because e.g. JIS can contain
1905 // normally invalid characters
1906 // FIXME: This works only for the most simple cases.
1907 // Since TeX control characters are not parsed,
1908 // things like comments are completely wrong.
1909 string const s = p.plainEnvironment("CJK");
1910 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1913 if (snip == "\\" || is_known(snip, known_escaped_chars))
1914 output_ert_inset(os, snip, parent_context);
1915 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1920 output_ert_inset(os, "\\end{" + name + "}",
1924 supported_CJK_languages[where - supported_CJK_encodings];
1925 // store the language because we must reset it at the end
1926 string const lang_old = parent_context.font.language;
1927 parent_context.font.language = lang;
1928 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1929 parent_context.font.language = lang_old;
1930 parent_context.new_paragraph(os);
1932 p.setEncoding(encoding_old);
1937 if (name == "lyxgreyedout") {
1938 eat_whitespace(p, os, parent_context, false);
1939 parent_context.check_layout(os);
1940 begin_inset(os, "Note Greyedout\n");
1941 os << "status open\n";
1942 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1945 if (!preamble.notefontcolor().empty())
1946 preamble.registerAutomaticallyLoadedPackage("color");
1950 if (name == "btSect") {
1951 eat_whitespace(p, os, parent_context, false);
1952 parent_context.check_layout(os);
1953 begin_command_inset(os, "bibtex", "bibtex");
1954 string bibstyle = "plain";
1956 bibstyle = p.getArg('[', ']');
1957 p.skip_spaces(true);
1959 string const bibfile = p.getArg('{', '}');
1960 eat_whitespace(p, os, parent_context, false);
1961 Token t = p.get_token();
1962 if (t.asInput() == "\\btPrintCited") {
1963 p.skip_spaces(true);
1964 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1966 if (t.asInput() == "\\btPrintNotCited") {
1967 p.skip_spaces(true);
1968 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1970 if (t.asInput() == "\\btPrintAll") {
1971 p.skip_spaces(true);
1972 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1974 os << "bibfiles " << '"' << bibfile << "\"\n"
1975 << "options " << '"' << bibstyle << "\"\n";
1976 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1982 if (name == "btUnit") {
1983 string const nt = p.next_next_token().cs();
1984 // Do not attempt to overwrite a former diverging multibib.
1985 // Those are output as ERT instead.
1986 if ((nt == "part" || nt == "chapter"
1987 || nt == "section" || nt == "subsection")
1988 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1989 parse_text(p, os, FLAG_END, outer, parent_context);
1990 preamble.multibib(nt);
1992 parse_unknown_environment(p, name, os, FLAG_END, outer,
1997 // This is only attempted at turn environments that consist only
1998 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
1999 // Thus we will fall through in other cases.
2000 if (name == "turn") {
2001 // We check if the next thing is a tabular[*|x]
2003 p.getArg('{', '}');// eat turn argument
2004 bool found_end = false;
2005 bool only_table = false;
2006 bool end_table = false;
2009 string envname = p.getArg('{', '}');
2010 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2011 // Now we check if the table is the only content
2012 // of the turn environment
2013 string const tenv = envname;
2014 while (!found_end && !end_table && p.good()) {
2015 envname = p.next_token().cat() == catBegin
2016 ? p.getArg('{', '}') : string();
2017 Token const & t = p.get_token();
2019 end_table = t.asInput() != "\\end"
2021 found_end = t.asInput() == "\\end"
2022 && envname == "turn";
2026 envname = p.getArg('{', '}');
2027 only_table = p.next_next_token().asInput() == "\\end"
2028 && envname == "turn";
2032 string const angle = p.getArg('{', '}');
2034 int const save_tablerotation = parent_context.tablerotation;
2035 parent_context.tablerotation = convert<int>(angle);
2036 parse_text(p, os, FLAG_END, outer, parent_context);
2037 parent_context.tablerotation = save_tablerotation;
2047 // This is only attempted at landscape environments that consist only
2048 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2049 // Other landscape environment is handled via the landscape module, thus
2050 // we will fall through in that case.
2051 if (name == "landscape") {
2052 // We check if the next thing is a longtable
2054 bool found_end = false;
2055 bool only_longtable = false;
2056 bool end_longtable = false;
2059 string envname = p.getArg('{', '}');
2060 if (envname == "longtable" || envname == "xltabular") {
2061 // Now we check if the longtable is the only content
2062 // of the landscape environment
2063 string const ltenv = envname;
2064 while (!found_end && !end_longtable && p.good()) {
2065 envname = p.next_token().cat() == catBegin
2066 ? p.getArg('{', '}') : string();
2067 Token const & t = p.get_token();
2069 end_longtable = t.asInput() != "\\end"
2070 && envname == ltenv;
2071 found_end = t.asInput() == "\\end"
2072 && envname == "landscape";
2074 if (end_longtable) {
2076 envname = p.getArg('{', '}');
2077 only_longtable = p.next_next_token().asInput() == "\\end"
2078 && envname == "landscape";
2080 if (only_longtable) {
2083 int const save_tablerotation = parent_context.tablerotation;
2084 parent_context.tablerotation = 90;
2085 parse_text(p, os, FLAG_END, outer, parent_context);
2086 parent_context.tablerotation = save_tablerotation;
2096 if (name == "framed" || name == "shaded") {
2097 eat_whitespace(p, os, parent_context, false);
2098 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2100 preamble.registerAutomaticallyLoadedPackage("framed");
2104 if (name == "listing") {
2105 minted_float = "float";
2106 eat_whitespace(p, os, parent_context, false);
2107 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2109 minted_float += "=" + opt;
2110 // If something precedes \begin{minted}, we output it at the end
2111 // as a caption, in order to keep it inside the listings inset.
2112 eat_whitespace(p, os, parent_context, true);
2114 Token const & t = p.get_token();
2115 p.skip_spaces(true);
2116 string const envname = p.next_token().cat() == catBegin
2117 ? p.getArg('{', '}') : string();
2118 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2120 minted_float_has_caption = false;
2121 string content = parse_text_snippet(p, FLAG_END, outer,
2123 size_t i = content.find("\\begin_inset listings");
2124 bool minted_env = i != string::npos;
2127 caption = content.substr(0, i);
2128 content.erase(0, i);
2130 parent_context.check_layout(os);
2131 if (minted_env && minted_float_has_caption) {
2132 eat_whitespace(p, os, parent_context, true);
2133 os << content << "\n";
2134 if (!caption.empty())
2135 os << caption << "\n";
2136 os << "\n\\end_layout\n"; // close inner layout
2137 end_inset(os); // close caption inset
2138 os << "\n\\end_layout\n"; // close outer layout
2139 } else if (!caption.empty()) {
2141 begin_inset(os, "listings\n");
2142 os << "lstparams " << '"' << minted_float << '"' << '\n';
2143 os << "inline false\n";
2144 os << "status collapsed\n";
2146 os << "\n\\begin_layout Plain Layout\n";
2147 begin_inset(os, "Caption Standard\n");
2148 Context newcontext(true, parent_context.textclass,
2149 0, 0, parent_context.font);
2150 newcontext.check_layout(os);
2151 os << caption << "\n";
2152 newcontext.check_end_layout(os);
2154 os << "\n\\end_layout\n";
2155 } else if (content.empty()) {
2156 begin_inset(os, "listings\n");
2157 os << "lstparams " << '"' << minted_float << '"' << '\n';
2158 os << "inline false\n";
2159 os << "status collapsed\n";
2161 os << content << "\n";
2163 end_inset(os); // close listings inset
2164 parent_context.check_end_layout(os);
2165 parent_context.new_paragraph(os);
2167 minted_float.clear();
2168 minted_float_has_caption = false;
2172 if (name == "lstlisting" || name == "minted") {
2173 bool use_minted = name == "minted";
2174 // with listings, we do not eat newlines here since
2175 // \begin{lstlistings}
2178 // // \begin{lstlistings}%
2181 // reads [foo] as content, whereas
2182 // // \begin{lstlistings}%
2185 // \begin{lstlistings}[foo,
2187 // reads [foo...] as argument.
2188 eat_whitespace(p, os, parent_context, false, use_minted);
2189 if (use_minted && minted_float.empty()) {
2190 // look ahead for a bottom caption
2192 bool found_end_minted = false;
2193 while (!found_end_minted && p.good()) {
2194 Token const & t = p.get_token();
2196 string const envname =
2197 p.next_token().cat() == catBegin
2198 ? p.getArg('{', '}') : string();
2199 found_end_minted = t.asInput() == "\\end"
2200 && envname == "minted";
2202 eat_whitespace(p, os, parent_context, true);
2203 Token const & t = p.get_token();
2204 p.skip_spaces(true);
2205 if (t.asInput() == "\\lyxmintcaption") {
2206 string const pos = p.getArg('[', ']');
2208 string const caption =
2209 parse_text_snippet(p, FLAG_ITEM,
2210 false, parent_context);
2211 minted_nonfloat_caption = "[b]" + caption;
2212 eat_whitespace(p, os, parent_context, true);
2217 parse_listings(p, os, parent_context, false, use_minted);
2222 if (!parent_context.new_layout_allowed) {
2223 parse_unknown_environment(p, name, os, FLAG_END, outer,
2228 // Alignment and spacing settings
2229 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2230 // therefore are totally broken!
2231 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2232 // they are commands not environments. They are furthermore switches that
2233 // can be ended by another switches, but also by commands like \footnote or
2234 // \parbox. So the only safe way is to leave them untouched.
2235 // However, we support the pseudo-environments
2236 // \begin{centering} ... \end{centering}
2237 // \begin{raggedright} ... \end{raggedright}
2238 // \begin{raggedleft} ... \end{raggedleft}
2239 // since they are used by LyX in floats (for spacing reasons)
2240 if (name == "center" || name == "centering"
2241 || name == "flushleft" || name == "raggedright"
2242 || name == "flushright" || name == "raggedleft"
2243 || name == "singlespace" || name == "onehalfspace"
2244 || name == "doublespace" || name == "spacing") {
2245 eat_whitespace(p, os, parent_context, false);
2246 // We must begin a new paragraph if not already done
2247 if (! parent_context.atParagraphStart()) {
2248 parent_context.check_end_layout(os);
2249 parent_context.new_paragraph(os);
2251 if (name == "flushleft" || name == "raggedright")
2252 parent_context.add_extra_stuff("\\align left\n");
2253 else if (name == "flushright" || name == "raggedleft")
2254 parent_context.add_extra_stuff("\\align right\n");
2255 else if (name == "center" || name == "centering")
2256 parent_context.add_extra_stuff("\\align center\n");
2257 else if (name == "singlespace")
2258 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2259 else if (name == "onehalfspace") {
2260 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2261 preamble.registerAutomaticallyLoadedPackage("setspace");
2262 } else if (name == "doublespace") {
2263 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2264 preamble.registerAutomaticallyLoadedPackage("setspace");
2265 } else if (name == "spacing") {
2266 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2267 preamble.registerAutomaticallyLoadedPackage("setspace");
2269 parse_text(p, os, FLAG_END, outer, parent_context);
2270 // Just in case the environment is empty
2271 parent_context.extra_stuff.erase();
2272 // We must begin a new paragraph to reset the alignment
2273 parent_context.new_paragraph(os);
2278 // The single '=' is meant here.
2279 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2280 eat_whitespace(p, os, parent_context, false);
2281 Context context(true, parent_context.textclass, newlayout,
2282 parent_context.layout, parent_context.font);
2283 if (parent_context.deeper_paragraph) {
2284 // We are beginning a nested environment after a
2285 // deeper paragraph inside the outer list environment.
2286 // Therefore we don't need to output a "begin deeper".
2287 context.need_end_deeper = true;
2289 parent_context.check_end_layout(os);
2290 if (last_env == name) {
2291 // we need to output a separator since LyX would export
2292 // the two environments as one otherwise (bug 5716)
2293 TeX2LyXDocClass const & textclass(parent_context.textclass);
2294 Context newcontext(true, textclass,
2295 &(textclass.defaultLayout()));
2296 newcontext.check_layout(os);
2297 begin_inset(os, "Separator plain\n");
2299 newcontext.check_end_layout(os);
2301 switch (context.layout->latextype) {
2302 case LATEX_LIST_ENVIRONMENT:
2303 context.add_par_extra_stuff("\\labelwidthstring "
2304 + p.verbatim_item() + '\n');
2307 case LATEX_BIB_ENVIRONMENT:
2308 p.verbatim_item(); // swallow next arg
2314 context.check_deeper(os);
2315 if (newlayout->keepempty) {
2316 // We need to start a new paragraph
2317 // even if it is empty.
2318 context.new_paragraph(os);
2319 context.check_layout(os);
2321 // handle known optional and required arguments
2322 if (context.layout->latextype == LATEX_ENVIRONMENT)
2323 output_arguments(os, p, outer, false, string(), context,
2324 context.layout->latexargs());
2325 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2327 output_arguments(oss, p, outer, false, string(), context,
2328 context.layout->latexargs());
2329 context.list_extra_stuff = oss.str();
2331 parse_text(p, os, FLAG_END, outer, context);
2332 if (context.layout->latextype == LATEX_ENVIRONMENT)
2333 output_arguments(os, p, outer, false, "post", context,
2334 context.layout->postcommandargs());
2335 context.check_end_layout(os);
2336 if (parent_context.deeper_paragraph) {
2337 // We must suppress the "end deeper" because we
2338 // suppressed the "begin deeper" above.
2339 context.need_end_deeper = false;
2341 context.check_end_deeper(os);
2342 parent_context.new_paragraph(os);
2344 if (!preamble.titleLayoutFound())
2345 preamble.titleLayoutFound(newlayout->intitle);
2346 set<string> const & req = newlayout->requires();
2347 set<string>::const_iterator it = req.begin();
2348 set<string>::const_iterator en = req.end();
2349 for (; it != en; ++it)
2350 preamble.registerAutomaticallyLoadedPackage(*it);
2354 // The single '=' is meant here.
2355 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2356 eat_whitespace(p, os, parent_context, false);
2357 parent_context.check_layout(os);
2358 begin_inset(os, "Flex ");
2359 docstring flex_name = newinsetlayout->name();
2360 // FIXME: what do we do if the prefix is not Flex: ?
2361 if (prefixIs(flex_name, from_ascii("Flex:")))
2362 flex_name.erase(0, 5);
2363 os << to_utf8(flex_name) << '\n'
2364 << "status collapsed\n";
2365 if (newinsetlayout->isPassThru()) {
2366 string const arg = p.verbatimEnvironment(name);
2367 Context context(true, parent_context.textclass,
2368 &parent_context.textclass.plainLayout(),
2369 parent_context.layout);
2370 output_ert(os, arg, parent_context);
2372 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2377 if (name == "appendix") {
2378 // This is no good latex style, but it works and is used in some documents...
2379 eat_whitespace(p, os, parent_context, false);
2380 parent_context.check_end_layout(os);
2381 Context context(true, parent_context.textclass, parent_context.layout,
2382 parent_context.layout, parent_context.font);
2383 context.check_layout(os);
2384 os << "\\start_of_appendix\n";
2385 parse_text(p, os, FLAG_END, outer, context);
2386 context.check_end_layout(os);
2391 if (known_environments.find(name) != known_environments.end()) {
2392 vector<ArgumentType> arguments = known_environments[name];
2393 // The last "argument" denotes wether we may translate the
2394 // environment contents to LyX
2395 // The default required if no argument is given makes us
2396 // compatible with the reLyXre environment.
2397 ArgumentType contents = arguments.empty() ?
2400 if (!arguments.empty())
2401 arguments.pop_back();
2402 // See comment in parse_unknown_environment()
2403 bool const specialfont =
2404 (parent_context.font != parent_context.normalfont);
2405 bool const new_layout_allowed =
2406 parent_context.new_layout_allowed;
2408 parent_context.new_layout_allowed = false;
2409 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2410 outer, parent_context);
2411 if (contents == verbatim)
2412 output_ert_inset(os, p.ertEnvironment(name),
2415 parse_text_snippet(p, os, FLAG_END, outer,
2417 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2419 parent_context.new_layout_allowed = new_layout_allowed;
2423 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2428 active_environments.pop_back();
2432 /// parses a comment and outputs it to \p os.
2433 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2434 bool skipNewlines = false)
2436 LASSERT(t.cat() == catComment, return);
2437 if (!t.cs().empty()) {
2438 context.check_layout(os);
2439 output_comment(p, os, t.cs(), context);
2440 if (p.next_token().cat() == catNewline) {
2441 // A newline after a comment line starts a new
2443 if (context.new_layout_allowed) {
2444 if(!context.atParagraphStart())
2445 // Only start a new paragraph if not already
2446 // done (we might get called recursively)
2447 context.new_paragraph(os);
2449 output_ert_inset(os, "\n", context);
2450 eat_whitespace(p, os, context, true);
2452 } else if (!skipNewlines) {
2453 // "%\n" combination
2460 * Reads spaces and comments until the first non-space, non-comment token.
2461 * New paragraphs (double newlines or \\par) are handled like simple spaces
2462 * if \p eatParagraph is true.
2463 * If \p eatNewline is false, newlines won't be treated as whitespace.
2464 * Spaces are skipped, but comments are written to \p os.
2466 void eat_whitespace(Parser & p, ostream & os, Context & context,
2467 bool eatParagraph, bool eatNewline)
2470 Token const & t = p.get_token();
2471 if (t.cat() == catComment)
2472 parse_comment(p, os, t, context, !eatNewline);
2473 else if ((!eatParagraph && p.isParagraph()) ||
2474 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2483 * Set a font attribute, parse text and reset the font attribute.
2484 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2485 * \param currentvalue Current value of the attribute. Is set to the new
2486 * value during parsing.
2487 * \param newvalue New value of the attribute
2489 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2490 Context & context, string const & attribute,
2491 string & currentvalue, string const & newvalue)
2493 context.check_layout(os);
2494 string const oldvalue = currentvalue;
2495 currentvalue = newvalue;
2496 os << '\n' << attribute << ' ' << newvalue << "\n";
2497 parse_text_snippet(p, os, flags, outer, context);
2498 context.check_layout(os);
2499 os << '\n' << attribute << ' ' << oldvalue << "\n";
2500 currentvalue = oldvalue;
2504 /// get the arguments of a natbib or jurabib citation command
2505 void get_cite_arguments(Parser & p, bool natbibOrder,
2506 string & before, string & after, bool const qualified = false)
2508 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2510 // text before the citation
2512 // text after the citation
2513 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2515 if (!after.empty()) {
2516 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2517 if (natbibOrder && !before.empty())
2518 swap(before, after);
2523 void copy_file(FileName const & src, string dstname)
2527 string const absParent = getParentFilePath(false);
2529 if (FileName::isAbsolute(dstname))
2530 dst = FileName(dstname);
2532 dst = makeAbsPath(dstname, absParent);
2533 FileName const srcpath = src.onlyPath();
2534 FileName const dstpath = dst.onlyPath();
2535 if (equivalent(srcpath, dstpath))
2537 if (!dstpath.isDirectory()) {
2538 if (!dstpath.createPath()) {
2539 cerr << "Warning: Could not create directory for file `"
2540 << dst.absFileName() << "´." << endl;
2544 if (dst.isReadableFile()) {
2545 if (overwriteFiles())
2546 cerr << "Warning: Overwriting existing file `"
2547 << dst.absFileName() << "´." << endl;
2549 cerr << "Warning: Not overwriting existing file `"
2550 << dst.absFileName() << "´." << endl;
2554 if (!src.copyTo(dst))
2555 cerr << "Warning: Could not copy file `" << src.absFileName()
2556 << "´ to `" << dst.absFileName() << "´." << endl;
2560 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2561 bool parse_chunk(Parser & p, ostream & os, Context & context)
2563 // check whether a chunk is possible here.
2564 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2570 // read the parameters
2571 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2572 if (!params.first) {
2577 Parser::Arg const code = p.verbatimStuff("\n@");
2582 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2583 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2587 // The last newline read is important for paragraph handling
2591 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2592 // We must have a valid layout before outputting the Chunk inset.
2593 context.check_layout(os);
2594 Context chunkcontext(true, context.textclass);
2595 chunkcontext.layout = &context.textclass.plainLayout();
2596 begin_inset(os, "Flex Chunk");
2597 os << "\nstatus open\n";
2598 if (!params.second.empty()) {
2599 chunkcontext.check_layout(os);
2600 Context paramscontext(true, context.textclass);
2601 paramscontext.layout = &context.textclass.plainLayout();
2602 begin_inset(os, "Argument 1");
2603 os << "\nstatus open\n";
2604 output_ert(os, params.second, paramscontext);
2607 output_ert(os, code.second, chunkcontext);
2615 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2616 bool is_macro(Parser & p)
2618 Token first = p.curr_token();
2619 if (first.cat() != catEscape || !p.good())
2621 if (first.cs() == "def")
2623 if (first.cs() != "global" && first.cs() != "long")
2625 Token second = p.get_token();
2627 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2628 second.cat() == catNewline || second.cat() == catComment)) {
2629 second = p.get_token();
2632 bool secondvalid = second.cat() == catEscape;
2634 bool thirdvalid = false;
2635 if (p.good() && first.cs() == "global" && secondvalid &&
2636 second.cs() == "long") {
2637 third = p.get_token();
2639 while (p.good() && !p.isParagraph() &&
2640 (third.cat() == catSpace ||
2641 third.cat() == catNewline ||
2642 third.cat() == catComment)) {
2643 third = p.get_token();
2646 thirdvalid = third.cat() == catEscape;
2648 for (int i = 0; i < pos; ++i)
2653 return (first.cs() == "global" || first.cs() == "long") &&
2654 second.cs() == "def";
2655 return first.cs() == "global" && second.cs() == "long" &&
2656 third.cs() == "def";
2660 /// Parse a macro definition (assumes that is_macro() returned true)
2661 void parse_macro(Parser & p, ostream & os, Context & context)
2663 context.check_layout(os);
2664 Token first = p.curr_token();
2667 string command = first.asInput();
2668 if (first.cs() != "def") {
2670 eat_whitespace(p, os, context, false);
2671 second = p.curr_token();
2672 command += second.asInput();
2673 if (second.cs() != "def") {
2675 eat_whitespace(p, os, context, false);
2676 third = p.curr_token();
2677 command += third.asInput();
2680 eat_whitespace(p, os, context, false);
2681 string const name = p.get_token().cs();
2682 eat_whitespace(p, os, context, false);
2688 while (p.next_token().cat() != catBegin) {
2689 if (p.next_token().cat() == catParameter) {
2694 // followed by number?
2695 if (p.next_token().cat() == catOther) {
2696 string s = p.get_token().asInput();
2698 // number = current arity + 1?
2699 if (s.size() == 1 && s[0] == arity + '0' + 1)
2704 paramtext += p.get_token().cs();
2706 paramtext += p.get_token().cs();
2711 // only output simple (i.e. compatible) macro as FormulaMacros
2712 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2714 context.check_layout(os);
2715 begin_inset(os, "FormulaMacro");
2716 os << "\n\\def" << ert;
2719 output_ert_inset(os, command + ert, context);
2723 void registerExternalTemplatePackages(string const & name)
2725 external::TemplateManager const & etm = external::TemplateManager::get();
2726 external::Template const * const et = etm.getTemplateByName(name);
2729 external::Template::Formats::const_iterator cit = et->formats.end();
2731 cit = et->formats.find("PDFLaTeX");
2732 if (cit == et->formats.end())
2733 // If the template has not specified a PDFLaTeX output,
2734 // we try the LaTeX format.
2735 cit = et->formats.find("LaTeX");
2736 if (cit == et->formats.end())
2738 vector<string>::const_iterator qit = cit->second.requirements.begin();
2739 vector<string>::const_iterator qend = cit->second.requirements.end();
2740 for (; qit != qend; ++qit)
2741 preamble.registerAutomaticallyLoadedPackage(*qit);
2744 } // anonymous namespace
2748 * Find a file with basename \p name in path \p path and an extension
2751 string find_file(string const & name, string const & path,
2752 char const * const * extensions)
2754 for (char const * const * what = extensions; *what; ++what) {
2755 string const trial = addExtension(name, *what);
2756 if (makeAbsPath(trial, path).exists())
2763 /// Convert filenames with TeX macros and/or quotes to something LyX
2765 string const normalize_filename(string const & name)
2770 Token const & t = p.get_token();
2771 if (t.cat() != catEscape)
2773 else if (t.cs() == "lyxdot") {
2774 // This is used by LyX for simple dots in relative
2778 } else if (t.cs() == "space") {
2781 } else if (t.cs() == "string") {
2782 // Convert \string" to " and \string~ to ~
2783 Token const & n = p.next_token();
2784 if (n.asInput() != "\"" && n.asInput() != "~")
2789 // Strip quotes. This is a bit complicated (see latex_path()).
2790 string full = os.str();
2791 if (!full.empty() && full[0] == '"') {
2792 string base = removeExtension(full);
2793 string ext = getExtension(full);
2794 if (!base.empty() && base[base.length()-1] == '"')
2797 return addExtension(trim(base, "\""), ext);
2798 if (full[full.length()-1] == '"')
2801 return trim(full, "\"");
2807 /// Convert \p name from TeX convention (relative to master file) to LyX
2808 /// convention (relative to .lyx file) if it is relative
2809 void fix_child_filename(string & name)
2811 string const absMasterTeX = getMasterFilePath(true);
2812 bool const isabs = FileName::isAbsolute(name);
2813 // convert from "relative to .tex master" to absolute original path
2815 name = makeAbsPath(name, absMasterTeX).absFileName();
2816 bool copyfile = copyFiles();
2817 string const absParentLyX = getParentFilePath(false);
2820 // convert from absolute original path to "relative to master file"
2821 string const rel = to_utf8(makeRelPath(from_utf8(name),
2822 from_utf8(absMasterTeX)));
2823 // re-interpret "relative to .tex file" as "relative to .lyx file"
2824 // (is different if the master .lyx file resides in a
2825 // different path than the master .tex file)
2826 string const absMasterLyX = getMasterFilePath(false);
2827 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2828 // Do not copy if the new path is impossible to create. Example:
2829 // absMasterTeX = "/foo/bar/"
2830 // absMasterLyX = "/bar/"
2831 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2832 if (contains(name, "/../"))
2839 // convert from absolute original path to
2840 // "relative to .lyx file"
2841 name = to_utf8(makeRelPath(from_utf8(abs),
2842 from_utf8(absParentLyX)));
2846 // convert from absolute original path to "relative to .lyx file"
2847 name = to_utf8(makeRelPath(from_utf8(name),
2848 from_utf8(absParentLyX)));
2853 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2854 Context & context, string const rdelim)
2856 Layout const * newlayout = 0;
2857 InsetLayout const * newinsetlayout = 0;
2858 char const * const * where = 0;
2859 // Store the latest bibliographystyle, addcontentslineContent and
2860 // nocite{*} option (needed for bibtex inset)
2862 string contentslineContent;
2863 // Some classes provide a \bibliographystyle, so do not output
2864 // any if none is explicitly set.
2865 string bibliographystyle;
2866 bool const use_natbib = isProvided("natbib");
2867 bool const use_jurabib = isProvided("jurabib");
2868 bool const use_biblatex = isProvided("biblatex")
2869 && preamble.citeEngine() != "biblatex-natbib";
2870 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2871 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2872 need_commentbib = use_biblatex || use_biblatex_natbib;
2875 // it is impossible to determine the correct encoding for non-CJK Japanese.
2876 // Therefore write a note at the beginning of the document
2877 if (is_nonCJKJapanese) {
2878 context.check_layout(os);
2879 begin_inset(os, "Note Note\n");
2880 os << "status open\n\\begin_layout Plain Layout\n"
2881 << "\\series bold\n"
2882 << "Important information:\n"
2883 << "\\end_layout\n\n"
2884 << "\\begin_layout Plain Layout\n"
2885 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2886 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2887 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2888 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2889 << " and specify the encoding using the -e command-line switch.\n"
2890 << " In addition, you might want to double check that the desired output encoding\n"
2891 << " is correctly selected in Document > Settings > Language.\n"
2892 << "\\end_layout\n";
2894 is_nonCJKJapanese = false;
2897 bool have_cycled = false;
2899 // Leave here only after at least one cycle
2900 if (have_cycled && flags & FLAG_LEAVE) {
2901 flags &= ~FLAG_LEAVE;
2905 Token const & t = p.get_token();
2907 debugToken(cerr, t, flags);
2910 if (flags & FLAG_ITEM) {
2911 if (t.cat() == catSpace)
2914 flags &= ~FLAG_ITEM;
2915 if (t.cat() == catBegin) {
2916 // skip the brace and collect everything to the next matching
2918 flags |= FLAG_BRACE_LAST;
2922 // handle only this single token, leave the loop if done
2923 flags |= FLAG_LEAVE;
2926 if (t.cat() != catEscape && t.character() == ']' &&
2927 (flags & FLAG_BRACK_LAST))
2929 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2931 string tok = t.asInput();
2932 // we only support delimiters with max 2 chars for now.
2933 if (rdelim.size() > 1)
2934 tok += p.next_token().asInput();
2935 if (t.cat() != catEscape && !rdelim.empty()
2936 && tok == rdelim && (flags & FLAG_RDELIM)) {
2937 if (rdelim.size() > 1)
2938 p.get_token(); // eat rdelim
2942 // If there is anything between \end{env} and \begin{env} we
2943 // don't need to output a separator.
2944 if (t.cat() != catSpace && t.cat() != catNewline &&
2945 t.asInput() != "\\begin")
2952 bool const starred = p.next_token().asInput() == "*";
2953 string const starredname(starred ? (t.cs() + '*') : t.cs());
2954 if (t.cat() == catMath) {
2955 // we are inside some text mode thingy, so opening new math is allowed
2956 context.check_layout(os);
2957 begin_inset(os, "Formula ");
2958 Token const & n = p.get_token();
2959 bool const display(n.cat() == catMath && outer);
2961 // TeX's $$...$$ syntax for displayed math
2963 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2965 p.get_token(); // skip the second '$' token
2967 // simple $...$ stuff
2970 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2975 // Prevent the conversion of a line break to a
2976 // space (bug 7668). This does not change the
2977 // output, but looks ugly in LyX.
2978 eat_whitespace(p, os, context, false);
2983 if (t.cat() == catSuper || t.cat() == catSub) {
2984 cerr << "catcode " << t << " illegal in text mode\n";
2988 // Basic support for quotes. We try to disambiguate
2989 // quotes from the context (e.g., a left english quote is
2990 // the same as a right german quote...).
2991 // Try to make a smart guess about the side
2992 Token const prev = p.prev_token();
2993 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2994 && prev.character() != '\n' && prev.character() != '~');
2995 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2996 context.check_layout(os);
2997 begin_inset(os, "Quotes ");
2998 os << guessQuoteStyle("eld", opening);
3004 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3005 context.check_layout(os);
3006 begin_inset(os, "Quotes ");
3007 os << guessQuoteStyle("erd", opening);
3014 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3015 context.check_layout(os);
3016 begin_inset(os, "Quotes ");
3017 os << guessQuoteStyle("ald", opening);
3024 if (t.asInput() == "<"
3025 && p.next_token().asInput() == "<") {
3026 bool has_chunk = false;
3030 has_chunk = parse_chunk(p, os, context);
3036 context.check_layout(os);
3037 begin_inset(os, "Quotes ");
3038 os << guessQuoteStyle("ard", opening);
3046 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3047 check_space(p, os, context);
3051 // babel shorthands (also used by polyglossia)
3052 // Since these can have different meanings for different languages
3053 // we import them as ERT (but they must be put in ERT to get output
3055 if (t.asInput() == "\"") {
3057 // These are known pairs. We put them together in
3058 // one ERT inset. In other cases (such as "a), only
3059 // the quotation mark is ERTed.
3060 if (p.next_token().asInput() == "\""
3061 || p.next_token().asInput() == "|"
3062 || p.next_token().asInput() == "-"
3063 || p.next_token().asInput() == "~"
3064 || p.next_token().asInput() == "="
3065 || p.next_token().asInput() == "/"
3066 || p.next_token().asInput() == "~"
3067 || p.next_token().asInput() == "'"
3068 || p.next_token().asInput() == "`"
3069 || p.next_token().asInput() == "<"
3070 || p.next_token().asInput() == ">") {
3071 s += p.next_token().asInput();
3074 output_ert_inset(os, s, context);
3078 if (t.character() == '[' && noweb_mode &&
3079 p.next_token().character() == '[') {
3080 // These can contain underscores
3082 string const s = p.getFullOpt() + ']';
3083 if (p.next_token().character() == ']')
3086 cerr << "Warning: Inserting missing ']' in '"
3087 << s << "'." << endl;
3088 output_ert_inset(os, s, context);
3092 if (t.cat() == catLetter) {
3093 context.check_layout(os);
3098 if (t.cat() == catOther ||
3099 t.cat() == catAlign ||
3100 t.cat() == catParameter) {
3101 context.check_layout(os);
3102 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3103 context.merging_hyphens_allowed &&
3104 context.font.family != "ttfamily" &&
3105 !context.layout->pass_thru) {
3106 if (p.next_next_token().asInput() == "-") {
3108 os << to_utf8(docstring(1, 0x2014));
3112 os << to_utf8(docstring(1, 0x2013));
3115 // This translates "&" to "\\&" which may be wrong...
3120 if (p.isParagraph()) {
3121 // In minted floating listings we will collect
3122 // everything into the caption, where multiple
3123 // paragraphs are forbidden.
3124 if (minted_float.empty()) {
3125 if (context.new_layout_allowed)
3126 context.new_paragraph(os);
3128 output_ert_inset(os, "\\par ", context);
3131 eat_whitespace(p, os, context, true);
3135 if (t.cat() == catActive) {
3136 context.check_layout(os);
3137 if (t.character() == '~') {
3138 if (context.layout->free_spacing)
3141 begin_inset(os, "space ~\n");
3149 if (t.cat() == catBegin) {
3150 Token const next = p.next_token();
3151 Token const end = p.next_next_token();
3152 if (next.cat() == catEnd) {
3154 Token const prev = p.prev_token();
3156 if (p.next_token().character() == '`')
3157 ; // ignore it in {}``
3159 output_ert_inset(os, "{}", context);
3160 } else if (next.cat() == catEscape &&
3161 is_known(next.cs(), known_quotes) &&
3162 end.cat() == catEnd) {
3163 // Something like {\textquoteright} (e.g.
3164 // from writer2latex). We may skip the
3165 // braces here for better readability.
3166 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3168 } else if (p.next_token().asInput() == "\\ascii") {
3169 // handle the \ascii characters
3170 // (the case without braces is handled later)
3171 // the code is "{\ascii\xxx}"
3172 p.get_token(); // eat \ascii
3173 string name2 = p.get_token().asInput();
3174 p.get_token(); // eat the final '}'
3175 string const name = "{\\ascii" + name2 + "}";
3179 // get the character from unicodesymbols
3180 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3181 Encodings::TEXT_CMD, termination, rem, &req);
3183 context.check_layout(os);
3186 output_ert_inset(os,
3187 to_utf8(rem), context);
3188 for (set<string>::const_iterator it = req.begin();
3189 it != req.end(); ++it)
3190 preamble.registerAutomaticallyLoadedPackage(*it);
3192 // we did not find a non-ert version
3193 output_ert_inset(os, name, context);
3195 context.check_layout(os);
3196 // special handling of font attribute changes
3197 Token const prev = p.prev_token();
3198 TeXFont const oldFont = context.font;
3199 if (next.character() == '[' ||
3200 next.character() == ']' ||
3201 next.character() == '*') {
3203 if (p.next_token().cat() == catEnd) {
3208 output_ert_inset(os, "{", context);
3209 parse_text_snippet(p, os,
3212 output_ert_inset(os, "}", context);
3214 } else if (! context.new_layout_allowed) {
3215 output_ert_inset(os, "{", context);
3216 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3218 output_ert_inset(os, "}", context);
3219 } else if (is_known(next.cs(), known_sizes)) {
3220 // next will change the size, so we must
3222 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3224 if (!context.atParagraphStart())
3226 << context.font.size << "\n";
3227 } else if (is_known(next.cs(), known_font_families)) {
3228 // next will change the font family, so we
3229 // must reset it here
3230 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3232 if (!context.atParagraphStart())
3234 << context.font.family << "\n";
3235 } else if (is_known(next.cs(), known_font_series)) {
3236 // next will change the font series, so we
3237 // must reset it here
3238 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3240 if (!context.atParagraphStart())
3242 << context.font.series << "\n";
3243 } else if (is_known(next.cs(), known_font_shapes)) {
3244 // next will change the font shape, so we
3245 // must reset it here
3246 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3248 if (!context.atParagraphStart())
3250 << context.font.shape << "\n";
3251 } else if (is_known(next.cs(), known_old_font_families) ||
3252 is_known(next.cs(), known_old_font_series) ||
3253 is_known(next.cs(), known_old_font_shapes)) {
3254 // next will change the font family, series
3255 // and shape, so we must reset it here
3256 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3258 if (!context.atParagraphStart())
3260 << context.font.family
3262 << context.font.series
3264 << context.font.shape << "\n";
3266 output_ert_inset(os, "{", context);
3267 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3269 output_ert_inset(os, "}", context);
3275 if (t.cat() == catEnd) {
3276 if (flags & FLAG_BRACE_LAST) {
3279 cerr << "stray '}' in text\n";
3280 output_ert_inset(os, "}", context);
3284 if (t.cat() == catComment) {
3285 parse_comment(p, os, t, context);
3290 // control sequences
3293 if (t.cs() == "(" || t.cs() == "[") {
3294 bool const simple = t.cs() == "(";
3295 context.check_layout(os);
3296 begin_inset(os, "Formula");
3297 os << " \\" << t.cs();
3298 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3299 os << '\\' << (simple ? ')' : ']');
3302 // Prevent the conversion of a line break to a
3303 // space (bug 7668). This does not change the
3304 // output, but looks ugly in LyX.
3305 eat_whitespace(p, os, context, false);
3310 if (t.cs() == "begin") {
3311 parse_environment(p, os, outer, last_env,
3316 if (t.cs() == "end") {
3317 if (flags & FLAG_END) {
3318 // eat environment name
3319 string const name = p.getArg('{', '}');
3320 if (name != active_environment())
3321 cerr << "\\end{" + name + "} does not match \\begin{"
3322 + active_environment() + "}\n";
3325 p.error("found 'end' unexpectedly");
3329 // "item" by default, but could be something else
3330 if (t.cs() == context.layout->itemcommand()) {
3332 if (context.layout->labeltype == LABEL_MANUAL) {
3333 // FIXME: This swallows comments, but we cannot use
3334 // eat_whitespace() since we must not output
3335 // anything before the item.
3336 p.skip_spaces(true);
3337 s = p.verbatimOption();
3339 p.skip_spaces(false);
3341 context.check_layout(os);
3342 if (context.has_item) {
3343 // An item in an unknown list-like environment
3344 // FIXME: Do this in check_layout()!
3345 context.has_item = false;
3346 string item = "\\" + context.layout->itemcommand();
3349 output_ert_inset(os, item, context);
3351 if (context.layout->labeltype != LABEL_MANUAL)
3352 output_arguments(os, p, outer, false, "item", context,
3353 context.layout->itemargs());
3354 if (!context.list_extra_stuff.empty()) {
3355 os << context.list_extra_stuff;
3356 context.list_extra_stuff.clear();
3358 else if (!s.empty()) {
3359 // LyX adds braces around the argument,
3360 // so we need to remove them here.
3361 if (s.size() > 2 && s[0] == '{' &&
3362 s[s.size()-1] == '}')
3363 s = s.substr(1, s.size()-2);
3364 // If the argument contains a space we
3365 // must put it into ERT: Otherwise LyX
3366 // would misinterpret the space as
3367 // item delimiter (bug 7663)
3368 if (contains(s, ' ')) {
3369 output_ert_inset(os, s, context);
3372 os << parse_text_snippet(p2,
3373 FLAG_BRACK_LAST, outer, context);
3375 // The space is needed to separate the
3376 // item from the rest of the sentence.
3378 eat_whitespace(p, os, context, false);
3383 if (t.cs() == "bibitem") {
3385 context.check_layout(os);
3386 eat_whitespace(p, os, context, false);
3387 string label = p.verbatimOption();
3388 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3389 bool const literal = !lbl.first;
3390 label = literal ? subst(label, "\n", " ") : lbl.second;
3391 string lit = literal ? "\"true\"" : "\"false\"";
3392 string key = convert_literate_command_inset_arg(p.verbatim_item());
3393 begin_command_inset(os, "bibitem", "bibitem");
3394 os << "label \"" << label << "\"\n"
3395 << "key \"" << key << "\"\n"
3396 << "literal " << lit << "\n";
3402 // catch the case of \def\inputGnumericTable
3404 if (t.cs() == "def") {
3405 Token second = p.next_token();
3406 if (second.cs() == "inputGnumericTable") {
3410 Token third = p.get_token();
3412 if (third.cs() == "input") {
3416 string name = normalize_filename(p.verbatim_item());
3417 string const path = getMasterFilePath(true);
3418 // We want to preserve relative / absolute filenames,
3419 // therefore path is only used for testing
3420 // The file extension is in every case ".tex".
3421 // So we need to remove this extension and check for
3422 // the original one.
3423 name = removeExtension(name);
3424 if (!makeAbsPath(name, path).exists()) {
3425 char const * const Gnumeric_formats[] = {"gnumeric",
3427 string const Gnumeric_name =
3428 find_file(name, path, Gnumeric_formats);
3429 if (!Gnumeric_name.empty())
3430 name = Gnumeric_name;
3432 FileName const absname = makeAbsPath(name, path);
3433 if (absname.exists()) {
3434 fix_child_filename(name);
3435 copy_file(absname, name);
3437 cerr << "Warning: Could not find file '"
3438 << name << "'." << endl;
3439 context.check_layout(os);
3440 begin_inset(os, "External\n\ttemplate ");
3441 os << "GnumericSpreadsheet\n\tfilename "
3444 context.check_layout(os);
3446 // register the packages that are automatically loaded
3447 // by the Gnumeric template
3448 registerExternalTemplatePackages("GnumericSpreadsheet");
3453 parse_macro(p, os, context);
3457 if (t.cs() == "noindent") {
3459 context.add_par_extra_stuff("\\noindent\n");
3463 if (t.cs() == "appendix") {
3464 context.add_par_extra_stuff("\\start_of_appendix\n");
3465 // We need to start a new paragraph. Otherwise the
3466 // appendix in 'bla\appendix\chapter{' would start
3468 context.new_paragraph(os);
3469 // We need to make sure that the paragraph is
3470 // generated even if it is empty. Otherwise the
3471 // appendix in '\par\appendix\par\chapter{' would
3473 context.check_layout(os);
3474 // FIXME: This is a hack to prevent paragraph
3475 // deletion if it is empty. Handle this better!
3476 output_comment(p, os,
3477 "dummy comment inserted by tex2lyx to "
3478 "ensure that this paragraph is not empty",
3480 // Both measures above may generate an additional
3481 // empty paragraph, but that does not hurt, because
3482 // whitespace does not matter here.
3483 eat_whitespace(p, os, context, true);
3487 // Must catch empty dates before findLayout is called below
3488 if (t.cs() == "date") {
3489 eat_whitespace(p, os, context, false);
3491 string const date = p.verbatim_item();
3494 preamble.suppressDate(true);
3497 preamble.suppressDate(false);
3498 if (context.new_layout_allowed &&
3499 (newlayout = findLayout(context.textclass,
3502 output_command_layout(os, p, outer,
3503 context, newlayout);
3504 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3505 if (!preamble.titleLayoutFound())
3506 preamble.titleLayoutFound(newlayout->intitle);
3507 set<string> const & req = newlayout->requires();
3508 set<string>::const_iterator it = req.begin();
3509 set<string>::const_iterator en = req.end();
3510 for (; it != en; ++it)
3511 preamble.registerAutomaticallyLoadedPackage(*it);
3513 output_ert_inset(os,
3514 "\\date{" + p.verbatim_item() + '}',
3520 // Before we look for the layout name with star and alone below, we check the layouts including
3521 // the LateXParam, which might be one or several options or a star.
3522 // The single '=' is meant here.
3523 if (context.new_layout_allowed &&
3524 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3525 // store the latexparam here. This is eaten in output_command_layout
3526 context.latexparam = newlayout->latexparam();
3528 output_command_layout(os, p, outer, context, newlayout);
3529 context.latexparam.clear();
3531 if (!preamble.titleLayoutFound())
3532 preamble.titleLayoutFound(newlayout->intitle);
3533 set<string> const & req = newlayout->requires();
3534 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3535 preamble.registerAutomaticallyLoadedPackage(*it);
3539 // Starred section headings
3540 // Must attempt to parse "Section*" before "Section".
3541 if ((p.next_token().asInput() == "*") &&
3542 context.new_layout_allowed &&
3543 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3546 output_command_layout(os, p, outer, context, newlayout);
3548 if (!preamble.titleLayoutFound())
3549 preamble.titleLayoutFound(newlayout->intitle);
3550 set<string> const & req = newlayout->requires();
3551 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3552 preamble.registerAutomaticallyLoadedPackage(*it);
3556 // Section headings and the like
3557 if (context.new_layout_allowed &&
3558 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3560 output_command_layout(os, p, outer, context, newlayout);
3562 if (!preamble.titleLayoutFound())
3563 preamble.titleLayoutFound(newlayout->intitle);
3564 set<string> const & req = newlayout->requires();
3565 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3566 preamble.registerAutomaticallyLoadedPackage(*it);
3570 if (t.cs() == "subfloat") {
3571 // the syntax is \subfloat[list entry][sub caption]{content}
3572 // if it is a table of figure depends on the surrounding float
3574 // do nothing if there is no outer float
3575 if (!float_type.empty()) {
3576 context.check_layout(os);
3578 begin_inset(os, "Float " + float_type + "\n");
3580 << "\nsideways false"
3581 << "\nstatus collapsed\n\n";
3584 bool has_caption = false;
3585 if (p.next_token().cat() != catEscape &&
3586 p.next_token().character() == '[') {
3587 p.get_token(); // eat '['
3588 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3591 // In case we have two optional args, the second is the caption.
3592 if (p.next_token().cat() != catEscape &&
3593 p.next_token().character() == '[') {
3594 p.get_token(); // eat '['
3595 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3598 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3599 // the caption comes always as the last
3601 // we must make sure that the caption gets a \begin_layout
3602 os << "\n\\begin_layout Plain Layout";
3604 begin_inset(os, "Caption Standard\n");
3605 Context newcontext(true, context.textclass,
3606 0, 0, context.font);
3607 newcontext.check_layout(os);
3608 os << caption << "\n";
3609 newcontext.check_end_layout(os);
3612 // close the layout we opened
3613 os << "\n\\end_layout";
3618 // if the float type is not supported or there is no surrounding float
3623 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3625 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3627 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3628 + "{" + p.verbatim_item() + '}', context);
3633 if (t.cs() == "xymatrix") {
3634 // we must open a new math because LyX's xy support is in math
3635 context.check_layout(os);
3636 begin_inset(os, "Formula ");
3638 os << "\\" << t.cs() << '{';
3639 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3642 preamble.registerAutomaticallyLoadedPackage("xy");
3646 if (t.cs() == "includegraphics") {
3647 bool const clip = p.next_token().asInput() == "*";
3650 string const arg = p.getArg('[', ']');
3651 map<string, string> opts;
3652 vector<string> keys;
3653 split_map(arg, opts, keys);
3655 opts["clip"] = string();
3656 string name = normalize_filename(p.verbatim_item());
3658 string const path = getMasterFilePath(true);
3659 // We want to preserve relative / absolute filenames,
3660 // therefore path is only used for testing
3661 if (!makeAbsPath(name, path).exists()) {
3662 // The file extension is probably missing.
3663 // Now try to find it out.
3664 string const dvips_name =
3665 find_file(name, path,
3666 known_dvips_graphics_formats);
3667 string const pdftex_name =
3668 find_file(name, path,
3669 known_pdftex_graphics_formats);
3670 if (!dvips_name.empty()) {
3671 if (!pdftex_name.empty()) {
3672 cerr << "This file contains the "
3674 "\"\\includegraphics{"
3676 "However, files\n\""
3677 << dvips_name << "\" and\n\""
3678 << pdftex_name << "\"\n"
3679 "both exist, so I had to make a "
3680 "choice and took the first one.\n"
3681 "Please move the unwanted one "
3682 "someplace else and try again\n"
3683 "if my choice was wrong."
3687 } else if (!pdftex_name.empty()) {
3693 FileName const absname = makeAbsPath(name, path);
3694 if (absname.exists()) {
3695 fix_child_filename(name);
3696 copy_file(absname, name);
3698 cerr << "Warning: Could not find graphics file '"
3699 << name << "'." << endl;
3701 context.check_layout(os);
3702 begin_inset(os, "Graphics ");
3703 os << "\n\tfilename " << name << '\n';
3704 if (opts.find("width") != opts.end())
3706 << translate_len(opts["width"]) << '\n';
3707 if (opts.find("height") != opts.end())
3709 << translate_len(opts["height"]) << '\n';
3710 if (opts.find("scale") != opts.end()) {
3711 istringstream iss(opts["scale"]);
3715 os << "\tscale " << val << '\n';
3717 if (opts.find("angle") != opts.end()) {
3718 os << "\trotateAngle "
3719 << opts["angle"] << '\n';
3720 vector<string>::const_iterator a =
3721 find(keys.begin(), keys.end(), "angle");
3722 vector<string>::const_iterator s =
3723 find(keys.begin(), keys.end(), "width");
3724 if (s == keys.end())
3725 s = find(keys.begin(), keys.end(), "height");
3726 if (s == keys.end())
3727 s = find(keys.begin(), keys.end(), "scale");
3728 if (s != keys.end() && distance(s, a) > 0)
3729 os << "\tscaleBeforeRotation\n";
3731 if (opts.find("origin") != opts.end()) {
3733 string const opt = opts["origin"];
3734 if (opt.find('l') != string::npos) ss << "left";
3735 if (opt.find('r') != string::npos) ss << "right";
3736 if (opt.find('c') != string::npos) ss << "center";
3737 if (opt.find('t') != string::npos) ss << "Top";
3738 if (opt.find('b') != string::npos) ss << "Bottom";
3739 if (opt.find('B') != string::npos) ss << "Baseline";
3740 if (!ss.str().empty())
3741 os << "\trotateOrigin " << ss.str() << '\n';
3743 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3745 if (opts.find("keepaspectratio") != opts.end())
3746 os << "\tkeepAspectRatio\n";
3747 if (opts.find("clip") != opts.end())
3749 if (opts.find("draft") != opts.end())
3751 if (opts.find("bb") != opts.end())
3752 os << "\tBoundingBox "
3753 << opts["bb"] << '\n';
3754 int numberOfbbOptions = 0;
3755 if (opts.find("bbllx") != opts.end())
3756 numberOfbbOptions++;
3757 if (opts.find("bblly") != opts.end())
3758 numberOfbbOptions++;
3759 if (opts.find("bburx") != opts.end())
3760 numberOfbbOptions++;
3761 if (opts.find("bbury") != opts.end())
3762 numberOfbbOptions++;
3763 if (numberOfbbOptions == 4)
3764 os << "\tBoundingBox "
3765 << opts["bbllx"] << " " << opts["bblly"] << " "
3766 << opts["bburx"] << " " << opts["bbury"] << '\n';
3767 else if (numberOfbbOptions > 0)
3768 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3769 numberOfbbOptions = 0;
3770 if (opts.find("natwidth") != opts.end())
3771 numberOfbbOptions++;
3772 if (opts.find("natheight") != opts.end())
3773 numberOfbbOptions++;
3774 if (numberOfbbOptions == 2)
3775 os << "\tBoundingBox 0bp 0bp "
3776 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3777 else if (numberOfbbOptions > 0)
3778 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3779 ostringstream special;
3780 if (opts.find("hiresbb") != opts.end())
3781 special << "hiresbb,";
3782 if (opts.find("trim") != opts.end())
3784 if (opts.find("viewport") != opts.end())
3785 special << "viewport=" << opts["viewport"] << ',';
3786 if (opts.find("totalheight") != opts.end())
3787 special << "totalheight=" << opts["totalheight"] << ',';
3788 if (opts.find("type") != opts.end())
3789 special << "type=" << opts["type"] << ',';
3790 if (opts.find("ext") != opts.end())
3791 special << "ext=" << opts["ext"] << ',';
3792 if (opts.find("read") != opts.end())
3793 special << "read=" << opts["read"] << ',';
3794 if (opts.find("command") != opts.end())
3795 special << "command=" << opts["command"] << ',';
3796 string s_special = special.str();
3797 if (!s_special.empty()) {
3798 // We had special arguments. Remove the trailing ','.
3799 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3801 // TODO: Handle the unknown settings better.
3802 // Warn about invalid options.
3803 // Check whether some option was given twice.
3805 preamble.registerAutomaticallyLoadedPackage("graphicx");
3809 if (t.cs() == "footnote" ||
3810 (t.cs() == "thanks" && context.layout->intitle)) {
3812 context.check_layout(os);
3813 begin_inset(os, "Foot\n");
3814 os << "status collapsed\n\n";
3815 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3820 if (t.cs() == "marginpar") {
3822 context.check_layout(os);
3823 begin_inset(os, "Marginal\n");
3824 os << "status collapsed\n\n";
3825 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3830 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3831 bool const use_minted = t.cs() == "mintinline";
3833 parse_listings(p, os, context, true, use_minted);
3837 if (t.cs() == "ensuremath") {
3839 context.check_layout(os);
3840 string const s = p.verbatim_item();
3841 //FIXME: this never triggers in UTF8
3842 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3845 output_ert_inset(os, "\\ensuremath{" + s + "}",
3850 else if (t.cs() == "makeindex"
3851 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3852 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3853 if (preamble.titleLayoutFound()) {
3855 skip_spaces_braces(p);
3857 output_ert_inset(os, t.asInput(), context);
3861 if (t.cs() == "tableofcontents"
3862 || t.cs() == "lstlistoflistings"
3863 || t.cs() == "listoflistings") {
3864 string name = t.cs();
3865 if (preamble.minted() && name == "listoflistings")
3866 name.insert(0, "lst");
3867 context.check_layout(os);
3868 begin_command_inset(os, "toc", name);
3870 skip_spaces_braces(p);
3871 if (name == "lstlistoflistings") {
3872 if (preamble.minted())
3873 preamble.registerAutomaticallyLoadedPackage("minted");
3875 preamble.registerAutomaticallyLoadedPackage("listings");
3880 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3881 context.check_layout(os);
3882 if (t.cs() == "listoffigures")
3883 begin_inset(os, "FloatList figure\n");
3885 begin_inset(os, "FloatList table\n");
3887 skip_spaces_braces(p);
3891 if (t.cs() == "listof") {
3892 p.skip_spaces(true);
3893 string const name = p.get_token().cs();
3894 if (context.textclass.floats().typeExist(name)) {
3895 context.check_layout(os);
3896 begin_inset(os, "FloatList ");
3899 p.get_token(); // swallow second arg
3901 output_ert_inset(os, "\\listof{" + name + "}", context);
3905 if ((where = is_known(t.cs(), known_text_font_families))) {
3906 parse_text_attributes(p, os, FLAG_ITEM, outer,
3907 context, "\\family", context.font.family,
3908 known_coded_font_families[where - known_text_font_families]);
3912 // beamer has a \textbf<overlay>{} inset
3913 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3914 parse_text_attributes(p, os, FLAG_ITEM, outer,
3915 context, "\\series", context.font.series,
3916 known_coded_font_series[where - known_text_font_series]);
3920 // beamer has a \textit<overlay>{} inset
3921 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3922 parse_text_attributes(p, os, FLAG_ITEM, outer,
3923 context, "\\shape", context.font.shape,
3924 known_coded_font_shapes[where - known_text_font_shapes]);
3928 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3929 context.check_layout(os);
3930 TeXFont oldFont = context.font;
3931 context.font.init();
3932 context.font.size = oldFont.size;
3933 os << "\n\\family " << context.font.family << "\n";
3934 os << "\n\\series " << context.font.series << "\n";
3935 os << "\n\\shape " << context.font.shape << "\n";
3936 if (t.cs() == "textnormal") {
3937 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3938 output_font_change(os, context.font, oldFont);
3939 context.font = oldFont;
3941 eat_whitespace(p, os, context, false);
3945 if (t.cs() == "textcolor") {
3946 // scheme is \textcolor{color name}{text}
3947 string const color = p.verbatim_item();
3948 // we support the predefined colors of the color and the xcolor package
3949 if (color == "black" || color == "blue" || color == "cyan"
3950 || color == "green" || color == "magenta" || color == "red"
3951 || color == "white" || color == "yellow") {
3952 context.check_layout(os);
3953 os << "\n\\color " << color << "\n";
3954 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3955 context.check_layout(os);
3956 os << "\n\\color inherit\n";
3957 preamble.registerAutomaticallyLoadedPackage("color");
3958 } else if (color == "brown" || color == "darkgray" || color == "gray"
3959 || color == "lightgray" || color == "lime" || color == "olive"
3960 || color == "orange" || color == "pink" || color == "purple"
3961 || color == "teal" || color == "violet") {
3962 context.check_layout(os);
3963 os << "\n\\color " << color << "\n";
3964 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3965 context.check_layout(os);
3966 os << "\n\\color inherit\n";
3967 preamble.registerAutomaticallyLoadedPackage("xcolor");
3969 // for custom defined colors
3970 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3974 if (t.cs() == "underbar" || t.cs() == "uline") {
3975 // \underbar is not 100% correct (LyX outputs \uline
3976 // of ulem.sty). The difference is that \ulem allows
3977 // line breaks, and \underbar does not.
3978 // Do NOT handle \underline.
3979 // \underbar cuts through y, g, q, p etc.,
3980 // \underline does not.
3981 context.check_layout(os);
3982 os << "\n\\bar under\n";
3983 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3984 context.check_layout(os);
3985 os << "\n\\bar default\n";
3986 preamble.registerAutomaticallyLoadedPackage("ulem");
3990 if (t.cs() == "sout") {
3991 context.check_layout(os);
3992 os << "\n\\strikeout on\n";
3993 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3994 context.check_layout(os);
3995 os << "\n\\strikeout default\n";
3996 preamble.registerAutomaticallyLoadedPackage("ulem");
4000 // beamer has an \emph<overlay>{} inset
4001 if ((t.cs() == "uuline" || t.cs() == "uwave"
4002 || t.cs() == "emph" || t.cs() == "noun"
4003 || t.cs() == "xout") && !p.hasOpt("<")) {
4004 context.check_layout(os);
4005 os << "\n\\" << t.cs() << " on\n";
4006 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4007 context.check_layout(os);
4008 os << "\n\\" << t.cs() << " default\n";
4009 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4010 preamble.registerAutomaticallyLoadedPackage("ulem");
4014 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
4015 context.check_layout(os);
4016 string name = p.getArg('{', '}');
4017 string localtime = p.getArg('{', '}');
4018 preamble.registerAuthor(name);
4019 Author const & author = preamble.getAuthor(name);
4020 // from_asctime_utc() will fail if LyX decides to output the
4021 // time in the text language.
4022 time_t ptime = from_asctime_utc(localtime);
4023 if (ptime == static_cast<time_t>(-1)) {
4024 cerr << "Warning: Could not parse time `" << localtime
4025 << "´ for change tracking, using current time instead.\n";
4026 ptime = current_time();
4028 if (t.cs() == "lyxadded")
4029 os << "\n\\change_inserted ";
4031 os << "\n\\change_deleted ";
4032 os << author.bufferId() << ' ' << ptime << '\n';
4033 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4034 bool dvipost = LaTeXPackages::isAvailable("dvipost");
4035 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4036 LaTeXPackages::isAvailable("xcolor");
4037 // No need to test for luatex, since luatex comes in
4038 // two flavours (dvi and pdf), like latex, and those
4039 // are detected by pdflatex.
4040 if (pdflatex || xetex) {
4042 preamble.registerAutomaticallyLoadedPackage("ulem");
4043 preamble.registerAutomaticallyLoadedPackage("xcolor");
4044 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4048 preamble.registerAutomaticallyLoadedPackage("dvipost");
4049 } else if (xcolorulem) {
4050 preamble.registerAutomaticallyLoadedPackage("ulem");
4051 preamble.registerAutomaticallyLoadedPackage("xcolor");
4057 if (t.cs() == "textipa") {
4058 context.check_layout(os);
4059 begin_inset(os, "IPA\n");
4060 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4061 context.merging_hyphens_allowed = false;
4062 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4063 context.merging_hyphens_allowed = merging_hyphens_allowed;
4065 preamble.registerAutomaticallyLoadedPackage("tipa");
4066 preamble.registerAutomaticallyLoadedPackage("tipx");
4070 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4071 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4072 context.check_layout(os);
4076 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4077 begin_inset(os, "IPADeco " + type + "\n");
4078 os << "status open\n";
4079 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4085 if (t.cs() == "textvertline") {
4086 // FIXME: This is not correct, \textvertline is higher than |
4092 if (t.cs() == "tone" ) {
4093 context.check_layout(os);
4094 // register the tone package
4095 preamble.registerAutomaticallyLoadedPackage("tone");
4096 string content = trimSpaceAndEol(p.verbatim_item());
4097 string command = t.asInput() + "{" + content + "}";
4098 // some tones can be detected by unicodesymbols, some need special code
4099 if (is_known(content, known_tones)) {
4100 os << "\\IPAChar " << command << "\n";
4103 // try to see whether the string is in unicodesymbols
4107 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4108 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4109 termination, rem, &req);
4113 output_ert_inset(os, to_utf8(rem), context);
4114 for (set<string>::const_iterator it = req.begin();
4115 it != req.end(); ++it)
4116 preamble.registerAutomaticallyLoadedPackage(*it);
4118 // we did not find a non-ert version
4119 output_ert_inset(os, command, context);
4123 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4124 t.cs() == "vphantom") {
4125 context.check_layout(os);
4126 if (t.cs() == "phantom")
4127 begin_inset(os, "Phantom Phantom\n");
4128 if (t.cs() == "hphantom")
4129 begin_inset(os, "Phantom HPhantom\n");
4130 if (t.cs() == "vphantom")
4131 begin_inset(os, "Phantom VPhantom\n");
4132 os << "status open\n";
4133 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4139 if (t.cs() == "href") {
4140 context.check_layout(os);
4141 string target = convert_literate_command_inset_arg(p.verbatim_item());
4142 string name = p.verbatim_item();
4143 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4144 bool const literal = !nm.first;
4145 name = literal ? subst(name, "\n", " ") : nm.second;
4146 string lit = literal ? "\"true\"" : "\"false\"";
4148 size_t i = target.find(':');
4149 if (i != string::npos) {
4150 type = target.substr(0, i + 1);
4151 if (type == "mailto:" || type == "file:")
4152 target = target.substr(i + 1);
4153 // handle the case that name is equal to target, except of "http(s)://"
4154 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4157 begin_command_inset(os, "href", "href");
4159 os << "name \"" << name << "\"\n";
4160 os << "target \"" << target << "\"\n";
4161 if (type == "mailto:" || type == "file:")
4162 os << "type \"" << type << "\"\n";
4163 os << "literal " << lit << "\n";
4165 skip_spaces_braces(p);
4169 if (t.cs() == "lyxline") {
4170 // swallow size argument (it is not used anyway)
4172 if (!context.atParagraphStart()) {
4173 // so our line is in the middle of a paragraph
4174 // we need to add a new line, lest this line
4175 // follow the other content on that line and
4176 // run off the side of the page
4177 // FIXME: This may create an empty paragraph,
4178 // but without that it would not be
4179 // possible to set noindent below.
4180 // Fortunately LaTeX does not care
4181 // about the empty paragraph.
4182 context.new_paragraph(os);
4184 if (preamble.indentParagraphs()) {
4185 // we need to unindent, lest the line be too long
4186 context.add_par_extra_stuff("\\noindent\n");
4188 context.check_layout(os);
4189 begin_command_inset(os, "line", "rule");
4190 os << "offset \"0.5ex\"\n"
4191 "width \"100line%\"\n"
4197 if (t.cs() == "rule") {
4198 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4199 string const width = p.getArg('{', '}');
4200 string const thickness = p.getArg('{', '}');
4201 context.check_layout(os);
4202 begin_command_inset(os, "line", "rule");
4203 if (!offset.empty())
4204 os << "offset \"" << translate_len(offset) << "\"\n";
4205 os << "width \"" << translate_len(width) << "\"\n"
4206 "height \"" << translate_len(thickness) << "\"\n";
4211 // Handle refstyle first in order to to catch \eqref, because this
4212 // can also occur without refstyle. Only recognize these commands if
4213 // refstyle.sty was found in the preamble (otherwise \eqref
4214 // and user defined ref commands could be misdetected).
4215 // We uncapitalize the input in order to catch capitalized commands
4217 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4218 && preamble.refstyle()) {
4219 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4220 string plural = "false";
4221 // Catch the plural option [s]
4223 string const opt = p.getOpt();
4227 // LyX does not yet support other optional arguments of ref commands
4228 output_ert_inset(os, t.asInput() + opt + "{" +
4229 p.verbatim_item() + '}', context);
4233 context.check_layout(os);
4234 begin_command_inset(os, "ref", "formatted");
4235 os << "reference \"";
4236 os << known_refstyle_prefixes[where - known_refstyle_commands]
4238 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4240 os << "plural \"" << plural << "\"\n";
4241 os << "caps \"" << cap << "\"\n";
4242 os << "noprefix \"false\"\n";
4244 preamble.registerAutomaticallyLoadedPackage("refstyle");
4248 // if refstyle is used, we must not convert \prettyref to a
4249 // formatted reference, since that would result in a refstyle command.
4250 if ((where = is_known(t.cs(), known_ref_commands)) &&
4251 (t.cs() != "prettyref" || !preamble.refstyle())) {
4252 string const opt = p.getOpt();
4254 context.check_layout(os);
4255 begin_command_inset(os, "ref",
4256 known_coded_ref_commands[where - known_ref_commands]);
4257 os << "reference \""
4258 << convert_literate_command_inset_arg(p.verbatim_item())
4260 os << "plural \"false\"\n";
4261 os << "caps \"false\"\n";
4262 os << "noprefix \"false\"\n";
4264 if (t.cs() == "vref" || t.cs() == "vpageref")
4265 preamble.registerAutomaticallyLoadedPackage("varioref");
4266 else if (t.cs() == "prettyref")
4267 preamble.registerAutomaticallyLoadedPackage("prettyref");
4269 // LyX does not yet support optional arguments of ref commands
4270 output_ert_inset(os, t.asInput() + opt + "{" +
4271 p.verbatim_item() + '}', context);
4277 is_known(t.cs(), known_natbib_commands) &&
4278 ((t.cs() != "citefullauthor" &&
4279 t.cs() != "citeyear" &&
4280 t.cs() != "citeyearpar") ||
4281 p.next_token().asInput() != "*")) {
4282 context.check_layout(os);
4283 string command = t.cs();
4284 if (p.next_token().asInput() == "*") {
4288 if (command == "citefullauthor")
4289 // alternative name for "\\citeauthor*"
4290 command = "citeauthor*";
4292 // text before the citation
4294 // text after the citation
4296 get_cite_arguments(p, true, before, after);
4298 if (command == "cite") {
4299 // \cite without optional argument means
4300 // \citet, \cite with at least one optional
4301 // argument means \citep.
4302 if (before.empty() && after.empty())
4307 if (before.empty() && after == "[]")
4308 // avoid \citet[]{a}
4310 else if (before == "[]" && after == "[]") {
4311 // avoid \citet[][]{a}
4315 bool literal = false;
4316 pair<bool, string> aft;
4317 pair<bool, string> bef;
4318 // remove the brackets around after and before
4319 if (!after.empty()) {
4321 after.erase(after.length() - 1, 1);
4322 aft = convert_latexed_command_inset_arg(after);
4323 literal = !aft.first;
4324 after = literal ? subst(after, "\n", " ") : aft.second;
4326 if (!before.empty()) {
4328 before.erase(before.length() - 1, 1);
4329 bef = convert_latexed_command_inset_arg(before);
4330 literal |= !bef.first;
4331 before = literal ? subst(before, "\n", " ") : bef.second;
4332 if (literal && !after.empty())
4333 after = subst(after, "\n", " ");
4335 string lit = literal ? "\"true\"" : "\"false\"";
4336 begin_command_inset(os, "citation", command);
4337 os << "after " << '"' << after << '"' << "\n";
4338 os << "before " << '"' << before << '"' << "\n";
4340 << convert_literate_command_inset_arg(p.verbatim_item())
4342 << "literal " << lit << "\n";
4344 // Need to set the cite engine if natbib is loaded by
4345 // the document class directly
4346 if (preamble.citeEngine() == "basic")
4347 preamble.citeEngine("natbib");
4352 && is_known(t.cs(), known_biblatex_commands)
4353 && ((t.cs() == "cite"
4354 || t.cs() == "citeauthor"
4355 || t.cs() == "Citeauthor"
4356 || t.cs() == "parencite"
4357 || t.cs() == "citetitle")
4358 || p.next_token().asInput() != "*"))
4359 || (use_biblatex_natbib
4360 && (is_known(t.cs(), known_biblatex_commands)
4361 || is_known(t.cs(), known_natbib_commands))
4362 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4363 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4364 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4365 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4366 || t.cs() == "parencite" || t.cs() == "citetitle")
4367 || p.next_token().asInput() != "*"))){
4368 context.check_layout(os);
4369 string command = t.cs();
4370 if (p.next_token().asInput() == "*") {
4375 bool const qualified = suffixIs(command, "s");
4377 command = rtrim(command, "s");
4379 // text before the citation
4381 // text after the citation
4383 get_cite_arguments(p, true, before, after, qualified);
4385 // These use natbib cmd names in LyX
4386 // for inter-citeengine compativility
4387 if (command == "citeyear")
4388 command = "citebyear";
4389 else if (command == "cite*")
4390 command = "citeyear";
4391 else if (command == "textcite")
4393 else if (command == "Textcite")
4395 else if (command == "parencite")
4397 else if (command == "Parencite")
4399 else if (command == "parencite*")
4400 command = "citeyearpar";
4401 else if (command == "smartcite")
4402 command = "footcite";
4403 else if (command == "Smartcite")
4404 command = "Footcite";
4406 string const emptyarg = qualified ? "()" : "[]";
4407 if (before.empty() && after == emptyarg)
4410 else if (before == emptyarg && after == emptyarg) {
4411 // avoid \cite[][]{a}
4415 bool literal = false;
4416 pair<bool, string> aft;
4417 pair<bool, string> bef;
4418 // remove the brackets around after and before
4419 if (!after.empty()) {
4421 after.erase(after.length() - 1, 1);
4422 aft = convert_latexed_command_inset_arg(after);
4423 literal = !aft.first;
4424 after = literal ? subst(after, "\n", " ") : aft.second;
4426 if (!before.empty()) {
4428 before.erase(before.length() - 1, 1);
4429 bef = convert_latexed_command_inset_arg(before);
4430 literal |= !bef.first;
4431 before = literal ? subst(before, "\n", " ") : bef.second;
4433 string keys, pretextlist, posttextlist;
4435 map<string, string> pres, posts, preslit, postslit;
4436 vector<string> lkeys;
4437 // text before the citation
4438 string lbefore, lbeforelit;
4439 // text after the citation
4440 string lafter, lafterlit;
4442 pair<bool, string> laft, lbef;
4444 get_cite_arguments(p, true, lbefore, lafter);
4445 // remove the brackets around after and before
4446 if (!lafter.empty()) {
4448 lafter.erase(lafter.length() - 1, 1);
4449 laft = convert_latexed_command_inset_arg(lafter);
4450 literal |= !laft.first;
4451 lafter = laft.second;
4452 lafterlit = subst(lbefore, "\n", " ");
4454 if (!lbefore.empty()) {
4455 lbefore.erase(0, 1);
4456 lbefore.erase(lbefore.length() - 1, 1);
4457 lbef = convert_latexed_command_inset_arg(lbefore);
4458 literal |= !lbef.first;
4459 lbefore = lbef.second;
4460 lbeforelit = subst(lbefore, "\n", " ");
4462 if (lbefore.empty() && lafter == "[]") {
4467 else if (lbefore == "[]" && lafter == "[]") {
4468 // avoid \cite[][]{a}
4474 lkey = p.getArg('{', '}');
4477 if (!lbefore.empty()) {
4478 pres.insert(make_pair(lkey, lbefore));
4479 preslit.insert(make_pair(lkey, lbeforelit));
4481 if (!lafter.empty()) {
4482 posts.insert(make_pair(lkey, lafter));
4483 postslit.insert(make_pair(lkey, lafterlit));
4485 lkeys.push_back(lkey);
4487 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4492 for (auto const & ptl : pres) {
4493 if (!pretextlist.empty())
4494 pretextlist += '\t';
4495 pretextlist += ptl.first + " " + ptl.second;
4497 for (auto const & potl : posts) {
4498 if (!posttextlist.empty())
4499 posttextlist += '\t';
4500 posttextlist += potl.first + " " + potl.second;
4503 keys = convert_literate_command_inset_arg(p.verbatim_item());
4506 after = subst(after, "\n", " ");
4507 if (!before.empty())
4508 before = subst(after, "\n", " ");
4510 string lit = literal ? "\"true\"" : "\"false\"";
4511 begin_command_inset(os, "citation", command);
4512 os << "after " << '"' << after << '"' << "\n";
4513 os << "before " << '"' << before << '"' << "\n";
4517 if (!pretextlist.empty())
4518 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4519 if (!posttextlist.empty())
4520 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4521 os << "literal " << lit << "\n";
4523 // Need to set the cite engine if biblatex is loaded by
4524 // the document class directly
4525 if (preamble.citeEngine() == "basic")
4526 use_biblatex_natbib ?
4527 preamble.citeEngine("biblatex-natbib")
4528 : preamble.citeEngine("biblatex");
4533 is_known(t.cs(), known_jurabib_commands) &&
4534 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4535 context.check_layout(os);
4536 string command = t.cs();
4537 if (p.next_token().asInput() == "*") {
4541 char argumentOrder = '\0';
4542 vector<string> const options =
4543 preamble.getPackageOptions("jurabib");
4544 if (find(options.begin(), options.end(),
4545 "natbiborder") != options.end())
4546 argumentOrder = 'n';
4547 else if (find(options.begin(), options.end(),
4548 "jurabiborder") != options.end())
4549 argumentOrder = 'j';
4551 // text before the citation
4553 // text after the citation
4555 get_cite_arguments(p, argumentOrder != 'j', before, after);
4557 string const citation = p.verbatim_item();
4558 if (!before.empty() && argumentOrder == '\0') {
4559 cerr << "Warning: Assuming argument order "
4560 "of jurabib version 0.6 for\n'"
4561 << command << before << after << '{'
4562 << citation << "}'.\n"
4563 "Add 'jurabiborder' to the jurabib "
4564 "package options if you used an\n"
4565 "earlier jurabib version." << endl;
4567 bool literal = false;
4568 pair<bool, string> aft;
4569 pair<bool, string> bef;
4570 // remove the brackets around after and before
4571 if (!after.empty()) {
4573 after.erase(after.length() - 1, 1);
4574 aft = convert_latexed_command_inset_arg(after);
4575 literal = !aft.first;
4576 after = literal ? subst(after, "\n", " ") : aft.second;
4578 if (!before.empty()) {
4580 before.erase(before.length() - 1, 1);
4581 bef = convert_latexed_command_inset_arg(before);
4582 literal |= !bef.first;
4583 before = literal ? subst(before, "\n", " ") : bef.second;
4584 if (literal && !after.empty())
4585 after = subst(after, "\n", " ");
4587 string lit = literal ? "\"true\"" : "\"false\"";
4588 begin_command_inset(os, "citation", command);
4589 os << "after " << '"' << after << "\"\n"
4590 << "before " << '"' << before << "\"\n"
4591 << "key " << '"' << citation << "\"\n"
4592 << "literal " << lit << "\n";
4594 // Need to set the cite engine if jurabib is loaded by
4595 // the document class directly
4596 if (preamble.citeEngine() == "basic")
4597 preamble.citeEngine("jurabib");
4601 if (t.cs() == "cite"
4602 || t.cs() == "nocite") {
4603 context.check_layout(os);
4604 string after = p.getArg('[', ']');
4605 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4606 bool const literal = !aft.first;
4607 after = literal ? subst(after, "\n", " ") : aft.second;
4608 string lit = literal ? "\"true\"" : "\"false\"";
4609 string key = convert_literate_command_inset_arg(p.verbatim_item());
4610 // store the case that it is "\nocite{*}" to use it later for
4613 begin_command_inset(os, "citation", t.cs());
4614 os << "after " << '"' << after << "\"\n"
4615 << "key " << '"' << key << "\"\n"
4616 << "literal " << lit << "\n";
4618 } else if (t.cs() == "nocite")
4623 if (t.cs() == "index" ||
4624 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4625 context.check_layout(os);
4626 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4627 p.getArg('[', ']') : "";
4628 string const kind = arg.empty() ? "idx" : arg;
4629 begin_inset(os, "Index ");
4630 os << kind << "\nstatus collapsed\n";
4631 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4634 preamble.registerAutomaticallyLoadedPackage("splitidx");
4638 if (t.cs() == "nomenclature") {
4639 context.check_layout(os);
4640 begin_command_inset(os, "nomenclature", "nomenclature");
4641 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4642 if (!prefix.empty())
4643 os << "prefix " << '"' << prefix << '"' << "\n";
4644 string symbol = p.verbatim_item();
4645 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4646 bool literal = !sym.first;
4647 string description = p.verbatim_item();
4648 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4649 literal |= !desc.first;
4651 symbol = subst(symbol, "\n", " ");
4652 description = subst(description, "\n", " ");
4654 symbol = sym.second;
4655 description = desc.second;
4657 string lit = literal ? "\"true\"" : "\"false\"";
4658 os << "symbol " << '"' << symbol;
4659 os << "\"\ndescription \""
4660 << description << "\"\n"
4661 << "literal " << lit << "\n";
4663 preamble.registerAutomaticallyLoadedPackage("nomencl");
4667 if (t.cs() == "label") {
4668 context.check_layout(os);
4669 begin_command_inset(os, "label", "label");
4671 << convert_literate_command_inset_arg(p.verbatim_item())
4677 if (t.cs() == "lyxmintcaption") {
4678 string const pos = p.getArg('[', ']');
4680 string const caption =
4681 parse_text_snippet(p, FLAG_ITEM, false,
4683 minted_nonfloat_caption = "[t]" + caption;
4685 // We already got the caption at the bottom,
4686 // so simply skip it.
4687 parse_text_snippet(p, FLAG_ITEM, false, context);
4689 eat_whitespace(p, os, context, true);
4693 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4694 context.check_layout(os);
4695 string commandname = t.cs();
4697 if (p.next_token().asInput() == "*") {
4702 begin_command_inset(os, "index_print", commandname);
4703 string const indexname = p.getArg('[', ']');
4705 if (indexname.empty())
4706 os << "type \"idx\"\n";
4708 os << "type \"" << indexname << "\"\n";
4709 os << "literal \"true\"\n";
4712 skip_spaces_braces(p);
4713 preamble.registerAutomaticallyLoadedPackage("makeidx");
4714 if (preamble.use_indices() == "true")
4715 preamble.registerAutomaticallyLoadedPackage("splitidx");
4719 if (t.cs() == "printnomenclature") {
4721 string width_type = "";
4722 context.check_layout(os);
4723 begin_command_inset(os, "nomencl_print", "printnomenclature");
4724 // case of a custom width
4726 width = p.getArg('[', ']');
4727 width = translate_len(width);
4728 width_type = "custom";
4730 // case of no custom width
4731 // the case of no custom width but the width set
4732 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4733 // because the user could have set anything, not only the width
4734 // of the longest label (which would be width_type = "auto")
4735 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4736 if (label.empty() && width_type.empty())
4737 width_type = "none";
4738 os << "set_width \"" << width_type << "\"\n";
4739 if (width_type == "custom")
4740 os << "width \"" << width << '\"';
4742 skip_spaces_braces(p);
4743 preamble.registerAutomaticallyLoadedPackage("nomencl");
4747 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4748 context.check_layout(os);
4749 begin_inset(os, "script ");
4750 os << t.cs().substr(4) << '\n';
4751 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4752 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4754 if (t.cs() == "textsubscript")
4755 preamble.registerAutomaticallyLoadedPackage("subscript");
4759 if ((where = is_known(t.cs(), known_quotes))) {
4760 context.check_layout(os);
4761 begin_inset(os, "Quotes ");
4762 string quotetype = known_coded_quotes[where - known_quotes];
4763 // try to make a smart guess about the side
4764 Token const prev = p.prev_token();
4765 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4766 && prev.character() != '\n' && prev.character() != '~');
4767 quotetype = guessQuoteStyle(quotetype, opening);
4770 // LyX adds {} after the quote, so we have to eat
4771 // spaces here if there are any before a possible
4773 eat_whitespace(p, os, context, false);
4778 if ((where = is_known(t.cs(), known_sizes)) &&
4779 context.new_layout_allowed) {
4780 context.check_layout(os);
4781 TeXFont const oldFont = context.font;
4782 context.font.size = known_coded_sizes[where - known_sizes];
4783 output_font_change(os, oldFont, context.font);
4784 eat_whitespace(p, os, context, false);
4788 if ((where = is_known(t.cs(), known_font_families)) &&
4789 context.new_layout_allowed) {
4790 context.check_layout(os);
4791 TeXFont const oldFont = context.font;
4792 context.font.family =
4793 known_coded_font_families[where - known_font_families];
4794 output_font_change(os, oldFont, context.font);
4795 eat_whitespace(p, os, context, false);
4799 if ((where = is_known(t.cs(), known_font_series)) &&
4800 context.new_layout_allowed) {
4801 context.check_layout(os);
4802 TeXFont const oldFont = context.font;
4803 context.font.series =
4804 known_coded_font_series[where - known_font_series];
4805 output_font_change(os, oldFont, context.font);
4806 eat_whitespace(p, os, context, false);
4810 if ((where = is_known(t.cs(), known_font_shapes)) &&
4811 context.new_layout_allowed) {
4812 context.check_layout(os);
4813 TeXFont const oldFont = context.font;
4814 context.font.shape =
4815 known_coded_font_shapes[where - known_font_shapes];
4816 output_font_change(os, oldFont, context.font);
4817 eat_whitespace(p, os, context, false);
4820 if ((where = is_known(t.cs(), known_old_font_families)) &&
4821 context.new_layout_allowed) {
4822 context.check_layout(os);
4823 TeXFont const oldFont = context.font;
4824 context.font.init();
4825 context.font.size = oldFont.size;
4826 context.font.family =
4827 known_coded_font_families[where - known_old_font_families];
4828 output_font_change(os, oldFont, context.font);
4829 eat_whitespace(p, os, context, false);
4833 if ((where = is_known(t.cs(), known_old_font_series)) &&
4834 context.new_layout_allowed) {
4835 context.check_layout(os);
4836 TeXFont const oldFont = context.font;
4837 context.font.init();
4838 context.font.size = oldFont.size;
4839 context.font.series =
4840 known_coded_font_series[where - known_old_font_series];
4841 output_font_change(os, oldFont, context.font);
4842 eat_whitespace(p, os, context, false);
4846 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4847 context.new_layout_allowed) {
4848 context.check_layout(os);
4849 TeXFont const oldFont = context.font;
4850 context.font.init();
4851 context.font.size = oldFont.size;
4852 context.font.shape =
4853 known_coded_font_shapes[where - known_old_font_shapes];
4854 output_font_change(os, oldFont, context.font);
4855 eat_whitespace(p, os, context, false);
4859 if (t.cs() == "selectlanguage") {
4860 context.check_layout(os);
4861 // save the language for the case that a
4862 // \foreignlanguage is used
4863 context.font.language = babel2lyx(p.verbatim_item());
4864 os << "\n\\lang " << context.font.language << "\n";
4868 if (t.cs() == "foreignlanguage") {
4869 string const lang = babel2lyx(p.verbatim_item());
4870 parse_text_attributes(p, os, FLAG_ITEM, outer,
4872 context.font.language, lang);
4876 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4877 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4878 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4880 // We have to output the whole command if it has an option
4881 // because LyX doesn't support this yet, see bug #8214,
4882 // only if there is a single option specifying a variant, we can handle it.
4884 string langopts = p.getOpt();
4885 // check if the option contains a variant, if yes, extract it
4886 string::size_type pos_var = langopts.find("variant");
4887 string::size_type i = langopts.find(',');
4888 string::size_type k = langopts.find('=', pos_var);
4889 if (pos_var != string::npos && i == string::npos) {
4891 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4892 lang = preamble.polyglossia2lyx(variant);
4893 parse_text_attributes(p, os, FLAG_ITEM, outer,
4895 context.font.language, lang);
4897 output_ert_inset(os, t.asInput() + langopts, context);
4899 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4900 parse_text_attributes(p, os, FLAG_ITEM, outer,
4902 context.font.language, lang);
4907 if (t.cs() == "inputencoding") {
4908 // nothing to write here
4909 string const enc = subst(p.verbatim_item(), "\n", " ");
4910 p.setEncoding(enc, Encoding::inputenc);
4914 if (is_known(t.cs(), known_special_chars) ||
4915 (t.cs() == "protect" &&
4916 p.next_token().cat() == catEscape &&
4917 is_known(p.next_token().cs(), known_special_protect_chars))) {
4918 // LyX sometimes puts a \protect in front, so we have to ignore it
4920 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4921 known_special_chars);
4922 context.check_layout(os);
4923 os << known_coded_special_chars[where - known_special_chars];
4924 skip_spaces_braces(p);
4928 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4929 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4930 p.next_next_token().asInput() == "-") ||
4931 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4932 // LyX sometimes puts a \protect in front, so we have to ignore it
4933 if (t.cs() == "protect")
4935 context.check_layout(os);
4936 if (t.cs() == "nobreakdash")
4937 os << "\\SpecialChar nobreakdash\n";
4939 os << "\\SpecialChar endofsentence\n";
4944 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4945 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4946 || t.cs() == "%" || t.cs() == "-") {
4947 context.check_layout(os);
4949 os << "\\SpecialChar softhyphen\n";
4955 if (t.cs() == "char") {
4956 context.check_layout(os);
4957 if (p.next_token().character() == '`') {
4959 if (p.next_token().cs() == "\"") {
4964 output_ert_inset(os, "\\char`", context);
4967 output_ert_inset(os, "\\char", context);
4972 if (t.cs() == "verb") {
4973 context.check_layout(os);
4974 // set catcodes to verbatim early, just in case.
4975 p.setCatcodes(VERBATIM_CATCODES);
4976 string delim = p.get_token().asInput();
4977 Parser::Arg arg = p.verbatimStuff(delim);
4979 output_ert_inset(os, "\\verb" + delim
4980 + arg.second + delim, context);
4982 cerr << "invalid \\verb command. Skipping" << endl;
4986 // Problem: \= creates a tabstop inside the tabbing environment
4987 // and else an accent. In the latter case we really would want
4988 // \={o} instead of \= o.
4989 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4990 output_ert_inset(os, t.asInput(), context);
4994 if (t.cs() == "\\") {
4995 context.check_layout(os);
4997 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4998 else if (p.next_token().asInput() == "*") {
5000 // getOpt() eats the following space if there
5001 // is no optional argument, but that is OK
5002 // here since it has no effect in the output.
5003 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5006 begin_inset(os, "Newline newline");
5012 if (t.cs() == "newline" ||
5013 (t.cs() == "linebreak" && !p.hasOpt())) {
5014 context.check_layout(os);
5015 begin_inset(os, "Newline ");
5018 skip_spaces_braces(p);
5022 if (t.cs() == "input" || t.cs() == "include"
5023 || t.cs() == "verbatiminput"
5024 || t.cs() == "lstinputlisting"
5025 || t.cs() == "inputminted") {
5026 string name = t.cs();
5027 if (name == "verbatiminput"
5028 && p.next_token().asInput() == "*")
5029 name += p.get_token().asInput();
5030 context.check_layout(os);
5032 bool literal = false;
5033 if (name == "lstinputlisting" && p.hasOpt()) {
5034 lstparams = p.getArg('[', ']');
5035 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5036 literal = !oa.first;
5038 lstparams = subst(lstparams, "\n", " ");
5040 lstparams = oa.second;
5041 } else if (name == "inputminted") {
5042 name = "lstinputlisting";
5043 string const lang = p.getArg('{', '}');
5044 if (lang != "tex") {
5045 string cmd = "\\inputminted{" + lang + "}{";
5046 cmd += p.getArg('{', '}') + "}";
5047 output_ert_inset(os, cmd, context);
5050 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5051 minted_nonfloat_caption.erase(0,3);
5052 // extract label and caption from the already produced LyX code
5053 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5054 string const caption = nfc.front();
5056 vector<string>::iterator it =
5057 find(nfc.begin(), nfc.end(), "LatexCommand label");
5058 if (it != nfc.end()) {
5060 if (it != nfc.end())
5062 label = support::split(label, '"');
5065 minted_nonfloat_caption.clear();
5066 lstparams = "caption=" + caption;
5068 lstparams += ",label=" + label;
5069 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5070 literal = !oa.first;
5072 lstparams = subst(lstparams, "\n", " ");
5074 lstparams = oa.second;
5077 string lit = literal ? "\"true\"" : "\"false\"";
5078 string filename(normalize_filename(p.getArg('{', '}')));
5079 string const path = getMasterFilePath(true);
5080 // We want to preserve relative / absolute filenames,
5081 // therefore path is only used for testing
5082 if ((t.cs() == "include" || t.cs() == "input") &&
5083 !makeAbsPath(filename, path).exists()) {
5084 // The file extension is probably missing.
5085 // Now try to find it out.
5086 string const tex_name =
5087 find_file(filename, path,
5088 known_tex_extensions);
5089 if (!tex_name.empty())
5090 filename = tex_name;
5092 bool external = false;
5094 if (makeAbsPath(filename, path).exists()) {
5095 string const abstexname =
5096 makeAbsPath(filename, path).absFileName();
5097 string const absfigname =
5098 changeExtension(abstexname, ".fig");
5099 fix_child_filename(filename);
5100 string const lyxname = changeExtension(filename,
5101 roundtripMode() ? ".lyx.lyx" : ".lyx");
5102 string const abslyxname = makeAbsPath(
5103 lyxname, getParentFilePath(false)).absFileName();
5105 if (!skipChildren())
5106 external = FileName(absfigname).exists();
5107 if (t.cs() == "input" && !skipChildren()) {
5108 string const ext = getExtension(abstexname);
5110 // Combined PS/LaTeX:
5111 // x.eps, x.pstex_t (old xfig)
5112 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5113 FileName const absepsname(
5114 changeExtension(abstexname, ".eps"));
5115 FileName const abspstexname(
5116 changeExtension(abstexname, ".pstex"));
5117 bool const xfigeps =
5118 (absepsname.exists() ||
5119 abspstexname.exists()) &&
5122 // Combined PDF/LaTeX:
5123 // x.pdf, x.pdftex_t (old xfig)
5124 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5125 FileName const abspdfname(
5126 changeExtension(abstexname, ".pdf"));
5127 bool const xfigpdf =
5128 abspdfname.exists() &&
5129 (ext == "pdftex_t" || ext == "pdf_t");
5133 // Combined PS/PDF/LaTeX:
5134 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5135 string const absbase2(
5136 removeExtension(abstexname) + "_pspdftex");
5137 FileName const abseps2name(
5138 addExtension(absbase2, ".eps"));
5139 FileName const abspdf2name(
5140 addExtension(absbase2, ".pdf"));
5141 bool const xfigboth =
5142 abspdf2name.exists() &&
5143 abseps2name.exists() && ext == "pspdftex";
5145 xfig = xfigpdf || xfigeps || xfigboth;
5146 external = external && xfig;
5149 outname = changeExtension(filename, ".fig");
5150 FileName abssrc(changeExtension(abstexname, ".fig"));
5151 copy_file(abssrc, outname);
5153 // Don't try to convert, the result
5154 // would be full of ERT.
5156 FileName abssrc(abstexname);
5157 copy_file(abssrc, outname);
5158 } else if (t.cs() != "verbatiminput" &&
5160 tex2lyx(abstexname, FileName(abslyxname),
5163 // no need to call copy_file
5164 // tex2lyx creates the file
5167 FileName abssrc(abstexname);
5168 copy_file(abssrc, outname);
5171 cerr << "Warning: Could not find included file '"
5172 << filename << "'." << endl;
5176 begin_inset(os, "External\n");
5177 os << "\ttemplate XFig\n"
5178 << "\tfilename " << outname << '\n';
5179 registerExternalTemplatePackages("XFig");
5181 begin_command_inset(os, "include", name);
5182 outname = subst(outname, "\"", "\\\"");
5183 os << "preview false\n"
5184 "filename \"" << outname << "\"\n";
5185 if (!lstparams.empty())
5186 os << "lstparams \"" << lstparams << "\"\n";
5187 os << "literal " << lit << "\n";
5188 if (t.cs() == "verbatiminput")
5189 preamble.registerAutomaticallyLoadedPackage("verbatim");
5195 if (t.cs() == "bibliographystyle") {
5196 // store new bibliographystyle
5197 bibliographystyle = p.verbatim_item();
5198 // If any other command than \bibliography, \addcontentsline
5199 // and \nocite{*} follows, we need to output the style
5200 // (because it might be used by that command).
5201 // Otherwise, it will automatically be output by LyX.
5204 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5205 if (t2.cat() == catBegin)
5207 if (t2.cat() != catEscape)
5209 if (t2.cs() == "nocite") {
5210 if (p.getArg('{', '}') == "*")
5212 } else if (t2.cs() == "bibliography")
5214 else if (t2.cs() == "phantomsection") {
5218 else if (t2.cs() == "addcontentsline") {
5219 // get the 3 arguments of \addcontentsline
5222 contentslineContent = p.getArg('{', '}');
5223 // if the last argument is not \refname we must output
5224 if (contentslineContent == "\\refname")
5231 output_ert_inset(os,
5232 "\\bibliographystyle{" + bibliographystyle + '}',
5238 if (t.cs() == "phantomsection") {
5239 // we only support this if it occurs between
5240 // \bibliographystyle and \bibliography
5241 if (bibliographystyle.empty())
5242 output_ert_inset(os, "\\phantomsection", context);
5246 if (t.cs() == "addcontentsline") {
5247 context.check_layout(os);
5248 // get the 3 arguments of \addcontentsline
5249 string const one = p.getArg('{', '}');
5250 string const two = p.getArg('{', '}');
5251 string const three = p.getArg('{', '}');
5252 // only if it is a \refname, we support if for the bibtex inset
5253 if (contentslineContent != "\\refname") {
5254 output_ert_inset(os,
5255 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5261 else if (t.cs() == "bibliography") {
5262 context.check_layout(os);
5264 begin_command_inset(os, "bibtex", "bibtex");
5265 if (!btprint.empty()) {
5266 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5267 // clear the string because the next BibTeX inset can be without the
5268 // \nocite{*} option
5271 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5272 // Do we have addcontentsline?
5273 if (contentslineContent == "\\refname") {
5274 BibOpts = "bibtotoc";
5275 // clear string because next BibTeX inset can be without addcontentsline
5276 contentslineContent.clear();
5278 // Do we have a bibliographystyle set?
5279 if (!bibliographystyle.empty()) {
5280 if (BibOpts.empty())
5281 BibOpts = normalize_filename(bibliographystyle);
5283 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5284 // clear it because each bibtex entry has its style
5285 // and we need an empty string to handle \phantomsection
5286 bibliographystyle.clear();
5288 os << "options " << '"' << BibOpts << '"' << "\n";
5289 if (p.getEncoding() != preamble.docencoding) {
5290 Encoding const * const enc = encodings.fromIconvName(
5291 p.getEncoding(), Encoding::inputenc, true);
5293 cerr << "Unknown bib encoding " << p.getEncoding()
5294 << ". Ignoring." << std::endl;
5296 os << "encoding " << '"' << enc->name() << '"' << "\n";
5302 if (t.cs() == "printbibliography") {
5303 context.check_layout(os);
5305 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5306 vector<string> opts = getVectorFromString(bbloptions);
5307 vector<string>::iterator it =
5308 find(opts.begin(), opts.end(), "heading=bibintoc");
5309 if (it != opts.end()) {
5311 BibOpts = "bibtotoc";
5313 bbloptions = getStringFromVector(opts);
5314 begin_command_inset(os, "bibtex", "bibtex");
5315 if (!btprint.empty()) {
5316 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5317 // clear the string because the next BibTeX inset can be without the
5318 // \nocite{*} option
5322 for (auto const & bf : preamble.biblatex_bibliographies) {
5323 if (!bibfiles.empty())
5325 bibfiles += normalize_filename(bf);
5327 if (!bibfiles.empty())
5328 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5329 // Do we have addcontentsline?
5330 if (contentslineContent == "\\refname") {
5331 BibOpts = "bibtotoc";
5332 // clear string because next BibTeX inset can be without addcontentsline
5333 contentslineContent.clear();
5335 os << "options " << '"' << BibOpts << '"' << "\n";
5336 if (!bbloptions.empty())
5337 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5338 if (!preamble.bibencoding.empty()) {
5339 Encoding const * const enc = encodings.fromLaTeXName(
5340 preamble.bibencoding, Encoding::inputenc, true);
5342 cerr << "Unknown bib encoding " << preamble.bibencoding
5343 << ". Ignoring." << std::endl;
5345 os << "encoding " << '"' << enc->name() << '"' << "\n";
5348 need_commentbib = false;
5352 if (t.cs() == "bibbysection") {
5353 context.check_layout(os);
5355 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5356 vector<string> opts = getVectorFromString(bbloptions);
5357 vector<string>::iterator it =
5358 find(opts.begin(), opts.end(), "heading=bibintoc");
5359 if (it != opts.end()) {
5361 BibOpts = "bibtotoc";
5363 bbloptions = getStringFromVector(opts);
5364 begin_command_inset(os, "bibtex", "bibtex");
5365 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5367 for (auto const & bf : preamble.biblatex_bibliographies) {
5368 if (!bibfiles.empty())
5370 bibfiles += normalize_filename(bf);
5372 if (!bibfiles.empty())
5373 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5374 os << "options " << '"' << BibOpts << '"' << "\n";
5375 if (!bbloptions.empty())
5376 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5378 need_commentbib = false;
5382 if (t.cs() == "parbox") {
5383 // Test whether this is an outer box of a shaded box
5385 // swallow arguments
5386 while (p.hasOpt()) {
5388 p.skip_spaces(true);
5391 p.skip_spaces(true);
5393 if (p.next_token().cat() == catBegin)
5395 p.skip_spaces(true);
5396 Token to = p.get_token();
5397 bool shaded = false;
5398 if (to.asInput() == "\\begin") {
5399 p.skip_spaces(true);
5400 if (p.getArg('{', '}') == "shaded")
5405 parse_outer_box(p, os, FLAG_ITEM, outer,
5406 context, "parbox", "shaded");
5408 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5409 "", "", t.cs(), "", "");
5413 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5414 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5415 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5416 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5420 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5421 string backgroundcolor;
5422 preamble.registerAutomaticallyLoadedPackage("xcolor");
5423 if (t.cs() == "fcolorbox") {
5424 string const framecolor = p.getArg('{', '}');
5425 backgroundcolor = p.getArg('{', '}');
5426 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5428 backgroundcolor = p.getArg('{', '}');
5429 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5434 // FIXME: due to the compiler limit of "if" nestings
5435 // the code for the alignment was put here
5436 // put them in their own if if this is fixed
5437 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5438 || t.cs() == "shadowsize"
5439 || t.cs() == "raggedleft" || t.cs() == "centering"
5440 || t.cs() == "raggedright") {
5441 if (t.cs() == "fboxrule")
5443 if (t.cs() == "fboxsep")
5445 if (t.cs() == "shadowsize")
5447 if (t.cs() != "raggedleft" && t.cs() != "centering"
5448 && t.cs() != "raggedright") {
5449 p.skip_spaces(true);
5450 while (p.good() && p.next_token().cat() != catSpace
5451 && p.next_token().cat() != catNewline
5452 && p.next_token().cat() != catEscape) {
5453 if (t.cs() == "fboxrule")
5454 fboxrule = fboxrule + p.get_token().asInput();
5455 if (t.cs() == "fboxsep")
5456 fboxsep = fboxsep + p.get_token().asInput();
5457 if (t.cs() == "shadowsize")
5458 shadow_size = shadow_size + p.get_token().asInput();
5461 output_ert_inset(os, t.asInput(), context);
5466 //\framebox() is part of the picture environment and different from \framebox{}
5467 //\framebox{} will be parsed by parse_outer_box
5468 if (t.cs() == "framebox") {
5469 if (p.next_token().character() == '(') {
5470 //the syntax is: \framebox(x,y)[position]{content}
5471 string arg = t.asInput();
5472 arg += p.getFullParentheseArg();
5473 arg += p.getFullOpt();
5474 eat_whitespace(p, os, context, false);
5475 output_ert_inset(os, arg + '{', context);
5476 parse_text(p, os, FLAG_ITEM, outer, context);
5477 output_ert_inset(os, "}", context);
5479 //the syntax is: \framebox[width][position]{content}
5480 string special = p.getFullOpt();
5481 special += p.getOpt();
5482 parse_outer_box(p, os, FLAG_ITEM, outer,
5483 context, t.cs(), special);
5488 //\makebox() is part of the picture environment and different from \makebox{}
5489 //\makebox{} will be parsed by parse_box
5490 if (t.cs() == "makebox") {
5491 if (p.next_token().character() == '(') {
5492 //the syntax is: \makebox(x,y)[position]{content}
5493 string arg = t.asInput();
5494 arg += p.getFullParentheseArg();
5495 arg += p.getFullOpt();
5496 eat_whitespace(p, os, context, false);
5497 output_ert_inset(os, arg + '{', context);
5498 parse_text(p, os, FLAG_ITEM, outer, context);
5499 output_ert_inset(os, "}", context);
5501 //the syntax is: \makebox[width][position]{content}
5502 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5503 "", "", t.cs(), "", "");
5507 if (t.cs() == "smallskip" ||
5508 t.cs() == "medskip" ||
5509 t.cs() == "bigskip" ||
5510 t.cs() == "vfill") {
5511 context.check_layout(os);
5512 begin_inset(os, "VSpace ");
5515 skip_spaces_braces(p);
5519 if ((where = is_known(t.cs(), known_spaces))) {
5520 context.check_layout(os);
5521 begin_inset(os, "space ");
5522 os << '\\' << known_coded_spaces[where - known_spaces]
5525 // LaTeX swallows whitespace after all spaces except
5526 // "\\,". We have to do that here, too, because LyX
5527 // adds "{}" which would make the spaces significant.
5529 eat_whitespace(p, os, context, false);
5530 // LyX adds "{}" after all spaces except "\\ " and
5531 // "\\,", so we have to remove "{}".
5532 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5533 // remove the braces after "\\,", too.
5539 if (t.cs() == "newpage" ||
5540 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5541 t.cs() == "clearpage" ||
5542 t.cs() == "cleardoublepage") {
5543 context.check_layout(os);
5544 begin_inset(os, "Newpage ");
5547 skip_spaces_braces(p);
5551 if (t.cs() == "DeclareRobustCommand" ||
5552 t.cs() == "DeclareRobustCommandx" ||
5553 t.cs() == "newcommand" ||
5554 t.cs() == "newcommandx" ||
5555 t.cs() == "providecommand" ||
5556 t.cs() == "providecommandx" ||
5557 t.cs() == "renewcommand" ||
5558 t.cs() == "renewcommandx") {
5559 // DeclareRobustCommand, DeclareRobustCommandx,
5560 // providecommand and providecommandx could be handled
5561 // by parse_command(), but we need to call
5562 // add_known_command() here.
5563 string name = t.asInput();
5564 if (p.next_token().asInput() == "*") {
5565 // Starred form. Eat '*'
5569 string const command = p.verbatim_item();
5570 string const opt1 = p.getFullOpt();
5571 string const opt2 = p.getFullOpt();
5572 add_known_command(command, opt1, !opt2.empty());
5573 string const ert = name + '{' + command + '}' +
5575 '{' + p.verbatim_item() + '}';
5577 if (t.cs() == "DeclareRobustCommand" ||
5578 t.cs() == "DeclareRobustCommandx" ||
5579 t.cs() == "providecommand" ||
5580 t.cs() == "providecommandx" ||
5581 name[name.length()-1] == '*')
5582 output_ert_inset(os, ert, context);
5584 context.check_layout(os);
5585 begin_inset(os, "FormulaMacro");
5592 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5593 // let could be handled by parse_command(),
5594 // but we need to call add_known_command() here.
5595 string ert = t.asInput();
5598 if (p.next_token().cat() == catBegin) {
5599 name = p.verbatim_item();
5600 ert += '{' + name + '}';
5602 name = p.verbatim_item();
5607 if (p.next_token().cat() == catBegin) {
5608 command = p.verbatim_item();
5609 ert += '{' + command + '}';
5611 command = p.verbatim_item();
5614 // If command is known, make name known too, to parse
5615 // its arguments correctly. For this reason we also
5616 // have commands in syntax.default that are hardcoded.
5617 CommandMap::iterator it = known_commands.find(command);
5618 if (it != known_commands.end())
5619 known_commands[t.asInput()] = it->second;
5620 output_ert_inset(os, ert, context);
5624 if (t.cs() == "hspace" || t.cs() == "vspace") {
5627 string name = t.asInput();
5628 string const length = p.verbatim_item();
5631 bool valid = splitLatexLength(length, valstring, unit);
5632 bool known_hspace = false;
5633 bool known_vspace = false;
5634 bool known_unit = false;
5637 istringstream iss(valstring);
5640 if (t.cs()[0] == 'h') {
5641 if (unit == "\\fill") {
5646 known_hspace = true;
5649 if (unit == "\\smallskipamount") {
5651 known_vspace = true;
5652 } else if (unit == "\\medskipamount") {
5654 known_vspace = true;
5655 } else if (unit == "\\bigskipamount") {
5657 known_vspace = true;
5658 } else if (unit == "\\fill") {
5660 known_vspace = true;
5664 if (!known_hspace && !known_vspace) {
5665 switch (unitFromString(unit)) {
5681 //unitFromString(unit) fails for relative units like Length::PCW
5682 // therefore handle them separately
5683 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5684 || unit == "\\textwidth" || unit == "\\linewidth"
5685 || unit == "\\textheight" || unit == "\\paperheight"
5686 || unit == "\\baselineskip")
5694 // check for glue lengths
5695 bool is_gluelength = false;
5696 string gluelength = length;
5697 string::size_type i = length.find(" minus");
5698 if (i == string::npos) {
5699 i = length.find(" plus");
5700 if (i != string::npos)
5701 is_gluelength = true;
5703 is_gluelength = true;
5704 // if yes transform "9xx minus 8yy plus 7zz"
5706 if (is_gluelength) {
5707 i = gluelength.find(" minus");
5708 if (i != string::npos)
5709 gluelength.replace(i, 7, "-");
5710 i = gluelength.find(" plus");
5711 if (i != string::npos)
5712 gluelength.replace(i, 6, "+");
5715 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5716 // Literal horizontal length or known variable
5717 context.check_layout(os);
5718 begin_inset(os, "space ");
5726 if (known_unit && !known_hspace)
5727 os << "\n\\length " << translate_len(length);
5729 os << "\n\\length " << gluelength;
5731 } else if (known_unit || known_vspace || is_gluelength) {
5732 // Literal vertical length or known variable
5733 context.check_layout(os);
5734 begin_inset(os, "VSpace ");
5737 if (known_unit && !known_vspace)
5738 os << translate_len(length);
5745 // LyX can't handle other length variables in Inset VSpace/space
5750 output_ert_inset(os, name + '{' + unit + '}', context);
5751 else if (value == -1.0)
5752 output_ert_inset(os, name + "{-" + unit + '}', context);
5754 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5756 output_ert_inset(os, name + '{' + length + '}', context);
5761 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5762 // might be one or several options or a star.
5763 // The single '=' is meant here.
5764 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5768 context.check_layout(os);
5769 // store the latexparam here. This is eaten in parse_text_in_inset
5770 context.latexparam = newinsetlayout->latexparam();
5771 docstring name = newinsetlayout->name();
5772 bool const caption = name.find(from_ascii("Caption:")) == 0;
5774 // Already done for floating minted listings.
5775 if (minted_float.empty()) {
5776 begin_inset(os, "Caption ");
5777 os << to_utf8(name.substr(8)) << '\n';
5780 // FIXME: what do we do if the prefix is not Flex: ?
5781 if (prefixIs(name, from_ascii("Flex:")))
5783 begin_inset(os, "Flex ");
5784 os << to_utf8(name) << '\n'
5785 << "status collapsed\n";
5787 if (!minted_float.empty()) {
5788 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5789 } else if (newinsetlayout->isPassThru()) {
5790 // set catcodes to verbatim early, just in case.
5791 p.setCatcodes(VERBATIM_CATCODES);
5792 string delim = p.get_token().asInput();
5794 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5795 //FIXME: handle error condition
5796 string const arg = p.verbatimStuff("}").second;
5797 Context newcontext(true, context.textclass);
5798 if (newinsetlayout->forcePlainLayout())
5799 newcontext.layout = &context.textclass.plainLayout();
5800 output_ert(os, arg, newcontext);
5802 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5803 context.latexparam.clear();
5806 // Minted caption insets are not closed here because
5807 // we collect everything into the caption.
5808 if (minted_float.empty())
5813 // The single '=' is meant here.
5814 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5818 context.check_layout(os);
5819 docstring name = newinsetlayout->name();
5820 bool const caption = name.find(from_ascii("Caption:")) == 0;
5822 // Already done for floating minted listings.
5823 if (minted_float.empty()) {
5824 begin_inset(os, "Caption ");
5825 os << to_utf8(name.substr(8)) << '\n';
5828 // FIXME: what do we do if the prefix is not Flex: ?
5829 if (prefixIs(name, from_ascii("Flex:")))
5831 begin_inset(os, "Flex ");
5832 os << to_utf8(name) << '\n'
5833 << "status collapsed\n";
5835 if (!minted_float.empty()) {
5836 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5837 } else if (newinsetlayout->isPassThru()) {
5838 // set catcodes to verbatim early, just in case.
5839 p.setCatcodes(VERBATIM_CATCODES);
5840 string delim = p.get_token().asInput();
5842 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5843 //FIXME: handle error condition
5844 string const arg = p.verbatimStuff("}").second;
5845 Context newcontext(true, context.textclass);
5846 if (newinsetlayout->forcePlainLayout())
5847 newcontext.layout = &context.textclass.plainLayout();
5848 output_ert(os, arg, newcontext);
5850 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5853 // Minted caption insets are not closed here because
5854 // we collect everything into the caption.
5855 if (minted_float.empty())
5860 if (t.cs() == "includepdf") {
5862 string const arg = p.getArg('[', ']');
5863 map<string, string> opts;
5864 vector<string> keys;
5865 split_map(arg, opts, keys);
5866 string name = normalize_filename(p.verbatim_item());
5867 string const path = getMasterFilePath(true);
5868 // We want to preserve relative / absolute filenames,
5869 // therefore path is only used for testing
5870 if (!makeAbsPath(name, path).exists()) {
5871 // The file extension is probably missing.
5872 // Now try to find it out.
5873 char const * const pdfpages_format[] = {"pdf", 0};
5874 string const pdftex_name =
5875 find_file(name, path, pdfpages_format);
5876 if (!pdftex_name.empty()) {
5881 FileName const absname = makeAbsPath(name, path);
5882 if (absname.exists())
5884 fix_child_filename(name);
5885 copy_file(absname, name);
5887 cerr << "Warning: Could not find file '"
5888 << name << "'." << endl;
5890 context.check_layout(os);
5891 begin_inset(os, "External\n\ttemplate ");
5892 os << "PDFPages\n\tfilename "
5894 // parse the options
5895 if (opts.find("pages") != opts.end())
5896 os << "\textra LaTeX \"pages="
5897 << opts["pages"] << "\"\n";
5898 if (opts.find("angle") != opts.end())
5899 os << "\trotateAngle "
5900 << opts["angle"] << '\n';
5901 if (opts.find("origin") != opts.end()) {
5903 string const opt = opts["origin"];
5904 if (opt == "tl") ss << "topleft";
5905 if (opt == "bl") ss << "bottomleft";
5906 if (opt == "Bl") ss << "baselineleft";
5907 if (opt == "c") ss << "center";
5908 if (opt == "tc") ss << "topcenter";
5909 if (opt == "bc") ss << "bottomcenter";
5910 if (opt == "Bc") ss << "baselinecenter";
5911 if (opt == "tr") ss << "topright";
5912 if (opt == "br") ss << "bottomright";
5913 if (opt == "Br") ss << "baselineright";
5914 if (!ss.str().empty())
5915 os << "\trotateOrigin " << ss.str() << '\n';
5917 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5919 if (opts.find("width") != opts.end())
5921 << translate_len(opts["width"]) << '\n';
5922 if (opts.find("height") != opts.end())
5924 << translate_len(opts["height"]) << '\n';
5925 if (opts.find("keepaspectratio") != opts.end())
5926 os << "\tkeepAspectRatio\n";
5928 context.check_layout(os);
5929 registerExternalTemplatePackages("PDFPages");
5933 if (t.cs() == "loadgame") {
5935 string name = normalize_filename(p.verbatim_item());
5936 string const path = getMasterFilePath(true);
5937 // We want to preserve relative / absolute filenames,
5938 // therefore path is only used for testing
5939 if (!makeAbsPath(name, path).exists()) {
5940 // The file extension is probably missing.
5941 // Now try to find it out.
5942 char const * const lyxskak_format[] = {"fen", 0};
5943 string const lyxskak_name =
5944 find_file(name, path, lyxskak_format);
5945 if (!lyxskak_name.empty())
5946 name = lyxskak_name;
5948 FileName const absname = makeAbsPath(name, path);
5949 if (absname.exists())
5951 fix_child_filename(name);
5952 copy_file(absname, name);
5954 cerr << "Warning: Could not find file '"
5955 << name << "'." << endl;
5956 context.check_layout(os);
5957 begin_inset(os, "External\n\ttemplate ");
5958 os << "ChessDiagram\n\tfilename "
5961 context.check_layout(os);
5962 // after a \loadgame follows a \showboard
5963 if (p.get_token().asInput() == "showboard")
5965 registerExternalTemplatePackages("ChessDiagram");
5969 // try to see whether the string is in unicodesymbols
5970 // Only use text mode commands, since we are in text mode here,
5971 // and math commands may be invalid (bug 6797)
5972 string name = t.asInput();
5973 // handle the dingbats, cyrillic and greek
5974 if (name == "\\textcyr")
5975 name = "\\textcyrillic";
5976 if (name == "\\ding" || name == "\\textcyrillic" ||
5977 (name == "\\textgreek" && !preamble.usePolyglossia()))
5978 name = name + '{' + p.getArg('{', '}') + '}';
5979 // handle the ifsym characters
5980 else if (name == "\\textifsymbol") {
5981 string const optif = p.getFullOpt();
5982 string const argif = p.getArg('{', '}');
5983 name = name + optif + '{' + argif + '}';
5985 // handle the \ascii characters
5986 // the case of \ascii within braces, as LyX outputs it, is already
5987 // handled for t.cat() == catBegin
5988 else if (name == "\\ascii") {
5989 // the code is "\asci\xxx"
5990 name = "{" + name + p.get_token().asInput() + "}";
5993 // handle some TIPA special characters
5994 else if (preamble.isPackageUsed("tipa")) {
5995 if (name == "\\s") {
5996 // fromLaTeXCommand() does not yet
5997 // recognize tipa short cuts
5998 name = "\\textsyllabic";
5999 } else if (name == "\\=" &&
6000 p.next_token().asInput() == "*") {
6001 // fromLaTeXCommand() does not yet
6002 // recognize tipa short cuts
6004 name = "\\textsubbar";
6005 } else if (name == "\\textdoublevertline") {
6006 // FIXME: This is not correct,
6007 // \textvertline is higher than \textbardbl
6008 name = "\\textbardbl";
6010 } else if (name == "\\!" ) {
6011 if (p.next_token().asInput() == "b") {
6012 p.get_token(); // eat 'b'
6015 } else if (p.next_token().asInput() == "d") {
6019 } else if (p.next_token().asInput() == "g") {
6023 } else if (p.next_token().asInput() == "G") {
6025 name = "\\texthtscg";
6027 } else if (p.next_token().asInput() == "j") {
6029 name = "\\texthtbardotlessj";
6031 } else if (p.next_token().asInput() == "o") {
6033 name = "\\textbullseye";
6036 } else if (name == "\\*" ) {
6037 if (p.next_token().asInput() == "k") {
6039 name = "\\textturnk";
6041 } else if (p.next_token().asInput() == "r") {
6042 p.get_token(); // eat 'b'
6043 name = "\\textturnr";
6045 } else if (p.next_token().asInput() == "t") {
6047 name = "\\textturnt";
6049 } else if (p.next_token().asInput() == "w") {
6051 name = "\\textturnw";
6056 if ((name.size() == 2 &&
6057 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6058 p.next_token().asInput() != "*") ||
6059 is_known(name.substr(1), known_tipa_marks)) {
6060 // name is a command that corresponds to a
6061 // combining character in unicodesymbols.
6062 // Append the argument, fromLaTeXCommand()
6063 // will either convert it to a single
6064 // character or a combining sequence.
6065 name += '{' + p.verbatim_item() + '}';
6067 // now get the character from unicodesymbols
6071 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6072 Encodings::TEXT_CMD, termination, rem, &req));
6074 context.check_layout(os);
6077 output_ert_inset(os, to_utf8(rem), context);
6079 skip_spaces_braces(p);
6080 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6081 preamble.registerAutomaticallyLoadedPackage(*it);
6083 //cerr << "#: " << t << " mode: " << mode << endl;
6084 // heuristic: read up to next non-nested space
6086 string s = t.asInput();
6087 string z = p.verbatim_item();
6088 while (p.good() && z != " " && !z.empty()) {
6089 //cerr << "read: " << z << endl;
6091 z = p.verbatim_item();
6093 cerr << "found ERT: " << s << endl;
6094 output_ert_inset(os, s + ' ', context);
6097 if (t.asInput() == name &&
6098 p.next_token().asInput() == "*") {
6099 // Starred commands like \vspace*{}
6100 p.get_token(); // Eat '*'
6103 if (!parse_command(name, p, os, outer, context)) {
6104 output_ert_inset(os, name, context);
6105 // Try to handle options of unknown commands:
6106 // Look if we have optional arguments,
6107 // and if so, put the brackets in ERT.
6108 while (p.hasOpt()) {
6109 p.get_token(); // eat '['
6110 output_ert_inset(os, "[", context);
6111 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6112 output_ert_inset(os, "]", context);
6120 string guessLanguage(Parser & p, string const & lang)
6122 typedef std::map<std::string, size_t> LangMap;
6123 // map from language names to number of characters
6126 for (char const * const * i = supported_CJK_languages; *i; i++)
6127 used[string(*i)] = 0;
6130 Token const t = p.get_token();
6131 // comments are not counted for any language
6132 if (t.cat() == catComment)
6134 // commands are not counted as well, but we need to detect
6135 // \begin{CJK} and switch encoding if needed
6136 if (t.cat() == catEscape) {
6137 if (t.cs() == "inputencoding") {
6138 string const enc = subst(p.verbatim_item(), "\n", " ");
6139 p.setEncoding(enc, Encoding::inputenc);
6142 if (t.cs() != "begin")
6145 // Non-CJK content is counted for lang.
6146 // We do not care about the real language here:
6147 // If we have more non-CJK contents than CJK contents,
6148 // we simply use the language that was specified as
6149 // babel main language.
6150 used[lang] += t.asInput().length();
6153 // Now we are starting an environment
6155 string const name = p.getArg('{', '}');
6156 if (name != "CJK") {
6160 // It is a CJK environment
6162 /* name = */ p.getArg('{', '}');
6163 string const encoding = p.getArg('{', '}');
6164 /* mapping = */ p.getArg('{', '}');
6165 string const encoding_old = p.getEncoding();
6166 char const * const * const where =
6167 is_known(encoding, supported_CJK_encodings);
6169 p.setEncoding(encoding, Encoding::CJK);
6171 p.setEncoding("UTF-8");
6172 string const text = p.ertEnvironment("CJK");
6173 p.setEncoding(encoding_old);
6176 // ignore contents in unknown CJK encoding
6179 // the language of the text
6181 supported_CJK_languages[where - supported_CJK_encodings];
6182 used[cjk] += text.length();
6184 LangMap::const_iterator use = used.begin();
6185 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6186 if (it->second > use->second)
6193 void check_comment_bib(ostream & os, Context & context)
6195 if (!need_commentbib)
6197 // We have a bibliography database, but no bibliography with biblatex
6198 // which is completely valid. Insert a bibtex inset in a note.
6199 context.check_layout(os);
6200 begin_inset(os, "Note Note\n");
6201 os << "status open\n";
6202 os << "\\begin_layout Plain Layout\n";
6203 begin_command_inset(os, "bibtex", "bibtex");
6205 for (auto const & bf : preamble.biblatex_bibliographies) {
6206 if (!bibfiles.empty())
6208 bibfiles += normalize_filename(bf);
6210 if (!bibfiles.empty())
6211 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6212 end_inset(os);// Bibtex
6213 os << "\\end_layout\n";
6214 end_inset(os);// Note