2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, string, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
68 output_arguments(os, p, outer, false, string(), newcontext,
70 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space", ",",
320 "thinspace", "quad", "qquad", "enspace", "enskip",
321 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
322 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
323 "upbracefill", "downbracefill", 0};
325 /// the same as known_spaces with .lyx names
326 char const * const known_coded_spaces[] = { "space{}", "space{}",
327 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
328 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
329 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
330 "upbracefill{}", "downbracefill{}", 0};
332 /// known TIPA combining diacritical marks
333 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
334 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
335 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
336 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
337 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
338 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
339 "textsubring", "textsubbar", 0};
341 /// TIPA tones that need special handling
342 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
344 // string to store the float type to be able to determine the type of subfloats
345 string float_type = "";
347 // string to store the float status of minted listings
348 string minted_float = "";
350 // whether a caption has been parsed for a floating minted listing
351 bool minted_float_has_caption = false;
353 // The caption for non-floating minted listings
354 string minted_nonfloat_caption = "";
356 // Characters that have to be escaped by \\ in LaTeX
357 char const * const known_escaped_chars[] = {
358 "&", "_", "$", "%", "#", "^", "{", "}", 0};
361 /// splits "x=z, y=b" into a map and an ordered keyword vector
362 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
367 keys.resize(v.size());
368 for (size_t i = 0; i < v.size(); ++i) {
369 size_t const pos = v[i].find('=');
370 string const index = trimSpaceAndEol(v[i].substr(0, pos));
371 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
379 * Split a LaTeX length into value and unit.
380 * The latter can be a real unit like "pt", or a latex length variable
381 * like "\textwidth". The unit may contain additional stuff like glue
382 * lengths, but we don't care, because such lengths are ERT anyway.
383 * \returns true if \p value and \p unit are valid.
385 bool splitLatexLength(string const & len, string & value, string & unit)
389 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
390 //'4,5' is a valid LaTeX length number. Change it to '4.5'
391 string const length = subst(len, ',', '.');
392 if (i == string::npos)
395 if (len[0] == '\\') {
396 // We had something like \textwidth without a factor
402 value = trimSpaceAndEol(string(length, 0, i));
406 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
407 if (contains(len, '\\'))
408 unit = trimSpaceAndEol(string(len, i));
410 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
415 /// A simple function to translate a latex length to something LyX can
416 /// understand. Not perfect, but rather best-effort.
417 bool translate_len(string const & length, string & valstring, string & unit)
419 if (!splitLatexLength(length, valstring, unit))
421 // LyX uses percent values
423 istringstream iss(valstring);
428 string const percentval = oss.str();
430 if (unit.empty() || unit[0] != '\\')
432 string::size_type const i = unit.find(' ');
433 string const endlen = (i == string::npos) ? string() : string(unit, i);
434 if (unit == "\\textwidth") {
435 valstring = percentval;
436 unit = "text%" + endlen;
437 } else if (unit == "\\columnwidth") {
438 valstring = percentval;
439 unit = "col%" + endlen;
440 } else if (unit == "\\paperwidth") {
441 valstring = percentval;
442 unit = "page%" + endlen;
443 } else if (unit == "\\linewidth") {
444 valstring = percentval;
445 unit = "line%" + endlen;
446 } else if (unit == "\\paperheight") {
447 valstring = percentval;
448 unit = "pheight%" + endlen;
449 } else if (unit == "\\textheight") {
450 valstring = percentval;
451 unit = "theight%" + endlen;
452 } else if (unit == "\\baselineskip") {
453 valstring = percentval;
454 unit = "baselineskip%" + endlen;
460 /// If we have ambiguous quotation marks, make a smart guess
461 /// based on main quote style
462 string guessQuoteStyle(string in, bool const opening)
465 if (prefixIs(in, "qr")) {// straight quote
467 res = subst(res, "r", "l");
468 } else if (in == "eld") {// ``
469 if (preamble.quotesStyle() == "german")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "russian")
477 } else if (in == "erd") {// ''
478 if (preamble.quotesStyle() == "polish")
480 else if (preamble.quotesStyle() == "british")
482 else if (preamble.quotesStyle() == "french")
484 else if (preamble.quotesStyle() == "swedish")
485 res = opening ? "sld" : "srd";
486 } else if (in == "els") {// `
487 if (preamble.quotesStyle() == "german")
489 else if (preamble.quotesStyle() == "british")
491 } else if (in == "ers") {// '
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sls" : "srs";
498 } else if (in == "ard") {// >>
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ald") {// <<
506 if (preamble.quotesStyle() == "swiss")
508 else if (preamble.quotesStyle() == "french")
510 else if (preamble.quotesStyle() == "russian")
512 } else if (in == "ars") {// >
513 if (preamble.quotesStyle() == "swiss")
515 } else if (in == "als") {// <
516 if (preamble.quotesStyle() == "swiss")
518 } else if (in == "gld") {// ,,
519 if (preamble.quotesStyle() == "polish")
521 else if (preamble.quotesStyle() == "russian")
523 } else if (in == "gls") {// ,
524 if (preamble.quotesStyle() == "polish")
531 string const fromPolyglossiaEnvironment(string const s)
533 // Since \arabic is taken by the LaTeX kernel,
534 // the Arabic polyglossia environment is upcased
545 string translate_len(string const & length)
549 if (translate_len(length, value, unit))
551 // If the input is invalid, return what we have.
559 * Translates a LaTeX length into \p value, \p unit and
560 * \p special parts suitable for a box inset.
561 * The difference from translate_len() is that a box inset knows about
562 * some special "units" that are stored in \p special.
564 void translate_box_len(string const & length, string & value, string & unit, string & special)
566 if (translate_len(length, value, unit)) {
567 if (unit == "\\height" || unit == "\\depth" ||
568 unit == "\\totalheight" || unit == "\\width") {
569 special = unit.substr(1);
570 // The unit is not used, but LyX requires a dummy setting
582 void begin_inset(ostream & os, string const & name)
584 os << "\n\\begin_inset " << name;
588 void begin_command_inset(ostream & os, string const & name,
589 string const & latexname)
591 begin_inset(os, "CommandInset ");
592 os << name << "\nLatexCommand " << latexname << '\n';
596 void end_inset(ostream & os)
598 os << "\n\\end_inset\n\n";
602 bool skip_braces(Parser & p)
604 if (p.next_token().cat() != catBegin)
607 if (p.next_token().cat() == catEnd) {
616 /// replace LaTeX commands in \p s from the unicodesymbols file with their
618 pair<bool, docstring> convert_unicodesymbols(docstring s)
622 for (size_t i = 0; i < s.size();) {
631 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
632 Encodings::TEXT_CMD, termination, rem, &req));
633 set<string>::const_iterator it = req.begin();
634 set<string>::const_iterator en = req.end();
635 for (; it != en; ++it)
636 preamble.registerAutomaticallyLoadedPackage(*it);
639 if (s.empty() || s[0] != '\\')
643 for (auto const & c : known_escaped_chars)
644 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
649 return make_pair(res, os.str());
653 /// try to convert \p s to a valid InsetCommand argument
654 /// return whether this succeeded. If not, these command insets
655 /// get the "literate" flag.
656 pair<bool, string> convert_latexed_command_inset_arg(string s)
658 bool success = false;
660 // since we don't know the input encoding we can't use from_utf8
661 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
663 s = to_utf8(res.second);
665 // LyX cannot handle newlines in a latex command
666 return make_pair(success, subst(s, "\n", " "));
669 /// try to convert \p s to a valid InsetCommand argument
670 /// without trying to recode macros.
671 string convert_literate_command_inset_arg(string s)
673 // LyX cannot handle newlines in a latex command
674 return subst(s, "\n", " ");
677 void output_ert(ostream & os, string const & s, Context & context)
679 context.check_layout(os);
680 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
682 os << "\n\\backslash\n";
683 else if (*it == '\n') {
684 context.new_paragraph(os);
685 context.check_layout(os);
689 context.check_end_layout(os);
693 void output_ert_inset(ostream & os, string const & s, Context & context)
695 // We must have a valid layout before outputting the ERT inset.
696 context.check_layout(os);
697 Context newcontext(true, context.textclass);
698 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
699 if (layout.forcePlainLayout())
700 newcontext.layout = &context.textclass.plainLayout();
701 begin_inset(os, "ERT");
702 os << "\nstatus collapsed\n";
703 output_ert(os, s, newcontext);
708 void output_comment(Parser & p, ostream & os, string const & s,
711 if (p.next_token().cat() == catNewline)
712 output_ert_inset(os, '%' + s, context);
714 output_ert_inset(os, '%' + s + '\n', context);
718 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
719 string const & latexparam = string())
721 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
724 if (checkModule(name, command))
725 return findLayoutWithoutModule(textclass, name, command, latexparam);
730 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
731 string const & latexparam = string())
733 InsetLayout const * insetlayout =
734 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
737 if (checkModule(name, command))
738 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
743 void eat_whitespace(Parser &, ostream &, Context &, bool);
747 * Skips whitespace and braces.
748 * This should be called after a command has been parsed that is not put into
749 * ERT, and where LyX adds "{}" if needed.
751 void skip_spaces_braces(Parser & p, bool keepws = false)
753 /* The following four examples produce the same typeset output and
754 should be handled by this function:
762 // Unfortunately we need to skip comments, too.
763 // We can't use eat_whitespace since writing them after the {}
764 // results in different output in some cases.
765 bool const skipped_spaces = p.skip_spaces(true);
766 bool const skipped_braces = skip_braces(p);
767 if (keepws && skipped_spaces && !skipped_braces)
768 // put back the space (it is better handled by check_space)
769 p.unskip_spaces(true);
773 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
774 Context & context, Layout::LaTeXArgMap const & latexargs)
776 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
778 context.check_layout(os);
784 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
785 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
786 for (; lait != laend; ++lait) {
788 eat_whitespace(p, os, context, false);
789 if (lait->second.mandatory) {
790 if (p.next_token().cat() != catBegin)
792 string ldelim = to_utf8(lait->second.ldelim);
793 string rdelim = to_utf8(lait->second.rdelim);
798 p.get_token(); // eat ldelim
799 if (ldelim.size() > 1)
800 p.get_token(); // eat ldelim
802 context.check_layout(os);
805 begin_inset(os, "Argument ");
808 os << i << "\nstatus collapsed\n\n";
809 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
812 string ldelim = to_utf8(lait->second.ldelim);
813 string rdelim = to_utf8(lait->second.rdelim);
818 string tok = p.next_token().asInput();
819 // we only support delimiters with max 2 chars for now.
820 if (ldelim.size() > 1)
821 tok += p.next_next_token().asInput();
822 if (p.next_token().cat() == catEscape || tok != ldelim)
824 p.get_token(); // eat ldelim
825 if (ldelim.size() > 1)
826 p.get_token(); // eat ldelim
828 context.check_layout(os);
831 begin_inset(os, "Argument ");
834 os << i << "\nstatus collapsed\n\n";
835 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
838 eat_whitespace(p, os, context, false);
843 void output_command_layout(ostream & os, Parser & p, bool outer,
844 Context & parent_context,
845 Layout const * newlayout)
847 TeXFont const oldFont = parent_context.font;
848 // save the current font size
849 string const size = oldFont.size;
850 // reset the font size to default, because the font size switches
851 // don't affect section headings and the like
852 parent_context.font.size = Context::normalfont.size;
853 // we only need to write the font change if we have an open layout
854 if (!parent_context.atParagraphStart())
855 output_font_change(os, oldFont, parent_context.font);
856 parent_context.check_end_layout(os);
857 Context context(true, parent_context.textclass, newlayout,
858 parent_context.layout, parent_context.font);
859 if (parent_context.deeper_paragraph) {
860 // We are beginning a nested environment after a
861 // deeper paragraph inside the outer list environment.
862 // Therefore we don't need to output a "begin deeper".
863 context.need_end_deeper = true;
865 context.check_deeper(os);
866 output_arguments(os, p, outer, true, string(), context,
867 context.layout->latexargs());
868 // If we have a latex param, we eat it here.
869 if (!parent_context.latexparam.empty()) {
871 Context dummy(true, parent_context.textclass);
872 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
873 string(1, parent_context.latexparam.back()));
875 parse_text(p, os, FLAG_ITEM, outer, context);
876 output_arguments(os, p, outer, false, "post", context,
877 context.layout->postcommandargs());
878 context.check_end_layout(os);
879 if (parent_context.deeper_paragraph) {
880 // We must suppress the "end deeper" because we
881 // suppressed the "begin deeper" above.
882 context.need_end_deeper = false;
884 context.check_end_deeper(os);
885 // We don't need really a new paragraph, but
886 // we must make sure that the next item gets a \begin_layout.
887 parent_context.new_paragraph(os);
888 // Set the font size to the original value. No need to output it here
889 // (Context::begin_layout() will do that if needed)
890 parent_context.font.size = size;
895 * Output a space if necessary.
896 * This function gets called for every whitespace token.
898 * We have three cases here:
899 * 1. A space must be suppressed. Example: The lyxcode case below
900 * 2. A space may be suppressed. Example: Spaces before "\par"
901 * 3. A space must not be suppressed. Example: A space between two words
903 * We currently handle only 1. and 3 and from 2. only the case of
904 * spaces before newlines as a side effect.
906 * 2. could be used to suppress as many spaces as possible. This has two effects:
907 * - Reimporting LyX generated LaTeX files changes almost no whitespace
908 * - Superflous whitespace from non LyX generated LaTeX files is removed.
909 * The drawback is that the logic inside the function becomes
910 * complicated, and that is the reason why it is not implemented.
912 void check_space(Parser & p, ostream & os, Context & context)
914 Token const next = p.next_token();
915 Token const curr = p.curr_token();
916 // A space before a single newline and vice versa must be ignored
917 // LyX emits a newline before \end{lyxcode}.
918 // This newline must be ignored,
919 // otherwise LyX will add an additional protected space.
920 if (next.cat() == catSpace ||
921 next.cat() == catNewline ||
922 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
925 context.check_layout(os);
931 * Parse all arguments of \p command
933 void parse_arguments(string const & command,
934 vector<ArgumentType> const & template_arguments,
935 Parser & p, ostream & os, bool outer, Context & context)
937 string ert = command;
938 size_t no_arguments = template_arguments.size();
939 for (size_t i = 0; i < no_arguments; ++i) {
940 switch (template_arguments[i]) {
943 // This argument contains regular LaTeX
944 output_ert_inset(os, ert + '{', context);
945 eat_whitespace(p, os, context, false);
946 if (template_arguments[i] == required)
947 parse_text(p, os, FLAG_ITEM, outer, context);
949 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
953 // This argument consists only of a single item.
954 // The presence of '{' or not must be preserved.
956 if (p.next_token().cat() == catBegin)
957 ert += '{' + p.verbatim_item() + '}';
959 ert += p.verbatim_item();
963 // This argument may contain special characters
964 ert += '{' + p.verbatim_item() + '}';
968 // true because we must not eat whitespace
969 // if an optional arg follows we must not strip the
970 // brackets from this one
971 if (i < no_arguments - 1 &&
972 template_arguments[i+1] == optional)
973 ert += p.getFullOpt(true);
975 ert += p.getOpt(true);
979 output_ert_inset(os, ert, context);
984 * Check whether \p command is a known command. If yes,
985 * handle the command with all arguments.
986 * \return true if the command was parsed, false otherwise.
988 bool parse_command(string const & command, Parser & p, ostream & os,
989 bool outer, Context & context)
991 if (known_commands.find(command) != known_commands.end()) {
992 parse_arguments(command, known_commands[command], p, os,
1000 /// Parses a minipage or parbox
1001 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1002 unsigned inner_flags, bool outer, Context & parent_context,
1003 string const & outer_type, string const & special,
1004 string inner_type, string const & frame_color,
1005 string const & background_color)
1009 string hor_pos = "l";
1010 // We need to set the height to the LaTeX default of 1\\totalheight
1011 // for the case when no height argument is given
1012 string height_value = "1";
1013 string height_unit = "in";
1014 string height_special = "totalheight";
1015 string latex_height;
1019 string width_special = "none";
1020 string thickness = "0.4pt";
1021 if (!fboxrule.empty())
1022 thickness = fboxrule;
1024 thickness = "0.4pt";
1026 if (!fboxsep.empty())
1027 separation = fboxsep;
1031 if (!shadow_size.empty())
1032 shadowsize = shadow_size;
1035 string framecolor = "black";
1036 string backgroundcolor = "none";
1037 if (!frame_color.empty())
1038 framecolor = frame_color;
1039 if (!background_color.empty())
1040 backgroundcolor = background_color;
1041 // if there is a color box around the \begin statements have not yet been parsed
1043 if (!frame_color.empty() || !background_color.empty()) {
1044 eat_whitespace(p, os, parent_context, false);
1045 p.get_token().asInput(); // the '{'
1047 if (p.next_token().asInput() == "\\begin") {
1048 p.get_token().asInput();
1050 inner_type = "minipage";
1051 inner_flags = FLAG_END;
1052 active_environments.push_back("minipage");
1055 else if (p.next_token().asInput() == "\\parbox") {
1056 p.get_token().asInput();
1057 inner_type = "parbox";
1058 inner_flags = FLAG_ITEM;
1061 else if (p.next_token().asInput() == "\\makebox") {
1062 p.get_token().asInput();
1063 inner_type = "makebox";
1064 inner_flags = FLAG_ITEM;
1066 // in case there is just \colorbox{color}{text}
1069 inner_type = "makebox";
1070 inner_flags = FLAG_BRACE_LAST;
1075 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1077 if (!inner_type.empty() && p.hasOpt()) {
1078 if (inner_type != "makebox")
1079 position = p.getArg('[', ']');
1081 latex_width = p.getArg('[', ']');
1082 translate_box_len(latex_width, width_value, width_unit, width_special);
1085 if (position != "t" && position != "c" && position != "b") {
1086 cerr << "invalid position " << position << " for "
1087 << inner_type << endl;
1091 if (inner_type != "makebox") {
1092 latex_height = p.getArg('[', ']');
1093 translate_box_len(latex_height, height_value, height_unit, height_special);
1095 string const opt = p.getArg('[', ']');
1098 if (hor_pos != "l" && hor_pos != "c" &&
1099 hor_pos != "r" && hor_pos != "s") {
1100 cerr << "invalid hor_pos " << hor_pos
1101 << " for " << inner_type << endl;
1108 inner_pos = p.getArg('[', ']');
1109 if (inner_pos != "c" && inner_pos != "t" &&
1110 inner_pos != "b" && inner_pos != "s") {
1111 cerr << "invalid inner_pos "
1112 << inner_pos << " for "
1113 << inner_type << endl;
1114 inner_pos = position;
1118 if (inner_type == "makebox")
1122 if (inner_type.empty()) {
1123 if (special.empty() && outer_type != "framebox")
1124 latex_width = "1\\columnwidth";
1127 latex_width = p2.getArg('[', ']');
1128 string const opt = p2.getArg('[', ']');
1131 if (hor_pos != "l" && hor_pos != "c" &&
1132 hor_pos != "r" && hor_pos != "s") {
1133 cerr << "invalid hor_pos " << hor_pos
1134 << " for " << outer_type << endl;
1138 if (outer_type == "framebox")
1142 } else if (inner_type != "makebox")
1143 latex_width = p.verbatim_item();
1144 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1145 // as this is LyX's standard for such cases (except for makebox)
1146 // \framebox is more special and handled below
1147 if (latex_width.empty() && inner_type != "makebox"
1148 && outer_type != "framebox")
1149 latex_width = "1\\columnwidth";
1151 translate_len(latex_width, width_value, width_unit);
1153 bool shadedparbox = false;
1154 if (inner_type == "shaded") {
1155 eat_whitespace(p, os, parent_context, false);
1156 if (outer_type == "parbox") {
1158 if (p.next_token().cat() == catBegin)
1160 eat_whitespace(p, os, parent_context, false);
1161 shadedparbox = true;
1166 // If we already read the inner box we have to push the inner env
1167 if (!outer_type.empty() && !inner_type.empty() &&
1168 (inner_flags & FLAG_END))
1169 active_environments.push_back(inner_type);
1170 bool use_ert = false;
1171 if (!outer_type.empty() && !inner_type.empty()) {
1172 // Look whether there is some content after the end of the
1173 // inner box, but before the end of the outer box.
1174 // If yes, we need to output ERT.
1176 if (inner_flags & FLAG_END)
1177 p.ertEnvironment(inner_type);
1180 p.skip_spaces(true);
1181 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1182 if ((outer_env && p.next_token().asInput() != "\\end") ||
1183 (!outer_env && p.next_token().cat() != catEnd)) {
1184 // something is between the end of the inner box and
1185 // the end of the outer box, so we need to use ERT.
1193 if (!outer_type.empty()) {
1194 if (outer_flags & FLAG_END)
1195 ss << "\\begin{" << outer_type << '}';
1197 ss << '\\' << outer_type << '{';
1198 if (!special.empty())
1202 if (!inner_type.empty()) {
1203 if (inner_type != "shaded") {
1204 if (inner_flags & FLAG_END)
1205 ss << "\\begin{" << inner_type << '}';
1207 ss << '\\' << inner_type;
1209 if (!position.empty())
1210 ss << '[' << position << ']';
1211 if (!latex_height.empty())
1212 ss << '[' << latex_height << ']';
1213 if (!inner_pos.empty())
1214 ss << '[' << inner_pos << ']';
1215 ss << '{' << latex_width << '}';
1216 if (!(inner_flags & FLAG_END))
1219 if (inner_type == "shaded")
1220 ss << "\\begin{shaded}";
1221 output_ert_inset(os, ss.str(), parent_context);
1222 if (!inner_type.empty()) {
1223 parse_text(p, os, inner_flags, outer, parent_context);
1224 if (inner_flags & FLAG_END)
1225 output_ert_inset(os, "\\end{" + inner_type + '}',
1228 output_ert_inset(os, "}", parent_context);
1230 if (!outer_type.empty()) {
1231 // If we already read the inner box we have to pop
1233 if (!inner_type.empty() && (inner_flags & FLAG_END))
1234 active_environments.pop_back();
1236 // Ensure that the end of the outer box is parsed correctly:
1237 // The opening brace has been eaten by parse_outer_box()
1238 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1239 outer_flags &= ~FLAG_ITEM;
1240 outer_flags |= FLAG_BRACE_LAST;
1242 parse_text(p, os, outer_flags, outer, parent_context);
1243 if (outer_flags & FLAG_END)
1244 output_ert_inset(os, "\\end{" + outer_type + '}',
1247 output_ert_inset(os, "}", parent_context);
1250 // LyX does not like empty positions, so we have
1251 // to set them to the LaTeX default values here.
1252 if (position.empty())
1254 if (inner_pos.empty())
1255 inner_pos = position;
1256 parent_context.check_layout(os);
1257 begin_inset(os, "Box ");
1258 if (outer_type == "framed")
1260 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1262 else if (outer_type == "shadowbox")
1263 os << "Shadowbox\n";
1264 else if ((outer_type == "shaded" && inner_type.empty()) ||
1265 (outer_type == "minipage" && inner_type == "shaded") ||
1266 (outer_type == "parbox" && inner_type == "shaded")) {
1268 preamble.registerAutomaticallyLoadedPackage("color");
1269 } else if (outer_type == "doublebox")
1270 os << "Doublebox\n";
1271 else if (outer_type.empty() || outer_type == "mbox")
1272 os << "Frameless\n";
1274 os << outer_type << '\n';
1275 os << "position \"" << position << "\"\n";
1276 os << "hor_pos \"" << hor_pos << "\"\n";
1277 if (outer_type == "mbox")
1278 os << "has_inner_box 1\n";
1279 else if (!frame_color.empty() && inner_type == "makebox")
1280 os << "has_inner_box 0\n";
1282 os << "has_inner_box " << !inner_type.empty() << "\n";
1283 os << "inner_pos \"" << inner_pos << "\"\n";
1284 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1286 if (outer_type == "mbox")
1287 os << "use_makebox 1\n";
1288 else if (!frame_color.empty())
1289 os << "use_makebox 0\n";
1291 os << "use_makebox " << (inner_type == "makebox") << '\n';
1292 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1293 os << "width \"\"\n";
1294 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1295 else if (contains(width_unit, '\\'))
1296 os << "width \"" << width_value << "in" << "\"\n";
1298 os << "width \"" << width_value << width_unit << "\"\n";
1299 if (contains(width_unit, '\\')) {
1300 width_unit.erase (0,1); // remove the leading '\'
1301 os << "special \"" << width_unit << "\"\n";
1303 os << "special \"" << width_special << "\"\n";
1304 if (contains(height_unit, '\\'))
1305 os << "height \"" << height_value << "in" << "\"\n";
1307 os << "height \"" << height_value << height_unit << "\"\n";
1308 os << "height_special \"" << height_special << "\"\n";
1309 os << "thickness \"" << thickness << "\"\n";
1310 os << "separation \"" << separation << "\"\n";
1311 os << "shadowsize \"" << shadowsize << "\"\n";
1312 os << "framecolor \"" << framecolor << "\"\n";
1313 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1314 os << "status open\n\n";
1316 // Unfortunately we can't use parse_text_in_inset:
1317 // InsetBox::forcePlainLayout() is hard coded and does not
1318 // use the inset layout. Apart from that do we call parse_text
1319 // up to two times, but need only one check_end_layout.
1320 bool const forcePlainLayout =
1321 (!inner_type.empty() || inner_type == "makebox") &&
1322 outer_type != "shaded" && outer_type != "framed";
1323 Context context(true, parent_context.textclass);
1324 if (forcePlainLayout)
1325 context.layout = &context.textclass.plainLayout();
1327 context.font = parent_context.font;
1329 // If we have no inner box the contents will be read with the outer box
1330 if (!inner_type.empty())
1331 parse_text(p, os, inner_flags, outer, context);
1333 // Ensure that the end of the outer box is parsed correctly:
1334 // The opening brace has been eaten by parse_outer_box()
1335 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1336 outer_flags &= ~FLAG_ITEM;
1337 outer_flags |= FLAG_BRACE_LAST;
1340 // Find end of outer box, output contents if inner_type is
1341 // empty and output possible comments
1342 if (!outer_type.empty()) {
1343 // If we already read the inner box we have to pop
1345 if (!inner_type.empty() && (inner_flags & FLAG_END))
1346 active_environments.pop_back();
1347 // This does not output anything but comments if
1348 // inner_type is not empty (see use_ert)
1349 parse_text(p, os, outer_flags, outer, context);
1352 context.check_end_layout(os);
1354 #ifdef PRESERVE_LAYOUT
1355 // LyX puts a % after the end of the minipage
1356 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1358 //output_comment(p, os, "dummy", parent_context);
1361 parent_context.new_paragraph(os);
1363 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1364 //output_comment(p, os, "dummy", parent_context);
1367 // We add a protected space if something real follows
1368 if (p.good() && p.next_token().cat() != catComment) {
1369 begin_inset(os, "space ~\n");
1375 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1376 active_environments.pop_back();
1377 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1378 // in this case we have to eat the the closing brace of the color box
1379 p.get_token().asInput(); // the '}'
1381 if (p.next_token().asInput() == "}") {
1382 // in this case we assume that the closing brace is from the box settings
1383 // therefore reset these values for the next box
1389 // all boxes except of Frameless and Shaded require calc
1390 if (!(outer_type.empty() || outer_type == "mbox") &&
1391 !((outer_type == "shaded" && inner_type.empty()) ||
1392 (outer_type == "minipage" && inner_type == "shaded") ||
1393 (outer_type == "parbox" && inner_type == "shaded")))
1394 preamble.registerAutomaticallyLoadedPackage("calc");
1398 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1399 Context & parent_context, string const & outer_type,
1400 string const & special)
1402 eat_whitespace(p, os, parent_context, false);
1403 if (flags & FLAG_ITEM) {
1405 if (p.next_token().cat() == catBegin)
1408 cerr << "Warning: Ignoring missing '{' after \\"
1409 << outer_type << '.' << endl;
1410 eat_whitespace(p, os, parent_context, false);
1413 unsigned int inner_flags = 0;
1415 if (outer_type == "minipage" || outer_type == "parbox") {
1416 p.skip_spaces(true);
1417 while (p.hasOpt()) {
1419 p.skip_spaces(true);
1422 p.skip_spaces(true);
1423 if (outer_type == "parbox") {
1425 if (p.next_token().cat() == catBegin)
1427 p.skip_spaces(true);
1430 if (outer_type == "shaded" || outer_type == "mbox") {
1431 // These boxes never have an inner box
1433 } else if (p.next_token().asInput() == "\\parbox") {
1434 inner = p.get_token().cs();
1435 inner_flags = FLAG_ITEM;
1436 } else if (p.next_token().asInput() == "\\begin") {
1437 // Is this a minipage or shaded box?
1440 inner = p.getArg('{', '}');
1442 if (inner == "minipage" || inner == "shaded")
1443 inner_flags = FLAG_END;
1448 if (inner_flags == FLAG_END) {
1449 if (inner != "shaded")
1453 eat_whitespace(p, os, parent_context, false);
1455 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1456 outer_type, special, inner, "", "");
1458 if (inner_flags == FLAG_ITEM) {
1460 eat_whitespace(p, os, parent_context, false);
1462 parse_box(p, os, flags, inner_flags, outer, parent_context,
1463 outer_type, special, inner, "", "");
1468 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1469 bool in_line, bool use_minted)
1471 parent_context.check_layout(os);
1472 begin_inset(os, "listings\n");
1473 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1475 while ((i = arg.find(", ")) != string::npos
1476 || (i = arg.find(",\t")) != string::npos)
1477 arg.erase(i + 1, 1);
1480 string const language = p.getArg('{', '}');
1481 p.skip_spaces(true);
1482 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1483 if (!minted_float.empty()) {
1484 arg += string(arg.empty() ? "" : ",") + minted_float;
1485 minted_nonfloat_caption.clear();
1489 os << "lstparams " << '"' << arg << '"' << '\n';
1490 if (arg.find("\\color") != string::npos)
1491 preamble.registerAutomaticallyLoadedPackage("color");
1494 os << "inline true\n";
1496 os << "inline false\n";
1497 os << "status open\n";
1498 Context context(true, parent_context.textclass);
1499 context.layout = &parent_context.textclass.plainLayout();
1500 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1501 minted_nonfloat_caption.erase(0,3);
1502 os << "\n\\begin_layout Plain Layout\n";
1503 begin_inset(os, "Caption Standard\n");
1504 Context newcontext(true, context.textclass,
1505 context.layout, 0, context.font);
1506 newcontext.check_layout(os);
1507 os << minted_nonfloat_caption << "\n";
1508 newcontext.check_end_layout(os);
1510 os << "\n\\end_layout\n";
1511 minted_nonfloat_caption.clear();
1515 // set catcodes to verbatim early, just in case.
1516 p.setCatcodes(VERBATIM_CATCODES);
1517 string delim = p.get_token().asInput();
1518 //FIXME: handler error condition
1519 s = p.verbatimStuff(delim).second;
1520 // context.new_paragraph(os);
1521 } else if (use_minted) {
1522 s = p.verbatimEnvironment("minted");
1524 s = p.verbatimEnvironment("lstlisting");
1526 output_ert(os, s, context);
1527 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1528 minted_nonfloat_caption.erase(0,3);
1529 os << "\n\\begin_layout Plain Layout\n";
1530 begin_inset(os, "Caption Standard\n");
1531 Context newcontext(true, context.textclass,
1532 context.layout, 0, context.font);
1533 newcontext.check_layout(os);
1534 os << minted_nonfloat_caption << "\n";
1535 newcontext.check_end_layout(os);
1537 os << "\n\\end_layout\n";
1538 minted_nonfloat_caption.clear();
1540 // Don't close the inset here for floating minted listings.
1541 // It will be closed at the end of the listing environment.
1542 if (!use_minted || minted_float.empty())
1545 eat_whitespace(p, os, parent_context, true);
1546 Token t = p.get_token();
1547 if (t.asInput() != "\\end") {
1548 // If anything follows, collect it into a caption.
1549 minted_float_has_caption = true;
1550 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1551 begin_inset(os, "Caption Standard\n");
1552 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1559 /// parse an unknown environment
1560 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1561 unsigned flags, bool outer,
1562 Context & parent_context)
1564 if (name == "tabbing")
1565 // We need to remember that we have to handle '\=' specially
1566 flags |= FLAG_TABBING;
1568 // We need to translate font changes and paragraphs inside the
1569 // environment to ERT if we have a non standard font.
1570 // Otherwise things like
1571 // \large\begin{foo}\huge bar\end{foo}
1573 bool const specialfont =
1574 (parent_context.font != parent_context.normalfont);
1575 bool const new_layout_allowed = parent_context.new_layout_allowed;
1577 parent_context.new_layout_allowed = false;
1578 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1579 // Try to handle options: Look if we have an optional arguments,
1580 // and if so, put the brackets in ERT.
1581 while (p.hasOpt()) {
1582 p.get_token(); // eat '['
1583 output_ert_inset(os, "[", parent_context);
1584 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1585 output_ert_inset(os, "]", parent_context);
1587 parse_text_snippet(p, os, flags, outer, parent_context);
1588 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1590 parent_context.new_layout_allowed = new_layout_allowed;
1594 void parse_environment(Parser & p, ostream & os, bool outer,
1595 string & last_env, Context & parent_context)
1597 Layout const * newlayout;
1598 InsetLayout const * newinsetlayout = 0;
1599 string const name = p.getArg('{', '}');
1600 const bool is_starred = suffixIs(name, '*');
1601 string const unstarred_name = rtrim(name, "*");
1602 active_environments.push_back(name);
1604 if (is_math_env(name)) {
1605 parent_context.check_layout(os);
1606 begin_inset(os, "Formula ");
1607 os << "\\begin{" << name << "}";
1608 parse_math(p, os, FLAG_END, MATH_MODE);
1609 os << "\\end{" << name << "}";
1611 if (is_display_math_env(name)) {
1612 // Prevent the conversion of a line break to a space
1613 // (bug 7668). This does not change the output, but
1614 // looks ugly in LyX.
1615 eat_whitespace(p, os, parent_context, false);
1619 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1620 else if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1621 // We must begin a new paragraph if not already done
1622 if (! parent_context.atParagraphStart()) {
1623 parent_context.check_end_layout(os);
1624 parent_context.new_paragraph(os);
1626 // save the language in the context so that it is
1627 // handled by parse_text
1628 parent_context.font.language =
1629 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1630 parse_text(p, os, FLAG_END, outer, parent_context);
1631 // Just in case the environment is empty
1632 parent_context.extra_stuff.erase();
1633 // We must begin a new paragraph to reset the language
1634 parent_context.new_paragraph(os);
1638 else if (unstarred_name == "tabular" || name == "longtable") {
1639 eat_whitespace(p, os, parent_context, false);
1640 string width = "0pt";
1641 if (name == "tabular*") {
1642 width = lyx::translate_len(p.getArg('{', '}'));
1643 eat_whitespace(p, os, parent_context, false);
1645 parent_context.check_layout(os);
1646 begin_inset(os, "Tabular ");
1647 handle_tabular(p, os, name, width, parent_context);
1652 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1653 eat_whitespace(p, os, parent_context, false);
1654 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1655 eat_whitespace(p, os, parent_context, false);
1656 parent_context.check_layout(os);
1657 begin_inset(os, "Float " + unstarred_name + "\n");
1658 // store the float type for subfloats
1659 // subfloats only work with figures and tables
1660 if (unstarred_name == "figure")
1661 float_type = unstarred_name;
1662 else if (unstarred_name == "table")
1663 float_type = unstarred_name;
1667 os << "placement " << opt << '\n';
1668 if (contains(opt, "H"))
1669 preamble.registerAutomaticallyLoadedPackage("float");
1671 Floating const & fl = parent_context.textclass.floats()
1672 .getType(unstarred_name);
1673 if (!fl.floattype().empty() && fl.usesFloatPkg())
1674 preamble.registerAutomaticallyLoadedPackage("float");
1677 os << "wide " << convert<string>(is_starred)
1678 << "\nsideways false"
1679 << "\nstatus open\n\n";
1680 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1682 // We don't need really a new paragraph, but
1683 // we must make sure that the next item gets a \begin_layout.
1684 parent_context.new_paragraph(os);
1686 // the float is parsed thus delete the type
1690 else if (unstarred_name == "sidewaysfigure"
1691 || unstarred_name == "sidewaystable"
1692 || unstarred_name == "sidewaysalgorithm") {
1693 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1694 eat_whitespace(p, os, parent_context, false);
1695 parent_context.check_layout(os);
1696 if (unstarred_name == "sidewaysfigure")
1697 begin_inset(os, "Float figure\n");
1698 else if (unstarred_name == "sidewaystable")
1699 begin_inset(os, "Float table\n");
1700 else if (unstarred_name == "sidewaysalgorithm")
1701 begin_inset(os, "Float algorithm\n");
1703 os << "placement " << opt << '\n';
1704 if (contains(opt, "H"))
1705 preamble.registerAutomaticallyLoadedPackage("float");
1706 os << "wide " << convert<string>(is_starred)
1707 << "\nsideways true"
1708 << "\nstatus open\n\n";
1709 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1711 // We don't need really a new paragraph, but
1712 // we must make sure that the next item gets a \begin_layout.
1713 parent_context.new_paragraph(os);
1715 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1718 else if (name == "wrapfigure" || name == "wraptable") {
1719 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1720 eat_whitespace(p, os, parent_context, false);
1721 parent_context.check_layout(os);
1724 string overhang = "0col%";
1727 lines = p.getArg('[', ']');
1728 string const placement = p.getArg('{', '}');
1730 overhang = p.getArg('[', ']');
1731 string const width = p.getArg('{', '}');
1733 if (name == "wrapfigure")
1734 begin_inset(os, "Wrap figure\n");
1736 begin_inset(os, "Wrap table\n");
1737 os << "lines " << lines
1738 << "\nplacement " << placement
1739 << "\noverhang " << lyx::translate_len(overhang)
1740 << "\nwidth " << lyx::translate_len(width)
1741 << "\nstatus open\n\n";
1742 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1744 // We don't need really a new paragraph, but
1745 // we must make sure that the next item gets a \begin_layout.
1746 parent_context.new_paragraph(os);
1748 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1751 else if (name == "minipage") {
1752 eat_whitespace(p, os, parent_context, false);
1753 // Test whether this is an outer box of a shaded box
1755 // swallow arguments
1756 while (p.hasOpt()) {
1758 p.skip_spaces(true);
1761 p.skip_spaces(true);
1762 Token t = p.get_token();
1763 bool shaded = false;
1764 if (t.asInput() == "\\begin") {
1765 p.skip_spaces(true);
1766 if (p.getArg('{', '}') == "shaded")
1771 parse_outer_box(p, os, FLAG_END, outer,
1772 parent_context, name, "shaded");
1774 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1775 "", "", name, "", "");
1779 else if (name == "comment") {
1780 eat_whitespace(p, os, parent_context, false);
1781 parent_context.check_layout(os);
1782 begin_inset(os, "Note Comment\n");
1783 os << "status open\n";
1784 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1787 skip_braces(p); // eat {} that might by set by LyX behind comments
1788 preamble.registerAutomaticallyLoadedPackage("verbatim");
1791 else if (unstarred_name == "verbatim") {
1792 // FIXME: this should go in the generic code that
1793 // handles environments defined in layout file that
1794 // have "PassThru 1". However, the code over there is
1795 // already too complicated for my taste.
1796 string const ascii_name =
1797 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1798 parent_context.new_paragraph(os);
1799 Context context(true, parent_context.textclass,
1800 &parent_context.textclass[from_ascii(ascii_name)]);
1801 string s = p.verbatimEnvironment(name);
1802 output_ert(os, s, context);
1806 else if (name == "IPA") {
1807 eat_whitespace(p, os, parent_context, false);
1808 parent_context.check_layout(os);
1809 begin_inset(os, "IPA\n");
1810 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1813 preamble.registerAutomaticallyLoadedPackage("tipa");
1814 preamble.registerAutomaticallyLoadedPackage("tipx");
1817 else if (name == parent_context.textclass.titlename()
1818 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1819 parse_text(p, os, FLAG_END, outer, parent_context);
1820 // Just in case the environment is empty
1821 parent_context.extra_stuff.erase();
1822 // We must begin a new paragraph
1823 parent_context.new_paragraph(os);
1827 else if (name == "CJK") {
1828 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1829 // It is impossible to decide if a CJK environment was in its own paragraph or within
1830 // a line. We therefore always assume a paragraph since the latter is a rare case.
1831 eat_whitespace(p, os, parent_context, false);
1832 parent_context.check_end_layout(os);
1833 // store the encoding to be able to reset it
1834 string const encoding_old = p.getEncoding();
1835 string const encoding = p.getArg('{', '}');
1836 // FIXME: For some reason JIS does not work. Although the text
1837 // in tests/CJK.tex is identical with the SJIS version if you
1838 // convert both snippets using the recode command line utility,
1839 // the resulting .lyx file contains some extra characters if
1840 // you set buggy_encoding to false for JIS.
1841 bool const buggy_encoding = encoding == "JIS";
1842 if (!buggy_encoding)
1843 p.setEncoding(encoding, Encoding::CJK);
1845 // FIXME: This will read garbage, since the data is not encoded in utf8.
1846 p.setEncoding("UTF-8");
1848 // LyX only supports the same mapping for all CJK
1849 // environments, so we might need to output everything as ERT
1850 string const mapping = trim(p.getArg('{', '}'));
1851 char const * const * const where =
1852 is_known(encoding, supported_CJK_encodings);
1853 if (!buggy_encoding && !preamble.fontCJKSet())
1854 preamble.fontCJK(mapping);
1855 bool knownMapping = mapping == preamble.fontCJK();
1856 if (buggy_encoding || !knownMapping || !where) {
1857 parent_context.check_layout(os);
1858 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1860 // we must parse the content as verbatim because e.g. JIS can contain
1861 // normally invalid characters
1862 // FIXME: This works only for the most simple cases.
1863 // Since TeX control characters are not parsed,
1864 // things like comments are completely wrong.
1865 string const s = p.plainEnvironment("CJK");
1866 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1869 if (snip == "\\" || is_known(snip, known_escaped_chars))
1870 output_ert_inset(os, snip, parent_context);
1871 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1876 output_ert_inset(os, "\\end{" + name + "}",
1880 supported_CJK_languages[where - supported_CJK_encodings];
1881 // store the language because we must reset it at the end
1882 string const lang_old = parent_context.font.language;
1883 parent_context.font.language = lang;
1884 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1885 parent_context.font.language = lang_old;
1886 parent_context.new_paragraph(os);
1888 p.setEncoding(encoding_old);
1892 else if (name == "lyxgreyedout") {
1893 eat_whitespace(p, os, parent_context, false);
1894 parent_context.check_layout(os);
1895 begin_inset(os, "Note Greyedout\n");
1896 os << "status open\n";
1897 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1900 if (!preamble.notefontcolor().empty())
1901 preamble.registerAutomaticallyLoadedPackage("color");
1904 else if (name == "btSect") {
1905 eat_whitespace(p, os, parent_context, false);
1906 parent_context.check_layout(os);
1907 begin_command_inset(os, "bibtex", "bibtex");
1908 string bibstyle = "plain";
1910 bibstyle = p.getArg('[', ']');
1911 p.skip_spaces(true);
1913 string const bibfile = p.getArg('{', '}');
1914 eat_whitespace(p, os, parent_context, false);
1915 Token t = p.get_token();
1916 if (t.asInput() == "\\btPrintCited") {
1917 p.skip_spaces(true);
1918 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1920 if (t.asInput() == "\\btPrintNotCited") {
1921 p.skip_spaces(true);
1922 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1924 if (t.asInput() == "\\btPrintAll") {
1925 p.skip_spaces(true);
1926 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1928 os << "bibfiles " << '"' << bibfile << "\"\n"
1929 << "options " << '"' << bibstyle << "\"\n";
1930 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1935 else if (name == "framed" || name == "shaded") {
1936 eat_whitespace(p, os, parent_context, false);
1937 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1939 preamble.registerAutomaticallyLoadedPackage("framed");
1942 else if (name == "listing") {
1943 minted_float = "float";
1944 eat_whitespace(p, os, parent_context, false);
1945 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1947 minted_float += "=" + opt;
1948 // If something precedes \begin{minted}, we output it at the end
1949 // as a caption, in order to keep it inside the listings inset.
1950 eat_whitespace(p, os, parent_context, true);
1952 Token const & t = p.get_token();
1953 p.skip_spaces(true);
1954 string const envname = p.next_token().cat() == catBegin
1955 ? p.getArg('{', '}') : string();
1956 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1958 minted_float_has_caption = false;
1959 string content = parse_text_snippet(p, FLAG_END, outer,
1961 size_t i = content.find("\\begin_inset listings");
1962 bool minted_env = i != string::npos;
1965 caption = content.substr(0, i);
1966 content.erase(0, i);
1968 parent_context.check_layout(os);
1969 if (minted_env && minted_float_has_caption) {
1970 eat_whitespace(p, os, parent_context, true);
1971 os << content << "\n";
1972 if (!caption.empty())
1973 os << caption << "\n";
1974 os << "\n\\end_layout\n"; // close inner layout
1975 end_inset(os); // close caption inset
1976 os << "\n\\end_layout\n"; // close outer layout
1977 } else if (!caption.empty()) {
1979 begin_inset(os, "listings\n");
1980 os << "lstparams " << '"' << minted_float << '"' << '\n';
1981 os << "inline false\n";
1982 os << "status collapsed\n";
1984 os << "\n\\begin_layout Plain Layout\n";
1985 begin_inset(os, "Caption Standard\n");
1986 Context newcontext(true, parent_context.textclass,
1987 0, 0, parent_context.font);
1988 newcontext.check_layout(os);
1989 os << caption << "\n";
1990 newcontext.check_end_layout(os);
1992 os << "\n\\end_layout\n";
1993 } else if (content.empty()) {
1994 begin_inset(os, "listings\n");
1995 os << "lstparams " << '"' << minted_float << '"' << '\n';
1996 os << "inline false\n";
1997 os << "status collapsed\n";
1999 os << content << "\n";
2001 end_inset(os); // close listings inset
2002 parent_context.check_end_layout(os);
2003 parent_context.new_paragraph(os);
2005 minted_float.clear();
2006 minted_float_has_caption = false;
2009 else if (name == "lstlisting" || name == "minted") {
2010 bool use_minted = name == "minted";
2011 eat_whitespace(p, os, parent_context, false);
2012 if (use_minted && minted_float.empty()) {
2013 // look ahead for a bottom caption
2015 bool found_end_minted = false;
2016 while (!found_end_minted && p.good()) {
2017 Token const & t = p.get_token();
2019 string const envname =
2020 p.next_token().cat() == catBegin
2021 ? p.getArg('{', '}') : string();
2022 found_end_minted = t.asInput() == "\\end"
2023 && envname == "minted";
2025 eat_whitespace(p, os, parent_context, true);
2026 Token const & t = p.get_token();
2027 p.skip_spaces(true);
2028 if (t.asInput() == "\\lyxmintcaption") {
2029 string const pos = p.getArg('[', ']');
2031 string const caption =
2032 parse_text_snippet(p, FLAG_ITEM,
2033 false, parent_context);
2034 minted_nonfloat_caption = "[b]" + caption;
2035 eat_whitespace(p, os, parent_context, true);
2040 parse_listings(p, os, parent_context, false, use_minted);
2044 else if (!parent_context.new_layout_allowed)
2045 parse_unknown_environment(p, name, os, FLAG_END, outer,
2048 // Alignment and spacing settings
2049 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2050 // therefore are totally broken!
2051 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2052 // they are commands not environments. They are furthermore switches that
2053 // can be ended by another switches, but also by commands like \footnote or
2054 // \parbox. So the only safe way is to leave them untouched.
2055 // However, we support the pseudo-environments
2056 // \begin{centering} ... \end{centering}
2057 // \begin{raggedright} ... \end{raggedright}
2058 // \begin{raggedleft} ... \end{raggedleft}
2059 // since they are used by LyX in floats (for spacing reasons)
2060 else if (name == "center" || name == "centering" ||
2061 name == "flushleft" || name == "raggedright" ||
2062 name == "flushright" || name == "raggedleft" ||
2063 name == "singlespace" || name == "onehalfspace" ||
2064 name == "doublespace" || name == "spacing") {
2065 eat_whitespace(p, os, parent_context, false);
2066 // We must begin a new paragraph if not already done
2067 if (! parent_context.atParagraphStart()) {
2068 parent_context.check_end_layout(os);
2069 parent_context.new_paragraph(os);
2071 if (name == "flushleft" || name == "raggedright")
2072 parent_context.add_extra_stuff("\\align left\n");
2073 else if (name == "flushright" || name == "raggedleft")
2074 parent_context.add_extra_stuff("\\align right\n");
2075 else if (name == "center" || name == "centering")
2076 parent_context.add_extra_stuff("\\align center\n");
2077 else if (name == "singlespace")
2078 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2079 else if (name == "onehalfspace") {
2080 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2081 preamble.registerAutomaticallyLoadedPackage("setspace");
2082 } else if (name == "doublespace") {
2083 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2084 preamble.registerAutomaticallyLoadedPackage("setspace");
2085 } else if (name == "spacing") {
2086 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2087 preamble.registerAutomaticallyLoadedPackage("setspace");
2089 parse_text(p, os, FLAG_END, outer, parent_context);
2090 // Just in case the environment is empty
2091 parent_context.extra_stuff.erase();
2092 // We must begin a new paragraph to reset the alignment
2093 parent_context.new_paragraph(os);
2097 // The single '=' is meant here.
2098 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2099 eat_whitespace(p, os, parent_context, false);
2100 Context context(true, parent_context.textclass, newlayout,
2101 parent_context.layout, parent_context.font);
2102 if (parent_context.deeper_paragraph) {
2103 // We are beginning a nested environment after a
2104 // deeper paragraph inside the outer list environment.
2105 // Therefore we don't need to output a "begin deeper".
2106 context.need_end_deeper = true;
2108 parent_context.check_end_layout(os);
2109 if (last_env == name) {
2110 // we need to output a separator since LyX would export
2111 // the two environments as one otherwise (bug 5716)
2112 TeX2LyXDocClass const & textclass(parent_context.textclass);
2113 Context newcontext(true, textclass,
2114 &(textclass.defaultLayout()));
2115 newcontext.check_layout(os);
2116 begin_inset(os, "Separator plain\n");
2118 newcontext.check_end_layout(os);
2120 switch (context.layout->latextype) {
2121 case LATEX_LIST_ENVIRONMENT:
2122 context.add_par_extra_stuff("\\labelwidthstring "
2123 + p.verbatim_item() + '\n');
2126 case LATEX_BIB_ENVIRONMENT:
2127 p.verbatim_item(); // swallow next arg
2133 context.check_deeper(os);
2134 if (newlayout->keepempty) {
2135 // We need to start a new paragraph
2136 // even if it is empty.
2137 context.new_paragraph(os);
2138 context.check_layout(os);
2140 // handle known optional and required arguments
2141 if (context.layout->latextype == LATEX_ENVIRONMENT)
2142 output_arguments(os, p, outer, false, string(), context,
2143 context.layout->latexargs());
2144 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2146 output_arguments(oss, p, outer, false, string(), context,
2147 context.layout->latexargs());
2148 context.list_extra_stuff = oss.str();
2150 parse_text(p, os, FLAG_END, outer, context);
2151 if (context.layout->latextype == LATEX_ENVIRONMENT)
2152 output_arguments(os, p, outer, false, "post", context,
2153 context.layout->postcommandargs());
2154 context.check_end_layout(os);
2155 if (parent_context.deeper_paragraph) {
2156 // We must suppress the "end deeper" because we
2157 // suppressed the "begin deeper" above.
2158 context.need_end_deeper = false;
2160 context.check_end_deeper(os);
2161 parent_context.new_paragraph(os);
2163 if (!preamble.titleLayoutFound())
2164 preamble.titleLayoutFound(newlayout->intitle);
2165 set<string> const & req = newlayout->requires();
2166 set<string>::const_iterator it = req.begin();
2167 set<string>::const_iterator en = req.end();
2168 for (; it != en; ++it)
2169 preamble.registerAutomaticallyLoadedPackage(*it);
2172 // The single '=' is meant here.
2173 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2174 eat_whitespace(p, os, parent_context, false);
2175 parent_context.check_layout(os);
2176 begin_inset(os, "Flex ");
2177 os << to_utf8(newinsetlayout->name()) << '\n'
2178 << "status collapsed\n";
2179 if (newinsetlayout->isPassThru()) {
2180 string const arg = p.verbatimEnvironment(name);
2181 Context context(true, parent_context.textclass,
2182 &parent_context.textclass.plainLayout(),
2183 parent_context.layout);
2184 output_ert(os, arg, parent_context);
2186 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2190 else if (name == "appendix") {
2191 // This is no good latex style, but it works and is used in some documents...
2192 eat_whitespace(p, os, parent_context, false);
2193 parent_context.check_end_layout(os);
2194 Context context(true, parent_context.textclass, parent_context.layout,
2195 parent_context.layout, parent_context.font);
2196 context.check_layout(os);
2197 os << "\\start_of_appendix\n";
2198 parse_text(p, os, FLAG_END, outer, context);
2199 context.check_end_layout(os);
2203 else if (known_environments.find(name) != known_environments.end()) {
2204 vector<ArgumentType> arguments = known_environments[name];
2205 // The last "argument" denotes wether we may translate the
2206 // environment contents to LyX
2207 // The default required if no argument is given makes us
2208 // compatible with the reLyXre environment.
2209 ArgumentType contents = arguments.empty() ?
2212 if (!arguments.empty())
2213 arguments.pop_back();
2214 // See comment in parse_unknown_environment()
2215 bool const specialfont =
2216 (parent_context.font != parent_context.normalfont);
2217 bool const new_layout_allowed =
2218 parent_context.new_layout_allowed;
2220 parent_context.new_layout_allowed = false;
2221 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2222 outer, parent_context);
2223 if (contents == verbatim)
2224 output_ert_inset(os, p.ertEnvironment(name),
2227 parse_text_snippet(p, os, FLAG_END, outer,
2229 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2231 parent_context.new_layout_allowed = new_layout_allowed;
2235 parse_unknown_environment(p, name, os, FLAG_END, outer,
2239 active_environments.pop_back();
2243 /// parses a comment and outputs it to \p os.
2244 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2246 LASSERT(t.cat() == catComment, return);
2247 if (!t.cs().empty()) {
2248 context.check_layout(os);
2249 output_comment(p, os, t.cs(), context);
2250 if (p.next_token().cat() == catNewline) {
2251 // A newline after a comment line starts a new
2253 if (context.new_layout_allowed) {
2254 if(!context.atParagraphStart())
2255 // Only start a new paragraph if not already
2256 // done (we might get called recursively)
2257 context.new_paragraph(os);
2259 output_ert_inset(os, "\n", context);
2260 eat_whitespace(p, os, context, true);
2263 // "%\n" combination
2270 * Reads spaces and comments until the first non-space, non-comment token.
2271 * New paragraphs (double newlines or \\par) are handled like simple spaces
2272 * if \p eatParagraph is true.
2273 * Spaces are skipped, but comments are written to \p os.
2275 void eat_whitespace(Parser & p, ostream & os, Context & context,
2279 Token const & t = p.get_token();
2280 if (t.cat() == catComment)
2281 parse_comment(p, os, t, context);
2282 else if ((! eatParagraph && p.isParagraph()) ||
2283 (t.cat() != catSpace && t.cat() != catNewline)) {
2292 * Set a font attribute, parse text and reset the font attribute.
2293 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2294 * \param currentvalue Current value of the attribute. Is set to the new
2295 * value during parsing.
2296 * \param newvalue New value of the attribute
2298 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2299 Context & context, string const & attribute,
2300 string & currentvalue, string const & newvalue)
2302 context.check_layout(os);
2303 string const oldvalue = currentvalue;
2304 currentvalue = newvalue;
2305 os << '\n' << attribute << ' ' << newvalue << "\n";
2306 parse_text_snippet(p, os, flags, outer, context);
2307 context.check_layout(os);
2308 os << '\n' << attribute << ' ' << oldvalue << "\n";
2309 currentvalue = oldvalue;
2313 /// get the arguments of a natbib or jurabib citation command
2314 void get_cite_arguments(Parser & p, bool natbibOrder,
2315 string & before, string & after, bool const qualified = false)
2317 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2319 // text before the citation
2321 // text after the citation
2322 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2324 if (!after.empty()) {
2325 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2326 if (natbibOrder && !before.empty())
2327 swap(before, after);
2332 void copy_file(FileName const & src, string dstname)
2336 string const absParent = getParentFilePath(false);
2338 if (FileName::isAbsolute(dstname))
2339 dst = FileName(dstname);
2341 dst = makeAbsPath(dstname, absParent);
2342 FileName const srcpath = src.onlyPath();
2343 FileName const dstpath = dst.onlyPath();
2344 if (equivalent(srcpath, dstpath))
2346 if (!dstpath.isDirectory()) {
2347 if (!dstpath.createPath()) {
2348 cerr << "Warning: Could not create directory for file `"
2349 << dst.absFileName() << "´." << endl;
2353 if (dst.isReadableFile()) {
2354 if (overwriteFiles())
2355 cerr << "Warning: Overwriting existing file `"
2356 << dst.absFileName() << "´." << endl;
2358 cerr << "Warning: Not overwriting existing file `"
2359 << dst.absFileName() << "´." << endl;
2363 if (!src.copyTo(dst))
2364 cerr << "Warning: Could not copy file `" << src.absFileName()
2365 << "´ to `" << dst.absFileName() << "´." << endl;
2369 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2370 bool parse_chunk(Parser & p, ostream & os, Context & context)
2372 // check whether a chunk is possible here.
2373 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2379 // read the parameters
2380 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2381 if (!params.first) {
2386 Parser::Arg const code = p.verbatimStuff("\n@");
2391 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2392 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2396 // The last newline read is important for paragraph handling
2400 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2401 // We must have a valid layout before outputting the Chunk inset.
2402 context.check_layout(os);
2403 Context chunkcontext(true, context.textclass);
2404 chunkcontext.layout = &context.textclass.plainLayout();
2405 begin_inset(os, "Flex Chunk");
2406 os << "\nstatus open\n";
2407 if (!params.second.empty()) {
2408 chunkcontext.check_layout(os);
2409 Context paramscontext(true, context.textclass);
2410 paramscontext.layout = &context.textclass.plainLayout();
2411 begin_inset(os, "Argument 1");
2412 os << "\nstatus open\n";
2413 output_ert(os, params.second, paramscontext);
2416 output_ert(os, code.second, chunkcontext);
2424 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2425 bool is_macro(Parser & p)
2427 Token first = p.curr_token();
2428 if (first.cat() != catEscape || !p.good())
2430 if (first.cs() == "def")
2432 if (first.cs() != "global" && first.cs() != "long")
2434 Token second = p.get_token();
2436 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2437 second.cat() == catNewline || second.cat() == catComment)) {
2438 second = p.get_token();
2441 bool secondvalid = second.cat() == catEscape;
2443 bool thirdvalid = false;
2444 if (p.good() && first.cs() == "global" && secondvalid &&
2445 second.cs() == "long") {
2446 third = p.get_token();
2448 while (p.good() && !p.isParagraph() &&
2449 (third.cat() == catSpace ||
2450 third.cat() == catNewline ||
2451 third.cat() == catComment)) {
2452 third = p.get_token();
2455 thirdvalid = third.cat() == catEscape;
2457 for (int i = 0; i < pos; ++i)
2462 return (first.cs() == "global" || first.cs() == "long") &&
2463 second.cs() == "def";
2464 return first.cs() == "global" && second.cs() == "long" &&
2465 third.cs() == "def";
2469 /// Parse a macro definition (assumes that is_macro() returned true)
2470 void parse_macro(Parser & p, ostream & os, Context & context)
2472 context.check_layout(os);
2473 Token first = p.curr_token();
2476 string command = first.asInput();
2477 if (first.cs() != "def") {
2479 eat_whitespace(p, os, context, false);
2480 second = p.curr_token();
2481 command += second.asInput();
2482 if (second.cs() != "def") {
2484 eat_whitespace(p, os, context, false);
2485 third = p.curr_token();
2486 command += third.asInput();
2489 eat_whitespace(p, os, context, false);
2490 string const name = p.get_token().cs();
2491 eat_whitespace(p, os, context, false);
2497 while (p.next_token().cat() != catBegin) {
2498 if (p.next_token().cat() == catParameter) {
2503 // followed by number?
2504 if (p.next_token().cat() == catOther) {
2505 string s = p.get_token().asInput();
2507 // number = current arity + 1?
2508 if (s.size() == 1 && s[0] == arity + '0' + 1)
2513 paramtext += p.get_token().cs();
2515 paramtext += p.get_token().cs();
2520 // only output simple (i.e. compatible) macro as FormulaMacros
2521 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2523 context.check_layout(os);
2524 begin_inset(os, "FormulaMacro");
2525 os << "\n\\def" << ert;
2528 output_ert_inset(os, command + ert, context);
2532 void registerExternalTemplatePackages(string const & name)
2534 external::TemplateManager const & etm = external::TemplateManager::get();
2535 external::Template const * const et = etm.getTemplateByName(name);
2538 external::Template::Formats::const_iterator cit = et->formats.end();
2540 cit = et->formats.find("PDFLaTeX");
2541 if (cit == et->formats.end())
2542 // If the template has not specified a PDFLaTeX output,
2543 // we try the LaTeX format.
2544 cit = et->formats.find("LaTeX");
2545 if (cit == et->formats.end())
2547 vector<string>::const_iterator qit = cit->second.requirements.begin();
2548 vector<string>::const_iterator qend = cit->second.requirements.end();
2549 for (; qit != qend; ++qit)
2550 preamble.registerAutomaticallyLoadedPackage(*qit);
2553 } // anonymous namespace
2557 * Find a file with basename \p name in path \p path and an extension
2560 string find_file(string const & name, string const & path,
2561 char const * const * extensions)
2563 for (char const * const * what = extensions; *what; ++what) {
2564 string const trial = addExtension(name, *what);
2565 if (makeAbsPath(trial, path).exists())
2572 /// Convert filenames with TeX macros and/or quotes to something LyX
2574 string const normalize_filename(string const & name)
2579 Token const & t = p.get_token();
2580 if (t.cat() != catEscape)
2582 else if (t.cs() == "lyxdot") {
2583 // This is used by LyX for simple dots in relative
2587 } else if (t.cs() == "space") {
2590 } else if (t.cs() == "string") {
2591 // Convert \string" to " and \string~ to ~
2592 Token const & n = p.next_token();
2593 if (n.asInput() != "\"" && n.asInput() != "~")
2598 // Strip quotes. This is a bit complicated (see latex_path()).
2599 string full = os.str();
2600 if (!full.empty() && full[0] == '"') {
2601 string base = removeExtension(full);
2602 string ext = getExtension(full);
2603 if (!base.empty() && base[base.length()-1] == '"')
2606 return addExtension(trim(base, "\""), ext);
2607 if (full[full.length()-1] == '"')
2610 return trim(full, "\"");
2616 /// Convert \p name from TeX convention (relative to master file) to LyX
2617 /// convention (relative to .lyx file) if it is relative
2618 void fix_child_filename(string & name)
2620 string const absMasterTeX = getMasterFilePath(true);
2621 bool const isabs = FileName::isAbsolute(name);
2622 // convert from "relative to .tex master" to absolute original path
2624 name = makeAbsPath(name, absMasterTeX).absFileName();
2625 bool copyfile = copyFiles();
2626 string const absParentLyX = getParentFilePath(false);
2629 // convert from absolute original path to "relative to master file"
2630 string const rel = to_utf8(makeRelPath(from_utf8(name),
2631 from_utf8(absMasterTeX)));
2632 // re-interpret "relative to .tex file" as "relative to .lyx file"
2633 // (is different if the master .lyx file resides in a
2634 // different path than the master .tex file)
2635 string const absMasterLyX = getMasterFilePath(false);
2636 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2637 // Do not copy if the new path is impossible to create. Example:
2638 // absMasterTeX = "/foo/bar/"
2639 // absMasterLyX = "/bar/"
2640 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2641 if (contains(name, "/../"))
2648 // convert from absolute original path to
2649 // "relative to .lyx file"
2650 name = to_utf8(makeRelPath(from_utf8(abs),
2651 from_utf8(absParentLyX)));
2655 // convert from absolute original path to "relative to .lyx file"
2656 name = to_utf8(makeRelPath(from_utf8(name),
2657 from_utf8(absParentLyX)));
2662 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2663 Context & context, string const rdelim)
2665 Layout const * newlayout = 0;
2666 InsetLayout const * newinsetlayout = 0;
2667 char const * const * where = 0;
2668 // Store the latest bibliographystyle, addcontentslineContent and
2669 // nocite{*} option (needed for bibtex inset)
2671 string contentslineContent;
2672 // Some classes provide a \bibliographystyle, so do not output
2673 // any if none is explicitly set.
2674 string bibliographystyle;
2675 bool const use_natbib = isProvided("natbib");
2676 bool const use_jurabib = isProvided("jurabib");
2677 bool const use_biblatex = isProvided("biblatex")
2678 && preamble.citeEngine() != "biblatex-natbib";
2679 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2680 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2681 need_commentbib = use_biblatex || use_biblatex_natbib;
2684 // it is impossible to determine the correct encoding for non-CJK Japanese.
2685 // Therefore write a note at the beginning of the document
2686 if (is_nonCJKJapanese) {
2687 context.check_layout(os);
2688 begin_inset(os, "Note Note\n");
2689 os << "status open\n\\begin_layout Plain Layout\n"
2690 << "\\series bold\n"
2691 << "Important information:\n"
2692 << "\\end_layout\n\n"
2693 << "\\begin_layout Plain Layout\n"
2694 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2695 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2696 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2697 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2698 << " and specify the encoding using the -e command-line switch.\n"
2699 << " In addition, you might want to double check that the desired output encoding\n"
2700 << " is correctly selected in Document > Settings > Language.\n"
2701 << "\\end_layout\n";
2703 is_nonCJKJapanese = false;
2706 bool have_cycled = false;
2708 // Leave here only after at least one cycle
2709 if (have_cycled && flags & FLAG_LEAVE) {
2710 flags &= ~FLAG_LEAVE;
2714 Token const & t = p.get_token();
2716 debugToken(cerr, t, flags);
2719 if (flags & FLAG_ITEM) {
2720 if (t.cat() == catSpace)
2723 flags &= ~FLAG_ITEM;
2724 if (t.cat() == catBegin) {
2725 // skip the brace and collect everything to the next matching
2727 flags |= FLAG_BRACE_LAST;
2731 // handle only this single token, leave the loop if done
2732 flags |= FLAG_LEAVE;
2735 if (t.cat() != catEscape && t.character() == ']' &&
2736 (flags & FLAG_BRACK_LAST))
2738 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2740 string tok = t.asInput();
2741 // we only support delimiters with max 2 chars for now.
2742 if (rdelim.size() > 1)
2743 tok += p.next_token().asInput();
2744 if (t.cat() != catEscape && !rdelim.empty()
2745 && tok == rdelim && (flags & FLAG_RDELIM)) {
2746 if (rdelim.size() > 1)
2747 p.get_token(); // eat rdelim
2751 // If there is anything between \end{env} and \begin{env} we
2752 // don't need to output a separator.
2753 if (t.cat() != catSpace && t.cat() != catNewline &&
2754 t.asInput() != "\\begin")
2761 bool const starred = p.next_token().asInput() == "*";
2762 string const starredname(starred ? (t.cs() + '*') : t.cs());
2763 if (t.cat() == catMath) {
2764 // we are inside some text mode thingy, so opening new math is allowed
2765 context.check_layout(os);
2766 begin_inset(os, "Formula ");
2767 Token const & n = p.get_token();
2768 bool const display(n.cat() == catMath && outer);
2770 // TeX's $$...$$ syntax for displayed math
2772 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2774 p.get_token(); // skip the second '$' token
2776 // simple $...$ stuff
2779 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2784 // Prevent the conversion of a line break to a
2785 // space (bug 7668). This does not change the
2786 // output, but looks ugly in LyX.
2787 eat_whitespace(p, os, context, false);
2792 if (t.cat() == catSuper || t.cat() == catSub) {
2793 cerr << "catcode " << t << " illegal in text mode\n";
2797 // Basic support for quotes. We try to disambiguate
2798 // quotes from the context (e.g., a left english quote is
2799 // the same as a right german quote...).
2800 // Try to make a smart guess about the side
2801 Token const prev = p.prev_token();
2802 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2803 && prev.character() != '\n' && prev.character() != '~');
2804 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2805 context.check_layout(os);
2806 begin_inset(os, "Quotes ");
2807 os << guessQuoteStyle("eld", opening);
2813 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2814 context.check_layout(os);
2815 begin_inset(os, "Quotes ");
2816 os << guessQuoteStyle("erd", opening);
2823 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2824 context.check_layout(os);
2825 begin_inset(os, "Quotes ");
2826 os << guessQuoteStyle("ald", opening);
2833 if (t.asInput() == "<"
2834 && p.next_token().asInput() == "<") {
2835 bool has_chunk = false;
2839 has_chunk = parse_chunk(p, os, context);
2845 context.check_layout(os);
2846 begin_inset(os, "Quotes ");
2847 os << guessQuoteStyle("ard", opening);
2855 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2856 check_space(p, os, context);
2860 // babel shorthands (also used by polyglossia)
2861 // Since these can have different meanings for different languages
2862 // we import them as ERT (but they must be put in ERT to get output
2864 if (t.asInput() == "\"") {
2866 // These are known pairs. We put them together in
2867 // one ERT inset. In other cases (such as "a), only
2868 // the quotation mark is ERTed.
2869 if (p.next_token().asInput() == "\""
2870 || p.next_token().asInput() == "|"
2871 || p.next_token().asInput() == "-"
2872 || p.next_token().asInput() == "~"
2873 || p.next_token().asInput() == "="
2874 || p.next_token().asInput() == "/"
2875 || p.next_token().asInput() == "~"
2876 || p.next_token().asInput() == "'"
2877 || p.next_token().asInput() == "`"
2878 || p.next_token().asInput() == "<"
2879 || p.next_token().asInput() == ">") {
2880 s += p.next_token().asInput();
2883 output_ert_inset(os, s, context);
2887 if (t.character() == '[' && noweb_mode &&
2888 p.next_token().character() == '[') {
2889 // These can contain underscores
2891 string const s = p.getFullOpt() + ']';
2892 if (p.next_token().character() == ']')
2895 cerr << "Warning: Inserting missing ']' in '"
2896 << s << "'." << endl;
2897 output_ert_inset(os, s, context);
2901 if (t.cat() == catLetter) {
2902 context.check_layout(os);
2907 if (t.cat() == catOther ||
2908 t.cat() == catAlign ||
2909 t.cat() == catParameter) {
2910 context.check_layout(os);
2911 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2912 context.merging_hyphens_allowed &&
2913 context.font.family != "ttfamily" &&
2914 !context.layout->pass_thru) {
2915 if (p.next_next_token().asInput() == "-") {
2917 os << to_utf8(docstring(1, 0x2014));
2921 os << to_utf8(docstring(1, 0x2013));
2924 // This translates "&" to "\\&" which may be wrong...
2929 if (p.isParagraph()) {
2930 // In minted floating listings we will collect
2931 // everything into the caption, where multiple
2932 // paragraphs are forbidden.
2933 if (minted_float.empty()) {
2934 if (context.new_layout_allowed)
2935 context.new_paragraph(os);
2937 output_ert_inset(os, "\\par ", context);
2940 eat_whitespace(p, os, context, true);
2944 if (t.cat() == catActive) {
2945 context.check_layout(os);
2946 if (t.character() == '~') {
2947 if (context.layout->free_spacing)
2950 begin_inset(os, "space ~\n");
2958 if (t.cat() == catBegin) {
2959 Token const next = p.next_token();
2960 Token const end = p.next_next_token();
2961 if (next.cat() == catEnd) {
2963 Token const prev = p.prev_token();
2965 if (p.next_token().character() == '`')
2966 ; // ignore it in {}``
2968 output_ert_inset(os, "{}", context);
2969 } else if (next.cat() == catEscape &&
2970 is_known(next.cs(), known_quotes) &&
2971 end.cat() == catEnd) {
2972 // Something like {\textquoteright} (e.g.
2973 // from writer2latex). We may skip the
2974 // braces here for better readability.
2975 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2977 } else if (p.next_token().asInput() == "\\ascii") {
2978 // handle the \ascii characters
2979 // (the case without braces is handled later)
2980 // the code is "{\ascii\xxx}"
2981 p.get_token(); // eat \ascii
2982 string name2 = p.get_token().asInput();
2983 p.get_token(); // eat the final '}'
2984 string const name = "{\\ascii" + name2 + "}";
2988 // get the character from unicodesymbols
2989 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2990 Encodings::TEXT_CMD, termination, rem, &req);
2992 context.check_layout(os);
2995 output_ert_inset(os,
2996 to_utf8(rem), context);
2997 for (set<string>::const_iterator it = req.begin();
2998 it != req.end(); ++it)
2999 preamble.registerAutomaticallyLoadedPackage(*it);
3001 // we did not find a non-ert version
3002 output_ert_inset(os, name, context);
3004 context.check_layout(os);
3005 // special handling of font attribute changes
3006 Token const prev = p.prev_token();
3007 TeXFont const oldFont = context.font;
3008 if (next.character() == '[' ||
3009 next.character() == ']' ||
3010 next.character() == '*') {
3012 if (p.next_token().cat() == catEnd) {
3017 output_ert_inset(os, "{", context);
3018 parse_text_snippet(p, os,
3021 output_ert_inset(os, "}", context);
3023 } else if (! context.new_layout_allowed) {
3024 output_ert_inset(os, "{", context);
3025 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3027 output_ert_inset(os, "}", context);
3028 } else if (is_known(next.cs(), known_sizes)) {
3029 // next will change the size, so we must
3031 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3033 if (!context.atParagraphStart())
3035 << context.font.size << "\n";
3036 } else if (is_known(next.cs(), known_font_families)) {
3037 // next will change the font family, so we
3038 // must reset it here
3039 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3041 if (!context.atParagraphStart())
3043 << context.font.family << "\n";
3044 } else if (is_known(next.cs(), known_font_series)) {
3045 // next will change the font series, so we
3046 // must reset it here
3047 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3049 if (!context.atParagraphStart())
3051 << context.font.series << "\n";
3052 } else if (is_known(next.cs(), known_font_shapes)) {
3053 // next will change the font shape, so we
3054 // must reset it here
3055 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3057 if (!context.atParagraphStart())
3059 << context.font.shape << "\n";
3060 } else if (is_known(next.cs(), known_old_font_families) ||
3061 is_known(next.cs(), known_old_font_series) ||
3062 is_known(next.cs(), known_old_font_shapes)) {
3063 // next will change the font family, series
3064 // and shape, so we must reset it here
3065 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3067 if (!context.atParagraphStart())
3069 << context.font.family
3071 << context.font.series
3073 << context.font.shape << "\n";
3075 output_ert_inset(os, "{", context);
3076 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3078 output_ert_inset(os, "}", context);
3084 if (t.cat() == catEnd) {
3085 if (flags & FLAG_BRACE_LAST) {
3088 cerr << "stray '}' in text\n";
3089 output_ert_inset(os, "}", context);
3093 if (t.cat() == catComment) {
3094 parse_comment(p, os, t, context);
3099 // control sequences
3102 if (t.cs() == "(" || t.cs() == "[") {
3103 bool const simple = t.cs() == "(";
3104 context.check_layout(os);
3105 begin_inset(os, "Formula");
3106 os << " \\" << t.cs();
3107 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3108 os << '\\' << (simple ? ')' : ']');
3111 // Prevent the conversion of a line break to a
3112 // space (bug 7668). This does not change the
3113 // output, but looks ugly in LyX.
3114 eat_whitespace(p, os, context, false);
3119 if (t.cs() == "begin") {
3120 parse_environment(p, os, outer, last_env,
3125 if (t.cs() == "end") {
3126 if (flags & FLAG_END) {
3127 // eat environment name
3128 string const name = p.getArg('{', '}');
3129 if (name != active_environment())
3130 cerr << "\\end{" + name + "} does not match \\begin{"
3131 + active_environment() + "}\n";
3134 p.error("found 'end' unexpectedly");
3138 // "item" by default, but could be something else
3139 if (t.cs() == context.layout->itemcommand()) {
3141 if (context.layout->labeltype == LABEL_MANUAL) {
3142 // FIXME: This swallows comments, but we cannot use
3143 // eat_whitespace() since we must not output
3144 // anything before the item.
3145 p.skip_spaces(true);
3146 s = p.verbatimOption();
3148 p.skip_spaces(false);
3150 context.check_layout(os);
3151 if (context.has_item) {
3152 // An item in an unknown list-like environment
3153 // FIXME: Do this in check_layout()!
3154 context.has_item = false;
3155 string item = "\\" + context.layout->itemcommand();
3158 output_ert_inset(os, item, context);
3160 if (context.layout->labeltype != LABEL_MANUAL)
3161 output_arguments(os, p, outer, false, "item", context,
3162 context.layout->itemargs());
3163 if (!context.list_extra_stuff.empty()) {
3164 os << context.list_extra_stuff;
3165 context.list_extra_stuff.clear();
3167 else if (!s.empty()) {
3168 // LyX adds braces around the argument,
3169 // so we need to remove them here.
3170 if (s.size() > 2 && s[0] == '{' &&
3171 s[s.size()-1] == '}')
3172 s = s.substr(1, s.size()-2);
3173 // If the argument contains a space we
3174 // must put it into ERT: Otherwise LyX
3175 // would misinterpret the space as
3176 // item delimiter (bug 7663)
3177 if (contains(s, ' ')) {
3178 output_ert_inset(os, s, context);
3181 os << parse_text_snippet(p2,
3182 FLAG_BRACK_LAST, outer, context);
3184 // The space is needed to separate the
3185 // item from the rest of the sentence.
3187 eat_whitespace(p, os, context, false);
3192 if (t.cs() == "bibitem") {
3194 context.check_layout(os);
3195 eat_whitespace(p, os, context, false);
3196 string label = p.verbatimOption();
3197 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3198 bool const literal = !lbl.first;
3199 label = literal ? subst(label, "\n", " ") : lbl.second;
3200 string lit = literal ? "\"true\"" : "\"false\"";
3201 string key = convert_literate_command_inset_arg(p.verbatim_item());
3202 begin_command_inset(os, "bibitem", "bibitem");
3203 os << "label \"" << label << "\"\n"
3204 << "key \"" << key << "\"\n"
3205 << "literal " << lit << "\n";
3211 // catch the case of \def\inputGnumericTable
3213 if (t.cs() == "def") {
3214 Token second = p.next_token();
3215 if (second.cs() == "inputGnumericTable") {
3219 Token third = p.get_token();
3221 if (third.cs() == "input") {
3225 string name = normalize_filename(p.verbatim_item());
3226 string const path = getMasterFilePath(true);
3227 // We want to preserve relative / absolute filenames,
3228 // therefore path is only used for testing
3229 // The file extension is in every case ".tex".
3230 // So we need to remove this extension and check for
3231 // the original one.
3232 name = removeExtension(name);
3233 if (!makeAbsPath(name, path).exists()) {
3234 char const * const Gnumeric_formats[] = {"gnumeric",
3236 string const Gnumeric_name =
3237 find_file(name, path, Gnumeric_formats);
3238 if (!Gnumeric_name.empty())
3239 name = Gnumeric_name;
3241 FileName const absname = makeAbsPath(name, path);
3242 if (absname.exists()) {
3243 fix_child_filename(name);
3244 copy_file(absname, name);
3246 cerr << "Warning: Could not find file '"
3247 << name << "'." << endl;
3248 context.check_layout(os);
3249 begin_inset(os, "External\n\ttemplate ");
3250 os << "GnumericSpreadsheet\n\tfilename "
3253 context.check_layout(os);
3255 // register the packages that are automatically loaded
3256 // by the Gnumeric template
3257 registerExternalTemplatePackages("GnumericSpreadsheet");
3262 parse_macro(p, os, context);
3266 if (t.cs() == "noindent") {
3268 context.add_par_extra_stuff("\\noindent\n");
3272 if (t.cs() == "appendix") {
3273 context.add_par_extra_stuff("\\start_of_appendix\n");
3274 // We need to start a new paragraph. Otherwise the
3275 // appendix in 'bla\appendix\chapter{' would start
3277 context.new_paragraph(os);
3278 // We need to make sure that the paragraph is
3279 // generated even if it is empty. Otherwise the
3280 // appendix in '\par\appendix\par\chapter{' would
3282 context.check_layout(os);
3283 // FIXME: This is a hack to prevent paragraph
3284 // deletion if it is empty. Handle this better!
3285 output_comment(p, os,
3286 "dummy comment inserted by tex2lyx to "
3287 "ensure that this paragraph is not empty",
3289 // Both measures above may generate an additional
3290 // empty paragraph, but that does not hurt, because
3291 // whitespace does not matter here.
3292 eat_whitespace(p, os, context, true);
3296 // Must catch empty dates before findLayout is called below
3297 if (t.cs() == "date") {
3298 eat_whitespace(p, os, context, false);
3300 string const date = p.verbatim_item();
3303 preamble.suppressDate(true);
3306 preamble.suppressDate(false);
3307 if (context.new_layout_allowed &&
3308 (newlayout = findLayout(context.textclass,
3311 output_command_layout(os, p, outer,
3312 context, newlayout);
3313 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3314 if (!preamble.titleLayoutFound())
3315 preamble.titleLayoutFound(newlayout->intitle);
3316 set<string> const & req = newlayout->requires();
3317 set<string>::const_iterator it = req.begin();
3318 set<string>::const_iterator en = req.end();
3319 for (; it != en; ++it)
3320 preamble.registerAutomaticallyLoadedPackage(*it);
3322 output_ert_inset(os,
3323 "\\date{" + p.verbatim_item() + '}',
3329 // Before we look for the layout name with star and alone below, we check the layouts including
3330 // the LateXParam, which might be one or several options or a star.
3331 // The single '=' is meant here.
3332 if (context.new_layout_allowed &&
3333 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3334 // store the latexparam here. This is eaten in output_command_layout
3335 context.latexparam = newlayout->latexparam();
3337 output_command_layout(os, p, outer, context, newlayout);
3338 context.latexparam.clear();
3340 if (!preamble.titleLayoutFound())
3341 preamble.titleLayoutFound(newlayout->intitle);
3342 set<string> const & req = newlayout->requires();
3343 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3344 preamble.registerAutomaticallyLoadedPackage(*it);
3348 // Starred section headings
3349 // Must attempt to parse "Section*" before "Section".
3350 if ((p.next_token().asInput() == "*") &&
3351 context.new_layout_allowed &&
3352 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3355 output_command_layout(os, p, outer, context, newlayout);
3357 if (!preamble.titleLayoutFound())
3358 preamble.titleLayoutFound(newlayout->intitle);
3359 set<string> const & req = newlayout->requires();
3360 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3361 preamble.registerAutomaticallyLoadedPackage(*it);
3365 // Section headings and the like
3366 if (context.new_layout_allowed &&
3367 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3369 output_command_layout(os, p, outer, context, newlayout);
3371 if (!preamble.titleLayoutFound())
3372 preamble.titleLayoutFound(newlayout->intitle);
3373 set<string> const & req = newlayout->requires();
3374 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3375 preamble.registerAutomaticallyLoadedPackage(*it);
3379 if (t.cs() == "subfloat") {
3380 // the syntax is \subfloat[list entry][sub caption]{content}
3381 // if it is a table of figure depends on the surrounding float
3383 // do nothing if there is no outer float
3384 if (!float_type.empty()) {
3385 context.check_layout(os);
3387 begin_inset(os, "Float " + float_type + "\n");
3389 << "\nsideways false"
3390 << "\nstatus collapsed\n\n";
3393 bool has_caption = false;
3394 if (p.next_token().cat() != catEscape &&
3395 p.next_token().character() == '[') {
3396 p.get_token(); // eat '['
3397 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3400 // In case we have two optional args, the second is the caption.
3401 if (p.next_token().cat() != catEscape &&
3402 p.next_token().character() == '[') {
3403 p.get_token(); // eat '['
3404 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3407 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3408 // the caption comes always as the last
3410 // we must make sure that the caption gets a \begin_layout
3411 os << "\n\\begin_layout Plain Layout";
3413 begin_inset(os, "Caption Standard\n");
3414 Context newcontext(true, context.textclass,
3415 0, 0, context.font);
3416 newcontext.check_layout(os);
3417 os << caption << "\n";
3418 newcontext.check_end_layout(os);
3421 // close the layout we opened
3422 os << "\n\\end_layout";
3427 // if the float type is not supported or there is no surrounding float
3432 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3434 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3436 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3437 + "{" + p.verbatim_item() + '}', context);
3442 if (t.cs() == "xymatrix") {
3443 // we must open a new math because LyX's xy support is in math
3444 context.check_layout(os);
3445 begin_inset(os, "Formula ");
3447 os << "\\" << t.cs() << '{';
3448 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3451 preamble.registerAutomaticallyLoadedPackage("xy");
3455 if (t.cs() == "includegraphics") {
3456 bool const clip = p.next_token().asInput() == "*";
3459 string const arg = p.getArg('[', ']');
3460 map<string, string> opts;
3461 vector<string> keys;
3462 split_map(arg, opts, keys);
3464 opts["clip"] = string();
3465 string name = normalize_filename(p.verbatim_item());
3467 string const path = getMasterFilePath(true);
3468 // We want to preserve relative / absolute filenames,
3469 // therefore path is only used for testing
3470 if (!makeAbsPath(name, path).exists()) {
3471 // The file extension is probably missing.
3472 // Now try to find it out.
3473 string const dvips_name =
3474 find_file(name, path,
3475 known_dvips_graphics_formats);
3476 string const pdftex_name =
3477 find_file(name, path,
3478 known_pdftex_graphics_formats);
3479 if (!dvips_name.empty()) {
3480 if (!pdftex_name.empty()) {
3481 cerr << "This file contains the "
3483 "\"\\includegraphics{"
3485 "However, files\n\""
3486 << dvips_name << "\" and\n\""
3487 << pdftex_name << "\"\n"
3488 "both exist, so I had to make a "
3489 "choice and took the first one.\n"
3490 "Please move the unwanted one "
3491 "someplace else and try again\n"
3492 "if my choice was wrong."
3496 } else if (!pdftex_name.empty()) {
3502 FileName const absname = makeAbsPath(name, path);
3503 if (absname.exists()) {
3504 fix_child_filename(name);
3505 copy_file(absname, name);
3507 cerr << "Warning: Could not find graphics file '"
3508 << name << "'." << endl;
3510 context.check_layout(os);
3511 begin_inset(os, "Graphics ");
3512 os << "\n\tfilename " << name << '\n';
3513 if (opts.find("width") != opts.end())
3515 << translate_len(opts["width"]) << '\n';
3516 if (opts.find("height") != opts.end())
3518 << translate_len(opts["height"]) << '\n';
3519 if (opts.find("scale") != opts.end()) {
3520 istringstream iss(opts["scale"]);
3524 os << "\tscale " << val << '\n';
3526 if (opts.find("angle") != opts.end()) {
3527 os << "\trotateAngle "
3528 << opts["angle"] << '\n';
3529 vector<string>::const_iterator a =
3530 find(keys.begin(), keys.end(), "angle");
3531 vector<string>::const_iterator s =
3532 find(keys.begin(), keys.end(), "width");
3533 if (s == keys.end())
3534 s = find(keys.begin(), keys.end(), "height");
3535 if (s == keys.end())
3536 s = find(keys.begin(), keys.end(), "scale");
3537 if (s != keys.end() && distance(s, a) > 0)
3538 os << "\tscaleBeforeRotation\n";
3540 if (opts.find("origin") != opts.end()) {
3542 string const opt = opts["origin"];
3543 if (opt.find('l') != string::npos) ss << "left";
3544 if (opt.find('r') != string::npos) ss << "right";
3545 if (opt.find('c') != string::npos) ss << "center";
3546 if (opt.find('t') != string::npos) ss << "Top";
3547 if (opt.find('b') != string::npos) ss << "Bottom";
3548 if (opt.find('B') != string::npos) ss << "Baseline";
3549 if (!ss.str().empty())
3550 os << "\trotateOrigin " << ss.str() << '\n';
3552 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3554 if (opts.find("keepaspectratio") != opts.end())
3555 os << "\tkeepAspectRatio\n";
3556 if (opts.find("clip") != opts.end())
3558 if (opts.find("draft") != opts.end())
3560 if (opts.find("bb") != opts.end())
3561 os << "\tBoundingBox "
3562 << opts["bb"] << '\n';
3563 int numberOfbbOptions = 0;
3564 if (opts.find("bbllx") != opts.end())
3565 numberOfbbOptions++;
3566 if (opts.find("bblly") != opts.end())
3567 numberOfbbOptions++;
3568 if (opts.find("bburx") != opts.end())
3569 numberOfbbOptions++;
3570 if (opts.find("bbury") != opts.end())
3571 numberOfbbOptions++;
3572 if (numberOfbbOptions == 4)
3573 os << "\tBoundingBox "
3574 << opts["bbllx"] << " " << opts["bblly"] << " "
3575 << opts["bburx"] << " " << opts["bbury"] << '\n';
3576 else if (numberOfbbOptions > 0)
3577 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3578 numberOfbbOptions = 0;
3579 if (opts.find("natwidth") != opts.end())
3580 numberOfbbOptions++;
3581 if (opts.find("natheight") != opts.end())
3582 numberOfbbOptions++;
3583 if (numberOfbbOptions == 2)
3584 os << "\tBoundingBox 0bp 0bp "
3585 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3586 else if (numberOfbbOptions > 0)
3587 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3588 ostringstream special;
3589 if (opts.find("hiresbb") != opts.end())
3590 special << "hiresbb,";
3591 if (opts.find("trim") != opts.end())
3593 if (opts.find("viewport") != opts.end())
3594 special << "viewport=" << opts["viewport"] << ',';
3595 if (opts.find("totalheight") != opts.end())
3596 special << "totalheight=" << opts["totalheight"] << ',';
3597 if (opts.find("type") != opts.end())
3598 special << "type=" << opts["type"] << ',';
3599 if (opts.find("ext") != opts.end())
3600 special << "ext=" << opts["ext"] << ',';
3601 if (opts.find("read") != opts.end())
3602 special << "read=" << opts["read"] << ',';
3603 if (opts.find("command") != opts.end())
3604 special << "command=" << opts["command"] << ',';
3605 string s_special = special.str();
3606 if (!s_special.empty()) {
3607 // We had special arguments. Remove the trailing ','.
3608 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3610 // TODO: Handle the unknown settings better.
3611 // Warn about invalid options.
3612 // Check whether some option was given twice.
3614 preamble.registerAutomaticallyLoadedPackage("graphicx");
3618 if (t.cs() == "footnote" ||
3619 (t.cs() == "thanks" && context.layout->intitle)) {
3621 context.check_layout(os);
3622 begin_inset(os, "Foot\n");
3623 os << "status collapsed\n\n";
3624 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3629 if (t.cs() == "marginpar") {
3631 context.check_layout(os);
3632 begin_inset(os, "Marginal\n");
3633 os << "status collapsed\n\n";
3634 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3639 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3640 bool const use_minted = t.cs() == "mintinline";
3642 parse_listings(p, os, context, true, use_minted);
3646 if (t.cs() == "ensuremath") {
3648 context.check_layout(os);
3649 string const s = p.verbatim_item();
3650 //FIXME: this never triggers in UTF8
3651 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3654 output_ert_inset(os, "\\ensuremath{" + s + "}",
3659 else if (t.cs() == "makeindex"
3660 || (t.cs() == context.textclass.titlename()
3661 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3662 if (preamble.titleLayoutFound()) {
3664 skip_spaces_braces(p);
3666 output_ert_inset(os, t.asInput(), context);
3670 if (t.cs() == "tableofcontents"
3671 || t.cs() == "lstlistoflistings"
3672 || t.cs() == "listoflistings") {
3673 string name = t.cs();
3674 if (preamble.minted() && name == "listoflistings")
3675 name.insert(0, "lst");
3676 context.check_layout(os);
3677 begin_command_inset(os, "toc", name);
3679 skip_spaces_braces(p);
3680 if (name == "lstlistoflistings") {
3681 if (preamble.minted())
3682 preamble.registerAutomaticallyLoadedPackage("minted");
3684 preamble.registerAutomaticallyLoadedPackage("listings");
3689 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3690 context.check_layout(os);
3691 if (t.cs() == "listoffigures")
3692 begin_inset(os, "FloatList figure\n");
3694 begin_inset(os, "FloatList table\n");
3696 skip_spaces_braces(p);
3700 if (t.cs() == "listof") {
3701 p.skip_spaces(true);
3702 string const name = p.get_token().cs();
3703 if (context.textclass.floats().typeExist(name)) {
3704 context.check_layout(os);
3705 begin_inset(os, "FloatList ");
3708 p.get_token(); // swallow second arg
3710 output_ert_inset(os, "\\listof{" + name + "}", context);
3714 if ((where = is_known(t.cs(), known_text_font_families))) {
3715 parse_text_attributes(p, os, FLAG_ITEM, outer,
3716 context, "\\family", context.font.family,
3717 known_coded_font_families[where - known_text_font_families]);
3721 // beamer has a \textbf<overlay>{} inset
3722 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3723 parse_text_attributes(p, os, FLAG_ITEM, outer,
3724 context, "\\series", context.font.series,
3725 known_coded_font_series[where - known_text_font_series]);
3729 // beamer has a \textit<overlay>{} inset
3730 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3731 parse_text_attributes(p, os, FLAG_ITEM, outer,
3732 context, "\\shape", context.font.shape,
3733 known_coded_font_shapes[where - known_text_font_shapes]);
3737 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3738 context.check_layout(os);
3739 TeXFont oldFont = context.font;
3740 context.font.init();
3741 context.font.size = oldFont.size;
3742 os << "\n\\family " << context.font.family << "\n";
3743 os << "\n\\series " << context.font.series << "\n";
3744 os << "\n\\shape " << context.font.shape << "\n";
3745 if (t.cs() == "textnormal") {
3746 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3747 output_font_change(os, context.font, oldFont);
3748 context.font = oldFont;
3750 eat_whitespace(p, os, context, false);
3754 if (t.cs() == "textcolor") {
3755 // scheme is \textcolor{color name}{text}
3756 string const color = p.verbatim_item();
3757 // we support the predefined colors of the color and the xcolor package
3758 if (color == "black" || color == "blue" || color == "cyan"
3759 || color == "green" || color == "magenta" || color == "red"
3760 || color == "white" || color == "yellow") {
3761 context.check_layout(os);
3762 os << "\n\\color " << color << "\n";
3763 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3764 context.check_layout(os);
3765 os << "\n\\color inherit\n";
3766 preamble.registerAutomaticallyLoadedPackage("color");
3767 } else if (color == "brown" || color == "darkgray" || color == "gray"
3768 || color == "lightgray" || color == "lime" || color == "olive"
3769 || color == "orange" || color == "pink" || color == "purple"
3770 || color == "teal" || color == "violet") {
3771 context.check_layout(os);
3772 os << "\n\\color " << color << "\n";
3773 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3774 context.check_layout(os);
3775 os << "\n\\color inherit\n";
3776 preamble.registerAutomaticallyLoadedPackage("xcolor");
3778 // for custom defined colors
3779 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3783 if (t.cs() == "underbar" || t.cs() == "uline") {
3784 // \underbar is not 100% correct (LyX outputs \uline
3785 // of ulem.sty). The difference is that \ulem allows
3786 // line breaks, and \underbar does not.
3787 // Do NOT handle \underline.
3788 // \underbar cuts through y, g, q, p etc.,
3789 // \underline does not.
3790 context.check_layout(os);
3791 os << "\n\\bar under\n";
3792 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3793 context.check_layout(os);
3794 os << "\n\\bar default\n";
3795 preamble.registerAutomaticallyLoadedPackage("ulem");
3799 if (t.cs() == "sout") {
3800 context.check_layout(os);
3801 os << "\n\\strikeout on\n";
3802 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3803 context.check_layout(os);
3804 os << "\n\\strikeout default\n";
3805 preamble.registerAutomaticallyLoadedPackage("ulem");
3809 // beamer has an \emph<overlay>{} inset
3810 if ((t.cs() == "uuline" || t.cs() == "uwave"
3811 || t.cs() == "emph" || t.cs() == "noun"
3812 || t.cs() == "xout") && !p.hasOpt("<")) {
3813 context.check_layout(os);
3814 os << "\n\\" << t.cs() << " on\n";
3815 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3816 context.check_layout(os);
3817 os << "\n\\" << t.cs() << " default\n";
3818 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3819 preamble.registerAutomaticallyLoadedPackage("ulem");
3823 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3824 context.check_layout(os);
3825 string name = p.getArg('{', '}');
3826 string localtime = p.getArg('{', '}');
3827 preamble.registerAuthor(name);
3828 Author const & author = preamble.getAuthor(name);
3829 // from_asctime_utc() will fail if LyX decides to output the
3830 // time in the text language.
3831 time_t ptime = from_asctime_utc(localtime);
3832 if (ptime == static_cast<time_t>(-1)) {
3833 cerr << "Warning: Could not parse time `" << localtime
3834 << "´ for change tracking, using current time instead.\n";
3835 ptime = current_time();
3837 if (t.cs() == "lyxadded")
3838 os << "\n\\change_inserted ";
3840 os << "\n\\change_deleted ";
3841 os << author.bufferId() << ' ' << ptime << '\n';
3842 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3843 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3844 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3845 LaTeXPackages::isAvailable("xcolor");
3846 // No need to test for luatex, since luatex comes in
3847 // two flavours (dvi and pdf), like latex, and those
3848 // are detected by pdflatex.
3849 if (pdflatex || xetex) {
3851 preamble.registerAutomaticallyLoadedPackage("ulem");
3852 preamble.registerAutomaticallyLoadedPackage("xcolor");
3853 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3857 preamble.registerAutomaticallyLoadedPackage("dvipost");
3858 } else if (xcolorulem) {
3859 preamble.registerAutomaticallyLoadedPackage("ulem");
3860 preamble.registerAutomaticallyLoadedPackage("xcolor");
3866 if (t.cs() == "textipa") {
3867 context.check_layout(os);
3868 begin_inset(os, "IPA\n");
3869 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3870 context.merging_hyphens_allowed = false;
3871 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3872 context.merging_hyphens_allowed = merging_hyphens_allowed;
3874 preamble.registerAutomaticallyLoadedPackage("tipa");
3875 preamble.registerAutomaticallyLoadedPackage("tipx");
3879 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3880 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3881 context.check_layout(os);
3885 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3886 begin_inset(os, "IPADeco " + type + "\n");
3887 os << "status open\n";
3888 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3894 if (t.cs() == "textvertline") {
3895 // FIXME: This is not correct, \textvertline is higher than |
3901 if (t.cs() == "tone" ) {
3902 context.check_layout(os);
3903 // register the tone package
3904 preamble.registerAutomaticallyLoadedPackage("tone");
3905 string content = trimSpaceAndEol(p.verbatim_item());
3906 string command = t.asInput() + "{" + content + "}";
3907 // some tones can be detected by unicodesymbols, some need special code
3908 if (is_known(content, known_tones)) {
3909 os << "\\IPAChar " << command << "\n";
3912 // try to see whether the string is in unicodesymbols
3916 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3917 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3918 termination, rem, &req);
3922 output_ert_inset(os, to_utf8(rem), context);
3923 for (set<string>::const_iterator it = req.begin();
3924 it != req.end(); ++it)
3925 preamble.registerAutomaticallyLoadedPackage(*it);
3927 // we did not find a non-ert version
3928 output_ert_inset(os, command, context);
3932 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3933 t.cs() == "vphantom") {
3934 context.check_layout(os);
3935 if (t.cs() == "phantom")
3936 begin_inset(os, "Phantom Phantom\n");
3937 if (t.cs() == "hphantom")
3938 begin_inset(os, "Phantom HPhantom\n");
3939 if (t.cs() == "vphantom")
3940 begin_inset(os, "Phantom VPhantom\n");
3941 os << "status open\n";
3942 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3948 if (t.cs() == "href") {
3949 context.check_layout(os);
3950 string target = convert_literate_command_inset_arg(p.verbatim_item());
3951 string name = p.verbatim_item();
3952 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3953 bool const literal = !nm.first;
3954 name = literal ? subst(name, "\n", " ") : nm.second;
3955 string lit = literal ? "\"true\"" : "\"false\"";
3957 size_t i = target.find(':');
3958 if (i != string::npos) {
3959 type = target.substr(0, i + 1);
3960 if (type == "mailto:" || type == "file:")
3961 target = target.substr(i + 1);
3962 // handle the case that name is equal to target, except of "http(s)://"
3963 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3966 begin_command_inset(os, "href", "href");
3968 os << "name \"" << name << "\"\n";
3969 os << "target \"" << target << "\"\n";
3970 if (type == "mailto:" || type == "file:")
3971 os << "type \"" << type << "\"\n";
3972 os << "literal " << lit << "\n";
3974 skip_spaces_braces(p);
3978 if (t.cs() == "lyxline") {
3979 // swallow size argument (it is not used anyway)
3981 if (!context.atParagraphStart()) {
3982 // so our line is in the middle of a paragraph
3983 // we need to add a new line, lest this line
3984 // follow the other content on that line and
3985 // run off the side of the page
3986 // FIXME: This may create an empty paragraph,
3987 // but without that it would not be
3988 // possible to set noindent below.
3989 // Fortunately LaTeX does not care
3990 // about the empty paragraph.
3991 context.new_paragraph(os);
3993 if (preamble.indentParagraphs()) {
3994 // we need to unindent, lest the line be too long
3995 context.add_par_extra_stuff("\\noindent\n");
3997 context.check_layout(os);
3998 begin_command_inset(os, "line", "rule");
3999 os << "offset \"0.5ex\"\n"
4000 "width \"100line%\"\n"
4006 if (t.cs() == "rule") {
4007 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4008 string const width = p.getArg('{', '}');
4009 string const thickness = p.getArg('{', '}');
4010 context.check_layout(os);
4011 begin_command_inset(os, "line", "rule");
4012 if (!offset.empty())
4013 os << "offset \"" << translate_len(offset) << "\"\n";
4014 os << "width \"" << translate_len(width) << "\"\n"
4015 "height \"" << translate_len(thickness) << "\"\n";
4020 // handle refstyle first to catch \eqref which can also occur
4021 // without refstyle. Only recognize these commands if
4022 // refstyle.sty was found in the preamble (otherwise \eqref
4023 // and user defined ref commands could be misdetected).
4024 if ((where = is_known(t.cs(), known_refstyle_commands))
4025 && preamble.refstyle()) {
4026 context.check_layout(os);
4027 begin_command_inset(os, "ref", "formatted");
4028 os << "reference \"";
4029 os << known_refstyle_prefixes[where - known_refstyle_commands]
4031 os << convert_literate_command_inset_arg(p.verbatim_item())
4033 os << "plural \"false\"\n";
4034 os << "caps \"false\"\n";
4035 os << "noprefix \"false\"\n";
4037 preamble.registerAutomaticallyLoadedPackage("refstyle");
4041 // if refstyle is used, we must not convert \prettyref to a
4042 // formatted reference, since that would result in a refstyle command.
4043 if ((where = is_known(t.cs(), known_ref_commands)) &&
4044 (t.cs() != "prettyref" || !preamble.refstyle())) {
4045 string const opt = p.getOpt();
4047 context.check_layout(os);
4048 begin_command_inset(os, "ref",
4049 known_coded_ref_commands[where - known_ref_commands]);
4050 os << "reference \""
4051 << convert_literate_command_inset_arg(p.verbatim_item())
4053 os << "plural \"false\"\n";
4054 os << "caps \"false\"\n";
4055 os << "noprefix \"false\"\n";
4057 if (t.cs() == "vref" || t.cs() == "vpageref")
4058 preamble.registerAutomaticallyLoadedPackage("varioref");
4059 else if (t.cs() == "prettyref")
4060 preamble.registerAutomaticallyLoadedPackage("prettyref");
4062 // LyX does not yet support optional arguments of ref commands
4063 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4064 p.verbatim_item() + '}', context);
4070 is_known(t.cs(), known_natbib_commands) &&
4071 ((t.cs() != "citefullauthor" &&
4072 t.cs() != "citeyear" &&
4073 t.cs() != "citeyearpar") ||
4074 p.next_token().asInput() != "*")) {
4075 context.check_layout(os);
4076 string command = t.cs();
4077 if (p.next_token().asInput() == "*") {
4081 if (command == "citefullauthor")
4082 // alternative name for "\\citeauthor*"
4083 command = "citeauthor*";
4085 // text before the citation
4087 // text after the citation
4089 get_cite_arguments(p, true, before, after);
4091 if (command == "cite") {
4092 // \cite without optional argument means
4093 // \citet, \cite with at least one optional
4094 // argument means \citep.
4095 if (before.empty() && after.empty())
4100 if (before.empty() && after == "[]")
4101 // avoid \citet[]{a}
4103 else if (before == "[]" && after == "[]") {
4104 // avoid \citet[][]{a}
4108 bool literal = false;
4109 pair<bool, string> aft;
4110 pair<bool, string> bef;
4111 // remove the brackets around after and before
4112 if (!after.empty()) {
4114 after.erase(after.length() - 1, 1);
4115 aft = convert_latexed_command_inset_arg(after);
4116 literal = !aft.first;
4117 after = literal ? subst(after, "\n", " ") : aft.second;
4119 if (!before.empty()) {
4121 before.erase(before.length() - 1, 1);
4122 bef = convert_latexed_command_inset_arg(before);
4123 literal |= !bef.first;
4124 before = literal ? subst(before, "\n", " ") : bef.second;
4125 if (literal && !after.empty())
4126 after = subst(after, "\n", " ");
4128 string lit = literal ? "\"true\"" : "\"false\"";
4129 begin_command_inset(os, "citation", command);
4130 os << "after " << '"' << after << '"' << "\n";
4131 os << "before " << '"' << before << '"' << "\n";
4133 << convert_literate_command_inset_arg(p.verbatim_item())
4135 << "literal " << lit << "\n";
4137 // Need to set the cite engine if natbib is loaded by
4138 // the document class directly
4139 if (preamble.citeEngine() == "basic")
4140 preamble.citeEngine("natbib");
4145 && is_known(t.cs(), known_biblatex_commands)
4146 && ((t.cs() == "cite"
4147 || t.cs() == "citeauthor"
4148 || t.cs() == "Citeauthor"
4149 || t.cs() == "parencite"
4150 || t.cs() == "citetitle")
4151 || p.next_token().asInput() != "*"))
4152 || (use_biblatex_natbib
4153 && (is_known(t.cs(), known_biblatex_commands)
4154 || is_known(t.cs(), known_natbib_commands))
4155 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4156 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4157 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4158 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4159 || t.cs() == "parencite" || t.cs() == "citetitle")
4160 || p.next_token().asInput() != "*"))){
4161 context.check_layout(os);
4162 string command = t.cs();
4163 if (p.next_token().asInput() == "*") {
4168 bool const qualified = suffixIs(command, "s");
4170 command = rtrim(command, "s");
4172 // text before the citation
4174 // text after the citation
4176 get_cite_arguments(p, true, before, after, qualified);
4178 // These use natbib cmd names in LyX
4179 // for inter-citeengine compativility
4180 if (command == "citeyear")
4181 command = "citebyear";
4182 else if (command == "cite*")
4183 command = "citeyear";
4184 else if (command == "textcite")
4186 else if (command == "Textcite")
4188 else if (command == "parencite")
4190 else if (command == "Parencite")
4192 else if (command == "parencite*")
4193 command = "citeyearpar";
4194 else if (command == "smartcite")
4195 command = "footcite";
4196 else if (command == "Smartcite")
4197 command = "Footcite";
4199 string const emptyarg = qualified ? "()" : "[]";
4200 if (before.empty() && after == emptyarg)
4203 else if (before == emptyarg && after == emptyarg) {
4204 // avoid \cite[][]{a}
4208 bool literal = false;
4209 pair<bool, string> aft;
4210 pair<bool, string> bef;
4211 // remove the brackets around after and before
4212 if (!after.empty()) {
4214 after.erase(after.length() - 1, 1);
4215 aft = convert_latexed_command_inset_arg(after);
4216 literal = !aft.first;
4217 after = literal ? subst(after, "\n", " ") : aft.second;
4219 if (!before.empty()) {
4221 before.erase(before.length() - 1, 1);
4222 bef = convert_latexed_command_inset_arg(before);
4223 literal |= !bef.first;
4224 before = literal ? subst(before, "\n", " ") : bef.second;
4226 string keys, pretextlist, posttextlist;
4228 map<string, string> pres, posts, preslit, postslit;
4229 vector<string> lkeys;
4230 // text before the citation
4231 string lbefore, lbeforelit;
4232 // text after the citation
4233 string lafter, lafterlit;
4235 pair<bool, string> laft, lbef;
4237 get_cite_arguments(p, true, lbefore, lafter);
4238 // remove the brackets around after and before
4239 if (!lafter.empty()) {
4241 lafter.erase(lafter.length() - 1, 1);
4242 laft = convert_latexed_command_inset_arg(lafter);
4243 literal |= !laft.first;
4244 lafter = laft.second;
4245 lafterlit = subst(lbefore, "\n", " ");
4247 if (!lbefore.empty()) {
4248 lbefore.erase(0, 1);
4249 lbefore.erase(lbefore.length() - 1, 1);
4250 lbef = convert_latexed_command_inset_arg(lbefore);
4251 literal |= !lbef.first;
4252 lbefore = lbef.second;
4253 lbeforelit = subst(lbefore, "\n", " ");
4255 if (lbefore.empty() && lafter == "[]") {
4260 else if (lbefore == "[]" && lafter == "[]") {
4261 // avoid \cite[][]{a}
4267 lkey = p.getArg('{', '}');
4270 if (!lbefore.empty()) {
4271 pres.insert(make_pair(lkey, lbefore));
4272 preslit.insert(make_pair(lkey, lbeforelit));
4274 if (!lafter.empty()) {
4275 posts.insert(make_pair(lkey, lafter));
4276 postslit.insert(make_pair(lkey, lafterlit));
4278 lkeys.push_back(lkey);
4280 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4285 for (auto const & ptl : pres) {
4286 if (!pretextlist.empty())
4287 pretextlist += '\t';
4288 pretextlist += ptl.first + " " + ptl.second;
4290 for (auto const & potl : posts) {
4291 if (!posttextlist.empty())
4292 posttextlist += '\t';
4293 posttextlist += potl.first + " " + potl.second;
4296 keys = convert_literate_command_inset_arg(p.verbatim_item());
4299 after = subst(after, "\n", " ");
4300 if (!before.empty())
4301 before = subst(after, "\n", " ");
4303 string lit = literal ? "\"true\"" : "\"false\"";
4304 begin_command_inset(os, "citation", command);
4305 os << "after " << '"' << after << '"' << "\n";
4306 os << "before " << '"' << before << '"' << "\n";
4310 if (!pretextlist.empty())
4311 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4312 if (!posttextlist.empty())
4313 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4314 os << "literal " << lit << "\n";
4316 // Need to set the cite engine if biblatex is loaded by
4317 // the document class directly
4318 if (preamble.citeEngine() == "basic")
4319 use_biblatex_natbib ?
4320 preamble.citeEngine("biblatex-natbib")
4321 : preamble.citeEngine("biblatex");
4326 is_known(t.cs(), known_jurabib_commands) &&
4327 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4328 context.check_layout(os);
4329 string command = t.cs();
4330 if (p.next_token().asInput() == "*") {
4334 char argumentOrder = '\0';
4335 vector<string> const options =
4336 preamble.getPackageOptions("jurabib");
4337 if (find(options.begin(), options.end(),
4338 "natbiborder") != options.end())
4339 argumentOrder = 'n';
4340 else if (find(options.begin(), options.end(),
4341 "jurabiborder") != options.end())
4342 argumentOrder = 'j';
4344 // text before the citation
4346 // text after the citation
4348 get_cite_arguments(p, argumentOrder != 'j', before, after);
4350 string const citation = p.verbatim_item();
4351 if (!before.empty() && argumentOrder == '\0') {
4352 cerr << "Warning: Assuming argument order "
4353 "of jurabib version 0.6 for\n'"
4354 << command << before << after << '{'
4355 << citation << "}'.\n"
4356 "Add 'jurabiborder' to the jurabib "
4357 "package options if you used an\n"
4358 "earlier jurabib version." << endl;
4360 bool literal = false;
4361 pair<bool, string> aft;
4362 pair<bool, string> bef;
4363 // remove the brackets around after and before
4364 if (!after.empty()) {
4366 after.erase(after.length() - 1, 1);
4367 aft = convert_latexed_command_inset_arg(after);
4368 literal = !aft.first;
4369 after = literal ? subst(after, "\n", " ") : aft.second;
4371 if (!before.empty()) {
4373 before.erase(before.length() - 1, 1);
4374 bef = convert_latexed_command_inset_arg(before);
4375 literal |= !bef.first;
4376 before = literal ? subst(before, "\n", " ") : bef.second;
4377 if (literal && !after.empty())
4378 after = subst(after, "\n", " ");
4380 string lit = literal ? "\"true\"" : "\"false\"";
4381 begin_command_inset(os, "citation", command);
4382 os << "after " << '"' << after << "\"\n"
4383 << "before " << '"' << before << "\"\n"
4384 << "key " << '"' << citation << "\"\n"
4385 << "literal " << lit << "\n";
4387 // Need to set the cite engine if jurabib is loaded by
4388 // the document class directly
4389 if (preamble.citeEngine() == "basic")
4390 preamble.citeEngine("jurabib");
4394 if (t.cs() == "cite"
4395 || t.cs() == "nocite") {
4396 context.check_layout(os);
4397 string after = p.getArg('[', ']');
4398 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4399 bool const literal = !aft.first;
4400 after = literal ? subst(after, "\n", " ") : aft.second;
4401 string lit = literal ? "\"true\"" : "\"false\"";
4402 string key = convert_literate_command_inset_arg(p.verbatim_item());
4403 // store the case that it is "\nocite{*}" to use it later for
4406 begin_command_inset(os, "citation", t.cs());
4407 os << "after " << '"' << after << "\"\n"
4408 << "key " << '"' << key << "\"\n"
4409 << "literal " << lit << "\n";
4411 } else if (t.cs() == "nocite")
4416 if (t.cs() == "index" ||
4417 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4418 context.check_layout(os);
4419 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4420 p.getArg('[', ']') : "";
4421 string const kind = arg.empty() ? "idx" : arg;
4422 begin_inset(os, "Index ");
4423 os << kind << "\nstatus collapsed\n";
4424 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4427 preamble.registerAutomaticallyLoadedPackage("splitidx");
4431 if (t.cs() == "nomenclature") {
4432 context.check_layout(os);
4433 begin_command_inset(os, "nomenclature", "nomenclature");
4434 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4435 if (!prefix.empty())
4436 os << "prefix " << '"' << prefix << '"' << "\n";
4437 string symbol = p.verbatim_item();
4438 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4439 bool literal = !sym.first;
4440 string description = p.verbatim_item();
4441 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4442 literal |= !desc.first;
4444 symbol = subst(symbol, "\n", " ");
4445 description = subst(description, "\n", " ");
4447 symbol = sym.second;
4448 description = desc.second;
4450 string lit = literal ? "\"true\"" : "\"false\"";
4451 os << "symbol " << '"' << symbol;
4452 os << "\"\ndescription \""
4453 << description << "\"\n"
4454 << "literal " << lit << "\n";
4456 preamble.registerAutomaticallyLoadedPackage("nomencl");
4460 if (t.cs() == "label") {
4461 context.check_layout(os);
4462 begin_command_inset(os, "label", "label");
4464 << convert_literate_command_inset_arg(p.verbatim_item())
4470 if (t.cs() == "lyxmintcaption") {
4471 string const pos = p.getArg('[', ']');
4473 string const caption =
4474 parse_text_snippet(p, FLAG_ITEM, false,
4476 minted_nonfloat_caption = "[t]" + caption;
4478 // We already got the caption at the bottom,
4479 // so simply skip it.
4480 parse_text_snippet(p, FLAG_ITEM, false, context);
4482 eat_whitespace(p, os, context, true);
4486 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4487 context.check_layout(os);
4488 string commandname = t.cs();
4490 if (p.next_token().asInput() == "*") {
4495 begin_command_inset(os, "index_print", commandname);
4496 string const indexname = p.getArg('[', ']');
4498 if (indexname.empty())
4499 os << "type \"idx\"\n";
4501 os << "type \"" << indexname << "\"\n";
4502 os << "literal \"true\"\n";
4505 skip_spaces_braces(p);
4506 preamble.registerAutomaticallyLoadedPackage("makeidx");
4507 if (preamble.use_indices() == "true")
4508 preamble.registerAutomaticallyLoadedPackage("splitidx");
4512 if (t.cs() == "printnomenclature") {
4514 string width_type = "";
4515 context.check_layout(os);
4516 begin_command_inset(os, "nomencl_print", "printnomenclature");
4517 // case of a custom width
4519 width = p.getArg('[', ']');
4520 width = translate_len(width);
4521 width_type = "custom";
4523 // case of no custom width
4524 // the case of no custom width but the width set
4525 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4526 // because the user could have set anything, not only the width
4527 // of the longest label (which would be width_type = "auto")
4528 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4529 if (label.empty() && width_type.empty())
4530 width_type = "none";
4531 os << "set_width \"" << width_type << "\"\n";
4532 if (width_type == "custom")
4533 os << "width \"" << width << '\"';
4535 skip_spaces_braces(p);
4536 preamble.registerAutomaticallyLoadedPackage("nomencl");
4540 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4541 context.check_layout(os);
4542 begin_inset(os, "script ");
4543 os << t.cs().substr(4) << '\n';
4544 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4545 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4547 if (t.cs() == "textsubscript")
4548 preamble.registerAutomaticallyLoadedPackage("subscript");
4552 if ((where = is_known(t.cs(), known_quotes))) {
4553 context.check_layout(os);
4554 begin_inset(os, "Quotes ");
4555 string quotetype = known_coded_quotes[where - known_quotes];
4556 // try to make a smart guess about the side
4557 Token const prev = p.prev_token();
4558 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4559 && prev.character() != '\n' && prev.character() != '~');
4560 quotetype = guessQuoteStyle(quotetype, opening);
4563 // LyX adds {} after the quote, so we have to eat
4564 // spaces here if there are any before a possible
4566 eat_whitespace(p, os, context, false);
4571 if ((where = is_known(t.cs(), known_sizes)) &&
4572 context.new_layout_allowed) {
4573 context.check_layout(os);
4574 TeXFont const oldFont = context.font;
4575 context.font.size = known_coded_sizes[where - known_sizes];
4576 output_font_change(os, oldFont, context.font);
4577 eat_whitespace(p, os, context, false);
4581 if ((where = is_known(t.cs(), known_font_families)) &&
4582 context.new_layout_allowed) {
4583 context.check_layout(os);
4584 TeXFont const oldFont = context.font;
4585 context.font.family =
4586 known_coded_font_families[where - known_font_families];
4587 output_font_change(os, oldFont, context.font);
4588 eat_whitespace(p, os, context, false);
4592 if ((where = is_known(t.cs(), known_font_series)) &&
4593 context.new_layout_allowed) {
4594 context.check_layout(os);
4595 TeXFont const oldFont = context.font;
4596 context.font.series =
4597 known_coded_font_series[where - known_font_series];
4598 output_font_change(os, oldFont, context.font);
4599 eat_whitespace(p, os, context, false);
4603 if ((where = is_known(t.cs(), known_font_shapes)) &&
4604 context.new_layout_allowed) {
4605 context.check_layout(os);
4606 TeXFont const oldFont = context.font;
4607 context.font.shape =
4608 known_coded_font_shapes[where - known_font_shapes];
4609 output_font_change(os, oldFont, context.font);
4610 eat_whitespace(p, os, context, false);
4613 if ((where = is_known(t.cs(), known_old_font_families)) &&
4614 context.new_layout_allowed) {
4615 context.check_layout(os);
4616 TeXFont const oldFont = context.font;
4617 context.font.init();
4618 context.font.size = oldFont.size;
4619 context.font.family =
4620 known_coded_font_families[where - known_old_font_families];
4621 output_font_change(os, oldFont, context.font);
4622 eat_whitespace(p, os, context, false);
4626 if ((where = is_known(t.cs(), known_old_font_series)) &&
4627 context.new_layout_allowed) {
4628 context.check_layout(os);
4629 TeXFont const oldFont = context.font;
4630 context.font.init();
4631 context.font.size = oldFont.size;
4632 context.font.series =
4633 known_coded_font_series[where - known_old_font_series];
4634 output_font_change(os, oldFont, context.font);
4635 eat_whitespace(p, os, context, false);
4639 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
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.shape =
4646 known_coded_font_shapes[where - known_old_font_shapes];
4647 output_font_change(os, oldFont, context.font);
4648 eat_whitespace(p, os, context, false);
4652 if (t.cs() == "selectlanguage") {
4653 context.check_layout(os);
4654 // save the language for the case that a
4655 // \foreignlanguage is used
4656 context.font.language = babel2lyx(p.verbatim_item());
4657 os << "\n\\lang " << context.font.language << "\n";
4661 if (t.cs() == "foreignlanguage") {
4662 string const lang = babel2lyx(p.verbatim_item());
4663 parse_text_attributes(p, os, FLAG_ITEM, outer,
4665 context.font.language, lang);
4669 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4670 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4671 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4673 // We have to output the whole command if it has an option
4674 // because LyX doesn't support this yet, see bug #8214,
4675 // only if there is a single option specifying a variant, we can handle it.
4677 string langopts = p.getOpt();
4678 // check if the option contains a variant, if yes, extract it
4679 string::size_type pos_var = langopts.find("variant");
4680 string::size_type i = langopts.find(',');
4681 string::size_type k = langopts.find('=', pos_var);
4682 if (pos_var != string::npos && i == string::npos) {
4684 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4685 lang = preamble.polyglossia2lyx(variant);
4686 parse_text_attributes(p, os, FLAG_ITEM, outer,
4688 context.font.language, lang);
4690 output_ert_inset(os, t.asInput() + langopts, context);
4692 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4693 parse_text_attributes(p, os, FLAG_ITEM, outer,
4695 context.font.language, lang);
4700 if (t.cs() == "inputencoding") {
4701 // nothing to write here
4702 string const enc = subst(p.verbatim_item(), "\n", " ");
4703 p.setEncoding(enc, Encoding::inputenc);
4707 if (is_known(t.cs(), known_special_chars) ||
4708 (t.cs() == "protect" &&
4709 p.next_token().cat() == catEscape &&
4710 is_known(p.next_token().cs(), known_special_protect_chars))) {
4711 // LyX sometimes puts a \protect in front, so we have to ignore it
4713 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4714 known_special_chars);
4715 context.check_layout(os);
4716 os << known_coded_special_chars[where - known_special_chars];
4717 skip_spaces_braces(p);
4721 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4722 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4723 p.next_next_token().asInput() == "-") ||
4724 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4725 // LyX sometimes puts a \protect in front, so we have to ignore it
4726 if (t.cs() == "protect")
4728 context.check_layout(os);
4729 if (t.cs() == "nobreakdash")
4730 os << "\\SpecialChar nobreakdash\n";
4732 os << "\\SpecialChar endofsentence\n";
4737 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4738 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4739 || t.cs() == "%" || t.cs() == "-") {
4740 context.check_layout(os);
4742 os << "\\SpecialChar softhyphen\n";
4748 if (t.cs() == "char") {
4749 context.check_layout(os);
4750 if (p.next_token().character() == '`') {
4752 if (p.next_token().cs() == "\"") {
4757 output_ert_inset(os, "\\char`", context);
4760 output_ert_inset(os, "\\char", context);
4765 if (t.cs() == "verb") {
4766 context.check_layout(os);
4767 // set catcodes to verbatim early, just in case.
4768 p.setCatcodes(VERBATIM_CATCODES);
4769 string delim = p.get_token().asInput();
4770 Parser::Arg arg = p.verbatimStuff(delim);
4772 output_ert_inset(os, "\\verb" + delim
4773 + arg.second + delim, context);
4775 cerr << "invalid \\verb command. Skipping" << endl;
4779 // Problem: \= creates a tabstop inside the tabbing environment
4780 // and else an accent. In the latter case we really would want
4781 // \={o} instead of \= o.
4782 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4783 output_ert_inset(os, t.asInput(), context);
4787 if (t.cs() == "\\") {
4788 context.check_layout(os);
4790 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4791 else if (p.next_token().asInput() == "*") {
4793 // getOpt() eats the following space if there
4794 // is no optional argument, but that is OK
4795 // here since it has no effect in the output.
4796 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4799 begin_inset(os, "Newline newline");
4805 if (t.cs() == "newline" ||
4806 (t.cs() == "linebreak" && !p.hasOpt())) {
4807 context.check_layout(os);
4808 begin_inset(os, "Newline ");
4811 skip_spaces_braces(p);
4815 if (t.cs() == "input" || t.cs() == "include"
4816 || t.cs() == "verbatiminput"
4817 || t.cs() == "lstinputlisting"
4818 || t.cs() == "inputminted") {
4819 string name = t.cs();
4820 if (name == "verbatiminput"
4821 && p.next_token().asInput() == "*")
4822 name += p.get_token().asInput();
4823 context.check_layout(os);
4825 if (name == "lstinputlisting" && p.hasOpt()) {
4826 lstparams = p.getArg('[', ']');
4827 lstparams = subst(lstparams, "\n", " ");
4828 } else if (name == "inputminted") {
4829 name = "lstinputlisting";
4830 string const lang = p.getArg('{', '}');
4831 if (lang != "tex") {
4832 string cmd = "\\inputminted{" + lang + "}{";
4833 cmd += p.getArg('{', '}') + "}";
4834 output_ert_inset(os, cmd, context);
4837 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4838 minted_nonfloat_caption.erase(0,3);
4839 // extract label and caption from the already produced LyX code
4840 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4841 string const caption = nfc.front();
4843 vector<string>::iterator it =
4844 find(nfc.begin(), nfc.end(), "LatexCommand label");
4845 if (it != nfc.end()) {
4847 if (it != nfc.end())
4849 label = support::split(label, '"');
4852 minted_nonfloat_caption.clear();
4853 lstparams = "caption=" + caption;
4855 lstparams += ",label=" + label;
4856 lstparams = subst(lstparams, "\n", " ");
4859 string filename(normalize_filename(p.getArg('{', '}')));
4860 string const path = getMasterFilePath(true);
4861 // We want to preserve relative / absolute filenames,
4862 // therefore path is only used for testing
4863 if ((t.cs() == "include" || t.cs() == "input") &&
4864 !makeAbsPath(filename, path).exists()) {
4865 // The file extension is probably missing.
4866 // Now try to find it out.
4867 string const tex_name =
4868 find_file(filename, path,
4869 known_tex_extensions);
4870 if (!tex_name.empty())
4871 filename = tex_name;
4873 bool external = false;
4875 if (makeAbsPath(filename, path).exists()) {
4876 string const abstexname =
4877 makeAbsPath(filename, path).absFileName();
4878 string const absfigname =
4879 changeExtension(abstexname, ".fig");
4880 fix_child_filename(filename);
4881 string const lyxname = changeExtension(filename,
4882 roundtripMode() ? ".lyx.lyx" : ".lyx");
4883 string const abslyxname = makeAbsPath(
4884 lyxname, getParentFilePath(false)).absFileName();
4886 if (!skipChildren())
4887 external = FileName(absfigname).exists();
4888 if (t.cs() == "input" && !skipChildren()) {
4889 string const ext = getExtension(abstexname);
4891 // Combined PS/LaTeX:
4892 // x.eps, x.pstex_t (old xfig)
4893 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4894 FileName const absepsname(
4895 changeExtension(abstexname, ".eps"));
4896 FileName const abspstexname(
4897 changeExtension(abstexname, ".pstex"));
4898 bool const xfigeps =
4899 (absepsname.exists() ||
4900 abspstexname.exists()) &&
4903 // Combined PDF/LaTeX:
4904 // x.pdf, x.pdftex_t (old xfig)
4905 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4906 FileName const abspdfname(
4907 changeExtension(abstexname, ".pdf"));
4908 bool const xfigpdf =
4909 abspdfname.exists() &&
4910 (ext == "pdftex_t" || ext == "pdf_t");
4914 // Combined PS/PDF/LaTeX:
4915 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4916 string const absbase2(
4917 removeExtension(abstexname) + "_pspdftex");
4918 FileName const abseps2name(
4919 addExtension(absbase2, ".eps"));
4920 FileName const abspdf2name(
4921 addExtension(absbase2, ".pdf"));
4922 bool const xfigboth =
4923 abspdf2name.exists() &&
4924 abseps2name.exists() && ext == "pspdftex";
4926 xfig = xfigpdf || xfigeps || xfigboth;
4927 external = external && xfig;
4930 outname = changeExtension(filename, ".fig");
4931 FileName abssrc(changeExtension(abstexname, ".fig"));
4932 copy_file(abssrc, outname);
4934 // Don't try to convert, the result
4935 // would be full of ERT.
4937 FileName abssrc(abstexname);
4938 copy_file(abssrc, outname);
4939 } else if (t.cs() != "verbatiminput" &&
4941 tex2lyx(abstexname, FileName(abslyxname),
4944 // no need to call copy_file
4945 // tex2lyx creates the file
4948 FileName abssrc(abstexname);
4949 copy_file(abssrc, outname);
4952 cerr << "Warning: Could not find included file '"
4953 << filename << "'." << endl;
4957 begin_inset(os, "External\n");
4958 os << "\ttemplate XFig\n"
4959 << "\tfilename " << outname << '\n';
4960 registerExternalTemplatePackages("XFig");
4962 begin_command_inset(os, "include", name);
4963 outname = subst(outname, "\"", "\\\"");
4964 os << "preview false\n"
4965 "filename \"" << outname << "\"\n";
4966 if (!lstparams.empty())
4967 os << "lstparams \"" << lstparams << "\"\n";
4968 if (t.cs() == "verbatiminput")
4969 preamble.registerAutomaticallyLoadedPackage("verbatim");
4975 if (t.cs() == "bibliographystyle") {
4976 // store new bibliographystyle
4977 bibliographystyle = p.verbatim_item();
4978 // If any other command than \bibliography, \addcontentsline
4979 // and \nocite{*} follows, we need to output the style
4980 // (because it might be used by that command).
4981 // Otherwise, it will automatically be output by LyX.
4984 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4985 if (t2.cat() == catBegin)
4987 if (t2.cat() != catEscape)
4989 if (t2.cs() == "nocite") {
4990 if (p.getArg('{', '}') == "*")
4992 } else if (t2.cs() == "bibliography")
4994 else if (t2.cs() == "phantomsection") {
4998 else if (t2.cs() == "addcontentsline") {
4999 // get the 3 arguments of \addcontentsline
5002 contentslineContent = p.getArg('{', '}');
5003 // if the last argument is not \refname we must output
5004 if (contentslineContent == "\\refname")
5011 output_ert_inset(os,
5012 "\\bibliographystyle{" + bibliographystyle + '}',
5018 if (t.cs() == "phantomsection") {
5019 // we only support this if it occurs between
5020 // \bibliographystyle and \bibliography
5021 if (bibliographystyle.empty())
5022 output_ert_inset(os, "\\phantomsection", context);
5026 if (t.cs() == "addcontentsline") {
5027 context.check_layout(os);
5028 // get the 3 arguments of \addcontentsline
5029 string const one = p.getArg('{', '}');
5030 string const two = p.getArg('{', '}');
5031 string const three = p.getArg('{', '}');
5032 // only if it is a \refname, we support if for the bibtex inset
5033 if (contentslineContent != "\\refname") {
5034 output_ert_inset(os,
5035 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5041 else if (t.cs() == "bibliography") {
5042 context.check_layout(os);
5044 begin_command_inset(os, "bibtex", "bibtex");
5045 if (!btprint.empty()) {
5046 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5047 // clear the string because the next BibTeX inset can be without the
5048 // \nocite{*} option
5051 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5052 // Do we have addcontentsline?
5053 if (contentslineContent == "\\refname") {
5054 BibOpts = "bibtotoc";
5055 // clear string because next BibTeX inset can be without addcontentsline
5056 contentslineContent.clear();
5058 // Do we have a bibliographystyle set?
5059 if (!bibliographystyle.empty()) {
5060 if (BibOpts.empty())
5061 BibOpts = normalize_filename(bibliographystyle);
5063 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5064 // clear it because each bibtex entry has its style
5065 // and we need an empty string to handle \phantomsection
5066 bibliographystyle.clear();
5068 os << "options " << '"' << BibOpts << '"' << "\n";
5073 if (t.cs() == "printbibliography") {
5074 context.check_layout(os);
5076 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5077 vector<string> opts = getVectorFromString(bbloptions);
5078 vector<string>::iterator it =
5079 find(opts.begin(), opts.end(), "heading=bibintoc");
5080 if (it != opts.end()) {
5082 BibOpts = "bibtotoc";
5084 bbloptions = getStringFromVector(opts);
5085 begin_command_inset(os, "bibtex", "bibtex");
5086 if (!btprint.empty()) {
5087 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5088 // clear the string because the next BibTeX inset can be without the
5089 // \nocite{*} option
5093 for (auto const & bf : preamble.biblatex_bibliographies) {
5094 if (!bibfiles.empty())
5096 bibfiles += normalize_filename(bf);
5098 if (!bibfiles.empty())
5099 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5100 // Do we have addcontentsline?
5101 if (contentslineContent == "\\refname") {
5102 BibOpts = "bibtotoc";
5103 // clear string because next BibTeX inset can be without addcontentsline
5104 contentslineContent.clear();
5106 os << "options " << '"' << BibOpts << '"' << "\n";
5107 if (!bbloptions.empty())
5108 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5110 need_commentbib = false;
5114 if (t.cs() == "bibbysection") {
5115 context.check_layout(os);
5117 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5118 vector<string> opts = getVectorFromString(bbloptions);
5119 vector<string>::iterator it =
5120 find(opts.begin(), opts.end(), "heading=bibintoc");
5121 if (it != opts.end()) {
5123 BibOpts = "bibtotoc";
5125 bbloptions = getStringFromVector(opts);
5126 begin_command_inset(os, "bibtex", "bibtex");
5127 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5129 for (auto const & bf : preamble.biblatex_bibliographies) {
5130 if (!bibfiles.empty())
5132 bibfiles += normalize_filename(bf);
5134 if (!bibfiles.empty())
5135 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5136 os << "options " << '"' << BibOpts << '"' << "\n";
5137 if (!bbloptions.empty())
5138 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5140 need_commentbib = false;
5144 if (t.cs() == "parbox") {
5145 // Test whether this is an outer box of a shaded box
5147 // swallow arguments
5148 while (p.hasOpt()) {
5150 p.skip_spaces(true);
5153 p.skip_spaces(true);
5155 if (p.next_token().cat() == catBegin)
5157 p.skip_spaces(true);
5158 Token to = p.get_token();
5159 bool shaded = false;
5160 if (to.asInput() == "\\begin") {
5161 p.skip_spaces(true);
5162 if (p.getArg('{', '}') == "shaded")
5167 parse_outer_box(p, os, FLAG_ITEM, outer,
5168 context, "parbox", "shaded");
5170 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5171 "", "", t.cs(), "", "");
5175 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5176 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5177 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5178 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5182 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5183 string backgroundcolor;
5184 preamble.registerAutomaticallyLoadedPackage("xcolor");
5185 if (t.cs() == "fcolorbox") {
5186 string const framecolor = p.getArg('{', '}');
5187 backgroundcolor = p.getArg('{', '}');
5188 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5190 backgroundcolor = p.getArg('{', '}');
5191 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5196 // FIXME: due to the compiler limit of "if" nestings
5197 // the code for the alignment was put here
5198 // put them in their own if if this is fixed
5199 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5200 || t.cs() == "shadowsize"
5201 || t.cs() == "raggedleft" || t.cs() == "centering"
5202 || t.cs() == "raggedright") {
5203 if (t.cs() == "fboxrule")
5205 if (t.cs() == "fboxsep")
5207 if (t.cs() == "shadowsize")
5209 if (t.cs() != "raggedleft" && t.cs() != "centering"
5210 && t.cs() != "raggedright") {
5211 p.skip_spaces(true);
5212 while (p.good() && p.next_token().cat() != catSpace
5213 && p.next_token().cat() != catNewline
5214 && p.next_token().cat() != catEscape) {
5215 if (t.cs() == "fboxrule")
5216 fboxrule = fboxrule + p.get_token().asInput();
5217 if (t.cs() == "fboxsep")
5218 fboxsep = fboxsep + p.get_token().asInput();
5219 if (t.cs() == "shadowsize")
5220 shadow_size = shadow_size + p.get_token().asInput();
5223 output_ert_inset(os, t.asInput(), context);
5228 //\framebox() is part of the picture environment and different from \framebox{}
5229 //\framebox{} will be parsed by parse_outer_box
5230 if (t.cs() == "framebox") {
5231 if (p.next_token().character() == '(') {
5232 //the syntax is: \framebox(x,y)[position]{content}
5233 string arg = t.asInput();
5234 arg += p.getFullParentheseArg();
5235 arg += p.getFullOpt();
5236 eat_whitespace(p, os, context, false);
5237 output_ert_inset(os, arg + '{', context);
5238 parse_text(p, os, FLAG_ITEM, outer, context);
5239 output_ert_inset(os, "}", context);
5241 //the syntax is: \framebox[width][position]{content}
5242 string special = p.getFullOpt();
5243 special += p.getOpt();
5244 parse_outer_box(p, os, FLAG_ITEM, outer,
5245 context, t.cs(), special);
5250 //\makebox() is part of the picture environment and different from \makebox{}
5251 //\makebox{} will be parsed by parse_box
5252 if (t.cs() == "makebox") {
5253 if (p.next_token().character() == '(') {
5254 //the syntax is: \makebox(x,y)[position]{content}
5255 string arg = t.asInput();
5256 arg += p.getFullParentheseArg();
5257 arg += p.getFullOpt();
5258 eat_whitespace(p, os, context, false);
5259 output_ert_inset(os, arg + '{', context);
5260 parse_text(p, os, FLAG_ITEM, outer, context);
5261 output_ert_inset(os, "}", context);
5263 //the syntax is: \makebox[width][position]{content}
5264 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5265 "", "", t.cs(), "", "");
5269 if (t.cs() == "smallskip" ||
5270 t.cs() == "medskip" ||
5271 t.cs() == "bigskip" ||
5272 t.cs() == "vfill") {
5273 context.check_layout(os);
5274 begin_inset(os, "VSpace ");
5277 skip_spaces_braces(p);
5281 if ((where = is_known(t.cs(), known_spaces))) {
5282 context.check_layout(os);
5283 begin_inset(os, "space ");
5284 os << '\\' << known_coded_spaces[where - known_spaces]
5287 // LaTeX swallows whitespace after all spaces except
5288 // "\\,". We have to do that here, too, because LyX
5289 // adds "{}" which would make the spaces significant.
5291 eat_whitespace(p, os, context, false);
5292 // LyX adds "{}" after all spaces except "\\ " and
5293 // "\\,", so we have to remove "{}".
5294 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5295 // remove the braces after "\\,", too.
5301 if (t.cs() == "newpage" ||
5302 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5303 t.cs() == "clearpage" ||
5304 t.cs() == "cleardoublepage") {
5305 context.check_layout(os);
5306 begin_inset(os, "Newpage ");
5309 skip_spaces_braces(p);
5313 if (t.cs() == "DeclareRobustCommand" ||
5314 t.cs() == "DeclareRobustCommandx" ||
5315 t.cs() == "newcommand" ||
5316 t.cs() == "newcommandx" ||
5317 t.cs() == "providecommand" ||
5318 t.cs() == "providecommandx" ||
5319 t.cs() == "renewcommand" ||
5320 t.cs() == "renewcommandx") {
5321 // DeclareRobustCommand, DeclareRobustCommandx,
5322 // providecommand and providecommandx could be handled
5323 // by parse_command(), but we need to call
5324 // add_known_command() here.
5325 string name = t.asInput();
5326 if (p.next_token().asInput() == "*") {
5327 // Starred form. Eat '*'
5331 string const command = p.verbatim_item();
5332 string const opt1 = p.getFullOpt();
5333 string const opt2 = p.getFullOpt();
5334 add_known_command(command, opt1, !opt2.empty());
5335 string const ert = name + '{' + command + '}' +
5337 '{' + p.verbatim_item() + '}';
5339 if (t.cs() == "DeclareRobustCommand" ||
5340 t.cs() == "DeclareRobustCommandx" ||
5341 t.cs() == "providecommand" ||
5342 t.cs() == "providecommandx" ||
5343 name[name.length()-1] == '*')
5344 output_ert_inset(os, ert, context);
5346 context.check_layout(os);
5347 begin_inset(os, "FormulaMacro");
5354 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5355 // let could be handled by parse_command(),
5356 // but we need to call add_known_command() here.
5357 string ert = t.asInput();
5360 if (p.next_token().cat() == catBegin) {
5361 name = p.verbatim_item();
5362 ert += '{' + name + '}';
5364 name = p.verbatim_item();
5369 if (p.next_token().cat() == catBegin) {
5370 command = p.verbatim_item();
5371 ert += '{' + command + '}';
5373 command = p.verbatim_item();
5376 // If command is known, make name known too, to parse
5377 // its arguments correctly. For this reason we also
5378 // have commands in syntax.default that are hardcoded.
5379 CommandMap::iterator it = known_commands.find(command);
5380 if (it != known_commands.end())
5381 known_commands[t.asInput()] = it->second;
5382 output_ert_inset(os, ert, context);
5386 if (t.cs() == "hspace" || t.cs() == "vspace") {
5389 string name = t.asInput();
5390 string const length = p.verbatim_item();
5393 bool valid = splitLatexLength(length, valstring, unit);
5394 bool known_hspace = false;
5395 bool known_vspace = false;
5396 bool known_unit = false;
5399 istringstream iss(valstring);
5402 if (t.cs()[0] == 'h') {
5403 if (unit == "\\fill") {
5408 known_hspace = true;
5411 if (unit == "\\smallskipamount") {
5413 known_vspace = true;
5414 } else if (unit == "\\medskipamount") {
5416 known_vspace = true;
5417 } else if (unit == "\\bigskipamount") {
5419 known_vspace = true;
5420 } else if (unit == "\\fill") {
5422 known_vspace = true;
5426 if (!known_hspace && !known_vspace) {
5427 switch (unitFromString(unit)) {
5443 //unitFromString(unit) fails for relative units like Length::PCW
5444 // therefore handle them separately
5445 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5446 || unit == "\\textwidth" || unit == "\\linewidth"
5447 || unit == "\\textheight" || unit == "\\paperheight"
5448 || unit == "\\baselineskip")
5456 // check for glue lengths
5457 bool is_gluelength = false;
5458 string gluelength = length;
5459 string::size_type i = length.find(" minus");
5460 if (i == string::npos) {
5461 i = length.find(" plus");
5462 if (i != string::npos)
5463 is_gluelength = true;
5465 is_gluelength = true;
5466 // if yes transform "9xx minus 8yy plus 7zz"
5468 if (is_gluelength) {
5469 i = gluelength.find(" minus");
5470 if (i != string::npos)
5471 gluelength.replace(i, 7, "-");
5472 i = gluelength.find(" plus");
5473 if (i != string::npos)
5474 gluelength.replace(i, 6, "+");
5477 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5478 // Literal horizontal length or known variable
5479 context.check_layout(os);
5480 begin_inset(os, "space ");
5488 if (known_unit && !known_hspace)
5489 os << "\n\\length " << translate_len(length);
5491 os << "\n\\length " << gluelength;
5493 } else if (known_unit || known_vspace || is_gluelength) {
5494 // Literal vertical length or known variable
5495 context.check_layout(os);
5496 begin_inset(os, "VSpace ");
5499 if (known_unit && !known_vspace)
5500 os << translate_len(length);
5507 // LyX can't handle other length variables in Inset VSpace/space
5512 output_ert_inset(os, name + '{' + unit + '}', context);
5513 else if (value == -1.0)
5514 output_ert_inset(os, name + "{-" + unit + '}', context);
5516 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5518 output_ert_inset(os, name + '{' + length + '}', context);
5523 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5524 // might be one or several options or a star.
5525 // The single '=' is meant here.
5526 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5530 context.check_layout(os);
5531 // store the latexparam here. This is eaten in parse_text_in_inset
5532 context.latexparam = newinsetlayout->latexparam();
5533 docstring name = newinsetlayout->name();
5534 bool const caption = name.find(from_ascii("Caption:")) == 0;
5536 // Already done for floating minted listings.
5537 if (minted_float.empty()) {
5538 begin_inset(os, "Caption ");
5539 os << to_utf8(name.substr(8)) << '\n';
5542 // FIXME: what do we do if the prefix is not Flex: ?
5543 if (prefixIs(name, from_ascii("Flex:")))
5545 begin_inset(os, "Flex ");
5546 os << to_utf8(name) << '\n'
5547 << "status collapsed\n";
5549 if (!minted_float.empty()) {
5550 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5551 } else if (newinsetlayout->isPassThru()) {
5552 // set catcodes to verbatim early, just in case.
5553 p.setCatcodes(VERBATIM_CATCODES);
5554 string delim = p.get_token().asInput();
5556 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5557 //FIXME: handle error condition
5558 string const arg = p.verbatimStuff("}").second;
5559 Context newcontext(true, context.textclass);
5560 if (newinsetlayout->forcePlainLayout())
5561 newcontext.layout = &context.textclass.plainLayout();
5562 output_ert(os, arg, newcontext);
5564 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5565 context.latexparam.clear();
5568 // Minted caption insets are not closed here because
5569 // we collect everything into the caption.
5570 if (minted_float.empty())
5575 // The single '=' is meant here.
5576 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5580 context.check_layout(os);
5581 docstring const name = newinsetlayout->name();
5582 bool const caption = name.find(from_ascii("Caption:")) == 0;
5584 // Already done for floating minted listings.
5585 if (minted_float.empty()) {
5586 begin_inset(os, "Caption ");
5587 os << to_utf8(name.substr(8)) << '\n';
5590 begin_inset(os, "Flex ");
5591 os << to_utf8(name) << '\n'
5592 << "status collapsed\n";
5594 if (!minted_float.empty()) {
5595 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5596 } else if (newinsetlayout->isPassThru()) {
5597 // set catcodes to verbatim early, just in case.
5598 p.setCatcodes(VERBATIM_CATCODES);
5599 string delim = p.get_token().asInput();
5601 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5602 //FIXME: handle error condition
5603 string const arg = p.verbatimStuff("}").second;
5604 Context newcontext(true, context.textclass);
5605 if (newinsetlayout->forcePlainLayout())
5606 newcontext.layout = &context.textclass.plainLayout();
5607 output_ert(os, arg, newcontext);
5609 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5612 // Minted caption insets are not closed here because
5613 // we collect everything into the caption.
5614 if (minted_float.empty())
5619 if (t.cs() == "includepdf") {
5621 string const arg = p.getArg('[', ']');
5622 map<string, string> opts;
5623 vector<string> keys;
5624 split_map(arg, opts, keys);
5625 string name = normalize_filename(p.verbatim_item());
5626 string const path = getMasterFilePath(true);
5627 // We want to preserve relative / absolute filenames,
5628 // therefore path is only used for testing
5629 if (!makeAbsPath(name, path).exists()) {
5630 // The file extension is probably missing.
5631 // Now try to find it out.
5632 char const * const pdfpages_format[] = {"pdf", 0};
5633 string const pdftex_name =
5634 find_file(name, path, pdfpages_format);
5635 if (!pdftex_name.empty()) {
5640 FileName const absname = makeAbsPath(name, path);
5641 if (absname.exists())
5643 fix_child_filename(name);
5644 copy_file(absname, name);
5646 cerr << "Warning: Could not find file '"
5647 << name << "'." << endl;
5649 context.check_layout(os);
5650 begin_inset(os, "External\n\ttemplate ");
5651 os << "PDFPages\n\tfilename "
5653 // parse the options
5654 if (opts.find("pages") != opts.end())
5655 os << "\textra LaTeX \"pages="
5656 << opts["pages"] << "\"\n";
5657 if (opts.find("angle") != opts.end())
5658 os << "\trotateAngle "
5659 << opts["angle"] << '\n';
5660 if (opts.find("origin") != opts.end()) {
5662 string const opt = opts["origin"];
5663 if (opt == "tl") ss << "topleft";
5664 if (opt == "bl") ss << "bottomleft";
5665 if (opt == "Bl") ss << "baselineleft";
5666 if (opt == "c") ss << "center";
5667 if (opt == "tc") ss << "topcenter";
5668 if (opt == "bc") ss << "bottomcenter";
5669 if (opt == "Bc") ss << "baselinecenter";
5670 if (opt == "tr") ss << "topright";
5671 if (opt == "br") ss << "bottomright";
5672 if (opt == "Br") ss << "baselineright";
5673 if (!ss.str().empty())
5674 os << "\trotateOrigin " << ss.str() << '\n';
5676 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5678 if (opts.find("width") != opts.end())
5680 << translate_len(opts["width"]) << '\n';
5681 if (opts.find("height") != opts.end())
5683 << translate_len(opts["height"]) << '\n';
5684 if (opts.find("keepaspectratio") != opts.end())
5685 os << "\tkeepAspectRatio\n";
5687 context.check_layout(os);
5688 registerExternalTemplatePackages("PDFPages");
5692 if (t.cs() == "loadgame") {
5694 string name = normalize_filename(p.verbatim_item());
5695 string const path = getMasterFilePath(true);
5696 // We want to preserve relative / absolute filenames,
5697 // therefore path is only used for testing
5698 if (!makeAbsPath(name, path).exists()) {
5699 // The file extension is probably missing.
5700 // Now try to find it out.
5701 char const * const lyxskak_format[] = {"fen", 0};
5702 string const lyxskak_name =
5703 find_file(name, path, lyxskak_format);
5704 if (!lyxskak_name.empty())
5705 name = lyxskak_name;
5707 FileName const absname = makeAbsPath(name, path);
5708 if (absname.exists())
5710 fix_child_filename(name);
5711 copy_file(absname, name);
5713 cerr << "Warning: Could not find file '"
5714 << name << "'." << endl;
5715 context.check_layout(os);
5716 begin_inset(os, "External\n\ttemplate ");
5717 os << "ChessDiagram\n\tfilename "
5720 context.check_layout(os);
5721 // after a \loadgame follows a \showboard
5722 if (p.get_token().asInput() == "showboard")
5724 registerExternalTemplatePackages("ChessDiagram");
5728 // try to see whether the string is in unicodesymbols
5729 // Only use text mode commands, since we are in text mode here,
5730 // and math commands may be invalid (bug 6797)
5731 string name = t.asInput();
5732 // handle the dingbats, cyrillic and greek
5733 if (name == "\\ding" || name == "\\textcyr" ||
5734 (name == "\\textgreek" && !preamble.usePolyglossia()))
5735 name = name + '{' + p.getArg('{', '}') + '}';
5736 // handle the ifsym characters
5737 else if (name == "\\textifsymbol") {
5738 string const optif = p.getFullOpt();
5739 string const argif = p.getArg('{', '}');
5740 name = name + optif + '{' + argif + '}';
5742 // handle the \ascii characters
5743 // the case of \ascii within braces, as LyX outputs it, is already
5744 // handled for t.cat() == catBegin
5745 else if (name == "\\ascii") {
5746 // the code is "\asci\xxx"
5747 name = "{" + name + p.get_token().asInput() + "}";
5750 // handle some TIPA special characters
5751 else if (preamble.isPackageUsed("tipa")) {
5752 if (name == "\\s") {
5753 // fromLaTeXCommand() does not yet
5754 // recognize tipa short cuts
5755 name = "\\textsyllabic";
5756 } else if (name == "\\=" &&
5757 p.next_token().asInput() == "*") {
5758 // fromLaTeXCommand() does not yet
5759 // recognize tipa short cuts
5761 name = "\\textsubbar";
5762 } else if (name == "\\textdoublevertline") {
5763 // FIXME: This is not correct,
5764 // \textvertline is higher than \textbardbl
5765 name = "\\textbardbl";
5767 } else if (name == "\\!" ) {
5768 if (p.next_token().asInput() == "b") {
5769 p.get_token(); // eat 'b'
5772 } else if (p.next_token().asInput() == "d") {
5776 } else if (p.next_token().asInput() == "g") {
5780 } else if (p.next_token().asInput() == "G") {
5782 name = "\\texthtscg";
5784 } else if (p.next_token().asInput() == "j") {
5786 name = "\\texthtbardotlessj";
5788 } else if (p.next_token().asInput() == "o") {
5790 name = "\\textbullseye";
5793 } else if (name == "\\*" ) {
5794 if (p.next_token().asInput() == "k") {
5796 name = "\\textturnk";
5798 } else if (p.next_token().asInput() == "r") {
5799 p.get_token(); // eat 'b'
5800 name = "\\textturnr";
5802 } else if (p.next_token().asInput() == "t") {
5804 name = "\\textturnt";
5806 } else if (p.next_token().asInput() == "w") {
5808 name = "\\textturnw";
5813 if ((name.size() == 2 &&
5814 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5815 p.next_token().asInput() != "*") ||
5816 is_known(name.substr(1), known_tipa_marks)) {
5817 // name is a command that corresponds to a
5818 // combining character in unicodesymbols.
5819 // Append the argument, fromLaTeXCommand()
5820 // will either convert it to a single
5821 // character or a combining sequence.
5822 name += '{' + p.verbatim_item() + '}';
5824 // now get the character from unicodesymbols
5828 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5829 Encodings::TEXT_CMD, termination, rem, &req));
5831 context.check_layout(os);
5834 output_ert_inset(os, to_utf8(rem), context);
5836 skip_spaces_braces(p);
5837 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5838 preamble.registerAutomaticallyLoadedPackage(*it);
5840 //cerr << "#: " << t << " mode: " << mode << endl;
5841 // heuristic: read up to next non-nested space
5843 string s = t.asInput();
5844 string z = p.verbatim_item();
5845 while (p.good() && z != " " && !z.empty()) {
5846 //cerr << "read: " << z << endl;
5848 z = p.verbatim_item();
5850 cerr << "found ERT: " << s << endl;
5851 output_ert_inset(os, s + ' ', context);
5854 if (t.asInput() == name &&
5855 p.next_token().asInput() == "*") {
5856 // Starred commands like \vspace*{}
5857 p.get_token(); // Eat '*'
5860 if (!parse_command(name, p, os, outer, context)) {
5861 output_ert_inset(os, name, context);
5862 // Try to handle options of unknown commands:
5863 // Look if we have an optional arguments,
5864 // and if so, put the brackets in ERT.
5865 while (p.hasOpt()) {
5866 p.get_token(); // eat '['
5867 output_ert_inset(os, "[", context);
5868 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
5869 output_ert_inset(os, "]", context);
5877 string guessLanguage(Parser & p, string const & lang)
5879 typedef std::map<std::string, size_t> LangMap;
5880 // map from language names to number of characters
5883 for (char const * const * i = supported_CJK_languages; *i; i++)
5884 used[string(*i)] = 0;
5887 Token const t = p.get_token();
5888 // comments are not counted for any language
5889 if (t.cat() == catComment)
5891 // commands are not counted as well, but we need to detect
5892 // \begin{CJK} and switch encoding if needed
5893 if (t.cat() == catEscape) {
5894 if (t.cs() == "inputencoding") {
5895 string const enc = subst(p.verbatim_item(), "\n", " ");
5896 p.setEncoding(enc, Encoding::inputenc);
5899 if (t.cs() != "begin")
5902 // Non-CJK content is counted for lang.
5903 // We do not care about the real language here:
5904 // If we have more non-CJK contents than CJK contents,
5905 // we simply use the language that was specified as
5906 // babel main language.
5907 used[lang] += t.asInput().length();
5910 // Now we are starting an environment
5912 string const name = p.getArg('{', '}');
5913 if (name != "CJK") {
5917 // It is a CJK environment
5919 /* name = */ p.getArg('{', '}');
5920 string const encoding = p.getArg('{', '}');
5921 /* mapping = */ p.getArg('{', '}');
5922 string const encoding_old = p.getEncoding();
5923 char const * const * const where =
5924 is_known(encoding, supported_CJK_encodings);
5926 p.setEncoding(encoding, Encoding::CJK);
5928 p.setEncoding("UTF-8");
5929 string const text = p.ertEnvironment("CJK");
5930 p.setEncoding(encoding_old);
5933 // ignore contents in unknown CJK encoding
5936 // the language of the text
5938 supported_CJK_languages[where - supported_CJK_encodings];
5939 used[cjk] += text.length();
5941 LangMap::const_iterator use = used.begin();
5942 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5943 if (it->second > use->second)
5950 void check_comment_bib(ostream & os, Context & context)
5952 if (!need_commentbib)
5954 // We have a bibliography database, but no bibliography with biblatex
5955 // which is completely valid. Insert a bibtex inset in a note.
5956 context.check_layout(os);
5957 begin_inset(os, "Note Note\n");
5958 os << "status open\n";
5959 os << "\\begin_layout Plain Layout\n";
5960 begin_command_inset(os, "bibtex", "bibtex");
5962 for (auto const & bf : preamble.biblatex_bibliographies) {
5963 if (!bibfiles.empty())
5965 bibfiles += normalize_filename(bf);
5967 if (!bibfiles.empty())
5968 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5969 end_inset(os);// Bibtex
5970 os << "\\end_layout\n";
5971 end_inset(os);// Note