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
545 string translate_len(string const & length)
549 if (translate_len(length, value, unit))
551 // If the input is invalid, return what we have.
559 * Translates a LaTeX length into \p value, \p unit and
560 * \p special parts suitable for a box inset.
561 * The difference from translate_len() is that a box inset knows about
562 * some special "units" that are stored in \p special.
564 void translate_box_len(string const & length, string & value, string & unit, string & special)
566 if (translate_len(length, value, unit)) {
567 if (unit == "\\height" || unit == "\\depth" ||
568 unit == "\\totalheight" || unit == "\\width") {
569 special = unit.substr(1);
570 // The unit is not used, but LyX requires a dummy setting
582 void begin_inset(ostream & os, string const & name)
584 os << "\n\\begin_inset " << name;
588 void begin_command_inset(ostream & os, string const & name,
589 string const & latexname)
591 begin_inset(os, "CommandInset ");
592 os << name << "\nLatexCommand " << latexname << '\n';
596 void end_inset(ostream & os)
598 os << "\n\\end_inset\n\n";
602 bool skip_braces(Parser & p)
604 if (p.next_token().cat() != catBegin)
607 if (p.next_token().cat() == catEnd) {
616 /// replace LaTeX commands in \p s from the unicodesymbols file with their
618 pair<bool, docstring> convert_unicodesymbols(docstring s)
622 for (size_t i = 0; i < s.size();) {
631 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
632 Encodings::TEXT_CMD, termination, rem, &req));
633 set<string>::const_iterator it = req.begin();
634 set<string>::const_iterator en = req.end();
635 for (; it != en; ++it)
636 preamble.registerAutomaticallyLoadedPackage(*it);
639 if (s.empty() || s[0] != '\\')
643 for (auto const & c : known_escaped_chars)
644 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
649 return make_pair(res, os.str());
653 /// try to convert \p s to a valid InsetCommand argument
654 /// return whether this succeeded. If not, these command insets
655 /// get the "literate" flag.
656 pair<bool, string> convert_latexed_command_inset_arg(string s)
658 bool success = false;
660 // since we don't know the input encoding we can't use from_utf8
661 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
663 s = to_utf8(res.second);
665 // LyX cannot handle newlines in a latex command
666 return make_pair(success, subst(s, "\n", " "));
669 /// try to convert \p s to a valid InsetCommand argument
670 /// without trying to recode macros.
671 string convert_literate_command_inset_arg(string s)
673 // LyX cannot handle newlines in a latex command
674 return subst(s, "\n", " ");
677 void output_ert(ostream & os, string const & s, Context & context)
679 context.check_layout(os);
680 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
682 os << "\n\\backslash\n";
683 else if (*it == '\n') {
684 context.new_paragraph(os);
685 context.check_layout(os);
689 context.check_end_layout(os);
693 void output_ert_inset(ostream & os, string const & s, Context & context)
695 // We must have a valid layout before outputting the ERT inset.
696 context.check_layout(os);
697 Context newcontext(true, context.textclass);
698 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
699 if (layout.forcePlainLayout())
700 newcontext.layout = &context.textclass.plainLayout();
701 begin_inset(os, "ERT");
702 os << "\nstatus collapsed\n";
703 output_ert(os, s, newcontext);
708 void output_comment(Parser & p, ostream & os, string const & s,
711 if (p.next_token().cat() == catNewline)
712 output_ert_inset(os, '%' + s, context);
714 output_ert_inset(os, '%' + s + '\n', context);
718 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
719 string const & latexparam = string())
721 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
724 if (checkModule(name, command))
725 return findLayoutWithoutModule(textclass, name, command, latexparam);
730 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
731 string const & latexparam = string())
733 InsetLayout const * insetlayout =
734 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
737 if (checkModule(name, command))
738 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
743 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
744 bool eatNewline = true);
748 * Skips whitespace and braces.
749 * This should be called after a command has been parsed that is not put into
750 * ERT, and where LyX adds "{}" if needed.
752 void skip_spaces_braces(Parser & p, bool keepws = false)
754 /* The following four examples produce the same typeset output and
755 should be handled by this function:
763 // Unfortunately we need to skip comments, too.
764 // We can't use eat_whitespace since writing them after the {}
765 // results in different output in some cases.
766 bool const skipped_spaces = p.skip_spaces(true);
767 bool const skipped_braces = skip_braces(p);
768 if (keepws && skipped_spaces && !skipped_braces)
769 // put back the space (it is better handled by check_space)
770 p.unskip_spaces(true);
774 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
775 Context & context, Layout::LaTeXArgMap const & latexargs)
777 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
779 context.check_layout(os);
785 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
786 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
787 for (; lait != laend; ++lait) {
789 eat_whitespace(p, os, context, false);
790 if (lait->second.mandatory) {
791 if (p.next_token().cat() != catBegin)
793 string ldelim = to_utf8(lait->second.ldelim);
794 string rdelim = to_utf8(lait->second.rdelim);
799 p.get_token(); // eat ldelim
800 if (ldelim.size() > 1)
801 p.get_token(); // eat ldelim
803 context.check_layout(os);
806 begin_inset(os, "Argument ");
809 os << i << "\nstatus collapsed\n\n";
810 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
813 string ldelim = to_utf8(lait->second.ldelim);
814 string rdelim = to_utf8(lait->second.rdelim);
819 string tok = p.next_token().asInput();
820 // we only support delimiters with max 2 chars for now.
821 if (ldelim.size() > 1)
822 tok += p.next_next_token().asInput();
823 if (p.next_token().cat() == catEscape || tok != ldelim)
825 p.get_token(); // eat ldelim
826 if (ldelim.size() > 1)
827 p.get_token(); // eat ldelim
829 context.check_layout(os);
832 begin_inset(os, "Argument ");
835 os << i << "\nstatus collapsed\n\n";
836 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
839 eat_whitespace(p, os, context, false);
844 void output_command_layout(ostream & os, Parser & p, bool outer,
845 Context & parent_context,
846 Layout const * newlayout)
848 TeXFont const oldFont = parent_context.font;
849 // save the current font size
850 string const size = oldFont.size;
851 // reset the font size to default, because the font size switches
852 // don't affect section headings and the like
853 parent_context.font.size = Context::normalfont.size;
854 // we only need to write the font change if we have an open layout
855 if (!parent_context.atParagraphStart())
856 output_font_change(os, oldFont, parent_context.font);
857 parent_context.check_end_layout(os);
858 Context context(true, parent_context.textclass, newlayout,
859 parent_context.layout, parent_context.font);
860 if (parent_context.deeper_paragraph) {
861 // We are beginning a nested environment after a
862 // deeper paragraph inside the outer list environment.
863 // Therefore we don't need to output a "begin deeper".
864 context.need_end_deeper = true;
866 context.check_deeper(os);
867 output_arguments(os, p, outer, true, string(), context,
868 context.layout->latexargs());
869 // If we have a latex param, we eat it here.
870 if (!parent_context.latexparam.empty()) {
872 Context dummy(true, parent_context.textclass);
873 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
874 string(1, parent_context.latexparam.back()));
876 parse_text(p, os, FLAG_ITEM, outer, context);
877 output_arguments(os, p, outer, false, "post", context,
878 context.layout->postcommandargs());
879 context.check_end_layout(os);
880 if (parent_context.deeper_paragraph) {
881 // We must suppress the "end deeper" because we
882 // suppressed the "begin deeper" above.
883 context.need_end_deeper = false;
885 context.check_end_deeper(os);
886 // We don't need really a new paragraph, but
887 // we must make sure that the next item gets a \begin_layout.
888 parent_context.new_paragraph(os);
889 // Set the font size to the original value. No need to output it here
890 // (Context::begin_layout() will do that if needed)
891 parent_context.font.size = size;
896 * Output a space if necessary.
897 * This function gets called for every whitespace token.
899 * We have three cases here:
900 * 1. A space must be suppressed. Example: The lyxcode case below
901 * 2. A space may be suppressed. Example: Spaces before "\par"
902 * 3. A space must not be suppressed. Example: A space between two words
904 * We currently handle only 1. and 3 and from 2. only the case of
905 * spaces before newlines as a side effect.
907 * 2. could be used to suppress as many spaces as possible. This has two effects:
908 * - Reimporting LyX generated LaTeX files changes almost no whitespace
909 * - Superflous whitespace from non LyX generated LaTeX files is removed.
910 * The drawback is that the logic inside the function becomes
911 * complicated, and that is the reason why it is not implemented.
913 void check_space(Parser & p, ostream & os, Context & context)
915 Token const next = p.next_token();
916 Token const curr = p.curr_token();
917 // A space before a single newline and vice versa must be ignored
918 // LyX emits a newline before \end{lyxcode}.
919 // This newline must be ignored,
920 // otherwise LyX will add an additional protected space.
921 if (next.cat() == catSpace ||
922 next.cat() == catNewline ||
923 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
926 context.check_layout(os);
932 * Parse all arguments of \p command
934 void parse_arguments(string const & command,
935 vector<ArgumentType> const & template_arguments,
936 Parser & p, ostream & os, bool outer, Context & context)
938 string ert = command;
939 size_t no_arguments = template_arguments.size();
940 for (size_t i = 0; i < no_arguments; ++i) {
941 switch (template_arguments[i]) {
944 // This argument contains regular LaTeX
945 output_ert_inset(os, ert + '{', context);
946 eat_whitespace(p, os, context, false);
947 if (template_arguments[i] == required)
948 parse_text(p, os, FLAG_ITEM, outer, context);
950 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
954 // This argument consists only of a single item.
955 // The presence of '{' or not must be preserved.
957 if (p.next_token().cat() == catBegin)
958 ert += '{' + p.verbatim_item() + '}';
960 ert += p.verbatim_item();
964 // This argument may contain special characters
965 ert += '{' + p.verbatim_item() + '}';
969 // true because we must not eat whitespace
970 // if an optional arg follows we must not strip the
971 // brackets from this one
972 if (i < no_arguments - 1 &&
973 template_arguments[i+1] == optional)
974 ert += p.getFullOpt(true);
976 ert += p.getOpt(true);
980 output_ert_inset(os, ert, context);
985 * Check whether \p command is a known command. If yes,
986 * handle the command with all arguments.
987 * \return true if the command was parsed, false otherwise.
989 bool parse_command(string const & command, Parser & p, ostream & os,
990 bool outer, Context & context)
992 if (known_commands.find(command) != known_commands.end()) {
993 parse_arguments(command, known_commands[command], p, os,
1001 /// Parses a minipage or parbox
1002 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1003 unsigned inner_flags, bool outer, Context & parent_context,
1004 string const & outer_type, string const & special,
1005 string inner_type, string const & frame_color,
1006 string const & background_color)
1010 string hor_pos = "l";
1011 // We need to set the height to the LaTeX default of 1\\totalheight
1012 // for the case when no height argument is given
1013 string height_value = "1";
1014 string height_unit = "in";
1015 string height_special = "totalheight";
1016 string latex_height;
1020 string width_special = "none";
1021 string thickness = "0.4pt";
1022 if (!fboxrule.empty())
1023 thickness = fboxrule;
1025 thickness = "0.4pt";
1027 if (!fboxsep.empty())
1028 separation = fboxsep;
1032 if (!shadow_size.empty())
1033 shadowsize = shadow_size;
1036 string framecolor = "black";
1037 string backgroundcolor = "none";
1038 if (!frame_color.empty())
1039 framecolor = frame_color;
1040 if (!background_color.empty())
1041 backgroundcolor = background_color;
1042 // if there is a color box around the \begin statements have not yet been parsed
1044 if (!frame_color.empty() || !background_color.empty()) {
1045 eat_whitespace(p, os, parent_context, false);
1046 p.get_token().asInput(); // the '{'
1048 if (p.next_token().asInput() == "\\begin") {
1049 p.get_token().asInput();
1051 inner_type = "minipage";
1052 inner_flags = FLAG_END;
1053 active_environments.push_back("minipage");
1056 else if (p.next_token().asInput() == "\\parbox") {
1057 p.get_token().asInput();
1058 inner_type = "parbox";
1059 inner_flags = FLAG_ITEM;
1062 else if (p.next_token().asInput() == "\\makebox") {
1063 p.get_token().asInput();
1064 inner_type = "makebox";
1065 inner_flags = FLAG_ITEM;
1067 // in case there is just \colorbox{color}{text}
1070 inner_type = "makebox";
1071 inner_flags = FLAG_BRACE_LAST;
1076 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1078 if (!inner_type.empty() && p.hasOpt()) {
1079 if (inner_type != "makebox")
1080 position = p.getArg('[', ']');
1082 latex_width = p.getArg('[', ']');
1083 translate_box_len(latex_width, width_value, width_unit, width_special);
1086 if (position != "t" && position != "c" && position != "b") {
1087 cerr << "invalid position " << position << " for "
1088 << inner_type << endl;
1092 if (inner_type != "makebox") {
1093 latex_height = p.getArg('[', ']');
1094 translate_box_len(latex_height, height_value, height_unit, height_special);
1096 string const opt = p.getArg('[', ']');
1099 if (hor_pos != "l" && hor_pos != "c" &&
1100 hor_pos != "r" && hor_pos != "s") {
1101 cerr << "invalid hor_pos " << hor_pos
1102 << " for " << inner_type << endl;
1109 inner_pos = p.getArg('[', ']');
1110 if (inner_pos != "c" && inner_pos != "t" &&
1111 inner_pos != "b" && inner_pos != "s") {
1112 cerr << "invalid inner_pos "
1113 << inner_pos << " for "
1114 << inner_type << endl;
1115 inner_pos = position;
1119 if (inner_type == "makebox")
1123 if (inner_type.empty()) {
1124 if (special.empty() && outer_type != "framebox")
1125 latex_width = "1\\columnwidth";
1128 latex_width = p2.getArg('[', ']');
1129 string const opt = p2.getArg('[', ']');
1132 if (hor_pos != "l" && hor_pos != "c" &&
1133 hor_pos != "r" && hor_pos != "s") {
1134 cerr << "invalid hor_pos " << hor_pos
1135 << " for " << outer_type << endl;
1139 if (outer_type == "framebox")
1143 } else if (inner_type != "makebox")
1144 latex_width = p.verbatim_item();
1145 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1146 // as this is LyX's standard for such cases (except for makebox)
1147 // \framebox is more special and handled below
1148 if (latex_width.empty() && inner_type != "makebox"
1149 && outer_type != "framebox")
1150 latex_width = "1\\columnwidth";
1152 translate_len(latex_width, width_value, width_unit);
1154 bool shadedparbox = false;
1155 if (inner_type == "shaded") {
1156 eat_whitespace(p, os, parent_context, false);
1157 if (outer_type == "parbox") {
1159 if (p.next_token().cat() == catBegin)
1161 eat_whitespace(p, os, parent_context, false);
1162 shadedparbox = true;
1167 // If we already read the inner box we have to push the inner env
1168 if (!outer_type.empty() && !inner_type.empty() &&
1169 (inner_flags & FLAG_END))
1170 active_environments.push_back(inner_type);
1171 bool use_ert = false;
1172 if (!outer_type.empty() && !inner_type.empty()) {
1173 // Look whether there is some content after the end of the
1174 // inner box, but before the end of the outer box.
1175 // If yes, we need to output ERT.
1177 if (inner_flags & FLAG_END)
1178 p.ertEnvironment(inner_type);
1181 p.skip_spaces(true);
1182 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1183 if ((outer_env && p.next_token().asInput() != "\\end") ||
1184 (!outer_env && p.next_token().cat() != catEnd)) {
1185 // something is between the end of the inner box and
1186 // the end of the outer box, so we need to use ERT.
1194 if (!outer_type.empty()) {
1195 if (outer_flags & FLAG_END)
1196 ss << "\\begin{" << outer_type << '}';
1198 ss << '\\' << outer_type << '{';
1199 if (!special.empty())
1203 if (!inner_type.empty()) {
1204 if (inner_type != "shaded") {
1205 if (inner_flags & FLAG_END)
1206 ss << "\\begin{" << inner_type << '}';
1208 ss << '\\' << inner_type;
1210 if (!position.empty())
1211 ss << '[' << position << ']';
1212 if (!latex_height.empty())
1213 ss << '[' << latex_height << ']';
1214 if (!inner_pos.empty())
1215 ss << '[' << inner_pos << ']';
1216 ss << '{' << latex_width << '}';
1217 if (!(inner_flags & FLAG_END))
1220 if (inner_type == "shaded")
1221 ss << "\\begin{shaded}";
1222 output_ert_inset(os, ss.str(), parent_context);
1223 if (!inner_type.empty()) {
1224 parse_text(p, os, inner_flags, outer, parent_context);
1225 if (inner_flags & FLAG_END)
1226 output_ert_inset(os, "\\end{" + inner_type + '}',
1229 output_ert_inset(os, "}", parent_context);
1231 if (!outer_type.empty()) {
1232 // If we already read the inner box we have to pop
1234 if (!inner_type.empty() && (inner_flags & FLAG_END))
1235 active_environments.pop_back();
1237 // Ensure that the end of the outer box is parsed correctly:
1238 // The opening brace has been eaten by parse_outer_box()
1239 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1240 outer_flags &= ~FLAG_ITEM;
1241 outer_flags |= FLAG_BRACE_LAST;
1243 parse_text(p, os, outer_flags, outer, parent_context);
1244 if (outer_flags & FLAG_END)
1245 output_ert_inset(os, "\\end{" + outer_type + '}',
1248 output_ert_inset(os, "}", parent_context);
1251 // LyX does not like empty positions, so we have
1252 // to set them to the LaTeX default values here.
1253 if (position.empty())
1255 if (inner_pos.empty())
1256 inner_pos = position;
1257 parent_context.check_layout(os);
1258 begin_inset(os, "Box ");
1259 if (outer_type == "framed")
1261 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1263 else if (outer_type == "shadowbox")
1264 os << "Shadowbox\n";
1265 else if ((outer_type == "shaded" && inner_type.empty()) ||
1266 (outer_type == "minipage" && inner_type == "shaded") ||
1267 (outer_type == "parbox" && inner_type == "shaded")) {
1269 preamble.registerAutomaticallyLoadedPackage("color");
1270 } else if (outer_type == "doublebox")
1271 os << "Doublebox\n";
1272 else if (outer_type.empty() || outer_type == "mbox")
1273 os << "Frameless\n";
1275 os << outer_type << '\n';
1276 os << "position \"" << position << "\"\n";
1277 os << "hor_pos \"" << hor_pos << "\"\n";
1278 if (outer_type == "mbox")
1279 os << "has_inner_box 1\n";
1280 else if (!frame_color.empty() && inner_type == "makebox")
1281 os << "has_inner_box 0\n";
1283 os << "has_inner_box " << !inner_type.empty() << "\n";
1284 os << "inner_pos \"" << inner_pos << "\"\n";
1285 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1287 if (outer_type == "mbox")
1288 os << "use_makebox 1\n";
1289 else if (!frame_color.empty())
1290 os << "use_makebox 0\n";
1292 os << "use_makebox " << (inner_type == "makebox") << '\n';
1293 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1294 os << "width \"\"\n";
1295 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1296 else if (contains(width_unit, '\\'))
1297 os << "width \"" << width_value << "in" << "\"\n";
1299 os << "width \"" << width_value << width_unit << "\"\n";
1300 if (contains(width_unit, '\\')) {
1301 width_unit.erase (0,1); // remove the leading '\'
1302 os << "special \"" << width_unit << "\"\n";
1304 os << "special \"" << width_special << "\"\n";
1305 if (contains(height_unit, '\\'))
1306 os << "height \"" << height_value << "in" << "\"\n";
1308 os << "height \"" << height_value << height_unit << "\"\n";
1309 os << "height_special \"" << height_special << "\"\n";
1310 os << "thickness \"" << thickness << "\"\n";
1311 os << "separation \"" << separation << "\"\n";
1312 os << "shadowsize \"" << shadowsize << "\"\n";
1313 os << "framecolor \"" << framecolor << "\"\n";
1314 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1315 os << "status open\n\n";
1317 // Unfortunately we can't use parse_text_in_inset:
1318 // InsetBox::forcePlainLayout() is hard coded and does not
1319 // use the inset layout. Apart from that do we call parse_text
1320 // up to two times, but need only one check_end_layout.
1321 bool const forcePlainLayout =
1322 (!inner_type.empty() || inner_type == "makebox") &&
1323 outer_type != "shaded" && outer_type != "framed";
1324 Context context(true, parent_context.textclass);
1325 if (forcePlainLayout)
1326 context.layout = &context.textclass.plainLayout();
1328 context.font = parent_context.font;
1330 // If we have no inner box the contents will be read with the outer box
1331 if (!inner_type.empty())
1332 parse_text(p, os, inner_flags, outer, context);
1334 // Ensure that the end of the outer box is parsed correctly:
1335 // The opening brace has been eaten by parse_outer_box()
1336 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1337 outer_flags &= ~FLAG_ITEM;
1338 outer_flags |= FLAG_BRACE_LAST;
1341 // Find end of outer box, output contents if inner_type is
1342 // empty and output possible comments
1343 if (!outer_type.empty()) {
1344 // If we already read the inner box we have to pop
1346 if (!inner_type.empty() && (inner_flags & FLAG_END))
1347 active_environments.pop_back();
1348 // This does not output anything but comments if
1349 // inner_type is not empty (see use_ert)
1350 parse_text(p, os, outer_flags, outer, context);
1353 context.check_end_layout(os);
1355 #ifdef PRESERVE_LAYOUT
1356 // LyX puts a % after the end of the minipage
1357 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1359 //output_comment(p, os, "dummy", parent_context);
1362 parent_context.new_paragraph(os);
1364 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1365 //output_comment(p, os, "dummy", parent_context);
1368 // We add a protected space if something real follows
1369 if (p.good() && p.next_token().cat() != catComment) {
1370 begin_inset(os, "space ~\n");
1376 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1377 active_environments.pop_back();
1378 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1379 // in this case we have to eat the the closing brace of the color box
1380 p.get_token().asInput(); // the '}'
1382 if (p.next_token().asInput() == "}") {
1383 // in this case we assume that the closing brace is from the box settings
1384 // therefore reset these values for the next box
1390 // all boxes except of Frameless and Shaded require calc
1391 if (!(outer_type.empty() || outer_type == "mbox") &&
1392 !((outer_type == "shaded" && inner_type.empty()) ||
1393 (outer_type == "minipage" && inner_type == "shaded") ||
1394 (outer_type == "parbox" && inner_type == "shaded")))
1395 preamble.registerAutomaticallyLoadedPackage("calc");
1399 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1400 Context & parent_context, string const & outer_type,
1401 string const & special)
1403 eat_whitespace(p, os, parent_context, false);
1404 if (flags & FLAG_ITEM) {
1406 if (p.next_token().cat() == catBegin)
1409 cerr << "Warning: Ignoring missing '{' after \\"
1410 << outer_type << '.' << endl;
1411 eat_whitespace(p, os, parent_context, false);
1414 unsigned int inner_flags = 0;
1416 if (outer_type == "minipage" || outer_type == "parbox") {
1417 p.skip_spaces(true);
1418 while (p.hasOpt()) {
1420 p.skip_spaces(true);
1423 p.skip_spaces(true);
1424 if (outer_type == "parbox") {
1426 if (p.next_token().cat() == catBegin)
1428 p.skip_spaces(true);
1431 if (outer_type == "shaded" || outer_type == "mbox") {
1432 // These boxes never have an inner box
1434 } else if (p.next_token().asInput() == "\\parbox") {
1435 inner = p.get_token().cs();
1436 inner_flags = FLAG_ITEM;
1437 } else if (p.next_token().asInput() == "\\begin") {
1438 // Is this a minipage or shaded box?
1441 inner = p.getArg('{', '}');
1443 if (inner == "minipage" || inner == "shaded")
1444 inner_flags = FLAG_END;
1449 if (inner_flags == FLAG_END) {
1450 if (inner != "shaded")
1454 eat_whitespace(p, os, parent_context, false);
1456 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1457 outer_type, special, inner, "", "");
1459 if (inner_flags == FLAG_ITEM) {
1461 eat_whitespace(p, os, parent_context, false);
1463 parse_box(p, os, flags, inner_flags, outer, parent_context,
1464 outer_type, special, inner, "", "");
1469 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1470 bool in_line, bool use_minted)
1472 parent_context.check_layout(os);
1473 begin_inset(os, "listings\n");
1474 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1476 while ((i = arg.find(", ")) != string::npos
1477 || (i = arg.find(",\t")) != string::npos)
1478 arg.erase(i + 1, 1);
1481 string const language = p.getArg('{', '}');
1482 p.skip_spaces(true);
1483 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1484 if (!minted_float.empty()) {
1485 arg += string(arg.empty() ? "" : ",") + minted_float;
1486 minted_nonfloat_caption.clear();
1490 os << "lstparams " << '"' << arg << '"' << '\n';
1491 if (arg.find("\\color") != string::npos)
1492 preamble.registerAutomaticallyLoadedPackage("color");
1495 os << "inline true\n";
1497 os << "inline false\n";
1498 os << "status open\n";
1499 Context context(true, parent_context.textclass);
1500 context.layout = &parent_context.textclass.plainLayout();
1501 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1502 minted_nonfloat_caption.erase(0,3);
1503 os << "\n\\begin_layout Plain Layout\n";
1504 begin_inset(os, "Caption Standard\n");
1505 Context newcontext(true, context.textclass,
1506 context.layout, 0, context.font);
1507 newcontext.check_layout(os);
1508 os << minted_nonfloat_caption << "\n";
1509 newcontext.check_end_layout(os);
1511 os << "\n\\end_layout\n";
1512 minted_nonfloat_caption.clear();
1516 // set catcodes to verbatim early, just in case.
1517 p.setCatcodes(VERBATIM_CATCODES);
1518 string delim = p.get_token().asInput();
1519 //FIXME: handler error condition
1520 s = p.verbatimStuff(delim).second;
1521 // context.new_paragraph(os);
1522 } else if (use_minted) {
1523 s = p.verbatimEnvironment("minted");
1525 s = p.verbatimEnvironment("lstlisting");
1527 output_ert(os, s, context);
1528 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1529 minted_nonfloat_caption.erase(0,3);
1530 os << "\n\\begin_layout Plain Layout\n";
1531 begin_inset(os, "Caption Standard\n");
1532 Context newcontext(true, context.textclass,
1533 context.layout, 0, context.font);
1534 newcontext.check_layout(os);
1535 os << minted_nonfloat_caption << "\n";
1536 newcontext.check_end_layout(os);
1538 os << "\n\\end_layout\n";
1539 minted_nonfloat_caption.clear();
1541 // Don't close the inset here for floating minted listings.
1542 // It will be closed at the end of the listing environment.
1543 if (!use_minted || minted_float.empty())
1546 eat_whitespace(p, os, parent_context, true);
1547 Token t = p.get_token();
1548 if (t.asInput() != "\\end") {
1549 // If anything follows, collect it into a caption.
1550 minted_float_has_caption = true;
1551 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1552 begin_inset(os, "Caption Standard\n");
1553 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1560 /// parse an unknown environment
1561 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1562 unsigned flags, bool outer,
1563 Context & parent_context)
1565 if (name == "tabbing")
1566 // We need to remember that we have to handle '\=' specially
1567 flags |= FLAG_TABBING;
1569 // We need to translate font changes and paragraphs inside the
1570 // environment to ERT if we have a non standard font.
1571 // Otherwise things like
1572 // \large\begin{foo}\huge bar\end{foo}
1574 bool const specialfont =
1575 (parent_context.font != parent_context.normalfont);
1576 bool const new_layout_allowed = parent_context.new_layout_allowed;
1578 parent_context.new_layout_allowed = false;
1579 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1580 parse_text_snippet(p, os, flags, outer, parent_context);
1581 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1583 parent_context.new_layout_allowed = new_layout_allowed;
1587 void parse_environment(Parser & p, ostream & os, bool outer,
1588 string & last_env, Context & parent_context)
1590 Layout const * newlayout;
1591 InsetLayout const * newinsetlayout = 0;
1592 string const name = p.getArg('{', '}');
1593 const bool is_starred = suffixIs(name, '*');
1594 string const unstarred_name = rtrim(name, "*");
1595 active_environments.push_back(name);
1597 // We use this loop and break out after a condition is met
1598 // rather than a huge else-if-chain.
1600 if (is_math_env(name)) {
1601 parent_context.check_layout(os);
1602 begin_inset(os, "Formula ");
1603 os << "\\begin{" << name << "}";
1604 parse_math(p, os, FLAG_END, MATH_MODE);
1605 os << "\\end{" << name << "}";
1607 if (is_display_math_env(name)) {
1608 // Prevent the conversion of a line break to a space
1609 // (bug 7668). This does not change the output, but
1610 // looks ugly in LyX.
1611 eat_whitespace(p, os, parent_context, false);
1616 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1617 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1618 // We must begin a new paragraph if not already done
1619 if (! parent_context.atParagraphStart()) {
1620 parent_context.check_end_layout(os);
1621 parent_context.new_paragraph(os);
1623 // save the language in the context so that it is
1624 // handled by parse_text
1625 parent_context.font.language =
1626 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1627 parse_text(p, os, FLAG_END, outer, parent_context);
1628 // Just in case the environment is empty
1629 parent_context.extra_stuff.erase();
1630 // We must begin a new paragraph to reset the language
1631 parent_context.new_paragraph(os);
1636 if (unstarred_name == "tabular" || name == "longtable"
1637 || name == "tabularx" || name == "xltabular") {
1638 eat_whitespace(p, os, parent_context, false);
1639 string width = "0pt";
1641 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1642 string const opt = p.getArg('[', ']');
1645 else if (opt == "l")
1647 else if (opt == "r")
1650 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1651 width = lyx::translate_len(p.getArg('{', '}'));
1652 eat_whitespace(p, os, parent_context, false);
1654 parent_context.check_layout(os);
1655 begin_inset(os, "Tabular ");
1656 handle_tabular(p, os, name, width, halign, parent_context);
1662 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1663 eat_whitespace(p, os, parent_context, false);
1664 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1665 eat_whitespace(p, os, parent_context, false);
1666 parent_context.check_layout(os);
1667 begin_inset(os, "Float " + unstarred_name + "\n");
1668 // store the float type for subfloats
1669 // subfloats only work with figures and tables
1670 if (unstarred_name == "figure")
1671 float_type = unstarred_name;
1672 else if (unstarred_name == "table")
1673 float_type = unstarred_name;
1677 os << "placement " << opt << '\n';
1678 if (contains(opt, "H"))
1679 preamble.registerAutomaticallyLoadedPackage("float");
1681 Floating const & fl = parent_context.textclass.floats()
1682 .getType(unstarred_name);
1683 if (!fl.floattype().empty() && fl.usesFloatPkg())
1684 preamble.registerAutomaticallyLoadedPackage("float");
1687 os << "wide " << convert<string>(is_starred)
1688 << "\nsideways false"
1689 << "\nstatus open\n\n";
1690 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1692 // We don't need really a new paragraph, but
1693 // we must make sure that the next item gets a \begin_layout.
1694 parent_context.new_paragraph(os);
1696 // the float is parsed thus delete the type
1701 if (unstarred_name == "sidewaysfigure"
1702 || unstarred_name == "sidewaystable"
1703 || unstarred_name == "sidewaysalgorithm") {
1704 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1705 eat_whitespace(p, os, parent_context, false);
1706 parent_context.check_layout(os);
1707 if (unstarred_name == "sidewaysfigure")
1708 begin_inset(os, "Float figure\n");
1709 else if (unstarred_name == "sidewaystable")
1710 begin_inset(os, "Float table\n");
1711 else if (unstarred_name == "sidewaysalgorithm")
1712 begin_inset(os, "Float algorithm\n");
1714 os << "placement " << opt << '\n';
1715 if (contains(opt, "H"))
1716 preamble.registerAutomaticallyLoadedPackage("float");
1717 os << "wide " << convert<string>(is_starred)
1718 << "\nsideways true"
1719 << "\nstatus open\n\n";
1720 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1722 // We don't need really a new paragraph, but
1723 // we must make sure that the next item gets a \begin_layout.
1724 parent_context.new_paragraph(os);
1726 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1730 if (name == "wrapfigure" || name == "wraptable") {
1731 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1732 eat_whitespace(p, os, parent_context, false);
1733 parent_context.check_layout(os);
1736 string overhang = "0col%";
1739 lines = p.getArg('[', ']');
1740 string const placement = p.getArg('{', '}');
1742 overhang = p.getArg('[', ']');
1743 string const width = p.getArg('{', '}');
1745 if (name == "wrapfigure")
1746 begin_inset(os, "Wrap figure\n");
1748 begin_inset(os, "Wrap table\n");
1749 os << "lines " << lines
1750 << "\nplacement " << placement
1751 << "\noverhang " << lyx::translate_len(overhang)
1752 << "\nwidth " << lyx::translate_len(width)
1753 << "\nstatus open\n\n";
1754 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1756 // We don't need really a new paragraph, but
1757 // we must make sure that the next item gets a \begin_layout.
1758 parent_context.new_paragraph(os);
1760 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1764 if (name == "minipage") {
1765 eat_whitespace(p, os, parent_context, false);
1766 // Test whether this is an outer box of a shaded box
1768 // swallow arguments
1769 while (p.hasOpt()) {
1771 p.skip_spaces(true);
1774 p.skip_spaces(true);
1775 Token t = p.get_token();
1776 bool shaded = false;
1777 if (t.asInput() == "\\begin") {
1778 p.skip_spaces(true);
1779 if (p.getArg('{', '}') == "shaded")
1784 parse_outer_box(p, os, FLAG_END, outer,
1785 parent_context, name, "shaded");
1787 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1788 "", "", name, "", "");
1793 if (name == "comment") {
1794 eat_whitespace(p, os, parent_context, false);
1795 parent_context.check_layout(os);
1796 begin_inset(os, "Note Comment\n");
1797 os << "status open\n";
1798 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1801 skip_braces(p); // eat {} that might by set by LyX behind comments
1802 preamble.registerAutomaticallyLoadedPackage("verbatim");
1806 if (unstarred_name == "verbatim") {
1807 // FIXME: this should go in the generic code that
1808 // handles environments defined in layout file that
1809 // have "PassThru 1". However, the code over there is
1810 // already too complicated for my taste.
1811 string const ascii_name =
1812 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1813 parent_context.new_paragraph(os);
1814 Context context(true, parent_context.textclass,
1815 &parent_context.textclass[from_ascii(ascii_name)]);
1816 string s = p.verbatimEnvironment(name);
1817 output_ert(os, s, context);
1822 if (name == "IPA") {
1823 eat_whitespace(p, os, parent_context, false);
1824 parent_context.check_layout(os);
1825 begin_inset(os, "IPA\n");
1826 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1829 preamble.registerAutomaticallyLoadedPackage("tipa");
1830 preamble.registerAutomaticallyLoadedPackage("tipx");
1834 if (name == parent_context.textclass.titlename()
1835 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1836 parse_text(p, os, FLAG_END, outer, parent_context);
1837 // Just in case the environment is empty
1838 parent_context.extra_stuff.erase();
1839 // We must begin a new paragraph
1840 parent_context.new_paragraph(os);
1845 if (name == "CJK") {
1846 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1847 // It is impossible to decide if a CJK environment was in its own paragraph or within
1848 // a line. We therefore always assume a paragraph since the latter is a rare case.
1849 eat_whitespace(p, os, parent_context, false);
1850 parent_context.check_end_layout(os);
1851 // store the encoding to be able to reset it
1852 string const encoding_old = p.getEncoding();
1853 string const encoding = p.getArg('{', '}');
1854 // FIXME: For some reason JIS does not work. Although the text
1855 // in tests/CJK.tex is identical with the SJIS version if you
1856 // convert both snippets using the recode command line utility,
1857 // the resulting .lyx file contains some extra characters if
1858 // you set buggy_encoding to false for JIS.
1859 bool const buggy_encoding = encoding == "JIS";
1860 if (!buggy_encoding)
1861 p.setEncoding(encoding, Encoding::CJK);
1863 // FIXME: This will read garbage, since the data is not encoded in utf8.
1864 p.setEncoding("UTF-8");
1866 // LyX only supports the same mapping for all CJK
1867 // environments, so we might need to output everything as ERT
1868 string const mapping = trim(p.getArg('{', '}'));
1869 char const * const * const where =
1870 is_known(encoding, supported_CJK_encodings);
1871 if (!buggy_encoding && !preamble.fontCJKSet())
1872 preamble.fontCJK(mapping);
1873 bool knownMapping = mapping == preamble.fontCJK();
1874 if (buggy_encoding || !knownMapping || !where) {
1875 parent_context.check_layout(os);
1876 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1878 // we must parse the content as verbatim because e.g. JIS can contain
1879 // normally invalid characters
1880 // FIXME: This works only for the most simple cases.
1881 // Since TeX control characters are not parsed,
1882 // things like comments are completely wrong.
1883 string const s = p.plainEnvironment("CJK");
1884 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1887 if (snip == "\\" || is_known(snip, known_escaped_chars))
1888 output_ert_inset(os, snip, parent_context);
1889 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1894 output_ert_inset(os, "\\end{" + name + "}",
1898 supported_CJK_languages[where - supported_CJK_encodings];
1899 // store the language because we must reset it at the end
1900 string const lang_old = parent_context.font.language;
1901 parent_context.font.language = lang;
1902 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1903 parent_context.font.language = lang_old;
1904 parent_context.new_paragraph(os);
1906 p.setEncoding(encoding_old);
1911 if (name == "lyxgreyedout") {
1912 eat_whitespace(p, os, parent_context, false);
1913 parent_context.check_layout(os);
1914 begin_inset(os, "Note Greyedout\n");
1915 os << "status open\n";
1916 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1919 if (!preamble.notefontcolor().empty())
1920 preamble.registerAutomaticallyLoadedPackage("color");
1924 if (name == "btSect") {
1925 eat_whitespace(p, os, parent_context, false);
1926 parent_context.check_layout(os);
1927 begin_command_inset(os, "bibtex", "bibtex");
1928 string bibstyle = "plain";
1930 bibstyle = p.getArg('[', ']');
1931 p.skip_spaces(true);
1933 string const bibfile = p.getArg('{', '}');
1934 eat_whitespace(p, os, parent_context, false);
1935 Token t = p.get_token();
1936 if (t.asInput() == "\\btPrintCited") {
1937 p.skip_spaces(true);
1938 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1940 if (t.asInput() == "\\btPrintNotCited") {
1941 p.skip_spaces(true);
1942 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1944 if (t.asInput() == "\\btPrintAll") {
1945 p.skip_spaces(true);
1946 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1948 os << "bibfiles " << '"' << bibfile << "\"\n"
1949 << "options " << '"' << bibstyle << "\"\n";
1950 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1956 if (name == "btUnit") {
1957 string const nt = p.next_next_token().cs();
1958 // Do not attempt to overwrite a former diverging multibib.
1959 // Those are output as ERT instead.
1960 if ((nt == "part" || nt == "chapter"
1961 || nt == "section" || nt == "subsection")
1962 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1963 parse_text(p, os, FLAG_END, outer, parent_context);
1964 preamble.multibib(nt);
1966 parse_unknown_environment(p, name, os, FLAG_END, outer,
1971 // This is only attempted at turn environments that consist only
1972 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
1973 // Thus we will fall through in other cases.
1974 if (name == "turn") {
1975 // We check if the next thing is a tabular[*|x]
1977 p.getArg('{', '}');// eat turn argument
1978 bool found_end = false;
1979 bool only_table = false;
1980 bool end_table = false;
1983 string envname = p.getArg('{', '}');
1984 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
1985 // Now we check if the table is the only content
1986 // of the turn environment
1987 string const tenv = envname;
1988 while (!found_end && !end_table && p.good()) {
1989 envname = p.next_token().cat() == catBegin
1990 ? p.getArg('{', '}') : string();
1991 Token const & t = p.get_token();
1993 end_table = t.asInput() != "\\end"
1995 found_end = t.asInput() == "\\end"
1996 && envname == "turn";
2000 envname = p.getArg('{', '}');
2001 only_table = p.next_next_token().asInput() == "\\end"
2002 && envname == "turn";
2006 string const angle = p.getArg('{', '}');
2008 int const save_tablerotation = parent_context.tablerotation;
2009 parent_context.tablerotation = convert<int>(angle);
2010 parse_text(p, os, FLAG_END, outer, parent_context);
2011 parent_context.tablerotation = save_tablerotation;
2021 // This is only attempted at landscape environments that consist only
2022 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2023 // Other landscape environment is handled via the landscape module, thus
2024 // we will fall through in that case.
2025 if (name == "landscape") {
2026 // We check if the next thing is a longtable
2028 bool found_end = false;
2029 bool only_longtable = false;
2030 bool end_longtable = false;
2033 string envname = p.getArg('{', '}');
2034 if (envname == "longtable" || envname == "xltabular") {
2035 // Now we check if the longtable is the only content
2036 // of the landscape environment
2037 string const ltenv = envname;
2038 while (!found_end && !end_longtable && p.good()) {
2039 envname = p.next_token().cat() == catBegin
2040 ? p.getArg('{', '}') : string();
2041 Token const & t = p.get_token();
2043 end_longtable = t.asInput() != "\\end"
2044 && envname == ltenv;
2045 found_end = t.asInput() == "\\end"
2046 && envname == "landscape";
2048 if (end_longtable) {
2050 envname = p.getArg('{', '}');
2051 only_longtable = p.next_next_token().asInput() == "\\end"
2052 && envname == "landscape";
2054 if (only_longtable) {
2057 int const save_tablerotation = parent_context.tablerotation;
2058 parent_context.tablerotation = 90;
2059 parse_text(p, os, FLAG_END, outer, parent_context);
2060 parent_context.tablerotation = save_tablerotation;
2070 if (name == "framed" || name == "shaded") {
2071 eat_whitespace(p, os, parent_context, false);
2072 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2074 preamble.registerAutomaticallyLoadedPackage("framed");
2078 if (name == "listing") {
2079 minted_float = "float";
2080 eat_whitespace(p, os, parent_context, false);
2081 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2083 minted_float += "=" + opt;
2084 // If something precedes \begin{minted}, we output it at the end
2085 // as a caption, in order to keep it inside the listings inset.
2086 eat_whitespace(p, os, parent_context, true);
2088 Token const & t = p.get_token();
2089 p.skip_spaces(true);
2090 string const envname = p.next_token().cat() == catBegin
2091 ? p.getArg('{', '}') : string();
2092 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2094 minted_float_has_caption = false;
2095 string content = parse_text_snippet(p, FLAG_END, outer,
2097 size_t i = content.find("\\begin_inset listings");
2098 bool minted_env = i != string::npos;
2101 caption = content.substr(0, i);
2102 content.erase(0, i);
2104 parent_context.check_layout(os);
2105 if (minted_env && minted_float_has_caption) {
2106 eat_whitespace(p, os, parent_context, true);
2107 os << content << "\n";
2108 if (!caption.empty())
2109 os << caption << "\n";
2110 os << "\n\\end_layout\n"; // close inner layout
2111 end_inset(os); // close caption inset
2112 os << "\n\\end_layout\n"; // close outer layout
2113 } else if (!caption.empty()) {
2115 begin_inset(os, "listings\n");
2116 os << "lstparams " << '"' << minted_float << '"' << '\n';
2117 os << "inline false\n";
2118 os << "status collapsed\n";
2120 os << "\n\\begin_layout Plain Layout\n";
2121 begin_inset(os, "Caption Standard\n");
2122 Context newcontext(true, parent_context.textclass,
2123 0, 0, parent_context.font);
2124 newcontext.check_layout(os);
2125 os << caption << "\n";
2126 newcontext.check_end_layout(os);
2128 os << "\n\\end_layout\n";
2129 } else if (content.empty()) {
2130 begin_inset(os, "listings\n");
2131 os << "lstparams " << '"' << minted_float << '"' << '\n';
2132 os << "inline false\n";
2133 os << "status collapsed\n";
2135 os << content << "\n";
2137 end_inset(os); // close listings inset
2138 parent_context.check_end_layout(os);
2139 parent_context.new_paragraph(os);
2141 minted_float.clear();
2142 minted_float_has_caption = false;
2146 if (name == "lstlisting" || name == "minted") {
2147 bool use_minted = name == "minted";
2148 // with listings, we do not eat newlines here since
2149 // \begin{lstlistings}
2152 // // \begin{lstlistings}%
2155 // reads [foo] as content, whereas
2156 // // \begin{lstlistings}%
2159 // \begin{lstlistings}[foo,
2161 // reads [foo...] as argument.
2162 eat_whitespace(p, os, parent_context, false, use_minted);
2163 if (use_minted && minted_float.empty()) {
2164 // look ahead for a bottom caption
2166 bool found_end_minted = false;
2167 while (!found_end_minted && p.good()) {
2168 Token const & t = p.get_token();
2170 string const envname =
2171 p.next_token().cat() == catBegin
2172 ? p.getArg('{', '}') : string();
2173 found_end_minted = t.asInput() == "\\end"
2174 && envname == "minted";
2176 eat_whitespace(p, os, parent_context, true);
2177 Token const & t = p.get_token();
2178 p.skip_spaces(true);
2179 if (t.asInput() == "\\lyxmintcaption") {
2180 string const pos = p.getArg('[', ']');
2182 string const caption =
2183 parse_text_snippet(p, FLAG_ITEM,
2184 false, parent_context);
2185 minted_nonfloat_caption = "[b]" + caption;
2186 eat_whitespace(p, os, parent_context, true);
2191 parse_listings(p, os, parent_context, false, use_minted);
2196 if (!parent_context.new_layout_allowed) {
2197 parse_unknown_environment(p, name, os, FLAG_END, outer,
2202 // Alignment and spacing settings
2203 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2204 // therefore are totally broken!
2205 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2206 // they are commands not environments. They are furthermore switches that
2207 // can be ended by another switches, but also by commands like \footnote or
2208 // \parbox. So the only safe way is to leave them untouched.
2209 // However, we support the pseudo-environments
2210 // \begin{centering} ... \end{centering}
2211 // \begin{raggedright} ... \end{raggedright}
2212 // \begin{raggedleft} ... \end{raggedleft}
2213 // since they are used by LyX in floats (for spacing reasons)
2214 if (name == "center" || name == "centering"
2215 || name == "flushleft" || name == "raggedright"
2216 || name == "flushright" || name == "raggedleft"
2217 || name == "singlespace" || name == "onehalfspace"
2218 || name == "doublespace" || name == "spacing") {
2219 eat_whitespace(p, os, parent_context, false);
2220 // We must begin a new paragraph if not already done
2221 if (! parent_context.atParagraphStart()) {
2222 parent_context.check_end_layout(os);
2223 parent_context.new_paragraph(os);
2225 if (name == "flushleft" || name == "raggedright")
2226 parent_context.add_extra_stuff("\\align left\n");
2227 else if (name == "flushright" || name == "raggedleft")
2228 parent_context.add_extra_stuff("\\align right\n");
2229 else if (name == "center" || name == "centering")
2230 parent_context.add_extra_stuff("\\align center\n");
2231 else if (name == "singlespace")
2232 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2233 else if (name == "onehalfspace") {
2234 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2235 preamble.registerAutomaticallyLoadedPackage("setspace");
2236 } else if (name == "doublespace") {
2237 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2238 preamble.registerAutomaticallyLoadedPackage("setspace");
2239 } else if (name == "spacing") {
2240 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2241 preamble.registerAutomaticallyLoadedPackage("setspace");
2243 parse_text(p, os, FLAG_END, outer, parent_context);
2244 // Just in case the environment is empty
2245 parent_context.extra_stuff.erase();
2246 // We must begin a new paragraph to reset the alignment
2247 parent_context.new_paragraph(os);
2252 // The single '=' is meant here.
2253 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2254 eat_whitespace(p, os, parent_context, false);
2255 Context context(true, parent_context.textclass, newlayout,
2256 parent_context.layout, parent_context.font);
2257 if (parent_context.deeper_paragraph) {
2258 // We are beginning a nested environment after a
2259 // deeper paragraph inside the outer list environment.
2260 // Therefore we don't need to output a "begin deeper".
2261 context.need_end_deeper = true;
2263 parent_context.check_end_layout(os);
2264 if (last_env == name) {
2265 // we need to output a separator since LyX would export
2266 // the two environments as one otherwise (bug 5716)
2267 TeX2LyXDocClass const & textclass(parent_context.textclass);
2268 Context newcontext(true, textclass,
2269 &(textclass.defaultLayout()));
2270 newcontext.check_layout(os);
2271 begin_inset(os, "Separator plain\n");
2273 newcontext.check_end_layout(os);
2275 switch (context.layout->latextype) {
2276 case LATEX_LIST_ENVIRONMENT:
2277 context.add_par_extra_stuff("\\labelwidthstring "
2278 + p.verbatim_item() + '\n');
2281 case LATEX_BIB_ENVIRONMENT:
2282 p.verbatim_item(); // swallow next arg
2288 context.check_deeper(os);
2289 if (newlayout->keepempty) {
2290 // We need to start a new paragraph
2291 // even if it is empty.
2292 context.new_paragraph(os);
2293 context.check_layout(os);
2295 // handle known optional and required arguments
2296 if (context.layout->latextype == LATEX_ENVIRONMENT)
2297 output_arguments(os, p, outer, false, string(), context,
2298 context.layout->latexargs());
2299 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2301 output_arguments(oss, p, outer, false, string(), context,
2302 context.layout->latexargs());
2303 context.list_extra_stuff = oss.str();
2305 parse_text(p, os, FLAG_END, outer, context);
2306 if (context.layout->latextype == LATEX_ENVIRONMENT)
2307 output_arguments(os, p, outer, false, "post", context,
2308 context.layout->postcommandargs());
2309 context.check_end_layout(os);
2310 if (parent_context.deeper_paragraph) {
2311 // We must suppress the "end deeper" because we
2312 // suppressed the "begin deeper" above.
2313 context.need_end_deeper = false;
2315 context.check_end_deeper(os);
2316 parent_context.new_paragraph(os);
2318 if (!preamble.titleLayoutFound())
2319 preamble.titleLayoutFound(newlayout->intitle);
2320 set<string> const & req = newlayout->requires();
2321 set<string>::const_iterator it = req.begin();
2322 set<string>::const_iterator en = req.end();
2323 for (; it != en; ++it)
2324 preamble.registerAutomaticallyLoadedPackage(*it);
2328 // The single '=' is meant here.
2329 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2330 eat_whitespace(p, os, parent_context, false);
2331 parent_context.check_layout(os);
2332 begin_inset(os, "Flex ");
2333 docstring flex_name = newinsetlayout->name();
2334 // FIXME: what do we do if the prefix is not Flex: ?
2335 if (prefixIs(flex_name, from_ascii("Flex:")))
2336 flex_name.erase(0, 5);
2337 os << to_utf8(flex_name) << '\n'
2338 << "status collapsed\n";
2339 if (newinsetlayout->isPassThru()) {
2340 string const arg = p.verbatimEnvironment(name);
2341 Context context(true, parent_context.textclass,
2342 &parent_context.textclass.plainLayout(),
2343 parent_context.layout);
2344 output_ert(os, arg, parent_context);
2346 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2351 if (name == "appendix") {
2352 // This is no good latex style, but it works and is used in some documents...
2353 eat_whitespace(p, os, parent_context, false);
2354 parent_context.check_end_layout(os);
2355 Context context(true, parent_context.textclass, parent_context.layout,
2356 parent_context.layout, parent_context.font);
2357 context.check_layout(os);
2358 os << "\\start_of_appendix\n";
2359 parse_text(p, os, FLAG_END, outer, context);
2360 context.check_end_layout(os);
2365 if (known_environments.find(name) != known_environments.end()) {
2366 vector<ArgumentType> arguments = known_environments[name];
2367 // The last "argument" denotes wether we may translate the
2368 // environment contents to LyX
2369 // The default required if no argument is given makes us
2370 // compatible with the reLyXre environment.
2371 ArgumentType contents = arguments.empty() ?
2374 if (!arguments.empty())
2375 arguments.pop_back();
2376 // See comment in parse_unknown_environment()
2377 bool const specialfont =
2378 (parent_context.font != parent_context.normalfont);
2379 bool const new_layout_allowed =
2380 parent_context.new_layout_allowed;
2382 parent_context.new_layout_allowed = false;
2383 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2384 outer, parent_context);
2385 if (contents == verbatim)
2386 output_ert_inset(os, p.ertEnvironment(name),
2389 parse_text_snippet(p, os, FLAG_END, outer,
2391 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2393 parent_context.new_layout_allowed = new_layout_allowed;
2397 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2402 active_environments.pop_back();
2406 /// parses a comment and outputs it to \p os.
2407 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2408 bool skipNewlines = false)
2410 LASSERT(t.cat() == catComment, return);
2411 if (!t.cs().empty()) {
2412 context.check_layout(os);
2413 output_comment(p, os, t.cs(), context);
2414 if (p.next_token().cat() == catNewline) {
2415 // A newline after a comment line starts a new
2417 if (context.new_layout_allowed) {
2418 if(!context.atParagraphStart())
2419 // Only start a new paragraph if not already
2420 // done (we might get called recursively)
2421 context.new_paragraph(os);
2423 output_ert_inset(os, "\n", context);
2424 eat_whitespace(p, os, context, true);
2426 } else if (!skipNewlines) {
2427 // "%\n" combination
2434 * Reads spaces and comments until the first non-space, non-comment token.
2435 * New paragraphs (double newlines or \\par) are handled like simple spaces
2436 * if \p eatParagraph is true.
2437 * If \p eatNewline is false, newlines won't be treated as whitespace.
2438 * Spaces are skipped, but comments are written to \p os.
2440 void eat_whitespace(Parser & p, ostream & os, Context & context,
2441 bool eatParagraph, bool eatNewline)
2444 Token const & t = p.get_token();
2445 if (t.cat() == catComment)
2446 parse_comment(p, os, t, context, !eatNewline);
2447 else if ((!eatParagraph && p.isParagraph()) ||
2448 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2457 * Set a font attribute, parse text and reset the font attribute.
2458 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2459 * \param currentvalue Current value of the attribute. Is set to the new
2460 * value during parsing.
2461 * \param newvalue New value of the attribute
2463 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2464 Context & context, string const & attribute,
2465 string & currentvalue, string const & newvalue)
2467 context.check_layout(os);
2468 string const oldvalue = currentvalue;
2469 currentvalue = newvalue;
2470 os << '\n' << attribute << ' ' << newvalue << "\n";
2471 parse_text_snippet(p, os, flags, outer, context);
2472 context.check_layout(os);
2473 os << '\n' << attribute << ' ' << oldvalue << "\n";
2474 currentvalue = oldvalue;
2478 /// get the arguments of a natbib or jurabib citation command
2479 void get_cite_arguments(Parser & p, bool natbibOrder,
2480 string & before, string & after, bool const qualified = false)
2482 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2484 // text before the citation
2486 // text after the citation
2487 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2489 if (!after.empty()) {
2490 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2491 if (natbibOrder && !before.empty())
2492 swap(before, after);
2497 void copy_file(FileName const & src, string dstname)
2501 string const absParent = getParentFilePath(false);
2503 if (FileName::isAbsolute(dstname))
2504 dst = FileName(dstname);
2506 dst = makeAbsPath(dstname, absParent);
2507 FileName const srcpath = src.onlyPath();
2508 FileName const dstpath = dst.onlyPath();
2509 if (equivalent(srcpath, dstpath))
2511 if (!dstpath.isDirectory()) {
2512 if (!dstpath.createPath()) {
2513 cerr << "Warning: Could not create directory for file `"
2514 << dst.absFileName() << "´." << endl;
2518 if (dst.isReadableFile()) {
2519 if (overwriteFiles())
2520 cerr << "Warning: Overwriting existing file `"
2521 << dst.absFileName() << "´." << endl;
2523 cerr << "Warning: Not overwriting existing file `"
2524 << dst.absFileName() << "´." << endl;
2528 if (!src.copyTo(dst))
2529 cerr << "Warning: Could not copy file `" << src.absFileName()
2530 << "´ to `" << dst.absFileName() << "´." << endl;
2534 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2535 bool parse_chunk(Parser & p, ostream & os, Context & context)
2537 // check whether a chunk is possible here.
2538 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2544 // read the parameters
2545 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2546 if (!params.first) {
2551 Parser::Arg const code = p.verbatimStuff("\n@");
2556 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2557 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2561 // The last newline read is important for paragraph handling
2565 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2566 // We must have a valid layout before outputting the Chunk inset.
2567 context.check_layout(os);
2568 Context chunkcontext(true, context.textclass);
2569 chunkcontext.layout = &context.textclass.plainLayout();
2570 begin_inset(os, "Flex Chunk");
2571 os << "\nstatus open\n";
2572 if (!params.second.empty()) {
2573 chunkcontext.check_layout(os);
2574 Context paramscontext(true, context.textclass);
2575 paramscontext.layout = &context.textclass.plainLayout();
2576 begin_inset(os, "Argument 1");
2577 os << "\nstatus open\n";
2578 output_ert(os, params.second, paramscontext);
2581 output_ert(os, code.second, chunkcontext);
2589 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2590 bool is_macro(Parser & p)
2592 Token first = p.curr_token();
2593 if (first.cat() != catEscape || !p.good())
2595 if (first.cs() == "def")
2597 if (first.cs() != "global" && first.cs() != "long")
2599 Token second = p.get_token();
2601 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2602 second.cat() == catNewline || second.cat() == catComment)) {
2603 second = p.get_token();
2606 bool secondvalid = second.cat() == catEscape;
2608 bool thirdvalid = false;
2609 if (p.good() && first.cs() == "global" && secondvalid &&
2610 second.cs() == "long") {
2611 third = p.get_token();
2613 while (p.good() && !p.isParagraph() &&
2614 (third.cat() == catSpace ||
2615 third.cat() == catNewline ||
2616 third.cat() == catComment)) {
2617 third = p.get_token();
2620 thirdvalid = third.cat() == catEscape;
2622 for (int i = 0; i < pos; ++i)
2627 return (first.cs() == "global" || first.cs() == "long") &&
2628 second.cs() == "def";
2629 return first.cs() == "global" && second.cs() == "long" &&
2630 third.cs() == "def";
2634 /// Parse a macro definition (assumes that is_macro() returned true)
2635 void parse_macro(Parser & p, ostream & os, Context & context)
2637 context.check_layout(os);
2638 Token first = p.curr_token();
2641 string command = first.asInput();
2642 if (first.cs() != "def") {
2644 eat_whitespace(p, os, context, false);
2645 second = p.curr_token();
2646 command += second.asInput();
2647 if (second.cs() != "def") {
2649 eat_whitespace(p, os, context, false);
2650 third = p.curr_token();
2651 command += third.asInput();
2654 eat_whitespace(p, os, context, false);
2655 string const name = p.get_token().cs();
2656 eat_whitespace(p, os, context, false);
2662 while (p.next_token().cat() != catBegin) {
2663 if (p.next_token().cat() == catParameter) {
2668 // followed by number?
2669 if (p.next_token().cat() == catOther) {
2670 string s = p.get_token().asInput();
2672 // number = current arity + 1?
2673 if (s.size() == 1 && s[0] == arity + '0' + 1)
2678 paramtext += p.get_token().cs();
2680 paramtext += p.get_token().cs();
2685 // only output simple (i.e. compatible) macro as FormulaMacros
2686 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2688 context.check_layout(os);
2689 begin_inset(os, "FormulaMacro");
2690 os << "\n\\def" << ert;
2693 output_ert_inset(os, command + ert, context);
2697 void registerExternalTemplatePackages(string const & name)
2699 external::TemplateManager const & etm = external::TemplateManager::get();
2700 external::Template const * const et = etm.getTemplateByName(name);
2703 external::Template::Formats::const_iterator cit = et->formats.end();
2705 cit = et->formats.find("PDFLaTeX");
2706 if (cit == et->formats.end())
2707 // If the template has not specified a PDFLaTeX output,
2708 // we try the LaTeX format.
2709 cit = et->formats.find("LaTeX");
2710 if (cit == et->formats.end())
2712 vector<string>::const_iterator qit = cit->second.requirements.begin();
2713 vector<string>::const_iterator qend = cit->second.requirements.end();
2714 for (; qit != qend; ++qit)
2715 preamble.registerAutomaticallyLoadedPackage(*qit);
2718 } // anonymous namespace
2722 * Find a file with basename \p name in path \p path and an extension
2725 string find_file(string const & name, string const & path,
2726 char const * const * extensions)
2728 for (char const * const * what = extensions; *what; ++what) {
2729 string const trial = addExtension(name, *what);
2730 if (makeAbsPath(trial, path).exists())
2737 /// Convert filenames with TeX macros and/or quotes to something LyX
2739 string const normalize_filename(string const & name)
2744 Token const & t = p.get_token();
2745 if (t.cat() != catEscape)
2747 else if (t.cs() == "lyxdot") {
2748 // This is used by LyX for simple dots in relative
2752 } else if (t.cs() == "space") {
2755 } else if (t.cs() == "string") {
2756 // Convert \string" to " and \string~ to ~
2757 Token const & n = p.next_token();
2758 if (n.asInput() != "\"" && n.asInput() != "~")
2763 // Strip quotes. This is a bit complicated (see latex_path()).
2764 string full = os.str();
2765 if (!full.empty() && full[0] == '"') {
2766 string base = removeExtension(full);
2767 string ext = getExtension(full);
2768 if (!base.empty() && base[base.length()-1] == '"')
2771 return addExtension(trim(base, "\""), ext);
2772 if (full[full.length()-1] == '"')
2775 return trim(full, "\"");
2781 /// Convert \p name from TeX convention (relative to master file) to LyX
2782 /// convention (relative to .lyx file) if it is relative
2783 void fix_child_filename(string & name)
2785 string const absMasterTeX = getMasterFilePath(true);
2786 bool const isabs = FileName::isAbsolute(name);
2787 // convert from "relative to .tex master" to absolute original path
2789 name = makeAbsPath(name, absMasterTeX).absFileName();
2790 bool copyfile = copyFiles();
2791 string const absParentLyX = getParentFilePath(false);
2794 // convert from absolute original path to "relative to master file"
2795 string const rel = to_utf8(makeRelPath(from_utf8(name),
2796 from_utf8(absMasterTeX)));
2797 // re-interpret "relative to .tex file" as "relative to .lyx file"
2798 // (is different if the master .lyx file resides in a
2799 // different path than the master .tex file)
2800 string const absMasterLyX = getMasterFilePath(false);
2801 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2802 // Do not copy if the new path is impossible to create. Example:
2803 // absMasterTeX = "/foo/bar/"
2804 // absMasterLyX = "/bar/"
2805 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2806 if (contains(name, "/../"))
2813 // convert from absolute original path to
2814 // "relative to .lyx file"
2815 name = to_utf8(makeRelPath(from_utf8(abs),
2816 from_utf8(absParentLyX)));
2820 // convert from absolute original path to "relative to .lyx file"
2821 name = to_utf8(makeRelPath(from_utf8(name),
2822 from_utf8(absParentLyX)));
2827 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2828 Context & context, string const rdelim)
2830 Layout const * newlayout = 0;
2831 InsetLayout const * newinsetlayout = 0;
2832 char const * const * where = 0;
2833 // Store the latest bibliographystyle, addcontentslineContent and
2834 // nocite{*} option (needed for bibtex inset)
2836 string contentslineContent;
2837 // Some classes provide a \bibliographystyle, so do not output
2838 // any if none is explicitly set.
2839 string bibliographystyle;
2840 bool const use_natbib = isProvided("natbib");
2841 bool const use_jurabib = isProvided("jurabib");
2842 bool const use_biblatex = isProvided("biblatex")
2843 && preamble.citeEngine() != "biblatex-natbib";
2844 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2845 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2846 need_commentbib = use_biblatex || use_biblatex_natbib;
2849 // it is impossible to determine the correct encoding for non-CJK Japanese.
2850 // Therefore write a note at the beginning of the document
2851 if (is_nonCJKJapanese) {
2852 context.check_layout(os);
2853 begin_inset(os, "Note Note\n");
2854 os << "status open\n\\begin_layout Plain Layout\n"
2855 << "\\series bold\n"
2856 << "Important information:\n"
2857 << "\\end_layout\n\n"
2858 << "\\begin_layout Plain Layout\n"
2859 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2860 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2861 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2862 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2863 << " and specify the encoding using the -e command-line switch.\n"
2864 << " In addition, you might want to double check that the desired output encoding\n"
2865 << " is correctly selected in Document > Settings > Language.\n"
2866 << "\\end_layout\n";
2868 is_nonCJKJapanese = false;
2871 bool have_cycled = false;
2873 // Leave here only after at least one cycle
2874 if (have_cycled && flags & FLAG_LEAVE) {
2875 flags &= ~FLAG_LEAVE;
2879 Token const & t = p.get_token();
2881 debugToken(cerr, t, flags);
2884 if (flags & FLAG_ITEM) {
2885 if (t.cat() == catSpace)
2888 flags &= ~FLAG_ITEM;
2889 if (t.cat() == catBegin) {
2890 // skip the brace and collect everything to the next matching
2892 flags |= FLAG_BRACE_LAST;
2896 // handle only this single token, leave the loop if done
2897 flags |= FLAG_LEAVE;
2900 if (t.cat() != catEscape && t.character() == ']' &&
2901 (flags & FLAG_BRACK_LAST))
2903 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2905 string tok = t.asInput();
2906 // we only support delimiters with max 2 chars for now.
2907 if (rdelim.size() > 1)
2908 tok += p.next_token().asInput();
2909 if (t.cat() != catEscape && !rdelim.empty()
2910 && tok == rdelim && (flags & FLAG_RDELIM)) {
2911 if (rdelim.size() > 1)
2912 p.get_token(); // eat rdelim
2916 // If there is anything between \end{env} and \begin{env} we
2917 // don't need to output a separator.
2918 if (t.cat() != catSpace && t.cat() != catNewline &&
2919 t.asInput() != "\\begin")
2926 bool const starred = p.next_token().asInput() == "*";
2927 string const starredname(starred ? (t.cs() + '*') : t.cs());
2928 if (t.cat() == catMath) {
2929 // we are inside some text mode thingy, so opening new math is allowed
2930 context.check_layout(os);
2931 begin_inset(os, "Formula ");
2932 Token const & n = p.get_token();
2933 bool const display(n.cat() == catMath && outer);
2935 // TeX's $$...$$ syntax for displayed math
2937 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2939 p.get_token(); // skip the second '$' token
2941 // simple $...$ stuff
2944 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2949 // Prevent the conversion of a line break to a
2950 // space (bug 7668). This does not change the
2951 // output, but looks ugly in LyX.
2952 eat_whitespace(p, os, context, false);
2957 if (t.cat() == catSuper || t.cat() == catSub) {
2958 cerr << "catcode " << t << " illegal in text mode\n";
2962 // Basic support for quotes. We try to disambiguate
2963 // quotes from the context (e.g., a left english quote is
2964 // the same as a right german quote...).
2965 // Try to make a smart guess about the side
2966 Token const prev = p.prev_token();
2967 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2968 && prev.character() != '\n' && prev.character() != '~');
2969 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2970 context.check_layout(os);
2971 begin_inset(os, "Quotes ");
2972 os << guessQuoteStyle("eld", opening);
2978 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2979 context.check_layout(os);
2980 begin_inset(os, "Quotes ");
2981 os << guessQuoteStyle("erd", opening);
2988 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2989 context.check_layout(os);
2990 begin_inset(os, "Quotes ");
2991 os << guessQuoteStyle("ald", opening);
2998 if (t.asInput() == "<"
2999 && p.next_token().asInput() == "<") {
3000 bool has_chunk = false;
3004 has_chunk = parse_chunk(p, os, context);
3010 context.check_layout(os);
3011 begin_inset(os, "Quotes ");
3012 os << guessQuoteStyle("ard", opening);
3020 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3021 check_space(p, os, context);
3025 // babel shorthands (also used by polyglossia)
3026 // Since these can have different meanings for different languages
3027 // we import them as ERT (but they must be put in ERT to get output
3029 if (t.asInput() == "\"") {
3031 // These are known pairs. We put them together in
3032 // one ERT inset. In other cases (such as "a), only
3033 // the quotation mark is ERTed.
3034 if (p.next_token().asInput() == "\""
3035 || p.next_token().asInput() == "|"
3036 || p.next_token().asInput() == "-"
3037 || p.next_token().asInput() == "~"
3038 || p.next_token().asInput() == "="
3039 || p.next_token().asInput() == "/"
3040 || p.next_token().asInput() == "~"
3041 || p.next_token().asInput() == "'"
3042 || p.next_token().asInput() == "`"
3043 || p.next_token().asInput() == "<"
3044 || p.next_token().asInput() == ">") {
3045 s += p.next_token().asInput();
3048 output_ert_inset(os, s, context);
3052 if (t.character() == '[' && noweb_mode &&
3053 p.next_token().character() == '[') {
3054 // These can contain underscores
3056 string const s = p.getFullOpt() + ']';
3057 if (p.next_token().character() == ']')
3060 cerr << "Warning: Inserting missing ']' in '"
3061 << s << "'." << endl;
3062 output_ert_inset(os, s, context);
3066 if (t.cat() == catLetter) {
3067 context.check_layout(os);
3072 if (t.cat() == catOther ||
3073 t.cat() == catAlign ||
3074 t.cat() == catParameter) {
3075 context.check_layout(os);
3076 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3077 context.merging_hyphens_allowed &&
3078 context.font.family != "ttfamily" &&
3079 !context.layout->pass_thru) {
3080 if (p.next_next_token().asInput() == "-") {
3082 os << to_utf8(docstring(1, 0x2014));
3086 os << to_utf8(docstring(1, 0x2013));
3089 // This translates "&" to "\\&" which may be wrong...
3094 if (p.isParagraph()) {
3095 // In minted floating listings we will collect
3096 // everything into the caption, where multiple
3097 // paragraphs are forbidden.
3098 if (minted_float.empty()) {
3099 if (context.new_layout_allowed)
3100 context.new_paragraph(os);
3102 output_ert_inset(os, "\\par ", context);
3105 eat_whitespace(p, os, context, true);
3109 if (t.cat() == catActive) {
3110 context.check_layout(os);
3111 if (t.character() == '~') {
3112 if (context.layout->free_spacing)
3115 begin_inset(os, "space ~\n");
3123 if (t.cat() == catBegin) {
3124 Token const next = p.next_token();
3125 Token const end = p.next_next_token();
3126 if (next.cat() == catEnd) {
3128 Token const prev = p.prev_token();
3130 if (p.next_token().character() == '`')
3131 ; // ignore it in {}``
3133 output_ert_inset(os, "{}", context);
3134 } else if (next.cat() == catEscape &&
3135 is_known(next.cs(), known_quotes) &&
3136 end.cat() == catEnd) {
3137 // Something like {\textquoteright} (e.g.
3138 // from writer2latex). We may skip the
3139 // braces here for better readability.
3140 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3142 } else if (p.next_token().asInput() == "\\ascii") {
3143 // handle the \ascii characters
3144 // (the case without braces is handled later)
3145 // the code is "{\ascii\xxx}"
3146 p.get_token(); // eat \ascii
3147 string name2 = p.get_token().asInput();
3148 p.get_token(); // eat the final '}'
3149 string const name = "{\\ascii" + name2 + "}";
3153 // get the character from unicodesymbols
3154 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3155 Encodings::TEXT_CMD, termination, rem, &req);
3157 context.check_layout(os);
3160 output_ert_inset(os,
3161 to_utf8(rem), context);
3162 for (set<string>::const_iterator it = req.begin();
3163 it != req.end(); ++it)
3164 preamble.registerAutomaticallyLoadedPackage(*it);
3166 // we did not find a non-ert version
3167 output_ert_inset(os, name, context);
3169 context.check_layout(os);
3170 // special handling of font attribute changes
3171 Token const prev = p.prev_token();
3172 TeXFont const oldFont = context.font;
3173 if (next.character() == '[' ||
3174 next.character() == ']' ||
3175 next.character() == '*') {
3177 if (p.next_token().cat() == catEnd) {
3182 output_ert_inset(os, "{", context);
3183 parse_text_snippet(p, os,
3186 output_ert_inset(os, "}", context);
3188 } else if (! context.new_layout_allowed) {
3189 output_ert_inset(os, "{", context);
3190 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3192 output_ert_inset(os, "}", context);
3193 } else if (is_known(next.cs(), known_sizes)) {
3194 // next will change the size, so we must
3196 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3198 if (!context.atParagraphStart())
3200 << context.font.size << "\n";
3201 } else if (is_known(next.cs(), known_font_families)) {
3202 // next will change the font family, so we
3203 // must reset it here
3204 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3206 if (!context.atParagraphStart())
3208 << context.font.family << "\n";
3209 } else if (is_known(next.cs(), known_font_series)) {
3210 // next will change the font series, so we
3211 // must reset it here
3212 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3214 if (!context.atParagraphStart())
3216 << context.font.series << "\n";
3217 } else if (is_known(next.cs(), known_font_shapes)) {
3218 // next will change the font shape, so we
3219 // must reset it here
3220 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3222 if (!context.atParagraphStart())
3224 << context.font.shape << "\n";
3225 } else if (is_known(next.cs(), known_old_font_families) ||
3226 is_known(next.cs(), known_old_font_series) ||
3227 is_known(next.cs(), known_old_font_shapes)) {
3228 // next will change the font family, series
3229 // and shape, so we must reset it here
3230 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3232 if (!context.atParagraphStart())
3234 << context.font.family
3236 << context.font.series
3238 << context.font.shape << "\n";
3240 output_ert_inset(os, "{", context);
3241 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3243 output_ert_inset(os, "}", context);
3249 if (t.cat() == catEnd) {
3250 if (flags & FLAG_BRACE_LAST) {
3253 cerr << "stray '}' in text\n";
3254 output_ert_inset(os, "}", context);
3258 if (t.cat() == catComment) {
3259 parse_comment(p, os, t, context);
3264 // control sequences
3267 if (t.cs() == "(" || t.cs() == "[") {
3268 bool const simple = t.cs() == "(";
3269 context.check_layout(os);
3270 begin_inset(os, "Formula");
3271 os << " \\" << t.cs();
3272 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3273 os << '\\' << (simple ? ')' : ']');
3276 // Prevent the conversion of a line break to a
3277 // space (bug 7668). This does not change the
3278 // output, but looks ugly in LyX.
3279 eat_whitespace(p, os, context, false);
3284 if (t.cs() == "begin") {
3285 parse_environment(p, os, outer, last_env,
3290 if (t.cs() == "end") {
3291 if (flags & FLAG_END) {
3292 // eat environment name
3293 string const name = p.getArg('{', '}');
3294 if (name != active_environment())
3295 cerr << "\\end{" + name + "} does not match \\begin{"
3296 + active_environment() + "}\n";
3299 p.error("found 'end' unexpectedly");
3303 // "item" by default, but could be something else
3304 if (t.cs() == context.layout->itemcommand()) {
3306 if (context.layout->labeltype == LABEL_MANUAL) {
3307 // FIXME: This swallows comments, but we cannot use
3308 // eat_whitespace() since we must not output
3309 // anything before the item.
3310 p.skip_spaces(true);
3311 s = p.verbatimOption();
3313 p.skip_spaces(false);
3315 context.check_layout(os);
3316 if (context.has_item) {
3317 // An item in an unknown list-like environment
3318 // FIXME: Do this in check_layout()!
3319 context.has_item = false;
3320 string item = "\\" + context.layout->itemcommand();
3323 output_ert_inset(os, item, context);
3325 if (context.layout->labeltype != LABEL_MANUAL)
3326 output_arguments(os, p, outer, false, "item", context,
3327 context.layout->itemargs());
3328 if (!context.list_extra_stuff.empty()) {
3329 os << context.list_extra_stuff;
3330 context.list_extra_stuff.clear();
3332 else if (!s.empty()) {
3333 // LyX adds braces around the argument,
3334 // so we need to remove them here.
3335 if (s.size() > 2 && s[0] == '{' &&
3336 s[s.size()-1] == '}')
3337 s = s.substr(1, s.size()-2);
3338 // If the argument contains a space we
3339 // must put it into ERT: Otherwise LyX
3340 // would misinterpret the space as
3341 // item delimiter (bug 7663)
3342 if (contains(s, ' ')) {
3343 output_ert_inset(os, s, context);
3346 os << parse_text_snippet(p2,
3347 FLAG_BRACK_LAST, outer, context);
3349 // The space is needed to separate the
3350 // item from the rest of the sentence.
3352 eat_whitespace(p, os, context, false);
3357 if (t.cs() == "bibitem") {
3359 context.check_layout(os);
3360 eat_whitespace(p, os, context, false);
3361 string label = p.verbatimOption();
3362 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3363 bool const literal = !lbl.first;
3364 label = literal ? subst(label, "\n", " ") : lbl.second;
3365 string lit = literal ? "\"true\"" : "\"false\"";
3366 string key = convert_literate_command_inset_arg(p.verbatim_item());
3367 begin_command_inset(os, "bibitem", "bibitem");
3368 os << "label \"" << label << "\"\n"
3369 << "key \"" << key << "\"\n"
3370 << "literal " << lit << "\n";
3376 // catch the case of \def\inputGnumericTable
3378 if (t.cs() == "def") {
3379 Token second = p.next_token();
3380 if (second.cs() == "inputGnumericTable") {
3384 Token third = p.get_token();
3386 if (third.cs() == "input") {
3390 string name = normalize_filename(p.verbatim_item());
3391 string const path = getMasterFilePath(true);
3392 // We want to preserve relative / absolute filenames,
3393 // therefore path is only used for testing
3394 // The file extension is in every case ".tex".
3395 // So we need to remove this extension and check for
3396 // the original one.
3397 name = removeExtension(name);
3398 if (!makeAbsPath(name, path).exists()) {
3399 char const * const Gnumeric_formats[] = {"gnumeric",
3401 string const Gnumeric_name =
3402 find_file(name, path, Gnumeric_formats);
3403 if (!Gnumeric_name.empty())
3404 name = Gnumeric_name;
3406 FileName const absname = makeAbsPath(name, path);
3407 if (absname.exists()) {
3408 fix_child_filename(name);
3409 copy_file(absname, name);
3411 cerr << "Warning: Could not find file '"
3412 << name << "'." << endl;
3413 context.check_layout(os);
3414 begin_inset(os, "External\n\ttemplate ");
3415 os << "GnumericSpreadsheet\n\tfilename "
3418 context.check_layout(os);
3420 // register the packages that are automatically loaded
3421 // by the Gnumeric template
3422 registerExternalTemplatePackages("GnumericSpreadsheet");
3427 parse_macro(p, os, context);
3431 if (t.cs() == "noindent") {
3433 context.add_par_extra_stuff("\\noindent\n");
3437 if (t.cs() == "appendix") {
3438 context.add_par_extra_stuff("\\start_of_appendix\n");
3439 // We need to start a new paragraph. Otherwise the
3440 // appendix in 'bla\appendix\chapter{' would start
3442 context.new_paragraph(os);
3443 // We need to make sure that the paragraph is
3444 // generated even if it is empty. Otherwise the
3445 // appendix in '\par\appendix\par\chapter{' would
3447 context.check_layout(os);
3448 // FIXME: This is a hack to prevent paragraph
3449 // deletion if it is empty. Handle this better!
3450 output_comment(p, os,
3451 "dummy comment inserted by tex2lyx to "
3452 "ensure that this paragraph is not empty",
3454 // Both measures above may generate an additional
3455 // empty paragraph, but that does not hurt, because
3456 // whitespace does not matter here.
3457 eat_whitespace(p, os, context, true);
3461 // Must catch empty dates before findLayout is called below
3462 if (t.cs() == "date") {
3463 eat_whitespace(p, os, context, false);
3465 string const date = p.verbatim_item();
3468 preamble.suppressDate(true);
3471 preamble.suppressDate(false);
3472 if (context.new_layout_allowed &&
3473 (newlayout = findLayout(context.textclass,
3476 output_command_layout(os, p, outer,
3477 context, newlayout);
3478 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3479 if (!preamble.titleLayoutFound())
3480 preamble.titleLayoutFound(newlayout->intitle);
3481 set<string> const & req = newlayout->requires();
3482 set<string>::const_iterator it = req.begin();
3483 set<string>::const_iterator en = req.end();
3484 for (; it != en; ++it)
3485 preamble.registerAutomaticallyLoadedPackage(*it);
3487 output_ert_inset(os,
3488 "\\date{" + p.verbatim_item() + '}',
3494 // Before we look for the layout name with star and alone below, we check the layouts including
3495 // the LateXParam, which might be one or several options or a star.
3496 // The single '=' is meant here.
3497 if (context.new_layout_allowed &&
3498 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3499 // store the latexparam here. This is eaten in output_command_layout
3500 context.latexparam = newlayout->latexparam();
3502 output_command_layout(os, p, outer, context, newlayout);
3503 context.latexparam.clear();
3505 if (!preamble.titleLayoutFound())
3506 preamble.titleLayoutFound(newlayout->intitle);
3507 set<string> const & req = newlayout->requires();
3508 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3509 preamble.registerAutomaticallyLoadedPackage(*it);
3513 // Starred section headings
3514 // Must attempt to parse "Section*" before "Section".
3515 if ((p.next_token().asInput() == "*") &&
3516 context.new_layout_allowed &&
3517 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3520 output_command_layout(os, p, outer, context, newlayout);
3522 if (!preamble.titleLayoutFound())
3523 preamble.titleLayoutFound(newlayout->intitle);
3524 set<string> const & req = newlayout->requires();
3525 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3526 preamble.registerAutomaticallyLoadedPackage(*it);
3530 // Section headings and the like
3531 if (context.new_layout_allowed &&
3532 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3534 output_command_layout(os, p, outer, context, newlayout);
3536 if (!preamble.titleLayoutFound())
3537 preamble.titleLayoutFound(newlayout->intitle);
3538 set<string> const & req = newlayout->requires();
3539 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3540 preamble.registerAutomaticallyLoadedPackage(*it);
3544 if (t.cs() == "subfloat") {
3545 // the syntax is \subfloat[list entry][sub caption]{content}
3546 // if it is a table of figure depends on the surrounding float
3548 // do nothing if there is no outer float
3549 if (!float_type.empty()) {
3550 context.check_layout(os);
3552 begin_inset(os, "Float " + float_type + "\n");
3554 << "\nsideways false"
3555 << "\nstatus collapsed\n\n";
3558 bool has_caption = false;
3559 if (p.next_token().cat() != catEscape &&
3560 p.next_token().character() == '[') {
3561 p.get_token(); // eat '['
3562 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3565 // In case we have two optional args, the second is the caption.
3566 if (p.next_token().cat() != catEscape &&
3567 p.next_token().character() == '[') {
3568 p.get_token(); // eat '['
3569 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3572 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3573 // the caption comes always as the last
3575 // we must make sure that the caption gets a \begin_layout
3576 os << "\n\\begin_layout Plain Layout";
3578 begin_inset(os, "Caption Standard\n");
3579 Context newcontext(true, context.textclass,
3580 0, 0, context.font);
3581 newcontext.check_layout(os);
3582 os << caption << "\n";
3583 newcontext.check_end_layout(os);
3586 // close the layout we opened
3587 os << "\n\\end_layout";
3592 // if the float type is not supported or there is no surrounding float
3597 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3599 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3601 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3602 + "{" + p.verbatim_item() + '}', context);
3607 if (t.cs() == "xymatrix") {
3608 // we must open a new math because LyX's xy support is in math
3609 context.check_layout(os);
3610 begin_inset(os, "Formula ");
3612 os << "\\" << t.cs() << '{';
3613 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3616 preamble.registerAutomaticallyLoadedPackage("xy");
3620 if (t.cs() == "includegraphics") {
3621 bool const clip = p.next_token().asInput() == "*";
3624 string const arg = p.getArg('[', ']');
3625 map<string, string> opts;
3626 vector<string> keys;
3627 split_map(arg, opts, keys);
3629 opts["clip"] = string();
3630 string name = normalize_filename(p.verbatim_item());
3632 string const path = getMasterFilePath(true);
3633 // We want to preserve relative / absolute filenames,
3634 // therefore path is only used for testing
3635 if (!makeAbsPath(name, path).exists()) {
3636 // The file extension is probably missing.
3637 // Now try to find it out.
3638 string const dvips_name =
3639 find_file(name, path,
3640 known_dvips_graphics_formats);
3641 string const pdftex_name =
3642 find_file(name, path,
3643 known_pdftex_graphics_formats);
3644 if (!dvips_name.empty()) {
3645 if (!pdftex_name.empty()) {
3646 cerr << "This file contains the "
3648 "\"\\includegraphics{"
3650 "However, files\n\""
3651 << dvips_name << "\" and\n\""
3652 << pdftex_name << "\"\n"
3653 "both exist, so I had to make a "
3654 "choice and took the first one.\n"
3655 "Please move the unwanted one "
3656 "someplace else and try again\n"
3657 "if my choice was wrong."
3661 } else if (!pdftex_name.empty()) {
3667 FileName const absname = makeAbsPath(name, path);
3668 if (absname.exists()) {
3669 fix_child_filename(name);
3670 copy_file(absname, name);
3672 cerr << "Warning: Could not find graphics file '"
3673 << name << "'." << endl;
3675 context.check_layout(os);
3676 begin_inset(os, "Graphics ");
3677 os << "\n\tfilename " << name << '\n';
3678 if (opts.find("width") != opts.end())
3680 << translate_len(opts["width"]) << '\n';
3681 if (opts.find("height") != opts.end())
3683 << translate_len(opts["height"]) << '\n';
3684 if (opts.find("scale") != opts.end()) {
3685 istringstream iss(opts["scale"]);
3689 os << "\tscale " << val << '\n';
3691 if (opts.find("angle") != opts.end()) {
3692 os << "\trotateAngle "
3693 << opts["angle"] << '\n';
3694 vector<string>::const_iterator a =
3695 find(keys.begin(), keys.end(), "angle");
3696 vector<string>::const_iterator s =
3697 find(keys.begin(), keys.end(), "width");
3698 if (s == keys.end())
3699 s = find(keys.begin(), keys.end(), "height");
3700 if (s == keys.end())
3701 s = find(keys.begin(), keys.end(), "scale");
3702 if (s != keys.end() && distance(s, a) > 0)
3703 os << "\tscaleBeforeRotation\n";
3705 if (opts.find("origin") != opts.end()) {
3707 string const opt = opts["origin"];
3708 if (opt.find('l') != string::npos) ss << "left";
3709 if (opt.find('r') != string::npos) ss << "right";
3710 if (opt.find('c') != string::npos) ss << "center";
3711 if (opt.find('t') != string::npos) ss << "Top";
3712 if (opt.find('b') != string::npos) ss << "Bottom";
3713 if (opt.find('B') != string::npos) ss << "Baseline";
3714 if (!ss.str().empty())
3715 os << "\trotateOrigin " << ss.str() << '\n';
3717 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3719 if (opts.find("keepaspectratio") != opts.end())
3720 os << "\tkeepAspectRatio\n";
3721 if (opts.find("clip") != opts.end())
3723 if (opts.find("draft") != opts.end())
3725 if (opts.find("bb") != opts.end())
3726 os << "\tBoundingBox "
3727 << opts["bb"] << '\n';
3728 int numberOfbbOptions = 0;
3729 if (opts.find("bbllx") != opts.end())
3730 numberOfbbOptions++;
3731 if (opts.find("bblly") != opts.end())
3732 numberOfbbOptions++;
3733 if (opts.find("bburx") != opts.end())
3734 numberOfbbOptions++;
3735 if (opts.find("bbury") != opts.end())
3736 numberOfbbOptions++;
3737 if (numberOfbbOptions == 4)
3738 os << "\tBoundingBox "
3739 << opts["bbllx"] << " " << opts["bblly"] << " "
3740 << opts["bburx"] << " " << opts["bbury"] << '\n';
3741 else if (numberOfbbOptions > 0)
3742 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3743 numberOfbbOptions = 0;
3744 if (opts.find("natwidth") != opts.end())
3745 numberOfbbOptions++;
3746 if (opts.find("natheight") != opts.end())
3747 numberOfbbOptions++;
3748 if (numberOfbbOptions == 2)
3749 os << "\tBoundingBox 0bp 0bp "
3750 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3751 else if (numberOfbbOptions > 0)
3752 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3753 ostringstream special;
3754 if (opts.find("hiresbb") != opts.end())
3755 special << "hiresbb,";
3756 if (opts.find("trim") != opts.end())
3758 if (opts.find("viewport") != opts.end())
3759 special << "viewport=" << opts["viewport"] << ',';
3760 if (opts.find("totalheight") != opts.end())
3761 special << "totalheight=" << opts["totalheight"] << ',';
3762 if (opts.find("type") != opts.end())
3763 special << "type=" << opts["type"] << ',';
3764 if (opts.find("ext") != opts.end())
3765 special << "ext=" << opts["ext"] << ',';
3766 if (opts.find("read") != opts.end())
3767 special << "read=" << opts["read"] << ',';
3768 if (opts.find("command") != opts.end())
3769 special << "command=" << opts["command"] << ',';
3770 string s_special = special.str();
3771 if (!s_special.empty()) {
3772 // We had special arguments. Remove the trailing ','.
3773 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3775 // TODO: Handle the unknown settings better.
3776 // Warn about invalid options.
3777 // Check whether some option was given twice.
3779 preamble.registerAutomaticallyLoadedPackage("graphicx");
3783 if (t.cs() == "footnote" ||
3784 (t.cs() == "thanks" && context.layout->intitle)) {
3786 context.check_layout(os);
3787 begin_inset(os, "Foot\n");
3788 os << "status collapsed\n\n";
3789 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3794 if (t.cs() == "marginpar") {
3796 context.check_layout(os);
3797 begin_inset(os, "Marginal\n");
3798 os << "status collapsed\n\n";
3799 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3804 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3805 bool const use_minted = t.cs() == "mintinline";
3807 parse_listings(p, os, context, true, use_minted);
3811 if (t.cs() == "ensuremath") {
3813 context.check_layout(os);
3814 string const s = p.verbatim_item();
3815 //FIXME: this never triggers in UTF8
3816 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3819 output_ert_inset(os, "\\ensuremath{" + s + "}",
3824 else if (t.cs() == "makeindex"
3825 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3826 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3827 if (preamble.titleLayoutFound()) {
3829 skip_spaces_braces(p);
3831 output_ert_inset(os, t.asInput(), context);
3835 if (t.cs() == "tableofcontents"
3836 || t.cs() == "lstlistoflistings"
3837 || t.cs() == "listoflistings") {
3838 string name = t.cs();
3839 if (preamble.minted() && name == "listoflistings")
3840 name.insert(0, "lst");
3841 context.check_layout(os);
3842 begin_command_inset(os, "toc", name);
3844 skip_spaces_braces(p);
3845 if (name == "lstlistoflistings") {
3846 if (preamble.minted())
3847 preamble.registerAutomaticallyLoadedPackage("minted");
3849 preamble.registerAutomaticallyLoadedPackage("listings");
3854 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3855 context.check_layout(os);
3856 if (t.cs() == "listoffigures")
3857 begin_inset(os, "FloatList figure\n");
3859 begin_inset(os, "FloatList table\n");
3861 skip_spaces_braces(p);
3865 if (t.cs() == "listof") {
3866 p.skip_spaces(true);
3867 string const name = p.get_token().cs();
3868 if (context.textclass.floats().typeExist(name)) {
3869 context.check_layout(os);
3870 begin_inset(os, "FloatList ");
3873 p.get_token(); // swallow second arg
3875 output_ert_inset(os, "\\listof{" + name + "}", context);
3879 if ((where = is_known(t.cs(), known_text_font_families))) {
3880 parse_text_attributes(p, os, FLAG_ITEM, outer,
3881 context, "\\family", context.font.family,
3882 known_coded_font_families[where - known_text_font_families]);
3886 // beamer has a \textbf<overlay>{} inset
3887 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3888 parse_text_attributes(p, os, FLAG_ITEM, outer,
3889 context, "\\series", context.font.series,
3890 known_coded_font_series[where - known_text_font_series]);
3894 // beamer has a \textit<overlay>{} inset
3895 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3896 parse_text_attributes(p, os, FLAG_ITEM, outer,
3897 context, "\\shape", context.font.shape,
3898 known_coded_font_shapes[where - known_text_font_shapes]);
3902 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3903 context.check_layout(os);
3904 TeXFont oldFont = context.font;
3905 context.font.init();
3906 context.font.size = oldFont.size;
3907 os << "\n\\family " << context.font.family << "\n";
3908 os << "\n\\series " << context.font.series << "\n";
3909 os << "\n\\shape " << context.font.shape << "\n";
3910 if (t.cs() == "textnormal") {
3911 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3912 output_font_change(os, context.font, oldFont);
3913 context.font = oldFont;
3915 eat_whitespace(p, os, context, false);
3919 if (t.cs() == "textcolor") {
3920 // scheme is \textcolor{color name}{text}
3921 string const color = p.verbatim_item();
3922 // we support the predefined colors of the color and the xcolor package
3923 if (color == "black" || color == "blue" || color == "cyan"
3924 || color == "green" || color == "magenta" || color == "red"
3925 || color == "white" || color == "yellow") {
3926 context.check_layout(os);
3927 os << "\n\\color " << color << "\n";
3928 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3929 context.check_layout(os);
3930 os << "\n\\color inherit\n";
3931 preamble.registerAutomaticallyLoadedPackage("color");
3932 } else if (color == "brown" || color == "darkgray" || color == "gray"
3933 || color == "lightgray" || color == "lime" || color == "olive"
3934 || color == "orange" || color == "pink" || color == "purple"
3935 || color == "teal" || color == "violet") {
3936 context.check_layout(os);
3937 os << "\n\\color " << color << "\n";
3938 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3939 context.check_layout(os);
3940 os << "\n\\color inherit\n";
3941 preamble.registerAutomaticallyLoadedPackage("xcolor");
3943 // for custom defined colors
3944 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3948 if (t.cs() == "underbar" || t.cs() == "uline") {
3949 // \underbar is not 100% correct (LyX outputs \uline
3950 // of ulem.sty). The difference is that \ulem allows
3951 // line breaks, and \underbar does not.
3952 // Do NOT handle \underline.
3953 // \underbar cuts through y, g, q, p etc.,
3954 // \underline does not.
3955 context.check_layout(os);
3956 os << "\n\\bar under\n";
3957 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3958 context.check_layout(os);
3959 os << "\n\\bar default\n";
3960 preamble.registerAutomaticallyLoadedPackage("ulem");
3964 if (t.cs() == "sout") {
3965 context.check_layout(os);
3966 os << "\n\\strikeout on\n";
3967 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3968 context.check_layout(os);
3969 os << "\n\\strikeout default\n";
3970 preamble.registerAutomaticallyLoadedPackage("ulem");
3974 // beamer has an \emph<overlay>{} inset
3975 if ((t.cs() == "uuline" || t.cs() == "uwave"
3976 || t.cs() == "emph" || t.cs() == "noun"
3977 || t.cs() == "xout") && !p.hasOpt("<")) {
3978 context.check_layout(os);
3979 os << "\n\\" << t.cs() << " on\n";
3980 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3981 context.check_layout(os);
3982 os << "\n\\" << t.cs() << " default\n";
3983 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3984 preamble.registerAutomaticallyLoadedPackage("ulem");
3988 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3989 context.check_layout(os);
3990 string name = p.getArg('{', '}');
3991 string localtime = p.getArg('{', '}');
3992 preamble.registerAuthor(name);
3993 Author const & author = preamble.getAuthor(name);
3994 // from_asctime_utc() will fail if LyX decides to output the
3995 // time in the text language.
3996 time_t ptime = from_asctime_utc(localtime);
3997 if (ptime == static_cast<time_t>(-1)) {
3998 cerr << "Warning: Could not parse time `" << localtime
3999 << "´ for change tracking, using current time instead.\n";
4000 ptime = current_time();
4002 if (t.cs() == "lyxadded")
4003 os << "\n\\change_inserted ";
4005 os << "\n\\change_deleted ";
4006 os << author.bufferId() << ' ' << ptime << '\n';
4007 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4008 bool dvipost = LaTeXPackages::isAvailable("dvipost");
4009 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4010 LaTeXPackages::isAvailable("xcolor");
4011 // No need to test for luatex, since luatex comes in
4012 // two flavours (dvi and pdf), like latex, and those
4013 // are detected by pdflatex.
4014 if (pdflatex || xetex) {
4016 preamble.registerAutomaticallyLoadedPackage("ulem");
4017 preamble.registerAutomaticallyLoadedPackage("xcolor");
4018 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4022 preamble.registerAutomaticallyLoadedPackage("dvipost");
4023 } else if (xcolorulem) {
4024 preamble.registerAutomaticallyLoadedPackage("ulem");
4025 preamble.registerAutomaticallyLoadedPackage("xcolor");
4031 if (t.cs() == "textipa") {
4032 context.check_layout(os);
4033 begin_inset(os, "IPA\n");
4034 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4035 context.merging_hyphens_allowed = false;
4036 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4037 context.merging_hyphens_allowed = merging_hyphens_allowed;
4039 preamble.registerAutomaticallyLoadedPackage("tipa");
4040 preamble.registerAutomaticallyLoadedPackage("tipx");
4044 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4045 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4046 context.check_layout(os);
4050 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4051 begin_inset(os, "IPADeco " + type + "\n");
4052 os << "status open\n";
4053 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4059 if (t.cs() == "textvertline") {
4060 // FIXME: This is not correct, \textvertline is higher than |
4066 if (t.cs() == "tone" ) {
4067 context.check_layout(os);
4068 // register the tone package
4069 preamble.registerAutomaticallyLoadedPackage("tone");
4070 string content = trimSpaceAndEol(p.verbatim_item());
4071 string command = t.asInput() + "{" + content + "}";
4072 // some tones can be detected by unicodesymbols, some need special code
4073 if (is_known(content, known_tones)) {
4074 os << "\\IPAChar " << command << "\n";
4077 // try to see whether the string is in unicodesymbols
4081 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4082 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4083 termination, rem, &req);
4087 output_ert_inset(os, to_utf8(rem), context);
4088 for (set<string>::const_iterator it = req.begin();
4089 it != req.end(); ++it)
4090 preamble.registerAutomaticallyLoadedPackage(*it);
4092 // we did not find a non-ert version
4093 output_ert_inset(os, command, context);
4097 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4098 t.cs() == "vphantom") {
4099 context.check_layout(os);
4100 if (t.cs() == "phantom")
4101 begin_inset(os, "Phantom Phantom\n");
4102 if (t.cs() == "hphantom")
4103 begin_inset(os, "Phantom HPhantom\n");
4104 if (t.cs() == "vphantom")
4105 begin_inset(os, "Phantom VPhantom\n");
4106 os << "status open\n";
4107 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4113 if (t.cs() == "href") {
4114 context.check_layout(os);
4115 string target = convert_literate_command_inset_arg(p.verbatim_item());
4116 string name = p.verbatim_item();
4117 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4118 bool const literal = !nm.first;
4119 name = literal ? subst(name, "\n", " ") : nm.second;
4120 string lit = literal ? "\"true\"" : "\"false\"";
4122 size_t i = target.find(':');
4123 if (i != string::npos) {
4124 type = target.substr(0, i + 1);
4125 if (type == "mailto:" || type == "file:")
4126 target = target.substr(i + 1);
4127 // handle the case that name is equal to target, except of "http(s)://"
4128 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4131 begin_command_inset(os, "href", "href");
4133 os << "name \"" << name << "\"\n";
4134 os << "target \"" << target << "\"\n";
4135 if (type == "mailto:" || type == "file:")
4136 os << "type \"" << type << "\"\n";
4137 os << "literal " << lit << "\n";
4139 skip_spaces_braces(p);
4143 if (t.cs() == "lyxline") {
4144 // swallow size argument (it is not used anyway)
4146 if (!context.atParagraphStart()) {
4147 // so our line is in the middle of a paragraph
4148 // we need to add a new line, lest this line
4149 // follow the other content on that line and
4150 // run off the side of the page
4151 // FIXME: This may create an empty paragraph,
4152 // but without that it would not be
4153 // possible to set noindent below.
4154 // Fortunately LaTeX does not care
4155 // about the empty paragraph.
4156 context.new_paragraph(os);
4158 if (preamble.indentParagraphs()) {
4159 // we need to unindent, lest the line be too long
4160 context.add_par_extra_stuff("\\noindent\n");
4162 context.check_layout(os);
4163 begin_command_inset(os, "line", "rule");
4164 os << "offset \"0.5ex\"\n"
4165 "width \"100line%\"\n"
4171 if (t.cs() == "rule") {
4172 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4173 string const width = p.getArg('{', '}');
4174 string const thickness = p.getArg('{', '}');
4175 context.check_layout(os);
4176 begin_command_inset(os, "line", "rule");
4177 if (!offset.empty())
4178 os << "offset \"" << translate_len(offset) << "\"\n";
4179 os << "width \"" << translate_len(width) << "\"\n"
4180 "height \"" << translate_len(thickness) << "\"\n";
4185 // handle refstyle first to catch \eqref which can also occur
4186 // without refstyle. Only recognize these commands if
4187 // refstyle.sty was found in the preamble (otherwise \eqref
4188 // and user defined ref commands could be misdetected).
4189 if ((where = is_known(t.cs(), known_refstyle_commands))
4190 && preamble.refstyle()) {
4191 context.check_layout(os);
4192 begin_command_inset(os, "ref", "formatted");
4193 os << "reference \"";
4194 os << known_refstyle_prefixes[where - known_refstyle_commands]
4196 os << convert_literate_command_inset_arg(p.verbatim_item())
4198 os << "plural \"false\"\n";
4199 os << "caps \"false\"\n";
4200 os << "noprefix \"false\"\n";
4202 preamble.registerAutomaticallyLoadedPackage("refstyle");
4206 // if refstyle is used, we must not convert \prettyref to a
4207 // formatted reference, since that would result in a refstyle command.
4208 if ((where = is_known(t.cs(), known_ref_commands)) &&
4209 (t.cs() != "prettyref" || !preamble.refstyle())) {
4210 string const opt = p.getOpt();
4212 context.check_layout(os);
4213 begin_command_inset(os, "ref",
4214 known_coded_ref_commands[where - known_ref_commands]);
4215 os << "reference \""
4216 << convert_literate_command_inset_arg(p.verbatim_item())
4218 os << "plural \"false\"\n";
4219 os << "caps \"false\"\n";
4220 os << "noprefix \"false\"\n";
4222 if (t.cs() == "vref" || t.cs() == "vpageref")
4223 preamble.registerAutomaticallyLoadedPackage("varioref");
4224 else if (t.cs() == "prettyref")
4225 preamble.registerAutomaticallyLoadedPackage("prettyref");
4227 // LyX does not yet support optional arguments of ref commands
4228 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4229 p.verbatim_item() + '}', context);
4235 is_known(t.cs(), known_natbib_commands) &&
4236 ((t.cs() != "citefullauthor" &&
4237 t.cs() != "citeyear" &&
4238 t.cs() != "citeyearpar") ||
4239 p.next_token().asInput() != "*")) {
4240 context.check_layout(os);
4241 string command = t.cs();
4242 if (p.next_token().asInput() == "*") {
4246 if (command == "citefullauthor")
4247 // alternative name for "\\citeauthor*"
4248 command = "citeauthor*";
4250 // text before the citation
4252 // text after the citation
4254 get_cite_arguments(p, true, before, after);
4256 if (command == "cite") {
4257 // \cite without optional argument means
4258 // \citet, \cite with at least one optional
4259 // argument means \citep.
4260 if (before.empty() && after.empty())
4265 if (before.empty() && after == "[]")
4266 // avoid \citet[]{a}
4268 else if (before == "[]" && after == "[]") {
4269 // avoid \citet[][]{a}
4273 bool literal = false;
4274 pair<bool, string> aft;
4275 pair<bool, string> bef;
4276 // remove the brackets around after and before
4277 if (!after.empty()) {
4279 after.erase(after.length() - 1, 1);
4280 aft = convert_latexed_command_inset_arg(after);
4281 literal = !aft.first;
4282 after = literal ? subst(after, "\n", " ") : aft.second;
4284 if (!before.empty()) {
4286 before.erase(before.length() - 1, 1);
4287 bef = convert_latexed_command_inset_arg(before);
4288 literal |= !bef.first;
4289 before = literal ? subst(before, "\n", " ") : bef.second;
4290 if (literal && !after.empty())
4291 after = subst(after, "\n", " ");
4293 string lit = literal ? "\"true\"" : "\"false\"";
4294 begin_command_inset(os, "citation", command);
4295 os << "after " << '"' << after << '"' << "\n";
4296 os << "before " << '"' << before << '"' << "\n";
4298 << convert_literate_command_inset_arg(p.verbatim_item())
4300 << "literal " << lit << "\n";
4302 // Need to set the cite engine if natbib is loaded by
4303 // the document class directly
4304 if (preamble.citeEngine() == "basic")
4305 preamble.citeEngine("natbib");
4310 && is_known(t.cs(), known_biblatex_commands)
4311 && ((t.cs() == "cite"
4312 || t.cs() == "citeauthor"
4313 || t.cs() == "Citeauthor"
4314 || t.cs() == "parencite"
4315 || t.cs() == "citetitle")
4316 || p.next_token().asInput() != "*"))
4317 || (use_biblatex_natbib
4318 && (is_known(t.cs(), known_biblatex_commands)
4319 || is_known(t.cs(), known_natbib_commands))
4320 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4321 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4322 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4323 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4324 || t.cs() == "parencite" || t.cs() == "citetitle")
4325 || p.next_token().asInput() != "*"))){
4326 context.check_layout(os);
4327 string command = t.cs();
4328 if (p.next_token().asInput() == "*") {
4333 bool const qualified = suffixIs(command, "s");
4335 command = rtrim(command, "s");
4337 // text before the citation
4339 // text after the citation
4341 get_cite_arguments(p, true, before, after, qualified);
4343 // These use natbib cmd names in LyX
4344 // for inter-citeengine compativility
4345 if (command == "citeyear")
4346 command = "citebyear";
4347 else if (command == "cite*")
4348 command = "citeyear";
4349 else if (command == "textcite")
4351 else if (command == "Textcite")
4353 else if (command == "parencite")
4355 else if (command == "Parencite")
4357 else if (command == "parencite*")
4358 command = "citeyearpar";
4359 else if (command == "smartcite")
4360 command = "footcite";
4361 else if (command == "Smartcite")
4362 command = "Footcite";
4364 string const emptyarg = qualified ? "()" : "[]";
4365 if (before.empty() && after == emptyarg)
4368 else if (before == emptyarg && after == emptyarg) {
4369 // avoid \cite[][]{a}
4373 bool literal = false;
4374 pair<bool, string> aft;
4375 pair<bool, string> bef;
4376 // remove the brackets around after and before
4377 if (!after.empty()) {
4379 after.erase(after.length() - 1, 1);
4380 aft = convert_latexed_command_inset_arg(after);
4381 literal = !aft.first;
4382 after = literal ? subst(after, "\n", " ") : aft.second;
4384 if (!before.empty()) {
4386 before.erase(before.length() - 1, 1);
4387 bef = convert_latexed_command_inset_arg(before);
4388 literal |= !bef.first;
4389 before = literal ? subst(before, "\n", " ") : bef.second;
4391 string keys, pretextlist, posttextlist;
4393 map<string, string> pres, posts, preslit, postslit;
4394 vector<string> lkeys;
4395 // text before the citation
4396 string lbefore, lbeforelit;
4397 // text after the citation
4398 string lafter, lafterlit;
4400 pair<bool, string> laft, lbef;
4402 get_cite_arguments(p, true, lbefore, lafter);
4403 // remove the brackets around after and before
4404 if (!lafter.empty()) {
4406 lafter.erase(lafter.length() - 1, 1);
4407 laft = convert_latexed_command_inset_arg(lafter);
4408 literal |= !laft.first;
4409 lafter = laft.second;
4410 lafterlit = subst(lbefore, "\n", " ");
4412 if (!lbefore.empty()) {
4413 lbefore.erase(0, 1);
4414 lbefore.erase(lbefore.length() - 1, 1);
4415 lbef = convert_latexed_command_inset_arg(lbefore);
4416 literal |= !lbef.first;
4417 lbefore = lbef.second;
4418 lbeforelit = subst(lbefore, "\n", " ");
4420 if (lbefore.empty() && lafter == "[]") {
4425 else if (lbefore == "[]" && lafter == "[]") {
4426 // avoid \cite[][]{a}
4432 lkey = p.getArg('{', '}');
4435 if (!lbefore.empty()) {
4436 pres.insert(make_pair(lkey, lbefore));
4437 preslit.insert(make_pair(lkey, lbeforelit));
4439 if (!lafter.empty()) {
4440 posts.insert(make_pair(lkey, lafter));
4441 postslit.insert(make_pair(lkey, lafterlit));
4443 lkeys.push_back(lkey);
4445 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4450 for (auto const & ptl : pres) {
4451 if (!pretextlist.empty())
4452 pretextlist += '\t';
4453 pretextlist += ptl.first + " " + ptl.second;
4455 for (auto const & potl : posts) {
4456 if (!posttextlist.empty())
4457 posttextlist += '\t';
4458 posttextlist += potl.first + " " + potl.second;
4461 keys = convert_literate_command_inset_arg(p.verbatim_item());
4464 after = subst(after, "\n", " ");
4465 if (!before.empty())
4466 before = subst(after, "\n", " ");
4468 string lit = literal ? "\"true\"" : "\"false\"";
4469 begin_command_inset(os, "citation", command);
4470 os << "after " << '"' << after << '"' << "\n";
4471 os << "before " << '"' << before << '"' << "\n";
4475 if (!pretextlist.empty())
4476 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4477 if (!posttextlist.empty())
4478 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4479 os << "literal " << lit << "\n";
4481 // Need to set the cite engine if biblatex is loaded by
4482 // the document class directly
4483 if (preamble.citeEngine() == "basic")
4484 use_biblatex_natbib ?
4485 preamble.citeEngine("biblatex-natbib")
4486 : preamble.citeEngine("biblatex");
4491 is_known(t.cs(), known_jurabib_commands) &&
4492 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4493 context.check_layout(os);
4494 string command = t.cs();
4495 if (p.next_token().asInput() == "*") {
4499 char argumentOrder = '\0';
4500 vector<string> const options =
4501 preamble.getPackageOptions("jurabib");
4502 if (find(options.begin(), options.end(),
4503 "natbiborder") != options.end())
4504 argumentOrder = 'n';
4505 else if (find(options.begin(), options.end(),
4506 "jurabiborder") != options.end())
4507 argumentOrder = 'j';
4509 // text before the citation
4511 // text after the citation
4513 get_cite_arguments(p, argumentOrder != 'j', before, after);
4515 string const citation = p.verbatim_item();
4516 if (!before.empty() && argumentOrder == '\0') {
4517 cerr << "Warning: Assuming argument order "
4518 "of jurabib version 0.6 for\n'"
4519 << command << before << after << '{'
4520 << citation << "}'.\n"
4521 "Add 'jurabiborder' to the jurabib "
4522 "package options if you used an\n"
4523 "earlier jurabib version." << endl;
4525 bool literal = false;
4526 pair<bool, string> aft;
4527 pair<bool, string> bef;
4528 // remove the brackets around after and before
4529 if (!after.empty()) {
4531 after.erase(after.length() - 1, 1);
4532 aft = convert_latexed_command_inset_arg(after);
4533 literal = !aft.first;
4534 after = literal ? subst(after, "\n", " ") : aft.second;
4536 if (!before.empty()) {
4538 before.erase(before.length() - 1, 1);
4539 bef = convert_latexed_command_inset_arg(before);
4540 literal |= !bef.first;
4541 before = literal ? subst(before, "\n", " ") : bef.second;
4542 if (literal && !after.empty())
4543 after = subst(after, "\n", " ");
4545 string lit = literal ? "\"true\"" : "\"false\"";
4546 begin_command_inset(os, "citation", command);
4547 os << "after " << '"' << after << "\"\n"
4548 << "before " << '"' << before << "\"\n"
4549 << "key " << '"' << citation << "\"\n"
4550 << "literal " << lit << "\n";
4552 // Need to set the cite engine if jurabib is loaded by
4553 // the document class directly
4554 if (preamble.citeEngine() == "basic")
4555 preamble.citeEngine("jurabib");
4559 if (t.cs() == "cite"
4560 || t.cs() == "nocite") {
4561 context.check_layout(os);
4562 string after = p.getArg('[', ']');
4563 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4564 bool const literal = !aft.first;
4565 after = literal ? subst(after, "\n", " ") : aft.second;
4566 string lit = literal ? "\"true\"" : "\"false\"";
4567 string key = convert_literate_command_inset_arg(p.verbatim_item());
4568 // store the case that it is "\nocite{*}" to use it later for
4571 begin_command_inset(os, "citation", t.cs());
4572 os << "after " << '"' << after << "\"\n"
4573 << "key " << '"' << key << "\"\n"
4574 << "literal " << lit << "\n";
4576 } else if (t.cs() == "nocite")
4581 if (t.cs() == "index" ||
4582 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4583 context.check_layout(os);
4584 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4585 p.getArg('[', ']') : "";
4586 string const kind = arg.empty() ? "idx" : arg;
4587 begin_inset(os, "Index ");
4588 os << kind << "\nstatus collapsed\n";
4589 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4592 preamble.registerAutomaticallyLoadedPackage("splitidx");
4596 if (t.cs() == "nomenclature") {
4597 context.check_layout(os);
4598 begin_command_inset(os, "nomenclature", "nomenclature");
4599 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4600 if (!prefix.empty())
4601 os << "prefix " << '"' << prefix << '"' << "\n";
4602 string symbol = p.verbatim_item();
4603 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4604 bool literal = !sym.first;
4605 string description = p.verbatim_item();
4606 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4607 literal |= !desc.first;
4609 symbol = subst(symbol, "\n", " ");
4610 description = subst(description, "\n", " ");
4612 symbol = sym.second;
4613 description = desc.second;
4615 string lit = literal ? "\"true\"" : "\"false\"";
4616 os << "symbol " << '"' << symbol;
4617 os << "\"\ndescription \""
4618 << description << "\"\n"
4619 << "literal " << lit << "\n";
4621 preamble.registerAutomaticallyLoadedPackage("nomencl");
4625 if (t.cs() == "label") {
4626 context.check_layout(os);
4627 begin_command_inset(os, "label", "label");
4629 << convert_literate_command_inset_arg(p.verbatim_item())
4635 if (t.cs() == "lyxmintcaption") {
4636 string const pos = p.getArg('[', ']');
4638 string const caption =
4639 parse_text_snippet(p, FLAG_ITEM, false,
4641 minted_nonfloat_caption = "[t]" + caption;
4643 // We already got the caption at the bottom,
4644 // so simply skip it.
4645 parse_text_snippet(p, FLAG_ITEM, false, context);
4647 eat_whitespace(p, os, context, true);
4651 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4652 context.check_layout(os);
4653 string commandname = t.cs();
4655 if (p.next_token().asInput() == "*") {
4660 begin_command_inset(os, "index_print", commandname);
4661 string const indexname = p.getArg('[', ']');
4663 if (indexname.empty())
4664 os << "type \"idx\"\n";
4666 os << "type \"" << indexname << "\"\n";
4667 os << "literal \"true\"\n";
4670 skip_spaces_braces(p);
4671 preamble.registerAutomaticallyLoadedPackage("makeidx");
4672 if (preamble.use_indices() == "true")
4673 preamble.registerAutomaticallyLoadedPackage("splitidx");
4677 if (t.cs() == "printnomenclature") {
4679 string width_type = "";
4680 context.check_layout(os);
4681 begin_command_inset(os, "nomencl_print", "printnomenclature");
4682 // case of a custom width
4684 width = p.getArg('[', ']');
4685 width = translate_len(width);
4686 width_type = "custom";
4688 // case of no custom width
4689 // the case of no custom width but the width set
4690 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4691 // because the user could have set anything, not only the width
4692 // of the longest label (which would be width_type = "auto")
4693 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4694 if (label.empty() && width_type.empty())
4695 width_type = "none";
4696 os << "set_width \"" << width_type << "\"\n";
4697 if (width_type == "custom")
4698 os << "width \"" << width << '\"';
4700 skip_spaces_braces(p);
4701 preamble.registerAutomaticallyLoadedPackage("nomencl");
4705 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4706 context.check_layout(os);
4707 begin_inset(os, "script ");
4708 os << t.cs().substr(4) << '\n';
4709 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4710 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4712 if (t.cs() == "textsubscript")
4713 preamble.registerAutomaticallyLoadedPackage("subscript");
4717 if ((where = is_known(t.cs(), known_quotes))) {
4718 context.check_layout(os);
4719 begin_inset(os, "Quotes ");
4720 string quotetype = known_coded_quotes[where - known_quotes];
4721 // try to make a smart guess about the side
4722 Token const prev = p.prev_token();
4723 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4724 && prev.character() != '\n' && prev.character() != '~');
4725 quotetype = guessQuoteStyle(quotetype, opening);
4728 // LyX adds {} after the quote, so we have to eat
4729 // spaces here if there are any before a possible
4731 eat_whitespace(p, os, context, false);
4736 if ((where = is_known(t.cs(), known_sizes)) &&
4737 context.new_layout_allowed) {
4738 context.check_layout(os);
4739 TeXFont const oldFont = context.font;
4740 context.font.size = known_coded_sizes[where - known_sizes];
4741 output_font_change(os, oldFont, context.font);
4742 eat_whitespace(p, os, context, false);
4746 if ((where = is_known(t.cs(), known_font_families)) &&
4747 context.new_layout_allowed) {
4748 context.check_layout(os);
4749 TeXFont const oldFont = context.font;
4750 context.font.family =
4751 known_coded_font_families[where - known_font_families];
4752 output_font_change(os, oldFont, context.font);
4753 eat_whitespace(p, os, context, false);
4757 if ((where = is_known(t.cs(), known_font_series)) &&
4758 context.new_layout_allowed) {
4759 context.check_layout(os);
4760 TeXFont const oldFont = context.font;
4761 context.font.series =
4762 known_coded_font_series[where - known_font_series];
4763 output_font_change(os, oldFont, context.font);
4764 eat_whitespace(p, os, context, false);
4768 if ((where = is_known(t.cs(), known_font_shapes)) &&
4769 context.new_layout_allowed) {
4770 context.check_layout(os);
4771 TeXFont const oldFont = context.font;
4772 context.font.shape =
4773 known_coded_font_shapes[where - known_font_shapes];
4774 output_font_change(os, oldFont, context.font);
4775 eat_whitespace(p, os, context, false);
4778 if ((where = is_known(t.cs(), known_old_font_families)) &&
4779 context.new_layout_allowed) {
4780 context.check_layout(os);
4781 TeXFont const oldFont = context.font;
4782 context.font.init();
4783 context.font.size = oldFont.size;
4784 context.font.family =
4785 known_coded_font_families[where - known_old_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_old_font_series)) &&
4792 context.new_layout_allowed) {
4793 context.check_layout(os);
4794 TeXFont const oldFont = context.font;
4795 context.font.init();
4796 context.font.size = oldFont.size;
4797 context.font.series =
4798 known_coded_font_series[where - known_old_font_series];
4799 output_font_change(os, oldFont, context.font);
4800 eat_whitespace(p, os, context, false);
4804 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4805 context.new_layout_allowed) {
4806 context.check_layout(os);
4807 TeXFont const oldFont = context.font;
4808 context.font.init();
4809 context.font.size = oldFont.size;
4810 context.font.shape =
4811 known_coded_font_shapes[where - known_old_font_shapes];
4812 output_font_change(os, oldFont, context.font);
4813 eat_whitespace(p, os, context, false);
4817 if (t.cs() == "selectlanguage") {
4818 context.check_layout(os);
4819 // save the language for the case that a
4820 // \foreignlanguage is used
4821 context.font.language = babel2lyx(p.verbatim_item());
4822 os << "\n\\lang " << context.font.language << "\n";
4826 if (t.cs() == "foreignlanguage") {
4827 string const lang = babel2lyx(p.verbatim_item());
4828 parse_text_attributes(p, os, FLAG_ITEM, outer,
4830 context.font.language, lang);
4834 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4835 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4836 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4838 // We have to output the whole command if it has an option
4839 // because LyX doesn't support this yet, see bug #8214,
4840 // only if there is a single option specifying a variant, we can handle it.
4842 string langopts = p.getOpt();
4843 // check if the option contains a variant, if yes, extract it
4844 string::size_type pos_var = langopts.find("variant");
4845 string::size_type i = langopts.find(',');
4846 string::size_type k = langopts.find('=', pos_var);
4847 if (pos_var != string::npos && i == string::npos) {
4849 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4850 lang = preamble.polyglossia2lyx(variant);
4851 parse_text_attributes(p, os, FLAG_ITEM, outer,
4853 context.font.language, lang);
4855 output_ert_inset(os, t.asInput() + langopts, context);
4857 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4858 parse_text_attributes(p, os, FLAG_ITEM, outer,
4860 context.font.language, lang);
4865 if (t.cs() == "inputencoding") {
4866 // nothing to write here
4867 string const enc = subst(p.verbatim_item(), "\n", " ");
4868 p.setEncoding(enc, Encoding::inputenc);
4872 if (is_known(t.cs(), known_special_chars) ||
4873 (t.cs() == "protect" &&
4874 p.next_token().cat() == catEscape &&
4875 is_known(p.next_token().cs(), known_special_protect_chars))) {
4876 // LyX sometimes puts a \protect in front, so we have to ignore it
4878 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4879 known_special_chars);
4880 context.check_layout(os);
4881 os << known_coded_special_chars[where - known_special_chars];
4882 skip_spaces_braces(p);
4886 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4887 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4888 p.next_next_token().asInput() == "-") ||
4889 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4890 // LyX sometimes puts a \protect in front, so we have to ignore it
4891 if (t.cs() == "protect")
4893 context.check_layout(os);
4894 if (t.cs() == "nobreakdash")
4895 os << "\\SpecialChar nobreakdash\n";
4897 os << "\\SpecialChar endofsentence\n";
4902 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4903 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4904 || t.cs() == "%" || t.cs() == "-") {
4905 context.check_layout(os);
4907 os << "\\SpecialChar softhyphen\n";
4913 if (t.cs() == "char") {
4914 context.check_layout(os);
4915 if (p.next_token().character() == '`') {
4917 if (p.next_token().cs() == "\"") {
4922 output_ert_inset(os, "\\char`", context);
4925 output_ert_inset(os, "\\char", context);
4930 if (t.cs() == "verb") {
4931 context.check_layout(os);
4932 // set catcodes to verbatim early, just in case.
4933 p.setCatcodes(VERBATIM_CATCODES);
4934 string delim = p.get_token().asInput();
4935 Parser::Arg arg = p.verbatimStuff(delim);
4937 output_ert_inset(os, "\\verb" + delim
4938 + arg.second + delim, context);
4940 cerr << "invalid \\verb command. Skipping" << endl;
4944 // Problem: \= creates a tabstop inside the tabbing environment
4945 // and else an accent. In the latter case we really would want
4946 // \={o} instead of \= o.
4947 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4948 output_ert_inset(os, t.asInput(), context);
4952 if (t.cs() == "\\") {
4953 context.check_layout(os);
4955 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4956 else if (p.next_token().asInput() == "*") {
4958 // getOpt() eats the following space if there
4959 // is no optional argument, but that is OK
4960 // here since it has no effect in the output.
4961 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4964 begin_inset(os, "Newline newline");
4970 if (t.cs() == "newline" ||
4971 (t.cs() == "linebreak" && !p.hasOpt())) {
4972 context.check_layout(os);
4973 begin_inset(os, "Newline ");
4976 skip_spaces_braces(p);
4980 if (t.cs() == "input" || t.cs() == "include"
4981 || t.cs() == "verbatiminput"
4982 || t.cs() == "lstinputlisting"
4983 || t.cs() == "inputminted") {
4984 string name = t.cs();
4985 if (name == "verbatiminput"
4986 && p.next_token().asInput() == "*")
4987 name += p.get_token().asInput();
4988 context.check_layout(os);
4990 bool literal = false;
4991 if (name == "lstinputlisting" && p.hasOpt()) {
4992 lstparams = p.getArg('[', ']');
4993 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4994 literal = !oa.first;
4996 lstparams = subst(lstparams, "\n", " ");
4998 lstparams = oa.second;
4999 } else if (name == "inputminted") {
5000 name = "lstinputlisting";
5001 string const lang = p.getArg('{', '}');
5002 if (lang != "tex") {
5003 string cmd = "\\inputminted{" + lang + "}{";
5004 cmd += p.getArg('{', '}') + "}";
5005 output_ert_inset(os, cmd, context);
5008 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5009 minted_nonfloat_caption.erase(0,3);
5010 // extract label and caption from the already produced LyX code
5011 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5012 string const caption = nfc.front();
5014 vector<string>::iterator it =
5015 find(nfc.begin(), nfc.end(), "LatexCommand label");
5016 if (it != nfc.end()) {
5018 if (it != nfc.end())
5020 label = support::split(label, '"');
5023 minted_nonfloat_caption.clear();
5024 lstparams = "caption=" + caption;
5026 lstparams += ",label=" + label;
5027 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5028 literal = !oa.first;
5030 lstparams = subst(lstparams, "\n", " ");
5032 lstparams = oa.second;
5035 string lit = literal ? "\"true\"" : "\"false\"";
5036 string filename(normalize_filename(p.getArg('{', '}')));
5037 string const path = getMasterFilePath(true);
5038 // We want to preserve relative / absolute filenames,
5039 // therefore path is only used for testing
5040 if ((t.cs() == "include" || t.cs() == "input") &&
5041 !makeAbsPath(filename, path).exists()) {
5042 // The file extension is probably missing.
5043 // Now try to find it out.
5044 string const tex_name =
5045 find_file(filename, path,
5046 known_tex_extensions);
5047 if (!tex_name.empty())
5048 filename = tex_name;
5050 bool external = false;
5052 if (makeAbsPath(filename, path).exists()) {
5053 string const abstexname =
5054 makeAbsPath(filename, path).absFileName();
5055 string const absfigname =
5056 changeExtension(abstexname, ".fig");
5057 fix_child_filename(filename);
5058 string const lyxname = changeExtension(filename,
5059 roundtripMode() ? ".lyx.lyx" : ".lyx");
5060 string const abslyxname = makeAbsPath(
5061 lyxname, getParentFilePath(false)).absFileName();
5063 if (!skipChildren())
5064 external = FileName(absfigname).exists();
5065 if (t.cs() == "input" && !skipChildren()) {
5066 string const ext = getExtension(abstexname);
5068 // Combined PS/LaTeX:
5069 // x.eps, x.pstex_t (old xfig)
5070 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5071 FileName const absepsname(
5072 changeExtension(abstexname, ".eps"));
5073 FileName const abspstexname(
5074 changeExtension(abstexname, ".pstex"));
5075 bool const xfigeps =
5076 (absepsname.exists() ||
5077 abspstexname.exists()) &&
5080 // Combined PDF/LaTeX:
5081 // x.pdf, x.pdftex_t (old xfig)
5082 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5083 FileName const abspdfname(
5084 changeExtension(abstexname, ".pdf"));
5085 bool const xfigpdf =
5086 abspdfname.exists() &&
5087 (ext == "pdftex_t" || ext == "pdf_t");
5091 // Combined PS/PDF/LaTeX:
5092 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5093 string const absbase2(
5094 removeExtension(abstexname) + "_pspdftex");
5095 FileName const abseps2name(
5096 addExtension(absbase2, ".eps"));
5097 FileName const abspdf2name(
5098 addExtension(absbase2, ".pdf"));
5099 bool const xfigboth =
5100 abspdf2name.exists() &&
5101 abseps2name.exists() && ext == "pspdftex";
5103 xfig = xfigpdf || xfigeps || xfigboth;
5104 external = external && xfig;
5107 outname = changeExtension(filename, ".fig");
5108 FileName abssrc(changeExtension(abstexname, ".fig"));
5109 copy_file(abssrc, outname);
5111 // Don't try to convert, the result
5112 // would be full of ERT.
5114 FileName abssrc(abstexname);
5115 copy_file(abssrc, outname);
5116 } else if (t.cs() != "verbatiminput" &&
5118 tex2lyx(abstexname, FileName(abslyxname),
5121 // no need to call copy_file
5122 // tex2lyx creates the file
5125 FileName abssrc(abstexname);
5126 copy_file(abssrc, outname);
5129 cerr << "Warning: Could not find included file '"
5130 << filename << "'." << endl;
5134 begin_inset(os, "External\n");
5135 os << "\ttemplate XFig\n"
5136 << "\tfilename " << outname << '\n';
5137 registerExternalTemplatePackages("XFig");
5139 begin_command_inset(os, "include", name);
5140 outname = subst(outname, "\"", "\\\"");
5141 os << "preview false\n"
5142 "filename \"" << outname << "\"\n";
5143 if (!lstparams.empty())
5144 os << "lstparams \"" << lstparams << "\"\n";
5145 os << "literal " << lit << "\n";
5146 if (t.cs() == "verbatiminput")
5147 preamble.registerAutomaticallyLoadedPackage("verbatim");
5153 if (t.cs() == "bibliographystyle") {
5154 // store new bibliographystyle
5155 bibliographystyle = p.verbatim_item();
5156 // If any other command than \bibliography, \addcontentsline
5157 // and \nocite{*} follows, we need to output the style
5158 // (because it might be used by that command).
5159 // Otherwise, it will automatically be output by LyX.
5162 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5163 if (t2.cat() == catBegin)
5165 if (t2.cat() != catEscape)
5167 if (t2.cs() == "nocite") {
5168 if (p.getArg('{', '}') == "*")
5170 } else if (t2.cs() == "bibliography")
5172 else if (t2.cs() == "phantomsection") {
5176 else if (t2.cs() == "addcontentsline") {
5177 // get the 3 arguments of \addcontentsline
5180 contentslineContent = p.getArg('{', '}');
5181 // if the last argument is not \refname we must output
5182 if (contentslineContent == "\\refname")
5189 output_ert_inset(os,
5190 "\\bibliographystyle{" + bibliographystyle + '}',
5196 if (t.cs() == "phantomsection") {
5197 // we only support this if it occurs between
5198 // \bibliographystyle and \bibliography
5199 if (bibliographystyle.empty())
5200 output_ert_inset(os, "\\phantomsection", context);
5204 if (t.cs() == "addcontentsline") {
5205 context.check_layout(os);
5206 // get the 3 arguments of \addcontentsline
5207 string const one = p.getArg('{', '}');
5208 string const two = p.getArg('{', '}');
5209 string const three = p.getArg('{', '}');
5210 // only if it is a \refname, we support if for the bibtex inset
5211 if (contentslineContent != "\\refname") {
5212 output_ert_inset(os,
5213 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5219 else if (t.cs() == "bibliography") {
5220 context.check_layout(os);
5222 begin_command_inset(os, "bibtex", "bibtex");
5223 if (!btprint.empty()) {
5224 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5225 // clear the string because the next BibTeX inset can be without the
5226 // \nocite{*} option
5229 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5230 // Do we have addcontentsline?
5231 if (contentslineContent == "\\refname") {
5232 BibOpts = "bibtotoc";
5233 // clear string because next BibTeX inset can be without addcontentsline
5234 contentslineContent.clear();
5236 // Do we have a bibliographystyle set?
5237 if (!bibliographystyle.empty()) {
5238 if (BibOpts.empty())
5239 BibOpts = normalize_filename(bibliographystyle);
5241 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5242 // clear it because each bibtex entry has its style
5243 // and we need an empty string to handle \phantomsection
5244 bibliographystyle.clear();
5246 os << "options " << '"' << BibOpts << '"' << "\n";
5247 if (p.getEncoding() != preamble.docencoding) {
5248 Encoding const * const enc = encodings.fromIconvName(
5249 p.getEncoding(), Encoding::inputenc, true);
5251 cerr << "Unknown bib encoding " << p.getEncoding()
5252 << ". Ignoring." << std::endl;
5254 os << "encoding " << '"' << enc->name() << '"' << "\n";
5260 if (t.cs() == "printbibliography") {
5261 context.check_layout(os);
5263 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5264 vector<string> opts = getVectorFromString(bbloptions);
5265 vector<string>::iterator it =
5266 find(opts.begin(), opts.end(), "heading=bibintoc");
5267 if (it != opts.end()) {
5269 BibOpts = "bibtotoc";
5271 bbloptions = getStringFromVector(opts);
5272 begin_command_inset(os, "bibtex", "bibtex");
5273 if (!btprint.empty()) {
5274 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5275 // clear the string because the next BibTeX inset can be without the
5276 // \nocite{*} option
5280 for (auto const & bf : preamble.biblatex_bibliographies) {
5281 if (!bibfiles.empty())
5283 bibfiles += normalize_filename(bf);
5285 if (!bibfiles.empty())
5286 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5287 // Do we have addcontentsline?
5288 if (contentslineContent == "\\refname") {
5289 BibOpts = "bibtotoc";
5290 // clear string because next BibTeX inset can be without addcontentsline
5291 contentslineContent.clear();
5293 os << "options " << '"' << BibOpts << '"' << "\n";
5294 if (!bbloptions.empty())
5295 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5296 if (!preamble.bibencoding.empty()) {
5297 Encoding const * const enc = encodings.fromLaTeXName(
5298 preamble.bibencoding, Encoding::inputenc, true);
5300 cerr << "Unknown bib encoding " << preamble.bibencoding
5301 << ". Ignoring." << std::endl;
5303 os << "encoding " << '"' << enc->name() << '"' << "\n";
5306 need_commentbib = false;
5310 if (t.cs() == "bibbysection") {
5311 context.check_layout(os);
5313 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5314 vector<string> opts = getVectorFromString(bbloptions);
5315 vector<string>::iterator it =
5316 find(opts.begin(), opts.end(), "heading=bibintoc");
5317 if (it != opts.end()) {
5319 BibOpts = "bibtotoc";
5321 bbloptions = getStringFromVector(opts);
5322 begin_command_inset(os, "bibtex", "bibtex");
5323 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5325 for (auto const & bf : preamble.biblatex_bibliographies) {
5326 if (!bibfiles.empty())
5328 bibfiles += normalize_filename(bf);
5330 if (!bibfiles.empty())
5331 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5332 os << "options " << '"' << BibOpts << '"' << "\n";
5333 if (!bbloptions.empty())
5334 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5336 need_commentbib = false;
5340 if (t.cs() == "parbox") {
5341 // Test whether this is an outer box of a shaded box
5343 // swallow arguments
5344 while (p.hasOpt()) {
5346 p.skip_spaces(true);
5349 p.skip_spaces(true);
5351 if (p.next_token().cat() == catBegin)
5353 p.skip_spaces(true);
5354 Token to = p.get_token();
5355 bool shaded = false;
5356 if (to.asInput() == "\\begin") {
5357 p.skip_spaces(true);
5358 if (p.getArg('{', '}') == "shaded")
5363 parse_outer_box(p, os, FLAG_ITEM, outer,
5364 context, "parbox", "shaded");
5366 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5367 "", "", t.cs(), "", "");
5371 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5372 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5373 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5374 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5378 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5379 string backgroundcolor;
5380 preamble.registerAutomaticallyLoadedPackage("xcolor");
5381 if (t.cs() == "fcolorbox") {
5382 string const framecolor = p.getArg('{', '}');
5383 backgroundcolor = p.getArg('{', '}');
5384 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5386 backgroundcolor = p.getArg('{', '}');
5387 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5392 // FIXME: due to the compiler limit of "if" nestings
5393 // the code for the alignment was put here
5394 // put them in their own if if this is fixed
5395 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5396 || t.cs() == "shadowsize"
5397 || t.cs() == "raggedleft" || t.cs() == "centering"
5398 || t.cs() == "raggedright") {
5399 if (t.cs() == "fboxrule")
5401 if (t.cs() == "fboxsep")
5403 if (t.cs() == "shadowsize")
5405 if (t.cs() != "raggedleft" && t.cs() != "centering"
5406 && t.cs() != "raggedright") {
5407 p.skip_spaces(true);
5408 while (p.good() && p.next_token().cat() != catSpace
5409 && p.next_token().cat() != catNewline
5410 && p.next_token().cat() != catEscape) {
5411 if (t.cs() == "fboxrule")
5412 fboxrule = fboxrule + p.get_token().asInput();
5413 if (t.cs() == "fboxsep")
5414 fboxsep = fboxsep + p.get_token().asInput();
5415 if (t.cs() == "shadowsize")
5416 shadow_size = shadow_size + p.get_token().asInput();
5419 output_ert_inset(os, t.asInput(), context);
5424 //\framebox() is part of the picture environment and different from \framebox{}
5425 //\framebox{} will be parsed by parse_outer_box
5426 if (t.cs() == "framebox") {
5427 if (p.next_token().character() == '(') {
5428 //the syntax is: \framebox(x,y)[position]{content}
5429 string arg = t.asInput();
5430 arg += p.getFullParentheseArg();
5431 arg += p.getFullOpt();
5432 eat_whitespace(p, os, context, false);
5433 output_ert_inset(os, arg + '{', context);
5434 parse_text(p, os, FLAG_ITEM, outer, context);
5435 output_ert_inset(os, "}", context);
5437 //the syntax is: \framebox[width][position]{content}
5438 string special = p.getFullOpt();
5439 special += p.getOpt();
5440 parse_outer_box(p, os, FLAG_ITEM, outer,
5441 context, t.cs(), special);
5446 //\makebox() is part of the picture environment and different from \makebox{}
5447 //\makebox{} will be parsed by parse_box
5448 if (t.cs() == "makebox") {
5449 if (p.next_token().character() == '(') {
5450 //the syntax is: \makebox(x,y)[position]{content}
5451 string arg = t.asInput();
5452 arg += p.getFullParentheseArg();
5453 arg += p.getFullOpt();
5454 eat_whitespace(p, os, context, false);
5455 output_ert_inset(os, arg + '{', context);
5456 parse_text(p, os, FLAG_ITEM, outer, context);
5457 output_ert_inset(os, "}", context);
5459 //the syntax is: \makebox[width][position]{content}
5460 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5461 "", "", t.cs(), "", "");
5465 if (t.cs() == "smallskip" ||
5466 t.cs() == "medskip" ||
5467 t.cs() == "bigskip" ||
5468 t.cs() == "vfill") {
5469 context.check_layout(os);
5470 begin_inset(os, "VSpace ");
5473 skip_spaces_braces(p);
5477 if ((where = is_known(t.cs(), known_spaces))) {
5478 context.check_layout(os);
5479 begin_inset(os, "space ");
5480 os << '\\' << known_coded_spaces[where - known_spaces]
5483 // LaTeX swallows whitespace after all spaces except
5484 // "\\,". We have to do that here, too, because LyX
5485 // adds "{}" which would make the spaces significant.
5487 eat_whitespace(p, os, context, false);
5488 // LyX adds "{}" after all spaces except "\\ " and
5489 // "\\,", so we have to remove "{}".
5490 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5491 // remove the braces after "\\,", too.
5497 if (t.cs() == "newpage" ||
5498 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5499 t.cs() == "clearpage" ||
5500 t.cs() == "cleardoublepage") {
5501 context.check_layout(os);
5502 begin_inset(os, "Newpage ");
5505 skip_spaces_braces(p);
5509 if (t.cs() == "DeclareRobustCommand" ||
5510 t.cs() == "DeclareRobustCommandx" ||
5511 t.cs() == "newcommand" ||
5512 t.cs() == "newcommandx" ||
5513 t.cs() == "providecommand" ||
5514 t.cs() == "providecommandx" ||
5515 t.cs() == "renewcommand" ||
5516 t.cs() == "renewcommandx") {
5517 // DeclareRobustCommand, DeclareRobustCommandx,
5518 // providecommand and providecommandx could be handled
5519 // by parse_command(), but we need to call
5520 // add_known_command() here.
5521 string name = t.asInput();
5522 if (p.next_token().asInput() == "*") {
5523 // Starred form. Eat '*'
5527 string const command = p.verbatim_item();
5528 string const opt1 = p.getFullOpt();
5529 string const opt2 = p.getFullOpt();
5530 add_known_command(command, opt1, !opt2.empty());
5531 string const ert = name + '{' + command + '}' +
5533 '{' + p.verbatim_item() + '}';
5535 if (t.cs() == "DeclareRobustCommand" ||
5536 t.cs() == "DeclareRobustCommandx" ||
5537 t.cs() == "providecommand" ||
5538 t.cs() == "providecommandx" ||
5539 name[name.length()-1] == '*')
5540 output_ert_inset(os, ert, context);
5542 context.check_layout(os);
5543 begin_inset(os, "FormulaMacro");
5550 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5551 // let could be handled by parse_command(),
5552 // but we need to call add_known_command() here.
5553 string ert = t.asInput();
5556 if (p.next_token().cat() == catBegin) {
5557 name = p.verbatim_item();
5558 ert += '{' + name + '}';
5560 name = p.verbatim_item();
5565 if (p.next_token().cat() == catBegin) {
5566 command = p.verbatim_item();
5567 ert += '{' + command + '}';
5569 command = p.verbatim_item();
5572 // If command is known, make name known too, to parse
5573 // its arguments correctly. For this reason we also
5574 // have commands in syntax.default that are hardcoded.
5575 CommandMap::iterator it = known_commands.find(command);
5576 if (it != known_commands.end())
5577 known_commands[t.asInput()] = it->second;
5578 output_ert_inset(os, ert, context);
5582 if (t.cs() == "hspace" || t.cs() == "vspace") {
5585 string name = t.asInput();
5586 string const length = p.verbatim_item();
5589 bool valid = splitLatexLength(length, valstring, unit);
5590 bool known_hspace = false;
5591 bool known_vspace = false;
5592 bool known_unit = false;
5595 istringstream iss(valstring);
5598 if (t.cs()[0] == 'h') {
5599 if (unit == "\\fill") {
5604 known_hspace = true;
5607 if (unit == "\\smallskipamount") {
5609 known_vspace = true;
5610 } else if (unit == "\\medskipamount") {
5612 known_vspace = true;
5613 } else if (unit == "\\bigskipamount") {
5615 known_vspace = true;
5616 } else if (unit == "\\fill") {
5618 known_vspace = true;
5622 if (!known_hspace && !known_vspace) {
5623 switch (unitFromString(unit)) {
5639 //unitFromString(unit) fails for relative units like Length::PCW
5640 // therefore handle them separately
5641 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5642 || unit == "\\textwidth" || unit == "\\linewidth"
5643 || unit == "\\textheight" || unit == "\\paperheight"
5644 || unit == "\\baselineskip")
5652 // check for glue lengths
5653 bool is_gluelength = false;
5654 string gluelength = length;
5655 string::size_type i = length.find(" minus");
5656 if (i == string::npos) {
5657 i = length.find(" plus");
5658 if (i != string::npos)
5659 is_gluelength = true;
5661 is_gluelength = true;
5662 // if yes transform "9xx minus 8yy plus 7zz"
5664 if (is_gluelength) {
5665 i = gluelength.find(" minus");
5666 if (i != string::npos)
5667 gluelength.replace(i, 7, "-");
5668 i = gluelength.find(" plus");
5669 if (i != string::npos)
5670 gluelength.replace(i, 6, "+");
5673 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5674 // Literal horizontal length or known variable
5675 context.check_layout(os);
5676 begin_inset(os, "space ");
5684 if (known_unit && !known_hspace)
5685 os << "\n\\length " << translate_len(length);
5687 os << "\n\\length " << gluelength;
5689 } else if (known_unit || known_vspace || is_gluelength) {
5690 // Literal vertical length or known variable
5691 context.check_layout(os);
5692 begin_inset(os, "VSpace ");
5695 if (known_unit && !known_vspace)
5696 os << translate_len(length);
5703 // LyX can't handle other length variables in Inset VSpace/space
5708 output_ert_inset(os, name + '{' + unit + '}', context);
5709 else if (value == -1.0)
5710 output_ert_inset(os, name + "{-" + unit + '}', context);
5712 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5714 output_ert_inset(os, name + '{' + length + '}', context);
5719 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5720 // might be one or several options or a star.
5721 // The single '=' is meant here.
5722 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5726 context.check_layout(os);
5727 // store the latexparam here. This is eaten in parse_text_in_inset
5728 context.latexparam = newinsetlayout->latexparam();
5729 docstring name = newinsetlayout->name();
5730 bool const caption = name.find(from_ascii("Caption:")) == 0;
5732 // Already done for floating minted listings.
5733 if (minted_float.empty()) {
5734 begin_inset(os, "Caption ");
5735 os << to_utf8(name.substr(8)) << '\n';
5738 // FIXME: what do we do if the prefix is not Flex: ?
5739 if (prefixIs(name, from_ascii("Flex:")))
5741 begin_inset(os, "Flex ");
5742 os << to_utf8(name) << '\n'
5743 << "status collapsed\n";
5745 if (!minted_float.empty()) {
5746 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5747 } else if (newinsetlayout->isPassThru()) {
5748 // set catcodes to verbatim early, just in case.
5749 p.setCatcodes(VERBATIM_CATCODES);
5750 string delim = p.get_token().asInput();
5752 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5753 //FIXME: handle error condition
5754 string const arg = p.verbatimStuff("}").second;
5755 Context newcontext(true, context.textclass);
5756 if (newinsetlayout->forcePlainLayout())
5757 newcontext.layout = &context.textclass.plainLayout();
5758 output_ert(os, arg, newcontext);
5760 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5761 context.latexparam.clear();
5764 // Minted caption insets are not closed here because
5765 // we collect everything into the caption.
5766 if (minted_float.empty())
5771 // The single '=' is meant here.
5772 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5776 context.check_layout(os);
5777 docstring name = newinsetlayout->name();
5778 bool const caption = name.find(from_ascii("Caption:")) == 0;
5780 // Already done for floating minted listings.
5781 if (minted_float.empty()) {
5782 begin_inset(os, "Caption ");
5783 os << to_utf8(name.substr(8)) << '\n';
5786 // FIXME: what do we do if the prefix is not Flex: ?
5787 if (prefixIs(name, from_ascii("Flex:")))
5789 begin_inset(os, "Flex ");
5790 os << to_utf8(name) << '\n'
5791 << "status collapsed\n";
5793 if (!minted_float.empty()) {
5794 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5795 } else if (newinsetlayout->isPassThru()) {
5796 // set catcodes to verbatim early, just in case.
5797 p.setCatcodes(VERBATIM_CATCODES);
5798 string delim = p.get_token().asInput();
5800 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5801 //FIXME: handle error condition
5802 string const arg = p.verbatimStuff("}").second;
5803 Context newcontext(true, context.textclass);
5804 if (newinsetlayout->forcePlainLayout())
5805 newcontext.layout = &context.textclass.plainLayout();
5806 output_ert(os, arg, newcontext);
5808 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5811 // Minted caption insets are not closed here because
5812 // we collect everything into the caption.
5813 if (minted_float.empty())
5818 if (t.cs() == "includepdf") {
5820 string const arg = p.getArg('[', ']');
5821 map<string, string> opts;
5822 vector<string> keys;
5823 split_map(arg, opts, keys);
5824 string name = normalize_filename(p.verbatim_item());
5825 string const path = getMasterFilePath(true);
5826 // We want to preserve relative / absolute filenames,
5827 // therefore path is only used for testing
5828 if (!makeAbsPath(name, path).exists()) {
5829 // The file extension is probably missing.
5830 // Now try to find it out.
5831 char const * const pdfpages_format[] = {"pdf", 0};
5832 string const pdftex_name =
5833 find_file(name, path, pdfpages_format);
5834 if (!pdftex_name.empty()) {
5839 FileName const absname = makeAbsPath(name, path);
5840 if (absname.exists())
5842 fix_child_filename(name);
5843 copy_file(absname, name);
5845 cerr << "Warning: Could not find file '"
5846 << name << "'." << endl;
5848 context.check_layout(os);
5849 begin_inset(os, "External\n\ttemplate ");
5850 os << "PDFPages\n\tfilename "
5852 // parse the options
5853 if (opts.find("pages") != opts.end())
5854 os << "\textra LaTeX \"pages="
5855 << opts["pages"] << "\"\n";
5856 if (opts.find("angle") != opts.end())
5857 os << "\trotateAngle "
5858 << opts["angle"] << '\n';
5859 if (opts.find("origin") != opts.end()) {
5861 string const opt = opts["origin"];
5862 if (opt == "tl") ss << "topleft";
5863 if (opt == "bl") ss << "bottomleft";
5864 if (opt == "Bl") ss << "baselineleft";
5865 if (opt == "c") ss << "center";
5866 if (opt == "tc") ss << "topcenter";
5867 if (opt == "bc") ss << "bottomcenter";
5868 if (opt == "Bc") ss << "baselinecenter";
5869 if (opt == "tr") ss << "topright";
5870 if (opt == "br") ss << "bottomright";
5871 if (opt == "Br") ss << "baselineright";
5872 if (!ss.str().empty())
5873 os << "\trotateOrigin " << ss.str() << '\n';
5875 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5877 if (opts.find("width") != opts.end())
5879 << translate_len(opts["width"]) << '\n';
5880 if (opts.find("height") != opts.end())
5882 << translate_len(opts["height"]) << '\n';
5883 if (opts.find("keepaspectratio") != opts.end())
5884 os << "\tkeepAspectRatio\n";
5886 context.check_layout(os);
5887 registerExternalTemplatePackages("PDFPages");
5891 if (t.cs() == "loadgame") {
5893 string name = normalize_filename(p.verbatim_item());
5894 string const path = getMasterFilePath(true);
5895 // We want to preserve relative / absolute filenames,
5896 // therefore path is only used for testing
5897 if (!makeAbsPath(name, path).exists()) {
5898 // The file extension is probably missing.
5899 // Now try to find it out.
5900 char const * const lyxskak_format[] = {"fen", 0};
5901 string const lyxskak_name =
5902 find_file(name, path, lyxskak_format);
5903 if (!lyxskak_name.empty())
5904 name = lyxskak_name;
5906 FileName const absname = makeAbsPath(name, path);
5907 if (absname.exists())
5909 fix_child_filename(name);
5910 copy_file(absname, name);
5912 cerr << "Warning: Could not find file '"
5913 << name << "'." << endl;
5914 context.check_layout(os);
5915 begin_inset(os, "External\n\ttemplate ");
5916 os << "ChessDiagram\n\tfilename "
5919 context.check_layout(os);
5920 // after a \loadgame follows a \showboard
5921 if (p.get_token().asInput() == "showboard")
5923 registerExternalTemplatePackages("ChessDiagram");
5927 // try to see whether the string is in unicodesymbols
5928 // Only use text mode commands, since we are in text mode here,
5929 // and math commands may be invalid (bug 6797)
5930 string name = t.asInput();
5931 // handle the dingbats, cyrillic and greek
5932 if (name == "\\textcyr")
5933 name = "\\textcyrillic";
5934 if (name == "\\ding" || name == "\\textcyrillic" ||
5935 (name == "\\textgreek" && !preamble.usePolyglossia()))
5936 name = name + '{' + p.getArg('{', '}') + '}';
5937 // handle the ifsym characters
5938 else if (name == "\\textifsymbol") {
5939 string const optif = p.getFullOpt();
5940 string const argif = p.getArg('{', '}');
5941 name = name + optif + '{' + argif + '}';
5943 // handle the \ascii characters
5944 // the case of \ascii within braces, as LyX outputs it, is already
5945 // handled for t.cat() == catBegin
5946 else if (name == "\\ascii") {
5947 // the code is "\asci\xxx"
5948 name = "{" + name + p.get_token().asInput() + "}";
5951 // handle some TIPA special characters
5952 else if (preamble.isPackageUsed("tipa")) {
5953 if (name == "\\s") {
5954 // fromLaTeXCommand() does not yet
5955 // recognize tipa short cuts
5956 name = "\\textsyllabic";
5957 } else if (name == "\\=" &&
5958 p.next_token().asInput() == "*") {
5959 // fromLaTeXCommand() does not yet
5960 // recognize tipa short cuts
5962 name = "\\textsubbar";
5963 } else if (name == "\\textdoublevertline") {
5964 // FIXME: This is not correct,
5965 // \textvertline is higher than \textbardbl
5966 name = "\\textbardbl";
5968 } else if (name == "\\!" ) {
5969 if (p.next_token().asInput() == "b") {
5970 p.get_token(); // eat 'b'
5973 } else if (p.next_token().asInput() == "d") {
5977 } else if (p.next_token().asInput() == "g") {
5981 } else if (p.next_token().asInput() == "G") {
5983 name = "\\texthtscg";
5985 } else if (p.next_token().asInput() == "j") {
5987 name = "\\texthtbardotlessj";
5989 } else if (p.next_token().asInput() == "o") {
5991 name = "\\textbullseye";
5994 } else if (name == "\\*" ) {
5995 if (p.next_token().asInput() == "k") {
5997 name = "\\textturnk";
5999 } else if (p.next_token().asInput() == "r") {
6000 p.get_token(); // eat 'b'
6001 name = "\\textturnr";
6003 } else if (p.next_token().asInput() == "t") {
6005 name = "\\textturnt";
6007 } else if (p.next_token().asInput() == "w") {
6009 name = "\\textturnw";
6014 if ((name.size() == 2 &&
6015 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6016 p.next_token().asInput() != "*") ||
6017 is_known(name.substr(1), known_tipa_marks)) {
6018 // name is a command that corresponds to a
6019 // combining character in unicodesymbols.
6020 // Append the argument, fromLaTeXCommand()
6021 // will either convert it to a single
6022 // character or a combining sequence.
6023 name += '{' + p.verbatim_item() + '}';
6025 // now get the character from unicodesymbols
6029 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6030 Encodings::TEXT_CMD, termination, rem, &req));
6032 context.check_layout(os);
6035 output_ert_inset(os, to_utf8(rem), context);
6037 skip_spaces_braces(p);
6038 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6039 preamble.registerAutomaticallyLoadedPackage(*it);
6041 //cerr << "#: " << t << " mode: " << mode << endl;
6042 // heuristic: read up to next non-nested space
6044 string s = t.asInput();
6045 string z = p.verbatim_item();
6046 while (p.good() && z != " " && !z.empty()) {
6047 //cerr << "read: " << z << endl;
6049 z = p.verbatim_item();
6051 cerr << "found ERT: " << s << endl;
6052 output_ert_inset(os, s + ' ', context);
6055 if (t.asInput() == name &&
6056 p.next_token().asInput() == "*") {
6057 // Starred commands like \vspace*{}
6058 p.get_token(); // Eat '*'
6061 if (!parse_command(name, p, os, outer, context))
6062 output_ert_inset(os, name, context);
6068 string guessLanguage(Parser & p, string const & lang)
6070 typedef std::map<std::string, size_t> LangMap;
6071 // map from language names to number of characters
6074 for (char const * const * i = supported_CJK_languages; *i; i++)
6075 used[string(*i)] = 0;
6078 Token const t = p.get_token();
6079 // comments are not counted for any language
6080 if (t.cat() == catComment)
6082 // commands are not counted as well, but we need to detect
6083 // \begin{CJK} and switch encoding if needed
6084 if (t.cat() == catEscape) {
6085 if (t.cs() == "inputencoding") {
6086 string const enc = subst(p.verbatim_item(), "\n", " ");
6087 p.setEncoding(enc, Encoding::inputenc);
6090 if (t.cs() != "begin")
6093 // Non-CJK content is counted for lang.
6094 // We do not care about the real language here:
6095 // If we have more non-CJK contents than CJK contents,
6096 // we simply use the language that was specified as
6097 // babel main language.
6098 used[lang] += t.asInput().length();
6101 // Now we are starting an environment
6103 string const name = p.getArg('{', '}');
6104 if (name != "CJK") {
6108 // It is a CJK environment
6110 /* name = */ p.getArg('{', '}');
6111 string const encoding = p.getArg('{', '}');
6112 /* mapping = */ p.getArg('{', '}');
6113 string const encoding_old = p.getEncoding();
6114 char const * const * const where =
6115 is_known(encoding, supported_CJK_encodings);
6117 p.setEncoding(encoding, Encoding::CJK);
6119 p.setEncoding("UTF-8");
6120 string const text = p.ertEnvironment("CJK");
6121 p.setEncoding(encoding_old);
6124 // ignore contents in unknown CJK encoding
6127 // the language of the text
6129 supported_CJK_languages[where - supported_CJK_encodings];
6130 used[cjk] += text.length();
6132 LangMap::const_iterator use = used.begin();
6133 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6134 if (it->second > use->second)
6141 void check_comment_bib(ostream & os, Context & context)
6143 if (!need_commentbib)
6145 // We have a bibliography database, but no bibliography with biblatex
6146 // which is completely valid. Insert a bibtex inset in a note.
6147 context.check_layout(os);
6148 begin_inset(os, "Note Note\n");
6149 os << "status open\n";
6150 os << "\\begin_layout Plain Layout\n";
6151 begin_command_inset(os, "bibtex", "bibtex");
6153 for (auto const & bf : preamble.biblatex_bibliographies) {
6154 if (!bibfiles.empty())
6156 bibfiles += normalize_filename(bf);
6158 if (!bibfiles.empty())
6159 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6160 end_inset(os);// Bibtex
6161 os << "\\end_layout\n";
6162 end_inset(os);// Note