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 "medspace", "thickspace", "negthinspace", "negmedspace", "negthickspace",
322 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
323 "rightarrowfill", "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 "medspace{}", "thickspace{}", "negthinspace{}", "negmedspace{}", "negthickspace{}",
329 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
330 "rightarrowfill{}", "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 eatParagraph,
762 bool eatNewline = true);
766 * Skips whitespace and braces.
767 * This should be called after a command has been parsed that is not put into
768 * ERT, and where LyX adds "{}" if needed.
770 void skip_spaces_braces(Parser & p, bool keepws = false)
772 /* The following four examples produce the same typeset output and
773 should be handled by this function:
781 // Unfortunately we need to skip comments, too.
782 // We can't use eat_whitespace since writing them after the {}
783 // results in different output in some cases.
784 bool const skipped_spaces = p.skip_spaces(true);
785 bool const skipped_braces = skip_braces(p);
786 if (keepws && skipped_spaces && !skipped_braces)
787 // put back the space (it is better handled by check_space)
788 p.unskip_spaces(true);
792 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
793 Context & context, Layout::LaTeXArgMap const & latexargs)
795 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
797 context.check_layout(os);
803 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
804 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
805 for (; lait != laend; ++lait) {
807 eat_whitespace(p, os, context, false);
808 if (lait->second.mandatory) {
809 if (p.next_token().cat() != catBegin)
811 string ldelim = to_utf8(lait->second.ldelim);
812 string rdelim = to_utf8(lait->second.rdelim);
817 p.get_token(); // eat ldelim
818 if (ldelim.size() > 1)
819 p.get_token(); // eat ldelim
821 context.check_layout(os);
824 begin_inset(os, "Argument ");
827 os << i << "\nstatus collapsed\n\n";
828 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
831 string ldelim = to_utf8(lait->second.ldelim);
832 string rdelim = to_utf8(lait->second.rdelim);
837 string tok = p.next_token().asInput();
838 // we only support delimiters with max 2 chars for now.
839 if (ldelim.size() > 1)
840 tok += p.next_next_token().asInput();
841 if (p.next_token().cat() == catEscape || tok != ldelim)
843 p.get_token(); // eat ldelim
844 if (ldelim.size() > 1)
845 p.get_token(); // eat ldelim
847 context.check_layout(os);
850 begin_inset(os, "Argument ");
853 os << i << "\nstatus collapsed\n\n";
854 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
857 eat_whitespace(p, os, context, false);
862 void output_command_layout(ostream & os, Parser & p, bool outer,
863 Context & parent_context,
864 Layout const * newlayout)
866 TeXFont const oldFont = parent_context.font;
867 // save the current font size
868 string const size = oldFont.size;
869 // reset the font size to default, because the font size switches
870 // don't affect section headings and the like
871 parent_context.font.size = Context::normalfont.size;
872 // we only need to write the font change if we have an open layout
873 if (!parent_context.atParagraphStart())
874 output_font_change(os, oldFont, parent_context.font);
875 parent_context.check_end_layout(os);
876 Context context(true, parent_context.textclass, newlayout,
877 parent_context.layout, parent_context.font);
878 if (parent_context.deeper_paragraph) {
879 // We are beginning a nested environment after a
880 // deeper paragraph inside the outer list environment.
881 // Therefore we don't need to output a "begin deeper".
882 context.need_end_deeper = true;
884 context.check_deeper(os);
885 output_arguments(os, p, outer, true, string(), context,
886 context.layout->latexargs());
887 // If we have a latex param, we eat it here.
888 if (!parent_context.latexparam.empty()) {
890 Context dummy(true, parent_context.textclass);
891 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
892 string(1, parent_context.latexparam.back()));
894 parse_text(p, os, FLAG_ITEM, outer, context);
895 output_arguments(os, p, outer, false, "post", context,
896 context.layout->postcommandargs());
897 context.check_end_layout(os);
898 if (parent_context.deeper_paragraph) {
899 // We must suppress the "end deeper" because we
900 // suppressed the "begin deeper" above.
901 context.need_end_deeper = false;
903 context.check_end_deeper(os);
904 // We don't need really a new paragraph, but
905 // we must make sure that the next item gets a \begin_layout.
906 parent_context.new_paragraph(os);
907 // Set the font size to the original value. No need to output it here
908 // (Context::begin_layout() will do that if needed)
909 parent_context.font.size = size;
914 * Output a space if necessary.
915 * This function gets called for every whitespace token.
917 * We have three cases here:
918 * 1. A space must be suppressed. Example: The lyxcode case below
919 * 2. A space may be suppressed. Example: Spaces before "\par"
920 * 3. A space must not be suppressed. Example: A space between two words
922 * We currently handle only 1. and 3 and from 2. only the case of
923 * spaces before newlines as a side effect.
925 * 2. could be used to suppress as many spaces as possible. This has two effects:
926 * - Reimporting LyX generated LaTeX files changes almost no whitespace
927 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
928 * The drawback is that the logic inside the function becomes
929 * complicated, and that is the reason why it is not implemented.
931 void check_space(Parser & p, ostream & os, Context & context)
933 Token const next = p.next_token();
934 Token const curr = p.curr_token();
935 // A space before a single newline and vice versa must be ignored
936 // LyX emits a newline before \end{lyxcode}.
937 // This newline must be ignored,
938 // otherwise LyX will add an additional protected space.
939 if (next.cat() == catSpace ||
940 next.cat() == catNewline ||
941 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
944 context.check_layout(os);
950 * Parse all arguments of \p command
952 void parse_arguments(string const & command,
953 vector<ArgumentType> const & template_arguments,
954 Parser & p, ostream & os, bool outer, Context & context)
956 string ert = command;
957 size_t no_arguments = template_arguments.size();
958 for (size_t i = 0; i < no_arguments; ++i) {
959 switch (template_arguments[i]) {
962 // This argument contains regular LaTeX
963 output_ert_inset(os, ert + '{', context);
964 eat_whitespace(p, os, context, false);
965 if (template_arguments[i] == required)
966 parse_text(p, os, FLAG_ITEM, outer, context);
968 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
972 // This argument consists only of a single item.
973 // The presence of '{' or not must be preserved.
975 if (p.next_token().cat() == catBegin)
976 ert += '{' + p.verbatim_item() + '}';
978 ert += p.verbatim_item();
982 // This argument may contain special characters
983 ert += '{' + p.verbatim_item() + '}';
987 // true because we must not eat whitespace
988 // if an optional arg follows we must not strip the
989 // brackets from this one
990 if (i < no_arguments - 1 &&
991 template_arguments[i+1] == optional)
992 ert += p.getFullOpt(true);
994 ert += p.getOpt(true);
998 output_ert_inset(os, ert, context);
1003 * Check whether \p command is a known command. If yes,
1004 * handle the command with all arguments.
1005 * \return true if the command was parsed, false otherwise.
1007 bool parse_command(string const & command, Parser & p, ostream & os,
1008 bool outer, Context & context)
1010 if (known_commands.find(command) != known_commands.end()) {
1011 parse_arguments(command, known_commands[command], p, os,
1019 /// Parses a minipage or parbox
1020 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1021 unsigned inner_flags, bool outer, Context & parent_context,
1022 string const & outer_type, string const & special,
1023 string inner_type, string const & frame_color,
1024 string const & background_color)
1028 string hor_pos = "l";
1029 // We need to set the height to the LaTeX default of 1\\totalheight
1030 // for the case when no height argument is given
1031 string height_value = "1";
1032 string height_unit = "in";
1033 string height_special = "totalheight";
1034 string latex_height;
1038 string width_special = "none";
1039 string thickness = "0.4pt";
1040 if (!fboxrule.empty())
1041 thickness = fboxrule;
1043 thickness = "0.4pt";
1045 if (!fboxsep.empty())
1046 separation = fboxsep;
1050 if (!shadow_size.empty())
1051 shadowsize = shadow_size;
1054 string framecolor = "black";
1055 string backgroundcolor = "none";
1056 if (!frame_color.empty())
1057 framecolor = frame_color;
1058 if (!background_color.empty())
1059 backgroundcolor = background_color;
1060 // if there is a color box around the \begin statements have not yet been parsed
1062 if (!frame_color.empty() || !background_color.empty()) {
1063 eat_whitespace(p, os, parent_context, false);
1064 p.get_token().asInput(); // the '{'
1066 if (p.next_token().asInput() == "\\begin") {
1067 p.get_token().asInput();
1069 inner_type = "minipage";
1070 inner_flags = FLAG_END;
1071 active_environments.push_back("minipage");
1074 else if (p.next_token().asInput() == "\\parbox") {
1075 p.get_token().asInput();
1076 inner_type = "parbox";
1077 inner_flags = FLAG_ITEM;
1080 else if (p.next_token().asInput() == "\\makebox") {
1081 p.get_token().asInput();
1082 inner_type = "makebox";
1083 inner_flags = FLAG_ITEM;
1085 // in case there is just \colorbox{color}{text}
1088 inner_type = "makebox";
1089 inner_flags = FLAG_BRACE_LAST;
1094 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1096 if (!inner_type.empty() && p.hasOpt()) {
1097 if (inner_type != "makebox")
1098 position = p.getArg('[', ']');
1100 latex_width = p.getArg('[', ']');
1101 translate_box_len(latex_width, width_value, width_unit, width_special);
1104 if (position != "t" && position != "c" && position != "b") {
1105 cerr << "invalid position " << position << " for "
1106 << inner_type << endl;
1110 if (inner_type != "makebox") {
1111 latex_height = p.getArg('[', ']');
1112 translate_box_len(latex_height, height_value, height_unit, height_special);
1114 string const opt = p.getArg('[', ']');
1117 if (hor_pos != "l" && hor_pos != "c" &&
1118 hor_pos != "r" && hor_pos != "s") {
1119 cerr << "invalid hor_pos " << hor_pos
1120 << " for " << inner_type << endl;
1127 inner_pos = p.getArg('[', ']');
1128 if (inner_pos != "c" && inner_pos != "t" &&
1129 inner_pos != "b" && inner_pos != "s") {
1130 cerr << "invalid inner_pos "
1131 << inner_pos << " for "
1132 << inner_type << endl;
1133 inner_pos = position;
1137 if (inner_type == "makebox")
1141 if (inner_type.empty()) {
1142 if (special.empty() && outer_type != "framebox")
1143 latex_width = "1\\columnwidth";
1146 latex_width = p2.getArg('[', ']');
1147 string const opt = p2.getArg('[', ']');
1150 if (hor_pos != "l" && hor_pos != "c" &&
1151 hor_pos != "r" && hor_pos != "s") {
1152 cerr << "invalid hor_pos " << hor_pos
1153 << " for " << outer_type << endl;
1157 if (outer_type == "framebox")
1161 } else if (inner_type != "makebox")
1162 latex_width = p.verbatim_item();
1163 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1164 // as this is LyX's standard for such cases (except for makebox)
1165 // \framebox is more special and handled below
1166 if (latex_width.empty() && inner_type != "makebox"
1167 && outer_type != "framebox")
1168 latex_width = "1\\columnwidth";
1170 translate_len(latex_width, width_value, width_unit);
1172 bool shadedparbox = false;
1173 if (inner_type == "shaded") {
1174 eat_whitespace(p, os, parent_context, false);
1175 if (outer_type == "parbox") {
1177 if (p.next_token().cat() == catBegin)
1179 eat_whitespace(p, os, parent_context, false);
1180 shadedparbox = true;
1185 // If we already read the inner box we have to push the inner env
1186 if (!outer_type.empty() && !inner_type.empty() &&
1187 (inner_flags & FLAG_END))
1188 active_environments.push_back(inner_type);
1189 bool use_ert = false;
1190 if (!outer_type.empty() && !inner_type.empty()) {
1191 // Look whether there is some content after the end of the
1192 // inner box, but before the end of the outer box.
1193 // If yes, we need to output ERT.
1195 if (inner_flags & FLAG_END)
1196 p.ertEnvironment(inner_type);
1199 p.skip_spaces(true);
1200 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1201 if ((outer_env && p.next_token().asInput() != "\\end") ||
1202 (!outer_env && p.next_token().cat() != catEnd)) {
1203 // something is between the end of the inner box and
1204 // the end of the outer box, so we need to use ERT.
1212 if (!outer_type.empty()) {
1213 if (outer_flags & FLAG_END)
1214 ss << "\\begin{" << outer_type << '}';
1216 ss << '\\' << outer_type << '{';
1217 if (!special.empty())
1221 if (!inner_type.empty()) {
1222 if (inner_type != "shaded") {
1223 if (inner_flags & FLAG_END)
1224 ss << "\\begin{" << inner_type << '}';
1226 ss << '\\' << inner_type;
1228 if (!position.empty())
1229 ss << '[' << position << ']';
1230 if (!latex_height.empty())
1231 ss << '[' << latex_height << ']';
1232 if (!inner_pos.empty())
1233 ss << '[' << inner_pos << ']';
1234 ss << '{' << latex_width << '}';
1235 if (!(inner_flags & FLAG_END))
1238 if (inner_type == "shaded")
1239 ss << "\\begin{shaded}";
1240 output_ert_inset(os, ss.str(), parent_context);
1241 if (!inner_type.empty()) {
1242 parse_text(p, os, inner_flags, outer, parent_context);
1243 if (inner_flags & FLAG_END)
1244 output_ert_inset(os, "\\end{" + inner_type + '}',
1247 output_ert_inset(os, "}", parent_context);
1249 if (!outer_type.empty()) {
1250 // If we already read the inner box we have to pop
1252 if (!inner_type.empty() && (inner_flags & FLAG_END))
1253 active_environments.pop_back();
1255 // Ensure that the end of the outer box is parsed correctly:
1256 // The opening brace has been eaten by parse_outer_box()
1257 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1258 outer_flags &= ~FLAG_ITEM;
1259 outer_flags |= FLAG_BRACE_LAST;
1261 parse_text(p, os, outer_flags, outer, parent_context);
1262 if (outer_flags & FLAG_END)
1263 output_ert_inset(os, "\\end{" + outer_type + '}',
1266 output_ert_inset(os, "}", parent_context);
1269 // LyX does not like empty positions, so we have
1270 // to set them to the LaTeX default values here.
1271 if (position.empty())
1273 if (inner_pos.empty())
1274 inner_pos = position;
1275 parent_context.check_layout(os);
1276 begin_inset(os, "Box ");
1277 if (outer_type == "framed")
1279 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1281 else if (outer_type == "shadowbox")
1282 os << "Shadowbox\n";
1283 else if ((outer_type == "shaded" && inner_type.empty()) ||
1284 (outer_type == "minipage" && inner_type == "shaded") ||
1285 (outer_type == "parbox" && inner_type == "shaded")) {
1287 preamble.registerAutomaticallyLoadedPackage("color");
1288 } else if (outer_type == "doublebox")
1289 os << "Doublebox\n";
1290 else if (outer_type.empty() || outer_type == "mbox")
1291 os << "Frameless\n";
1293 os << outer_type << '\n';
1294 os << "position \"" << position << "\"\n";
1295 os << "hor_pos \"" << hor_pos << "\"\n";
1296 if (outer_type == "mbox")
1297 os << "has_inner_box 1\n";
1298 else if (!frame_color.empty() && inner_type == "makebox")
1299 os << "has_inner_box 0\n";
1301 os << "has_inner_box " << !inner_type.empty() << "\n";
1302 os << "inner_pos \"" << inner_pos << "\"\n";
1303 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1305 if (outer_type == "mbox")
1306 os << "use_makebox 1\n";
1307 else if (!frame_color.empty())
1308 os << "use_makebox 0\n";
1310 os << "use_makebox " << (inner_type == "makebox") << '\n';
1311 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1312 os << "width \"\"\n";
1313 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1314 else if (contains(width_unit, '\\'))
1315 os << "width \"" << width_value << "in" << "\"\n";
1317 os << "width \"" << width_value << width_unit << "\"\n";
1318 if (contains(width_unit, '\\')) {
1319 width_unit.erase (0,1); // remove the leading '\'
1320 os << "special \"" << width_unit << "\"\n";
1322 os << "special \"" << width_special << "\"\n";
1323 if (contains(height_unit, '\\'))
1324 os << "height \"" << height_value << "in" << "\"\n";
1326 os << "height \"" << height_value << height_unit << "\"\n";
1327 os << "height_special \"" << height_special << "\"\n";
1328 os << "thickness \"" << thickness << "\"\n";
1329 os << "separation \"" << separation << "\"\n";
1330 os << "shadowsize \"" << shadowsize << "\"\n";
1331 os << "framecolor \"" << framecolor << "\"\n";
1332 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1333 os << "status open\n\n";
1335 // Unfortunately we can't use parse_text_in_inset:
1336 // InsetBox::forcePlainLayout() is hard coded and does not
1337 // use the inset layout. Apart from that do we call parse_text
1338 // up to two times, but need only one check_end_layout.
1339 bool const forcePlainLayout =
1340 (!inner_type.empty() || inner_type == "makebox") &&
1341 outer_type != "shaded" && outer_type != "framed";
1342 Context context(true, parent_context.textclass);
1343 if (forcePlainLayout)
1344 context.layout = &context.textclass.plainLayout();
1346 context.font = parent_context.font;
1348 // If we have no inner box the contents will be read with the outer box
1349 if (!inner_type.empty())
1350 parse_text(p, os, inner_flags, outer, context);
1352 // Ensure that the end of the outer box is parsed correctly:
1353 // The opening brace has been eaten by parse_outer_box()
1354 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1355 outer_flags &= ~FLAG_ITEM;
1356 outer_flags |= FLAG_BRACE_LAST;
1359 // Find end of outer box, output contents if inner_type is
1360 // empty and output possible comments
1361 if (!outer_type.empty()) {
1362 // If we already read the inner box we have to pop
1364 if (!inner_type.empty() && (inner_flags & FLAG_END))
1365 active_environments.pop_back();
1366 // This does not output anything but comments if
1367 // inner_type is not empty (see use_ert)
1368 parse_text(p, os, outer_flags, outer, context);
1371 context.check_end_layout(os);
1373 #ifdef PRESERVE_LAYOUT
1374 // LyX puts a % after the end of the minipage
1375 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1377 //output_comment(p, os, "dummy", parent_context);
1380 parent_context.new_paragraph(os);
1382 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1383 //output_comment(p, os, "dummy", parent_context);
1386 // We add a protected space if something real follows
1387 if (p.good() && p.next_token().cat() != catComment) {
1388 begin_inset(os, "space ~\n");
1394 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1395 active_environments.pop_back();
1396 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1397 // in this case we have to eat the the closing brace of the color box
1398 p.get_token().asInput(); // the '}'
1400 if (p.next_token().asInput() == "}") {
1401 // in this case we assume that the closing brace is from the box settings
1402 // therefore reset these values for the next box
1408 // all boxes except of Frameless and Shaded require calc
1409 if (!(outer_type.empty() || outer_type == "mbox") &&
1410 !((outer_type == "shaded" && inner_type.empty()) ||
1411 (outer_type == "minipage" && inner_type == "shaded") ||
1412 (outer_type == "parbox" && inner_type == "shaded")))
1413 preamble.registerAutomaticallyLoadedPackage("calc");
1417 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1418 Context & parent_context, string const & outer_type,
1419 string const & special)
1421 eat_whitespace(p, os, parent_context, false);
1422 if (flags & FLAG_ITEM) {
1424 if (p.next_token().cat() == catBegin)
1427 cerr << "Warning: Ignoring missing '{' after \\"
1428 << outer_type << '.' << endl;
1429 eat_whitespace(p, os, parent_context, false);
1432 unsigned int inner_flags = 0;
1434 if (outer_type == "minipage" || outer_type == "parbox") {
1435 p.skip_spaces(true);
1436 while (p.hasOpt()) {
1438 p.skip_spaces(true);
1441 p.skip_spaces(true);
1442 if (outer_type == "parbox") {
1444 if (p.next_token().cat() == catBegin)
1446 p.skip_spaces(true);
1449 if (outer_type == "shaded" || outer_type == "mbox") {
1450 // These boxes never have an inner box
1452 } else if (p.next_token().asInput() == "\\parbox") {
1453 inner = p.get_token().cs();
1454 inner_flags = FLAG_ITEM;
1455 } else if (p.next_token().asInput() == "\\begin") {
1456 // Is this a minipage or shaded box?
1459 inner = p.getArg('{', '}');
1461 if (inner == "minipage" || inner == "shaded")
1462 inner_flags = FLAG_END;
1467 if (inner_flags == FLAG_END) {
1468 if (inner != "shaded")
1472 eat_whitespace(p, os, parent_context, false);
1474 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1475 outer_type, special, inner, "", "");
1477 if (inner_flags == FLAG_ITEM) {
1479 eat_whitespace(p, os, parent_context, false);
1481 parse_box(p, os, flags, inner_flags, outer, parent_context,
1482 outer_type, special, inner, "", "");
1487 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1488 bool in_line, bool use_minted)
1490 parent_context.check_layout(os);
1491 begin_inset(os, "listings\n");
1492 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1494 while ((i = arg.find(", ")) != string::npos
1495 || (i = arg.find(",\t")) != string::npos)
1496 arg.erase(i + 1, 1);
1499 string const language = p.getArg('{', '}');
1500 p.skip_spaces(true);
1501 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1502 if (!minted_float.empty()) {
1503 arg += string(arg.empty() ? "" : ",") + minted_float;
1504 minted_nonfloat_caption.clear();
1508 os << "lstparams " << '"' << arg << '"' << '\n';
1509 if (arg.find("\\color") != string::npos)
1510 preamble.registerAutomaticallyLoadedPackage("color");
1513 os << "inline true\n";
1515 os << "inline false\n";
1516 os << "status open\n";
1517 Context context(true, parent_context.textclass);
1518 context.layout = &parent_context.textclass.plainLayout();
1519 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1520 minted_nonfloat_caption.erase(0,3);
1521 os << "\n\\begin_layout Plain Layout\n";
1522 begin_inset(os, "Caption Standard\n");
1523 Context newcontext(true, context.textclass,
1524 context.layout, 0, context.font);
1525 newcontext.check_layout(os);
1526 os << minted_nonfloat_caption << "\n";
1527 newcontext.check_end_layout(os);
1529 os << "\n\\end_layout\n";
1530 minted_nonfloat_caption.clear();
1534 // set catcodes to verbatim early, just in case.
1535 p.setCatcodes(VERBATIM_CATCODES);
1536 string delim = p.get_token().asInput();
1537 //FIXME: handler error condition
1538 s = p.verbatimStuff(delim).second;
1539 // context.new_paragraph(os);
1540 } else if (use_minted) {
1541 s = p.verbatimEnvironment("minted");
1543 s = p.verbatimEnvironment("lstlisting");
1545 output_ert(os, s, context);
1546 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1547 minted_nonfloat_caption.erase(0,3);
1548 os << "\n\\begin_layout Plain Layout\n";
1549 begin_inset(os, "Caption Standard\n");
1550 Context newcontext(true, context.textclass,
1551 context.layout, 0, context.font);
1552 newcontext.check_layout(os);
1553 os << minted_nonfloat_caption << "\n";
1554 newcontext.check_end_layout(os);
1556 os << "\n\\end_layout\n";
1557 minted_nonfloat_caption.clear();
1559 // Don't close the inset here for floating minted listings.
1560 // It will be closed at the end of the listing environment.
1561 if (!use_minted || minted_float.empty())
1564 eat_whitespace(p, os, parent_context, true);
1565 Token t = p.get_token();
1566 if (t.asInput() != "\\end") {
1567 // If anything follows, collect it into a caption.
1568 minted_float_has_caption = true;
1569 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1570 begin_inset(os, "Caption Standard\n");
1571 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1578 /// parse an unknown environment
1579 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1580 unsigned flags, bool outer,
1581 Context & parent_context)
1583 if (name == "tabbing")
1584 // We need to remember that we have to handle '\=' specially
1585 flags |= FLAG_TABBING;
1587 // We need to translate font changes and paragraphs inside the
1588 // environment to ERT if we have a non standard font.
1589 // Otherwise things like
1590 // \large\begin{foo}\huge bar\end{foo}
1592 bool const specialfont =
1593 (parent_context.font != parent_context.normalfont);
1594 bool const new_layout_allowed = parent_context.new_layout_allowed;
1596 parent_context.new_layout_allowed = false;
1597 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1598 // Try to handle options: Look if we have optional arguments,
1599 // and if so, put the brackets in ERT.
1600 while (p.hasOpt()) {
1601 p.get_token(); // eat '['
1602 output_ert_inset(os, "[", parent_context);
1603 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1604 output_ert_inset(os, "]", parent_context);
1606 parse_text_snippet(p, os, flags, outer, parent_context);
1607 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1609 parent_context.new_layout_allowed = new_layout_allowed;
1613 void parse_environment(Parser & p, ostream & os, bool outer,
1614 string & last_env, Context & parent_context)
1616 Layout const * newlayout;
1617 InsetLayout const * newinsetlayout = 0;
1618 string const name = p.getArg('{', '}');
1619 const bool is_starred = suffixIs(name, '*');
1620 string const unstarred_name = rtrim(name, "*");
1621 active_environments.push_back(name);
1623 // We use this loop and break out after a condition is met
1624 // rather than a huge else-if-chain.
1626 if (is_math_env(name)) {
1627 parent_context.check_layout(os);
1628 begin_inset(os, "Formula ");
1629 os << "\\begin{" << name << "}";
1630 parse_math(p, os, FLAG_END, MATH_MODE);
1631 os << "\\end{" << name << "}";
1633 if (is_display_math_env(name)) {
1634 // Prevent the conversion of a line break to a space
1635 // (bug 7668). This does not change the output, but
1636 // looks ugly in LyX.
1637 eat_whitespace(p, os, parent_context, false);
1642 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1643 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1644 // We must begin a new paragraph if not already done
1645 if (!parent_context.atParagraphStart()) {
1646 parent_context.check_end_layout(os);
1647 parent_context.new_paragraph(os);
1649 // store previous language because we must reset it at the end
1650 string const lang_old = parent_context.font.language;
1651 // save new language in context so that it is
1652 // handled by parse_text
1653 parent_context.font.language =
1654 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1655 parse_text(p, os, FLAG_END, outer, parent_context);
1656 // reset previous language
1657 parent_context.font.language = lang_old;
1658 // Just in case the environment is empty
1659 parent_context.extra_stuff.erase();
1660 // We must begin a new paragraph to reset the language
1661 parent_context.new_paragraph(os);
1666 if (unstarred_name == "tabular" || name == "longtable"
1667 || name == "tabularx" || name == "xltabular") {
1668 eat_whitespace(p, os, parent_context, false);
1669 string width = "0pt";
1671 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1672 string const opt = p.getArg('[', ']');
1675 else if (opt == "l")
1677 else if (opt == "r")
1680 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1681 width = lyx::translate_len(p.getArg('{', '}'));
1682 eat_whitespace(p, os, parent_context, false);
1684 parent_context.check_layout(os);
1685 begin_inset(os, "Tabular ");
1686 handle_tabular(p, os, name, width, halign, parent_context);
1692 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1693 eat_whitespace(p, os, parent_context, false);
1694 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1695 eat_whitespace(p, os, parent_context, false);
1696 parent_context.check_layout(os);
1697 begin_inset(os, "Float " + unstarred_name + "\n");
1698 // store the float type for subfloats
1699 // subfloats only work with figures and tables
1700 if (unstarred_name == "figure")
1701 float_type = unstarred_name;
1702 else if (unstarred_name == "table")
1703 float_type = unstarred_name;
1707 os << "placement " << opt << '\n';
1708 if (contains(opt, "H"))
1709 preamble.registerAutomaticallyLoadedPackage("float");
1711 Floating const & fl = parent_context.textclass.floats()
1712 .getType(unstarred_name);
1713 if (!fl.floattype().empty() && fl.usesFloatPkg())
1714 preamble.registerAutomaticallyLoadedPackage("float");
1717 os << "wide " << convert<string>(is_starred)
1718 << "\nsideways false"
1719 << "\nstatus open\n\n";
1720 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1722 // We don't need really a new paragraph, but
1723 // we must make sure that the next item gets a \begin_layout.
1724 parent_context.new_paragraph(os);
1726 // the float is parsed thus delete the type
1731 if (unstarred_name == "sidewaysfigure"
1732 || unstarred_name == "sidewaystable"
1733 || unstarred_name == "sidewaysalgorithm") {
1734 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1735 eat_whitespace(p, os, parent_context, false);
1736 parent_context.check_layout(os);
1737 if (unstarred_name == "sidewaysfigure")
1738 begin_inset(os, "Float figure\n");
1739 else if (unstarred_name == "sidewaystable")
1740 begin_inset(os, "Float table\n");
1741 else if (unstarred_name == "sidewaysalgorithm")
1742 begin_inset(os, "Float algorithm\n");
1744 os << "placement " << opt << '\n';
1745 if (contains(opt, "H"))
1746 preamble.registerAutomaticallyLoadedPackage("float");
1747 os << "wide " << convert<string>(is_starred)
1748 << "\nsideways true"
1749 << "\nstatus open\n\n";
1750 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1752 // We don't need really a new paragraph, but
1753 // we must make sure that the next item gets a \begin_layout.
1754 parent_context.new_paragraph(os);
1756 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1760 if (name == "wrapfigure" || name == "wraptable") {
1761 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1762 eat_whitespace(p, os, parent_context, false);
1763 parent_context.check_layout(os);
1766 string overhang = "0col%";
1769 lines = p.getArg('[', ']');
1770 string const placement = p.getArg('{', '}');
1772 overhang = p.getArg('[', ']');
1773 string const width = p.getArg('{', '}');
1775 if (name == "wrapfigure")
1776 begin_inset(os, "Wrap figure\n");
1778 begin_inset(os, "Wrap table\n");
1779 os << "lines " << lines
1780 << "\nplacement " << placement
1781 << "\noverhang " << lyx::translate_len(overhang)
1782 << "\nwidth " << lyx::translate_len(width)
1783 << "\nstatus open\n\n";
1784 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1786 // We don't need really a new paragraph, but
1787 // we must make sure that the next item gets a \begin_layout.
1788 parent_context.new_paragraph(os);
1790 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1794 if (name == "minipage") {
1795 eat_whitespace(p, os, parent_context, false);
1796 // Test whether this is an outer box of a shaded box
1798 // swallow arguments
1799 while (p.hasOpt()) {
1801 p.skip_spaces(true);
1804 p.skip_spaces(true);
1805 Token t = p.get_token();
1806 bool shaded = false;
1807 if (t.asInput() == "\\begin") {
1808 p.skip_spaces(true);
1809 if (p.getArg('{', '}') == "shaded")
1814 parse_outer_box(p, os, FLAG_END, outer,
1815 parent_context, name, "shaded");
1817 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1818 "", "", name, "", "");
1823 if (name == "comment") {
1824 eat_whitespace(p, os, parent_context, false);
1825 parent_context.check_layout(os);
1826 begin_inset(os, "Note Comment\n");
1827 os << "status open\n";
1828 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1831 skip_braces(p); // eat {} that might by set by LyX behind comments
1832 preamble.registerAutomaticallyLoadedPackage("verbatim");
1836 if (unstarred_name == "verbatim") {
1837 // FIXME: this should go in the generic code that
1838 // handles environments defined in layout file that
1839 // have "PassThru 1". However, the code over there is
1840 // already too complicated for my taste.
1841 string const ascii_name =
1842 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1843 parent_context.new_paragraph(os);
1844 Context context(true, parent_context.textclass,
1845 &parent_context.textclass[from_ascii(ascii_name)]);
1846 string s = p.verbatimEnvironment(name);
1847 output_ert(os, s, context);
1852 if (name == "IPA") {
1853 eat_whitespace(p, os, parent_context, false);
1854 parent_context.check_layout(os);
1855 begin_inset(os, "IPA\n");
1856 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1859 preamble.registerAutomaticallyLoadedPackage("tipa");
1860 preamble.registerAutomaticallyLoadedPackage("tipx");
1864 if (name == parent_context.textclass.titlename()
1865 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1866 parse_text(p, os, FLAG_END, outer, parent_context);
1867 // Just in case the environment is empty
1868 parent_context.extra_stuff.erase();
1869 // We must begin a new paragraph
1870 parent_context.new_paragraph(os);
1875 if (name == "CJK") {
1876 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1877 // It is impossible to decide if a CJK environment was in its own paragraph or within
1878 // a line. We therefore always assume a paragraph since the latter is a rare case.
1879 eat_whitespace(p, os, parent_context, false);
1880 parent_context.check_end_layout(os);
1881 // store the encoding to be able to reset it
1882 string const encoding_old = p.getEncoding();
1883 string const encoding = p.getArg('{', '}');
1884 // FIXME: For some reason JIS does not work. Although the text
1885 // in tests/CJK.tex is identical with the SJIS version if you
1886 // convert both snippets using the recode command line utility,
1887 // the resulting .lyx file contains some extra characters if
1888 // you set buggy_encoding to false for JIS.
1889 bool const buggy_encoding = encoding == "JIS";
1890 if (!buggy_encoding)
1891 p.setEncoding(encoding, Encoding::CJK);
1893 // FIXME: This will read garbage, since the data is not encoded in utf8.
1894 p.setEncoding("UTF-8");
1896 // LyX only supports the same mapping for all CJK
1897 // environments, so we might need to output everything as ERT
1898 string const mapping = trim(p.getArg('{', '}'));
1899 char const * const * const where =
1900 is_known(encoding, supported_CJK_encodings);
1901 if (!buggy_encoding && !preamble.fontCJKSet())
1902 preamble.fontCJK(mapping);
1903 bool knownMapping = mapping == preamble.fontCJK();
1904 if (buggy_encoding || !knownMapping || !where) {
1905 parent_context.check_layout(os);
1906 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1908 // we must parse the content as verbatim because e.g. JIS can contain
1909 // normally invalid characters
1910 // FIXME: This works only for the most simple cases.
1911 // Since TeX control characters are not parsed,
1912 // things like comments are completely wrong.
1913 string const s = p.plainEnvironment("CJK");
1914 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1917 if (snip == "\\" || is_known(snip, known_escaped_chars))
1918 output_ert_inset(os, snip, parent_context);
1919 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1924 output_ert_inset(os, "\\end{" + name + "}",
1928 supported_CJK_languages[where - supported_CJK_encodings];
1929 // store the language because we must reset it at the end
1930 string const lang_old = parent_context.font.language;
1931 parent_context.font.language = lang;
1932 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1933 parent_context.font.language = lang_old;
1934 parent_context.new_paragraph(os);
1936 p.setEncoding(encoding_old);
1941 if (name == "lyxgreyedout") {
1942 eat_whitespace(p, os, parent_context, false);
1943 parent_context.check_layout(os);
1944 begin_inset(os, "Note Greyedout\n");
1945 os << "status open\n";
1946 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1949 if (!preamble.notefontcolor().empty())
1950 preamble.registerAutomaticallyLoadedPackage("color");
1954 if (name == "btSect") {
1955 eat_whitespace(p, os, parent_context, false);
1956 parent_context.check_layout(os);
1957 begin_command_inset(os, "bibtex", "bibtex");
1958 string bibstyle = "plain";
1960 bibstyle = p.getArg('[', ']');
1961 p.skip_spaces(true);
1963 string const bibfile = p.getArg('{', '}');
1964 eat_whitespace(p, os, parent_context, false);
1965 Token t = p.get_token();
1966 if (t.asInput() == "\\btPrintCited") {
1967 p.skip_spaces(true);
1968 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1970 if (t.asInput() == "\\btPrintNotCited") {
1971 p.skip_spaces(true);
1972 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1974 if (t.asInput() == "\\btPrintAll") {
1975 p.skip_spaces(true);
1976 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1978 os << "bibfiles " << '"' << bibfile << "\"\n"
1979 << "options " << '"' << bibstyle << "\"\n";
1980 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1986 if (name == "btUnit") {
1987 string const nt = p.next_next_token().cs();
1988 // Do not attempt to overwrite a former diverging multibib.
1989 // Those are output as ERT instead.
1990 if ((nt == "part" || nt == "chapter"
1991 || nt == "section" || nt == "subsection")
1992 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1993 parse_text(p, os, FLAG_END, outer, parent_context);
1994 preamble.multibib(nt);
1996 parse_unknown_environment(p, name, os, FLAG_END, outer,
2001 // This is only attempted at turn environments that consist only
2002 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2003 // Thus we will fall through in other cases.
2004 if (name == "turn") {
2005 // We check if the next thing is a tabular[*|x]
2007 p.getArg('{', '}');// eat turn argument
2008 bool found_end = false;
2009 bool only_table = false;
2010 bool end_table = false;
2013 string envname = p.getArg('{', '}');
2014 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2015 // Now we check if the table is the only content
2016 // of the turn environment
2017 string const tenv = envname;
2018 while (!found_end && !end_table && p.good()) {
2019 envname = p.next_token().cat() == catBegin
2020 ? p.getArg('{', '}') : string();
2021 Token const & t = p.get_token();
2023 end_table = t.asInput() != "\\end"
2025 found_end = t.asInput() == "\\end"
2026 && envname == "turn";
2030 envname = p.getArg('{', '}');
2031 only_table = p.next_next_token().asInput() == "\\end"
2032 && envname == "turn";
2036 string const angle = p.getArg('{', '}');
2038 int const save_tablerotation = parent_context.tablerotation;
2039 parent_context.tablerotation = convert<int>(angle);
2040 parse_text(p, os, FLAG_END, outer, parent_context);
2041 parent_context.tablerotation = save_tablerotation;
2051 // This is only attempted at landscape environments that consist only
2052 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2053 // Other landscape environment is handled via the landscape module, thus
2054 // we will fall through in that case.
2055 if (name == "landscape") {
2056 // We check if the next thing is a longtable
2058 bool found_end = false;
2059 bool only_longtable = false;
2060 bool end_longtable = false;
2063 string envname = p.getArg('{', '}');
2064 if (envname == "longtable" || envname == "xltabular") {
2065 // Now we check if the longtable is the only content
2066 // of the landscape environment
2067 string const ltenv = envname;
2068 while (!found_end && !end_longtable && p.good()) {
2069 envname = p.next_token().cat() == catBegin
2070 ? p.getArg('{', '}') : string();
2071 Token const & t = p.get_token();
2073 end_longtable = t.asInput() != "\\end"
2074 && envname == ltenv;
2075 found_end = t.asInput() == "\\end"
2076 && envname == "landscape";
2078 if (end_longtable) {
2080 envname = p.getArg('{', '}');
2081 only_longtable = p.next_next_token().asInput() == "\\end"
2082 && envname == "landscape";
2084 if (only_longtable) {
2087 int const save_tablerotation = parent_context.tablerotation;
2088 parent_context.tablerotation = 90;
2089 parse_text(p, os, FLAG_END, outer, parent_context);
2090 parent_context.tablerotation = save_tablerotation;
2100 if (name == "framed" || name == "shaded") {
2101 eat_whitespace(p, os, parent_context, false);
2102 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2104 preamble.registerAutomaticallyLoadedPackage("framed");
2108 if (name == "listing") {
2109 minted_float = "float";
2110 eat_whitespace(p, os, parent_context, false);
2111 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2113 minted_float += "=" + opt;
2114 // If something precedes \begin{minted}, we output it at the end
2115 // as a caption, in order to keep it inside the listings inset.
2116 eat_whitespace(p, os, parent_context, true);
2118 Token const & t = p.get_token();
2119 p.skip_spaces(true);
2120 string const envname = p.next_token().cat() == catBegin
2121 ? p.getArg('{', '}') : string();
2122 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2124 minted_float_has_caption = false;
2125 string content = parse_text_snippet(p, FLAG_END, outer,
2127 size_t i = content.find("\\begin_inset listings");
2128 bool minted_env = i != string::npos;
2131 caption = content.substr(0, i);
2132 content.erase(0, i);
2134 parent_context.check_layout(os);
2135 if (minted_env && minted_float_has_caption) {
2136 eat_whitespace(p, os, parent_context, true);
2137 os << content << "\n";
2138 if (!caption.empty())
2139 os << caption << "\n";
2140 os << "\n\\end_layout\n"; // close inner layout
2141 end_inset(os); // close caption inset
2142 os << "\n\\end_layout\n"; // close outer layout
2143 } else if (!caption.empty()) {
2145 begin_inset(os, "listings\n");
2146 os << "lstparams " << '"' << minted_float << '"' << '\n';
2147 os << "inline false\n";
2148 os << "status collapsed\n";
2150 os << "\n\\begin_layout Plain Layout\n";
2151 begin_inset(os, "Caption Standard\n");
2152 Context newcontext(true, parent_context.textclass,
2153 0, 0, parent_context.font);
2154 newcontext.check_layout(os);
2155 os << caption << "\n";
2156 newcontext.check_end_layout(os);
2158 os << "\n\\end_layout\n";
2159 } else if (content.empty()) {
2160 begin_inset(os, "listings\n");
2161 os << "lstparams " << '"' << minted_float << '"' << '\n';
2162 os << "inline false\n";
2163 os << "status collapsed\n";
2165 os << content << "\n";
2167 end_inset(os); // close listings inset
2168 parent_context.check_end_layout(os);
2169 parent_context.new_paragraph(os);
2171 minted_float.clear();
2172 minted_float_has_caption = false;
2176 if (name == "lstlisting" || name == "minted") {
2177 bool use_minted = name == "minted";
2178 // with listings, we do not eat newlines here since
2179 // \begin{lstlistings}
2182 // // \begin{lstlistings}%
2185 // reads [foo] as content, whereas
2186 // // \begin{lstlistings}%
2189 // \begin{lstlistings}[foo,
2191 // reads [foo...] as argument.
2192 eat_whitespace(p, os, parent_context, false, use_minted);
2193 if (use_minted && minted_float.empty()) {
2194 // look ahead for a bottom caption
2196 bool found_end_minted = false;
2197 while (!found_end_minted && p.good()) {
2198 Token const & t = p.get_token();
2200 string const envname =
2201 p.next_token().cat() == catBegin
2202 ? p.getArg('{', '}') : string();
2203 found_end_minted = t.asInput() == "\\end"
2204 && envname == "minted";
2206 eat_whitespace(p, os, parent_context, true);
2207 Token const & t = p.get_token();
2208 p.skip_spaces(true);
2209 if (t.asInput() == "\\lyxmintcaption") {
2210 string const pos = p.getArg('[', ']');
2212 string const caption =
2213 parse_text_snippet(p, FLAG_ITEM,
2214 false, parent_context);
2215 minted_nonfloat_caption = "[b]" + caption;
2216 eat_whitespace(p, os, parent_context, true);
2221 parse_listings(p, os, parent_context, false, use_minted);
2226 if (!parent_context.new_layout_allowed) {
2227 parse_unknown_environment(p, name, os, FLAG_END, outer,
2232 // Alignment and spacing settings
2233 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2234 // therefore are totally broken!
2235 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2236 // they are commands not environments. They are furthermore switches that
2237 // can be ended by another switches, but also by commands like \footnote or
2238 // \parbox. So the only safe way is to leave them untouched.
2239 // However, we support the pseudo-environments
2240 // \begin{centering} ... \end{centering}
2241 // \begin{raggedright} ... \end{raggedright}
2242 // \begin{raggedleft} ... \end{raggedleft}
2243 // since they are used by LyX in floats (for spacing reasons)
2244 if (name == "center" || name == "centering"
2245 || name == "flushleft" || name == "raggedright"
2246 || name == "flushright" || name == "raggedleft"
2247 || name == "singlespace" || name == "onehalfspace"
2248 || name == "doublespace" || name == "spacing") {
2249 eat_whitespace(p, os, parent_context, false);
2250 // We must begin a new paragraph if not already done
2251 if (! parent_context.atParagraphStart()) {
2252 parent_context.check_end_layout(os);
2253 parent_context.new_paragraph(os);
2255 if (name == "flushleft" || name == "raggedright")
2256 parent_context.add_extra_stuff("\\align left\n");
2257 else if (name == "flushright" || name == "raggedleft")
2258 parent_context.add_extra_stuff("\\align right\n");
2259 else if (name == "center" || name == "centering")
2260 parent_context.add_extra_stuff("\\align center\n");
2261 else if (name == "singlespace")
2262 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2263 else if (name == "onehalfspace") {
2264 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2265 preamble.registerAutomaticallyLoadedPackage("setspace");
2266 } else if (name == "doublespace") {
2267 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2268 preamble.registerAutomaticallyLoadedPackage("setspace");
2269 } else if (name == "spacing") {
2270 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2271 preamble.registerAutomaticallyLoadedPackage("setspace");
2273 parse_text(p, os, FLAG_END, outer, parent_context);
2274 // Just in case the environment is empty
2275 parent_context.extra_stuff.erase();
2276 // We must begin a new paragraph to reset the alignment
2277 parent_context.new_paragraph(os);
2282 // The single '=' is meant here.
2283 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2284 eat_whitespace(p, os, parent_context, false);
2285 Context context(true, parent_context.textclass, newlayout,
2286 parent_context.layout, parent_context.font);
2287 if (parent_context.deeper_paragraph) {
2288 // We are beginning a nested environment after a
2289 // deeper paragraph inside the outer list environment.
2290 // Therefore we don't need to output a "begin deeper".
2291 context.need_end_deeper = true;
2293 parent_context.check_end_layout(os);
2294 if (last_env == name) {
2295 // we need to output a separator since LyX would export
2296 // the two environments as one otherwise (bug 5716)
2297 TeX2LyXDocClass const & textclass(parent_context.textclass);
2298 Context newcontext(true, textclass,
2299 &(textclass.defaultLayout()));
2300 newcontext.check_layout(os);
2301 begin_inset(os, "Separator plain\n");
2303 newcontext.check_end_layout(os);
2305 switch (context.layout->latextype) {
2306 case LATEX_LIST_ENVIRONMENT:
2307 context.in_list_preamble =
2308 !context.layout->listpreamble().empty()
2309 && p.hasListPreamble(context.layout->itemcommand());
2310 context.add_par_extra_stuff("\\labelwidthstring "
2311 + p.verbatim_item() + '\n');
2314 case LATEX_BIB_ENVIRONMENT:
2315 p.verbatim_item(); // swallow next arg
2321 context.check_deeper(os);
2322 if (newlayout->keepempty) {
2323 // We need to start a new paragraph
2324 // even if it is empty.
2325 context.new_paragraph(os);
2326 context.check_layout(os);
2328 // handle known optional and required arguments
2329 if (context.layout->latextype == LATEX_ENVIRONMENT)
2330 output_arguments(os, p, outer, false, string(), context,
2331 context.layout->latexargs());
2332 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2333 context.in_list_preamble =
2334 !context.layout->listpreamble().empty()
2335 && p.hasListPreamble(context.layout->itemcommand());
2337 output_arguments(oss, p, outer, false, string(), context,
2338 context.layout->latexargs());
2339 context.list_extra_stuff = oss.str();
2341 if (context.in_list_preamble) {
2342 // Collect the stuff between \begin and first \item
2343 context.list_preamble =
2344 parse_text_snippet(p, FLAG_END, outer, context);
2345 context.in_list_preamble = false;
2347 parse_text(p, os, FLAG_END, outer, context);
2348 if (context.layout->latextype == LATEX_ENVIRONMENT)
2349 output_arguments(os, p, outer, false, "post", context,
2350 context.layout->postcommandargs());
2351 context.check_end_layout(os);
2352 if (parent_context.deeper_paragraph) {
2353 // We must suppress the "end deeper" because we
2354 // suppressed the "begin deeper" above.
2355 context.need_end_deeper = false;
2357 context.check_end_deeper(os);
2358 parent_context.new_paragraph(os);
2360 if (!preamble.titleLayoutFound())
2361 preamble.titleLayoutFound(newlayout->intitle);
2362 set<string> const & req = newlayout->required();
2363 set<string>::const_iterator it = req.begin();
2364 set<string>::const_iterator en = req.end();
2365 for (; it != en; ++it)
2366 preamble.registerAutomaticallyLoadedPackage(*it);
2370 // The single '=' is meant here.
2371 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2372 eat_whitespace(p, os, parent_context, false);
2373 parent_context.check_layout(os);
2374 begin_inset(os, "Flex ");
2375 docstring flex_name = newinsetlayout->name();
2376 // FIXME: what do we do if the prefix is not Flex: ?
2377 if (prefixIs(flex_name, from_ascii("Flex:")))
2378 flex_name.erase(0, 5);
2379 os << to_utf8(flex_name) << '\n'
2380 << "status collapsed\n";
2381 if (newinsetlayout->isPassThru()) {
2382 string const arg = p.verbatimEnvironment(name);
2383 Context context(true, parent_context.textclass,
2384 &parent_context.textclass.plainLayout(),
2385 parent_context.layout);
2386 output_ert(os, arg, parent_context);
2388 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2393 if (name == "appendix") {
2394 // This is no good latex style, but it works and is used in some documents...
2395 eat_whitespace(p, os, parent_context, false);
2396 parent_context.check_end_layout(os);
2397 Context context(true, parent_context.textclass, parent_context.layout,
2398 parent_context.layout, parent_context.font);
2399 context.check_layout(os);
2400 os << "\\start_of_appendix\n";
2401 parse_text(p, os, FLAG_END, outer, context);
2402 context.check_end_layout(os);
2407 if (known_environments.find(name) != known_environments.end()) {
2408 vector<ArgumentType> arguments = known_environments[name];
2409 // The last "argument" denotes whether we may translate the
2410 // environment contents to LyX
2411 // The default required if no argument is given makes us
2412 // compatible with the reLyXre environment.
2413 ArgumentType contents = arguments.empty() ?
2416 if (!arguments.empty())
2417 arguments.pop_back();
2418 // See comment in parse_unknown_environment()
2419 bool const specialfont =
2420 (parent_context.font != parent_context.normalfont);
2421 bool const new_layout_allowed =
2422 parent_context.new_layout_allowed;
2424 parent_context.new_layout_allowed = false;
2425 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2426 outer, parent_context);
2427 if (contents == verbatim)
2428 output_ert_inset(os, p.ertEnvironment(name),
2431 parse_text_snippet(p, os, FLAG_END, outer,
2433 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2435 parent_context.new_layout_allowed = new_layout_allowed;
2439 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2444 active_environments.pop_back();
2448 /// parses a comment and outputs it to \p os.
2449 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2450 bool skipNewlines = false)
2452 LASSERT(t.cat() == catComment, return);
2453 if (!t.cs().empty()) {
2454 context.check_layout(os);
2455 output_comment(p, os, t.cs(), context);
2456 if (p.next_token().cat() == catNewline) {
2457 // A newline after a comment line starts a new
2459 if (context.new_layout_allowed) {
2460 if(!context.atParagraphStart())
2461 // Only start a new paragraph if not already
2462 // done (we might get called recursively)
2463 context.new_paragraph(os);
2465 output_ert_inset(os, "\n", context);
2466 eat_whitespace(p, os, context, true);
2468 } else if (!skipNewlines) {
2469 // "%\n" combination
2476 * Reads spaces and comments until the first non-space, non-comment token.
2477 * New paragraphs (double newlines or \\par) are handled like simple spaces
2478 * if \p eatParagraph is true.
2479 * If \p eatNewline is false, newlines won't be treated as whitespace.
2480 * Spaces are skipped, but comments are written to \p os.
2482 void eat_whitespace(Parser & p, ostream & os, Context & context,
2483 bool eatParagraph, bool eatNewline)
2486 Token const & t = p.get_token();
2487 if (t.cat() == catComment)
2488 parse_comment(p, os, t, context, !eatNewline);
2489 else if ((!eatParagraph && p.isParagraph()) ||
2490 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2499 * Set a font attribute, parse text and reset the font attribute.
2500 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2501 * \param currentvalue Current value of the attribute. Is set to the new
2502 * value during parsing.
2503 * \param newvalue New value of the attribute
2505 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2506 Context & context, string const & attribute,
2507 string & currentvalue, string const & newvalue)
2509 context.check_layout(os);
2510 string const oldvalue = currentvalue;
2511 currentvalue = newvalue;
2512 os << '\n' << attribute << ' ' << newvalue << "\n";
2513 parse_text_snippet(p, os, flags, outer, context);
2514 context.check_layout(os);
2515 os << '\n' << attribute << ' ' << oldvalue << "\n";
2516 currentvalue = oldvalue;
2520 /// get the arguments of a natbib or jurabib citation command
2521 void get_cite_arguments(Parser & p, bool natbibOrder,
2522 string & before, string & after, bool const qualified = false)
2524 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2526 // text before the citation
2528 // text after the citation
2529 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2531 if (!after.empty()) {
2532 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2533 if (natbibOrder && !before.empty())
2534 swap(before, after);
2539 void copy_file(FileName const & src, string dstname)
2543 string const absParent = getParentFilePath(false);
2545 if (FileName::isAbsolute(dstname))
2546 dst = FileName(dstname);
2548 dst = makeAbsPath(dstname, absParent);
2549 FileName const srcpath = src.onlyPath();
2550 FileName const dstpath = dst.onlyPath();
2551 if (equivalent(srcpath, dstpath))
2553 if (!dstpath.isDirectory()) {
2554 if (!dstpath.createPath()) {
2555 cerr << "Warning: Could not create directory for file `"
2556 << dst.absFileName() << "´." << endl;
2560 if (dst.isReadableFile()) {
2561 if (overwriteFiles())
2562 cerr << "Warning: Overwriting existing file `"
2563 << dst.absFileName() << "´." << endl;
2565 cerr << "Warning: Not overwriting existing file `"
2566 << dst.absFileName() << "´." << endl;
2570 if (!src.copyTo(dst))
2571 cerr << "Warning: Could not copy file `" << src.absFileName()
2572 << "´ to `" << dst.absFileName() << "´." << endl;
2576 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2577 bool parse_chunk(Parser & p, ostream & os, Context & context)
2579 // check whether a chunk is possible here.
2580 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2586 // read the parameters
2587 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2588 if (!params.first) {
2593 Parser::Arg const code = p.verbatimStuff("\n@");
2598 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2599 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2603 // The last newline read is important for paragraph handling
2607 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2608 // We must have a valid layout before outputting the Chunk inset.
2609 context.check_layout(os);
2610 Context chunkcontext(true, context.textclass);
2611 chunkcontext.layout = &context.textclass.plainLayout();
2612 begin_inset(os, "Flex Chunk");
2613 os << "\nstatus open\n";
2614 if (!params.second.empty()) {
2615 chunkcontext.check_layout(os);
2616 Context paramscontext(true, context.textclass);
2617 paramscontext.layout = &context.textclass.plainLayout();
2618 begin_inset(os, "Argument 1");
2619 os << "\nstatus open\n";
2620 output_ert(os, params.second, paramscontext);
2623 output_ert(os, code.second, chunkcontext);
2631 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2632 bool is_macro(Parser & p)
2634 Token first = p.curr_token();
2635 if (first.cat() != catEscape || !p.good())
2637 if (first.cs() == "def")
2639 if (first.cs() != "global" && first.cs() != "long")
2641 Token second = p.get_token();
2643 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2644 second.cat() == catNewline || second.cat() == catComment)) {
2645 second = p.get_token();
2648 bool secondvalid = second.cat() == catEscape;
2650 bool thirdvalid = false;
2651 if (p.good() && first.cs() == "global" && secondvalid &&
2652 second.cs() == "long") {
2653 third = p.get_token();
2655 while (p.good() && !p.isParagraph() &&
2656 (third.cat() == catSpace ||
2657 third.cat() == catNewline ||
2658 third.cat() == catComment)) {
2659 third = p.get_token();
2662 thirdvalid = third.cat() == catEscape;
2664 for (int i = 0; i < pos; ++i)
2669 return (first.cs() == "global" || first.cs() == "long") &&
2670 second.cs() == "def";
2671 return first.cs() == "global" && second.cs() == "long" &&
2672 third.cs() == "def";
2676 /// Parse a macro definition (assumes that is_macro() returned true)
2677 void parse_macro(Parser & p, ostream & os, Context & context)
2679 context.check_layout(os);
2680 Token first = p.curr_token();
2683 string command = first.asInput();
2684 if (first.cs() != "def") {
2686 eat_whitespace(p, os, context, false);
2687 second = p.curr_token();
2688 command += second.asInput();
2689 if (second.cs() != "def") {
2691 eat_whitespace(p, os, context, false);
2692 third = p.curr_token();
2693 command += third.asInput();
2696 eat_whitespace(p, os, context, false);
2697 string const name = p.get_token().cs();
2698 eat_whitespace(p, os, context, false);
2704 while (p.next_token().cat() != catBegin) {
2705 if (p.next_token().cat() == catParameter) {
2710 // followed by number?
2711 if (p.next_token().cat() == catOther) {
2712 string s = p.get_token().asInput();
2714 // number = current arity + 1?
2715 if (s.size() == 1 && s[0] == arity + '0' + 1)
2720 paramtext += p.get_token().cs();
2722 paramtext += p.get_token().cs();
2727 // only output simple (i.e. compatible) macro as FormulaMacros
2728 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2730 context.check_layout(os);
2731 begin_inset(os, "FormulaMacro");
2732 os << "\n\\def" << ert;
2735 output_ert_inset(os, command + ert, context);
2739 void registerExternalTemplatePackages(string const & name)
2741 external::TemplateManager const & etm = external::TemplateManager::get();
2742 external::Template const * const et = etm.getTemplateByName(name);
2745 external::Template::Formats::const_iterator cit = et->formats.end();
2747 cit = et->formats.find("PDFLaTeX");
2748 if (cit == et->formats.end())
2749 // If the template has not specified a PDFLaTeX output,
2750 // we try the LaTeX format.
2751 cit = et->formats.find("LaTeX");
2752 if (cit == et->formats.end())
2754 vector<string>::const_iterator qit = cit->second.requirements.begin();
2755 vector<string>::const_iterator qend = cit->second.requirements.end();
2756 for (; qit != qend; ++qit)
2757 preamble.registerAutomaticallyLoadedPackage(*qit);
2760 } // anonymous namespace
2764 * Find a file with basename \p name in path \p path and an extension
2767 string find_file(string const & name, string const & path,
2768 char const * const * extensions)
2770 for (char const * const * what = extensions; *what; ++what) {
2771 string const trial = addExtension(name, *what);
2772 if (makeAbsPath(trial, path).exists())
2779 /// Convert filenames with TeX macros and/or quotes to something LyX
2781 string const normalize_filename(string const & name)
2786 Token const & t = p.get_token();
2787 if (t.cat() != catEscape)
2789 else if (t.cs() == "lyxdot") {
2790 // This is used by LyX for simple dots in relative
2794 } else if (t.cs() == "space") {
2797 } else if (t.cs() == "string") {
2798 // Convert \string" to " and \string~ to ~
2799 Token const & n = p.next_token();
2800 if (n.asInput() != "\"" && n.asInput() != "~")
2805 // Strip quotes. This is a bit complicated (see latex_path()).
2806 string full = os.str();
2807 if (!full.empty() && full[0] == '"') {
2808 string base = removeExtension(full);
2809 string ext = getExtension(full);
2810 if (!base.empty() && base[base.length()-1] == '"')
2813 return addExtension(trim(base, "\""), ext);
2814 if (full[full.length()-1] == '"')
2817 return trim(full, "\"");
2823 /// Convert \p name from TeX convention (relative to master file) to LyX
2824 /// convention (relative to .lyx file) if it is relative
2825 void fix_child_filename(string & name)
2827 string const absMasterTeX = getMasterFilePath(true);
2828 bool const isabs = FileName::isAbsolute(name);
2829 // convert from "relative to .tex master" to absolute original path
2831 name = makeAbsPath(name, absMasterTeX).absFileName();
2832 bool copyfile = copyFiles();
2833 string const absParentLyX = getParentFilePath(false);
2836 // convert from absolute original path to "relative to master file"
2837 string const rel = to_utf8(makeRelPath(from_utf8(name),
2838 from_utf8(absMasterTeX)));
2839 // re-interpret "relative to .tex file" as "relative to .lyx file"
2840 // (is different if the master .lyx file resides in a
2841 // different path than the master .tex file)
2842 string const absMasterLyX = getMasterFilePath(false);
2843 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2844 // Do not copy if the new path is impossible to create. Example:
2845 // absMasterTeX = "/foo/bar/"
2846 // absMasterLyX = "/bar/"
2847 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2848 if (contains(name, "/../"))
2855 // convert from absolute original path to
2856 // "relative to .lyx file"
2857 name = to_utf8(makeRelPath(from_utf8(abs),
2858 from_utf8(absParentLyX)));
2862 // convert from absolute original path to "relative to .lyx file"
2863 name = to_utf8(makeRelPath(from_utf8(name),
2864 from_utf8(absParentLyX)));
2869 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2870 Context & context, string const rdelim)
2872 Layout const * newlayout = 0;
2873 InsetLayout const * newinsetlayout = 0;
2874 char const * const * where = 0;
2875 // Store the latest bibliographystyle, addcontentslineContent and
2876 // nocite{*} option (needed for bibtex inset)
2878 string contentslineContent;
2879 // Some classes provide a \bibliographystyle, so do not output
2880 // any if none is explicitly set.
2881 string bibliographystyle;
2882 bool const use_natbib = isProvided("natbib");
2883 bool const use_jurabib = isProvided("jurabib");
2884 bool const use_biblatex = isProvided("biblatex")
2885 && preamble.citeEngine() != "biblatex-natbib";
2886 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2887 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2888 need_commentbib = use_biblatex || use_biblatex_natbib;
2891 // it is impossible to determine the correct encoding for non-CJK Japanese.
2892 // Therefore write a note at the beginning of the document
2893 if (is_nonCJKJapanese) {
2894 context.check_layout(os);
2895 begin_inset(os, "Note Note\n");
2896 os << "status open\n\\begin_layout Plain Layout\n"
2897 << "\\series bold\n"
2898 << "Important information:\n"
2899 << "\\end_layout\n\n"
2900 << "\\begin_layout Plain Layout\n"
2901 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2902 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2903 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2904 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2905 << " and specify the encoding using the -e command-line switch.\n"
2906 << " In addition, you might want to double check that the desired output encoding\n"
2907 << " is correctly selected in Document > Settings > Language.\n"
2908 << "\\end_layout\n";
2910 is_nonCJKJapanese = false;
2913 bool have_cycled = false;
2915 // Leave here only after at least one cycle
2916 if (have_cycled && flags & FLAG_LEAVE) {
2917 flags &= ~FLAG_LEAVE;
2921 Token const & t = p.get_token();
2923 debugToken(cerr, t, flags);
2926 if (context.in_list_preamble
2927 && p.next_token().cs() == context.layout->itemcommand()) {
2928 // We are parsing a list preamble. End before first \item.
2929 flags |= FLAG_LEAVE;
2930 context.in_list_preamble = false;
2933 if (flags & FLAG_ITEM) {
2934 if (t.cat() == catSpace)
2937 flags &= ~FLAG_ITEM;
2938 if (t.cat() == catBegin) {
2939 // skip the brace and collect everything to the next matching
2941 flags |= FLAG_BRACE_LAST;
2945 // handle only this single token, leave the loop if done
2946 flags |= FLAG_LEAVE;
2949 if (t.cat() != catEscape && t.character() == ']' &&
2950 (flags & FLAG_BRACK_LAST))
2952 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2954 string tok = t.asInput();
2955 // we only support delimiters with max 2 chars for now.
2956 if (rdelim.size() > 1)
2957 tok += p.next_token().asInput();
2958 if (t.cat() != catEscape && !rdelim.empty()
2959 && tok == rdelim && (flags & FLAG_RDELIM)) {
2960 if (rdelim.size() > 1)
2961 p.get_token(); // eat rdelim
2965 // If there is anything between \end{env} and \begin{env} we
2966 // don't need to output a separator.
2967 if (t.cat() != catSpace && t.cat() != catNewline &&
2968 t.asInput() != "\\begin")
2975 bool const starred = p.next_token().asInput() == "*";
2976 string const starredname(starred ? (t.cs() + '*') : t.cs());
2977 if (t.cat() == catMath) {
2978 // we are inside some text mode thingy, so opening new math is allowed
2979 context.check_layout(os);
2980 begin_inset(os, "Formula ");
2981 Token const & n = p.get_token();
2982 bool const display(n.cat() == catMath && outer);
2984 // TeX's $$...$$ syntax for displayed math
2986 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2988 p.get_token(); // skip the second '$' token
2990 // simple $...$ stuff
2993 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2998 // Prevent the conversion of a line break to a
2999 // space (bug 7668). This does not change the
3000 // output, but looks ugly in LyX.
3001 eat_whitespace(p, os, context, false);
3006 if (t.cat() == catSuper || t.cat() == catSub) {
3007 cerr << "catcode " << t << " illegal in text mode\n";
3011 // Basic support for quotes. We try to disambiguate
3012 // quotes from the context (e.g., a left english quote is
3013 // the same as a right german quote...).
3014 // Try to make a smart guess about the side
3015 Token const prev = p.prev_token();
3016 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3017 && prev.character() != '\n' && prev.character() != '~');
3018 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3019 context.check_layout(os);
3020 begin_inset(os, "Quotes ");
3021 os << guessQuoteStyle("eld", opening);
3027 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3028 context.check_layout(os);
3029 begin_inset(os, "Quotes ");
3030 os << guessQuoteStyle("erd", opening);
3037 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3038 context.check_layout(os);
3039 begin_inset(os, "Quotes ");
3040 os << guessQuoteStyle("ald", opening);
3047 if (t.asInput() == "<"
3048 && p.next_token().asInput() == "<") {
3049 bool has_chunk = false;
3053 has_chunk = parse_chunk(p, os, context);
3059 context.check_layout(os);
3060 begin_inset(os, "Quotes ");
3061 os << guessQuoteStyle("ard", opening);
3069 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3070 check_space(p, os, context);
3074 // babel shorthands (also used by polyglossia)
3075 // Since these can have different meanings for different languages
3076 // we import them as ERT (but they must be put in ERT to get output
3078 if (t.asInput() == "\"") {
3080 // These are known pairs. We put them together in
3081 // one ERT inset. In other cases (such as "a), only
3082 // the quotation mark is ERTed.
3083 if (p.next_token().asInput() == "\""
3084 || p.next_token().asInput() == "|"
3085 || p.next_token().asInput() == "-"
3086 || p.next_token().asInput() == "~"
3087 || p.next_token().asInput() == "="
3088 || p.next_token().asInput() == "/"
3089 || p.next_token().asInput() == "~"
3090 || p.next_token().asInput() == "'"
3091 || p.next_token().asInput() == "`"
3092 || p.next_token().asInput() == "<"
3093 || p.next_token().asInput() == ">") {
3094 s += p.next_token().asInput();
3097 output_ert_inset(os, s, context);
3101 if (t.character() == '[' && noweb_mode &&
3102 p.next_token().character() == '[') {
3103 // These can contain underscores
3105 string const s = p.getFullOpt() + ']';
3106 if (p.next_token().character() == ']')
3109 cerr << "Warning: Inserting missing ']' in '"
3110 << s << "'." << endl;
3111 output_ert_inset(os, s, context);
3115 if (t.cat() == catLetter) {
3116 context.check_layout(os);
3121 if (t.cat() == catOther ||
3122 t.cat() == catAlign ||
3123 t.cat() == catParameter) {
3124 context.check_layout(os);
3125 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3126 context.merging_hyphens_allowed &&
3127 context.font.family != "ttfamily" &&
3128 !context.layout->pass_thru) {
3129 if (p.next_next_token().asInput() == "-") {
3131 os << to_utf8(docstring(1, 0x2014));
3135 os << to_utf8(docstring(1, 0x2013));
3138 // This translates "&" to "\\&" which may be wrong...
3143 if (p.isParagraph()) {
3144 // In minted floating listings we will collect
3145 // everything into the caption, where multiple
3146 // paragraphs are forbidden.
3147 if (minted_float.empty()) {
3148 if (context.new_layout_allowed)
3149 context.new_paragraph(os);
3151 output_ert_inset(os, "\\par ", context);
3154 eat_whitespace(p, os, context, true);
3158 if (t.cat() == catActive) {
3159 context.check_layout(os);
3160 if (t.character() == '~') {
3161 if (context.layout->free_spacing)
3164 begin_inset(os, "space ~\n");
3172 if (t.cat() == catBegin) {
3173 Token const next = p.next_token();
3174 Token const end = p.next_next_token();
3175 if (next.cat() == catEnd) {
3177 Token const prev = p.prev_token();
3179 if (p.next_token().character() == '`')
3180 ; // ignore it in {}``
3182 output_ert_inset(os, "{}", context);
3183 } else if (next.cat() == catEscape &&
3184 is_known(next.cs(), known_quotes) &&
3185 end.cat() == catEnd) {
3186 // Something like {\textquoteright} (e.g.
3187 // from writer2latex). We may skip the
3188 // braces here for better readability.
3189 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3191 } else if (p.next_token().asInput() == "\\ascii") {
3192 // handle the \ascii characters
3193 // (the case without braces is handled later)
3194 // the code is "{\ascii\xxx}"
3195 p.get_token(); // eat \ascii
3196 string name2 = p.get_token().asInput();
3197 p.get_token(); // eat the final '}'
3198 string const name = "{\\ascii" + name2 + "}";
3202 // get the character from unicodesymbols
3203 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3204 Encodings::TEXT_CMD, termination, rem, &req);
3206 context.check_layout(os);
3209 output_ert_inset(os,
3210 to_utf8(rem), context);
3211 for (set<string>::const_iterator it = req.begin();
3212 it != req.end(); ++it)
3213 preamble.registerAutomaticallyLoadedPackage(*it);
3215 // we did not find a non-ert version
3216 output_ert_inset(os, name, context);
3218 context.check_layout(os);
3219 // special handling of font attribute changes
3220 Token const prev = p.prev_token();
3221 TeXFont const oldFont = context.font;
3222 if (next.character() == '[' ||
3223 next.character() == ']' ||
3224 next.character() == '*') {
3226 if (p.next_token().cat() == catEnd) {
3231 output_ert_inset(os, "{", context);
3232 parse_text_snippet(p, os,
3235 output_ert_inset(os, "}", context);
3237 } else if (! context.new_layout_allowed) {
3238 output_ert_inset(os, "{", context);
3239 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3241 output_ert_inset(os, "}", context);
3242 } else if (is_known(next.cs(), known_sizes)) {
3243 // next will change the size, so we must
3245 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3247 if (!context.atParagraphStart())
3249 << context.font.size << "\n";
3250 } else if (is_known(next.cs(), known_font_families)) {
3251 // next will change the font family, so we
3252 // must reset it here
3253 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3255 if (!context.atParagraphStart())
3257 << context.font.family << "\n";
3258 } else if (is_known(next.cs(), known_font_series)) {
3259 // next will change the font series, so we
3260 // must reset it here
3261 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3263 if (!context.atParagraphStart())
3265 << context.font.series << "\n";
3266 } else if (is_known(next.cs(), known_font_shapes)) {
3267 // next will change the font shape, so we
3268 // must reset it here
3269 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3271 if (!context.atParagraphStart())
3273 << context.font.shape << "\n";
3274 } else if (is_known(next.cs(), known_old_font_families) ||
3275 is_known(next.cs(), known_old_font_series) ||
3276 is_known(next.cs(), known_old_font_shapes)) {
3277 // next will change the font family, series
3278 // and shape, so we must reset it here
3279 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3281 if (!context.atParagraphStart())
3283 << context.font.family
3285 << context.font.series
3287 << context.font.shape << "\n";
3289 output_ert_inset(os, "{", context);
3290 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3292 output_ert_inset(os, "}", context);
3298 if (t.cat() == catEnd) {
3299 if (flags & FLAG_BRACE_LAST) {
3302 cerr << "stray '}' in text\n";
3303 output_ert_inset(os, "}", context);
3307 if (t.cat() == catComment) {
3308 parse_comment(p, os, t, context);
3313 // control sequences
3316 if (t.cs() == "(" || t.cs() == "[") {
3317 bool const simple = t.cs() == "(";
3318 context.check_layout(os);
3319 begin_inset(os, "Formula");
3320 os << " \\" << t.cs();
3321 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3322 os << '\\' << (simple ? ')' : ']');
3325 // Prevent the conversion of a line break to a
3326 // space (bug 7668). This does not change the
3327 // output, but looks ugly in LyX.
3328 eat_whitespace(p, os, context, false);
3333 if (t.cs() == "begin") {
3334 parse_environment(p, os, outer, last_env,
3339 if (t.cs() == "end") {
3340 if (flags & FLAG_END) {
3341 // eat environment name
3342 string const name = p.getArg('{', '}');
3343 if (name != active_environment())
3344 cerr << "\\end{" + name + "} does not match \\begin{"
3345 + active_environment() + "}\n";
3348 p.error("found 'end' unexpectedly");
3352 // "item" by default, but could be something else
3353 if (t.cs() == context.layout->itemcommand()) {
3355 if (context.layout->labeltype == LABEL_MANUAL) {
3356 // FIXME: This swallows comments, but we cannot use
3357 // eat_whitespace() since we must not output
3358 // anything before the item.
3359 p.skip_spaces(true);
3360 s = p.verbatimOption();
3362 p.skip_spaces(false);
3364 context.check_layout(os);
3365 if (context.has_item) {
3366 // An item in an unknown list-like environment
3367 // FIXME: Do this in check_layout()!
3368 context.has_item = false;
3369 string item = "\\" + context.layout->itemcommand();
3372 output_ert_inset(os, item, context);
3374 if (context.layout->labeltype != LABEL_MANUAL)
3375 output_arguments(os, p, outer, false, "item", context,
3376 context.layout->itemargs());
3377 if (!context.list_preamble.empty()) {
3378 // We have a list preamble. Output it here.
3379 begin_inset(os, "Argument listpreamble:1");
3380 os << "\nstatus collapsed\n\n"
3381 << "\\begin_layout Plain Layout\n\n"
3382 << rtrim(context.list_preamble)
3383 << "\n\\end_layout";
3385 context.list_preamble.clear();
3387 if (!context.list_extra_stuff.empty()) {
3388 os << context.list_extra_stuff;
3389 context.list_extra_stuff.clear();
3391 else if (!s.empty()) {
3392 // LyX adds braces around the argument,
3393 // so we need to remove them here.
3394 if (s.size() > 2 && s[0] == '{' &&
3395 s[s.size()-1] == '}')
3396 s = s.substr(1, s.size()-2);
3397 // If the argument contains a space we
3398 // must put it into ERT: Otherwise LyX
3399 // would misinterpret the space as
3400 // item delimiter (bug 7663)
3401 if (contains(s, ' ')) {
3402 output_ert_inset(os, s, context);
3405 os << parse_text_snippet(p2,
3406 FLAG_BRACK_LAST, outer, context);
3408 // The space is needed to separate the
3409 // item from the rest of the sentence.
3411 eat_whitespace(p, os, context, false);
3416 if (t.cs() == "bibitem") {
3418 context.check_layout(os);
3419 eat_whitespace(p, os, context, false);
3420 string label = p.verbatimOption();
3421 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3422 bool const literal = !lbl.first;
3423 label = literal ? subst(label, "\n", " ") : lbl.second;
3424 string lit = literal ? "\"true\"" : "\"false\"";
3425 string key = convert_literate_command_inset_arg(p.verbatim_item());
3426 begin_command_inset(os, "bibitem", "bibitem");
3427 os << "label \"" << label << "\"\n"
3428 << "key \"" << key << "\"\n"
3429 << "literal " << lit << "\n";
3435 // catch the case of \def\inputGnumericTable
3437 if (t.cs() == "def") {
3438 Token second = p.next_token();
3439 if (second.cs() == "inputGnumericTable") {
3443 Token third = p.get_token();
3445 if (third.cs() == "input") {
3449 string name = normalize_filename(p.verbatim_item());
3450 string const path = getMasterFilePath(true);
3451 // We want to preserve relative / absolute filenames,
3452 // therefore path is only used for testing
3453 // The file extension is in every case ".tex".
3454 // So we need to remove this extension and check for
3455 // the original one.
3456 name = removeExtension(name);
3457 if (!makeAbsPath(name, path).exists()) {
3458 char const * const Gnumeric_formats[] = {"gnumeric",
3460 string const Gnumeric_name =
3461 find_file(name, path, Gnumeric_formats);
3462 if (!Gnumeric_name.empty())
3463 name = Gnumeric_name;
3465 FileName const absname = makeAbsPath(name, path);
3466 if (absname.exists()) {
3467 fix_child_filename(name);
3468 copy_file(absname, name);
3470 cerr << "Warning: Could not find file '"
3471 << name << "'." << endl;
3472 context.check_layout(os);
3473 begin_inset(os, "External\n\ttemplate ");
3474 os << "GnumericSpreadsheet\n\tfilename "
3477 context.check_layout(os);
3479 // register the packages that are automatically loaded
3480 // by the Gnumeric template
3481 registerExternalTemplatePackages("GnumericSpreadsheet");
3486 parse_macro(p, os, context);
3490 if (t.cs() == "noindent") {
3492 context.add_par_extra_stuff("\\noindent\n");
3496 if (t.cs() == "appendix") {
3497 context.add_par_extra_stuff("\\start_of_appendix\n");
3498 // We need to start a new paragraph. Otherwise the
3499 // appendix in 'bla\appendix\chapter{' would start
3501 context.new_paragraph(os);
3502 // We need to make sure that the paragraph is
3503 // generated even if it is empty. Otherwise the
3504 // appendix in '\par\appendix\par\chapter{' would
3506 context.check_layout(os);
3507 // FIXME: This is a hack to prevent paragraph
3508 // deletion if it is empty. Handle this better!
3509 output_comment(p, os,
3510 "dummy comment inserted by tex2lyx to "
3511 "ensure that this paragraph is not empty",
3513 // Both measures above may generate an additional
3514 // empty paragraph, but that does not hurt, because
3515 // whitespace does not matter here.
3516 eat_whitespace(p, os, context, true);
3520 // Must catch empty dates before findLayout is called below
3521 if (t.cs() == "date") {
3522 eat_whitespace(p, os, context, false);
3524 string const date = p.verbatim_item();
3527 preamble.suppressDate(true);
3530 preamble.suppressDate(false);
3531 if (context.new_layout_allowed &&
3532 (newlayout = findLayout(context.textclass,
3535 output_command_layout(os, p, outer,
3536 context, newlayout);
3537 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3538 if (!preamble.titleLayoutFound())
3539 preamble.titleLayoutFound(newlayout->intitle);
3540 set<string> const & req = newlayout->required();
3541 set<string>::const_iterator it = req.begin();
3542 set<string>::const_iterator en = req.end();
3543 for (; it != en; ++it)
3544 preamble.registerAutomaticallyLoadedPackage(*it);
3546 output_ert_inset(os,
3547 "\\date{" + p.verbatim_item() + '}',
3553 // Before we look for the layout name with star and alone below, we check the layouts including
3554 // the LateXParam, which might be one or several options or a star.
3555 // The single '=' is meant here.
3556 if (context.new_layout_allowed &&
3557 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3558 // store the latexparam here. This is eaten in output_command_layout
3559 context.latexparam = newlayout->latexparam();
3561 output_command_layout(os, p, outer, context, newlayout);
3562 context.latexparam.clear();
3564 if (!preamble.titleLayoutFound())
3565 preamble.titleLayoutFound(newlayout->intitle);
3566 set<string> const & req = newlayout->required();
3567 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3568 preamble.registerAutomaticallyLoadedPackage(*it);
3572 // Starred section headings
3573 // Must attempt to parse "Section*" before "Section".
3574 if ((p.next_token().asInput() == "*") &&
3575 context.new_layout_allowed &&
3576 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3579 output_command_layout(os, p, outer, context, newlayout);
3581 if (!preamble.titleLayoutFound())
3582 preamble.titleLayoutFound(newlayout->intitle);
3583 set<string> const & req = newlayout->required();
3584 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3585 preamble.registerAutomaticallyLoadedPackage(*it);
3589 // Section headings and the like
3590 if (context.new_layout_allowed &&
3591 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3593 output_command_layout(os, p, outer, context, newlayout);
3595 if (!preamble.titleLayoutFound())
3596 preamble.titleLayoutFound(newlayout->intitle);
3597 set<string> const & req = newlayout->required();
3598 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3599 preamble.registerAutomaticallyLoadedPackage(*it);
3603 if (t.cs() == "subfloat") {
3604 // the syntax is \subfloat[list entry][sub caption]{content}
3605 // if it is a table of figure depends on the surrounding float
3607 // do nothing if there is no outer float
3608 if (!float_type.empty()) {
3609 context.check_layout(os);
3611 begin_inset(os, "Float " + float_type + "\n");
3613 << "\nsideways false"
3614 << "\nstatus collapsed\n\n";
3617 bool has_caption = false;
3618 if (p.next_token().cat() != catEscape &&
3619 p.next_token().character() == '[') {
3620 p.get_token(); // eat '['
3621 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3624 // In case we have two optional args, the second is the caption.
3625 if (p.next_token().cat() != catEscape &&
3626 p.next_token().character() == '[') {
3627 p.get_token(); // eat '['
3628 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3631 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3632 // the caption comes always as the last
3634 // we must make sure that the caption gets a \begin_layout
3635 os << "\n\\begin_layout Plain Layout";
3637 begin_inset(os, "Caption Standard\n");
3638 Context newcontext(true, context.textclass,
3639 0, 0, context.font);
3640 newcontext.check_layout(os);
3641 os << caption << "\n";
3642 newcontext.check_end_layout(os);
3645 // close the layout we opened
3646 os << "\n\\end_layout";
3651 // if the float type is not supported or there is no surrounding float
3656 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3658 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3660 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3661 + "{" + p.verbatim_item() + '}', context);
3666 if (t.cs() == "xymatrix") {
3667 // we must open a new math because LyX's xy support is in math
3668 context.check_layout(os);
3669 begin_inset(os, "Formula ");
3671 os << "\\" << t.cs() << '{';
3672 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3675 preamble.registerAutomaticallyLoadedPackage("xy");
3679 if (t.cs() == "includegraphics") {
3680 bool const clip = p.next_token().asInput() == "*";
3683 string const arg = p.getArg('[', ']');
3684 map<string, string> opts;
3685 vector<string> keys;
3686 split_map(arg, opts, keys);
3688 opts["clip"] = string();
3689 string name = normalize_filename(p.verbatim_item());
3691 string const path = getMasterFilePath(true);
3692 // We want to preserve relative / absolute filenames,
3693 // therefore path is only used for testing
3694 if (!makeAbsPath(name, path).exists()) {
3695 // The file extension is probably missing.
3696 // Now try to find it out.
3697 string const dvips_name =
3698 find_file(name, path,
3699 known_dvips_graphics_formats);
3700 string const pdftex_name =
3701 find_file(name, path,
3702 known_pdftex_graphics_formats);
3703 if (!dvips_name.empty()) {
3704 if (!pdftex_name.empty()) {
3705 cerr << "This file contains the "
3707 "\"\\includegraphics{"
3709 "However, files\n\""
3710 << dvips_name << "\" and\n\""
3711 << pdftex_name << "\"\n"
3712 "both exist, so I had to make a "
3713 "choice and took the first one.\n"
3714 "Please move the unwanted one "
3715 "someplace else and try again\n"
3716 "if my choice was wrong."
3720 } else if (!pdftex_name.empty()) {
3726 FileName const absname = makeAbsPath(name, path);
3727 if (absname.exists()) {
3728 fix_child_filename(name);
3729 copy_file(absname, name);
3731 cerr << "Warning: Could not find graphics file '"
3732 << name << "'." << endl;
3734 context.check_layout(os);
3735 begin_inset(os, "Graphics ");
3736 os << "\n\tfilename " << name << '\n';
3737 if (opts.find("width") != opts.end())
3739 << translate_len(opts["width"]) << '\n';
3740 if (opts.find("totalheight") != opts.end())
3742 << translate_len(opts["totalheight"]) << '\n';
3743 if (opts.find("scale") != opts.end()) {
3744 istringstream iss(opts["scale"]);
3748 os << "\tscale " << val << '\n';
3750 if (opts.find("angle") != opts.end()) {
3751 os << "\trotateAngle "
3752 << opts["angle"] << '\n';
3753 vector<string>::const_iterator a =
3754 find(keys.begin(), keys.end(), "angle");
3755 vector<string>::const_iterator s =
3756 find(keys.begin(), keys.end(), "width");
3757 if (s == keys.end())
3758 s = find(keys.begin(), keys.end(), "totalheight");
3759 if (s == keys.end())
3760 s = find(keys.begin(), keys.end(), "scale");
3761 if (s != keys.end() && distance(s, a) > 0)
3762 os << "\tscaleBeforeRotation\n";
3764 if (opts.find("origin") != opts.end()) {
3766 string const opt = opts["origin"];
3767 if (opt.find('l') != string::npos) ss << "left";
3768 if (opt.find('r') != string::npos) ss << "right";
3769 if (opt.find('c') != string::npos) ss << "center";
3770 if (opt.find('t') != string::npos) ss << "Top";
3771 if (opt.find('b') != string::npos) ss << "Bottom";
3772 if (opt.find('B') != string::npos) ss << "Baseline";
3773 if (!ss.str().empty())
3774 os << "\trotateOrigin " << ss.str() << '\n';
3776 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3778 if (opts.find("keepaspectratio") != opts.end())
3779 os << "\tkeepAspectRatio\n";
3780 if (opts.find("clip") != opts.end())
3782 if (opts.find("draft") != opts.end())
3784 if (opts.find("bb") != opts.end())
3785 os << "\tBoundingBox "
3786 << opts["bb"] << '\n';
3787 int numberOfbbOptions = 0;
3788 if (opts.find("bbllx") != opts.end())
3789 numberOfbbOptions++;
3790 if (opts.find("bblly") != opts.end())
3791 numberOfbbOptions++;
3792 if (opts.find("bburx") != opts.end())
3793 numberOfbbOptions++;
3794 if (opts.find("bbury") != opts.end())
3795 numberOfbbOptions++;
3796 if (numberOfbbOptions == 4)
3797 os << "\tBoundingBox "
3798 << opts["bbllx"] << " " << opts["bblly"] << " "
3799 << opts["bburx"] << " " << opts["bbury"] << '\n';
3800 else if (numberOfbbOptions > 0)
3801 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3802 numberOfbbOptions = 0;
3803 if (opts.find("natwidth") != opts.end())
3804 numberOfbbOptions++;
3805 if (opts.find("natheight") != opts.end())
3806 numberOfbbOptions++;
3807 if (numberOfbbOptions == 2)
3808 os << "\tBoundingBox 0bp 0bp "
3809 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3810 else if (numberOfbbOptions > 0)
3811 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3812 ostringstream special;
3813 if (opts.find("hiresbb") != opts.end())
3814 special << "hiresbb,";
3815 if (opts.find("trim") != opts.end())
3817 if (opts.find("viewport") != opts.end())
3818 special << "viewport=" << opts["viewport"] << ',';
3819 if (opts.find("height") != opts.end())
3820 special << "height=" << opts["height"] << ',';
3821 if (opts.find("type") != opts.end())
3822 special << "type=" << opts["type"] << ',';
3823 if (opts.find("ext") != opts.end())
3824 special << "ext=" << opts["ext"] << ',';
3825 if (opts.find("read") != opts.end())
3826 special << "read=" << opts["read"] << ',';
3827 if (opts.find("command") != opts.end())
3828 special << "command=" << opts["command"] << ',';
3829 string s_special = special.str();
3830 if (!s_special.empty()) {
3831 // We had special arguments. Remove the trailing ','.
3832 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3834 // TODO: Handle the unknown settings better.
3835 // Warn about invalid options.
3836 // Check whether some option was given twice.
3838 preamble.registerAutomaticallyLoadedPackage("graphicx");
3842 if (t.cs() == "footnote" ||
3843 (t.cs() == "thanks" && context.layout->intitle)) {
3845 context.check_layout(os);
3846 begin_inset(os, "Foot\n");
3847 os << "status collapsed\n\n";
3848 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3853 if (t.cs() == "marginpar") {
3855 context.check_layout(os);
3856 begin_inset(os, "Marginal\n");
3857 os << "status collapsed\n\n";
3858 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3863 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3864 bool const use_minted = t.cs() == "mintinline";
3866 parse_listings(p, os, context, true, use_minted);
3870 if (t.cs() == "ensuremath") {
3872 context.check_layout(os);
3873 string const s = p.verbatim_item();
3874 //FIXME: this never triggers in UTF8
3875 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3878 output_ert_inset(os, "\\ensuremath{" + s + "}",
3883 else if (t.cs() == "makeindex"
3884 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3885 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3886 if (preamble.titleLayoutFound()) {
3888 skip_spaces_braces(p);
3890 output_ert_inset(os, t.asInput(), context);
3894 if (t.cs() == "tableofcontents"
3895 || t.cs() == "lstlistoflistings"
3896 || t.cs() == "listoflistings") {
3897 string name = t.cs();
3898 if (preamble.minted() && name == "listoflistings")
3899 name.insert(0, "lst");
3900 context.check_layout(os);
3901 begin_command_inset(os, "toc", name);
3903 skip_spaces_braces(p);
3904 if (name == "lstlistoflistings") {
3905 if (preamble.minted())
3906 preamble.registerAutomaticallyLoadedPackage("minted");
3908 preamble.registerAutomaticallyLoadedPackage("listings");
3913 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3914 context.check_layout(os);
3915 if (t.cs() == "listoffigures")
3916 begin_inset(os, "FloatList figure\n");
3918 begin_inset(os, "FloatList table\n");
3920 skip_spaces_braces(p);
3924 if (t.cs() == "listof") {
3925 p.skip_spaces(true);
3926 string const name = p.verbatim_item();
3927 if (context.textclass.floats().typeExist(name)) {
3928 context.check_layout(os);
3929 begin_inset(os, "FloatList ");
3932 p.verbatim_item(); // swallow second arg
3934 output_ert_inset(os, "\\listof{" + name + "}", context);
3938 if (t.cs() == "theendnotes"
3939 || (t.cs() == "printendnotes"
3940 && p.next_token().asInput() != "*"
3942 context.check_layout(os);
3943 begin_inset(os, "FloatList endnote\n");
3945 skip_spaces_braces(p);
3949 if ((where = is_known(t.cs(), known_text_font_families))) {
3950 parse_text_attributes(p, os, FLAG_ITEM, outer,
3951 context, "\\family", context.font.family,
3952 known_coded_font_families[where - known_text_font_families]);
3956 // beamer has a \textbf<overlay>{} inset
3957 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3958 parse_text_attributes(p, os, FLAG_ITEM, outer,
3959 context, "\\series", context.font.series,
3960 known_coded_font_series[where - known_text_font_series]);
3964 // beamer has a \textit<overlay>{} inset
3965 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3966 parse_text_attributes(p, os, FLAG_ITEM, outer,
3967 context, "\\shape", context.font.shape,
3968 known_coded_font_shapes[where - known_text_font_shapes]);
3972 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3973 context.check_layout(os);
3974 TeXFont oldFont = context.font;
3975 context.font.init();
3976 context.font.size = oldFont.size;
3977 os << "\n\\family " << context.font.family << "\n";
3978 os << "\n\\series " << context.font.series << "\n";
3979 os << "\n\\shape " << context.font.shape << "\n";
3980 if (t.cs() == "textnormal") {
3981 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3982 output_font_change(os, context.font, oldFont);
3983 context.font = oldFont;
3985 eat_whitespace(p, os, context, false);
3989 if (t.cs() == "textcolor") {
3990 // scheme is \textcolor{color name}{text}
3991 string const color = p.verbatim_item();
3992 // we support the predefined colors of the color and the xcolor package
3993 if (color == "black" || color == "blue" || color == "cyan"
3994 || color == "green" || color == "magenta" || color == "red"
3995 || color == "white" || color == "yellow") {
3996 context.check_layout(os);
3997 os << "\n\\color " << color << "\n";
3998 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3999 context.check_layout(os);
4000 os << "\n\\color inherit\n";
4001 preamble.registerAutomaticallyLoadedPackage("color");
4002 } else if (color == "brown" || color == "darkgray" || color == "gray"
4003 || color == "lightgray" || color == "lime" || color == "olive"
4004 || color == "orange" || color == "pink" || color == "purple"
4005 || color == "teal" || color == "violet") {
4006 context.check_layout(os);
4007 os << "\n\\color " << color << "\n";
4008 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4009 context.check_layout(os);
4010 os << "\n\\color inherit\n";
4011 preamble.registerAutomaticallyLoadedPackage("xcolor");
4013 // for custom defined colors
4014 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4018 if (t.cs() == "underbar" || t.cs() == "uline") {
4019 // \underbar is not 100% correct (LyX outputs \uline
4020 // of ulem.sty). The difference is that \ulem allows
4021 // line breaks, and \underbar does not.
4022 // Do NOT handle \underline.
4023 // \underbar cuts through y, g, q, p etc.,
4024 // \underline does not.
4025 context.check_layout(os);
4026 os << "\n\\bar under\n";
4027 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4028 context.check_layout(os);
4029 os << "\n\\bar default\n";
4030 preamble.registerAutomaticallyLoadedPackage("ulem");
4034 if (t.cs() == "sout") {
4035 context.check_layout(os);
4036 os << "\n\\strikeout on\n";
4037 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4038 context.check_layout(os);
4039 os << "\n\\strikeout default\n";
4040 preamble.registerAutomaticallyLoadedPackage("ulem");
4044 // beamer has an \emph<overlay>{} inset
4045 if ((t.cs() == "uuline" || t.cs() == "uwave"
4046 || t.cs() == "emph" || t.cs() == "noun"
4047 || t.cs() == "xout") && !p.hasOpt("<")) {
4048 context.check_layout(os);
4049 os << "\n\\" << t.cs() << " on\n";
4050 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4051 context.check_layout(os);
4052 os << "\n\\" << t.cs() << " default\n";
4053 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4054 preamble.registerAutomaticallyLoadedPackage("ulem");
4058 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4059 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4060 context.check_layout(os);
4063 initials = p.getArg('[', ']');
4065 string name = p.getArg('{', '}');
4066 string localtime = p.getArg('{', '}');
4067 preamble.registerAuthor(name, initials);
4068 Author const & author = preamble.getAuthor(name);
4069 // from_asctime_utc() will fail if LyX decides to output the
4070 // time in the text language.
4071 time_t ptime = from_asctime_utc(localtime);
4072 if (ptime == static_cast<time_t>(-1)) {
4073 cerr << "Warning: Could not parse time `" << localtime
4074 << "´ for change tracking, using current time instead.\n";
4075 ptime = current_time();
4077 if (t.cs() == "lyxadded")
4078 os << "\n\\change_inserted ";
4080 os << "\n\\change_deleted ";
4081 os << author.bufferId() << ' ' << ptime << '\n';
4082 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4083 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4084 LaTeXPackages::isAvailable("xcolor");
4085 // No need to test for luatex, since luatex comes in
4086 // two flavours (dvi and pdf), like latex, and those
4087 // are detected by pdflatex.
4088 if (pdflatex || xetex) {
4090 preamble.registerAutomaticallyLoadedPackage("ulem");
4091 preamble.registerAutomaticallyLoadedPackage("xcolor");
4092 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4096 preamble.registerAutomaticallyLoadedPackage("ulem");
4097 preamble.registerAutomaticallyLoadedPackage("xcolor");
4103 if (t.cs() == "textipa") {
4104 context.check_layout(os);
4105 begin_inset(os, "IPA\n");
4106 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4107 context.merging_hyphens_allowed = false;
4108 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4109 context.merging_hyphens_allowed = merging_hyphens_allowed;
4111 preamble.registerAutomaticallyLoadedPackage("tipa");
4112 preamble.registerAutomaticallyLoadedPackage("tipx");
4116 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4117 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4118 context.check_layout(os);
4122 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4123 begin_inset(os, "IPADeco " + type + "\n");
4124 os << "status open\n";
4125 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4131 if (t.cs() == "textvertline") {
4132 // FIXME: This is not correct, \textvertline is higher than |
4138 if (t.cs() == "tone" ) {
4139 context.check_layout(os);
4140 // register the tone package
4141 preamble.registerAutomaticallyLoadedPackage("tone");
4142 string content = trimSpaceAndEol(p.verbatim_item());
4143 string command = t.asInput() + "{" + content + "}";
4144 // some tones can be detected by unicodesymbols, some need special code
4145 if (is_known(content, known_tones)) {
4146 os << "\\IPAChar " << command << "\n";
4149 // try to see whether the string is in unicodesymbols
4153 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4154 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4155 termination, rem, &req);
4159 output_ert_inset(os, to_utf8(rem), context);
4160 for (set<string>::const_iterator it = req.begin();
4161 it != req.end(); ++it)
4162 preamble.registerAutomaticallyLoadedPackage(*it);
4164 // we did not find a non-ert version
4165 output_ert_inset(os, command, context);
4169 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4170 t.cs() == "vphantom") {
4171 context.check_layout(os);
4172 if (t.cs() == "phantom")
4173 begin_inset(os, "Phantom Phantom\n");
4174 if (t.cs() == "hphantom")
4175 begin_inset(os, "Phantom HPhantom\n");
4176 if (t.cs() == "vphantom")
4177 begin_inset(os, "Phantom VPhantom\n");
4178 os << "status open\n";
4179 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4185 if (t.cs() == "href") {
4186 context.check_layout(os);
4187 string target = convert_literate_command_inset_arg(p.verbatim_item());
4188 string name = p.verbatim_item();
4189 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4190 bool const literal = !nm.first;
4191 name = literal ? subst(name, "\n", " ") : nm.second;
4192 string lit = literal ? "\"true\"" : "\"false\"";
4194 size_t i = target.find(':');
4195 if (i != string::npos) {
4196 type = target.substr(0, i + 1);
4197 if (type == "mailto:" || type == "file:")
4198 target = target.substr(i + 1);
4199 // handle the case that name is equal to target, except of "http(s)://"
4200 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4203 begin_command_inset(os, "href", "href");
4205 os << "name \"" << name << "\"\n";
4206 os << "target \"" << target << "\"\n";
4207 if (type == "mailto:" || type == "file:")
4208 os << "type \"" << type << "\"\n";
4209 os << "literal " << lit << "\n";
4211 skip_spaces_braces(p);
4215 if (t.cs() == "lyxline") {
4216 // swallow size argument (it is not used anyway)
4218 if (!context.atParagraphStart()) {
4219 // so our line is in the middle of a paragraph
4220 // we need to add a new line, lest this line
4221 // follow the other content on that line and
4222 // run off the side of the page
4223 // FIXME: This may create an empty paragraph,
4224 // but without that it would not be
4225 // possible to set noindent below.
4226 // Fortunately LaTeX does not care
4227 // about the empty paragraph.
4228 context.new_paragraph(os);
4230 if (preamble.indentParagraphs()) {
4231 // we need to unindent, lest the line be too long
4232 context.add_par_extra_stuff("\\noindent\n");
4234 context.check_layout(os);
4235 begin_command_inset(os, "line", "rule");
4236 os << "offset \"0.5ex\"\n"
4237 "width \"100line%\"\n"
4243 if (t.cs() == "rule") {
4244 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4245 string const width = p.getArg('{', '}');
4246 string const thickness = p.getArg('{', '}');
4247 context.check_layout(os);
4248 begin_command_inset(os, "line", "rule");
4249 if (!offset.empty())
4250 os << "offset \"" << translate_len(offset) << "\"\n";
4251 os << "width \"" << translate_len(width) << "\"\n"
4252 "height \"" << translate_len(thickness) << "\"\n";
4257 // Handle refstyle first in order to to catch \eqref, because this
4258 // can also occur without refstyle. Only recognize these commands if
4259 // refstyle.sty was found in the preamble (otherwise \eqref
4260 // and user defined ref commands could be misdetected).
4261 // We uncapitalize the input in order to catch capitalized commands
4263 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4264 && preamble.refstyle()) {
4265 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4266 string plural = "false";
4267 // Catch the plural option [s]
4269 string const opt = p.getOpt();
4273 // LyX does not yet support other optional arguments of ref commands
4274 output_ert_inset(os, t.asInput() + opt + "{" +
4275 p.verbatim_item() + '}', context);
4279 context.check_layout(os);
4280 begin_command_inset(os, "ref", "formatted");
4281 os << "reference \"";
4282 os << known_refstyle_prefixes[where - known_refstyle_commands]
4284 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4286 os << "plural \"" << plural << "\"\n";
4287 os << "caps \"" << cap << "\"\n";
4288 os << "noprefix \"false\"\n";
4290 preamble.registerAutomaticallyLoadedPackage("refstyle");
4294 // if refstyle is used, we must not convert \prettyref to a
4295 // formatted reference, since that would result in a refstyle command.
4296 if ((where = is_known(t.cs(), known_ref_commands)) &&
4297 (t.cs() != "prettyref" || !preamble.refstyle())) {
4298 string const opt = p.getOpt();
4300 context.check_layout(os);
4301 begin_command_inset(os, "ref",
4302 known_coded_ref_commands[where - known_ref_commands]);
4303 os << "reference \""
4304 << convert_literate_command_inset_arg(p.verbatim_item())
4306 os << "plural \"false\"\n";
4307 os << "caps \"false\"\n";
4308 os << "noprefix \"false\"\n";
4310 if (t.cs() == "vref" || t.cs() == "vpageref")
4311 preamble.registerAutomaticallyLoadedPackage("varioref");
4312 else if (t.cs() == "prettyref")
4313 preamble.registerAutomaticallyLoadedPackage("prettyref");
4315 // LyX does not yet support optional arguments of ref commands
4316 output_ert_inset(os, t.asInput() + opt + "{" +
4317 p.verbatim_item() + '}', context);
4323 is_known(t.cs(), known_natbib_commands) &&
4324 ((t.cs() != "citefullauthor" &&
4325 t.cs() != "citeyear" &&
4326 t.cs() != "citeyearpar") ||
4327 p.next_token().asInput() != "*")) {
4328 context.check_layout(os);
4329 string command = t.cs();
4330 if (p.next_token().asInput() == "*") {
4334 if (command == "citefullauthor")
4335 // alternative name for "\\citeauthor*"
4336 command = "citeauthor*";
4338 // text before the citation
4340 // text after the citation
4342 get_cite_arguments(p, true, before, after);
4344 if (command == "cite") {
4345 // \cite without optional argument means
4346 // \citet, \cite with at least one optional
4347 // argument means \citep.
4348 if (before.empty() && after.empty())
4353 if (before.empty() && after == "[]")
4354 // avoid \citet[]{a}
4356 else if (before == "[]" && after == "[]") {
4357 // avoid \citet[][]{a}
4361 bool literal = false;
4362 pair<bool, string> aft;
4363 pair<bool, string> bef;
4364 // remove the brackets around after and before
4365 if (!after.empty()) {
4367 after.erase(after.length() - 1, 1);
4368 aft = convert_latexed_command_inset_arg(after);
4369 literal = !aft.first;
4370 after = literal ? subst(after, "\n", " ") : aft.second;
4372 if (!before.empty()) {
4374 before.erase(before.length() - 1, 1);
4375 bef = convert_latexed_command_inset_arg(before);
4376 literal |= !bef.first;
4377 before = literal ? subst(before, "\n", " ") : bef.second;
4378 if (literal && !after.empty())
4379 after = subst(after, "\n", " ");
4381 string lit = literal ? "\"true\"" : "\"false\"";
4382 begin_command_inset(os, "citation", command);
4383 os << "after " << '"' << after << '"' << "\n";
4384 os << "before " << '"' << before << '"' << "\n";
4386 << convert_literate_command_inset_arg(p.verbatim_item())
4388 << "literal " << lit << "\n";
4390 // Need to set the cite engine if natbib is loaded by
4391 // the document class directly
4392 if (preamble.citeEngine() == "basic")
4393 preamble.citeEngine("natbib");
4398 && is_known(t.cs(), known_biblatex_commands)
4399 && ((t.cs() == "cite"
4400 || t.cs() == "citeauthor"
4401 || t.cs() == "Citeauthor"
4402 || t.cs() == "parencite"
4403 || t.cs() == "citetitle")
4404 || p.next_token().asInput() != "*"))
4405 || (use_biblatex_natbib
4406 && (is_known(t.cs(), known_biblatex_commands)
4407 || is_known(t.cs(), known_natbib_commands))
4408 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4409 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4410 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4411 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4412 || t.cs() == "parencite" || t.cs() == "citetitle")
4413 || p.next_token().asInput() != "*"))){
4414 context.check_layout(os);
4415 string command = t.cs();
4416 if (p.next_token().asInput() == "*") {
4421 bool const qualified = suffixIs(command, "s");
4423 command = rtrim(command, "s");
4425 // text before the citation
4427 // text after the citation
4429 get_cite_arguments(p, true, before, after, qualified);
4431 // These use natbib cmd names in LyX
4432 // for inter-citeengine compativility
4433 if (command == "citeyear")
4434 command = "citebyear";
4435 else if (command == "cite*")
4436 command = "citeyear";
4437 else if (command == "textcite")
4439 else if (command == "Textcite")
4441 else if (command == "parencite")
4443 else if (command == "Parencite")
4445 else if (command == "parencite*")
4446 command = "citeyearpar";
4447 else if (command == "smartcite")
4448 command = "footcite";
4449 else if (command == "Smartcite")
4450 command = "Footcite";
4452 string const emptyarg = qualified ? "()" : "[]";
4453 if (before.empty() && after == emptyarg)
4456 else if (before == emptyarg && after == emptyarg) {
4457 // avoid \cite[][]{a}
4461 bool literal = false;
4462 pair<bool, string> aft;
4463 pair<bool, string> bef;
4464 // remove the brackets around after and before
4465 if (!after.empty()) {
4467 after.erase(after.length() - 1, 1);
4468 aft = convert_latexed_command_inset_arg(after);
4469 literal = !aft.first;
4470 after = literal ? subst(after, "\n", " ") : aft.second;
4472 if (!before.empty()) {
4474 before.erase(before.length() - 1, 1);
4475 bef = convert_latexed_command_inset_arg(before);
4476 literal |= !bef.first;
4477 before = literal ? subst(before, "\n", " ") : bef.second;
4479 string keys, pretextlist, posttextlist;
4481 vector<pair<string, string>> pres, posts, preslit, postslit;
4482 vector<string> lkeys;
4483 // text before the citation
4484 string lbefore, lbeforelit;
4485 // text after the citation
4486 string lafter, lafterlit;
4488 pair<bool, string> laft, lbef;
4490 get_cite_arguments(p, true, lbefore, lafter);
4491 // remove the brackets around after and before
4492 if (!lafter.empty()) {
4494 lafter.erase(lafter.length() - 1, 1);
4495 laft = convert_latexed_command_inset_arg(lafter);
4496 literal |= !laft.first;
4497 lafter = laft.second;
4498 lafterlit = subst(lafter, "\n", " ");
4500 if (!lbefore.empty()) {
4501 lbefore.erase(0, 1);
4502 lbefore.erase(lbefore.length() - 1, 1);
4503 lbef = convert_latexed_command_inset_arg(lbefore);
4504 literal |= !lbef.first;
4505 lbefore = lbef.second;
4506 lbeforelit = subst(lbefore, "\n", " ");
4508 if (lbefore.empty() && lafter == "[]") {
4513 else if (lbefore == "[]" && lafter == "[]") {
4514 // avoid \cite[][]{a}
4520 lkey = p.getArg('{', '}');
4523 pres.push_back(make_pair(lkey, lbefore));
4524 preslit.push_back(make_pair(lkey, lbeforelit));
4525 posts.push_back(make_pair(lkey, lafter));
4526 postslit.push_back(make_pair(lkey, lafterlit));
4527 lkeys.push_back(lkey);
4529 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4534 for (auto const & ptl : pres) {
4535 if (!pretextlist.empty())
4536 pretextlist += '\t';
4537 pretextlist += ptl.first;
4538 if (!ptl.second.empty())
4539 pretextlist += " " + ptl.second;
4541 for (auto const & potl : posts) {
4542 if (!posttextlist.empty())
4543 posttextlist += '\t';
4544 posttextlist += potl.first;
4545 if (!potl.second.empty())
4546 posttextlist += " " + potl.second;
4549 keys = convert_literate_command_inset_arg(p.verbatim_item());
4552 after = subst(after, "\n", " ");
4553 if (!before.empty())
4554 before = subst(after, "\n", " ");
4556 string lit = literal ? "\"true\"" : "\"false\"";
4557 begin_command_inset(os, "citation", command);
4558 os << "after " << '"' << after << '"' << "\n";
4559 os << "before " << '"' << before << '"' << "\n";
4563 if (!pretextlist.empty())
4564 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4565 if (!posttextlist.empty())
4566 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4567 os << "literal " << lit << "\n";
4569 // Need to set the cite engine if biblatex is loaded by
4570 // the document class directly
4571 if (preamble.citeEngine() == "basic")
4572 use_biblatex_natbib ?
4573 preamble.citeEngine("biblatex-natbib")
4574 : preamble.citeEngine("biblatex");
4579 is_known(t.cs(), known_jurabib_commands) &&
4580 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4581 context.check_layout(os);
4582 string command = t.cs();
4583 if (p.next_token().asInput() == "*") {
4587 char argumentOrder = '\0';
4588 vector<string> const options =
4589 preamble.getPackageOptions("jurabib");
4590 if (find(options.begin(), options.end(),
4591 "natbiborder") != options.end())
4592 argumentOrder = 'n';
4593 else if (find(options.begin(), options.end(),
4594 "jurabiborder") != options.end())
4595 argumentOrder = 'j';
4597 // text before the citation
4599 // text after the citation
4601 get_cite_arguments(p, argumentOrder != 'j', before, after);
4603 string const citation = p.verbatim_item();
4604 if (!before.empty() && argumentOrder == '\0') {
4605 cerr << "Warning: Assuming argument order "
4606 "of jurabib version 0.6 for\n'"
4607 << command << before << after << '{'
4608 << citation << "}'.\n"
4609 "Add 'jurabiborder' to the jurabib "
4610 "package options if you used an\n"
4611 "earlier jurabib version." << endl;
4613 bool literal = false;
4614 pair<bool, string> aft;
4615 pair<bool, string> bef;
4616 // remove the brackets around after and before
4617 if (!after.empty()) {
4619 after.erase(after.length() - 1, 1);
4620 aft = convert_latexed_command_inset_arg(after);
4621 literal = !aft.first;
4622 after = literal ? subst(after, "\n", " ") : aft.second;
4624 if (!before.empty()) {
4626 before.erase(before.length() - 1, 1);
4627 bef = convert_latexed_command_inset_arg(before);
4628 literal |= !bef.first;
4629 before = literal ? subst(before, "\n", " ") : bef.second;
4630 if (literal && !after.empty())
4631 after = subst(after, "\n", " ");
4633 string lit = literal ? "\"true\"" : "\"false\"";
4634 begin_command_inset(os, "citation", command);
4635 os << "after " << '"' << after << "\"\n"
4636 << "before " << '"' << before << "\"\n"
4637 << "key " << '"' << citation << "\"\n"
4638 << "literal " << lit << "\n";
4640 // Need to set the cite engine if jurabib is loaded by
4641 // the document class directly
4642 if (preamble.citeEngine() == "basic")
4643 preamble.citeEngine("jurabib");
4647 if (t.cs() == "cite"
4648 || t.cs() == "nocite") {
4649 context.check_layout(os);
4650 string after = p.getArg('[', ']');
4651 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4652 bool const literal = !aft.first;
4653 after = literal ? subst(after, "\n", " ") : aft.second;
4654 string lit = literal ? "\"true\"" : "\"false\"";
4655 string key = convert_literate_command_inset_arg(p.verbatim_item());
4656 // store the case that it is "\nocite{*}" to use it later for
4659 begin_command_inset(os, "citation", t.cs());
4660 os << "after " << '"' << after << "\"\n"
4661 << "key " << '"' << key << "\"\n"
4662 << "literal " << lit << "\n";
4664 } else if (t.cs() == "nocite")
4669 if (t.cs() == "index" ||
4670 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4671 context.check_layout(os);
4672 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4673 p.getArg('[', ']') : "";
4674 string const kind = arg.empty() ? "idx" : arg;
4675 begin_inset(os, "Index ");
4676 os << kind << "\nstatus collapsed\n";
4677 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4680 preamble.registerAutomaticallyLoadedPackage("splitidx");
4684 if (t.cs() == "nomenclature") {
4685 context.check_layout(os);
4686 begin_command_inset(os, "nomenclature", "nomenclature");
4687 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4688 if (!prefix.empty())
4689 os << "prefix " << '"' << prefix << '"' << "\n";
4690 string symbol = p.verbatim_item();
4691 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4692 bool literal = !sym.first;
4693 string description = p.verbatim_item();
4694 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4695 literal |= !desc.first;
4697 symbol = subst(symbol, "\n", " ");
4698 description = subst(description, "\n", " ");
4700 symbol = sym.second;
4701 description = desc.second;
4703 string lit = literal ? "\"true\"" : "\"false\"";
4704 os << "symbol " << '"' << symbol;
4705 os << "\"\ndescription \""
4706 << description << "\"\n"
4707 << "literal " << lit << "\n";
4709 preamble.registerAutomaticallyLoadedPackage("nomencl");
4713 if (t.cs() == "label") {
4714 context.check_layout(os);
4715 begin_command_inset(os, "label", "label");
4717 << convert_literate_command_inset_arg(p.verbatim_item())
4723 if (t.cs() == "lyxmintcaption") {
4724 string const pos = p.getArg('[', ']');
4726 string const caption =
4727 parse_text_snippet(p, FLAG_ITEM, false,
4729 minted_nonfloat_caption = "[t]" + caption;
4731 // We already got the caption at the bottom,
4732 // so simply skip it.
4733 parse_text_snippet(p, FLAG_ITEM, false, context);
4735 eat_whitespace(p, os, context, true);
4739 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4740 context.check_layout(os);
4741 string commandname = t.cs();
4743 if (p.next_token().asInput() == "*") {
4748 begin_command_inset(os, "index_print", commandname);
4749 string const indexname = p.getArg('[', ']');
4751 if (indexname.empty())
4752 os << "type \"idx\"\n";
4754 os << "type \"" << indexname << "\"\n";
4755 os << "literal \"true\"\n";
4758 skip_spaces_braces(p);
4759 preamble.registerAutomaticallyLoadedPackage("makeidx");
4760 if (preamble.use_indices() == "true")
4761 preamble.registerAutomaticallyLoadedPackage("splitidx");
4765 if (t.cs() == "printnomenclature") {
4767 string width_type = "";
4768 context.check_layout(os);
4769 begin_command_inset(os, "nomencl_print", "printnomenclature");
4770 // case of a custom width
4772 width = p.getArg('[', ']');
4773 width = translate_len(width);
4774 width_type = "custom";
4776 // case of no custom width
4777 // the case of no custom width but the width set
4778 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4779 // because the user could have set anything, not only the width
4780 // of the longest label (which would be width_type = "auto")
4781 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4782 if (label.empty() && width_type.empty())
4783 width_type = "none";
4784 os << "set_width \"" << width_type << "\"\n";
4785 if (width_type == "custom")
4786 os << "width \"" << width << '\"';
4788 skip_spaces_braces(p);
4789 preamble.registerAutomaticallyLoadedPackage("nomencl");
4793 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4794 context.check_layout(os);
4795 begin_inset(os, "script ");
4796 os << t.cs().substr(4) << '\n';
4797 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4798 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4800 if (t.cs() == "textsubscript")
4801 preamble.registerAutomaticallyLoadedPackage("subscript");
4805 if ((where = is_known(t.cs(), known_quotes))) {
4806 context.check_layout(os);
4807 begin_inset(os, "Quotes ");
4808 string quotetype = known_coded_quotes[where - known_quotes];
4809 // try to make a smart guess about the side
4810 Token const prev = p.prev_token();
4811 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4812 && prev.character() != '\n' && prev.character() != '~');
4813 quotetype = guessQuoteStyle(quotetype, opening);
4816 // LyX adds {} after the quote, so we have to eat
4817 // spaces here if there are any before a possible
4819 eat_whitespace(p, os, context, false);
4824 if ((where = is_known(t.cs(), known_sizes)) &&
4825 context.new_layout_allowed) {
4826 context.check_layout(os);
4827 TeXFont const oldFont = context.font;
4828 context.font.size = known_coded_sizes[where - known_sizes];
4829 output_font_change(os, oldFont, context.font);
4830 eat_whitespace(p, os, context, false);
4834 if ((where = is_known(t.cs(), known_font_families)) &&
4835 context.new_layout_allowed) {
4836 context.check_layout(os);
4837 TeXFont const oldFont = context.font;
4838 context.font.family =
4839 known_coded_font_families[where - known_font_families];
4840 output_font_change(os, oldFont, context.font);
4841 eat_whitespace(p, os, context, false);
4845 if ((where = is_known(t.cs(), known_font_series)) &&
4846 context.new_layout_allowed) {
4847 context.check_layout(os);
4848 TeXFont const oldFont = context.font;
4849 context.font.series =
4850 known_coded_font_series[where - known_font_series];
4851 output_font_change(os, oldFont, context.font);
4852 eat_whitespace(p, os, context, false);
4856 if ((where = is_known(t.cs(), known_font_shapes)) &&
4857 context.new_layout_allowed) {
4858 context.check_layout(os);
4859 TeXFont const oldFont = context.font;
4860 context.font.shape =
4861 known_coded_font_shapes[where - known_font_shapes];
4862 output_font_change(os, oldFont, context.font);
4863 eat_whitespace(p, os, context, false);
4866 if ((where = is_known(t.cs(), known_old_font_families)) &&
4867 context.new_layout_allowed) {
4868 context.check_layout(os);
4869 TeXFont const oldFont = context.font;
4870 context.font.init();
4871 context.font.size = oldFont.size;
4872 context.font.family =
4873 known_coded_font_families[where - known_old_font_families];
4874 output_font_change(os, oldFont, context.font);
4875 eat_whitespace(p, os, context, false);
4879 if ((where = is_known(t.cs(), known_old_font_series)) &&
4880 context.new_layout_allowed) {
4881 context.check_layout(os);
4882 TeXFont const oldFont = context.font;
4883 context.font.init();
4884 context.font.size = oldFont.size;
4885 context.font.series =
4886 known_coded_font_series[where - known_old_font_series];
4887 output_font_change(os, oldFont, context.font);
4888 eat_whitespace(p, os, context, false);
4892 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4893 context.new_layout_allowed) {
4894 context.check_layout(os);
4895 TeXFont const oldFont = context.font;
4896 context.font.init();
4897 context.font.size = oldFont.size;
4898 context.font.shape =
4899 known_coded_font_shapes[where - known_old_font_shapes];
4900 output_font_change(os, oldFont, context.font);
4901 eat_whitespace(p, os, context, false);
4905 if (t.cs() == "selectlanguage") {
4906 context.check_layout(os);
4907 // save the language for the case that a
4908 // \foreignlanguage is used
4909 context.font.language = babel2lyx(p.verbatim_item());
4910 os << "\n\\lang " << context.font.language << "\n";
4914 if (t.cs() == "foreignlanguage") {
4915 string const lang = babel2lyx(p.verbatim_item());
4916 parse_text_attributes(p, os, FLAG_ITEM, outer,
4918 context.font.language, lang);
4922 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4923 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4924 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4926 // We have to output the whole command if it has an option
4927 // because LyX doesn't support this yet, see bug #8214,
4928 // only if there is a single option specifying a variant, we can handle it.
4930 string langopts = p.getOpt();
4931 // check if the option contains a variant, if yes, extract it
4932 string::size_type pos_var = langopts.find("variant");
4933 string::size_type i = langopts.find(',');
4934 string::size_type k = langopts.find('=', pos_var);
4935 if (pos_var != string::npos && i == string::npos) {
4937 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4938 lang = preamble.polyglossia2lyx(variant);
4939 parse_text_attributes(p, os, FLAG_ITEM, outer,
4941 context.font.language, lang);
4943 output_ert_inset(os, t.asInput() + langopts, context);
4945 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4946 parse_text_attributes(p, os, FLAG_ITEM, outer,
4948 context.font.language, lang);
4953 if (t.cs() == "inputencoding") {
4954 // nothing to write here
4955 string const enc = subst(p.verbatim_item(), "\n", " ");
4956 p.setEncoding(enc, Encoding::inputenc);
4960 if (is_known(t.cs(), known_special_chars) ||
4961 (t.cs() == "protect" &&
4962 p.next_token().cat() == catEscape &&
4963 is_known(p.next_token().cs(), known_special_protect_chars))) {
4964 // LyX sometimes puts a \protect in front, so we have to ignore it
4966 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4967 known_special_chars);
4968 context.check_layout(os);
4969 os << known_coded_special_chars[where - known_special_chars];
4970 skip_spaces_braces(p);
4974 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4975 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4976 p.next_next_token().asInput() == "-") ||
4977 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4978 // LyX sometimes puts a \protect in front, so we have to ignore it
4979 if (t.cs() == "protect")
4981 context.check_layout(os);
4982 if (t.cs() == "nobreakdash")
4983 os << "\\SpecialChar nobreakdash\n";
4985 os << "\\SpecialChar endofsentence\n";
4990 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4991 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4992 || t.cs() == "%" || t.cs() == "-") {
4993 context.check_layout(os);
4995 os << "\\SpecialChar softhyphen\n";
5001 if (t.cs() == "char") {
5002 context.check_layout(os);
5003 if (p.next_token().character() == '`') {
5005 if (p.next_token().cs() == "\"") {
5010 output_ert_inset(os, "\\char`", context);
5013 output_ert_inset(os, "\\char", context);
5018 if (t.cs() == "verb") {
5019 context.check_layout(os);
5020 // set catcodes to verbatim early, just in case.
5021 p.setCatcodes(VERBATIM_CATCODES);
5022 string delim = p.get_token().asInput();
5023 Parser::Arg arg = p.verbatimStuff(delim);
5025 output_ert_inset(os, "\\verb" + delim
5026 + arg.second + delim, context);
5028 cerr << "invalid \\verb command. Skipping" << endl;
5032 // Problem: \= creates a tabstop inside the tabbing environment
5033 // and else an accent. In the latter case we really would want
5034 // \={o} instead of \= o.
5035 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5036 output_ert_inset(os, t.asInput(), context);
5040 if (t.cs() == "\\") {
5041 context.check_layout(os);
5043 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5044 else if (p.next_token().asInput() == "*") {
5046 // getOpt() eats the following space if there
5047 // is no optional argument, but that is OK
5048 // here since it has no effect in the output.
5049 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5052 begin_inset(os, "Newline newline");
5058 if (t.cs() == "newline" ||
5059 (t.cs() == "linebreak" && !p.hasOpt())) {
5060 context.check_layout(os);
5061 begin_inset(os, "Newline ");
5064 skip_spaces_braces(p);
5068 if (t.cs() == "input" || t.cs() == "include"
5069 || t.cs() == "verbatiminput"
5070 || t.cs() == "lstinputlisting"
5071 || t.cs() == "inputminted") {
5072 string name = t.cs();
5073 if (name == "verbatiminput"
5074 && p.next_token().asInput() == "*")
5075 name += p.get_token().asInput();
5076 context.check_layout(os);
5078 bool literal = false;
5079 if (name == "lstinputlisting" && p.hasOpt()) {
5080 lstparams = p.getArg('[', ']');
5081 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5082 literal = !oa.first;
5084 lstparams = subst(lstparams, "\n", " ");
5086 lstparams = oa.second;
5087 } else if (name == "inputminted") {
5088 name = "lstinputlisting";
5089 string const lang = p.getArg('{', '}');
5090 if (lang != "tex") {
5091 string cmd = "\\inputminted{" + lang + "}{";
5092 cmd += p.getArg('{', '}') + "}";
5093 output_ert_inset(os, cmd, context);
5096 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5097 minted_nonfloat_caption.erase(0,3);
5098 // extract label and caption from the already produced LyX code
5099 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5100 string const caption = nfc.front();
5102 vector<string>::iterator it =
5103 find(nfc.begin(), nfc.end(), "LatexCommand label");
5104 if (it != nfc.end()) {
5106 if (it != nfc.end())
5108 label = support::split(label, '"');
5111 minted_nonfloat_caption.clear();
5112 lstparams = "caption=" + caption;
5114 lstparams += ",label=" + label;
5115 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5116 literal = !oa.first;
5118 lstparams = subst(lstparams, "\n", " ");
5120 lstparams = oa.second;
5123 string lit = literal ? "\"true\"" : "\"false\"";
5124 string filename(normalize_filename(p.getArg('{', '}')));
5125 string const path = getMasterFilePath(true);
5126 // We want to preserve relative / absolute filenames,
5127 // therefore path is only used for testing
5128 if ((t.cs() == "include" || t.cs() == "input") &&
5129 !makeAbsPath(filename, path).exists()) {
5130 // The file extension is probably missing.
5131 // Now try to find it out.
5132 string const tex_name =
5133 find_file(filename, path,
5134 known_tex_extensions);
5135 if (!tex_name.empty())
5136 filename = tex_name;
5138 bool external = false;
5140 if (makeAbsPath(filename, path).exists()) {
5141 string const abstexname =
5142 makeAbsPath(filename, path).absFileName();
5143 string const absfigname =
5144 changeExtension(abstexname, ".fig");
5145 fix_child_filename(filename);
5146 string const lyxname = changeExtension(filename,
5147 roundtripMode() ? ".lyx.lyx" : ".lyx");
5148 string const abslyxname = makeAbsPath(
5149 lyxname, getParentFilePath(false)).absFileName();
5151 if (!skipChildren())
5152 external = FileName(absfigname).exists();
5153 if (t.cs() == "input" && !skipChildren()) {
5154 string const ext = getExtension(abstexname);
5156 // Combined PS/LaTeX:
5157 // x.eps, x.pstex_t (old xfig)
5158 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5159 FileName const absepsname(
5160 changeExtension(abstexname, ".eps"));
5161 FileName const abspstexname(
5162 changeExtension(abstexname, ".pstex"));
5163 bool const xfigeps =
5164 (absepsname.exists() ||
5165 abspstexname.exists()) &&
5168 // Combined PDF/LaTeX:
5169 // x.pdf, x.pdftex_t (old xfig)
5170 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5171 FileName const abspdfname(
5172 changeExtension(abstexname, ".pdf"));
5173 bool const xfigpdf =
5174 abspdfname.exists() &&
5175 (ext == "pdftex_t" || ext == "pdf_t");
5179 // Combined PS/PDF/LaTeX:
5180 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5181 string const absbase2(
5182 removeExtension(abstexname) + "_pspdftex");
5183 FileName const abseps2name(
5184 addExtension(absbase2, ".eps"));
5185 FileName const abspdf2name(
5186 addExtension(absbase2, ".pdf"));
5187 bool const xfigboth =
5188 abspdf2name.exists() &&
5189 abseps2name.exists() && ext == "pspdftex";
5191 xfig = xfigpdf || xfigeps || xfigboth;
5192 external = external && xfig;
5195 outname = changeExtension(filename, ".fig");
5196 FileName abssrc(changeExtension(abstexname, ".fig"));
5197 copy_file(abssrc, outname);
5199 // Don't try to convert, the result
5200 // would be full of ERT.
5202 FileName abssrc(abstexname);
5203 copy_file(abssrc, outname);
5204 } else if (t.cs() != "verbatiminput" &&
5206 tex2lyx(abstexname, FileName(abslyxname),
5209 // no need to call copy_file
5210 // tex2lyx creates the file
5213 FileName abssrc(abstexname);
5214 copy_file(abssrc, outname);
5217 cerr << "Warning: Could not find included file '"
5218 << filename << "'." << endl;
5222 begin_inset(os, "External\n");
5223 os << "\ttemplate XFig\n"
5224 << "\tfilename " << outname << '\n';
5225 registerExternalTemplatePackages("XFig");
5227 begin_command_inset(os, "include", name);
5228 outname = subst(outname, "\"", "\\\"");
5229 os << "preview false\n"
5230 "filename \"" << outname << "\"\n";
5231 if (!lstparams.empty())
5232 os << "lstparams \"" << lstparams << "\"\n";
5233 os << "literal " << lit << "\n";
5234 if (t.cs() == "verbatiminput")
5235 preamble.registerAutomaticallyLoadedPackage("verbatim");
5241 if (t.cs() == "bibliographystyle") {
5242 // store new bibliographystyle
5243 bibliographystyle = p.verbatim_item();
5244 // If any other command than \bibliography, \addcontentsline
5245 // and \nocite{*} follows, we need to output the style
5246 // (because it might be used by that command).
5247 // Otherwise, it will automatically be output by LyX.
5250 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5251 if (t2.cat() == catBegin)
5253 if (t2.cat() != catEscape)
5255 if (t2.cs() == "nocite") {
5256 if (p.getArg('{', '}') == "*")
5258 } else if (t2.cs() == "bibliography")
5260 else if (t2.cs() == "phantomsection") {
5264 else if (t2.cs() == "addcontentsline") {
5265 // get the 3 arguments of \addcontentsline
5268 contentslineContent = p.getArg('{', '}');
5269 // if the last argument is not \refname we must output
5270 if (contentslineContent == "\\refname")
5277 output_ert_inset(os,
5278 "\\bibliographystyle{" + bibliographystyle + '}',
5284 if (t.cs() == "phantomsection") {
5285 // we only support this if it occurs between
5286 // \bibliographystyle and \bibliography
5287 if (bibliographystyle.empty())
5288 output_ert_inset(os, "\\phantomsection", context);
5292 if (t.cs() == "addcontentsline") {
5293 context.check_layout(os);
5294 // get the 3 arguments of \addcontentsline
5295 string const one = p.getArg('{', '}');
5296 string const two = p.getArg('{', '}');
5297 string const three = p.getArg('{', '}');
5298 // only if it is a \refname, we support if for the bibtex inset
5299 if (contentslineContent != "\\refname") {
5300 output_ert_inset(os,
5301 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5307 else if (t.cs() == "bibliography") {
5308 context.check_layout(os);
5310 begin_command_inset(os, "bibtex", "bibtex");
5311 if (!btprint.empty()) {
5312 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5313 // clear the string because the next BibTeX inset can be without the
5314 // \nocite{*} option
5317 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5318 // Do we have addcontentsline?
5319 if (contentslineContent == "\\refname") {
5320 BibOpts = "bibtotoc";
5321 // clear string because next BibTeX inset can be without addcontentsline
5322 contentslineContent.clear();
5324 // Do we have a bibliographystyle set?
5325 if (!bibliographystyle.empty()) {
5326 if (BibOpts.empty())
5327 BibOpts = normalize_filename(bibliographystyle);
5329 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5330 // clear it because each bibtex entry has its style
5331 // and we need an empty string to handle \phantomsection
5332 bibliographystyle.clear();
5334 os << "options " << '"' << BibOpts << '"' << "\n";
5335 if (p.getEncoding() != preamble.docencoding) {
5336 Encoding const * const enc = encodings.fromIconvName(
5337 p.getEncoding(), Encoding::inputenc, true);
5339 cerr << "Unknown bib encoding " << p.getEncoding()
5340 << ". Ignoring." << std::endl;
5342 os << "encoding " << '"' << enc->name() << '"' << "\n";
5348 if (t.cs() == "printbibliography") {
5349 context.check_layout(os);
5351 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5352 vector<string> opts = getVectorFromString(bbloptions);
5353 vector<string>::iterator it =
5354 find(opts.begin(), opts.end(), "heading=bibintoc");
5355 if (it != opts.end()) {
5357 BibOpts = "bibtotoc";
5359 bbloptions = getStringFromVector(opts);
5360 begin_command_inset(os, "bibtex", "bibtex");
5361 if (!btprint.empty()) {
5362 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5363 // clear the string because the next BibTeX inset can be without the
5364 // \nocite{*} option
5368 for (auto const & bf : preamble.biblatex_bibliographies) {
5369 if (!bibfiles.empty())
5371 bibfiles += normalize_filename(bf);
5373 if (!bibfiles.empty())
5374 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5375 // Do we have addcontentsline?
5376 if (contentslineContent == "\\refname") {
5377 BibOpts = "bibtotoc";
5378 // clear string because next BibTeX inset can be without addcontentsline
5379 contentslineContent.clear();
5381 os << "options " << '"' << BibOpts << '"' << "\n";
5382 if (!bbloptions.empty())
5383 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5384 if (!preamble.bibencoding.empty()) {
5385 Encoding const * const enc = encodings.fromLaTeXName(
5386 preamble.bibencoding, Encoding::inputenc, true);
5388 cerr << "Unknown bib encoding " << preamble.bibencoding
5389 << ". Ignoring." << std::endl;
5391 os << "encoding " << '"' << enc->name() << '"' << "\n";
5394 for (auto const & bf : preamble.biblatex_encodings) {
5395 if (!bibfileencs.empty())
5396 bibfileencs += "\t";
5399 if (!bibfileencs.empty())
5400 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5402 need_commentbib = false;
5406 if (t.cs() == "bibbysection") {
5407 context.check_layout(os);
5409 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5410 vector<string> opts = getVectorFromString(bbloptions);
5411 vector<string>::iterator it =
5412 find(opts.begin(), opts.end(), "heading=bibintoc");
5413 if (it != opts.end()) {
5415 BibOpts = "bibtotoc";
5417 bbloptions = getStringFromVector(opts);
5418 begin_command_inset(os, "bibtex", "bibtex");
5419 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5421 for (auto const & bf : preamble.biblatex_bibliographies) {
5422 if (!bibfiles.empty())
5424 bibfiles += normalize_filename(bf);
5426 if (!bibfiles.empty())
5427 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5428 os << "options " << '"' << BibOpts << '"' << "\n";
5429 if (!bbloptions.empty())
5430 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5432 need_commentbib = false;
5436 if (t.cs() == "parbox") {
5437 // Test whether this is an outer box of a shaded box
5439 // swallow arguments
5440 while (p.hasOpt()) {
5442 p.skip_spaces(true);
5445 p.skip_spaces(true);
5447 if (p.next_token().cat() == catBegin)
5449 p.skip_spaces(true);
5450 Token to = p.get_token();
5451 bool shaded = false;
5452 if (to.asInput() == "\\begin") {
5453 p.skip_spaces(true);
5454 if (p.getArg('{', '}') == "shaded")
5459 parse_outer_box(p, os, FLAG_ITEM, outer,
5460 context, "parbox", "shaded");
5462 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5463 "", "", t.cs(), "", "");
5467 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5468 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5469 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5470 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5474 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5475 string backgroundcolor;
5476 preamble.registerAutomaticallyLoadedPackage("xcolor");
5477 if (t.cs() == "fcolorbox") {
5478 string const framecolor = p.getArg('{', '}');
5479 backgroundcolor = p.getArg('{', '}');
5480 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5482 backgroundcolor = p.getArg('{', '}');
5483 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5488 // FIXME: due to the compiler limit of "if" nestings
5489 // the code for the alignment was put here
5490 // put them in their own if if this is fixed
5491 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5492 || t.cs() == "shadowsize"
5493 || t.cs() == "raggedleft" || t.cs() == "centering"
5494 || t.cs() == "raggedright") {
5495 if (t.cs() == "fboxrule")
5497 if (t.cs() == "fboxsep")
5499 if (t.cs() == "shadowsize")
5501 if (t.cs() != "raggedleft" && t.cs() != "centering"
5502 && t.cs() != "raggedright") {
5503 p.skip_spaces(true);
5504 while (p.good() && p.next_token().cat() != catSpace
5505 && p.next_token().cat() != catNewline
5506 && p.next_token().cat() != catEscape) {
5507 if (t.cs() == "fboxrule")
5508 fboxrule = fboxrule + p.get_token().asInput();
5509 if (t.cs() == "fboxsep")
5510 fboxsep = fboxsep + p.get_token().asInput();
5511 if (t.cs() == "shadowsize")
5512 shadow_size = shadow_size + p.get_token().asInput();
5515 output_ert_inset(os, t.asInput(), context);
5520 //\framebox() is part of the picture environment and different from \framebox{}
5521 //\framebox{} will be parsed by parse_outer_box
5522 if (t.cs() == "framebox") {
5523 if (p.next_token().character() == '(') {
5524 //the syntax is: \framebox(x,y)[position]{content}
5525 string arg = t.asInput();
5526 arg += p.getFullParentheseArg();
5527 arg += p.getFullOpt();
5528 eat_whitespace(p, os, context, false);
5529 output_ert_inset(os, arg + '{', context);
5530 parse_text(p, os, FLAG_ITEM, outer, context);
5531 output_ert_inset(os, "}", context);
5533 //the syntax is: \framebox[width][position]{content}
5534 string special = p.getFullOpt();
5535 special += p.getOpt();
5536 parse_outer_box(p, os, FLAG_ITEM, outer,
5537 context, t.cs(), special);
5542 //\makebox() is part of the picture environment and different from \makebox{}
5543 //\makebox{} will be parsed by parse_box
5544 if (t.cs() == "makebox") {
5545 if (p.next_token().character() == '(') {
5546 //the syntax is: \makebox(x,y)[position]{content}
5547 string arg = t.asInput();
5548 arg += p.getFullParentheseArg();
5549 arg += p.getFullOpt();
5550 eat_whitespace(p, os, context, false);
5551 output_ert_inset(os, arg + '{', context);
5552 parse_text(p, os, FLAG_ITEM, outer, context);
5553 output_ert_inset(os, "}", context);
5555 //the syntax is: \makebox[width][position]{content}
5556 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5557 "", "", t.cs(), "", "");
5561 if (t.cs() == "smallskip" ||
5562 t.cs() == "medskip" ||
5563 t.cs() == "bigskip" ||
5564 t.cs() == "vfill") {
5565 context.check_layout(os);
5566 begin_inset(os, "VSpace ");
5569 skip_spaces_braces(p);
5573 if ((where = is_known(t.cs(), known_spaces))) {
5574 context.check_layout(os);
5575 begin_inset(os, "space ");
5576 os << '\\' << known_coded_spaces[where - known_spaces]
5579 // LaTeX swallows whitespace after all spaces except
5580 // "\\,". We have to do that here, too, because LyX
5581 // adds "{}" which would make the spaces significant.
5583 eat_whitespace(p, os, context, false);
5584 // LyX adds "{}" after all spaces except "\\ " and
5585 // "\\,", so we have to remove "{}".
5586 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5587 // remove the braces after "\\,", too.
5593 if (t.cs() == "newpage" ||
5594 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5595 t.cs() == "clearpage" ||
5596 t.cs() == "cleardoublepage") {
5597 context.check_layout(os);
5598 begin_inset(os, "Newpage ");
5601 skip_spaces_braces(p);
5605 if (t.cs() == "DeclareRobustCommand" ||
5606 t.cs() == "DeclareRobustCommandx" ||
5607 t.cs() == "newcommand" ||
5608 t.cs() == "newcommandx" ||
5609 t.cs() == "providecommand" ||
5610 t.cs() == "providecommandx" ||
5611 t.cs() == "renewcommand" ||
5612 t.cs() == "renewcommandx") {
5613 // DeclareRobustCommand, DeclareRobustCommandx,
5614 // providecommand and providecommandx could be handled
5615 // by parse_command(), but we need to call
5616 // add_known_command() here.
5617 string name = t.asInput();
5618 if (p.next_token().asInput() == "*") {
5619 // Starred form. Eat '*'
5623 string const command = p.verbatim_item();
5624 string const opt1 = p.getFullOpt();
5625 string const opt2 = p.getFullOpt();
5626 add_known_command(command, opt1, !opt2.empty());
5627 string const ert = name + '{' + command + '}' +
5629 '{' + p.verbatim_item() + '}';
5631 if (t.cs() == "DeclareRobustCommand" ||
5632 t.cs() == "DeclareRobustCommandx" ||
5633 t.cs() == "providecommand" ||
5634 t.cs() == "providecommandx" ||
5635 name[name.length()-1] == '*')
5636 output_ert_inset(os, ert, context);
5638 context.check_layout(os);
5639 begin_inset(os, "FormulaMacro");
5646 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5647 // let could be handled by parse_command(),
5648 // but we need to call add_known_command() here.
5649 string ert = t.asInput();
5652 if (p.next_token().cat() == catBegin) {
5653 name = p.verbatim_item();
5654 ert += '{' + name + '}';
5656 name = p.verbatim_item();
5661 if (p.next_token().cat() == catBegin) {
5662 command = p.verbatim_item();
5663 ert += '{' + command + '}';
5665 command = p.verbatim_item();
5668 // If command is known, make name known too, to parse
5669 // its arguments correctly. For this reason we also
5670 // have commands in syntax.default that are hardcoded.
5671 CommandMap::iterator it = known_commands.find(command);
5672 if (it != known_commands.end())
5673 known_commands[t.asInput()] = it->second;
5674 output_ert_inset(os, ert, context);
5678 if (t.cs() == "hspace" || t.cs() == "vspace") {
5681 string name = t.asInput();
5682 string const length = p.verbatim_item();
5685 bool valid = splitLatexLength(length, valstring, unit);
5686 bool known_hspace = false;
5687 bool known_vspace = false;
5688 bool known_unit = false;
5691 istringstream iss(valstring);
5694 if (t.cs()[0] == 'h') {
5695 if (unit == "\\fill") {
5700 known_hspace = true;
5703 if (unit == "\\smallskipamount") {
5705 known_vspace = true;
5706 } else if (unit == "\\medskipamount") {
5708 known_vspace = true;
5709 } else if (unit == "\\bigskipamount") {
5711 known_vspace = true;
5712 } else if (length == "\\baselineskip") {
5714 known_vspace = true;
5715 } else if (unit == "\\fill") {
5717 known_vspace = true;
5721 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5723 known_vspace = true;
5725 if (!known_hspace && !known_vspace) {
5726 switch (unitFromString(unit)) {
5742 //unitFromString(unit) fails for relative units like Length::PCW
5743 // therefore handle them separately
5744 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5745 || unit == "\\textwidth" || unit == "\\linewidth"
5746 || unit == "\\textheight" || unit == "\\paperheight"
5747 || unit == "\\baselineskip")
5755 // check for glue lengths
5756 bool is_gluelength = false;
5757 string gluelength = length;
5758 string::size_type i = length.find(" minus");
5759 if (i == string::npos) {
5760 i = length.find(" plus");
5761 if (i != string::npos)
5762 is_gluelength = true;
5764 is_gluelength = true;
5765 // if yes transform "9xx minus 8yy plus 7zz"
5767 if (is_gluelength) {
5768 i = gluelength.find(" minus");
5769 if (i != string::npos)
5770 gluelength.replace(i, 7, "-");
5771 i = gluelength.find(" plus");
5772 if (i != string::npos)
5773 gluelength.replace(i, 6, "+");
5776 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5777 // Literal horizontal length or known variable
5778 context.check_layout(os);
5779 begin_inset(os, "space ");
5787 if (known_unit && !known_hspace)
5788 os << "\n\\length " << translate_len(length);
5790 os << "\n\\length " << gluelength;
5792 } else if (known_unit || known_vspace || is_gluelength) {
5793 // Literal vertical length or known variable
5794 context.check_layout(os);
5795 begin_inset(os, "VSpace ");
5798 if (known_unit && !known_vspace)
5799 os << translate_len(length);
5806 // LyX can't handle other length variables in Inset VSpace/space
5811 output_ert_inset(os, name + '{' + unit + '}', context);
5812 else if (value == -1.0)
5813 output_ert_inset(os, name + "{-" + unit + '}', context);
5815 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5817 output_ert_inset(os, name + '{' + length + '}', context);
5822 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5823 // might be one or several options or a star.
5824 // The single '=' is meant here.
5825 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5829 context.check_layout(os);
5830 // store the latexparam here. This is eaten in parse_text_in_inset
5831 context.latexparam = newinsetlayout->latexparam();
5832 docstring name = newinsetlayout->name();
5833 bool const caption = name.find(from_ascii("Caption:")) == 0;
5835 // Already done for floating minted listings.
5836 if (minted_float.empty()) {
5837 begin_inset(os, "Caption ");
5838 os << to_utf8(name.substr(8)) << '\n';
5841 // FIXME: what do we do if the prefix is not Flex: ?
5842 if (prefixIs(name, from_ascii("Flex:")))
5844 begin_inset(os, "Flex ");
5845 os << to_utf8(name) << '\n'
5846 << "status collapsed\n";
5848 if (!minted_float.empty()) {
5849 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5850 } else if (newinsetlayout->isPassThru()) {
5851 // set catcodes to verbatim early, just in case.
5852 p.setCatcodes(VERBATIM_CATCODES);
5853 string delim = p.get_token().asInput();
5855 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5856 //FIXME: handle error condition
5857 string const arg = p.verbatimStuff("}").second;
5858 Context newcontext(true, context.textclass);
5859 if (newinsetlayout->forcePlainLayout())
5860 newcontext.layout = &context.textclass.plainLayout();
5861 output_ert(os, arg, newcontext);
5863 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5864 context.latexparam.clear();
5867 // Minted caption insets are not closed here because
5868 // we collect everything into the caption.
5869 if (minted_float.empty())
5874 // The single '=' is meant here.
5875 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5879 context.check_layout(os);
5880 docstring name = newinsetlayout->name();
5881 bool const caption = name.find(from_ascii("Caption:")) == 0;
5883 // Already done for floating minted listings.
5884 if (minted_float.empty()) {
5885 begin_inset(os, "Caption ");
5886 os << to_utf8(name.substr(8)) << '\n';
5889 // FIXME: what do we do if the prefix is not Flex: ?
5890 if (prefixIs(name, from_ascii("Flex:")))
5892 begin_inset(os, "Flex ");
5893 os << to_utf8(name) << '\n'
5894 << "status collapsed\n";
5896 if (!minted_float.empty()) {
5897 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5898 } else if (newinsetlayout->isPassThru()) {
5899 // set catcodes to verbatim early, just in case.
5900 p.setCatcodes(VERBATIM_CATCODES);
5901 string delim = p.get_token().asInput();
5903 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5904 //FIXME: handle error condition
5905 string const arg = p.verbatimStuff("}").second;
5906 Context newcontext(true, context.textclass);
5907 if (newinsetlayout->forcePlainLayout())
5908 newcontext.layout = &context.textclass.plainLayout();
5909 output_ert(os, arg, newcontext);
5911 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5914 // Minted caption insets are not closed here because
5915 // we collect everything into the caption.
5916 if (minted_float.empty())
5921 if (t.cs() == "includepdf") {
5923 string const arg = p.getArg('[', ']');
5924 map<string, string> opts;
5925 vector<string> keys;
5926 split_map(arg, opts, keys);
5927 string name = normalize_filename(p.verbatim_item());
5928 string const path = getMasterFilePath(true);
5929 // We want to preserve relative / absolute filenames,
5930 // therefore path is only used for testing
5931 if (!makeAbsPath(name, path).exists()) {
5932 // The file extension is probably missing.
5933 // Now try to find it out.
5934 char const * const pdfpages_format[] = {"pdf", 0};
5935 string const pdftex_name =
5936 find_file(name, path, pdfpages_format);
5937 if (!pdftex_name.empty()) {
5942 FileName const absname = makeAbsPath(name, path);
5943 if (absname.exists())
5945 fix_child_filename(name);
5946 copy_file(absname, name);
5948 cerr << "Warning: Could not find file '"
5949 << name << "'." << endl;
5951 context.check_layout(os);
5952 begin_inset(os, "External\n\ttemplate ");
5953 os << "PDFPages\n\tfilename "
5955 // parse the options
5956 if (opts.find("pages") != opts.end())
5957 os << "\textra LaTeX \"pages="
5958 << opts["pages"] << "\"\n";
5959 if (opts.find("angle") != opts.end())
5960 os << "\trotateAngle "
5961 << opts["angle"] << '\n';
5962 if (opts.find("origin") != opts.end()) {
5964 string const opt = opts["origin"];
5965 if (opt == "tl") ss << "topleft";
5966 if (opt == "bl") ss << "bottomleft";
5967 if (opt == "Bl") ss << "baselineleft";
5968 if (opt == "c") ss << "center";
5969 if (opt == "tc") ss << "topcenter";
5970 if (opt == "bc") ss << "bottomcenter";
5971 if (opt == "Bc") ss << "baselinecenter";
5972 if (opt == "tr") ss << "topright";
5973 if (opt == "br") ss << "bottomright";
5974 if (opt == "Br") ss << "baselineright";
5975 if (!ss.str().empty())
5976 os << "\trotateOrigin " << ss.str() << '\n';
5978 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5980 if (opts.find("width") != opts.end())
5982 << translate_len(opts["width"]) << '\n';
5983 if (opts.find("height") != opts.end())
5985 << translate_len(opts["height"]) << '\n';
5986 if (opts.find("keepaspectratio") != opts.end())
5987 os << "\tkeepAspectRatio\n";
5989 context.check_layout(os);
5990 registerExternalTemplatePackages("PDFPages");
5994 if (t.cs() == "loadgame") {
5996 string name = normalize_filename(p.verbatim_item());
5997 string const path = getMasterFilePath(true);
5998 // We want to preserve relative / absolute filenames,
5999 // therefore path is only used for testing
6000 if (!makeAbsPath(name, path).exists()) {
6001 // The file extension is probably missing.
6002 // Now try to find it out.
6003 char const * const lyxskak_format[] = {"fen", 0};
6004 string const lyxskak_name =
6005 find_file(name, path, lyxskak_format);
6006 if (!lyxskak_name.empty())
6007 name = lyxskak_name;
6009 FileName const absname = makeAbsPath(name, path);
6010 if (absname.exists())
6012 fix_child_filename(name);
6013 copy_file(absname, name);
6015 cerr << "Warning: Could not find file '"
6016 << name << "'." << endl;
6017 context.check_layout(os);
6018 begin_inset(os, "External\n\ttemplate ");
6019 os << "ChessDiagram\n\tfilename "
6022 context.check_layout(os);
6023 // after a \loadgame follows a \showboard
6024 if (p.get_token().asInput() == "showboard")
6026 registerExternalTemplatePackages("ChessDiagram");
6030 // try to see whether the string is in unicodesymbols
6031 // Only use text mode commands, since we are in text mode here,
6032 // and math commands may be invalid (bug 6797)
6033 string name = t.asInput();
6034 // handle the dingbats, cyrillic and greek
6035 if (name == "\\textcyr")
6036 name = "\\textcyrillic";
6037 if (name == "\\ding" || name == "\\textcyrillic" ||
6038 (name == "\\textgreek" && !preamble.usePolyglossia()))
6039 name = name + '{' + p.getArg('{', '}') + '}';
6040 // handle the ifsym characters
6041 else if (name == "\\textifsymbol") {
6042 string const optif = p.getFullOpt();
6043 string const argif = p.getArg('{', '}');
6044 name = name + optif + '{' + argif + '}';
6046 // handle the \ascii characters
6047 // the case of \ascii within braces, as LyX outputs it, is already
6048 // handled for t.cat() == catBegin
6049 else if (name == "\\ascii") {
6050 // the code is "\asci\xxx"
6051 name = "{" + name + p.get_token().asInput() + "}";
6054 // handle some TIPA special characters
6055 else if (preamble.isPackageUsed("tipa")) {
6056 if (name == "\\s") {
6057 // fromLaTeXCommand() does not yet
6058 // recognize tipa short cuts
6059 name = "\\textsyllabic";
6060 } else if (name == "\\=" &&
6061 p.next_token().asInput() == "*") {
6062 // fromLaTeXCommand() does not yet
6063 // recognize tipa short cuts
6065 name = "\\textsubbar";
6066 } else if (name == "\\textdoublevertline") {
6067 // FIXME: This is not correct,
6068 // \textvertline is higher than \textbardbl
6069 name = "\\textbardbl";
6071 } else if (name == "\\!" ) {
6072 if (p.next_token().asInput() == "b") {
6073 p.get_token(); // eat 'b'
6076 } else if (p.next_token().asInput() == "d") {
6080 } else if (p.next_token().asInput() == "g") {
6084 } else if (p.next_token().asInput() == "G") {
6086 name = "\\texthtscg";
6088 } else if (p.next_token().asInput() == "j") {
6090 name = "\\texthtbardotlessj";
6092 } else if (p.next_token().asInput() == "o") {
6094 name = "\\textbullseye";
6097 } else if (name == "\\*" ) {
6098 if (p.next_token().asInput() == "k") {
6100 name = "\\textturnk";
6102 } else if (p.next_token().asInput() == "r") {
6103 p.get_token(); // eat 'b'
6104 name = "\\textturnr";
6106 } else if (p.next_token().asInput() == "t") {
6108 name = "\\textturnt";
6110 } else if (p.next_token().asInput() == "w") {
6112 name = "\\textturnw";
6117 if ((name.size() == 2 &&
6118 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6119 p.next_token().asInput() != "*") ||
6120 is_known(name.substr(1), known_tipa_marks)) {
6121 // name is a command that corresponds to a
6122 // combining character in unicodesymbols.
6123 // Append the argument, fromLaTeXCommand()
6124 // will either convert it to a single
6125 // character or a combining sequence.
6126 name += '{' + p.verbatim_item() + '}';
6128 // now get the character from unicodesymbols
6132 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6133 Encodings::TEXT_CMD, termination, rem, &req));
6135 context.check_layout(os);
6138 output_ert_inset(os, to_utf8(rem), context);
6140 skip_spaces_braces(p);
6141 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6142 preamble.registerAutomaticallyLoadedPackage(*it);
6144 //cerr << "#: " << t << " mode: " << mode << endl;
6145 // heuristic: read up to next non-nested space
6147 string s = t.asInput();
6148 string z = p.verbatim_item();
6149 while (p.good() && z != " " && !z.empty()) {
6150 //cerr << "read: " << z << endl;
6152 z = p.verbatim_item();
6154 cerr << "found ERT: " << s << endl;
6155 output_ert_inset(os, s + ' ', context);
6158 if (t.asInput() == name &&
6159 p.next_token().asInput() == "*") {
6160 // Starred commands like \vspace*{}
6161 p.get_token(); // Eat '*'
6164 if (!parse_command(name, p, os, outer, context)) {
6165 output_ert_inset(os, name, context);
6166 // Try to handle options of unknown commands:
6167 // Look if we have optional arguments,
6168 // and if so, put the brackets in ERT.
6169 while (p.hasOpt()) {
6170 p.get_token(); // eat '['
6171 output_ert_inset(os, "[", context);
6172 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6173 output_ert_inset(os, "]", context);
6181 string guessLanguage(Parser & p, string const & lang)
6183 typedef std::map<std::string, size_t> LangMap;
6184 // map from language names to number of characters
6187 for (char const * const * i = supported_CJK_languages; *i; i++)
6188 used[string(*i)] = 0;
6191 Token const t = p.get_token();
6192 // comments are not counted for any language
6193 if (t.cat() == catComment)
6195 // commands are not counted as well, but we need to detect
6196 // \begin{CJK} and switch encoding if needed
6197 if (t.cat() == catEscape) {
6198 if (t.cs() == "inputencoding") {
6199 string const enc = subst(p.verbatim_item(), "\n", " ");
6200 p.setEncoding(enc, Encoding::inputenc);
6203 if (t.cs() != "begin")
6206 // Non-CJK content is counted for lang.
6207 // We do not care about the real language here:
6208 // If we have more non-CJK contents than CJK contents,
6209 // we simply use the language that was specified as
6210 // babel main language.
6211 used[lang] += t.asInput().length();
6214 // Now we are starting an environment
6216 string const name = p.getArg('{', '}');
6217 if (name != "CJK") {
6221 // It is a CJK environment
6223 /* name = */ p.getArg('{', '}');
6224 string const encoding = p.getArg('{', '}');
6225 /* mapping = */ p.getArg('{', '}');
6226 string const encoding_old = p.getEncoding();
6227 char const * const * const where =
6228 is_known(encoding, supported_CJK_encodings);
6230 p.setEncoding(encoding, Encoding::CJK);
6232 p.setEncoding("UTF-8");
6233 string const text = p.ertEnvironment("CJK");
6234 p.setEncoding(encoding_old);
6237 // ignore contents in unknown CJK encoding
6240 // the language of the text
6242 supported_CJK_languages[where - supported_CJK_encodings];
6243 used[cjk] += text.length();
6245 LangMap::const_iterator use = used.begin();
6246 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6247 if (it->second > use->second)
6254 void check_comment_bib(ostream & os, Context & context)
6256 if (!need_commentbib)
6258 // We have a bibliography database, but no bibliography with biblatex
6259 // which is completely valid. Insert a bibtex inset in a note.
6260 context.check_layout(os);
6261 begin_inset(os, "Note Note\n");
6262 os << "status open\n";
6263 os << "\\begin_layout Plain Layout\n";
6264 begin_command_inset(os, "bibtex", "bibtex");
6266 for (auto const & bf : preamble.biblatex_bibliographies) {
6267 if (!bibfiles.empty())
6269 bibfiles += normalize_filename(bf);
6271 if (!bibfiles.empty())
6272 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6274 for (auto const & bf : preamble.biblatex_encodings) {
6275 if (!bibfileencs.empty())
6276 bibfileencs += "\t";
6279 if (!bibfileencs.empty())
6280 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6281 end_inset(os);// Bibtex
6282 os << "\\end_layout\n";
6283 end_inset(os);// Note