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"
26 #include "insets/ExternalTemplate.h"
28 #include "support/lassert.h"
29 #include "support/convert.h"
30 #include "support/FileName.h"
31 #include "support/filetools.h"
32 #include "support/Length.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, const 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,
58 string const & rdelim)
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 const & 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() == "hungarian")
486 else if (preamble.quotesStyle() == "swedish")
487 res = opening ? "sld" : "srd";
488 } else if (in == "els") {// `
489 if (preamble.quotesStyle() == "german")
491 else if (preamble.quotesStyle() == "british")
493 } else if (in == "ers") {// '
494 if (preamble.quotesStyle() == "polish")
496 else if (preamble.quotesStyle() == "british")
498 else if (preamble.quotesStyle() == "swedish")
499 res = opening ? "sls" : "srs";
500 } else if (in == "ard") {// >>
501 if (preamble.quotesStyle() == "swiss")
503 else if (preamble.quotesStyle() == "french")
505 else if (preamble.quotesStyle() == "russian")
507 else if (preamble.quotesStyle() == "hungarian")
509 } else if (in == "ald") {// <<
510 if (preamble.quotesStyle() == "swiss")
512 else if (preamble.quotesStyle() == "french")
514 else if (preamble.quotesStyle() == "russian")
516 else if (preamble.quotesStyle() == "hungarian")
518 } else if (in == "ars") {// >
519 if (preamble.quotesStyle() == "swiss")
521 } else if (in == "als") {// <
522 if (preamble.quotesStyle() == "swiss")
524 } else if (in == "gld") {// ,,
525 if (preamble.quotesStyle() == "polish")
527 else if (preamble.quotesStyle() == "hungarian")
529 else if (preamble.quotesStyle() == "russian")
531 } else if (in == "gls") {// ,
532 if (preamble.quotesStyle() == "polish")
539 string const fromPolyglossiaEnvironment(string const & s)
541 // Since \arabic is taken by the LaTeX kernel,
542 // the Arabic polyglossia environment is upcased
550 string uncapitalize(string const & s)
552 docstring in = from_ascii(s);
553 char_type t = lowercase(s[0]);
559 bool isCapitalized(string const & s)
561 docstring in = from_ascii(s);
562 char_type t = uppercase(s[0]);
564 return to_ascii(in) == s;
571 string translate_len(string const & length)
575 if (translate_len(length, value, unit))
577 // If the input is invalid, return what we have.
585 * Translates a LaTeX length into \p value, \p unit and
586 * \p special parts suitable for a box inset.
587 * The difference from translate_len() is that a box inset knows about
588 * some special "units" that are stored in \p special.
590 void translate_box_len(string const & length, string & value, string & unit, string & special)
592 if (translate_len(length, value, unit)) {
593 if (unit == "\\height" || unit == "\\depth" ||
594 unit == "\\totalheight" || unit == "\\width") {
595 special = unit.substr(1);
596 // The unit is not used, but LyX requires a dummy setting
608 void begin_inset(ostream & os, string const & name)
610 os << "\n\\begin_inset " << name;
614 void begin_command_inset(ostream & os, string const & name,
615 string const & latexname)
617 begin_inset(os, "CommandInset ");
618 os << name << "\nLatexCommand " << latexname << '\n';
622 void end_inset(ostream & os)
624 os << "\n\\end_inset\n\n";
628 bool skip_braces(Parser & p)
630 if (p.next_token().cat() != catBegin)
633 if (p.next_token().cat() == catEnd) {
642 /// replace LaTeX commands in \p s from the unicodesymbols file with their
644 pair<bool, docstring> convert_unicodesymbols(docstring s)
648 for (size_t i = 0; i < s.size();) {
657 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
658 Encodings::TEXT_CMD, termination, rem, &req));
659 set<string>::const_iterator it = req.begin();
660 set<string>::const_iterator en = req.end();
661 for (; it != en; ++it)
662 preamble.registerAutomaticallyLoadedPackage(*it);
665 if (s.empty() || s[0] != '\\')
669 for (auto const & c : known_escaped_chars)
670 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
675 return make_pair(res, os.str());
679 /// try to convert \p s to a valid InsetCommand argument
680 /// return whether this succeeded. If not, these command insets
681 /// get the "literate" flag.
682 pair<bool, string> convert_latexed_command_inset_arg(string s)
684 bool success = false;
686 // since we don't know the input encoding we can't use from_utf8
687 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
689 s = to_utf8(res.second);
691 // LyX cannot handle newlines in a latex command
692 return make_pair(success, subst(s, "\n", " "));
695 /// try to convert \p s to a valid InsetCommand argument
696 /// without trying to recode macros.
697 string convert_literate_command_inset_arg(string const & s)
699 // LyX cannot handle newlines in a latex command
700 return subst(s, "\n", " ");
703 void output_ert(ostream & os, string const & s, Context & context)
705 context.check_layout(os);
706 for (char const c : s) {
708 os << "\n\\backslash\n";
709 else if (c == '\n') {
710 context.new_paragraph(os);
711 context.check_layout(os);
715 context.check_end_layout(os);
719 void output_ert_inset(ostream & os, string const & s, Context & context)
721 // We must have a valid layout before outputting the ERT inset.
722 context.check_layout(os);
723 Context newcontext(true, context.textclass);
724 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
725 if (layout.forcePlainLayout())
726 newcontext.layout = &context.textclass.plainLayout();
727 begin_inset(os, "ERT");
728 os << "\nstatus collapsed\n";
729 output_ert(os, s, newcontext);
734 void output_comment(Parser & p, ostream & os, string const & s,
737 if (p.next_token().cat() == catNewline)
738 output_ert_inset(os, '%' + s, context);
740 output_ert_inset(os, '%' + s + '\n', context);
744 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
745 string const & latexparam = string())
747 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
750 if (checkModule(name, command))
751 return findLayoutWithoutModule(textclass, name, command, latexparam);
756 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
757 string const & latexparam = string())
759 InsetLayout const * insetlayout =
760 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
763 if (checkModule(name, command))
764 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
769 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
770 bool eatNewline = true);
774 * Skips whitespace and braces.
775 * This should be called after a command has been parsed that is not put into
776 * ERT, and where LyX adds "{}" if needed.
778 void skip_spaces_braces(Parser & p, bool keepws = false)
780 /* The following four examples produce the same typeset output and
781 should be handled by this function:
789 // Unfortunately we need to skip comments, too.
790 // We can't use eat_whitespace since writing them after the {}
791 // results in different output in some cases.
792 bool const skipped_spaces = p.skip_spaces(true);
793 bool const skipped_braces = skip_braces(p);
794 if (keepws && skipped_spaces && !skipped_braces)
795 // put back the space (it is better handled by check_space)
796 p.unskip_spaces(true);
800 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
801 Context & context, Layout::LaTeXArgMap const & latexargs)
803 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
805 context.check_layout(os);
811 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
812 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
813 for (; lait != laend; ++lait) {
815 eat_whitespace(p, os, context, false);
816 if (lait->second.mandatory) {
817 if (p.next_token().cat() != catBegin)
819 string ldelim = to_utf8(lait->second.ldelim);
820 string rdelim = to_utf8(lait->second.rdelim);
825 p.get_token(); // eat ldelim
826 if (ldelim.size() > 1)
827 p.get_token(); // eat ldelim
829 context.check_layout(os);
832 begin_inset(os, "Argument ");
835 os << i << "\nstatus collapsed\n\n";
836 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
839 string ldelim = to_utf8(lait->second.ldelim);
840 string rdelim = to_utf8(lait->second.rdelim);
845 string tok = p.next_token().asInput();
846 // we only support delimiters with max 2 chars for now.
847 if (ldelim.size() > 1)
848 tok += p.next_next_token().asInput();
849 if (p.next_token().cat() == catEscape || tok != ldelim)
851 p.get_token(); // eat ldelim
852 if (ldelim.size() > 1)
853 p.get_token(); // eat ldelim
855 context.check_layout(os);
858 begin_inset(os, "Argument ");
861 os << i << "\nstatus collapsed\n\n";
862 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
865 eat_whitespace(p, os, context, false);
870 void output_command_layout(ostream & os, Parser & p, bool outer,
871 Context & parent_context,
872 Layout const * newlayout)
874 TeXFont const oldFont = parent_context.font;
875 // save the current font size
876 string const size = oldFont.size;
877 // reset the font size to default, because the font size switches
878 // don't affect section headings and the like
879 parent_context.font.size = Context::normalfont.size;
880 // we only need to write the font change if we have an open layout
881 if (!parent_context.atParagraphStart())
882 output_font_change(os, oldFont, parent_context.font);
883 parent_context.check_end_layout(os);
884 Context context(true, parent_context.textclass, newlayout,
885 parent_context.layout, parent_context.font);
886 if (parent_context.deeper_paragraph) {
887 // We are beginning a nested environment after a
888 // deeper paragraph inside the outer list environment.
889 // Therefore we don't need to output a "begin deeper".
890 context.need_end_deeper = true;
892 context.check_deeper(os);
893 output_arguments(os, p, outer, true, string(), context,
894 context.layout->latexargs());
895 // If we have a latex param, we eat it here.
896 if (!parent_context.latexparam.empty()) {
898 Context dummy(true, parent_context.textclass);
899 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
900 string(1, parent_context.latexparam.back()));
902 parse_text(p, os, FLAG_ITEM, outer, context);
903 output_arguments(os, p, outer, false, "post", context,
904 context.layout->postcommandargs());
905 context.check_end_layout(os);
906 if (parent_context.deeper_paragraph) {
907 // We must suppress the "end deeper" because we
908 // suppressed the "begin deeper" above.
909 context.need_end_deeper = false;
911 context.check_end_deeper(os);
912 // We don't need really a new paragraph, but
913 // we must make sure that the next item gets a \begin_layout.
914 parent_context.new_paragraph(os);
915 // Set the font size to the original value. No need to output it here
916 // (Context::begin_layout() will do that if needed)
917 parent_context.font.size = size;
922 * Output a space if necessary.
923 * This function gets called for every whitespace token.
925 * We have three cases here:
926 * 1. A space must be suppressed. Example: The lyxcode case below
927 * 2. A space may be suppressed. Example: Spaces before "\par"
928 * 3. A space must not be suppressed. Example: A space between two words
930 * We currently handle only 1. and 3 and from 2. only the case of
931 * spaces before newlines as a side effect.
933 * 2. could be used to suppress as many spaces as possible. This has two effects:
934 * - Reimporting LyX generated LaTeX files changes almost no whitespace
935 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
936 * The drawback is that the logic inside the function becomes
937 * complicated, and that is the reason why it is not implemented.
939 void check_space(Parser & p, ostream & os, Context & context)
941 Token const next = p.next_token();
942 Token const curr = p.curr_token();
943 // A space before a single newline and vice versa must be ignored
944 // LyX emits a newline before \end{lyxcode}.
945 // This newline must be ignored,
946 // otherwise LyX will add an additional protected space.
947 if (next.cat() == catSpace ||
948 next.cat() == catNewline ||
949 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
952 context.check_layout(os);
958 * Parse all arguments of \p command
960 void parse_arguments(string const & command,
961 vector<ArgumentType> const & template_arguments,
962 Parser & p, ostream & os, bool outer, Context & context)
964 string ert = command;
965 size_t no_arguments = template_arguments.size();
966 for (size_t i = 0; i < no_arguments; ++i) {
967 switch (template_arguments[i]) {
970 // This argument contains regular LaTeX
971 output_ert_inset(os, ert + '{', context);
972 eat_whitespace(p, os, context, false);
973 if (template_arguments[i] == required)
974 parse_text(p, os, FLAG_ITEM, outer, context);
976 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
980 // This argument consists only of a single item.
981 // The presence of '{' or not must be preserved.
983 if (p.next_token().cat() == catBegin)
984 ert += '{' + p.verbatim_item() + '}';
986 ert += p.verbatim_item();
990 // This argument may contain special characters
991 ert += '{' + p.verbatim_item() + '}';
995 // true because we must not eat whitespace
996 // if an optional arg follows we must not strip the
997 // brackets from this one
998 if (i < no_arguments - 1 &&
999 template_arguments[i+1] == optional)
1000 ert += p.getFullOpt(true);
1002 ert += p.getOpt(true);
1006 output_ert_inset(os, ert, context);
1011 * Check whether \p command is a known command. If yes,
1012 * handle the command with all arguments.
1013 * \return true if the command was parsed, false otherwise.
1015 bool parse_command(string const & command, Parser & p, ostream & os,
1016 bool outer, Context & context)
1018 if (known_commands.find(command) != known_commands.end()) {
1019 parse_arguments(command, known_commands[command], p, os,
1027 /// Parses a minipage or parbox
1028 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1029 unsigned inner_flags, bool outer, Context & parent_context,
1030 string const & outer_type, string const & special,
1031 string inner_type, string const & frame_color,
1032 string const & background_color)
1036 string hor_pos = "l";
1037 // We need to set the height to the LaTeX default of 1\\totalheight
1038 // for the case when no height argument is given
1039 string height_value = "1";
1040 string height_unit = "in";
1041 string height_special = "totalheight";
1042 string latex_height;
1046 string width_special = "none";
1047 string thickness = "0.4pt";
1048 if (!fboxrule.empty())
1049 thickness = fboxrule;
1051 thickness = "0.4pt";
1053 if (!fboxsep.empty())
1054 separation = fboxsep;
1058 if (!shadow_size.empty())
1059 shadowsize = shadow_size;
1062 string framecolor = "black";
1063 string backgroundcolor = "none";
1064 if (!frame_color.empty())
1065 framecolor = frame_color;
1066 if (!background_color.empty())
1067 backgroundcolor = background_color;
1068 // if there is a color box around the \begin statements have not yet been parsed
1070 if (!frame_color.empty() || !background_color.empty()) {
1071 eat_whitespace(p, os, parent_context, false);
1072 p.get_token().asInput(); // the '{'
1074 if (p.next_token().asInput() == "\\begin") {
1075 p.get_token().asInput();
1077 inner_type = "minipage";
1078 inner_flags = FLAG_END;
1079 active_environments.push_back("minipage");
1082 else if (p.next_token().asInput() == "\\parbox") {
1083 p.get_token().asInput();
1084 inner_type = "parbox";
1085 inner_flags = FLAG_ITEM;
1088 else if (p.next_token().asInput() == "\\makebox") {
1089 p.get_token().asInput();
1090 inner_type = "makebox";
1091 inner_flags = FLAG_ITEM;
1093 // in case there is just \colorbox{color}{text}
1096 inner_type = "makebox";
1097 inner_flags = FLAG_BRACE_LAST;
1102 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1104 if (!inner_type.empty() && p.hasOpt()) {
1105 if (inner_type != "makebox")
1106 position = p.getArg('[', ']');
1108 latex_width = p.getArg('[', ']');
1109 translate_box_len(latex_width, width_value, width_unit, width_special);
1112 if (position != "t" && position != "c" && position != "b") {
1113 cerr << "invalid position " << position << " for "
1114 << inner_type << endl;
1118 if (inner_type != "makebox") {
1119 latex_height = p.getArg('[', ']');
1120 translate_box_len(latex_height, height_value, height_unit, height_special);
1122 string const opt = p.getArg('[', ']');
1125 if (hor_pos != "l" && hor_pos != "c" &&
1126 hor_pos != "r" && hor_pos != "s") {
1127 cerr << "invalid hor_pos " << hor_pos
1128 << " for " << inner_type << endl;
1135 inner_pos = p.getArg('[', ']');
1136 if (inner_pos != "c" && inner_pos != "t" &&
1137 inner_pos != "b" && inner_pos != "s") {
1138 cerr << "invalid inner_pos "
1139 << inner_pos << " for "
1140 << inner_type << endl;
1141 inner_pos = position;
1145 if (inner_type == "makebox")
1149 if (inner_type.empty()) {
1150 if (special.empty() && outer_type != "framebox")
1151 latex_width = "1\\columnwidth";
1154 latex_width = p2.getArg('[', ']');
1155 string const opt = p2.getArg('[', ']');
1158 if (hor_pos != "l" && hor_pos != "c" &&
1159 hor_pos != "r" && hor_pos != "s") {
1160 cerr << "invalid hor_pos " << hor_pos
1161 << " for " << outer_type << endl;
1165 if (outer_type == "framebox")
1169 } else if (inner_type != "makebox")
1170 latex_width = p.verbatim_item();
1171 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1172 // as this is LyX's standard for such cases (except for makebox)
1173 // \framebox is more special and handled below
1174 if (latex_width.empty() && inner_type != "makebox"
1175 && outer_type != "framebox")
1176 latex_width = "1\\columnwidth";
1178 translate_len(latex_width, width_value, width_unit);
1180 bool shadedparbox = false;
1181 if (inner_type == "shaded") {
1182 eat_whitespace(p, os, parent_context, false);
1183 if (outer_type == "parbox") {
1185 if (p.next_token().cat() == catBegin)
1187 eat_whitespace(p, os, parent_context, false);
1188 shadedparbox = true;
1193 // If we already read the inner box we have to push the inner env
1194 if (!outer_type.empty() && !inner_type.empty() &&
1195 (inner_flags & FLAG_END))
1196 active_environments.push_back(inner_type);
1197 bool use_ert = false;
1198 if (!outer_type.empty() && !inner_type.empty()) {
1199 // Look whether there is some content after the end of the
1200 // inner box, but before the end of the outer box.
1201 // If yes, we need to output ERT.
1203 if (inner_flags & FLAG_END)
1204 p.ertEnvironment(inner_type);
1207 p.skip_spaces(true);
1208 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1209 if ((outer_env && p.next_token().asInput() != "\\end") ||
1210 (!outer_env && p.next_token().cat() != catEnd)) {
1211 // something is between the end of the inner box and
1212 // the end of the outer box, so we need to use ERT.
1220 if (!outer_type.empty()) {
1221 if (outer_flags & FLAG_END)
1222 ss << "\\begin{" << outer_type << '}';
1224 ss << '\\' << outer_type << '{';
1225 if (!special.empty())
1229 if (!inner_type.empty()) {
1230 if (inner_type != "shaded") {
1231 if (inner_flags & FLAG_END)
1232 ss << "\\begin{" << inner_type << '}';
1234 ss << '\\' << inner_type;
1236 if (!position.empty())
1237 ss << '[' << position << ']';
1238 if (!latex_height.empty())
1239 ss << '[' << latex_height << ']';
1240 if (!inner_pos.empty())
1241 ss << '[' << inner_pos << ']';
1242 ss << '{' << latex_width << '}';
1243 if (!(inner_flags & FLAG_END))
1246 if (inner_type == "shaded")
1247 ss << "\\begin{shaded}";
1248 output_ert_inset(os, ss.str(), parent_context);
1249 if (!inner_type.empty()) {
1250 parse_text(p, os, inner_flags, outer, parent_context);
1251 if (inner_flags & FLAG_END)
1252 output_ert_inset(os, "\\end{" + inner_type + '}',
1255 output_ert_inset(os, "}", parent_context);
1257 if (!outer_type.empty()) {
1258 // If we already read the inner box we have to pop
1260 if (!inner_type.empty() && (inner_flags & FLAG_END))
1261 active_environments.pop_back();
1263 // Ensure that the end of the outer box is parsed correctly:
1264 // The opening brace has been eaten by parse_outer_box()
1265 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1266 outer_flags &= ~FLAG_ITEM;
1267 outer_flags |= FLAG_BRACE_LAST;
1269 parse_text(p, os, outer_flags, outer, parent_context);
1270 if (outer_flags & FLAG_END)
1271 output_ert_inset(os, "\\end{" + outer_type + '}',
1274 output_ert_inset(os, "}", parent_context);
1277 // LyX does not like empty positions, so we have
1278 // to set them to the LaTeX default values here.
1279 if (position.empty())
1281 if (inner_pos.empty())
1282 inner_pos = position;
1283 parent_context.check_layout(os);
1284 begin_inset(os, "Box ");
1285 if (outer_type == "framed")
1287 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1289 else if (outer_type == "shadowbox")
1290 os << "Shadowbox\n";
1291 else if ((outer_type == "shaded" && inner_type.empty()) ||
1292 (outer_type == "minipage" && inner_type == "shaded") ||
1293 (outer_type == "parbox" && inner_type == "shaded")) {
1295 preamble.registerAutomaticallyLoadedPackage("color");
1296 } else if (outer_type == "doublebox")
1297 os << "Doublebox\n";
1298 else if (outer_type.empty() || outer_type == "mbox")
1299 os << "Frameless\n";
1301 os << outer_type << '\n';
1302 os << "position \"" << position << "\"\n";
1303 os << "hor_pos \"" << hor_pos << "\"\n";
1304 if (outer_type == "mbox")
1305 os << "has_inner_box 1\n";
1306 else if (!frame_color.empty() && inner_type == "makebox")
1307 os << "has_inner_box 0\n";
1309 os << "has_inner_box " << !inner_type.empty() << "\n";
1310 os << "inner_pos \"" << inner_pos << "\"\n";
1311 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1313 if (outer_type == "mbox")
1314 os << "use_makebox 1\n";
1315 else if (!frame_color.empty())
1316 os << "use_makebox 0\n";
1318 os << "use_makebox " << (inner_type == "makebox") << '\n';
1319 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1320 os << "width \"\"\n";
1321 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1322 else if (contains(width_unit, '\\'))
1323 os << "width \"" << width_value << "in" << "\"\n";
1325 os << "width \"" << width_value << width_unit << "\"\n";
1326 if (contains(width_unit, '\\')) {
1327 width_unit.erase (0,1); // remove the leading '\'
1328 os << "special \"" << width_unit << "\"\n";
1330 os << "special \"" << width_special << "\"\n";
1331 if (contains(height_unit, '\\'))
1332 os << "height \"" << height_value << "in" << "\"\n";
1334 os << "height \"" << height_value << height_unit << "\"\n";
1335 os << "height_special \"" << height_special << "\"\n";
1336 os << "thickness \"" << thickness << "\"\n";
1337 os << "separation \"" << separation << "\"\n";
1338 os << "shadowsize \"" << shadowsize << "\"\n";
1339 os << "framecolor \"" << framecolor << "\"\n";
1340 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1341 os << "status open\n\n";
1343 // Unfortunately we can't use parse_text_in_inset:
1344 // InsetBox::forcePlainLayout() is hard coded and does not
1345 // use the inset layout. Apart from that do we call parse_text
1346 // up to two times, but need only one check_end_layout.
1347 bool const forcePlainLayout =
1348 (!inner_type.empty() || inner_type == "makebox") &&
1349 outer_type != "shaded" && outer_type != "framed";
1350 Context context(true, parent_context.textclass);
1351 if (forcePlainLayout)
1352 context.layout = &context.textclass.plainLayout();
1354 context.font = parent_context.font;
1356 // If we have no inner box the contents will be read with the outer box
1357 if (!inner_type.empty())
1358 parse_text(p, os, inner_flags, outer, context);
1360 // Ensure that the end of the outer box is parsed correctly:
1361 // The opening brace has been eaten by parse_outer_box()
1362 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1363 outer_flags &= ~FLAG_ITEM;
1364 outer_flags |= FLAG_BRACE_LAST;
1367 // Find end of outer box, output contents if inner_type is
1368 // empty and output possible comments
1369 if (!outer_type.empty()) {
1370 // If we already read the inner box we have to pop
1372 if (!inner_type.empty() && (inner_flags & FLAG_END))
1373 active_environments.pop_back();
1374 // This does not output anything but comments if
1375 // inner_type is not empty (see use_ert)
1376 parse_text(p, os, outer_flags, outer, context);
1379 context.check_end_layout(os);
1381 #ifdef PRESERVE_LAYOUT
1382 // LyX puts a % after the end of the minipage
1383 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1385 //output_comment(p, os, "dummy", parent_context);
1388 parent_context.new_paragraph(os);
1390 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1391 //output_comment(p, os, "dummy", parent_context);
1394 // We add a protected space if something real follows
1395 if (p.good() && p.next_token().cat() != catComment) {
1396 begin_inset(os, "space ~\n");
1402 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1403 active_environments.pop_back();
1404 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1405 // in this case we have to eat the the closing brace of the color box
1406 p.get_token().asInput(); // the '}'
1408 if (p.next_token().asInput() == "}") {
1409 // in this case we assume that the closing brace is from the box settings
1410 // therefore reset these values for the next box
1416 // all boxes except of Frameless and Shaded require calc
1417 if (!(outer_type.empty() || outer_type == "mbox") &&
1418 !((outer_type == "shaded" && inner_type.empty()) ||
1419 (outer_type == "minipage" && inner_type == "shaded") ||
1420 (outer_type == "parbox" && inner_type == "shaded")))
1421 preamble.registerAutomaticallyLoadedPackage("calc");
1425 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1426 Context & parent_context, string const & outer_type,
1427 string const & special)
1429 eat_whitespace(p, os, parent_context, false);
1430 if (flags & FLAG_ITEM) {
1432 if (p.next_token().cat() == catBegin)
1435 cerr << "Warning: Ignoring missing '{' after \\"
1436 << outer_type << '.' << endl;
1437 eat_whitespace(p, os, parent_context, false);
1440 unsigned int inner_flags = 0;
1442 if (outer_type == "minipage" || outer_type == "parbox") {
1443 p.skip_spaces(true);
1444 while (p.hasOpt()) {
1446 p.skip_spaces(true);
1449 p.skip_spaces(true);
1450 if (outer_type == "parbox") {
1452 if (p.next_token().cat() == catBegin)
1454 p.skip_spaces(true);
1457 if (outer_type == "shaded" || outer_type == "mbox") {
1458 // These boxes never have an inner box
1460 } else if (p.next_token().asInput() == "\\parbox") {
1461 inner = p.get_token().cs();
1462 inner_flags = FLAG_ITEM;
1463 } else if (p.next_token().asInput() == "\\begin") {
1464 // Is this a minipage or shaded box?
1467 inner = p.getArg('{', '}');
1469 if (inner == "minipage" || inner == "shaded")
1470 inner_flags = FLAG_END;
1475 if (inner_flags == FLAG_END) {
1476 if (inner != "shaded")
1480 eat_whitespace(p, os, parent_context, false);
1482 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1483 outer_type, special, inner, "", "");
1485 if (inner_flags == FLAG_ITEM) {
1487 eat_whitespace(p, os, parent_context, false);
1489 parse_box(p, os, flags, inner_flags, outer, parent_context,
1490 outer_type, special, inner, "", "");
1495 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1496 bool in_line, bool use_minted)
1498 parent_context.check_layout(os);
1499 begin_inset(os, "listings\n");
1500 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1502 while ((i = arg.find(", ")) != string::npos
1503 || (i = arg.find(",\t")) != string::npos)
1504 arg.erase(i + 1, 1);
1507 string const language = p.getArg('{', '}');
1508 p.skip_spaces(true);
1509 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1510 if (!minted_float.empty()) {
1511 arg += string(arg.empty() ? "" : ",") + minted_float;
1512 minted_nonfloat_caption.clear();
1516 os << "lstparams " << '"' << arg << '"' << '\n';
1517 if (arg.find("\\color") != string::npos)
1518 preamble.registerAutomaticallyLoadedPackage("color");
1521 os << "inline true\n";
1523 os << "inline false\n";
1524 os << "status open\n";
1525 Context context(true, parent_context.textclass);
1526 context.layout = &parent_context.textclass.plainLayout();
1527 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1528 minted_nonfloat_caption.erase(0,3);
1529 os << "\n\\begin_layout Plain Layout\n";
1530 begin_inset(os, "Caption Standard\n");
1531 Context newcontext(true, context.textclass,
1532 context.layout, 0, context.font);
1533 newcontext.check_layout(os);
1534 os << minted_nonfloat_caption << "\n";
1535 newcontext.check_end_layout(os);
1537 os << "\n\\end_layout\n";
1538 minted_nonfloat_caption.clear();
1542 // set catcodes to verbatim early, just in case.
1543 p.setCatcodes(VERBATIM_CATCODES);
1544 string delim = p.get_token().asInput();
1545 //FIXME: handler error condition
1546 s = p.verbatimStuff(delim).second;
1547 // context.new_paragraph(os);
1548 } else if (use_minted) {
1549 s = p.verbatimEnvironment("minted");
1551 s = p.verbatimEnvironment("lstlisting");
1553 output_ert(os, s, context);
1554 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1555 minted_nonfloat_caption.erase(0,3);
1556 os << "\n\\begin_layout Plain Layout\n";
1557 begin_inset(os, "Caption Standard\n");
1558 Context newcontext(true, context.textclass,
1559 context.layout, 0, context.font);
1560 newcontext.check_layout(os);
1561 os << minted_nonfloat_caption << "\n";
1562 newcontext.check_end_layout(os);
1564 os << "\n\\end_layout\n";
1565 minted_nonfloat_caption.clear();
1567 // Don't close the inset here for floating minted listings.
1568 // It will be closed at the end of the listing environment.
1569 if (!use_minted || minted_float.empty())
1572 eat_whitespace(p, os, parent_context, true);
1573 Token t = p.get_token();
1574 if (t.asInput() != "\\end") {
1575 // If anything follows, collect it into a caption.
1576 minted_float_has_caption = true;
1577 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1578 begin_inset(os, "Caption Standard\n");
1579 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1586 /// parse an unknown environment
1587 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1588 unsigned flags, bool outer,
1589 Context & parent_context)
1591 if (name == "tabbing")
1592 // We need to remember that we have to handle '\=' specially
1593 flags |= FLAG_TABBING;
1595 // We need to translate font changes and paragraphs inside the
1596 // environment to ERT if we have a non standard font.
1597 // Otherwise things like
1598 // \large\begin{foo}\huge bar\end{foo}
1600 bool const specialfont =
1601 (parent_context.font != parent_context.normalfont);
1602 bool const new_layout_allowed = parent_context.new_layout_allowed;
1604 parent_context.new_layout_allowed = false;
1605 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1606 // Try to handle options: Look if we have optional arguments,
1607 // and if so, put the brackets in ERT.
1608 while (p.hasOpt()) {
1609 p.get_token(); // eat '['
1610 output_ert_inset(os, "[", parent_context);
1611 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1612 output_ert_inset(os, "]", parent_context);
1614 parse_text_snippet(p, os, flags, outer, parent_context);
1615 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1617 parent_context.new_layout_allowed = new_layout_allowed;
1621 void parse_environment(Parser & p, ostream & os, bool outer,
1622 string & last_env, Context & parent_context)
1624 Layout const * newlayout;
1625 InsetLayout const * newinsetlayout = 0;
1626 string const name = p.getArg('{', '}');
1627 const bool is_starred = suffixIs(name, '*');
1628 string const unstarred_name = rtrim(name, "*");
1629 active_environments.push_back(name);
1631 // We use this loop and break out after a condition is met
1632 // rather than a huge else-if-chain.
1634 if (is_math_env(name)) {
1635 parent_context.check_layout(os);
1636 begin_inset(os, "Formula ");
1637 os << "\\begin{" << name << "}";
1638 parse_math(p, os, FLAG_END, MATH_MODE);
1639 os << "\\end{" << name << "}";
1641 if (is_display_math_env(name)) {
1642 // Prevent the conversion of a line break to a space
1643 // (bug 7668). This does not change the output, but
1644 // looks ugly in LyX.
1645 eat_whitespace(p, os, parent_context, false);
1650 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1651 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1652 // We must begin a new paragraph if not already done
1653 if (!parent_context.atParagraphStart()) {
1654 parent_context.check_end_layout(os);
1655 parent_context.new_paragraph(os);
1657 // store previous language because we must reset it at the end
1658 string const lang_old = parent_context.font.language;
1659 // save new language in context so that it is
1660 // handled by parse_text
1661 parent_context.font.language =
1662 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1663 parse_text(p, os, FLAG_END, outer, parent_context);
1664 // reset previous language
1665 parent_context.font.language = lang_old;
1666 // Just in case the environment is empty
1667 parent_context.extra_stuff.erase();
1668 // We must begin a new paragraph to reset the language
1669 parent_context.new_paragraph(os);
1674 if (unstarred_name == "tabular" || name == "longtable"
1675 || name == "tabularx" || name == "xltabular") {
1676 eat_whitespace(p, os, parent_context, false);
1677 string width = "0pt";
1679 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1680 string const opt = p.getArg('[', ']');
1683 else if (opt == "l")
1685 else if (opt == "r")
1688 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1689 width = lyx::translate_len(p.getArg('{', '}'));
1690 eat_whitespace(p, os, parent_context, false);
1692 parent_context.check_layout(os);
1693 begin_inset(os, "Tabular ");
1694 handle_tabular(p, os, name, width, halign, parent_context);
1700 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1701 eat_whitespace(p, os, parent_context, false);
1702 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1703 eat_whitespace(p, os, parent_context, false);
1704 parent_context.check_layout(os);
1705 begin_inset(os, "Float " + unstarred_name + "\n");
1706 // store the float type for subfloats
1707 // subfloats only work with figures and tables
1708 if (unstarred_name == "figure")
1709 float_type = unstarred_name;
1710 else if (unstarred_name == "table")
1711 float_type = unstarred_name;
1715 os << "placement " << opt << '\n';
1716 if (contains(opt, "H"))
1717 preamble.registerAutomaticallyLoadedPackage("float");
1719 Floating const & fl = parent_context.textclass.floats()
1720 .getType(unstarred_name);
1721 if (!fl.floattype().empty() && fl.usesFloatPkg())
1722 preamble.registerAutomaticallyLoadedPackage("float");
1725 os << "wide " << convert<string>(is_starred)
1726 << "\nsideways false"
1727 << "\nstatus open\n\n";
1728 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1730 // We don't need really a new paragraph, but
1731 // we must make sure that the next item gets a \begin_layout.
1732 parent_context.new_paragraph(os);
1734 // the float is parsed thus delete the type
1739 if (unstarred_name == "sidewaysfigure"
1740 || unstarred_name == "sidewaystable"
1741 || unstarred_name == "sidewaysalgorithm") {
1742 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1743 eat_whitespace(p, os, parent_context, false);
1744 parent_context.check_layout(os);
1745 if (unstarred_name == "sidewaysfigure")
1746 begin_inset(os, "Float figure\n");
1747 else if (unstarred_name == "sidewaystable")
1748 begin_inset(os, "Float table\n");
1749 else if (unstarred_name == "sidewaysalgorithm")
1750 begin_inset(os, "Float algorithm\n");
1752 os << "placement " << opt << '\n';
1753 if (contains(opt, "H"))
1754 preamble.registerAutomaticallyLoadedPackage("float");
1755 os << "wide " << convert<string>(is_starred)
1756 << "\nsideways true"
1757 << "\nstatus open\n\n";
1758 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1760 // We don't need really a new paragraph, but
1761 // we must make sure that the next item gets a \begin_layout.
1762 parent_context.new_paragraph(os);
1764 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1768 if (name == "wrapfigure" || name == "wraptable") {
1769 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1770 eat_whitespace(p, os, parent_context, false);
1771 parent_context.check_layout(os);
1774 string overhang = "0col%";
1777 lines = p.getArg('[', ']');
1778 string const placement = p.getArg('{', '}');
1780 overhang = p.getArg('[', ']');
1781 string const width = p.getArg('{', '}');
1783 if (name == "wrapfigure")
1784 begin_inset(os, "Wrap figure\n");
1786 begin_inset(os, "Wrap table\n");
1787 os << "lines " << lines
1788 << "\nplacement " << placement
1789 << "\noverhang " << lyx::translate_len(overhang)
1790 << "\nwidth " << lyx::translate_len(width)
1791 << "\nstatus open\n\n";
1792 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1794 // We don't need really a new paragraph, but
1795 // we must make sure that the next item gets a \begin_layout.
1796 parent_context.new_paragraph(os);
1798 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1802 if (name == "minipage") {
1803 eat_whitespace(p, os, parent_context, false);
1804 // Test whether this is an outer box of a shaded box
1806 // swallow arguments
1807 while (p.hasOpt()) {
1809 p.skip_spaces(true);
1812 p.skip_spaces(true);
1813 Token t = p.get_token();
1814 bool shaded = false;
1815 if (t.asInput() == "\\begin") {
1816 p.skip_spaces(true);
1817 if (p.getArg('{', '}') == "shaded")
1822 parse_outer_box(p, os, FLAG_END, outer,
1823 parent_context, name, "shaded");
1825 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1826 "", "", name, "", "");
1831 if (name == "comment") {
1832 eat_whitespace(p, os, parent_context, false);
1833 parent_context.check_layout(os);
1834 begin_inset(os, "Note Comment\n");
1835 os << "status open\n";
1836 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1839 skip_braces(p); // eat {} that might by set by LyX behind comments
1840 preamble.registerAutomaticallyLoadedPackage("verbatim");
1844 if (unstarred_name == "verbatim") {
1845 // FIXME: this should go in the generic code that
1846 // handles environments defined in layout file that
1847 // have "PassThru 1". However, the code over there is
1848 // already too complicated for my taste.
1849 string const ascii_name =
1850 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1851 parent_context.new_paragraph(os);
1852 Context context(true, parent_context.textclass,
1853 &parent_context.textclass[from_ascii(ascii_name)]);
1854 string s = p.verbatimEnvironment(name);
1855 output_ert(os, s, context);
1860 if (name == "IPA") {
1861 eat_whitespace(p, os, parent_context, false);
1862 parent_context.check_layout(os);
1863 begin_inset(os, "IPA\n");
1864 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1867 preamble.registerAutomaticallyLoadedPackage("tipa");
1868 preamble.registerAutomaticallyLoadedPackage("tipx");
1872 if (name == parent_context.textclass.titlename()
1873 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1874 parse_text(p, os, FLAG_END, outer, parent_context);
1875 // Just in case the environment is empty
1876 parent_context.extra_stuff.erase();
1877 // We must begin a new paragraph
1878 parent_context.new_paragraph(os);
1883 if (name == "CJK") {
1884 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1885 // It is impossible to decide if a CJK environment was in its own paragraph or within
1886 // a line. We therefore always assume a paragraph since the latter is a rare case.
1887 eat_whitespace(p, os, parent_context, false);
1888 parent_context.check_end_layout(os);
1889 // store the encoding to be able to reset it
1890 string const encoding_old = p.getEncoding();
1891 string const encoding = p.getArg('{', '}');
1892 // FIXME: For some reason JIS does not work. Although the text
1893 // in tests/CJK.tex is identical with the SJIS version if you
1894 // convert both snippets using the recode command line utility,
1895 // the resulting .lyx file contains some extra characters if
1896 // you set buggy_encoding to false for JIS.
1897 bool const buggy_encoding = encoding == "JIS";
1898 if (!buggy_encoding)
1899 p.setEncoding(encoding, Encoding::CJK);
1901 // FIXME: This will read garbage, since the data is not encoded in utf8.
1902 p.setEncoding("UTF-8");
1904 // LyX only supports the same mapping for all CJK
1905 // environments, so we might need to output everything as ERT
1906 string const mapping = trim(p.getArg('{', '}'));
1907 char const * const * const where =
1908 is_known(encoding, supported_CJK_encodings);
1909 if (!buggy_encoding && !preamble.fontCJKSet())
1910 preamble.fontCJK(mapping);
1911 bool knownMapping = mapping == preamble.fontCJK();
1912 if (buggy_encoding || !knownMapping || !where) {
1913 parent_context.check_layout(os);
1914 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1916 // we must parse the content as verbatim because e.g. JIS can contain
1917 // normally invalid characters
1918 // FIXME: This works only for the most simple cases.
1919 // Since TeX control characters are not parsed,
1920 // things like comments are completely wrong.
1921 string const s = p.plainEnvironment("CJK");
1922 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1925 if (snip == "\\" || is_known(snip, known_escaped_chars))
1926 output_ert_inset(os, snip, parent_context);
1927 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1932 output_ert_inset(os, "\\end{" + name + "}",
1936 supported_CJK_languages[where - supported_CJK_encodings];
1937 // store the language because we must reset it at the end
1938 string const lang_old = parent_context.font.language;
1939 parent_context.font.language = lang;
1940 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1941 parent_context.font.language = lang_old;
1942 parent_context.new_paragraph(os);
1944 p.setEncoding(encoding_old);
1949 if (name == "lyxgreyedout") {
1950 eat_whitespace(p, os, parent_context, false);
1951 parent_context.check_layout(os);
1952 begin_inset(os, "Note Greyedout\n");
1953 os << "status open\n";
1954 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1957 if (!preamble.notefontcolor().empty())
1958 preamble.registerAutomaticallyLoadedPackage("color");
1962 if (name == "btSect") {
1963 eat_whitespace(p, os, parent_context, false);
1964 parent_context.check_layout(os);
1965 begin_command_inset(os, "bibtex", "bibtex");
1966 string bibstyle = "plain";
1968 bibstyle = p.getArg('[', ']');
1969 p.skip_spaces(true);
1971 string const bibfile = p.getArg('{', '}');
1972 eat_whitespace(p, os, parent_context, false);
1973 Token t = p.get_token();
1974 if (t.asInput() == "\\btPrintCited") {
1975 p.skip_spaces(true);
1976 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1978 if (t.asInput() == "\\btPrintNotCited") {
1979 p.skip_spaces(true);
1980 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1982 if (t.asInput() == "\\btPrintAll") {
1983 p.skip_spaces(true);
1984 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1986 os << "bibfiles " << '"' << bibfile << "\"\n"
1987 << "options " << '"' << bibstyle << "\"\n";
1988 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1994 if (name == "btUnit") {
1995 string const nt = p.next_next_token().cs();
1996 // Do not attempt to overwrite a former diverging multibib.
1997 // Those are output as ERT instead.
1998 if ((nt == "part" || nt == "chapter"
1999 || nt == "section" || nt == "subsection")
2000 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2001 parse_text(p, os, FLAG_END, outer, parent_context);
2002 preamble.multibib(nt);
2004 parse_unknown_environment(p, name, os, FLAG_END, outer,
2009 // This is only attempted at turn environments that consist only
2010 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2011 // Thus we will fall through in other cases.
2012 if (name == "turn") {
2013 // We check if the next thing is a tabular[*|x]
2015 p.getArg('{', '}');// eat turn argument
2016 bool found_end = false;
2017 bool only_table = false;
2018 bool end_table = false;
2021 string envname = p.getArg('{', '}');
2022 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2023 // Now we check if the table is the only content
2024 // of the turn environment
2025 string const tenv = envname;
2026 while (!found_end && !end_table && p.good()) {
2027 envname = p.next_token().cat() == catBegin
2028 ? p.getArg('{', '}') : string();
2029 Token const & t = p.get_token();
2031 end_table = t.asInput() != "\\end"
2033 found_end = t.asInput() == "\\end"
2034 && envname == "turn";
2038 envname = p.getArg('{', '}');
2039 only_table = p.next_next_token().asInput() == "\\end"
2040 && envname == "turn";
2044 string const angle = p.getArg('{', '}');
2046 int const save_tablerotation = parent_context.tablerotation;
2047 parent_context.tablerotation = convert<int>(angle);
2048 parse_text(p, os, FLAG_END, outer, parent_context);
2049 parent_context.tablerotation = save_tablerotation;
2059 // This is only attempted at landscape environments that consist only
2060 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2061 // Other landscape environment is handled via the landscape module, thus
2062 // we will fall through in that case.
2063 if (name == "landscape") {
2064 // We check if the next thing is a longtable
2066 bool found_end = false;
2067 bool only_longtable = false;
2068 bool end_longtable = false;
2071 string envname = p.getArg('{', '}');
2072 if (envname == "longtable" || envname == "xltabular") {
2073 // Now we check if the longtable is the only content
2074 // of the landscape environment
2075 string const ltenv = envname;
2076 while (!found_end && !end_longtable && p.good()) {
2077 envname = p.next_token().cat() == catBegin
2078 ? p.getArg('{', '}') : string();
2079 Token const & t = p.get_token();
2081 end_longtable = t.asInput() != "\\end"
2082 && envname == ltenv;
2083 found_end = t.asInput() == "\\end"
2084 && envname == "landscape";
2086 if (end_longtable) {
2088 envname = p.getArg('{', '}');
2089 only_longtable = p.next_next_token().asInput() == "\\end"
2090 && envname == "landscape";
2092 if (only_longtable) {
2095 int const save_tablerotation = parent_context.tablerotation;
2096 parent_context.tablerotation = 90;
2097 parse_text(p, os, FLAG_END, outer, parent_context);
2098 parent_context.tablerotation = save_tablerotation;
2108 if (name == "framed" || name == "shaded") {
2109 eat_whitespace(p, os, parent_context, false);
2110 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2112 preamble.registerAutomaticallyLoadedPackage("framed");
2116 if (name == "listing") {
2117 minted_float = "float";
2118 eat_whitespace(p, os, parent_context, false);
2119 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2121 minted_float += "=" + opt;
2122 // If something precedes \begin{minted}, we output it at the end
2123 // as a caption, in order to keep it inside the listings inset.
2124 eat_whitespace(p, os, parent_context, true);
2126 Token const & t = p.get_token();
2127 p.skip_spaces(true);
2128 string const envname = p.next_token().cat() == catBegin
2129 ? p.getArg('{', '}') : string();
2130 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2132 minted_float_has_caption = false;
2133 string content = parse_text_snippet(p, FLAG_END, outer,
2135 size_t i = content.find("\\begin_inset listings");
2136 bool minted_env = i != string::npos;
2139 caption = content.substr(0, i);
2140 content.erase(0, i);
2142 parent_context.check_layout(os);
2143 if (minted_env && minted_float_has_caption) {
2144 eat_whitespace(p, os, parent_context, true);
2145 os << content << "\n";
2146 if (!caption.empty())
2147 os << caption << "\n";
2148 os << "\n\\end_layout\n"; // close inner layout
2149 end_inset(os); // close caption inset
2150 os << "\n\\end_layout\n"; // close outer layout
2151 } else if (!caption.empty()) {
2153 begin_inset(os, "listings\n");
2154 os << "lstparams " << '"' << minted_float << '"' << '\n';
2155 os << "inline false\n";
2156 os << "status collapsed\n";
2158 os << "\n\\begin_layout Plain Layout\n";
2159 begin_inset(os, "Caption Standard\n");
2160 Context newcontext(true, parent_context.textclass,
2161 0, 0, parent_context.font);
2162 newcontext.check_layout(os);
2163 os << caption << "\n";
2164 newcontext.check_end_layout(os);
2166 os << "\n\\end_layout\n";
2167 } else if (content.empty()) {
2168 begin_inset(os, "listings\n");
2169 os << "lstparams " << '"' << minted_float << '"' << '\n';
2170 os << "inline false\n";
2171 os << "status collapsed\n";
2173 os << content << "\n";
2175 end_inset(os); // close listings inset
2176 parent_context.check_end_layout(os);
2177 parent_context.new_paragraph(os);
2179 minted_float.clear();
2180 minted_float_has_caption = false;
2184 if (name == "lstlisting" || name == "minted") {
2185 bool use_minted = name == "minted";
2186 // with listings, we do not eat newlines here since
2187 // \begin{lstlistings}
2190 // // \begin{lstlistings}%
2193 // reads [foo] as content, whereas
2194 // // \begin{lstlistings}%
2197 // \begin{lstlistings}[foo,
2199 // reads [foo...] as argument.
2200 eat_whitespace(p, os, parent_context, false, use_minted);
2201 if (use_minted && minted_float.empty()) {
2202 // look ahead for a bottom caption
2204 bool found_end_minted = false;
2205 while (!found_end_minted && p.good()) {
2206 Token const & t = p.get_token();
2208 string const envname =
2209 p.next_token().cat() == catBegin
2210 ? p.getArg('{', '}') : string();
2211 found_end_minted = t.asInput() == "\\end"
2212 && envname == "minted";
2214 eat_whitespace(p, os, parent_context, true);
2215 Token const & t = p.get_token();
2216 p.skip_spaces(true);
2217 if (t.asInput() == "\\lyxmintcaption") {
2218 string const pos = p.getArg('[', ']');
2220 string const caption =
2221 parse_text_snippet(p, FLAG_ITEM,
2222 false, parent_context);
2223 minted_nonfloat_caption = "[b]" + caption;
2224 eat_whitespace(p, os, parent_context, true);
2229 parse_listings(p, os, parent_context, false, use_minted);
2234 if (!parent_context.new_layout_allowed) {
2235 parse_unknown_environment(p, name, os, FLAG_END, outer,
2240 // Alignment and spacing settings
2241 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2242 // therefore are totally broken!
2243 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2244 // they are commands not environments. They are furthermore switches that
2245 // can be ended by another switches, but also by commands like \footnote or
2246 // \parbox. So the only safe way is to leave them untouched.
2247 // However, we support the pseudo-environments
2248 // \begin{centering} ... \end{centering}
2249 // \begin{raggedright} ... \end{raggedright}
2250 // \begin{raggedleft} ... \end{raggedleft}
2251 // since they are used by LyX in floats (for spacing reasons)
2252 if (name == "center" || name == "centering"
2253 || name == "flushleft" || name == "raggedright"
2254 || name == "flushright" || name == "raggedleft"
2255 || name == "singlespace" || name == "onehalfspace"
2256 || name == "doublespace" || name == "spacing") {
2257 eat_whitespace(p, os, parent_context, false);
2258 // We must begin a new paragraph if not already done
2259 if (! parent_context.atParagraphStart()) {
2260 parent_context.check_end_layout(os);
2261 parent_context.new_paragraph(os);
2263 if (name == "flushleft" || name == "raggedright")
2264 parent_context.add_extra_stuff("\\align left\n");
2265 else if (name == "flushright" || name == "raggedleft")
2266 parent_context.add_extra_stuff("\\align right\n");
2267 else if (name == "center" || name == "centering")
2268 parent_context.add_extra_stuff("\\align center\n");
2269 else if (name == "singlespace")
2270 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2271 else if (name == "onehalfspace") {
2272 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2273 preamble.registerAutomaticallyLoadedPackage("setspace");
2274 } else if (name == "doublespace") {
2275 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2276 preamble.registerAutomaticallyLoadedPackage("setspace");
2277 } else if (name == "spacing") {
2278 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2279 preamble.registerAutomaticallyLoadedPackage("setspace");
2281 parse_text(p, os, FLAG_END, outer, parent_context);
2282 // Just in case the environment is empty
2283 parent_context.extra_stuff.erase();
2284 // We must begin a new paragraph to reset the alignment
2285 parent_context.new_paragraph(os);
2290 // The single '=' is meant here.
2291 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2292 eat_whitespace(p, os, parent_context, false);
2293 Context context(true, parent_context.textclass, newlayout,
2294 parent_context.layout, parent_context.font);
2295 if (parent_context.deeper_paragraph) {
2296 // We are beginning a nested environment after a
2297 // deeper paragraph inside the outer list environment.
2298 // Therefore we don't need to output a "begin deeper".
2299 context.need_end_deeper = true;
2301 parent_context.check_end_layout(os);
2302 if (last_env == name) {
2303 // we need to output a separator since LyX would export
2304 // the two environments as one otherwise (bug 5716)
2305 TeX2LyXDocClass const & textclass(parent_context.textclass);
2306 Context newcontext(true, textclass,
2307 &(textclass.defaultLayout()));
2308 newcontext.check_layout(os);
2309 begin_inset(os, "Separator plain\n");
2311 newcontext.check_end_layout(os);
2313 switch (context.layout->latextype) {
2314 case LATEX_LIST_ENVIRONMENT:
2315 context.in_list_preamble =
2316 !context.layout->listpreamble().empty()
2317 && p.hasListPreamble(context.layout->itemcommand());
2318 context.add_par_extra_stuff("\\labelwidthstring "
2319 + p.verbatim_item() + '\n');
2322 case LATEX_BIB_ENVIRONMENT:
2323 p.verbatim_item(); // swallow next arg
2329 context.check_deeper(os);
2330 if (newlayout->keepempty) {
2331 // We need to start a new paragraph
2332 // even if it is empty.
2333 context.new_paragraph(os);
2334 context.check_layout(os);
2336 // handle known optional and required arguments
2337 if (context.layout->latextype == LATEX_ENVIRONMENT)
2338 output_arguments(os, p, outer, false, string(), context,
2339 context.layout->latexargs());
2340 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2341 context.in_list_preamble =
2342 !context.layout->listpreamble().empty()
2343 && p.hasListPreamble(context.layout->itemcommand());
2345 output_arguments(oss, p, outer, false, string(), context,
2346 context.layout->latexargs());
2347 context.list_extra_stuff = oss.str();
2349 if (context.in_list_preamble) {
2350 // Collect the stuff between \begin and first \item
2351 context.list_preamble =
2352 parse_text_snippet(p, FLAG_END, outer, context);
2353 context.in_list_preamble = false;
2355 parse_text(p, os, FLAG_END, outer, context);
2356 if (context.layout->latextype == LATEX_ENVIRONMENT)
2357 output_arguments(os, p, outer, false, "post", context,
2358 context.layout->postcommandargs());
2359 context.check_end_layout(os);
2360 if (parent_context.deeper_paragraph) {
2361 // We must suppress the "end deeper" because we
2362 // suppressed the "begin deeper" above.
2363 context.need_end_deeper = false;
2365 context.check_end_deeper(os);
2366 parent_context.new_paragraph(os);
2368 if (!preamble.titleLayoutFound())
2369 preamble.titleLayoutFound(newlayout->intitle);
2370 set<string> const & req = newlayout->required();
2371 set<string>::const_iterator it = req.begin();
2372 set<string>::const_iterator en = req.end();
2373 for (; it != en; ++it)
2374 preamble.registerAutomaticallyLoadedPackage(*it);
2378 // The single '=' is meant here.
2379 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2380 eat_whitespace(p, os, parent_context, false);
2381 parent_context.check_layout(os);
2382 begin_inset(os, "Flex ");
2383 docstring flex_name = newinsetlayout->name();
2384 // FIXME: what do we do if the prefix is not Flex: ?
2385 if (prefixIs(flex_name, from_ascii("Flex:")))
2386 flex_name.erase(0, 5);
2387 os << to_utf8(flex_name) << '\n'
2388 << "status collapsed\n";
2389 if (newinsetlayout->isPassThru()) {
2390 string const arg = p.verbatimEnvironment(name);
2391 Context context(true, parent_context.textclass,
2392 &parent_context.textclass.plainLayout(),
2393 parent_context.layout);
2394 output_ert(os, arg, parent_context);
2396 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2401 if (name == "appendix") {
2402 // This is no good latex style, but it works and is used in some documents...
2403 eat_whitespace(p, os, parent_context, false);
2404 parent_context.check_end_layout(os);
2405 Context context(true, parent_context.textclass, parent_context.layout,
2406 parent_context.layout, parent_context.font);
2407 context.check_layout(os);
2408 os << "\\start_of_appendix\n";
2409 parse_text(p, os, FLAG_END, outer, context);
2410 context.check_end_layout(os);
2415 if (known_environments.find(name) != known_environments.end()) {
2416 vector<ArgumentType> arguments = known_environments[name];
2417 // The last "argument" denotes whether we may translate the
2418 // environment contents to LyX
2419 // The default required if no argument is given makes us
2420 // compatible with the reLyXre environment.
2421 ArgumentType contents = arguments.empty() ?
2424 if (!arguments.empty())
2425 arguments.pop_back();
2426 // See comment in parse_unknown_environment()
2427 bool const specialfont =
2428 (parent_context.font != parent_context.normalfont);
2429 bool const new_layout_allowed =
2430 parent_context.new_layout_allowed;
2432 parent_context.new_layout_allowed = false;
2433 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2434 outer, parent_context);
2435 if (contents == verbatim)
2436 output_ert_inset(os, p.ertEnvironment(name),
2439 parse_text_snippet(p, os, FLAG_END, outer,
2441 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2443 parent_context.new_layout_allowed = new_layout_allowed;
2447 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2452 active_environments.pop_back();
2456 /// parses a comment and outputs it to \p os.
2457 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2458 bool skipNewlines = false)
2460 LASSERT(t.cat() == catComment, return);
2461 if (!t.cs().empty()) {
2462 context.check_layout(os);
2463 output_comment(p, os, t.cs(), context);
2464 if (p.next_token().cat() == catNewline) {
2465 // A newline after a comment line starts a new
2467 if (context.new_layout_allowed) {
2468 if(!context.atParagraphStart())
2469 // Only start a new paragraph if not already
2470 // done (we might get called recursively)
2471 context.new_paragraph(os);
2473 output_ert_inset(os, "\n", context);
2474 eat_whitespace(p, os, context, true);
2476 } else if (!skipNewlines) {
2477 // "%\n" combination
2484 * Reads spaces and comments until the first non-space, non-comment token.
2485 * New paragraphs (double newlines or \\par) are handled like simple spaces
2486 * if \p eatParagraph is true.
2487 * If \p eatNewline is false, newlines won't be treated as whitespace.
2488 * Spaces are skipped, but comments are written to \p os.
2490 void eat_whitespace(Parser & p, ostream & os, Context & context,
2491 bool eatParagraph, bool eatNewline)
2494 Token const & t = p.get_token();
2495 if (t.cat() == catComment)
2496 parse_comment(p, os, t, context, !eatNewline);
2497 else if ((!eatParagraph && p.isParagraph()) ||
2498 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2507 * Set a font attribute, parse text and reset the font attribute.
2508 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2509 * \param currentvalue Current value of the attribute. Is set to the new
2510 * value during parsing.
2511 * \param newvalue New value of the attribute
2513 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2514 Context & context, string const & attribute,
2515 string & currentvalue, string const & newvalue)
2517 context.check_layout(os);
2518 string const oldvalue = currentvalue;
2519 currentvalue = newvalue;
2520 os << '\n' << attribute << ' ' << newvalue << "\n";
2521 parse_text_snippet(p, os, flags, outer, context);
2522 context.check_layout(os);
2523 os << '\n' << attribute << ' ' << oldvalue << "\n";
2524 currentvalue = oldvalue;
2528 /// get the arguments of a natbib or jurabib citation command
2529 void get_cite_arguments(Parser & p, bool natbibOrder,
2530 string & before, string & after, bool const qualified = false)
2532 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2534 // text before the citation
2536 // text after the citation
2537 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2539 if (!after.empty()) {
2540 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2541 if (natbibOrder && !before.empty())
2542 swap(before, after);
2547 void copy_file(FileName const & src, string const & dstname)
2551 string const absParent = getParentFilePath(false);
2553 if (FileName::isAbsolute(dstname))
2554 dst = FileName(dstname);
2556 dst = makeAbsPath(dstname, absParent);
2557 FileName const srcpath = src.onlyPath();
2558 FileName const dstpath = dst.onlyPath();
2559 if (equivalent(srcpath, dstpath))
2561 if (!dstpath.isDirectory()) {
2562 if (!dstpath.createPath()) {
2563 cerr << "Warning: Could not create directory for file `"
2564 << dst.absFileName() << "´." << endl;
2568 if (dst.isReadableFile()) {
2569 if (overwriteFiles())
2570 cerr << "Warning: Overwriting existing file `"
2571 << dst.absFileName() << "´." << endl;
2573 cerr << "Warning: Not overwriting existing file `"
2574 << dst.absFileName() << "´." << endl;
2578 if (!src.copyTo(dst))
2579 cerr << "Warning: Could not copy file `" << src.absFileName()
2580 << "´ to `" << dst.absFileName() << "´." << endl;
2584 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2585 bool parse_chunk(Parser & p, ostream & os, Context & context)
2587 // check whether a chunk is possible here.
2588 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2594 // read the parameters
2595 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2596 if (!params.first) {
2601 Parser::Arg const code = p.verbatimStuff("\n@");
2606 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2607 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2611 // The last newline read is important for paragraph handling
2615 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2616 // We must have a valid layout before outputting the Chunk inset.
2617 context.check_layout(os);
2618 Context chunkcontext(true, context.textclass);
2619 chunkcontext.layout = &context.textclass.plainLayout();
2620 begin_inset(os, "Flex Chunk");
2621 os << "\nstatus open\n";
2622 if (!params.second.empty()) {
2623 chunkcontext.check_layout(os);
2624 Context paramscontext(true, context.textclass);
2625 paramscontext.layout = &context.textclass.plainLayout();
2626 begin_inset(os, "Argument 1");
2627 os << "\nstatus open\n";
2628 output_ert(os, params.second, paramscontext);
2631 output_ert(os, code.second, chunkcontext);
2639 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2640 bool is_macro(Parser & p)
2642 Token first = p.curr_token();
2643 if (first.cat() != catEscape || !p.good())
2645 if (first.cs() == "def")
2647 if (first.cs() != "global" && first.cs() != "long")
2649 Token second = p.get_token();
2651 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2652 second.cat() == catNewline || second.cat() == catComment)) {
2653 second = p.get_token();
2656 bool secondvalid = second.cat() == catEscape;
2658 bool thirdvalid = false;
2659 if (p.good() && first.cs() == "global" && secondvalid &&
2660 second.cs() == "long") {
2661 third = p.get_token();
2663 while (p.good() && !p.isParagraph() &&
2664 (third.cat() == catSpace ||
2665 third.cat() == catNewline ||
2666 third.cat() == catComment)) {
2667 third = p.get_token();
2670 thirdvalid = third.cat() == catEscape;
2672 for (int i = 0; i < pos; ++i)
2677 return (first.cs() == "global" || first.cs() == "long") &&
2678 second.cs() == "def";
2679 return first.cs() == "global" && second.cs() == "long" &&
2680 third.cs() == "def";
2684 /// Parse a macro definition (assumes that is_macro() returned true)
2685 void parse_macro(Parser & p, ostream & os, Context & context)
2687 context.check_layout(os);
2688 Token first = p.curr_token();
2691 string command = first.asInput();
2692 if (first.cs() != "def") {
2694 eat_whitespace(p, os, context, false);
2695 second = p.curr_token();
2696 command += second.asInput();
2697 if (second.cs() != "def") {
2699 eat_whitespace(p, os, context, false);
2700 third = p.curr_token();
2701 command += third.asInput();
2704 eat_whitespace(p, os, context, false);
2705 string const name = p.get_token().cs();
2706 eat_whitespace(p, os, context, false);
2712 while (p.next_token().cat() != catBegin) {
2713 if (p.next_token().cat() == catParameter) {
2718 // followed by number?
2719 if (p.next_token().cat() == catOther) {
2720 string s = p.get_token().asInput();
2722 // number = current arity + 1?
2723 if (s.size() == 1 && s[0] == arity + '0' + 1)
2728 paramtext += p.get_token().cs();
2730 paramtext += p.get_token().cs();
2735 // only output simple (i.e. compatible) macro as FormulaMacros
2736 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2738 context.check_layout(os);
2739 begin_inset(os, "FormulaMacro");
2740 os << "\n\\def" << ert;
2743 output_ert_inset(os, command + ert, context);
2747 void registerExternalTemplatePackages(string const & name)
2749 external::TemplateManager const & etm = external::TemplateManager::get();
2750 external::Template const * const et = etm.getTemplateByName(name);
2753 external::Template::Formats::const_iterator cit = et->formats.end();
2755 cit = et->formats.find("PDFLaTeX");
2756 if (cit == et->formats.end())
2757 // If the template has not specified a PDFLaTeX output,
2758 // we try the LaTeX format.
2759 cit = et->formats.find("LaTeX");
2760 if (cit == et->formats.end())
2762 vector<string>::const_iterator qit = cit->second.requirements.begin();
2763 vector<string>::const_iterator qend = cit->second.requirements.end();
2764 for (; qit != qend; ++qit)
2765 preamble.registerAutomaticallyLoadedPackage(*qit);
2768 } // anonymous namespace
2772 * Find a file with basename \p name in path \p path and an extension
2775 string find_file(string const & name, string const & path,
2776 char const * const * extensions)
2778 for (char const * const * what = extensions; *what; ++what) {
2779 string const trial = addExtension(name, *what);
2780 if (makeAbsPath(trial, path).exists())
2787 /// Convert filenames with TeX macros and/or quotes to something LyX
2789 string const normalize_filename(string const & name)
2794 Token const & t = p.get_token();
2795 if (t.cat() != catEscape)
2797 else if (t.cs() == "lyxdot") {
2798 // This is used by LyX for simple dots in relative
2802 } else if (t.cs() == "space") {
2805 } else if (t.cs() == "string") {
2806 // Convert \string" to " and \string~ to ~
2807 Token const & n = p.next_token();
2808 if (n.asInput() != "\"" && n.asInput() != "~")
2813 // Strip quotes. This is a bit complicated (see latex_path()).
2814 string full = os.str();
2815 if (!full.empty() && full[0] == '"') {
2816 string base = removeExtension(full);
2817 string ext = getExtension(full);
2818 if (!base.empty() && base[base.length()-1] == '"')
2821 return addExtension(trim(base, "\""), ext);
2822 if (full[full.length()-1] == '"')
2825 return trim(full, "\"");
2831 /// Convert \p name from TeX convention (relative to master file) to LyX
2832 /// convention (relative to .lyx file) if it is relative
2833 void fix_child_filename(string & name)
2835 string const absMasterTeX = getMasterFilePath(true);
2836 bool const isabs = FileName::isAbsolute(name);
2837 // convert from "relative to .tex master" to absolute original path
2839 name = makeAbsPath(name, absMasterTeX).absFileName();
2840 bool copyfile = copyFiles();
2841 string const absParentLyX = getParentFilePath(false);
2844 // convert from absolute original path to "relative to master file"
2845 string const rel = to_utf8(makeRelPath(from_utf8(name),
2846 from_utf8(absMasterTeX)));
2847 // re-interpret "relative to .tex file" as "relative to .lyx file"
2848 // (is different if the master .lyx file resides in a
2849 // different path than the master .tex file)
2850 string const absMasterLyX = getMasterFilePath(false);
2851 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2852 // Do not copy if the new path is impossible to create. Example:
2853 // absMasterTeX = "/foo/bar/"
2854 // absMasterLyX = "/bar/"
2855 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2856 if (contains(name, "/../"))
2863 // convert from absolute original path to
2864 // "relative to .lyx file"
2865 name = to_utf8(makeRelPath(from_utf8(abs),
2866 from_utf8(absParentLyX)));
2870 // convert from absolute original path to "relative to .lyx file"
2871 name = to_utf8(makeRelPath(from_utf8(name),
2872 from_utf8(absParentLyX)));
2877 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2878 Context & context, string const & rdelim)
2880 Layout const * newlayout = 0;
2881 InsetLayout const * newinsetlayout = 0;
2882 char const * const * where = 0;
2883 // Store the latest bibliographystyle, addcontentslineContent and
2884 // nocite{*} option (needed for bibtex inset)
2886 string contentslineContent;
2887 // Some classes provide a \bibliographystyle, so do not output
2888 // any if none is explicitly set.
2889 string bibliographystyle;
2890 bool const use_natbib = isProvided("natbib");
2891 bool const use_jurabib = isProvided("jurabib");
2892 bool const use_biblatex = isProvided("biblatex")
2893 && preamble.citeEngine() != "biblatex-natbib";
2894 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2895 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2896 need_commentbib = use_biblatex || use_biblatex_natbib;
2899 // it is impossible to determine the correct encoding for non-CJK Japanese.
2900 // Therefore write a note at the beginning of the document
2901 if (is_nonCJKJapanese) {
2902 context.check_layout(os);
2903 begin_inset(os, "Note Note\n");
2904 os << "status open\n\\begin_layout Plain Layout\n"
2905 << "\\series bold\n"
2906 << "Important information:\n"
2907 << "\\end_layout\n\n"
2908 << "\\begin_layout Plain Layout\n"
2909 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2910 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2911 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2912 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2913 << " and specify the encoding using the -e command-line switch.\n"
2914 << " In addition, you might want to double check that the desired output encoding\n"
2915 << " is correctly selected in Document > Settings > Language.\n"
2916 << "\\end_layout\n";
2918 is_nonCJKJapanese = false;
2921 bool have_cycled = false;
2923 // Leave here only after at least one cycle
2924 if (have_cycled && flags & FLAG_LEAVE) {
2925 flags &= ~FLAG_LEAVE;
2929 Token const & t = p.get_token();
2931 debugToken(cerr, t, flags);
2934 if (context.in_list_preamble
2935 && p.next_token().cs() == context.layout->itemcommand()) {
2936 // We are parsing a list preamble. End before first \item.
2937 flags |= FLAG_LEAVE;
2938 context.in_list_preamble = false;
2941 if (flags & FLAG_ITEM) {
2942 if (t.cat() == catSpace)
2945 flags &= ~FLAG_ITEM;
2946 if (t.cat() == catBegin) {
2947 // skip the brace and collect everything to the next matching
2949 flags |= FLAG_BRACE_LAST;
2953 // handle only this single token, leave the loop if done
2954 flags |= FLAG_LEAVE;
2957 if (t.cat() != catEscape && t.character() == ']' &&
2958 (flags & FLAG_BRACK_LAST))
2960 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2962 string tok = t.asInput();
2963 // we only support delimiters with max 2 chars for now.
2964 if (rdelim.size() > 1)
2965 tok += p.next_token().asInput();
2966 if (t.cat() != catEscape && !rdelim.empty()
2967 && tok == rdelim && (flags & FLAG_RDELIM)) {
2968 if (rdelim.size() > 1)
2969 p.get_token(); // eat rdelim
2973 // If there is anything between \end{env} and \begin{env} we
2974 // don't need to output a separator.
2975 if (t.cat() != catSpace && t.cat() != catNewline &&
2976 t.asInput() != "\\begin")
2983 bool const starred = p.next_token().asInput() == "*";
2984 string const starredname(starred ? (t.cs() + '*') : t.cs());
2985 if (t.cat() == catMath) {
2986 // we are inside some text mode thingy, so opening new math is allowed
2987 context.check_layout(os);
2988 begin_inset(os, "Formula ");
2989 Token const & n = p.get_token();
2990 bool const display(n.cat() == catMath && outer);
2992 // TeX's $$...$$ syntax for displayed math
2994 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2996 p.get_token(); // skip the second '$' token
2998 // simple $...$ stuff
3001 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3006 // Prevent the conversion of a line break to a
3007 // space (bug 7668). This does not change the
3008 // output, but looks ugly in LyX.
3009 eat_whitespace(p, os, context, false);
3014 if (t.cat() == catSuper || t.cat() == catSub) {
3015 cerr << "catcode " << t << " illegal in text mode\n";
3019 // Basic support for quotes. We try to disambiguate
3020 // quotes from the context (e.g., a left english quote is
3021 // the same as a right german quote...).
3022 // Try to make a smart guess about the side
3023 Token const prev = p.prev_token();
3024 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3025 && prev.character() != '\n' && prev.character() != '~');
3026 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3027 context.check_layout(os);
3028 begin_inset(os, "Quotes ");
3029 os << guessQuoteStyle("eld", opening);
3035 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3036 context.check_layout(os);
3037 begin_inset(os, "Quotes ");
3038 os << guessQuoteStyle("erd", opening);
3045 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3046 context.check_layout(os);
3047 begin_inset(os, "Quotes ");
3048 os << guessQuoteStyle("ald", opening);
3055 if (t.asInput() == "<"
3056 && p.next_token().asInput() == "<") {
3057 bool has_chunk = false;
3061 has_chunk = parse_chunk(p, os, context);
3067 context.check_layout(os);
3068 begin_inset(os, "Quotes ");
3069 os << guessQuoteStyle("ard", opening);
3077 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3078 check_space(p, os, context);
3082 // babel shorthands (also used by polyglossia)
3083 // Since these can have different meanings for different languages
3084 // we import them as ERT (but they must be put in ERT to get output
3086 if (t.asInput() == "\"") {
3088 // These are known pairs. We put them together in
3089 // one ERT inset. In other cases (such as "a), only
3090 // the quotation mark is ERTed.
3091 if (p.next_token().asInput() == "\""
3092 || p.next_token().asInput() == "|"
3093 || p.next_token().asInput() == "-"
3094 || p.next_token().asInput() == "~"
3095 || p.next_token().asInput() == "="
3096 || p.next_token().asInput() == "/"
3097 || p.next_token().asInput() == "~"
3098 || p.next_token().asInput() == "'"
3099 || p.next_token().asInput() == "`"
3100 || p.next_token().asInput() == "<"
3101 || p.next_token().asInput() == ">") {
3102 s += p.next_token().asInput();
3105 output_ert_inset(os, s, context);
3109 if (t.character() == '[' && noweb_mode &&
3110 p.next_token().character() == '[') {
3111 // These can contain underscores
3113 string const s = p.getFullOpt() + ']';
3114 if (p.next_token().character() == ']')
3117 cerr << "Warning: Inserting missing ']' in '"
3118 << s << "'." << endl;
3119 output_ert_inset(os, s, context);
3123 if (t.cat() == catLetter) {
3124 context.check_layout(os);
3129 if (t.cat() == catOther ||
3130 t.cat() == catAlign ||
3131 t.cat() == catParameter) {
3132 context.check_layout(os);
3133 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3134 context.merging_hyphens_allowed &&
3135 context.font.family != "ttfamily" &&
3136 !context.layout->pass_thru) {
3137 if (p.next_next_token().asInput() == "-") {
3139 os << to_utf8(docstring(1, 0x2014));
3143 os << to_utf8(docstring(1, 0x2013));
3146 // This translates "&" to "\\&" which may be wrong...
3151 if (p.isParagraph()) {
3152 // In minted floating listings we will collect
3153 // everything into the caption, where multiple
3154 // paragraphs are forbidden.
3155 if (minted_float.empty()) {
3156 if (context.new_layout_allowed)
3157 context.new_paragraph(os);
3159 output_ert_inset(os, "\\par ", context);
3162 eat_whitespace(p, os, context, true);
3166 if (t.cat() == catActive) {
3167 context.check_layout(os);
3168 if (t.character() == '~') {
3169 if (context.layout->free_spacing)
3172 begin_inset(os, "space ~\n");
3180 if (t.cat() == catBegin) {
3181 Token const next = p.next_token();
3182 Token const end = p.next_next_token();
3183 if (next.cat() == catEnd) {
3185 Token const prev = p.prev_token();
3187 if (p.next_token().character() == '`')
3188 ; // ignore it in {}``
3190 output_ert_inset(os, "{}", context);
3191 } else if (next.cat() == catEscape &&
3192 is_known(next.cs(), known_quotes) &&
3193 end.cat() == catEnd) {
3194 // Something like {\textquoteright} (e.g.
3195 // from writer2latex). We may skip the
3196 // braces here for better readability.
3197 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3199 } else if (p.next_token().asInput() == "\\ascii") {
3200 // handle the \ascii characters
3201 // (the case without braces is handled later)
3202 // the code is "{\ascii\xxx}"
3203 p.get_token(); // eat \ascii
3204 string name2 = p.get_token().asInput();
3205 p.get_token(); // eat the final '}'
3206 string const name = "{\\ascii" + name2 + "}";
3210 // get the character from unicodesymbols
3211 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3212 Encodings::TEXT_CMD, termination, rem, &req);
3214 context.check_layout(os);
3217 output_ert_inset(os,
3218 to_utf8(rem), context);
3219 for (set<string>::const_iterator it = req.begin();
3220 it != req.end(); ++it)
3221 preamble.registerAutomaticallyLoadedPackage(*it);
3223 // we did not find a non-ert version
3224 output_ert_inset(os, name, context);
3226 context.check_layout(os);
3227 // special handling of font attribute changes
3228 Token const prev = p.prev_token();
3229 TeXFont const oldFont = context.font;
3230 if (next.character() == '[' ||
3231 next.character() == ']' ||
3232 next.character() == '*') {
3234 if (p.next_token().cat() == catEnd) {
3239 output_ert_inset(os, "{", context);
3240 parse_text_snippet(p, os,
3243 output_ert_inset(os, "}", context);
3245 } else if (! context.new_layout_allowed) {
3246 output_ert_inset(os, "{", context);
3247 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3249 output_ert_inset(os, "}", context);
3250 } else if (is_known(next.cs(), known_sizes)) {
3251 // next will change the size, so we must
3253 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3255 if (!context.atParagraphStart())
3257 << context.font.size << "\n";
3258 } else if (is_known(next.cs(), known_font_families)) {
3259 // next will change the font family, so we
3260 // must reset it here
3261 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3263 if (!context.atParagraphStart())
3265 << context.font.family << "\n";
3266 } else if (is_known(next.cs(), known_font_series)) {
3267 // next will change the font series, so we
3268 // must reset it here
3269 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3271 if (!context.atParagraphStart())
3273 << context.font.series << "\n";
3274 } else if (is_known(next.cs(), known_font_shapes)) {
3275 // next will change the font shape, so we
3276 // must reset it here
3277 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3279 if (!context.atParagraphStart())
3281 << context.font.shape << "\n";
3282 } else if (is_known(next.cs(), known_old_font_families) ||
3283 is_known(next.cs(), known_old_font_series) ||
3284 is_known(next.cs(), known_old_font_shapes)) {
3285 // next will change the font family, series
3286 // and shape, so we must reset it here
3287 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3289 if (!context.atParagraphStart())
3291 << context.font.family
3293 << context.font.series
3295 << context.font.shape << "\n";
3297 output_ert_inset(os, "{", context);
3298 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3300 output_ert_inset(os, "}", context);
3306 if (t.cat() == catEnd) {
3307 if (flags & FLAG_BRACE_LAST) {
3310 cerr << "stray '}' in text\n";
3311 output_ert_inset(os, "}", context);
3315 if (t.cat() == catComment) {
3316 parse_comment(p, os, t, context);
3321 // control sequences
3324 if (t.cs() == "(" || t.cs() == "[") {
3325 bool const simple = t.cs() == "(";
3326 context.check_layout(os);
3327 begin_inset(os, "Formula");
3328 os << " \\" << t.cs();
3329 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3330 os << '\\' << (simple ? ')' : ']');
3333 // Prevent the conversion of a line break to a
3334 // space (bug 7668). This does not change the
3335 // output, but looks ugly in LyX.
3336 eat_whitespace(p, os, context, false);
3341 if (t.cs() == "begin") {
3342 parse_environment(p, os, outer, last_env,
3347 if (t.cs() == "end") {
3348 if (flags & FLAG_END) {
3349 // eat environment name
3350 string const name = p.getArg('{', '}');
3351 if (name != active_environment())
3352 cerr << "\\end{" + name + "} does not match \\begin{"
3353 + active_environment() + "}\n";
3356 p.error("found 'end' unexpectedly");
3360 // "item" by default, but could be something else
3361 if (t.cs() == context.layout->itemcommand()) {
3363 if (context.layout->labeltype == LABEL_MANUAL) {
3364 // FIXME: This swallows comments, but we cannot use
3365 // eat_whitespace() since we must not output
3366 // anything before the item.
3367 p.skip_spaces(true);
3368 s = p.verbatimOption();
3370 p.skip_spaces(false);
3372 context.check_layout(os);
3373 if (context.has_item) {
3374 // An item in an unknown list-like environment
3375 // FIXME: Do this in check_layout()!
3376 context.has_item = false;
3377 string item = "\\" + context.layout->itemcommand();
3380 output_ert_inset(os, item, context);
3382 if (context.layout->labeltype != LABEL_MANUAL)
3383 output_arguments(os, p, outer, false, "item", context,
3384 context.layout->itemargs());
3385 if (!context.list_preamble.empty()) {
3386 // We have a list preamble. Output it here.
3387 begin_inset(os, "Argument listpreamble:1");
3388 os << "\nstatus collapsed\n\n"
3389 << "\\begin_layout Plain Layout\n\n"
3390 << rtrim(context.list_preamble)
3391 << "\n\\end_layout";
3393 context.list_preamble.clear();
3395 if (!context.list_extra_stuff.empty()) {
3396 os << context.list_extra_stuff;
3397 context.list_extra_stuff.clear();
3399 else if (!s.empty()) {
3400 // LyX adds braces around the argument,
3401 // so we need to remove them here.
3402 if (s.size() > 2 && s[0] == '{' &&
3403 s[s.size()-1] == '}')
3404 s = s.substr(1, s.size()-2);
3405 // If the argument contains a space we
3406 // must put it into ERT: Otherwise LyX
3407 // would misinterpret the space as
3408 // item delimiter (bug 7663)
3409 if (contains(s, ' ')) {
3410 output_ert_inset(os, s, context);
3413 os << parse_text_snippet(p2,
3414 FLAG_BRACK_LAST, outer, context);
3416 // The space is needed to separate the
3417 // item from the rest of the sentence.
3419 eat_whitespace(p, os, context, false);
3424 if (t.cs() == "bibitem") {
3426 context.check_layout(os);
3427 eat_whitespace(p, os, context, false);
3428 string label = p.verbatimOption();
3429 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3430 bool const literal = !lbl.first;
3431 label = literal ? subst(label, "\n", " ") : lbl.second;
3432 string lit = literal ? "\"true\"" : "\"false\"";
3433 string key = convert_literate_command_inset_arg(p.verbatim_item());
3434 begin_command_inset(os, "bibitem", "bibitem");
3435 os << "label \"" << label << "\"\n"
3436 << "key \"" << key << "\"\n"
3437 << "literal " << lit << "\n";
3443 // catch the case of \def\inputGnumericTable
3445 if (t.cs() == "def") {
3446 Token second = p.next_token();
3447 if (second.cs() == "inputGnumericTable") {
3451 Token third = p.get_token();
3453 if (third.cs() == "input") {
3457 string name = normalize_filename(p.verbatim_item());
3458 string const path = getMasterFilePath(true);
3459 // We want to preserve relative / absolute filenames,
3460 // therefore path is only used for testing
3461 // The file extension is in every case ".tex".
3462 // So we need to remove this extension and check for
3463 // the original one.
3464 name = removeExtension(name);
3465 if (!makeAbsPath(name, path).exists()) {
3466 char const * const Gnumeric_formats[] = {"gnumeric",
3468 string const Gnumeric_name =
3469 find_file(name, path, Gnumeric_formats);
3470 if (!Gnumeric_name.empty())
3471 name = Gnumeric_name;
3473 FileName const absname = makeAbsPath(name, path);
3474 if (absname.exists()) {
3475 fix_child_filename(name);
3476 copy_file(absname, name);
3478 cerr << "Warning: Could not find file '"
3479 << name << "'." << endl;
3480 context.check_layout(os);
3481 begin_inset(os, "External\n\ttemplate ");
3482 os << "GnumericSpreadsheet\n\tfilename "
3485 context.check_layout(os);
3487 // register the packages that are automatically loaded
3488 // by the Gnumeric template
3489 registerExternalTemplatePackages("GnumericSpreadsheet");
3494 parse_macro(p, os, context);
3498 if (t.cs() == "noindent") {
3500 context.add_par_extra_stuff("\\noindent\n");
3504 if (t.cs() == "appendix") {
3505 context.add_par_extra_stuff("\\start_of_appendix\n");
3506 // We need to start a new paragraph. Otherwise the
3507 // appendix in 'bla\appendix\chapter{' would start
3509 context.new_paragraph(os);
3510 // We need to make sure that the paragraph is
3511 // generated even if it is empty. Otherwise the
3512 // appendix in '\par\appendix\par\chapter{' would
3514 context.check_layout(os);
3515 // FIXME: This is a hack to prevent paragraph
3516 // deletion if it is empty. Handle this better!
3517 output_comment(p, os,
3518 "dummy comment inserted by tex2lyx to "
3519 "ensure that this paragraph is not empty",
3521 // Both measures above may generate an additional
3522 // empty paragraph, but that does not hurt, because
3523 // whitespace does not matter here.
3524 eat_whitespace(p, os, context, true);
3528 // Must catch empty dates before findLayout is called below
3529 if (t.cs() == "date") {
3530 eat_whitespace(p, os, context, false);
3532 string const date = p.verbatim_item();
3535 preamble.suppressDate(true);
3538 preamble.suppressDate(false);
3539 if (context.new_layout_allowed &&
3540 (newlayout = findLayout(context.textclass,
3543 output_command_layout(os, p, outer,
3544 context, newlayout);
3545 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3546 if (!preamble.titleLayoutFound())
3547 preamble.titleLayoutFound(newlayout->intitle);
3548 set<string> const & req = newlayout->required();
3549 set<string>::const_iterator it = req.begin();
3550 set<string>::const_iterator en = req.end();
3551 for (; it != en; ++it)
3552 preamble.registerAutomaticallyLoadedPackage(*it);
3554 output_ert_inset(os,
3555 "\\date{" + p.verbatim_item() + '}',
3561 // Before we look for the layout name with star and alone below, we check the layouts including
3562 // the LateXParam, which might be one or several options or a star.
3563 // The single '=' is meant here.
3564 if (context.new_layout_allowed &&
3565 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3566 // store the latexparam here. This is eaten in output_command_layout
3567 context.latexparam = newlayout->latexparam();
3569 output_command_layout(os, p, outer, context, newlayout);
3570 context.latexparam.clear();
3572 if (!preamble.titleLayoutFound())
3573 preamble.titleLayoutFound(newlayout->intitle);
3574 set<string> const & req = newlayout->required();
3575 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3576 preamble.registerAutomaticallyLoadedPackage(*it);
3580 // Starred section headings
3581 // Must attempt to parse "Section*" before "Section".
3582 if ((p.next_token().asInput() == "*") &&
3583 context.new_layout_allowed &&
3584 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3587 output_command_layout(os, p, outer, context, newlayout);
3589 if (!preamble.titleLayoutFound())
3590 preamble.titleLayoutFound(newlayout->intitle);
3591 set<string> const & req = newlayout->required();
3592 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3593 preamble.registerAutomaticallyLoadedPackage(*it);
3597 // Section headings and the like
3598 if (context.new_layout_allowed &&
3599 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3601 output_command_layout(os, p, outer, context, newlayout);
3603 if (!preamble.titleLayoutFound())
3604 preamble.titleLayoutFound(newlayout->intitle);
3605 set<string> const & req = newlayout->required();
3606 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3607 preamble.registerAutomaticallyLoadedPackage(*it);
3611 if (t.cs() == "subfloat") {
3612 // the syntax is \subfloat[list entry][sub caption]{content}
3613 // if it is a table of figure depends on the surrounding float
3615 // do nothing if there is no outer float
3616 if (!float_type.empty()) {
3617 context.check_layout(os);
3619 begin_inset(os, "Float " + float_type + "\n");
3621 << "\nsideways false"
3622 << "\nstatus collapsed\n\n";
3625 bool has_caption = false;
3626 if (p.next_token().cat() != catEscape &&
3627 p.next_token().character() == '[') {
3628 p.get_token(); // eat '['
3629 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3632 // In case we have two optional args, the second is the caption.
3633 if (p.next_token().cat() != catEscape &&
3634 p.next_token().character() == '[') {
3635 p.get_token(); // eat '['
3636 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3639 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3640 // the caption comes always as the last
3642 // we must make sure that the caption gets a \begin_layout
3643 os << "\n\\begin_layout Plain Layout";
3645 begin_inset(os, "Caption Standard\n");
3646 Context newcontext(true, context.textclass,
3647 0, 0, context.font);
3648 newcontext.check_layout(os);
3649 os << caption << "\n";
3650 newcontext.check_end_layout(os);
3653 // close the layout we opened
3654 os << "\n\\end_layout";
3659 // if the float type is not supported or there is no surrounding float
3664 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3666 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3668 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3669 + "{" + p.verbatim_item() + '}', context);
3674 if (t.cs() == "xymatrix") {
3675 // we must open a new math because LyX's xy support is in math
3676 context.check_layout(os);
3677 begin_inset(os, "Formula ");
3679 os << "\\" << t.cs() << '{';
3680 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3683 preamble.registerAutomaticallyLoadedPackage("xy");
3687 if (t.cs() == "includegraphics") {
3688 bool const clip = p.next_token().asInput() == "*";
3691 string const arg = p.getArg('[', ']');
3692 map<string, string> opts;
3693 vector<string> keys;
3694 split_map(arg, opts, keys);
3696 opts["clip"] = string();
3697 string name = normalize_filename(p.verbatim_item());
3699 string const path = getMasterFilePath(true);
3700 // We want to preserve relative / absolute filenames,
3701 // therefore path is only used for testing
3702 if (!makeAbsPath(name, path).exists()) {
3703 // The file extension is probably missing.
3704 // Now try to find it out.
3705 string const dvips_name =
3706 find_file(name, path,
3707 known_dvips_graphics_formats);
3708 string const pdftex_name =
3709 find_file(name, path,
3710 known_pdftex_graphics_formats);
3711 if (!dvips_name.empty()) {
3712 if (!pdftex_name.empty()) {
3713 cerr << "This file contains the "
3715 "\"\\includegraphics{"
3717 "However, files\n\""
3718 << dvips_name << "\" and\n\""
3719 << pdftex_name << "\"\n"
3720 "both exist, so I had to make a "
3721 "choice and took the first one.\n"
3722 "Please move the unwanted one "
3723 "someplace else and try again\n"
3724 "if my choice was wrong."
3728 } else if (!pdftex_name.empty()) {
3734 FileName const absname = makeAbsPath(name, path);
3735 if (absname.exists()) {
3736 fix_child_filename(name);
3737 copy_file(absname, name);
3739 cerr << "Warning: Could not find graphics file '"
3740 << name << "'." << endl;
3742 context.check_layout(os);
3743 begin_inset(os, "Graphics ");
3744 os << "\n\tfilename " << name << '\n';
3745 if (opts.find("width") != opts.end())
3747 << translate_len(opts["width"]) << '\n';
3748 if (opts.find("totalheight") != opts.end())
3750 << translate_len(opts["totalheight"]) << '\n';
3751 if (opts.find("scale") != opts.end()) {
3752 istringstream iss(opts["scale"]);
3756 os << "\tscale " << val << '\n';
3758 if (opts.find("angle") != opts.end()) {
3759 os << "\trotateAngle "
3760 << opts["angle"] << '\n';
3761 vector<string>::const_iterator a =
3762 find(keys.begin(), keys.end(), "angle");
3763 vector<string>::const_iterator s =
3764 find(keys.begin(), keys.end(), "width");
3765 if (s == keys.end())
3766 s = find(keys.begin(), keys.end(), "totalheight");
3767 if (s == keys.end())
3768 s = find(keys.begin(), keys.end(), "scale");
3769 if (s != keys.end() && distance(s, a) > 0)
3770 os << "\tscaleBeforeRotation\n";
3772 if (opts.find("origin") != opts.end()) {
3774 string const opt = opts["origin"];
3775 if (opt.find('l') != string::npos) ss << "left";
3776 if (opt.find('r') != string::npos) ss << "right";
3777 if (opt.find('c') != string::npos) ss << "center";
3778 if (opt.find('t') != string::npos) ss << "Top";
3779 if (opt.find('b') != string::npos) ss << "Bottom";
3780 if (opt.find('B') != string::npos) ss << "Baseline";
3781 if (!ss.str().empty())
3782 os << "\trotateOrigin " << ss.str() << '\n';
3784 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3786 if (opts.find("keepaspectratio") != opts.end())
3787 os << "\tkeepAspectRatio\n";
3788 if (opts.find("clip") != opts.end())
3790 if (opts.find("draft") != opts.end())
3792 if (opts.find("bb") != opts.end())
3793 os << "\tBoundingBox "
3794 << opts["bb"] << '\n';
3795 int numberOfbbOptions = 0;
3796 if (opts.find("bbllx") != opts.end())
3797 numberOfbbOptions++;
3798 if (opts.find("bblly") != opts.end())
3799 numberOfbbOptions++;
3800 if (opts.find("bburx") != opts.end())
3801 numberOfbbOptions++;
3802 if (opts.find("bbury") != opts.end())
3803 numberOfbbOptions++;
3804 if (numberOfbbOptions == 4)
3805 os << "\tBoundingBox "
3806 << opts["bbllx"] << " " << opts["bblly"] << " "
3807 << opts["bburx"] << " " << opts["bbury"] << '\n';
3808 else if (numberOfbbOptions > 0)
3809 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3810 numberOfbbOptions = 0;
3811 if (opts.find("natwidth") != opts.end())
3812 numberOfbbOptions++;
3813 if (opts.find("natheight") != opts.end())
3814 numberOfbbOptions++;
3815 if (numberOfbbOptions == 2)
3816 os << "\tBoundingBox 0bp 0bp "
3817 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3818 else if (numberOfbbOptions > 0)
3819 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3820 ostringstream special;
3821 if (opts.find("hiresbb") != opts.end())
3822 special << "hiresbb,";
3823 if (opts.find("trim") != opts.end())
3825 if (opts.find("viewport") != opts.end())
3826 special << "viewport=" << opts["viewport"] << ',';
3827 if (opts.find("height") != opts.end())
3828 special << "height=" << opts["height"] << ',';
3829 if (opts.find("type") != opts.end())
3830 special << "type=" << opts["type"] << ',';
3831 if (opts.find("ext") != opts.end())
3832 special << "ext=" << opts["ext"] << ',';
3833 if (opts.find("read") != opts.end())
3834 special << "read=" << opts["read"] << ',';
3835 if (opts.find("command") != opts.end())
3836 special << "command=" << opts["command"] << ',';
3837 string s_special = special.str();
3838 if (!s_special.empty()) {
3839 // We had special arguments. Remove the trailing ','.
3840 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3842 // TODO: Handle the unknown settings better.
3843 // Warn about invalid options.
3844 // Check whether some option was given twice.
3846 preamble.registerAutomaticallyLoadedPackage("graphicx");
3850 if (t.cs() == "footnote" ||
3851 (t.cs() == "thanks" && context.layout->intitle)) {
3853 context.check_layout(os);
3854 begin_inset(os, "Foot\n");
3855 os << "status collapsed\n\n";
3856 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3861 if (t.cs() == "marginpar") {
3863 context.check_layout(os);
3864 begin_inset(os, "Marginal\n");
3865 os << "status collapsed\n\n";
3866 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3871 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3872 bool const use_minted = t.cs() == "mintinline";
3874 parse_listings(p, os, context, true, use_minted);
3878 if (t.cs() == "ensuremath") {
3880 context.check_layout(os);
3881 string const s = p.verbatim_item();
3882 //FIXME: this never triggers in UTF8
3883 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3886 output_ert_inset(os, "\\ensuremath{" + s + "}",
3891 else if (t.cs() == "makeindex"
3892 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3893 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3894 if (preamble.titleLayoutFound()) {
3896 skip_spaces_braces(p);
3898 output_ert_inset(os, t.asInput(), context);
3902 if (t.cs() == "tableofcontents"
3903 || t.cs() == "lstlistoflistings"
3904 || t.cs() == "listoflistings") {
3905 string name = t.cs();
3906 if (preamble.minted() && name == "listoflistings")
3907 name.insert(0, "lst");
3908 context.check_layout(os);
3909 begin_command_inset(os, "toc", name);
3911 skip_spaces_braces(p);
3912 if (name == "lstlistoflistings") {
3913 if (preamble.minted())
3914 preamble.registerAutomaticallyLoadedPackage("minted");
3916 preamble.registerAutomaticallyLoadedPackage("listings");
3921 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3922 context.check_layout(os);
3923 if (t.cs() == "listoffigures")
3924 begin_inset(os, "FloatList figure\n");
3926 begin_inset(os, "FloatList table\n");
3928 skip_spaces_braces(p);
3932 if (t.cs() == "listof") {
3933 p.skip_spaces(true);
3934 string const name = p.verbatim_item();
3935 if (context.textclass.floats().typeExist(name)) {
3936 context.check_layout(os);
3937 begin_inset(os, "FloatList ");
3940 p.verbatim_item(); // swallow second arg
3942 output_ert_inset(os, "\\listof{" + name + "}", context);
3946 if (t.cs() == "theendnotes"
3947 || (t.cs() == "printendnotes"
3948 && p.next_token().asInput() != "*"
3950 context.check_layout(os);
3951 begin_inset(os, "FloatList endnote\n");
3953 skip_spaces_braces(p);
3957 if ((where = is_known(t.cs(), known_text_font_families))) {
3958 parse_text_attributes(p, os, FLAG_ITEM, outer,
3959 context, "\\family", context.font.family,
3960 known_coded_font_families[where - known_text_font_families]);
3964 // beamer has a \textbf<overlay>{} inset
3965 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3966 parse_text_attributes(p, os, FLAG_ITEM, outer,
3967 context, "\\series", context.font.series,
3968 known_coded_font_series[where - known_text_font_series]);
3972 // beamer has a \textit<overlay>{} inset
3973 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3974 parse_text_attributes(p, os, FLAG_ITEM, outer,
3975 context, "\\shape", context.font.shape,
3976 known_coded_font_shapes[where - known_text_font_shapes]);
3980 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3981 context.check_layout(os);
3982 TeXFont oldFont = context.font;
3983 context.font.init();
3984 context.font.size = oldFont.size;
3985 os << "\n\\family " << context.font.family << "\n";
3986 os << "\n\\series " << context.font.series << "\n";
3987 os << "\n\\shape " << context.font.shape << "\n";
3988 if (t.cs() == "textnormal") {
3989 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3990 output_font_change(os, context.font, oldFont);
3991 context.font = oldFont;
3993 eat_whitespace(p, os, context, false);
3997 if (t.cs() == "textcolor") {
3998 // scheme is \textcolor{color name}{text}
3999 string const color = p.verbatim_item();
4000 // we support the predefined colors of the color and the xcolor package
4001 if (color == "black" || color == "blue" || color == "cyan"
4002 || color == "green" || color == "magenta" || color == "red"
4003 || color == "white" || color == "yellow") {
4004 context.check_layout(os);
4005 os << "\n\\color " << color << "\n";
4006 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4007 context.check_layout(os);
4008 os << "\n\\color inherit\n";
4009 preamble.registerAutomaticallyLoadedPackage("color");
4010 } else if (color == "brown" || color == "darkgray" || color == "gray"
4011 || color == "lightgray" || color == "lime" || color == "olive"
4012 || color == "orange" || color == "pink" || color == "purple"
4013 || color == "teal" || color == "violet") {
4014 context.check_layout(os);
4015 os << "\n\\color " << color << "\n";
4016 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4017 context.check_layout(os);
4018 os << "\n\\color inherit\n";
4019 preamble.registerAutomaticallyLoadedPackage("xcolor");
4021 // for custom defined colors
4022 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4026 if (t.cs() == "underbar" || t.cs() == "uline") {
4027 // \underbar is not 100% correct (LyX outputs \uline
4028 // of ulem.sty). The difference is that \ulem allows
4029 // line breaks, and \underbar does not.
4030 // Do NOT handle \underline.
4031 // \underbar cuts through y, g, q, p etc.,
4032 // \underline does not.
4033 context.check_layout(os);
4034 os << "\n\\bar under\n";
4035 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4036 context.check_layout(os);
4037 os << "\n\\bar default\n";
4038 preamble.registerAutomaticallyLoadedPackage("ulem");
4042 if (t.cs() == "sout") {
4043 context.check_layout(os);
4044 os << "\n\\strikeout on\n";
4045 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4046 context.check_layout(os);
4047 os << "\n\\strikeout default\n";
4048 preamble.registerAutomaticallyLoadedPackage("ulem");
4052 // beamer has an \emph<overlay>{} inset
4053 if ((t.cs() == "uuline" || t.cs() == "uwave"
4054 || t.cs() == "emph" || t.cs() == "noun"
4055 || t.cs() == "xout") && !p.hasOpt("<")) {
4056 context.check_layout(os);
4057 os << "\n\\" << t.cs() << " on\n";
4058 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4059 context.check_layout(os);
4060 os << "\n\\" << t.cs() << " default\n";
4061 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4062 preamble.registerAutomaticallyLoadedPackage("ulem");
4066 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4067 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4068 context.check_layout(os);
4071 initials = p.getArg('[', ']');
4073 string name = p.getArg('{', '}');
4074 string localtime = p.getArg('{', '}');
4075 preamble.registerAuthor(name, initials);
4076 Author const & author = preamble.getAuthor(name);
4077 // from_asctime_utc() will fail if LyX decides to output the
4078 // time in the text language.
4079 time_t ptime = from_asctime_utc(localtime);
4080 if (ptime == static_cast<time_t>(-1)) {
4081 cerr << "Warning: Could not parse time `" << localtime
4082 << "´ for change tracking, using current time instead.\n";
4083 ptime = current_time();
4085 if (t.cs() == "lyxadded")
4086 os << "\n\\change_inserted ";
4088 os << "\n\\change_deleted ";
4089 os << author.bufferId() << ' ' << ptime << '\n';
4090 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4091 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4092 LaTeXPackages::isAvailable("xcolor");
4093 // No need to test for luatex, since luatex comes in
4094 // two flavours (dvi and pdf), like latex, and those
4095 // are detected by pdflatex.
4096 if (pdflatex || xetex) {
4098 preamble.registerAutomaticallyLoadedPackage("ulem");
4099 preamble.registerAutomaticallyLoadedPackage("xcolor");
4100 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4104 preamble.registerAutomaticallyLoadedPackage("ulem");
4105 preamble.registerAutomaticallyLoadedPackage("xcolor");
4111 if (t.cs() == "textipa") {
4112 context.check_layout(os);
4113 begin_inset(os, "IPA\n");
4114 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4115 context.merging_hyphens_allowed = false;
4116 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4117 context.merging_hyphens_allowed = merging_hyphens_allowed;
4119 preamble.registerAutomaticallyLoadedPackage("tipa");
4120 preamble.registerAutomaticallyLoadedPackage("tipx");
4124 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4125 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4126 context.check_layout(os);
4130 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4131 begin_inset(os, "IPADeco " + type + "\n");
4132 os << "status open\n";
4133 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4139 if (t.cs() == "textvertline") {
4140 // FIXME: This is not correct, \textvertline is higher than |
4146 if (t.cs() == "tone" ) {
4147 context.check_layout(os);
4148 // register the tone package
4149 preamble.registerAutomaticallyLoadedPackage("tone");
4150 string content = trimSpaceAndEol(p.verbatim_item());
4151 string command = t.asInput() + "{" + content + "}";
4152 // some tones can be detected by unicodesymbols, some need special code
4153 if (is_known(content, known_tones)) {
4154 os << "\\IPAChar " << command << "\n";
4157 // try to see whether the string is in unicodesymbols
4161 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4162 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4163 termination, rem, &req);
4167 output_ert_inset(os, to_utf8(rem), context);
4168 for (set<string>::const_iterator it = req.begin();
4169 it != req.end(); ++it)
4170 preamble.registerAutomaticallyLoadedPackage(*it);
4172 // we did not find a non-ert version
4173 output_ert_inset(os, command, context);
4177 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4178 t.cs() == "vphantom") {
4179 context.check_layout(os);
4180 if (t.cs() == "phantom")
4181 begin_inset(os, "Phantom Phantom\n");
4182 if (t.cs() == "hphantom")
4183 begin_inset(os, "Phantom HPhantom\n");
4184 if (t.cs() == "vphantom")
4185 begin_inset(os, "Phantom VPhantom\n");
4186 os << "status open\n";
4187 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4193 if (t.cs() == "href") {
4194 context.check_layout(os);
4195 string target = convert_literate_command_inset_arg(p.verbatim_item());
4196 string name = p.verbatim_item();
4197 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4198 bool const literal = !nm.first;
4199 name = literal ? subst(name, "\n", " ") : nm.second;
4200 string lit = literal ? "\"true\"" : "\"false\"";
4202 size_t i = target.find(':');
4203 if (i != string::npos) {
4204 type = target.substr(0, i + 1);
4205 if (type == "mailto:" || type == "file:")
4206 target = target.substr(i + 1);
4207 // handle the case that name is equal to target, except of "http(s)://"
4208 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4211 begin_command_inset(os, "href", "href");
4213 os << "name \"" << name << "\"\n";
4214 os << "target \"" << target << "\"\n";
4215 if (type == "mailto:" || type == "file:")
4216 os << "type \"" << type << "\"\n";
4217 os << "literal " << lit << "\n";
4219 skip_spaces_braces(p);
4223 if (t.cs() == "lyxline") {
4224 // swallow size argument (it is not used anyway)
4226 if (!context.atParagraphStart()) {
4227 // so our line is in the middle of a paragraph
4228 // we need to add a new line, lest this line
4229 // follow the other content on that line and
4230 // run off the side of the page
4231 // FIXME: This may create an empty paragraph,
4232 // but without that it would not be
4233 // possible to set noindent below.
4234 // Fortunately LaTeX does not care
4235 // about the empty paragraph.
4236 context.new_paragraph(os);
4238 if (preamble.indentParagraphs()) {
4239 // we need to unindent, lest the line be too long
4240 context.add_par_extra_stuff("\\noindent\n");
4242 context.check_layout(os);
4243 begin_command_inset(os, "line", "rule");
4244 os << "offset \"0.5ex\"\n"
4245 "width \"100line%\"\n"
4251 if (t.cs() == "rule") {
4252 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4253 string const width = p.getArg('{', '}');
4254 string const thickness = p.getArg('{', '}');
4255 context.check_layout(os);
4256 begin_command_inset(os, "line", "rule");
4257 if (!offset.empty())
4258 os << "offset \"" << translate_len(offset) << "\"\n";
4259 os << "width \"" << translate_len(width) << "\"\n"
4260 "height \"" << translate_len(thickness) << "\"\n";
4265 // Handle refstyle first in order to to catch \eqref, because this
4266 // can also occur without refstyle. Only recognize these commands if
4267 // refstyle.sty was found in the preamble (otherwise \eqref
4268 // and user defined ref commands could be misdetected).
4269 // We uncapitalize the input in order to catch capitalized commands
4271 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4272 && preamble.refstyle()) {
4273 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4274 string plural = "false";
4275 // Catch the plural option [s]
4277 string const opt = p.getOpt();
4281 // LyX does not yet support other optional arguments of ref commands
4282 output_ert_inset(os, t.asInput() + opt + "{" +
4283 p.verbatim_item() + '}', context);
4287 context.check_layout(os);
4288 begin_command_inset(os, "ref", "formatted");
4289 os << "reference \"";
4290 os << known_refstyle_prefixes[where - known_refstyle_commands]
4292 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4294 os << "plural \"" << plural << "\"\n";
4295 os << "caps \"" << cap << "\"\n";
4296 os << "noprefix \"false\"\n";
4298 preamble.registerAutomaticallyLoadedPackage("refstyle");
4302 // if refstyle is used, we must not convert \prettyref to a
4303 // formatted reference, since that would result in a refstyle command.
4304 if ((where = is_known(t.cs(), known_ref_commands)) &&
4305 (t.cs() != "prettyref" || !preamble.refstyle())) {
4306 string const opt = p.getOpt();
4308 context.check_layout(os);
4309 begin_command_inset(os, "ref",
4310 known_coded_ref_commands[where - known_ref_commands]);
4311 os << "reference \""
4312 << convert_literate_command_inset_arg(p.verbatim_item())
4314 os << "plural \"false\"\n";
4315 os << "caps \"false\"\n";
4316 os << "noprefix \"false\"\n";
4318 if (t.cs() == "vref" || t.cs() == "vpageref")
4319 preamble.registerAutomaticallyLoadedPackage("varioref");
4320 else if (t.cs() == "prettyref")
4321 preamble.registerAutomaticallyLoadedPackage("prettyref");
4323 // LyX does not yet support optional arguments of ref commands
4324 output_ert_inset(os, t.asInput() + opt + "{" +
4325 p.verbatim_item() + '}', context);
4331 is_known(t.cs(), known_natbib_commands) &&
4332 ((t.cs() != "citefullauthor" &&
4333 t.cs() != "citeyear" &&
4334 t.cs() != "citeyearpar") ||
4335 p.next_token().asInput() != "*")) {
4336 context.check_layout(os);
4337 string command = t.cs();
4338 if (p.next_token().asInput() == "*") {
4342 if (command == "citefullauthor")
4343 // alternative name for "\\citeauthor*"
4344 command = "citeauthor*";
4346 // text before the citation
4348 // text after the citation
4350 get_cite_arguments(p, true, before, after);
4352 if (command == "cite") {
4353 // \cite without optional argument means
4354 // \citet, \cite with at least one optional
4355 // argument means \citep.
4356 if (before.empty() && after.empty())
4361 if (before.empty() && after == "[]")
4362 // avoid \citet[]{a}
4364 else if (before == "[]" && after == "[]") {
4365 // avoid \citet[][]{a}
4369 bool literal = false;
4370 pair<bool, string> aft;
4371 pair<bool, string> bef;
4372 // remove the brackets around after and before
4373 if (!after.empty()) {
4375 after.erase(after.length() - 1, 1);
4376 aft = convert_latexed_command_inset_arg(after);
4377 literal = !aft.first;
4378 after = literal ? subst(after, "\n", " ") : aft.second;
4380 if (!before.empty()) {
4382 before.erase(before.length() - 1, 1);
4383 bef = convert_latexed_command_inset_arg(before);
4384 literal |= !bef.first;
4385 before = literal ? subst(before, "\n", " ") : bef.second;
4386 if (literal && !after.empty())
4387 after = subst(after, "\n", " ");
4389 string lit = literal ? "\"true\"" : "\"false\"";
4390 begin_command_inset(os, "citation", command);
4391 os << "after " << '"' << after << '"' << "\n";
4392 os << "before " << '"' << before << '"' << "\n";
4394 << convert_literate_command_inset_arg(p.verbatim_item())
4396 << "literal " << lit << "\n";
4398 // Need to set the cite engine if natbib is loaded by
4399 // the document class directly
4400 if (preamble.citeEngine() == "basic")
4401 preamble.citeEngine("natbib");
4406 && is_known(t.cs(), known_biblatex_commands)
4407 && ((t.cs() == "cite"
4408 || t.cs() == "citeauthor"
4409 || t.cs() == "Citeauthor"
4410 || t.cs() == "parencite"
4411 || t.cs() == "citetitle")
4412 || p.next_token().asInput() != "*"))
4413 || (use_biblatex_natbib
4414 && (is_known(t.cs(), known_biblatex_commands)
4415 || is_known(t.cs(), known_natbib_commands))
4416 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4417 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4418 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4419 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4420 || t.cs() == "parencite" || t.cs() == "citetitle")
4421 || p.next_token().asInput() != "*"))){
4422 context.check_layout(os);
4423 string command = t.cs();
4424 if (p.next_token().asInput() == "*") {
4429 bool const qualified = suffixIs(command, "s");
4431 command = rtrim(command, "s");
4433 // text before the citation
4435 // text after the citation
4437 get_cite_arguments(p, true, before, after, qualified);
4439 // These use natbib cmd names in LyX
4440 // for inter-citeengine compativility
4441 if (command == "citeyear")
4442 command = "citebyear";
4443 else if (command == "cite*")
4444 command = "citeyear";
4445 else if (command == "textcite")
4447 else if (command == "Textcite")
4449 else if (command == "parencite")
4451 else if (command == "Parencite")
4453 else if (command == "parencite*")
4454 command = "citeyearpar";
4455 else if (command == "smartcite")
4456 command = "footcite";
4457 else if (command == "Smartcite")
4458 command = "Footcite";
4460 string const emptyarg = qualified ? "()" : "[]";
4461 if (before.empty() && after == emptyarg)
4464 else if (before == emptyarg && after == emptyarg) {
4465 // avoid \cite[][]{a}
4469 bool literal = false;
4470 pair<bool, string> aft;
4471 pair<bool, string> bef;
4472 // remove the brackets around after and before
4473 if (!after.empty()) {
4475 after.erase(after.length() - 1, 1);
4476 aft = convert_latexed_command_inset_arg(after);
4477 literal = !aft.first;
4478 after = literal ? subst(after, "\n", " ") : aft.second;
4480 if (!before.empty()) {
4482 before.erase(before.length() - 1, 1);
4483 bef = convert_latexed_command_inset_arg(before);
4484 literal |= !bef.first;
4485 before = literal ? subst(before, "\n", " ") : bef.second;
4487 string keys, pretextlist, posttextlist;
4489 vector<pair<string, string>> pres, posts, preslit, postslit;
4490 vector<string> lkeys;
4491 // text before the citation
4492 string lbefore, lbeforelit;
4493 // text after the citation
4494 string lafter, lafterlit;
4496 pair<bool, string> laft, lbef;
4498 get_cite_arguments(p, true, lbefore, lafter);
4499 // remove the brackets around after and before
4500 if (!lafter.empty()) {
4502 lafter.erase(lafter.length() - 1, 1);
4503 laft = convert_latexed_command_inset_arg(lafter);
4504 literal |= !laft.first;
4505 lafter = laft.second;
4506 lafterlit = subst(lafter, "\n", " ");
4508 if (!lbefore.empty()) {
4509 lbefore.erase(0, 1);
4510 lbefore.erase(lbefore.length() - 1, 1);
4511 lbef = convert_latexed_command_inset_arg(lbefore);
4512 literal |= !lbef.first;
4513 lbefore = lbef.second;
4514 lbeforelit = subst(lbefore, "\n", " ");
4516 if (lbefore.empty() && lafter == "[]") {
4521 else if (lbefore == "[]" && lafter == "[]") {
4522 // avoid \cite[][]{a}
4528 lkey = p.getArg('{', '}');
4531 pres.push_back(make_pair(lkey, lbefore));
4532 preslit.push_back(make_pair(lkey, lbeforelit));
4533 posts.push_back(make_pair(lkey, lafter));
4534 postslit.push_back(make_pair(lkey, lafterlit));
4535 lkeys.push_back(lkey);
4537 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4542 for (auto const & ptl : pres) {
4543 if (!pretextlist.empty())
4544 pretextlist += '\t';
4545 pretextlist += ptl.first;
4546 if (!ptl.second.empty())
4547 pretextlist += " " + ptl.second;
4549 for (auto const & potl : posts) {
4550 if (!posttextlist.empty())
4551 posttextlist += '\t';
4552 posttextlist += potl.first;
4553 if (!potl.second.empty())
4554 posttextlist += " " + potl.second;
4557 keys = convert_literate_command_inset_arg(p.verbatim_item());
4560 after = subst(after, "\n", " ");
4561 if (!before.empty())
4562 before = subst(after, "\n", " ");
4564 string lit = literal ? "\"true\"" : "\"false\"";
4565 begin_command_inset(os, "citation", command);
4566 os << "after " << '"' << after << '"' << "\n";
4567 os << "before " << '"' << before << '"' << "\n";
4571 if (!pretextlist.empty())
4572 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4573 if (!posttextlist.empty())
4574 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4575 os << "literal " << lit << "\n";
4577 // Need to set the cite engine if biblatex is loaded by
4578 // the document class directly
4579 if (preamble.citeEngine() == "basic")
4580 use_biblatex_natbib ?
4581 preamble.citeEngine("biblatex-natbib")
4582 : preamble.citeEngine("biblatex");
4587 is_known(t.cs(), known_jurabib_commands) &&
4588 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4589 context.check_layout(os);
4590 string command = t.cs();
4591 if (p.next_token().asInput() == "*") {
4595 char argumentOrder = '\0';
4596 vector<string> const options =
4597 preamble.getPackageOptions("jurabib");
4598 if (find(options.begin(), options.end(),
4599 "natbiborder") != options.end())
4600 argumentOrder = 'n';
4601 else if (find(options.begin(), options.end(),
4602 "jurabiborder") != options.end())
4603 argumentOrder = 'j';
4605 // text before the citation
4607 // text after the citation
4609 get_cite_arguments(p, argumentOrder != 'j', before, after);
4611 string const citation = p.verbatim_item();
4612 if (!before.empty() && argumentOrder == '\0') {
4613 cerr << "Warning: Assuming argument order "
4614 "of jurabib version 0.6 for\n'"
4615 << command << before << after << '{'
4616 << citation << "}'.\n"
4617 "Add 'jurabiborder' to the jurabib "
4618 "package options if you used an\n"
4619 "earlier jurabib version." << endl;
4621 bool literal = false;
4622 pair<bool, string> aft;
4623 pair<bool, string> bef;
4624 // remove the brackets around after and before
4625 if (!after.empty()) {
4627 after.erase(after.length() - 1, 1);
4628 aft = convert_latexed_command_inset_arg(after);
4629 literal = !aft.first;
4630 after = literal ? subst(after, "\n", " ") : aft.second;
4632 if (!before.empty()) {
4634 before.erase(before.length() - 1, 1);
4635 bef = convert_latexed_command_inset_arg(before);
4636 literal |= !bef.first;
4637 before = literal ? subst(before, "\n", " ") : bef.second;
4638 if (literal && !after.empty())
4639 after = subst(after, "\n", " ");
4641 string lit = literal ? "\"true\"" : "\"false\"";
4642 begin_command_inset(os, "citation", command);
4643 os << "after " << '"' << after << "\"\n"
4644 << "before " << '"' << before << "\"\n"
4645 << "key " << '"' << citation << "\"\n"
4646 << "literal " << lit << "\n";
4648 // Need to set the cite engine if jurabib is loaded by
4649 // the document class directly
4650 if (preamble.citeEngine() == "basic")
4651 preamble.citeEngine("jurabib");
4655 if (t.cs() == "cite"
4656 || t.cs() == "nocite") {
4657 context.check_layout(os);
4658 string after = p.getArg('[', ']');
4659 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4660 bool const literal = !aft.first;
4661 after = literal ? subst(after, "\n", " ") : aft.second;
4662 string lit = literal ? "\"true\"" : "\"false\"";
4663 string key = convert_literate_command_inset_arg(p.verbatim_item());
4664 // store the case that it is "\nocite{*}" to use it later for
4667 begin_command_inset(os, "citation", t.cs());
4668 os << "after " << '"' << after << "\"\n"
4669 << "key " << '"' << key << "\"\n"
4670 << "literal " << lit << "\n";
4672 } else if (t.cs() == "nocite")
4677 if (t.cs() == "index" ||
4678 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4679 context.check_layout(os);
4680 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4681 p.getArg('[', ']') : "";
4682 string const kind = arg.empty() ? "idx" : arg;
4683 begin_inset(os, "Index ");
4684 os << kind << "\nstatus collapsed\n";
4685 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4688 preamble.registerAutomaticallyLoadedPackage("splitidx");
4692 if (t.cs() == "nomenclature") {
4693 context.check_layout(os);
4694 begin_command_inset(os, "nomenclature", "nomenclature");
4695 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4696 if (!prefix.empty())
4697 os << "prefix " << '"' << prefix << '"' << "\n";
4698 string symbol = p.verbatim_item();
4699 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4700 bool literal = !sym.first;
4701 string description = p.verbatim_item();
4702 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4703 literal |= !desc.first;
4705 symbol = subst(symbol, "\n", " ");
4706 description = subst(description, "\n", " ");
4708 symbol = sym.second;
4709 description = desc.second;
4711 string lit = literal ? "\"true\"" : "\"false\"";
4712 os << "symbol " << '"' << symbol;
4713 os << "\"\ndescription \""
4714 << description << "\"\n"
4715 << "literal " << lit << "\n";
4717 preamble.registerAutomaticallyLoadedPackage("nomencl");
4721 if (t.cs() == "label") {
4722 context.check_layout(os);
4723 begin_command_inset(os, "label", "label");
4725 << convert_literate_command_inset_arg(p.verbatim_item())
4731 if (t.cs() == "lyxmintcaption") {
4732 string const pos = p.getArg('[', ']');
4734 string const caption =
4735 parse_text_snippet(p, FLAG_ITEM, false,
4737 minted_nonfloat_caption = "[t]" + caption;
4739 // We already got the caption at the bottom,
4740 // so simply skip it.
4741 parse_text_snippet(p, FLAG_ITEM, false, context);
4743 eat_whitespace(p, os, context, true);
4747 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4748 context.check_layout(os);
4749 string commandname = t.cs();
4751 if (p.next_token().asInput() == "*") {
4756 begin_command_inset(os, "index_print", commandname);
4757 string const indexname = p.getArg('[', ']');
4759 if (indexname.empty())
4760 os << "type \"idx\"\n";
4762 os << "type \"" << indexname << "\"\n";
4763 os << "literal \"true\"\n";
4766 skip_spaces_braces(p);
4767 preamble.registerAutomaticallyLoadedPackage("makeidx");
4768 if (preamble.use_indices() == "true")
4769 preamble.registerAutomaticallyLoadedPackage("splitidx");
4773 if (t.cs() == "printnomenclature") {
4775 string width_type = "";
4776 context.check_layout(os);
4777 begin_command_inset(os, "nomencl_print", "printnomenclature");
4778 // case of a custom width
4780 width = p.getArg('[', ']');
4781 width = translate_len(width);
4782 width_type = "custom";
4784 // case of no custom width
4785 // the case of no custom width but the width set
4786 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4787 // because the user could have set anything, not only the width
4788 // of the longest label (which would be width_type = "auto")
4789 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4790 if (label.empty() && width_type.empty())
4791 width_type = "none";
4792 os << "set_width \"" << width_type << "\"\n";
4793 if (width_type == "custom")
4794 os << "width \"" << width << '\"';
4796 skip_spaces_braces(p);
4797 preamble.registerAutomaticallyLoadedPackage("nomencl");
4801 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4802 context.check_layout(os);
4803 begin_inset(os, "script ");
4804 os << t.cs().substr(4) << '\n';
4805 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4806 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4808 if (t.cs() == "textsubscript")
4809 preamble.registerAutomaticallyLoadedPackage("subscript");
4813 if ((where = is_known(t.cs(), known_quotes))) {
4814 context.check_layout(os);
4815 begin_inset(os, "Quotes ");
4816 string quotetype = known_coded_quotes[where - known_quotes];
4817 // try to make a smart guess about the side
4818 Token const prev = p.prev_token();
4819 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4820 && prev.character() != '\n' && prev.character() != '~');
4821 quotetype = guessQuoteStyle(quotetype, opening);
4824 // LyX adds {} after the quote, so we have to eat
4825 // spaces here if there are any before a possible
4827 eat_whitespace(p, os, context, false);
4832 if ((where = is_known(t.cs(), known_sizes)) &&
4833 context.new_layout_allowed) {
4834 context.check_layout(os);
4835 TeXFont const oldFont = context.font;
4836 context.font.size = known_coded_sizes[where - known_sizes];
4837 output_font_change(os, oldFont, context.font);
4838 eat_whitespace(p, os, context, false);
4842 if ((where = is_known(t.cs(), known_font_families)) &&
4843 context.new_layout_allowed) {
4844 context.check_layout(os);
4845 TeXFont const oldFont = context.font;
4846 context.font.family =
4847 known_coded_font_families[where - known_font_families];
4848 output_font_change(os, oldFont, context.font);
4849 eat_whitespace(p, os, context, false);
4853 if ((where = is_known(t.cs(), known_font_series)) &&
4854 context.new_layout_allowed) {
4855 context.check_layout(os);
4856 TeXFont const oldFont = context.font;
4857 context.font.series =
4858 known_coded_font_series[where - known_font_series];
4859 output_font_change(os, oldFont, context.font);
4860 eat_whitespace(p, os, context, false);
4864 if ((where = is_known(t.cs(), known_font_shapes)) &&
4865 context.new_layout_allowed) {
4866 context.check_layout(os);
4867 TeXFont const oldFont = context.font;
4868 context.font.shape =
4869 known_coded_font_shapes[where - known_font_shapes];
4870 output_font_change(os, oldFont, context.font);
4871 eat_whitespace(p, os, context, false);
4874 if ((where = is_known(t.cs(), known_old_font_families)) &&
4875 context.new_layout_allowed) {
4876 context.check_layout(os);
4877 TeXFont const oldFont = context.font;
4878 context.font.init();
4879 context.font.size = oldFont.size;
4880 context.font.family =
4881 known_coded_font_families[where - known_old_font_families];
4882 output_font_change(os, oldFont, context.font);
4883 eat_whitespace(p, os, context, false);
4887 if ((where = is_known(t.cs(), known_old_font_series)) &&
4888 context.new_layout_allowed) {
4889 context.check_layout(os);
4890 TeXFont const oldFont = context.font;
4891 context.font.init();
4892 context.font.size = oldFont.size;
4893 context.font.series =
4894 known_coded_font_series[where - known_old_font_series];
4895 output_font_change(os, oldFont, context.font);
4896 eat_whitespace(p, os, context, false);
4900 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4901 context.new_layout_allowed) {
4902 context.check_layout(os);
4903 TeXFont const oldFont = context.font;
4904 context.font.init();
4905 context.font.size = oldFont.size;
4906 context.font.shape =
4907 known_coded_font_shapes[where - known_old_font_shapes];
4908 output_font_change(os, oldFont, context.font);
4909 eat_whitespace(p, os, context, false);
4913 if (t.cs() == "selectlanguage") {
4914 context.check_layout(os);
4915 // save the language for the case that a
4916 // \foreignlanguage is used
4917 context.font.language = babel2lyx(p.verbatim_item());
4918 os << "\n\\lang " << context.font.language << "\n";
4922 if (t.cs() == "foreignlanguage") {
4923 string const lang = babel2lyx(p.verbatim_item());
4924 parse_text_attributes(p, os, FLAG_ITEM, outer,
4926 context.font.language, lang);
4930 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4931 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4932 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4934 // We have to output the whole command if it has an option
4935 // because LyX doesn't support this yet, see bug #8214,
4936 // only if there is a single option specifying a variant, we can handle it.
4938 string langopts = p.getOpt();
4939 // check if the option contains a variant, if yes, extract it
4940 string::size_type pos_var = langopts.find("variant");
4941 string::size_type i = langopts.find(',');
4942 string::size_type k = langopts.find('=', pos_var);
4943 if (pos_var != string::npos && i == string::npos) {
4945 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4946 lang = preamble.polyglossia2lyx(variant);
4947 parse_text_attributes(p, os, FLAG_ITEM, outer,
4949 context.font.language, lang);
4951 output_ert_inset(os, t.asInput() + langopts, context);
4953 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4954 parse_text_attributes(p, os, FLAG_ITEM, outer,
4956 context.font.language, lang);
4961 if (t.cs() == "inputencoding") {
4962 // nothing to write here
4963 string const enc = subst(p.verbatim_item(), "\n", " ");
4964 p.setEncoding(enc, Encoding::inputenc);
4968 if (is_known(t.cs(), known_special_chars) ||
4969 (t.cs() == "protect" &&
4970 p.next_token().cat() == catEscape &&
4971 is_known(p.next_token().cs(), known_special_protect_chars))) {
4972 // LyX sometimes puts a \protect in front, so we have to ignore it
4974 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4975 known_special_chars);
4976 context.check_layout(os);
4977 os << known_coded_special_chars[where - known_special_chars];
4978 skip_spaces_braces(p);
4982 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4983 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4984 p.next_next_token().asInput() == "-") ||
4985 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4986 // LyX sometimes puts a \protect in front, so we have to ignore it
4987 if (t.cs() == "protect")
4989 context.check_layout(os);
4990 if (t.cs() == "nobreakdash")
4991 os << "\\SpecialChar nobreakdash\n";
4993 os << "\\SpecialChar endofsentence\n";
4998 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4999 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5000 || t.cs() == "%" || t.cs() == "-") {
5001 context.check_layout(os);
5003 os << "\\SpecialChar softhyphen\n";
5009 if (t.cs() == "char") {
5010 context.check_layout(os);
5011 if (p.next_token().character() == '`') {
5013 if (p.next_token().cs() == "\"") {
5018 output_ert_inset(os, "\\char`", context);
5021 output_ert_inset(os, "\\char", context);
5026 if (t.cs() == "verb") {
5027 context.check_layout(os);
5028 // set catcodes to verbatim early, just in case.
5029 p.setCatcodes(VERBATIM_CATCODES);
5030 string delim = p.get_token().asInput();
5031 Parser::Arg arg = p.verbatimStuff(delim);
5033 output_ert_inset(os, "\\verb" + delim
5034 + arg.second + delim, context);
5036 cerr << "invalid \\verb command. Skipping" << endl;
5040 // Problem: \= creates a tabstop inside the tabbing environment
5041 // and else an accent. In the latter case we really would want
5042 // \={o} instead of \= o.
5043 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5044 output_ert_inset(os, t.asInput(), context);
5048 if (t.cs() == "\\") {
5049 context.check_layout(os);
5051 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5052 else if (p.next_token().asInput() == "*") {
5054 // getOpt() eats the following space if there
5055 // is no optional argument, but that is OK
5056 // here since it has no effect in the output.
5057 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5060 begin_inset(os, "Newline newline");
5066 if (t.cs() == "newline" ||
5067 (t.cs() == "linebreak" && !p.hasOpt())) {
5068 context.check_layout(os);
5069 begin_inset(os, "Newline ");
5072 skip_spaces_braces(p);
5076 if (t.cs() == "input" || t.cs() == "include"
5077 || t.cs() == "verbatiminput"
5078 || t.cs() == "lstinputlisting"
5079 || t.cs() == "inputminted") {
5080 string name = t.cs();
5081 if (name == "verbatiminput"
5082 && p.next_token().asInput() == "*")
5083 name += p.get_token().asInput();
5084 context.check_layout(os);
5086 bool literal = false;
5087 if (name == "lstinputlisting" && p.hasOpt()) {
5088 lstparams = p.getArg('[', ']');
5089 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5090 literal = !oa.first;
5092 lstparams = subst(lstparams, "\n", " ");
5094 lstparams = oa.second;
5095 } else if (name == "inputminted") {
5096 name = "lstinputlisting";
5097 string const lang = p.getArg('{', '}');
5098 if (lang != "tex") {
5099 string cmd = "\\inputminted{" + lang + "}{";
5100 cmd += p.getArg('{', '}') + "}";
5101 output_ert_inset(os, cmd, context);
5104 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5105 minted_nonfloat_caption.erase(0,3);
5106 // extract label and caption from the already produced LyX code
5107 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5108 string const caption = nfc.front();
5110 vector<string>::iterator it =
5111 find(nfc.begin(), nfc.end(), "LatexCommand label");
5112 if (it != nfc.end()) {
5114 if (it != nfc.end())
5116 label = support::split(label, '"');
5119 minted_nonfloat_caption.clear();
5120 lstparams = "caption=" + caption;
5122 lstparams += ",label=" + label;
5123 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5124 literal = !oa.first;
5126 lstparams = subst(lstparams, "\n", " ");
5128 lstparams = oa.second;
5131 string lit = literal ? "\"true\"" : "\"false\"";
5132 string filename(normalize_filename(p.getArg('{', '}')));
5133 string const path = getMasterFilePath(true);
5134 // We want to preserve relative / absolute filenames,
5135 // therefore path is only used for testing
5136 if ((t.cs() == "include" || t.cs() == "input") &&
5137 !makeAbsPath(filename, path).exists()) {
5138 // The file extension is probably missing.
5139 // Now try to find it out.
5140 string const tex_name =
5141 find_file(filename, path,
5142 known_tex_extensions);
5143 if (!tex_name.empty())
5144 filename = tex_name;
5146 bool external = false;
5148 if (makeAbsPath(filename, path).exists()) {
5149 string const abstexname =
5150 makeAbsPath(filename, path).absFileName();
5151 string const absfigname =
5152 changeExtension(abstexname, ".fig");
5153 fix_child_filename(filename);
5154 string const lyxname = changeExtension(filename,
5155 roundtripMode() ? ".lyx.lyx" : ".lyx");
5156 string const abslyxname = makeAbsPath(
5157 lyxname, getParentFilePath(false)).absFileName();
5159 if (!skipChildren())
5160 external = FileName(absfigname).exists();
5161 if (t.cs() == "input" && !skipChildren()) {
5162 string const ext = getExtension(abstexname);
5164 // Combined PS/LaTeX:
5165 // x.eps, x.pstex_t (old xfig)
5166 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5167 FileName const absepsname(
5168 changeExtension(abstexname, ".eps"));
5169 FileName const abspstexname(
5170 changeExtension(abstexname, ".pstex"));
5171 bool const xfigeps =
5172 (absepsname.exists() ||
5173 abspstexname.exists()) &&
5176 // Combined PDF/LaTeX:
5177 // x.pdf, x.pdftex_t (old xfig)
5178 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5179 FileName const abspdfname(
5180 changeExtension(abstexname, ".pdf"));
5181 bool const xfigpdf =
5182 abspdfname.exists() &&
5183 (ext == "pdftex_t" || ext == "pdf_t");
5187 // Combined PS/PDF/LaTeX:
5188 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5189 string const absbase2(
5190 removeExtension(abstexname) + "_pspdftex");
5191 FileName const abseps2name(
5192 addExtension(absbase2, ".eps"));
5193 FileName const abspdf2name(
5194 addExtension(absbase2, ".pdf"));
5195 bool const xfigboth =
5196 abspdf2name.exists() &&
5197 abseps2name.exists() && ext == "pspdftex";
5199 xfig = xfigpdf || xfigeps || xfigboth;
5200 external = external && xfig;
5203 outname = changeExtension(filename, ".fig");
5204 FileName abssrc(changeExtension(abstexname, ".fig"));
5205 copy_file(abssrc, outname);
5207 // Don't try to convert, the result
5208 // would be full of ERT.
5210 FileName abssrc(abstexname);
5211 copy_file(abssrc, outname);
5212 } else if (t.cs() != "verbatiminput" &&
5214 tex2lyx(abstexname, FileName(abslyxname),
5217 // no need to call copy_file
5218 // tex2lyx creates the file
5221 FileName abssrc(abstexname);
5222 copy_file(abssrc, outname);
5225 cerr << "Warning: Could not find included file '"
5226 << filename << "'." << endl;
5230 begin_inset(os, "External\n");
5231 os << "\ttemplate XFig\n"
5232 << "\tfilename " << outname << '\n';
5233 registerExternalTemplatePackages("XFig");
5235 begin_command_inset(os, "include", name);
5236 outname = subst(outname, "\"", "\\\"");
5237 os << "preview false\n"
5238 "filename \"" << outname << "\"\n";
5239 if (!lstparams.empty())
5240 os << "lstparams \"" << lstparams << "\"\n";
5241 os << "literal " << lit << "\n";
5242 if (t.cs() == "verbatiminput")
5243 preamble.registerAutomaticallyLoadedPackage("verbatim");
5249 if (t.cs() == "bibliographystyle") {
5250 // store new bibliographystyle
5251 bibliographystyle = p.verbatim_item();
5252 // If any other command than \bibliography, \addcontentsline
5253 // and \nocite{*} follows, we need to output the style
5254 // (because it might be used by that command).
5255 // Otherwise, it will automatically be output by LyX.
5258 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5259 if (t2.cat() == catBegin)
5261 if (t2.cat() != catEscape)
5263 if (t2.cs() == "nocite") {
5264 if (p.getArg('{', '}') == "*")
5266 } else if (t2.cs() == "bibliography")
5268 else if (t2.cs() == "phantomsection") {
5272 else if (t2.cs() == "addcontentsline") {
5273 // get the 3 arguments of \addcontentsline
5276 contentslineContent = p.getArg('{', '}');
5277 // if the last argument is not \refname we must output
5278 if (contentslineContent == "\\refname")
5285 output_ert_inset(os,
5286 "\\bibliographystyle{" + bibliographystyle + '}',
5292 if (t.cs() == "phantomsection") {
5293 // we only support this if it occurs between
5294 // \bibliographystyle and \bibliography
5295 if (bibliographystyle.empty())
5296 output_ert_inset(os, "\\phantomsection", context);
5300 if (t.cs() == "addcontentsline") {
5301 context.check_layout(os);
5302 // get the 3 arguments of \addcontentsline
5303 string const one = p.getArg('{', '}');
5304 string const two = p.getArg('{', '}');
5305 string const three = p.getArg('{', '}');
5306 // only if it is a \refname, we support if for the bibtex inset
5307 if (contentslineContent != "\\refname") {
5308 output_ert_inset(os,
5309 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5315 else if (t.cs() == "bibliography") {
5316 context.check_layout(os);
5318 begin_command_inset(os, "bibtex", "bibtex");
5319 if (!btprint.empty()) {
5320 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5321 // clear the string because the next BibTeX inset can be without the
5322 // \nocite{*} option
5325 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5326 // Do we have addcontentsline?
5327 if (contentslineContent == "\\refname") {
5328 BibOpts = "bibtotoc";
5329 // clear string because next BibTeX inset can be without addcontentsline
5330 contentslineContent.clear();
5332 // Do we have a bibliographystyle set?
5333 if (!bibliographystyle.empty()) {
5334 if (BibOpts.empty())
5335 BibOpts = normalize_filename(bibliographystyle);
5337 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5338 // clear it because each bibtex entry has its style
5339 // and we need an empty string to handle \phantomsection
5340 bibliographystyle.clear();
5342 os << "options " << '"' << BibOpts << '"' << "\n";
5343 if (p.getEncoding() != preamble.docencoding) {
5344 Encoding const * const enc = encodings.fromIconvName(
5345 p.getEncoding(), Encoding::inputenc, true);
5347 cerr << "Unknown bib encoding " << p.getEncoding()
5348 << ". Ignoring." << std::endl;
5350 os << "encoding " << '"' << enc->name() << '"' << "\n";
5356 if (t.cs() == "printbibliography") {
5357 context.check_layout(os);
5359 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5360 vector<string> opts = getVectorFromString(bbloptions);
5361 vector<string>::iterator it =
5362 find(opts.begin(), opts.end(), "heading=bibintoc");
5363 if (it != opts.end()) {
5365 BibOpts = "bibtotoc";
5367 bbloptions = getStringFromVector(opts);
5368 begin_command_inset(os, "bibtex", "bibtex");
5369 if (!btprint.empty()) {
5370 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5371 // clear the string because the next BibTeX inset can be without the
5372 // \nocite{*} option
5376 for (auto const & bf : preamble.biblatex_bibliographies) {
5377 if (!bibfiles.empty())
5379 bibfiles += normalize_filename(bf);
5381 if (!bibfiles.empty())
5382 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5383 // Do we have addcontentsline?
5384 if (contentslineContent == "\\refname") {
5385 BibOpts = "bibtotoc";
5386 // clear string because next BibTeX inset can be without addcontentsline
5387 contentslineContent.clear();
5389 os << "options " << '"' << BibOpts << '"' << "\n";
5390 if (!bbloptions.empty())
5391 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5392 if (!preamble.bibencoding.empty()) {
5393 Encoding const * const enc = encodings.fromLaTeXName(
5394 preamble.bibencoding, Encoding::inputenc, true);
5396 cerr << "Unknown bib encoding " << preamble.bibencoding
5397 << ". Ignoring." << std::endl;
5399 os << "encoding " << '"' << enc->name() << '"' << "\n";
5402 for (auto const & bf : preamble.biblatex_encodings) {
5403 if (!bibfileencs.empty())
5404 bibfileencs += "\t";
5407 if (!bibfileencs.empty())
5408 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5410 need_commentbib = false;
5414 if (t.cs() == "bibbysection") {
5415 context.check_layout(os);
5417 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5418 vector<string> opts = getVectorFromString(bbloptions);
5419 vector<string>::iterator it =
5420 find(opts.begin(), opts.end(), "heading=bibintoc");
5421 if (it != opts.end()) {
5423 BibOpts = "bibtotoc";
5425 bbloptions = getStringFromVector(opts);
5426 begin_command_inset(os, "bibtex", "bibtex");
5427 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5429 for (auto const & bf : preamble.biblatex_bibliographies) {
5430 if (!bibfiles.empty())
5432 bibfiles += normalize_filename(bf);
5434 if (!bibfiles.empty())
5435 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5436 os << "options " << '"' << BibOpts << '"' << "\n";
5437 if (!bbloptions.empty())
5438 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5440 need_commentbib = false;
5444 if (t.cs() == "parbox") {
5445 // Test whether this is an outer box of a shaded box
5447 // swallow arguments
5448 while (p.hasOpt()) {
5450 p.skip_spaces(true);
5453 p.skip_spaces(true);
5455 if (p.next_token().cat() == catBegin)
5457 p.skip_spaces(true);
5458 Token to = p.get_token();
5459 bool shaded = false;
5460 if (to.asInput() == "\\begin") {
5461 p.skip_spaces(true);
5462 if (p.getArg('{', '}') == "shaded")
5467 parse_outer_box(p, os, FLAG_ITEM, outer,
5468 context, "parbox", "shaded");
5470 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5471 "", "", t.cs(), "", "");
5475 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5476 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5477 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5478 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5482 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5483 string backgroundcolor;
5484 preamble.registerAutomaticallyLoadedPackage("xcolor");
5485 if (t.cs() == "fcolorbox") {
5486 string const framecolor = p.getArg('{', '}');
5487 backgroundcolor = p.getArg('{', '}');
5488 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5490 backgroundcolor = p.getArg('{', '}');
5491 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5496 // FIXME: due to the compiler limit of "if" nestings
5497 // the code for the alignment was put here
5498 // put them in their own if if this is fixed
5499 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5500 || t.cs() == "shadowsize"
5501 || t.cs() == "raggedleft" || t.cs() == "centering"
5502 || t.cs() == "raggedright") {
5503 if (t.cs() == "fboxrule")
5505 if (t.cs() == "fboxsep")
5507 if (t.cs() == "shadowsize")
5509 if (t.cs() != "raggedleft" && t.cs() != "centering"
5510 && t.cs() != "raggedright") {
5511 p.skip_spaces(true);
5512 while (p.good() && p.next_token().cat() != catSpace
5513 && p.next_token().cat() != catNewline
5514 && p.next_token().cat() != catEscape) {
5515 if (t.cs() == "fboxrule")
5516 fboxrule = fboxrule + p.get_token().asInput();
5517 if (t.cs() == "fboxsep")
5518 fboxsep = fboxsep + p.get_token().asInput();
5519 if (t.cs() == "shadowsize")
5520 shadow_size = shadow_size + p.get_token().asInput();
5523 output_ert_inset(os, t.asInput(), context);
5528 //\framebox() is part of the picture environment and different from \framebox{}
5529 //\framebox{} will be parsed by parse_outer_box
5530 if (t.cs() == "framebox") {
5531 if (p.next_token().character() == '(') {
5532 //the syntax is: \framebox(x,y)[position]{content}
5533 string arg = t.asInput();
5534 arg += p.getFullParentheseArg();
5535 arg += p.getFullOpt();
5536 eat_whitespace(p, os, context, false);
5537 output_ert_inset(os, arg + '{', context);
5538 parse_text(p, os, FLAG_ITEM, outer, context);
5539 output_ert_inset(os, "}", context);
5541 //the syntax is: \framebox[width][position]{content}
5542 string special = p.getFullOpt();
5543 special += p.getOpt();
5544 parse_outer_box(p, os, FLAG_ITEM, outer,
5545 context, t.cs(), special);
5550 //\makebox() is part of the picture environment and different from \makebox{}
5551 //\makebox{} will be parsed by parse_box
5552 if (t.cs() == "makebox") {
5553 if (p.next_token().character() == '(') {
5554 //the syntax is: \makebox(x,y)[position]{content}
5555 string arg = t.asInput();
5556 arg += p.getFullParentheseArg();
5557 arg += p.getFullOpt();
5558 eat_whitespace(p, os, context, false);
5559 output_ert_inset(os, arg + '{', context);
5560 parse_text(p, os, FLAG_ITEM, outer, context);
5561 output_ert_inset(os, "}", context);
5563 //the syntax is: \makebox[width][position]{content}
5564 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5565 "", "", t.cs(), "", "");
5569 if (t.cs() == "smallskip" ||
5570 t.cs() == "medskip" ||
5571 t.cs() == "bigskip" ||
5572 t.cs() == "vfill") {
5573 context.check_layout(os);
5574 begin_inset(os, "VSpace ");
5577 skip_spaces_braces(p);
5581 if ((where = is_known(t.cs(), known_spaces))) {
5582 context.check_layout(os);
5583 begin_inset(os, "space ");
5584 os << '\\' << known_coded_spaces[where - known_spaces]
5587 // LaTeX swallows whitespace after all spaces except
5588 // "\\,". We have to do that here, too, because LyX
5589 // adds "{}" which would make the spaces significant.
5591 eat_whitespace(p, os, context, false);
5592 // LyX adds "{}" after all spaces except "\\ " and
5593 // "\\,", so we have to remove "{}".
5594 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5595 // remove the braces after "\\,", too.
5601 if (t.cs() == "newpage" ||
5602 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5603 t.cs() == "clearpage" ||
5604 t.cs() == "cleardoublepage" ||
5605 t.cs() == "nopagebreak") {
5606 context.check_layout(os);
5607 begin_inset(os, "Newpage ");
5610 skip_spaces_braces(p);
5614 if (t.cs() == "DeclareRobustCommand" ||
5615 t.cs() == "DeclareRobustCommandx" ||
5616 t.cs() == "newcommand" ||
5617 t.cs() == "newcommandx" ||
5618 t.cs() == "providecommand" ||
5619 t.cs() == "providecommandx" ||
5620 t.cs() == "renewcommand" ||
5621 t.cs() == "renewcommandx") {
5622 // DeclareRobustCommand, DeclareRobustCommandx,
5623 // providecommand and providecommandx could be handled
5624 // by parse_command(), but we need to call
5625 // add_known_command() here.
5626 string name = t.asInput();
5627 if (p.next_token().asInput() == "*") {
5628 // Starred form. Eat '*'
5632 string const command = p.verbatim_item();
5633 string const opt1 = p.getFullOpt();
5634 string const opt2 = p.getFullOpt();
5635 add_known_command(command, opt1, !opt2.empty());
5636 string const ert = name + '{' + command + '}' +
5638 '{' + p.verbatim_item() + '}';
5640 if (t.cs() == "DeclareRobustCommand" ||
5641 t.cs() == "DeclareRobustCommandx" ||
5642 t.cs() == "providecommand" ||
5643 t.cs() == "providecommandx" ||
5644 name[name.length()-1] == '*')
5645 output_ert_inset(os, ert, context);
5647 context.check_layout(os);
5648 begin_inset(os, "FormulaMacro");
5655 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5656 // let could be handled by parse_command(),
5657 // but we need to call add_known_command() here.
5658 string ert = t.asInput();
5661 if (p.next_token().cat() == catBegin) {
5662 name = p.verbatim_item();
5663 ert += '{' + name + '}';
5665 name = p.verbatim_item();
5670 if (p.next_token().cat() == catBegin) {
5671 command = p.verbatim_item();
5672 ert += '{' + command + '}';
5674 command = p.verbatim_item();
5677 // If command is known, make name known too, to parse
5678 // its arguments correctly. For this reason we also
5679 // have commands in syntax.default that are hardcoded.
5680 CommandMap::iterator it = known_commands.find(command);
5681 if (it != known_commands.end())
5682 known_commands[t.asInput()] = it->second;
5683 output_ert_inset(os, ert, context);
5687 if (t.cs() == "hspace" || t.cs() == "vspace") {
5690 string name = t.asInput();
5691 string const length = p.verbatim_item();
5694 bool valid = splitLatexLength(length, valstring, unit);
5695 bool known_hspace = false;
5696 bool known_vspace = false;
5697 bool known_unit = false;
5700 istringstream iss(valstring);
5703 if (t.cs()[0] == 'h') {
5704 if (unit == "\\fill") {
5709 known_hspace = true;
5712 if (unit == "\\smallskipamount") {
5714 known_vspace = true;
5715 } else if (unit == "\\medskipamount") {
5717 known_vspace = true;
5718 } else if (unit == "\\bigskipamount") {
5720 known_vspace = true;
5721 } else if (length == "\\baselineskip") {
5723 known_vspace = true;
5724 } else if (unit == "\\fill") {
5726 known_vspace = true;
5730 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5732 known_vspace = true;
5734 if (!known_hspace && !known_vspace) {
5735 switch (unitFromString(unit)) {
5751 //unitFromString(unit) fails for relative units like Length::PCW
5752 // therefore handle them separately
5753 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5754 || unit == "\\textwidth" || unit == "\\linewidth"
5755 || unit == "\\textheight" || unit == "\\paperheight"
5756 || unit == "\\baselineskip")
5764 // check for glue lengths
5765 bool is_gluelength = false;
5766 string gluelength = length;
5767 string::size_type i = length.find(" minus");
5768 if (i == string::npos) {
5769 i = length.find(" plus");
5770 if (i != string::npos)
5771 is_gluelength = true;
5773 is_gluelength = true;
5774 // if yes transform "9xx minus 8yy plus 7zz"
5776 if (is_gluelength) {
5777 i = gluelength.find(" minus");
5778 if (i != string::npos)
5779 gluelength.replace(i, 7, "-");
5780 i = gluelength.find(" plus");
5781 if (i != string::npos)
5782 gluelength.replace(i, 6, "+");
5785 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5786 // Literal horizontal length or known variable
5787 context.check_layout(os);
5788 begin_inset(os, "space ");
5796 if (known_unit && !known_hspace)
5797 os << "\n\\length " << translate_len(length);
5799 os << "\n\\length " << gluelength;
5801 } else if (known_unit || known_vspace || is_gluelength) {
5802 // Literal vertical length or known variable
5803 context.check_layout(os);
5804 begin_inset(os, "VSpace ");
5807 if (known_unit && !known_vspace)
5808 os << translate_len(length);
5815 // LyX can't handle other length variables in Inset VSpace/space
5820 output_ert_inset(os, name + '{' + unit + '}', context);
5821 else if (value == -1.0)
5822 output_ert_inset(os, name + "{-" + unit + '}', context);
5824 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5826 output_ert_inset(os, name + '{' + length + '}', context);
5831 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5832 // might be one or several options or a star.
5833 // The single '=' is meant here.
5834 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5838 context.check_layout(os);
5839 // store the latexparam here. This is eaten in parse_text_in_inset
5840 context.latexparam = newinsetlayout->latexparam();
5841 docstring name = newinsetlayout->name();
5842 bool const caption = name.find(from_ascii("Caption:")) == 0;
5844 // Already done for floating minted listings.
5845 if (minted_float.empty()) {
5846 begin_inset(os, "Caption ");
5847 os << to_utf8(name.substr(8)) << '\n';
5850 // FIXME: what do we do if the prefix is not Flex: ?
5851 if (prefixIs(name, from_ascii("Flex:")))
5853 begin_inset(os, "Flex ");
5854 os << to_utf8(name) << '\n'
5855 << "status collapsed\n";
5857 if (!minted_float.empty()) {
5858 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5859 } else if (newinsetlayout->isPassThru()) {
5860 // set catcodes to verbatim early, just in case.
5861 p.setCatcodes(VERBATIM_CATCODES);
5862 string delim = p.get_token().asInput();
5864 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5865 //FIXME: handle error condition
5866 string const arg = p.verbatimStuff("}").second;
5867 Context newcontext(true, context.textclass);
5868 if (newinsetlayout->forcePlainLayout())
5869 newcontext.layout = &context.textclass.plainLayout();
5870 output_ert(os, arg, newcontext);
5872 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5873 context.latexparam.clear();
5876 // Minted caption insets are not closed here because
5877 // we collect everything into the caption.
5878 if (minted_float.empty())
5883 // The single '=' is meant here.
5884 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5888 context.check_layout(os);
5889 docstring name = newinsetlayout->name();
5890 bool const caption = name.find(from_ascii("Caption:")) == 0;
5892 // Already done for floating minted listings.
5893 if (minted_float.empty()) {
5894 begin_inset(os, "Caption ");
5895 os << to_utf8(name.substr(8)) << '\n';
5898 // FIXME: what do we do if the prefix is not Flex: ?
5899 if (prefixIs(name, from_ascii("Flex:")))
5901 begin_inset(os, "Flex ");
5902 os << to_utf8(name) << '\n'
5903 << "status collapsed\n";
5905 if (!minted_float.empty()) {
5906 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5907 } else if (newinsetlayout->isPassThru()) {
5908 // set catcodes to verbatim early, just in case.
5909 p.setCatcodes(VERBATIM_CATCODES);
5910 string delim = p.get_token().asInput();
5912 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5913 //FIXME: handle error condition
5914 string const arg = p.verbatimStuff("}").second;
5915 Context newcontext(true, context.textclass);
5916 if (newinsetlayout->forcePlainLayout())
5917 newcontext.layout = &context.textclass.plainLayout();
5918 output_ert(os, arg, newcontext);
5920 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5923 // Minted caption insets are not closed here because
5924 // we collect everything into the caption.
5925 if (minted_float.empty())
5930 if (t.cs() == "includepdf") {
5932 string const arg = p.getArg('[', ']');
5933 map<string, string> opts;
5934 vector<string> keys;
5935 split_map(arg, opts, keys);
5936 string name = normalize_filename(p.verbatim_item());
5937 string const path = getMasterFilePath(true);
5938 // We want to preserve relative / absolute filenames,
5939 // therefore path is only used for testing
5940 if (!makeAbsPath(name, path).exists()) {
5941 // The file extension is probably missing.
5942 // Now try to find it out.
5943 char const * const pdfpages_format[] = {"pdf", 0};
5944 string const pdftex_name =
5945 find_file(name, path, pdfpages_format);
5946 if (!pdftex_name.empty()) {
5951 FileName const absname = makeAbsPath(name, path);
5952 if (absname.exists())
5954 fix_child_filename(name);
5955 copy_file(absname, name);
5957 cerr << "Warning: Could not find file '"
5958 << name << "'." << endl;
5960 context.check_layout(os);
5961 begin_inset(os, "External\n\ttemplate ");
5962 os << "PDFPages\n\tfilename "
5964 // parse the options
5965 if (opts.find("pages") != opts.end())
5966 os << "\textra LaTeX \"pages="
5967 << opts["pages"] << "\"\n";
5968 if (opts.find("angle") != opts.end())
5969 os << "\trotateAngle "
5970 << opts["angle"] << '\n';
5971 if (opts.find("origin") != opts.end()) {
5973 string const opt = opts["origin"];
5974 if (opt == "tl") ss << "topleft";
5975 if (opt == "bl") ss << "bottomleft";
5976 if (opt == "Bl") ss << "baselineleft";
5977 if (opt == "c") ss << "center";
5978 if (opt == "tc") ss << "topcenter";
5979 if (opt == "bc") ss << "bottomcenter";
5980 if (opt == "Bc") ss << "baselinecenter";
5981 if (opt == "tr") ss << "topright";
5982 if (opt == "br") ss << "bottomright";
5983 if (opt == "Br") ss << "baselineright";
5984 if (!ss.str().empty())
5985 os << "\trotateOrigin " << ss.str() << '\n';
5987 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5989 if (opts.find("width") != opts.end())
5991 << translate_len(opts["width"]) << '\n';
5992 if (opts.find("height") != opts.end())
5994 << translate_len(opts["height"]) << '\n';
5995 if (opts.find("keepaspectratio") != opts.end())
5996 os << "\tkeepAspectRatio\n";
5998 context.check_layout(os);
5999 registerExternalTemplatePackages("PDFPages");
6003 if (t.cs() == "loadgame") {
6005 string name = normalize_filename(p.verbatim_item());
6006 string const path = getMasterFilePath(true);
6007 // We want to preserve relative / absolute filenames,
6008 // therefore path is only used for testing
6009 if (!makeAbsPath(name, path).exists()) {
6010 // The file extension is probably missing.
6011 // Now try to find it out.
6012 char const * const lyxskak_format[] = {"fen", 0};
6013 string const lyxskak_name =
6014 find_file(name, path, lyxskak_format);
6015 if (!lyxskak_name.empty())
6016 name = lyxskak_name;
6018 FileName const absname = makeAbsPath(name, path);
6019 if (absname.exists())
6021 fix_child_filename(name);
6022 copy_file(absname, name);
6024 cerr << "Warning: Could not find file '"
6025 << name << "'." << endl;
6026 context.check_layout(os);
6027 begin_inset(os, "External\n\ttemplate ");
6028 os << "ChessDiagram\n\tfilename "
6031 context.check_layout(os);
6032 // after a \loadgame follows a \showboard
6033 if (p.get_token().asInput() == "showboard")
6035 registerExternalTemplatePackages("ChessDiagram");
6039 // try to see whether the string is in unicodesymbols
6040 // Only use text mode commands, since we are in text mode here,
6041 // and math commands may be invalid (bug 6797)
6042 string name = t.asInput();
6043 // handle the dingbats, cyrillic and greek
6044 if (name == "\\textcyr")
6045 name = "\\textcyrillic";
6046 if (name == "\\ding" || name == "\\textcyrillic" ||
6047 (name == "\\textgreek" && !preamble.usePolyglossia()))
6048 name = name + '{' + p.getArg('{', '}') + '}';
6049 // handle the ifsym characters
6050 else if (name == "\\textifsymbol") {
6051 string const optif = p.getFullOpt();
6052 string const argif = p.getArg('{', '}');
6053 name = name + optif + '{' + argif + '}';
6055 // handle the \ascii characters
6056 // the case of \ascii within braces, as LyX outputs it, is already
6057 // handled for t.cat() == catBegin
6058 else if (name == "\\ascii") {
6059 // the code is "\asci\xxx"
6060 name = "{" + name + p.get_token().asInput() + "}";
6063 // handle some TIPA special characters
6064 else if (preamble.isPackageUsed("tipa")) {
6065 if (name == "\\s") {
6066 // fromLaTeXCommand() does not yet
6067 // recognize tipa short cuts
6068 name = "\\textsyllabic";
6069 } else if (name == "\\=" &&
6070 p.next_token().asInput() == "*") {
6071 // fromLaTeXCommand() does not yet
6072 // recognize tipa short cuts
6074 name = "\\textsubbar";
6075 } else if (name == "\\textdoublevertline") {
6076 // FIXME: This is not correct,
6077 // \textvertline is higher than \textbardbl
6078 name = "\\textbardbl";
6080 } else if (name == "\\!" ) {
6081 if (p.next_token().asInput() == "b") {
6082 p.get_token(); // eat 'b'
6085 } else if (p.next_token().asInput() == "d") {
6089 } else if (p.next_token().asInput() == "g") {
6093 } else if (p.next_token().asInput() == "G") {
6095 name = "\\texthtscg";
6097 } else if (p.next_token().asInput() == "j") {
6099 name = "\\texthtbardotlessj";
6101 } else if (p.next_token().asInput() == "o") {
6103 name = "\\textbullseye";
6106 } else if (name == "\\*" ) {
6107 if (p.next_token().asInput() == "k") {
6109 name = "\\textturnk";
6111 } else if (p.next_token().asInput() == "r") {
6112 p.get_token(); // eat 'b'
6113 name = "\\textturnr";
6115 } else if (p.next_token().asInput() == "t") {
6117 name = "\\textturnt";
6119 } else if (p.next_token().asInput() == "w") {
6121 name = "\\textturnw";
6126 if ((name.size() == 2 &&
6127 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6128 p.next_token().asInput() != "*") ||
6129 is_known(name.substr(1), known_tipa_marks)) {
6130 // name is a command that corresponds to a
6131 // combining character in unicodesymbols.
6132 // Append the argument, fromLaTeXCommand()
6133 // will either convert it to a single
6134 // character or a combining sequence.
6135 name += '{' + p.verbatim_item() + '}';
6137 // now get the character from unicodesymbols
6141 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6142 Encodings::TEXT_CMD, termination, rem, &req));
6144 context.check_layout(os);
6147 output_ert_inset(os, to_utf8(rem), context);
6149 skip_spaces_braces(p);
6150 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6151 preamble.registerAutomaticallyLoadedPackage(*it);
6153 //cerr << "#: " << t << " mode: " << mode << endl;
6154 // heuristic: read up to next non-nested space
6156 string s = t.asInput();
6157 string z = p.verbatim_item();
6158 while (p.good() && z != " " && !z.empty()) {
6159 //cerr << "read: " << z << endl;
6161 z = p.verbatim_item();
6163 cerr << "found ERT: " << s << endl;
6164 output_ert_inset(os, s + ' ', context);
6167 if (t.asInput() == name &&
6168 p.next_token().asInput() == "*") {
6169 // Starred commands like \vspace*{}
6170 p.get_token(); // Eat '*'
6173 if (!parse_command(name, p, os, outer, context)) {
6174 output_ert_inset(os, name, context);
6175 // Try to handle options of unknown commands:
6176 // Look if we have optional arguments,
6177 // and if so, put the brackets in ERT.
6178 while (p.hasOpt()) {
6179 p.get_token(); // eat '['
6180 output_ert_inset(os, "[", context);
6181 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6182 output_ert_inset(os, "]", context);
6190 string guessLanguage(Parser & p, string const & lang)
6192 typedef std::map<std::string, size_t> LangMap;
6193 // map from language names to number of characters
6196 for (char const * const * i = supported_CJK_languages; *i; i++)
6197 used[string(*i)] = 0;
6200 Token const t = p.get_token();
6201 // comments are not counted for any language
6202 if (t.cat() == catComment)
6204 // commands are not counted as well, but we need to detect
6205 // \begin{CJK} and switch encoding if needed
6206 if (t.cat() == catEscape) {
6207 if (t.cs() == "inputencoding") {
6208 string const enc = subst(p.verbatim_item(), "\n", " ");
6209 p.setEncoding(enc, Encoding::inputenc);
6212 if (t.cs() != "begin")
6215 // Non-CJK content is counted for lang.
6216 // We do not care about the real language here:
6217 // If we have more non-CJK contents than CJK contents,
6218 // we simply use the language that was specified as
6219 // babel main language.
6220 used[lang] += t.asInput().length();
6223 // Now we are starting an environment
6225 string const name = p.getArg('{', '}');
6226 if (name != "CJK") {
6230 // It is a CJK environment
6232 /* name = */ p.getArg('{', '}');
6233 string const encoding = p.getArg('{', '}');
6234 /* mapping = */ p.getArg('{', '}');
6235 string const encoding_old = p.getEncoding();
6236 char const * const * const where =
6237 is_known(encoding, supported_CJK_encodings);
6239 p.setEncoding(encoding, Encoding::CJK);
6241 p.setEncoding("UTF-8");
6242 string const text = p.ertEnvironment("CJK");
6243 p.setEncoding(encoding_old);
6246 // ignore contents in unknown CJK encoding
6249 // the language of the text
6251 supported_CJK_languages[where - supported_CJK_encodings];
6252 used[cjk] += text.length();
6254 LangMap::const_iterator use = used.begin();
6255 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6256 if (it->second > use->second)
6263 void check_comment_bib(ostream & os, Context & context)
6265 if (!need_commentbib)
6267 // We have a bibliography database, but no bibliography with biblatex
6268 // which is completely valid. Insert a bibtex inset in a note.
6269 context.check_layout(os);
6270 begin_inset(os, "Note Note\n");
6271 os << "status open\n";
6272 os << "\\begin_layout Plain Layout\n";
6273 begin_command_inset(os, "bibtex", "bibtex");
6275 for (auto const & bf : preamble.biblatex_bibliographies) {
6276 if (!bibfiles.empty())
6278 bibfiles += normalize_filename(bf);
6280 if (!bibfiles.empty())
6281 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6283 for (auto const & bf : preamble.biblatex_encodings) {
6284 if (!bibfileencs.empty())
6285 bibfileencs += "\t";
6288 if (!bibfileencs.empty())
6289 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6290 end_inset(os);// Bibtex
6291 os << "\\end_layout\n";
6292 end_inset(os);// Note