2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, string, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
68 output_arguments(os, p, outer, false, string(), newcontext,
70 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space", ",",
320 "thinspace", "quad", "qquad", "enspace", "enskip",
321 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
322 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
323 "upbracefill", "downbracefill", 0};
325 /// the same as known_spaces with .lyx names
326 char const * const known_coded_spaces[] = { "space{}", "space{}",
327 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
328 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
329 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
330 "upbracefill{}", "downbracefill{}", 0};
332 /// known TIPA combining diacritical marks
333 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
334 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
335 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
336 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
337 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
338 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
339 "textsubring", "textsubbar", 0};
341 /// TIPA tones that need special handling
342 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
344 // string to store the float type to be able to determine the type of subfloats
345 string float_type = "";
347 // string to store the float status of minted listings
348 string minted_float = "";
350 // whether a caption has been parsed for a floating minted listing
351 bool minted_float_has_caption = false;
353 // The caption for non-floating minted listings
354 string minted_nonfloat_caption = "";
356 // Characters that have to be escaped by \\ in LaTeX
357 char const * const known_escaped_chars[] = {
358 "&", "_", "$", "%", "#", "^", "{", "}", 0};
361 /// splits "x=z, y=b" into a map and an ordered keyword vector
362 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
367 keys.resize(v.size());
368 for (size_t i = 0; i < v.size(); ++i) {
369 size_t const pos = v[i].find('=');
370 string const index = trimSpaceAndEol(v[i].substr(0, pos));
371 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
379 * Split a LaTeX length into value and unit.
380 * The latter can be a real unit like "pt", or a latex length variable
381 * like "\textwidth". The unit may contain additional stuff like glue
382 * lengths, but we don't care, because such lengths are ERT anyway.
383 * \returns true if \p value and \p unit are valid.
385 bool splitLatexLength(string const & len, string & value, string & unit)
389 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
390 //'4,5' is a valid LaTeX length number. Change it to '4.5'
391 string const length = subst(len, ',', '.');
392 if (i == string::npos)
395 if (len[0] == '\\') {
396 // We had something like \textwidth without a factor
402 value = trimSpaceAndEol(string(length, 0, i));
406 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
407 if (contains(len, '\\'))
408 unit = trimSpaceAndEol(string(len, i));
410 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
415 /// A simple function to translate a latex length to something LyX can
416 /// understand. Not perfect, but rather best-effort.
417 bool translate_len(string const & length, string & valstring, string & unit)
419 if (!splitLatexLength(length, valstring, unit))
421 // LyX uses percent values
423 istringstream iss(valstring);
428 string const percentval = oss.str();
430 if (unit.empty() || unit[0] != '\\')
432 string::size_type const i = unit.find(' ');
433 string const endlen = (i == string::npos) ? string() : string(unit, i);
434 if (unit == "\\textwidth") {
435 valstring = percentval;
436 unit = "text%" + endlen;
437 } else if (unit == "\\columnwidth") {
438 valstring = percentval;
439 unit = "col%" + endlen;
440 } else if (unit == "\\paperwidth") {
441 valstring = percentval;
442 unit = "page%" + endlen;
443 } else if (unit == "\\linewidth") {
444 valstring = percentval;
445 unit = "line%" + endlen;
446 } else if (unit == "\\paperheight") {
447 valstring = percentval;
448 unit = "pheight%" + endlen;
449 } else if (unit == "\\textheight") {
450 valstring = percentval;
451 unit = "theight%" + endlen;
452 } else if (unit == "\\baselineskip") {
453 valstring = percentval;
454 unit = "baselineskip%" + endlen;
460 /// If we have ambiguous quotation marks, make a smart guess
461 /// based on main quote style
462 string guessQuoteStyle(string in, bool const opening)
465 if (prefixIs(in, "qr")) {// straight quote
467 res = subst(res, "r", "l");
468 } else if (in == "eld") {// ``
469 if (preamble.quotesStyle() == "german")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "russian")
477 } else if (in == "erd") {// ''
478 if (preamble.quotesStyle() == "polish")
480 else if (preamble.quotesStyle() == "british")
482 else if (preamble.quotesStyle() == "french")
484 else if (preamble.quotesStyle() == "swedish")
485 res = opening ? "sld" : "srd";
486 } else if (in == "els") {// `
487 if (preamble.quotesStyle() == "german")
489 else if (preamble.quotesStyle() == "british")
491 } else if (in == "ers") {// '
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sls" : "srs";
498 } else if (in == "ard") {// >>
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ald") {// <<
506 if (preamble.quotesStyle() == "swiss")
508 else if (preamble.quotesStyle() == "french")
510 else if (preamble.quotesStyle() == "russian")
512 } else if (in == "ars") {// >
513 if (preamble.quotesStyle() == "swiss")
515 } else if (in == "als") {// <
516 if (preamble.quotesStyle() == "swiss")
518 } else if (in == "gld") {// ,,
519 if (preamble.quotesStyle() == "polish")
521 else if (preamble.quotesStyle() == "russian")
523 } else if (in == "gls") {// ,
524 if (preamble.quotesStyle() == "polish")
531 string const fromPolyglossiaEnvironment(string const s)
533 // Since \arabic is taken by the LaTeX kernel,
534 // the Arabic polyglossia environment is upcased
542 string uncapitalize(string const s)
544 docstring in = from_ascii(s);
545 char_type t = lowercase(s[0]);
551 bool isCapitalized(string const s)
553 docstring in = from_ascii(s);
554 char_type t = uppercase(s[0]);
556 return to_ascii(in) == s;
563 string translate_len(string const & length)
567 if (translate_len(length, value, unit))
569 // If the input is invalid, return what we have.
577 * Translates a LaTeX length into \p value, \p unit and
578 * \p special parts suitable for a box inset.
579 * The difference from translate_len() is that a box inset knows about
580 * some special "units" that are stored in \p special.
582 void translate_box_len(string const & length, string & value, string & unit, string & special)
584 if (translate_len(length, value, unit)) {
585 if (unit == "\\height" || unit == "\\depth" ||
586 unit == "\\totalheight" || unit == "\\width") {
587 special = unit.substr(1);
588 // The unit is not used, but LyX requires a dummy setting
600 void begin_inset(ostream & os, string const & name)
602 os << "\n\\begin_inset " << name;
606 void begin_command_inset(ostream & os, string const & name,
607 string const & latexname)
609 begin_inset(os, "CommandInset ");
610 os << name << "\nLatexCommand " << latexname << '\n';
614 void end_inset(ostream & os)
616 os << "\n\\end_inset\n\n";
620 bool skip_braces(Parser & p)
622 if (p.next_token().cat() != catBegin)
625 if (p.next_token().cat() == catEnd) {
634 /// replace LaTeX commands in \p s from the unicodesymbols file with their
636 pair<bool, docstring> convert_unicodesymbols(docstring s)
640 for (size_t i = 0; i < s.size();) {
649 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
650 Encodings::TEXT_CMD, termination, rem, &req));
651 set<string>::const_iterator it = req.begin();
652 set<string>::const_iterator en = req.end();
653 for (; it != en; ++it)
654 preamble.registerAutomaticallyLoadedPackage(*it);
657 if (s.empty() || s[0] != '\\')
661 for (auto const & c : known_escaped_chars)
662 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
667 return make_pair(res, os.str());
671 /// try to convert \p s to a valid InsetCommand argument
672 /// return whether this succeeded. If not, these command insets
673 /// get the "literate" flag.
674 pair<bool, string> convert_latexed_command_inset_arg(string s)
676 bool success = false;
678 // since we don't know the input encoding we can't use from_utf8
679 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
681 s = to_utf8(res.second);
683 // LyX cannot handle newlines in a latex command
684 return make_pair(success, subst(s, "\n", " "));
687 /// try to convert \p s to a valid InsetCommand argument
688 /// without trying to recode macros.
689 string convert_literate_command_inset_arg(string s)
691 // LyX cannot handle newlines in a latex command
692 return subst(s, "\n", " ");
695 void output_ert(ostream & os, string const & s, Context & context)
697 context.check_layout(os);
698 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
700 os << "\n\\backslash\n";
701 else if (*it == '\n') {
702 context.new_paragraph(os);
703 context.check_layout(os);
707 context.check_end_layout(os);
711 void output_ert_inset(ostream & os, string const & s, Context & context)
713 // We must have a valid layout before outputting the ERT inset.
714 context.check_layout(os);
715 Context newcontext(true, context.textclass);
716 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
717 if (layout.forcePlainLayout())
718 newcontext.layout = &context.textclass.plainLayout();
719 begin_inset(os, "ERT");
720 os << "\nstatus collapsed\n";
721 output_ert(os, s, newcontext);
726 void output_comment(Parser & p, ostream & os, string const & s,
729 if (p.next_token().cat() == catNewline)
730 output_ert_inset(os, '%' + s, context);
732 output_ert_inset(os, '%' + s + '\n', context);
736 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
737 string const & latexparam = string())
739 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
742 if (checkModule(name, command))
743 return findLayoutWithoutModule(textclass, name, command, latexparam);
748 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
749 string const & latexparam = string())
751 InsetLayout const * insetlayout =
752 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
755 if (checkModule(name, command))
756 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
761 void eat_whitespace(Parser &, ostream &, Context &, bool);
765 * Skips whitespace and braces.
766 * This should be called after a command has been parsed that is not put into
767 * ERT, and where LyX adds "{}" if needed.
769 void skip_spaces_braces(Parser & p, bool keepws = false)
771 /* The following four examples produce the same typeset output and
772 should be handled by this function:
780 // Unfortunately we need to skip comments, too.
781 // We can't use eat_whitespace since writing them after the {}
782 // results in different output in some cases.
783 bool const skipped_spaces = p.skip_spaces(true);
784 bool const skipped_braces = skip_braces(p);
785 if (keepws && skipped_spaces && !skipped_braces)
786 // put back the space (it is better handled by check_space)
787 p.unskip_spaces(true);
791 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
792 Context & context, Layout::LaTeXArgMap const & latexargs)
794 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
796 context.check_layout(os);
802 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
803 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
804 for (; lait != laend; ++lait) {
806 eat_whitespace(p, os, context, false);
807 if (lait->second.mandatory) {
808 if (p.next_token().cat() != catBegin)
810 string ldelim = to_utf8(lait->second.ldelim);
811 string rdelim = to_utf8(lait->second.rdelim);
816 p.get_token(); // eat ldelim
817 if (ldelim.size() > 1)
818 p.get_token(); // eat ldelim
820 context.check_layout(os);
823 begin_inset(os, "Argument ");
826 os << i << "\nstatus collapsed\n\n";
827 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
830 string ldelim = to_utf8(lait->second.ldelim);
831 string rdelim = to_utf8(lait->second.rdelim);
836 string tok = p.next_token().asInput();
837 // we only support delimiters with max 2 chars for now.
838 if (ldelim.size() > 1)
839 tok += p.next_next_token().asInput();
840 if (p.next_token().cat() == catEscape || tok != ldelim)
842 p.get_token(); // eat ldelim
843 if (ldelim.size() > 1)
844 p.get_token(); // eat ldelim
846 context.check_layout(os);
849 begin_inset(os, "Argument ");
852 os << i << "\nstatus collapsed\n\n";
853 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
856 eat_whitespace(p, os, context, false);
861 void output_command_layout(ostream & os, Parser & p, bool outer,
862 Context & parent_context,
863 Layout const * newlayout)
865 TeXFont const oldFont = parent_context.font;
866 // save the current font size
867 string const size = oldFont.size;
868 // reset the font size to default, because the font size switches
869 // don't affect section headings and the like
870 parent_context.font.size = Context::normalfont.size;
871 // we only need to write the font change if we have an open layout
872 if (!parent_context.atParagraphStart())
873 output_font_change(os, oldFont, parent_context.font);
874 parent_context.check_end_layout(os);
875 Context context(true, parent_context.textclass, newlayout,
876 parent_context.layout, parent_context.font);
877 if (parent_context.deeper_paragraph) {
878 // We are beginning a nested environment after a
879 // deeper paragraph inside the outer list environment.
880 // Therefore we don't need to output a "begin deeper".
881 context.need_end_deeper = true;
883 context.check_deeper(os);
884 output_arguments(os, p, outer, true, string(), context,
885 context.layout->latexargs());
886 // If we have a latex param, we eat it here.
887 if (!parent_context.latexparam.empty()) {
889 Context dummy(true, parent_context.textclass);
890 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
891 string(1, parent_context.latexparam.back()));
893 parse_text(p, os, FLAG_ITEM, outer, context);
894 output_arguments(os, p, outer, false, "post", context,
895 context.layout->postcommandargs());
896 context.check_end_layout(os);
897 if (parent_context.deeper_paragraph) {
898 // We must suppress the "end deeper" because we
899 // suppressed the "begin deeper" above.
900 context.need_end_deeper = false;
902 context.check_end_deeper(os);
903 // We don't need really a new paragraph, but
904 // we must make sure that the next item gets a \begin_layout.
905 parent_context.new_paragraph(os);
906 // Set the font size to the original value. No need to output it here
907 // (Context::begin_layout() will do that if needed)
908 parent_context.font.size = size;
913 * Output a space if necessary.
914 * This function gets called for every whitespace token.
916 * We have three cases here:
917 * 1. A space must be suppressed. Example: The lyxcode case below
918 * 2. A space may be suppressed. Example: Spaces before "\par"
919 * 3. A space must not be suppressed. Example: A space between two words
921 * We currently handle only 1. and 3 and from 2. only the case of
922 * spaces before newlines as a side effect.
924 * 2. could be used to suppress as many spaces as possible. This has two effects:
925 * - Reimporting LyX generated LaTeX files changes almost no whitespace
926 * - Superflous whitespace from non LyX generated LaTeX files is removed.
927 * The drawback is that the logic inside the function becomes
928 * complicated, and that is the reason why it is not implemented.
930 void check_space(Parser & p, ostream & os, Context & context)
932 Token const next = p.next_token();
933 Token const curr = p.curr_token();
934 // A space before a single newline and vice versa must be ignored
935 // LyX emits a newline before \end{lyxcode}.
936 // This newline must be ignored,
937 // otherwise LyX will add an additional protected space.
938 if (next.cat() == catSpace ||
939 next.cat() == catNewline ||
940 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
943 context.check_layout(os);
949 * Parse all arguments of \p command
951 void parse_arguments(string const & command,
952 vector<ArgumentType> const & template_arguments,
953 Parser & p, ostream & os, bool outer, Context & context)
955 string ert = command;
956 size_t no_arguments = template_arguments.size();
957 for (size_t i = 0; i < no_arguments; ++i) {
958 switch (template_arguments[i]) {
961 // This argument contains regular LaTeX
962 output_ert_inset(os, ert + '{', context);
963 eat_whitespace(p, os, context, false);
964 if (template_arguments[i] == required)
965 parse_text(p, os, FLAG_ITEM, outer, context);
967 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
971 // This argument consists only of a single item.
972 // The presence of '{' or not must be preserved.
974 if (p.next_token().cat() == catBegin)
975 ert += '{' + p.verbatim_item() + '}';
977 ert += p.verbatim_item();
981 // This argument may contain special characters
982 ert += '{' + p.verbatim_item() + '}';
986 // true because we must not eat whitespace
987 // if an optional arg follows we must not strip the
988 // brackets from this one
989 if (i < no_arguments - 1 &&
990 template_arguments[i+1] == optional)
991 ert += p.getFullOpt(true);
993 ert += p.getOpt(true);
997 output_ert_inset(os, ert, context);
1002 * Check whether \p command is a known command. If yes,
1003 * handle the command with all arguments.
1004 * \return true if the command was parsed, false otherwise.
1006 bool parse_command(string const & command, Parser & p, ostream & os,
1007 bool outer, Context & context)
1009 if (known_commands.find(command) != known_commands.end()) {
1010 parse_arguments(command, known_commands[command], p, os,
1018 /// Parses a minipage or parbox
1019 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1020 unsigned inner_flags, bool outer, Context & parent_context,
1021 string const & outer_type, string const & special,
1022 string inner_type, string const & frame_color,
1023 string const & background_color)
1027 string hor_pos = "l";
1028 // We need to set the height to the LaTeX default of 1\\totalheight
1029 // for the case when no height argument is given
1030 string height_value = "1";
1031 string height_unit = "in";
1032 string height_special = "totalheight";
1033 string latex_height;
1037 string width_special = "none";
1038 string thickness = "0.4pt";
1039 if (!fboxrule.empty())
1040 thickness = fboxrule;
1042 thickness = "0.4pt";
1044 if (!fboxsep.empty())
1045 separation = fboxsep;
1049 if (!shadow_size.empty())
1050 shadowsize = shadow_size;
1053 string framecolor = "black";
1054 string backgroundcolor = "none";
1055 if (!frame_color.empty())
1056 framecolor = frame_color;
1057 if (!background_color.empty())
1058 backgroundcolor = background_color;
1059 // if there is a color box around the \begin statements have not yet been parsed
1061 if (!frame_color.empty() || !background_color.empty()) {
1062 eat_whitespace(p, os, parent_context, false);
1063 p.get_token().asInput(); // the '{'
1065 if (p.next_token().asInput() == "\\begin") {
1066 p.get_token().asInput();
1068 inner_type = "minipage";
1069 inner_flags = FLAG_END;
1070 active_environments.push_back("minipage");
1073 else if (p.next_token().asInput() == "\\parbox") {
1074 p.get_token().asInput();
1075 inner_type = "parbox";
1076 inner_flags = FLAG_ITEM;
1079 else if (p.next_token().asInput() == "\\makebox") {
1080 p.get_token().asInput();
1081 inner_type = "makebox";
1082 inner_flags = FLAG_ITEM;
1084 // in case there is just \colorbox{color}{text}
1087 inner_type = "makebox";
1088 inner_flags = FLAG_BRACE_LAST;
1093 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1095 if (!inner_type.empty() && p.hasOpt()) {
1096 if (inner_type != "makebox")
1097 position = p.getArg('[', ']');
1099 latex_width = p.getArg('[', ']');
1100 translate_box_len(latex_width, width_value, width_unit, width_special);
1103 if (position != "t" && position != "c" && position != "b") {
1104 cerr << "invalid position " << position << " for "
1105 << inner_type << endl;
1109 if (inner_type != "makebox") {
1110 latex_height = p.getArg('[', ']');
1111 translate_box_len(latex_height, height_value, height_unit, height_special);
1113 string const opt = p.getArg('[', ']');
1116 if (hor_pos != "l" && hor_pos != "c" &&
1117 hor_pos != "r" && hor_pos != "s") {
1118 cerr << "invalid hor_pos " << hor_pos
1119 << " for " << inner_type << endl;
1126 inner_pos = p.getArg('[', ']');
1127 if (inner_pos != "c" && inner_pos != "t" &&
1128 inner_pos != "b" && inner_pos != "s") {
1129 cerr << "invalid inner_pos "
1130 << inner_pos << " for "
1131 << inner_type << endl;
1132 inner_pos = position;
1136 if (inner_type == "makebox")
1140 if (inner_type.empty()) {
1141 if (special.empty() && outer_type != "framebox")
1142 latex_width = "1\\columnwidth";
1145 latex_width = p2.getArg('[', ']');
1146 string const opt = p2.getArg('[', ']');
1149 if (hor_pos != "l" && hor_pos != "c" &&
1150 hor_pos != "r" && hor_pos != "s") {
1151 cerr << "invalid hor_pos " << hor_pos
1152 << " for " << outer_type << endl;
1156 if (outer_type == "framebox")
1160 } else if (inner_type != "makebox")
1161 latex_width = p.verbatim_item();
1162 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1163 // as this is LyX's standard for such cases (except for makebox)
1164 // \framebox is more special and handled below
1165 if (latex_width.empty() && inner_type != "makebox"
1166 && outer_type != "framebox")
1167 latex_width = "1\\columnwidth";
1169 translate_len(latex_width, width_value, width_unit);
1171 bool shadedparbox = false;
1172 if (inner_type == "shaded") {
1173 eat_whitespace(p, os, parent_context, false);
1174 if (outer_type == "parbox") {
1176 if (p.next_token().cat() == catBegin)
1178 eat_whitespace(p, os, parent_context, false);
1179 shadedparbox = true;
1184 // If we already read the inner box we have to push the inner env
1185 if (!outer_type.empty() && !inner_type.empty() &&
1186 (inner_flags & FLAG_END))
1187 active_environments.push_back(inner_type);
1188 bool use_ert = false;
1189 if (!outer_type.empty() && !inner_type.empty()) {
1190 // Look whether there is some content after the end of the
1191 // inner box, but before the end of the outer box.
1192 // If yes, we need to output ERT.
1194 if (inner_flags & FLAG_END)
1195 p.ertEnvironment(inner_type);
1198 p.skip_spaces(true);
1199 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1200 if ((outer_env && p.next_token().asInput() != "\\end") ||
1201 (!outer_env && p.next_token().cat() != catEnd)) {
1202 // something is between the end of the inner box and
1203 // the end of the outer box, so we need to use ERT.
1211 if (!outer_type.empty()) {
1212 if (outer_flags & FLAG_END)
1213 ss << "\\begin{" << outer_type << '}';
1215 ss << '\\' << outer_type << '{';
1216 if (!special.empty())
1220 if (!inner_type.empty()) {
1221 if (inner_type != "shaded") {
1222 if (inner_flags & FLAG_END)
1223 ss << "\\begin{" << inner_type << '}';
1225 ss << '\\' << inner_type;
1227 if (!position.empty())
1228 ss << '[' << position << ']';
1229 if (!latex_height.empty())
1230 ss << '[' << latex_height << ']';
1231 if (!inner_pos.empty())
1232 ss << '[' << inner_pos << ']';
1233 ss << '{' << latex_width << '}';
1234 if (!(inner_flags & FLAG_END))
1237 if (inner_type == "shaded")
1238 ss << "\\begin{shaded}";
1239 output_ert_inset(os, ss.str(), parent_context);
1240 if (!inner_type.empty()) {
1241 parse_text(p, os, inner_flags, outer, parent_context);
1242 if (inner_flags & FLAG_END)
1243 output_ert_inset(os, "\\end{" + inner_type + '}',
1246 output_ert_inset(os, "}", parent_context);
1248 if (!outer_type.empty()) {
1249 // If we already read the inner box we have to pop
1251 if (!inner_type.empty() && (inner_flags & FLAG_END))
1252 active_environments.pop_back();
1254 // Ensure that the end of the outer box is parsed correctly:
1255 // The opening brace has been eaten by parse_outer_box()
1256 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1257 outer_flags &= ~FLAG_ITEM;
1258 outer_flags |= FLAG_BRACE_LAST;
1260 parse_text(p, os, outer_flags, outer, parent_context);
1261 if (outer_flags & FLAG_END)
1262 output_ert_inset(os, "\\end{" + outer_type + '}',
1265 output_ert_inset(os, "}", parent_context);
1268 // LyX does not like empty positions, so we have
1269 // to set them to the LaTeX default values here.
1270 if (position.empty())
1272 if (inner_pos.empty())
1273 inner_pos = position;
1274 parent_context.check_layout(os);
1275 begin_inset(os, "Box ");
1276 if (outer_type == "framed")
1278 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1280 else if (outer_type == "shadowbox")
1281 os << "Shadowbox\n";
1282 else if ((outer_type == "shaded" && inner_type.empty()) ||
1283 (outer_type == "minipage" && inner_type == "shaded") ||
1284 (outer_type == "parbox" && inner_type == "shaded")) {
1286 preamble.registerAutomaticallyLoadedPackage("color");
1287 } else if (outer_type == "doublebox")
1288 os << "Doublebox\n";
1289 else if (outer_type.empty() || outer_type == "mbox")
1290 os << "Frameless\n";
1292 os << outer_type << '\n';
1293 os << "position \"" << position << "\"\n";
1294 os << "hor_pos \"" << hor_pos << "\"\n";
1295 if (outer_type == "mbox")
1296 os << "has_inner_box 1\n";
1297 else if (!frame_color.empty() && inner_type == "makebox")
1298 os << "has_inner_box 0\n";
1300 os << "has_inner_box " << !inner_type.empty() << "\n";
1301 os << "inner_pos \"" << inner_pos << "\"\n";
1302 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1304 if (outer_type == "mbox")
1305 os << "use_makebox 1\n";
1306 else if (!frame_color.empty())
1307 os << "use_makebox 0\n";
1309 os << "use_makebox " << (inner_type == "makebox") << '\n';
1310 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1311 os << "width \"\"\n";
1312 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1313 else if (contains(width_unit, '\\'))
1314 os << "width \"" << width_value << "in" << "\"\n";
1316 os << "width \"" << width_value << width_unit << "\"\n";
1317 if (contains(width_unit, '\\')) {
1318 width_unit.erase (0,1); // remove the leading '\'
1319 os << "special \"" << width_unit << "\"\n";
1321 os << "special \"" << width_special << "\"\n";
1322 if (contains(height_unit, '\\'))
1323 os << "height \"" << height_value << "in" << "\"\n";
1325 os << "height \"" << height_value << height_unit << "\"\n";
1326 os << "height_special \"" << height_special << "\"\n";
1327 os << "thickness \"" << thickness << "\"\n";
1328 os << "separation \"" << separation << "\"\n";
1329 os << "shadowsize \"" << shadowsize << "\"\n";
1330 os << "framecolor \"" << framecolor << "\"\n";
1331 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1332 os << "status open\n\n";
1334 // Unfortunately we can't use parse_text_in_inset:
1335 // InsetBox::forcePlainLayout() is hard coded and does not
1336 // use the inset layout. Apart from that do we call parse_text
1337 // up to two times, but need only one check_end_layout.
1338 bool const forcePlainLayout =
1339 (!inner_type.empty() || inner_type == "makebox") &&
1340 outer_type != "shaded" && outer_type != "framed";
1341 Context context(true, parent_context.textclass);
1342 if (forcePlainLayout)
1343 context.layout = &context.textclass.plainLayout();
1345 context.font = parent_context.font;
1347 // If we have no inner box the contents will be read with the outer box
1348 if (!inner_type.empty())
1349 parse_text(p, os, inner_flags, outer, context);
1351 // Ensure that the end of the outer box is parsed correctly:
1352 // The opening brace has been eaten by parse_outer_box()
1353 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1354 outer_flags &= ~FLAG_ITEM;
1355 outer_flags |= FLAG_BRACE_LAST;
1358 // Find end of outer box, output contents if inner_type is
1359 // empty and output possible comments
1360 if (!outer_type.empty()) {
1361 // If we already read the inner box we have to pop
1363 if (!inner_type.empty() && (inner_flags & FLAG_END))
1364 active_environments.pop_back();
1365 // This does not output anything but comments if
1366 // inner_type is not empty (see use_ert)
1367 parse_text(p, os, outer_flags, outer, context);
1370 context.check_end_layout(os);
1372 #ifdef PRESERVE_LAYOUT
1373 // LyX puts a % after the end of the minipage
1374 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1376 //output_comment(p, os, "dummy", parent_context);
1379 parent_context.new_paragraph(os);
1381 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1382 //output_comment(p, os, "dummy", parent_context);
1385 // We add a protected space if something real follows
1386 if (p.good() && p.next_token().cat() != catComment) {
1387 begin_inset(os, "space ~\n");
1393 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1394 active_environments.pop_back();
1395 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1396 // in this case we have to eat the the closing brace of the color box
1397 p.get_token().asInput(); // the '}'
1399 if (p.next_token().asInput() == "}") {
1400 // in this case we assume that the closing brace is from the box settings
1401 // therefore reset these values for the next box
1407 // all boxes except of Frameless and Shaded require calc
1408 if (!(outer_type.empty() || outer_type == "mbox") &&
1409 !((outer_type == "shaded" && inner_type.empty()) ||
1410 (outer_type == "minipage" && inner_type == "shaded") ||
1411 (outer_type == "parbox" && inner_type == "shaded")))
1412 preamble.registerAutomaticallyLoadedPackage("calc");
1416 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1417 Context & parent_context, string const & outer_type,
1418 string const & special)
1420 eat_whitespace(p, os, parent_context, false);
1421 if (flags & FLAG_ITEM) {
1423 if (p.next_token().cat() == catBegin)
1426 cerr << "Warning: Ignoring missing '{' after \\"
1427 << outer_type << '.' << endl;
1428 eat_whitespace(p, os, parent_context, false);
1431 unsigned int inner_flags = 0;
1433 if (outer_type == "minipage" || outer_type == "parbox") {
1434 p.skip_spaces(true);
1435 while (p.hasOpt()) {
1437 p.skip_spaces(true);
1440 p.skip_spaces(true);
1441 if (outer_type == "parbox") {
1443 if (p.next_token().cat() == catBegin)
1445 p.skip_spaces(true);
1448 if (outer_type == "shaded" || outer_type == "mbox") {
1449 // These boxes never have an inner box
1451 } else if (p.next_token().asInput() == "\\parbox") {
1452 inner = p.get_token().cs();
1453 inner_flags = FLAG_ITEM;
1454 } else if (p.next_token().asInput() == "\\begin") {
1455 // Is this a minipage or shaded box?
1458 inner = p.getArg('{', '}');
1460 if (inner == "minipage" || inner == "shaded")
1461 inner_flags = FLAG_END;
1466 if (inner_flags == FLAG_END) {
1467 if (inner != "shaded")
1471 eat_whitespace(p, os, parent_context, false);
1473 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1474 outer_type, special, inner, "", "");
1476 if (inner_flags == FLAG_ITEM) {
1478 eat_whitespace(p, os, parent_context, false);
1480 parse_box(p, os, flags, inner_flags, outer, parent_context,
1481 outer_type, special, inner, "", "");
1486 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1487 bool in_line, bool use_minted)
1489 parent_context.check_layout(os);
1490 begin_inset(os, "listings\n");
1491 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1493 while ((i = arg.find(", ")) != string::npos
1494 || (i = arg.find(",\t")) != string::npos)
1495 arg.erase(i + 1, 1);
1498 string const language = p.getArg('{', '}');
1499 p.skip_spaces(true);
1500 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1501 if (!minted_float.empty()) {
1502 arg += string(arg.empty() ? "" : ",") + minted_float;
1503 minted_nonfloat_caption.clear();
1507 os << "lstparams " << '"' << arg << '"' << '\n';
1508 if (arg.find("\\color") != string::npos)
1509 preamble.registerAutomaticallyLoadedPackage("color");
1512 os << "inline true\n";
1514 os << "inline false\n";
1515 os << "status open\n";
1516 Context context(true, parent_context.textclass);
1517 context.layout = &parent_context.textclass.plainLayout();
1518 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1519 minted_nonfloat_caption.erase(0,3);
1520 os << "\n\\begin_layout Plain Layout\n";
1521 begin_inset(os, "Caption Standard\n");
1522 Context newcontext(true, context.textclass,
1523 context.layout, 0, context.font);
1524 newcontext.check_layout(os);
1525 os << minted_nonfloat_caption << "\n";
1526 newcontext.check_end_layout(os);
1528 os << "\n\\end_layout\n";
1529 minted_nonfloat_caption.clear();
1533 // set catcodes to verbatim early, just in case.
1534 p.setCatcodes(VERBATIM_CATCODES);
1535 string delim = p.get_token().asInput();
1536 //FIXME: handler error condition
1537 s = p.verbatimStuff(delim).second;
1538 // context.new_paragraph(os);
1539 } else if (use_minted) {
1540 s = p.verbatimEnvironment("minted");
1542 s = p.verbatimEnvironment("lstlisting");
1544 output_ert(os, s, context);
1545 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1546 minted_nonfloat_caption.erase(0,3);
1547 os << "\n\\begin_layout Plain Layout\n";
1548 begin_inset(os, "Caption Standard\n");
1549 Context newcontext(true, context.textclass,
1550 context.layout, 0, context.font);
1551 newcontext.check_layout(os);
1552 os << minted_nonfloat_caption << "\n";
1553 newcontext.check_end_layout(os);
1555 os << "\n\\end_layout\n";
1556 minted_nonfloat_caption.clear();
1558 // Don't close the inset here for floating minted listings.
1559 // It will be closed at the end of the listing environment.
1560 if (!use_minted || minted_float.empty())
1563 eat_whitespace(p, os, parent_context, true);
1564 Token t = p.get_token();
1565 if (t.asInput() != "\\end") {
1566 // If anything follows, collect it into a caption.
1567 minted_float_has_caption = true;
1568 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1569 begin_inset(os, "Caption Standard\n");
1570 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1577 /// parse an unknown environment
1578 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1579 unsigned flags, bool outer,
1580 Context & parent_context)
1582 if (name == "tabbing")
1583 // We need to remember that we have to handle '\=' specially
1584 flags |= FLAG_TABBING;
1586 // We need to translate font changes and paragraphs inside the
1587 // environment to ERT if we have a non standard font.
1588 // Otherwise things like
1589 // \large\begin{foo}\huge bar\end{foo}
1591 bool const specialfont =
1592 (parent_context.font != parent_context.normalfont);
1593 bool const new_layout_allowed = parent_context.new_layout_allowed;
1595 parent_context.new_layout_allowed = false;
1596 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1597 // Try to handle options: Look if we have an optional arguments,
1598 // and if so, put the brackets in ERT.
1599 while (p.hasOpt()) {
1600 p.get_token(); // eat '['
1601 output_ert_inset(os, "[", parent_context);
1602 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1603 output_ert_inset(os, "]", parent_context);
1605 parse_text_snippet(p, os, flags, outer, parent_context);
1606 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1608 parent_context.new_layout_allowed = new_layout_allowed;
1612 void parse_environment(Parser & p, ostream & os, bool outer,
1613 string & last_env, Context & parent_context)
1615 Layout const * newlayout;
1616 InsetLayout const * newinsetlayout = 0;
1617 string const name = p.getArg('{', '}');
1618 const bool is_starred = suffixIs(name, '*');
1619 string const unstarred_name = rtrim(name, "*");
1620 active_environments.push_back(name);
1622 if (is_math_env(name)) {
1623 parent_context.check_layout(os);
1624 begin_inset(os, "Formula ");
1625 os << "\\begin{" << name << "}";
1626 parse_math(p, os, FLAG_END, MATH_MODE);
1627 os << "\\end{" << name << "}";
1629 if (is_display_math_env(name)) {
1630 // Prevent the conversion of a line break to a space
1631 // (bug 7668). This does not change the output, but
1632 // looks ugly in LyX.
1633 eat_whitespace(p, os, parent_context, false);
1637 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1638 else if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1639 // We must begin a new paragraph if not already done
1640 if (! parent_context.atParagraphStart()) {
1641 parent_context.check_end_layout(os);
1642 parent_context.new_paragraph(os);
1644 // store previous language because we must reset it at the end
1645 string const lang_old = parent_context.font.language;
1646 // save the language in the context so that it is
1647 // handled by parse_text
1648 parent_context.font.language =
1649 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1650 parse_text(p, os, FLAG_END, outer, parent_context);
1651 // reset previous language
1652 parent_context.font.language = lang_old;
1653 // Just in case the environment is empty
1654 parent_context.extra_stuff.erase();
1655 // We must begin a new paragraph to reset the language
1656 parent_context.new_paragraph(os);
1660 else if (unstarred_name == "tabular" || name == "longtable") {
1661 eat_whitespace(p, os, parent_context, false);
1662 string width = "0pt";
1664 if (name == "longtable" && p.hasOpt()) {
1665 string const opt = p.getArg('[', ']');
1668 else if (opt == "l")
1670 else if (opt == "r")
1673 if (name == "tabular*") {
1674 width = lyx::translate_len(p.getArg('{', '}'));
1675 eat_whitespace(p, os, parent_context, false);
1677 parent_context.check_layout(os);
1678 begin_inset(os, "Tabular ");
1679 handle_tabular(p, os, name, width, halign, parent_context);
1684 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1685 eat_whitespace(p, os, parent_context, false);
1686 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1687 eat_whitespace(p, os, parent_context, false);
1688 parent_context.check_layout(os);
1689 begin_inset(os, "Float " + unstarred_name + "\n");
1690 // store the float type for subfloats
1691 // subfloats only work with figures and tables
1692 if (unstarred_name == "figure")
1693 float_type = unstarred_name;
1694 else if (unstarred_name == "table")
1695 float_type = unstarred_name;
1699 os << "placement " << opt << '\n';
1700 if (contains(opt, "H"))
1701 preamble.registerAutomaticallyLoadedPackage("float");
1703 Floating const & fl = parent_context.textclass.floats()
1704 .getType(unstarred_name);
1705 if (!fl.floattype().empty() && fl.usesFloatPkg())
1706 preamble.registerAutomaticallyLoadedPackage("float");
1709 os << "wide " << convert<string>(is_starred)
1710 << "\nsideways false"
1711 << "\nstatus open\n\n";
1712 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1714 // We don't need really a new paragraph, but
1715 // we must make sure that the next item gets a \begin_layout.
1716 parent_context.new_paragraph(os);
1718 // the float is parsed thus delete the type
1722 else if (unstarred_name == "sidewaysfigure"
1723 || unstarred_name == "sidewaystable"
1724 || unstarred_name == "sidewaysalgorithm") {
1725 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1726 eat_whitespace(p, os, parent_context, false);
1727 parent_context.check_layout(os);
1728 if (unstarred_name == "sidewaysfigure")
1729 begin_inset(os, "Float figure\n");
1730 else if (unstarred_name == "sidewaystable")
1731 begin_inset(os, "Float table\n");
1732 else if (unstarred_name == "sidewaysalgorithm")
1733 begin_inset(os, "Float algorithm\n");
1735 os << "placement " << opt << '\n';
1736 if (contains(opt, "H"))
1737 preamble.registerAutomaticallyLoadedPackage("float");
1738 os << "wide " << convert<string>(is_starred)
1739 << "\nsideways true"
1740 << "\nstatus open\n\n";
1741 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1743 // We don't need really a new paragraph, but
1744 // we must make sure that the next item gets a \begin_layout.
1745 parent_context.new_paragraph(os);
1747 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1750 else if (name == "wrapfigure" || name == "wraptable") {
1751 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1752 eat_whitespace(p, os, parent_context, false);
1753 parent_context.check_layout(os);
1756 string overhang = "0col%";
1759 lines = p.getArg('[', ']');
1760 string const placement = p.getArg('{', '}');
1762 overhang = p.getArg('[', ']');
1763 string const width = p.getArg('{', '}');
1765 if (name == "wrapfigure")
1766 begin_inset(os, "Wrap figure\n");
1768 begin_inset(os, "Wrap table\n");
1769 os << "lines " << lines
1770 << "\nplacement " << placement
1771 << "\noverhang " << lyx::translate_len(overhang)
1772 << "\nwidth " << lyx::translate_len(width)
1773 << "\nstatus open\n\n";
1774 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1776 // We don't need really a new paragraph, but
1777 // we must make sure that the next item gets a \begin_layout.
1778 parent_context.new_paragraph(os);
1780 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1783 else if (name == "minipage") {
1784 eat_whitespace(p, os, parent_context, false);
1785 // Test whether this is an outer box of a shaded box
1787 // swallow arguments
1788 while (p.hasOpt()) {
1790 p.skip_spaces(true);
1793 p.skip_spaces(true);
1794 Token t = p.get_token();
1795 bool shaded = false;
1796 if (t.asInput() == "\\begin") {
1797 p.skip_spaces(true);
1798 if (p.getArg('{', '}') == "shaded")
1803 parse_outer_box(p, os, FLAG_END, outer,
1804 parent_context, name, "shaded");
1806 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1807 "", "", name, "", "");
1811 else if (name == "comment") {
1812 eat_whitespace(p, os, parent_context, false);
1813 parent_context.check_layout(os);
1814 begin_inset(os, "Note Comment\n");
1815 os << "status open\n";
1816 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1819 skip_braces(p); // eat {} that might by set by LyX behind comments
1820 preamble.registerAutomaticallyLoadedPackage("verbatim");
1823 else if (unstarred_name == "verbatim") {
1824 // FIXME: this should go in the generic code that
1825 // handles environments defined in layout file that
1826 // have "PassThru 1". However, the code over there is
1827 // already too complicated for my taste.
1828 string const ascii_name =
1829 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1830 parent_context.new_paragraph(os);
1831 Context context(true, parent_context.textclass,
1832 &parent_context.textclass[from_ascii(ascii_name)]);
1833 string s = p.verbatimEnvironment(name);
1834 output_ert(os, s, context);
1838 else if (name == "IPA") {
1839 eat_whitespace(p, os, parent_context, false);
1840 parent_context.check_layout(os);
1841 begin_inset(os, "IPA\n");
1842 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1845 preamble.registerAutomaticallyLoadedPackage("tipa");
1846 preamble.registerAutomaticallyLoadedPackage("tipx");
1849 else if (name == parent_context.textclass.titlename()
1850 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1851 parse_text(p, os, FLAG_END, outer, parent_context);
1852 // Just in case the environment is empty
1853 parent_context.extra_stuff.erase();
1854 // We must begin a new paragraph
1855 parent_context.new_paragraph(os);
1859 else if (name == "CJK") {
1860 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1861 // It is impossible to decide if a CJK environment was in its own paragraph or within
1862 // a line. We therefore always assume a paragraph since the latter is a rare case.
1863 eat_whitespace(p, os, parent_context, false);
1864 parent_context.check_end_layout(os);
1865 // store the encoding to be able to reset it
1866 string const encoding_old = p.getEncoding();
1867 string const encoding = p.getArg('{', '}');
1868 // FIXME: For some reason JIS does not work. Although the text
1869 // in tests/CJK.tex is identical with the SJIS version if you
1870 // convert both snippets using the recode command line utility,
1871 // the resulting .lyx file contains some extra characters if
1872 // you set buggy_encoding to false for JIS.
1873 bool const buggy_encoding = encoding == "JIS";
1874 if (!buggy_encoding)
1875 p.setEncoding(encoding, Encoding::CJK);
1877 // FIXME: This will read garbage, since the data is not encoded in utf8.
1878 p.setEncoding("UTF-8");
1880 // LyX only supports the same mapping for all CJK
1881 // environments, so we might need to output everything as ERT
1882 string const mapping = trim(p.getArg('{', '}'));
1883 char const * const * const where =
1884 is_known(encoding, supported_CJK_encodings);
1885 if (!buggy_encoding && !preamble.fontCJKSet())
1886 preamble.fontCJK(mapping);
1887 bool knownMapping = mapping == preamble.fontCJK();
1888 if (buggy_encoding || !knownMapping || !where) {
1889 parent_context.check_layout(os);
1890 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1892 // we must parse the content as verbatim because e.g. JIS can contain
1893 // normally invalid characters
1894 // FIXME: This works only for the most simple cases.
1895 // Since TeX control characters are not parsed,
1896 // things like comments are completely wrong.
1897 string const s = p.plainEnvironment("CJK");
1898 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1901 if (snip == "\\" || is_known(snip, known_escaped_chars))
1902 output_ert_inset(os, snip, parent_context);
1903 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1908 output_ert_inset(os, "\\end{" + name + "}",
1912 supported_CJK_languages[where - supported_CJK_encodings];
1913 // store the language because we must reset it at the end
1914 string const lang_old = parent_context.font.language;
1915 parent_context.font.language = lang;
1916 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1917 parent_context.font.language = lang_old;
1918 parent_context.new_paragraph(os);
1920 p.setEncoding(encoding_old);
1924 else if (name == "lyxgreyedout") {
1925 eat_whitespace(p, os, parent_context, false);
1926 parent_context.check_layout(os);
1927 begin_inset(os, "Note Greyedout\n");
1928 os << "status open\n";
1929 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1932 if (!preamble.notefontcolor().empty())
1933 preamble.registerAutomaticallyLoadedPackage("color");
1936 else if (name == "btSect") {
1937 eat_whitespace(p, os, parent_context, false);
1938 parent_context.check_layout(os);
1939 begin_command_inset(os, "bibtex", "bibtex");
1940 string bibstyle = "plain";
1942 bibstyle = p.getArg('[', ']');
1943 p.skip_spaces(true);
1945 string const bibfile = p.getArg('{', '}');
1946 eat_whitespace(p, os, parent_context, false);
1947 Token t = p.get_token();
1948 if (t.asInput() == "\\btPrintCited") {
1949 p.skip_spaces(true);
1950 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1952 if (t.asInput() == "\\btPrintNotCited") {
1953 p.skip_spaces(true);
1954 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1956 if (t.asInput() == "\\btPrintAll") {
1957 p.skip_spaces(true);
1958 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1960 os << "bibfiles " << '"' << bibfile << "\"\n"
1961 << "options " << '"' << bibstyle << "\"\n";
1962 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1967 else if (name == "btUnit") {
1968 string const nt = p.next_next_token().cs();
1969 // Do not attempt to overwrite a former diverging multibib.
1970 // Those are output as ERT instead.
1971 if ((nt == "part" || nt == "chapter"
1972 || nt == "section" || nt == "subsection")
1973 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1974 parse_text(p, os, FLAG_END, outer, parent_context);
1975 preamble.multibib(nt);
1977 parse_unknown_environment(p, name, os, FLAG_END, outer,
1981 else if (name == "framed" || name == "shaded") {
1982 eat_whitespace(p, os, parent_context, false);
1983 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1985 preamble.registerAutomaticallyLoadedPackage("framed");
1988 else if (name == "listing") {
1989 minted_float = "float";
1990 eat_whitespace(p, os, parent_context, false);
1991 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1993 minted_float += "=" + opt;
1994 // If something precedes \begin{minted}, we output it at the end
1995 // as a caption, in order to keep it inside the listings inset.
1996 eat_whitespace(p, os, parent_context, true);
1998 Token const & t = p.get_token();
1999 p.skip_spaces(true);
2000 string const envname = p.next_token().cat() == catBegin
2001 ? p.getArg('{', '}') : string();
2002 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2004 minted_float_has_caption = false;
2005 string content = parse_text_snippet(p, FLAG_END, outer,
2007 size_t i = content.find("\\begin_inset listings");
2008 bool minted_env = i != string::npos;
2011 caption = content.substr(0, i);
2012 content.erase(0, i);
2014 parent_context.check_layout(os);
2015 if (minted_env && minted_float_has_caption) {
2016 eat_whitespace(p, os, parent_context, true);
2017 os << content << "\n";
2018 if (!caption.empty())
2019 os << caption << "\n";
2020 os << "\n\\end_layout\n"; // close inner layout
2021 end_inset(os); // close caption inset
2022 os << "\n\\end_layout\n"; // close outer layout
2023 } else if (!caption.empty()) {
2025 begin_inset(os, "listings\n");
2026 os << "lstparams " << '"' << minted_float << '"' << '\n';
2027 os << "inline false\n";
2028 os << "status collapsed\n";
2030 os << "\n\\begin_layout Plain Layout\n";
2031 begin_inset(os, "Caption Standard\n");
2032 Context newcontext(true, parent_context.textclass,
2033 0, 0, parent_context.font);
2034 newcontext.check_layout(os);
2035 os << caption << "\n";
2036 newcontext.check_end_layout(os);
2038 os << "\n\\end_layout\n";
2039 } else if (content.empty()) {
2040 begin_inset(os, "listings\n");
2041 os << "lstparams " << '"' << minted_float << '"' << '\n';
2042 os << "inline false\n";
2043 os << "status collapsed\n";
2045 os << content << "\n";
2047 end_inset(os); // close listings inset
2048 parent_context.check_end_layout(os);
2049 parent_context.new_paragraph(os);
2051 minted_float.clear();
2052 minted_float_has_caption = false;
2055 else if (name == "lstlisting" || name == "minted") {
2056 bool use_minted = name == "minted";
2057 eat_whitespace(p, os, parent_context, false);
2058 if (use_minted && minted_float.empty()) {
2059 // look ahead for a bottom caption
2061 bool found_end_minted = false;
2062 while (!found_end_minted && p.good()) {
2063 Token const & t = p.get_token();
2065 string const envname =
2066 p.next_token().cat() == catBegin
2067 ? p.getArg('{', '}') : string();
2068 found_end_minted = t.asInput() == "\\end"
2069 && envname == "minted";
2071 eat_whitespace(p, os, parent_context, true);
2072 Token const & t = p.get_token();
2073 p.skip_spaces(true);
2074 if (t.asInput() == "\\lyxmintcaption") {
2075 string const pos = p.getArg('[', ']');
2077 string const caption =
2078 parse_text_snippet(p, FLAG_ITEM,
2079 false, parent_context);
2080 minted_nonfloat_caption = "[b]" + caption;
2081 eat_whitespace(p, os, parent_context, true);
2086 parse_listings(p, os, parent_context, false, use_minted);
2090 else if (!parent_context.new_layout_allowed)
2091 parse_unknown_environment(p, name, os, FLAG_END, outer,
2094 // Alignment and spacing settings
2095 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2096 // therefore are totally broken!
2097 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2098 // they are commands not environments. They are furthermore switches that
2099 // can be ended by another switches, but also by commands like \footnote or
2100 // \parbox. So the only safe way is to leave them untouched.
2101 // However, we support the pseudo-environments
2102 // \begin{centering} ... \end{centering}
2103 // \begin{raggedright} ... \end{raggedright}
2104 // \begin{raggedleft} ... \end{raggedleft}
2105 // since they are used by LyX in floats (for spacing reasons)
2106 else if (name == "center" || name == "centering" ||
2107 name == "flushleft" || name == "raggedright" ||
2108 name == "flushright" || name == "raggedleft" ||
2109 name == "singlespace" || name == "onehalfspace" ||
2110 name == "doublespace" || name == "spacing") {
2111 eat_whitespace(p, os, parent_context, false);
2112 // We must begin a new paragraph if not already done
2113 if (! parent_context.atParagraphStart()) {
2114 parent_context.check_end_layout(os);
2115 parent_context.new_paragraph(os);
2117 if (name == "flushleft" || name == "raggedright")
2118 parent_context.add_extra_stuff("\\align left\n");
2119 else if (name == "flushright" || name == "raggedleft")
2120 parent_context.add_extra_stuff("\\align right\n");
2121 else if (name == "center" || name == "centering")
2122 parent_context.add_extra_stuff("\\align center\n");
2123 else if (name == "singlespace")
2124 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2125 else if (name == "onehalfspace") {
2126 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2127 preamble.registerAutomaticallyLoadedPackage("setspace");
2128 } else if (name == "doublespace") {
2129 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2130 preamble.registerAutomaticallyLoadedPackage("setspace");
2131 } else if (name == "spacing") {
2132 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2133 preamble.registerAutomaticallyLoadedPackage("setspace");
2135 parse_text(p, os, FLAG_END, outer, parent_context);
2136 // Just in case the environment is empty
2137 parent_context.extra_stuff.erase();
2138 // We must begin a new paragraph to reset the alignment
2139 parent_context.new_paragraph(os);
2143 // The single '=' is meant here.
2144 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2145 eat_whitespace(p, os, parent_context, false);
2146 Context context(true, parent_context.textclass, newlayout,
2147 parent_context.layout, parent_context.font);
2148 if (parent_context.deeper_paragraph) {
2149 // We are beginning a nested environment after a
2150 // deeper paragraph inside the outer list environment.
2151 // Therefore we don't need to output a "begin deeper".
2152 context.need_end_deeper = true;
2154 parent_context.check_end_layout(os);
2155 if (last_env == name) {
2156 // we need to output a separator since LyX would export
2157 // the two environments as one otherwise (bug 5716)
2158 TeX2LyXDocClass const & textclass(parent_context.textclass);
2159 Context newcontext(true, textclass,
2160 &(textclass.defaultLayout()));
2161 newcontext.check_layout(os);
2162 begin_inset(os, "Separator plain\n");
2164 newcontext.check_end_layout(os);
2166 switch (context.layout->latextype) {
2167 case LATEX_LIST_ENVIRONMENT:
2168 context.add_par_extra_stuff("\\labelwidthstring "
2169 + p.verbatim_item() + '\n');
2172 case LATEX_BIB_ENVIRONMENT:
2173 p.verbatim_item(); // swallow next arg
2179 context.check_deeper(os);
2180 if (newlayout->keepempty) {
2181 // We need to start a new paragraph
2182 // even if it is empty.
2183 context.new_paragraph(os);
2184 context.check_layout(os);
2186 // handle known optional and required arguments
2187 if (context.layout->latextype == LATEX_ENVIRONMENT)
2188 output_arguments(os, p, outer, false, string(), context,
2189 context.layout->latexargs());
2190 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2192 output_arguments(oss, p, outer, false, string(), context,
2193 context.layout->latexargs());
2194 context.list_extra_stuff = oss.str();
2196 parse_text(p, os, FLAG_END, outer, context);
2197 if (context.layout->latextype == LATEX_ENVIRONMENT)
2198 output_arguments(os, p, outer, false, "post", context,
2199 context.layout->postcommandargs());
2200 context.check_end_layout(os);
2201 if (parent_context.deeper_paragraph) {
2202 // We must suppress the "end deeper" because we
2203 // suppressed the "begin deeper" above.
2204 context.need_end_deeper = false;
2206 context.check_end_deeper(os);
2207 parent_context.new_paragraph(os);
2209 if (!preamble.titleLayoutFound())
2210 preamble.titleLayoutFound(newlayout->intitle);
2211 set<string> const & req = newlayout->requires();
2212 set<string>::const_iterator it = req.begin();
2213 set<string>::const_iterator en = req.end();
2214 for (; it != en; ++it)
2215 preamble.registerAutomaticallyLoadedPackage(*it);
2218 // The single '=' is meant here.
2219 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2220 eat_whitespace(p, os, parent_context, false);
2221 parent_context.check_layout(os);
2222 begin_inset(os, "Flex ");
2223 os << to_utf8(newinsetlayout->name()) << '\n'
2224 << "status collapsed\n";
2225 if (newinsetlayout->isPassThru()) {
2226 string const arg = p.verbatimEnvironment(name);
2227 Context context(true, parent_context.textclass,
2228 &parent_context.textclass.plainLayout(),
2229 parent_context.layout);
2230 output_ert(os, arg, parent_context);
2232 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2236 else if (name == "appendix") {
2237 // This is no good latex style, but it works and is used in some documents...
2238 eat_whitespace(p, os, parent_context, false);
2239 parent_context.check_end_layout(os);
2240 Context context(true, parent_context.textclass, parent_context.layout,
2241 parent_context.layout, parent_context.font);
2242 context.check_layout(os);
2243 os << "\\start_of_appendix\n";
2244 parse_text(p, os, FLAG_END, outer, context);
2245 context.check_end_layout(os);
2249 else if (known_environments.find(name) != known_environments.end()) {
2250 vector<ArgumentType> arguments = known_environments[name];
2251 // The last "argument" denotes wether we may translate the
2252 // environment contents to LyX
2253 // The default required if no argument is given makes us
2254 // compatible with the reLyXre environment.
2255 ArgumentType contents = arguments.empty() ?
2258 if (!arguments.empty())
2259 arguments.pop_back();
2260 // See comment in parse_unknown_environment()
2261 bool const specialfont =
2262 (parent_context.font != parent_context.normalfont);
2263 bool const new_layout_allowed =
2264 parent_context.new_layout_allowed;
2266 parent_context.new_layout_allowed = false;
2267 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2268 outer, parent_context);
2269 if (contents == verbatim)
2270 output_ert_inset(os, p.ertEnvironment(name),
2273 parse_text_snippet(p, os, FLAG_END, outer,
2275 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2277 parent_context.new_layout_allowed = new_layout_allowed;
2281 parse_unknown_environment(p, name, os, FLAG_END, outer,
2285 active_environments.pop_back();
2289 /// parses a comment and outputs it to \p os.
2290 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2292 LASSERT(t.cat() == catComment, return);
2293 if (!t.cs().empty()) {
2294 context.check_layout(os);
2295 output_comment(p, os, t.cs(), context);
2296 if (p.next_token().cat() == catNewline) {
2297 // A newline after a comment line starts a new
2299 if (context.new_layout_allowed) {
2300 if(!context.atParagraphStart())
2301 // Only start a new paragraph if not already
2302 // done (we might get called recursively)
2303 context.new_paragraph(os);
2305 output_ert_inset(os, "\n", context);
2306 eat_whitespace(p, os, context, true);
2309 // "%\n" combination
2316 * Reads spaces and comments until the first non-space, non-comment token.
2317 * New paragraphs (double newlines or \\par) are handled like simple spaces
2318 * if \p eatParagraph is true.
2319 * Spaces are skipped, but comments are written to \p os.
2321 void eat_whitespace(Parser & p, ostream & os, Context & context,
2325 Token const & t = p.get_token();
2326 if (t.cat() == catComment)
2327 parse_comment(p, os, t, context);
2328 else if ((! eatParagraph && p.isParagraph()) ||
2329 (t.cat() != catSpace && t.cat() != catNewline)) {
2338 * Set a font attribute, parse text and reset the font attribute.
2339 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2340 * \param currentvalue Current value of the attribute. Is set to the new
2341 * value during parsing.
2342 * \param newvalue New value of the attribute
2344 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2345 Context & context, string const & attribute,
2346 string & currentvalue, string const & newvalue)
2348 context.check_layout(os);
2349 string const oldvalue = currentvalue;
2350 currentvalue = newvalue;
2351 os << '\n' << attribute << ' ' << newvalue << "\n";
2352 parse_text_snippet(p, os, flags, outer, context);
2353 context.check_layout(os);
2354 os << '\n' << attribute << ' ' << oldvalue << "\n";
2355 currentvalue = oldvalue;
2359 /// get the arguments of a natbib or jurabib citation command
2360 void get_cite_arguments(Parser & p, bool natbibOrder,
2361 string & before, string & after, bool const qualified = false)
2363 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2365 // text before the citation
2367 // text after the citation
2368 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2370 if (!after.empty()) {
2371 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2372 if (natbibOrder && !before.empty())
2373 swap(before, after);
2378 void copy_file(FileName const & src, string dstname)
2382 string const absParent = getParentFilePath(false);
2384 if (FileName::isAbsolute(dstname))
2385 dst = FileName(dstname);
2387 dst = makeAbsPath(dstname, absParent);
2388 FileName const srcpath = src.onlyPath();
2389 FileName const dstpath = dst.onlyPath();
2390 if (equivalent(srcpath, dstpath))
2392 if (!dstpath.isDirectory()) {
2393 if (!dstpath.createPath()) {
2394 cerr << "Warning: Could not create directory for file `"
2395 << dst.absFileName() << "´." << endl;
2399 if (dst.isReadableFile()) {
2400 if (overwriteFiles())
2401 cerr << "Warning: Overwriting existing file `"
2402 << dst.absFileName() << "´." << endl;
2404 cerr << "Warning: Not overwriting existing file `"
2405 << dst.absFileName() << "´." << endl;
2409 if (!src.copyTo(dst))
2410 cerr << "Warning: Could not copy file `" << src.absFileName()
2411 << "´ to `" << dst.absFileName() << "´." << endl;
2415 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2416 bool parse_chunk(Parser & p, ostream & os, Context & context)
2418 // check whether a chunk is possible here.
2419 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2425 // read the parameters
2426 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2427 if (!params.first) {
2432 Parser::Arg const code = p.verbatimStuff("\n@");
2437 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2438 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2442 // The last newline read is important for paragraph handling
2446 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2447 // We must have a valid layout before outputting the Chunk inset.
2448 context.check_layout(os);
2449 Context chunkcontext(true, context.textclass);
2450 chunkcontext.layout = &context.textclass.plainLayout();
2451 begin_inset(os, "Flex Chunk");
2452 os << "\nstatus open\n";
2453 if (!params.second.empty()) {
2454 chunkcontext.check_layout(os);
2455 Context paramscontext(true, context.textclass);
2456 paramscontext.layout = &context.textclass.plainLayout();
2457 begin_inset(os, "Argument 1");
2458 os << "\nstatus open\n";
2459 output_ert(os, params.second, paramscontext);
2462 output_ert(os, code.second, chunkcontext);
2470 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2471 bool is_macro(Parser & p)
2473 Token first = p.curr_token();
2474 if (first.cat() != catEscape || !p.good())
2476 if (first.cs() == "def")
2478 if (first.cs() != "global" && first.cs() != "long")
2480 Token second = p.get_token();
2482 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2483 second.cat() == catNewline || second.cat() == catComment)) {
2484 second = p.get_token();
2487 bool secondvalid = second.cat() == catEscape;
2489 bool thirdvalid = false;
2490 if (p.good() && first.cs() == "global" && secondvalid &&
2491 second.cs() == "long") {
2492 third = p.get_token();
2494 while (p.good() && !p.isParagraph() &&
2495 (third.cat() == catSpace ||
2496 third.cat() == catNewline ||
2497 third.cat() == catComment)) {
2498 third = p.get_token();
2501 thirdvalid = third.cat() == catEscape;
2503 for (int i = 0; i < pos; ++i)
2508 return (first.cs() == "global" || first.cs() == "long") &&
2509 second.cs() == "def";
2510 return first.cs() == "global" && second.cs() == "long" &&
2511 third.cs() == "def";
2515 /// Parse a macro definition (assumes that is_macro() returned true)
2516 void parse_macro(Parser & p, ostream & os, Context & context)
2518 context.check_layout(os);
2519 Token first = p.curr_token();
2522 string command = first.asInput();
2523 if (first.cs() != "def") {
2525 eat_whitespace(p, os, context, false);
2526 second = p.curr_token();
2527 command += second.asInput();
2528 if (second.cs() != "def") {
2530 eat_whitespace(p, os, context, false);
2531 third = p.curr_token();
2532 command += third.asInput();
2535 eat_whitespace(p, os, context, false);
2536 string const name = p.get_token().cs();
2537 eat_whitespace(p, os, context, false);
2543 while (p.next_token().cat() != catBegin) {
2544 if (p.next_token().cat() == catParameter) {
2549 // followed by number?
2550 if (p.next_token().cat() == catOther) {
2551 string s = p.get_token().asInput();
2553 // number = current arity + 1?
2554 if (s.size() == 1 && s[0] == arity + '0' + 1)
2559 paramtext += p.get_token().cs();
2561 paramtext += p.get_token().cs();
2566 // only output simple (i.e. compatible) macro as FormulaMacros
2567 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2569 context.check_layout(os);
2570 begin_inset(os, "FormulaMacro");
2571 os << "\n\\def" << ert;
2574 output_ert_inset(os, command + ert, context);
2578 void registerExternalTemplatePackages(string const & name)
2580 external::TemplateManager const & etm = external::TemplateManager::get();
2581 external::Template const * const et = etm.getTemplateByName(name);
2584 external::Template::Formats::const_iterator cit = et->formats.end();
2586 cit = et->formats.find("PDFLaTeX");
2587 if (cit == et->formats.end())
2588 // If the template has not specified a PDFLaTeX output,
2589 // we try the LaTeX format.
2590 cit = et->formats.find("LaTeX");
2591 if (cit == et->formats.end())
2593 vector<string>::const_iterator qit = cit->second.requirements.begin();
2594 vector<string>::const_iterator qend = cit->second.requirements.end();
2595 for (; qit != qend; ++qit)
2596 preamble.registerAutomaticallyLoadedPackage(*qit);
2599 } // anonymous namespace
2603 * Find a file with basename \p name in path \p path and an extension
2606 string find_file(string const & name, string const & path,
2607 char const * const * extensions)
2609 for (char const * const * what = extensions; *what; ++what) {
2610 string const trial = addExtension(name, *what);
2611 if (makeAbsPath(trial, path).exists())
2618 /// Convert filenames with TeX macros and/or quotes to something LyX
2620 string const normalize_filename(string const & name)
2625 Token const & t = p.get_token();
2626 if (t.cat() != catEscape)
2628 else if (t.cs() == "lyxdot") {
2629 // This is used by LyX for simple dots in relative
2633 } else if (t.cs() == "space") {
2636 } else if (t.cs() == "string") {
2637 // Convert \string" to " and \string~ to ~
2638 Token const & n = p.next_token();
2639 if (n.asInput() != "\"" && n.asInput() != "~")
2644 // Strip quotes. This is a bit complicated (see latex_path()).
2645 string full = os.str();
2646 if (!full.empty() && full[0] == '"') {
2647 string base = removeExtension(full);
2648 string ext = getExtension(full);
2649 if (!base.empty() && base[base.length()-1] == '"')
2652 return addExtension(trim(base, "\""), ext);
2653 if (full[full.length()-1] == '"')
2656 return trim(full, "\"");
2662 /// Convert \p name from TeX convention (relative to master file) to LyX
2663 /// convention (relative to .lyx file) if it is relative
2664 void fix_child_filename(string & name)
2666 string const absMasterTeX = getMasterFilePath(true);
2667 bool const isabs = FileName::isAbsolute(name);
2668 // convert from "relative to .tex master" to absolute original path
2670 name = makeAbsPath(name, absMasterTeX).absFileName();
2671 bool copyfile = copyFiles();
2672 string const absParentLyX = getParentFilePath(false);
2675 // convert from absolute original path to "relative to master file"
2676 string const rel = to_utf8(makeRelPath(from_utf8(name),
2677 from_utf8(absMasterTeX)));
2678 // re-interpret "relative to .tex file" as "relative to .lyx file"
2679 // (is different if the master .lyx file resides in a
2680 // different path than the master .tex file)
2681 string const absMasterLyX = getMasterFilePath(false);
2682 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2683 // Do not copy if the new path is impossible to create. Example:
2684 // absMasterTeX = "/foo/bar/"
2685 // absMasterLyX = "/bar/"
2686 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2687 if (contains(name, "/../"))
2694 // convert from absolute original path to
2695 // "relative to .lyx file"
2696 name = to_utf8(makeRelPath(from_utf8(abs),
2697 from_utf8(absParentLyX)));
2701 // convert from absolute original path to "relative to .lyx file"
2702 name = to_utf8(makeRelPath(from_utf8(name),
2703 from_utf8(absParentLyX)));
2708 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2709 Context & context, string const rdelim)
2711 Layout const * newlayout = 0;
2712 InsetLayout const * newinsetlayout = 0;
2713 char const * const * where = 0;
2714 // Store the latest bibliographystyle, addcontentslineContent and
2715 // nocite{*} option (needed for bibtex inset)
2717 string contentslineContent;
2718 // Some classes provide a \bibliographystyle, so do not output
2719 // any if none is explicitly set.
2720 string bibliographystyle;
2721 bool const use_natbib = isProvided("natbib");
2722 bool const use_jurabib = isProvided("jurabib");
2723 bool const use_biblatex = isProvided("biblatex")
2724 && preamble.citeEngine() != "biblatex-natbib";
2725 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2726 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2727 need_commentbib = use_biblatex || use_biblatex_natbib;
2730 // it is impossible to determine the correct encoding for non-CJK Japanese.
2731 // Therefore write a note at the beginning of the document
2732 if (is_nonCJKJapanese) {
2733 context.check_layout(os);
2734 begin_inset(os, "Note Note\n");
2735 os << "status open\n\\begin_layout Plain Layout\n"
2736 << "\\series bold\n"
2737 << "Important information:\n"
2738 << "\\end_layout\n\n"
2739 << "\\begin_layout Plain Layout\n"
2740 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2741 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2742 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2743 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2744 << " and specify the encoding using the -e command-line switch.\n"
2745 << " In addition, you might want to double check that the desired output encoding\n"
2746 << " is correctly selected in Document > Settings > Language.\n"
2747 << "\\end_layout\n";
2749 is_nonCJKJapanese = false;
2752 bool have_cycled = false;
2754 // Leave here only after at least one cycle
2755 if (have_cycled && flags & FLAG_LEAVE) {
2756 flags &= ~FLAG_LEAVE;
2760 Token const & t = p.get_token();
2762 debugToken(cerr, t, flags);
2765 if (flags & FLAG_ITEM) {
2766 if (t.cat() == catSpace)
2769 flags &= ~FLAG_ITEM;
2770 if (t.cat() == catBegin) {
2771 // skip the brace and collect everything to the next matching
2773 flags |= FLAG_BRACE_LAST;
2777 // handle only this single token, leave the loop if done
2778 flags |= FLAG_LEAVE;
2781 if (t.cat() != catEscape && t.character() == ']' &&
2782 (flags & FLAG_BRACK_LAST))
2784 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2786 string tok = t.asInput();
2787 // we only support delimiters with max 2 chars for now.
2788 if (rdelim.size() > 1)
2789 tok += p.next_token().asInput();
2790 if (t.cat() != catEscape && !rdelim.empty()
2791 && tok == rdelim && (flags & FLAG_RDELIM)) {
2792 if (rdelim.size() > 1)
2793 p.get_token(); // eat rdelim
2797 // If there is anything between \end{env} and \begin{env} we
2798 // don't need to output a separator.
2799 if (t.cat() != catSpace && t.cat() != catNewline &&
2800 t.asInput() != "\\begin")
2807 bool const starred = p.next_token().asInput() == "*";
2808 string const starredname(starred ? (t.cs() + '*') : t.cs());
2809 if (t.cat() == catMath) {
2810 // we are inside some text mode thingy, so opening new math is allowed
2811 context.check_layout(os);
2812 begin_inset(os, "Formula ");
2813 Token const & n = p.get_token();
2814 bool const display(n.cat() == catMath && outer);
2816 // TeX's $$...$$ syntax for displayed math
2818 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2820 p.get_token(); // skip the second '$' token
2822 // simple $...$ stuff
2825 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2830 // Prevent the conversion of a line break to a
2831 // space (bug 7668). This does not change the
2832 // output, but looks ugly in LyX.
2833 eat_whitespace(p, os, context, false);
2838 if (t.cat() == catSuper || t.cat() == catSub) {
2839 cerr << "catcode " << t << " illegal in text mode\n";
2843 // Basic support for quotes. We try to disambiguate
2844 // quotes from the context (e.g., a left english quote is
2845 // the same as a right german quote...).
2846 // Try to make a smart guess about the side
2847 Token const prev = p.prev_token();
2848 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2849 && prev.character() != '\n' && prev.character() != '~');
2850 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2851 context.check_layout(os);
2852 begin_inset(os, "Quotes ");
2853 os << guessQuoteStyle("eld", opening);
2859 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2860 context.check_layout(os);
2861 begin_inset(os, "Quotes ");
2862 os << guessQuoteStyle("erd", opening);
2869 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2870 context.check_layout(os);
2871 begin_inset(os, "Quotes ");
2872 os << guessQuoteStyle("ald", opening);
2879 if (t.asInput() == "<"
2880 && p.next_token().asInput() == "<") {
2881 bool has_chunk = false;
2885 has_chunk = parse_chunk(p, os, context);
2891 context.check_layout(os);
2892 begin_inset(os, "Quotes ");
2893 os << guessQuoteStyle("ard", opening);
2901 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2902 check_space(p, os, context);
2906 // babel shorthands (also used by polyglossia)
2907 // Since these can have different meanings for different languages
2908 // we import them as ERT (but they must be put in ERT to get output
2910 if (t.asInput() == "\"") {
2912 // These are known pairs. We put them together in
2913 // one ERT inset. In other cases (such as "a), only
2914 // the quotation mark is ERTed.
2915 if (p.next_token().asInput() == "\""
2916 || p.next_token().asInput() == "|"
2917 || p.next_token().asInput() == "-"
2918 || p.next_token().asInput() == "~"
2919 || p.next_token().asInput() == "="
2920 || p.next_token().asInput() == "/"
2921 || p.next_token().asInput() == "~"
2922 || p.next_token().asInput() == "'"
2923 || p.next_token().asInput() == "`"
2924 || p.next_token().asInput() == "<"
2925 || p.next_token().asInput() == ">") {
2926 s += p.next_token().asInput();
2929 output_ert_inset(os, s, context);
2933 if (t.character() == '[' && noweb_mode &&
2934 p.next_token().character() == '[') {
2935 // These can contain underscores
2937 string const s = p.getFullOpt() + ']';
2938 if (p.next_token().character() == ']')
2941 cerr << "Warning: Inserting missing ']' in '"
2942 << s << "'." << endl;
2943 output_ert_inset(os, s, context);
2947 if (t.cat() == catLetter) {
2948 context.check_layout(os);
2953 if (t.cat() == catOther ||
2954 t.cat() == catAlign ||
2955 t.cat() == catParameter) {
2956 context.check_layout(os);
2957 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2958 context.merging_hyphens_allowed &&
2959 context.font.family != "ttfamily" &&
2960 !context.layout->pass_thru) {
2961 if (p.next_next_token().asInput() == "-") {
2963 os << to_utf8(docstring(1, 0x2014));
2967 os << to_utf8(docstring(1, 0x2013));
2970 // This translates "&" to "\\&" which may be wrong...
2975 if (p.isParagraph()) {
2976 // In minted floating listings we will collect
2977 // everything into the caption, where multiple
2978 // paragraphs are forbidden.
2979 if (minted_float.empty()) {
2980 if (context.new_layout_allowed)
2981 context.new_paragraph(os);
2983 output_ert_inset(os, "\\par ", context);
2986 eat_whitespace(p, os, context, true);
2990 if (t.cat() == catActive) {
2991 context.check_layout(os);
2992 if (t.character() == '~') {
2993 if (context.layout->free_spacing)
2996 begin_inset(os, "space ~\n");
3004 if (t.cat() == catBegin) {
3005 Token const next = p.next_token();
3006 Token const end = p.next_next_token();
3007 if (next.cat() == catEnd) {
3009 Token const prev = p.prev_token();
3011 if (p.next_token().character() == '`')
3012 ; // ignore it in {}``
3014 output_ert_inset(os, "{}", context);
3015 } else if (next.cat() == catEscape &&
3016 is_known(next.cs(), known_quotes) &&
3017 end.cat() == catEnd) {
3018 // Something like {\textquoteright} (e.g.
3019 // from writer2latex). We may skip the
3020 // braces here for better readability.
3021 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3023 } else if (p.next_token().asInput() == "\\ascii") {
3024 // handle the \ascii characters
3025 // (the case without braces is handled later)
3026 // the code is "{\ascii\xxx}"
3027 p.get_token(); // eat \ascii
3028 string name2 = p.get_token().asInput();
3029 p.get_token(); // eat the final '}'
3030 string const name = "{\\ascii" + name2 + "}";
3034 // get the character from unicodesymbols
3035 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3036 Encodings::TEXT_CMD, termination, rem, &req);
3038 context.check_layout(os);
3041 output_ert_inset(os,
3042 to_utf8(rem), context);
3043 for (set<string>::const_iterator it = req.begin();
3044 it != req.end(); ++it)
3045 preamble.registerAutomaticallyLoadedPackage(*it);
3047 // we did not find a non-ert version
3048 output_ert_inset(os, name, context);
3050 context.check_layout(os);
3051 // special handling of font attribute changes
3052 Token const prev = p.prev_token();
3053 TeXFont const oldFont = context.font;
3054 if (next.character() == '[' ||
3055 next.character() == ']' ||
3056 next.character() == '*') {
3058 if (p.next_token().cat() == catEnd) {
3063 output_ert_inset(os, "{", context);
3064 parse_text_snippet(p, os,
3067 output_ert_inset(os, "}", context);
3069 } else if (! context.new_layout_allowed) {
3070 output_ert_inset(os, "{", context);
3071 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3073 output_ert_inset(os, "}", context);
3074 } else if (is_known(next.cs(), known_sizes)) {
3075 // next will change the size, so we must
3077 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3079 if (!context.atParagraphStart())
3081 << context.font.size << "\n";
3082 } else if (is_known(next.cs(), known_font_families)) {
3083 // next will change the font family, so we
3084 // must reset it here
3085 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3087 if (!context.atParagraphStart())
3089 << context.font.family << "\n";
3090 } else if (is_known(next.cs(), known_font_series)) {
3091 // next will change the font series, so we
3092 // must reset it here
3093 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3095 if (!context.atParagraphStart())
3097 << context.font.series << "\n";
3098 } else if (is_known(next.cs(), known_font_shapes)) {
3099 // next will change the font shape, so we
3100 // must reset it here
3101 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3103 if (!context.atParagraphStart())
3105 << context.font.shape << "\n";
3106 } else if (is_known(next.cs(), known_old_font_families) ||
3107 is_known(next.cs(), known_old_font_series) ||
3108 is_known(next.cs(), known_old_font_shapes)) {
3109 // next will change the font family, series
3110 // and shape, so we must reset it here
3111 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3113 if (!context.atParagraphStart())
3115 << context.font.family
3117 << context.font.series
3119 << context.font.shape << "\n";
3121 output_ert_inset(os, "{", context);
3122 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3124 output_ert_inset(os, "}", context);
3130 if (t.cat() == catEnd) {
3131 if (flags & FLAG_BRACE_LAST) {
3134 cerr << "stray '}' in text\n";
3135 output_ert_inset(os, "}", context);
3139 if (t.cat() == catComment) {
3140 parse_comment(p, os, t, context);
3145 // control sequences
3148 if (t.cs() == "(" || t.cs() == "[") {
3149 bool const simple = t.cs() == "(";
3150 context.check_layout(os);
3151 begin_inset(os, "Formula");
3152 os << " \\" << t.cs();
3153 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3154 os << '\\' << (simple ? ')' : ']');
3157 // Prevent the conversion of a line break to a
3158 // space (bug 7668). This does not change the
3159 // output, but looks ugly in LyX.
3160 eat_whitespace(p, os, context, false);
3165 if (t.cs() == "begin") {
3166 parse_environment(p, os, outer, last_env,
3171 if (t.cs() == "end") {
3172 if (flags & FLAG_END) {
3173 // eat environment name
3174 string const name = p.getArg('{', '}');
3175 if (name != active_environment())
3176 cerr << "\\end{" + name + "} does not match \\begin{"
3177 + active_environment() + "}\n";
3180 p.error("found 'end' unexpectedly");
3184 // "item" by default, but could be something else
3185 if (t.cs() == context.layout->itemcommand()) {
3187 if (context.layout->labeltype == LABEL_MANUAL) {
3188 // FIXME: This swallows comments, but we cannot use
3189 // eat_whitespace() since we must not output
3190 // anything before the item.
3191 p.skip_spaces(true);
3192 s = p.verbatimOption();
3194 p.skip_spaces(false);
3196 context.check_layout(os);
3197 if (context.has_item) {
3198 // An item in an unknown list-like environment
3199 // FIXME: Do this in check_layout()!
3200 context.has_item = false;
3201 string item = "\\" + context.layout->itemcommand();
3204 output_ert_inset(os, item, context);
3206 if (context.layout->labeltype != LABEL_MANUAL)
3207 output_arguments(os, p, outer, false, "item", context,
3208 context.layout->itemargs());
3209 if (!context.list_extra_stuff.empty()) {
3210 os << context.list_extra_stuff;
3211 context.list_extra_stuff.clear();
3213 else if (!s.empty()) {
3214 // LyX adds braces around the argument,
3215 // so we need to remove them here.
3216 if (s.size() > 2 && s[0] == '{' &&
3217 s[s.size()-1] == '}')
3218 s = s.substr(1, s.size()-2);
3219 // If the argument contains a space we
3220 // must put it into ERT: Otherwise LyX
3221 // would misinterpret the space as
3222 // item delimiter (bug 7663)
3223 if (contains(s, ' ')) {
3224 output_ert_inset(os, s, context);
3227 os << parse_text_snippet(p2,
3228 FLAG_BRACK_LAST, outer, context);
3230 // The space is needed to separate the
3231 // item from the rest of the sentence.
3233 eat_whitespace(p, os, context, false);
3238 if (t.cs() == "bibitem") {
3240 context.check_layout(os);
3241 eat_whitespace(p, os, context, false);
3242 string label = p.verbatimOption();
3243 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3244 bool const literal = !lbl.first;
3245 label = literal ? subst(label, "\n", " ") : lbl.second;
3246 string lit = literal ? "\"true\"" : "\"false\"";
3247 string key = convert_literate_command_inset_arg(p.verbatim_item());
3248 begin_command_inset(os, "bibitem", "bibitem");
3249 os << "label \"" << label << "\"\n"
3250 << "key \"" << key << "\"\n"
3251 << "literal " << lit << "\n";
3257 // catch the case of \def\inputGnumericTable
3259 if (t.cs() == "def") {
3260 Token second = p.next_token();
3261 if (second.cs() == "inputGnumericTable") {
3265 Token third = p.get_token();
3267 if (third.cs() == "input") {
3271 string name = normalize_filename(p.verbatim_item());
3272 string const path = getMasterFilePath(true);
3273 // We want to preserve relative / absolute filenames,
3274 // therefore path is only used for testing
3275 // The file extension is in every case ".tex".
3276 // So we need to remove this extension and check for
3277 // the original one.
3278 name = removeExtension(name);
3279 if (!makeAbsPath(name, path).exists()) {
3280 char const * const Gnumeric_formats[] = {"gnumeric",
3282 string const Gnumeric_name =
3283 find_file(name, path, Gnumeric_formats);
3284 if (!Gnumeric_name.empty())
3285 name = Gnumeric_name;
3287 FileName const absname = makeAbsPath(name, path);
3288 if (absname.exists()) {
3289 fix_child_filename(name);
3290 copy_file(absname, name);
3292 cerr << "Warning: Could not find file '"
3293 << name << "'." << endl;
3294 context.check_layout(os);
3295 begin_inset(os, "External\n\ttemplate ");
3296 os << "GnumericSpreadsheet\n\tfilename "
3299 context.check_layout(os);
3301 // register the packages that are automatically loaded
3302 // by the Gnumeric template
3303 registerExternalTemplatePackages("GnumericSpreadsheet");
3308 parse_macro(p, os, context);
3312 if (t.cs() == "noindent") {
3314 context.add_par_extra_stuff("\\noindent\n");
3318 if (t.cs() == "appendix") {
3319 context.add_par_extra_stuff("\\start_of_appendix\n");
3320 // We need to start a new paragraph. Otherwise the
3321 // appendix in 'bla\appendix\chapter{' would start
3323 context.new_paragraph(os);
3324 // We need to make sure that the paragraph is
3325 // generated even if it is empty. Otherwise the
3326 // appendix in '\par\appendix\par\chapter{' would
3328 context.check_layout(os);
3329 // FIXME: This is a hack to prevent paragraph
3330 // deletion if it is empty. Handle this better!
3331 output_comment(p, os,
3332 "dummy comment inserted by tex2lyx to "
3333 "ensure that this paragraph is not empty",
3335 // Both measures above may generate an additional
3336 // empty paragraph, but that does not hurt, because
3337 // whitespace does not matter here.
3338 eat_whitespace(p, os, context, true);
3342 // Must catch empty dates before findLayout is called below
3343 if (t.cs() == "date") {
3344 eat_whitespace(p, os, context, false);
3346 string const date = p.verbatim_item();
3349 preamble.suppressDate(true);
3352 preamble.suppressDate(false);
3353 if (context.new_layout_allowed &&
3354 (newlayout = findLayout(context.textclass,
3357 output_command_layout(os, p, outer,
3358 context, newlayout);
3359 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3360 if (!preamble.titleLayoutFound())
3361 preamble.titleLayoutFound(newlayout->intitle);
3362 set<string> const & req = newlayout->requires();
3363 set<string>::const_iterator it = req.begin();
3364 set<string>::const_iterator en = req.end();
3365 for (; it != en; ++it)
3366 preamble.registerAutomaticallyLoadedPackage(*it);
3368 output_ert_inset(os,
3369 "\\date{" + p.verbatim_item() + '}',
3375 // Before we look for the layout name with star and alone below, we check the layouts including
3376 // the LateXParam, which might be one or several options or a star.
3377 // The single '=' is meant here.
3378 if (context.new_layout_allowed &&
3379 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3380 // store the latexparam here. This is eaten in output_command_layout
3381 context.latexparam = newlayout->latexparam();
3383 output_command_layout(os, p, outer, context, newlayout);
3384 context.latexparam.clear();
3386 if (!preamble.titleLayoutFound())
3387 preamble.titleLayoutFound(newlayout->intitle);
3388 set<string> const & req = newlayout->requires();
3389 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3390 preamble.registerAutomaticallyLoadedPackage(*it);
3394 // Starred section headings
3395 // Must attempt to parse "Section*" before "Section".
3396 if ((p.next_token().asInput() == "*") &&
3397 context.new_layout_allowed &&
3398 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3401 output_command_layout(os, p, outer, context, newlayout);
3403 if (!preamble.titleLayoutFound())
3404 preamble.titleLayoutFound(newlayout->intitle);
3405 set<string> const & req = newlayout->requires();
3406 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3407 preamble.registerAutomaticallyLoadedPackage(*it);
3411 // Section headings and the like
3412 if (context.new_layout_allowed &&
3413 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3415 output_command_layout(os, p, outer, context, newlayout);
3417 if (!preamble.titleLayoutFound())
3418 preamble.titleLayoutFound(newlayout->intitle);
3419 set<string> const & req = newlayout->requires();
3420 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3421 preamble.registerAutomaticallyLoadedPackage(*it);
3425 if (t.cs() == "subfloat") {
3426 // the syntax is \subfloat[list entry][sub caption]{content}
3427 // if it is a table of figure depends on the surrounding float
3429 // do nothing if there is no outer float
3430 if (!float_type.empty()) {
3431 context.check_layout(os);
3433 begin_inset(os, "Float " + float_type + "\n");
3435 << "\nsideways false"
3436 << "\nstatus collapsed\n\n";
3439 bool has_caption = false;
3440 if (p.next_token().cat() != catEscape &&
3441 p.next_token().character() == '[') {
3442 p.get_token(); // eat '['
3443 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3446 // In case we have two optional args, the second is the caption.
3447 if (p.next_token().cat() != catEscape &&
3448 p.next_token().character() == '[') {
3449 p.get_token(); // eat '['
3450 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3453 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3454 // the caption comes always as the last
3456 // we must make sure that the caption gets a \begin_layout
3457 os << "\n\\begin_layout Plain Layout";
3459 begin_inset(os, "Caption Standard\n");
3460 Context newcontext(true, context.textclass,
3461 0, 0, context.font);
3462 newcontext.check_layout(os);
3463 os << caption << "\n";
3464 newcontext.check_end_layout(os);
3467 // close the layout we opened
3468 os << "\n\\end_layout";
3473 // if the float type is not supported or there is no surrounding float
3478 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3480 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3482 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3483 + "{" + p.verbatim_item() + '}', context);
3488 if (t.cs() == "xymatrix") {
3489 // we must open a new math because LyX's xy support is in math
3490 context.check_layout(os);
3491 begin_inset(os, "Formula ");
3493 os << "\\" << t.cs() << '{';
3494 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3497 preamble.registerAutomaticallyLoadedPackage("xy");
3501 if (t.cs() == "includegraphics") {
3502 bool const clip = p.next_token().asInput() == "*";
3505 string const arg = p.getArg('[', ']');
3506 map<string, string> opts;
3507 vector<string> keys;
3508 split_map(arg, opts, keys);
3510 opts["clip"] = string();
3511 string name = normalize_filename(p.verbatim_item());
3513 string const path = getMasterFilePath(true);
3514 // We want to preserve relative / absolute filenames,
3515 // therefore path is only used for testing
3516 if (!makeAbsPath(name, path).exists()) {
3517 // The file extension is probably missing.
3518 // Now try to find it out.
3519 string const dvips_name =
3520 find_file(name, path,
3521 known_dvips_graphics_formats);
3522 string const pdftex_name =
3523 find_file(name, path,
3524 known_pdftex_graphics_formats);
3525 if (!dvips_name.empty()) {
3526 if (!pdftex_name.empty()) {
3527 cerr << "This file contains the "
3529 "\"\\includegraphics{"
3531 "However, files\n\""
3532 << dvips_name << "\" and\n\""
3533 << pdftex_name << "\"\n"
3534 "both exist, so I had to make a "
3535 "choice and took the first one.\n"
3536 "Please move the unwanted one "
3537 "someplace else and try again\n"
3538 "if my choice was wrong."
3542 } else if (!pdftex_name.empty()) {
3548 FileName const absname = makeAbsPath(name, path);
3549 if (absname.exists()) {
3550 fix_child_filename(name);
3551 copy_file(absname, name);
3553 cerr << "Warning: Could not find graphics file '"
3554 << name << "'." << endl;
3556 context.check_layout(os);
3557 begin_inset(os, "Graphics ");
3558 os << "\n\tfilename " << name << '\n';
3559 if (opts.find("width") != opts.end())
3561 << translate_len(opts["width"]) << '\n';
3562 if (opts.find("height") != opts.end())
3564 << translate_len(opts["height"]) << '\n';
3565 if (opts.find("scale") != opts.end()) {
3566 istringstream iss(opts["scale"]);
3570 os << "\tscale " << val << '\n';
3572 if (opts.find("angle") != opts.end()) {
3573 os << "\trotateAngle "
3574 << opts["angle"] << '\n';
3575 vector<string>::const_iterator a =
3576 find(keys.begin(), keys.end(), "angle");
3577 vector<string>::const_iterator s =
3578 find(keys.begin(), keys.end(), "width");
3579 if (s == keys.end())
3580 s = find(keys.begin(), keys.end(), "height");
3581 if (s == keys.end())
3582 s = find(keys.begin(), keys.end(), "scale");
3583 if (s != keys.end() && distance(s, a) > 0)
3584 os << "\tscaleBeforeRotation\n";
3586 if (opts.find("origin") != opts.end()) {
3588 string const opt = opts["origin"];
3589 if (opt.find('l') != string::npos) ss << "left";
3590 if (opt.find('r') != string::npos) ss << "right";
3591 if (opt.find('c') != string::npos) ss << "center";
3592 if (opt.find('t') != string::npos) ss << "Top";
3593 if (opt.find('b') != string::npos) ss << "Bottom";
3594 if (opt.find('B') != string::npos) ss << "Baseline";
3595 if (!ss.str().empty())
3596 os << "\trotateOrigin " << ss.str() << '\n';
3598 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3600 if (opts.find("keepaspectratio") != opts.end())
3601 os << "\tkeepAspectRatio\n";
3602 if (opts.find("clip") != opts.end())
3604 if (opts.find("draft") != opts.end())
3606 if (opts.find("bb") != opts.end())
3607 os << "\tBoundingBox "
3608 << opts["bb"] << '\n';
3609 int numberOfbbOptions = 0;
3610 if (opts.find("bbllx") != opts.end())
3611 numberOfbbOptions++;
3612 if (opts.find("bblly") != opts.end())
3613 numberOfbbOptions++;
3614 if (opts.find("bburx") != opts.end())
3615 numberOfbbOptions++;
3616 if (opts.find("bbury") != opts.end())
3617 numberOfbbOptions++;
3618 if (numberOfbbOptions == 4)
3619 os << "\tBoundingBox "
3620 << opts["bbllx"] << " " << opts["bblly"] << " "
3621 << opts["bburx"] << " " << opts["bbury"] << '\n';
3622 else if (numberOfbbOptions > 0)
3623 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3624 numberOfbbOptions = 0;
3625 if (opts.find("natwidth") != opts.end())
3626 numberOfbbOptions++;
3627 if (opts.find("natheight") != opts.end())
3628 numberOfbbOptions++;
3629 if (numberOfbbOptions == 2)
3630 os << "\tBoundingBox 0bp 0bp "
3631 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3632 else if (numberOfbbOptions > 0)
3633 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3634 ostringstream special;
3635 if (opts.find("hiresbb") != opts.end())
3636 special << "hiresbb,";
3637 if (opts.find("trim") != opts.end())
3639 if (opts.find("viewport") != opts.end())
3640 special << "viewport=" << opts["viewport"] << ',';
3641 if (opts.find("totalheight") != opts.end())
3642 special << "totalheight=" << opts["totalheight"] << ',';
3643 if (opts.find("type") != opts.end())
3644 special << "type=" << opts["type"] << ',';
3645 if (opts.find("ext") != opts.end())
3646 special << "ext=" << opts["ext"] << ',';
3647 if (opts.find("read") != opts.end())
3648 special << "read=" << opts["read"] << ',';
3649 if (opts.find("command") != opts.end())
3650 special << "command=" << opts["command"] << ',';
3651 string s_special = special.str();
3652 if (!s_special.empty()) {
3653 // We had special arguments. Remove the trailing ','.
3654 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3656 // TODO: Handle the unknown settings better.
3657 // Warn about invalid options.
3658 // Check whether some option was given twice.
3660 preamble.registerAutomaticallyLoadedPackage("graphicx");
3664 if (t.cs() == "footnote" ||
3665 (t.cs() == "thanks" && context.layout->intitle)) {
3667 context.check_layout(os);
3668 begin_inset(os, "Foot\n");
3669 os << "status collapsed\n\n";
3670 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3675 if (t.cs() == "marginpar") {
3677 context.check_layout(os);
3678 begin_inset(os, "Marginal\n");
3679 os << "status collapsed\n\n";
3680 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3685 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3686 bool const use_minted = t.cs() == "mintinline";
3688 parse_listings(p, os, context, true, use_minted);
3692 if (t.cs() == "ensuremath") {
3694 context.check_layout(os);
3695 string const s = p.verbatim_item();
3696 //FIXME: this never triggers in UTF8
3697 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3700 output_ert_inset(os, "\\ensuremath{" + s + "}",
3705 else if (t.cs() == "makeindex"
3706 || (t.cs() == context.textclass.titlename()
3707 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3708 if (preamble.titleLayoutFound()) {
3710 skip_spaces_braces(p);
3712 output_ert_inset(os, t.asInput(), context);
3716 if (t.cs() == "tableofcontents"
3717 || t.cs() == "lstlistoflistings"
3718 || t.cs() == "listoflistings") {
3719 string name = t.cs();
3720 if (preamble.minted() && name == "listoflistings")
3721 name.insert(0, "lst");
3722 context.check_layout(os);
3723 begin_command_inset(os, "toc", name);
3725 skip_spaces_braces(p);
3726 if (name == "lstlistoflistings") {
3727 if (preamble.minted())
3728 preamble.registerAutomaticallyLoadedPackage("minted");
3730 preamble.registerAutomaticallyLoadedPackage("listings");
3735 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3736 context.check_layout(os);
3737 if (t.cs() == "listoffigures")
3738 begin_inset(os, "FloatList figure\n");
3740 begin_inset(os, "FloatList table\n");
3742 skip_spaces_braces(p);
3746 if (t.cs() == "listof") {
3747 p.skip_spaces(true);
3748 string const name = p.verbatim_item();
3749 if (context.textclass.floats().typeExist(name)) {
3750 context.check_layout(os);
3751 begin_inset(os, "FloatList ");
3754 p.verbatim_item(); // swallow second arg
3756 output_ert_inset(os, "\\listof{" + name + "}", context);
3760 if ((where = is_known(t.cs(), known_text_font_families))) {
3761 parse_text_attributes(p, os, FLAG_ITEM, outer,
3762 context, "\\family", context.font.family,
3763 known_coded_font_families[where - known_text_font_families]);
3767 // beamer has a \textbf<overlay>{} inset
3768 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3769 parse_text_attributes(p, os, FLAG_ITEM, outer,
3770 context, "\\series", context.font.series,
3771 known_coded_font_series[where - known_text_font_series]);
3775 // beamer has a \textit<overlay>{} inset
3776 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3777 parse_text_attributes(p, os, FLAG_ITEM, outer,
3778 context, "\\shape", context.font.shape,
3779 known_coded_font_shapes[where - known_text_font_shapes]);
3783 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3784 context.check_layout(os);
3785 TeXFont oldFont = context.font;
3786 context.font.init();
3787 context.font.size = oldFont.size;
3788 os << "\n\\family " << context.font.family << "\n";
3789 os << "\n\\series " << context.font.series << "\n";
3790 os << "\n\\shape " << context.font.shape << "\n";
3791 if (t.cs() == "textnormal") {
3792 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3793 output_font_change(os, context.font, oldFont);
3794 context.font = oldFont;
3796 eat_whitespace(p, os, context, false);
3800 if (t.cs() == "textcolor") {
3801 // scheme is \textcolor{color name}{text}
3802 string const color = p.verbatim_item();
3803 // we support the predefined colors of the color and the xcolor package
3804 if (color == "black" || color == "blue" || color == "cyan"
3805 || color == "green" || color == "magenta" || color == "red"
3806 || color == "white" || color == "yellow") {
3807 context.check_layout(os);
3808 os << "\n\\color " << color << "\n";
3809 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3810 context.check_layout(os);
3811 os << "\n\\color inherit\n";
3812 preamble.registerAutomaticallyLoadedPackage("color");
3813 } else if (color == "brown" || color == "darkgray" || color == "gray"
3814 || color == "lightgray" || color == "lime" || color == "olive"
3815 || color == "orange" || color == "pink" || color == "purple"
3816 || color == "teal" || color == "violet") {
3817 context.check_layout(os);
3818 os << "\n\\color " << color << "\n";
3819 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3820 context.check_layout(os);
3821 os << "\n\\color inherit\n";
3822 preamble.registerAutomaticallyLoadedPackage("xcolor");
3824 // for custom defined colors
3825 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3829 if (t.cs() == "underbar" || t.cs() == "uline") {
3830 // \underbar is not 100% correct (LyX outputs \uline
3831 // of ulem.sty). The difference is that \ulem allows
3832 // line breaks, and \underbar does not.
3833 // Do NOT handle \underline.
3834 // \underbar cuts through y, g, q, p etc.,
3835 // \underline does not.
3836 context.check_layout(os);
3837 os << "\n\\bar under\n";
3838 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3839 context.check_layout(os);
3840 os << "\n\\bar default\n";
3841 preamble.registerAutomaticallyLoadedPackage("ulem");
3845 if (t.cs() == "sout") {
3846 context.check_layout(os);
3847 os << "\n\\strikeout on\n";
3848 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3849 context.check_layout(os);
3850 os << "\n\\strikeout default\n";
3851 preamble.registerAutomaticallyLoadedPackage("ulem");
3855 // beamer has an \emph<overlay>{} inset
3856 if ((t.cs() == "uuline" || t.cs() == "uwave"
3857 || t.cs() == "emph" || t.cs() == "noun"
3858 || t.cs() == "xout") && !p.hasOpt("<")) {
3859 context.check_layout(os);
3860 os << "\n\\" << t.cs() << " on\n";
3861 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3862 context.check_layout(os);
3863 os << "\n\\" << t.cs() << " default\n";
3864 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3865 preamble.registerAutomaticallyLoadedPackage("ulem");
3869 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3870 context.check_layout(os);
3871 string name = p.getArg('{', '}');
3872 string localtime = p.getArg('{', '}');
3873 preamble.registerAuthor(name);
3874 Author const & author = preamble.getAuthor(name);
3875 // from_asctime_utc() will fail if LyX decides to output the
3876 // time in the text language.
3877 time_t ptime = from_asctime_utc(localtime);
3878 if (ptime == static_cast<time_t>(-1)) {
3879 cerr << "Warning: Could not parse time `" << localtime
3880 << "´ for change tracking, using current time instead.\n";
3881 ptime = current_time();
3883 if (t.cs() == "lyxadded")
3884 os << "\n\\change_inserted ";
3886 os << "\n\\change_deleted ";
3887 os << author.bufferId() << ' ' << ptime << '\n';
3888 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3889 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3890 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3891 LaTeXPackages::isAvailable("xcolor");
3892 // No need to test for luatex, since luatex comes in
3893 // two flavours (dvi and pdf), like latex, and those
3894 // are detected by pdflatex.
3895 if (pdflatex || xetex) {
3897 preamble.registerAutomaticallyLoadedPackage("ulem");
3898 preamble.registerAutomaticallyLoadedPackage("xcolor");
3899 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3903 preamble.registerAutomaticallyLoadedPackage("dvipost");
3904 } else if (xcolorulem) {
3905 preamble.registerAutomaticallyLoadedPackage("ulem");
3906 preamble.registerAutomaticallyLoadedPackage("xcolor");
3912 if (t.cs() == "textipa") {
3913 context.check_layout(os);
3914 begin_inset(os, "IPA\n");
3915 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3916 context.merging_hyphens_allowed = false;
3917 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3918 context.merging_hyphens_allowed = merging_hyphens_allowed;
3920 preamble.registerAutomaticallyLoadedPackage("tipa");
3921 preamble.registerAutomaticallyLoadedPackage("tipx");
3925 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3926 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3927 context.check_layout(os);
3931 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3932 begin_inset(os, "IPADeco " + type + "\n");
3933 os << "status open\n";
3934 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3940 if (t.cs() == "textvertline") {
3941 // FIXME: This is not correct, \textvertline is higher than |
3947 if (t.cs() == "tone" ) {
3948 context.check_layout(os);
3949 // register the tone package
3950 preamble.registerAutomaticallyLoadedPackage("tone");
3951 string content = trimSpaceAndEol(p.verbatim_item());
3952 string command = t.asInput() + "{" + content + "}";
3953 // some tones can be detected by unicodesymbols, some need special code
3954 if (is_known(content, known_tones)) {
3955 os << "\\IPAChar " << command << "\n";
3958 // try to see whether the string is in unicodesymbols
3962 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3963 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3964 termination, rem, &req);
3968 output_ert_inset(os, to_utf8(rem), context);
3969 for (set<string>::const_iterator it = req.begin();
3970 it != req.end(); ++it)
3971 preamble.registerAutomaticallyLoadedPackage(*it);
3973 // we did not find a non-ert version
3974 output_ert_inset(os, command, context);
3978 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3979 t.cs() == "vphantom") {
3980 context.check_layout(os);
3981 if (t.cs() == "phantom")
3982 begin_inset(os, "Phantom Phantom\n");
3983 if (t.cs() == "hphantom")
3984 begin_inset(os, "Phantom HPhantom\n");
3985 if (t.cs() == "vphantom")
3986 begin_inset(os, "Phantom VPhantom\n");
3987 os << "status open\n";
3988 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3994 if (t.cs() == "href") {
3995 context.check_layout(os);
3996 string target = convert_literate_command_inset_arg(p.verbatim_item());
3997 string name = p.verbatim_item();
3998 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3999 bool const literal = !nm.first;
4000 name = literal ? subst(name, "\n", " ") : nm.second;
4001 string lit = literal ? "\"true\"" : "\"false\"";
4003 size_t i = target.find(':');
4004 if (i != string::npos) {
4005 type = target.substr(0, i + 1);
4006 if (type == "mailto:" || type == "file:")
4007 target = target.substr(i + 1);
4008 // handle the case that name is equal to target, except of "http(s)://"
4009 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4012 begin_command_inset(os, "href", "href");
4014 os << "name \"" << name << "\"\n";
4015 os << "target \"" << target << "\"\n";
4016 if (type == "mailto:" || type == "file:")
4017 os << "type \"" << type << "\"\n";
4018 os << "literal " << lit << "\n";
4020 skip_spaces_braces(p);
4024 if (t.cs() == "lyxline") {
4025 // swallow size argument (it is not used anyway)
4027 if (!context.atParagraphStart()) {
4028 // so our line is in the middle of a paragraph
4029 // we need to add a new line, lest this line
4030 // follow the other content on that line and
4031 // run off the side of the page
4032 // FIXME: This may create an empty paragraph,
4033 // but without that it would not be
4034 // possible to set noindent below.
4035 // Fortunately LaTeX does not care
4036 // about the empty paragraph.
4037 context.new_paragraph(os);
4039 if (preamble.indentParagraphs()) {
4040 // we need to unindent, lest the line be too long
4041 context.add_par_extra_stuff("\\noindent\n");
4043 context.check_layout(os);
4044 begin_command_inset(os, "line", "rule");
4045 os << "offset \"0.5ex\"\n"
4046 "width \"100line%\"\n"
4052 if (t.cs() == "rule") {
4053 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4054 string const width = p.getArg('{', '}');
4055 string const thickness = p.getArg('{', '}');
4056 context.check_layout(os);
4057 begin_command_inset(os, "line", "rule");
4058 if (!offset.empty())
4059 os << "offset \"" << translate_len(offset) << "\"\n";
4060 os << "width \"" << translate_len(width) << "\"\n"
4061 "height \"" << translate_len(thickness) << "\"\n";
4066 // Handle refstyle first in order to to catch \eqref, because this
4067 // can also occur without refstyle. Only recognize these commands if
4068 // refstyle.sty was found in the preamble (otherwise \eqref
4069 // and user defined ref commands could be misdetected).
4070 // We uncapitalize the input in order to catch capitalized commands
4072 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4073 && preamble.refstyle()) {
4074 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4075 string plural = "false";
4076 // Catch the plural option [s]
4078 string const opt = p.getOpt();
4082 // LyX does not yet support other optional arguments of ref commands
4083 output_ert_inset(os, t.asInput() + opt + "{" +
4084 p.verbatim_item() + '}', context);
4088 context.check_layout(os);
4089 begin_command_inset(os, "ref", "formatted");
4090 os << "reference \"";
4091 os << known_refstyle_prefixes[where - known_refstyle_commands]
4093 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4095 os << "plural \"" << plural << "\"\n";
4096 os << "caps \"" << cap << "\"\n";
4097 os << "noprefix \"false\"\n";
4099 preamble.registerAutomaticallyLoadedPackage("refstyle");
4103 // if refstyle is used, we must not convert \prettyref to a
4104 // formatted reference, since that would result in a refstyle command.
4105 if ((where = is_known(t.cs(), known_ref_commands)) &&
4106 (t.cs() != "prettyref" || !preamble.refstyle())) {
4107 string const opt = p.getOpt();
4109 context.check_layout(os);
4110 begin_command_inset(os, "ref",
4111 known_coded_ref_commands[where - known_ref_commands]);
4112 os << "reference \""
4113 << convert_literate_command_inset_arg(p.verbatim_item())
4115 os << "plural \"false\"\n";
4116 os << "caps \"false\"\n";
4117 os << "noprefix \"false\"\n";
4119 if (t.cs() == "vref" || t.cs() == "vpageref")
4120 preamble.registerAutomaticallyLoadedPackage("varioref");
4121 else if (t.cs() == "prettyref")
4122 preamble.registerAutomaticallyLoadedPackage("prettyref");
4124 // LyX does not yet support optional arguments of ref commands
4125 output_ert_inset(os, t.asInput() + opt + "{" +
4126 p.verbatim_item() + '}', context);
4132 is_known(t.cs(), known_natbib_commands) &&
4133 ((t.cs() != "citefullauthor" &&
4134 t.cs() != "citeyear" &&
4135 t.cs() != "citeyearpar") ||
4136 p.next_token().asInput() != "*")) {
4137 context.check_layout(os);
4138 string command = t.cs();
4139 if (p.next_token().asInput() == "*") {
4143 if (command == "citefullauthor")
4144 // alternative name for "\\citeauthor*"
4145 command = "citeauthor*";
4147 // text before the citation
4149 // text after the citation
4151 get_cite_arguments(p, true, before, after);
4153 if (command == "cite") {
4154 // \cite without optional argument means
4155 // \citet, \cite with at least one optional
4156 // argument means \citep.
4157 if (before.empty() && after.empty())
4162 if (before.empty() && after == "[]")
4163 // avoid \citet[]{a}
4165 else if (before == "[]" && after == "[]") {
4166 // avoid \citet[][]{a}
4170 bool literal = false;
4171 pair<bool, string> aft;
4172 pair<bool, string> bef;
4173 // remove the brackets around after and before
4174 if (!after.empty()) {
4176 after.erase(after.length() - 1, 1);
4177 aft = convert_latexed_command_inset_arg(after);
4178 literal = !aft.first;
4179 after = literal ? subst(after, "\n", " ") : aft.second;
4181 if (!before.empty()) {
4183 before.erase(before.length() - 1, 1);
4184 bef = convert_latexed_command_inset_arg(before);
4185 literal |= !bef.first;
4186 before = literal ? subst(before, "\n", " ") : bef.second;
4187 if (literal && !after.empty())
4188 after = subst(after, "\n", " ");
4190 string lit = literal ? "\"true\"" : "\"false\"";
4191 begin_command_inset(os, "citation", command);
4192 os << "after " << '"' << after << '"' << "\n";
4193 os << "before " << '"' << before << '"' << "\n";
4195 << convert_literate_command_inset_arg(p.verbatim_item())
4197 << "literal " << lit << "\n";
4199 // Need to set the cite engine if natbib is loaded by
4200 // the document class directly
4201 if (preamble.citeEngine() == "basic")
4202 preamble.citeEngine("natbib");
4207 && is_known(t.cs(), known_biblatex_commands)
4208 && ((t.cs() == "cite"
4209 || t.cs() == "citeauthor"
4210 || t.cs() == "Citeauthor"
4211 || t.cs() == "parencite"
4212 || t.cs() == "citetitle")
4213 || p.next_token().asInput() != "*"))
4214 || (use_biblatex_natbib
4215 && (is_known(t.cs(), known_biblatex_commands)
4216 || is_known(t.cs(), known_natbib_commands))
4217 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4218 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4219 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4220 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4221 || t.cs() == "parencite" || t.cs() == "citetitle")
4222 || p.next_token().asInput() != "*"))){
4223 context.check_layout(os);
4224 string command = t.cs();
4225 if (p.next_token().asInput() == "*") {
4230 bool const qualified = suffixIs(command, "s");
4232 command = rtrim(command, "s");
4234 // text before the citation
4236 // text after the citation
4238 get_cite_arguments(p, true, before, after, qualified);
4240 // These use natbib cmd names in LyX
4241 // for inter-citeengine compativility
4242 if (command == "citeyear")
4243 command = "citebyear";
4244 else if (command == "cite*")
4245 command = "citeyear";
4246 else if (command == "textcite")
4248 else if (command == "Textcite")
4250 else if (command == "parencite")
4252 else if (command == "Parencite")
4254 else if (command == "parencite*")
4255 command = "citeyearpar";
4256 else if (command == "smartcite")
4257 command = "footcite";
4258 else if (command == "Smartcite")
4259 command = "Footcite";
4261 string const emptyarg = qualified ? "()" : "[]";
4262 if (before.empty() && after == emptyarg)
4265 else if (before == emptyarg && after == emptyarg) {
4266 // avoid \cite[][]{a}
4270 bool literal = false;
4271 pair<bool, string> aft;
4272 pair<bool, string> bef;
4273 // remove the brackets around after and before
4274 if (!after.empty()) {
4276 after.erase(after.length() - 1, 1);
4277 aft = convert_latexed_command_inset_arg(after);
4278 literal = !aft.first;
4279 after = literal ? subst(after, "\n", " ") : aft.second;
4281 if (!before.empty()) {
4283 before.erase(before.length() - 1, 1);
4284 bef = convert_latexed_command_inset_arg(before);
4285 literal |= !bef.first;
4286 before = literal ? subst(before, "\n", " ") : bef.second;
4288 string keys, pretextlist, posttextlist;
4290 map<string, string> pres, posts, preslit, postslit;
4291 vector<string> lkeys;
4292 // text before the citation
4293 string lbefore, lbeforelit;
4294 // text after the citation
4295 string lafter, lafterlit;
4297 pair<bool, string> laft, lbef;
4299 get_cite_arguments(p, true, lbefore, lafter);
4300 // remove the brackets around after and before
4301 if (!lafter.empty()) {
4303 lafter.erase(lafter.length() - 1, 1);
4304 laft = convert_latexed_command_inset_arg(lafter);
4305 literal |= !laft.first;
4306 lafter = laft.second;
4307 lafterlit = subst(lbefore, "\n", " ");
4309 if (!lbefore.empty()) {
4310 lbefore.erase(0, 1);
4311 lbefore.erase(lbefore.length() - 1, 1);
4312 lbef = convert_latexed_command_inset_arg(lbefore);
4313 literal |= !lbef.first;
4314 lbefore = lbef.second;
4315 lbeforelit = subst(lbefore, "\n", " ");
4317 if (lbefore.empty() && lafter == "[]") {
4322 else if (lbefore == "[]" && lafter == "[]") {
4323 // avoid \cite[][]{a}
4329 lkey = p.getArg('{', '}');
4332 if (!lbefore.empty()) {
4333 pres.insert(make_pair(lkey, lbefore));
4334 preslit.insert(make_pair(lkey, lbeforelit));
4336 if (!lafter.empty()) {
4337 posts.insert(make_pair(lkey, lafter));
4338 postslit.insert(make_pair(lkey, lafterlit));
4340 lkeys.push_back(lkey);
4342 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4347 for (auto const & ptl : pres) {
4348 if (!pretextlist.empty())
4349 pretextlist += '\t';
4350 pretextlist += ptl.first + " " + ptl.second;
4352 for (auto const & potl : posts) {
4353 if (!posttextlist.empty())
4354 posttextlist += '\t';
4355 posttextlist += potl.first + " " + potl.second;
4358 keys = convert_literate_command_inset_arg(p.verbatim_item());
4361 after = subst(after, "\n", " ");
4362 if (!before.empty())
4363 before = subst(after, "\n", " ");
4365 string lit = literal ? "\"true\"" : "\"false\"";
4366 begin_command_inset(os, "citation", command);
4367 os << "after " << '"' << after << '"' << "\n";
4368 os << "before " << '"' << before << '"' << "\n";
4372 if (!pretextlist.empty())
4373 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4374 if (!posttextlist.empty())
4375 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4376 os << "literal " << lit << "\n";
4378 // Need to set the cite engine if biblatex is loaded by
4379 // the document class directly
4380 if (preamble.citeEngine() == "basic")
4381 use_biblatex_natbib ?
4382 preamble.citeEngine("biblatex-natbib")
4383 : preamble.citeEngine("biblatex");
4388 is_known(t.cs(), known_jurabib_commands) &&
4389 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4390 context.check_layout(os);
4391 string command = t.cs();
4392 if (p.next_token().asInput() == "*") {
4396 char argumentOrder = '\0';
4397 vector<string> const options =
4398 preamble.getPackageOptions("jurabib");
4399 if (find(options.begin(), options.end(),
4400 "natbiborder") != options.end())
4401 argumentOrder = 'n';
4402 else if (find(options.begin(), options.end(),
4403 "jurabiborder") != options.end())
4404 argumentOrder = 'j';
4406 // text before the citation
4408 // text after the citation
4410 get_cite_arguments(p, argumentOrder != 'j', before, after);
4412 string const citation = p.verbatim_item();
4413 if (!before.empty() && argumentOrder == '\0') {
4414 cerr << "Warning: Assuming argument order "
4415 "of jurabib version 0.6 for\n'"
4416 << command << before << after << '{'
4417 << citation << "}'.\n"
4418 "Add 'jurabiborder' to the jurabib "
4419 "package options if you used an\n"
4420 "earlier jurabib version." << endl;
4422 bool literal = false;
4423 pair<bool, string> aft;
4424 pair<bool, string> bef;
4425 // remove the brackets around after and before
4426 if (!after.empty()) {
4428 after.erase(after.length() - 1, 1);
4429 aft = convert_latexed_command_inset_arg(after);
4430 literal = !aft.first;
4431 after = literal ? subst(after, "\n", " ") : aft.second;
4433 if (!before.empty()) {
4435 before.erase(before.length() - 1, 1);
4436 bef = convert_latexed_command_inset_arg(before);
4437 literal |= !bef.first;
4438 before = literal ? subst(before, "\n", " ") : bef.second;
4439 if (literal && !after.empty())
4440 after = subst(after, "\n", " ");
4442 string lit = literal ? "\"true\"" : "\"false\"";
4443 begin_command_inset(os, "citation", command);
4444 os << "after " << '"' << after << "\"\n"
4445 << "before " << '"' << before << "\"\n"
4446 << "key " << '"' << citation << "\"\n"
4447 << "literal " << lit << "\n";
4449 // Need to set the cite engine if jurabib is loaded by
4450 // the document class directly
4451 if (preamble.citeEngine() == "basic")
4452 preamble.citeEngine("jurabib");
4456 if (t.cs() == "cite"
4457 || t.cs() == "nocite") {
4458 context.check_layout(os);
4459 string after = p.getArg('[', ']');
4460 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4461 bool const literal = !aft.first;
4462 after = literal ? subst(after, "\n", " ") : aft.second;
4463 string lit = literal ? "\"true\"" : "\"false\"";
4464 string key = convert_literate_command_inset_arg(p.verbatim_item());
4465 // store the case that it is "\nocite{*}" to use it later for
4468 begin_command_inset(os, "citation", t.cs());
4469 os << "after " << '"' << after << "\"\n"
4470 << "key " << '"' << key << "\"\n"
4471 << "literal " << lit << "\n";
4473 } else if (t.cs() == "nocite")
4478 if (t.cs() == "index" ||
4479 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4480 context.check_layout(os);
4481 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4482 p.getArg('[', ']') : "";
4483 string const kind = arg.empty() ? "idx" : arg;
4484 begin_inset(os, "Index ");
4485 os << kind << "\nstatus collapsed\n";
4486 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4489 preamble.registerAutomaticallyLoadedPackage("splitidx");
4493 if (t.cs() == "nomenclature") {
4494 context.check_layout(os);
4495 begin_command_inset(os, "nomenclature", "nomenclature");
4496 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4497 if (!prefix.empty())
4498 os << "prefix " << '"' << prefix << '"' << "\n";
4499 string symbol = p.verbatim_item();
4500 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4501 bool literal = !sym.first;
4502 string description = p.verbatim_item();
4503 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4504 literal |= !desc.first;
4506 symbol = subst(symbol, "\n", " ");
4507 description = subst(description, "\n", " ");
4509 symbol = sym.second;
4510 description = desc.second;
4512 string lit = literal ? "\"true\"" : "\"false\"";
4513 os << "symbol " << '"' << symbol;
4514 os << "\"\ndescription \""
4515 << description << "\"\n"
4516 << "literal " << lit << "\n";
4518 preamble.registerAutomaticallyLoadedPackage("nomencl");
4522 if (t.cs() == "label") {
4523 context.check_layout(os);
4524 begin_command_inset(os, "label", "label");
4526 << convert_literate_command_inset_arg(p.verbatim_item())
4532 if (t.cs() == "lyxmintcaption") {
4533 string const pos = p.getArg('[', ']');
4535 string const caption =
4536 parse_text_snippet(p, FLAG_ITEM, false,
4538 minted_nonfloat_caption = "[t]" + caption;
4540 // We already got the caption at the bottom,
4541 // so simply skip it.
4542 parse_text_snippet(p, FLAG_ITEM, false, context);
4544 eat_whitespace(p, os, context, true);
4548 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4549 context.check_layout(os);
4550 string commandname = t.cs();
4552 if (p.next_token().asInput() == "*") {
4557 begin_command_inset(os, "index_print", commandname);
4558 string const indexname = p.getArg('[', ']');
4560 if (indexname.empty())
4561 os << "type \"idx\"\n";
4563 os << "type \"" << indexname << "\"\n";
4564 os << "literal \"true\"\n";
4567 skip_spaces_braces(p);
4568 preamble.registerAutomaticallyLoadedPackage("makeidx");
4569 if (preamble.use_indices() == "true")
4570 preamble.registerAutomaticallyLoadedPackage("splitidx");
4574 if (t.cs() == "printnomenclature") {
4576 string width_type = "";
4577 context.check_layout(os);
4578 begin_command_inset(os, "nomencl_print", "printnomenclature");
4579 // case of a custom width
4581 width = p.getArg('[', ']');
4582 width = translate_len(width);
4583 width_type = "custom";
4585 // case of no custom width
4586 // the case of no custom width but the width set
4587 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4588 // because the user could have set anything, not only the width
4589 // of the longest label (which would be width_type = "auto")
4590 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4591 if (label.empty() && width_type.empty())
4592 width_type = "none";
4593 os << "set_width \"" << width_type << "\"\n";
4594 if (width_type == "custom")
4595 os << "width \"" << width << '\"';
4597 skip_spaces_braces(p);
4598 preamble.registerAutomaticallyLoadedPackage("nomencl");
4602 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4603 context.check_layout(os);
4604 begin_inset(os, "script ");
4605 os << t.cs().substr(4) << '\n';
4606 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4607 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4609 if (t.cs() == "textsubscript")
4610 preamble.registerAutomaticallyLoadedPackage("subscript");
4614 if ((where = is_known(t.cs(), known_quotes))) {
4615 context.check_layout(os);
4616 begin_inset(os, "Quotes ");
4617 string quotetype = known_coded_quotes[where - known_quotes];
4618 // try to make a smart guess about the side
4619 Token const prev = p.prev_token();
4620 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4621 && prev.character() != '\n' && prev.character() != '~');
4622 quotetype = guessQuoteStyle(quotetype, opening);
4625 // LyX adds {} after the quote, so we have to eat
4626 // spaces here if there are any before a possible
4628 eat_whitespace(p, os, context, false);
4633 if ((where = is_known(t.cs(), known_sizes)) &&
4634 context.new_layout_allowed) {
4635 context.check_layout(os);
4636 TeXFont const oldFont = context.font;
4637 context.font.size = known_coded_sizes[where - known_sizes];
4638 output_font_change(os, oldFont, context.font);
4639 eat_whitespace(p, os, context, false);
4643 if ((where = is_known(t.cs(), known_font_families)) &&
4644 context.new_layout_allowed) {
4645 context.check_layout(os);
4646 TeXFont const oldFont = context.font;
4647 context.font.family =
4648 known_coded_font_families[where - known_font_families];
4649 output_font_change(os, oldFont, context.font);
4650 eat_whitespace(p, os, context, false);
4654 if ((where = is_known(t.cs(), known_font_series)) &&
4655 context.new_layout_allowed) {
4656 context.check_layout(os);
4657 TeXFont const oldFont = context.font;
4658 context.font.series =
4659 known_coded_font_series[where - known_font_series];
4660 output_font_change(os, oldFont, context.font);
4661 eat_whitespace(p, os, context, false);
4665 if ((where = is_known(t.cs(), known_font_shapes)) &&
4666 context.new_layout_allowed) {
4667 context.check_layout(os);
4668 TeXFont const oldFont = context.font;
4669 context.font.shape =
4670 known_coded_font_shapes[where - known_font_shapes];
4671 output_font_change(os, oldFont, context.font);
4672 eat_whitespace(p, os, context, false);
4675 if ((where = is_known(t.cs(), known_old_font_families)) &&
4676 context.new_layout_allowed) {
4677 context.check_layout(os);
4678 TeXFont const oldFont = context.font;
4679 context.font.init();
4680 context.font.size = oldFont.size;
4681 context.font.family =
4682 known_coded_font_families[where - known_old_font_families];
4683 output_font_change(os, oldFont, context.font);
4684 eat_whitespace(p, os, context, false);
4688 if ((where = is_known(t.cs(), known_old_font_series)) &&
4689 context.new_layout_allowed) {
4690 context.check_layout(os);
4691 TeXFont const oldFont = context.font;
4692 context.font.init();
4693 context.font.size = oldFont.size;
4694 context.font.series =
4695 known_coded_font_series[where - known_old_font_series];
4696 output_font_change(os, oldFont, context.font);
4697 eat_whitespace(p, os, context, false);
4701 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4702 context.new_layout_allowed) {
4703 context.check_layout(os);
4704 TeXFont const oldFont = context.font;
4705 context.font.init();
4706 context.font.size = oldFont.size;
4707 context.font.shape =
4708 known_coded_font_shapes[where - known_old_font_shapes];
4709 output_font_change(os, oldFont, context.font);
4710 eat_whitespace(p, os, context, false);
4714 if (t.cs() == "selectlanguage") {
4715 context.check_layout(os);
4716 // save the language for the case that a
4717 // \foreignlanguage is used
4718 context.font.language = babel2lyx(p.verbatim_item());
4719 os << "\n\\lang " << context.font.language << "\n";
4723 if (t.cs() == "foreignlanguage") {
4724 string const lang = babel2lyx(p.verbatim_item());
4725 parse_text_attributes(p, os, FLAG_ITEM, outer,
4727 context.font.language, lang);
4731 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4732 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4733 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4735 // We have to output the whole command if it has an option
4736 // because LyX doesn't support this yet, see bug #8214,
4737 // only if there is a single option specifying a variant, we can handle it.
4739 string langopts = p.getOpt();
4740 // check if the option contains a variant, if yes, extract it
4741 string::size_type pos_var = langopts.find("variant");
4742 string::size_type i = langopts.find(',');
4743 string::size_type k = langopts.find('=', pos_var);
4744 if (pos_var != string::npos && i == string::npos) {
4746 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4747 lang = preamble.polyglossia2lyx(variant);
4748 parse_text_attributes(p, os, FLAG_ITEM, outer,
4750 context.font.language, lang);
4752 output_ert_inset(os, t.asInput() + langopts, context);
4754 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4755 parse_text_attributes(p, os, FLAG_ITEM, outer,
4757 context.font.language, lang);
4762 if (t.cs() == "inputencoding") {
4763 // nothing to write here
4764 string const enc = subst(p.verbatim_item(), "\n", " ");
4765 p.setEncoding(enc, Encoding::inputenc);
4769 if (is_known(t.cs(), known_special_chars) ||
4770 (t.cs() == "protect" &&
4771 p.next_token().cat() == catEscape &&
4772 is_known(p.next_token().cs(), known_special_protect_chars))) {
4773 // LyX sometimes puts a \protect in front, so we have to ignore it
4775 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4776 known_special_chars);
4777 context.check_layout(os);
4778 os << known_coded_special_chars[where - known_special_chars];
4779 skip_spaces_braces(p);
4783 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4784 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4785 p.next_next_token().asInput() == "-") ||
4786 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4787 // LyX sometimes puts a \protect in front, so we have to ignore it
4788 if (t.cs() == "protect")
4790 context.check_layout(os);
4791 if (t.cs() == "nobreakdash")
4792 os << "\\SpecialChar nobreakdash\n";
4794 os << "\\SpecialChar endofsentence\n";
4799 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4800 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4801 || t.cs() == "%" || t.cs() == "-") {
4802 context.check_layout(os);
4804 os << "\\SpecialChar softhyphen\n";
4810 if (t.cs() == "char") {
4811 context.check_layout(os);
4812 if (p.next_token().character() == '`') {
4814 if (p.next_token().cs() == "\"") {
4819 output_ert_inset(os, "\\char`", context);
4822 output_ert_inset(os, "\\char", context);
4827 if (t.cs() == "verb") {
4828 context.check_layout(os);
4829 // set catcodes to verbatim early, just in case.
4830 p.setCatcodes(VERBATIM_CATCODES);
4831 string delim = p.get_token().asInput();
4832 Parser::Arg arg = p.verbatimStuff(delim);
4834 output_ert_inset(os, "\\verb" + delim
4835 + arg.second + delim, context);
4837 cerr << "invalid \\verb command. Skipping" << endl;
4841 // Problem: \= creates a tabstop inside the tabbing environment
4842 // and else an accent. In the latter case we really would want
4843 // \={o} instead of \= o.
4844 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4845 output_ert_inset(os, t.asInput(), context);
4849 if (t.cs() == "\\") {
4850 context.check_layout(os);
4852 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4853 else if (p.next_token().asInput() == "*") {
4855 // getOpt() eats the following space if there
4856 // is no optional argument, but that is OK
4857 // here since it has no effect in the output.
4858 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4861 begin_inset(os, "Newline newline");
4867 if (t.cs() == "newline" ||
4868 (t.cs() == "linebreak" && !p.hasOpt())) {
4869 context.check_layout(os);
4870 begin_inset(os, "Newline ");
4873 skip_spaces_braces(p);
4877 if (t.cs() == "input" || t.cs() == "include"
4878 || t.cs() == "verbatiminput"
4879 || t.cs() == "lstinputlisting"
4880 || t.cs() == "inputminted") {
4881 string name = t.cs();
4882 if (name == "verbatiminput"
4883 && p.next_token().asInput() == "*")
4884 name += p.get_token().asInput();
4885 context.check_layout(os);
4887 if (name == "lstinputlisting" && p.hasOpt()) {
4888 lstparams = p.getArg('[', ']');
4889 lstparams = subst(lstparams, "\n", " ");
4890 } else if (name == "inputminted") {
4891 name = "lstinputlisting";
4892 string const lang = p.getArg('{', '}');
4893 if (lang != "tex") {
4894 string cmd = "\\inputminted{" + lang + "}{";
4895 cmd += p.getArg('{', '}') + "}";
4896 output_ert_inset(os, cmd, context);
4899 if (prefixIs(minted_nonfloat_caption, "[t]")) {
4900 minted_nonfloat_caption.erase(0,3);
4901 // extract label and caption from the already produced LyX code
4902 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
4903 string const caption = nfc.front();
4905 vector<string>::iterator it =
4906 find(nfc.begin(), nfc.end(), "LatexCommand label");
4907 if (it != nfc.end()) {
4909 if (it != nfc.end())
4911 label = support::split(label, '"');
4914 minted_nonfloat_caption.clear();
4915 lstparams = "caption=" + caption;
4917 lstparams += ",label=" + label;
4918 lstparams = subst(lstparams, "\n", " ");
4921 string filename(normalize_filename(p.getArg('{', '}')));
4922 string const path = getMasterFilePath(true);
4923 // We want to preserve relative / absolute filenames,
4924 // therefore path is only used for testing
4925 if ((t.cs() == "include" || t.cs() == "input") &&
4926 !makeAbsPath(filename, path).exists()) {
4927 // The file extension is probably missing.
4928 // Now try to find it out.
4929 string const tex_name =
4930 find_file(filename, path,
4931 known_tex_extensions);
4932 if (!tex_name.empty())
4933 filename = tex_name;
4935 bool external = false;
4937 if (makeAbsPath(filename, path).exists()) {
4938 string const abstexname =
4939 makeAbsPath(filename, path).absFileName();
4940 string const absfigname =
4941 changeExtension(abstexname, ".fig");
4942 fix_child_filename(filename);
4943 string const lyxname = changeExtension(filename,
4944 roundtripMode() ? ".lyx.lyx" : ".lyx");
4945 string const abslyxname = makeAbsPath(
4946 lyxname, getParentFilePath(false)).absFileName();
4948 if (!skipChildren())
4949 external = FileName(absfigname).exists();
4950 if (t.cs() == "input" && !skipChildren()) {
4951 string const ext = getExtension(abstexname);
4953 // Combined PS/LaTeX:
4954 // x.eps, x.pstex_t (old xfig)
4955 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4956 FileName const absepsname(
4957 changeExtension(abstexname, ".eps"));
4958 FileName const abspstexname(
4959 changeExtension(abstexname, ".pstex"));
4960 bool const xfigeps =
4961 (absepsname.exists() ||
4962 abspstexname.exists()) &&
4965 // Combined PDF/LaTeX:
4966 // x.pdf, x.pdftex_t (old xfig)
4967 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4968 FileName const abspdfname(
4969 changeExtension(abstexname, ".pdf"));
4970 bool const xfigpdf =
4971 abspdfname.exists() &&
4972 (ext == "pdftex_t" || ext == "pdf_t");
4976 // Combined PS/PDF/LaTeX:
4977 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4978 string const absbase2(
4979 removeExtension(abstexname) + "_pspdftex");
4980 FileName const abseps2name(
4981 addExtension(absbase2, ".eps"));
4982 FileName const abspdf2name(
4983 addExtension(absbase2, ".pdf"));
4984 bool const xfigboth =
4985 abspdf2name.exists() &&
4986 abseps2name.exists() && ext == "pspdftex";
4988 xfig = xfigpdf || xfigeps || xfigboth;
4989 external = external && xfig;
4992 outname = changeExtension(filename, ".fig");
4993 FileName abssrc(changeExtension(abstexname, ".fig"));
4994 copy_file(abssrc, outname);
4996 // Don't try to convert, the result
4997 // would be full of ERT.
4999 FileName abssrc(abstexname);
5000 copy_file(abssrc, outname);
5001 } else if (t.cs() != "verbatiminput" &&
5003 tex2lyx(abstexname, FileName(abslyxname),
5006 // no need to call copy_file
5007 // tex2lyx creates the file
5010 FileName abssrc(abstexname);
5011 copy_file(abssrc, outname);
5014 cerr << "Warning: Could not find included file '"
5015 << filename << "'." << endl;
5019 begin_inset(os, "External\n");
5020 os << "\ttemplate XFig\n"
5021 << "\tfilename " << outname << '\n';
5022 registerExternalTemplatePackages("XFig");
5024 begin_command_inset(os, "include", name);
5025 outname = subst(outname, "\"", "\\\"");
5026 os << "preview false\n"
5027 "filename \"" << outname << "\"\n";
5028 if (!lstparams.empty())
5029 os << "lstparams \"" << lstparams << "\"\n";
5030 if (t.cs() == "verbatiminput")
5031 preamble.registerAutomaticallyLoadedPackage("verbatim");
5037 if (t.cs() == "bibliographystyle") {
5038 // store new bibliographystyle
5039 bibliographystyle = p.verbatim_item();
5040 // If any other command than \bibliography, \addcontentsline
5041 // and \nocite{*} follows, we need to output the style
5042 // (because it might be used by that command).
5043 // Otherwise, it will automatically be output by LyX.
5046 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5047 if (t2.cat() == catBegin)
5049 if (t2.cat() != catEscape)
5051 if (t2.cs() == "nocite") {
5052 if (p.getArg('{', '}') == "*")
5054 } else if (t2.cs() == "bibliography")
5056 else if (t2.cs() == "phantomsection") {
5060 else if (t2.cs() == "addcontentsline") {
5061 // get the 3 arguments of \addcontentsline
5064 contentslineContent = p.getArg('{', '}');
5065 // if the last argument is not \refname we must output
5066 if (contentslineContent == "\\refname")
5073 output_ert_inset(os,
5074 "\\bibliographystyle{" + bibliographystyle + '}',
5080 if (t.cs() == "phantomsection") {
5081 // we only support this if it occurs between
5082 // \bibliographystyle and \bibliography
5083 if (bibliographystyle.empty())
5084 output_ert_inset(os, "\\phantomsection", context);
5088 if (t.cs() == "addcontentsline") {
5089 context.check_layout(os);
5090 // get the 3 arguments of \addcontentsline
5091 string const one = p.getArg('{', '}');
5092 string const two = p.getArg('{', '}');
5093 string const three = p.getArg('{', '}');
5094 // only if it is a \refname, we support if for the bibtex inset
5095 if (contentslineContent != "\\refname") {
5096 output_ert_inset(os,
5097 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5103 else if (t.cs() == "bibliography") {
5104 context.check_layout(os);
5106 begin_command_inset(os, "bibtex", "bibtex");
5107 if (!btprint.empty()) {
5108 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5109 // clear the string because the next BibTeX inset can be without the
5110 // \nocite{*} option
5113 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5114 // Do we have addcontentsline?
5115 if (contentslineContent == "\\refname") {
5116 BibOpts = "bibtotoc";
5117 // clear string because next BibTeX inset can be without addcontentsline
5118 contentslineContent.clear();
5120 // Do we have a bibliographystyle set?
5121 if (!bibliographystyle.empty()) {
5122 if (BibOpts.empty())
5123 BibOpts = normalize_filename(bibliographystyle);
5125 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5126 // clear it because each bibtex entry has its style
5127 // and we need an empty string to handle \phantomsection
5128 bibliographystyle.clear();
5130 os << "options " << '"' << BibOpts << '"' << "\n";
5135 if (t.cs() == "printbibliography") {
5136 context.check_layout(os);
5138 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5139 vector<string> opts = getVectorFromString(bbloptions);
5140 vector<string>::iterator it =
5141 find(opts.begin(), opts.end(), "heading=bibintoc");
5142 if (it != opts.end()) {
5144 BibOpts = "bibtotoc";
5146 bbloptions = getStringFromVector(opts);
5147 begin_command_inset(os, "bibtex", "bibtex");
5148 if (!btprint.empty()) {
5149 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5150 // clear the string because the next BibTeX inset can be without the
5151 // \nocite{*} option
5155 for (auto const & bf : preamble.biblatex_bibliographies) {
5156 if (!bibfiles.empty())
5158 bibfiles += normalize_filename(bf);
5160 if (!bibfiles.empty())
5161 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5162 // Do we have addcontentsline?
5163 if (contentslineContent == "\\refname") {
5164 BibOpts = "bibtotoc";
5165 // clear string because next BibTeX inset can be without addcontentsline
5166 contentslineContent.clear();
5168 os << "options " << '"' << BibOpts << '"' << "\n";
5169 if (!bbloptions.empty())
5170 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5172 need_commentbib = false;
5176 if (t.cs() == "bibbysection") {
5177 context.check_layout(os);
5179 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5180 vector<string> opts = getVectorFromString(bbloptions);
5181 vector<string>::iterator it =
5182 find(opts.begin(), opts.end(), "heading=bibintoc");
5183 if (it != opts.end()) {
5185 BibOpts = "bibtotoc";
5187 bbloptions = getStringFromVector(opts);
5188 begin_command_inset(os, "bibtex", "bibtex");
5189 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5191 for (auto const & bf : preamble.biblatex_bibliographies) {
5192 if (!bibfiles.empty())
5194 bibfiles += normalize_filename(bf);
5196 if (!bibfiles.empty())
5197 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5198 os << "options " << '"' << BibOpts << '"' << "\n";
5199 if (!bbloptions.empty())
5200 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5202 need_commentbib = false;
5206 if (t.cs() == "parbox") {
5207 // Test whether this is an outer box of a shaded box
5209 // swallow arguments
5210 while (p.hasOpt()) {
5212 p.skip_spaces(true);
5215 p.skip_spaces(true);
5217 if (p.next_token().cat() == catBegin)
5219 p.skip_spaces(true);
5220 Token to = p.get_token();
5221 bool shaded = false;
5222 if (to.asInput() == "\\begin") {
5223 p.skip_spaces(true);
5224 if (p.getArg('{', '}') == "shaded")
5229 parse_outer_box(p, os, FLAG_ITEM, outer,
5230 context, "parbox", "shaded");
5232 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5233 "", "", t.cs(), "", "");
5237 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5238 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5239 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5240 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5244 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5245 string backgroundcolor;
5246 preamble.registerAutomaticallyLoadedPackage("xcolor");
5247 if (t.cs() == "fcolorbox") {
5248 string const framecolor = p.getArg('{', '}');
5249 backgroundcolor = p.getArg('{', '}');
5250 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5252 backgroundcolor = p.getArg('{', '}');
5253 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5258 // FIXME: due to the compiler limit of "if" nestings
5259 // the code for the alignment was put here
5260 // put them in their own if if this is fixed
5261 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5262 || t.cs() == "shadowsize"
5263 || t.cs() == "raggedleft" || t.cs() == "centering"
5264 || t.cs() == "raggedright") {
5265 if (t.cs() == "fboxrule")
5267 if (t.cs() == "fboxsep")
5269 if (t.cs() == "shadowsize")
5271 if (t.cs() != "raggedleft" && t.cs() != "centering"
5272 && t.cs() != "raggedright") {
5273 p.skip_spaces(true);
5274 while (p.good() && p.next_token().cat() != catSpace
5275 && p.next_token().cat() != catNewline
5276 && p.next_token().cat() != catEscape) {
5277 if (t.cs() == "fboxrule")
5278 fboxrule = fboxrule + p.get_token().asInput();
5279 if (t.cs() == "fboxsep")
5280 fboxsep = fboxsep + p.get_token().asInput();
5281 if (t.cs() == "shadowsize")
5282 shadow_size = shadow_size + p.get_token().asInput();
5285 output_ert_inset(os, t.asInput(), context);
5290 //\framebox() is part of the picture environment and different from \framebox{}
5291 //\framebox{} will be parsed by parse_outer_box
5292 if (t.cs() == "framebox") {
5293 if (p.next_token().character() == '(') {
5294 //the syntax is: \framebox(x,y)[position]{content}
5295 string arg = t.asInput();
5296 arg += p.getFullParentheseArg();
5297 arg += p.getFullOpt();
5298 eat_whitespace(p, os, context, false);
5299 output_ert_inset(os, arg + '{', context);
5300 parse_text(p, os, FLAG_ITEM, outer, context);
5301 output_ert_inset(os, "}", context);
5303 //the syntax is: \framebox[width][position]{content}
5304 string special = p.getFullOpt();
5305 special += p.getOpt();
5306 parse_outer_box(p, os, FLAG_ITEM, outer,
5307 context, t.cs(), special);
5312 //\makebox() is part of the picture environment and different from \makebox{}
5313 //\makebox{} will be parsed by parse_box
5314 if (t.cs() == "makebox") {
5315 if (p.next_token().character() == '(') {
5316 //the syntax is: \makebox(x,y)[position]{content}
5317 string arg = t.asInput();
5318 arg += p.getFullParentheseArg();
5319 arg += p.getFullOpt();
5320 eat_whitespace(p, os, context, false);
5321 output_ert_inset(os, arg + '{', context);
5322 parse_text(p, os, FLAG_ITEM, outer, context);
5323 output_ert_inset(os, "}", context);
5325 //the syntax is: \makebox[width][position]{content}
5326 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5327 "", "", t.cs(), "", "");
5331 if (t.cs() == "smallskip" ||
5332 t.cs() == "medskip" ||
5333 t.cs() == "bigskip" ||
5334 t.cs() == "vfill") {
5335 context.check_layout(os);
5336 begin_inset(os, "VSpace ");
5339 skip_spaces_braces(p);
5343 if ((where = is_known(t.cs(), known_spaces))) {
5344 context.check_layout(os);
5345 begin_inset(os, "space ");
5346 os << '\\' << known_coded_spaces[where - known_spaces]
5349 // LaTeX swallows whitespace after all spaces except
5350 // "\\,". We have to do that here, too, because LyX
5351 // adds "{}" which would make the spaces significant.
5353 eat_whitespace(p, os, context, false);
5354 // LyX adds "{}" after all spaces except "\\ " and
5355 // "\\,", so we have to remove "{}".
5356 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5357 // remove the braces after "\\,", too.
5363 if (t.cs() == "newpage" ||
5364 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5365 t.cs() == "clearpage" ||
5366 t.cs() == "cleardoublepage") {
5367 context.check_layout(os);
5368 begin_inset(os, "Newpage ");
5371 skip_spaces_braces(p);
5375 if (t.cs() == "DeclareRobustCommand" ||
5376 t.cs() == "DeclareRobustCommandx" ||
5377 t.cs() == "newcommand" ||
5378 t.cs() == "newcommandx" ||
5379 t.cs() == "providecommand" ||
5380 t.cs() == "providecommandx" ||
5381 t.cs() == "renewcommand" ||
5382 t.cs() == "renewcommandx") {
5383 // DeclareRobustCommand, DeclareRobustCommandx,
5384 // providecommand and providecommandx could be handled
5385 // by parse_command(), but we need to call
5386 // add_known_command() here.
5387 string name = t.asInput();
5388 if (p.next_token().asInput() == "*") {
5389 // Starred form. Eat '*'
5393 string const command = p.verbatim_item();
5394 string const opt1 = p.getFullOpt();
5395 string const opt2 = p.getFullOpt();
5396 add_known_command(command, opt1, !opt2.empty());
5397 string const ert = name + '{' + command + '}' +
5399 '{' + p.verbatim_item() + '}';
5401 if (t.cs() == "DeclareRobustCommand" ||
5402 t.cs() == "DeclareRobustCommandx" ||
5403 t.cs() == "providecommand" ||
5404 t.cs() == "providecommandx" ||
5405 name[name.length()-1] == '*')
5406 output_ert_inset(os, ert, context);
5408 context.check_layout(os);
5409 begin_inset(os, "FormulaMacro");
5416 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5417 // let could be handled by parse_command(),
5418 // but we need to call add_known_command() here.
5419 string ert = t.asInput();
5422 if (p.next_token().cat() == catBegin) {
5423 name = p.verbatim_item();
5424 ert += '{' + name + '}';
5426 name = p.verbatim_item();
5431 if (p.next_token().cat() == catBegin) {
5432 command = p.verbatim_item();
5433 ert += '{' + command + '}';
5435 command = p.verbatim_item();
5438 // If command is known, make name known too, to parse
5439 // its arguments correctly. For this reason we also
5440 // have commands in syntax.default that are hardcoded.
5441 CommandMap::iterator it = known_commands.find(command);
5442 if (it != known_commands.end())
5443 known_commands[t.asInput()] = it->second;
5444 output_ert_inset(os, ert, context);
5448 if (t.cs() == "hspace" || t.cs() == "vspace") {
5451 string name = t.asInput();
5452 string const length = p.verbatim_item();
5455 bool valid = splitLatexLength(length, valstring, unit);
5456 bool known_hspace = false;
5457 bool known_vspace = false;
5458 bool known_unit = false;
5461 istringstream iss(valstring);
5464 if (t.cs()[0] == 'h') {
5465 if (unit == "\\fill") {
5470 known_hspace = true;
5473 if (unit == "\\smallskipamount") {
5475 known_vspace = true;
5476 } else if (unit == "\\medskipamount") {
5478 known_vspace = true;
5479 } else if (unit == "\\bigskipamount") {
5481 known_vspace = true;
5482 } else if (unit == "\\fill") {
5484 known_vspace = true;
5488 if (!known_hspace && !known_vspace) {
5489 switch (unitFromString(unit)) {
5505 //unitFromString(unit) fails for relative units like Length::PCW
5506 // therefore handle them separately
5507 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5508 || unit == "\\textwidth" || unit == "\\linewidth"
5509 || unit == "\\textheight" || unit == "\\paperheight"
5510 || unit == "\\baselineskip")
5518 // check for glue lengths
5519 bool is_gluelength = false;
5520 string gluelength = length;
5521 string::size_type i = length.find(" minus");
5522 if (i == string::npos) {
5523 i = length.find(" plus");
5524 if (i != string::npos)
5525 is_gluelength = true;
5527 is_gluelength = true;
5528 // if yes transform "9xx minus 8yy plus 7zz"
5530 if (is_gluelength) {
5531 i = gluelength.find(" minus");
5532 if (i != string::npos)
5533 gluelength.replace(i, 7, "-");
5534 i = gluelength.find(" plus");
5535 if (i != string::npos)
5536 gluelength.replace(i, 6, "+");
5539 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5540 // Literal horizontal length or known variable
5541 context.check_layout(os);
5542 begin_inset(os, "space ");
5550 if (known_unit && !known_hspace)
5551 os << "\n\\length " << translate_len(length);
5553 os << "\n\\length " << gluelength;
5555 } else if (known_unit || known_vspace || is_gluelength) {
5556 // Literal vertical length or known variable
5557 context.check_layout(os);
5558 begin_inset(os, "VSpace ");
5561 if (known_unit && !known_vspace)
5562 os << translate_len(length);
5569 // LyX can't handle other length variables in Inset VSpace/space
5574 output_ert_inset(os, name + '{' + unit + '}', context);
5575 else if (value == -1.0)
5576 output_ert_inset(os, name + "{-" + unit + '}', context);
5578 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5580 output_ert_inset(os, name + '{' + length + '}', context);
5585 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5586 // might be one or several options or a star.
5587 // The single '=' is meant here.
5588 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5592 context.check_layout(os);
5593 // store the latexparam here. This is eaten in parse_text_in_inset
5594 context.latexparam = newinsetlayout->latexparam();
5595 docstring name = newinsetlayout->name();
5596 bool const caption = name.find(from_ascii("Caption:")) == 0;
5598 // Already done for floating minted listings.
5599 if (minted_float.empty()) {
5600 begin_inset(os, "Caption ");
5601 os << to_utf8(name.substr(8)) << '\n';
5604 // FIXME: what do we do if the prefix is not Flex: ?
5605 if (prefixIs(name, from_ascii("Flex:")))
5607 begin_inset(os, "Flex ");
5608 os << to_utf8(name) << '\n'
5609 << "status collapsed\n";
5611 if (!minted_float.empty()) {
5612 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5613 } else if (newinsetlayout->isPassThru()) {
5614 // set catcodes to verbatim early, just in case.
5615 p.setCatcodes(VERBATIM_CATCODES);
5616 string delim = p.get_token().asInput();
5618 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5619 //FIXME: handle error condition
5620 string const arg = p.verbatimStuff("}").second;
5621 Context newcontext(true, context.textclass);
5622 if (newinsetlayout->forcePlainLayout())
5623 newcontext.layout = &context.textclass.plainLayout();
5624 output_ert(os, arg, newcontext);
5626 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5627 context.latexparam.clear();
5630 // Minted caption insets are not closed here because
5631 // we collect everything into the caption.
5632 if (minted_float.empty())
5637 // The single '=' is meant here.
5638 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5642 context.check_layout(os);
5643 docstring const name = newinsetlayout->name();
5644 bool const caption = name.find(from_ascii("Caption:")) == 0;
5646 // Already done for floating minted listings.
5647 if (minted_float.empty()) {
5648 begin_inset(os, "Caption ");
5649 os << to_utf8(name.substr(8)) << '\n';
5652 begin_inset(os, "Flex ");
5653 os << to_utf8(name) << '\n'
5654 << "status collapsed\n";
5656 if (!minted_float.empty()) {
5657 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5658 } else if (newinsetlayout->isPassThru()) {
5659 // set catcodes to verbatim early, just in case.
5660 p.setCatcodes(VERBATIM_CATCODES);
5661 string delim = p.get_token().asInput();
5663 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5664 //FIXME: handle error condition
5665 string const arg = p.verbatimStuff("}").second;
5666 Context newcontext(true, context.textclass);
5667 if (newinsetlayout->forcePlainLayout())
5668 newcontext.layout = &context.textclass.plainLayout();
5669 output_ert(os, arg, newcontext);
5671 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5674 // Minted caption insets are not closed here because
5675 // we collect everything into the caption.
5676 if (minted_float.empty())
5681 if (t.cs() == "includepdf") {
5683 string const arg = p.getArg('[', ']');
5684 map<string, string> opts;
5685 vector<string> keys;
5686 split_map(arg, opts, keys);
5687 string name = normalize_filename(p.verbatim_item());
5688 string const path = getMasterFilePath(true);
5689 // We want to preserve relative / absolute filenames,
5690 // therefore path is only used for testing
5691 if (!makeAbsPath(name, path).exists()) {
5692 // The file extension is probably missing.
5693 // Now try to find it out.
5694 char const * const pdfpages_format[] = {"pdf", 0};
5695 string const pdftex_name =
5696 find_file(name, path, pdfpages_format);
5697 if (!pdftex_name.empty()) {
5702 FileName const absname = makeAbsPath(name, path);
5703 if (absname.exists())
5705 fix_child_filename(name);
5706 copy_file(absname, name);
5708 cerr << "Warning: Could not find file '"
5709 << name << "'." << endl;
5711 context.check_layout(os);
5712 begin_inset(os, "External\n\ttemplate ");
5713 os << "PDFPages\n\tfilename "
5715 // parse the options
5716 if (opts.find("pages") != opts.end())
5717 os << "\textra LaTeX \"pages="
5718 << opts["pages"] << "\"\n";
5719 if (opts.find("angle") != opts.end())
5720 os << "\trotateAngle "
5721 << opts["angle"] << '\n';
5722 if (opts.find("origin") != opts.end()) {
5724 string const opt = opts["origin"];
5725 if (opt == "tl") ss << "topleft";
5726 if (opt == "bl") ss << "bottomleft";
5727 if (opt == "Bl") ss << "baselineleft";
5728 if (opt == "c") ss << "center";
5729 if (opt == "tc") ss << "topcenter";
5730 if (opt == "bc") ss << "bottomcenter";
5731 if (opt == "Bc") ss << "baselinecenter";
5732 if (opt == "tr") ss << "topright";
5733 if (opt == "br") ss << "bottomright";
5734 if (opt == "Br") ss << "baselineright";
5735 if (!ss.str().empty())
5736 os << "\trotateOrigin " << ss.str() << '\n';
5738 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5740 if (opts.find("width") != opts.end())
5742 << translate_len(opts["width"]) << '\n';
5743 if (opts.find("height") != opts.end())
5745 << translate_len(opts["height"]) << '\n';
5746 if (opts.find("keepaspectratio") != opts.end())
5747 os << "\tkeepAspectRatio\n";
5749 context.check_layout(os);
5750 registerExternalTemplatePackages("PDFPages");
5754 if (t.cs() == "loadgame") {
5756 string name = normalize_filename(p.verbatim_item());
5757 string const path = getMasterFilePath(true);
5758 // We want to preserve relative / absolute filenames,
5759 // therefore path is only used for testing
5760 if (!makeAbsPath(name, path).exists()) {
5761 // The file extension is probably missing.
5762 // Now try to find it out.
5763 char const * const lyxskak_format[] = {"fen", 0};
5764 string const lyxskak_name =
5765 find_file(name, path, lyxskak_format);
5766 if (!lyxskak_name.empty())
5767 name = lyxskak_name;
5769 FileName const absname = makeAbsPath(name, path);
5770 if (absname.exists())
5772 fix_child_filename(name);
5773 copy_file(absname, name);
5775 cerr << "Warning: Could not find file '"
5776 << name << "'." << endl;
5777 context.check_layout(os);
5778 begin_inset(os, "External\n\ttemplate ");
5779 os << "ChessDiagram\n\tfilename "
5782 context.check_layout(os);
5783 // after a \loadgame follows a \showboard
5784 if (p.get_token().asInput() == "showboard")
5786 registerExternalTemplatePackages("ChessDiagram");
5790 // try to see whether the string is in unicodesymbols
5791 // Only use text mode commands, since we are in text mode here,
5792 // and math commands may be invalid (bug 6797)
5793 string name = t.asInput();
5794 // handle the dingbats, cyrillic and greek
5795 if (name == "\\ding" || name == "\\textcyr" ||
5796 (name == "\\textgreek" && !preamble.usePolyglossia()))
5797 name = name + '{' + p.getArg('{', '}') + '}';
5798 // handle the ifsym characters
5799 else if (name == "\\textifsymbol") {
5800 string const optif = p.getFullOpt();
5801 string const argif = p.getArg('{', '}');
5802 name = name + optif + '{' + argif + '}';
5804 // handle the \ascii characters
5805 // the case of \ascii within braces, as LyX outputs it, is already
5806 // handled for t.cat() == catBegin
5807 else if (name == "\\ascii") {
5808 // the code is "\asci\xxx"
5809 name = "{" + name + p.get_token().asInput() + "}";
5812 // handle some TIPA special characters
5813 else if (preamble.isPackageUsed("tipa")) {
5814 if (name == "\\s") {
5815 // fromLaTeXCommand() does not yet
5816 // recognize tipa short cuts
5817 name = "\\textsyllabic";
5818 } else if (name == "\\=" &&
5819 p.next_token().asInput() == "*") {
5820 // fromLaTeXCommand() does not yet
5821 // recognize tipa short cuts
5823 name = "\\textsubbar";
5824 } else if (name == "\\textdoublevertline") {
5825 // FIXME: This is not correct,
5826 // \textvertline is higher than \textbardbl
5827 name = "\\textbardbl";
5829 } else if (name == "\\!" ) {
5830 if (p.next_token().asInput() == "b") {
5831 p.get_token(); // eat 'b'
5834 } else if (p.next_token().asInput() == "d") {
5838 } else if (p.next_token().asInput() == "g") {
5842 } else if (p.next_token().asInput() == "G") {
5844 name = "\\texthtscg";
5846 } else if (p.next_token().asInput() == "j") {
5848 name = "\\texthtbardotlessj";
5850 } else if (p.next_token().asInput() == "o") {
5852 name = "\\textbullseye";
5855 } else if (name == "\\*" ) {
5856 if (p.next_token().asInput() == "k") {
5858 name = "\\textturnk";
5860 } else if (p.next_token().asInput() == "r") {
5861 p.get_token(); // eat 'b'
5862 name = "\\textturnr";
5864 } else if (p.next_token().asInput() == "t") {
5866 name = "\\textturnt";
5868 } else if (p.next_token().asInput() == "w") {
5870 name = "\\textturnw";
5875 if ((name.size() == 2 &&
5876 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5877 p.next_token().asInput() != "*") ||
5878 is_known(name.substr(1), known_tipa_marks)) {
5879 // name is a command that corresponds to a
5880 // combining character in unicodesymbols.
5881 // Append the argument, fromLaTeXCommand()
5882 // will either convert it to a single
5883 // character or a combining sequence.
5884 name += '{' + p.verbatim_item() + '}';
5886 // now get the character from unicodesymbols
5890 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5891 Encodings::TEXT_CMD, termination, rem, &req));
5893 context.check_layout(os);
5896 output_ert_inset(os, to_utf8(rem), context);
5898 skip_spaces_braces(p);
5899 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5900 preamble.registerAutomaticallyLoadedPackage(*it);
5902 //cerr << "#: " << t << " mode: " << mode << endl;
5903 // heuristic: read up to next non-nested space
5905 string s = t.asInput();
5906 string z = p.verbatim_item();
5907 while (p.good() && z != " " && !z.empty()) {
5908 //cerr << "read: " << z << endl;
5910 z = p.verbatim_item();
5912 cerr << "found ERT: " << s << endl;
5913 output_ert_inset(os, s + ' ', context);
5916 if (t.asInput() == name &&
5917 p.next_token().asInput() == "*") {
5918 // Starred commands like \vspace*{}
5919 p.get_token(); // Eat '*'
5922 if (!parse_command(name, p, os, outer, context)) {
5923 output_ert_inset(os, name, context);
5924 // Try to handle options of unknown commands:
5925 // Look if we have an optional arguments,
5926 // and if so, put the brackets in ERT.
5927 while (p.hasOpt()) {
5928 p.get_token(); // eat '['
5929 output_ert_inset(os, "[", context);
5930 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
5931 output_ert_inset(os, "]", context);
5939 string guessLanguage(Parser & p, string const & lang)
5941 typedef std::map<std::string, size_t> LangMap;
5942 // map from language names to number of characters
5945 for (char const * const * i = supported_CJK_languages; *i; i++)
5946 used[string(*i)] = 0;
5949 Token const t = p.get_token();
5950 // comments are not counted for any language
5951 if (t.cat() == catComment)
5953 // commands are not counted as well, but we need to detect
5954 // \begin{CJK} and switch encoding if needed
5955 if (t.cat() == catEscape) {
5956 if (t.cs() == "inputencoding") {
5957 string const enc = subst(p.verbatim_item(), "\n", " ");
5958 p.setEncoding(enc, Encoding::inputenc);
5961 if (t.cs() != "begin")
5964 // Non-CJK content is counted for lang.
5965 // We do not care about the real language here:
5966 // If we have more non-CJK contents than CJK contents,
5967 // we simply use the language that was specified as
5968 // babel main language.
5969 used[lang] += t.asInput().length();
5972 // Now we are starting an environment
5974 string const name = p.getArg('{', '}');
5975 if (name != "CJK") {
5979 // It is a CJK environment
5981 /* name = */ p.getArg('{', '}');
5982 string const encoding = p.getArg('{', '}');
5983 /* mapping = */ p.getArg('{', '}');
5984 string const encoding_old = p.getEncoding();
5985 char const * const * const where =
5986 is_known(encoding, supported_CJK_encodings);
5988 p.setEncoding(encoding, Encoding::CJK);
5990 p.setEncoding("UTF-8");
5991 string const text = p.ertEnvironment("CJK");
5992 p.setEncoding(encoding_old);
5995 // ignore contents in unknown CJK encoding
5998 // the language of the text
6000 supported_CJK_languages[where - supported_CJK_encodings];
6001 used[cjk] += text.length();
6003 LangMap::const_iterator use = used.begin();
6004 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6005 if (it->second > use->second)
6012 void check_comment_bib(ostream & os, Context & context)
6014 if (!need_commentbib)
6016 // We have a bibliography database, but no bibliography with biblatex
6017 // which is completely valid. Insert a bibtex inset in a note.
6018 context.check_layout(os);
6019 begin_inset(os, "Note Note\n");
6020 os << "status open\n";
6021 os << "\\begin_layout Plain Layout\n";
6022 begin_command_inset(os, "bibtex", "bibtex");
6024 for (auto const & bf : preamble.biblatex_bibliographies) {
6025 if (!bibfiles.empty())
6027 bibfiles += normalize_filename(bf);
6029 if (!bibfiles.empty())
6030 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6031 end_inset(os);// Bibtex
6032 os << "\\end_layout\n";
6033 end_inset(os);// Note