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 parse_text_snippet(p, os, flags, outer, parent_context);
1599 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1601 parent_context.new_layout_allowed = new_layout_allowed;
1605 void parse_environment(Parser & p, ostream & os, bool outer,
1606 string & last_env, Context & parent_context)
1608 Layout const * newlayout;
1609 InsetLayout const * newinsetlayout = 0;
1610 string const name = p.getArg('{', '}');
1611 const bool is_starred = suffixIs(name, '*');
1612 string const unstarred_name = rtrim(name, "*");
1613 active_environments.push_back(name);
1615 // We use this loop and break out after a condition is met
1616 // rather than a huge else-if-chain.
1618 if (is_math_env(name)) {
1619 parent_context.check_layout(os);
1620 begin_inset(os, "Formula ");
1621 os << "\\begin{" << name << "}";
1622 parse_math(p, os, FLAG_END, MATH_MODE);
1623 os << "\\end{" << name << "}";
1625 if (is_display_math_env(name)) {
1626 // Prevent the conversion of a line break to a space
1627 // (bug 7668). This does not change the output, but
1628 // looks ugly in LyX.
1629 eat_whitespace(p, os, parent_context, false);
1634 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1635 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1636 // We must begin a new paragraph if not already done
1637 if (! parent_context.atParagraphStart()) {
1638 parent_context.check_end_layout(os);
1639 parent_context.new_paragraph(os);
1641 // save the language in the context so that it is
1642 // handled by parse_text
1643 parent_context.font.language =
1644 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1645 parse_text(p, os, FLAG_END, outer, parent_context);
1646 // Just in case the environment is empty
1647 parent_context.extra_stuff.erase();
1648 // We must begin a new paragraph to reset the language
1649 parent_context.new_paragraph(os);
1654 if (unstarred_name == "tabular" || name == "longtable"
1655 || name == "tabularx" || name == "xltabular") {
1656 eat_whitespace(p, os, parent_context, false);
1657 string width = "0pt";
1659 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1660 string const opt = p.getArg('[', ']');
1663 else if (opt == "l")
1665 else if (opt == "r")
1668 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1669 width = lyx::translate_len(p.getArg('{', '}'));
1670 eat_whitespace(p, os, parent_context, false);
1672 parent_context.check_layout(os);
1673 begin_inset(os, "Tabular ");
1674 handle_tabular(p, os, name, width, halign, parent_context);
1680 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1681 eat_whitespace(p, os, parent_context, false);
1682 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1683 eat_whitespace(p, os, parent_context, false);
1684 parent_context.check_layout(os);
1685 begin_inset(os, "Float " + unstarred_name + "\n");
1686 // store the float type for subfloats
1687 // subfloats only work with figures and tables
1688 if (unstarred_name == "figure")
1689 float_type = unstarred_name;
1690 else if (unstarred_name == "table")
1691 float_type = unstarred_name;
1695 os << "placement " << opt << '\n';
1696 if (contains(opt, "H"))
1697 preamble.registerAutomaticallyLoadedPackage("float");
1699 Floating const & fl = parent_context.textclass.floats()
1700 .getType(unstarred_name);
1701 if (!fl.floattype().empty() && fl.usesFloatPkg())
1702 preamble.registerAutomaticallyLoadedPackage("float");
1705 os << "wide " << convert<string>(is_starred)
1706 << "\nsideways false"
1707 << "\nstatus open\n\n";
1708 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1710 // We don't need really a new paragraph, but
1711 // we must make sure that the next item gets a \begin_layout.
1712 parent_context.new_paragraph(os);
1714 // the float is parsed thus delete the type
1719 if (unstarred_name == "sidewaysfigure"
1720 || unstarred_name == "sidewaystable"
1721 || unstarred_name == "sidewaysalgorithm") {
1722 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1723 eat_whitespace(p, os, parent_context, false);
1724 parent_context.check_layout(os);
1725 if (unstarred_name == "sidewaysfigure")
1726 begin_inset(os, "Float figure\n");
1727 else if (unstarred_name == "sidewaystable")
1728 begin_inset(os, "Float table\n");
1729 else if (unstarred_name == "sidewaysalgorithm")
1730 begin_inset(os, "Float algorithm\n");
1732 os << "placement " << opt << '\n';
1733 if (contains(opt, "H"))
1734 preamble.registerAutomaticallyLoadedPackage("float");
1735 os << "wide " << convert<string>(is_starred)
1736 << "\nsideways true"
1737 << "\nstatus open\n\n";
1738 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1740 // We don't need really a new paragraph, but
1741 // we must make sure that the next item gets a \begin_layout.
1742 parent_context.new_paragraph(os);
1744 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1748 if (name == "wrapfigure" || name == "wraptable") {
1749 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1750 eat_whitespace(p, os, parent_context, false);
1751 parent_context.check_layout(os);
1754 string overhang = "0col%";
1757 lines = p.getArg('[', ']');
1758 string const placement = p.getArg('{', '}');
1760 overhang = p.getArg('[', ']');
1761 string const width = p.getArg('{', '}');
1763 if (name == "wrapfigure")
1764 begin_inset(os, "Wrap figure\n");
1766 begin_inset(os, "Wrap table\n");
1767 os << "lines " << lines
1768 << "\nplacement " << placement
1769 << "\noverhang " << lyx::translate_len(overhang)
1770 << "\nwidth " << lyx::translate_len(width)
1771 << "\nstatus open\n\n";
1772 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1774 // We don't need really a new paragraph, but
1775 // we must make sure that the next item gets a \begin_layout.
1776 parent_context.new_paragraph(os);
1778 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1782 if (name == "minipage") {
1783 eat_whitespace(p, os, parent_context, false);
1784 // Test whether this is an outer box of a shaded box
1786 // swallow arguments
1787 while (p.hasOpt()) {
1789 p.skip_spaces(true);
1792 p.skip_spaces(true);
1793 Token t = p.get_token();
1794 bool shaded = false;
1795 if (t.asInput() == "\\begin") {
1796 p.skip_spaces(true);
1797 if (p.getArg('{', '}') == "shaded")
1802 parse_outer_box(p, os, FLAG_END, outer,
1803 parent_context, name, "shaded");
1805 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1806 "", "", name, "", "");
1811 if (name == "comment") {
1812 eat_whitespace(p, os, parent_context, false);
1813 parent_context.check_layout(os);
1814 begin_inset(os, "Note Comment\n");
1815 os << "status open\n";
1816 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1819 skip_braces(p); // eat {} that might by set by LyX behind comments
1820 preamble.registerAutomaticallyLoadedPackage("verbatim");
1824 if (unstarred_name == "verbatim") {
1825 // FIXME: this should go in the generic code that
1826 // handles environments defined in layout file that
1827 // have "PassThru 1". However, the code over there is
1828 // already too complicated for my taste.
1829 string const ascii_name =
1830 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1831 parent_context.new_paragraph(os);
1832 Context context(true, parent_context.textclass,
1833 &parent_context.textclass[from_ascii(ascii_name)]);
1834 string s = p.verbatimEnvironment(name);
1835 output_ert(os, s, context);
1840 if (name == "IPA") {
1841 eat_whitespace(p, os, parent_context, false);
1842 parent_context.check_layout(os);
1843 begin_inset(os, "IPA\n");
1844 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1847 preamble.registerAutomaticallyLoadedPackage("tipa");
1848 preamble.registerAutomaticallyLoadedPackage("tipx");
1852 if (name == parent_context.textclass.titlename()
1853 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1854 parse_text(p, os, FLAG_END, outer, parent_context);
1855 // Just in case the environment is empty
1856 parent_context.extra_stuff.erase();
1857 // We must begin a new paragraph
1858 parent_context.new_paragraph(os);
1863 if (name == "CJK") {
1864 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1865 // It is impossible to decide if a CJK environment was in its own paragraph or within
1866 // a line. We therefore always assume a paragraph since the latter is a rare case.
1867 eat_whitespace(p, os, parent_context, false);
1868 parent_context.check_end_layout(os);
1869 // store the encoding to be able to reset it
1870 string const encoding_old = p.getEncoding();
1871 string const encoding = p.getArg('{', '}');
1872 // FIXME: For some reason JIS does not work. Although the text
1873 // in tests/CJK.tex is identical with the SJIS version if you
1874 // convert both snippets using the recode command line utility,
1875 // the resulting .lyx file contains some extra characters if
1876 // you set buggy_encoding to false for JIS.
1877 bool const buggy_encoding = encoding == "JIS";
1878 if (!buggy_encoding)
1879 p.setEncoding(encoding, Encoding::CJK);
1881 // FIXME: This will read garbage, since the data is not encoded in utf8.
1882 p.setEncoding("UTF-8");
1884 // LyX only supports the same mapping for all CJK
1885 // environments, so we might need to output everything as ERT
1886 string const mapping = trim(p.getArg('{', '}'));
1887 char const * const * const where =
1888 is_known(encoding, supported_CJK_encodings);
1889 if (!buggy_encoding && !preamble.fontCJKSet())
1890 preamble.fontCJK(mapping);
1891 bool knownMapping = mapping == preamble.fontCJK();
1892 if (buggy_encoding || !knownMapping || !where) {
1893 parent_context.check_layout(os);
1894 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1896 // we must parse the content as verbatim because e.g. JIS can contain
1897 // normally invalid characters
1898 // FIXME: This works only for the most simple cases.
1899 // Since TeX control characters are not parsed,
1900 // things like comments are completely wrong.
1901 string const s = p.plainEnvironment("CJK");
1902 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1905 if (snip == "\\" || is_known(snip, known_escaped_chars))
1906 output_ert_inset(os, snip, parent_context);
1907 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1912 output_ert_inset(os, "\\end{" + name + "}",
1916 supported_CJK_languages[where - supported_CJK_encodings];
1917 // store the language because we must reset it at the end
1918 string const lang_old = parent_context.font.language;
1919 parent_context.font.language = lang;
1920 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1921 parent_context.font.language = lang_old;
1922 parent_context.new_paragraph(os);
1924 p.setEncoding(encoding_old);
1929 if (name == "lyxgreyedout") {
1930 eat_whitespace(p, os, parent_context, false);
1931 parent_context.check_layout(os);
1932 begin_inset(os, "Note Greyedout\n");
1933 os << "status open\n";
1934 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1937 if (!preamble.notefontcolor().empty())
1938 preamble.registerAutomaticallyLoadedPackage("color");
1942 if (name == "btSect") {
1943 eat_whitespace(p, os, parent_context, false);
1944 parent_context.check_layout(os);
1945 begin_command_inset(os, "bibtex", "bibtex");
1946 string bibstyle = "plain";
1948 bibstyle = p.getArg('[', ']');
1949 p.skip_spaces(true);
1951 string const bibfile = p.getArg('{', '}');
1952 eat_whitespace(p, os, parent_context, false);
1953 Token t = p.get_token();
1954 if (t.asInput() == "\\btPrintCited") {
1955 p.skip_spaces(true);
1956 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1958 if (t.asInput() == "\\btPrintNotCited") {
1959 p.skip_spaces(true);
1960 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1962 if (t.asInput() == "\\btPrintAll") {
1963 p.skip_spaces(true);
1964 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1966 os << "bibfiles " << '"' << bibfile << "\"\n"
1967 << "options " << '"' << bibstyle << "\"\n";
1968 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1974 if (name == "btUnit") {
1975 string const nt = p.next_next_token().cs();
1976 // Do not attempt to overwrite a former diverging multibib.
1977 // Those are output as ERT instead.
1978 if ((nt == "part" || nt == "chapter"
1979 || nt == "section" || nt == "subsection")
1980 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1981 parse_text(p, os, FLAG_END, outer, parent_context);
1982 preamble.multibib(nt);
1984 parse_unknown_environment(p, name, os, FLAG_END, outer,
1989 // This is only attempted at turn environments that consist only
1990 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
1991 // Thus we will fall through in other cases.
1992 if (name == "turn") {
1993 // We check if the next thing is a tabular[*|x]
1995 p.getArg('{', '}');// eat turn argument
1996 bool found_end = false;
1997 bool only_table = false;
1998 bool end_table = false;
2001 string envname = p.getArg('{', '}');
2002 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2003 // Now we check if the table is the only content
2004 // of the turn environment
2005 string const tenv = envname;
2006 while (!found_end && !end_table && p.good()) {
2007 envname = p.next_token().cat() == catBegin
2008 ? p.getArg('{', '}') : string();
2009 Token const & t = p.get_token();
2011 end_table = t.asInput() != "\\end"
2013 found_end = t.asInput() == "\\end"
2014 && envname == "turn";
2018 envname = p.getArg('{', '}');
2019 only_table = p.next_next_token().asInput() == "\\end"
2020 && envname == "turn";
2024 string const angle = p.getArg('{', '}');
2026 int const save_tablerotation = parent_context.tablerotation;
2027 parent_context.tablerotation = convert<int>(angle);
2028 parse_text(p, os, FLAG_END, outer, parent_context);
2029 parent_context.tablerotation = save_tablerotation;
2039 // This is only attempted at landscape environments that consist only
2040 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2041 // Other landscape environment is handled via the landscape module, thus
2042 // we will fall through in that case.
2043 if (name == "landscape") {
2044 // We check if the next thing is a longtable
2046 bool found_end = false;
2047 bool only_longtable = false;
2048 bool end_longtable = false;
2051 string envname = p.getArg('{', '}');
2052 if (envname == "longtable" || envname == "xltabular") {
2053 // Now we check if the longtable is the only content
2054 // of the landscape environment
2055 string const ltenv = envname;
2056 while (!found_end && !end_longtable && p.good()) {
2057 envname = p.next_token().cat() == catBegin
2058 ? p.getArg('{', '}') : string();
2059 Token const & t = p.get_token();
2061 end_longtable = t.asInput() != "\\end"
2062 && envname == ltenv;
2063 found_end = t.asInput() == "\\end"
2064 && envname == "landscape";
2066 if (end_longtable) {
2068 envname = p.getArg('{', '}');
2069 only_longtable = p.next_next_token().asInput() == "\\end"
2070 && envname == "landscape";
2072 if (only_longtable) {
2075 int const save_tablerotation = parent_context.tablerotation;
2076 parent_context.tablerotation = 90;
2077 parse_text(p, os, FLAG_END, outer, parent_context);
2078 parent_context.tablerotation = save_tablerotation;
2088 if (name == "framed" || name == "shaded") {
2089 eat_whitespace(p, os, parent_context, false);
2090 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2092 preamble.registerAutomaticallyLoadedPackage("framed");
2096 if (name == "listing") {
2097 minted_float = "float";
2098 eat_whitespace(p, os, parent_context, false);
2099 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2101 minted_float += "=" + opt;
2102 // If something precedes \begin{minted}, we output it at the end
2103 // as a caption, in order to keep it inside the listings inset.
2104 eat_whitespace(p, os, parent_context, true);
2106 Token const & t = p.get_token();
2107 p.skip_spaces(true);
2108 string const envname = p.next_token().cat() == catBegin
2109 ? p.getArg('{', '}') : string();
2110 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2112 minted_float_has_caption = false;
2113 string content = parse_text_snippet(p, FLAG_END, outer,
2115 size_t i = content.find("\\begin_inset listings");
2116 bool minted_env = i != string::npos;
2119 caption = content.substr(0, i);
2120 content.erase(0, i);
2122 parent_context.check_layout(os);
2123 if (minted_env && minted_float_has_caption) {
2124 eat_whitespace(p, os, parent_context, true);
2125 os << content << "\n";
2126 if (!caption.empty())
2127 os << caption << "\n";
2128 os << "\n\\end_layout\n"; // close inner layout
2129 end_inset(os); // close caption inset
2130 os << "\n\\end_layout\n"; // close outer layout
2131 } else if (!caption.empty()) {
2133 begin_inset(os, "listings\n");
2134 os << "lstparams " << '"' << minted_float << '"' << '\n';
2135 os << "inline false\n";
2136 os << "status collapsed\n";
2138 os << "\n\\begin_layout Plain Layout\n";
2139 begin_inset(os, "Caption Standard\n");
2140 Context newcontext(true, parent_context.textclass,
2141 0, 0, parent_context.font);
2142 newcontext.check_layout(os);
2143 os << caption << "\n";
2144 newcontext.check_end_layout(os);
2146 os << "\n\\end_layout\n";
2147 } else if (content.empty()) {
2148 begin_inset(os, "listings\n");
2149 os << "lstparams " << '"' << minted_float << '"' << '\n';
2150 os << "inline false\n";
2151 os << "status collapsed\n";
2153 os << content << "\n";
2155 end_inset(os); // close listings inset
2156 parent_context.check_end_layout(os);
2157 parent_context.new_paragraph(os);
2159 minted_float.clear();
2160 minted_float_has_caption = false;
2164 if (name == "lstlisting" || name == "minted") {
2165 bool use_minted = name == "minted";
2166 // with listings, we do not eat newlines here since
2167 // \begin{lstlistings}
2170 // // \begin{lstlistings}%
2173 // reads [foo] as content, whereas
2174 // // \begin{lstlistings}%
2177 // \begin{lstlistings}[foo,
2179 // reads [foo...] as argument.
2180 eat_whitespace(p, os, parent_context, false, use_minted);
2181 if (use_minted && minted_float.empty()) {
2182 // look ahead for a bottom caption
2184 bool found_end_minted = false;
2185 while (!found_end_minted && p.good()) {
2186 Token const & t = p.get_token();
2188 string const envname =
2189 p.next_token().cat() == catBegin
2190 ? p.getArg('{', '}') : string();
2191 found_end_minted = t.asInput() == "\\end"
2192 && envname == "minted";
2194 eat_whitespace(p, os, parent_context, true);
2195 Token const & t = p.get_token();
2196 p.skip_spaces(true);
2197 if (t.asInput() == "\\lyxmintcaption") {
2198 string const pos = p.getArg('[', ']');
2200 string const caption =
2201 parse_text_snippet(p, FLAG_ITEM,
2202 false, parent_context);
2203 minted_nonfloat_caption = "[b]" + caption;
2204 eat_whitespace(p, os, parent_context, true);
2209 parse_listings(p, os, parent_context, false, use_minted);
2214 if (!parent_context.new_layout_allowed) {
2215 parse_unknown_environment(p, name, os, FLAG_END, outer,
2220 // Alignment and spacing settings
2221 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2222 // therefore are totally broken!
2223 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2224 // they are commands not environments. They are furthermore switches that
2225 // can be ended by another switches, but also by commands like \footnote or
2226 // \parbox. So the only safe way is to leave them untouched.
2227 // However, we support the pseudo-environments
2228 // \begin{centering} ... \end{centering}
2229 // \begin{raggedright} ... \end{raggedright}
2230 // \begin{raggedleft} ... \end{raggedleft}
2231 // since they are used by LyX in floats (for spacing reasons)
2232 if (name == "center" || name == "centering"
2233 || name == "flushleft" || name == "raggedright"
2234 || name == "flushright" || name == "raggedleft"
2235 || name == "singlespace" || name == "onehalfspace"
2236 || name == "doublespace" || name == "spacing") {
2237 eat_whitespace(p, os, parent_context, false);
2238 // We must begin a new paragraph if not already done
2239 if (! parent_context.atParagraphStart()) {
2240 parent_context.check_end_layout(os);
2241 parent_context.new_paragraph(os);
2243 if (name == "flushleft" || name == "raggedright")
2244 parent_context.add_extra_stuff("\\align left\n");
2245 else if (name == "flushright" || name == "raggedleft")
2246 parent_context.add_extra_stuff("\\align right\n");
2247 else if (name == "center" || name == "centering")
2248 parent_context.add_extra_stuff("\\align center\n");
2249 else if (name == "singlespace")
2250 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2251 else if (name == "onehalfspace") {
2252 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2253 preamble.registerAutomaticallyLoadedPackage("setspace");
2254 } else if (name == "doublespace") {
2255 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2256 preamble.registerAutomaticallyLoadedPackage("setspace");
2257 } else if (name == "spacing") {
2258 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2259 preamble.registerAutomaticallyLoadedPackage("setspace");
2261 parse_text(p, os, FLAG_END, outer, parent_context);
2262 // Just in case the environment is empty
2263 parent_context.extra_stuff.erase();
2264 // We must begin a new paragraph to reset the alignment
2265 parent_context.new_paragraph(os);
2270 // The single '=' is meant here.
2271 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2272 eat_whitespace(p, os, parent_context, false);
2273 Context context(true, parent_context.textclass, newlayout,
2274 parent_context.layout, parent_context.font);
2275 if (parent_context.deeper_paragraph) {
2276 // We are beginning a nested environment after a
2277 // deeper paragraph inside the outer list environment.
2278 // Therefore we don't need to output a "begin deeper".
2279 context.need_end_deeper = true;
2281 parent_context.check_end_layout(os);
2282 if (last_env == name) {
2283 // we need to output a separator since LyX would export
2284 // the two environments as one otherwise (bug 5716)
2285 TeX2LyXDocClass const & textclass(parent_context.textclass);
2286 Context newcontext(true, textclass,
2287 &(textclass.defaultLayout()));
2288 newcontext.check_layout(os);
2289 begin_inset(os, "Separator plain\n");
2291 newcontext.check_end_layout(os);
2293 switch (context.layout->latextype) {
2294 case LATEX_LIST_ENVIRONMENT:
2295 context.add_par_extra_stuff("\\labelwidthstring "
2296 + p.verbatim_item() + '\n');
2299 case LATEX_BIB_ENVIRONMENT:
2300 p.verbatim_item(); // swallow next arg
2306 context.check_deeper(os);
2307 if (newlayout->keepempty) {
2308 // We need to start a new paragraph
2309 // even if it is empty.
2310 context.new_paragraph(os);
2311 context.check_layout(os);
2313 // handle known optional and required arguments
2314 if (context.layout->latextype == LATEX_ENVIRONMENT)
2315 output_arguments(os, p, outer, false, string(), context,
2316 context.layout->latexargs());
2317 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2319 output_arguments(oss, p, outer, false, string(), context,
2320 context.layout->latexargs());
2321 context.list_extra_stuff = oss.str();
2323 parse_text(p, os, FLAG_END, outer, context);
2324 if (context.layout->latextype == LATEX_ENVIRONMENT)
2325 output_arguments(os, p, outer, false, "post", context,
2326 context.layout->postcommandargs());
2327 context.check_end_layout(os);
2328 if (parent_context.deeper_paragraph) {
2329 // We must suppress the "end deeper" because we
2330 // suppressed the "begin deeper" above.
2331 context.need_end_deeper = false;
2333 context.check_end_deeper(os);
2334 parent_context.new_paragraph(os);
2336 if (!preamble.titleLayoutFound())
2337 preamble.titleLayoutFound(newlayout->intitle);
2338 set<string> const & req = newlayout->requires();
2339 set<string>::const_iterator it = req.begin();
2340 set<string>::const_iterator en = req.end();
2341 for (; it != en; ++it)
2342 preamble.registerAutomaticallyLoadedPackage(*it);
2346 // The single '=' is meant here.
2347 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2348 eat_whitespace(p, os, parent_context, false);
2349 parent_context.check_layout(os);
2350 begin_inset(os, "Flex ");
2351 docstring flex_name = newinsetlayout->name();
2352 // FIXME: what do we do if the prefix is not Flex: ?
2353 if (prefixIs(flex_name, from_ascii("Flex:")))
2354 flex_name.erase(0, 5);
2355 os << to_utf8(flex_name) << '\n'
2356 << "status collapsed\n";
2357 if (newinsetlayout->isPassThru()) {
2358 string const arg = p.verbatimEnvironment(name);
2359 Context context(true, parent_context.textclass,
2360 &parent_context.textclass.plainLayout(),
2361 parent_context.layout);
2362 output_ert(os, arg, parent_context);
2364 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2369 if (name == "appendix") {
2370 // This is no good latex style, but it works and is used in some documents...
2371 eat_whitespace(p, os, parent_context, false);
2372 parent_context.check_end_layout(os);
2373 Context context(true, parent_context.textclass, parent_context.layout,
2374 parent_context.layout, parent_context.font);
2375 context.check_layout(os);
2376 os << "\\start_of_appendix\n";
2377 parse_text(p, os, FLAG_END, outer, context);
2378 context.check_end_layout(os);
2383 if (known_environments.find(name) != known_environments.end()) {
2384 vector<ArgumentType> arguments = known_environments[name];
2385 // The last "argument" denotes wether we may translate the
2386 // environment contents to LyX
2387 // The default required if no argument is given makes us
2388 // compatible with the reLyXre environment.
2389 ArgumentType contents = arguments.empty() ?
2392 if (!arguments.empty())
2393 arguments.pop_back();
2394 // See comment in parse_unknown_environment()
2395 bool const specialfont =
2396 (parent_context.font != parent_context.normalfont);
2397 bool const new_layout_allowed =
2398 parent_context.new_layout_allowed;
2400 parent_context.new_layout_allowed = false;
2401 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2402 outer, parent_context);
2403 if (contents == verbatim)
2404 output_ert_inset(os, p.ertEnvironment(name),
2407 parse_text_snippet(p, os, FLAG_END, outer,
2409 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2411 parent_context.new_layout_allowed = new_layout_allowed;
2415 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2420 active_environments.pop_back();
2424 /// parses a comment and outputs it to \p os.
2425 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2426 bool skipNewlines = false)
2428 LASSERT(t.cat() == catComment, return);
2429 if (!t.cs().empty()) {
2430 context.check_layout(os);
2431 output_comment(p, os, t.cs(), context);
2432 if (p.next_token().cat() == catNewline) {
2433 // A newline after a comment line starts a new
2435 if (context.new_layout_allowed) {
2436 if(!context.atParagraphStart())
2437 // Only start a new paragraph if not already
2438 // done (we might get called recursively)
2439 context.new_paragraph(os);
2441 output_ert_inset(os, "\n", context);
2442 eat_whitespace(p, os, context, true);
2444 } else if (!skipNewlines) {
2445 // "%\n" combination
2452 * Reads spaces and comments until the first non-space, non-comment token.
2453 * New paragraphs (double newlines or \\par) are handled like simple spaces
2454 * if \p eatParagraph is true.
2455 * If \p eatNewline is false, newlines won't be treated as whitespace.
2456 * Spaces are skipped, but comments are written to \p os.
2458 void eat_whitespace(Parser & p, ostream & os, Context & context,
2459 bool eatParagraph, bool eatNewline)
2462 Token const & t = p.get_token();
2463 if (t.cat() == catComment)
2464 parse_comment(p, os, t, context, !eatNewline);
2465 else if ((!eatParagraph && p.isParagraph()) ||
2466 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2475 * Set a font attribute, parse text and reset the font attribute.
2476 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2477 * \param currentvalue Current value of the attribute. Is set to the new
2478 * value during parsing.
2479 * \param newvalue New value of the attribute
2481 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2482 Context & context, string const & attribute,
2483 string & currentvalue, string const & newvalue)
2485 context.check_layout(os);
2486 string const oldvalue = currentvalue;
2487 currentvalue = newvalue;
2488 os << '\n' << attribute << ' ' << newvalue << "\n";
2489 parse_text_snippet(p, os, flags, outer, context);
2490 context.check_layout(os);
2491 os << '\n' << attribute << ' ' << oldvalue << "\n";
2492 currentvalue = oldvalue;
2496 /// get the arguments of a natbib or jurabib citation command
2497 void get_cite_arguments(Parser & p, bool natbibOrder,
2498 string & before, string & after, bool const qualified = false)
2500 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2502 // text before the citation
2504 // text after the citation
2505 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2507 if (!after.empty()) {
2508 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2509 if (natbibOrder && !before.empty())
2510 swap(before, after);
2515 void copy_file(FileName const & src, string dstname)
2519 string const absParent = getParentFilePath(false);
2521 if (FileName::isAbsolute(dstname))
2522 dst = FileName(dstname);
2524 dst = makeAbsPath(dstname, absParent);
2525 FileName const srcpath = src.onlyPath();
2526 FileName const dstpath = dst.onlyPath();
2527 if (equivalent(srcpath, dstpath))
2529 if (!dstpath.isDirectory()) {
2530 if (!dstpath.createPath()) {
2531 cerr << "Warning: Could not create directory for file `"
2532 << dst.absFileName() << "´." << endl;
2536 if (dst.isReadableFile()) {
2537 if (overwriteFiles())
2538 cerr << "Warning: Overwriting existing file `"
2539 << dst.absFileName() << "´." << endl;
2541 cerr << "Warning: Not overwriting existing file `"
2542 << dst.absFileName() << "´." << endl;
2546 if (!src.copyTo(dst))
2547 cerr << "Warning: Could not copy file `" << src.absFileName()
2548 << "´ to `" << dst.absFileName() << "´." << endl;
2552 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2553 bool parse_chunk(Parser & p, ostream & os, Context & context)
2555 // check whether a chunk is possible here.
2556 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2562 // read the parameters
2563 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2564 if (!params.first) {
2569 Parser::Arg const code = p.verbatimStuff("\n@");
2574 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2575 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2579 // The last newline read is important for paragraph handling
2583 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2584 // We must have a valid layout before outputting the Chunk inset.
2585 context.check_layout(os);
2586 Context chunkcontext(true, context.textclass);
2587 chunkcontext.layout = &context.textclass.plainLayout();
2588 begin_inset(os, "Flex Chunk");
2589 os << "\nstatus open\n";
2590 if (!params.second.empty()) {
2591 chunkcontext.check_layout(os);
2592 Context paramscontext(true, context.textclass);
2593 paramscontext.layout = &context.textclass.plainLayout();
2594 begin_inset(os, "Argument 1");
2595 os << "\nstatus open\n";
2596 output_ert(os, params.second, paramscontext);
2599 output_ert(os, code.second, chunkcontext);
2607 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2608 bool is_macro(Parser & p)
2610 Token first = p.curr_token();
2611 if (first.cat() != catEscape || !p.good())
2613 if (first.cs() == "def")
2615 if (first.cs() != "global" && first.cs() != "long")
2617 Token second = p.get_token();
2619 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2620 second.cat() == catNewline || second.cat() == catComment)) {
2621 second = p.get_token();
2624 bool secondvalid = second.cat() == catEscape;
2626 bool thirdvalid = false;
2627 if (p.good() && first.cs() == "global" && secondvalid &&
2628 second.cs() == "long") {
2629 third = p.get_token();
2631 while (p.good() && !p.isParagraph() &&
2632 (third.cat() == catSpace ||
2633 third.cat() == catNewline ||
2634 third.cat() == catComment)) {
2635 third = p.get_token();
2638 thirdvalid = third.cat() == catEscape;
2640 for (int i = 0; i < pos; ++i)
2645 return (first.cs() == "global" || first.cs() == "long") &&
2646 second.cs() == "def";
2647 return first.cs() == "global" && second.cs() == "long" &&
2648 third.cs() == "def";
2652 /// Parse a macro definition (assumes that is_macro() returned true)
2653 void parse_macro(Parser & p, ostream & os, Context & context)
2655 context.check_layout(os);
2656 Token first = p.curr_token();
2659 string command = first.asInput();
2660 if (first.cs() != "def") {
2662 eat_whitespace(p, os, context, false);
2663 second = p.curr_token();
2664 command += second.asInput();
2665 if (second.cs() != "def") {
2667 eat_whitespace(p, os, context, false);
2668 third = p.curr_token();
2669 command += third.asInput();
2672 eat_whitespace(p, os, context, false);
2673 string const name = p.get_token().cs();
2674 eat_whitespace(p, os, context, false);
2680 while (p.next_token().cat() != catBegin) {
2681 if (p.next_token().cat() == catParameter) {
2686 // followed by number?
2687 if (p.next_token().cat() == catOther) {
2688 string s = p.get_token().asInput();
2690 // number = current arity + 1?
2691 if (s.size() == 1 && s[0] == arity + '0' + 1)
2696 paramtext += p.get_token().cs();
2698 paramtext += p.get_token().cs();
2703 // only output simple (i.e. compatible) macro as FormulaMacros
2704 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2706 context.check_layout(os);
2707 begin_inset(os, "FormulaMacro");
2708 os << "\n\\def" << ert;
2711 output_ert_inset(os, command + ert, context);
2715 void registerExternalTemplatePackages(string const & name)
2717 external::TemplateManager const & etm = external::TemplateManager::get();
2718 external::Template const * const et = etm.getTemplateByName(name);
2721 external::Template::Formats::const_iterator cit = et->formats.end();
2723 cit = et->formats.find("PDFLaTeX");
2724 if (cit == et->formats.end())
2725 // If the template has not specified a PDFLaTeX output,
2726 // we try the LaTeX format.
2727 cit = et->formats.find("LaTeX");
2728 if (cit == et->formats.end())
2730 vector<string>::const_iterator qit = cit->second.requirements.begin();
2731 vector<string>::const_iterator qend = cit->second.requirements.end();
2732 for (; qit != qend; ++qit)
2733 preamble.registerAutomaticallyLoadedPackage(*qit);
2736 } // anonymous namespace
2740 * Find a file with basename \p name in path \p path and an extension
2743 string find_file(string const & name, string const & path,
2744 char const * const * extensions)
2746 for (char const * const * what = extensions; *what; ++what) {
2747 string const trial = addExtension(name, *what);
2748 if (makeAbsPath(trial, path).exists())
2755 /// Convert filenames with TeX macros and/or quotes to something LyX
2757 string const normalize_filename(string const & name)
2762 Token const & t = p.get_token();
2763 if (t.cat() != catEscape)
2765 else if (t.cs() == "lyxdot") {
2766 // This is used by LyX for simple dots in relative
2770 } else if (t.cs() == "space") {
2773 } else if (t.cs() == "string") {
2774 // Convert \string" to " and \string~ to ~
2775 Token const & n = p.next_token();
2776 if (n.asInput() != "\"" && n.asInput() != "~")
2781 // Strip quotes. This is a bit complicated (see latex_path()).
2782 string full = os.str();
2783 if (!full.empty() && full[0] == '"') {
2784 string base = removeExtension(full);
2785 string ext = getExtension(full);
2786 if (!base.empty() && base[base.length()-1] == '"')
2789 return addExtension(trim(base, "\""), ext);
2790 if (full[full.length()-1] == '"')
2793 return trim(full, "\"");
2799 /// Convert \p name from TeX convention (relative to master file) to LyX
2800 /// convention (relative to .lyx file) if it is relative
2801 void fix_child_filename(string & name)
2803 string const absMasterTeX = getMasterFilePath(true);
2804 bool const isabs = FileName::isAbsolute(name);
2805 // convert from "relative to .tex master" to absolute original path
2807 name = makeAbsPath(name, absMasterTeX).absFileName();
2808 bool copyfile = copyFiles();
2809 string const absParentLyX = getParentFilePath(false);
2812 // convert from absolute original path to "relative to master file"
2813 string const rel = to_utf8(makeRelPath(from_utf8(name),
2814 from_utf8(absMasterTeX)));
2815 // re-interpret "relative to .tex file" as "relative to .lyx file"
2816 // (is different if the master .lyx file resides in a
2817 // different path than the master .tex file)
2818 string const absMasterLyX = getMasterFilePath(false);
2819 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2820 // Do not copy if the new path is impossible to create. Example:
2821 // absMasterTeX = "/foo/bar/"
2822 // absMasterLyX = "/bar/"
2823 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2824 if (contains(name, "/../"))
2831 // convert from absolute original path to
2832 // "relative to .lyx file"
2833 name = to_utf8(makeRelPath(from_utf8(abs),
2834 from_utf8(absParentLyX)));
2838 // convert from absolute original path to "relative to .lyx file"
2839 name = to_utf8(makeRelPath(from_utf8(name),
2840 from_utf8(absParentLyX)));
2845 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2846 Context & context, string const rdelim)
2848 Layout const * newlayout = 0;
2849 InsetLayout const * newinsetlayout = 0;
2850 char const * const * where = 0;
2851 // Store the latest bibliographystyle, addcontentslineContent and
2852 // nocite{*} option (needed for bibtex inset)
2854 string contentslineContent;
2855 // Some classes provide a \bibliographystyle, so do not output
2856 // any if none is explicitly set.
2857 string bibliographystyle;
2858 bool const use_natbib = isProvided("natbib");
2859 bool const use_jurabib = isProvided("jurabib");
2860 bool const use_biblatex = isProvided("biblatex")
2861 && preamble.citeEngine() != "biblatex-natbib";
2862 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2863 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2864 need_commentbib = use_biblatex || use_biblatex_natbib;
2867 // it is impossible to determine the correct encoding for non-CJK Japanese.
2868 // Therefore write a note at the beginning of the document
2869 if (is_nonCJKJapanese) {
2870 context.check_layout(os);
2871 begin_inset(os, "Note Note\n");
2872 os << "status open\n\\begin_layout Plain Layout\n"
2873 << "\\series bold\n"
2874 << "Important information:\n"
2875 << "\\end_layout\n\n"
2876 << "\\begin_layout Plain Layout\n"
2877 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2878 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2879 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2880 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2881 << " and specify the encoding using the -e command-line switch.\n"
2882 << " In addition, you might want to double check that the desired output encoding\n"
2883 << " is correctly selected in Document > Settings > Language.\n"
2884 << "\\end_layout\n";
2886 is_nonCJKJapanese = false;
2889 bool have_cycled = false;
2891 // Leave here only after at least one cycle
2892 if (have_cycled && flags & FLAG_LEAVE) {
2893 flags &= ~FLAG_LEAVE;
2897 Token const & t = p.get_token();
2899 debugToken(cerr, t, flags);
2902 if (flags & FLAG_ITEM) {
2903 if (t.cat() == catSpace)
2906 flags &= ~FLAG_ITEM;
2907 if (t.cat() == catBegin) {
2908 // skip the brace and collect everything to the next matching
2910 flags |= FLAG_BRACE_LAST;
2914 // handle only this single token, leave the loop if done
2915 flags |= FLAG_LEAVE;
2918 if (t.cat() != catEscape && t.character() == ']' &&
2919 (flags & FLAG_BRACK_LAST))
2921 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2923 string tok = t.asInput();
2924 // we only support delimiters with max 2 chars for now.
2925 if (rdelim.size() > 1)
2926 tok += p.next_token().asInput();
2927 if (t.cat() != catEscape && !rdelim.empty()
2928 && tok == rdelim && (flags & FLAG_RDELIM)) {
2929 if (rdelim.size() > 1)
2930 p.get_token(); // eat rdelim
2934 // If there is anything between \end{env} and \begin{env} we
2935 // don't need to output a separator.
2936 if (t.cat() != catSpace && t.cat() != catNewline &&
2937 t.asInput() != "\\begin")
2944 bool const starred = p.next_token().asInput() == "*";
2945 string const starredname(starred ? (t.cs() + '*') : t.cs());
2946 if (t.cat() == catMath) {
2947 // we are inside some text mode thingy, so opening new math is allowed
2948 context.check_layout(os);
2949 begin_inset(os, "Formula ");
2950 Token const & n = p.get_token();
2951 bool const display(n.cat() == catMath && outer);
2953 // TeX's $$...$$ syntax for displayed math
2955 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2957 p.get_token(); // skip the second '$' token
2959 // simple $...$ stuff
2962 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2967 // Prevent the conversion of a line break to a
2968 // space (bug 7668). This does not change the
2969 // output, but looks ugly in LyX.
2970 eat_whitespace(p, os, context, false);
2975 if (t.cat() == catSuper || t.cat() == catSub) {
2976 cerr << "catcode " << t << " illegal in text mode\n";
2980 // Basic support for quotes. We try to disambiguate
2981 // quotes from the context (e.g., a left english quote is
2982 // the same as a right german quote...).
2983 // Try to make a smart guess about the side
2984 Token const prev = p.prev_token();
2985 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2986 && prev.character() != '\n' && prev.character() != '~');
2987 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2988 context.check_layout(os);
2989 begin_inset(os, "Quotes ");
2990 os << guessQuoteStyle("eld", opening);
2996 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2997 context.check_layout(os);
2998 begin_inset(os, "Quotes ");
2999 os << guessQuoteStyle("erd", opening);
3006 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3007 context.check_layout(os);
3008 begin_inset(os, "Quotes ");
3009 os << guessQuoteStyle("ald", opening);
3016 if (t.asInput() == "<"
3017 && p.next_token().asInput() == "<") {
3018 bool has_chunk = false;
3022 has_chunk = parse_chunk(p, os, context);
3028 context.check_layout(os);
3029 begin_inset(os, "Quotes ");
3030 os << guessQuoteStyle("ard", opening);
3038 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3039 check_space(p, os, context);
3043 // babel shorthands (also used by polyglossia)
3044 // Since these can have different meanings for different languages
3045 // we import them as ERT (but they must be put in ERT to get output
3047 if (t.asInput() == "\"") {
3049 // These are known pairs. We put them together in
3050 // one ERT inset. In other cases (such as "a), only
3051 // the quotation mark is ERTed.
3052 if (p.next_token().asInput() == "\""
3053 || p.next_token().asInput() == "|"
3054 || p.next_token().asInput() == "-"
3055 || p.next_token().asInput() == "~"
3056 || p.next_token().asInput() == "="
3057 || p.next_token().asInput() == "/"
3058 || p.next_token().asInput() == "~"
3059 || p.next_token().asInput() == "'"
3060 || p.next_token().asInput() == "`"
3061 || p.next_token().asInput() == "<"
3062 || p.next_token().asInput() == ">") {
3063 s += p.next_token().asInput();
3066 output_ert_inset(os, s, context);
3070 if (t.character() == '[' && noweb_mode &&
3071 p.next_token().character() == '[') {
3072 // These can contain underscores
3074 string const s = p.getFullOpt() + ']';
3075 if (p.next_token().character() == ']')
3078 cerr << "Warning: Inserting missing ']' in '"
3079 << s << "'." << endl;
3080 output_ert_inset(os, s, context);
3084 if (t.cat() == catLetter) {
3085 context.check_layout(os);
3090 if (t.cat() == catOther ||
3091 t.cat() == catAlign ||
3092 t.cat() == catParameter) {
3093 context.check_layout(os);
3094 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3095 context.merging_hyphens_allowed &&
3096 context.font.family != "ttfamily" &&
3097 !context.layout->pass_thru) {
3098 if (p.next_next_token().asInput() == "-") {
3100 os << to_utf8(docstring(1, 0x2014));
3104 os << to_utf8(docstring(1, 0x2013));
3107 // This translates "&" to "\\&" which may be wrong...
3112 if (p.isParagraph()) {
3113 // In minted floating listings we will collect
3114 // everything into the caption, where multiple
3115 // paragraphs are forbidden.
3116 if (minted_float.empty()) {
3117 if (context.new_layout_allowed)
3118 context.new_paragraph(os);
3120 output_ert_inset(os, "\\par ", context);
3123 eat_whitespace(p, os, context, true);
3127 if (t.cat() == catActive) {
3128 context.check_layout(os);
3129 if (t.character() == '~') {
3130 if (context.layout->free_spacing)
3133 begin_inset(os, "space ~\n");
3141 if (t.cat() == catBegin) {
3142 Token const next = p.next_token();
3143 Token const end = p.next_next_token();
3144 if (next.cat() == catEnd) {
3146 Token const prev = p.prev_token();
3148 if (p.next_token().character() == '`')
3149 ; // ignore it in {}``
3151 output_ert_inset(os, "{}", context);
3152 } else if (next.cat() == catEscape &&
3153 is_known(next.cs(), known_quotes) &&
3154 end.cat() == catEnd) {
3155 // Something like {\textquoteright} (e.g.
3156 // from writer2latex). We may skip the
3157 // braces here for better readability.
3158 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3160 } else if (p.next_token().asInput() == "\\ascii") {
3161 // handle the \ascii characters
3162 // (the case without braces is handled later)
3163 // the code is "{\ascii\xxx}"
3164 p.get_token(); // eat \ascii
3165 string name2 = p.get_token().asInput();
3166 p.get_token(); // eat the final '}'
3167 string const name = "{\\ascii" + name2 + "}";
3171 // get the character from unicodesymbols
3172 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3173 Encodings::TEXT_CMD, termination, rem, &req);
3175 context.check_layout(os);
3178 output_ert_inset(os,
3179 to_utf8(rem), context);
3180 for (set<string>::const_iterator it = req.begin();
3181 it != req.end(); ++it)
3182 preamble.registerAutomaticallyLoadedPackage(*it);
3184 // we did not find a non-ert version
3185 output_ert_inset(os, name, context);
3187 context.check_layout(os);
3188 // special handling of font attribute changes
3189 Token const prev = p.prev_token();
3190 TeXFont const oldFont = context.font;
3191 if (next.character() == '[' ||
3192 next.character() == ']' ||
3193 next.character() == '*') {
3195 if (p.next_token().cat() == catEnd) {
3200 output_ert_inset(os, "{", context);
3201 parse_text_snippet(p, os,
3204 output_ert_inset(os, "}", context);
3206 } else if (! context.new_layout_allowed) {
3207 output_ert_inset(os, "{", context);
3208 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3210 output_ert_inset(os, "}", context);
3211 } else if (is_known(next.cs(), known_sizes)) {
3212 // next will change the size, so we must
3214 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3216 if (!context.atParagraphStart())
3218 << context.font.size << "\n";
3219 } else if (is_known(next.cs(), known_font_families)) {
3220 // next will change the font family, so we
3221 // must reset it here
3222 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3224 if (!context.atParagraphStart())
3226 << context.font.family << "\n";
3227 } else if (is_known(next.cs(), known_font_series)) {
3228 // next will change the font series, so we
3229 // must reset it here
3230 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3232 if (!context.atParagraphStart())
3234 << context.font.series << "\n";
3235 } else if (is_known(next.cs(), known_font_shapes)) {
3236 // next will change the font shape, so we
3237 // must reset it here
3238 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3240 if (!context.atParagraphStart())
3242 << context.font.shape << "\n";
3243 } else if (is_known(next.cs(), known_old_font_families) ||
3244 is_known(next.cs(), known_old_font_series) ||
3245 is_known(next.cs(), known_old_font_shapes)) {
3246 // next will change the font family, series
3247 // and shape, so we must reset it here
3248 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3250 if (!context.atParagraphStart())
3252 << context.font.family
3254 << context.font.series
3256 << context.font.shape << "\n";
3258 output_ert_inset(os, "{", context);
3259 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3261 output_ert_inset(os, "}", context);
3267 if (t.cat() == catEnd) {
3268 if (flags & FLAG_BRACE_LAST) {
3271 cerr << "stray '}' in text\n";
3272 output_ert_inset(os, "}", context);
3276 if (t.cat() == catComment) {
3277 parse_comment(p, os, t, context);
3282 // control sequences
3285 if (t.cs() == "(" || t.cs() == "[") {
3286 bool const simple = t.cs() == "(";
3287 context.check_layout(os);
3288 begin_inset(os, "Formula");
3289 os << " \\" << t.cs();
3290 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3291 os << '\\' << (simple ? ')' : ']');
3294 // Prevent the conversion of a line break to a
3295 // space (bug 7668). This does not change the
3296 // output, but looks ugly in LyX.
3297 eat_whitespace(p, os, context, false);
3302 if (t.cs() == "begin") {
3303 parse_environment(p, os, outer, last_env,
3308 if (t.cs() == "end") {
3309 if (flags & FLAG_END) {
3310 // eat environment name
3311 string const name = p.getArg('{', '}');
3312 if (name != active_environment())
3313 cerr << "\\end{" + name + "} does not match \\begin{"
3314 + active_environment() + "}\n";
3317 p.error("found 'end' unexpectedly");
3321 // "item" by default, but could be something else
3322 if (t.cs() == context.layout->itemcommand()) {
3324 if (context.layout->labeltype == LABEL_MANUAL) {
3325 // FIXME: This swallows comments, but we cannot use
3326 // eat_whitespace() since we must not output
3327 // anything before the item.
3328 p.skip_spaces(true);
3329 s = p.verbatimOption();
3331 p.skip_spaces(false);
3333 context.check_layout(os);
3334 if (context.has_item) {
3335 // An item in an unknown list-like environment
3336 // FIXME: Do this in check_layout()!
3337 context.has_item = false;
3338 string item = "\\" + context.layout->itemcommand();
3341 output_ert_inset(os, item, context);
3343 if (context.layout->labeltype != LABEL_MANUAL)
3344 output_arguments(os, p, outer, false, "item", context,
3345 context.layout->itemargs());
3346 if (!context.list_extra_stuff.empty()) {
3347 os << context.list_extra_stuff;
3348 context.list_extra_stuff.clear();
3350 else if (!s.empty()) {
3351 // LyX adds braces around the argument,
3352 // so we need to remove them here.
3353 if (s.size() > 2 && s[0] == '{' &&
3354 s[s.size()-1] == '}')
3355 s = s.substr(1, s.size()-2);
3356 // If the argument contains a space we
3357 // must put it into ERT: Otherwise LyX
3358 // would misinterpret the space as
3359 // item delimiter (bug 7663)
3360 if (contains(s, ' ')) {
3361 output_ert_inset(os, s, context);
3364 os << parse_text_snippet(p2,
3365 FLAG_BRACK_LAST, outer, context);
3367 // The space is needed to separate the
3368 // item from the rest of the sentence.
3370 eat_whitespace(p, os, context, false);
3375 if (t.cs() == "bibitem") {
3377 context.check_layout(os);
3378 eat_whitespace(p, os, context, false);
3379 string label = p.verbatimOption();
3380 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3381 bool const literal = !lbl.first;
3382 label = literal ? subst(label, "\n", " ") : lbl.second;
3383 string lit = literal ? "\"true\"" : "\"false\"";
3384 string key = convert_literate_command_inset_arg(p.verbatim_item());
3385 begin_command_inset(os, "bibitem", "bibitem");
3386 os << "label \"" << label << "\"\n"
3387 << "key \"" << key << "\"\n"
3388 << "literal " << lit << "\n";
3394 // catch the case of \def\inputGnumericTable
3396 if (t.cs() == "def") {
3397 Token second = p.next_token();
3398 if (second.cs() == "inputGnumericTable") {
3402 Token third = p.get_token();
3404 if (third.cs() == "input") {
3408 string name = normalize_filename(p.verbatim_item());
3409 string const path = getMasterFilePath(true);
3410 // We want to preserve relative / absolute filenames,
3411 // therefore path is only used for testing
3412 // The file extension is in every case ".tex".
3413 // So we need to remove this extension and check for
3414 // the original one.
3415 name = removeExtension(name);
3416 if (!makeAbsPath(name, path).exists()) {
3417 char const * const Gnumeric_formats[] = {"gnumeric",
3419 string const Gnumeric_name =
3420 find_file(name, path, Gnumeric_formats);
3421 if (!Gnumeric_name.empty())
3422 name = Gnumeric_name;
3424 FileName const absname = makeAbsPath(name, path);
3425 if (absname.exists()) {
3426 fix_child_filename(name);
3427 copy_file(absname, name);
3429 cerr << "Warning: Could not find file '"
3430 << name << "'." << endl;
3431 context.check_layout(os);
3432 begin_inset(os, "External\n\ttemplate ");
3433 os << "GnumericSpreadsheet\n\tfilename "
3436 context.check_layout(os);
3438 // register the packages that are automatically loaded
3439 // by the Gnumeric template
3440 registerExternalTemplatePackages("GnumericSpreadsheet");
3445 parse_macro(p, os, context);
3449 if (t.cs() == "noindent") {
3451 context.add_par_extra_stuff("\\noindent\n");
3455 if (t.cs() == "appendix") {
3456 context.add_par_extra_stuff("\\start_of_appendix\n");
3457 // We need to start a new paragraph. Otherwise the
3458 // appendix in 'bla\appendix\chapter{' would start
3460 context.new_paragraph(os);
3461 // We need to make sure that the paragraph is
3462 // generated even if it is empty. Otherwise the
3463 // appendix in '\par\appendix\par\chapter{' would
3465 context.check_layout(os);
3466 // FIXME: This is a hack to prevent paragraph
3467 // deletion if it is empty. Handle this better!
3468 output_comment(p, os,
3469 "dummy comment inserted by tex2lyx to "
3470 "ensure that this paragraph is not empty",
3472 // Both measures above may generate an additional
3473 // empty paragraph, but that does not hurt, because
3474 // whitespace does not matter here.
3475 eat_whitespace(p, os, context, true);
3479 // Must catch empty dates before findLayout is called below
3480 if (t.cs() == "date") {
3481 eat_whitespace(p, os, context, false);
3483 string const date = p.verbatim_item();
3486 preamble.suppressDate(true);
3489 preamble.suppressDate(false);
3490 if (context.new_layout_allowed &&
3491 (newlayout = findLayout(context.textclass,
3494 output_command_layout(os, p, outer,
3495 context, newlayout);
3496 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3497 if (!preamble.titleLayoutFound())
3498 preamble.titleLayoutFound(newlayout->intitle);
3499 set<string> const & req = newlayout->requires();
3500 set<string>::const_iterator it = req.begin();
3501 set<string>::const_iterator en = req.end();
3502 for (; it != en; ++it)
3503 preamble.registerAutomaticallyLoadedPackage(*it);
3505 output_ert_inset(os,
3506 "\\date{" + p.verbatim_item() + '}',
3512 // Before we look for the layout name with star and alone below, we check the layouts including
3513 // the LateXParam, which might be one or several options or a star.
3514 // The single '=' is meant here.
3515 if (context.new_layout_allowed &&
3516 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3517 // store the latexparam here. This is eaten in output_command_layout
3518 context.latexparam = newlayout->latexparam();
3520 output_command_layout(os, p, outer, context, newlayout);
3521 context.latexparam.clear();
3523 if (!preamble.titleLayoutFound())
3524 preamble.titleLayoutFound(newlayout->intitle);
3525 set<string> const & req = newlayout->requires();
3526 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3527 preamble.registerAutomaticallyLoadedPackage(*it);
3531 // Starred section headings
3532 // Must attempt to parse "Section*" before "Section".
3533 if ((p.next_token().asInput() == "*") &&
3534 context.new_layout_allowed &&
3535 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3538 output_command_layout(os, p, outer, context, newlayout);
3540 if (!preamble.titleLayoutFound())
3541 preamble.titleLayoutFound(newlayout->intitle);
3542 set<string> const & req = newlayout->requires();
3543 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3544 preamble.registerAutomaticallyLoadedPackage(*it);
3548 // Section headings and the like
3549 if (context.new_layout_allowed &&
3550 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3552 output_command_layout(os, p, outer, context, newlayout);
3554 if (!preamble.titleLayoutFound())
3555 preamble.titleLayoutFound(newlayout->intitle);
3556 set<string> const & req = newlayout->requires();
3557 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3558 preamble.registerAutomaticallyLoadedPackage(*it);
3562 if (t.cs() == "subfloat") {
3563 // the syntax is \subfloat[list entry][sub caption]{content}
3564 // if it is a table of figure depends on the surrounding float
3566 // do nothing if there is no outer float
3567 if (!float_type.empty()) {
3568 context.check_layout(os);
3570 begin_inset(os, "Float " + float_type + "\n");
3572 << "\nsideways false"
3573 << "\nstatus collapsed\n\n";
3576 bool has_caption = false;
3577 if (p.next_token().cat() != catEscape &&
3578 p.next_token().character() == '[') {
3579 p.get_token(); // eat '['
3580 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3583 // In case we have two optional args, the second is the caption.
3584 if (p.next_token().cat() != catEscape &&
3585 p.next_token().character() == '[') {
3586 p.get_token(); // eat '['
3587 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3590 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3591 // the caption comes always as the last
3593 // we must make sure that the caption gets a \begin_layout
3594 os << "\n\\begin_layout Plain Layout";
3596 begin_inset(os, "Caption Standard\n");
3597 Context newcontext(true, context.textclass,
3598 0, 0, context.font);
3599 newcontext.check_layout(os);
3600 os << caption << "\n";
3601 newcontext.check_end_layout(os);
3604 // close the layout we opened
3605 os << "\n\\end_layout";
3610 // if the float type is not supported or there is no surrounding float
3615 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3617 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3619 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3620 + "{" + p.verbatim_item() + '}', context);
3625 if (t.cs() == "xymatrix") {
3626 // we must open a new math because LyX's xy support is in math
3627 context.check_layout(os);
3628 begin_inset(os, "Formula ");
3630 os << "\\" << t.cs() << '{';
3631 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3634 preamble.registerAutomaticallyLoadedPackage("xy");
3638 if (t.cs() == "includegraphics") {
3639 bool const clip = p.next_token().asInput() == "*";
3642 string const arg = p.getArg('[', ']');
3643 map<string, string> opts;
3644 vector<string> keys;
3645 split_map(arg, opts, keys);
3647 opts["clip"] = string();
3648 string name = normalize_filename(p.verbatim_item());
3650 string const path = getMasterFilePath(true);
3651 // We want to preserve relative / absolute filenames,
3652 // therefore path is only used for testing
3653 if (!makeAbsPath(name, path).exists()) {
3654 // The file extension is probably missing.
3655 // Now try to find it out.
3656 string const dvips_name =
3657 find_file(name, path,
3658 known_dvips_graphics_formats);
3659 string const pdftex_name =
3660 find_file(name, path,
3661 known_pdftex_graphics_formats);
3662 if (!dvips_name.empty()) {
3663 if (!pdftex_name.empty()) {
3664 cerr << "This file contains the "
3666 "\"\\includegraphics{"
3668 "However, files\n\""
3669 << dvips_name << "\" and\n\""
3670 << pdftex_name << "\"\n"
3671 "both exist, so I had to make a "
3672 "choice and took the first one.\n"
3673 "Please move the unwanted one "
3674 "someplace else and try again\n"
3675 "if my choice was wrong."
3679 } else if (!pdftex_name.empty()) {
3685 FileName const absname = makeAbsPath(name, path);
3686 if (absname.exists()) {
3687 fix_child_filename(name);
3688 copy_file(absname, name);
3690 cerr << "Warning: Could not find graphics file '"
3691 << name << "'." << endl;
3693 context.check_layout(os);
3694 begin_inset(os, "Graphics ");
3695 os << "\n\tfilename " << name << '\n';
3696 if (opts.find("width") != opts.end())
3698 << translate_len(opts["width"]) << '\n';
3699 if (opts.find("height") != opts.end())
3701 << translate_len(opts["height"]) << '\n';
3702 if (opts.find("scale") != opts.end()) {
3703 istringstream iss(opts["scale"]);
3707 os << "\tscale " << val << '\n';
3709 if (opts.find("angle") != opts.end()) {
3710 os << "\trotateAngle "
3711 << opts["angle"] << '\n';
3712 vector<string>::const_iterator a =
3713 find(keys.begin(), keys.end(), "angle");
3714 vector<string>::const_iterator s =
3715 find(keys.begin(), keys.end(), "width");
3716 if (s == keys.end())
3717 s = find(keys.begin(), keys.end(), "height");
3718 if (s == keys.end())
3719 s = find(keys.begin(), keys.end(), "scale");
3720 if (s != keys.end() && distance(s, a) > 0)
3721 os << "\tscaleBeforeRotation\n";
3723 if (opts.find("origin") != opts.end()) {
3725 string const opt = opts["origin"];
3726 if (opt.find('l') != string::npos) ss << "left";
3727 if (opt.find('r') != string::npos) ss << "right";
3728 if (opt.find('c') != string::npos) ss << "center";
3729 if (opt.find('t') != string::npos) ss << "Top";
3730 if (opt.find('b') != string::npos) ss << "Bottom";
3731 if (opt.find('B') != string::npos) ss << "Baseline";
3732 if (!ss.str().empty())
3733 os << "\trotateOrigin " << ss.str() << '\n';
3735 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3737 if (opts.find("keepaspectratio") != opts.end())
3738 os << "\tkeepAspectRatio\n";
3739 if (opts.find("clip") != opts.end())
3741 if (opts.find("draft") != opts.end())
3743 if (opts.find("bb") != opts.end())
3744 os << "\tBoundingBox "
3745 << opts["bb"] << '\n';
3746 int numberOfbbOptions = 0;
3747 if (opts.find("bbllx") != opts.end())
3748 numberOfbbOptions++;
3749 if (opts.find("bblly") != opts.end())
3750 numberOfbbOptions++;
3751 if (opts.find("bburx") != opts.end())
3752 numberOfbbOptions++;
3753 if (opts.find("bbury") != opts.end())
3754 numberOfbbOptions++;
3755 if (numberOfbbOptions == 4)
3756 os << "\tBoundingBox "
3757 << opts["bbllx"] << " " << opts["bblly"] << " "
3758 << opts["bburx"] << " " << opts["bbury"] << '\n';
3759 else if (numberOfbbOptions > 0)
3760 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3761 numberOfbbOptions = 0;
3762 if (opts.find("natwidth") != opts.end())
3763 numberOfbbOptions++;
3764 if (opts.find("natheight") != opts.end())
3765 numberOfbbOptions++;
3766 if (numberOfbbOptions == 2)
3767 os << "\tBoundingBox 0bp 0bp "
3768 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3769 else if (numberOfbbOptions > 0)
3770 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3771 ostringstream special;
3772 if (opts.find("hiresbb") != opts.end())
3773 special << "hiresbb,";
3774 if (opts.find("trim") != opts.end())
3776 if (opts.find("viewport") != opts.end())
3777 special << "viewport=" << opts["viewport"] << ',';
3778 if (opts.find("totalheight") != opts.end())
3779 special << "totalheight=" << opts["totalheight"] << ',';
3780 if (opts.find("type") != opts.end())
3781 special << "type=" << opts["type"] << ',';
3782 if (opts.find("ext") != opts.end())
3783 special << "ext=" << opts["ext"] << ',';
3784 if (opts.find("read") != opts.end())
3785 special << "read=" << opts["read"] << ',';
3786 if (opts.find("command") != opts.end())
3787 special << "command=" << opts["command"] << ',';
3788 string s_special = special.str();
3789 if (!s_special.empty()) {
3790 // We had special arguments. Remove the trailing ','.
3791 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3793 // TODO: Handle the unknown settings better.
3794 // Warn about invalid options.
3795 // Check whether some option was given twice.
3797 preamble.registerAutomaticallyLoadedPackage("graphicx");
3801 if (t.cs() == "footnote" ||
3802 (t.cs() == "thanks" && context.layout->intitle)) {
3804 context.check_layout(os);
3805 begin_inset(os, "Foot\n");
3806 os << "status collapsed\n\n";
3807 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3812 if (t.cs() == "marginpar") {
3814 context.check_layout(os);
3815 begin_inset(os, "Marginal\n");
3816 os << "status collapsed\n\n";
3817 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3822 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3823 bool const use_minted = t.cs() == "mintinline";
3825 parse_listings(p, os, context, true, use_minted);
3829 if (t.cs() == "ensuremath") {
3831 context.check_layout(os);
3832 string const s = p.verbatim_item();
3833 //FIXME: this never triggers in UTF8
3834 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3837 output_ert_inset(os, "\\ensuremath{" + s + "}",
3842 else if (t.cs() == "makeindex"
3843 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3844 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3845 if (preamble.titleLayoutFound()) {
3847 skip_spaces_braces(p);
3849 output_ert_inset(os, t.asInput(), context);
3853 if (t.cs() == "tableofcontents"
3854 || t.cs() == "lstlistoflistings"
3855 || t.cs() == "listoflistings") {
3856 string name = t.cs();
3857 if (preamble.minted() && name == "listoflistings")
3858 name.insert(0, "lst");
3859 context.check_layout(os);
3860 begin_command_inset(os, "toc", name);
3862 skip_spaces_braces(p);
3863 if (name == "lstlistoflistings") {
3864 if (preamble.minted())
3865 preamble.registerAutomaticallyLoadedPackage("minted");
3867 preamble.registerAutomaticallyLoadedPackage("listings");
3872 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3873 context.check_layout(os);
3874 if (t.cs() == "listoffigures")
3875 begin_inset(os, "FloatList figure\n");
3877 begin_inset(os, "FloatList table\n");
3879 skip_spaces_braces(p);
3883 if (t.cs() == "listof") {
3884 p.skip_spaces(true);
3885 string const name = p.get_token().cs();
3886 if (context.textclass.floats().typeExist(name)) {
3887 context.check_layout(os);
3888 begin_inset(os, "FloatList ");
3891 p.get_token(); // swallow second arg
3893 output_ert_inset(os, "\\listof{" + name + "}", context);
3897 if ((where = is_known(t.cs(), known_text_font_families))) {
3898 parse_text_attributes(p, os, FLAG_ITEM, outer,
3899 context, "\\family", context.font.family,
3900 known_coded_font_families[where - known_text_font_families]);
3904 // beamer has a \textbf<overlay>{} inset
3905 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3906 parse_text_attributes(p, os, FLAG_ITEM, outer,
3907 context, "\\series", context.font.series,
3908 known_coded_font_series[where - known_text_font_series]);
3912 // beamer has a \textit<overlay>{} inset
3913 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3914 parse_text_attributes(p, os, FLAG_ITEM, outer,
3915 context, "\\shape", context.font.shape,
3916 known_coded_font_shapes[where - known_text_font_shapes]);
3920 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3921 context.check_layout(os);
3922 TeXFont oldFont = context.font;
3923 context.font.init();
3924 context.font.size = oldFont.size;
3925 os << "\n\\family " << context.font.family << "\n";
3926 os << "\n\\series " << context.font.series << "\n";
3927 os << "\n\\shape " << context.font.shape << "\n";
3928 if (t.cs() == "textnormal") {
3929 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3930 output_font_change(os, context.font, oldFont);
3931 context.font = oldFont;
3933 eat_whitespace(p, os, context, false);
3937 if (t.cs() == "textcolor") {
3938 // scheme is \textcolor{color name}{text}
3939 string const color = p.verbatim_item();
3940 // we support the predefined colors of the color and the xcolor package
3941 if (color == "black" || color == "blue" || color == "cyan"
3942 || color == "green" || color == "magenta" || color == "red"
3943 || color == "white" || color == "yellow") {
3944 context.check_layout(os);
3945 os << "\n\\color " << color << "\n";
3946 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3947 context.check_layout(os);
3948 os << "\n\\color inherit\n";
3949 preamble.registerAutomaticallyLoadedPackage("color");
3950 } else if (color == "brown" || color == "darkgray" || color == "gray"
3951 || color == "lightgray" || color == "lime" || color == "olive"
3952 || color == "orange" || color == "pink" || color == "purple"
3953 || color == "teal" || color == "violet") {
3954 context.check_layout(os);
3955 os << "\n\\color " << color << "\n";
3956 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3957 context.check_layout(os);
3958 os << "\n\\color inherit\n";
3959 preamble.registerAutomaticallyLoadedPackage("xcolor");
3961 // for custom defined colors
3962 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3966 if (t.cs() == "underbar" || t.cs() == "uline") {
3967 // \underbar is not 100% correct (LyX outputs \uline
3968 // of ulem.sty). The difference is that \ulem allows
3969 // line breaks, and \underbar does not.
3970 // Do NOT handle \underline.
3971 // \underbar cuts through y, g, q, p etc.,
3972 // \underline does not.
3973 context.check_layout(os);
3974 os << "\n\\bar under\n";
3975 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3976 context.check_layout(os);
3977 os << "\n\\bar default\n";
3978 preamble.registerAutomaticallyLoadedPackage("ulem");
3982 if (t.cs() == "sout") {
3983 context.check_layout(os);
3984 os << "\n\\strikeout on\n";
3985 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3986 context.check_layout(os);
3987 os << "\n\\strikeout default\n";
3988 preamble.registerAutomaticallyLoadedPackage("ulem");
3992 // beamer has an \emph<overlay>{} inset
3993 if ((t.cs() == "uuline" || t.cs() == "uwave"
3994 || t.cs() == "emph" || t.cs() == "noun"
3995 || t.cs() == "xout") && !p.hasOpt("<")) {
3996 context.check_layout(os);
3997 os << "\n\\" << t.cs() << " on\n";
3998 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3999 context.check_layout(os);
4000 os << "\n\\" << t.cs() << " default\n";
4001 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4002 preamble.registerAutomaticallyLoadedPackage("ulem");
4006 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
4007 context.check_layout(os);
4008 string name = p.getArg('{', '}');
4009 string localtime = p.getArg('{', '}');
4010 preamble.registerAuthor(name);
4011 Author const & author = preamble.getAuthor(name);
4012 // from_asctime_utc() will fail if LyX decides to output the
4013 // time in the text language.
4014 time_t ptime = from_asctime_utc(localtime);
4015 if (ptime == static_cast<time_t>(-1)) {
4016 cerr << "Warning: Could not parse time `" << localtime
4017 << "´ for change tracking, using current time instead.\n";
4018 ptime = current_time();
4020 if (t.cs() == "lyxadded")
4021 os << "\n\\change_inserted ";
4023 os << "\n\\change_deleted ";
4024 os << author.bufferId() << ' ' << ptime << '\n';
4025 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4026 bool dvipost = LaTeXPackages::isAvailable("dvipost");
4027 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4028 LaTeXPackages::isAvailable("xcolor");
4029 // No need to test for luatex, since luatex comes in
4030 // two flavours (dvi and pdf), like latex, and those
4031 // are detected by pdflatex.
4032 if (pdflatex || xetex) {
4034 preamble.registerAutomaticallyLoadedPackage("ulem");
4035 preamble.registerAutomaticallyLoadedPackage("xcolor");
4036 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4040 preamble.registerAutomaticallyLoadedPackage("dvipost");
4041 } else if (xcolorulem) {
4042 preamble.registerAutomaticallyLoadedPackage("ulem");
4043 preamble.registerAutomaticallyLoadedPackage("xcolor");
4049 if (t.cs() == "textipa") {
4050 context.check_layout(os);
4051 begin_inset(os, "IPA\n");
4052 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4053 context.merging_hyphens_allowed = false;
4054 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4055 context.merging_hyphens_allowed = merging_hyphens_allowed;
4057 preamble.registerAutomaticallyLoadedPackage("tipa");
4058 preamble.registerAutomaticallyLoadedPackage("tipx");
4062 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4063 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4064 context.check_layout(os);
4068 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4069 begin_inset(os, "IPADeco " + type + "\n");
4070 os << "status open\n";
4071 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4077 if (t.cs() == "textvertline") {
4078 // FIXME: This is not correct, \textvertline is higher than |
4084 if (t.cs() == "tone" ) {
4085 context.check_layout(os);
4086 // register the tone package
4087 preamble.registerAutomaticallyLoadedPackage("tone");
4088 string content = trimSpaceAndEol(p.verbatim_item());
4089 string command = t.asInput() + "{" + content + "}";
4090 // some tones can be detected by unicodesymbols, some need special code
4091 if (is_known(content, known_tones)) {
4092 os << "\\IPAChar " << command << "\n";
4095 // try to see whether the string is in unicodesymbols
4099 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4100 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4101 termination, rem, &req);
4105 output_ert_inset(os, to_utf8(rem), context);
4106 for (set<string>::const_iterator it = req.begin();
4107 it != req.end(); ++it)
4108 preamble.registerAutomaticallyLoadedPackage(*it);
4110 // we did not find a non-ert version
4111 output_ert_inset(os, command, context);
4115 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4116 t.cs() == "vphantom") {
4117 context.check_layout(os);
4118 if (t.cs() == "phantom")
4119 begin_inset(os, "Phantom Phantom\n");
4120 if (t.cs() == "hphantom")
4121 begin_inset(os, "Phantom HPhantom\n");
4122 if (t.cs() == "vphantom")
4123 begin_inset(os, "Phantom VPhantom\n");
4124 os << "status open\n";
4125 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4131 if (t.cs() == "href") {
4132 context.check_layout(os);
4133 string target = convert_literate_command_inset_arg(p.verbatim_item());
4134 string name = p.verbatim_item();
4135 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4136 bool const literal = !nm.first;
4137 name = literal ? subst(name, "\n", " ") : nm.second;
4138 string lit = literal ? "\"true\"" : "\"false\"";
4140 size_t i = target.find(':');
4141 if (i != string::npos) {
4142 type = target.substr(0, i + 1);
4143 if (type == "mailto:" || type == "file:")
4144 target = target.substr(i + 1);
4145 // handle the case that name is equal to target, except of "http(s)://"
4146 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4149 begin_command_inset(os, "href", "href");
4151 os << "name \"" << name << "\"\n";
4152 os << "target \"" << target << "\"\n";
4153 if (type == "mailto:" || type == "file:")
4154 os << "type \"" << type << "\"\n";
4155 os << "literal " << lit << "\n";
4157 skip_spaces_braces(p);
4161 if (t.cs() == "lyxline") {
4162 // swallow size argument (it is not used anyway)
4164 if (!context.atParagraphStart()) {
4165 // so our line is in the middle of a paragraph
4166 // we need to add a new line, lest this line
4167 // follow the other content on that line and
4168 // run off the side of the page
4169 // FIXME: This may create an empty paragraph,
4170 // but without that it would not be
4171 // possible to set noindent below.
4172 // Fortunately LaTeX does not care
4173 // about the empty paragraph.
4174 context.new_paragraph(os);
4176 if (preamble.indentParagraphs()) {
4177 // we need to unindent, lest the line be too long
4178 context.add_par_extra_stuff("\\noindent\n");
4180 context.check_layout(os);
4181 begin_command_inset(os, "line", "rule");
4182 os << "offset \"0.5ex\"\n"
4183 "width \"100line%\"\n"
4189 if (t.cs() == "rule") {
4190 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4191 string const width = p.getArg('{', '}');
4192 string const thickness = p.getArg('{', '}');
4193 context.check_layout(os);
4194 begin_command_inset(os, "line", "rule");
4195 if (!offset.empty())
4196 os << "offset \"" << translate_len(offset) << "\"\n";
4197 os << "width \"" << translate_len(width) << "\"\n"
4198 "height \"" << translate_len(thickness) << "\"\n";
4203 // Handle refstyle first in order to to catch \eqref, because this
4204 // can also occur without refstyle. Only recognize these commands if
4205 // refstyle.sty was found in the preamble (otherwise \eqref
4206 // and user defined ref commands could be misdetected).
4207 // We uncapitalize the input in order to catch capitalized commands
4209 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4210 && preamble.refstyle()) {
4211 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4212 string plural = "false";
4213 // Catch the plural option [s]
4215 string const opt = p.getOpt();
4219 // LyX does not yet support other optional arguments of ref commands
4220 output_ert_inset(os, t.asInput() + opt + "{" +
4221 p.verbatim_item() + '}', context);
4225 context.check_layout(os);
4226 begin_command_inset(os, "ref", "formatted");
4227 os << "reference \"";
4228 os << known_refstyle_prefixes[where - known_refstyle_commands]
4230 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4232 os << "plural \"" << plural << "\"\n";
4233 os << "caps \"" << cap << "\"\n";
4234 os << "noprefix \"false\"\n";
4236 preamble.registerAutomaticallyLoadedPackage("refstyle");
4240 // if refstyle is used, we must not convert \prettyref to a
4241 // formatted reference, since that would result in a refstyle command.
4242 if ((where = is_known(t.cs(), known_ref_commands)) &&
4243 (t.cs() != "prettyref" || !preamble.refstyle())) {
4244 string const opt = p.getOpt();
4246 context.check_layout(os);
4247 begin_command_inset(os, "ref",
4248 known_coded_ref_commands[where - known_ref_commands]);
4249 os << "reference \""
4250 << convert_literate_command_inset_arg(p.verbatim_item())
4252 os << "plural \"false\"\n";
4253 os << "caps \"false\"\n";
4254 os << "noprefix \"false\"\n";
4256 if (t.cs() == "vref" || t.cs() == "vpageref")
4257 preamble.registerAutomaticallyLoadedPackage("varioref");
4258 else if (t.cs() == "prettyref")
4259 preamble.registerAutomaticallyLoadedPackage("prettyref");
4261 // LyX does not yet support optional arguments of ref commands
4262 output_ert_inset(os, t.asInput() + opt + "{" +
4263 p.verbatim_item() + '}', context);
4269 is_known(t.cs(), known_natbib_commands) &&
4270 ((t.cs() != "citefullauthor" &&
4271 t.cs() != "citeyear" &&
4272 t.cs() != "citeyearpar") ||
4273 p.next_token().asInput() != "*")) {
4274 context.check_layout(os);
4275 string command = t.cs();
4276 if (p.next_token().asInput() == "*") {
4280 if (command == "citefullauthor")
4281 // alternative name for "\\citeauthor*"
4282 command = "citeauthor*";
4284 // text before the citation
4286 // text after the citation
4288 get_cite_arguments(p, true, before, after);
4290 if (command == "cite") {
4291 // \cite without optional argument means
4292 // \citet, \cite with at least one optional
4293 // argument means \citep.
4294 if (before.empty() && after.empty())
4299 if (before.empty() && after == "[]")
4300 // avoid \citet[]{a}
4302 else if (before == "[]" && after == "[]") {
4303 // avoid \citet[][]{a}
4307 bool literal = false;
4308 pair<bool, string> aft;
4309 pair<bool, string> bef;
4310 // remove the brackets around after and before
4311 if (!after.empty()) {
4313 after.erase(after.length() - 1, 1);
4314 aft = convert_latexed_command_inset_arg(after);
4315 literal = !aft.first;
4316 after = literal ? subst(after, "\n", " ") : aft.second;
4318 if (!before.empty()) {
4320 before.erase(before.length() - 1, 1);
4321 bef = convert_latexed_command_inset_arg(before);
4322 literal |= !bef.first;
4323 before = literal ? subst(before, "\n", " ") : bef.second;
4324 if (literal && !after.empty())
4325 after = subst(after, "\n", " ");
4327 string lit = literal ? "\"true\"" : "\"false\"";
4328 begin_command_inset(os, "citation", command);
4329 os << "after " << '"' << after << '"' << "\n";
4330 os << "before " << '"' << before << '"' << "\n";
4332 << convert_literate_command_inset_arg(p.verbatim_item())
4334 << "literal " << lit << "\n";
4336 // Need to set the cite engine if natbib is loaded by
4337 // the document class directly
4338 if (preamble.citeEngine() == "basic")
4339 preamble.citeEngine("natbib");
4344 && is_known(t.cs(), known_biblatex_commands)
4345 && ((t.cs() == "cite"
4346 || t.cs() == "citeauthor"
4347 || t.cs() == "Citeauthor"
4348 || t.cs() == "parencite"
4349 || t.cs() == "citetitle")
4350 || p.next_token().asInput() != "*"))
4351 || (use_biblatex_natbib
4352 && (is_known(t.cs(), known_biblatex_commands)
4353 || is_known(t.cs(), known_natbib_commands))
4354 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4355 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4356 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4357 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4358 || t.cs() == "parencite" || t.cs() == "citetitle")
4359 || p.next_token().asInput() != "*"))){
4360 context.check_layout(os);
4361 string command = t.cs();
4362 if (p.next_token().asInput() == "*") {
4367 bool const qualified = suffixIs(command, "s");
4369 command = rtrim(command, "s");
4371 // text before the citation
4373 // text after the citation
4375 get_cite_arguments(p, true, before, after, qualified);
4377 // These use natbib cmd names in LyX
4378 // for inter-citeengine compativility
4379 if (command == "citeyear")
4380 command = "citebyear";
4381 else if (command == "cite*")
4382 command = "citeyear";
4383 else if (command == "textcite")
4385 else if (command == "Textcite")
4387 else if (command == "parencite")
4389 else if (command == "Parencite")
4391 else if (command == "parencite*")
4392 command = "citeyearpar";
4393 else if (command == "smartcite")
4394 command = "footcite";
4395 else if (command == "Smartcite")
4396 command = "Footcite";
4398 string const emptyarg = qualified ? "()" : "[]";
4399 if (before.empty() && after == emptyarg)
4402 else if (before == emptyarg && after == emptyarg) {
4403 // avoid \cite[][]{a}
4407 bool literal = false;
4408 pair<bool, string> aft;
4409 pair<bool, string> bef;
4410 // remove the brackets around after and before
4411 if (!after.empty()) {
4413 after.erase(after.length() - 1, 1);
4414 aft = convert_latexed_command_inset_arg(after);
4415 literal = !aft.first;
4416 after = literal ? subst(after, "\n", " ") : aft.second;
4418 if (!before.empty()) {
4420 before.erase(before.length() - 1, 1);
4421 bef = convert_latexed_command_inset_arg(before);
4422 literal |= !bef.first;
4423 before = literal ? subst(before, "\n", " ") : bef.second;
4425 string keys, pretextlist, posttextlist;
4427 map<string, string> pres, posts, preslit, postslit;
4428 vector<string> lkeys;
4429 // text before the citation
4430 string lbefore, lbeforelit;
4431 // text after the citation
4432 string lafter, lafterlit;
4434 pair<bool, string> laft, lbef;
4436 get_cite_arguments(p, true, lbefore, lafter);
4437 // remove the brackets around after and before
4438 if (!lafter.empty()) {
4440 lafter.erase(lafter.length() - 1, 1);
4441 laft = convert_latexed_command_inset_arg(lafter);
4442 literal |= !laft.first;
4443 lafter = laft.second;
4444 lafterlit = subst(lbefore, "\n", " ");
4446 if (!lbefore.empty()) {
4447 lbefore.erase(0, 1);
4448 lbefore.erase(lbefore.length() - 1, 1);
4449 lbef = convert_latexed_command_inset_arg(lbefore);
4450 literal |= !lbef.first;
4451 lbefore = lbef.second;
4452 lbeforelit = subst(lbefore, "\n", " ");
4454 if (lbefore.empty() && lafter == "[]") {
4459 else if (lbefore == "[]" && lafter == "[]") {
4460 // avoid \cite[][]{a}
4466 lkey = p.getArg('{', '}');
4469 if (!lbefore.empty()) {
4470 pres.insert(make_pair(lkey, lbefore));
4471 preslit.insert(make_pair(lkey, lbeforelit));
4473 if (!lafter.empty()) {
4474 posts.insert(make_pair(lkey, lafter));
4475 postslit.insert(make_pair(lkey, lafterlit));
4477 lkeys.push_back(lkey);
4479 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4484 for (auto const & ptl : pres) {
4485 if (!pretextlist.empty())
4486 pretextlist += '\t';
4487 pretextlist += ptl.first + " " + ptl.second;
4489 for (auto const & potl : posts) {
4490 if (!posttextlist.empty())
4491 posttextlist += '\t';
4492 posttextlist += potl.first + " " + potl.second;
4495 keys = convert_literate_command_inset_arg(p.verbatim_item());
4498 after = subst(after, "\n", " ");
4499 if (!before.empty())
4500 before = subst(after, "\n", " ");
4502 string lit = literal ? "\"true\"" : "\"false\"";
4503 begin_command_inset(os, "citation", command);
4504 os << "after " << '"' << after << '"' << "\n";
4505 os << "before " << '"' << before << '"' << "\n";
4509 if (!pretextlist.empty())
4510 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4511 if (!posttextlist.empty())
4512 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4513 os << "literal " << lit << "\n";
4515 // Need to set the cite engine if biblatex is loaded by
4516 // the document class directly
4517 if (preamble.citeEngine() == "basic")
4518 use_biblatex_natbib ?
4519 preamble.citeEngine("biblatex-natbib")
4520 : preamble.citeEngine("biblatex");
4525 is_known(t.cs(), known_jurabib_commands) &&
4526 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4527 context.check_layout(os);
4528 string command = t.cs();
4529 if (p.next_token().asInput() == "*") {
4533 char argumentOrder = '\0';
4534 vector<string> const options =
4535 preamble.getPackageOptions("jurabib");
4536 if (find(options.begin(), options.end(),
4537 "natbiborder") != options.end())
4538 argumentOrder = 'n';
4539 else if (find(options.begin(), options.end(),
4540 "jurabiborder") != options.end())
4541 argumentOrder = 'j';
4543 // text before the citation
4545 // text after the citation
4547 get_cite_arguments(p, argumentOrder != 'j', before, after);
4549 string const citation = p.verbatim_item();
4550 if (!before.empty() && argumentOrder == '\0') {
4551 cerr << "Warning: Assuming argument order "
4552 "of jurabib version 0.6 for\n'"
4553 << command << before << after << '{'
4554 << citation << "}'.\n"
4555 "Add 'jurabiborder' to the jurabib "
4556 "package options if you used an\n"
4557 "earlier jurabib version." << endl;
4559 bool literal = false;
4560 pair<bool, string> aft;
4561 pair<bool, string> bef;
4562 // remove the brackets around after and before
4563 if (!after.empty()) {
4565 after.erase(after.length() - 1, 1);
4566 aft = convert_latexed_command_inset_arg(after);
4567 literal = !aft.first;
4568 after = literal ? subst(after, "\n", " ") : aft.second;
4570 if (!before.empty()) {
4572 before.erase(before.length() - 1, 1);
4573 bef = convert_latexed_command_inset_arg(before);
4574 literal |= !bef.first;
4575 before = literal ? subst(before, "\n", " ") : bef.second;
4576 if (literal && !after.empty())
4577 after = subst(after, "\n", " ");
4579 string lit = literal ? "\"true\"" : "\"false\"";
4580 begin_command_inset(os, "citation", command);
4581 os << "after " << '"' << after << "\"\n"
4582 << "before " << '"' << before << "\"\n"
4583 << "key " << '"' << citation << "\"\n"
4584 << "literal " << lit << "\n";
4586 // Need to set the cite engine if jurabib is loaded by
4587 // the document class directly
4588 if (preamble.citeEngine() == "basic")
4589 preamble.citeEngine("jurabib");
4593 if (t.cs() == "cite"
4594 || t.cs() == "nocite") {
4595 context.check_layout(os);
4596 string after = p.getArg('[', ']');
4597 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4598 bool const literal = !aft.first;
4599 after = literal ? subst(after, "\n", " ") : aft.second;
4600 string lit = literal ? "\"true\"" : "\"false\"";
4601 string key = convert_literate_command_inset_arg(p.verbatim_item());
4602 // store the case that it is "\nocite{*}" to use it later for
4605 begin_command_inset(os, "citation", t.cs());
4606 os << "after " << '"' << after << "\"\n"
4607 << "key " << '"' << key << "\"\n"
4608 << "literal " << lit << "\n";
4610 } else if (t.cs() == "nocite")
4615 if (t.cs() == "index" ||
4616 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4617 context.check_layout(os);
4618 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4619 p.getArg('[', ']') : "";
4620 string const kind = arg.empty() ? "idx" : arg;
4621 begin_inset(os, "Index ");
4622 os << kind << "\nstatus collapsed\n";
4623 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4626 preamble.registerAutomaticallyLoadedPackage("splitidx");
4630 if (t.cs() == "nomenclature") {
4631 context.check_layout(os);
4632 begin_command_inset(os, "nomenclature", "nomenclature");
4633 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4634 if (!prefix.empty())
4635 os << "prefix " << '"' << prefix << '"' << "\n";
4636 string symbol = p.verbatim_item();
4637 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4638 bool literal = !sym.first;
4639 string description = p.verbatim_item();
4640 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4641 literal |= !desc.first;
4643 symbol = subst(symbol, "\n", " ");
4644 description = subst(description, "\n", " ");
4646 symbol = sym.second;
4647 description = desc.second;
4649 string lit = literal ? "\"true\"" : "\"false\"";
4650 os << "symbol " << '"' << symbol;
4651 os << "\"\ndescription \""
4652 << description << "\"\n"
4653 << "literal " << lit << "\n";
4655 preamble.registerAutomaticallyLoadedPackage("nomencl");
4659 if (t.cs() == "label") {
4660 context.check_layout(os);
4661 begin_command_inset(os, "label", "label");
4663 << convert_literate_command_inset_arg(p.verbatim_item())
4669 if (t.cs() == "lyxmintcaption") {
4670 string const pos = p.getArg('[', ']');
4672 string const caption =
4673 parse_text_snippet(p, FLAG_ITEM, false,
4675 minted_nonfloat_caption = "[t]" + caption;
4677 // We already got the caption at the bottom,
4678 // so simply skip it.
4679 parse_text_snippet(p, FLAG_ITEM, false, context);
4681 eat_whitespace(p, os, context, true);
4685 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4686 context.check_layout(os);
4687 string commandname = t.cs();
4689 if (p.next_token().asInput() == "*") {
4694 begin_command_inset(os, "index_print", commandname);
4695 string const indexname = p.getArg('[', ']');
4697 if (indexname.empty())
4698 os << "type \"idx\"\n";
4700 os << "type \"" << indexname << "\"\n";
4701 os << "literal \"true\"\n";
4704 skip_spaces_braces(p);
4705 preamble.registerAutomaticallyLoadedPackage("makeidx");
4706 if (preamble.use_indices() == "true")
4707 preamble.registerAutomaticallyLoadedPackage("splitidx");
4711 if (t.cs() == "printnomenclature") {
4713 string width_type = "";
4714 context.check_layout(os);
4715 begin_command_inset(os, "nomencl_print", "printnomenclature");
4716 // case of a custom width
4718 width = p.getArg('[', ']');
4719 width = translate_len(width);
4720 width_type = "custom";
4722 // case of no custom width
4723 // the case of no custom width but the width set
4724 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4725 // because the user could have set anything, not only the width
4726 // of the longest label (which would be width_type = "auto")
4727 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4728 if (label.empty() && width_type.empty())
4729 width_type = "none";
4730 os << "set_width \"" << width_type << "\"\n";
4731 if (width_type == "custom")
4732 os << "width \"" << width << '\"';
4734 skip_spaces_braces(p);
4735 preamble.registerAutomaticallyLoadedPackage("nomencl");
4739 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4740 context.check_layout(os);
4741 begin_inset(os, "script ");
4742 os << t.cs().substr(4) << '\n';
4743 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4744 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4746 if (t.cs() == "textsubscript")
4747 preamble.registerAutomaticallyLoadedPackage("subscript");
4751 if ((where = is_known(t.cs(), known_quotes))) {
4752 context.check_layout(os);
4753 begin_inset(os, "Quotes ");
4754 string quotetype = known_coded_quotes[where - known_quotes];
4755 // try to make a smart guess about the side
4756 Token const prev = p.prev_token();
4757 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4758 && prev.character() != '\n' && prev.character() != '~');
4759 quotetype = guessQuoteStyle(quotetype, opening);
4762 // LyX adds {} after the quote, so we have to eat
4763 // spaces here if there are any before a possible
4765 eat_whitespace(p, os, context, false);
4770 if ((where = is_known(t.cs(), known_sizes)) &&
4771 context.new_layout_allowed) {
4772 context.check_layout(os);
4773 TeXFont const oldFont = context.font;
4774 context.font.size = known_coded_sizes[where - known_sizes];
4775 output_font_change(os, oldFont, context.font);
4776 eat_whitespace(p, os, context, false);
4780 if ((where = is_known(t.cs(), known_font_families)) &&
4781 context.new_layout_allowed) {
4782 context.check_layout(os);
4783 TeXFont const oldFont = context.font;
4784 context.font.family =
4785 known_coded_font_families[where - known_font_families];
4786 output_font_change(os, oldFont, context.font);
4787 eat_whitespace(p, os, context, false);
4791 if ((where = is_known(t.cs(), known_font_series)) &&
4792 context.new_layout_allowed) {
4793 context.check_layout(os);
4794 TeXFont const oldFont = context.font;
4795 context.font.series =
4796 known_coded_font_series[where - known_font_series];
4797 output_font_change(os, oldFont, context.font);
4798 eat_whitespace(p, os, context, false);
4802 if ((where = is_known(t.cs(), known_font_shapes)) &&
4803 context.new_layout_allowed) {
4804 context.check_layout(os);
4805 TeXFont const oldFont = context.font;
4806 context.font.shape =
4807 known_coded_font_shapes[where - known_font_shapes];
4808 output_font_change(os, oldFont, context.font);
4809 eat_whitespace(p, os, context, false);
4812 if ((where = is_known(t.cs(), known_old_font_families)) &&
4813 context.new_layout_allowed) {
4814 context.check_layout(os);
4815 TeXFont const oldFont = context.font;
4816 context.font.init();
4817 context.font.size = oldFont.size;
4818 context.font.family =
4819 known_coded_font_families[where - known_old_font_families];
4820 output_font_change(os, oldFont, context.font);
4821 eat_whitespace(p, os, context, false);
4825 if ((where = is_known(t.cs(), known_old_font_series)) &&
4826 context.new_layout_allowed) {
4827 context.check_layout(os);
4828 TeXFont const oldFont = context.font;
4829 context.font.init();
4830 context.font.size = oldFont.size;
4831 context.font.series =
4832 known_coded_font_series[where - known_old_font_series];
4833 output_font_change(os, oldFont, context.font);
4834 eat_whitespace(p, os, context, false);
4838 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4839 context.new_layout_allowed) {
4840 context.check_layout(os);
4841 TeXFont const oldFont = context.font;
4842 context.font.init();
4843 context.font.size = oldFont.size;
4844 context.font.shape =
4845 known_coded_font_shapes[where - known_old_font_shapes];
4846 output_font_change(os, oldFont, context.font);
4847 eat_whitespace(p, os, context, false);
4851 if (t.cs() == "selectlanguage") {
4852 context.check_layout(os);
4853 // save the language for the case that a
4854 // \foreignlanguage is used
4855 context.font.language = babel2lyx(p.verbatim_item());
4856 os << "\n\\lang " << context.font.language << "\n";
4860 if (t.cs() == "foreignlanguage") {
4861 string const lang = babel2lyx(p.verbatim_item());
4862 parse_text_attributes(p, os, FLAG_ITEM, outer,
4864 context.font.language, lang);
4868 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4869 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4870 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4872 // We have to output the whole command if it has an option
4873 // because LyX doesn't support this yet, see bug #8214,
4874 // only if there is a single option specifying a variant, we can handle it.
4876 string langopts = p.getOpt();
4877 // check if the option contains a variant, if yes, extract it
4878 string::size_type pos_var = langopts.find("variant");
4879 string::size_type i = langopts.find(',');
4880 string::size_type k = langopts.find('=', pos_var);
4881 if (pos_var != string::npos && i == string::npos) {
4883 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4884 lang = preamble.polyglossia2lyx(variant);
4885 parse_text_attributes(p, os, FLAG_ITEM, outer,
4887 context.font.language, lang);
4889 output_ert_inset(os, t.asInput() + langopts, context);
4891 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4892 parse_text_attributes(p, os, FLAG_ITEM, outer,
4894 context.font.language, lang);
4899 if (t.cs() == "inputencoding") {
4900 // nothing to write here
4901 string const enc = subst(p.verbatim_item(), "\n", " ");
4902 p.setEncoding(enc, Encoding::inputenc);
4906 if (is_known(t.cs(), known_special_chars) ||
4907 (t.cs() == "protect" &&
4908 p.next_token().cat() == catEscape &&
4909 is_known(p.next_token().cs(), known_special_protect_chars))) {
4910 // LyX sometimes puts a \protect in front, so we have to ignore it
4912 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4913 known_special_chars);
4914 context.check_layout(os);
4915 os << known_coded_special_chars[where - known_special_chars];
4916 skip_spaces_braces(p);
4920 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4921 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4922 p.next_next_token().asInput() == "-") ||
4923 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4924 // LyX sometimes puts a \protect in front, so we have to ignore it
4925 if (t.cs() == "protect")
4927 context.check_layout(os);
4928 if (t.cs() == "nobreakdash")
4929 os << "\\SpecialChar nobreakdash\n";
4931 os << "\\SpecialChar endofsentence\n";
4936 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4937 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4938 || t.cs() == "%" || t.cs() == "-") {
4939 context.check_layout(os);
4941 os << "\\SpecialChar softhyphen\n";
4947 if (t.cs() == "char") {
4948 context.check_layout(os);
4949 if (p.next_token().character() == '`') {
4951 if (p.next_token().cs() == "\"") {
4956 output_ert_inset(os, "\\char`", context);
4959 output_ert_inset(os, "\\char", context);
4964 if (t.cs() == "verb") {
4965 context.check_layout(os);
4966 // set catcodes to verbatim early, just in case.
4967 p.setCatcodes(VERBATIM_CATCODES);
4968 string delim = p.get_token().asInput();
4969 Parser::Arg arg = p.verbatimStuff(delim);
4971 output_ert_inset(os, "\\verb" + delim
4972 + arg.second + delim, context);
4974 cerr << "invalid \\verb command. Skipping" << endl;
4978 // Problem: \= creates a tabstop inside the tabbing environment
4979 // and else an accent. In the latter case we really would want
4980 // \={o} instead of \= o.
4981 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4982 output_ert_inset(os, t.asInput(), context);
4986 if (t.cs() == "\\") {
4987 context.check_layout(os);
4989 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4990 else if (p.next_token().asInput() == "*") {
4992 // getOpt() eats the following space if there
4993 // is no optional argument, but that is OK
4994 // here since it has no effect in the output.
4995 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4998 begin_inset(os, "Newline newline");
5004 if (t.cs() == "newline" ||
5005 (t.cs() == "linebreak" && !p.hasOpt())) {
5006 context.check_layout(os);
5007 begin_inset(os, "Newline ");
5010 skip_spaces_braces(p);
5014 if (t.cs() == "input" || t.cs() == "include"
5015 || t.cs() == "verbatiminput"
5016 || t.cs() == "lstinputlisting"
5017 || t.cs() == "inputminted") {
5018 string name = t.cs();
5019 if (name == "verbatiminput"
5020 && p.next_token().asInput() == "*")
5021 name += p.get_token().asInput();
5022 context.check_layout(os);
5024 bool literal = false;
5025 if (name == "lstinputlisting" && p.hasOpt()) {
5026 lstparams = p.getArg('[', ']');
5027 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5028 literal = !oa.first;
5030 lstparams = subst(lstparams, "\n", " ");
5032 lstparams = oa.second;
5033 } else if (name == "inputminted") {
5034 name = "lstinputlisting";
5035 string const lang = p.getArg('{', '}');
5036 if (lang != "tex") {
5037 string cmd = "\\inputminted{" + lang + "}{";
5038 cmd += p.getArg('{', '}') + "}";
5039 output_ert_inset(os, cmd, context);
5042 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5043 minted_nonfloat_caption.erase(0,3);
5044 // extract label and caption from the already produced LyX code
5045 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5046 string const caption = nfc.front();
5048 vector<string>::iterator it =
5049 find(nfc.begin(), nfc.end(), "LatexCommand label");
5050 if (it != nfc.end()) {
5052 if (it != nfc.end())
5054 label = support::split(label, '"');
5057 minted_nonfloat_caption.clear();
5058 lstparams = "caption=" + caption;
5060 lstparams += ",label=" + label;
5061 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5062 literal = !oa.first;
5064 lstparams = subst(lstparams, "\n", " ");
5066 lstparams = oa.second;
5069 string lit = literal ? "\"true\"" : "\"false\"";
5070 string filename(normalize_filename(p.getArg('{', '}')));
5071 string const path = getMasterFilePath(true);
5072 // We want to preserve relative / absolute filenames,
5073 // therefore path is only used for testing
5074 if ((t.cs() == "include" || t.cs() == "input") &&
5075 !makeAbsPath(filename, path).exists()) {
5076 // The file extension is probably missing.
5077 // Now try to find it out.
5078 string const tex_name =
5079 find_file(filename, path,
5080 known_tex_extensions);
5081 if (!tex_name.empty())
5082 filename = tex_name;
5084 bool external = false;
5086 if (makeAbsPath(filename, path).exists()) {
5087 string const abstexname =
5088 makeAbsPath(filename, path).absFileName();
5089 string const absfigname =
5090 changeExtension(abstexname, ".fig");
5091 fix_child_filename(filename);
5092 string const lyxname = changeExtension(filename,
5093 roundtripMode() ? ".lyx.lyx" : ".lyx");
5094 string const abslyxname = makeAbsPath(
5095 lyxname, getParentFilePath(false)).absFileName();
5097 if (!skipChildren())
5098 external = FileName(absfigname).exists();
5099 if (t.cs() == "input" && !skipChildren()) {
5100 string const ext = getExtension(abstexname);
5102 // Combined PS/LaTeX:
5103 // x.eps, x.pstex_t (old xfig)
5104 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5105 FileName const absepsname(
5106 changeExtension(abstexname, ".eps"));
5107 FileName const abspstexname(
5108 changeExtension(abstexname, ".pstex"));
5109 bool const xfigeps =
5110 (absepsname.exists() ||
5111 abspstexname.exists()) &&
5114 // Combined PDF/LaTeX:
5115 // x.pdf, x.pdftex_t (old xfig)
5116 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5117 FileName const abspdfname(
5118 changeExtension(abstexname, ".pdf"));
5119 bool const xfigpdf =
5120 abspdfname.exists() &&
5121 (ext == "pdftex_t" || ext == "pdf_t");
5125 // Combined PS/PDF/LaTeX:
5126 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5127 string const absbase2(
5128 removeExtension(abstexname) + "_pspdftex");
5129 FileName const abseps2name(
5130 addExtension(absbase2, ".eps"));
5131 FileName const abspdf2name(
5132 addExtension(absbase2, ".pdf"));
5133 bool const xfigboth =
5134 abspdf2name.exists() &&
5135 abseps2name.exists() && ext == "pspdftex";
5137 xfig = xfigpdf || xfigeps || xfigboth;
5138 external = external && xfig;
5141 outname = changeExtension(filename, ".fig");
5142 FileName abssrc(changeExtension(abstexname, ".fig"));
5143 copy_file(abssrc, outname);
5145 // Don't try to convert, the result
5146 // would be full of ERT.
5148 FileName abssrc(abstexname);
5149 copy_file(abssrc, outname);
5150 } else if (t.cs() != "verbatiminput" &&
5152 tex2lyx(abstexname, FileName(abslyxname),
5155 // no need to call copy_file
5156 // tex2lyx creates the file
5159 FileName abssrc(abstexname);
5160 copy_file(abssrc, outname);
5163 cerr << "Warning: Could not find included file '"
5164 << filename << "'." << endl;
5168 begin_inset(os, "External\n");
5169 os << "\ttemplate XFig\n"
5170 << "\tfilename " << outname << '\n';
5171 registerExternalTemplatePackages("XFig");
5173 begin_command_inset(os, "include", name);
5174 outname = subst(outname, "\"", "\\\"");
5175 os << "preview false\n"
5176 "filename \"" << outname << "\"\n";
5177 if (!lstparams.empty())
5178 os << "lstparams \"" << lstparams << "\"\n";
5179 os << "literal " << lit << "\n";
5180 if (t.cs() == "verbatiminput")
5181 preamble.registerAutomaticallyLoadedPackage("verbatim");
5187 if (t.cs() == "bibliographystyle") {
5188 // store new bibliographystyle
5189 bibliographystyle = p.verbatim_item();
5190 // If any other command than \bibliography, \addcontentsline
5191 // and \nocite{*} follows, we need to output the style
5192 // (because it might be used by that command).
5193 // Otherwise, it will automatically be output by LyX.
5196 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5197 if (t2.cat() == catBegin)
5199 if (t2.cat() != catEscape)
5201 if (t2.cs() == "nocite") {
5202 if (p.getArg('{', '}') == "*")
5204 } else if (t2.cs() == "bibliography")
5206 else if (t2.cs() == "phantomsection") {
5210 else if (t2.cs() == "addcontentsline") {
5211 // get the 3 arguments of \addcontentsline
5214 contentslineContent = p.getArg('{', '}');
5215 // if the last argument is not \refname we must output
5216 if (contentslineContent == "\\refname")
5223 output_ert_inset(os,
5224 "\\bibliographystyle{" + bibliographystyle + '}',
5230 if (t.cs() == "phantomsection") {
5231 // we only support this if it occurs between
5232 // \bibliographystyle and \bibliography
5233 if (bibliographystyle.empty())
5234 output_ert_inset(os, "\\phantomsection", context);
5238 if (t.cs() == "addcontentsline") {
5239 context.check_layout(os);
5240 // get the 3 arguments of \addcontentsline
5241 string const one = p.getArg('{', '}');
5242 string const two = p.getArg('{', '}');
5243 string const three = p.getArg('{', '}');
5244 // only if it is a \refname, we support if for the bibtex inset
5245 if (contentslineContent != "\\refname") {
5246 output_ert_inset(os,
5247 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5253 else if (t.cs() == "bibliography") {
5254 context.check_layout(os);
5256 begin_command_inset(os, "bibtex", "bibtex");
5257 if (!btprint.empty()) {
5258 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5259 // clear the string because the next BibTeX inset can be without the
5260 // \nocite{*} option
5263 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5264 // Do we have addcontentsline?
5265 if (contentslineContent == "\\refname") {
5266 BibOpts = "bibtotoc";
5267 // clear string because next BibTeX inset can be without addcontentsline
5268 contentslineContent.clear();
5270 // Do we have a bibliographystyle set?
5271 if (!bibliographystyle.empty()) {
5272 if (BibOpts.empty())
5273 BibOpts = normalize_filename(bibliographystyle);
5275 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5276 // clear it because each bibtex entry has its style
5277 // and we need an empty string to handle \phantomsection
5278 bibliographystyle.clear();
5280 os << "options " << '"' << BibOpts << '"' << "\n";
5281 if (p.getEncoding() != preamble.docencoding) {
5282 Encoding const * const enc = encodings.fromIconvName(
5283 p.getEncoding(), Encoding::inputenc, true);
5285 cerr << "Unknown bib encoding " << p.getEncoding()
5286 << ". Ignoring." << std::endl;
5288 os << "encoding " << '"' << enc->name() << '"' << "\n";
5294 if (t.cs() == "printbibliography") {
5295 context.check_layout(os);
5297 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5298 vector<string> opts = getVectorFromString(bbloptions);
5299 vector<string>::iterator it =
5300 find(opts.begin(), opts.end(), "heading=bibintoc");
5301 if (it != opts.end()) {
5303 BibOpts = "bibtotoc";
5305 bbloptions = getStringFromVector(opts);
5306 begin_command_inset(os, "bibtex", "bibtex");
5307 if (!btprint.empty()) {
5308 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5309 // clear the string because the next BibTeX inset can be without the
5310 // \nocite{*} option
5314 for (auto const & bf : preamble.biblatex_bibliographies) {
5315 if (!bibfiles.empty())
5317 bibfiles += normalize_filename(bf);
5319 if (!bibfiles.empty())
5320 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5321 // Do we have addcontentsline?
5322 if (contentslineContent == "\\refname") {
5323 BibOpts = "bibtotoc";
5324 // clear string because next BibTeX inset can be without addcontentsline
5325 contentslineContent.clear();
5327 os << "options " << '"' << BibOpts << '"' << "\n";
5328 if (!bbloptions.empty())
5329 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5330 if (!preamble.bibencoding.empty()) {
5331 Encoding const * const enc = encodings.fromLaTeXName(
5332 preamble.bibencoding, Encoding::inputenc, true);
5334 cerr << "Unknown bib encoding " << preamble.bibencoding
5335 << ". Ignoring." << std::endl;
5337 os << "encoding " << '"' << enc->name() << '"' << "\n";
5340 need_commentbib = false;
5344 if (t.cs() == "bibbysection") {
5345 context.check_layout(os);
5347 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5348 vector<string> opts = getVectorFromString(bbloptions);
5349 vector<string>::iterator it =
5350 find(opts.begin(), opts.end(), "heading=bibintoc");
5351 if (it != opts.end()) {
5353 BibOpts = "bibtotoc";
5355 bbloptions = getStringFromVector(opts);
5356 begin_command_inset(os, "bibtex", "bibtex");
5357 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5359 for (auto const & bf : preamble.biblatex_bibliographies) {
5360 if (!bibfiles.empty())
5362 bibfiles += normalize_filename(bf);
5364 if (!bibfiles.empty())
5365 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5366 os << "options " << '"' << BibOpts << '"' << "\n";
5367 if (!bbloptions.empty())
5368 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5370 need_commentbib = false;
5374 if (t.cs() == "parbox") {
5375 // Test whether this is an outer box of a shaded box
5377 // swallow arguments
5378 while (p.hasOpt()) {
5380 p.skip_spaces(true);
5383 p.skip_spaces(true);
5385 if (p.next_token().cat() == catBegin)
5387 p.skip_spaces(true);
5388 Token to = p.get_token();
5389 bool shaded = false;
5390 if (to.asInput() == "\\begin") {
5391 p.skip_spaces(true);
5392 if (p.getArg('{', '}') == "shaded")
5397 parse_outer_box(p, os, FLAG_ITEM, outer,
5398 context, "parbox", "shaded");
5400 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5401 "", "", t.cs(), "", "");
5405 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5406 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5407 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5408 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5412 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5413 string backgroundcolor;
5414 preamble.registerAutomaticallyLoadedPackage("xcolor");
5415 if (t.cs() == "fcolorbox") {
5416 string const framecolor = p.getArg('{', '}');
5417 backgroundcolor = p.getArg('{', '}');
5418 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5420 backgroundcolor = p.getArg('{', '}');
5421 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5426 // FIXME: due to the compiler limit of "if" nestings
5427 // the code for the alignment was put here
5428 // put them in their own if if this is fixed
5429 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5430 || t.cs() == "shadowsize"
5431 || t.cs() == "raggedleft" || t.cs() == "centering"
5432 || t.cs() == "raggedright") {
5433 if (t.cs() == "fboxrule")
5435 if (t.cs() == "fboxsep")
5437 if (t.cs() == "shadowsize")
5439 if (t.cs() != "raggedleft" && t.cs() != "centering"
5440 && t.cs() != "raggedright") {
5441 p.skip_spaces(true);
5442 while (p.good() && p.next_token().cat() != catSpace
5443 && p.next_token().cat() != catNewline
5444 && p.next_token().cat() != catEscape) {
5445 if (t.cs() == "fboxrule")
5446 fboxrule = fboxrule + p.get_token().asInput();
5447 if (t.cs() == "fboxsep")
5448 fboxsep = fboxsep + p.get_token().asInput();
5449 if (t.cs() == "shadowsize")
5450 shadow_size = shadow_size + p.get_token().asInput();
5453 output_ert_inset(os, t.asInput(), context);
5458 //\framebox() is part of the picture environment and different from \framebox{}
5459 //\framebox{} will be parsed by parse_outer_box
5460 if (t.cs() == "framebox") {
5461 if (p.next_token().character() == '(') {
5462 //the syntax is: \framebox(x,y)[position]{content}
5463 string arg = t.asInput();
5464 arg += p.getFullParentheseArg();
5465 arg += p.getFullOpt();
5466 eat_whitespace(p, os, context, false);
5467 output_ert_inset(os, arg + '{', context);
5468 parse_text(p, os, FLAG_ITEM, outer, context);
5469 output_ert_inset(os, "}", context);
5471 //the syntax is: \framebox[width][position]{content}
5472 string special = p.getFullOpt();
5473 special += p.getOpt();
5474 parse_outer_box(p, os, FLAG_ITEM, outer,
5475 context, t.cs(), special);
5480 //\makebox() is part of the picture environment and different from \makebox{}
5481 //\makebox{} will be parsed by parse_box
5482 if (t.cs() == "makebox") {
5483 if (p.next_token().character() == '(') {
5484 //the syntax is: \makebox(x,y)[position]{content}
5485 string arg = t.asInput();
5486 arg += p.getFullParentheseArg();
5487 arg += p.getFullOpt();
5488 eat_whitespace(p, os, context, false);
5489 output_ert_inset(os, arg + '{', context);
5490 parse_text(p, os, FLAG_ITEM, outer, context);
5491 output_ert_inset(os, "}", context);
5493 //the syntax is: \makebox[width][position]{content}
5494 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5495 "", "", t.cs(), "", "");
5499 if (t.cs() == "smallskip" ||
5500 t.cs() == "medskip" ||
5501 t.cs() == "bigskip" ||
5502 t.cs() == "vfill") {
5503 context.check_layout(os);
5504 begin_inset(os, "VSpace ");
5507 skip_spaces_braces(p);
5511 if ((where = is_known(t.cs(), known_spaces))) {
5512 context.check_layout(os);
5513 begin_inset(os, "space ");
5514 os << '\\' << known_coded_spaces[where - known_spaces]
5517 // LaTeX swallows whitespace after all spaces except
5518 // "\\,". We have to do that here, too, because LyX
5519 // adds "{}" which would make the spaces significant.
5521 eat_whitespace(p, os, context, false);
5522 // LyX adds "{}" after all spaces except "\\ " and
5523 // "\\,", so we have to remove "{}".
5524 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5525 // remove the braces after "\\,", too.
5531 if (t.cs() == "newpage" ||
5532 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5533 t.cs() == "clearpage" ||
5534 t.cs() == "cleardoublepage") {
5535 context.check_layout(os);
5536 begin_inset(os, "Newpage ");
5539 skip_spaces_braces(p);
5543 if (t.cs() == "DeclareRobustCommand" ||
5544 t.cs() == "DeclareRobustCommandx" ||
5545 t.cs() == "newcommand" ||
5546 t.cs() == "newcommandx" ||
5547 t.cs() == "providecommand" ||
5548 t.cs() == "providecommandx" ||
5549 t.cs() == "renewcommand" ||
5550 t.cs() == "renewcommandx") {
5551 // DeclareRobustCommand, DeclareRobustCommandx,
5552 // providecommand and providecommandx could be handled
5553 // by parse_command(), but we need to call
5554 // add_known_command() here.
5555 string name = t.asInput();
5556 if (p.next_token().asInput() == "*") {
5557 // Starred form. Eat '*'
5561 string const command = p.verbatim_item();
5562 string const opt1 = p.getFullOpt();
5563 string const opt2 = p.getFullOpt();
5564 add_known_command(command, opt1, !opt2.empty());
5565 string const ert = name + '{' + command + '}' +
5567 '{' + p.verbatim_item() + '}';
5569 if (t.cs() == "DeclareRobustCommand" ||
5570 t.cs() == "DeclareRobustCommandx" ||
5571 t.cs() == "providecommand" ||
5572 t.cs() == "providecommandx" ||
5573 name[name.length()-1] == '*')
5574 output_ert_inset(os, ert, context);
5576 context.check_layout(os);
5577 begin_inset(os, "FormulaMacro");
5584 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5585 // let could be handled by parse_command(),
5586 // but we need to call add_known_command() here.
5587 string ert = t.asInput();
5590 if (p.next_token().cat() == catBegin) {
5591 name = p.verbatim_item();
5592 ert += '{' + name + '}';
5594 name = p.verbatim_item();
5599 if (p.next_token().cat() == catBegin) {
5600 command = p.verbatim_item();
5601 ert += '{' + command + '}';
5603 command = p.verbatim_item();
5606 // If command is known, make name known too, to parse
5607 // its arguments correctly. For this reason we also
5608 // have commands in syntax.default that are hardcoded.
5609 CommandMap::iterator it = known_commands.find(command);
5610 if (it != known_commands.end())
5611 known_commands[t.asInput()] = it->second;
5612 output_ert_inset(os, ert, context);
5616 if (t.cs() == "hspace" || t.cs() == "vspace") {
5619 string name = t.asInput();
5620 string const length = p.verbatim_item();
5623 bool valid = splitLatexLength(length, valstring, unit);
5624 bool known_hspace = false;
5625 bool known_vspace = false;
5626 bool known_unit = false;
5629 istringstream iss(valstring);
5632 if (t.cs()[0] == 'h') {
5633 if (unit == "\\fill") {
5638 known_hspace = true;
5641 if (unit == "\\smallskipamount") {
5643 known_vspace = true;
5644 } else if (unit == "\\medskipamount") {
5646 known_vspace = true;
5647 } else if (unit == "\\bigskipamount") {
5649 known_vspace = true;
5650 } else if (unit == "\\fill") {
5652 known_vspace = true;
5656 if (!known_hspace && !known_vspace) {
5657 switch (unitFromString(unit)) {
5673 //unitFromString(unit) fails for relative units like Length::PCW
5674 // therefore handle them separately
5675 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5676 || unit == "\\textwidth" || unit == "\\linewidth"
5677 || unit == "\\textheight" || unit == "\\paperheight"
5678 || unit == "\\baselineskip")
5686 // check for glue lengths
5687 bool is_gluelength = false;
5688 string gluelength = length;
5689 string::size_type i = length.find(" minus");
5690 if (i == string::npos) {
5691 i = length.find(" plus");
5692 if (i != string::npos)
5693 is_gluelength = true;
5695 is_gluelength = true;
5696 // if yes transform "9xx minus 8yy plus 7zz"
5698 if (is_gluelength) {
5699 i = gluelength.find(" minus");
5700 if (i != string::npos)
5701 gluelength.replace(i, 7, "-");
5702 i = gluelength.find(" plus");
5703 if (i != string::npos)
5704 gluelength.replace(i, 6, "+");
5707 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5708 // Literal horizontal length or known variable
5709 context.check_layout(os);
5710 begin_inset(os, "space ");
5718 if (known_unit && !known_hspace)
5719 os << "\n\\length " << translate_len(length);
5721 os << "\n\\length " << gluelength;
5723 } else if (known_unit || known_vspace || is_gluelength) {
5724 // Literal vertical length or known variable
5725 context.check_layout(os);
5726 begin_inset(os, "VSpace ");
5729 if (known_unit && !known_vspace)
5730 os << translate_len(length);
5737 // LyX can't handle other length variables in Inset VSpace/space
5742 output_ert_inset(os, name + '{' + unit + '}', context);
5743 else if (value == -1.0)
5744 output_ert_inset(os, name + "{-" + unit + '}', context);
5746 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5748 output_ert_inset(os, name + '{' + length + '}', context);
5753 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5754 // might be one or several options or a star.
5755 // The single '=' is meant here.
5756 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5760 context.check_layout(os);
5761 // store the latexparam here. This is eaten in parse_text_in_inset
5762 context.latexparam = newinsetlayout->latexparam();
5763 docstring name = newinsetlayout->name();
5764 bool const caption = name.find(from_ascii("Caption:")) == 0;
5766 // Already done for floating minted listings.
5767 if (minted_float.empty()) {
5768 begin_inset(os, "Caption ");
5769 os << to_utf8(name.substr(8)) << '\n';
5772 // FIXME: what do we do if the prefix is not Flex: ?
5773 if (prefixIs(name, from_ascii("Flex:")))
5775 begin_inset(os, "Flex ");
5776 os << to_utf8(name) << '\n'
5777 << "status collapsed\n";
5779 if (!minted_float.empty()) {
5780 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5781 } else if (newinsetlayout->isPassThru()) {
5782 // set catcodes to verbatim early, just in case.
5783 p.setCatcodes(VERBATIM_CATCODES);
5784 string delim = p.get_token().asInput();
5786 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5787 //FIXME: handle error condition
5788 string const arg = p.verbatimStuff("}").second;
5789 Context newcontext(true, context.textclass);
5790 if (newinsetlayout->forcePlainLayout())
5791 newcontext.layout = &context.textclass.plainLayout();
5792 output_ert(os, arg, newcontext);
5794 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5795 context.latexparam.clear();
5798 // Minted caption insets are not closed here because
5799 // we collect everything into the caption.
5800 if (minted_float.empty())
5805 // The single '=' is meant here.
5806 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5810 context.check_layout(os);
5811 docstring name = newinsetlayout->name();
5812 bool const caption = name.find(from_ascii("Caption:")) == 0;
5814 // Already done for floating minted listings.
5815 if (minted_float.empty()) {
5816 begin_inset(os, "Caption ");
5817 os << to_utf8(name.substr(8)) << '\n';
5820 // FIXME: what do we do if the prefix is not Flex: ?
5821 if (prefixIs(name, from_ascii("Flex:")))
5823 begin_inset(os, "Flex ");
5824 os << to_utf8(name) << '\n'
5825 << "status collapsed\n";
5827 if (!minted_float.empty()) {
5828 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5829 } else if (newinsetlayout->isPassThru()) {
5830 // set catcodes to verbatim early, just in case.
5831 p.setCatcodes(VERBATIM_CATCODES);
5832 string delim = p.get_token().asInput();
5834 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5835 //FIXME: handle error condition
5836 string const arg = p.verbatimStuff("}").second;
5837 Context newcontext(true, context.textclass);
5838 if (newinsetlayout->forcePlainLayout())
5839 newcontext.layout = &context.textclass.plainLayout();
5840 output_ert(os, arg, newcontext);
5842 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5845 // Minted caption insets are not closed here because
5846 // we collect everything into the caption.
5847 if (minted_float.empty())
5852 if (t.cs() == "includepdf") {
5854 string const arg = p.getArg('[', ']');
5855 map<string, string> opts;
5856 vector<string> keys;
5857 split_map(arg, opts, keys);
5858 string name = normalize_filename(p.verbatim_item());
5859 string const path = getMasterFilePath(true);
5860 // We want to preserve relative / absolute filenames,
5861 // therefore path is only used for testing
5862 if (!makeAbsPath(name, path).exists()) {
5863 // The file extension is probably missing.
5864 // Now try to find it out.
5865 char const * const pdfpages_format[] = {"pdf", 0};
5866 string const pdftex_name =
5867 find_file(name, path, pdfpages_format);
5868 if (!pdftex_name.empty()) {
5873 FileName const absname = makeAbsPath(name, path);
5874 if (absname.exists())
5876 fix_child_filename(name);
5877 copy_file(absname, name);
5879 cerr << "Warning: Could not find file '"
5880 << name << "'." << endl;
5882 context.check_layout(os);
5883 begin_inset(os, "External\n\ttemplate ");
5884 os << "PDFPages\n\tfilename "
5886 // parse the options
5887 if (opts.find("pages") != opts.end())
5888 os << "\textra LaTeX \"pages="
5889 << opts["pages"] << "\"\n";
5890 if (opts.find("angle") != opts.end())
5891 os << "\trotateAngle "
5892 << opts["angle"] << '\n';
5893 if (opts.find("origin") != opts.end()) {
5895 string const opt = opts["origin"];
5896 if (opt == "tl") ss << "topleft";
5897 if (opt == "bl") ss << "bottomleft";
5898 if (opt == "Bl") ss << "baselineleft";
5899 if (opt == "c") ss << "center";
5900 if (opt == "tc") ss << "topcenter";
5901 if (opt == "bc") ss << "bottomcenter";
5902 if (opt == "Bc") ss << "baselinecenter";
5903 if (opt == "tr") ss << "topright";
5904 if (opt == "br") ss << "bottomright";
5905 if (opt == "Br") ss << "baselineright";
5906 if (!ss.str().empty())
5907 os << "\trotateOrigin " << ss.str() << '\n';
5909 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5911 if (opts.find("width") != opts.end())
5913 << translate_len(opts["width"]) << '\n';
5914 if (opts.find("height") != opts.end())
5916 << translate_len(opts["height"]) << '\n';
5917 if (opts.find("keepaspectratio") != opts.end())
5918 os << "\tkeepAspectRatio\n";
5920 context.check_layout(os);
5921 registerExternalTemplatePackages("PDFPages");
5925 if (t.cs() == "loadgame") {
5927 string name = normalize_filename(p.verbatim_item());
5928 string const path = getMasterFilePath(true);
5929 // We want to preserve relative / absolute filenames,
5930 // therefore path is only used for testing
5931 if (!makeAbsPath(name, path).exists()) {
5932 // The file extension is probably missing.
5933 // Now try to find it out.
5934 char const * const lyxskak_format[] = {"fen", 0};
5935 string const lyxskak_name =
5936 find_file(name, path, lyxskak_format);
5937 if (!lyxskak_name.empty())
5938 name = lyxskak_name;
5940 FileName const absname = makeAbsPath(name, path);
5941 if (absname.exists())
5943 fix_child_filename(name);
5944 copy_file(absname, name);
5946 cerr << "Warning: Could not find file '"
5947 << name << "'." << endl;
5948 context.check_layout(os);
5949 begin_inset(os, "External\n\ttemplate ");
5950 os << "ChessDiagram\n\tfilename "
5953 context.check_layout(os);
5954 // after a \loadgame follows a \showboard
5955 if (p.get_token().asInput() == "showboard")
5957 registerExternalTemplatePackages("ChessDiagram");
5961 // try to see whether the string is in unicodesymbols
5962 // Only use text mode commands, since we are in text mode here,
5963 // and math commands may be invalid (bug 6797)
5964 string name = t.asInput();
5965 // handle the dingbats, cyrillic and greek
5966 if (name == "\\textcyr")
5967 name = "\\textcyrillic";
5968 if (name == "\\ding" || name == "\\textcyrillic" ||
5969 (name == "\\textgreek" && !preamble.usePolyglossia()))
5970 name = name + '{' + p.getArg('{', '}') + '}';
5971 // handle the ifsym characters
5972 else if (name == "\\textifsymbol") {
5973 string const optif = p.getFullOpt();
5974 string const argif = p.getArg('{', '}');
5975 name = name + optif + '{' + argif + '}';
5977 // handle the \ascii characters
5978 // the case of \ascii within braces, as LyX outputs it, is already
5979 // handled for t.cat() == catBegin
5980 else if (name == "\\ascii") {
5981 // the code is "\asci\xxx"
5982 name = "{" + name + p.get_token().asInput() + "}";
5985 // handle some TIPA special characters
5986 else if (preamble.isPackageUsed("tipa")) {
5987 if (name == "\\s") {
5988 // fromLaTeXCommand() does not yet
5989 // recognize tipa short cuts
5990 name = "\\textsyllabic";
5991 } else if (name == "\\=" &&
5992 p.next_token().asInput() == "*") {
5993 // fromLaTeXCommand() does not yet
5994 // recognize tipa short cuts
5996 name = "\\textsubbar";
5997 } else if (name == "\\textdoublevertline") {
5998 // FIXME: This is not correct,
5999 // \textvertline is higher than \textbardbl
6000 name = "\\textbardbl";
6002 } else if (name == "\\!" ) {
6003 if (p.next_token().asInput() == "b") {
6004 p.get_token(); // eat 'b'
6007 } else if (p.next_token().asInput() == "d") {
6011 } else if (p.next_token().asInput() == "g") {
6015 } else if (p.next_token().asInput() == "G") {
6017 name = "\\texthtscg";
6019 } else if (p.next_token().asInput() == "j") {
6021 name = "\\texthtbardotlessj";
6023 } else if (p.next_token().asInput() == "o") {
6025 name = "\\textbullseye";
6028 } else if (name == "\\*" ) {
6029 if (p.next_token().asInput() == "k") {
6031 name = "\\textturnk";
6033 } else if (p.next_token().asInput() == "r") {
6034 p.get_token(); // eat 'b'
6035 name = "\\textturnr";
6037 } else if (p.next_token().asInput() == "t") {
6039 name = "\\textturnt";
6041 } else if (p.next_token().asInput() == "w") {
6043 name = "\\textturnw";
6048 if ((name.size() == 2 &&
6049 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6050 p.next_token().asInput() != "*") ||
6051 is_known(name.substr(1), known_tipa_marks)) {
6052 // name is a command that corresponds to a
6053 // combining character in unicodesymbols.
6054 // Append the argument, fromLaTeXCommand()
6055 // will either convert it to a single
6056 // character or a combining sequence.
6057 name += '{' + p.verbatim_item() + '}';
6059 // now get the character from unicodesymbols
6063 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6064 Encodings::TEXT_CMD, termination, rem, &req));
6066 context.check_layout(os);
6069 output_ert_inset(os, to_utf8(rem), context);
6071 skip_spaces_braces(p);
6072 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6073 preamble.registerAutomaticallyLoadedPackage(*it);
6075 //cerr << "#: " << t << " mode: " << mode << endl;
6076 // heuristic: read up to next non-nested space
6078 string s = t.asInput();
6079 string z = p.verbatim_item();
6080 while (p.good() && z != " " && !z.empty()) {
6081 //cerr << "read: " << z << endl;
6083 z = p.verbatim_item();
6085 cerr << "found ERT: " << s << endl;
6086 output_ert_inset(os, s + ' ', context);
6089 if (t.asInput() == name &&
6090 p.next_token().asInput() == "*") {
6091 // Starred commands like \vspace*{}
6092 p.get_token(); // Eat '*'
6095 if (!parse_command(name, p, os, outer, context))
6096 output_ert_inset(os, name, context);
6102 string guessLanguage(Parser & p, string const & lang)
6104 typedef std::map<std::string, size_t> LangMap;
6105 // map from language names to number of characters
6108 for (char const * const * i = supported_CJK_languages; *i; i++)
6109 used[string(*i)] = 0;
6112 Token const t = p.get_token();
6113 // comments are not counted for any language
6114 if (t.cat() == catComment)
6116 // commands are not counted as well, but we need to detect
6117 // \begin{CJK} and switch encoding if needed
6118 if (t.cat() == catEscape) {
6119 if (t.cs() == "inputencoding") {
6120 string const enc = subst(p.verbatim_item(), "\n", " ");
6121 p.setEncoding(enc, Encoding::inputenc);
6124 if (t.cs() != "begin")
6127 // Non-CJK content is counted for lang.
6128 // We do not care about the real language here:
6129 // If we have more non-CJK contents than CJK contents,
6130 // we simply use the language that was specified as
6131 // babel main language.
6132 used[lang] += t.asInput().length();
6135 // Now we are starting an environment
6137 string const name = p.getArg('{', '}');
6138 if (name != "CJK") {
6142 // It is a CJK environment
6144 /* name = */ p.getArg('{', '}');
6145 string const encoding = p.getArg('{', '}');
6146 /* mapping = */ p.getArg('{', '}');
6147 string const encoding_old = p.getEncoding();
6148 char const * const * const where =
6149 is_known(encoding, supported_CJK_encodings);
6151 p.setEncoding(encoding, Encoding::CJK);
6153 p.setEncoding("UTF-8");
6154 string const text = p.ertEnvironment("CJK");
6155 p.setEncoding(encoding_old);
6158 // ignore contents in unknown CJK encoding
6161 // the language of the text
6163 supported_CJK_languages[where - supported_CJK_encodings];
6164 used[cjk] += text.length();
6166 LangMap::const_iterator use = used.begin();
6167 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6168 if (it->second > use->second)
6175 void check_comment_bib(ostream & os, Context & context)
6177 if (!need_commentbib)
6179 // We have a bibliography database, but no bibliography with biblatex
6180 // which is completely valid. Insert a bibtex inset in a note.
6181 context.check_layout(os);
6182 begin_inset(os, "Note Note\n");
6183 os << "status open\n";
6184 os << "\\begin_layout Plain Layout\n";
6185 begin_command_inset(os, "bibtex", "bibtex");
6187 for (auto const & bf : preamble.biblatex_bibliographies) {
6188 if (!bibfiles.empty())
6190 bibfiles += normalize_filename(bf);
6192 if (!bibfiles.empty())
6193 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6194 end_inset(os);// Bibtex
6195 os << "\\end_layout\n";
6196 end_inset(os);// Note