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 parse_text_snippet(p, os, flags, outer, parent_context);
1580 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1582 parent_context.new_layout_allowed = new_layout_allowed;
1586 void parse_environment(Parser & p, ostream & os, bool outer,
1587 string & last_env, Context & parent_context)
1589 Layout const * newlayout;
1590 InsetLayout const * newinsetlayout = 0;
1591 string const name = p.getArg('{', '}');
1592 const bool is_starred = suffixIs(name, '*');
1593 string const unstarred_name = rtrim(name, "*");
1594 active_environments.push_back(name);
1596 if (is_math_env(name)) {
1597 parent_context.check_layout(os);
1598 begin_inset(os, "Formula ");
1599 os << "\\begin{" << name << "}";
1600 parse_math(p, os, FLAG_END, MATH_MODE);
1601 os << "\\end{" << name << "}";
1603 if (is_display_math_env(name)) {
1604 // Prevent the conversion of a line break to a space
1605 // (bug 7668). This does not change the output, but
1606 // looks ugly in LyX.
1607 eat_whitespace(p, os, parent_context, false);
1611 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1612 else if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1613 // We must begin a new paragraph if not already done
1614 if (! parent_context.atParagraphStart()) {
1615 parent_context.check_end_layout(os);
1616 parent_context.new_paragraph(os);
1618 // save the language in the context so that it is
1619 // handled by parse_text
1620 parent_context.font.language =
1621 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1622 parse_text(p, os, FLAG_END, outer, parent_context);
1623 // Just in case the environment is empty
1624 parent_context.extra_stuff.erase();
1625 // We must begin a new paragraph to reset the language
1626 parent_context.new_paragraph(os);
1630 else if (unstarred_name == "tabular" || name == "longtable") {
1631 eat_whitespace(p, os, parent_context, false);
1632 string width = "0pt";
1633 if (name == "tabular*") {
1634 width = lyx::translate_len(p.getArg('{', '}'));
1635 eat_whitespace(p, os, parent_context, false);
1637 parent_context.check_layout(os);
1638 begin_inset(os, "Tabular ");
1639 handle_tabular(p, os, name, width, parent_context);
1644 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1645 eat_whitespace(p, os, parent_context, false);
1646 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1647 eat_whitespace(p, os, parent_context, false);
1648 parent_context.check_layout(os);
1649 begin_inset(os, "Float " + unstarred_name + "\n");
1650 // store the float type for subfloats
1651 // subfloats only work with figures and tables
1652 if (unstarred_name == "figure")
1653 float_type = unstarred_name;
1654 else if (unstarred_name == "table")
1655 float_type = unstarred_name;
1659 os << "placement " << opt << '\n';
1660 if (contains(opt, "H"))
1661 preamble.registerAutomaticallyLoadedPackage("float");
1663 Floating const & fl = parent_context.textclass.floats()
1664 .getType(unstarred_name);
1665 if (!fl.floattype().empty() && fl.usesFloatPkg())
1666 preamble.registerAutomaticallyLoadedPackage("float");
1669 os << "wide " << convert<string>(is_starred)
1670 << "\nsideways false"
1671 << "\nstatus open\n\n";
1672 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1674 // We don't need really a new paragraph, but
1675 // we must make sure that the next item gets a \begin_layout.
1676 parent_context.new_paragraph(os);
1678 // the float is parsed thus delete the type
1682 else if (unstarred_name == "sidewaysfigure"
1683 || unstarred_name == "sidewaystable"
1684 || unstarred_name == "sidewaysalgorithm") {
1685 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1686 eat_whitespace(p, os, parent_context, false);
1687 parent_context.check_layout(os);
1688 if (unstarred_name == "sidewaysfigure")
1689 begin_inset(os, "Float figure\n");
1690 else if (unstarred_name == "sidewaystable")
1691 begin_inset(os, "Float table\n");
1692 else if (unstarred_name == "sidewaysalgorithm")
1693 begin_inset(os, "Float algorithm\n");
1695 os << "placement " << opt << '\n';
1696 if (contains(opt, "H"))
1697 preamble.registerAutomaticallyLoadedPackage("float");
1698 os << "wide " << convert<string>(is_starred)
1699 << "\nsideways true"
1700 << "\nstatus open\n\n";
1701 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1703 // We don't need really a new paragraph, but
1704 // we must make sure that the next item gets a \begin_layout.
1705 parent_context.new_paragraph(os);
1707 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1710 else if (name == "wrapfigure" || name == "wraptable") {
1711 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1712 eat_whitespace(p, os, parent_context, false);
1713 parent_context.check_layout(os);
1716 string overhang = "0col%";
1719 lines = p.getArg('[', ']');
1720 string const placement = p.getArg('{', '}');
1722 overhang = p.getArg('[', ']');
1723 string const width = p.getArg('{', '}');
1725 if (name == "wrapfigure")
1726 begin_inset(os, "Wrap figure\n");
1728 begin_inset(os, "Wrap table\n");
1729 os << "lines " << lines
1730 << "\nplacement " << placement
1731 << "\noverhang " << lyx::translate_len(overhang)
1732 << "\nwidth " << lyx::translate_len(width)
1733 << "\nstatus open\n\n";
1734 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1736 // We don't need really a new paragraph, but
1737 // we must make sure that the next item gets a \begin_layout.
1738 parent_context.new_paragraph(os);
1740 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1743 else if (name == "minipage") {
1744 eat_whitespace(p, os, parent_context, false);
1745 // Test whether this is an outer box of a shaded box
1747 // swallow arguments
1748 while (p.hasOpt()) {
1750 p.skip_spaces(true);
1753 p.skip_spaces(true);
1754 Token t = p.get_token();
1755 bool shaded = false;
1756 if (t.asInput() == "\\begin") {
1757 p.skip_spaces(true);
1758 if (p.getArg('{', '}') == "shaded")
1763 parse_outer_box(p, os, FLAG_END, outer,
1764 parent_context, name, "shaded");
1766 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1767 "", "", name, "", "");
1771 else if (name == "comment") {
1772 eat_whitespace(p, os, parent_context, false);
1773 parent_context.check_layout(os);
1774 begin_inset(os, "Note Comment\n");
1775 os << "status open\n";
1776 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1779 skip_braces(p); // eat {} that might by set by LyX behind comments
1780 preamble.registerAutomaticallyLoadedPackage("verbatim");
1783 else if (unstarred_name == "verbatim") {
1784 // FIXME: this should go in the generic code that
1785 // handles environments defined in layout file that
1786 // have "PassThru 1". However, the code over there is
1787 // already too complicated for my taste.
1788 string const ascii_name =
1789 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1790 parent_context.new_paragraph(os);
1791 Context context(true, parent_context.textclass,
1792 &parent_context.textclass[from_ascii(ascii_name)]);
1793 string s = p.verbatimEnvironment(name);
1794 output_ert(os, s, context);
1798 else if (name == "IPA") {
1799 eat_whitespace(p, os, parent_context, false);
1800 parent_context.check_layout(os);
1801 begin_inset(os, "IPA\n");
1802 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1805 preamble.registerAutomaticallyLoadedPackage("tipa");
1806 preamble.registerAutomaticallyLoadedPackage("tipx");
1809 else if (name == parent_context.textclass.titlename()
1810 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1811 parse_text(p, os, FLAG_END, outer, parent_context);
1812 // Just in case the environment is empty
1813 parent_context.extra_stuff.erase();
1814 // We must begin a new paragraph
1815 parent_context.new_paragraph(os);
1819 else if (name == "CJK") {
1820 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1821 // It is impossible to decide if a CJK environment was in its own paragraph or within
1822 // a line. We therefore always assume a paragraph since the latter is a rare case.
1823 eat_whitespace(p, os, parent_context, false);
1824 parent_context.check_end_layout(os);
1825 // store the encoding to be able to reset it
1826 string const encoding_old = p.getEncoding();
1827 string const encoding = p.getArg('{', '}');
1828 // FIXME: For some reason JIS does not work. Although the text
1829 // in tests/CJK.tex is identical with the SJIS version if you
1830 // convert both snippets using the recode command line utility,
1831 // the resulting .lyx file contains some extra characters if
1832 // you set buggy_encoding to false for JIS.
1833 bool const buggy_encoding = encoding == "JIS";
1834 if (!buggy_encoding)
1835 p.setEncoding(encoding, Encoding::CJK);
1837 // FIXME: This will read garbage, since the data is not encoded in utf8.
1838 p.setEncoding("UTF-8");
1840 // LyX only supports the same mapping for all CJK
1841 // environments, so we might need to output everything as ERT
1842 string const mapping = trim(p.getArg('{', '}'));
1843 char const * const * const where =
1844 is_known(encoding, supported_CJK_encodings);
1845 if (!buggy_encoding && !preamble.fontCJKSet())
1846 preamble.fontCJK(mapping);
1847 bool knownMapping = mapping == preamble.fontCJK();
1848 if (buggy_encoding || !knownMapping || !where) {
1849 parent_context.check_layout(os);
1850 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1852 // we must parse the content as verbatim because e.g. JIS can contain
1853 // normally invalid characters
1854 // FIXME: This works only for the most simple cases.
1855 // Since TeX control characters are not parsed,
1856 // things like comments are completely wrong.
1857 string const s = p.plainEnvironment("CJK");
1858 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1861 if (snip == "\\" || is_known(snip, known_escaped_chars))
1862 output_ert_inset(os, snip, parent_context);
1863 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1868 output_ert_inset(os, "\\end{" + name + "}",
1872 supported_CJK_languages[where - supported_CJK_encodings];
1873 // store the language because we must reset it at the end
1874 string const lang_old = parent_context.font.language;
1875 parent_context.font.language = lang;
1876 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1877 parent_context.font.language = lang_old;
1878 parent_context.new_paragraph(os);
1880 p.setEncoding(encoding_old);
1884 else if (name == "lyxgreyedout") {
1885 eat_whitespace(p, os, parent_context, false);
1886 parent_context.check_layout(os);
1887 begin_inset(os, "Note Greyedout\n");
1888 os << "status open\n";
1889 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1892 if (!preamble.notefontcolor().empty())
1893 preamble.registerAutomaticallyLoadedPackage("color");
1896 else if (name == "btSect") {
1897 eat_whitespace(p, os, parent_context, false);
1898 parent_context.check_layout(os);
1899 begin_command_inset(os, "bibtex", "bibtex");
1900 string bibstyle = "plain";
1902 bibstyle = p.getArg('[', ']');
1903 p.skip_spaces(true);
1905 string const bibfile = p.getArg('{', '}');
1906 eat_whitespace(p, os, parent_context, false);
1907 Token t = p.get_token();
1908 if (t.asInput() == "\\btPrintCited") {
1909 p.skip_spaces(true);
1910 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1912 if (t.asInput() == "\\btPrintNotCited") {
1913 p.skip_spaces(true);
1914 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1916 if (t.asInput() == "\\btPrintAll") {
1917 p.skip_spaces(true);
1918 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1920 os << "bibfiles " << '"' << bibfile << "\"\n"
1921 << "options " << '"' << bibstyle << "\"\n";
1922 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1927 else if (name == "framed" || name == "shaded") {
1928 eat_whitespace(p, os, parent_context, false);
1929 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1931 preamble.registerAutomaticallyLoadedPackage("framed");
1934 else if (name == "listing") {
1935 minted_float = "float";
1936 eat_whitespace(p, os, parent_context, false);
1937 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1939 minted_float += "=" + opt;
1940 // If something precedes \begin{minted}, we output it at the end
1941 // as a caption, in order to keep it inside the listings inset.
1942 eat_whitespace(p, os, parent_context, true);
1944 Token const & t = p.get_token();
1945 p.skip_spaces(true);
1946 string const envname = p.next_token().cat() == catBegin
1947 ? p.getArg('{', '}') : string();
1948 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1950 minted_float_has_caption = false;
1951 string content = parse_text_snippet(p, FLAG_END, outer,
1953 size_t i = content.find("\\begin_inset listings");
1954 bool minted_env = i != string::npos;
1957 caption = content.substr(0, i);
1958 content.erase(0, i);
1960 parent_context.check_layout(os);
1961 if (minted_env && minted_float_has_caption) {
1962 eat_whitespace(p, os, parent_context, true);
1963 os << content << "\n";
1964 if (!caption.empty())
1965 os << caption << "\n";
1966 os << "\n\\end_layout\n"; // close inner layout
1967 end_inset(os); // close caption inset
1968 os << "\n\\end_layout\n"; // close outer layout
1969 } else if (!caption.empty()) {
1971 begin_inset(os, "listings\n");
1972 os << "lstparams " << '"' << minted_float << '"' << '\n';
1973 os << "inline false\n";
1974 os << "status collapsed\n";
1976 os << "\n\\begin_layout Plain Layout\n";
1977 begin_inset(os, "Caption Standard\n");
1978 Context newcontext(true, parent_context.textclass,
1979 0, 0, parent_context.font);
1980 newcontext.check_layout(os);
1981 os << caption << "\n";
1982 newcontext.check_end_layout(os);
1984 os << "\n\\end_layout\n";
1985 } else if (content.empty()) {
1986 begin_inset(os, "listings\n");
1987 os << "lstparams " << '"' << minted_float << '"' << '\n';
1988 os << "inline false\n";
1989 os << "status collapsed\n";
1991 os << content << "\n";
1993 end_inset(os); // close listings inset
1994 parent_context.check_end_layout(os);
1995 parent_context.new_paragraph(os);
1997 minted_float.clear();
1998 minted_float_has_caption = false;
2001 else if (name == "lstlisting" || name == "minted") {
2002 bool use_minted = name == "minted";
2003 eat_whitespace(p, os, parent_context, false);
2004 if (use_minted && minted_float.empty()) {
2005 // look ahead for a bottom caption
2007 bool found_end_minted = false;
2008 while (!found_end_minted && p.good()) {
2009 Token const & t = p.get_token();
2011 string const envname =
2012 p.next_token().cat() == catBegin
2013 ? p.getArg('{', '}') : string();
2014 found_end_minted = t.asInput() == "\\end"
2015 && envname == "minted";
2017 eat_whitespace(p, os, parent_context, true);
2018 Token const & t = p.get_token();
2019 p.skip_spaces(true);
2020 if (t.asInput() == "\\lyxmintcaption") {
2021 string const pos = p.getArg('[', ']');
2023 string const caption =
2024 parse_text_snippet(p, FLAG_ITEM,
2025 false, parent_context);
2026 minted_nonfloat_caption = "[b]" + caption;
2027 eat_whitespace(p, os, parent_context, true);
2032 parse_listings(p, os, parent_context, false, use_minted);
2036 else if (!parent_context.new_layout_allowed)
2037 parse_unknown_environment(p, name, os, FLAG_END, outer,
2040 // Alignment and spacing settings
2041 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2042 // therefore are totally broken!
2043 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2044 // they are commands not environments. They are furthermore switches that
2045 // can be ended by another switches, but also by commands like \footnote or
2046 // \parbox. So the only safe way is to leave them untouched.
2047 // However, we support the pseudo-environments
2048 // \begin{centering} ... \end{centering}
2049 // \begin{raggedright} ... \end{raggedright}
2050 // \begin{raggedleft} ... \end{raggedleft}
2051 // since they are used by LyX in floats (for spacing reasons)
2052 else if (name == "center" || name == "centering" ||
2053 name == "flushleft" || name == "raggedright" ||
2054 name == "flushright" || name == "raggedleft" ||
2055 name == "singlespace" || name == "onehalfspace" ||
2056 name == "doublespace" || name == "spacing") {
2057 eat_whitespace(p, os, parent_context, false);
2058 // We must begin a new paragraph if not already done
2059 if (! parent_context.atParagraphStart()) {
2060 parent_context.check_end_layout(os);
2061 parent_context.new_paragraph(os);
2063 if (name == "flushleft" || name == "raggedright")
2064 parent_context.add_extra_stuff("\\align left\n");
2065 else if (name == "flushright" || name == "raggedleft")
2066 parent_context.add_extra_stuff("\\align right\n");
2067 else if (name == "center" || name == "centering")
2068 parent_context.add_extra_stuff("\\align center\n");
2069 else if (name == "singlespace")
2070 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2071 else if (name == "onehalfspace") {
2072 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2073 preamble.registerAutomaticallyLoadedPackage("setspace");
2074 } else if (name == "doublespace") {
2075 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2076 preamble.registerAutomaticallyLoadedPackage("setspace");
2077 } else if (name == "spacing") {
2078 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2079 preamble.registerAutomaticallyLoadedPackage("setspace");
2081 parse_text(p, os, FLAG_END, outer, parent_context);
2082 // Just in case the environment is empty
2083 parent_context.extra_stuff.erase();
2084 // We must begin a new paragraph to reset the alignment
2085 parent_context.new_paragraph(os);
2089 // The single '=' is meant here.
2090 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2091 eat_whitespace(p, os, parent_context, false);
2092 Context context(true, parent_context.textclass, newlayout,
2093 parent_context.layout, parent_context.font);
2094 if (parent_context.deeper_paragraph) {
2095 // We are beginning a nested environment after a
2096 // deeper paragraph inside the outer list environment.
2097 // Therefore we don't need to output a "begin deeper".
2098 context.need_end_deeper = true;
2100 parent_context.check_end_layout(os);
2101 if (last_env == name) {
2102 // we need to output a separator since LyX would export
2103 // the two environments as one otherwise (bug 5716)
2104 TeX2LyXDocClass const & textclass(parent_context.textclass);
2105 Context newcontext(true, textclass,
2106 &(textclass.defaultLayout()));
2107 newcontext.check_layout(os);
2108 begin_inset(os, "Separator plain\n");
2110 newcontext.check_end_layout(os);
2112 switch (context.layout->latextype) {
2113 case LATEX_LIST_ENVIRONMENT:
2114 context.add_par_extra_stuff("\\labelwidthstring "
2115 + p.verbatim_item() + '\n');
2118 case LATEX_BIB_ENVIRONMENT:
2119 p.verbatim_item(); // swallow next arg
2125 context.check_deeper(os);
2126 if (newlayout->keepempty) {
2127 // We need to start a new paragraph
2128 // even if it is empty.
2129 context.new_paragraph(os);
2130 context.check_layout(os);
2132 // handle known optional and required arguments
2133 if (context.layout->latextype == LATEX_ENVIRONMENT)
2134 output_arguments(os, p, outer, false, string(), context,
2135 context.layout->latexargs());
2136 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2138 output_arguments(oss, p, outer, false, string(), context,
2139 context.layout->latexargs());
2140 context.list_extra_stuff = oss.str();
2142 parse_text(p, os, FLAG_END, outer, context);
2143 if (context.layout->latextype == LATEX_ENVIRONMENT)
2144 output_arguments(os, p, outer, false, "post", context,
2145 context.layout->postcommandargs());
2146 context.check_end_layout(os);
2147 if (parent_context.deeper_paragraph) {
2148 // We must suppress the "end deeper" because we
2149 // suppressed the "begin deeper" above.
2150 context.need_end_deeper = false;
2152 context.check_end_deeper(os);
2153 parent_context.new_paragraph(os);
2155 if (!preamble.titleLayoutFound())
2156 preamble.titleLayoutFound(newlayout->intitle);
2157 set<string> const & req = newlayout->requires();
2158 set<string>::const_iterator it = req.begin();
2159 set<string>::const_iterator en = req.end();
2160 for (; it != en; ++it)
2161 preamble.registerAutomaticallyLoadedPackage(*it);
2164 // The single '=' is meant here.
2165 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2166 eat_whitespace(p, os, parent_context, false);
2167 parent_context.check_layout(os);
2168 begin_inset(os, "Flex ");
2169 os << to_utf8(newinsetlayout->name()) << '\n'
2170 << "status collapsed\n";
2171 if (newinsetlayout->isPassThru()) {
2172 string const arg = p.verbatimEnvironment(name);
2173 Context context(true, parent_context.textclass,
2174 &parent_context.textclass.plainLayout(),
2175 parent_context.layout);
2176 output_ert(os, arg, parent_context);
2178 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2182 else if (name == "appendix") {
2183 // This is no good latex style, but it works and is used in some documents...
2184 eat_whitespace(p, os, parent_context, false);
2185 parent_context.check_end_layout(os);
2186 Context context(true, parent_context.textclass, parent_context.layout,
2187 parent_context.layout, parent_context.font);
2188 context.check_layout(os);
2189 os << "\\start_of_appendix\n";
2190 parse_text(p, os, FLAG_END, outer, context);
2191 context.check_end_layout(os);
2195 else if (known_environments.find(name) != known_environments.end()) {
2196 vector<ArgumentType> arguments = known_environments[name];
2197 // The last "argument" denotes wether we may translate the
2198 // environment contents to LyX
2199 // The default required if no argument is given makes us
2200 // compatible with the reLyXre environment.
2201 ArgumentType contents = arguments.empty() ?
2204 if (!arguments.empty())
2205 arguments.pop_back();
2206 // See comment in parse_unknown_environment()
2207 bool const specialfont =
2208 (parent_context.font != parent_context.normalfont);
2209 bool const new_layout_allowed =
2210 parent_context.new_layout_allowed;
2212 parent_context.new_layout_allowed = false;
2213 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2214 outer, parent_context);
2215 if (contents == verbatim)
2216 output_ert_inset(os, p.ertEnvironment(name),
2219 parse_text_snippet(p, os, FLAG_END, outer,
2221 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2223 parent_context.new_layout_allowed = new_layout_allowed;
2227 parse_unknown_environment(p, name, os, FLAG_END, outer,
2231 active_environments.pop_back();
2235 /// parses a comment and outputs it to \p os.
2236 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2238 LASSERT(t.cat() == catComment, return);
2239 if (!t.cs().empty()) {
2240 context.check_layout(os);
2241 output_comment(p, os, t.cs(), context);
2242 if (p.next_token().cat() == catNewline) {
2243 // A newline after a comment line starts a new
2245 if (context.new_layout_allowed) {
2246 if(!context.atParagraphStart())
2247 // Only start a new paragraph if not already
2248 // done (we might get called recursively)
2249 context.new_paragraph(os);
2251 output_ert_inset(os, "\n", context);
2252 eat_whitespace(p, os, context, true);
2255 // "%\n" combination
2262 * Reads spaces and comments until the first non-space, non-comment token.
2263 * New paragraphs (double newlines or \\par) are handled like simple spaces
2264 * if \p eatParagraph is true.
2265 * Spaces are skipped, but comments are written to \p os.
2267 void eat_whitespace(Parser & p, ostream & os, Context & context,
2271 Token const & t = p.get_token();
2272 if (t.cat() == catComment)
2273 parse_comment(p, os, t, context);
2274 else if ((! eatParagraph && p.isParagraph()) ||
2275 (t.cat() != catSpace && t.cat() != catNewline)) {
2284 * Set a font attribute, parse text and reset the font attribute.
2285 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2286 * \param currentvalue Current value of the attribute. Is set to the new
2287 * value during parsing.
2288 * \param newvalue New value of the attribute
2290 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2291 Context & context, string const & attribute,
2292 string & currentvalue, string const & newvalue)
2294 context.check_layout(os);
2295 string const oldvalue = currentvalue;
2296 currentvalue = newvalue;
2297 os << '\n' << attribute << ' ' << newvalue << "\n";
2298 parse_text_snippet(p, os, flags, outer, context);
2299 context.check_layout(os);
2300 os << '\n' << attribute << ' ' << oldvalue << "\n";
2301 currentvalue = oldvalue;
2305 /// get the arguments of a natbib or jurabib citation command
2306 void get_cite_arguments(Parser & p, bool natbibOrder,
2307 string & before, string & after, bool const qualified = false)
2309 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2311 // text before the citation
2313 // text after the citation
2314 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2316 if (!after.empty()) {
2317 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2318 if (natbibOrder && !before.empty())
2319 swap(before, after);
2324 void copy_file(FileName const & src, string dstname)
2328 string const absParent = getParentFilePath(false);
2330 if (FileName::isAbsolute(dstname))
2331 dst = FileName(dstname);
2333 dst = makeAbsPath(dstname, absParent);
2334 FileName const srcpath = src.onlyPath();
2335 FileName const dstpath = dst.onlyPath();
2336 if (equivalent(srcpath, dstpath))
2338 if (!dstpath.isDirectory()) {
2339 if (!dstpath.createPath()) {
2340 cerr << "Warning: Could not create directory for file `"
2341 << dst.absFileName() << "´." << endl;
2345 if (dst.isReadableFile()) {
2346 if (overwriteFiles())
2347 cerr << "Warning: Overwriting existing file `"
2348 << dst.absFileName() << "´." << endl;
2350 cerr << "Warning: Not overwriting existing file `"
2351 << dst.absFileName() << "´." << endl;
2355 if (!src.copyTo(dst))
2356 cerr << "Warning: Could not copy file `" << src.absFileName()
2357 << "´ to `" << dst.absFileName() << "´." << endl;
2361 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2362 bool parse_chunk(Parser & p, ostream & os, Context & context)
2364 // check whether a chunk is possible here.
2365 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2371 // read the parameters
2372 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2373 if (!params.first) {
2378 Parser::Arg const code = p.verbatimStuff("\n@");
2383 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2384 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2388 // The last newline read is important for paragraph handling
2392 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2393 // We must have a valid layout before outputting the Chunk inset.
2394 context.check_layout(os);
2395 Context chunkcontext(true, context.textclass);
2396 chunkcontext.layout = &context.textclass.plainLayout();
2397 begin_inset(os, "Flex Chunk");
2398 os << "\nstatus open\n";
2399 if (!params.second.empty()) {
2400 chunkcontext.check_layout(os);
2401 Context paramscontext(true, context.textclass);
2402 paramscontext.layout = &context.textclass.plainLayout();
2403 begin_inset(os, "Argument 1");
2404 os << "\nstatus open\n";
2405 output_ert(os, params.second, paramscontext);
2408 output_ert(os, code.second, chunkcontext);
2416 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2417 bool is_macro(Parser & p)
2419 Token first = p.curr_token();
2420 if (first.cat() != catEscape || !p.good())
2422 if (first.cs() == "def")
2424 if (first.cs() != "global" && first.cs() != "long")
2426 Token second = p.get_token();
2428 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2429 second.cat() == catNewline || second.cat() == catComment)) {
2430 second = p.get_token();
2433 bool secondvalid = second.cat() == catEscape;
2435 bool thirdvalid = false;
2436 if (p.good() && first.cs() == "global" && secondvalid &&
2437 second.cs() == "long") {
2438 third = p.get_token();
2440 while (p.good() && !p.isParagraph() &&
2441 (third.cat() == catSpace ||
2442 third.cat() == catNewline ||
2443 third.cat() == catComment)) {
2444 third = p.get_token();
2447 thirdvalid = third.cat() == catEscape;
2449 for (int i = 0; i < pos; ++i)
2454 return (first.cs() == "global" || first.cs() == "long") &&
2455 second.cs() == "def";
2456 return first.cs() == "global" && second.cs() == "long" &&
2457 third.cs() == "def";
2461 /// Parse a macro definition (assumes that is_macro() returned true)
2462 void parse_macro(Parser & p, ostream & os, Context & context)
2464 context.check_layout(os);
2465 Token first = p.curr_token();
2468 string command = first.asInput();
2469 if (first.cs() != "def") {
2471 eat_whitespace(p, os, context, false);
2472 second = p.curr_token();
2473 command += second.asInput();
2474 if (second.cs() != "def") {
2476 eat_whitespace(p, os, context, false);
2477 third = p.curr_token();
2478 command += third.asInput();
2481 eat_whitespace(p, os, context, false);
2482 string const name = p.get_token().cs();
2483 eat_whitespace(p, os, context, false);
2489 while (p.next_token().cat() != catBegin) {
2490 if (p.next_token().cat() == catParameter) {
2495 // followed by number?
2496 if (p.next_token().cat() == catOther) {
2497 string s = p.get_token().asInput();
2499 // number = current arity + 1?
2500 if (s.size() == 1 && s[0] == arity + '0' + 1)
2505 paramtext += p.get_token().cs();
2507 paramtext += p.get_token().cs();
2512 // only output simple (i.e. compatible) macro as FormulaMacros
2513 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2515 context.check_layout(os);
2516 begin_inset(os, "FormulaMacro");
2517 os << "\n\\def" << ert;
2520 output_ert_inset(os, command + ert, context);
2524 void registerExternalTemplatePackages(string const & name)
2526 external::TemplateManager const & etm = external::TemplateManager::get();
2527 external::Template const * const et = etm.getTemplateByName(name);
2530 external::Template::Formats::const_iterator cit = et->formats.end();
2532 cit = et->formats.find("PDFLaTeX");
2533 if (cit == et->formats.end())
2534 // If the template has not specified a PDFLaTeX output,
2535 // we try the LaTeX format.
2536 cit = et->formats.find("LaTeX");
2537 if (cit == et->formats.end())
2539 vector<string>::const_iterator qit = cit->second.requirements.begin();
2540 vector<string>::const_iterator qend = cit->second.requirements.end();
2541 for (; qit != qend; ++qit)
2542 preamble.registerAutomaticallyLoadedPackage(*qit);
2545 } // anonymous namespace
2549 * Find a file with basename \p name in path \p path and an extension
2552 string find_file(string const & name, string const & path,
2553 char const * const * extensions)
2555 for (char const * const * what = extensions; *what; ++what) {
2556 string const trial = addExtension(name, *what);
2557 if (makeAbsPath(trial, path).exists())
2564 /// Convert filenames with TeX macros and/or quotes to something LyX
2566 string const normalize_filename(string const & name)
2571 Token const & t = p.get_token();
2572 if (t.cat() != catEscape)
2574 else if (t.cs() == "lyxdot") {
2575 // This is used by LyX for simple dots in relative
2579 } else if (t.cs() == "space") {
2582 } else if (t.cs() == "string") {
2583 // Convert \string" to " and \string~ to ~
2584 Token const & n = p.next_token();
2585 if (n.asInput() != "\"" && n.asInput() != "~")
2590 // Strip quotes. This is a bit complicated (see latex_path()).
2591 string full = os.str();
2592 if (!full.empty() && full[0] == '"') {
2593 string base = removeExtension(full);
2594 string ext = getExtension(full);
2595 if (!base.empty() && base[base.length()-1] == '"')
2598 return addExtension(trim(base, "\""), ext);
2599 if (full[full.length()-1] == '"')
2602 return trim(full, "\"");
2608 /// Convert \p name from TeX convention (relative to master file) to LyX
2609 /// convention (relative to .lyx file) if it is relative
2610 void fix_child_filename(string & name)
2612 string const absMasterTeX = getMasterFilePath(true);
2613 bool const isabs = FileName::isAbsolute(name);
2614 // convert from "relative to .tex master" to absolute original path
2616 name = makeAbsPath(name, absMasterTeX).absFileName();
2617 bool copyfile = copyFiles();
2618 string const absParentLyX = getParentFilePath(false);
2621 // convert from absolute original path to "relative to master file"
2622 string const rel = to_utf8(makeRelPath(from_utf8(name),
2623 from_utf8(absMasterTeX)));
2624 // re-interpret "relative to .tex file" as "relative to .lyx file"
2625 // (is different if the master .lyx file resides in a
2626 // different path than the master .tex file)
2627 string const absMasterLyX = getMasterFilePath(false);
2628 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2629 // Do not copy if the new path is impossible to create. Example:
2630 // absMasterTeX = "/foo/bar/"
2631 // absMasterLyX = "/bar/"
2632 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2633 if (contains(name, "/../"))
2640 // convert from absolute original path to
2641 // "relative to .lyx file"
2642 name = to_utf8(makeRelPath(from_utf8(abs),
2643 from_utf8(absParentLyX)));
2647 // convert from absolute original path to "relative to .lyx file"
2648 name = to_utf8(makeRelPath(from_utf8(name),
2649 from_utf8(absParentLyX)));
2654 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2655 Context & context, string const rdelim)
2657 Layout const * newlayout = 0;
2658 InsetLayout const * newinsetlayout = 0;
2659 char const * const * where = 0;
2660 // Store the latest bibliographystyle, addcontentslineContent and
2661 // nocite{*} option (needed for bibtex inset)
2663 string contentslineContent;
2664 // Some classes provide a \bibliographystyle, so do not output
2665 // any if none is explicitly set.
2666 string bibliographystyle;
2667 bool const use_natbib = isProvided("natbib");
2668 bool const use_jurabib = isProvided("jurabib");
2669 bool const use_biblatex = isProvided("biblatex")
2670 && preamble.citeEngine() != "biblatex-natbib";
2671 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2672 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2673 need_commentbib = use_biblatex || use_biblatex_natbib;
2676 // it is impossible to determine the correct encoding for non-CJK Japanese.
2677 // Therefore write a note at the beginning of the document
2678 if (is_nonCJKJapanese) {
2679 context.check_layout(os);
2680 begin_inset(os, "Note Note\n");
2681 os << "status open\n\\begin_layout Plain Layout\n"
2682 << "\\series bold\n"
2683 << "Important information:\n"
2684 << "\\end_layout\n\n"
2685 << "\\begin_layout Plain Layout\n"
2686 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2687 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2688 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2689 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2690 << " and specify the encoding using the -e command-line switch.\n"
2691 << " In addition, you might want to double check that the desired output encoding\n"
2692 << " is correctly selected in Document > Settings > Language.\n"
2693 << "\\end_layout\n";
2695 is_nonCJKJapanese = false;
2698 bool have_cycled = false;
2700 // Leave here only after at least one cycle
2701 if (have_cycled && flags & FLAG_LEAVE) {
2702 flags &= ~FLAG_LEAVE;
2706 Token const & t = p.get_token();
2708 debugToken(cerr, t, flags);
2711 if (flags & FLAG_ITEM) {
2712 if (t.cat() == catSpace)
2715 flags &= ~FLAG_ITEM;
2716 if (t.cat() == catBegin) {
2717 // skip the brace and collect everything to the next matching
2719 flags |= FLAG_BRACE_LAST;
2723 // handle only this single token, leave the loop if done
2724 flags |= FLAG_LEAVE;
2727 if (t.cat() != catEscape && t.character() == ']' &&
2728 (flags & FLAG_BRACK_LAST))
2730 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2732 string tok = t.asInput();
2733 // we only support delimiters with max 2 chars for now.
2734 if (rdelim.size() > 1)
2735 tok += p.next_token().asInput();
2736 if (t.cat() != catEscape && !rdelim.empty()
2737 && tok == rdelim && (flags & FLAG_RDELIM)) {
2738 if (rdelim.size() > 1)
2739 p.get_token(); // eat rdelim
2743 // If there is anything between \end{env} and \begin{env} we
2744 // don't need to output a separator.
2745 if (t.cat() != catSpace && t.cat() != catNewline &&
2746 t.asInput() != "\\begin")
2753 bool const starred = p.next_token().asInput() == "*";
2754 string const starredname(starred ? (t.cs() + '*') : t.cs());
2755 if (t.cat() == catMath) {
2756 // we are inside some text mode thingy, so opening new math is allowed
2757 context.check_layout(os);
2758 begin_inset(os, "Formula ");
2759 Token const & n = p.get_token();
2760 bool const display(n.cat() == catMath && outer);
2762 // TeX's $$...$$ syntax for displayed math
2764 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2766 p.get_token(); // skip the second '$' token
2768 // simple $...$ stuff
2771 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2776 // Prevent the conversion of a line break to a
2777 // space (bug 7668). This does not change the
2778 // output, but looks ugly in LyX.
2779 eat_whitespace(p, os, context, false);
2784 if (t.cat() == catSuper || t.cat() == catSub) {
2785 cerr << "catcode " << t << " illegal in text mode\n";
2789 // Basic support for quotes. We try to disambiguate
2790 // quotes from the context (e.g., a left english quote is
2791 // the same as a right german quote...).
2792 // Try to make a smart guess about the side
2793 Token const prev = p.prev_token();
2794 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2795 && prev.character() != '\n' && prev.character() != '~');
2796 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2797 context.check_layout(os);
2798 begin_inset(os, "Quotes ");
2799 os << guessQuoteStyle("eld", opening);
2805 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2806 context.check_layout(os);
2807 begin_inset(os, "Quotes ");
2808 os << guessQuoteStyle("erd", opening);
2815 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2816 context.check_layout(os);
2817 begin_inset(os, "Quotes ");
2818 os << guessQuoteStyle("ald", opening);
2825 if (t.asInput() == "<"
2826 && p.next_token().asInput() == "<") {
2827 bool has_chunk = false;
2831 has_chunk = parse_chunk(p, os, context);
2837 context.check_layout(os);
2838 begin_inset(os, "Quotes ");
2839 os << guessQuoteStyle("ard", opening);
2847 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2848 check_space(p, os, context);
2852 // babel shorthands (also used by polyglossia)
2853 // Since these can have different meanings for different languages
2854 // we import them as ERT (but they must be put in ERT to get output
2856 if (t.asInput() == "\"") {
2858 // These are known pairs. We put them together in
2859 // one ERT inset. In other cases (such as "a), only
2860 // the quotation mark is ERTed.
2861 if (p.next_token().asInput() == "\""
2862 || p.next_token().asInput() == "|"
2863 || p.next_token().asInput() == "-"
2864 || p.next_token().asInput() == "~"
2865 || p.next_token().asInput() == "="
2866 || p.next_token().asInput() == "/"
2867 || p.next_token().asInput() == "~"
2868 || p.next_token().asInput() == "'"
2869 || p.next_token().asInput() == "`"
2870 || p.next_token().asInput() == "<"
2871 || p.next_token().asInput() == ">") {
2872 s += p.next_token().asInput();
2875 output_ert_inset(os, s, context);
2879 if (t.character() == '[' && noweb_mode &&
2880 p.next_token().character() == '[') {
2881 // These can contain underscores
2883 string const s = p.getFullOpt() + ']';
2884 if (p.next_token().character() == ']')
2887 cerr << "Warning: Inserting missing ']' in '"
2888 << s << "'." << endl;
2889 output_ert_inset(os, s, context);
2893 if (t.cat() == catLetter) {
2894 context.check_layout(os);
2899 if (t.cat() == catOther ||
2900 t.cat() == catAlign ||
2901 t.cat() == catParameter) {
2902 context.check_layout(os);
2903 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2904 context.merging_hyphens_allowed &&
2905 context.font.family != "ttfamily" &&
2906 !context.layout->pass_thru) {
2907 if (p.next_next_token().asInput() == "-") {
2909 os << to_utf8(docstring(1, 0x2014));
2913 os << to_utf8(docstring(1, 0x2013));
2916 // This translates "&" to "\\&" which may be wrong...
2921 if (p.isParagraph()) {
2922 // In minted floating listings we will collect
2923 // everything into the caption, where multiple
2924 // paragraphs are forbidden.
2925 if (minted_float.empty()) {
2926 if (context.new_layout_allowed)
2927 context.new_paragraph(os);
2929 output_ert_inset(os, "\\par ", context);
2932 eat_whitespace(p, os, context, true);
2936 if (t.cat() == catActive) {
2937 context.check_layout(os);
2938 if (t.character() == '~') {
2939 if (context.layout->free_spacing)
2942 begin_inset(os, "space ~\n");
2950 if (t.cat() == catBegin) {
2951 Token const next = p.next_token();
2952 Token const end = p.next_next_token();
2953 if (next.cat() == catEnd) {
2955 Token const prev = p.prev_token();
2957 if (p.next_token().character() == '`')
2958 ; // ignore it in {}``
2960 output_ert_inset(os, "{}", context);
2961 } else if (next.cat() == catEscape &&
2962 is_known(next.cs(), known_quotes) &&
2963 end.cat() == catEnd) {
2964 // Something like {\textquoteright} (e.g.
2965 // from writer2latex). We may skip the
2966 // braces here for better readability.
2967 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2969 } else if (p.next_token().asInput() == "\\ascii") {
2970 // handle the \ascii characters
2971 // (the case without braces is handled later)
2972 // the code is "{\ascii\xxx}"
2973 p.get_token(); // eat \ascii
2974 string name2 = p.get_token().asInput();
2975 p.get_token(); // eat the final '}'
2976 string const name = "{\\ascii" + name2 + "}";
2980 // get the character from unicodesymbols
2981 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2982 Encodings::TEXT_CMD, termination, rem, &req);
2984 context.check_layout(os);
2987 output_ert_inset(os,
2988 to_utf8(rem), context);
2989 for (set<string>::const_iterator it = req.begin();
2990 it != req.end(); ++it)
2991 preamble.registerAutomaticallyLoadedPackage(*it);
2993 // we did not find a non-ert version
2994 output_ert_inset(os, name, context);
2996 context.check_layout(os);
2997 // special handling of font attribute changes
2998 Token const prev = p.prev_token();
2999 TeXFont const oldFont = context.font;
3000 if (next.character() == '[' ||
3001 next.character() == ']' ||
3002 next.character() == '*') {
3004 if (p.next_token().cat() == catEnd) {
3009 output_ert_inset(os, "{", context);
3010 parse_text_snippet(p, os,
3013 output_ert_inset(os, "}", context);
3015 } else if (! context.new_layout_allowed) {
3016 output_ert_inset(os, "{", context);
3017 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3019 output_ert_inset(os, "}", context);
3020 } else if (is_known(next.cs(), known_sizes)) {
3021 // next will change the size, so we must
3023 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3025 if (!context.atParagraphStart())
3027 << context.font.size << "\n";
3028 } else if (is_known(next.cs(), known_font_families)) {
3029 // next will change the font family, so we
3030 // must reset it here
3031 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3033 if (!context.atParagraphStart())
3035 << context.font.family << "\n";
3036 } else if (is_known(next.cs(), known_font_series)) {
3037 // next will change the font series, so we
3038 // must reset it here
3039 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3041 if (!context.atParagraphStart())
3043 << context.font.series << "\n";
3044 } else if (is_known(next.cs(), known_font_shapes)) {
3045 // next will change the font shape, so we
3046 // must reset it here
3047 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3049 if (!context.atParagraphStart())
3051 << context.font.shape << "\n";
3052 } else if (is_known(next.cs(), known_old_font_families) ||
3053 is_known(next.cs(), known_old_font_series) ||
3054 is_known(next.cs(), known_old_font_shapes)) {
3055 // next will change the font family, series
3056 // and shape, so we must reset it here
3057 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3059 if (!context.atParagraphStart())
3061 << context.font.family
3063 << context.font.series
3065 << context.font.shape << "\n";
3067 output_ert_inset(os, "{", context);
3068 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3070 output_ert_inset(os, "}", context);
3076 if (t.cat() == catEnd) {
3077 if (flags & FLAG_BRACE_LAST) {
3080 cerr << "stray '}' in text\n";
3081 output_ert_inset(os, "}", context);
3085 if (t.cat() == catComment) {
3086 parse_comment(p, os, t, context);
3091 // control sequences
3094 if (t.cs() == "(" || t.cs() == "[") {
3095 bool const simple = t.cs() == "(";
3096 context.check_layout(os);
3097 begin_inset(os, "Formula");
3098 os << " \\" << t.cs();
3099 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3100 os << '\\' << (simple ? ')' : ']');
3103 // Prevent the conversion of a line break to a
3104 // space (bug 7668). This does not change the
3105 // output, but looks ugly in LyX.
3106 eat_whitespace(p, os, context, false);
3111 if (t.cs() == "begin") {
3112 parse_environment(p, os, outer, last_env,
3117 if (t.cs() == "end") {
3118 if (flags & FLAG_END) {
3119 // eat environment name
3120 string const name = p.getArg('{', '}');
3121 if (name != active_environment())
3122 cerr << "\\end{" + name + "} does not match \\begin{"
3123 + active_environment() + "}\n";
3126 p.error("found 'end' unexpectedly");
3130 // "item" by default, but could be something else
3131 if (t.cs() == context.layout->itemcommand()) {
3133 if (context.layout->labeltype == LABEL_MANUAL) {
3134 // FIXME: This swallows comments, but we cannot use
3135 // eat_whitespace() since we must not output
3136 // anything before the item.
3137 p.skip_spaces(true);
3138 s = p.verbatimOption();
3140 p.skip_spaces(false);
3142 context.check_layout(os);
3143 if (context.has_item) {
3144 // An item in an unknown list-like environment
3145 // FIXME: Do this in check_layout()!
3146 context.has_item = false;
3147 string item = "\\" + context.layout->itemcommand();
3150 output_ert_inset(os, item, context);
3152 if (context.layout->labeltype != LABEL_MANUAL)
3153 output_arguments(os, p, outer, false, "item", context,
3154 context.layout->itemargs());
3155 if (!context.list_extra_stuff.empty()) {
3156 os << context.list_extra_stuff;
3157 context.list_extra_stuff.clear();
3159 else if (!s.empty()) {
3160 // LyX adds braces around the argument,
3161 // so we need to remove them here.
3162 if (s.size() > 2 && s[0] == '{' &&
3163 s[s.size()-1] == '}')
3164 s = s.substr(1, s.size()-2);
3165 // If the argument contains a space we
3166 // must put it into ERT: Otherwise LyX
3167 // would misinterpret the space as
3168 // item delimiter (bug 7663)
3169 if (contains(s, ' ')) {
3170 output_ert_inset(os, s, context);
3173 os << parse_text_snippet(p2,
3174 FLAG_BRACK_LAST, outer, context);
3176 // The space is needed to separate the
3177 // item from the rest of the sentence.
3179 eat_whitespace(p, os, context, false);
3184 if (t.cs() == "bibitem") {
3186 context.check_layout(os);
3187 eat_whitespace(p, os, context, false);
3188 string label = p.verbatimOption();
3189 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3190 bool const literal = !lbl.first;
3191 label = literal ? subst(label, "\n", " ") : lbl.second;
3192 string lit = literal ? "\"true\"" : "\"false\"";
3193 string key = convert_literate_command_inset_arg(p.verbatim_item());
3194 begin_command_inset(os, "bibitem", "bibitem");
3195 os << "label \"" << label << "\"\n"
3196 << "key \"" << key << "\"\n"
3197 << "literal " << lit << "\n";
3203 // catch the case of \def\inputGnumericTable
3205 if (t.cs() == "def") {
3206 Token second = p.next_token();
3207 if (second.cs() == "inputGnumericTable") {
3211 Token third = p.get_token();
3213 if (third.cs() == "input") {
3217 string name = normalize_filename(p.verbatim_item());
3218 string const path = getMasterFilePath(true);
3219 // We want to preserve relative / absolute filenames,
3220 // therefore path is only used for testing
3221 // The file extension is in every case ".tex".
3222 // So we need to remove this extension and check for
3223 // the original one.
3224 name = removeExtension(name);
3225 if (!makeAbsPath(name, path).exists()) {
3226 char const * const Gnumeric_formats[] = {"gnumeric",
3228 string const Gnumeric_name =
3229 find_file(name, path, Gnumeric_formats);
3230 if (!Gnumeric_name.empty())
3231 name = Gnumeric_name;
3233 FileName const absname = makeAbsPath(name, path);
3234 if (absname.exists()) {
3235 fix_child_filename(name);
3236 copy_file(absname, name);
3238 cerr << "Warning: Could not find file '"
3239 << name << "'." << endl;
3240 context.check_layout(os);
3241 begin_inset(os, "External\n\ttemplate ");
3242 os << "GnumericSpreadsheet\n\tfilename "
3245 context.check_layout(os);
3247 // register the packages that are automatically loaded
3248 // by the Gnumeric template
3249 registerExternalTemplatePackages("GnumericSpreadsheet");
3254 parse_macro(p, os, context);
3258 if (t.cs() == "noindent") {
3260 context.add_par_extra_stuff("\\noindent\n");
3264 if (t.cs() == "appendix") {
3265 context.add_par_extra_stuff("\\start_of_appendix\n");
3266 // We need to start a new paragraph. Otherwise the
3267 // appendix in 'bla\appendix\chapter{' would start
3269 context.new_paragraph(os);
3270 // We need to make sure that the paragraph is
3271 // generated even if it is empty. Otherwise the
3272 // appendix in '\par\appendix\par\chapter{' would
3274 context.check_layout(os);
3275 // FIXME: This is a hack to prevent paragraph
3276 // deletion if it is empty. Handle this better!
3277 output_comment(p, os,
3278 "dummy comment inserted by tex2lyx to "
3279 "ensure that this paragraph is not empty",
3281 // Both measures above may generate an additional
3282 // empty paragraph, but that does not hurt, because
3283 // whitespace does not matter here.
3284 eat_whitespace(p, os, context, true);
3288 // Must catch empty dates before findLayout is called below
3289 if (t.cs() == "date") {
3290 eat_whitespace(p, os, context, false);
3292 string const date = p.verbatim_item();
3295 preamble.suppressDate(true);
3298 preamble.suppressDate(false);
3299 if (context.new_layout_allowed &&
3300 (newlayout = findLayout(context.textclass,
3303 output_command_layout(os, p, outer,
3304 context, newlayout);
3305 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3306 if (!preamble.titleLayoutFound())
3307 preamble.titleLayoutFound(newlayout->intitle);
3308 set<string> const & req = newlayout->requires();
3309 set<string>::const_iterator it = req.begin();
3310 set<string>::const_iterator en = req.end();
3311 for (; it != en; ++it)
3312 preamble.registerAutomaticallyLoadedPackage(*it);
3314 output_ert_inset(os,
3315 "\\date{" + p.verbatim_item() + '}',
3321 // Before we look for the layout name with star and alone below, we check the layouts including
3322 // the LateXParam, which might be one or several options or a star.
3323 // The single '=' is meant here.
3324 if (context.new_layout_allowed &&
3325 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3326 // store the latexparam here. This is eaten in output_command_layout
3327 context.latexparam = newlayout->latexparam();
3329 output_command_layout(os, p, outer, context, newlayout);
3330 context.latexparam.clear();
3332 if (!preamble.titleLayoutFound())
3333 preamble.titleLayoutFound(newlayout->intitle);
3334 set<string> const & req = newlayout->requires();
3335 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3336 preamble.registerAutomaticallyLoadedPackage(*it);
3340 // Starred section headings
3341 // Must attempt to parse "Section*" before "Section".
3342 if ((p.next_token().asInput() == "*") &&
3343 context.new_layout_allowed &&
3344 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3347 output_command_layout(os, p, outer, context, newlayout);
3349 if (!preamble.titleLayoutFound())
3350 preamble.titleLayoutFound(newlayout->intitle);
3351 set<string> const & req = newlayout->requires();
3352 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3353 preamble.registerAutomaticallyLoadedPackage(*it);
3357 // Section headings and the like
3358 if (context.new_layout_allowed &&
3359 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3361 output_command_layout(os, p, outer, context, newlayout);
3363 if (!preamble.titleLayoutFound())
3364 preamble.titleLayoutFound(newlayout->intitle);
3365 set<string> const & req = newlayout->requires();
3366 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3367 preamble.registerAutomaticallyLoadedPackage(*it);
3371 if (t.cs() == "subfloat") {
3372 // the syntax is \subfloat[list entry][sub caption]{content}
3373 // if it is a table of figure depends on the surrounding float
3375 // do nothing if there is no outer float
3376 if (!float_type.empty()) {
3377 context.check_layout(os);
3379 begin_inset(os, "Float " + float_type + "\n");
3381 << "\nsideways false"
3382 << "\nstatus collapsed\n\n";
3385 bool has_caption = false;
3386 if (p.next_token().cat() != catEscape &&
3387 p.next_token().character() == '[') {
3388 p.get_token(); // eat '['
3389 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3392 // In case we have two optional args, the second is the caption.
3393 if (p.next_token().cat() != catEscape &&
3394 p.next_token().character() == '[') {
3395 p.get_token(); // eat '['
3396 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3399 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3400 // the caption comes always as the last
3402 // we must make sure that the caption gets a \begin_layout
3403 os << "\n\\begin_layout Plain Layout";
3405 begin_inset(os, "Caption Standard\n");
3406 Context newcontext(true, context.textclass,
3407 0, 0, context.font);
3408 newcontext.check_layout(os);
3409 os << caption << "\n";
3410 newcontext.check_end_layout(os);
3413 // close the layout we opened
3414 os << "\n\\end_layout";
3419 // if the float type is not supported or there is no surrounding float
3424 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3426 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3428 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3429 + "{" + p.verbatim_item() + '}', context);
3434 if (t.cs() == "xymatrix") {
3435 // we must open a new math because LyX's xy support is in math
3436 context.check_layout(os);
3437 begin_inset(os, "Formula ");
3439 os << "\\" << t.cs() << '{';
3440 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3443 preamble.registerAutomaticallyLoadedPackage("xy");
3447 if (t.cs() == "includegraphics") {
3448 bool const clip = p.next_token().asInput() == "*";
3451 string const arg = p.getArg('[', ']');
3452 map<string, string> opts;
3453 vector<string> keys;
3454 split_map(arg, opts, keys);
3456 opts["clip"] = string();
3457 string name = normalize_filename(p.verbatim_item());
3459 string const path = getMasterFilePath(true);
3460 // We want to preserve relative / absolute filenames,
3461 // therefore path is only used for testing
3462 if (!makeAbsPath(name, path).exists()) {
3463 // The file extension is probably missing.
3464 // Now try to find it out.
3465 string const dvips_name =
3466 find_file(name, path,
3467 known_dvips_graphics_formats);
3468 string const pdftex_name =
3469 find_file(name, path,
3470 known_pdftex_graphics_formats);
3471 if (!dvips_name.empty()) {
3472 if (!pdftex_name.empty()) {
3473 cerr << "This file contains the "
3475 "\"\\includegraphics{"
3477 "However, files\n\""
3478 << dvips_name << "\" and\n\""
3479 << pdftex_name << "\"\n"
3480 "both exist, so I had to make a "
3481 "choice and took the first one.\n"
3482 "Please move the unwanted one "
3483 "someplace else and try again\n"
3484 "if my choice was wrong."
3488 } else if (!pdftex_name.empty()) {
3494 FileName const absname = makeAbsPath(name, path);
3495 if (absname.exists()) {
3496 fix_child_filename(name);
3497 copy_file(absname, name);
3499 cerr << "Warning: Could not find graphics file '"
3500 << name << "'." << endl;
3502 context.check_layout(os);
3503 begin_inset(os, "Graphics ");
3504 os << "\n\tfilename " << name << '\n';
3505 if (opts.find("width") != opts.end())
3507 << translate_len(opts["width"]) << '\n';
3508 if (opts.find("height") != opts.end())
3510 << translate_len(opts["height"]) << '\n';
3511 if (opts.find("scale") != opts.end()) {
3512 istringstream iss(opts["scale"]);
3516 os << "\tscale " << val << '\n';
3518 if (opts.find("angle") != opts.end()) {
3519 os << "\trotateAngle "
3520 << opts["angle"] << '\n';
3521 vector<string>::const_iterator a =
3522 find(keys.begin(), keys.end(), "angle");
3523 vector<string>::const_iterator s =
3524 find(keys.begin(), keys.end(), "width");
3525 if (s == keys.end())
3526 s = find(keys.begin(), keys.end(), "height");
3527 if (s == keys.end())
3528 s = find(keys.begin(), keys.end(), "scale");
3529 if (s != keys.end() && distance(s, a) > 0)
3530 os << "\tscaleBeforeRotation\n";
3532 if (opts.find("origin") != opts.end()) {
3534 string const opt = opts["origin"];
3535 if (opt.find('l') != string::npos) ss << "left";
3536 if (opt.find('r') != string::npos) ss << "right";
3537 if (opt.find('c') != string::npos) ss << "center";
3538 if (opt.find('t') != string::npos) ss << "Top";
3539 if (opt.find('b') != string::npos) ss << "Bottom";
3540 if (opt.find('B') != string::npos) ss << "Baseline";
3541 if (!ss.str().empty())
3542 os << "\trotateOrigin " << ss.str() << '\n';
3544 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3546 if (opts.find("keepaspectratio") != opts.end())
3547 os << "\tkeepAspectRatio\n";
3548 if (opts.find("clip") != opts.end())
3550 if (opts.find("draft") != opts.end())
3552 if (opts.find("bb") != opts.end())
3553 os << "\tBoundingBox "
3554 << opts["bb"] << '\n';
3555 int numberOfbbOptions = 0;
3556 if (opts.find("bbllx") != opts.end())
3557 numberOfbbOptions++;
3558 if (opts.find("bblly") != opts.end())
3559 numberOfbbOptions++;
3560 if (opts.find("bburx") != opts.end())
3561 numberOfbbOptions++;
3562 if (opts.find("bbury") != opts.end())
3563 numberOfbbOptions++;
3564 if (numberOfbbOptions == 4)
3565 os << "\tBoundingBox "
3566 << opts["bbllx"] << " " << opts["bblly"] << " "
3567 << opts["bburx"] << " " << opts["bbury"] << '\n';
3568 else if (numberOfbbOptions > 0)
3569 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3570 numberOfbbOptions = 0;
3571 if (opts.find("natwidth") != opts.end())
3572 numberOfbbOptions++;
3573 if (opts.find("natheight") != opts.end())
3574 numberOfbbOptions++;
3575 if (numberOfbbOptions == 2)
3576 os << "\tBoundingBox 0bp 0bp "
3577 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3578 else if (numberOfbbOptions > 0)
3579 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3580 ostringstream special;
3581 if (opts.find("hiresbb") != opts.end())
3582 special << "hiresbb,";
3583 if (opts.find("trim") != opts.end())
3585 if (opts.find("viewport") != opts.end())
3586 special << "viewport=" << opts["viewport"] << ',';
3587 if (opts.find("totalheight") != opts.end())
3588 special << "totalheight=" << opts["totalheight"] << ',';
3589 if (opts.find("type") != opts.end())
3590 special << "type=" << opts["type"] << ',';
3591 if (opts.find("ext") != opts.end())
3592 special << "ext=" << opts["ext"] << ',';
3593 if (opts.find("read") != opts.end())
3594 special << "read=" << opts["read"] << ',';
3595 if (opts.find("command") != opts.end())
3596 special << "command=" << opts["command"] << ',';
3597 string s_special = special.str();
3598 if (!s_special.empty()) {
3599 // We had special arguments. Remove the trailing ','.
3600 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3602 // TODO: Handle the unknown settings better.
3603 // Warn about invalid options.
3604 // Check whether some option was given twice.
3606 preamble.registerAutomaticallyLoadedPackage("graphicx");
3610 if (t.cs() == "footnote" ||
3611 (t.cs() == "thanks" && context.layout->intitle)) {
3613 context.check_layout(os);
3614 begin_inset(os, "Foot\n");
3615 os << "status collapsed\n\n";
3616 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3621 if (t.cs() == "marginpar") {
3623 context.check_layout(os);
3624 begin_inset(os, "Marginal\n");
3625 os << "status collapsed\n\n";
3626 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3631 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3632 bool const use_minted = t.cs() == "mintinline";
3634 parse_listings(p, os, context, true, use_minted);
3638 if (t.cs() == "ensuremath") {
3640 context.check_layout(os);
3641 string const s = p.verbatim_item();
3642 //FIXME: this never triggers in UTF8
3643 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3646 output_ert_inset(os, "\\ensuremath{" + s + "}",
3651 else if (t.cs() == "makeindex"
3652 || (t.cs() == context.textclass.titlename()
3653 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3654 if (preamble.titleLayoutFound()) {
3656 skip_spaces_braces(p);
3658 output_ert_inset(os, t.asInput(), context);
3662 if (t.cs() == "tableofcontents"
3663 || t.cs() == "lstlistoflistings"
3664 || t.cs() == "listoflistings") {
3665 string name = t.cs();
3666 if (preamble.minted() && name == "listoflistings")
3667 name.insert(0, "lst");
3668 context.check_layout(os);
3669 begin_command_inset(os, "toc", name);
3671 skip_spaces_braces(p);
3672 if (name == "lstlistoflistings") {
3673 if (preamble.minted())
3674 preamble.registerAutomaticallyLoadedPackage("minted");
3676 preamble.registerAutomaticallyLoadedPackage("listings");
3681 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3682 context.check_layout(os);
3683 if (t.cs() == "listoffigures")
3684 begin_inset(os, "FloatList figure\n");
3686 begin_inset(os, "FloatList table\n");
3688 skip_spaces_braces(p);
3692 if (t.cs() == "listof") {
3693 p.skip_spaces(true);
3694 string const name = p.get_token().cs();
3695 if (context.textclass.floats().typeExist(name)) {
3696 context.check_layout(os);
3697 begin_inset(os, "FloatList ");
3700 p.get_token(); // swallow second arg
3702 output_ert_inset(os, "\\listof{" + name + "}", context);
3706 if ((where = is_known(t.cs(), known_text_font_families))) {
3707 parse_text_attributes(p, os, FLAG_ITEM, outer,
3708 context, "\\family", context.font.family,
3709 known_coded_font_families[where - known_text_font_families]);
3713 // beamer has a \textbf<overlay>{} inset
3714 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3715 parse_text_attributes(p, os, FLAG_ITEM, outer,
3716 context, "\\series", context.font.series,
3717 known_coded_font_series[where - known_text_font_series]);
3721 // beamer has a \textit<overlay>{} inset
3722 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3723 parse_text_attributes(p, os, FLAG_ITEM, outer,
3724 context, "\\shape", context.font.shape,
3725 known_coded_font_shapes[where - known_text_font_shapes]);
3729 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3730 context.check_layout(os);
3731 TeXFont oldFont = context.font;
3732 context.font.init();
3733 context.font.size = oldFont.size;
3734 os << "\n\\family " << context.font.family << "\n";
3735 os << "\n\\series " << context.font.series << "\n";
3736 os << "\n\\shape " << context.font.shape << "\n";
3737 if (t.cs() == "textnormal") {
3738 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3739 output_font_change(os, context.font, oldFont);
3740 context.font = oldFont;
3742 eat_whitespace(p, os, context, false);
3746 if (t.cs() == "textcolor") {
3747 // scheme is \textcolor{color name}{text}
3748 string const color = p.verbatim_item();
3749 // we support the predefined colors of the color and the xcolor package
3750 if (color == "black" || color == "blue" || color == "cyan"
3751 || color == "green" || color == "magenta" || color == "red"
3752 || color == "white" || color == "yellow") {
3753 context.check_layout(os);
3754 os << "\n\\color " << color << "\n";
3755 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3756 context.check_layout(os);
3757 os << "\n\\color inherit\n";
3758 preamble.registerAutomaticallyLoadedPackage("color");
3759 } else if (color == "brown" || color == "darkgray" || color == "gray"
3760 || color == "lightgray" || color == "lime" || color == "olive"
3761 || color == "orange" || color == "pink" || color == "purple"
3762 || color == "teal" || color == "violet") {
3763 context.check_layout(os);
3764 os << "\n\\color " << color << "\n";
3765 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3766 context.check_layout(os);
3767 os << "\n\\color inherit\n";
3768 preamble.registerAutomaticallyLoadedPackage("xcolor");
3770 // for custom defined colors
3771 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3775 if (t.cs() == "underbar" || t.cs() == "uline") {
3776 // \underbar is not 100% correct (LyX outputs \uline
3777 // of ulem.sty). The difference is that \ulem allows
3778 // line breaks, and \underbar does not.
3779 // Do NOT handle \underline.
3780 // \underbar cuts through y, g, q, p etc.,
3781 // \underline does not.
3782 context.check_layout(os);
3783 os << "\n\\bar under\n";
3784 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3785 context.check_layout(os);
3786 os << "\n\\bar default\n";
3787 preamble.registerAutomaticallyLoadedPackage("ulem");
3791 if (t.cs() == "sout") {
3792 context.check_layout(os);
3793 os << "\n\\strikeout on\n";
3794 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3795 context.check_layout(os);
3796 os << "\n\\strikeout default\n";
3797 preamble.registerAutomaticallyLoadedPackage("ulem");
3801 // beamer has an \emph<overlay>{} inset
3802 if ((t.cs() == "uuline" || t.cs() == "uwave"
3803 || t.cs() == "emph" || t.cs() == "noun"
3804 || t.cs() == "xout") && !p.hasOpt("<")) {
3805 context.check_layout(os);
3806 os << "\n\\" << t.cs() << " on\n";
3807 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3808 context.check_layout(os);
3809 os << "\n\\" << t.cs() << " default\n";
3810 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3811 preamble.registerAutomaticallyLoadedPackage("ulem");
3815 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3816 context.check_layout(os);
3817 string name = p.getArg('{', '}');
3818 string localtime = p.getArg('{', '}');
3819 preamble.registerAuthor(name);
3820 Author const & author = preamble.getAuthor(name);
3821 // from_asctime_utc() will fail if LyX decides to output the
3822 // time in the text language.
3823 time_t ptime = from_asctime_utc(localtime);
3824 if (ptime == static_cast<time_t>(-1)) {
3825 cerr << "Warning: Could not parse time `" << localtime
3826 << "´ for change tracking, using current time instead.\n";
3827 ptime = current_time();
3829 if (t.cs() == "lyxadded")
3830 os << "\n\\change_inserted ";
3832 os << "\n\\change_deleted ";
3833 os << author.bufferId() << ' ' << ptime << '\n';
3834 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3835 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3836 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3837 LaTeXPackages::isAvailable("xcolor");
3838 // No need to test for luatex, since luatex comes in
3839 // two flavours (dvi and pdf), like latex, and those
3840 // are detected by pdflatex.
3841 if (pdflatex || xetex) {
3843 preamble.registerAutomaticallyLoadedPackage("ulem");
3844 preamble.registerAutomaticallyLoadedPackage("xcolor");
3845 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3849 preamble.registerAutomaticallyLoadedPackage("dvipost");
3850 } else if (xcolorulem) {
3851 preamble.registerAutomaticallyLoadedPackage("ulem");
3852 preamble.registerAutomaticallyLoadedPackage("xcolor");
3858 if (t.cs() == "textipa") {
3859 context.check_layout(os);
3860 begin_inset(os, "IPA\n");
3861 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3862 context.merging_hyphens_allowed = false;
3863 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3864 context.merging_hyphens_allowed = merging_hyphens_allowed;
3866 preamble.registerAutomaticallyLoadedPackage("tipa");
3867 preamble.registerAutomaticallyLoadedPackage("tipx");
3871 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3872 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3873 context.check_layout(os);
3877 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3878 begin_inset(os, "IPADeco " + type + "\n");
3879 os << "status open\n";
3880 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3886 if (t.cs() == "textvertline") {
3887 // FIXME: This is not correct, \textvertline is higher than |
3893 if (t.cs() == "tone" ) {
3894 context.check_layout(os);
3895 // register the tone package
3896 preamble.registerAutomaticallyLoadedPackage("tone");
3897 string content = trimSpaceAndEol(p.verbatim_item());
3898 string command = t.asInput() + "{" + content + "}";
3899 // some tones can be detected by unicodesymbols, some need special code
3900 if (is_known(content, known_tones)) {
3901 os << "\\IPAChar " << command << "\n";
3904 // try to see whether the string is in unicodesymbols
3908 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3909 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3910 termination, rem, &req);
3914 output_ert_inset(os, to_utf8(rem), context);
3915 for (set<string>::const_iterator it = req.begin();
3916 it != req.end(); ++it)
3917 preamble.registerAutomaticallyLoadedPackage(*it);
3919 // we did not find a non-ert version
3920 output_ert_inset(os, command, context);
3924 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3925 t.cs() == "vphantom") {
3926 context.check_layout(os);
3927 if (t.cs() == "phantom")
3928 begin_inset(os, "Phantom Phantom\n");
3929 if (t.cs() == "hphantom")
3930 begin_inset(os, "Phantom HPhantom\n");
3931 if (t.cs() == "vphantom")
3932 begin_inset(os, "Phantom VPhantom\n");
3933 os << "status open\n";
3934 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3940 if (t.cs() == "href") {
3941 context.check_layout(os);
3942 string target = convert_literate_command_inset_arg(p.verbatim_item());
3943 string name = p.verbatim_item();
3944 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3945 bool const literal = !nm.first;
3946 name = literal ? subst(name, "\n", " ") : nm.second;
3947 string lit = literal ? "\"true\"" : "\"false\"";
3949 size_t i = target.find(':');
3950 if (i != string::npos) {
3951 type = target.substr(0, i + 1);
3952 if (type == "mailto:" || type == "file:")
3953 target = target.substr(i + 1);
3954 // handle the case that name is equal to target, except of "http(s)://"
3955 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3958 begin_command_inset(os, "href", "href");
3960 os << "name \"" << name << "\"\n";
3961 os << "target \"" << target << "\"\n";
3962 if (type == "mailto:" || type == "file:")
3963 os << "type \"" << type << "\"\n";
3964 os << "literal " << lit << "\n";
3966 skip_spaces_braces(p);
3970 if (t.cs() == "lyxline") {
3971 // swallow size argument (it is not used anyway)
3973 if (!context.atParagraphStart()) {
3974 // so our line is in the middle of a paragraph
3975 // we need to add a new line, lest this line
3976 // follow the other content on that line and
3977 // run off the side of the page
3978 // FIXME: This may create an empty paragraph,
3979 // but without that it would not be
3980 // possible to set noindent below.
3981 // Fortunately LaTeX does not care
3982 // about the empty paragraph.
3983 context.new_paragraph(os);
3985 if (preamble.indentParagraphs()) {
3986 // we need to unindent, lest the line be too long
3987 context.add_par_extra_stuff("\\noindent\n");
3989 context.check_layout(os);
3990 begin_command_inset(os, "line", "rule");
3991 os << "offset \"0.5ex\"\n"
3992 "width \"100line%\"\n"
3998 if (t.cs() == "rule") {
3999 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4000 string const width = p.getArg('{', '}');
4001 string const thickness = p.getArg('{', '}');
4002 context.check_layout(os);
4003 begin_command_inset(os, "line", "rule");
4004 if (!offset.empty())
4005 os << "offset \"" << translate_len(offset) << "\"\n";
4006 os << "width \"" << translate_len(width) << "\"\n"
4007 "height \"" << translate_len(thickness) << "\"\n";
4012 // handle refstyle first to catch \eqref which can also occur
4013 // without refstyle. Only recognize these commands if
4014 // refstyle.sty was found in the preamble (otherwise \eqref
4015 // and user defined ref commands could be misdetected).
4016 if ((where = is_known(t.cs(), known_refstyle_commands))
4017 && preamble.refstyle()) {
4018 context.check_layout(os);
4019 begin_command_inset(os, "ref", "formatted");
4020 os << "reference \"";
4021 os << known_refstyle_prefixes[where - known_refstyle_commands]
4023 os << convert_literate_command_inset_arg(p.verbatim_item())
4025 os << "plural \"false\"\n";
4026 os << "caps \"false\"\n";
4027 os << "noprefix \"false\"\n";
4029 preamble.registerAutomaticallyLoadedPackage("refstyle");
4033 // if refstyle is used, we must not convert \prettyref to a
4034 // formatted reference, since that would result in a refstyle command.
4035 if ((where = is_known(t.cs(), known_ref_commands)) &&
4036 (t.cs() != "prettyref" || !preamble.refstyle())) {
4037 string const opt = p.getOpt();
4039 context.check_layout(os);
4040 begin_command_inset(os, "ref",
4041 known_coded_ref_commands[where - known_ref_commands]);
4042 os << "reference \""
4043 << convert_literate_command_inset_arg(p.verbatim_item())
4045 os << "plural \"false\"\n";
4046 os << "caps \"false\"\n";
4047 os << "noprefix \"false\"\n";
4049 if (t.cs() == "vref" || t.cs() == "vpageref")
4050 preamble.registerAutomaticallyLoadedPackage("varioref");
4051 else if (t.cs() == "prettyref")
4052 preamble.registerAutomaticallyLoadedPackage("prettyref");
4054 // LyX does not yet support optional arguments of ref commands
4055 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4056 p.verbatim_item() + '}', context);
4062 is_known(t.cs(), known_natbib_commands) &&
4063 ((t.cs() != "citefullauthor" &&
4064 t.cs() != "citeyear" &&
4065 t.cs() != "citeyearpar") ||
4066 p.next_token().asInput() != "*")) {
4067 context.check_layout(os);
4068 string command = t.cs();
4069 if (p.next_token().asInput() == "*") {
4073 if (command == "citefullauthor")
4074 // alternative name for "\\citeauthor*"
4075 command = "citeauthor*";
4077 // text before the citation
4079 // text after the citation
4081 get_cite_arguments(p, true, before, after);
4083 if (command == "cite") {
4084 // \cite without optional argument means
4085 // \citet, \cite with at least one optional
4086 // argument means \citep.
4087 if (before.empty() && after.empty())
4092 if (before.empty() && after == "[]")
4093 // avoid \citet[]{a}
4095 else if (before == "[]" && after == "[]") {
4096 // avoid \citet[][]{a}
4100 bool literal = false;
4101 pair<bool, string> aft;
4102 pair<bool, string> bef;
4103 // remove the brackets around after and before
4104 if (!after.empty()) {
4106 after.erase(after.length() - 1, 1);
4107 aft = convert_latexed_command_inset_arg(after);
4108 literal = !aft.first;
4109 after = literal ? subst(after, "\n", " ") : aft.second;
4111 if (!before.empty()) {
4113 before.erase(before.length() - 1, 1);
4114 bef = convert_latexed_command_inset_arg(before);
4115 literal |= !bef.first;
4116 before = literal ? subst(before, "\n", " ") : bef.second;
4117 if (literal && !after.empty())
4118 after = subst(after, "\n", " ");
4120 string lit = literal ? "\"true\"" : "\"false\"";
4121 begin_command_inset(os, "citation", command);
4122 os << "after " << '"' << after << '"' << "\n";
4123 os << "before " << '"' << before << '"' << "\n";
4125 << convert_literate_command_inset_arg(p.verbatim_item())
4127 << "literal " << lit << "\n";
4129 // Need to set the cite engine if natbib is loaded by
4130 // the document class directly
4131 if (preamble.citeEngine() == "basic")
4132 preamble.citeEngine("natbib");
4137 && is_known(t.cs(), known_biblatex_commands)
4138 && ((t.cs() == "cite"
4139 || t.cs() == "citeauthor"
4140 || t.cs() == "Citeauthor"
4141 || t.cs() == "parencite"
4142 || t.cs() == "citetitle")
4143 || p.next_token().asInput() != "*"))
4144 || (use_biblatex_natbib
4145 && (is_known(t.cs(), known_biblatex_commands)
4146 || is_known(t.cs(), known_natbib_commands))
4147 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4148 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4149 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4150 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4151 || t.cs() == "parencite" || t.cs() == "citetitle")
4152 || p.next_token().asInput() != "*"))){
4153 context.check_layout(os);
4154 string command = t.cs();
4155 if (p.next_token().asInput() == "*") {
4160 bool const qualified = suffixIs(command, "s");
4162 command = rtrim(command, "s");
4164 // text before the citation
4166 // text after the citation
4168 get_cite_arguments(p, true, before, after, qualified);
4170 // These use natbib cmd names in LyX
4171 // for inter-citeengine compativility
4172 if (command == "citeyear")
4173 command = "citebyear";
4174 else if (command == "cite*")
4175 command = "citeyear";
4176 else if (command == "textcite")
4178 else if (command == "Textcite")
4180 else if (command == "parencite")
4182 else if (command == "Parencite")
4184 else if (command == "parencite*")
4185 command = "citeyearpar";
4186 else if (command == "smartcite")
4187 command = "footcite";
4188 else if (command == "Smartcite")
4189 command = "Footcite";
4191 string const emptyarg = qualified ? "()" : "[]";
4192 if (before.empty() && after == emptyarg)
4195 else if (before == emptyarg && after == emptyarg) {
4196 // avoid \cite[][]{a}
4200 bool literal = false;
4201 pair<bool, string> aft;
4202 pair<bool, string> bef;
4203 // remove the brackets around after and before
4204 if (!after.empty()) {
4206 after.erase(after.length() - 1, 1);
4207 aft = convert_latexed_command_inset_arg(after);
4208 literal = !aft.first;
4209 after = literal ? subst(after, "\n", " ") : aft.second;
4211 if (!before.empty()) {
4213 before.erase(before.length() - 1, 1);
4214 bef = convert_latexed_command_inset_arg(before);
4215 literal |= !bef.first;
4216 before = literal ? subst(before, "\n", " ") : bef.second;
4218 string keys, pretextlist, posttextlist;
4220 map<string, string> pres, posts, preslit, postslit;
4221 vector<string> lkeys;
4222 // text before the citation
4223 string lbefore, lbeforelit;
4224 // text after the citation
4225 string lafter, lafterlit;
4227 pair<bool, string> laft, lbef;
4229 get_cite_arguments(p, true, lbefore, lafter);
4230 // remove the brackets around after and before
4231 if (!lafter.empty()) {
4233 lafter.erase(lafter.length() - 1, 1);
4234 laft = convert_latexed_command_inset_arg(lafter);
4235 literal |= !laft.first;
4236 lafter = laft.second;
4237 lafterlit = subst(lbefore, "\n", " ");
4239 if (!lbefore.empty()) {
4240 lbefore.erase(0, 1);
4241 lbefore.erase(lbefore.length() - 1, 1);
4242 lbef = convert_latexed_command_inset_arg(lbefore);
4243 literal |= !lbef.first;
4244 lbefore = lbef.second;
4245 lbeforelit = subst(lbefore, "\n", " ");
4247 if (lbefore.empty() && lafter == "[]") {
4252 else if (lbefore == "[]" && lafter == "[]") {
4253 // avoid \cite[][]{a}
4259 lkey = p.getArg('{', '}');
4262 if (!lbefore.empty()) {
4263 pres.insert(make_pair(lkey, lbefore));
4264 preslit.insert(make_pair(lkey, lbeforelit));
4266 if (!lafter.empty()) {
4267 posts.insert(make_pair(lkey, lafter));
4268 postslit.insert(make_pair(lkey, lafterlit));
4270 lkeys.push_back(lkey);
4272 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4277 for (auto const & ptl : pres) {
4278 if (!pretextlist.empty())
4279 pretextlist += '\t';
4280 pretextlist += ptl.first + " " + ptl.second;
4282 for (auto const & potl : posts) {
4283 if (!posttextlist.empty())
4284 posttextlist += '\t';
4285 posttextlist += potl.first + " " + potl.second;
4288 keys = convert_literate_command_inset_arg(p.verbatim_item());
4291 after = subst(after, "\n", " ");
4292 if (!before.empty())
4293 before = subst(after, "\n", " ");
4295 string lit = literal ? "\"true\"" : "\"false\"";
4296 begin_command_inset(os, "citation", command);
4297 os << "after " << '"' << after << '"' << "\n";
4298 os << "before " << '"' << before << '"' << "\n";
4302 if (!pretextlist.empty())
4303 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4304 if (!posttextlist.empty())
4305 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4306 os << "literal " << lit << "\n";
4308 // Need to set the cite engine if biblatex is loaded by
4309 // the document class directly
4310 if (preamble.citeEngine() == "basic")
4311 use_biblatex_natbib ?
4312 preamble.citeEngine("biblatex-natbib")
4313 : preamble.citeEngine("biblatex");
4318 is_known(t.cs(), known_jurabib_commands) &&
4319 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4320 context.check_layout(os);
4321 string command = t.cs();
4322 if (p.next_token().asInput() == "*") {
4326 char argumentOrder = '\0';
4327 vector<string> const options =
4328 preamble.getPackageOptions("jurabib");
4329 if (find(options.begin(), options.end(),
4330 "natbiborder") != options.end())
4331 argumentOrder = 'n';
4332 else if (find(options.begin(), options.end(),
4333 "jurabiborder") != options.end())
4334 argumentOrder = 'j';
4336 // text before the citation
4338 // text after the citation
4340 get_cite_arguments(p, argumentOrder != 'j', before, after);
4342 string const citation = p.verbatim_item();
4343 if (!before.empty() && argumentOrder == '\0') {
4344 cerr << "Warning: Assuming argument order "
4345 "of jurabib version 0.6 for\n'"
4346 << command << before << after << '{'
4347 << citation << "}'.\n"
4348 "Add 'jurabiborder' to the jurabib "
4349 "package options if you used an\n"
4350 "earlier jurabib version." << endl;
4352 bool literal = false;
4353 pair<bool, string> aft;
4354 pair<bool, string> bef;
4355 // remove the brackets around after and before
4356 if (!after.empty()) {
4358 after.erase(after.length() - 1, 1);
4359 aft = convert_latexed_command_inset_arg(after);
4360 literal = !aft.first;
4361 after = literal ? subst(after, "\n", " ") : aft.second;
4363 if (!before.empty()) {
4365 before.erase(before.length() - 1, 1);
4366 bef = convert_latexed_command_inset_arg(before);
4367 literal |= !bef.first;
4368 before = literal ? subst(before, "\n", " ") : bef.second;
4369 if (literal && !after.empty())
4370 after = subst(after, "\n", " ");
4372 string lit = literal ? "\"true\"" : "\"false\"";
4373 begin_command_inset(os, "citation", command);
4374 os << "after " << '"' << after << "\"\n"
4375 << "before " << '"' << before << "\"\n"
4376 << "key " << '"' << citation << "\"\n"
4377 << "literal " << lit << "\n";
4379 // Need to set the cite engine if jurabib is loaded by
4380 // the document class directly
4381 if (preamble.citeEngine() == "basic")
4382 preamble.citeEngine("jurabib");
4386 if (t.cs() == "cite"
4387 || t.cs() == "nocite") {
4388 context.check_layout(os);
4389 string after = p.getArg('[', ']');
4390 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4391 bool const literal = !aft.first;
4392 after = literal ? subst(after, "\n", " ") : aft.second;
4393 string lit = literal ? "\"true\"" : "\"false\"";
4394 string key = convert_literate_command_inset_arg(p.verbatim_item());
4395 // store the case that it is "\nocite{*}" to use it later for
4398 begin_command_inset(os, "citation", t.cs());
4399 os << "after " << '"' << after << "\"\n"
4400 << "key " << '"' << key << "\"\n"
4401 << "literal " << lit << "\n";
4403 } else if (t.cs() == "nocite")
4408 if (t.cs() == "index" ||
4409 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4410 context.check_layout(os);
4411 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4412 p.getArg('[', ']') : "";
4413 string const kind = arg.empty() ? "idx" : arg;
4414 begin_inset(os, "Index ");
4415 os << kind << "\nstatus collapsed\n";
4416 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4419 preamble.registerAutomaticallyLoadedPackage("splitidx");
4423 if (t.cs() == "nomenclature") {
4424 context.check_layout(os);
4425 begin_command_inset(os, "nomenclature", "nomenclature");
4426 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4427 if (!prefix.empty())
4428 os << "prefix " << '"' << prefix << '"' << "\n";
4429 string symbol = p.verbatim_item();
4430 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4431 bool literal = !sym.first;
4432 string description = p.verbatim_item();
4433 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4434 literal |= !desc.first;
4436 symbol = subst(symbol, "\n", " ");
4437 description = subst(description, "\n", " ");
4439 symbol = sym.second;
4440 description = desc.second;
4442 string lit = literal ? "\"true\"" : "\"false\"";
4443 os << "symbol " << '"' << symbol;
4444 os << "\"\ndescription \""
4445 << description << "\"\n"
4446 << "literal " << lit << "\n";
4448 preamble.registerAutomaticallyLoadedPackage("nomencl");
4452 if (t.cs() == "label") {
4453 context.check_layout(os);
4454 begin_command_inset(os, "label", "label");
4456 << convert_literate_command_inset_arg(p.verbatim_item())
4462 if (t.cs() == "lyxmintcaption") {
4463 string const pos = p.getArg('[', ']');
4465 string const caption =
4466 parse_text_snippet(p, FLAG_ITEM, false,
4468 minted_nonfloat_caption = "[t]" + caption;
4470 // We already got the caption at the bottom,
4471 // so simply skip it.
4472 parse_text_snippet(p, FLAG_ITEM, false, context);
4474 eat_whitespace(p, os, context, true);
4478 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4479 context.check_layout(os);
4480 string commandname = t.cs();
4482 if (p.next_token().asInput() == "*") {
4487 begin_command_inset(os, "index_print", commandname);
4488 string const indexname = p.getArg('[', ']');
4490 if (indexname.empty())
4491 os << "type \"idx\"\n";
4493 os << "type \"" << indexname << "\"\n";
4494 os << "literal \"true\"\n";
4497 skip_spaces_braces(p);
4498 preamble.registerAutomaticallyLoadedPackage("makeidx");
4499 if (preamble.use_indices() == "true")
4500 preamble.registerAutomaticallyLoadedPackage("splitidx");
4504 if (t.cs() == "printnomenclature") {
4506 string width_type = "";
4507 context.check_layout(os);
4508 begin_command_inset(os, "nomencl_print", "printnomenclature");
4509 // case of a custom width
4511 width = p.getArg('[', ']');
4512 width = translate_len(width);
4513 width_type = "custom";
4515 // case of no custom width
4516 // the case of no custom width but the width set
4517 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4518 // because the user could have set anything, not only the width
4519 // of the longest label (which would be width_type = "auto")
4520 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4521 if (label.empty() && width_type.empty())
4522 width_type = "none";
4523 os << "set_width \"" << width_type << "\"\n";
4524 if (width_type == "custom")
4525 os << "width \"" << width << '\"';
4527 skip_spaces_braces(p);
4528 preamble.registerAutomaticallyLoadedPackage("nomencl");
4532 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4533 context.check_layout(os);
4534 begin_inset(os, "script ");
4535 os << t.cs().substr(4) << '\n';
4536 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4537 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4539 if (t.cs() == "textsubscript")
4540 preamble.registerAutomaticallyLoadedPackage("subscript");
4544 if ((where = is_known(t.cs(), known_quotes))) {
4545 context.check_layout(os);
4546 begin_inset(os, "Quotes ");
4547 string quotetype = known_coded_quotes[where - known_quotes];
4548 // try to make a smart guess about the side
4549 Token const prev = p.prev_token();
4550 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4551 && prev.character() != '\n' && prev.character() != '~');
4552 quotetype = guessQuoteStyle(quotetype, opening);
4555 // LyX adds {} after the quote, so we have to eat
4556 // spaces here if there are any before a possible
4558 eat_whitespace(p, os, context, false);
4563 if ((where = is_known(t.cs(), known_sizes)) &&
4564 context.new_layout_allowed) {
4565 context.check_layout(os);
4566 TeXFont const oldFont = context.font;
4567 context.font.size = known_coded_sizes[where - known_sizes];
4568 output_font_change(os, oldFont, context.font);
4569 eat_whitespace(p, os, context, false);
4573 if ((where = is_known(t.cs(), known_font_families)) &&
4574 context.new_layout_allowed) {
4575 context.check_layout(os);
4576 TeXFont const oldFont = context.font;
4577 context.font.family =
4578 known_coded_font_families[where - known_font_families];
4579 output_font_change(os, oldFont, context.font);
4580 eat_whitespace(p, os, context, false);
4584 if ((where = is_known(t.cs(), known_font_series)) &&
4585 context.new_layout_allowed) {
4586 context.check_layout(os);
4587 TeXFont const oldFont = context.font;
4588 context.font.series =
4589 known_coded_font_series[where - known_font_series];
4590 output_font_change(os, oldFont, context.font);
4591 eat_whitespace(p, os, context, false);
4595 if ((where = is_known(t.cs(), known_font_shapes)) &&
4596 context.new_layout_allowed) {
4597 context.check_layout(os);
4598 TeXFont const oldFont = context.font;
4599 context.font.shape =
4600 known_coded_font_shapes[where - known_font_shapes];
4601 output_font_change(os, oldFont, context.font);
4602 eat_whitespace(p, os, context, false);
4605 if ((where = is_known(t.cs(), known_old_font_families)) &&
4606 context.new_layout_allowed) {
4607 context.check_layout(os);
4608 TeXFont const oldFont = context.font;
4609 context.font.init();
4610 context.font.size = oldFont.size;
4611 context.font.family =
4612 known_coded_font_families[where - known_old_font_families];
4613 output_font_change(os, oldFont, context.font);
4614 eat_whitespace(p, os, context, false);
4618 if ((where = is_known(t.cs(), known_old_font_series)) &&
4619 context.new_layout_allowed) {
4620 context.check_layout(os);
4621 TeXFont const oldFont = context.font;
4622 context.font.init();
4623 context.font.size = oldFont.size;
4624 context.font.series =
4625 known_coded_font_series[where - known_old_font_series];
4626 output_font_change(os, oldFont, context.font);
4627 eat_whitespace(p, os, context, false);
4631 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4632 context.new_layout_allowed) {
4633 context.check_layout(os);
4634 TeXFont const oldFont = context.font;
4635 context.font.init();
4636 context.font.size = oldFont.size;
4637 context.font.shape =
4638 known_coded_font_shapes[where - known_old_font_shapes];
4639 output_font_change(os, oldFont, context.font);
4640 eat_whitespace(p, os, context, false);
4644 if (t.cs() == "selectlanguage") {
4645 context.check_layout(os);
4646 // save the language for the case that a
4647 // \foreignlanguage is used
4648 context.font.language = babel2lyx(p.verbatim_item());
4649 os << "\n\\lang " << context.font.language << "\n";
4653 if (t.cs() == "foreignlanguage") {
4654 string const lang = babel2lyx(p.verbatim_item());
4655 parse_text_attributes(p, os, FLAG_ITEM, outer,
4657 context.font.language, lang);
4661 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4662 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4663 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4665 // We have to output the whole command if it has an option
4666 // because LyX doesn't support this yet, see bug #8214,
4667 // only if there is a single option specifying a variant, we can handle it.
4669 string langopts = p.getOpt();
4670 // check if the option contains a variant, if yes, extract it
4671 string::size_type pos_var = langopts.find("variant");
4672 string::size_type i = langopts.find(',');
4673 string::size_type k = langopts.find('=', pos_var);
4674 if (pos_var != string::npos && i == string::npos) {
4676 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4677 lang = preamble.polyglossia2lyx(variant);
4678 parse_text_attributes(p, os, FLAG_ITEM, outer,
4680 context.font.language, lang);
4682 output_ert_inset(os, t.asInput() + langopts, context);
4684 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4685 parse_text_attributes(p, os, FLAG_ITEM, outer,
4687 context.font.language, lang);
4692 if (t.cs() == "inputencoding") {
4693 // nothing to write here
4694 string const enc = subst(p.verbatim_item(), "\n", " ");
4695 p.setEncoding(enc, Encoding::inputenc);
4699 if (is_known(t.cs(), known_special_chars) ||
4700 (t.cs() == "protect" &&
4701 p.next_token().cat() == catEscape &&
4702 is_known(p.next_token().cs(), known_special_protect_chars))) {
4703 // LyX sometimes puts a \protect in front, so we have to ignore it
4705 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4706 known_special_chars);
4707 context.check_layout(os);
4708 os << known_coded_special_chars[where - known_special_chars];
4709 skip_spaces_braces(p);
4713 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4714 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4715 p.next_next_token().asInput() == "-") ||
4716 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4717 // LyX sometimes puts a \protect in front, so we have to ignore it
4718 if (t.cs() == "protect")
4720 context.check_layout(os);
4721 if (t.cs() == "nobreakdash")
4722 os << "\\SpecialChar nobreakdash\n";
4724 os << "\\SpecialChar endofsentence\n";
4729 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4730 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4731 || t.cs() == "%" || t.cs() == "-") {
4732 context.check_layout(os);
4734 os << "\\SpecialChar softhyphen\n";
4740 if (t.cs() == "char") {
4741 context.check_layout(os);
4742 if (p.next_token().character() == '`') {
4744 if (p.next_token().cs() == "\"") {
4749 output_ert_inset(os, "\\char`", context);
4752 output_ert_inset(os, "\\char", context);
4757 if (t.cs() == "verb") {
4758 context.check_layout(os);
4759 // set catcodes to verbatim early, just in case.
4760 p.setCatcodes(VERBATIM_CATCODES);
4761 string delim = p.get_token().asInput();
4762 Parser::Arg arg = p.verbatimStuff(delim);
4764 output_ert_inset(os, "\\verb" + delim
4765 + arg.second + delim, context);
4767 cerr << "invalid \\verb command. Skipping" << endl;
4771 // Problem: \= creates a tabstop inside the tabbing environment
4772 // and else an accent. In the latter case we really would want
4773 // \={o} instead of \= o.
4774 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4775 output_ert_inset(os, t.asInput(), context);
4779 if (t.cs() == "\\") {
4780 context.check_layout(os);
4782 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4783 else if (p.next_token().asInput() == "*") {
4785 // getOpt() eats the following space if there
4786 // is no optional argument, but that is OK
4787 // here since it has no effect in the output.
4788 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4791 begin_inset(os, "Newline newline");
4797 if (t.cs() == "newline" ||
4798 (t.cs() == "linebreak" && !p.hasOpt())) {
4799 context.check_layout(os);
4800 begin_inset(os, "Newline ");
4803 skip_spaces_braces(p);
4807 if (t.cs() == "input" || t.cs() == "include"
4808 || t.cs() == "verbatiminput"
4809 || t.cs() == "lstinputlisting"
4810 || t.cs() == "inputminted") {
4811 string name = t.cs();
4812 if (name == "verbatiminput"
4813 && p.next_token().asInput() == "*")
4814 name += p.get_token().asInput();
4815 context.check_layout(os);
4817 if (name == "lstinputlisting" && p.hasOpt()) {
4818 lstparams = p.getArg('[', ']');
4819 lstparams = subst(lstparams, "\n", " ");
4820 } else if (name == "inputminted") {
4821 name = "lstinputlisting";
4822 string const lang = p.getArg('{', '}');
4823 if (lang != "tex") {
4824 string cmd = "\\inputminted{" + lang + "}{";
4825 cmd += p.getArg('{', '}') + "}";
4826 output_ert_inset(os, cmd, context);
4829 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4830 minted_nonfloat_caption.erase(0,3);
4831 // extract label and caption from the already produced LyX code
4832 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4833 string const caption = nfc.front();
4835 vector<string>::iterator it =
4836 find(nfc.begin(), nfc.end(), "LatexCommand label");
4837 if (it != nfc.end()) {
4839 if (it != nfc.end())
4841 label = support::split(label, '"');
4844 minted_nonfloat_caption.clear();
4845 lstparams = "caption=" + caption;
4847 lstparams += ",label=" + label;
4848 lstparams = subst(lstparams, "\n", " ");
4851 string filename(normalize_filename(p.getArg('{', '}')));
4852 string const path = getMasterFilePath(true);
4853 // We want to preserve relative / absolute filenames,
4854 // therefore path is only used for testing
4855 if ((t.cs() == "include" || t.cs() == "input") &&
4856 !makeAbsPath(filename, path).exists()) {
4857 // The file extension is probably missing.
4858 // Now try to find it out.
4859 string const tex_name =
4860 find_file(filename, path,
4861 known_tex_extensions);
4862 if (!tex_name.empty())
4863 filename = tex_name;
4865 bool external = false;
4867 if (makeAbsPath(filename, path).exists()) {
4868 string const abstexname =
4869 makeAbsPath(filename, path).absFileName();
4870 string const absfigname =
4871 changeExtension(abstexname, ".fig");
4872 fix_child_filename(filename);
4873 string const lyxname = changeExtension(filename,
4874 roundtripMode() ? ".lyx.lyx" : ".lyx");
4875 string const abslyxname = makeAbsPath(
4876 lyxname, getParentFilePath(false)).absFileName();
4878 if (!skipChildren())
4879 external = FileName(absfigname).exists();
4880 if (t.cs() == "input" && !skipChildren()) {
4881 string const ext = getExtension(abstexname);
4883 // Combined PS/LaTeX:
4884 // x.eps, x.pstex_t (old xfig)
4885 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4886 FileName const absepsname(
4887 changeExtension(abstexname, ".eps"));
4888 FileName const abspstexname(
4889 changeExtension(abstexname, ".pstex"));
4890 bool const xfigeps =
4891 (absepsname.exists() ||
4892 abspstexname.exists()) &&
4895 // Combined PDF/LaTeX:
4896 // x.pdf, x.pdftex_t (old xfig)
4897 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4898 FileName const abspdfname(
4899 changeExtension(abstexname, ".pdf"));
4900 bool const xfigpdf =
4901 abspdfname.exists() &&
4902 (ext == "pdftex_t" || ext == "pdf_t");
4906 // Combined PS/PDF/LaTeX:
4907 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4908 string const absbase2(
4909 removeExtension(abstexname) + "_pspdftex");
4910 FileName const abseps2name(
4911 addExtension(absbase2, ".eps"));
4912 FileName const abspdf2name(
4913 addExtension(absbase2, ".pdf"));
4914 bool const xfigboth =
4915 abspdf2name.exists() &&
4916 abseps2name.exists() && ext == "pspdftex";
4918 xfig = xfigpdf || xfigeps || xfigboth;
4919 external = external && xfig;
4922 outname = changeExtension(filename, ".fig");
4923 FileName abssrc(changeExtension(abstexname, ".fig"));
4924 copy_file(abssrc, outname);
4926 // Don't try to convert, the result
4927 // would be full of ERT.
4929 FileName abssrc(abstexname);
4930 copy_file(abssrc, outname);
4931 } else if (t.cs() != "verbatiminput" &&
4933 tex2lyx(abstexname, FileName(abslyxname),
4936 // no need to call copy_file
4937 // tex2lyx creates the file
4940 FileName abssrc(abstexname);
4941 copy_file(abssrc, outname);
4944 cerr << "Warning: Could not find included file '"
4945 << filename << "'." << endl;
4949 begin_inset(os, "External\n");
4950 os << "\ttemplate XFig\n"
4951 << "\tfilename " << outname << '\n';
4952 registerExternalTemplatePackages("XFig");
4954 begin_command_inset(os, "include", name);
4955 outname = subst(outname, "\"", "\\\"");
4956 os << "preview false\n"
4957 "filename \"" << outname << "\"\n";
4958 if (!lstparams.empty())
4959 os << "lstparams \"" << lstparams << "\"\n";
4960 if (t.cs() == "verbatiminput")
4961 preamble.registerAutomaticallyLoadedPackage("verbatim");
4967 if (t.cs() == "bibliographystyle") {
4968 // store new bibliographystyle
4969 bibliographystyle = p.verbatim_item();
4970 // If any other command than \bibliography, \addcontentsline
4971 // and \nocite{*} follows, we need to output the style
4972 // (because it might be used by that command).
4973 // Otherwise, it will automatically be output by LyX.
4976 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4977 if (t2.cat() == catBegin)
4979 if (t2.cat() != catEscape)
4981 if (t2.cs() == "nocite") {
4982 if (p.getArg('{', '}') == "*")
4984 } else if (t2.cs() == "bibliography")
4986 else if (t2.cs() == "phantomsection") {
4990 else if (t2.cs() == "addcontentsline") {
4991 // get the 3 arguments of \addcontentsline
4994 contentslineContent = p.getArg('{', '}');
4995 // if the last argument is not \refname we must output
4996 if (contentslineContent == "\\refname")
5003 output_ert_inset(os,
5004 "\\bibliographystyle{" + bibliographystyle + '}',
5010 if (t.cs() == "phantomsection") {
5011 // we only support this if it occurs between
5012 // \bibliographystyle and \bibliography
5013 if (bibliographystyle.empty())
5014 output_ert_inset(os, "\\phantomsection", context);
5018 if (t.cs() == "addcontentsline") {
5019 context.check_layout(os);
5020 // get the 3 arguments of \addcontentsline
5021 string const one = p.getArg('{', '}');
5022 string const two = p.getArg('{', '}');
5023 string const three = p.getArg('{', '}');
5024 // only if it is a \refname, we support if for the bibtex inset
5025 if (contentslineContent != "\\refname") {
5026 output_ert_inset(os,
5027 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5033 else if (t.cs() == "bibliography") {
5034 context.check_layout(os);
5036 begin_command_inset(os, "bibtex", "bibtex");
5037 if (!btprint.empty()) {
5038 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5039 // clear the string because the next BibTeX inset can be without the
5040 // \nocite{*} option
5043 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5044 // Do we have addcontentsline?
5045 if (contentslineContent == "\\refname") {
5046 BibOpts = "bibtotoc";
5047 // clear string because next BibTeX inset can be without addcontentsline
5048 contentslineContent.clear();
5050 // Do we have a bibliographystyle set?
5051 if (!bibliographystyle.empty()) {
5052 if (BibOpts.empty())
5053 BibOpts = normalize_filename(bibliographystyle);
5055 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5056 // clear it because each bibtex entry has its style
5057 // and we need an empty string to handle \phantomsection
5058 bibliographystyle.clear();
5060 os << "options " << '"' << BibOpts << '"' << "\n";
5065 if (t.cs() == "printbibliography") {
5066 context.check_layout(os);
5068 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5069 vector<string> opts = getVectorFromString(bbloptions);
5070 vector<string>::iterator it =
5071 find(opts.begin(), opts.end(), "heading=bibintoc");
5072 if (it != opts.end()) {
5074 BibOpts = "bibtotoc";
5076 bbloptions = getStringFromVector(opts);
5077 begin_command_inset(os, "bibtex", "bibtex");
5078 if (!btprint.empty()) {
5079 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5080 // clear the string because the next BibTeX inset can be without the
5081 // \nocite{*} option
5085 for (auto const & bf : preamble.biblatex_bibliographies) {
5086 if (!bibfiles.empty())
5088 bibfiles += normalize_filename(bf);
5090 if (!bibfiles.empty())
5091 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5092 // Do we have addcontentsline?
5093 if (contentslineContent == "\\refname") {
5094 BibOpts = "bibtotoc";
5095 // clear string because next BibTeX inset can be without addcontentsline
5096 contentslineContent.clear();
5098 os << "options " << '"' << BibOpts << '"' << "\n";
5099 if (!bbloptions.empty())
5100 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5102 need_commentbib = false;
5106 if (t.cs() == "bibbysection") {
5107 context.check_layout(os);
5109 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5110 vector<string> opts = getVectorFromString(bbloptions);
5111 vector<string>::iterator it =
5112 find(opts.begin(), opts.end(), "heading=bibintoc");
5113 if (it != opts.end()) {
5115 BibOpts = "bibtotoc";
5117 bbloptions = getStringFromVector(opts);
5118 begin_command_inset(os, "bibtex", "bibtex");
5119 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5121 for (auto const & bf : preamble.biblatex_bibliographies) {
5122 if (!bibfiles.empty())
5124 bibfiles += normalize_filename(bf);
5126 if (!bibfiles.empty())
5127 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5128 os << "options " << '"' << BibOpts << '"' << "\n";
5129 if (!bbloptions.empty())
5130 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5132 need_commentbib = false;
5136 if (t.cs() == "parbox") {
5137 // Test whether this is an outer box of a shaded box
5139 // swallow arguments
5140 while (p.hasOpt()) {
5142 p.skip_spaces(true);
5145 p.skip_spaces(true);
5147 if (p.next_token().cat() == catBegin)
5149 p.skip_spaces(true);
5150 Token to = p.get_token();
5151 bool shaded = false;
5152 if (to.asInput() == "\\begin") {
5153 p.skip_spaces(true);
5154 if (p.getArg('{', '}') == "shaded")
5159 parse_outer_box(p, os, FLAG_ITEM, outer,
5160 context, "parbox", "shaded");
5162 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5163 "", "", t.cs(), "", "");
5167 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5168 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5169 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5170 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5174 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5175 string backgroundcolor;
5176 preamble.registerAutomaticallyLoadedPackage("xcolor");
5177 if (t.cs() == "fcolorbox") {
5178 string const framecolor = p.getArg('{', '}');
5179 backgroundcolor = p.getArg('{', '}');
5180 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5182 backgroundcolor = p.getArg('{', '}');
5183 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5188 // FIXME: due to the compiler limit of "if" nestings
5189 // the code for the alignment was put here
5190 // put them in their own if if this is fixed
5191 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5192 || t.cs() == "shadowsize"
5193 || t.cs() == "raggedleft" || t.cs() == "centering"
5194 || t.cs() == "raggedright") {
5195 if (t.cs() == "fboxrule")
5197 if (t.cs() == "fboxsep")
5199 if (t.cs() == "shadowsize")
5201 if (t.cs() != "raggedleft" && t.cs() != "centering"
5202 && t.cs() != "raggedright") {
5203 p.skip_spaces(true);
5204 while (p.good() && p.next_token().cat() != catSpace
5205 && p.next_token().cat() != catNewline
5206 && p.next_token().cat() != catEscape) {
5207 if (t.cs() == "fboxrule")
5208 fboxrule = fboxrule + p.get_token().asInput();
5209 if (t.cs() == "fboxsep")
5210 fboxsep = fboxsep + p.get_token().asInput();
5211 if (t.cs() == "shadowsize")
5212 shadow_size = shadow_size + p.get_token().asInput();
5215 output_ert_inset(os, t.asInput(), context);
5220 //\framebox() is part of the picture environment and different from \framebox{}
5221 //\framebox{} will be parsed by parse_outer_box
5222 if (t.cs() == "framebox") {
5223 if (p.next_token().character() == '(') {
5224 //the syntax is: \framebox(x,y)[position]{content}
5225 string arg = t.asInput();
5226 arg += p.getFullParentheseArg();
5227 arg += p.getFullOpt();
5228 eat_whitespace(p, os, context, false);
5229 output_ert_inset(os, arg + '{', context);
5230 parse_text(p, os, FLAG_ITEM, outer, context);
5231 output_ert_inset(os, "}", context);
5233 //the syntax is: \framebox[width][position]{content}
5234 string special = p.getFullOpt();
5235 special += p.getOpt();
5236 parse_outer_box(p, os, FLAG_ITEM, outer,
5237 context, t.cs(), special);
5242 //\makebox() is part of the picture environment and different from \makebox{}
5243 //\makebox{} will be parsed by parse_box
5244 if (t.cs() == "makebox") {
5245 if (p.next_token().character() == '(') {
5246 //the syntax is: \makebox(x,y)[position]{content}
5247 string arg = t.asInput();
5248 arg += p.getFullParentheseArg();
5249 arg += p.getFullOpt();
5250 eat_whitespace(p, os, context, false);
5251 output_ert_inset(os, arg + '{', context);
5252 parse_text(p, os, FLAG_ITEM, outer, context);
5253 output_ert_inset(os, "}", context);
5255 //the syntax is: \makebox[width][position]{content}
5256 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5257 "", "", t.cs(), "", "");
5261 if (t.cs() == "smallskip" ||
5262 t.cs() == "medskip" ||
5263 t.cs() == "bigskip" ||
5264 t.cs() == "vfill") {
5265 context.check_layout(os);
5266 begin_inset(os, "VSpace ");
5269 skip_spaces_braces(p);
5273 if ((where = is_known(t.cs(), known_spaces))) {
5274 context.check_layout(os);
5275 begin_inset(os, "space ");
5276 os << '\\' << known_coded_spaces[where - known_spaces]
5279 // LaTeX swallows whitespace after all spaces except
5280 // "\\,". We have to do that here, too, because LyX
5281 // adds "{}" which would make the spaces significant.
5283 eat_whitespace(p, os, context, false);
5284 // LyX adds "{}" after all spaces except "\\ " and
5285 // "\\,", so we have to remove "{}".
5286 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5287 // remove the braces after "\\,", too.
5293 if (t.cs() == "newpage" ||
5294 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5295 t.cs() == "clearpage" ||
5296 t.cs() == "cleardoublepage") {
5297 context.check_layout(os);
5298 begin_inset(os, "Newpage ");
5301 skip_spaces_braces(p);
5305 if (t.cs() == "DeclareRobustCommand" ||
5306 t.cs() == "DeclareRobustCommandx" ||
5307 t.cs() == "newcommand" ||
5308 t.cs() == "newcommandx" ||
5309 t.cs() == "providecommand" ||
5310 t.cs() == "providecommandx" ||
5311 t.cs() == "renewcommand" ||
5312 t.cs() == "renewcommandx") {
5313 // DeclareRobustCommand, DeclareRobustCommandx,
5314 // providecommand and providecommandx could be handled
5315 // by parse_command(), but we need to call
5316 // add_known_command() here.
5317 string name = t.asInput();
5318 if (p.next_token().asInput() == "*") {
5319 // Starred form. Eat '*'
5323 string const command = p.verbatim_item();
5324 string const opt1 = p.getFullOpt();
5325 string const opt2 = p.getFullOpt();
5326 add_known_command(command, opt1, !opt2.empty());
5327 string const ert = name + '{' + command + '}' +
5329 '{' + p.verbatim_item() + '}';
5331 if (t.cs() == "DeclareRobustCommand" ||
5332 t.cs() == "DeclareRobustCommandx" ||
5333 t.cs() == "providecommand" ||
5334 t.cs() == "providecommandx" ||
5335 name[name.length()-1] == '*')
5336 output_ert_inset(os, ert, context);
5338 context.check_layout(os);
5339 begin_inset(os, "FormulaMacro");
5346 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5347 // let could be handled by parse_command(),
5348 // but we need to call add_known_command() here.
5349 string ert = t.asInput();
5352 if (p.next_token().cat() == catBegin) {
5353 name = p.verbatim_item();
5354 ert += '{' + name + '}';
5356 name = p.verbatim_item();
5361 if (p.next_token().cat() == catBegin) {
5362 command = p.verbatim_item();
5363 ert += '{' + command + '}';
5365 command = p.verbatim_item();
5368 // If command is known, make name known too, to parse
5369 // its arguments correctly. For this reason we also
5370 // have commands in syntax.default that are hardcoded.
5371 CommandMap::iterator it = known_commands.find(command);
5372 if (it != known_commands.end())
5373 known_commands[t.asInput()] = it->second;
5374 output_ert_inset(os, ert, context);
5378 if (t.cs() == "hspace" || t.cs() == "vspace") {
5381 string name = t.asInput();
5382 string const length = p.verbatim_item();
5385 bool valid = splitLatexLength(length, valstring, unit);
5386 bool known_hspace = false;
5387 bool known_vspace = false;
5388 bool known_unit = false;
5391 istringstream iss(valstring);
5394 if (t.cs()[0] == 'h') {
5395 if (unit == "\\fill") {
5400 known_hspace = true;
5403 if (unit == "\\smallskipamount") {
5405 known_vspace = true;
5406 } else if (unit == "\\medskipamount") {
5408 known_vspace = true;
5409 } else if (unit == "\\bigskipamount") {
5411 known_vspace = true;
5412 } else if (unit == "\\fill") {
5414 known_vspace = true;
5418 if (!known_hspace && !known_vspace) {
5419 switch (unitFromString(unit)) {
5435 //unitFromString(unit) fails for relative units like Length::PCW
5436 // therefore handle them separately
5437 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5438 || unit == "\\textwidth" || unit == "\\linewidth"
5439 || unit == "\\textheight" || unit == "\\paperheight"
5440 || unit == "\\baselineskip")
5448 // check for glue lengths
5449 bool is_gluelength = false;
5450 string gluelength = length;
5451 string::size_type i = length.find(" minus");
5452 if (i == string::npos) {
5453 i = length.find(" plus");
5454 if (i != string::npos)
5455 is_gluelength = true;
5457 is_gluelength = true;
5458 // if yes transform "9xx minus 8yy plus 7zz"
5460 if (is_gluelength) {
5461 i = gluelength.find(" minus");
5462 if (i != string::npos)
5463 gluelength.replace(i, 7, "-");
5464 i = gluelength.find(" plus");
5465 if (i != string::npos)
5466 gluelength.replace(i, 6, "+");
5469 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5470 // Literal horizontal length or known variable
5471 context.check_layout(os);
5472 begin_inset(os, "space ");
5480 if (known_unit && !known_hspace)
5481 os << "\n\\length " << translate_len(length);
5483 os << "\n\\length " << gluelength;
5485 } else if (known_unit || known_vspace || is_gluelength) {
5486 // Literal vertical length or known variable
5487 context.check_layout(os);
5488 begin_inset(os, "VSpace ");
5491 if (known_unit && !known_vspace)
5492 os << translate_len(length);
5499 // LyX can't handle other length variables in Inset VSpace/space
5504 output_ert_inset(os, name + '{' + unit + '}', context);
5505 else if (value == -1.0)
5506 output_ert_inset(os, name + "{-" + unit + '}', context);
5508 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5510 output_ert_inset(os, name + '{' + length + '}', context);
5515 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5516 // might be one or several options or a star.
5517 // The single '=' is meant here.
5518 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5522 context.check_layout(os);
5523 // store the latexparam here. This is eaten in parse_text_in_inset
5524 context.latexparam = newinsetlayout->latexparam();
5525 docstring name = newinsetlayout->name();
5526 bool const caption = name.find(from_ascii("Caption:")) == 0;
5528 // Already done for floating minted listings.
5529 if (minted_float.empty()) {
5530 begin_inset(os, "Caption ");
5531 os << to_utf8(name.substr(8)) << '\n';
5534 // FIXME: what do we do if the prefix is not Flex: ?
5535 if (prefixIs(name, from_ascii("Flex:")))
5537 begin_inset(os, "Flex ");
5538 os << to_utf8(name) << '\n'
5539 << "status collapsed\n";
5541 if (!minted_float.empty()) {
5542 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5543 } else if (newinsetlayout->isPassThru()) {
5544 // set catcodes to verbatim early, just in case.
5545 p.setCatcodes(VERBATIM_CATCODES);
5546 string delim = p.get_token().asInput();
5548 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5549 //FIXME: handle error condition
5550 string const arg = p.verbatimStuff("}").second;
5551 Context newcontext(true, context.textclass);
5552 if (newinsetlayout->forcePlainLayout())
5553 newcontext.layout = &context.textclass.plainLayout();
5554 output_ert(os, arg, newcontext);
5556 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5557 context.latexparam.clear();
5560 // Minted caption insets are not closed here because
5561 // we collect everything into the caption.
5562 if (minted_float.empty())
5567 // The single '=' is meant here.
5568 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5572 context.check_layout(os);
5573 docstring const name = newinsetlayout->name();
5574 bool const caption = name.find(from_ascii("Caption:")) == 0;
5576 // Already done for floating minted listings.
5577 if (minted_float.empty()) {
5578 begin_inset(os, "Caption ");
5579 os << to_utf8(name.substr(8)) << '\n';
5582 begin_inset(os, "Flex ");
5583 os << to_utf8(name) << '\n'
5584 << "status collapsed\n";
5586 if (!minted_float.empty()) {
5587 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5588 } else if (newinsetlayout->isPassThru()) {
5589 // set catcodes to verbatim early, just in case.
5590 p.setCatcodes(VERBATIM_CATCODES);
5591 string delim = p.get_token().asInput();
5593 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5594 //FIXME: handle error condition
5595 string const arg = p.verbatimStuff("}").second;
5596 Context newcontext(true, context.textclass);
5597 if (newinsetlayout->forcePlainLayout())
5598 newcontext.layout = &context.textclass.plainLayout();
5599 output_ert(os, arg, newcontext);
5601 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5604 // Minted caption insets are not closed here because
5605 // we collect everything into the caption.
5606 if (minted_float.empty())
5611 if (t.cs() == "includepdf") {
5613 string const arg = p.getArg('[', ']');
5614 map<string, string> opts;
5615 vector<string> keys;
5616 split_map(arg, opts, keys);
5617 string name = normalize_filename(p.verbatim_item());
5618 string const path = getMasterFilePath(true);
5619 // We want to preserve relative / absolute filenames,
5620 // therefore path is only used for testing
5621 if (!makeAbsPath(name, path).exists()) {
5622 // The file extension is probably missing.
5623 // Now try to find it out.
5624 char const * const pdfpages_format[] = {"pdf", 0};
5625 string const pdftex_name =
5626 find_file(name, path, pdfpages_format);
5627 if (!pdftex_name.empty()) {
5632 FileName const absname = makeAbsPath(name, path);
5633 if (absname.exists())
5635 fix_child_filename(name);
5636 copy_file(absname, name);
5638 cerr << "Warning: Could not find file '"
5639 << name << "'." << endl;
5641 context.check_layout(os);
5642 begin_inset(os, "External\n\ttemplate ");
5643 os << "PDFPages\n\tfilename "
5645 // parse the options
5646 if (opts.find("pages") != opts.end())
5647 os << "\textra LaTeX \"pages="
5648 << opts["pages"] << "\"\n";
5649 if (opts.find("angle") != opts.end())
5650 os << "\trotateAngle "
5651 << opts["angle"] << '\n';
5652 if (opts.find("origin") != opts.end()) {
5654 string const opt = opts["origin"];
5655 if (opt == "tl") ss << "topleft";
5656 if (opt == "bl") ss << "bottomleft";
5657 if (opt == "Bl") ss << "baselineleft";
5658 if (opt == "c") ss << "center";
5659 if (opt == "tc") ss << "topcenter";
5660 if (opt == "bc") ss << "bottomcenter";
5661 if (opt == "Bc") ss << "baselinecenter";
5662 if (opt == "tr") ss << "topright";
5663 if (opt == "br") ss << "bottomright";
5664 if (opt == "Br") ss << "baselineright";
5665 if (!ss.str().empty())
5666 os << "\trotateOrigin " << ss.str() << '\n';
5668 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5670 if (opts.find("width") != opts.end())
5672 << translate_len(opts["width"]) << '\n';
5673 if (opts.find("height") != opts.end())
5675 << translate_len(opts["height"]) << '\n';
5676 if (opts.find("keepaspectratio") != opts.end())
5677 os << "\tkeepAspectRatio\n";
5679 context.check_layout(os);
5680 registerExternalTemplatePackages("PDFPages");
5684 if (t.cs() == "loadgame") {
5686 string name = normalize_filename(p.verbatim_item());
5687 string const path = getMasterFilePath(true);
5688 // We want to preserve relative / absolute filenames,
5689 // therefore path is only used for testing
5690 if (!makeAbsPath(name, path).exists()) {
5691 // The file extension is probably missing.
5692 // Now try to find it out.
5693 char const * const lyxskak_format[] = {"fen", 0};
5694 string const lyxskak_name =
5695 find_file(name, path, lyxskak_format);
5696 if (!lyxskak_name.empty())
5697 name = lyxskak_name;
5699 FileName const absname = makeAbsPath(name, path);
5700 if (absname.exists())
5702 fix_child_filename(name);
5703 copy_file(absname, name);
5705 cerr << "Warning: Could not find file '"
5706 << name << "'." << endl;
5707 context.check_layout(os);
5708 begin_inset(os, "External\n\ttemplate ");
5709 os << "ChessDiagram\n\tfilename "
5712 context.check_layout(os);
5713 // after a \loadgame follows a \showboard
5714 if (p.get_token().asInput() == "showboard")
5716 registerExternalTemplatePackages("ChessDiagram");
5720 // try to see whether the string is in unicodesymbols
5721 // Only use text mode commands, since we are in text mode here,
5722 // and math commands may be invalid (bug 6797)
5723 string name = t.asInput();
5724 // handle the dingbats, cyrillic and greek
5725 if (name == "\\ding" || name == "\\textcyr" ||
5726 (name == "\\textgreek" && !preamble.usePolyglossia()))
5727 name = name + '{' + p.getArg('{', '}') + '}';
5728 // handle the ifsym characters
5729 else if (name == "\\textifsymbol") {
5730 string const optif = p.getFullOpt();
5731 string const argif = p.getArg('{', '}');
5732 name = name + optif + '{' + argif + '}';
5734 // handle the \ascii characters
5735 // the case of \ascii within braces, as LyX outputs it, is already
5736 // handled for t.cat() == catBegin
5737 else if (name == "\\ascii") {
5738 // the code is "\asci\xxx"
5739 name = "{" + name + p.get_token().asInput() + "}";
5742 // handle some TIPA special characters
5743 else if (preamble.isPackageUsed("tipa")) {
5744 if (name == "\\s") {
5745 // fromLaTeXCommand() does not yet
5746 // recognize tipa short cuts
5747 name = "\\textsyllabic";
5748 } else if (name == "\\=" &&
5749 p.next_token().asInput() == "*") {
5750 // fromLaTeXCommand() does not yet
5751 // recognize tipa short cuts
5753 name = "\\textsubbar";
5754 } else if (name == "\\textdoublevertline") {
5755 // FIXME: This is not correct,
5756 // \textvertline is higher than \textbardbl
5757 name = "\\textbardbl";
5759 } else if (name == "\\!" ) {
5760 if (p.next_token().asInput() == "b") {
5761 p.get_token(); // eat 'b'
5764 } else if (p.next_token().asInput() == "d") {
5768 } else if (p.next_token().asInput() == "g") {
5772 } else if (p.next_token().asInput() == "G") {
5774 name = "\\texthtscg";
5776 } else if (p.next_token().asInput() == "j") {
5778 name = "\\texthtbardotlessj";
5780 } else if (p.next_token().asInput() == "o") {
5782 name = "\\textbullseye";
5785 } else if (name == "\\*" ) {
5786 if (p.next_token().asInput() == "k") {
5788 name = "\\textturnk";
5790 } else if (p.next_token().asInput() == "r") {
5791 p.get_token(); // eat 'b'
5792 name = "\\textturnr";
5794 } else if (p.next_token().asInput() == "t") {
5796 name = "\\textturnt";
5798 } else if (p.next_token().asInput() == "w") {
5800 name = "\\textturnw";
5805 if ((name.size() == 2 &&
5806 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5807 p.next_token().asInput() != "*") ||
5808 is_known(name.substr(1), known_tipa_marks)) {
5809 // name is a command that corresponds to a
5810 // combining character in unicodesymbols.
5811 // Append the argument, fromLaTeXCommand()
5812 // will either convert it to a single
5813 // character or a combining sequence.
5814 name += '{' + p.verbatim_item() + '}';
5816 // now get the character from unicodesymbols
5820 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5821 Encodings::TEXT_CMD, termination, rem, &req));
5823 context.check_layout(os);
5826 output_ert_inset(os, to_utf8(rem), context);
5828 skip_spaces_braces(p);
5829 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5830 preamble.registerAutomaticallyLoadedPackage(*it);
5832 //cerr << "#: " << t << " mode: " << mode << endl;
5833 // heuristic: read up to next non-nested space
5835 string s = t.asInput();
5836 string z = p.verbatim_item();
5837 while (p.good() && z != " " && !z.empty()) {
5838 //cerr << "read: " << z << endl;
5840 z = p.verbatim_item();
5842 cerr << "found ERT: " << s << endl;
5843 output_ert_inset(os, s + ' ', context);
5846 if (t.asInput() == name &&
5847 p.next_token().asInput() == "*") {
5848 // Starred commands like \vspace*{}
5849 p.get_token(); // Eat '*'
5852 if (!parse_command(name, p, os, outer, context))
5853 output_ert_inset(os, name, context);
5859 string guessLanguage(Parser & p, string const & lang)
5861 typedef std::map<std::string, size_t> LangMap;
5862 // map from language names to number of characters
5865 for (char const * const * i = supported_CJK_languages; *i; i++)
5866 used[string(*i)] = 0;
5869 Token const t = p.get_token();
5870 // comments are not counted for any language
5871 if (t.cat() == catComment)
5873 // commands are not counted as well, but we need to detect
5874 // \begin{CJK} and switch encoding if needed
5875 if (t.cat() == catEscape) {
5876 if (t.cs() == "inputencoding") {
5877 string const enc = subst(p.verbatim_item(), "\n", " ");
5878 p.setEncoding(enc, Encoding::inputenc);
5881 if (t.cs() != "begin")
5884 // Non-CJK content is counted for lang.
5885 // We do not care about the real language here:
5886 // If we have more non-CJK contents than CJK contents,
5887 // we simply use the language that was specified as
5888 // babel main language.
5889 used[lang] += t.asInput().length();
5892 // Now we are starting an environment
5894 string const name = p.getArg('{', '}');
5895 if (name != "CJK") {
5899 // It is a CJK environment
5901 /* name = */ p.getArg('{', '}');
5902 string const encoding = p.getArg('{', '}');
5903 /* mapping = */ p.getArg('{', '}');
5904 string const encoding_old = p.getEncoding();
5905 char const * const * const where =
5906 is_known(encoding, supported_CJK_encodings);
5908 p.setEncoding(encoding, Encoding::CJK);
5910 p.setEncoding("UTF-8");
5911 string const text = p.ertEnvironment("CJK");
5912 p.setEncoding(encoding_old);
5915 // ignore contents in unknown CJK encoding
5918 // the language of the text
5920 supported_CJK_languages[where - supported_CJK_encodings];
5921 used[cjk] += text.length();
5923 LangMap::const_iterator use = used.begin();
5924 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5925 if (it->second > use->second)
5932 void check_comment_bib(ostream & os, Context & context)
5934 if (!need_commentbib)
5936 // We have a bibliography database, but no bibliography with biblatex
5937 // which is completely valid. Insert a bibtex inset in a note.
5938 context.check_layout(os);
5939 begin_inset(os, "Note Note\n");
5940 os << "status open\n";
5941 os << "\\begin_layout Plain Layout\n";
5942 begin_command_inset(os, "bibtex", "bibtex");
5944 for (auto const & bf : preamble.biblatex_bibliographies) {
5945 if (!bibfiles.empty())
5947 bibfiles += normalize_filename(bf);
5949 if (!bibfiles.empty())
5950 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5951 end_inset(os);// Bibtex
5952 os << "\\end_layout\n";
5953 end_inset(os);// Note