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")
534 string translate_len(string const & length)
538 if (translate_len(length, value, unit))
540 // If the input is invalid, return what we have.
548 * Translates a LaTeX length into \p value, \p unit and
549 * \p special parts suitable for a box inset.
550 * The difference from translate_len() is that a box inset knows about
551 * some special "units" that are stored in \p special.
553 void translate_box_len(string const & length, string & value, string & unit, string & special)
555 if (translate_len(length, value, unit)) {
556 if (unit == "\\height" || unit == "\\depth" ||
557 unit == "\\totalheight" || unit == "\\width") {
558 special = unit.substr(1);
559 // The unit is not used, but LyX requires a dummy setting
571 void begin_inset(ostream & os, string const & name)
573 os << "\n\\begin_inset " << name;
577 void begin_command_inset(ostream & os, string const & name,
578 string const & latexname)
580 begin_inset(os, "CommandInset ");
581 os << name << "\nLatexCommand " << latexname << '\n';
585 void end_inset(ostream & os)
587 os << "\n\\end_inset\n\n";
591 bool skip_braces(Parser & p)
593 if (p.next_token().cat() != catBegin)
596 if (p.next_token().cat() == catEnd) {
605 /// replace LaTeX commands in \p s from the unicodesymbols file with their
607 pair<bool, docstring> convert_unicodesymbols(docstring s)
611 for (size_t i = 0; i < s.size();) {
620 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
621 Encodings::TEXT_CMD, termination, rem, &req));
622 set<string>::const_iterator it = req.begin();
623 set<string>::const_iterator en = req.end();
624 for (; it != en; ++it)
625 preamble.registerAutomaticallyLoadedPackage(*it);
628 if (s.empty() || s[0] != '\\')
632 for (auto const & c : known_escaped_chars)
633 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
638 return make_pair(res, os.str());
642 /// try to convert \p s to a valid InsetCommand argument
643 /// return whether this succeeded. If not, these command insets
644 /// get the "literate" flag.
645 pair<bool, string> convert_latexed_command_inset_arg(string s)
647 bool success = false;
649 // since we don't know the input encoding we can't use from_utf8
650 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
652 s = to_utf8(res.second);
654 // LyX cannot handle newlines in a latex command
655 return make_pair(success, subst(s, "\n", " "));
658 /// try to convert \p s to a valid InsetCommand argument
659 /// without trying to recode macros.
660 string convert_literate_command_inset_arg(string s)
662 // LyX cannot handle newlines in a latex command
663 return subst(s, "\n", " ");
666 void output_ert(ostream & os, string const & s, Context & context)
668 context.check_layout(os);
669 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
671 os << "\n\\backslash\n";
672 else if (*it == '\n') {
673 context.new_paragraph(os);
674 context.check_layout(os);
678 context.check_end_layout(os);
682 void output_ert_inset(ostream & os, string const & s, Context & context)
684 // We must have a valid layout before outputting the ERT inset.
685 context.check_layout(os);
686 Context newcontext(true, context.textclass);
687 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
688 if (layout.forcePlainLayout())
689 newcontext.layout = &context.textclass.plainLayout();
690 begin_inset(os, "ERT");
691 os << "\nstatus collapsed\n";
692 output_ert(os, s, newcontext);
697 void output_comment(Parser & p, ostream & os, string const & s,
700 if (p.next_token().cat() == catNewline)
701 output_ert_inset(os, '%' + s, context);
703 output_ert_inset(os, '%' + s + '\n', context);
707 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
708 string const & latexparam = string())
710 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
713 if (checkModule(name, command))
714 return findLayoutWithoutModule(textclass, name, command, latexparam);
719 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
720 string const & latexparam = string())
722 InsetLayout const * insetlayout =
723 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
726 if (checkModule(name, command))
727 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
732 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
733 bool eatNewline = true);
737 * Skips whitespace and braces.
738 * This should be called after a command has been parsed that is not put into
739 * ERT, and where LyX adds "{}" if needed.
741 void skip_spaces_braces(Parser & p, bool keepws = false)
743 /* The following four examples produce the same typeset output and
744 should be handled by this function:
752 // Unfortunately we need to skip comments, too.
753 // We can't use eat_whitespace since writing them after the {}
754 // results in different output in some cases.
755 bool const skipped_spaces = p.skip_spaces(true);
756 bool const skipped_braces = skip_braces(p);
757 if (keepws && skipped_spaces && !skipped_braces)
758 // put back the space (it is better handled by check_space)
759 p.unskip_spaces(true);
763 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
764 Context & context, Layout::LaTeXArgMap const & latexargs)
766 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
768 context.check_layout(os);
774 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
775 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
776 for (; lait != laend; ++lait) {
778 eat_whitespace(p, os, context, false);
779 if (lait->second.mandatory) {
780 if (p.next_token().cat() != catBegin)
782 string ldelim = to_utf8(lait->second.ldelim);
783 string rdelim = to_utf8(lait->second.rdelim);
788 p.get_token(); // eat ldelim
789 if (ldelim.size() > 1)
790 p.get_token(); // eat ldelim
792 context.check_layout(os);
795 begin_inset(os, "Argument ");
798 os << i << "\nstatus collapsed\n\n";
799 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
802 string ldelim = to_utf8(lait->second.ldelim);
803 string rdelim = to_utf8(lait->second.rdelim);
808 string tok = p.next_token().asInput();
809 // we only support delimiters with max 2 chars for now.
810 if (ldelim.size() > 1)
811 tok += p.next_next_token().asInput();
812 if (p.next_token().cat() == catEscape || tok != ldelim)
814 p.get_token(); // eat ldelim
815 if (ldelim.size() > 1)
816 p.get_token(); // eat ldelim
818 context.check_layout(os);
821 begin_inset(os, "Argument ");
824 os << i << "\nstatus collapsed\n\n";
825 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
828 eat_whitespace(p, os, context, false);
833 void output_command_layout(ostream & os, Parser & p, bool outer,
834 Context & parent_context,
835 Layout const * newlayout)
837 TeXFont const oldFont = parent_context.font;
838 // save the current font size
839 string const size = oldFont.size;
840 // reset the font size to default, because the font size switches
841 // don't affect section headings and the like
842 parent_context.font.size = Context::normalfont.size;
843 // we only need to write the font change if we have an open layout
844 if (!parent_context.atParagraphStart())
845 output_font_change(os, oldFont, parent_context.font);
846 parent_context.check_end_layout(os);
847 Context context(true, parent_context.textclass, newlayout,
848 parent_context.layout, parent_context.font);
849 if (parent_context.deeper_paragraph) {
850 // We are beginning a nested environment after a
851 // deeper paragraph inside the outer list environment.
852 // Therefore we don't need to output a "begin deeper".
853 context.need_end_deeper = true;
855 context.check_deeper(os);
856 output_arguments(os, p, outer, true, string(), context,
857 context.layout->latexargs());
858 // If we have a latex param, we eat it here.
859 if (!parent_context.latexparam.empty()) {
861 Context dummy(true, parent_context.textclass);
862 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
863 string(1, parent_context.latexparam.back()));
865 parse_text(p, os, FLAG_ITEM, outer, context);
866 output_arguments(os, p, outer, false, "post", context,
867 context.layout->postcommandargs());
868 context.check_end_layout(os);
869 if (parent_context.deeper_paragraph) {
870 // We must suppress the "end deeper" because we
871 // suppressed the "begin deeper" above.
872 context.need_end_deeper = false;
874 context.check_end_deeper(os);
875 // We don't need really a new paragraph, but
876 // we must make sure that the next item gets a \begin_layout.
877 parent_context.new_paragraph(os);
878 // Set the font size to the original value. No need to output it here
879 // (Context::begin_layout() will do that if needed)
880 parent_context.font.size = size;
885 * Output a space if necessary.
886 * This function gets called for every whitespace token.
888 * We have three cases here:
889 * 1. A space must be suppressed. Example: The lyxcode case below
890 * 2. A space may be suppressed. Example: Spaces before "\par"
891 * 3. A space must not be suppressed. Example: A space between two words
893 * We currently handle only 1. and 3 and from 2. only the case of
894 * spaces before newlines as a side effect.
896 * 2. could be used to suppress as many spaces as possible. This has two effects:
897 * - Reimporting LyX generated LaTeX files changes almost no whitespace
898 * - Superflous whitespace from non LyX generated LaTeX files is removed.
899 * The drawback is that the logic inside the function becomes
900 * complicated, and that is the reason why it is not implemented.
902 void check_space(Parser & p, ostream & os, Context & context)
904 Token const next = p.next_token();
905 Token const curr = p.curr_token();
906 // A space before a single newline and vice versa must be ignored
907 // LyX emits a newline before \end{lyxcode}.
908 // This newline must be ignored,
909 // otherwise LyX will add an additional protected space.
910 if (next.cat() == catSpace ||
911 next.cat() == catNewline ||
912 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
915 context.check_layout(os);
921 * Parse all arguments of \p command
923 void parse_arguments(string const & command,
924 vector<ArgumentType> const & template_arguments,
925 Parser & p, ostream & os, bool outer, Context & context)
927 string ert = command;
928 size_t no_arguments = template_arguments.size();
929 for (size_t i = 0; i < no_arguments; ++i) {
930 switch (template_arguments[i]) {
933 // This argument contains regular LaTeX
934 output_ert_inset(os, ert + '{', context);
935 eat_whitespace(p, os, context, false);
936 if (template_arguments[i] == required)
937 parse_text(p, os, FLAG_ITEM, outer, context);
939 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
943 // This argument consists only of a single item.
944 // The presence of '{' or not must be preserved.
946 if (p.next_token().cat() == catBegin)
947 ert += '{' + p.verbatim_item() + '}';
949 ert += p.verbatim_item();
953 // This argument may contain special characters
954 ert += '{' + p.verbatim_item() + '}';
958 // true because we must not eat whitespace
959 // if an optional arg follows we must not strip the
960 // brackets from this one
961 if (i < no_arguments - 1 &&
962 template_arguments[i+1] == optional)
963 ert += p.getFullOpt(true);
965 ert += p.getOpt(true);
969 output_ert_inset(os, ert, context);
974 * Check whether \p command is a known command. If yes,
975 * handle the command with all arguments.
976 * \return true if the command was parsed, false otherwise.
978 bool parse_command(string const & command, Parser & p, ostream & os,
979 bool outer, Context & context)
981 if (known_commands.find(command) != known_commands.end()) {
982 parse_arguments(command, known_commands[command], p, os,
990 /// Parses a minipage or parbox
991 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
992 unsigned inner_flags, bool outer, Context & parent_context,
993 string const & outer_type, string const & special,
994 string inner_type, string const & frame_color,
995 string const & background_color)
999 string hor_pos = "l";
1000 // We need to set the height to the LaTeX default of 1\\totalheight
1001 // for the case when no height argument is given
1002 string height_value = "1";
1003 string height_unit = "in";
1004 string height_special = "totalheight";
1005 string latex_height;
1009 string width_special = "none";
1010 string thickness = "0.4pt";
1011 if (!fboxrule.empty())
1012 thickness = fboxrule;
1014 thickness = "0.4pt";
1016 if (!fboxsep.empty())
1017 separation = fboxsep;
1021 if (!shadow_size.empty())
1022 shadowsize = shadow_size;
1025 string framecolor = "black";
1026 string backgroundcolor = "none";
1027 if (!frame_color.empty())
1028 framecolor = frame_color;
1029 if (!background_color.empty())
1030 backgroundcolor = background_color;
1031 // if there is a color box around the \begin statements have not yet been parsed
1033 if (!frame_color.empty() || !background_color.empty()) {
1034 eat_whitespace(p, os, parent_context, false);
1035 p.get_token().asInput(); // the '{'
1037 if (p.next_token().asInput() == "\\begin") {
1038 p.get_token().asInput();
1040 inner_type = "minipage";
1041 inner_flags = FLAG_END;
1042 active_environments.push_back("minipage");
1045 else if (p.next_token().asInput() == "\\parbox") {
1046 p.get_token().asInput();
1047 inner_type = "parbox";
1048 inner_flags = FLAG_ITEM;
1051 else if (p.next_token().asInput() == "\\makebox") {
1052 p.get_token().asInput();
1053 inner_type = "makebox";
1054 inner_flags = FLAG_ITEM;
1056 // in case there is just \colorbox{color}{text}
1059 inner_type = "makebox";
1060 inner_flags = FLAG_BRACE_LAST;
1065 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1067 if (!inner_type.empty() && p.hasOpt()) {
1068 if (inner_type != "makebox")
1069 position = p.getArg('[', ']');
1071 latex_width = p.getArg('[', ']');
1072 translate_box_len(latex_width, width_value, width_unit, width_special);
1075 if (position != "t" && position != "c" && position != "b") {
1076 cerr << "invalid position " << position << " for "
1077 << inner_type << endl;
1081 if (inner_type != "makebox") {
1082 latex_height = p.getArg('[', ']');
1083 translate_box_len(latex_height, height_value, height_unit, height_special);
1085 string const opt = p.getArg('[', ']');
1088 if (hor_pos != "l" && hor_pos != "c" &&
1089 hor_pos != "r" && hor_pos != "s") {
1090 cerr << "invalid hor_pos " << hor_pos
1091 << " for " << inner_type << endl;
1098 inner_pos = p.getArg('[', ']');
1099 if (inner_pos != "c" && inner_pos != "t" &&
1100 inner_pos != "b" && inner_pos != "s") {
1101 cerr << "invalid inner_pos "
1102 << inner_pos << " for "
1103 << inner_type << endl;
1104 inner_pos = position;
1108 if (inner_type == "makebox")
1112 if (inner_type.empty()) {
1113 if (special.empty() && outer_type != "framebox")
1114 latex_width = "1\\columnwidth";
1117 latex_width = p2.getArg('[', ']');
1118 string const opt = p2.getArg('[', ']');
1121 if (hor_pos != "l" && hor_pos != "c" &&
1122 hor_pos != "r" && hor_pos != "s") {
1123 cerr << "invalid hor_pos " << hor_pos
1124 << " for " << outer_type << endl;
1128 if (outer_type == "framebox")
1132 } else if (inner_type != "makebox")
1133 latex_width = p.verbatim_item();
1134 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1135 // as this is LyX's standard for such cases (except for makebox)
1136 // \framebox is more special and handled below
1137 if (latex_width.empty() && inner_type != "makebox"
1138 && outer_type != "framebox")
1139 latex_width = "1\\columnwidth";
1141 translate_len(latex_width, width_value, width_unit);
1143 bool shadedparbox = false;
1144 if (inner_type == "shaded") {
1145 eat_whitespace(p, os, parent_context, false);
1146 if (outer_type == "parbox") {
1148 if (p.next_token().cat() == catBegin)
1150 eat_whitespace(p, os, parent_context, false);
1151 shadedparbox = true;
1156 // If we already read the inner box we have to push the inner env
1157 if (!outer_type.empty() && !inner_type.empty() &&
1158 (inner_flags & FLAG_END))
1159 active_environments.push_back(inner_type);
1160 bool use_ert = false;
1161 if (!outer_type.empty() && !inner_type.empty()) {
1162 // Look whether there is some content after the end of the
1163 // inner box, but before the end of the outer box.
1164 // If yes, we need to output ERT.
1166 if (inner_flags & FLAG_END)
1167 p.ertEnvironment(inner_type);
1170 p.skip_spaces(true);
1171 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1172 if ((outer_env && p.next_token().asInput() != "\\end") ||
1173 (!outer_env && p.next_token().cat() != catEnd)) {
1174 // something is between the end of the inner box and
1175 // the end of the outer box, so we need to use ERT.
1183 if (!outer_type.empty()) {
1184 if (outer_flags & FLAG_END)
1185 ss << "\\begin{" << outer_type << '}';
1187 ss << '\\' << outer_type << '{';
1188 if (!special.empty())
1192 if (!inner_type.empty()) {
1193 if (inner_type != "shaded") {
1194 if (inner_flags & FLAG_END)
1195 ss << "\\begin{" << inner_type << '}';
1197 ss << '\\' << inner_type;
1199 if (!position.empty())
1200 ss << '[' << position << ']';
1201 if (!latex_height.empty())
1202 ss << '[' << latex_height << ']';
1203 if (!inner_pos.empty())
1204 ss << '[' << inner_pos << ']';
1205 ss << '{' << latex_width << '}';
1206 if (!(inner_flags & FLAG_END))
1209 if (inner_type == "shaded")
1210 ss << "\\begin{shaded}";
1211 output_ert_inset(os, ss.str(), parent_context);
1212 if (!inner_type.empty()) {
1213 parse_text(p, os, inner_flags, outer, parent_context);
1214 if (inner_flags & FLAG_END)
1215 output_ert_inset(os, "\\end{" + inner_type + '}',
1218 output_ert_inset(os, "}", parent_context);
1220 if (!outer_type.empty()) {
1221 // If we already read the inner box we have to pop
1223 if (!inner_type.empty() && (inner_flags & FLAG_END))
1224 active_environments.pop_back();
1226 // Ensure that the end of the outer box is parsed correctly:
1227 // The opening brace has been eaten by parse_outer_box()
1228 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1229 outer_flags &= ~FLAG_ITEM;
1230 outer_flags |= FLAG_BRACE_LAST;
1232 parse_text(p, os, outer_flags, outer, parent_context);
1233 if (outer_flags & FLAG_END)
1234 output_ert_inset(os, "\\end{" + outer_type + '}',
1237 output_ert_inset(os, "}", parent_context);
1240 // LyX does not like empty positions, so we have
1241 // to set them to the LaTeX default values here.
1242 if (position.empty())
1244 if (inner_pos.empty())
1245 inner_pos = position;
1246 parent_context.check_layout(os);
1247 begin_inset(os, "Box ");
1248 if (outer_type == "framed")
1250 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1252 else if (outer_type == "shadowbox")
1253 os << "Shadowbox\n";
1254 else if ((outer_type == "shaded" && inner_type.empty()) ||
1255 (outer_type == "minipage" && inner_type == "shaded") ||
1256 (outer_type == "parbox" && inner_type == "shaded")) {
1258 preamble.registerAutomaticallyLoadedPackage("color");
1259 } else if (outer_type == "doublebox")
1260 os << "Doublebox\n";
1261 else if (outer_type.empty() || outer_type == "mbox")
1262 os << "Frameless\n";
1264 os << outer_type << '\n';
1265 os << "position \"" << position << "\"\n";
1266 os << "hor_pos \"" << hor_pos << "\"\n";
1267 if (outer_type == "mbox")
1268 os << "has_inner_box 1\n";
1269 else if (!frame_color.empty() && inner_type == "makebox")
1270 os << "has_inner_box 0\n";
1272 os << "has_inner_box " << !inner_type.empty() << "\n";
1273 os << "inner_pos \"" << inner_pos << "\"\n";
1274 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1276 if (outer_type == "mbox")
1277 os << "use_makebox 1\n";
1278 else if (!frame_color.empty())
1279 os << "use_makebox 0\n";
1281 os << "use_makebox " << (inner_type == "makebox") << '\n';
1282 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1283 os << "width \"\"\n";
1284 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1285 else if (contains(width_unit, '\\'))
1286 os << "width \"" << width_value << "in" << "\"\n";
1288 os << "width \"" << width_value << width_unit << "\"\n";
1289 if (contains(width_unit, '\\')) {
1290 width_unit.erase (0,1); // remove the leading '\'
1291 os << "special \"" << width_unit << "\"\n";
1293 os << "special \"" << width_special << "\"\n";
1294 if (contains(height_unit, '\\'))
1295 os << "height \"" << height_value << "in" << "\"\n";
1297 os << "height \"" << height_value << height_unit << "\"\n";
1298 os << "height_special \"" << height_special << "\"\n";
1299 os << "thickness \"" << thickness << "\"\n";
1300 os << "separation \"" << separation << "\"\n";
1301 os << "shadowsize \"" << shadowsize << "\"\n";
1302 os << "framecolor \"" << framecolor << "\"\n";
1303 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1304 os << "status open\n\n";
1306 // Unfortunately we can't use parse_text_in_inset:
1307 // InsetBox::forcePlainLayout() is hard coded and does not
1308 // use the inset layout. Apart from that do we call parse_text
1309 // up to two times, but need only one check_end_layout.
1310 bool const forcePlainLayout =
1311 (!inner_type.empty() || inner_type == "makebox") &&
1312 outer_type != "shaded" && outer_type != "framed";
1313 Context context(true, parent_context.textclass);
1314 if (forcePlainLayout)
1315 context.layout = &context.textclass.plainLayout();
1317 context.font = parent_context.font;
1319 // If we have no inner box the contents will be read with the outer box
1320 if (!inner_type.empty())
1321 parse_text(p, os, inner_flags, outer, context);
1323 // Ensure that the end of the outer box is parsed correctly:
1324 // The opening brace has been eaten by parse_outer_box()
1325 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1326 outer_flags &= ~FLAG_ITEM;
1327 outer_flags |= FLAG_BRACE_LAST;
1330 // Find end of outer box, output contents if inner_type is
1331 // empty and output possible comments
1332 if (!outer_type.empty()) {
1333 // If we already read the inner box we have to pop
1335 if (!inner_type.empty() && (inner_flags & FLAG_END))
1336 active_environments.pop_back();
1337 // This does not output anything but comments if
1338 // inner_type is not empty (see use_ert)
1339 parse_text(p, os, outer_flags, outer, context);
1342 context.check_end_layout(os);
1344 #ifdef PRESERVE_LAYOUT
1345 // LyX puts a % after the end of the minipage
1346 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1348 //output_comment(p, os, "dummy", parent_context);
1351 parent_context.new_paragraph(os);
1353 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1354 //output_comment(p, os, "dummy", parent_context);
1357 // We add a protected space if something real follows
1358 if (p.good() && p.next_token().cat() != catComment) {
1359 begin_inset(os, "space ~\n");
1365 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1366 active_environments.pop_back();
1367 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1368 // in this case we have to eat the the closing brace of the color box
1369 p.get_token().asInput(); // the '}'
1371 if (p.next_token().asInput() == "}") {
1372 // in this case we assume that the closing brace is from the box settings
1373 // therefore reset these values for the next box
1379 // all boxes except of Frameless and Shaded require calc
1380 if (!(outer_type.empty() || outer_type == "mbox") &&
1381 !((outer_type == "shaded" && inner_type.empty()) ||
1382 (outer_type == "minipage" && inner_type == "shaded") ||
1383 (outer_type == "parbox" && inner_type == "shaded")))
1384 preamble.registerAutomaticallyLoadedPackage("calc");
1388 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1389 Context & parent_context, string const & outer_type,
1390 string const & special)
1392 eat_whitespace(p, os, parent_context, false);
1393 if (flags & FLAG_ITEM) {
1395 if (p.next_token().cat() == catBegin)
1398 cerr << "Warning: Ignoring missing '{' after \\"
1399 << outer_type << '.' << endl;
1400 eat_whitespace(p, os, parent_context, false);
1403 unsigned int inner_flags = 0;
1405 if (outer_type == "minipage" || outer_type == "parbox") {
1406 p.skip_spaces(true);
1407 while (p.hasOpt()) {
1409 p.skip_spaces(true);
1412 p.skip_spaces(true);
1413 if (outer_type == "parbox") {
1415 if (p.next_token().cat() == catBegin)
1417 p.skip_spaces(true);
1420 if (outer_type == "shaded" || outer_type == "mbox") {
1421 // These boxes never have an inner box
1423 } else if (p.next_token().asInput() == "\\parbox") {
1424 inner = p.get_token().cs();
1425 inner_flags = FLAG_ITEM;
1426 } else if (p.next_token().asInput() == "\\begin") {
1427 // Is this a minipage or shaded box?
1430 inner = p.getArg('{', '}');
1432 if (inner == "minipage" || inner == "shaded")
1433 inner_flags = FLAG_END;
1438 if (inner_flags == FLAG_END) {
1439 if (inner != "shaded")
1443 eat_whitespace(p, os, parent_context, false);
1445 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1446 outer_type, special, inner, "", "");
1448 if (inner_flags == FLAG_ITEM) {
1450 eat_whitespace(p, os, parent_context, false);
1452 parse_box(p, os, flags, inner_flags, outer, parent_context,
1453 outer_type, special, inner, "", "");
1458 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1459 bool in_line, bool use_minted)
1461 parent_context.check_layout(os);
1462 begin_inset(os, "listings\n");
1463 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1465 while ((i = arg.find(", ")) != string::npos
1466 || (i = arg.find(",\t")) != string::npos)
1467 arg.erase(i + 1, 1);
1470 string const language = p.getArg('{', '}');
1471 p.skip_spaces(true);
1472 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1473 if (!minted_float.empty()) {
1474 arg += string(arg.empty() ? "" : ",") + minted_float;
1475 minted_nonfloat_caption.clear();
1479 os << "lstparams " << '"' << arg << '"' << '\n';
1480 if (arg.find("\\color") != string::npos)
1481 preamble.registerAutomaticallyLoadedPackage("color");
1484 os << "inline true\n";
1486 os << "inline false\n";
1487 os << "status open\n";
1488 Context context(true, parent_context.textclass);
1489 context.layout = &parent_context.textclass.plainLayout();
1490 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1491 minted_nonfloat_caption.erase(0,3);
1492 os << "\n\\begin_layout Plain Layout\n";
1493 begin_inset(os, "Caption Standard\n");
1494 Context newcontext(true, context.textclass,
1495 context.layout, 0, context.font);
1496 newcontext.check_layout(os);
1497 os << minted_nonfloat_caption << "\n";
1498 newcontext.check_end_layout(os);
1500 os << "\n\\end_layout\n";
1501 minted_nonfloat_caption.clear();
1505 // set catcodes to verbatim early, just in case.
1506 p.setCatcodes(VERBATIM_CATCODES);
1507 string delim = p.get_token().asInput();
1508 //FIXME: handler error condition
1509 s = p.verbatimStuff(delim).second;
1510 // context.new_paragraph(os);
1511 } else if (use_minted) {
1512 s = p.verbatimEnvironment("minted");
1514 s = p.verbatimEnvironment("lstlisting");
1516 output_ert(os, s, context);
1517 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1518 minted_nonfloat_caption.erase(0,3);
1519 os << "\n\\begin_layout Plain Layout\n";
1520 begin_inset(os, "Caption Standard\n");
1521 Context newcontext(true, context.textclass,
1522 context.layout, 0, context.font);
1523 newcontext.check_layout(os);
1524 os << minted_nonfloat_caption << "\n";
1525 newcontext.check_end_layout(os);
1527 os << "\n\\end_layout\n";
1528 minted_nonfloat_caption.clear();
1530 // Don't close the inset here for floating minted listings.
1531 // It will be closed at the end of the listing environment.
1532 if (!use_minted || minted_float.empty())
1535 eat_whitespace(p, os, parent_context, true);
1536 Token t = p.get_token();
1537 if (t.asInput() != "\\end") {
1538 // If anything follows, collect it into a caption.
1539 minted_float_has_caption = true;
1540 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1541 begin_inset(os, "Caption Standard\n");
1542 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1549 /// parse an unknown environment
1550 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1551 unsigned flags, bool outer,
1552 Context & parent_context)
1554 if (name == "tabbing")
1555 // We need to remember that we have to handle '\=' specially
1556 flags |= FLAG_TABBING;
1558 // We need to translate font changes and paragraphs inside the
1559 // environment to ERT if we have a non standard font.
1560 // Otherwise things like
1561 // \large\begin{foo}\huge bar\end{foo}
1563 bool const specialfont =
1564 (parent_context.font != parent_context.normalfont);
1565 bool const new_layout_allowed = parent_context.new_layout_allowed;
1567 parent_context.new_layout_allowed = false;
1568 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1569 parse_text_snippet(p, os, flags, outer, parent_context);
1570 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1572 parent_context.new_layout_allowed = new_layout_allowed;
1576 void parse_environment(Parser & p, ostream & os, bool outer,
1577 string & last_env, Context & parent_context)
1579 Layout const * newlayout;
1580 InsetLayout const * newinsetlayout = 0;
1581 string const name = p.getArg('{', '}');
1582 const bool is_starred = suffixIs(name, '*');
1583 string const unstarred_name = rtrim(name, "*");
1584 active_environments.push_back(name);
1586 if (is_math_env(name)) {
1587 parent_context.check_layout(os);
1588 begin_inset(os, "Formula ");
1589 os << "\\begin{" << name << "}";
1590 parse_math(p, os, FLAG_END, MATH_MODE);
1591 os << "\\end{" << name << "}";
1593 if (is_display_math_env(name)) {
1594 // Prevent the conversion of a line break to a space
1595 // (bug 7668). This does not change the output, but
1596 // looks ugly in LyX.
1597 eat_whitespace(p, os, parent_context, false);
1601 else if (is_known(name, preamble.polyglossia_languages)) {
1602 // We must begin a new paragraph if not already done
1603 if (! parent_context.atParagraphStart()) {
1604 parent_context.check_end_layout(os);
1605 parent_context.new_paragraph(os);
1607 // save the language in the context so that it is
1608 // handled by parse_text
1609 parent_context.font.language = preamble.polyglossia2lyx(name);
1610 parse_text(p, os, FLAG_END, outer, parent_context);
1611 // Just in case the environment is empty
1612 parent_context.extra_stuff.erase();
1613 // We must begin a new paragraph to reset the language
1614 parent_context.new_paragraph(os);
1618 else if (unstarred_name == "tabular" || name == "longtable"
1619 || name == "tabularx" || name == "xltabular") {
1620 eat_whitespace(p, os, parent_context, false);
1621 string width = "0pt";
1623 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1624 string const opt = p.getArg('[', ']');
1627 else if (opt == "l")
1629 else if (opt == "r")
1632 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1633 width = lyx::translate_len(p.getArg('{', '}'));
1634 eat_whitespace(p, os, parent_context, false);
1636 parent_context.check_layout(os);
1637 begin_inset(os, "Tabular ");
1638 handle_tabular(p, os, name, width, halign, parent_context);
1643 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1644 eat_whitespace(p, os, parent_context, false);
1645 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1646 eat_whitespace(p, os, parent_context, false);
1647 parent_context.check_layout(os);
1648 begin_inset(os, "Float " + unstarred_name + "\n");
1649 // store the float type for subfloats
1650 // subfloats only work with figures and tables
1651 if (unstarred_name == "figure")
1652 float_type = unstarred_name;
1653 else if (unstarred_name == "table")
1654 float_type = unstarred_name;
1658 os << "placement " << opt << '\n';
1659 if (contains(opt, "H"))
1660 preamble.registerAutomaticallyLoadedPackage("float");
1662 Floating const & fl = parent_context.textclass.floats()
1663 .getType(unstarred_name);
1664 if (!fl.floattype().empty() && fl.usesFloatPkg())
1665 preamble.registerAutomaticallyLoadedPackage("float");
1668 os << "wide " << convert<string>(is_starred)
1669 << "\nsideways false"
1670 << "\nstatus open\n\n";
1671 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1673 // We don't need really a new paragraph, but
1674 // we must make sure that the next item gets a \begin_layout.
1675 parent_context.new_paragraph(os);
1677 // the float is parsed thus delete the type
1681 else if (unstarred_name == "sidewaysfigure"
1682 || unstarred_name == "sidewaystable"
1683 || unstarred_name == "sidewaysalgorithm") {
1684 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1685 eat_whitespace(p, os, parent_context, false);
1686 parent_context.check_layout(os);
1687 if (unstarred_name == "sidewaysfigure")
1688 begin_inset(os, "Float figure\n");
1689 else if (unstarred_name == "sidewaystable")
1690 begin_inset(os, "Float table\n");
1691 else if (unstarred_name == "sidewaysalgorithm")
1692 begin_inset(os, "Float algorithm\n");
1694 os << "placement " << opt << '\n';
1695 if (contains(opt, "H"))
1696 preamble.registerAutomaticallyLoadedPackage("float");
1697 os << "wide " << convert<string>(is_starred)
1698 << "\nsideways true"
1699 << "\nstatus open\n\n";
1700 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1702 // We don't need really a new paragraph, but
1703 // we must make sure that the next item gets a \begin_layout.
1704 parent_context.new_paragraph(os);
1706 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1709 else if (name == "wrapfigure" || name == "wraptable") {
1710 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1711 eat_whitespace(p, os, parent_context, false);
1712 parent_context.check_layout(os);
1715 string overhang = "0col%";
1718 lines = p.getArg('[', ']');
1719 string const placement = p.getArg('{', '}');
1721 overhang = p.getArg('[', ']');
1722 string const width = p.getArg('{', '}');
1724 if (name == "wrapfigure")
1725 begin_inset(os, "Wrap figure\n");
1727 begin_inset(os, "Wrap table\n");
1728 os << "lines " << lines
1729 << "\nplacement " << placement
1730 << "\noverhang " << lyx::translate_len(overhang)
1731 << "\nwidth " << lyx::translate_len(width)
1732 << "\nstatus open\n\n";
1733 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1735 // We don't need really a new paragraph, but
1736 // we must make sure that the next item gets a \begin_layout.
1737 parent_context.new_paragraph(os);
1739 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1742 else if (name == "minipage") {
1743 eat_whitespace(p, os, parent_context, false);
1744 // Test whether this is an outer box of a shaded box
1746 // swallow arguments
1747 while (p.hasOpt()) {
1749 p.skip_spaces(true);
1752 p.skip_spaces(true);
1753 Token t = p.get_token();
1754 bool shaded = false;
1755 if (t.asInput() == "\\begin") {
1756 p.skip_spaces(true);
1757 if (p.getArg('{', '}') == "shaded")
1762 parse_outer_box(p, os, FLAG_END, outer,
1763 parent_context, name, "shaded");
1765 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1766 "", "", name, "", "");
1770 else if (name == "comment") {
1771 eat_whitespace(p, os, parent_context, false);
1772 parent_context.check_layout(os);
1773 begin_inset(os, "Note Comment\n");
1774 os << "status open\n";
1775 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1778 skip_braces(p); // eat {} that might by set by LyX behind comments
1779 preamble.registerAutomaticallyLoadedPackage("verbatim");
1782 else if (unstarred_name == "verbatim") {
1783 // FIXME: this should go in the generic code that
1784 // handles environments defined in layout file that
1785 // have "PassThru 1". However, the code over there is
1786 // already too complicated for my taste.
1787 string const ascii_name =
1788 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1789 parent_context.new_paragraph(os);
1790 Context context(true, parent_context.textclass,
1791 &parent_context.textclass[from_ascii(ascii_name)]);
1792 string s = p.verbatimEnvironment(name);
1793 output_ert(os, s, context);
1797 else if (name == "IPA") {
1798 eat_whitespace(p, os, parent_context, false);
1799 parent_context.check_layout(os);
1800 begin_inset(os, "IPA\n");
1801 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1804 preamble.registerAutomaticallyLoadedPackage("tipa");
1805 preamble.registerAutomaticallyLoadedPackage("tipx");
1808 else if (name == parent_context.textclass.titlename()
1809 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1810 parse_text(p, os, FLAG_END, outer, parent_context);
1811 // Just in case the environment is empty
1812 parent_context.extra_stuff.erase();
1813 // We must begin a new paragraph
1814 parent_context.new_paragraph(os);
1818 else if (name == "CJK") {
1819 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1820 // It is impossible to decide if a CJK environment was in its own paragraph or within
1821 // a line. We therefore always assume a paragraph since the latter is a rare case.
1822 eat_whitespace(p, os, parent_context, false);
1823 parent_context.check_end_layout(os);
1824 // store the encoding to be able to reset it
1825 string const encoding_old = p.getEncoding();
1826 string const encoding = p.getArg('{', '}');
1827 // FIXME: For some reason JIS does not work. Although the text
1828 // in tests/CJK.tex is identical with the SJIS version if you
1829 // convert both snippets using the recode command line utility,
1830 // the resulting .lyx file contains some extra characters if
1831 // you set buggy_encoding to false for JIS.
1832 bool const buggy_encoding = encoding == "JIS";
1833 if (!buggy_encoding)
1834 p.setEncoding(encoding, Encoding::CJK);
1836 // FIXME: This will read garbage, since the data is not encoded in utf8.
1837 p.setEncoding("UTF-8");
1839 // LyX only supports the same mapping for all CJK
1840 // environments, so we might need to output everything as ERT
1841 string const mapping = trim(p.getArg('{', '}'));
1842 char const * const * const where =
1843 is_known(encoding, supported_CJK_encodings);
1844 if (!buggy_encoding && !preamble.fontCJKSet())
1845 preamble.fontCJK(mapping);
1846 bool knownMapping = mapping == preamble.fontCJK();
1847 if (buggy_encoding || !knownMapping || !where) {
1848 parent_context.check_layout(os);
1849 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1851 // we must parse the content as verbatim because e.g. JIS can contain
1852 // normally invalid characters
1853 // FIXME: This works only for the most simple cases.
1854 // Since TeX control characters are not parsed,
1855 // things like comments are completely wrong.
1856 string const s = p.plainEnvironment("CJK");
1857 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1860 if (snip == "\\" || is_known(snip, known_escaped_chars))
1861 output_ert_inset(os, snip, parent_context);
1862 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1867 output_ert_inset(os, "\\end{" + name + "}",
1871 supported_CJK_languages[where - supported_CJK_encodings];
1872 // store the language because we must reset it at the end
1873 string const lang_old = parent_context.font.language;
1874 parent_context.font.language = lang;
1875 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1876 parent_context.font.language = lang_old;
1877 parent_context.new_paragraph(os);
1879 p.setEncoding(encoding_old);
1883 else if (name == "lyxgreyedout") {
1884 eat_whitespace(p, os, parent_context, false);
1885 parent_context.check_layout(os);
1886 begin_inset(os, "Note Greyedout\n");
1887 os << "status open\n";
1888 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1891 if (!preamble.notefontcolor().empty())
1892 preamble.registerAutomaticallyLoadedPackage("color");
1895 else if (name == "btSect") {
1896 eat_whitespace(p, os, parent_context, false);
1897 parent_context.check_layout(os);
1898 begin_command_inset(os, "bibtex", "bibtex");
1899 string bibstyle = "plain";
1901 bibstyle = p.getArg('[', ']');
1902 p.skip_spaces(true);
1904 string const bibfile = p.getArg('{', '}');
1905 eat_whitespace(p, os, parent_context, false);
1906 Token t = p.get_token();
1907 if (t.asInput() == "\\btPrintCited") {
1908 p.skip_spaces(true);
1909 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1911 if (t.asInput() == "\\btPrintNotCited") {
1912 p.skip_spaces(true);
1913 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1915 if (t.asInput() == "\\btPrintAll") {
1916 p.skip_spaces(true);
1917 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1919 os << "bibfiles " << '"' << bibfile << "\"\n"
1920 << "options " << '"' << bibstyle << "\"\n";
1921 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1926 else if (name == "btUnit") {
1927 string const nt = p.next_next_token().cs();
1928 // Do not attempt to overwrite a former diverging multibib.
1929 // Those are output as ERT instead.
1930 if ((nt == "part" || nt == "chapter"
1931 || nt == "section" || nt == "subsection")
1932 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1933 parse_text(p, os, FLAG_END, outer, parent_context);
1934 preamble.multibib(nt);
1936 parse_unknown_environment(p, name, os, FLAG_END, outer,
1940 else if (name == "framed" || name == "shaded") {
1941 eat_whitespace(p, os, parent_context, false);
1942 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1944 preamble.registerAutomaticallyLoadedPackage("framed");
1947 else if (name == "listing") {
1948 minted_float = "float";
1949 eat_whitespace(p, os, parent_context, false);
1950 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1952 minted_float += "=" + opt;
1953 // If something precedes \begin{minted}, we output it at the end
1954 // as a caption, in order to keep it inside the listings inset.
1955 eat_whitespace(p, os, parent_context, true);
1957 Token const & t = p.get_token();
1958 p.skip_spaces(true);
1959 string const envname = p.next_token().cat() == catBegin
1960 ? p.getArg('{', '}') : string();
1961 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1963 minted_float_has_caption = false;
1964 string content = parse_text_snippet(p, FLAG_END, outer,
1966 size_t i = content.find("\\begin_inset listings");
1967 bool minted_env = i != string::npos;
1970 caption = content.substr(0, i);
1971 content.erase(0, i);
1973 parent_context.check_layout(os);
1974 if (minted_env && minted_float_has_caption) {
1975 eat_whitespace(p, os, parent_context, true);
1976 os << content << "\n";
1977 if (!caption.empty())
1978 os << caption << "\n";
1979 os << "\n\\end_layout\n"; // close inner layout
1980 end_inset(os); // close caption inset
1981 os << "\n\\end_layout\n"; // close outer layout
1982 } else if (!caption.empty()) {
1984 begin_inset(os, "listings\n");
1985 os << "lstparams " << '"' << minted_float << '"' << '\n';
1986 os << "inline false\n";
1987 os << "status collapsed\n";
1989 os << "\n\\begin_layout Plain Layout\n";
1990 begin_inset(os, "Caption Standard\n");
1991 Context newcontext(true, parent_context.textclass,
1992 0, 0, parent_context.font);
1993 newcontext.check_layout(os);
1994 os << caption << "\n";
1995 newcontext.check_end_layout(os);
1997 os << "\n\\end_layout\n";
1998 } else if (content.empty()) {
1999 begin_inset(os, "listings\n");
2000 os << "lstparams " << '"' << minted_float << '"' << '\n';
2001 os << "inline false\n";
2002 os << "status collapsed\n";
2004 os << content << "\n";
2006 end_inset(os); // close listings inset
2007 parent_context.check_end_layout(os);
2008 parent_context.new_paragraph(os);
2010 minted_float.clear();
2011 minted_float_has_caption = false;
2014 else if (name == "lstlisting" || name == "minted") {
2015 bool use_minted = name == "minted";
2016 // with listings, we do not eat newlines here since
2017 // \begin{lstlistings}
2020 // // \begin{lstlistings}%
2023 // reads [foo] as content, whereas
2024 // // \begin{lstlistings}%
2027 // \begin{lstlistings}[foo,
2029 // reads [foo...] as argument.
2030 eat_whitespace(p, os, parent_context, false, use_minted);
2031 if (use_minted && minted_float.empty()) {
2032 // look ahead for a bottom caption
2034 bool found_end_minted = false;
2035 while (!found_end_minted && p.good()) {
2036 Token const & t = p.get_token();
2038 string const envname =
2039 p.next_token().cat() == catBegin
2040 ? p.getArg('{', '}') : string();
2041 found_end_minted = t.asInput() == "\\end"
2042 && envname == "minted";
2044 eat_whitespace(p, os, parent_context, true);
2045 Token const & t = p.get_token();
2046 p.skip_spaces(true);
2047 if (t.asInput() == "\\lyxmintcaption") {
2048 string const pos = p.getArg('[', ']');
2050 string const caption =
2051 parse_text_snippet(p, FLAG_ITEM,
2052 false, parent_context);
2053 minted_nonfloat_caption = "[b]" + caption;
2054 eat_whitespace(p, os, parent_context, true);
2059 parse_listings(p, os, parent_context, false, use_minted);
2063 else if (!parent_context.new_layout_allowed)
2064 parse_unknown_environment(p, name, os, FLAG_END, outer,
2067 // Alignment and spacing settings
2068 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2069 // therefore are totally broken!
2070 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2071 // they are commands not environments. They are furthermore switches that
2072 // can be ended by another switches, but also by commands like \footnote or
2073 // \parbox. So the only safe way is to leave them untouched.
2074 // However, we support the pseudo-environments
2075 // \begin{centering} ... \end{centering}
2076 // \begin{raggedright} ... \end{raggedright}
2077 // \begin{raggedleft} ... \end{raggedleft}
2078 // since they are used by LyX in floats (for spacing reasons)
2079 else if (name == "center" || name == "centering" ||
2080 name == "flushleft" || name == "raggedright" ||
2081 name == "flushright" || name == "raggedleft" ||
2082 name == "singlespace" || name == "onehalfspace" ||
2083 name == "doublespace" || name == "spacing") {
2084 eat_whitespace(p, os, parent_context, false);
2085 // We must begin a new paragraph if not already done
2086 if (! parent_context.atParagraphStart()) {
2087 parent_context.check_end_layout(os);
2088 parent_context.new_paragraph(os);
2090 if (name == "flushleft" || name == "raggedright")
2091 parent_context.add_extra_stuff("\\align left\n");
2092 else if (name == "flushright" || name == "raggedleft")
2093 parent_context.add_extra_stuff("\\align right\n");
2094 else if (name == "center" || name == "centering")
2095 parent_context.add_extra_stuff("\\align center\n");
2096 else if (name == "singlespace")
2097 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2098 else if (name == "onehalfspace") {
2099 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2100 preamble.registerAutomaticallyLoadedPackage("setspace");
2101 } else if (name == "doublespace") {
2102 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2103 preamble.registerAutomaticallyLoadedPackage("setspace");
2104 } else if (name == "spacing") {
2105 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2106 preamble.registerAutomaticallyLoadedPackage("setspace");
2108 parse_text(p, os, FLAG_END, outer, parent_context);
2109 // Just in case the environment is empty
2110 parent_context.extra_stuff.erase();
2111 // We must begin a new paragraph to reset the alignment
2112 parent_context.new_paragraph(os);
2116 // The single '=' is meant here.
2117 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2118 eat_whitespace(p, os, parent_context, false);
2119 Context context(true, parent_context.textclass, newlayout,
2120 parent_context.layout, parent_context.font);
2121 if (parent_context.deeper_paragraph) {
2122 // We are beginning a nested environment after a
2123 // deeper paragraph inside the outer list environment.
2124 // Therefore we don't need to output a "begin deeper".
2125 context.need_end_deeper = true;
2127 parent_context.check_end_layout(os);
2128 if (last_env == name) {
2129 // we need to output a separator since LyX would export
2130 // the two environments as one otherwise (bug 5716)
2131 TeX2LyXDocClass const & textclass(parent_context.textclass);
2132 Context newcontext(true, textclass,
2133 &(textclass.defaultLayout()));
2134 newcontext.check_layout(os);
2135 begin_inset(os, "Separator plain\n");
2137 newcontext.check_end_layout(os);
2139 switch (context.layout->latextype) {
2140 case LATEX_LIST_ENVIRONMENT:
2141 context.add_par_extra_stuff("\\labelwidthstring "
2142 + p.verbatim_item() + '\n');
2145 case LATEX_BIB_ENVIRONMENT:
2146 p.verbatim_item(); // swallow next arg
2152 context.check_deeper(os);
2153 if (newlayout->keepempty) {
2154 // We need to start a new paragraph
2155 // even if it is empty.
2156 context.new_paragraph(os);
2157 context.check_layout(os);
2159 // handle known optional and required arguments
2160 if (context.layout->latextype == LATEX_ENVIRONMENT)
2161 output_arguments(os, p, outer, false, string(), context,
2162 context.layout->latexargs());
2163 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2165 output_arguments(oss, p, outer, false, string(), context,
2166 context.layout->latexargs());
2167 context.list_extra_stuff = oss.str();
2169 parse_text(p, os, FLAG_END, outer, context);
2170 if (context.layout->latextype == LATEX_ENVIRONMENT)
2171 output_arguments(os, p, outer, false, "post", context,
2172 context.layout->postcommandargs());
2173 context.check_end_layout(os);
2174 if (parent_context.deeper_paragraph) {
2175 // We must suppress the "end deeper" because we
2176 // suppressed the "begin deeper" above.
2177 context.need_end_deeper = false;
2179 context.check_end_deeper(os);
2180 parent_context.new_paragraph(os);
2182 if (!preamble.titleLayoutFound())
2183 preamble.titleLayoutFound(newlayout->intitle);
2184 set<string> const & req = newlayout->requires();
2185 set<string>::const_iterator it = req.begin();
2186 set<string>::const_iterator en = req.end();
2187 for (; it != en; ++it)
2188 preamble.registerAutomaticallyLoadedPackage(*it);
2191 // The single '=' is meant here.
2192 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2193 eat_whitespace(p, os, parent_context, false);
2194 parent_context.check_layout(os);
2195 begin_inset(os, "Flex ");
2196 docstring flex_name = newinsetlayout->name();
2197 // FIXME: what do we do if the prefix is not Flex: ?
2198 if (prefixIs(flex_name, from_ascii("Flex:")))
2199 flex_name.erase(0, 5);
2200 os << to_utf8(flex_name) << '\n'
2201 << "status collapsed\n";
2202 if (newinsetlayout->isPassThru()) {
2203 string const arg = p.verbatimEnvironment(name);
2204 Context context(true, parent_context.textclass,
2205 &parent_context.textclass.plainLayout(),
2206 parent_context.layout);
2207 output_ert(os, arg, parent_context);
2209 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2213 else if (name == "appendix") {
2214 // This is no good latex style, but it works and is used in some documents...
2215 eat_whitespace(p, os, parent_context, false);
2216 parent_context.check_end_layout(os);
2217 Context context(true, parent_context.textclass, parent_context.layout,
2218 parent_context.layout, parent_context.font);
2219 context.check_layout(os);
2220 os << "\\start_of_appendix\n";
2221 parse_text(p, os, FLAG_END, outer, context);
2222 context.check_end_layout(os);
2226 else if (known_environments.find(name) != known_environments.end()) {
2227 vector<ArgumentType> arguments = known_environments[name];
2228 // The last "argument" denotes wether we may translate the
2229 // environment contents to LyX
2230 // The default required if no argument is given makes us
2231 // compatible with the reLyXre environment.
2232 ArgumentType contents = arguments.empty() ?
2235 if (!arguments.empty())
2236 arguments.pop_back();
2237 // See comment in parse_unknown_environment()
2238 bool const specialfont =
2239 (parent_context.font != parent_context.normalfont);
2240 bool const new_layout_allowed =
2241 parent_context.new_layout_allowed;
2243 parent_context.new_layout_allowed = false;
2244 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2245 outer, parent_context);
2246 if (contents == verbatim)
2247 output_ert_inset(os, p.ertEnvironment(name),
2250 parse_text_snippet(p, os, FLAG_END, outer,
2252 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2254 parent_context.new_layout_allowed = new_layout_allowed;
2258 parse_unknown_environment(p, name, os, FLAG_END, outer,
2262 active_environments.pop_back();
2266 /// parses a comment and outputs it to \p os.
2267 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2268 bool skipNewlines = false)
2270 LASSERT(t.cat() == catComment, return);
2271 if (!t.cs().empty()) {
2272 context.check_layout(os);
2273 output_comment(p, os, t.cs(), context);
2274 if (p.next_token().cat() == catNewline) {
2275 // A newline after a comment line starts a new
2277 if (context.new_layout_allowed) {
2278 if(!context.atParagraphStart())
2279 // Only start a new paragraph if not already
2280 // done (we might get called recursively)
2281 context.new_paragraph(os);
2283 output_ert_inset(os, "\n", context);
2284 eat_whitespace(p, os, context, true);
2286 } else if (!skipNewlines) {
2287 // "%\n" combination
2294 * Reads spaces and comments until the first non-space, non-comment token.
2295 * New paragraphs (double newlines or \\par) are handled like simple spaces
2296 * if \p eatParagraph is true.
2297 * If \p eatNewline is false, newlines won't be treated as whitespace.
2298 * Spaces are skipped, but comments are written to \p os.
2300 void eat_whitespace(Parser & p, ostream & os, Context & context,
2301 bool eatParagraph, bool eatNewline)
2304 Token const & t = p.get_token();
2305 if (t.cat() == catComment)
2306 parse_comment(p, os, t, context, !eatNewline);
2307 else if ((!eatParagraph && p.isParagraph()) ||
2308 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2317 * Set a font attribute, parse text and reset the font attribute.
2318 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2319 * \param currentvalue Current value of the attribute. Is set to the new
2320 * value during parsing.
2321 * \param newvalue New value of the attribute
2323 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2324 Context & context, string const & attribute,
2325 string & currentvalue, string const & newvalue)
2327 context.check_layout(os);
2328 string const oldvalue = currentvalue;
2329 currentvalue = newvalue;
2330 os << '\n' << attribute << ' ' << newvalue << "\n";
2331 parse_text_snippet(p, os, flags, outer, context);
2332 context.check_layout(os);
2333 os << '\n' << attribute << ' ' << oldvalue << "\n";
2334 currentvalue = oldvalue;
2338 /// get the arguments of a natbib or jurabib citation command
2339 void get_cite_arguments(Parser & p, bool natbibOrder,
2340 string & before, string & after, bool const qualified = false)
2342 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2344 // text before the citation
2346 // text after the citation
2347 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2349 if (!after.empty()) {
2350 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2351 if (natbibOrder && !before.empty())
2352 swap(before, after);
2357 void copy_file(FileName const & src, string dstname)
2361 string const absParent = getParentFilePath(false);
2363 if (FileName::isAbsolute(dstname))
2364 dst = FileName(dstname);
2366 dst = makeAbsPath(dstname, absParent);
2367 FileName const srcpath = src.onlyPath();
2368 FileName const dstpath = dst.onlyPath();
2369 if (equivalent(srcpath, dstpath))
2371 if (!dstpath.isDirectory()) {
2372 if (!dstpath.createPath()) {
2373 cerr << "Warning: Could not create directory for file `"
2374 << dst.absFileName() << "´." << endl;
2378 if (dst.isReadableFile()) {
2379 if (overwriteFiles())
2380 cerr << "Warning: Overwriting existing file `"
2381 << dst.absFileName() << "´." << endl;
2383 cerr << "Warning: Not overwriting existing file `"
2384 << dst.absFileName() << "´." << endl;
2388 if (!src.copyTo(dst))
2389 cerr << "Warning: Could not copy file `" << src.absFileName()
2390 << "´ to `" << dst.absFileName() << "´." << endl;
2394 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2395 bool parse_chunk(Parser & p, ostream & os, Context & context)
2397 // check whether a chunk is possible here.
2398 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2404 // read the parameters
2405 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2406 if (!params.first) {
2411 Parser::Arg const code = p.verbatimStuff("\n@");
2416 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2417 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2421 // The last newline read is important for paragraph handling
2425 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2426 // We must have a valid layout before outputting the Chunk inset.
2427 context.check_layout(os);
2428 Context chunkcontext(true, context.textclass);
2429 chunkcontext.layout = &context.textclass.plainLayout();
2430 begin_inset(os, "Flex Chunk");
2431 os << "\nstatus open\n";
2432 if (!params.second.empty()) {
2433 chunkcontext.check_layout(os);
2434 Context paramscontext(true, context.textclass);
2435 paramscontext.layout = &context.textclass.plainLayout();
2436 begin_inset(os, "Argument 1");
2437 os << "\nstatus open\n";
2438 output_ert(os, params.second, paramscontext);
2441 output_ert(os, code.second, chunkcontext);
2449 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2450 bool is_macro(Parser & p)
2452 Token first = p.curr_token();
2453 if (first.cat() != catEscape || !p.good())
2455 if (first.cs() == "def")
2457 if (first.cs() != "global" && first.cs() != "long")
2459 Token second = p.get_token();
2461 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2462 second.cat() == catNewline || second.cat() == catComment)) {
2463 second = p.get_token();
2466 bool secondvalid = second.cat() == catEscape;
2468 bool thirdvalid = false;
2469 if (p.good() && first.cs() == "global" && secondvalid &&
2470 second.cs() == "long") {
2471 third = p.get_token();
2473 while (p.good() && !p.isParagraph() &&
2474 (third.cat() == catSpace ||
2475 third.cat() == catNewline ||
2476 third.cat() == catComment)) {
2477 third = p.get_token();
2480 thirdvalid = third.cat() == catEscape;
2482 for (int i = 0; i < pos; ++i)
2487 return (first.cs() == "global" || first.cs() == "long") &&
2488 second.cs() == "def";
2489 return first.cs() == "global" && second.cs() == "long" &&
2490 third.cs() == "def";
2494 /// Parse a macro definition (assumes that is_macro() returned true)
2495 void parse_macro(Parser & p, ostream & os, Context & context)
2497 context.check_layout(os);
2498 Token first = p.curr_token();
2501 string command = first.asInput();
2502 if (first.cs() != "def") {
2504 eat_whitespace(p, os, context, false);
2505 second = p.curr_token();
2506 command += second.asInput();
2507 if (second.cs() != "def") {
2509 eat_whitespace(p, os, context, false);
2510 third = p.curr_token();
2511 command += third.asInput();
2514 eat_whitespace(p, os, context, false);
2515 string const name = p.get_token().cs();
2516 eat_whitespace(p, os, context, false);
2522 while (p.next_token().cat() != catBegin) {
2523 if (p.next_token().cat() == catParameter) {
2528 // followed by number?
2529 if (p.next_token().cat() == catOther) {
2530 string s = p.get_token().asInput();
2532 // number = current arity + 1?
2533 if (s.size() == 1 && s[0] == arity + '0' + 1)
2538 paramtext += p.get_token().cs();
2540 paramtext += p.get_token().cs();
2545 // only output simple (i.e. compatible) macro as FormulaMacros
2546 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2548 context.check_layout(os);
2549 begin_inset(os, "FormulaMacro");
2550 os << "\n\\def" << ert;
2553 output_ert_inset(os, command + ert, context);
2557 void registerExternalTemplatePackages(string const & name)
2559 external::TemplateManager const & etm = external::TemplateManager::get();
2560 external::Template const * const et = etm.getTemplateByName(name);
2563 external::Template::Formats::const_iterator cit = et->formats.end();
2565 cit = et->formats.find("PDFLaTeX");
2566 if (cit == et->formats.end())
2567 // If the template has not specified a PDFLaTeX output,
2568 // we try the LaTeX format.
2569 cit = et->formats.find("LaTeX");
2570 if (cit == et->formats.end())
2572 vector<string>::const_iterator qit = cit->second.requirements.begin();
2573 vector<string>::const_iterator qend = cit->second.requirements.end();
2574 for (; qit != qend; ++qit)
2575 preamble.registerAutomaticallyLoadedPackage(*qit);
2578 } // anonymous namespace
2582 * Find a file with basename \p name in path \p path and an extension
2585 string find_file(string const & name, string const & path,
2586 char const * const * extensions)
2588 for (char const * const * what = extensions; *what; ++what) {
2589 string const trial = addExtension(name, *what);
2590 if (makeAbsPath(trial, path).exists())
2597 /// Convert filenames with TeX macros and/or quotes to something LyX
2599 string const normalize_filename(string const & name)
2604 Token const & t = p.get_token();
2605 if (t.cat() != catEscape)
2607 else if (t.cs() == "lyxdot") {
2608 // This is used by LyX for simple dots in relative
2612 } else if (t.cs() == "space") {
2615 } else if (t.cs() == "string") {
2616 // Convert \string" to " and \string~ to ~
2617 Token const & n = p.next_token();
2618 if (n.asInput() != "\"" && n.asInput() != "~")
2623 // Strip quotes. This is a bit complicated (see latex_path()).
2624 string full = os.str();
2625 if (!full.empty() && full[0] == '"') {
2626 string base = removeExtension(full);
2627 string ext = getExtension(full);
2628 if (!base.empty() && base[base.length()-1] == '"')
2631 return addExtension(trim(base, "\""), ext);
2632 if (full[full.length()-1] == '"')
2635 return trim(full, "\"");
2641 /// Convert \p name from TeX convention (relative to master file) to LyX
2642 /// convention (relative to .lyx file) if it is relative
2643 void fix_child_filename(string & name)
2645 string const absMasterTeX = getMasterFilePath(true);
2646 bool const isabs = FileName::isAbsolute(name);
2647 // convert from "relative to .tex master" to absolute original path
2649 name = makeAbsPath(name, absMasterTeX).absFileName();
2650 bool copyfile = copyFiles();
2651 string const absParentLyX = getParentFilePath(false);
2654 // convert from absolute original path to "relative to master file"
2655 string const rel = to_utf8(makeRelPath(from_utf8(name),
2656 from_utf8(absMasterTeX)));
2657 // re-interpret "relative to .tex file" as "relative to .lyx file"
2658 // (is different if the master .lyx file resides in a
2659 // different path than the master .tex file)
2660 string const absMasterLyX = getMasterFilePath(false);
2661 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2662 // Do not copy if the new path is impossible to create. Example:
2663 // absMasterTeX = "/foo/bar/"
2664 // absMasterLyX = "/bar/"
2665 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2666 if (contains(name, "/../"))
2673 // convert from absolute original path to
2674 // "relative to .lyx file"
2675 name = to_utf8(makeRelPath(from_utf8(abs),
2676 from_utf8(absParentLyX)));
2680 // convert from absolute original path to "relative to .lyx file"
2681 name = to_utf8(makeRelPath(from_utf8(name),
2682 from_utf8(absParentLyX)));
2687 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2688 Context & context, string const rdelim)
2690 Layout const * newlayout = 0;
2691 InsetLayout const * newinsetlayout = 0;
2692 char const * const * where = 0;
2693 // Store the latest bibliographystyle, addcontentslineContent and
2694 // nocite{*} option (needed for bibtex inset)
2696 string contentslineContent;
2697 // Some classes provide a \bibliographystyle, so do not output
2698 // any if none is explicitly set.
2699 string bibliographystyle;
2700 bool const use_natbib = isProvided("natbib");
2701 bool const use_jurabib = isProvided("jurabib");
2702 bool const use_biblatex = isProvided("biblatex")
2703 && preamble.citeEngine() != "biblatex-natbib";
2704 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2705 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2706 need_commentbib = use_biblatex || use_biblatex_natbib;
2709 // it is impossible to determine the correct encoding for non-CJK Japanese.
2710 // Therefore write a note at the beginning of the document
2711 if (is_nonCJKJapanese) {
2712 context.check_layout(os);
2713 begin_inset(os, "Note Note\n");
2714 os << "status open\n\\begin_layout Plain Layout\n"
2715 << "\\series bold\n"
2716 << "Important information:\n"
2717 << "\\end_layout\n\n"
2718 << "\\begin_layout Plain Layout\n"
2719 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2720 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2721 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2722 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2723 << " and specify the encoding using the -e command-line switch.\n"
2724 << " In addition, you might want to double check that the desired output encoding\n"
2725 << " is correctly selected in Document > Settings > Language.\n"
2726 << "\\end_layout\n";
2728 is_nonCJKJapanese = false;
2731 bool have_cycled = false;
2733 // Leave here only after at least one cycle
2734 if (have_cycled && flags & FLAG_LEAVE) {
2735 flags &= ~FLAG_LEAVE;
2739 Token const & t = p.get_token();
2741 debugToken(cerr, t, flags);
2744 if (flags & FLAG_ITEM) {
2745 if (t.cat() == catSpace)
2748 flags &= ~FLAG_ITEM;
2749 if (t.cat() == catBegin) {
2750 // skip the brace and collect everything to the next matching
2752 flags |= FLAG_BRACE_LAST;
2756 // handle only this single token, leave the loop if done
2757 flags |= FLAG_LEAVE;
2760 if (t.cat() != catEscape && t.character() == ']' &&
2761 (flags & FLAG_BRACK_LAST))
2763 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2765 string tok = t.asInput();
2766 // we only support delimiters with max 2 chars for now.
2767 if (rdelim.size() > 1)
2768 tok += p.next_token().asInput();
2769 if (t.cat() != catEscape && !rdelim.empty()
2770 && tok == rdelim && (flags & FLAG_RDELIM)) {
2771 if (rdelim.size() > 1)
2772 p.get_token(); // eat rdelim
2776 // If there is anything between \end{env} and \begin{env} we
2777 // don't need to output a separator.
2778 if (t.cat() != catSpace && t.cat() != catNewline &&
2779 t.asInput() != "\\begin")
2786 bool const starred = p.next_token().asInput() == "*";
2787 string const starredname(starred ? (t.cs() + '*') : t.cs());
2788 if (t.cat() == catMath) {
2789 // we are inside some text mode thingy, so opening new math is allowed
2790 context.check_layout(os);
2791 begin_inset(os, "Formula ");
2792 Token const & n = p.get_token();
2793 bool const display(n.cat() == catMath && outer);
2795 // TeX's $$...$$ syntax for displayed math
2797 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2799 p.get_token(); // skip the second '$' token
2801 // simple $...$ stuff
2804 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2809 // Prevent the conversion of a line break to a
2810 // space (bug 7668). This does not change the
2811 // output, but looks ugly in LyX.
2812 eat_whitespace(p, os, context, false);
2817 if (t.cat() == catSuper || t.cat() == catSub) {
2818 cerr << "catcode " << t << " illegal in text mode\n";
2822 // Basic support for quotes. We try to disambiguate
2823 // quotes from the context (e.g., a left english quote is
2824 // the same as a right german quote...).
2825 // Try to make a smart guess about the side
2826 Token const prev = p.prev_token();
2827 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2828 && prev.character() != '\n' && prev.character() != '~');
2829 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2830 context.check_layout(os);
2831 begin_inset(os, "Quotes ");
2832 os << guessQuoteStyle("eld", opening);
2838 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2839 context.check_layout(os);
2840 begin_inset(os, "Quotes ");
2841 os << guessQuoteStyle("erd", opening);
2848 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2849 context.check_layout(os);
2850 begin_inset(os, "Quotes ");
2851 os << guessQuoteStyle("ald", opening);
2858 if (t.asInput() == "<"
2859 && p.next_token().asInput() == "<") {
2860 bool has_chunk = false;
2864 has_chunk = parse_chunk(p, os, context);
2870 context.check_layout(os);
2871 begin_inset(os, "Quotes ");
2872 os << guessQuoteStyle("ard", opening);
2880 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2881 check_space(p, os, context);
2885 // babel shorthands (also used by polyglossia)
2886 // Since these can have different meanings for different languages
2887 // we import them as ERT (but they must be put in ERT to get output
2889 if (t.asInput() == "\"") {
2891 // These are known pairs. We put them together in
2892 // one ERT inset. In other cases (such as "a), only
2893 // the quotation mark is ERTed.
2894 if (p.next_token().asInput() == "\""
2895 || p.next_token().asInput() == "|"
2896 || p.next_token().asInput() == "-"
2897 || p.next_token().asInput() == "~"
2898 || p.next_token().asInput() == "="
2899 || p.next_token().asInput() == "/"
2900 || p.next_token().asInput() == "~"
2901 || p.next_token().asInput() == "'"
2902 || p.next_token().asInput() == "`"
2903 || p.next_token().asInput() == "<"
2904 || p.next_token().asInput() == ">") {
2905 s += p.next_token().asInput();
2908 output_ert_inset(os, s, context);
2912 if (t.character() == '[' && noweb_mode &&
2913 p.next_token().character() == '[') {
2914 // These can contain underscores
2916 string const s = p.getFullOpt() + ']';
2917 if (p.next_token().character() == ']')
2920 cerr << "Warning: Inserting missing ']' in '"
2921 << s << "'." << endl;
2922 output_ert_inset(os, s, context);
2926 if (t.cat() == catLetter) {
2927 context.check_layout(os);
2932 if (t.cat() == catOther ||
2933 t.cat() == catAlign ||
2934 t.cat() == catParameter) {
2935 context.check_layout(os);
2936 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2937 context.merging_hyphens_allowed &&
2938 context.font.family != "ttfamily" &&
2939 !context.layout->pass_thru) {
2940 if (p.next_next_token().asInput() == "-") {
2942 os << to_utf8(docstring(1, 0x2014));
2946 os << to_utf8(docstring(1, 0x2013));
2949 // This translates "&" to "\\&" which may be wrong...
2954 if (p.isParagraph()) {
2955 // In minted floating listings we will collect
2956 // everything into the caption, where multiple
2957 // paragraphs are forbidden.
2958 if (minted_float.empty()) {
2959 if (context.new_layout_allowed)
2960 context.new_paragraph(os);
2962 output_ert_inset(os, "\\par ", context);
2965 eat_whitespace(p, os, context, true);
2969 if (t.cat() == catActive) {
2970 context.check_layout(os);
2971 if (t.character() == '~') {
2972 if (context.layout->free_spacing)
2975 begin_inset(os, "space ~\n");
2983 if (t.cat() == catBegin) {
2984 Token const next = p.next_token();
2985 Token const end = p.next_next_token();
2986 if (next.cat() == catEnd) {
2988 Token const prev = p.prev_token();
2990 if (p.next_token().character() == '`')
2991 ; // ignore it in {}``
2993 output_ert_inset(os, "{}", context);
2994 } else if (next.cat() == catEscape &&
2995 is_known(next.cs(), known_quotes) &&
2996 end.cat() == catEnd) {
2997 // Something like {\textquoteright} (e.g.
2998 // from writer2latex). We may skip the
2999 // braces here for better readability.
3000 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3002 } else if (p.next_token().asInput() == "\\ascii") {
3003 // handle the \ascii characters
3004 // (the case without braces is handled later)
3005 // the code is "{\ascii\xxx}"
3006 p.get_token(); // eat \ascii
3007 string name2 = p.get_token().asInput();
3008 p.get_token(); // eat the final '}'
3009 string const name = "{\\ascii" + name2 + "}";
3013 // get the character from unicodesymbols
3014 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3015 Encodings::TEXT_CMD, termination, rem, &req);
3017 context.check_layout(os);
3020 output_ert_inset(os,
3021 to_utf8(rem), context);
3022 for (set<string>::const_iterator it = req.begin();
3023 it != req.end(); ++it)
3024 preamble.registerAutomaticallyLoadedPackage(*it);
3026 // we did not find a non-ert version
3027 output_ert_inset(os, name, context);
3029 context.check_layout(os);
3030 // special handling of font attribute changes
3031 Token const prev = p.prev_token();
3032 TeXFont const oldFont = context.font;
3033 if (next.character() == '[' ||
3034 next.character() == ']' ||
3035 next.character() == '*') {
3037 if (p.next_token().cat() == catEnd) {
3042 output_ert_inset(os, "{", context);
3043 parse_text_snippet(p, os,
3046 output_ert_inset(os, "}", context);
3048 } else if (! context.new_layout_allowed) {
3049 output_ert_inset(os, "{", context);
3050 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3052 output_ert_inset(os, "}", context);
3053 } else if (is_known(next.cs(), known_sizes)) {
3054 // next will change the size, so we must
3056 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3058 if (!context.atParagraphStart())
3060 << context.font.size << "\n";
3061 } else if (is_known(next.cs(), known_font_families)) {
3062 // next will change the font family, so we
3063 // must reset it here
3064 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3066 if (!context.atParagraphStart())
3068 << context.font.family << "\n";
3069 } else if (is_known(next.cs(), known_font_series)) {
3070 // next will change the font series, so we
3071 // must reset it here
3072 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3074 if (!context.atParagraphStart())
3076 << context.font.series << "\n";
3077 } else if (is_known(next.cs(), known_font_shapes)) {
3078 // next will change the font shape, so we
3079 // must reset it here
3080 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3082 if (!context.atParagraphStart())
3084 << context.font.shape << "\n";
3085 } else if (is_known(next.cs(), known_old_font_families) ||
3086 is_known(next.cs(), known_old_font_series) ||
3087 is_known(next.cs(), known_old_font_shapes)) {
3088 // next will change the font family, series
3089 // and shape, so we must reset it here
3090 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3092 if (!context.atParagraphStart())
3094 << context.font.family
3096 << context.font.series
3098 << context.font.shape << "\n";
3100 output_ert_inset(os, "{", context);
3101 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3103 output_ert_inset(os, "}", context);
3109 if (t.cat() == catEnd) {
3110 if (flags & FLAG_BRACE_LAST) {
3113 cerr << "stray '}' in text\n";
3114 output_ert_inset(os, "}", context);
3118 if (t.cat() == catComment) {
3119 parse_comment(p, os, t, context);
3124 // control sequences
3127 if (t.cs() == "(" || t.cs() == "[") {
3128 bool const simple = t.cs() == "(";
3129 context.check_layout(os);
3130 begin_inset(os, "Formula");
3131 os << " \\" << t.cs();
3132 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3133 os << '\\' << (simple ? ')' : ']');
3136 // Prevent the conversion of a line break to a
3137 // space (bug 7668). This does not change the
3138 // output, but looks ugly in LyX.
3139 eat_whitespace(p, os, context, false);
3144 if (t.cs() == "begin") {
3145 parse_environment(p, os, outer, last_env,
3150 if (t.cs() == "end") {
3151 if (flags & FLAG_END) {
3152 // eat environment name
3153 string const name = p.getArg('{', '}');
3154 if (name != active_environment())
3155 cerr << "\\end{" + name + "} does not match \\begin{"
3156 + active_environment() + "}\n";
3159 p.error("found 'end' unexpectedly");
3163 // "item" by default, but could be something else
3164 if (t.cs() == context.layout->itemcommand()) {
3166 if (context.layout->labeltype == LABEL_MANUAL) {
3167 // FIXME: This swallows comments, but we cannot use
3168 // eat_whitespace() since we must not output
3169 // anything before the item.
3170 p.skip_spaces(true);
3171 s = p.verbatimOption();
3173 p.skip_spaces(false);
3175 context.check_layout(os);
3176 if (context.has_item) {
3177 // An item in an unknown list-like environment
3178 // FIXME: Do this in check_layout()!
3179 context.has_item = false;
3180 string item = "\\" + context.layout->itemcommand();
3183 output_ert_inset(os, item, context);
3185 if (context.layout->labeltype != LABEL_MANUAL)
3186 output_arguments(os, p, outer, false, "item", context,
3187 context.layout->itemargs());
3188 if (!context.list_extra_stuff.empty()) {
3189 os << context.list_extra_stuff;
3190 context.list_extra_stuff.clear();
3192 else if (!s.empty()) {
3193 // LyX adds braces around the argument,
3194 // so we need to remove them here.
3195 if (s.size() > 2 && s[0] == '{' &&
3196 s[s.size()-1] == '}')
3197 s = s.substr(1, s.size()-2);
3198 // If the argument contains a space we
3199 // must put it into ERT: Otherwise LyX
3200 // would misinterpret the space as
3201 // item delimiter (bug 7663)
3202 if (contains(s, ' ')) {
3203 output_ert_inset(os, s, context);
3206 os << parse_text_snippet(p2,
3207 FLAG_BRACK_LAST, outer, context);
3209 // The space is needed to separate the
3210 // item from the rest of the sentence.
3212 eat_whitespace(p, os, context, false);
3217 if (t.cs() == "bibitem") {
3219 context.check_layout(os);
3220 eat_whitespace(p, os, context, false);
3221 string label = p.verbatimOption();
3222 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3223 bool const literal = !lbl.first;
3224 label = literal ? subst(label, "\n", " ") : lbl.second;
3225 string lit = literal ? "\"true\"" : "\"false\"";
3226 string key = convert_literate_command_inset_arg(p.verbatim_item());
3227 begin_command_inset(os, "bibitem", "bibitem");
3228 os << "label \"" << label << "\"\n"
3229 << "key \"" << key << "\"\n"
3230 << "literal " << lit << "\n";
3236 // catch the case of \def\inputGnumericTable
3238 if (t.cs() == "def") {
3239 Token second = p.next_token();
3240 if (second.cs() == "inputGnumericTable") {
3244 Token third = p.get_token();
3246 if (third.cs() == "input") {
3250 string name = normalize_filename(p.verbatim_item());
3251 string const path = getMasterFilePath(true);
3252 // We want to preserve relative / absolute filenames,
3253 // therefore path is only used for testing
3254 // The file extension is in every case ".tex".
3255 // So we need to remove this extension and check for
3256 // the original one.
3257 name = removeExtension(name);
3258 if (!makeAbsPath(name, path).exists()) {
3259 char const * const Gnumeric_formats[] = {"gnumeric",
3261 string const Gnumeric_name =
3262 find_file(name, path, Gnumeric_formats);
3263 if (!Gnumeric_name.empty())
3264 name = Gnumeric_name;
3266 FileName const absname = makeAbsPath(name, path);
3267 if (absname.exists()) {
3268 fix_child_filename(name);
3269 copy_file(absname, name);
3271 cerr << "Warning: Could not find file '"
3272 << name << "'." << endl;
3273 context.check_layout(os);
3274 begin_inset(os, "External\n\ttemplate ");
3275 os << "GnumericSpreadsheet\n\tfilename "
3278 context.check_layout(os);
3280 // register the packages that are automatically loaded
3281 // by the Gnumeric template
3282 registerExternalTemplatePackages("GnumericSpreadsheet");
3287 parse_macro(p, os, context);
3291 if (t.cs() == "noindent") {
3293 context.add_par_extra_stuff("\\noindent\n");
3297 if (t.cs() == "appendix") {
3298 context.add_par_extra_stuff("\\start_of_appendix\n");
3299 // We need to start a new paragraph. Otherwise the
3300 // appendix in 'bla\appendix\chapter{' would start
3302 context.new_paragraph(os);
3303 // We need to make sure that the paragraph is
3304 // generated even if it is empty. Otherwise the
3305 // appendix in '\par\appendix\par\chapter{' would
3307 context.check_layout(os);
3308 // FIXME: This is a hack to prevent paragraph
3309 // deletion if it is empty. Handle this better!
3310 output_comment(p, os,
3311 "dummy comment inserted by tex2lyx to "
3312 "ensure that this paragraph is not empty",
3314 // Both measures above may generate an additional
3315 // empty paragraph, but that does not hurt, because
3316 // whitespace does not matter here.
3317 eat_whitespace(p, os, context, true);
3321 // Must catch empty dates before findLayout is called below
3322 if (t.cs() == "date") {
3323 eat_whitespace(p, os, context, false);
3325 string const date = p.verbatim_item();
3328 preamble.suppressDate(true);
3331 preamble.suppressDate(false);
3332 if (context.new_layout_allowed &&
3333 (newlayout = findLayout(context.textclass,
3336 output_command_layout(os, p, outer,
3337 context, newlayout);
3338 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3339 if (!preamble.titleLayoutFound())
3340 preamble.titleLayoutFound(newlayout->intitle);
3341 set<string> const & req = newlayout->requires();
3342 set<string>::const_iterator it = req.begin();
3343 set<string>::const_iterator en = req.end();
3344 for (; it != en; ++it)
3345 preamble.registerAutomaticallyLoadedPackage(*it);
3347 output_ert_inset(os,
3348 "\\date{" + p.verbatim_item() + '}',
3354 // Before we look for the layout name with star and alone below, we check the layouts including
3355 // the LateXParam, which might be one or several options or a star.
3356 // The single '=' is meant here.
3357 if (context.new_layout_allowed &&
3358 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3359 // store the latexparam here. This is eaten in output_command_layout
3360 context.latexparam = newlayout->latexparam();
3362 output_command_layout(os, p, outer, context, newlayout);
3363 context.latexparam.clear();
3365 if (!preamble.titleLayoutFound())
3366 preamble.titleLayoutFound(newlayout->intitle);
3367 set<string> const & req = newlayout->requires();
3368 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3369 preamble.registerAutomaticallyLoadedPackage(*it);
3374 // Starred section headings
3375 // Must attempt to parse "Section*" before "Section".
3376 if ((p.next_token().asInput() == "*") &&
3377 context.new_layout_allowed &&
3378 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3381 output_command_layout(os, p, outer, context, newlayout);
3383 if (!preamble.titleLayoutFound())
3384 preamble.titleLayoutFound(newlayout->intitle);
3385 set<string> const & req = newlayout->requires();
3386 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3387 preamble.registerAutomaticallyLoadedPackage(*it);
3391 // Section headings and the like
3392 if (context.new_layout_allowed &&
3393 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3395 output_command_layout(os, p, outer, context, newlayout);
3397 if (!preamble.titleLayoutFound())
3398 preamble.titleLayoutFound(newlayout->intitle);
3399 set<string> const & req = newlayout->requires();
3400 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3401 preamble.registerAutomaticallyLoadedPackage(*it);
3405 if (t.cs() == "subfloat") {
3406 // the syntax is \subfloat[list entry][sub caption]{content}
3407 // if it is a table of figure depends on the surrounding float
3409 // do nothing if there is no outer float
3410 if (!float_type.empty()) {
3411 context.check_layout(os);
3413 begin_inset(os, "Float " + float_type + "\n");
3415 << "\nsideways false"
3416 << "\nstatus collapsed\n\n";
3419 bool has_caption = false;
3420 if (p.next_token().cat() != catEscape &&
3421 p.next_token().character() == '[') {
3422 p.get_token(); // eat '['
3423 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3426 // In case we have two optional args, the second is the caption.
3427 if (p.next_token().cat() != catEscape &&
3428 p.next_token().character() == '[') {
3429 p.get_token(); // eat '['
3430 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3433 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3434 // the caption comes always as the last
3436 // we must make sure that the caption gets a \begin_layout
3437 os << "\n\\begin_layout Plain Layout";
3439 begin_inset(os, "Caption Standard\n");
3440 Context newcontext(true, context.textclass,
3441 0, 0, context.font);
3442 newcontext.check_layout(os);
3443 os << caption << "\n";
3444 newcontext.check_end_layout(os);
3447 // close the layout we opened
3448 os << "\n\\end_layout";
3453 // if the float type is not supported or there is no surrounding float
3458 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3460 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3462 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3463 + "{" + p.verbatim_item() + '}', context);
3468 if (t.cs() == "xymatrix") {
3469 // we must open a new math because LyX's xy support is in math
3470 context.check_layout(os);
3471 begin_inset(os, "Formula ");
3473 os << "\\" << t.cs() << '{';
3474 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3477 preamble.registerAutomaticallyLoadedPackage("xy");
3481 if (t.cs() == "includegraphics") {
3482 bool const clip = p.next_token().asInput() == "*";
3485 string const arg = p.getArg('[', ']');
3486 map<string, string> opts;
3487 vector<string> keys;
3488 split_map(arg, opts, keys);
3490 opts["clip"] = string();
3491 string name = normalize_filename(p.verbatim_item());
3493 string const path = getMasterFilePath(true);
3494 // We want to preserve relative / absolute filenames,
3495 // therefore path is only used for testing
3496 if (!makeAbsPath(name, path).exists()) {
3497 // The file extension is probably missing.
3498 // Now try to find it out.
3499 string const dvips_name =
3500 find_file(name, path,
3501 known_dvips_graphics_formats);
3502 string const pdftex_name =
3503 find_file(name, path,
3504 known_pdftex_graphics_formats);
3505 if (!dvips_name.empty()) {
3506 if (!pdftex_name.empty()) {
3507 cerr << "This file contains the "
3509 "\"\\includegraphics{"
3511 "However, files\n\""
3512 << dvips_name << "\" and\n\""
3513 << pdftex_name << "\"\n"
3514 "both exist, so I had to make a "
3515 "choice and took the first one.\n"
3516 "Please move the unwanted one "
3517 "someplace else and try again\n"
3518 "if my choice was wrong."
3522 } else if (!pdftex_name.empty()) {
3528 FileName const absname = makeAbsPath(name, path);
3529 if (absname.exists()) {
3530 fix_child_filename(name);
3531 copy_file(absname, name);
3533 cerr << "Warning: Could not find graphics file '"
3534 << name << "'." << endl;
3536 context.check_layout(os);
3537 begin_inset(os, "Graphics ");
3538 os << "\n\tfilename " << name << '\n';
3539 if (opts.find("width") != opts.end())
3541 << translate_len(opts["width"]) << '\n';
3542 if (opts.find("height") != opts.end())
3544 << translate_len(opts["height"]) << '\n';
3545 if (opts.find("scale") != opts.end()) {
3546 istringstream iss(opts["scale"]);
3550 os << "\tscale " << val << '\n';
3552 if (opts.find("angle") != opts.end()) {
3553 os << "\trotateAngle "
3554 << opts["angle"] << '\n';
3555 vector<string>::const_iterator a =
3556 find(keys.begin(), keys.end(), "angle");
3557 vector<string>::const_iterator s =
3558 find(keys.begin(), keys.end(), "width");
3559 if (s == keys.end())
3560 s = find(keys.begin(), keys.end(), "height");
3561 if (s == keys.end())
3562 s = find(keys.begin(), keys.end(), "scale");
3563 if (s != keys.end() && distance(s, a) > 0)
3564 os << "\tscaleBeforeRotation\n";
3566 if (opts.find("origin") != opts.end()) {
3568 string const opt = opts["origin"];
3569 if (opt.find('l') != string::npos) ss << "left";
3570 if (opt.find('r') != string::npos) ss << "right";
3571 if (opt.find('c') != string::npos) ss << "center";
3572 if (opt.find('t') != string::npos) ss << "Top";
3573 if (opt.find('b') != string::npos) ss << "Bottom";
3574 if (opt.find('B') != string::npos) ss << "Baseline";
3575 if (!ss.str().empty())
3576 os << "\trotateOrigin " << ss.str() << '\n';
3578 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3580 if (opts.find("keepaspectratio") != opts.end())
3581 os << "\tkeepAspectRatio\n";
3582 if (opts.find("clip") != opts.end())
3584 if (opts.find("draft") != opts.end())
3586 if (opts.find("bb") != opts.end())
3587 os << "\tBoundingBox "
3588 << opts["bb"] << '\n';
3589 int numberOfbbOptions = 0;
3590 if (opts.find("bbllx") != opts.end())
3591 numberOfbbOptions++;
3592 if (opts.find("bblly") != opts.end())
3593 numberOfbbOptions++;
3594 if (opts.find("bburx") != opts.end())
3595 numberOfbbOptions++;
3596 if (opts.find("bbury") != opts.end())
3597 numberOfbbOptions++;
3598 if (numberOfbbOptions == 4)
3599 os << "\tBoundingBox "
3600 << opts["bbllx"] << " " << opts["bblly"] << " "
3601 << opts["bburx"] << " " << opts["bbury"] << '\n';
3602 else if (numberOfbbOptions > 0)
3603 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3604 numberOfbbOptions = 0;
3605 if (opts.find("natwidth") != opts.end())
3606 numberOfbbOptions++;
3607 if (opts.find("natheight") != opts.end())
3608 numberOfbbOptions++;
3609 if (numberOfbbOptions == 2)
3610 os << "\tBoundingBox 0bp 0bp "
3611 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3612 else if (numberOfbbOptions > 0)
3613 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3614 ostringstream special;
3615 if (opts.find("hiresbb") != opts.end())
3616 special << "hiresbb,";
3617 if (opts.find("trim") != opts.end())
3619 if (opts.find("viewport") != opts.end())
3620 special << "viewport=" << opts["viewport"] << ',';
3621 if (opts.find("totalheight") != opts.end())
3622 special << "totalheight=" << opts["totalheight"] << ',';
3623 if (opts.find("type") != opts.end())
3624 special << "type=" << opts["type"] << ',';
3625 if (opts.find("ext") != opts.end())
3626 special << "ext=" << opts["ext"] << ',';
3627 if (opts.find("read") != opts.end())
3628 special << "read=" << opts["read"] << ',';
3629 if (opts.find("command") != opts.end())
3630 special << "command=" << opts["command"] << ',';
3631 string s_special = special.str();
3632 if (!s_special.empty()) {
3633 // We had special arguments. Remove the trailing ','.
3634 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3636 // TODO: Handle the unknown settings better.
3637 // Warn about invalid options.
3638 // Check whether some option was given twice.
3640 preamble.registerAutomaticallyLoadedPackage("graphicx");
3644 if (t.cs() == "footnote" ||
3645 (t.cs() == "thanks" && context.layout->intitle)) {
3647 context.check_layout(os);
3648 begin_inset(os, "Foot\n");
3649 os << "status collapsed\n\n";
3650 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3655 if (t.cs() == "marginpar") {
3657 context.check_layout(os);
3658 begin_inset(os, "Marginal\n");
3659 os << "status collapsed\n\n";
3660 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3665 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3666 bool const use_minted = t.cs() == "mintinline";
3668 parse_listings(p, os, context, true, use_minted);
3672 if (t.cs() == "ensuremath") {
3674 context.check_layout(os);
3675 string const s = p.verbatim_item();
3676 //FIXME: this never triggers in UTF8
3677 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3680 output_ert_inset(os, "\\ensuremath{" + s + "}",
3685 else if (t.cs() == "makeindex"
3686 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3687 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3688 if (preamble.titleLayoutFound()) {
3690 skip_spaces_braces(p);
3692 output_ert_inset(os, t.asInput(), context);
3696 if (t.cs() == "tableofcontents"
3697 || t.cs() == "lstlistoflistings"
3698 || t.cs() == "listoflistings") {
3699 string name = t.cs();
3700 if (preamble.minted() && name == "listoflistings")
3701 name.insert(0, "lst");
3702 context.check_layout(os);
3703 begin_command_inset(os, "toc", name);
3705 skip_spaces_braces(p);
3706 if (name == "lstlistoflistings") {
3707 if (preamble.minted())
3708 preamble.registerAutomaticallyLoadedPackage("minted");
3710 preamble.registerAutomaticallyLoadedPackage("listings");
3715 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3716 context.check_layout(os);
3717 if (t.cs() == "listoffigures")
3718 begin_inset(os, "FloatList figure\n");
3720 begin_inset(os, "FloatList table\n");
3722 skip_spaces_braces(p);
3726 if (t.cs() == "listof") {
3727 p.skip_spaces(true);
3728 string const name = p.get_token().cs();
3729 if (context.textclass.floats().typeExist(name)) {
3730 context.check_layout(os);
3731 begin_inset(os, "FloatList ");
3734 p.get_token(); // swallow second arg
3736 output_ert_inset(os, "\\listof{" + name + "}", context);
3740 if ((where = is_known(t.cs(), known_text_font_families))) {
3741 parse_text_attributes(p, os, FLAG_ITEM, outer,
3742 context, "\\family", context.font.family,
3743 known_coded_font_families[where - known_text_font_families]);
3747 // beamer has a \textbf<overlay>{} inset
3748 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3749 parse_text_attributes(p, os, FLAG_ITEM, outer,
3750 context, "\\series", context.font.series,
3751 known_coded_font_series[where - known_text_font_series]);
3755 // beamer has a \textit<overlay>{} inset
3756 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3757 parse_text_attributes(p, os, FLAG_ITEM, outer,
3758 context, "\\shape", context.font.shape,
3759 known_coded_font_shapes[where - known_text_font_shapes]);
3763 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3764 context.check_layout(os);
3765 TeXFont oldFont = context.font;
3766 context.font.init();
3767 context.font.size = oldFont.size;
3768 os << "\n\\family " << context.font.family << "\n";
3769 os << "\n\\series " << context.font.series << "\n";
3770 os << "\n\\shape " << context.font.shape << "\n";
3771 if (t.cs() == "textnormal") {
3772 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3773 output_font_change(os, context.font, oldFont);
3774 context.font = oldFont;
3776 eat_whitespace(p, os, context, false);
3780 if (t.cs() == "textcolor") {
3781 // scheme is \textcolor{color name}{text}
3782 string const color = p.verbatim_item();
3783 // we support the predefined colors of the color and the xcolor package
3784 if (color == "black" || color == "blue" || color == "cyan"
3785 || color == "green" || color == "magenta" || color == "red"
3786 || color == "white" || color == "yellow") {
3787 context.check_layout(os);
3788 os << "\n\\color " << color << "\n";
3789 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3790 context.check_layout(os);
3791 os << "\n\\color inherit\n";
3792 preamble.registerAutomaticallyLoadedPackage("color");
3793 } else if (color == "brown" || color == "darkgray" || color == "gray"
3794 || color == "lightgray" || color == "lime" || color == "olive"
3795 || color == "orange" || color == "pink" || color == "purple"
3796 || color == "teal" || color == "violet") {
3797 context.check_layout(os);
3798 os << "\n\\color " << color << "\n";
3799 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3800 context.check_layout(os);
3801 os << "\n\\color inherit\n";
3802 preamble.registerAutomaticallyLoadedPackage("xcolor");
3804 // for custom defined colors
3805 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3809 if (t.cs() == "underbar" || t.cs() == "uline") {
3810 // \underbar is not 100% correct (LyX outputs \uline
3811 // of ulem.sty). The difference is that \ulem allows
3812 // line breaks, and \underbar does not.
3813 // Do NOT handle \underline.
3814 // \underbar cuts through y, g, q, p etc.,
3815 // \underline does not.
3816 context.check_layout(os);
3817 os << "\n\\bar under\n";
3818 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3819 context.check_layout(os);
3820 os << "\n\\bar default\n";
3821 preamble.registerAutomaticallyLoadedPackage("ulem");
3825 if (t.cs() == "sout") {
3826 context.check_layout(os);
3827 os << "\n\\strikeout on\n";
3828 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3829 context.check_layout(os);
3830 os << "\n\\strikeout default\n";
3831 preamble.registerAutomaticallyLoadedPackage("ulem");
3835 // beamer has an \emph<overlay>{} inset
3836 if ((t.cs() == "uuline" || t.cs() == "uwave"
3837 || t.cs() == "emph" || t.cs() == "noun"
3838 || t.cs() == "xout") && !p.hasOpt("<")) {
3839 context.check_layout(os);
3840 os << "\n\\" << t.cs() << " on\n";
3841 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3842 context.check_layout(os);
3843 os << "\n\\" << t.cs() << " default\n";
3844 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3845 preamble.registerAutomaticallyLoadedPackage("ulem");
3849 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3850 context.check_layout(os);
3851 string name = p.getArg('{', '}');
3852 string localtime = p.getArg('{', '}');
3853 preamble.registerAuthor(name);
3854 Author const & author = preamble.getAuthor(name);
3855 // from_asctime_utc() will fail if LyX decides to output the
3856 // time in the text language.
3857 time_t ptime = from_asctime_utc(localtime);
3858 if (ptime == static_cast<time_t>(-1)) {
3859 cerr << "Warning: Could not parse time `" << localtime
3860 << "´ for change tracking, using current time instead.\n";
3861 ptime = current_time();
3863 if (t.cs() == "lyxadded")
3864 os << "\n\\change_inserted ";
3866 os << "\n\\change_deleted ";
3867 os << author.bufferId() << ' ' << ptime << '\n';
3868 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3869 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3870 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3871 LaTeXPackages::isAvailable("xcolor");
3872 // No need to test for luatex, since luatex comes in
3873 // two flavours (dvi and pdf), like latex, and those
3874 // are detected by pdflatex.
3875 if (pdflatex || xetex) {
3877 preamble.registerAutomaticallyLoadedPackage("ulem");
3878 preamble.registerAutomaticallyLoadedPackage("xcolor");
3879 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3883 preamble.registerAutomaticallyLoadedPackage("dvipost");
3884 } else if (xcolorulem) {
3885 preamble.registerAutomaticallyLoadedPackage("ulem");
3886 preamble.registerAutomaticallyLoadedPackage("xcolor");
3892 if (t.cs() == "textipa") {
3893 context.check_layout(os);
3894 begin_inset(os, "IPA\n");
3895 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3896 context.merging_hyphens_allowed = false;
3897 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3898 context.merging_hyphens_allowed = merging_hyphens_allowed;
3900 preamble.registerAutomaticallyLoadedPackage("tipa");
3901 preamble.registerAutomaticallyLoadedPackage("tipx");
3905 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3906 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3907 context.check_layout(os);
3911 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3912 begin_inset(os, "IPADeco " + type + "\n");
3913 os << "status open\n";
3914 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3920 if (t.cs() == "textvertline") {
3921 // FIXME: This is not correct, \textvertline is higher than |
3927 if (t.cs() == "tone" ) {
3928 context.check_layout(os);
3929 // register the tone package
3930 preamble.registerAutomaticallyLoadedPackage("tone");
3931 string content = trimSpaceAndEol(p.verbatim_item());
3932 string command = t.asInput() + "{" + content + "}";
3933 // some tones can be detected by unicodesymbols, some need special code
3934 if (is_known(content, known_tones)) {
3935 os << "\\IPAChar " << command << "\n";
3938 // try to see whether the string is in unicodesymbols
3942 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3943 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3944 termination, rem, &req);
3948 output_ert_inset(os, to_utf8(rem), context);
3949 for (set<string>::const_iterator it = req.begin();
3950 it != req.end(); ++it)
3951 preamble.registerAutomaticallyLoadedPackage(*it);
3953 // we did not find a non-ert version
3954 output_ert_inset(os, command, context);
3958 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3959 t.cs() == "vphantom") {
3960 context.check_layout(os);
3961 if (t.cs() == "phantom")
3962 begin_inset(os, "Phantom Phantom\n");
3963 if (t.cs() == "hphantom")
3964 begin_inset(os, "Phantom HPhantom\n");
3965 if (t.cs() == "vphantom")
3966 begin_inset(os, "Phantom VPhantom\n");
3967 os << "status open\n";
3968 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3974 if (t.cs() == "href") {
3975 context.check_layout(os);
3976 string target = convert_literate_command_inset_arg(p.verbatim_item());
3977 string name = p.verbatim_item();
3978 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3979 bool const literal = !nm.first;
3980 name = literal ? subst(name, "\n", " ") : nm.second;
3981 string lit = literal ? "\"true\"" : "\"false\"";
3983 size_t i = target.find(':');
3984 if (i != string::npos) {
3985 type = target.substr(0, i + 1);
3986 if (type == "mailto:" || type == "file:")
3987 target = target.substr(i + 1);
3988 // handle the case that name is equal to target, except of "http(s)://"
3989 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3992 begin_command_inset(os, "href", "href");
3994 os << "name \"" << name << "\"\n";
3995 os << "target \"" << target << "\"\n";
3996 if (type == "mailto:" || type == "file:")
3997 os << "type \"" << type << "\"\n";
3998 os << "literal " << lit << "\n";
4000 skip_spaces_braces(p);
4004 if (t.cs() == "lyxline") {
4005 // swallow size argument (it is not used anyway)
4007 if (!context.atParagraphStart()) {
4008 // so our line is in the middle of a paragraph
4009 // we need to add a new line, lest this line
4010 // follow the other content on that line and
4011 // run off the side of the page
4012 // FIXME: This may create an empty paragraph,
4013 // but without that it would not be
4014 // possible to set noindent below.
4015 // Fortunately LaTeX does not care
4016 // about the empty paragraph.
4017 context.new_paragraph(os);
4019 if (preamble.indentParagraphs()) {
4020 // we need to unindent, lest the line be too long
4021 context.add_par_extra_stuff("\\noindent\n");
4023 context.check_layout(os);
4024 begin_command_inset(os, "line", "rule");
4025 os << "offset \"0.5ex\"\n"
4026 "width \"100line%\"\n"
4032 if (t.cs() == "rule") {
4033 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4034 string const width = p.getArg('{', '}');
4035 string const thickness = p.getArg('{', '}');
4036 context.check_layout(os);
4037 begin_command_inset(os, "line", "rule");
4038 if (!offset.empty())
4039 os << "offset \"" << translate_len(offset) << "\"\n";
4040 os << "width \"" << translate_len(width) << "\"\n"
4041 "height \"" << translate_len(thickness) << "\"\n";
4046 // handle refstyle first to catch \eqref which can also occur
4047 // without refstyle. Only recognize these commands if
4048 // refstyle.sty was found in the preamble (otherwise \eqref
4049 // and user defined ref commands could be misdetected).
4050 if ((where = is_known(t.cs(), known_refstyle_commands))
4051 && preamble.refstyle()) {
4052 context.check_layout(os);
4053 begin_command_inset(os, "ref", "formatted");
4054 os << "reference \"";
4055 os << known_refstyle_prefixes[where - known_refstyle_commands]
4057 os << convert_literate_command_inset_arg(p.verbatim_item())
4059 os << "plural \"false\"\n";
4060 os << "caps \"false\"\n";
4061 os << "noprefix \"false\"\n";
4063 preamble.registerAutomaticallyLoadedPackage("refstyle");
4067 // if refstyle is used, we must not convert \prettyref to a
4068 // formatted reference, since that would result in a refstyle command.
4069 if ((where = is_known(t.cs(), known_ref_commands)) &&
4070 (t.cs() != "prettyref" || !preamble.refstyle())) {
4071 string const opt = p.getOpt();
4073 context.check_layout(os);
4074 begin_command_inset(os, "ref",
4075 known_coded_ref_commands[where - known_ref_commands]);
4076 os << "reference \""
4077 << convert_literate_command_inset_arg(p.verbatim_item())
4079 os << "plural \"false\"\n";
4080 os << "caps \"false\"\n";
4081 os << "noprefix \"false\"\n";
4083 if (t.cs() == "vref" || t.cs() == "vpageref")
4084 preamble.registerAutomaticallyLoadedPackage("varioref");
4085 else if (t.cs() == "prettyref")
4086 preamble.registerAutomaticallyLoadedPackage("prettyref");
4088 // LyX does not yet support optional arguments of ref commands
4089 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4090 p.verbatim_item() + '}', context);
4096 is_known(t.cs(), known_natbib_commands) &&
4097 ((t.cs() != "citefullauthor" &&
4098 t.cs() != "citeyear" &&
4099 t.cs() != "citeyearpar") ||
4100 p.next_token().asInput() != "*")) {
4101 context.check_layout(os);
4102 string command = t.cs();
4103 if (p.next_token().asInput() == "*") {
4107 if (command == "citefullauthor")
4108 // alternative name for "\\citeauthor*"
4109 command = "citeauthor*";
4111 // text before the citation
4113 // text after the citation
4115 get_cite_arguments(p, true, before, after);
4117 if (command == "cite") {
4118 // \cite without optional argument means
4119 // \citet, \cite with at least one optional
4120 // argument means \citep.
4121 if (before.empty() && after.empty())
4126 if (before.empty() && after == "[]")
4127 // avoid \citet[]{a}
4129 else if (before == "[]" && after == "[]") {
4130 // avoid \citet[][]{a}
4134 bool literal = false;
4135 pair<bool, string> aft;
4136 pair<bool, string> bef;
4137 // remove the brackets around after and before
4138 if (!after.empty()) {
4140 after.erase(after.length() - 1, 1);
4141 aft = convert_latexed_command_inset_arg(after);
4142 literal = !aft.first;
4143 after = literal ? subst(after, "\n", " ") : aft.second;
4145 if (!before.empty()) {
4147 before.erase(before.length() - 1, 1);
4148 bef = convert_latexed_command_inset_arg(before);
4149 literal |= !bef.first;
4150 before = literal ? subst(before, "\n", " ") : bef.second;
4151 if (literal && !after.empty())
4152 after = subst(after, "\n", " ");
4154 string lit = literal ? "\"true\"" : "\"false\"";
4155 begin_command_inset(os, "citation", command);
4156 os << "after " << '"' << after << '"' << "\n";
4157 os << "before " << '"' << before << '"' << "\n";
4159 << convert_literate_command_inset_arg(p.verbatim_item())
4161 << "literal " << lit << "\n";
4163 // Need to set the cite engine if natbib is loaded by
4164 // the document class directly
4165 if (preamble.citeEngine() == "basic")
4166 preamble.citeEngine("natbib");
4171 && is_known(t.cs(), known_biblatex_commands)
4172 && ((t.cs() == "cite"
4173 || t.cs() == "citeauthor"
4174 || t.cs() == "Citeauthor"
4175 || t.cs() == "parencite"
4176 || t.cs() == "citetitle")
4177 || p.next_token().asInput() != "*"))
4178 || (use_biblatex_natbib
4179 && (is_known(t.cs(), known_biblatex_commands)
4180 || is_known(t.cs(), known_natbib_commands))
4181 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4182 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4183 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4184 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4185 || t.cs() == "parencite" || t.cs() == "citetitle")
4186 || p.next_token().asInput() != "*"))){
4187 context.check_layout(os);
4188 string command = t.cs();
4189 if (p.next_token().asInput() == "*") {
4194 bool const qualified = suffixIs(command, "s");
4196 command = rtrim(command, "s");
4198 // text before the citation
4200 // text after the citation
4202 get_cite_arguments(p, true, before, after, qualified);
4204 // These use natbib cmd names in LyX
4205 // for inter-citeengine compativility
4206 if (command == "citeyear")
4207 command = "citebyear";
4208 else if (command == "cite*")
4209 command = "citeyear";
4210 else if (command == "textcite")
4212 else if (command == "Textcite")
4214 else if (command == "parencite")
4216 else if (command == "Parencite")
4218 else if (command == "parencite*")
4219 command = "citeyearpar";
4220 else if (command == "smartcite")
4221 command = "footcite";
4222 else if (command == "Smartcite")
4223 command = "Footcite";
4225 string const emptyarg = qualified ? "()" : "[]";
4226 if (before.empty() && after == emptyarg)
4229 else if (before == emptyarg && after == emptyarg) {
4230 // avoid \cite[][]{a}
4234 bool literal = false;
4235 pair<bool, string> aft;
4236 pair<bool, string> bef;
4237 // remove the brackets around after and before
4238 if (!after.empty()) {
4240 after.erase(after.length() - 1, 1);
4241 aft = convert_latexed_command_inset_arg(after);
4242 literal = !aft.first;
4243 after = literal ? subst(after, "\n", " ") : aft.second;
4245 if (!before.empty()) {
4247 before.erase(before.length() - 1, 1);
4248 bef = convert_latexed_command_inset_arg(before);
4249 literal |= !bef.first;
4250 before = literal ? subst(before, "\n", " ") : bef.second;
4252 string keys, pretextlist, posttextlist;
4254 map<string, string> pres, posts, preslit, postslit;
4255 vector<string> lkeys;
4256 // text before the citation
4257 string lbefore, lbeforelit;
4258 // text after the citation
4259 string lafter, lafterlit;
4261 pair<bool, string> laft, lbef;
4263 get_cite_arguments(p, true, lbefore, lafter);
4264 // remove the brackets around after and before
4265 if (!lafter.empty()) {
4267 lafter.erase(lafter.length() - 1, 1);
4268 laft = convert_latexed_command_inset_arg(lafter);
4269 literal |= !laft.first;
4270 lafter = laft.second;
4271 lafterlit = subst(lbefore, "\n", " ");
4273 if (!lbefore.empty()) {
4274 lbefore.erase(0, 1);
4275 lbefore.erase(lbefore.length() - 1, 1);
4276 lbef = convert_latexed_command_inset_arg(lbefore);
4277 literal |= !lbef.first;
4278 lbefore = lbef.second;
4279 lbeforelit = subst(lbefore, "\n", " ");
4281 if (lbefore.empty() && lafter == "[]") {
4286 else if (lbefore == "[]" && lafter == "[]") {
4287 // avoid \cite[][]{a}
4293 lkey = p.getArg('{', '}');
4296 if (!lbefore.empty()) {
4297 pres.insert(make_pair(lkey, lbefore));
4298 preslit.insert(make_pair(lkey, lbeforelit));
4300 if (!lafter.empty()) {
4301 posts.insert(make_pair(lkey, lafter));
4302 postslit.insert(make_pair(lkey, lafterlit));
4304 lkeys.push_back(lkey);
4306 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4311 for (auto const & ptl : pres) {
4312 if (!pretextlist.empty())
4313 pretextlist += '\t';
4314 pretextlist += ptl.first + " " + ptl.second;
4316 for (auto const & potl : posts) {
4317 if (!posttextlist.empty())
4318 posttextlist += '\t';
4319 posttextlist += potl.first + " " + potl.second;
4322 keys = convert_literate_command_inset_arg(p.verbatim_item());
4325 after = subst(after, "\n", " ");
4326 if (!before.empty())
4327 before = subst(after, "\n", " ");
4329 string lit = literal ? "\"true\"" : "\"false\"";
4330 begin_command_inset(os, "citation", command);
4331 os << "after " << '"' << after << '"' << "\n";
4332 os << "before " << '"' << before << '"' << "\n";
4336 if (!pretextlist.empty())
4337 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4338 if (!posttextlist.empty())
4339 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4340 os << "literal " << lit << "\n";
4342 // Need to set the cite engine if biblatex is loaded by
4343 // the document class directly
4344 if (preamble.citeEngine() == "basic")
4345 use_biblatex_natbib ?
4346 preamble.citeEngine("biblatex-natbib")
4347 : preamble.citeEngine("biblatex");
4352 is_known(t.cs(), known_jurabib_commands) &&
4353 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4354 context.check_layout(os);
4355 string command = t.cs();
4356 if (p.next_token().asInput() == "*") {
4360 char argumentOrder = '\0';
4361 vector<string> const options =
4362 preamble.getPackageOptions("jurabib");
4363 if (find(options.begin(), options.end(),
4364 "natbiborder") != options.end())
4365 argumentOrder = 'n';
4366 else if (find(options.begin(), options.end(),
4367 "jurabiborder") != options.end())
4368 argumentOrder = 'j';
4370 // text before the citation
4372 // text after the citation
4374 get_cite_arguments(p, argumentOrder != 'j', before, after);
4376 string const citation = p.verbatim_item();
4377 if (!before.empty() && argumentOrder == '\0') {
4378 cerr << "Warning: Assuming argument order "
4379 "of jurabib version 0.6 for\n'"
4380 << command << before << after << '{'
4381 << citation << "}'.\n"
4382 "Add 'jurabiborder' to the jurabib "
4383 "package options if you used an\n"
4384 "earlier jurabib version." << endl;
4386 bool literal = false;
4387 pair<bool, string> aft;
4388 pair<bool, string> bef;
4389 // remove the brackets around after and before
4390 if (!after.empty()) {
4392 after.erase(after.length() - 1, 1);
4393 aft = convert_latexed_command_inset_arg(after);
4394 literal = !aft.first;
4395 after = literal ? subst(after, "\n", " ") : aft.second;
4397 if (!before.empty()) {
4399 before.erase(before.length() - 1, 1);
4400 bef = convert_latexed_command_inset_arg(before);
4401 literal |= !bef.first;
4402 before = literal ? subst(before, "\n", " ") : bef.second;
4403 if (literal && !after.empty())
4404 after = subst(after, "\n", " ");
4406 string lit = literal ? "\"true\"" : "\"false\"";
4407 begin_command_inset(os, "citation", command);
4408 os << "after " << '"' << after << "\"\n"
4409 << "before " << '"' << before << "\"\n"
4410 << "key " << '"' << citation << "\"\n"
4411 << "literal " << lit << "\n";
4413 // Need to set the cite engine if jurabib is loaded by
4414 // the document class directly
4415 if (preamble.citeEngine() == "basic")
4416 preamble.citeEngine("jurabib");
4420 if (t.cs() == "cite"
4421 || t.cs() == "nocite") {
4422 context.check_layout(os);
4423 string after = p.getArg('[', ']');
4424 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4425 bool const literal = !aft.first;
4426 after = literal ? subst(after, "\n", " ") : aft.second;
4427 string lit = literal ? "\"true\"" : "\"false\"";
4428 string key = convert_literate_command_inset_arg(p.verbatim_item());
4429 // store the case that it is "\nocite{*}" to use it later for
4432 begin_command_inset(os, "citation", t.cs());
4433 os << "after " << '"' << after << "\"\n"
4434 << "key " << '"' << key << "\"\n"
4435 << "literal " << lit << "\n";
4437 } else if (t.cs() == "nocite")
4442 if (t.cs() == "index" ||
4443 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4444 context.check_layout(os);
4445 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4446 p.getArg('[', ']') : "";
4447 string const kind = arg.empty() ? "idx" : arg;
4448 begin_inset(os, "Index ");
4449 os << kind << "\nstatus collapsed\n";
4450 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4453 preamble.registerAutomaticallyLoadedPackage("splitidx");
4457 if (t.cs() == "nomenclature") {
4458 context.check_layout(os);
4459 begin_command_inset(os, "nomenclature", "nomenclature");
4460 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4461 if (!prefix.empty())
4462 os << "prefix " << '"' << prefix << '"' << "\n";
4463 string symbol = p.verbatim_item();
4464 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4465 bool literal = !sym.first;
4466 string description = p.verbatim_item();
4467 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4468 literal |= !desc.first;
4470 symbol = subst(symbol, "\n", " ");
4471 description = subst(description, "\n", " ");
4473 symbol = sym.second;
4474 description = desc.second;
4476 string lit = literal ? "\"true\"" : "\"false\"";
4477 os << "symbol " << '"' << symbol;
4478 os << "\"\ndescription \""
4479 << description << "\"\n"
4480 << "literal " << lit << "\n";
4482 preamble.registerAutomaticallyLoadedPackage("nomencl");
4486 if (t.cs() == "label") {
4487 context.check_layout(os);
4488 begin_command_inset(os, "label", "label");
4490 << convert_literate_command_inset_arg(p.verbatim_item())
4496 if (t.cs() == "lyxmintcaption") {
4497 string const pos = p.getArg('[', ']');
4499 string const caption =
4500 parse_text_snippet(p, FLAG_ITEM, false,
4502 minted_nonfloat_caption = "[t]" + caption;
4504 // We already got the caption at the bottom,
4505 // so simply skip it.
4506 parse_text_snippet(p, FLAG_ITEM, false, context);
4508 eat_whitespace(p, os, context, true);
4512 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4513 context.check_layout(os);
4514 string commandname = t.cs();
4516 if (p.next_token().asInput() == "*") {
4521 begin_command_inset(os, "index_print", commandname);
4522 string const indexname = p.getArg('[', ']');
4524 if (indexname.empty())
4525 os << "type \"idx\"\n";
4527 os << "type \"" << indexname << "\"\n";
4528 os << "literal \"true\"\n";
4531 skip_spaces_braces(p);
4532 preamble.registerAutomaticallyLoadedPackage("makeidx");
4533 if (preamble.use_indices() == "true")
4534 preamble.registerAutomaticallyLoadedPackage("splitidx");
4538 if (t.cs() == "printnomenclature") {
4540 string width_type = "";
4541 context.check_layout(os);
4542 begin_command_inset(os, "nomencl_print", "printnomenclature");
4543 // case of a custom width
4545 width = p.getArg('[', ']');
4546 width = translate_len(width);
4547 width_type = "custom";
4549 // case of no custom width
4550 // the case of no custom width but the width set
4551 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4552 // because the user could have set anything, not only the width
4553 // of the longest label (which would be width_type = "auto")
4554 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4555 if (label.empty() && width_type.empty())
4556 width_type = "none";
4557 os << "set_width \"" << width_type << "\"\n";
4558 if (width_type == "custom")
4559 os << "width \"" << width << '\"';
4561 skip_spaces_braces(p);
4562 preamble.registerAutomaticallyLoadedPackage("nomencl");
4566 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4567 context.check_layout(os);
4568 begin_inset(os, "script ");
4569 os << t.cs().substr(4) << '\n';
4570 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4571 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4573 if (t.cs() == "textsubscript")
4574 preamble.registerAutomaticallyLoadedPackage("subscript");
4578 if ((where = is_known(t.cs(), known_quotes))) {
4579 context.check_layout(os);
4580 begin_inset(os, "Quotes ");
4581 string quotetype = known_coded_quotes[where - known_quotes];
4582 // try to make a smart guess about the side
4583 Token const prev = p.prev_token();
4584 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4585 && prev.character() != '\n' && prev.character() != '~');
4586 quotetype = guessQuoteStyle(quotetype, opening);
4589 // LyX adds {} after the quote, so we have to eat
4590 // spaces here if there are any before a possible
4592 eat_whitespace(p, os, context, false);
4597 if ((where = is_known(t.cs(), known_sizes)) &&
4598 context.new_layout_allowed) {
4599 context.check_layout(os);
4600 TeXFont const oldFont = context.font;
4601 context.font.size = known_coded_sizes[where - known_sizes];
4602 output_font_change(os, oldFont, context.font);
4603 eat_whitespace(p, os, context, false);
4607 if ((where = is_known(t.cs(), known_font_families)) &&
4608 context.new_layout_allowed) {
4609 context.check_layout(os);
4610 TeXFont const oldFont = context.font;
4611 context.font.family =
4612 known_coded_font_families[where - known_font_families];
4613 output_font_change(os, oldFont, context.font);
4614 eat_whitespace(p, os, context, false);
4618 if ((where = is_known(t.cs(), known_font_series)) &&
4619 context.new_layout_allowed) {
4620 context.check_layout(os);
4621 TeXFont const oldFont = context.font;
4622 context.font.series =
4623 known_coded_font_series[where - known_font_series];
4624 output_font_change(os, oldFont, context.font);
4625 eat_whitespace(p, os, context, false);
4629 if ((where = is_known(t.cs(), known_font_shapes)) &&
4630 context.new_layout_allowed) {
4631 context.check_layout(os);
4632 TeXFont const oldFont = context.font;
4633 context.font.shape =
4634 known_coded_font_shapes[where - known_font_shapes];
4635 output_font_change(os, oldFont, context.font);
4636 eat_whitespace(p, os, context, false);
4639 if ((where = is_known(t.cs(), known_old_font_families)) &&
4640 context.new_layout_allowed) {
4641 context.check_layout(os);
4642 TeXFont const oldFont = context.font;
4643 context.font.init();
4644 context.font.size = oldFont.size;
4645 context.font.family =
4646 known_coded_font_families[where - known_old_font_families];
4647 output_font_change(os, oldFont, context.font);
4648 eat_whitespace(p, os, context, false);
4652 if ((where = is_known(t.cs(), known_old_font_series)) &&
4653 context.new_layout_allowed) {
4654 context.check_layout(os);
4655 TeXFont const oldFont = context.font;
4656 context.font.init();
4657 context.font.size = oldFont.size;
4658 context.font.series =
4659 known_coded_font_series[where - known_old_font_series];
4660 output_font_change(os, oldFont, context.font);
4661 eat_whitespace(p, os, context, false);
4665 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4666 context.new_layout_allowed) {
4667 context.check_layout(os);
4668 TeXFont const oldFont = context.font;
4669 context.font.init();
4670 context.font.size = oldFont.size;
4671 context.font.shape =
4672 known_coded_font_shapes[where - known_old_font_shapes];
4673 output_font_change(os, oldFont, context.font);
4674 eat_whitespace(p, os, context, false);
4678 if (t.cs() == "selectlanguage") {
4679 context.check_layout(os);
4680 // save the language for the case that a
4681 // \foreignlanguage is used
4682 context.font.language = babel2lyx(p.verbatim_item());
4683 os << "\n\\lang " << context.font.language << "\n";
4687 if (t.cs() == "foreignlanguage") {
4688 string const lang = babel2lyx(p.verbatim_item());
4689 parse_text_attributes(p, os, FLAG_ITEM, outer,
4691 context.font.language, lang);
4695 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4696 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4697 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4699 // We have to output the whole command if it has an option
4700 // because LyX doesn't support this yet, see bug #8214,
4701 // only if there is a single option specifying a variant, we can handle it.
4703 string langopts = p.getOpt();
4704 // check if the option contains a variant, if yes, extract it
4705 string::size_type pos_var = langopts.find("variant");
4706 string::size_type i = langopts.find(',');
4707 string::size_type k = langopts.find('=', pos_var);
4708 if (pos_var != string::npos && i == string::npos) {
4710 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4711 lang = preamble.polyglossia2lyx(variant);
4712 parse_text_attributes(p, os, FLAG_ITEM, outer,
4714 context.font.language, lang);
4716 output_ert_inset(os, t.asInput() + langopts, context);
4718 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4719 parse_text_attributes(p, os, FLAG_ITEM, outer,
4721 context.font.language, lang);
4726 if (t.cs() == "inputencoding") {
4727 // nothing to write here
4728 string const enc = subst(p.verbatim_item(), "\n", " ");
4729 p.setEncoding(enc, Encoding::inputenc);
4733 if (is_known(t.cs(), known_special_chars) ||
4734 (t.cs() == "protect" &&
4735 p.next_token().cat() == catEscape &&
4736 is_known(p.next_token().cs(), known_special_protect_chars))) {
4737 // LyX sometimes puts a \protect in front, so we have to ignore it
4739 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4740 known_special_chars);
4741 context.check_layout(os);
4742 os << known_coded_special_chars[where - known_special_chars];
4743 skip_spaces_braces(p);
4747 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4748 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4749 p.next_next_token().asInput() == "-") ||
4750 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4751 // LyX sometimes puts a \protect in front, so we have to ignore it
4752 if (t.cs() == "protect")
4754 context.check_layout(os);
4755 if (t.cs() == "nobreakdash")
4756 os << "\\SpecialChar nobreakdash\n";
4758 os << "\\SpecialChar endofsentence\n";
4763 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4764 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4765 || t.cs() == "%" || t.cs() == "-") {
4766 context.check_layout(os);
4768 os << "\\SpecialChar softhyphen\n";
4774 if (t.cs() == "char") {
4775 context.check_layout(os);
4776 if (p.next_token().character() == '`') {
4778 if (p.next_token().cs() == "\"") {
4783 output_ert_inset(os, "\\char`", context);
4786 output_ert_inset(os, "\\char", context);
4791 if (t.cs() == "verb") {
4792 context.check_layout(os);
4793 // set catcodes to verbatim early, just in case.
4794 p.setCatcodes(VERBATIM_CATCODES);
4795 string delim = p.get_token().asInput();
4796 Parser::Arg arg = p.verbatimStuff(delim);
4798 output_ert_inset(os, "\\verb" + delim
4799 + arg.second + delim, context);
4801 cerr << "invalid \\verb command. Skipping" << endl;
4805 // Problem: \= creates a tabstop inside the tabbing environment
4806 // and else an accent. In the latter case we really would want
4807 // \={o} instead of \= o.
4808 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4809 output_ert_inset(os, t.asInput(), context);
4813 if (t.cs() == "\\") {
4814 context.check_layout(os);
4816 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4817 else if (p.next_token().asInput() == "*") {
4819 // getOpt() eats the following space if there
4820 // is no optional argument, but that is OK
4821 // here since it has no effect in the output.
4822 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4825 begin_inset(os, "Newline newline");
4831 if (t.cs() == "newline" ||
4832 (t.cs() == "linebreak" && !p.hasOpt())) {
4833 context.check_layout(os);
4834 begin_inset(os, "Newline ");
4837 skip_spaces_braces(p);
4841 if (t.cs() == "input" || t.cs() == "include"
4842 || t.cs() == "verbatiminput"
4843 || t.cs() == "lstinputlisting"
4844 || t.cs() == "inputminted") {
4845 string name = t.cs();
4846 if (name == "verbatiminput"
4847 && p.next_token().asInput() == "*")
4848 name += p.get_token().asInput();
4849 context.check_layout(os);
4851 bool literal = false;
4852 if (name == "lstinputlisting" && p.hasOpt()) {
4853 lstparams = p.getArg('[', ']');
4854 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4855 literal = !oa.first;
4857 lstparams = subst(lstparams, "\n", " ");
4859 lstparams = oa.second;
4860 } else if (name == "inputminted") {
4861 name = "lstinputlisting";
4862 string const lang = p.getArg('{', '}');
4863 if (lang != "tex") {
4864 string cmd = "\\inputminted{" + lang + "}{";
4865 cmd += p.getArg('{', '}') + "}";
4866 output_ert_inset(os, cmd, context);
4869 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4870 minted_nonfloat_caption.erase(0,3);
4871 // extract label and caption from the already produced LyX code
4872 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4873 string const caption = nfc.front();
4875 vector<string>::iterator it =
4876 find(nfc.begin(), nfc.end(), "LatexCommand label");
4877 if (it != nfc.end()) {
4879 if (it != nfc.end())
4881 label = support::split(label, '"');
4884 minted_nonfloat_caption.clear();
4885 lstparams = "caption=" + caption;
4887 lstparams += ",label=" + label;
4888 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4889 literal = !oa.first;
4891 lstparams = subst(lstparams, "\n", " ");
4893 lstparams = oa.second;
4896 string lit = literal ? "\"true\"" : "\"false\"";
4897 string filename(normalize_filename(p.getArg('{', '}')));
4898 string const path = getMasterFilePath(true);
4899 // We want to preserve relative / absolute filenames,
4900 // therefore path is only used for testing
4901 if ((t.cs() == "include" || t.cs() == "input") &&
4902 !makeAbsPath(filename, path).exists()) {
4903 // The file extension is probably missing.
4904 // Now try to find it out.
4905 string const tex_name =
4906 find_file(filename, path,
4907 known_tex_extensions);
4908 if (!tex_name.empty())
4909 filename = tex_name;
4911 bool external = false;
4913 if (makeAbsPath(filename, path).exists()) {
4914 string const abstexname =
4915 makeAbsPath(filename, path).absFileName();
4916 string const absfigname =
4917 changeExtension(abstexname, ".fig");
4918 fix_child_filename(filename);
4919 string const lyxname = changeExtension(filename,
4920 roundtripMode() ? ".lyx.lyx" : ".lyx");
4921 string const abslyxname = makeAbsPath(
4922 lyxname, getParentFilePath(false)).absFileName();
4924 if (!skipChildren())
4925 external = FileName(absfigname).exists();
4926 if (t.cs() == "input" && !skipChildren()) {
4927 string const ext = getExtension(abstexname);
4929 // Combined PS/LaTeX:
4930 // x.eps, x.pstex_t (old xfig)
4931 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4932 FileName const absepsname(
4933 changeExtension(abstexname, ".eps"));
4934 FileName const abspstexname(
4935 changeExtension(abstexname, ".pstex"));
4936 bool const xfigeps =
4937 (absepsname.exists() ||
4938 abspstexname.exists()) &&
4941 // Combined PDF/LaTeX:
4942 // x.pdf, x.pdftex_t (old xfig)
4943 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4944 FileName const abspdfname(
4945 changeExtension(abstexname, ".pdf"));
4946 bool const xfigpdf =
4947 abspdfname.exists() &&
4948 (ext == "pdftex_t" || ext == "pdf_t");
4952 // Combined PS/PDF/LaTeX:
4953 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4954 string const absbase2(
4955 removeExtension(abstexname) + "_pspdftex");
4956 FileName const abseps2name(
4957 addExtension(absbase2, ".eps"));
4958 FileName const abspdf2name(
4959 addExtension(absbase2, ".pdf"));
4960 bool const xfigboth =
4961 abspdf2name.exists() &&
4962 abseps2name.exists() && ext == "pspdftex";
4964 xfig = xfigpdf || xfigeps || xfigboth;
4965 external = external && xfig;
4968 outname = changeExtension(filename, ".fig");
4969 FileName abssrc(changeExtension(abstexname, ".fig"));
4970 copy_file(abssrc, outname);
4972 // Don't try to convert, the result
4973 // would be full of ERT.
4975 FileName abssrc(abstexname);
4976 copy_file(abssrc, outname);
4977 } else if (t.cs() != "verbatiminput" &&
4979 tex2lyx(abstexname, FileName(abslyxname),
4982 // no need to call copy_file
4983 // tex2lyx creates the file
4986 FileName abssrc(abstexname);
4987 copy_file(abssrc, outname);
4990 cerr << "Warning: Could not find included file '"
4991 << filename << "'." << endl;
4995 begin_inset(os, "External\n");
4996 os << "\ttemplate XFig\n"
4997 << "\tfilename " << outname << '\n';
4998 registerExternalTemplatePackages("XFig");
5000 begin_command_inset(os, "include", name);
5001 outname = subst(outname, "\"", "\\\"");
5002 os << "preview false\n"
5003 "filename \"" << outname << "\"\n";
5004 if (!lstparams.empty())
5005 os << "lstparams \"" << lstparams << "\"\n";
5006 os << "literal " << lit << "\n";
5007 if (t.cs() == "verbatiminput")
5008 preamble.registerAutomaticallyLoadedPackage("verbatim");
5014 if (t.cs() == "bibliographystyle") {
5015 // store new bibliographystyle
5016 bibliographystyle = p.verbatim_item();
5017 // If any other command than \bibliography, \addcontentsline
5018 // and \nocite{*} follows, we need to output the style
5019 // (because it might be used by that command).
5020 // Otherwise, it will automatically be output by LyX.
5023 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5024 if (t2.cat() == catBegin)
5026 if (t2.cat() != catEscape)
5028 if (t2.cs() == "nocite") {
5029 if (p.getArg('{', '}') == "*")
5031 } else if (t2.cs() == "bibliography")
5033 else if (t2.cs() == "phantomsection") {
5037 else if (t2.cs() == "addcontentsline") {
5038 // get the 3 arguments of \addcontentsline
5041 contentslineContent = p.getArg('{', '}');
5042 // if the last argument is not \refname we must output
5043 if (contentslineContent == "\\refname")
5050 output_ert_inset(os,
5051 "\\bibliographystyle{" + bibliographystyle + '}',
5057 if (t.cs() == "phantomsection") {
5058 // we only support this if it occurs between
5059 // \bibliographystyle and \bibliography
5060 if (bibliographystyle.empty())
5061 output_ert_inset(os, "\\phantomsection", context);
5065 if (t.cs() == "addcontentsline") {
5066 context.check_layout(os);
5067 // get the 3 arguments of \addcontentsline
5068 string const one = p.getArg('{', '}');
5069 string const two = p.getArg('{', '}');
5070 string const three = p.getArg('{', '}');
5071 // only if it is a \refname, we support if for the bibtex inset
5072 if (contentslineContent != "\\refname") {
5073 output_ert_inset(os,
5074 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5080 else if (t.cs() == "bibliography") {
5081 context.check_layout(os);
5083 begin_command_inset(os, "bibtex", "bibtex");
5084 if (!btprint.empty()) {
5085 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5086 // clear the string because the next BibTeX inset can be without the
5087 // \nocite{*} option
5090 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5091 // Do we have addcontentsline?
5092 if (contentslineContent == "\\refname") {
5093 BibOpts = "bibtotoc";
5094 // clear string because next BibTeX inset can be without addcontentsline
5095 contentslineContent.clear();
5097 // Do we have a bibliographystyle set?
5098 if (!bibliographystyle.empty()) {
5099 if (BibOpts.empty())
5100 BibOpts = normalize_filename(bibliographystyle);
5102 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5103 // clear it because each bibtex entry has its style
5104 // and we need an empty string to handle \phantomsection
5105 bibliographystyle.clear();
5107 os << "options " << '"' << BibOpts << '"' << "\n";
5108 if (p.getEncoding() != preamble.docencoding) {
5109 Encoding const * const enc = encodings.fromIconvName(
5110 p.getEncoding(), Encoding::inputenc, true);
5112 cerr << "Unknown bib encoding " << p.getEncoding()
5113 << ". Ignoring." << std::endl;
5115 os << "encoding " << '"' << enc->name() << '"' << "\n";
5121 if (t.cs() == "printbibliography") {
5122 context.check_layout(os);
5124 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5125 vector<string> opts = getVectorFromString(bbloptions);
5126 vector<string>::iterator it =
5127 find(opts.begin(), opts.end(), "heading=bibintoc");
5128 if (it != opts.end()) {
5130 BibOpts = "bibtotoc";
5132 bbloptions = getStringFromVector(opts);
5133 begin_command_inset(os, "bibtex", "bibtex");
5134 if (!btprint.empty()) {
5135 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5136 // clear the string because the next BibTeX inset can be without the
5137 // \nocite{*} option
5141 for (auto const & bf : preamble.biblatex_bibliographies) {
5142 if (!bibfiles.empty())
5144 bibfiles += normalize_filename(bf);
5146 if (!bibfiles.empty())
5147 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5148 // Do we have addcontentsline?
5149 if (contentslineContent == "\\refname") {
5150 BibOpts = "bibtotoc";
5151 // clear string because next BibTeX inset can be without addcontentsline
5152 contentslineContent.clear();
5154 os << "options " << '"' << BibOpts << '"' << "\n";
5155 if (!bbloptions.empty())
5156 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5157 if (!preamble.bibencoding.empty()) {
5158 Encoding const * const enc = encodings.fromLaTeXName(
5159 preamble.bibencoding, Encoding::inputenc, true);
5161 cerr << "Unknown bib encoding " << preamble.bibencoding
5162 << ". Ignoring." << std::endl;
5164 os << "encoding " << '"' << enc->name() << '"' << "\n";
5167 need_commentbib = false;
5171 if (t.cs() == "bibbysection") {
5172 context.check_layout(os);
5174 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5175 vector<string> opts = getVectorFromString(bbloptions);
5176 vector<string>::iterator it =
5177 find(opts.begin(), opts.end(), "heading=bibintoc");
5178 if (it != opts.end()) {
5180 BibOpts = "bibtotoc";
5182 bbloptions = getStringFromVector(opts);
5183 begin_command_inset(os, "bibtex", "bibtex");
5184 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5186 for (auto const & bf : preamble.biblatex_bibliographies) {
5187 if (!bibfiles.empty())
5189 bibfiles += normalize_filename(bf);
5191 if (!bibfiles.empty())
5192 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5193 os << "options " << '"' << BibOpts << '"' << "\n";
5194 if (!bbloptions.empty())
5195 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5197 need_commentbib = false;
5201 if (t.cs() == "parbox") {
5202 // Test whether this is an outer box of a shaded box
5204 // swallow arguments
5205 while (p.hasOpt()) {
5207 p.skip_spaces(true);
5210 p.skip_spaces(true);
5212 if (p.next_token().cat() == catBegin)
5214 p.skip_spaces(true);
5215 Token to = p.get_token();
5216 bool shaded = false;
5217 if (to.asInput() == "\\begin") {
5218 p.skip_spaces(true);
5219 if (p.getArg('{', '}') == "shaded")
5224 parse_outer_box(p, os, FLAG_ITEM, outer,
5225 context, "parbox", "shaded");
5227 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5228 "", "", t.cs(), "", "");
5232 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5233 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5234 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5235 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5239 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5240 string backgroundcolor;
5241 preamble.registerAutomaticallyLoadedPackage("xcolor");
5242 if (t.cs() == "fcolorbox") {
5243 string const framecolor = p.getArg('{', '}');
5244 backgroundcolor = p.getArg('{', '}');
5245 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5247 backgroundcolor = p.getArg('{', '}');
5248 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5253 // FIXME: due to the compiler limit of "if" nestings
5254 // the code for the alignment was put here
5255 // put them in their own if if this is fixed
5256 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5257 || t.cs() == "shadowsize"
5258 || t.cs() == "raggedleft" || t.cs() == "centering"
5259 || t.cs() == "raggedright") {
5260 if (t.cs() == "fboxrule")
5262 if (t.cs() == "fboxsep")
5264 if (t.cs() == "shadowsize")
5266 if (t.cs() != "raggedleft" && t.cs() != "centering"
5267 && t.cs() != "raggedright") {
5268 p.skip_spaces(true);
5269 while (p.good() && p.next_token().cat() != catSpace
5270 && p.next_token().cat() != catNewline
5271 && p.next_token().cat() != catEscape) {
5272 if (t.cs() == "fboxrule")
5273 fboxrule = fboxrule + p.get_token().asInput();
5274 if (t.cs() == "fboxsep")
5275 fboxsep = fboxsep + p.get_token().asInput();
5276 if (t.cs() == "shadowsize")
5277 shadow_size = shadow_size + p.get_token().asInput();
5280 output_ert_inset(os, t.asInput(), context);
5285 //\framebox() is part of the picture environment and different from \framebox{}
5286 //\framebox{} will be parsed by parse_outer_box
5287 if (t.cs() == "framebox") {
5288 if (p.next_token().character() == '(') {
5289 //the syntax is: \framebox(x,y)[position]{content}
5290 string arg = t.asInput();
5291 arg += p.getFullParentheseArg();
5292 arg += p.getFullOpt();
5293 eat_whitespace(p, os, context, false);
5294 output_ert_inset(os, arg + '{', context);
5295 parse_text(p, os, FLAG_ITEM, outer, context);
5296 output_ert_inset(os, "}", context);
5298 //the syntax is: \framebox[width][position]{content}
5299 string special = p.getFullOpt();
5300 special += p.getOpt();
5301 parse_outer_box(p, os, FLAG_ITEM, outer,
5302 context, t.cs(), special);
5307 //\makebox() is part of the picture environment and different from \makebox{}
5308 //\makebox{} will be parsed by parse_box
5309 if (t.cs() == "makebox") {
5310 if (p.next_token().character() == '(') {
5311 //the syntax is: \makebox(x,y)[position]{content}
5312 string arg = t.asInput();
5313 arg += p.getFullParentheseArg();
5314 arg += p.getFullOpt();
5315 eat_whitespace(p, os, context, false);
5316 output_ert_inset(os, arg + '{', context);
5317 parse_text(p, os, FLAG_ITEM, outer, context);
5318 output_ert_inset(os, "}", context);
5320 //the syntax is: \makebox[width][position]{content}
5321 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5322 "", "", t.cs(), "", "");
5326 if (t.cs() == "smallskip" ||
5327 t.cs() == "medskip" ||
5328 t.cs() == "bigskip" ||
5329 t.cs() == "vfill") {
5330 context.check_layout(os);
5331 begin_inset(os, "VSpace ");
5334 skip_spaces_braces(p);
5338 if ((where = is_known(t.cs(), known_spaces))) {
5339 context.check_layout(os);
5340 begin_inset(os, "space ");
5341 os << '\\' << known_coded_spaces[where - known_spaces]
5344 // LaTeX swallows whitespace after all spaces except
5345 // "\\,". We have to do that here, too, because LyX
5346 // adds "{}" which would make the spaces significant.
5348 eat_whitespace(p, os, context, false);
5349 // LyX adds "{}" after all spaces except "\\ " and
5350 // "\\,", so we have to remove "{}".
5351 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5352 // remove the braces after "\\,", too.
5358 if (t.cs() == "newpage" ||
5359 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5360 t.cs() == "clearpage" ||
5361 t.cs() == "cleardoublepage") {
5362 context.check_layout(os);
5363 begin_inset(os, "Newpage ");
5366 skip_spaces_braces(p);
5370 if (t.cs() == "DeclareRobustCommand" ||
5371 t.cs() == "DeclareRobustCommandx" ||
5372 t.cs() == "newcommand" ||
5373 t.cs() == "newcommandx" ||
5374 t.cs() == "providecommand" ||
5375 t.cs() == "providecommandx" ||
5376 t.cs() == "renewcommand" ||
5377 t.cs() == "renewcommandx") {
5378 // DeclareRobustCommand, DeclareRobustCommandx,
5379 // providecommand and providecommandx could be handled
5380 // by parse_command(), but we need to call
5381 // add_known_command() here.
5382 string name = t.asInput();
5383 if (p.next_token().asInput() == "*") {
5384 // Starred form. Eat '*'
5388 string const command = p.verbatim_item();
5389 string const opt1 = p.getFullOpt();
5390 string const opt2 = p.getFullOpt();
5391 add_known_command(command, opt1, !opt2.empty());
5392 string const ert = name + '{' + command + '}' +
5394 '{' + p.verbatim_item() + '}';
5396 if (t.cs() == "DeclareRobustCommand" ||
5397 t.cs() == "DeclareRobustCommandx" ||
5398 t.cs() == "providecommand" ||
5399 t.cs() == "providecommandx" ||
5400 name[name.length()-1] == '*')
5401 output_ert_inset(os, ert, context);
5403 context.check_layout(os);
5404 begin_inset(os, "FormulaMacro");
5411 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5412 // let could be handled by parse_command(),
5413 // but we need to call add_known_command() here.
5414 string ert = t.asInput();
5417 if (p.next_token().cat() == catBegin) {
5418 name = p.verbatim_item();
5419 ert += '{' + name + '}';
5421 name = p.verbatim_item();
5426 if (p.next_token().cat() == catBegin) {
5427 command = p.verbatim_item();
5428 ert += '{' + command + '}';
5430 command = p.verbatim_item();
5433 // If command is known, make name known too, to parse
5434 // its arguments correctly. For this reason we also
5435 // have commands in syntax.default that are hardcoded.
5436 CommandMap::iterator it = known_commands.find(command);
5437 if (it != known_commands.end())
5438 known_commands[t.asInput()] = it->second;
5439 output_ert_inset(os, ert, context);
5443 if (t.cs() == "hspace" || t.cs() == "vspace") {
5446 string name = t.asInput();
5447 string const length = p.verbatim_item();
5450 bool valid = splitLatexLength(length, valstring, unit);
5451 bool known_hspace = false;
5452 bool known_vspace = false;
5453 bool known_unit = false;
5456 istringstream iss(valstring);
5459 if (t.cs()[0] == 'h') {
5460 if (unit == "\\fill") {
5465 known_hspace = true;
5468 if (unit == "\\smallskipamount") {
5470 known_vspace = true;
5471 } else if (unit == "\\medskipamount") {
5473 known_vspace = true;
5474 } else if (unit == "\\bigskipamount") {
5476 known_vspace = true;
5477 } else if (unit == "\\fill") {
5479 known_vspace = true;
5483 if (!known_hspace && !known_vspace) {
5484 switch (unitFromString(unit)) {
5500 //unitFromString(unit) fails for relative units like Length::PCW
5501 // therefore handle them separately
5502 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5503 || unit == "\\textwidth" || unit == "\\linewidth"
5504 || unit == "\\textheight" || unit == "\\paperheight"
5505 || unit == "\\baselineskip")
5513 // check for glue lengths
5514 bool is_gluelength = false;
5515 string gluelength = length;
5516 string::size_type i = length.find(" minus");
5517 if (i == string::npos) {
5518 i = length.find(" plus");
5519 if (i != string::npos)
5520 is_gluelength = true;
5522 is_gluelength = true;
5523 // if yes transform "9xx minus 8yy plus 7zz"
5525 if (is_gluelength) {
5526 i = gluelength.find(" minus");
5527 if (i != string::npos)
5528 gluelength.replace(i, 7, "-");
5529 i = gluelength.find(" plus");
5530 if (i != string::npos)
5531 gluelength.replace(i, 6, "+");
5534 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5535 // Literal horizontal length or known variable
5536 context.check_layout(os);
5537 begin_inset(os, "space ");
5545 if (known_unit && !known_hspace)
5546 os << "\n\\length " << translate_len(length);
5548 os << "\n\\length " << gluelength;
5550 } else if (known_unit || known_vspace || is_gluelength) {
5551 // Literal vertical length or known variable
5552 context.check_layout(os);
5553 begin_inset(os, "VSpace ");
5556 if (known_unit && !known_vspace)
5557 os << translate_len(length);
5564 // LyX can't handle other length variables in Inset VSpace/space
5569 output_ert_inset(os, name + '{' + unit + '}', context);
5570 else if (value == -1.0)
5571 output_ert_inset(os, name + "{-" + unit + '}', context);
5573 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5575 output_ert_inset(os, name + '{' + length + '}', context);
5580 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5581 // might be one or several options or a star.
5582 // The single '=' is meant here.
5583 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5587 context.check_layout(os);
5588 // store the latexparam here. This is eaten in parse_text_in_inset
5589 context.latexparam = newinsetlayout->latexparam();
5590 docstring name = newinsetlayout->name();
5591 bool const caption = name.find(from_ascii("Caption:")) == 0;
5593 // Already done for floating minted listings.
5594 if (minted_float.empty()) {
5595 begin_inset(os, "Caption ");
5596 os << to_utf8(name.substr(8)) << '\n';
5599 // FIXME: what do we do if the prefix is not Flex: ?
5600 if (prefixIs(name, from_ascii("Flex:")))
5602 begin_inset(os, "Flex ");
5603 os << to_utf8(name) << '\n'
5604 << "status collapsed\n";
5606 if (!minted_float.empty()) {
5607 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5608 } else if (newinsetlayout->isPassThru()) {
5609 // set catcodes to verbatim early, just in case.
5610 p.setCatcodes(VERBATIM_CATCODES);
5611 string delim = p.get_token().asInput();
5613 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5614 //FIXME: handle error condition
5615 string const arg = p.verbatimStuff("}").second;
5616 Context newcontext(true, context.textclass);
5617 if (newinsetlayout->forcePlainLayout())
5618 newcontext.layout = &context.textclass.plainLayout();
5619 output_ert(os, arg, newcontext);
5621 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5622 context.latexparam.clear();
5625 // Minted caption insets are not closed here because
5626 // we collect everything into the caption.
5627 if (minted_float.empty())
5632 // The single '=' is meant here.
5633 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5637 context.check_layout(os);
5638 docstring name = newinsetlayout->name();
5639 bool const caption = name.find(from_ascii("Caption:")) == 0;
5641 // Already done for floating minted listings.
5642 if (minted_float.empty()) {
5643 begin_inset(os, "Caption ");
5644 os << to_utf8(name.substr(8)) << '\n';
5647 // FIXME: what do we do if the prefix is not Flex: ?
5648 if (prefixIs(name, from_ascii("Flex:")))
5650 begin_inset(os, "Flex ");
5651 os << to_utf8(name) << '\n'
5652 << "status collapsed\n";
5654 if (!minted_float.empty()) {
5655 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5656 } else if (newinsetlayout->isPassThru()) {
5657 // set catcodes to verbatim early, just in case.
5658 p.setCatcodes(VERBATIM_CATCODES);
5659 string delim = p.get_token().asInput();
5661 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5662 //FIXME: handle error condition
5663 string const arg = p.verbatimStuff("}").second;
5664 Context newcontext(true, context.textclass);
5665 if (newinsetlayout->forcePlainLayout())
5666 newcontext.layout = &context.textclass.plainLayout();
5667 output_ert(os, arg, newcontext);
5669 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5672 // Minted caption insets are not closed here because
5673 // we collect everything into the caption.
5674 if (minted_float.empty())
5679 if (t.cs() == "includepdf") {
5681 string const arg = p.getArg('[', ']');
5682 map<string, string> opts;
5683 vector<string> keys;
5684 split_map(arg, opts, keys);
5685 string name = normalize_filename(p.verbatim_item());
5686 string const path = getMasterFilePath(true);
5687 // We want to preserve relative / absolute filenames,
5688 // therefore path is only used for testing
5689 if (!makeAbsPath(name, path).exists()) {
5690 // The file extension is probably missing.
5691 // Now try to find it out.
5692 char const * const pdfpages_format[] = {"pdf", 0};
5693 string const pdftex_name =
5694 find_file(name, path, pdfpages_format);
5695 if (!pdftex_name.empty()) {
5700 FileName const absname = makeAbsPath(name, path);
5701 if (absname.exists())
5703 fix_child_filename(name);
5704 copy_file(absname, name);
5706 cerr << "Warning: Could not find file '"
5707 << name << "'." << endl;
5709 context.check_layout(os);
5710 begin_inset(os, "External\n\ttemplate ");
5711 os << "PDFPages\n\tfilename "
5713 // parse the options
5714 if (opts.find("pages") != opts.end())
5715 os << "\textra LaTeX \"pages="
5716 << opts["pages"] << "\"\n";
5717 if (opts.find("angle") != opts.end())
5718 os << "\trotateAngle "
5719 << opts["angle"] << '\n';
5720 if (opts.find("origin") != opts.end()) {
5722 string const opt = opts["origin"];
5723 if (opt == "tl") ss << "topleft";
5724 if (opt == "bl") ss << "bottomleft";
5725 if (opt == "Bl") ss << "baselineleft";
5726 if (opt == "c") ss << "center";
5727 if (opt == "tc") ss << "topcenter";
5728 if (opt == "bc") ss << "bottomcenter";
5729 if (opt == "Bc") ss << "baselinecenter";
5730 if (opt == "tr") ss << "topright";
5731 if (opt == "br") ss << "bottomright";
5732 if (opt == "Br") ss << "baselineright";
5733 if (!ss.str().empty())
5734 os << "\trotateOrigin " << ss.str() << '\n';
5736 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5738 if (opts.find("width") != opts.end())
5740 << translate_len(opts["width"]) << '\n';
5741 if (opts.find("height") != opts.end())
5743 << translate_len(opts["height"]) << '\n';
5744 if (opts.find("keepaspectratio") != opts.end())
5745 os << "\tkeepAspectRatio\n";
5747 context.check_layout(os);
5748 registerExternalTemplatePackages("PDFPages");
5752 if (t.cs() == "loadgame") {
5754 string name = normalize_filename(p.verbatim_item());
5755 string const path = getMasterFilePath(true);
5756 // We want to preserve relative / absolute filenames,
5757 // therefore path is only used for testing
5758 if (!makeAbsPath(name, path).exists()) {
5759 // The file extension is probably missing.
5760 // Now try to find it out.
5761 char const * const lyxskak_format[] = {"fen", 0};
5762 string const lyxskak_name =
5763 find_file(name, path, lyxskak_format);
5764 if (!lyxskak_name.empty())
5765 name = lyxskak_name;
5767 FileName const absname = makeAbsPath(name, path);
5768 if (absname.exists())
5770 fix_child_filename(name);
5771 copy_file(absname, name);
5773 cerr << "Warning: Could not find file '"
5774 << name << "'." << endl;
5775 context.check_layout(os);
5776 begin_inset(os, "External\n\ttemplate ");
5777 os << "ChessDiagram\n\tfilename "
5780 context.check_layout(os);
5781 // after a \loadgame follows a \showboard
5782 if (p.get_token().asInput() == "showboard")
5784 registerExternalTemplatePackages("ChessDiagram");
5788 // try to see whether the string is in unicodesymbols
5789 // Only use text mode commands, since we are in text mode here,
5790 // and math commands may be invalid (bug 6797)
5791 string name = t.asInput();
5792 // handle the dingbats, cyrillic and greek
5793 if (name == "\\textcyr")
5794 name = "\\textcyrillic";
5795 if (name == "\\ding" || name == "\\textcyrillic" ||
5796 (name == "\\textgreek" && !preamble.usePolyglossia()))
5797 name = name + '{' + p.getArg('{', '}') + '}';
5798 // handle the ifsym characters
5799 else if (name == "\\textifsymbol") {
5800 string const optif = p.getFullOpt();
5801 string const argif = p.getArg('{', '}');
5802 name = name + optif + '{' + argif + '}';
5804 // handle the \ascii characters
5805 // the case of \ascii within braces, as LyX outputs it, is already
5806 // handled for t.cat() == catBegin
5807 else if (name == "\\ascii") {
5808 // the code is "\asci\xxx"
5809 name = "{" + name + p.get_token().asInput() + "}";
5812 // handle some TIPA special characters
5813 else if (preamble.isPackageUsed("tipa")) {
5814 if (name == "\\s") {
5815 // fromLaTeXCommand() does not yet
5816 // recognize tipa short cuts
5817 name = "\\textsyllabic";
5818 } else if (name == "\\=" &&
5819 p.next_token().asInput() == "*") {
5820 // fromLaTeXCommand() does not yet
5821 // recognize tipa short cuts
5823 name = "\\textsubbar";
5824 } else if (name == "\\textdoublevertline") {
5825 // FIXME: This is not correct,
5826 // \textvertline is higher than \textbardbl
5827 name = "\\textbardbl";
5829 } else if (name == "\\!" ) {
5830 if (p.next_token().asInput() == "b") {
5831 p.get_token(); // eat 'b'
5834 } else if (p.next_token().asInput() == "d") {
5838 } else if (p.next_token().asInput() == "g") {
5842 } else if (p.next_token().asInput() == "G") {
5844 name = "\\texthtscg";
5846 } else if (p.next_token().asInput() == "j") {
5848 name = "\\texthtbardotlessj";
5850 } else if (p.next_token().asInput() == "o") {
5852 name = "\\textbullseye";
5855 } else if (name == "\\*" ) {
5856 if (p.next_token().asInput() == "k") {
5858 name = "\\textturnk";
5860 } else if (p.next_token().asInput() == "r") {
5861 p.get_token(); // eat 'b'
5862 name = "\\textturnr";
5864 } else if (p.next_token().asInput() == "t") {
5866 name = "\\textturnt";
5868 } else if (p.next_token().asInput() == "w") {
5870 name = "\\textturnw";
5875 if ((name.size() == 2 &&
5876 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5877 p.next_token().asInput() != "*") ||
5878 is_known(name.substr(1), known_tipa_marks)) {
5879 // name is a command that corresponds to a
5880 // combining character in unicodesymbols.
5881 // Append the argument, fromLaTeXCommand()
5882 // will either convert it to a single
5883 // character or a combining sequence.
5884 name += '{' + p.verbatim_item() + '}';
5886 // now get the character from unicodesymbols
5890 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5891 Encodings::TEXT_CMD, termination, rem, &req));
5893 context.check_layout(os);
5896 output_ert_inset(os, to_utf8(rem), context);
5898 skip_spaces_braces(p);
5899 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5900 preamble.registerAutomaticallyLoadedPackage(*it);
5902 //cerr << "#: " << t << " mode: " << mode << endl;
5903 // heuristic: read up to next non-nested space
5905 string s = t.asInput();
5906 string z = p.verbatim_item();
5907 while (p.good() && z != " " && !z.empty()) {
5908 //cerr << "read: " << z << endl;
5910 z = p.verbatim_item();
5912 cerr << "found ERT: " << s << endl;
5913 output_ert_inset(os, s + ' ', context);
5916 if (t.asInput() == name &&
5917 p.next_token().asInput() == "*") {
5918 // Starred commands like \vspace*{}
5919 p.get_token(); // Eat '*'
5922 if (!parse_command(name, p, os, outer, context))
5923 output_ert_inset(os, name, context);
5929 string guessLanguage(Parser & p, string const & lang)
5931 typedef std::map<std::string, size_t> LangMap;
5932 // map from language names to number of characters
5935 for (char const * const * i = supported_CJK_languages; *i; i++)
5936 used[string(*i)] = 0;
5939 Token const t = p.get_token();
5940 // comments are not counted for any language
5941 if (t.cat() == catComment)
5943 // commands are not counted as well, but we need to detect
5944 // \begin{CJK} and switch encoding if needed
5945 if (t.cat() == catEscape) {
5946 if (t.cs() == "inputencoding") {
5947 string const enc = subst(p.verbatim_item(), "\n", " ");
5948 p.setEncoding(enc, Encoding::inputenc);
5951 if (t.cs() != "begin")
5954 // Non-CJK content is counted for lang.
5955 // We do not care about the real language here:
5956 // If we have more non-CJK contents than CJK contents,
5957 // we simply use the language that was specified as
5958 // babel main language.
5959 used[lang] += t.asInput().length();
5962 // Now we are starting an environment
5964 string const name = p.getArg('{', '}');
5965 if (name != "CJK") {
5969 // It is a CJK environment
5971 /* name = */ p.getArg('{', '}');
5972 string const encoding = p.getArg('{', '}');
5973 /* mapping = */ p.getArg('{', '}');
5974 string const encoding_old = p.getEncoding();
5975 char const * const * const where =
5976 is_known(encoding, supported_CJK_encodings);
5978 p.setEncoding(encoding, Encoding::CJK);
5980 p.setEncoding("UTF-8");
5981 string const text = p.ertEnvironment("CJK");
5982 p.setEncoding(encoding_old);
5985 // ignore contents in unknown CJK encoding
5988 // the language of the text
5990 supported_CJK_languages[where - supported_CJK_encodings];
5991 used[cjk] += text.length();
5993 LangMap::const_iterator use = used.begin();
5994 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5995 if (it->second > use->second)
6002 void check_comment_bib(ostream & os, Context & context)
6004 if (!need_commentbib)
6006 // We have a bibliography database, but no bibliography with biblatex
6007 // which is completely valid. Insert a bibtex inset in a note.
6008 context.check_layout(os);
6009 begin_inset(os, "Note Note\n");
6010 os << "status open\n";
6011 os << "\\begin_layout Plain Layout\n";
6012 begin_command_inset(os, "bibtex", "bibtex");
6014 for (auto const & bf : preamble.biblatex_bibliographies) {
6015 if (!bibfiles.empty())
6017 bibfiles += normalize_filename(bf);
6019 if (!bibfiles.empty())
6020 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6021 end_inset(os);// Bibtex
6022 os << "\\end_layout\n";
6023 end_inset(os);// Note