2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, string, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
68 output_arguments(os, p, outer, false, string(), newcontext,
70 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space", ",",
320 "thinspace", "quad", "qquad", "enspace", "enskip",
321 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
322 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
323 "upbracefill", "downbracefill", 0};
325 /// the same as known_spaces with .lyx names
326 char const * const known_coded_spaces[] = { "space{}", "space{}",
327 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
328 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
329 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
330 "upbracefill{}", "downbracefill{}", 0};
332 /// known TIPA combining diacritical marks
333 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
334 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
335 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
336 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
337 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
338 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
339 "textsubring", "textsubbar", 0};
341 /// TIPA tones that need special handling
342 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
344 // string to store the float type to be able to determine the type of subfloats
345 string float_type = "";
347 // string to store the float status of minted listings
348 string minted_float = "";
350 // whether a caption has been parsed for a floating minted listing
351 bool minted_float_has_caption = false;
353 // The caption for non-floating minted listings
354 string minted_nonfloat_caption = "";
356 // Characters that have to be escaped by \\ in LaTeX
357 char const * const known_escaped_chars[] = {
358 "&", "_", "$", "%", "#", "^", "{", "}", 0};
361 /// splits "x=z, y=b" into a map and an ordered keyword vector
362 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
367 keys.resize(v.size());
368 for (size_t i = 0; i < v.size(); ++i) {
369 size_t const pos = v[i].find('=');
370 string const index = trimSpaceAndEol(v[i].substr(0, pos));
371 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
379 * Split a LaTeX length into value and unit.
380 * The latter can be a real unit like "pt", or a latex length variable
381 * like "\textwidth". The unit may contain additional stuff like glue
382 * lengths, but we don't care, because such lengths are ERT anyway.
383 * \returns true if \p value and \p unit are valid.
385 bool splitLatexLength(string const & len, string & value, string & unit)
389 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
390 //'4,5' is a valid LaTeX length number. Change it to '4.5'
391 string const length = subst(len, ',', '.');
392 if (i == string::npos)
395 if (len[0] == '\\') {
396 // We had something like \textwidth without a factor
402 value = trimSpaceAndEol(string(length, 0, i));
406 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
407 if (contains(len, '\\'))
408 unit = trimSpaceAndEol(string(len, i));
410 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
415 /// A simple function to translate a latex length to something LyX can
416 /// understand. Not perfect, but rather best-effort.
417 bool translate_len(string const & length, string & valstring, string & unit)
419 if (!splitLatexLength(length, valstring, unit))
421 // LyX uses percent values
423 istringstream iss(valstring);
428 string const percentval = oss.str();
430 if (unit.empty() || unit[0] != '\\')
432 string::size_type const i = unit.find(' ');
433 string const endlen = (i == string::npos) ? string() : string(unit, i);
434 if (unit == "\\textwidth") {
435 valstring = percentval;
436 unit = "text%" + endlen;
437 } else if (unit == "\\columnwidth") {
438 valstring = percentval;
439 unit = "col%" + endlen;
440 } else if (unit == "\\paperwidth") {
441 valstring = percentval;
442 unit = "page%" + endlen;
443 } else if (unit == "\\linewidth") {
444 valstring = percentval;
445 unit = "line%" + endlen;
446 } else if (unit == "\\paperheight") {
447 valstring = percentval;
448 unit = "pheight%" + endlen;
449 } else if (unit == "\\textheight") {
450 valstring = percentval;
451 unit = "theight%" + endlen;
452 } else if (unit == "\\baselineskip") {
453 valstring = percentval;
454 unit = "baselineskip%" + endlen;
460 /// If we have ambiguous quotation marks, make a smart guess
461 /// based on main quote style
462 string guessQuoteStyle(string in, bool const opening)
465 if (prefixIs(in, "qr")) {// straight quote
467 res = subst(res, "r", "l");
468 } else if (in == "eld") {// ``
469 if (preamble.quotesStyle() == "german")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "russian")
477 } else if (in == "erd") {// ''
478 if (preamble.quotesStyle() == "polish")
480 else if (preamble.quotesStyle() == "british")
482 else if (preamble.quotesStyle() == "french")
484 else if (preamble.quotesStyle() == "swedish")
485 res = opening ? "sld" : "srd";
486 } else if (in == "els") {// `
487 if (preamble.quotesStyle() == "german")
489 else if (preamble.quotesStyle() == "british")
491 } else if (in == "ers") {// '
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sls" : "srs";
498 } else if (in == "ard") {// >>
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ald") {// <<
506 if (preamble.quotesStyle() == "swiss")
508 else if (preamble.quotesStyle() == "french")
510 else if (preamble.quotesStyle() == "russian")
512 } else if (in == "ars") {// >
513 if (preamble.quotesStyle() == "swiss")
515 } else if (in == "als") {// <
516 if (preamble.quotesStyle() == "swiss")
518 } else if (in == "gld") {// ,,
519 if (preamble.quotesStyle() == "polish")
521 else if (preamble.quotesStyle() == "russian")
523 } else if (in == "gls") {// ,
524 if (preamble.quotesStyle() == "polish")
531 string const fromPolyglossiaEnvironment(string const s)
533 // Since \arabic is taken by the LaTeX kernel,
534 // the Arabic polyglossia environment is upcased
542 string uncapitalize(string const s)
544 docstring in = from_ascii(s);
545 char_type t = lowercase(s[0]);
551 bool isCapitalized(string const s)
553 docstring in = from_ascii(s);
554 char_type t = uppercase(s[0]);
556 return to_ascii(in) == s;
563 string translate_len(string const & length)
567 if (translate_len(length, value, unit))
569 // If the input is invalid, return what we have.
577 * Translates a LaTeX length into \p value, \p unit and
578 * \p special parts suitable for a box inset.
579 * The difference from translate_len() is that a box inset knows about
580 * some special "units" that are stored in \p special.
582 void translate_box_len(string const & length, string & value, string & unit, string & special)
584 if (translate_len(length, value, unit)) {
585 if (unit == "\\height" || unit == "\\depth" ||
586 unit == "\\totalheight" || unit == "\\width") {
587 special = unit.substr(1);
588 // The unit is not used, but LyX requires a dummy setting
600 void begin_inset(ostream & os, string const & name)
602 os << "\n\\begin_inset " << name;
606 void begin_command_inset(ostream & os, string const & name,
607 string const & latexname)
609 begin_inset(os, "CommandInset ");
610 os << name << "\nLatexCommand " << latexname << '\n';
614 void end_inset(ostream & os)
616 os << "\n\\end_inset\n\n";
620 bool skip_braces(Parser & p)
622 if (p.next_token().cat() != catBegin)
625 if (p.next_token().cat() == catEnd) {
634 /// replace LaTeX commands in \p s from the unicodesymbols file with their
636 pair<bool, docstring> convert_unicodesymbols(docstring s)
640 for (size_t i = 0; i < s.size();) {
649 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
650 Encodings::TEXT_CMD, termination, rem, &req));
651 set<string>::const_iterator it = req.begin();
652 set<string>::const_iterator en = req.end();
653 for (; it != en; ++it)
654 preamble.registerAutomaticallyLoadedPackage(*it);
657 if (s.empty() || s[0] != '\\')
661 for (auto const & c : known_escaped_chars)
662 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
667 return make_pair(res, os.str());
671 /// try to convert \p s to a valid InsetCommand argument
672 /// return whether this succeeded. If not, these command insets
673 /// get the "literate" flag.
674 pair<bool, string> convert_latexed_command_inset_arg(string s)
676 bool success = false;
678 // since we don't know the input encoding we can't use from_utf8
679 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
681 s = to_utf8(res.second);
683 // LyX cannot handle newlines in a latex command
684 return make_pair(success, subst(s, "\n", " "));
687 /// try to convert \p s to a valid InsetCommand argument
688 /// without trying to recode macros.
689 string convert_literate_command_inset_arg(string s)
691 // LyX cannot handle newlines in a latex command
692 return subst(s, "\n", " ");
695 void output_ert(ostream & os, string const & s, Context & context)
697 context.check_layout(os);
698 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
700 os << "\n\\backslash\n";
701 else if (*it == '\n') {
702 context.new_paragraph(os);
703 context.check_layout(os);
707 context.check_end_layout(os);
711 void output_ert_inset(ostream & os, string const & s, Context & context)
713 // We must have a valid layout before outputting the ERT inset.
714 context.check_layout(os);
715 Context newcontext(true, context.textclass);
716 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
717 if (layout.forcePlainLayout())
718 newcontext.layout = &context.textclass.plainLayout();
719 begin_inset(os, "ERT");
720 os << "\nstatus collapsed\n";
721 output_ert(os, s, newcontext);
726 void output_comment(Parser & p, ostream & os, string const & s,
729 if (p.next_token().cat() == catNewline)
730 output_ert_inset(os, '%' + s, context);
732 output_ert_inset(os, '%' + s + '\n', context);
736 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
737 string const & latexparam = string())
739 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
742 if (checkModule(name, command))
743 return findLayoutWithoutModule(textclass, name, command, latexparam);
748 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
749 string const & latexparam = string())
751 InsetLayout const * insetlayout =
752 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
755 if (checkModule(name, command))
756 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
761 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
762 bool eatNewline = true);
766 * Skips whitespace and braces.
767 * This should be called after a command has been parsed that is not put into
768 * ERT, and where LyX adds "{}" if needed.
770 void skip_spaces_braces(Parser & p, bool keepws = false)
772 /* The following four examples produce the same typeset output and
773 should be handled by this function:
781 // Unfortunately we need to skip comments, too.
782 // We can't use eat_whitespace since writing them after the {}
783 // results in different output in some cases.
784 bool const skipped_spaces = p.skip_spaces(true);
785 bool const skipped_braces = skip_braces(p);
786 if (keepws && skipped_spaces && !skipped_braces)
787 // put back the space (it is better handled by check_space)
788 p.unskip_spaces(true);
792 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
793 Context & context, Layout::LaTeXArgMap const & latexargs)
795 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
797 context.check_layout(os);
803 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
804 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
805 for (; lait != laend; ++lait) {
807 eat_whitespace(p, os, context, false);
808 if (lait->second.mandatory) {
809 if (p.next_token().cat() != catBegin)
811 string ldelim = to_utf8(lait->second.ldelim);
812 string rdelim = to_utf8(lait->second.rdelim);
817 p.get_token(); // eat ldelim
818 if (ldelim.size() > 1)
819 p.get_token(); // eat ldelim
821 context.check_layout(os);
824 begin_inset(os, "Argument ");
827 os << i << "\nstatus collapsed\n\n";
828 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
831 string ldelim = to_utf8(lait->second.ldelim);
832 string rdelim = to_utf8(lait->second.rdelim);
837 string tok = p.next_token().asInput();
838 // we only support delimiters with max 2 chars for now.
839 if (ldelim.size() > 1)
840 tok += p.next_next_token().asInput();
841 if (p.next_token().cat() == catEscape || tok != ldelim)
843 p.get_token(); // eat ldelim
844 if (ldelim.size() > 1)
845 p.get_token(); // eat ldelim
847 context.check_layout(os);
850 begin_inset(os, "Argument ");
853 os << i << "\nstatus collapsed\n\n";
854 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
857 eat_whitespace(p, os, context, false);
862 void output_command_layout(ostream & os, Parser & p, bool outer,
863 Context & parent_context,
864 Layout const * newlayout)
866 TeXFont const oldFont = parent_context.font;
867 // save the current font size
868 string const size = oldFont.size;
869 // reset the font size to default, because the font size switches
870 // don't affect section headings and the like
871 parent_context.font.size = Context::normalfont.size;
872 // we only need to write the font change if we have an open layout
873 if (!parent_context.atParagraphStart())
874 output_font_change(os, oldFont, parent_context.font);
875 parent_context.check_end_layout(os);
876 Context context(true, parent_context.textclass, newlayout,
877 parent_context.layout, parent_context.font);
878 if (parent_context.deeper_paragraph) {
879 // We are beginning a nested environment after a
880 // deeper paragraph inside the outer list environment.
881 // Therefore we don't need to output a "begin deeper".
882 context.need_end_deeper = true;
884 context.check_deeper(os);
885 output_arguments(os, p, outer, true, string(), context,
886 context.layout->latexargs());
887 // If we have a latex param, we eat it here.
888 if (!parent_context.latexparam.empty()) {
890 Context dummy(true, parent_context.textclass);
891 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
892 string(1, parent_context.latexparam.back()));
894 parse_text(p, os, FLAG_ITEM, outer, context);
895 output_arguments(os, p, outer, false, "post", context,
896 context.layout->postcommandargs());
897 context.check_end_layout(os);
898 if (parent_context.deeper_paragraph) {
899 // We must suppress the "end deeper" because we
900 // suppressed the "begin deeper" above.
901 context.need_end_deeper = false;
903 context.check_end_deeper(os);
904 // We don't need really a new paragraph, but
905 // we must make sure that the next item gets a \begin_layout.
906 parent_context.new_paragraph(os);
907 // Set the font size to the original value. No need to output it here
908 // (Context::begin_layout() will do that if needed)
909 parent_context.font.size = size;
914 * Output a space if necessary.
915 * This function gets called for every whitespace token.
917 * We have three cases here:
918 * 1. A space must be suppressed. Example: The lyxcode case below
919 * 2. A space may be suppressed. Example: Spaces before "\par"
920 * 3. A space must not be suppressed. Example: A space between two words
922 * We currently handle only 1. and 3 and from 2. only the case of
923 * spaces before newlines as a side effect.
925 * 2. could be used to suppress as many spaces as possible. This has two effects:
926 * - Reimporting LyX generated LaTeX files changes almost no whitespace
927 * - Superflous whitespace from non LyX generated LaTeX files is removed.
928 * The drawback is that the logic inside the function becomes
929 * complicated, and that is the reason why it is not implemented.
931 void check_space(Parser & p, ostream & os, Context & context)
933 Token const next = p.next_token();
934 Token const curr = p.curr_token();
935 // A space before a single newline and vice versa must be ignored
936 // LyX emits a newline before \end{lyxcode}.
937 // This newline must be ignored,
938 // otherwise LyX will add an additional protected space.
939 if (next.cat() == catSpace ||
940 next.cat() == catNewline ||
941 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
944 context.check_layout(os);
950 * Parse all arguments of \p command
952 void parse_arguments(string const & command,
953 vector<ArgumentType> const & template_arguments,
954 Parser & p, ostream & os, bool outer, Context & context)
956 string ert = command;
957 size_t no_arguments = template_arguments.size();
958 for (size_t i = 0; i < no_arguments; ++i) {
959 switch (template_arguments[i]) {
962 // This argument contains regular LaTeX
963 output_ert_inset(os, ert + '{', context);
964 eat_whitespace(p, os, context, false);
965 if (template_arguments[i] == required)
966 parse_text(p, os, FLAG_ITEM, outer, context);
968 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
972 // This argument consists only of a single item.
973 // The presence of '{' or not must be preserved.
975 if (p.next_token().cat() == catBegin)
976 ert += '{' + p.verbatim_item() + '}';
978 ert += p.verbatim_item();
982 // This argument may contain special characters
983 ert += '{' + p.verbatim_item() + '}';
987 // true because we must not eat whitespace
988 // if an optional arg follows we must not strip the
989 // brackets from this one
990 if (i < no_arguments - 1 &&
991 template_arguments[i+1] == optional)
992 ert += p.getFullOpt(true);
994 ert += p.getOpt(true);
998 output_ert_inset(os, ert, context);
1003 * Check whether \p command is a known command. If yes,
1004 * handle the command with all arguments.
1005 * \return true if the command was parsed, false otherwise.
1007 bool parse_command(string const & command, Parser & p, ostream & os,
1008 bool outer, Context & context)
1010 if (known_commands.find(command) != known_commands.end()) {
1011 parse_arguments(command, known_commands[command], p, os,
1019 /// Parses a minipage or parbox
1020 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1021 unsigned inner_flags, bool outer, Context & parent_context,
1022 string const & outer_type, string const & special,
1023 string inner_type, string const & frame_color,
1024 string const & background_color)
1028 string hor_pos = "l";
1029 // We need to set the height to the LaTeX default of 1\\totalheight
1030 // for the case when no height argument is given
1031 string height_value = "1";
1032 string height_unit = "in";
1033 string height_special = "totalheight";
1034 string latex_height;
1038 string width_special = "none";
1039 string thickness = "0.4pt";
1040 if (!fboxrule.empty())
1041 thickness = fboxrule;
1043 thickness = "0.4pt";
1045 if (!fboxsep.empty())
1046 separation = fboxsep;
1050 if (!shadow_size.empty())
1051 shadowsize = shadow_size;
1054 string framecolor = "black";
1055 string backgroundcolor = "none";
1056 if (!frame_color.empty())
1057 framecolor = frame_color;
1058 if (!background_color.empty())
1059 backgroundcolor = background_color;
1060 // if there is a color box around the \begin statements have not yet been parsed
1062 if (!frame_color.empty() || !background_color.empty()) {
1063 eat_whitespace(p, os, parent_context, false);
1064 p.get_token().asInput(); // the '{'
1066 if (p.next_token().asInput() == "\\begin") {
1067 p.get_token().asInput();
1069 inner_type = "minipage";
1070 inner_flags = FLAG_END;
1071 active_environments.push_back("minipage");
1074 else if (p.next_token().asInput() == "\\parbox") {
1075 p.get_token().asInput();
1076 inner_type = "parbox";
1077 inner_flags = FLAG_ITEM;
1080 else if (p.next_token().asInput() == "\\makebox") {
1081 p.get_token().asInput();
1082 inner_type = "makebox";
1083 inner_flags = FLAG_ITEM;
1085 // in case there is just \colorbox{color}{text}
1088 inner_type = "makebox";
1089 inner_flags = FLAG_BRACE_LAST;
1094 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1096 if (!inner_type.empty() && p.hasOpt()) {
1097 if (inner_type != "makebox")
1098 position = p.getArg('[', ']');
1100 latex_width = p.getArg('[', ']');
1101 translate_box_len(latex_width, width_value, width_unit, width_special);
1104 if (position != "t" && position != "c" && position != "b") {
1105 cerr << "invalid position " << position << " for "
1106 << inner_type << endl;
1110 if (inner_type != "makebox") {
1111 latex_height = p.getArg('[', ']');
1112 translate_box_len(latex_height, height_value, height_unit, height_special);
1114 string const opt = p.getArg('[', ']');
1117 if (hor_pos != "l" && hor_pos != "c" &&
1118 hor_pos != "r" && hor_pos != "s") {
1119 cerr << "invalid hor_pos " << hor_pos
1120 << " for " << inner_type << endl;
1127 inner_pos = p.getArg('[', ']');
1128 if (inner_pos != "c" && inner_pos != "t" &&
1129 inner_pos != "b" && inner_pos != "s") {
1130 cerr << "invalid inner_pos "
1131 << inner_pos << " for "
1132 << inner_type << endl;
1133 inner_pos = position;
1137 if (inner_type == "makebox")
1141 if (inner_type.empty()) {
1142 if (special.empty() && outer_type != "framebox")
1143 latex_width = "1\\columnwidth";
1146 latex_width = p2.getArg('[', ']');
1147 string const opt = p2.getArg('[', ']');
1150 if (hor_pos != "l" && hor_pos != "c" &&
1151 hor_pos != "r" && hor_pos != "s") {
1152 cerr << "invalid hor_pos " << hor_pos
1153 << " for " << outer_type << endl;
1157 if (outer_type == "framebox")
1161 } else if (inner_type != "makebox")
1162 latex_width = p.verbatim_item();
1163 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1164 // as this is LyX's standard for such cases (except for makebox)
1165 // \framebox is more special and handled below
1166 if (latex_width.empty() && inner_type != "makebox"
1167 && outer_type != "framebox")
1168 latex_width = "1\\columnwidth";
1170 translate_len(latex_width, width_value, width_unit);
1172 bool shadedparbox = false;
1173 if (inner_type == "shaded") {
1174 eat_whitespace(p, os, parent_context, false);
1175 if (outer_type == "parbox") {
1177 if (p.next_token().cat() == catBegin)
1179 eat_whitespace(p, os, parent_context, false);
1180 shadedparbox = true;
1185 // If we already read the inner box we have to push the inner env
1186 if (!outer_type.empty() && !inner_type.empty() &&
1187 (inner_flags & FLAG_END))
1188 active_environments.push_back(inner_type);
1189 bool use_ert = false;
1190 if (!outer_type.empty() && !inner_type.empty()) {
1191 // Look whether there is some content after the end of the
1192 // inner box, but before the end of the outer box.
1193 // If yes, we need to output ERT.
1195 if (inner_flags & FLAG_END)
1196 p.ertEnvironment(inner_type);
1199 p.skip_spaces(true);
1200 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1201 if ((outer_env && p.next_token().asInput() != "\\end") ||
1202 (!outer_env && p.next_token().cat() != catEnd)) {
1203 // something is between the end of the inner box and
1204 // the end of the outer box, so we need to use ERT.
1212 if (!outer_type.empty()) {
1213 if (outer_flags & FLAG_END)
1214 ss << "\\begin{" << outer_type << '}';
1216 ss << '\\' << outer_type << '{';
1217 if (!special.empty())
1221 if (!inner_type.empty()) {
1222 if (inner_type != "shaded") {
1223 if (inner_flags & FLAG_END)
1224 ss << "\\begin{" << inner_type << '}';
1226 ss << '\\' << inner_type;
1228 if (!position.empty())
1229 ss << '[' << position << ']';
1230 if (!latex_height.empty())
1231 ss << '[' << latex_height << ']';
1232 if (!inner_pos.empty())
1233 ss << '[' << inner_pos << ']';
1234 ss << '{' << latex_width << '}';
1235 if (!(inner_flags & FLAG_END))
1238 if (inner_type == "shaded")
1239 ss << "\\begin{shaded}";
1240 output_ert_inset(os, ss.str(), parent_context);
1241 if (!inner_type.empty()) {
1242 parse_text(p, os, inner_flags, outer, parent_context);
1243 if (inner_flags & FLAG_END)
1244 output_ert_inset(os, "\\end{" + inner_type + '}',
1247 output_ert_inset(os, "}", parent_context);
1249 if (!outer_type.empty()) {
1250 // If we already read the inner box we have to pop
1252 if (!inner_type.empty() && (inner_flags & FLAG_END))
1253 active_environments.pop_back();
1255 // Ensure that the end of the outer box is parsed correctly:
1256 // The opening brace has been eaten by parse_outer_box()
1257 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1258 outer_flags &= ~FLAG_ITEM;
1259 outer_flags |= FLAG_BRACE_LAST;
1261 parse_text(p, os, outer_flags, outer, parent_context);
1262 if (outer_flags & FLAG_END)
1263 output_ert_inset(os, "\\end{" + outer_type + '}',
1266 output_ert_inset(os, "}", parent_context);
1269 // LyX does not like empty positions, so we have
1270 // to set them to the LaTeX default values here.
1271 if (position.empty())
1273 if (inner_pos.empty())
1274 inner_pos = position;
1275 parent_context.check_layout(os);
1276 begin_inset(os, "Box ");
1277 if (outer_type == "framed")
1279 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1281 else if (outer_type == "shadowbox")
1282 os << "Shadowbox\n";
1283 else if ((outer_type == "shaded" && inner_type.empty()) ||
1284 (outer_type == "minipage" && inner_type == "shaded") ||
1285 (outer_type == "parbox" && inner_type == "shaded")) {
1287 preamble.registerAutomaticallyLoadedPackage("color");
1288 } else if (outer_type == "doublebox")
1289 os << "Doublebox\n";
1290 else if (outer_type.empty() || outer_type == "mbox")
1291 os << "Frameless\n";
1293 os << outer_type << '\n';
1294 os << "position \"" << position << "\"\n";
1295 os << "hor_pos \"" << hor_pos << "\"\n";
1296 if (outer_type == "mbox")
1297 os << "has_inner_box 1\n";
1298 else if (!frame_color.empty() && inner_type == "makebox")
1299 os << "has_inner_box 0\n";
1301 os << "has_inner_box " << !inner_type.empty() << "\n";
1302 os << "inner_pos \"" << inner_pos << "\"\n";
1303 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1305 if (outer_type == "mbox")
1306 os << "use_makebox 1\n";
1307 else if (!frame_color.empty())
1308 os << "use_makebox 0\n";
1310 os << "use_makebox " << (inner_type == "makebox") << '\n';
1311 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1312 os << "width \"\"\n";
1313 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1314 else if (contains(width_unit, '\\'))
1315 os << "width \"" << width_value << "in" << "\"\n";
1317 os << "width \"" << width_value << width_unit << "\"\n";
1318 if (contains(width_unit, '\\')) {
1319 width_unit.erase (0,1); // remove the leading '\'
1320 os << "special \"" << width_unit << "\"\n";
1322 os << "special \"" << width_special << "\"\n";
1323 if (contains(height_unit, '\\'))
1324 os << "height \"" << height_value << "in" << "\"\n";
1326 os << "height \"" << height_value << height_unit << "\"\n";
1327 os << "height_special \"" << height_special << "\"\n";
1328 os << "thickness \"" << thickness << "\"\n";
1329 os << "separation \"" << separation << "\"\n";
1330 os << "shadowsize \"" << shadowsize << "\"\n";
1331 os << "framecolor \"" << framecolor << "\"\n";
1332 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1333 os << "status open\n\n";
1335 // Unfortunately we can't use parse_text_in_inset:
1336 // InsetBox::forcePlainLayout() is hard coded and does not
1337 // use the inset layout. Apart from that do we call parse_text
1338 // up to two times, but need only one check_end_layout.
1339 bool const forcePlainLayout =
1340 (!inner_type.empty() || inner_type == "makebox") &&
1341 outer_type != "shaded" && outer_type != "framed";
1342 Context context(true, parent_context.textclass);
1343 if (forcePlainLayout)
1344 context.layout = &context.textclass.plainLayout();
1346 context.font = parent_context.font;
1348 // If we have no inner box the contents will be read with the outer box
1349 if (!inner_type.empty())
1350 parse_text(p, os, inner_flags, outer, context);
1352 // Ensure that the end of the outer box is parsed correctly:
1353 // The opening brace has been eaten by parse_outer_box()
1354 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1355 outer_flags &= ~FLAG_ITEM;
1356 outer_flags |= FLAG_BRACE_LAST;
1359 // Find end of outer box, output contents if inner_type is
1360 // empty and output possible comments
1361 if (!outer_type.empty()) {
1362 // If we already read the inner box we have to pop
1364 if (!inner_type.empty() && (inner_flags & FLAG_END))
1365 active_environments.pop_back();
1366 // This does not output anything but comments if
1367 // inner_type is not empty (see use_ert)
1368 parse_text(p, os, outer_flags, outer, context);
1371 context.check_end_layout(os);
1373 #ifdef PRESERVE_LAYOUT
1374 // LyX puts a % after the end of the minipage
1375 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1377 //output_comment(p, os, "dummy", parent_context);
1380 parent_context.new_paragraph(os);
1382 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1383 //output_comment(p, os, "dummy", parent_context);
1386 // We add a protected space if something real follows
1387 if (p.good() && p.next_token().cat() != catComment) {
1388 begin_inset(os, "space ~\n");
1394 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1395 active_environments.pop_back();
1396 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1397 // in this case we have to eat the the closing brace of the color box
1398 p.get_token().asInput(); // the '}'
1400 if (p.next_token().asInput() == "}") {
1401 // in this case we assume that the closing brace is from the box settings
1402 // therefore reset these values for the next box
1408 // all boxes except of Frameless and Shaded require calc
1409 if (!(outer_type.empty() || outer_type == "mbox") &&
1410 !((outer_type == "shaded" && inner_type.empty()) ||
1411 (outer_type == "minipage" && inner_type == "shaded") ||
1412 (outer_type == "parbox" && inner_type == "shaded")))
1413 preamble.registerAutomaticallyLoadedPackage("calc");
1417 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1418 Context & parent_context, string const & outer_type,
1419 string const & special)
1421 eat_whitespace(p, os, parent_context, false);
1422 if (flags & FLAG_ITEM) {
1424 if (p.next_token().cat() == catBegin)
1427 cerr << "Warning: Ignoring missing '{' after \\"
1428 << outer_type << '.' << endl;
1429 eat_whitespace(p, os, parent_context, false);
1432 unsigned int inner_flags = 0;
1434 if (outer_type == "minipage" || outer_type == "parbox") {
1435 p.skip_spaces(true);
1436 while (p.hasOpt()) {
1438 p.skip_spaces(true);
1441 p.skip_spaces(true);
1442 if (outer_type == "parbox") {
1444 if (p.next_token().cat() == catBegin)
1446 p.skip_spaces(true);
1449 if (outer_type == "shaded" || outer_type == "mbox") {
1450 // These boxes never have an inner box
1452 } else if (p.next_token().asInput() == "\\parbox") {
1453 inner = p.get_token().cs();
1454 inner_flags = FLAG_ITEM;
1455 } else if (p.next_token().asInput() == "\\begin") {
1456 // Is this a minipage or shaded box?
1459 inner = p.getArg('{', '}');
1461 if (inner == "minipage" || inner == "shaded")
1462 inner_flags = FLAG_END;
1467 if (inner_flags == FLAG_END) {
1468 if (inner != "shaded")
1472 eat_whitespace(p, os, parent_context, false);
1474 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1475 outer_type, special, inner, "", "");
1477 if (inner_flags == FLAG_ITEM) {
1479 eat_whitespace(p, os, parent_context, false);
1481 parse_box(p, os, flags, inner_flags, outer, parent_context,
1482 outer_type, special, inner, "", "");
1487 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1488 bool in_line, bool use_minted)
1490 parent_context.check_layout(os);
1491 begin_inset(os, "listings\n");
1492 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1494 while ((i = arg.find(", ")) != string::npos
1495 || (i = arg.find(",\t")) != string::npos)
1496 arg.erase(i + 1, 1);
1499 string const language = p.getArg('{', '}');
1500 p.skip_spaces(true);
1501 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1502 if (!minted_float.empty()) {
1503 arg += string(arg.empty() ? "" : ",") + minted_float;
1504 minted_nonfloat_caption.clear();
1508 os << "lstparams " << '"' << arg << '"' << '\n';
1509 if (arg.find("\\color") != string::npos)
1510 preamble.registerAutomaticallyLoadedPackage("color");
1513 os << "inline true\n";
1515 os << "inline false\n";
1516 os << "status open\n";
1517 Context context(true, parent_context.textclass);
1518 context.layout = &parent_context.textclass.plainLayout();
1519 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1520 minted_nonfloat_caption.erase(0,3);
1521 os << "\n\\begin_layout Plain Layout\n";
1522 begin_inset(os, "Caption Standard\n");
1523 Context newcontext(true, context.textclass,
1524 context.layout, 0, context.font);
1525 newcontext.check_layout(os);
1526 os << minted_nonfloat_caption << "\n";
1527 newcontext.check_end_layout(os);
1529 os << "\n\\end_layout\n";
1530 minted_nonfloat_caption.clear();
1534 // set catcodes to verbatim early, just in case.
1535 p.setCatcodes(VERBATIM_CATCODES);
1536 string delim = p.get_token().asInput();
1537 //FIXME: handler error condition
1538 s = p.verbatimStuff(delim).second;
1539 // context.new_paragraph(os);
1540 } else if (use_minted) {
1541 s = p.verbatimEnvironment("minted");
1543 s = p.verbatimEnvironment("lstlisting");
1545 output_ert(os, s, context);
1546 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1547 minted_nonfloat_caption.erase(0,3);
1548 os << "\n\\begin_layout Plain Layout\n";
1549 begin_inset(os, "Caption Standard\n");
1550 Context newcontext(true, context.textclass,
1551 context.layout, 0, context.font);
1552 newcontext.check_layout(os);
1553 os << minted_nonfloat_caption << "\n";
1554 newcontext.check_end_layout(os);
1556 os << "\n\\end_layout\n";
1557 minted_nonfloat_caption.clear();
1559 // Don't close the inset here for floating minted listings.
1560 // It will be closed at the end of the listing environment.
1561 if (!use_minted || minted_float.empty())
1564 eat_whitespace(p, os, parent_context, true);
1565 Token t = p.get_token();
1566 if (t.asInput() != "\\end") {
1567 // If anything follows, collect it into a caption.
1568 minted_float_has_caption = true;
1569 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1570 begin_inset(os, "Caption Standard\n");
1571 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1578 /// parse an unknown environment
1579 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1580 unsigned flags, bool outer,
1581 Context & parent_context)
1583 if (name == "tabbing")
1584 // We need to remember that we have to handle '\=' specially
1585 flags |= FLAG_TABBING;
1587 // We need to translate font changes and paragraphs inside the
1588 // environment to ERT if we have a non standard font.
1589 // Otherwise things like
1590 // \large\begin{foo}\huge bar\end{foo}
1592 bool const specialfont =
1593 (parent_context.font != parent_context.normalfont);
1594 bool const new_layout_allowed = parent_context.new_layout_allowed;
1596 parent_context.new_layout_allowed = false;
1597 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1598 // Try to handle options: Look if we have optional arguments,
1599 // and if so, put the brackets in ERT.
1600 while (p.hasOpt()) {
1601 p.get_token(); // eat '['
1602 output_ert_inset(os, "[", parent_context);
1603 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1604 output_ert_inset(os, "]", parent_context);
1606 parse_text_snippet(p, os, flags, outer, parent_context);
1607 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1609 parent_context.new_layout_allowed = new_layout_allowed;
1613 void parse_environment(Parser & p, ostream & os, bool outer,
1614 string & last_env, Context & parent_context)
1616 Layout const * newlayout;
1617 InsetLayout const * newinsetlayout = 0;
1618 string const name = p.getArg('{', '}');
1619 const bool is_starred = suffixIs(name, '*');
1620 string const unstarred_name = rtrim(name, "*");
1621 active_environments.push_back(name);
1623 // We use this loop and break out after a condition is met
1624 // rather than a huge else-if-chain.
1626 if (is_math_env(name)) {
1627 parent_context.check_layout(os);
1628 begin_inset(os, "Formula ");
1629 os << "\\begin{" << name << "}";
1630 parse_math(p, os, FLAG_END, MATH_MODE);
1631 os << "\\end{" << name << "}";
1633 if (is_display_math_env(name)) {
1634 // Prevent the conversion of a line break to a space
1635 // (bug 7668). This does not change the output, but
1636 // looks ugly in LyX.
1637 eat_whitespace(p, os, parent_context, false);
1642 // We need to use fromPolyglossiaEnvironment die to Arabic > arabic
1643 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1644 // We must begin a new paragraph if not already done
1645 if (! parent_context.atParagraphStart()) {
1646 parent_context.check_end_layout(os);
1647 parent_context.new_paragraph(os);
1649 // save the language in the context so that it is
1650 // handled by parse_text
1651 parent_context.font.language =
1652 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1653 parse_text(p, os, FLAG_END, outer, parent_context);
1654 // Just in case the environment is empty
1655 parent_context.extra_stuff.erase();
1656 // We must begin a new paragraph to reset the language
1657 parent_context.new_paragraph(os);
1662 if (unstarred_name == "tabular" || name == "longtable"
1663 || name == "tabularx" || name == "xltabular") {
1664 eat_whitespace(p, os, parent_context, false);
1665 string width = "0pt";
1667 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1668 string const opt = p.getArg('[', ']');
1671 else if (opt == "l")
1673 else if (opt == "r")
1676 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1677 width = lyx::translate_len(p.getArg('{', '}'));
1678 eat_whitespace(p, os, parent_context, false);
1680 parent_context.check_layout(os);
1681 begin_inset(os, "Tabular ");
1682 handle_tabular(p, os, name, width, halign, parent_context);
1688 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1689 eat_whitespace(p, os, parent_context, false);
1690 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1691 eat_whitespace(p, os, parent_context, false);
1692 parent_context.check_layout(os);
1693 begin_inset(os, "Float " + unstarred_name + "\n");
1694 // store the float type for subfloats
1695 // subfloats only work with figures and tables
1696 if (unstarred_name == "figure")
1697 float_type = unstarred_name;
1698 else if (unstarred_name == "table")
1699 float_type = unstarred_name;
1703 os << "placement " << opt << '\n';
1704 if (contains(opt, "H"))
1705 preamble.registerAutomaticallyLoadedPackage("float");
1707 Floating const & fl = parent_context.textclass.floats()
1708 .getType(unstarred_name);
1709 if (!fl.floattype().empty() && fl.usesFloatPkg())
1710 preamble.registerAutomaticallyLoadedPackage("float");
1713 os << "wide " << convert<string>(is_starred)
1714 << "\nsideways false"
1715 << "\nstatus open\n\n";
1716 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1718 // We don't need really a new paragraph, but
1719 // we must make sure that the next item gets a \begin_layout.
1720 parent_context.new_paragraph(os);
1722 // the float is parsed thus delete the type
1727 if (unstarred_name == "sidewaysfigure"
1728 || unstarred_name == "sidewaystable"
1729 || unstarred_name == "sidewaysalgorithm") {
1730 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1731 eat_whitespace(p, os, parent_context, false);
1732 parent_context.check_layout(os);
1733 if (unstarred_name == "sidewaysfigure")
1734 begin_inset(os, "Float figure\n");
1735 else if (unstarred_name == "sidewaystable")
1736 begin_inset(os, "Float table\n");
1737 else if (unstarred_name == "sidewaysalgorithm")
1738 begin_inset(os, "Float algorithm\n");
1740 os << "placement " << opt << '\n';
1741 if (contains(opt, "H"))
1742 preamble.registerAutomaticallyLoadedPackage("float");
1743 os << "wide " << convert<string>(is_starred)
1744 << "\nsideways true"
1745 << "\nstatus open\n\n";
1746 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1748 // We don't need really a new paragraph, but
1749 // we must make sure that the next item gets a \begin_layout.
1750 parent_context.new_paragraph(os);
1752 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1756 if (name == "wrapfigure" || name == "wraptable") {
1757 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1758 eat_whitespace(p, os, parent_context, false);
1759 parent_context.check_layout(os);
1762 string overhang = "0col%";
1765 lines = p.getArg('[', ']');
1766 string const placement = p.getArg('{', '}');
1768 overhang = p.getArg('[', ']');
1769 string const width = p.getArg('{', '}');
1771 if (name == "wrapfigure")
1772 begin_inset(os, "Wrap figure\n");
1774 begin_inset(os, "Wrap table\n");
1775 os << "lines " << lines
1776 << "\nplacement " << placement
1777 << "\noverhang " << lyx::translate_len(overhang)
1778 << "\nwidth " << lyx::translate_len(width)
1779 << "\nstatus open\n\n";
1780 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1782 // We don't need really a new paragraph, but
1783 // we must make sure that the next item gets a \begin_layout.
1784 parent_context.new_paragraph(os);
1786 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1790 if (name == "minipage") {
1791 eat_whitespace(p, os, parent_context, false);
1792 // Test whether this is an outer box of a shaded box
1794 // swallow arguments
1795 while (p.hasOpt()) {
1797 p.skip_spaces(true);
1800 p.skip_spaces(true);
1801 Token t = p.get_token();
1802 bool shaded = false;
1803 if (t.asInput() == "\\begin") {
1804 p.skip_spaces(true);
1805 if (p.getArg('{', '}') == "shaded")
1810 parse_outer_box(p, os, FLAG_END, outer,
1811 parent_context, name, "shaded");
1813 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1814 "", "", name, "", "");
1819 if (name == "comment") {
1820 eat_whitespace(p, os, parent_context, false);
1821 parent_context.check_layout(os);
1822 begin_inset(os, "Note Comment\n");
1823 os << "status open\n";
1824 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1827 skip_braces(p); // eat {} that might by set by LyX behind comments
1828 preamble.registerAutomaticallyLoadedPackage("verbatim");
1832 if (unstarred_name == "verbatim") {
1833 // FIXME: this should go in the generic code that
1834 // handles environments defined in layout file that
1835 // have "PassThru 1". However, the code over there is
1836 // already too complicated for my taste.
1837 string const ascii_name =
1838 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1839 parent_context.new_paragraph(os);
1840 Context context(true, parent_context.textclass,
1841 &parent_context.textclass[from_ascii(ascii_name)]);
1842 string s = p.verbatimEnvironment(name);
1843 output_ert(os, s, context);
1848 if (name == "IPA") {
1849 eat_whitespace(p, os, parent_context, false);
1850 parent_context.check_layout(os);
1851 begin_inset(os, "IPA\n");
1852 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1855 preamble.registerAutomaticallyLoadedPackage("tipa");
1856 preamble.registerAutomaticallyLoadedPackage("tipx");
1860 if (name == parent_context.textclass.titlename()
1861 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1862 parse_text(p, os, FLAG_END, outer, parent_context);
1863 // Just in case the environment is empty
1864 parent_context.extra_stuff.erase();
1865 // We must begin a new paragraph
1866 parent_context.new_paragraph(os);
1871 if (name == "CJK") {
1872 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1873 // It is impossible to decide if a CJK environment was in its own paragraph or within
1874 // a line. We therefore always assume a paragraph since the latter is a rare case.
1875 eat_whitespace(p, os, parent_context, false);
1876 parent_context.check_end_layout(os);
1877 // store the encoding to be able to reset it
1878 string const encoding_old = p.getEncoding();
1879 string const encoding = p.getArg('{', '}');
1880 // FIXME: For some reason JIS does not work. Although the text
1881 // in tests/CJK.tex is identical with the SJIS version if you
1882 // convert both snippets using the recode command line utility,
1883 // the resulting .lyx file contains some extra characters if
1884 // you set buggy_encoding to false for JIS.
1885 bool const buggy_encoding = encoding == "JIS";
1886 if (!buggy_encoding)
1887 p.setEncoding(encoding, Encoding::CJK);
1889 // FIXME: This will read garbage, since the data is not encoded in utf8.
1890 p.setEncoding("UTF-8");
1892 // LyX only supports the same mapping for all CJK
1893 // environments, so we might need to output everything as ERT
1894 string const mapping = trim(p.getArg('{', '}'));
1895 char const * const * const where =
1896 is_known(encoding, supported_CJK_encodings);
1897 if (!buggy_encoding && !preamble.fontCJKSet())
1898 preamble.fontCJK(mapping);
1899 bool knownMapping = mapping == preamble.fontCJK();
1900 if (buggy_encoding || !knownMapping || !where) {
1901 parent_context.check_layout(os);
1902 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1904 // we must parse the content as verbatim because e.g. JIS can contain
1905 // normally invalid characters
1906 // FIXME: This works only for the most simple cases.
1907 // Since TeX control characters are not parsed,
1908 // things like comments are completely wrong.
1909 string const s = p.plainEnvironment("CJK");
1910 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1913 if (snip == "\\" || is_known(snip, known_escaped_chars))
1914 output_ert_inset(os, snip, parent_context);
1915 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1920 output_ert_inset(os, "\\end{" + name + "}",
1924 supported_CJK_languages[where - supported_CJK_encodings];
1925 // store the language because we must reset it at the end
1926 string const lang_old = parent_context.font.language;
1927 parent_context.font.language = lang;
1928 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1929 parent_context.font.language = lang_old;
1930 parent_context.new_paragraph(os);
1932 p.setEncoding(encoding_old);
1937 if (name == "lyxgreyedout") {
1938 eat_whitespace(p, os, parent_context, false);
1939 parent_context.check_layout(os);
1940 begin_inset(os, "Note Greyedout\n");
1941 os << "status open\n";
1942 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1945 if (!preamble.notefontcolor().empty())
1946 preamble.registerAutomaticallyLoadedPackage("color");
1950 if (name == "btSect") {
1951 eat_whitespace(p, os, parent_context, false);
1952 parent_context.check_layout(os);
1953 begin_command_inset(os, "bibtex", "bibtex");
1954 string bibstyle = "plain";
1956 bibstyle = p.getArg('[', ']');
1957 p.skip_spaces(true);
1959 string const bibfile = p.getArg('{', '}');
1960 eat_whitespace(p, os, parent_context, false);
1961 Token t = p.get_token();
1962 if (t.asInput() == "\\btPrintCited") {
1963 p.skip_spaces(true);
1964 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1966 if (t.asInput() == "\\btPrintNotCited") {
1967 p.skip_spaces(true);
1968 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1970 if (t.asInput() == "\\btPrintAll") {
1971 p.skip_spaces(true);
1972 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1974 os << "bibfiles " << '"' << bibfile << "\"\n"
1975 << "options " << '"' << bibstyle << "\"\n";
1976 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1982 if (name == "btUnit") {
1983 string const nt = p.next_next_token().cs();
1984 // Do not attempt to overwrite a former diverging multibib.
1985 // Those are output as ERT instead.
1986 if ((nt == "part" || nt == "chapter"
1987 || nt == "section" || nt == "subsection")
1988 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
1989 parse_text(p, os, FLAG_END, outer, parent_context);
1990 preamble.multibib(nt);
1992 parse_unknown_environment(p, name, os, FLAG_END, outer,
1997 // This is only attempted at turn environments that consist only
1998 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
1999 // Thus we will fall through in other cases.
2000 if (name == "turn") {
2001 // We check if the next thing is a tabular[*|x]
2003 p.getArg('{', '}');// eat turn argument
2004 bool found_end = false;
2005 bool only_table = false;
2006 bool end_table = false;
2009 string envname = p.getArg('{', '}');
2010 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2011 // Now we check if the table is the only content
2012 // of the turn environment
2013 string const tenv = envname;
2014 while (!found_end && !end_table && p.good()) {
2015 envname = p.next_token().cat() == catBegin
2016 ? p.getArg('{', '}') : string();
2017 Token const & t = p.get_token();
2019 end_table = t.asInput() != "\\end"
2021 found_end = t.asInput() == "\\end"
2022 && envname == "turn";
2026 envname = p.getArg('{', '}');
2027 only_table = p.next_next_token().asInput() == "\\end"
2028 && envname == "turn";
2032 string const angle = p.getArg('{', '}');
2034 int const save_tablerotation = parent_context.tablerotation;
2035 parent_context.tablerotation = convert<int>(angle);
2036 parse_text(p, os, FLAG_END, outer, parent_context);
2037 parent_context.tablerotation = save_tablerotation;
2047 // This is only attempted at landscape environments that consist only
2048 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2049 // Other landscape environment is handled via the landscape module, thus
2050 // we will fall through in that case.
2051 if (name == "landscape") {
2052 // We check if the next thing is a longtable
2054 bool found_end = false;
2055 bool only_longtable = false;
2056 bool end_longtable = false;
2059 string envname = p.getArg('{', '}');
2060 if (envname == "longtable" || envname == "xltabular") {
2061 // Now we check if the longtable is the only content
2062 // of the landscape environment
2063 string const ltenv = envname;
2064 while (!found_end && !end_longtable && p.good()) {
2065 envname = p.next_token().cat() == catBegin
2066 ? p.getArg('{', '}') : string();
2067 Token const & t = p.get_token();
2069 end_longtable = t.asInput() != "\\end"
2070 && envname == ltenv;
2071 found_end = t.asInput() == "\\end"
2072 && envname == "landscape";
2074 if (end_longtable) {
2076 envname = p.getArg('{', '}');
2077 only_longtable = p.next_next_token().asInput() == "\\end"
2078 && envname == "landscape";
2080 if (only_longtable) {
2083 int const save_tablerotation = parent_context.tablerotation;
2084 parent_context.tablerotation = 90;
2085 parse_text(p, os, FLAG_END, outer, parent_context);
2086 parent_context.tablerotation = save_tablerotation;
2096 if (name == "framed" || name == "shaded") {
2097 eat_whitespace(p, os, parent_context, false);
2098 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2100 preamble.registerAutomaticallyLoadedPackage("framed");
2104 if (name == "listing") {
2105 minted_float = "float";
2106 eat_whitespace(p, os, parent_context, false);
2107 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2109 minted_float += "=" + opt;
2110 // If something precedes \begin{minted}, we output it at the end
2111 // as a caption, in order to keep it inside the listings inset.
2112 eat_whitespace(p, os, parent_context, true);
2114 Token const & t = p.get_token();
2115 p.skip_spaces(true);
2116 string const envname = p.next_token().cat() == catBegin
2117 ? p.getArg('{', '}') : string();
2118 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2120 minted_float_has_caption = false;
2121 string content = parse_text_snippet(p, FLAG_END, outer,
2123 size_t i = content.find("\\begin_inset listings");
2124 bool minted_env = i != string::npos;
2127 caption = content.substr(0, i);
2128 content.erase(0, i);
2130 parent_context.check_layout(os);
2131 if (minted_env && minted_float_has_caption) {
2132 eat_whitespace(p, os, parent_context, true);
2133 os << content << "\n";
2134 if (!caption.empty())
2135 os << caption << "\n";
2136 os << "\n\\end_layout\n"; // close inner layout
2137 end_inset(os); // close caption inset
2138 os << "\n\\end_layout\n"; // close outer layout
2139 } else if (!caption.empty()) {
2141 begin_inset(os, "listings\n");
2142 os << "lstparams " << '"' << minted_float << '"' << '\n';
2143 os << "inline false\n";
2144 os << "status collapsed\n";
2146 os << "\n\\begin_layout Plain Layout\n";
2147 begin_inset(os, "Caption Standard\n");
2148 Context newcontext(true, parent_context.textclass,
2149 0, 0, parent_context.font);
2150 newcontext.check_layout(os);
2151 os << caption << "\n";
2152 newcontext.check_end_layout(os);
2154 os << "\n\\end_layout\n";
2155 } else if (content.empty()) {
2156 begin_inset(os, "listings\n");
2157 os << "lstparams " << '"' << minted_float << '"' << '\n';
2158 os << "inline false\n";
2159 os << "status collapsed\n";
2161 os << content << "\n";
2163 end_inset(os); // close listings inset
2164 parent_context.check_end_layout(os);
2165 parent_context.new_paragraph(os);
2167 minted_float.clear();
2168 minted_float_has_caption = false;
2172 if (name == "lstlisting" || name == "minted") {
2173 bool use_minted = name == "minted";
2174 // with listings, we do not eat newlines here since
2175 // \begin{lstlistings}
2178 // // \begin{lstlistings}%
2181 // reads [foo] as content, whereas
2182 // // \begin{lstlistings}%
2185 // \begin{lstlistings}[foo,
2187 // reads [foo...] as argument.
2188 eat_whitespace(p, os, parent_context, false, use_minted);
2189 if (use_minted && minted_float.empty()) {
2190 // look ahead for a bottom caption
2192 bool found_end_minted = false;
2193 while (!found_end_minted && p.good()) {
2194 Token const & t = p.get_token();
2196 string const envname =
2197 p.next_token().cat() == catBegin
2198 ? p.getArg('{', '}') : string();
2199 found_end_minted = t.asInput() == "\\end"
2200 && envname == "minted";
2202 eat_whitespace(p, os, parent_context, true);
2203 Token const & t = p.get_token();
2204 p.skip_spaces(true);
2205 if (t.asInput() == "\\lyxmintcaption") {
2206 string const pos = p.getArg('[', ']');
2208 string const caption =
2209 parse_text_snippet(p, FLAG_ITEM,
2210 false, parent_context);
2211 minted_nonfloat_caption = "[b]" + caption;
2212 eat_whitespace(p, os, parent_context, true);
2217 parse_listings(p, os, parent_context, false, use_minted);
2222 if (!parent_context.new_layout_allowed) {
2223 parse_unknown_environment(p, name, os, FLAG_END, outer,
2228 // Alignment and spacing settings
2229 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2230 // therefore are totally broken!
2231 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2232 // they are commands not environments. They are furthermore switches that
2233 // can be ended by another switches, but also by commands like \footnote or
2234 // \parbox. So the only safe way is to leave them untouched.
2235 // However, we support the pseudo-environments
2236 // \begin{centering} ... \end{centering}
2237 // \begin{raggedright} ... \end{raggedright}
2238 // \begin{raggedleft} ... \end{raggedleft}
2239 // since they are used by LyX in floats (for spacing reasons)
2240 if (name == "center" || name == "centering"
2241 || name == "flushleft" || name == "raggedright"
2242 || name == "flushright" || name == "raggedleft"
2243 || name == "singlespace" || name == "onehalfspace"
2244 || name == "doublespace" || name == "spacing") {
2245 eat_whitespace(p, os, parent_context, false);
2246 // We must begin a new paragraph if not already done
2247 if (! parent_context.atParagraphStart()) {
2248 parent_context.check_end_layout(os);
2249 parent_context.new_paragraph(os);
2251 if (name == "flushleft" || name == "raggedright")
2252 parent_context.add_extra_stuff("\\align left\n");
2253 else if (name == "flushright" || name == "raggedleft")
2254 parent_context.add_extra_stuff("\\align right\n");
2255 else if (name == "center" || name == "centering")
2256 parent_context.add_extra_stuff("\\align center\n");
2257 else if (name == "singlespace")
2258 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2259 else if (name == "onehalfspace") {
2260 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2261 preamble.registerAutomaticallyLoadedPackage("setspace");
2262 } else if (name == "doublespace") {
2263 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2264 preamble.registerAutomaticallyLoadedPackage("setspace");
2265 } else if (name == "spacing") {
2266 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2267 preamble.registerAutomaticallyLoadedPackage("setspace");
2269 parse_text(p, os, FLAG_END, outer, parent_context);
2270 // Just in case the environment is empty
2271 parent_context.extra_stuff.erase();
2272 // We must begin a new paragraph to reset the alignment
2273 parent_context.new_paragraph(os);
2278 // The single '=' is meant here.
2279 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2280 eat_whitespace(p, os, parent_context, false);
2281 Context context(true, parent_context.textclass, newlayout,
2282 parent_context.layout, parent_context.font);
2283 if (parent_context.deeper_paragraph) {
2284 // We are beginning a nested environment after a
2285 // deeper paragraph inside the outer list environment.
2286 // Therefore we don't need to output a "begin deeper".
2287 context.need_end_deeper = true;
2289 parent_context.check_end_layout(os);
2290 if (last_env == name) {
2291 // we need to output a separator since LyX would export
2292 // the two environments as one otherwise (bug 5716)
2293 TeX2LyXDocClass const & textclass(parent_context.textclass);
2294 Context newcontext(true, textclass,
2295 &(textclass.defaultLayout()));
2296 newcontext.check_layout(os);
2297 begin_inset(os, "Separator plain\n");
2299 newcontext.check_end_layout(os);
2301 switch (context.layout->latextype) {
2302 case LATEX_LIST_ENVIRONMENT:
2303 context.in_list_preamble =
2304 !context.layout->listpreamble().empty()
2305 && p.hasListPreamble(context.layout->itemcommand());
2306 context.add_par_extra_stuff("\\labelwidthstring "
2307 + p.verbatim_item() + '\n');
2310 case LATEX_BIB_ENVIRONMENT:
2311 p.verbatim_item(); // swallow next arg
2317 context.check_deeper(os);
2318 if (newlayout->keepempty) {
2319 // We need to start a new paragraph
2320 // even if it is empty.
2321 context.new_paragraph(os);
2322 context.check_layout(os);
2324 // handle known optional and required arguments
2325 if (context.layout->latextype == LATEX_ENVIRONMENT)
2326 output_arguments(os, p, outer, false, string(), context,
2327 context.layout->latexargs());
2328 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2329 context.in_list_preamble =
2330 !context.layout->listpreamble().empty()
2331 && p.hasListPreamble(context.layout->itemcommand());
2333 output_arguments(oss, p, outer, false, string(), context,
2334 context.layout->latexargs());
2335 context.list_extra_stuff = oss.str();
2337 if (context.in_list_preamble) {
2338 // Collect the stuff between \begin and first \item
2339 context.list_preamble =
2340 parse_text_snippet(p, FLAG_END, outer, context);
2341 context.in_list_preamble = false;
2343 parse_text(p, os, FLAG_END, outer, context);
2344 if (context.layout->latextype == LATEX_ENVIRONMENT)
2345 output_arguments(os, p, outer, false, "post", context,
2346 context.layout->postcommandargs());
2347 context.check_end_layout(os);
2348 if (parent_context.deeper_paragraph) {
2349 // We must suppress the "end deeper" because we
2350 // suppressed the "begin deeper" above.
2351 context.need_end_deeper = false;
2353 context.check_end_deeper(os);
2354 parent_context.new_paragraph(os);
2356 if (!preamble.titleLayoutFound())
2357 preamble.titleLayoutFound(newlayout->intitle);
2358 set<string> const & req = newlayout->requires();
2359 set<string>::const_iterator it = req.begin();
2360 set<string>::const_iterator en = req.end();
2361 for (; it != en; ++it)
2362 preamble.registerAutomaticallyLoadedPackage(*it);
2366 // The single '=' is meant here.
2367 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2368 eat_whitespace(p, os, parent_context, false);
2369 parent_context.check_layout(os);
2370 begin_inset(os, "Flex ");
2371 docstring flex_name = newinsetlayout->name();
2372 // FIXME: what do we do if the prefix is not Flex: ?
2373 if (prefixIs(flex_name, from_ascii("Flex:")))
2374 flex_name.erase(0, 5);
2375 os << to_utf8(flex_name) << '\n'
2376 << "status collapsed\n";
2377 if (newinsetlayout->isPassThru()) {
2378 string const arg = p.verbatimEnvironment(name);
2379 Context context(true, parent_context.textclass,
2380 &parent_context.textclass.plainLayout(),
2381 parent_context.layout);
2382 output_ert(os, arg, parent_context);
2384 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2389 if (name == "appendix") {
2390 // This is no good latex style, but it works and is used in some documents...
2391 eat_whitespace(p, os, parent_context, false);
2392 parent_context.check_end_layout(os);
2393 Context context(true, parent_context.textclass, parent_context.layout,
2394 parent_context.layout, parent_context.font);
2395 context.check_layout(os);
2396 os << "\\start_of_appendix\n";
2397 parse_text(p, os, FLAG_END, outer, context);
2398 context.check_end_layout(os);
2403 if (known_environments.find(name) != known_environments.end()) {
2404 vector<ArgumentType> arguments = known_environments[name];
2405 // The last "argument" denotes wether we may translate the
2406 // environment contents to LyX
2407 // The default required if no argument is given makes us
2408 // compatible with the reLyXre environment.
2409 ArgumentType contents = arguments.empty() ?
2412 if (!arguments.empty())
2413 arguments.pop_back();
2414 // See comment in parse_unknown_environment()
2415 bool const specialfont =
2416 (parent_context.font != parent_context.normalfont);
2417 bool const new_layout_allowed =
2418 parent_context.new_layout_allowed;
2420 parent_context.new_layout_allowed = false;
2421 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2422 outer, parent_context);
2423 if (contents == verbatim)
2424 output_ert_inset(os, p.ertEnvironment(name),
2427 parse_text_snippet(p, os, FLAG_END, outer,
2429 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2431 parent_context.new_layout_allowed = new_layout_allowed;
2435 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2440 active_environments.pop_back();
2444 /// parses a comment and outputs it to \p os.
2445 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2446 bool skipNewlines = false)
2448 LASSERT(t.cat() == catComment, return);
2449 if (!t.cs().empty()) {
2450 context.check_layout(os);
2451 output_comment(p, os, t.cs(), context);
2452 if (p.next_token().cat() == catNewline) {
2453 // A newline after a comment line starts a new
2455 if (context.new_layout_allowed) {
2456 if(!context.atParagraphStart())
2457 // Only start a new paragraph if not already
2458 // done (we might get called recursively)
2459 context.new_paragraph(os);
2461 output_ert_inset(os, "\n", context);
2462 eat_whitespace(p, os, context, true);
2464 } else if (!skipNewlines) {
2465 // "%\n" combination
2472 * Reads spaces and comments until the first non-space, non-comment token.
2473 * New paragraphs (double newlines or \\par) are handled like simple spaces
2474 * if \p eatParagraph is true.
2475 * If \p eatNewline is false, newlines won't be treated as whitespace.
2476 * Spaces are skipped, but comments are written to \p os.
2478 void eat_whitespace(Parser & p, ostream & os, Context & context,
2479 bool eatParagraph, bool eatNewline)
2482 Token const & t = p.get_token();
2483 if (t.cat() == catComment)
2484 parse_comment(p, os, t, context, !eatNewline);
2485 else if ((!eatParagraph && p.isParagraph()) ||
2486 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2495 * Set a font attribute, parse text and reset the font attribute.
2496 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2497 * \param currentvalue Current value of the attribute. Is set to the new
2498 * value during parsing.
2499 * \param newvalue New value of the attribute
2501 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2502 Context & context, string const & attribute,
2503 string & currentvalue, string const & newvalue)
2505 context.check_layout(os);
2506 string const oldvalue = currentvalue;
2507 currentvalue = newvalue;
2508 os << '\n' << attribute << ' ' << newvalue << "\n";
2509 parse_text_snippet(p, os, flags, outer, context);
2510 context.check_layout(os);
2511 os << '\n' << attribute << ' ' << oldvalue << "\n";
2512 currentvalue = oldvalue;
2516 /// get the arguments of a natbib or jurabib citation command
2517 void get_cite_arguments(Parser & p, bool natbibOrder,
2518 string & before, string & after, bool const qualified = false)
2520 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2522 // text before the citation
2524 // text after the citation
2525 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2527 if (!after.empty()) {
2528 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2529 if (natbibOrder && !before.empty())
2530 swap(before, after);
2535 void copy_file(FileName const & src, string dstname)
2539 string const absParent = getParentFilePath(false);
2541 if (FileName::isAbsolute(dstname))
2542 dst = FileName(dstname);
2544 dst = makeAbsPath(dstname, absParent);
2545 FileName const srcpath = src.onlyPath();
2546 FileName const dstpath = dst.onlyPath();
2547 if (equivalent(srcpath, dstpath))
2549 if (!dstpath.isDirectory()) {
2550 if (!dstpath.createPath()) {
2551 cerr << "Warning: Could not create directory for file `"
2552 << dst.absFileName() << "´." << endl;
2556 if (dst.isReadableFile()) {
2557 if (overwriteFiles())
2558 cerr << "Warning: Overwriting existing file `"
2559 << dst.absFileName() << "´." << endl;
2561 cerr << "Warning: Not overwriting existing file `"
2562 << dst.absFileName() << "´." << endl;
2566 if (!src.copyTo(dst))
2567 cerr << "Warning: Could not copy file `" << src.absFileName()
2568 << "´ to `" << dst.absFileName() << "´." << endl;
2572 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2573 bool parse_chunk(Parser & p, ostream & os, Context & context)
2575 // check whether a chunk is possible here.
2576 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2582 // read the parameters
2583 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2584 if (!params.first) {
2589 Parser::Arg const code = p.verbatimStuff("\n@");
2594 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2595 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2599 // The last newline read is important for paragraph handling
2603 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2604 // We must have a valid layout before outputting the Chunk inset.
2605 context.check_layout(os);
2606 Context chunkcontext(true, context.textclass);
2607 chunkcontext.layout = &context.textclass.plainLayout();
2608 begin_inset(os, "Flex Chunk");
2609 os << "\nstatus open\n";
2610 if (!params.second.empty()) {
2611 chunkcontext.check_layout(os);
2612 Context paramscontext(true, context.textclass);
2613 paramscontext.layout = &context.textclass.plainLayout();
2614 begin_inset(os, "Argument 1");
2615 os << "\nstatus open\n";
2616 output_ert(os, params.second, paramscontext);
2619 output_ert(os, code.second, chunkcontext);
2627 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2628 bool is_macro(Parser & p)
2630 Token first = p.curr_token();
2631 if (first.cat() != catEscape || !p.good())
2633 if (first.cs() == "def")
2635 if (first.cs() != "global" && first.cs() != "long")
2637 Token second = p.get_token();
2639 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2640 second.cat() == catNewline || second.cat() == catComment)) {
2641 second = p.get_token();
2644 bool secondvalid = second.cat() == catEscape;
2646 bool thirdvalid = false;
2647 if (p.good() && first.cs() == "global" && secondvalid &&
2648 second.cs() == "long") {
2649 third = p.get_token();
2651 while (p.good() && !p.isParagraph() &&
2652 (third.cat() == catSpace ||
2653 third.cat() == catNewline ||
2654 third.cat() == catComment)) {
2655 third = p.get_token();
2658 thirdvalid = third.cat() == catEscape;
2660 for (int i = 0; i < pos; ++i)
2665 return (first.cs() == "global" || first.cs() == "long") &&
2666 second.cs() == "def";
2667 return first.cs() == "global" && second.cs() == "long" &&
2668 third.cs() == "def";
2672 /// Parse a macro definition (assumes that is_macro() returned true)
2673 void parse_macro(Parser & p, ostream & os, Context & context)
2675 context.check_layout(os);
2676 Token first = p.curr_token();
2679 string command = first.asInput();
2680 if (first.cs() != "def") {
2682 eat_whitespace(p, os, context, false);
2683 second = p.curr_token();
2684 command += second.asInput();
2685 if (second.cs() != "def") {
2687 eat_whitespace(p, os, context, false);
2688 third = p.curr_token();
2689 command += third.asInput();
2692 eat_whitespace(p, os, context, false);
2693 string const name = p.get_token().cs();
2694 eat_whitespace(p, os, context, false);
2700 while (p.next_token().cat() != catBegin) {
2701 if (p.next_token().cat() == catParameter) {
2706 // followed by number?
2707 if (p.next_token().cat() == catOther) {
2708 string s = p.get_token().asInput();
2710 // number = current arity + 1?
2711 if (s.size() == 1 && s[0] == arity + '0' + 1)
2716 paramtext += p.get_token().cs();
2718 paramtext += p.get_token().cs();
2723 // only output simple (i.e. compatible) macro as FormulaMacros
2724 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2726 context.check_layout(os);
2727 begin_inset(os, "FormulaMacro");
2728 os << "\n\\def" << ert;
2731 output_ert_inset(os, command + ert, context);
2735 void registerExternalTemplatePackages(string const & name)
2737 external::TemplateManager const & etm = external::TemplateManager::get();
2738 external::Template const * const et = etm.getTemplateByName(name);
2741 external::Template::Formats::const_iterator cit = et->formats.end();
2743 cit = et->formats.find("PDFLaTeX");
2744 if (cit == et->formats.end())
2745 // If the template has not specified a PDFLaTeX output,
2746 // we try the LaTeX format.
2747 cit = et->formats.find("LaTeX");
2748 if (cit == et->formats.end())
2750 vector<string>::const_iterator qit = cit->second.requirements.begin();
2751 vector<string>::const_iterator qend = cit->second.requirements.end();
2752 for (; qit != qend; ++qit)
2753 preamble.registerAutomaticallyLoadedPackage(*qit);
2756 } // anonymous namespace
2760 * Find a file with basename \p name in path \p path and an extension
2763 string find_file(string const & name, string const & path,
2764 char const * const * extensions)
2766 for (char const * const * what = extensions; *what; ++what) {
2767 string const trial = addExtension(name, *what);
2768 if (makeAbsPath(trial, path).exists())
2775 /// Convert filenames with TeX macros and/or quotes to something LyX
2777 string const normalize_filename(string const & name)
2782 Token const & t = p.get_token();
2783 if (t.cat() != catEscape)
2785 else if (t.cs() == "lyxdot") {
2786 // This is used by LyX for simple dots in relative
2790 } else if (t.cs() == "space") {
2793 } else if (t.cs() == "string") {
2794 // Convert \string" to " and \string~ to ~
2795 Token const & n = p.next_token();
2796 if (n.asInput() != "\"" && n.asInput() != "~")
2801 // Strip quotes. This is a bit complicated (see latex_path()).
2802 string full = os.str();
2803 if (!full.empty() && full[0] == '"') {
2804 string base = removeExtension(full);
2805 string ext = getExtension(full);
2806 if (!base.empty() && base[base.length()-1] == '"')
2809 return addExtension(trim(base, "\""), ext);
2810 if (full[full.length()-1] == '"')
2813 return trim(full, "\"");
2819 /// Convert \p name from TeX convention (relative to master file) to LyX
2820 /// convention (relative to .lyx file) if it is relative
2821 void fix_child_filename(string & name)
2823 string const absMasterTeX = getMasterFilePath(true);
2824 bool const isabs = FileName::isAbsolute(name);
2825 // convert from "relative to .tex master" to absolute original path
2827 name = makeAbsPath(name, absMasterTeX).absFileName();
2828 bool copyfile = copyFiles();
2829 string const absParentLyX = getParentFilePath(false);
2832 // convert from absolute original path to "relative to master file"
2833 string const rel = to_utf8(makeRelPath(from_utf8(name),
2834 from_utf8(absMasterTeX)));
2835 // re-interpret "relative to .tex file" as "relative to .lyx file"
2836 // (is different if the master .lyx file resides in a
2837 // different path than the master .tex file)
2838 string const absMasterLyX = getMasterFilePath(false);
2839 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2840 // Do not copy if the new path is impossible to create. Example:
2841 // absMasterTeX = "/foo/bar/"
2842 // absMasterLyX = "/bar/"
2843 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2844 if (contains(name, "/../"))
2851 // convert from absolute original path to
2852 // "relative to .lyx file"
2853 name = to_utf8(makeRelPath(from_utf8(abs),
2854 from_utf8(absParentLyX)));
2858 // convert from absolute original path to "relative to .lyx file"
2859 name = to_utf8(makeRelPath(from_utf8(name),
2860 from_utf8(absParentLyX)));
2865 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2866 Context & context, string const rdelim)
2868 Layout const * newlayout = 0;
2869 InsetLayout const * newinsetlayout = 0;
2870 char const * const * where = 0;
2871 // Store the latest bibliographystyle, addcontentslineContent and
2872 // nocite{*} option (needed for bibtex inset)
2874 string contentslineContent;
2875 // Some classes provide a \bibliographystyle, so do not output
2876 // any if none is explicitly set.
2877 string bibliographystyle;
2878 bool const use_natbib = isProvided("natbib");
2879 bool const use_jurabib = isProvided("jurabib");
2880 bool const use_biblatex = isProvided("biblatex")
2881 && preamble.citeEngine() != "biblatex-natbib";
2882 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2883 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2884 need_commentbib = use_biblatex || use_biblatex_natbib;
2887 // it is impossible to determine the correct encoding for non-CJK Japanese.
2888 // Therefore write a note at the beginning of the document
2889 if (is_nonCJKJapanese) {
2890 context.check_layout(os);
2891 begin_inset(os, "Note Note\n");
2892 os << "status open\n\\begin_layout Plain Layout\n"
2893 << "\\series bold\n"
2894 << "Important information:\n"
2895 << "\\end_layout\n\n"
2896 << "\\begin_layout Plain Layout\n"
2897 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2898 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2899 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2900 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2901 << " and specify the encoding using the -e command-line switch.\n"
2902 << " In addition, you might want to double check that the desired output encoding\n"
2903 << " is correctly selected in Document > Settings > Language.\n"
2904 << "\\end_layout\n";
2906 is_nonCJKJapanese = false;
2909 bool have_cycled = false;
2911 // Leave here only after at least one cycle
2912 if (have_cycled && flags & FLAG_LEAVE) {
2913 flags &= ~FLAG_LEAVE;
2917 Token const & t = p.get_token();
2919 debugToken(cerr, t, flags);
2922 if (context.in_list_preamble
2923 && p.next_token().cs() == context.layout->itemcommand()) {
2924 // We are parsing a list preamble. End before first \item.
2925 flags |= FLAG_LEAVE;
2926 context.in_list_preamble = false;
2929 if (flags & FLAG_ITEM) {
2930 if (t.cat() == catSpace)
2933 flags &= ~FLAG_ITEM;
2934 if (t.cat() == catBegin) {
2935 // skip the brace and collect everything to the next matching
2937 flags |= FLAG_BRACE_LAST;
2941 // handle only this single token, leave the loop if done
2942 flags |= FLAG_LEAVE;
2945 if (t.cat() != catEscape && t.character() == ']' &&
2946 (flags & FLAG_BRACK_LAST))
2948 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2950 string tok = t.asInput();
2951 // we only support delimiters with max 2 chars for now.
2952 if (rdelim.size() > 1)
2953 tok += p.next_token().asInput();
2954 if (t.cat() != catEscape && !rdelim.empty()
2955 && tok == rdelim && (flags & FLAG_RDELIM)) {
2956 if (rdelim.size() > 1)
2957 p.get_token(); // eat rdelim
2961 // If there is anything between \end{env} and \begin{env} we
2962 // don't need to output a separator.
2963 if (t.cat() != catSpace && t.cat() != catNewline &&
2964 t.asInput() != "\\begin")
2971 bool const starred = p.next_token().asInput() == "*";
2972 string const starredname(starred ? (t.cs() + '*') : t.cs());
2973 if (t.cat() == catMath) {
2974 // we are inside some text mode thingy, so opening new math is allowed
2975 context.check_layout(os);
2976 begin_inset(os, "Formula ");
2977 Token const & n = p.get_token();
2978 bool const display(n.cat() == catMath && outer);
2980 // TeX's $$...$$ syntax for displayed math
2982 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2984 p.get_token(); // skip the second '$' token
2986 // simple $...$ stuff
2989 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2994 // Prevent the conversion of a line break to a
2995 // space (bug 7668). This does not change the
2996 // output, but looks ugly in LyX.
2997 eat_whitespace(p, os, context, false);
3002 if (t.cat() == catSuper || t.cat() == catSub) {
3003 cerr << "catcode " << t << " illegal in text mode\n";
3007 // Basic support for quotes. We try to disambiguate
3008 // quotes from the context (e.g., a left english quote is
3009 // the same as a right german quote...).
3010 // Try to make a smart guess about the side
3011 Token const prev = p.prev_token();
3012 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3013 && prev.character() != '\n' && prev.character() != '~');
3014 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3015 context.check_layout(os);
3016 begin_inset(os, "Quotes ");
3017 os << guessQuoteStyle("eld", opening);
3023 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3024 context.check_layout(os);
3025 begin_inset(os, "Quotes ");
3026 os << guessQuoteStyle("erd", opening);
3033 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3034 context.check_layout(os);
3035 begin_inset(os, "Quotes ");
3036 os << guessQuoteStyle("ald", opening);
3043 if (t.asInput() == "<"
3044 && p.next_token().asInput() == "<") {
3045 bool has_chunk = false;
3049 has_chunk = parse_chunk(p, os, context);
3055 context.check_layout(os);
3056 begin_inset(os, "Quotes ");
3057 os << guessQuoteStyle("ard", opening);
3065 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3066 check_space(p, os, context);
3070 // babel shorthands (also used by polyglossia)
3071 // Since these can have different meanings for different languages
3072 // we import them as ERT (but they must be put in ERT to get output
3074 if (t.asInput() == "\"") {
3076 // These are known pairs. We put them together in
3077 // one ERT inset. In other cases (such as "a), only
3078 // the quotation mark is ERTed.
3079 if (p.next_token().asInput() == "\""
3080 || p.next_token().asInput() == "|"
3081 || p.next_token().asInput() == "-"
3082 || p.next_token().asInput() == "~"
3083 || p.next_token().asInput() == "="
3084 || p.next_token().asInput() == "/"
3085 || p.next_token().asInput() == "~"
3086 || p.next_token().asInput() == "'"
3087 || p.next_token().asInput() == "`"
3088 || p.next_token().asInput() == "<"
3089 || p.next_token().asInput() == ">") {
3090 s += p.next_token().asInput();
3093 output_ert_inset(os, s, context);
3097 if (t.character() == '[' && noweb_mode &&
3098 p.next_token().character() == '[') {
3099 // These can contain underscores
3101 string const s = p.getFullOpt() + ']';
3102 if (p.next_token().character() == ']')
3105 cerr << "Warning: Inserting missing ']' in '"
3106 << s << "'." << endl;
3107 output_ert_inset(os, s, context);
3111 if (t.cat() == catLetter) {
3112 context.check_layout(os);
3117 if (t.cat() == catOther ||
3118 t.cat() == catAlign ||
3119 t.cat() == catParameter) {
3120 context.check_layout(os);
3121 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3122 context.merging_hyphens_allowed &&
3123 context.font.family != "ttfamily" &&
3124 !context.layout->pass_thru) {
3125 if (p.next_next_token().asInput() == "-") {
3127 os << to_utf8(docstring(1, 0x2014));
3131 os << to_utf8(docstring(1, 0x2013));
3134 // This translates "&" to "\\&" which may be wrong...
3139 if (p.isParagraph()) {
3140 // In minted floating listings we will collect
3141 // everything into the caption, where multiple
3142 // paragraphs are forbidden.
3143 if (minted_float.empty()) {
3144 if (context.new_layout_allowed)
3145 context.new_paragraph(os);
3147 output_ert_inset(os, "\\par ", context);
3150 eat_whitespace(p, os, context, true);
3154 if (t.cat() == catActive) {
3155 context.check_layout(os);
3156 if (t.character() == '~') {
3157 if (context.layout->free_spacing)
3160 begin_inset(os, "space ~\n");
3168 if (t.cat() == catBegin) {
3169 Token const next = p.next_token();
3170 Token const end = p.next_next_token();
3171 if (next.cat() == catEnd) {
3173 Token const prev = p.prev_token();
3175 if (p.next_token().character() == '`')
3176 ; // ignore it in {}``
3178 output_ert_inset(os, "{}", context);
3179 } else if (next.cat() == catEscape &&
3180 is_known(next.cs(), known_quotes) &&
3181 end.cat() == catEnd) {
3182 // Something like {\textquoteright} (e.g.
3183 // from writer2latex). We may skip the
3184 // braces here for better readability.
3185 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3187 } else if (p.next_token().asInput() == "\\ascii") {
3188 // handle the \ascii characters
3189 // (the case without braces is handled later)
3190 // the code is "{\ascii\xxx}"
3191 p.get_token(); // eat \ascii
3192 string name2 = p.get_token().asInput();
3193 p.get_token(); // eat the final '}'
3194 string const name = "{\\ascii" + name2 + "}";
3198 // get the character from unicodesymbols
3199 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3200 Encodings::TEXT_CMD, termination, rem, &req);
3202 context.check_layout(os);
3205 output_ert_inset(os,
3206 to_utf8(rem), context);
3207 for (set<string>::const_iterator it = req.begin();
3208 it != req.end(); ++it)
3209 preamble.registerAutomaticallyLoadedPackage(*it);
3211 // we did not find a non-ert version
3212 output_ert_inset(os, name, context);
3214 context.check_layout(os);
3215 // special handling of font attribute changes
3216 Token const prev = p.prev_token();
3217 TeXFont const oldFont = context.font;
3218 if (next.character() == '[' ||
3219 next.character() == ']' ||
3220 next.character() == '*') {
3222 if (p.next_token().cat() == catEnd) {
3227 output_ert_inset(os, "{", context);
3228 parse_text_snippet(p, os,
3231 output_ert_inset(os, "}", context);
3233 } else if (! context.new_layout_allowed) {
3234 output_ert_inset(os, "{", context);
3235 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3237 output_ert_inset(os, "}", context);
3238 } else if (is_known(next.cs(), known_sizes)) {
3239 // next will change the size, so we must
3241 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3243 if (!context.atParagraphStart())
3245 << context.font.size << "\n";
3246 } else if (is_known(next.cs(), known_font_families)) {
3247 // next will change the font family, so we
3248 // must reset it here
3249 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3251 if (!context.atParagraphStart())
3253 << context.font.family << "\n";
3254 } else if (is_known(next.cs(), known_font_series)) {
3255 // next will change the font series, so we
3256 // must reset it here
3257 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3259 if (!context.atParagraphStart())
3261 << context.font.series << "\n";
3262 } else if (is_known(next.cs(), known_font_shapes)) {
3263 // next will change the font shape, so we
3264 // must reset it here
3265 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3267 if (!context.atParagraphStart())
3269 << context.font.shape << "\n";
3270 } else if (is_known(next.cs(), known_old_font_families) ||
3271 is_known(next.cs(), known_old_font_series) ||
3272 is_known(next.cs(), known_old_font_shapes)) {
3273 // next will change the font family, series
3274 // and shape, so we must reset it here
3275 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3277 if (!context.atParagraphStart())
3279 << context.font.family
3281 << context.font.series
3283 << context.font.shape << "\n";
3285 output_ert_inset(os, "{", context);
3286 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3288 output_ert_inset(os, "}", context);
3294 if (t.cat() == catEnd) {
3295 if (flags & FLAG_BRACE_LAST) {
3298 cerr << "stray '}' in text\n";
3299 output_ert_inset(os, "}", context);
3303 if (t.cat() == catComment) {
3304 parse_comment(p, os, t, context);
3309 // control sequences
3312 if (t.cs() == "(" || t.cs() == "[") {
3313 bool const simple = t.cs() == "(";
3314 context.check_layout(os);
3315 begin_inset(os, "Formula");
3316 os << " \\" << t.cs();
3317 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3318 os << '\\' << (simple ? ')' : ']');
3321 // Prevent the conversion of a line break to a
3322 // space (bug 7668). This does not change the
3323 // output, but looks ugly in LyX.
3324 eat_whitespace(p, os, context, false);
3329 if (t.cs() == "begin") {
3330 parse_environment(p, os, outer, last_env,
3335 if (t.cs() == "end") {
3336 if (flags & FLAG_END) {
3337 // eat environment name
3338 string const name = p.getArg('{', '}');
3339 if (name != active_environment())
3340 cerr << "\\end{" + name + "} does not match \\begin{"
3341 + active_environment() + "}\n";
3344 p.error("found 'end' unexpectedly");
3348 // "item" by default, but could be something else
3349 if (t.cs() == context.layout->itemcommand()) {
3351 if (context.layout->labeltype == LABEL_MANUAL) {
3352 // FIXME: This swallows comments, but we cannot use
3353 // eat_whitespace() since we must not output
3354 // anything before the item.
3355 p.skip_spaces(true);
3356 s = p.verbatimOption();
3358 p.skip_spaces(false);
3360 context.check_layout(os);
3361 if (context.has_item) {
3362 // An item in an unknown list-like environment
3363 // FIXME: Do this in check_layout()!
3364 context.has_item = false;
3365 string item = "\\" + context.layout->itemcommand();
3368 output_ert_inset(os, item, context);
3370 if (context.layout->labeltype != LABEL_MANUAL)
3371 output_arguments(os, p, outer, false, "item", context,
3372 context.layout->itemargs());
3373 if (!context.list_preamble.empty()) {
3374 // We have a list preamble. Output it here.
3375 begin_inset(os, "Argument listpreamble:1");
3376 os << "\nstatus collapsed\n\n"
3377 << "\\begin_layout Plain Layout\n\n"
3378 << rtrim(context.list_preamble)
3379 << "\n\\end_layout";
3381 context.list_preamble.clear();
3383 if (!context.list_extra_stuff.empty()) {
3384 os << context.list_extra_stuff;
3385 context.list_extra_stuff.clear();
3387 else if (!s.empty()) {
3388 // LyX adds braces around the argument,
3389 // so we need to remove them here.
3390 if (s.size() > 2 && s[0] == '{' &&
3391 s[s.size()-1] == '}')
3392 s = s.substr(1, s.size()-2);
3393 // If the argument contains a space we
3394 // must put it into ERT: Otherwise LyX
3395 // would misinterpret the space as
3396 // item delimiter (bug 7663)
3397 if (contains(s, ' ')) {
3398 output_ert_inset(os, s, context);
3401 os << parse_text_snippet(p2,
3402 FLAG_BRACK_LAST, outer, context);
3404 // The space is needed to separate the
3405 // item from the rest of the sentence.
3407 eat_whitespace(p, os, context, false);
3412 if (t.cs() == "bibitem") {
3414 context.check_layout(os);
3415 eat_whitespace(p, os, context, false);
3416 string label = p.verbatimOption();
3417 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3418 bool const literal = !lbl.first;
3419 label = literal ? subst(label, "\n", " ") : lbl.second;
3420 string lit = literal ? "\"true\"" : "\"false\"";
3421 string key = convert_literate_command_inset_arg(p.verbatim_item());
3422 begin_command_inset(os, "bibitem", "bibitem");
3423 os << "label \"" << label << "\"\n"
3424 << "key \"" << key << "\"\n"
3425 << "literal " << lit << "\n";
3431 // catch the case of \def\inputGnumericTable
3433 if (t.cs() == "def") {
3434 Token second = p.next_token();
3435 if (second.cs() == "inputGnumericTable") {
3439 Token third = p.get_token();
3441 if (third.cs() == "input") {
3445 string name = normalize_filename(p.verbatim_item());
3446 string const path = getMasterFilePath(true);
3447 // We want to preserve relative / absolute filenames,
3448 // therefore path is only used for testing
3449 // The file extension is in every case ".tex".
3450 // So we need to remove this extension and check for
3451 // the original one.
3452 name = removeExtension(name);
3453 if (!makeAbsPath(name, path).exists()) {
3454 char const * const Gnumeric_formats[] = {"gnumeric",
3456 string const Gnumeric_name =
3457 find_file(name, path, Gnumeric_formats);
3458 if (!Gnumeric_name.empty())
3459 name = Gnumeric_name;
3461 FileName const absname = makeAbsPath(name, path);
3462 if (absname.exists()) {
3463 fix_child_filename(name);
3464 copy_file(absname, name);
3466 cerr << "Warning: Could not find file '"
3467 << name << "'." << endl;
3468 context.check_layout(os);
3469 begin_inset(os, "External\n\ttemplate ");
3470 os << "GnumericSpreadsheet\n\tfilename "
3473 context.check_layout(os);
3475 // register the packages that are automatically loaded
3476 // by the Gnumeric template
3477 registerExternalTemplatePackages("GnumericSpreadsheet");
3482 parse_macro(p, os, context);
3486 if (t.cs() == "noindent") {
3488 context.add_par_extra_stuff("\\noindent\n");
3492 if (t.cs() == "appendix") {
3493 context.add_par_extra_stuff("\\start_of_appendix\n");
3494 // We need to start a new paragraph. Otherwise the
3495 // appendix in 'bla\appendix\chapter{' would start
3497 context.new_paragraph(os);
3498 // We need to make sure that the paragraph is
3499 // generated even if it is empty. Otherwise the
3500 // appendix in '\par\appendix\par\chapter{' would
3502 context.check_layout(os);
3503 // FIXME: This is a hack to prevent paragraph
3504 // deletion if it is empty. Handle this better!
3505 output_comment(p, os,
3506 "dummy comment inserted by tex2lyx to "
3507 "ensure that this paragraph is not empty",
3509 // Both measures above may generate an additional
3510 // empty paragraph, but that does not hurt, because
3511 // whitespace does not matter here.
3512 eat_whitespace(p, os, context, true);
3516 // Must catch empty dates before findLayout is called below
3517 if (t.cs() == "date") {
3518 eat_whitespace(p, os, context, false);
3520 string const date = p.verbatim_item();
3523 preamble.suppressDate(true);
3526 preamble.suppressDate(false);
3527 if (context.new_layout_allowed &&
3528 (newlayout = findLayout(context.textclass,
3531 output_command_layout(os, p, outer,
3532 context, newlayout);
3533 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3534 if (!preamble.titleLayoutFound())
3535 preamble.titleLayoutFound(newlayout->intitle);
3536 set<string> const & req = newlayout->requires();
3537 set<string>::const_iterator it = req.begin();
3538 set<string>::const_iterator en = req.end();
3539 for (; it != en; ++it)
3540 preamble.registerAutomaticallyLoadedPackage(*it);
3542 output_ert_inset(os,
3543 "\\date{" + p.verbatim_item() + '}',
3549 // Before we look for the layout name with star and alone below, we check the layouts including
3550 // the LateXParam, which might be one or several options or a star.
3551 // The single '=' is meant here.
3552 if (context.new_layout_allowed &&
3553 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3554 // store the latexparam here. This is eaten in output_command_layout
3555 context.latexparam = newlayout->latexparam();
3557 output_command_layout(os, p, outer, context, newlayout);
3558 context.latexparam.clear();
3560 if (!preamble.titleLayoutFound())
3561 preamble.titleLayoutFound(newlayout->intitle);
3562 set<string> const & req = newlayout->requires();
3563 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3564 preamble.registerAutomaticallyLoadedPackage(*it);
3568 // Starred section headings
3569 // Must attempt to parse "Section*" before "Section".
3570 if ((p.next_token().asInput() == "*") &&
3571 context.new_layout_allowed &&
3572 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3575 output_command_layout(os, p, outer, context, newlayout);
3577 if (!preamble.titleLayoutFound())
3578 preamble.titleLayoutFound(newlayout->intitle);
3579 set<string> const & req = newlayout->requires();
3580 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3581 preamble.registerAutomaticallyLoadedPackage(*it);
3585 // Section headings and the like
3586 if (context.new_layout_allowed &&
3587 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3589 output_command_layout(os, p, outer, context, newlayout);
3591 if (!preamble.titleLayoutFound())
3592 preamble.titleLayoutFound(newlayout->intitle);
3593 set<string> const & req = newlayout->requires();
3594 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3595 preamble.registerAutomaticallyLoadedPackage(*it);
3599 if (t.cs() == "subfloat") {
3600 // the syntax is \subfloat[list entry][sub caption]{content}
3601 // if it is a table of figure depends on the surrounding float
3603 // do nothing if there is no outer float
3604 if (!float_type.empty()) {
3605 context.check_layout(os);
3607 begin_inset(os, "Float " + float_type + "\n");
3609 << "\nsideways false"
3610 << "\nstatus collapsed\n\n";
3613 bool has_caption = false;
3614 if (p.next_token().cat() != catEscape &&
3615 p.next_token().character() == '[') {
3616 p.get_token(); // eat '['
3617 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3620 // In case we have two optional args, the second is the caption.
3621 if (p.next_token().cat() != catEscape &&
3622 p.next_token().character() == '[') {
3623 p.get_token(); // eat '['
3624 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3627 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3628 // the caption comes always as the last
3630 // we must make sure that the caption gets a \begin_layout
3631 os << "\n\\begin_layout Plain Layout";
3633 begin_inset(os, "Caption Standard\n");
3634 Context newcontext(true, context.textclass,
3635 0, 0, context.font);
3636 newcontext.check_layout(os);
3637 os << caption << "\n";
3638 newcontext.check_end_layout(os);
3641 // close the layout we opened
3642 os << "\n\\end_layout";
3647 // if the float type is not supported or there is no surrounding float
3652 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3654 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3656 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3657 + "{" + p.verbatim_item() + '}', context);
3662 if (t.cs() == "xymatrix") {
3663 // we must open a new math because LyX's xy support is in math
3664 context.check_layout(os);
3665 begin_inset(os, "Formula ");
3667 os << "\\" << t.cs() << '{';
3668 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3671 preamble.registerAutomaticallyLoadedPackage("xy");
3675 if (t.cs() == "includegraphics") {
3676 bool const clip = p.next_token().asInput() == "*";
3679 string const arg = p.getArg('[', ']');
3680 map<string, string> opts;
3681 vector<string> keys;
3682 split_map(arg, opts, keys);
3684 opts["clip"] = string();
3685 string name = normalize_filename(p.verbatim_item());
3687 string const path = getMasterFilePath(true);
3688 // We want to preserve relative / absolute filenames,
3689 // therefore path is only used for testing
3690 if (!makeAbsPath(name, path).exists()) {
3691 // The file extension is probably missing.
3692 // Now try to find it out.
3693 string const dvips_name =
3694 find_file(name, path,
3695 known_dvips_graphics_formats);
3696 string const pdftex_name =
3697 find_file(name, path,
3698 known_pdftex_graphics_formats);
3699 if (!dvips_name.empty()) {
3700 if (!pdftex_name.empty()) {
3701 cerr << "This file contains the "
3703 "\"\\includegraphics{"
3705 "However, files\n\""
3706 << dvips_name << "\" and\n\""
3707 << pdftex_name << "\"\n"
3708 "both exist, so I had to make a "
3709 "choice and took the first one.\n"
3710 "Please move the unwanted one "
3711 "someplace else and try again\n"
3712 "if my choice was wrong."
3716 } else if (!pdftex_name.empty()) {
3722 FileName const absname = makeAbsPath(name, path);
3723 if (absname.exists()) {
3724 fix_child_filename(name);
3725 copy_file(absname, name);
3727 cerr << "Warning: Could not find graphics file '"
3728 << name << "'." << endl;
3730 context.check_layout(os);
3731 begin_inset(os, "Graphics ");
3732 os << "\n\tfilename " << name << '\n';
3733 if (opts.find("width") != opts.end())
3735 << translate_len(opts["width"]) << '\n';
3736 if (opts.find("height") != opts.end())
3738 << translate_len(opts["height"]) << '\n';
3739 if (opts.find("scale") != opts.end()) {
3740 istringstream iss(opts["scale"]);
3744 os << "\tscale " << val << '\n';
3746 if (opts.find("angle") != opts.end()) {
3747 os << "\trotateAngle "
3748 << opts["angle"] << '\n';
3749 vector<string>::const_iterator a =
3750 find(keys.begin(), keys.end(), "angle");
3751 vector<string>::const_iterator s =
3752 find(keys.begin(), keys.end(), "width");
3753 if (s == keys.end())
3754 s = find(keys.begin(), keys.end(), "height");
3755 if (s == keys.end())
3756 s = find(keys.begin(), keys.end(), "scale");
3757 if (s != keys.end() && distance(s, a) > 0)
3758 os << "\tscaleBeforeRotation\n";
3760 if (opts.find("origin") != opts.end()) {
3762 string const opt = opts["origin"];
3763 if (opt.find('l') != string::npos) ss << "left";
3764 if (opt.find('r') != string::npos) ss << "right";
3765 if (opt.find('c') != string::npos) ss << "center";
3766 if (opt.find('t') != string::npos) ss << "Top";
3767 if (opt.find('b') != string::npos) ss << "Bottom";
3768 if (opt.find('B') != string::npos) ss << "Baseline";
3769 if (!ss.str().empty())
3770 os << "\trotateOrigin " << ss.str() << '\n';
3772 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3774 if (opts.find("keepaspectratio") != opts.end())
3775 os << "\tkeepAspectRatio\n";
3776 if (opts.find("clip") != opts.end())
3778 if (opts.find("draft") != opts.end())
3780 if (opts.find("bb") != opts.end())
3781 os << "\tBoundingBox "
3782 << opts["bb"] << '\n';
3783 int numberOfbbOptions = 0;
3784 if (opts.find("bbllx") != opts.end())
3785 numberOfbbOptions++;
3786 if (opts.find("bblly") != opts.end())
3787 numberOfbbOptions++;
3788 if (opts.find("bburx") != opts.end())
3789 numberOfbbOptions++;
3790 if (opts.find("bbury") != opts.end())
3791 numberOfbbOptions++;
3792 if (numberOfbbOptions == 4)
3793 os << "\tBoundingBox "
3794 << opts["bbllx"] << " " << opts["bblly"] << " "
3795 << opts["bburx"] << " " << opts["bbury"] << '\n';
3796 else if (numberOfbbOptions > 0)
3797 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3798 numberOfbbOptions = 0;
3799 if (opts.find("natwidth") != opts.end())
3800 numberOfbbOptions++;
3801 if (opts.find("natheight") != opts.end())
3802 numberOfbbOptions++;
3803 if (numberOfbbOptions == 2)
3804 os << "\tBoundingBox 0bp 0bp "
3805 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3806 else if (numberOfbbOptions > 0)
3807 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3808 ostringstream special;
3809 if (opts.find("hiresbb") != opts.end())
3810 special << "hiresbb,";
3811 if (opts.find("trim") != opts.end())
3813 if (opts.find("viewport") != opts.end())
3814 special << "viewport=" << opts["viewport"] << ',';
3815 if (opts.find("totalheight") != opts.end())
3816 special << "totalheight=" << opts["totalheight"] << ',';
3817 if (opts.find("type") != opts.end())
3818 special << "type=" << opts["type"] << ',';
3819 if (opts.find("ext") != opts.end())
3820 special << "ext=" << opts["ext"] << ',';
3821 if (opts.find("read") != opts.end())
3822 special << "read=" << opts["read"] << ',';
3823 if (opts.find("command") != opts.end())
3824 special << "command=" << opts["command"] << ',';
3825 string s_special = special.str();
3826 if (!s_special.empty()) {
3827 // We had special arguments. Remove the trailing ','.
3828 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3830 // TODO: Handle the unknown settings better.
3831 // Warn about invalid options.
3832 // Check whether some option was given twice.
3834 preamble.registerAutomaticallyLoadedPackage("graphicx");
3838 if (t.cs() == "footnote" ||
3839 (t.cs() == "thanks" && context.layout->intitle)) {
3841 context.check_layout(os);
3842 begin_inset(os, "Foot\n");
3843 os << "status collapsed\n\n";
3844 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3849 if (t.cs() == "marginpar") {
3851 context.check_layout(os);
3852 begin_inset(os, "Marginal\n");
3853 os << "status collapsed\n\n";
3854 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3859 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3860 bool const use_minted = t.cs() == "mintinline";
3862 parse_listings(p, os, context, true, use_minted);
3866 if (t.cs() == "ensuremath") {
3868 context.check_layout(os);
3869 string const s = p.verbatim_item();
3870 //FIXME: this never triggers in UTF8
3871 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3874 output_ert_inset(os, "\\ensuremath{" + s + "}",
3879 else if (t.cs() == "makeindex"
3880 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3881 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3882 if (preamble.titleLayoutFound()) {
3884 skip_spaces_braces(p);
3886 output_ert_inset(os, t.asInput(), context);
3890 if (t.cs() == "tableofcontents"
3891 || t.cs() == "lstlistoflistings"
3892 || t.cs() == "listoflistings") {
3893 string name = t.cs();
3894 if (preamble.minted() && name == "listoflistings")
3895 name.insert(0, "lst");
3896 context.check_layout(os);
3897 begin_command_inset(os, "toc", name);
3899 skip_spaces_braces(p);
3900 if (name == "lstlistoflistings") {
3901 if (preamble.minted())
3902 preamble.registerAutomaticallyLoadedPackage("minted");
3904 preamble.registerAutomaticallyLoadedPackage("listings");
3909 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3910 context.check_layout(os);
3911 if (t.cs() == "listoffigures")
3912 begin_inset(os, "FloatList figure\n");
3914 begin_inset(os, "FloatList table\n");
3916 skip_spaces_braces(p);
3920 if (t.cs() == "listof") {
3921 p.skip_spaces(true);
3922 string const name = p.verbatim_item();
3923 if (context.textclass.floats().typeExist(name)) {
3924 context.check_layout(os);
3925 begin_inset(os, "FloatList ");
3928 p.verbatim_item(); // swallow second arg
3930 output_ert_inset(os, "\\listof{" + name + "}", context);
3934 if ((where = is_known(t.cs(), known_text_font_families))) {
3935 parse_text_attributes(p, os, FLAG_ITEM, outer,
3936 context, "\\family", context.font.family,
3937 known_coded_font_families[where - known_text_font_families]);
3941 // beamer has a \textbf<overlay>{} inset
3942 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3943 parse_text_attributes(p, os, FLAG_ITEM, outer,
3944 context, "\\series", context.font.series,
3945 known_coded_font_series[where - known_text_font_series]);
3949 // beamer has a \textit<overlay>{} inset
3950 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3951 parse_text_attributes(p, os, FLAG_ITEM, outer,
3952 context, "\\shape", context.font.shape,
3953 known_coded_font_shapes[where - known_text_font_shapes]);
3957 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3958 context.check_layout(os);
3959 TeXFont oldFont = context.font;
3960 context.font.init();
3961 context.font.size = oldFont.size;
3962 os << "\n\\family " << context.font.family << "\n";
3963 os << "\n\\series " << context.font.series << "\n";
3964 os << "\n\\shape " << context.font.shape << "\n";
3965 if (t.cs() == "textnormal") {
3966 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3967 output_font_change(os, context.font, oldFont);
3968 context.font = oldFont;
3970 eat_whitespace(p, os, context, false);
3974 if (t.cs() == "textcolor") {
3975 // scheme is \textcolor{color name}{text}
3976 string const color = p.verbatim_item();
3977 // we support the predefined colors of the color and the xcolor package
3978 if (color == "black" || color == "blue" || color == "cyan"
3979 || color == "green" || color == "magenta" || color == "red"
3980 || color == "white" || color == "yellow") {
3981 context.check_layout(os);
3982 os << "\n\\color " << color << "\n";
3983 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3984 context.check_layout(os);
3985 os << "\n\\color inherit\n";
3986 preamble.registerAutomaticallyLoadedPackage("color");
3987 } else if (color == "brown" || color == "darkgray" || color == "gray"
3988 || color == "lightgray" || color == "lime" || color == "olive"
3989 || color == "orange" || color == "pink" || color == "purple"
3990 || color == "teal" || color == "violet") {
3991 context.check_layout(os);
3992 os << "\n\\color " << color << "\n";
3993 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3994 context.check_layout(os);
3995 os << "\n\\color inherit\n";
3996 preamble.registerAutomaticallyLoadedPackage("xcolor");
3998 // for custom defined colors
3999 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4003 if (t.cs() == "underbar" || t.cs() == "uline") {
4004 // \underbar is not 100% correct (LyX outputs \uline
4005 // of ulem.sty). The difference is that \ulem allows
4006 // line breaks, and \underbar does not.
4007 // Do NOT handle \underline.
4008 // \underbar cuts through y, g, q, p etc.,
4009 // \underline does not.
4010 context.check_layout(os);
4011 os << "\n\\bar under\n";
4012 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4013 context.check_layout(os);
4014 os << "\n\\bar default\n";
4015 preamble.registerAutomaticallyLoadedPackage("ulem");
4019 if (t.cs() == "sout") {
4020 context.check_layout(os);
4021 os << "\n\\strikeout on\n";
4022 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4023 context.check_layout(os);
4024 os << "\n\\strikeout default\n";
4025 preamble.registerAutomaticallyLoadedPackage("ulem");
4029 // beamer has an \emph<overlay>{} inset
4030 if ((t.cs() == "uuline" || t.cs() == "uwave"
4031 || t.cs() == "emph" || t.cs() == "noun"
4032 || t.cs() == "xout") && !p.hasOpt("<")) {
4033 context.check_layout(os);
4034 os << "\n\\" << t.cs() << " on\n";
4035 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4036 context.check_layout(os);
4037 os << "\n\\" << t.cs() << " default\n";
4038 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4039 preamble.registerAutomaticallyLoadedPackage("ulem");
4043 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
4044 context.check_layout(os);
4045 string name = p.getArg('{', '}');
4046 string localtime = p.getArg('{', '}');
4047 preamble.registerAuthor(name);
4048 Author const & author = preamble.getAuthor(name);
4049 // from_asctime_utc() will fail if LyX decides to output the
4050 // time in the text language.
4051 time_t ptime = from_asctime_utc(localtime);
4052 if (ptime == static_cast<time_t>(-1)) {
4053 cerr << "Warning: Could not parse time `" << localtime
4054 << "´ for change tracking, using current time instead.\n";
4055 ptime = current_time();
4057 if (t.cs() == "lyxadded")
4058 os << "\n\\change_inserted ";
4060 os << "\n\\change_deleted ";
4061 os << author.bufferId() << ' ' << ptime << '\n';
4062 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4063 bool dvipost = LaTeXPackages::isAvailable("dvipost");
4064 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4065 LaTeXPackages::isAvailable("xcolor");
4066 // No need to test for luatex, since luatex comes in
4067 // two flavours (dvi and pdf), like latex, and those
4068 // are detected by pdflatex.
4069 if (pdflatex || xetex) {
4071 preamble.registerAutomaticallyLoadedPackage("ulem");
4072 preamble.registerAutomaticallyLoadedPackage("xcolor");
4073 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4077 preamble.registerAutomaticallyLoadedPackage("dvipost");
4078 } else if (xcolorulem) {
4079 preamble.registerAutomaticallyLoadedPackage("ulem");
4080 preamble.registerAutomaticallyLoadedPackage("xcolor");
4086 if (t.cs() == "textipa") {
4087 context.check_layout(os);
4088 begin_inset(os, "IPA\n");
4089 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4090 context.merging_hyphens_allowed = false;
4091 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4092 context.merging_hyphens_allowed = merging_hyphens_allowed;
4094 preamble.registerAutomaticallyLoadedPackage("tipa");
4095 preamble.registerAutomaticallyLoadedPackage("tipx");
4099 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4100 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4101 context.check_layout(os);
4105 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4106 begin_inset(os, "IPADeco " + type + "\n");
4107 os << "status open\n";
4108 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4114 if (t.cs() == "textvertline") {
4115 // FIXME: This is not correct, \textvertline is higher than |
4121 if (t.cs() == "tone" ) {
4122 context.check_layout(os);
4123 // register the tone package
4124 preamble.registerAutomaticallyLoadedPackage("tone");
4125 string content = trimSpaceAndEol(p.verbatim_item());
4126 string command = t.asInput() + "{" + content + "}";
4127 // some tones can be detected by unicodesymbols, some need special code
4128 if (is_known(content, known_tones)) {
4129 os << "\\IPAChar " << command << "\n";
4132 // try to see whether the string is in unicodesymbols
4136 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4137 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4138 termination, rem, &req);
4142 output_ert_inset(os, to_utf8(rem), context);
4143 for (set<string>::const_iterator it = req.begin();
4144 it != req.end(); ++it)
4145 preamble.registerAutomaticallyLoadedPackage(*it);
4147 // we did not find a non-ert version
4148 output_ert_inset(os, command, context);
4152 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4153 t.cs() == "vphantom") {
4154 context.check_layout(os);
4155 if (t.cs() == "phantom")
4156 begin_inset(os, "Phantom Phantom\n");
4157 if (t.cs() == "hphantom")
4158 begin_inset(os, "Phantom HPhantom\n");
4159 if (t.cs() == "vphantom")
4160 begin_inset(os, "Phantom VPhantom\n");
4161 os << "status open\n";
4162 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4168 if (t.cs() == "href") {
4169 context.check_layout(os);
4170 string target = convert_literate_command_inset_arg(p.verbatim_item());
4171 string name = p.verbatim_item();
4172 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4173 bool const literal = !nm.first;
4174 name = literal ? subst(name, "\n", " ") : nm.second;
4175 string lit = literal ? "\"true\"" : "\"false\"";
4177 size_t i = target.find(':');
4178 if (i != string::npos) {
4179 type = target.substr(0, i + 1);
4180 if (type == "mailto:" || type == "file:")
4181 target = target.substr(i + 1);
4182 // handle the case that name is equal to target, except of "http(s)://"
4183 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4186 begin_command_inset(os, "href", "href");
4188 os << "name \"" << name << "\"\n";
4189 os << "target \"" << target << "\"\n";
4190 if (type == "mailto:" || type == "file:")
4191 os << "type \"" << type << "\"\n";
4192 os << "literal " << lit << "\n";
4194 skip_spaces_braces(p);
4198 if (t.cs() == "lyxline") {
4199 // swallow size argument (it is not used anyway)
4201 if (!context.atParagraphStart()) {
4202 // so our line is in the middle of a paragraph
4203 // we need to add a new line, lest this line
4204 // follow the other content on that line and
4205 // run off the side of the page
4206 // FIXME: This may create an empty paragraph,
4207 // but without that it would not be
4208 // possible to set noindent below.
4209 // Fortunately LaTeX does not care
4210 // about the empty paragraph.
4211 context.new_paragraph(os);
4213 if (preamble.indentParagraphs()) {
4214 // we need to unindent, lest the line be too long
4215 context.add_par_extra_stuff("\\noindent\n");
4217 context.check_layout(os);
4218 begin_command_inset(os, "line", "rule");
4219 os << "offset \"0.5ex\"\n"
4220 "width \"100line%\"\n"
4226 if (t.cs() == "rule") {
4227 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4228 string const width = p.getArg('{', '}');
4229 string const thickness = p.getArg('{', '}');
4230 context.check_layout(os);
4231 begin_command_inset(os, "line", "rule");
4232 if (!offset.empty())
4233 os << "offset \"" << translate_len(offset) << "\"\n";
4234 os << "width \"" << translate_len(width) << "\"\n"
4235 "height \"" << translate_len(thickness) << "\"\n";
4240 // Handle refstyle first in order to to catch \eqref, because this
4241 // can also occur without refstyle. Only recognize these commands if
4242 // refstyle.sty was found in the preamble (otherwise \eqref
4243 // and user defined ref commands could be misdetected).
4244 // We uncapitalize the input in order to catch capitalized commands
4246 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4247 && preamble.refstyle()) {
4248 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4249 string plural = "false";
4250 // Catch the plural option [s]
4252 string const opt = p.getOpt();
4256 // LyX does not yet support other optional arguments of ref commands
4257 output_ert_inset(os, t.asInput() + opt + "{" +
4258 p.verbatim_item() + '}', context);
4262 context.check_layout(os);
4263 begin_command_inset(os, "ref", "formatted");
4264 os << "reference \"";
4265 os << known_refstyle_prefixes[where - known_refstyle_commands]
4267 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4269 os << "plural \"" << plural << "\"\n";
4270 os << "caps \"" << cap << "\"\n";
4271 os << "noprefix \"false\"\n";
4273 preamble.registerAutomaticallyLoadedPackage("refstyle");
4277 // if refstyle is used, we must not convert \prettyref to a
4278 // formatted reference, since that would result in a refstyle command.
4279 if ((where = is_known(t.cs(), known_ref_commands)) &&
4280 (t.cs() != "prettyref" || !preamble.refstyle())) {
4281 string const opt = p.getOpt();
4283 context.check_layout(os);
4284 begin_command_inset(os, "ref",
4285 known_coded_ref_commands[where - known_ref_commands]);
4286 os << "reference \""
4287 << convert_literate_command_inset_arg(p.verbatim_item())
4289 os << "plural \"false\"\n";
4290 os << "caps \"false\"\n";
4291 os << "noprefix \"false\"\n";
4293 if (t.cs() == "vref" || t.cs() == "vpageref")
4294 preamble.registerAutomaticallyLoadedPackage("varioref");
4295 else if (t.cs() == "prettyref")
4296 preamble.registerAutomaticallyLoadedPackage("prettyref");
4298 // LyX does not yet support optional arguments of ref commands
4299 output_ert_inset(os, t.asInput() + opt + "{" +
4300 p.verbatim_item() + '}', context);
4306 is_known(t.cs(), known_natbib_commands) &&
4307 ((t.cs() != "citefullauthor" &&
4308 t.cs() != "citeyear" &&
4309 t.cs() != "citeyearpar") ||
4310 p.next_token().asInput() != "*")) {
4311 context.check_layout(os);
4312 string command = t.cs();
4313 if (p.next_token().asInput() == "*") {
4317 if (command == "citefullauthor")
4318 // alternative name for "\\citeauthor*"
4319 command = "citeauthor*";
4321 // text before the citation
4323 // text after the citation
4325 get_cite_arguments(p, true, before, after);
4327 if (command == "cite") {
4328 // \cite without optional argument means
4329 // \citet, \cite with at least one optional
4330 // argument means \citep.
4331 if (before.empty() && after.empty())
4336 if (before.empty() && after == "[]")
4337 // avoid \citet[]{a}
4339 else if (before == "[]" && after == "[]") {
4340 // avoid \citet[][]{a}
4344 bool literal = false;
4345 pair<bool, string> aft;
4346 pair<bool, string> bef;
4347 // remove the brackets around after and before
4348 if (!after.empty()) {
4350 after.erase(after.length() - 1, 1);
4351 aft = convert_latexed_command_inset_arg(after);
4352 literal = !aft.first;
4353 after = literal ? subst(after, "\n", " ") : aft.second;
4355 if (!before.empty()) {
4357 before.erase(before.length() - 1, 1);
4358 bef = convert_latexed_command_inset_arg(before);
4359 literal |= !bef.first;
4360 before = literal ? subst(before, "\n", " ") : bef.second;
4361 if (literal && !after.empty())
4362 after = subst(after, "\n", " ");
4364 string lit = literal ? "\"true\"" : "\"false\"";
4365 begin_command_inset(os, "citation", command);
4366 os << "after " << '"' << after << '"' << "\n";
4367 os << "before " << '"' << before << '"' << "\n";
4369 << convert_literate_command_inset_arg(p.verbatim_item())
4371 << "literal " << lit << "\n";
4373 // Need to set the cite engine if natbib is loaded by
4374 // the document class directly
4375 if (preamble.citeEngine() == "basic")
4376 preamble.citeEngine("natbib");
4381 && is_known(t.cs(), known_biblatex_commands)
4382 && ((t.cs() == "cite"
4383 || t.cs() == "citeauthor"
4384 || t.cs() == "Citeauthor"
4385 || t.cs() == "parencite"
4386 || t.cs() == "citetitle")
4387 || p.next_token().asInput() != "*"))
4388 || (use_biblatex_natbib
4389 && (is_known(t.cs(), known_biblatex_commands)
4390 || is_known(t.cs(), known_natbib_commands))
4391 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4392 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4393 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4394 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4395 || t.cs() == "parencite" || t.cs() == "citetitle")
4396 || p.next_token().asInput() != "*"))){
4397 context.check_layout(os);
4398 string command = t.cs();
4399 if (p.next_token().asInput() == "*") {
4404 bool const qualified = suffixIs(command, "s");
4406 command = rtrim(command, "s");
4408 // text before the citation
4410 // text after the citation
4412 get_cite_arguments(p, true, before, after, qualified);
4414 // These use natbib cmd names in LyX
4415 // for inter-citeengine compativility
4416 if (command == "citeyear")
4417 command = "citebyear";
4418 else if (command == "cite*")
4419 command = "citeyear";
4420 else if (command == "textcite")
4422 else if (command == "Textcite")
4424 else if (command == "parencite")
4426 else if (command == "Parencite")
4428 else if (command == "parencite*")
4429 command = "citeyearpar";
4430 else if (command == "smartcite")
4431 command = "footcite";
4432 else if (command == "Smartcite")
4433 command = "Footcite";
4435 string const emptyarg = qualified ? "()" : "[]";
4436 if (before.empty() && after == emptyarg)
4439 else if (before == emptyarg && after == emptyarg) {
4440 // avoid \cite[][]{a}
4444 bool literal = false;
4445 pair<bool, string> aft;
4446 pair<bool, string> bef;
4447 // remove the brackets around after and before
4448 if (!after.empty()) {
4450 after.erase(after.length() - 1, 1);
4451 aft = convert_latexed_command_inset_arg(after);
4452 literal = !aft.first;
4453 after = literal ? subst(after, "\n", " ") : aft.second;
4455 if (!before.empty()) {
4457 before.erase(before.length() - 1, 1);
4458 bef = convert_latexed_command_inset_arg(before);
4459 literal |= !bef.first;
4460 before = literal ? subst(before, "\n", " ") : bef.second;
4462 string keys, pretextlist, posttextlist;
4464 map<string, string> pres, posts, preslit, postslit;
4465 vector<string> lkeys;
4466 // text before the citation
4467 string lbefore, lbeforelit;
4468 // text after the citation
4469 string lafter, lafterlit;
4471 pair<bool, string> laft, lbef;
4473 get_cite_arguments(p, true, lbefore, lafter);
4474 // remove the brackets around after and before
4475 if (!lafter.empty()) {
4477 lafter.erase(lafter.length() - 1, 1);
4478 laft = convert_latexed_command_inset_arg(lafter);
4479 literal |= !laft.first;
4480 lafter = laft.second;
4481 lafterlit = subst(lbefore, "\n", " ");
4483 if (!lbefore.empty()) {
4484 lbefore.erase(0, 1);
4485 lbefore.erase(lbefore.length() - 1, 1);
4486 lbef = convert_latexed_command_inset_arg(lbefore);
4487 literal |= !lbef.first;
4488 lbefore = lbef.second;
4489 lbeforelit = subst(lbefore, "\n", " ");
4491 if (lbefore.empty() && lafter == "[]") {
4496 else if (lbefore == "[]" && lafter == "[]") {
4497 // avoid \cite[][]{a}
4503 lkey = p.getArg('{', '}');
4506 if (!lbefore.empty()) {
4507 pres.insert(make_pair(lkey, lbefore));
4508 preslit.insert(make_pair(lkey, lbeforelit));
4510 if (!lafter.empty()) {
4511 posts.insert(make_pair(lkey, lafter));
4512 postslit.insert(make_pair(lkey, lafterlit));
4514 lkeys.push_back(lkey);
4516 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4521 for (auto const & ptl : pres) {
4522 if (!pretextlist.empty())
4523 pretextlist += '\t';
4524 pretextlist += ptl.first + " " + ptl.second;
4526 for (auto const & potl : posts) {
4527 if (!posttextlist.empty())
4528 posttextlist += '\t';
4529 posttextlist += potl.first + " " + potl.second;
4532 keys = convert_literate_command_inset_arg(p.verbatim_item());
4535 after = subst(after, "\n", " ");
4536 if (!before.empty())
4537 before = subst(after, "\n", " ");
4539 string lit = literal ? "\"true\"" : "\"false\"";
4540 begin_command_inset(os, "citation", command);
4541 os << "after " << '"' << after << '"' << "\n";
4542 os << "before " << '"' << before << '"' << "\n";
4546 if (!pretextlist.empty())
4547 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4548 if (!posttextlist.empty())
4549 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4550 os << "literal " << lit << "\n";
4552 // Need to set the cite engine if biblatex is loaded by
4553 // the document class directly
4554 if (preamble.citeEngine() == "basic")
4555 use_biblatex_natbib ?
4556 preamble.citeEngine("biblatex-natbib")
4557 : preamble.citeEngine("biblatex");
4562 is_known(t.cs(), known_jurabib_commands) &&
4563 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4564 context.check_layout(os);
4565 string command = t.cs();
4566 if (p.next_token().asInput() == "*") {
4570 char argumentOrder = '\0';
4571 vector<string> const options =
4572 preamble.getPackageOptions("jurabib");
4573 if (find(options.begin(), options.end(),
4574 "natbiborder") != options.end())
4575 argumentOrder = 'n';
4576 else if (find(options.begin(), options.end(),
4577 "jurabiborder") != options.end())
4578 argumentOrder = 'j';
4580 // text before the citation
4582 // text after the citation
4584 get_cite_arguments(p, argumentOrder != 'j', before, after);
4586 string const citation = p.verbatim_item();
4587 if (!before.empty() && argumentOrder == '\0') {
4588 cerr << "Warning: Assuming argument order "
4589 "of jurabib version 0.6 for\n'"
4590 << command << before << after << '{'
4591 << citation << "}'.\n"
4592 "Add 'jurabiborder' to the jurabib "
4593 "package options if you used an\n"
4594 "earlier jurabib version." << endl;
4596 bool literal = false;
4597 pair<bool, string> aft;
4598 pair<bool, string> bef;
4599 // remove the brackets around after and before
4600 if (!after.empty()) {
4602 after.erase(after.length() - 1, 1);
4603 aft = convert_latexed_command_inset_arg(after);
4604 literal = !aft.first;
4605 after = literal ? subst(after, "\n", " ") : aft.second;
4607 if (!before.empty()) {
4609 before.erase(before.length() - 1, 1);
4610 bef = convert_latexed_command_inset_arg(before);
4611 literal |= !bef.first;
4612 before = literal ? subst(before, "\n", " ") : bef.second;
4613 if (literal && !after.empty())
4614 after = subst(after, "\n", " ");
4616 string lit = literal ? "\"true\"" : "\"false\"";
4617 begin_command_inset(os, "citation", command);
4618 os << "after " << '"' << after << "\"\n"
4619 << "before " << '"' << before << "\"\n"
4620 << "key " << '"' << citation << "\"\n"
4621 << "literal " << lit << "\n";
4623 // Need to set the cite engine if jurabib is loaded by
4624 // the document class directly
4625 if (preamble.citeEngine() == "basic")
4626 preamble.citeEngine("jurabib");
4630 if (t.cs() == "cite"
4631 || t.cs() == "nocite") {
4632 context.check_layout(os);
4633 string after = p.getArg('[', ']');
4634 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4635 bool const literal = !aft.first;
4636 after = literal ? subst(after, "\n", " ") : aft.second;
4637 string lit = literal ? "\"true\"" : "\"false\"";
4638 string key = convert_literate_command_inset_arg(p.verbatim_item());
4639 // store the case that it is "\nocite{*}" to use it later for
4642 begin_command_inset(os, "citation", t.cs());
4643 os << "after " << '"' << after << "\"\n"
4644 << "key " << '"' << key << "\"\n"
4645 << "literal " << lit << "\n";
4647 } else if (t.cs() == "nocite")
4652 if (t.cs() == "index" ||
4653 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4654 context.check_layout(os);
4655 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4656 p.getArg('[', ']') : "";
4657 string const kind = arg.empty() ? "idx" : arg;
4658 begin_inset(os, "Index ");
4659 os << kind << "\nstatus collapsed\n";
4660 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4663 preamble.registerAutomaticallyLoadedPackage("splitidx");
4667 if (t.cs() == "nomenclature") {
4668 context.check_layout(os);
4669 begin_command_inset(os, "nomenclature", "nomenclature");
4670 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4671 if (!prefix.empty())
4672 os << "prefix " << '"' << prefix << '"' << "\n";
4673 string symbol = p.verbatim_item();
4674 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4675 bool literal = !sym.first;
4676 string description = p.verbatim_item();
4677 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4678 literal |= !desc.first;
4680 symbol = subst(symbol, "\n", " ");
4681 description = subst(description, "\n", " ");
4683 symbol = sym.second;
4684 description = desc.second;
4686 string lit = literal ? "\"true\"" : "\"false\"";
4687 os << "symbol " << '"' << symbol;
4688 os << "\"\ndescription \""
4689 << description << "\"\n"
4690 << "literal " << lit << "\n";
4692 preamble.registerAutomaticallyLoadedPackage("nomencl");
4696 if (t.cs() == "label") {
4697 context.check_layout(os);
4698 begin_command_inset(os, "label", "label");
4700 << convert_literate_command_inset_arg(p.verbatim_item())
4706 if (t.cs() == "lyxmintcaption") {
4707 string const pos = p.getArg('[', ']');
4709 string const caption =
4710 parse_text_snippet(p, FLAG_ITEM, false,
4712 minted_nonfloat_caption = "[t]" + caption;
4714 // We already got the caption at the bottom,
4715 // so simply skip it.
4716 parse_text_snippet(p, FLAG_ITEM, false, context);
4718 eat_whitespace(p, os, context, true);
4722 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4723 context.check_layout(os);
4724 string commandname = t.cs();
4726 if (p.next_token().asInput() == "*") {
4731 begin_command_inset(os, "index_print", commandname);
4732 string const indexname = p.getArg('[', ']');
4734 if (indexname.empty())
4735 os << "type \"idx\"\n";
4737 os << "type \"" << indexname << "\"\n";
4738 os << "literal \"true\"\n";
4741 skip_spaces_braces(p);
4742 preamble.registerAutomaticallyLoadedPackage("makeidx");
4743 if (preamble.use_indices() == "true")
4744 preamble.registerAutomaticallyLoadedPackage("splitidx");
4748 if (t.cs() == "printnomenclature") {
4750 string width_type = "";
4751 context.check_layout(os);
4752 begin_command_inset(os, "nomencl_print", "printnomenclature");
4753 // case of a custom width
4755 width = p.getArg('[', ']');
4756 width = translate_len(width);
4757 width_type = "custom";
4759 // case of no custom width
4760 // the case of no custom width but the width set
4761 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4762 // because the user could have set anything, not only the width
4763 // of the longest label (which would be width_type = "auto")
4764 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4765 if (label.empty() && width_type.empty())
4766 width_type = "none";
4767 os << "set_width \"" << width_type << "\"\n";
4768 if (width_type == "custom")
4769 os << "width \"" << width << '\"';
4771 skip_spaces_braces(p);
4772 preamble.registerAutomaticallyLoadedPackage("nomencl");
4776 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4777 context.check_layout(os);
4778 begin_inset(os, "script ");
4779 os << t.cs().substr(4) << '\n';
4780 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4781 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4783 if (t.cs() == "textsubscript")
4784 preamble.registerAutomaticallyLoadedPackage("subscript");
4788 if ((where = is_known(t.cs(), known_quotes))) {
4789 context.check_layout(os);
4790 begin_inset(os, "Quotes ");
4791 string quotetype = known_coded_quotes[where - known_quotes];
4792 // try to make a smart guess about the side
4793 Token const prev = p.prev_token();
4794 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4795 && prev.character() != '\n' && prev.character() != '~');
4796 quotetype = guessQuoteStyle(quotetype, opening);
4799 // LyX adds {} after the quote, so we have to eat
4800 // spaces here if there are any before a possible
4802 eat_whitespace(p, os, context, false);
4807 if ((where = is_known(t.cs(), known_sizes)) &&
4808 context.new_layout_allowed) {
4809 context.check_layout(os);
4810 TeXFont const oldFont = context.font;
4811 context.font.size = known_coded_sizes[where - known_sizes];
4812 output_font_change(os, oldFont, context.font);
4813 eat_whitespace(p, os, context, false);
4817 if ((where = is_known(t.cs(), known_font_families)) &&
4818 context.new_layout_allowed) {
4819 context.check_layout(os);
4820 TeXFont const oldFont = context.font;
4821 context.font.family =
4822 known_coded_font_families[where - known_font_families];
4823 output_font_change(os, oldFont, context.font);
4824 eat_whitespace(p, os, context, false);
4828 if ((where = is_known(t.cs(), known_font_series)) &&
4829 context.new_layout_allowed) {
4830 context.check_layout(os);
4831 TeXFont const oldFont = context.font;
4832 context.font.series =
4833 known_coded_font_series[where - known_font_series];
4834 output_font_change(os, oldFont, context.font);
4835 eat_whitespace(p, os, context, false);
4839 if ((where = is_known(t.cs(), known_font_shapes)) &&
4840 context.new_layout_allowed) {
4841 context.check_layout(os);
4842 TeXFont const oldFont = context.font;
4843 context.font.shape =
4844 known_coded_font_shapes[where - known_font_shapes];
4845 output_font_change(os, oldFont, context.font);
4846 eat_whitespace(p, os, context, false);
4849 if ((where = is_known(t.cs(), known_old_font_families)) &&
4850 context.new_layout_allowed) {
4851 context.check_layout(os);
4852 TeXFont const oldFont = context.font;
4853 context.font.init();
4854 context.font.size = oldFont.size;
4855 context.font.family =
4856 known_coded_font_families[where - known_old_font_families];
4857 output_font_change(os, oldFont, context.font);
4858 eat_whitespace(p, os, context, false);
4862 if ((where = is_known(t.cs(), known_old_font_series)) &&
4863 context.new_layout_allowed) {
4864 context.check_layout(os);
4865 TeXFont const oldFont = context.font;
4866 context.font.init();
4867 context.font.size = oldFont.size;
4868 context.font.series =
4869 known_coded_font_series[where - known_old_font_series];
4870 output_font_change(os, oldFont, context.font);
4871 eat_whitespace(p, os, context, false);
4875 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4876 context.new_layout_allowed) {
4877 context.check_layout(os);
4878 TeXFont const oldFont = context.font;
4879 context.font.init();
4880 context.font.size = oldFont.size;
4881 context.font.shape =
4882 known_coded_font_shapes[where - known_old_font_shapes];
4883 output_font_change(os, oldFont, context.font);
4884 eat_whitespace(p, os, context, false);
4888 if (t.cs() == "selectlanguage") {
4889 context.check_layout(os);
4890 // save the language for the case that a
4891 // \foreignlanguage is used
4892 context.font.language = babel2lyx(p.verbatim_item());
4893 os << "\n\\lang " << context.font.language << "\n";
4897 if (t.cs() == "foreignlanguage") {
4898 string const lang = babel2lyx(p.verbatim_item());
4899 parse_text_attributes(p, os, FLAG_ITEM, outer,
4901 context.font.language, lang);
4905 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4906 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4907 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4909 // We have to output the whole command if it has an option
4910 // because LyX doesn't support this yet, see bug #8214,
4911 // only if there is a single option specifying a variant, we can handle it.
4913 string langopts = p.getOpt();
4914 // check if the option contains a variant, if yes, extract it
4915 string::size_type pos_var = langopts.find("variant");
4916 string::size_type i = langopts.find(',');
4917 string::size_type k = langopts.find('=', pos_var);
4918 if (pos_var != string::npos && i == string::npos) {
4920 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4921 lang = preamble.polyglossia2lyx(variant);
4922 parse_text_attributes(p, os, FLAG_ITEM, outer,
4924 context.font.language, lang);
4926 output_ert_inset(os, t.asInput() + langopts, context);
4928 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4929 parse_text_attributes(p, os, FLAG_ITEM, outer,
4931 context.font.language, lang);
4936 if (t.cs() == "inputencoding") {
4937 // nothing to write here
4938 string const enc = subst(p.verbatim_item(), "\n", " ");
4939 p.setEncoding(enc, Encoding::inputenc);
4943 if (is_known(t.cs(), known_special_chars) ||
4944 (t.cs() == "protect" &&
4945 p.next_token().cat() == catEscape &&
4946 is_known(p.next_token().cs(), known_special_protect_chars))) {
4947 // LyX sometimes puts a \protect in front, so we have to ignore it
4949 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4950 known_special_chars);
4951 context.check_layout(os);
4952 os << known_coded_special_chars[where - known_special_chars];
4953 skip_spaces_braces(p);
4957 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4958 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4959 p.next_next_token().asInput() == "-") ||
4960 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4961 // LyX sometimes puts a \protect in front, so we have to ignore it
4962 if (t.cs() == "protect")
4964 context.check_layout(os);
4965 if (t.cs() == "nobreakdash")
4966 os << "\\SpecialChar nobreakdash\n";
4968 os << "\\SpecialChar endofsentence\n";
4973 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4974 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4975 || t.cs() == "%" || t.cs() == "-") {
4976 context.check_layout(os);
4978 os << "\\SpecialChar softhyphen\n";
4984 if (t.cs() == "char") {
4985 context.check_layout(os);
4986 if (p.next_token().character() == '`') {
4988 if (p.next_token().cs() == "\"") {
4993 output_ert_inset(os, "\\char`", context);
4996 output_ert_inset(os, "\\char", context);
5001 if (t.cs() == "verb") {
5002 context.check_layout(os);
5003 // set catcodes to verbatim early, just in case.
5004 p.setCatcodes(VERBATIM_CATCODES);
5005 string delim = p.get_token().asInput();
5006 Parser::Arg arg = p.verbatimStuff(delim);
5008 output_ert_inset(os, "\\verb" + delim
5009 + arg.second + delim, context);
5011 cerr << "invalid \\verb command. Skipping" << endl;
5015 // Problem: \= creates a tabstop inside the tabbing environment
5016 // and else an accent. In the latter case we really would want
5017 // \={o} instead of \= o.
5018 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5019 output_ert_inset(os, t.asInput(), context);
5023 if (t.cs() == "\\") {
5024 context.check_layout(os);
5026 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5027 else if (p.next_token().asInput() == "*") {
5029 // getOpt() eats the following space if there
5030 // is no optional argument, but that is OK
5031 // here since it has no effect in the output.
5032 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5035 begin_inset(os, "Newline newline");
5041 if (t.cs() == "newline" ||
5042 (t.cs() == "linebreak" && !p.hasOpt())) {
5043 context.check_layout(os);
5044 begin_inset(os, "Newline ");
5047 skip_spaces_braces(p);
5051 if (t.cs() == "input" || t.cs() == "include"
5052 || t.cs() == "verbatiminput"
5053 || t.cs() == "lstinputlisting"
5054 || t.cs() == "inputminted") {
5055 string name = t.cs();
5056 if (name == "verbatiminput"
5057 && p.next_token().asInput() == "*")
5058 name += p.get_token().asInput();
5059 context.check_layout(os);
5061 bool literal = false;
5062 if (name == "lstinputlisting" && p.hasOpt()) {
5063 lstparams = p.getArg('[', ']');
5064 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5065 literal = !oa.first;
5067 lstparams = subst(lstparams, "\n", " ");
5069 lstparams = oa.second;
5070 } else if (name == "inputminted") {
5071 name = "lstinputlisting";
5072 string const lang = p.getArg('{', '}');
5073 if (lang != "tex") {
5074 string cmd = "\\inputminted{" + lang + "}{";
5075 cmd += p.getArg('{', '}') + "}";
5076 output_ert_inset(os, cmd, context);
5079 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5080 minted_nonfloat_caption.erase(0,3);
5081 // extract label and caption from the already produced LyX code
5082 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5083 string const caption = nfc.front();
5085 vector<string>::iterator it =
5086 find(nfc.begin(), nfc.end(), "LatexCommand label");
5087 if (it != nfc.end()) {
5089 if (it != nfc.end())
5091 label = support::split(label, '"');
5094 minted_nonfloat_caption.clear();
5095 lstparams = "caption=" + caption;
5097 lstparams += ",label=" + label;
5098 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5099 literal = !oa.first;
5101 lstparams = subst(lstparams, "\n", " ");
5103 lstparams = oa.second;
5106 string lit = literal ? "\"true\"" : "\"false\"";
5107 string filename(normalize_filename(p.getArg('{', '}')));
5108 string const path = getMasterFilePath(true);
5109 // We want to preserve relative / absolute filenames,
5110 // therefore path is only used for testing
5111 if ((t.cs() == "include" || t.cs() == "input") &&
5112 !makeAbsPath(filename, path).exists()) {
5113 // The file extension is probably missing.
5114 // Now try to find it out.
5115 string const tex_name =
5116 find_file(filename, path,
5117 known_tex_extensions);
5118 if (!tex_name.empty())
5119 filename = tex_name;
5121 bool external = false;
5123 if (makeAbsPath(filename, path).exists()) {
5124 string const abstexname =
5125 makeAbsPath(filename, path).absFileName();
5126 string const absfigname =
5127 changeExtension(abstexname, ".fig");
5128 fix_child_filename(filename);
5129 string const lyxname = changeExtension(filename,
5130 roundtripMode() ? ".lyx.lyx" : ".lyx");
5131 string const abslyxname = makeAbsPath(
5132 lyxname, getParentFilePath(false)).absFileName();
5134 if (!skipChildren())
5135 external = FileName(absfigname).exists();
5136 if (t.cs() == "input" && !skipChildren()) {
5137 string const ext = getExtension(abstexname);
5139 // Combined PS/LaTeX:
5140 // x.eps, x.pstex_t (old xfig)
5141 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5142 FileName const absepsname(
5143 changeExtension(abstexname, ".eps"));
5144 FileName const abspstexname(
5145 changeExtension(abstexname, ".pstex"));
5146 bool const xfigeps =
5147 (absepsname.exists() ||
5148 abspstexname.exists()) &&
5151 // Combined PDF/LaTeX:
5152 // x.pdf, x.pdftex_t (old xfig)
5153 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5154 FileName const abspdfname(
5155 changeExtension(abstexname, ".pdf"));
5156 bool const xfigpdf =
5157 abspdfname.exists() &&
5158 (ext == "pdftex_t" || ext == "pdf_t");
5162 // Combined PS/PDF/LaTeX:
5163 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5164 string const absbase2(
5165 removeExtension(abstexname) + "_pspdftex");
5166 FileName const abseps2name(
5167 addExtension(absbase2, ".eps"));
5168 FileName const abspdf2name(
5169 addExtension(absbase2, ".pdf"));
5170 bool const xfigboth =
5171 abspdf2name.exists() &&
5172 abseps2name.exists() && ext == "pspdftex";
5174 xfig = xfigpdf || xfigeps || xfigboth;
5175 external = external && xfig;
5178 outname = changeExtension(filename, ".fig");
5179 FileName abssrc(changeExtension(abstexname, ".fig"));
5180 copy_file(abssrc, outname);
5182 // Don't try to convert, the result
5183 // would be full of ERT.
5185 FileName abssrc(abstexname);
5186 copy_file(abssrc, outname);
5187 } else if (t.cs() != "verbatiminput" &&
5189 tex2lyx(abstexname, FileName(abslyxname),
5192 // no need to call copy_file
5193 // tex2lyx creates the file
5196 FileName abssrc(abstexname);
5197 copy_file(abssrc, outname);
5200 cerr << "Warning: Could not find included file '"
5201 << filename << "'." << endl;
5205 begin_inset(os, "External\n");
5206 os << "\ttemplate XFig\n"
5207 << "\tfilename " << outname << '\n';
5208 registerExternalTemplatePackages("XFig");
5210 begin_command_inset(os, "include", name);
5211 outname = subst(outname, "\"", "\\\"");
5212 os << "preview false\n"
5213 "filename \"" << outname << "\"\n";
5214 if (!lstparams.empty())
5215 os << "lstparams \"" << lstparams << "\"\n";
5216 os << "literal " << lit << "\n";
5217 if (t.cs() == "verbatiminput")
5218 preamble.registerAutomaticallyLoadedPackage("verbatim");
5224 if (t.cs() == "bibliographystyle") {
5225 // store new bibliographystyle
5226 bibliographystyle = p.verbatim_item();
5227 // If any other command than \bibliography, \addcontentsline
5228 // and \nocite{*} follows, we need to output the style
5229 // (because it might be used by that command).
5230 // Otherwise, it will automatically be output by LyX.
5233 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5234 if (t2.cat() == catBegin)
5236 if (t2.cat() != catEscape)
5238 if (t2.cs() == "nocite") {
5239 if (p.getArg('{', '}') == "*")
5241 } else if (t2.cs() == "bibliography")
5243 else if (t2.cs() == "phantomsection") {
5247 else if (t2.cs() == "addcontentsline") {
5248 // get the 3 arguments of \addcontentsline
5251 contentslineContent = p.getArg('{', '}');
5252 // if the last argument is not \refname we must output
5253 if (contentslineContent == "\\refname")
5260 output_ert_inset(os,
5261 "\\bibliographystyle{" + bibliographystyle + '}',
5267 if (t.cs() == "phantomsection") {
5268 // we only support this if it occurs between
5269 // \bibliographystyle and \bibliography
5270 if (bibliographystyle.empty())
5271 output_ert_inset(os, "\\phantomsection", context);
5275 if (t.cs() == "addcontentsline") {
5276 context.check_layout(os);
5277 // get the 3 arguments of \addcontentsline
5278 string const one = p.getArg('{', '}');
5279 string const two = p.getArg('{', '}');
5280 string const three = p.getArg('{', '}');
5281 // only if it is a \refname, we support if for the bibtex inset
5282 if (contentslineContent != "\\refname") {
5283 output_ert_inset(os,
5284 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5290 else if (t.cs() == "bibliography") {
5291 context.check_layout(os);
5293 begin_command_inset(os, "bibtex", "bibtex");
5294 if (!btprint.empty()) {
5295 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5296 // clear the string because the next BibTeX inset can be without the
5297 // \nocite{*} option
5300 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5301 // Do we have addcontentsline?
5302 if (contentslineContent == "\\refname") {
5303 BibOpts = "bibtotoc";
5304 // clear string because next BibTeX inset can be without addcontentsline
5305 contentslineContent.clear();
5307 // Do we have a bibliographystyle set?
5308 if (!bibliographystyle.empty()) {
5309 if (BibOpts.empty())
5310 BibOpts = normalize_filename(bibliographystyle);
5312 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5313 // clear it because each bibtex entry has its style
5314 // and we need an empty string to handle \phantomsection
5315 bibliographystyle.clear();
5317 os << "options " << '"' << BibOpts << '"' << "\n";
5318 if (p.getEncoding() != preamble.docencoding) {
5319 Encoding const * const enc = encodings.fromIconvName(
5320 p.getEncoding(), Encoding::inputenc, true);
5322 cerr << "Unknown bib encoding " << p.getEncoding()
5323 << ". Ignoring." << std::endl;
5325 os << "encoding " << '"' << enc->name() << '"' << "\n";
5331 if (t.cs() == "printbibliography") {
5332 context.check_layout(os);
5334 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5335 vector<string> opts = getVectorFromString(bbloptions);
5336 vector<string>::iterator it =
5337 find(opts.begin(), opts.end(), "heading=bibintoc");
5338 if (it != opts.end()) {
5340 BibOpts = "bibtotoc";
5342 bbloptions = getStringFromVector(opts);
5343 begin_command_inset(os, "bibtex", "bibtex");
5344 if (!btprint.empty()) {
5345 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5346 // clear the string because the next BibTeX inset can be without the
5347 // \nocite{*} option
5351 for (auto const & bf : preamble.biblatex_bibliographies) {
5352 if (!bibfiles.empty())
5354 bibfiles += normalize_filename(bf);
5356 if (!bibfiles.empty())
5357 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5358 // Do we have addcontentsline?
5359 if (contentslineContent == "\\refname") {
5360 BibOpts = "bibtotoc";
5361 // clear string because next BibTeX inset can be without addcontentsline
5362 contentslineContent.clear();
5364 os << "options " << '"' << BibOpts << '"' << "\n";
5365 if (!bbloptions.empty())
5366 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5367 if (!preamble.bibencoding.empty()) {
5368 Encoding const * const enc = encodings.fromLaTeXName(
5369 preamble.bibencoding, Encoding::inputenc, true);
5371 cerr << "Unknown bib encoding " << preamble.bibencoding
5372 << ". Ignoring." << std::endl;
5374 os << "encoding " << '"' << enc->name() << '"' << "\n";
5377 for (auto const & bf : preamble.biblatex_encodings) {
5378 if (!bibfileencs.empty())
5379 bibfileencs += "\t";
5382 if (!bibfileencs.empty())
5383 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5385 need_commentbib = false;
5389 if (t.cs() == "bibbysection") {
5390 context.check_layout(os);
5392 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5393 vector<string> opts = getVectorFromString(bbloptions);
5394 vector<string>::iterator it =
5395 find(opts.begin(), opts.end(), "heading=bibintoc");
5396 if (it != opts.end()) {
5398 BibOpts = "bibtotoc";
5400 bbloptions = getStringFromVector(opts);
5401 begin_command_inset(os, "bibtex", "bibtex");
5402 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5404 for (auto const & bf : preamble.biblatex_bibliographies) {
5405 if (!bibfiles.empty())
5407 bibfiles += normalize_filename(bf);
5409 if (!bibfiles.empty())
5410 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5411 os << "options " << '"' << BibOpts << '"' << "\n";
5412 if (!bbloptions.empty())
5413 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5415 need_commentbib = false;
5419 if (t.cs() == "parbox") {
5420 // Test whether this is an outer box of a shaded box
5422 // swallow arguments
5423 while (p.hasOpt()) {
5425 p.skip_spaces(true);
5428 p.skip_spaces(true);
5430 if (p.next_token().cat() == catBegin)
5432 p.skip_spaces(true);
5433 Token to = p.get_token();
5434 bool shaded = false;
5435 if (to.asInput() == "\\begin") {
5436 p.skip_spaces(true);
5437 if (p.getArg('{', '}') == "shaded")
5442 parse_outer_box(p, os, FLAG_ITEM, outer,
5443 context, "parbox", "shaded");
5445 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5446 "", "", t.cs(), "", "");
5450 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5451 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5452 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5453 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5457 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5458 string backgroundcolor;
5459 preamble.registerAutomaticallyLoadedPackage("xcolor");
5460 if (t.cs() == "fcolorbox") {
5461 string const framecolor = p.getArg('{', '}');
5462 backgroundcolor = p.getArg('{', '}');
5463 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5465 backgroundcolor = p.getArg('{', '}');
5466 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5471 // FIXME: due to the compiler limit of "if" nestings
5472 // the code for the alignment was put here
5473 // put them in their own if if this is fixed
5474 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5475 || t.cs() == "shadowsize"
5476 || t.cs() == "raggedleft" || t.cs() == "centering"
5477 || t.cs() == "raggedright") {
5478 if (t.cs() == "fboxrule")
5480 if (t.cs() == "fboxsep")
5482 if (t.cs() == "shadowsize")
5484 if (t.cs() != "raggedleft" && t.cs() != "centering"
5485 && t.cs() != "raggedright") {
5486 p.skip_spaces(true);
5487 while (p.good() && p.next_token().cat() != catSpace
5488 && p.next_token().cat() != catNewline
5489 && p.next_token().cat() != catEscape) {
5490 if (t.cs() == "fboxrule")
5491 fboxrule = fboxrule + p.get_token().asInput();
5492 if (t.cs() == "fboxsep")
5493 fboxsep = fboxsep + p.get_token().asInput();
5494 if (t.cs() == "shadowsize")
5495 shadow_size = shadow_size + p.get_token().asInput();
5498 output_ert_inset(os, t.asInput(), context);
5503 //\framebox() is part of the picture environment and different from \framebox{}
5504 //\framebox{} will be parsed by parse_outer_box
5505 if (t.cs() == "framebox") {
5506 if (p.next_token().character() == '(') {
5507 //the syntax is: \framebox(x,y)[position]{content}
5508 string arg = t.asInput();
5509 arg += p.getFullParentheseArg();
5510 arg += p.getFullOpt();
5511 eat_whitespace(p, os, context, false);
5512 output_ert_inset(os, arg + '{', context);
5513 parse_text(p, os, FLAG_ITEM, outer, context);
5514 output_ert_inset(os, "}", context);
5516 //the syntax is: \framebox[width][position]{content}
5517 string special = p.getFullOpt();
5518 special += p.getOpt();
5519 parse_outer_box(p, os, FLAG_ITEM, outer,
5520 context, t.cs(), special);
5525 //\makebox() is part of the picture environment and different from \makebox{}
5526 //\makebox{} will be parsed by parse_box
5527 if (t.cs() == "makebox") {
5528 if (p.next_token().character() == '(') {
5529 //the syntax is: \makebox(x,y)[position]{content}
5530 string arg = t.asInput();
5531 arg += p.getFullParentheseArg();
5532 arg += p.getFullOpt();
5533 eat_whitespace(p, os, context, false);
5534 output_ert_inset(os, arg + '{', context);
5535 parse_text(p, os, FLAG_ITEM, outer, context);
5536 output_ert_inset(os, "}", context);
5538 //the syntax is: \makebox[width][position]{content}
5539 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5540 "", "", t.cs(), "", "");
5544 if (t.cs() == "smallskip" ||
5545 t.cs() == "medskip" ||
5546 t.cs() == "bigskip" ||
5547 t.cs() == "vfill") {
5548 context.check_layout(os);
5549 begin_inset(os, "VSpace ");
5552 skip_spaces_braces(p);
5556 if ((where = is_known(t.cs(), known_spaces))) {
5557 context.check_layout(os);
5558 begin_inset(os, "space ");
5559 os << '\\' << known_coded_spaces[where - known_spaces]
5562 // LaTeX swallows whitespace after all spaces except
5563 // "\\,". We have to do that here, too, because LyX
5564 // adds "{}" which would make the spaces significant.
5566 eat_whitespace(p, os, context, false);
5567 // LyX adds "{}" after all spaces except "\\ " and
5568 // "\\,", so we have to remove "{}".
5569 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5570 // remove the braces after "\\,", too.
5576 if (t.cs() == "newpage" ||
5577 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5578 t.cs() == "clearpage" ||
5579 t.cs() == "cleardoublepage") {
5580 context.check_layout(os);
5581 begin_inset(os, "Newpage ");
5584 skip_spaces_braces(p);
5588 if (t.cs() == "DeclareRobustCommand" ||
5589 t.cs() == "DeclareRobustCommandx" ||
5590 t.cs() == "newcommand" ||
5591 t.cs() == "newcommandx" ||
5592 t.cs() == "providecommand" ||
5593 t.cs() == "providecommandx" ||
5594 t.cs() == "renewcommand" ||
5595 t.cs() == "renewcommandx") {
5596 // DeclareRobustCommand, DeclareRobustCommandx,
5597 // providecommand and providecommandx could be handled
5598 // by parse_command(), but we need to call
5599 // add_known_command() here.
5600 string name = t.asInput();
5601 if (p.next_token().asInput() == "*") {
5602 // Starred form. Eat '*'
5606 string const command = p.verbatim_item();
5607 string const opt1 = p.getFullOpt();
5608 string const opt2 = p.getFullOpt();
5609 add_known_command(command, opt1, !opt2.empty());
5610 string const ert = name + '{' + command + '}' +
5612 '{' + p.verbatim_item() + '}';
5614 if (t.cs() == "DeclareRobustCommand" ||
5615 t.cs() == "DeclareRobustCommandx" ||
5616 t.cs() == "providecommand" ||
5617 t.cs() == "providecommandx" ||
5618 name[name.length()-1] == '*')
5619 output_ert_inset(os, ert, context);
5621 context.check_layout(os);
5622 begin_inset(os, "FormulaMacro");
5629 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5630 // let could be handled by parse_command(),
5631 // but we need to call add_known_command() here.
5632 string ert = t.asInput();
5635 if (p.next_token().cat() == catBegin) {
5636 name = p.verbatim_item();
5637 ert += '{' + name + '}';
5639 name = p.verbatim_item();
5644 if (p.next_token().cat() == catBegin) {
5645 command = p.verbatim_item();
5646 ert += '{' + command + '}';
5648 command = p.verbatim_item();
5651 // If command is known, make name known too, to parse
5652 // its arguments correctly. For this reason we also
5653 // have commands in syntax.default that are hardcoded.
5654 CommandMap::iterator it = known_commands.find(command);
5655 if (it != known_commands.end())
5656 known_commands[t.asInput()] = it->second;
5657 output_ert_inset(os, ert, context);
5661 if (t.cs() == "hspace" || t.cs() == "vspace") {
5664 string name = t.asInput();
5665 string const length = p.verbatim_item();
5668 bool valid = splitLatexLength(length, valstring, unit);
5669 bool known_hspace = false;
5670 bool known_vspace = false;
5671 bool known_unit = false;
5674 istringstream iss(valstring);
5677 if (t.cs()[0] == 'h') {
5678 if (unit == "\\fill") {
5683 known_hspace = true;
5686 if (unit == "\\smallskipamount") {
5688 known_vspace = true;
5689 } else if (unit == "\\medskipamount") {
5691 known_vspace = true;
5692 } else if (unit == "\\bigskipamount") {
5694 known_vspace = true;
5695 } else if (unit == "\\fill") {
5697 known_vspace = true;
5701 if (!known_hspace && !known_vspace) {
5702 switch (unitFromString(unit)) {
5718 //unitFromString(unit) fails for relative units like Length::PCW
5719 // therefore handle them separately
5720 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5721 || unit == "\\textwidth" || unit == "\\linewidth"
5722 || unit == "\\textheight" || unit == "\\paperheight"
5723 || unit == "\\baselineskip")
5731 // check for glue lengths
5732 bool is_gluelength = false;
5733 string gluelength = length;
5734 string::size_type i = length.find(" minus");
5735 if (i == string::npos) {
5736 i = length.find(" plus");
5737 if (i != string::npos)
5738 is_gluelength = true;
5740 is_gluelength = true;
5741 // if yes transform "9xx minus 8yy plus 7zz"
5743 if (is_gluelength) {
5744 i = gluelength.find(" minus");
5745 if (i != string::npos)
5746 gluelength.replace(i, 7, "-");
5747 i = gluelength.find(" plus");
5748 if (i != string::npos)
5749 gluelength.replace(i, 6, "+");
5752 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5753 // Literal horizontal length or known variable
5754 context.check_layout(os);
5755 begin_inset(os, "space ");
5763 if (known_unit && !known_hspace)
5764 os << "\n\\length " << translate_len(length);
5766 os << "\n\\length " << gluelength;
5768 } else if (known_unit || known_vspace || is_gluelength) {
5769 // Literal vertical length or known variable
5770 context.check_layout(os);
5771 begin_inset(os, "VSpace ");
5774 if (known_unit && !known_vspace)
5775 os << translate_len(length);
5782 // LyX can't handle other length variables in Inset VSpace/space
5787 output_ert_inset(os, name + '{' + unit + '}', context);
5788 else if (value == -1.0)
5789 output_ert_inset(os, name + "{-" + unit + '}', context);
5791 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5793 output_ert_inset(os, name + '{' + length + '}', context);
5798 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5799 // might be one or several options or a star.
5800 // The single '=' is meant here.
5801 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5805 context.check_layout(os);
5806 // store the latexparam here. This is eaten in parse_text_in_inset
5807 context.latexparam = newinsetlayout->latexparam();
5808 docstring name = newinsetlayout->name();
5809 bool const caption = name.find(from_ascii("Caption:")) == 0;
5811 // Already done for floating minted listings.
5812 if (minted_float.empty()) {
5813 begin_inset(os, "Caption ");
5814 os << to_utf8(name.substr(8)) << '\n';
5817 // FIXME: what do we do if the prefix is not Flex: ?
5818 if (prefixIs(name, from_ascii("Flex:")))
5820 begin_inset(os, "Flex ");
5821 os << to_utf8(name) << '\n'
5822 << "status collapsed\n";
5824 if (!minted_float.empty()) {
5825 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5826 } else if (newinsetlayout->isPassThru()) {
5827 // set catcodes to verbatim early, just in case.
5828 p.setCatcodes(VERBATIM_CATCODES);
5829 string delim = p.get_token().asInput();
5831 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5832 //FIXME: handle error condition
5833 string const arg = p.verbatimStuff("}").second;
5834 Context newcontext(true, context.textclass);
5835 if (newinsetlayout->forcePlainLayout())
5836 newcontext.layout = &context.textclass.plainLayout();
5837 output_ert(os, arg, newcontext);
5839 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5840 context.latexparam.clear();
5843 // Minted caption insets are not closed here because
5844 // we collect everything into the caption.
5845 if (minted_float.empty())
5850 // The single '=' is meant here.
5851 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5855 context.check_layout(os);
5856 docstring name = newinsetlayout->name();
5857 bool const caption = name.find(from_ascii("Caption:")) == 0;
5859 // Already done for floating minted listings.
5860 if (minted_float.empty()) {
5861 begin_inset(os, "Caption ");
5862 os << to_utf8(name.substr(8)) << '\n';
5865 // FIXME: what do we do if the prefix is not Flex: ?
5866 if (prefixIs(name, from_ascii("Flex:")))
5868 begin_inset(os, "Flex ");
5869 os << to_utf8(name) << '\n'
5870 << "status collapsed\n";
5872 if (!minted_float.empty()) {
5873 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5874 } else if (newinsetlayout->isPassThru()) {
5875 // set catcodes to verbatim early, just in case.
5876 p.setCatcodes(VERBATIM_CATCODES);
5877 string delim = p.get_token().asInput();
5879 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5880 //FIXME: handle error condition
5881 string const arg = p.verbatimStuff("}").second;
5882 Context newcontext(true, context.textclass);
5883 if (newinsetlayout->forcePlainLayout())
5884 newcontext.layout = &context.textclass.plainLayout();
5885 output_ert(os, arg, newcontext);
5887 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5890 // Minted caption insets are not closed here because
5891 // we collect everything into the caption.
5892 if (minted_float.empty())
5897 if (t.cs() == "includepdf") {
5899 string const arg = p.getArg('[', ']');
5900 map<string, string> opts;
5901 vector<string> keys;
5902 split_map(arg, opts, keys);
5903 string name = normalize_filename(p.verbatim_item());
5904 string const path = getMasterFilePath(true);
5905 // We want to preserve relative / absolute filenames,
5906 // therefore path is only used for testing
5907 if (!makeAbsPath(name, path).exists()) {
5908 // The file extension is probably missing.
5909 // Now try to find it out.
5910 char const * const pdfpages_format[] = {"pdf", 0};
5911 string const pdftex_name =
5912 find_file(name, path, pdfpages_format);
5913 if (!pdftex_name.empty()) {
5918 FileName const absname = makeAbsPath(name, path);
5919 if (absname.exists())
5921 fix_child_filename(name);
5922 copy_file(absname, name);
5924 cerr << "Warning: Could not find file '"
5925 << name << "'." << endl;
5927 context.check_layout(os);
5928 begin_inset(os, "External\n\ttemplate ");
5929 os << "PDFPages\n\tfilename "
5931 // parse the options
5932 if (opts.find("pages") != opts.end())
5933 os << "\textra LaTeX \"pages="
5934 << opts["pages"] << "\"\n";
5935 if (opts.find("angle") != opts.end())
5936 os << "\trotateAngle "
5937 << opts["angle"] << '\n';
5938 if (opts.find("origin") != opts.end()) {
5940 string const opt = opts["origin"];
5941 if (opt == "tl") ss << "topleft";
5942 if (opt == "bl") ss << "bottomleft";
5943 if (opt == "Bl") ss << "baselineleft";
5944 if (opt == "c") ss << "center";
5945 if (opt == "tc") ss << "topcenter";
5946 if (opt == "bc") ss << "bottomcenter";
5947 if (opt == "Bc") ss << "baselinecenter";
5948 if (opt == "tr") ss << "topright";
5949 if (opt == "br") ss << "bottomright";
5950 if (opt == "Br") ss << "baselineright";
5951 if (!ss.str().empty())
5952 os << "\trotateOrigin " << ss.str() << '\n';
5954 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5956 if (opts.find("width") != opts.end())
5958 << translate_len(opts["width"]) << '\n';
5959 if (opts.find("height") != opts.end())
5961 << translate_len(opts["height"]) << '\n';
5962 if (opts.find("keepaspectratio") != opts.end())
5963 os << "\tkeepAspectRatio\n";
5965 context.check_layout(os);
5966 registerExternalTemplatePackages("PDFPages");
5970 if (t.cs() == "loadgame") {
5972 string name = normalize_filename(p.verbatim_item());
5973 string const path = getMasterFilePath(true);
5974 // We want to preserve relative / absolute filenames,
5975 // therefore path is only used for testing
5976 if (!makeAbsPath(name, path).exists()) {
5977 // The file extension is probably missing.
5978 // Now try to find it out.
5979 char const * const lyxskak_format[] = {"fen", 0};
5980 string const lyxskak_name =
5981 find_file(name, path, lyxskak_format);
5982 if (!lyxskak_name.empty())
5983 name = lyxskak_name;
5985 FileName const absname = makeAbsPath(name, path);
5986 if (absname.exists())
5988 fix_child_filename(name);
5989 copy_file(absname, name);
5991 cerr << "Warning: Could not find file '"
5992 << name << "'." << endl;
5993 context.check_layout(os);
5994 begin_inset(os, "External\n\ttemplate ");
5995 os << "ChessDiagram\n\tfilename "
5998 context.check_layout(os);
5999 // after a \loadgame follows a \showboard
6000 if (p.get_token().asInput() == "showboard")
6002 registerExternalTemplatePackages("ChessDiagram");
6006 // try to see whether the string is in unicodesymbols
6007 // Only use text mode commands, since we are in text mode here,
6008 // and math commands may be invalid (bug 6797)
6009 string name = t.asInput();
6010 // handle the dingbats, cyrillic and greek
6011 if (name == "\\textcyr")
6012 name = "\\textcyrillic";
6013 if (name == "\\ding" || name == "\\textcyrillic" ||
6014 (name == "\\textgreek" && !preamble.usePolyglossia()))
6015 name = name + '{' + p.getArg('{', '}') + '}';
6016 // handle the ifsym characters
6017 else if (name == "\\textifsymbol") {
6018 string const optif = p.getFullOpt();
6019 string const argif = p.getArg('{', '}');
6020 name = name + optif + '{' + argif + '}';
6022 // handle the \ascii characters
6023 // the case of \ascii within braces, as LyX outputs it, is already
6024 // handled for t.cat() == catBegin
6025 else if (name == "\\ascii") {
6026 // the code is "\asci\xxx"
6027 name = "{" + name + p.get_token().asInput() + "}";
6030 // handle some TIPA special characters
6031 else if (preamble.isPackageUsed("tipa")) {
6032 if (name == "\\s") {
6033 // fromLaTeXCommand() does not yet
6034 // recognize tipa short cuts
6035 name = "\\textsyllabic";
6036 } else if (name == "\\=" &&
6037 p.next_token().asInput() == "*") {
6038 // fromLaTeXCommand() does not yet
6039 // recognize tipa short cuts
6041 name = "\\textsubbar";
6042 } else if (name == "\\textdoublevertline") {
6043 // FIXME: This is not correct,
6044 // \textvertline is higher than \textbardbl
6045 name = "\\textbardbl";
6047 } else if (name == "\\!" ) {
6048 if (p.next_token().asInput() == "b") {
6049 p.get_token(); // eat 'b'
6052 } else if (p.next_token().asInput() == "d") {
6056 } else if (p.next_token().asInput() == "g") {
6060 } else if (p.next_token().asInput() == "G") {
6062 name = "\\texthtscg";
6064 } else if (p.next_token().asInput() == "j") {
6066 name = "\\texthtbardotlessj";
6068 } else if (p.next_token().asInput() == "o") {
6070 name = "\\textbullseye";
6073 } else if (name == "\\*" ) {
6074 if (p.next_token().asInput() == "k") {
6076 name = "\\textturnk";
6078 } else if (p.next_token().asInput() == "r") {
6079 p.get_token(); // eat 'b'
6080 name = "\\textturnr";
6082 } else if (p.next_token().asInput() == "t") {
6084 name = "\\textturnt";
6086 } else if (p.next_token().asInput() == "w") {
6088 name = "\\textturnw";
6093 if ((name.size() == 2 &&
6094 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6095 p.next_token().asInput() != "*") ||
6096 is_known(name.substr(1), known_tipa_marks)) {
6097 // name is a command that corresponds to a
6098 // combining character in unicodesymbols.
6099 // Append the argument, fromLaTeXCommand()
6100 // will either convert it to a single
6101 // character or a combining sequence.
6102 name += '{' + p.verbatim_item() + '}';
6104 // now get the character from unicodesymbols
6108 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6109 Encodings::TEXT_CMD, termination, rem, &req));
6111 context.check_layout(os);
6114 output_ert_inset(os, to_utf8(rem), context);
6116 skip_spaces_braces(p);
6117 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6118 preamble.registerAutomaticallyLoadedPackage(*it);
6120 //cerr << "#: " << t << " mode: " << mode << endl;
6121 // heuristic: read up to next non-nested space
6123 string s = t.asInput();
6124 string z = p.verbatim_item();
6125 while (p.good() && z != " " && !z.empty()) {
6126 //cerr << "read: " << z << endl;
6128 z = p.verbatim_item();
6130 cerr << "found ERT: " << s << endl;
6131 output_ert_inset(os, s + ' ', context);
6134 if (t.asInput() == name &&
6135 p.next_token().asInput() == "*") {
6136 // Starred commands like \vspace*{}
6137 p.get_token(); // Eat '*'
6140 if (!parse_command(name, p, os, outer, context)) {
6141 output_ert_inset(os, name, context);
6142 // Try to handle options of unknown commands:
6143 // Look if we have optional arguments,
6144 // and if so, put the brackets in ERT.
6145 while (p.hasOpt()) {
6146 p.get_token(); // eat '['
6147 output_ert_inset(os, "[", context);
6148 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6149 output_ert_inset(os, "]", context);
6157 string guessLanguage(Parser & p, string const & lang)
6159 typedef std::map<std::string, size_t> LangMap;
6160 // map from language names to number of characters
6163 for (char const * const * i = supported_CJK_languages; *i; i++)
6164 used[string(*i)] = 0;
6167 Token const t = p.get_token();
6168 // comments are not counted for any language
6169 if (t.cat() == catComment)
6171 // commands are not counted as well, but we need to detect
6172 // \begin{CJK} and switch encoding if needed
6173 if (t.cat() == catEscape) {
6174 if (t.cs() == "inputencoding") {
6175 string const enc = subst(p.verbatim_item(), "\n", " ");
6176 p.setEncoding(enc, Encoding::inputenc);
6179 if (t.cs() != "begin")
6182 // Non-CJK content is counted for lang.
6183 // We do not care about the real language here:
6184 // If we have more non-CJK contents than CJK contents,
6185 // we simply use the language that was specified as
6186 // babel main language.
6187 used[lang] += t.asInput().length();
6190 // Now we are starting an environment
6192 string const name = p.getArg('{', '}');
6193 if (name != "CJK") {
6197 // It is a CJK environment
6199 /* name = */ p.getArg('{', '}');
6200 string const encoding = p.getArg('{', '}');
6201 /* mapping = */ p.getArg('{', '}');
6202 string const encoding_old = p.getEncoding();
6203 char const * const * const where =
6204 is_known(encoding, supported_CJK_encodings);
6206 p.setEncoding(encoding, Encoding::CJK);
6208 p.setEncoding("UTF-8");
6209 string const text = p.ertEnvironment("CJK");
6210 p.setEncoding(encoding_old);
6213 // ignore contents in unknown CJK encoding
6216 // the language of the text
6218 supported_CJK_languages[where - supported_CJK_encodings];
6219 used[cjk] += text.length();
6221 LangMap::const_iterator use = used.begin();
6222 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6223 if (it->second > use->second)
6230 void check_comment_bib(ostream & os, Context & context)
6232 if (!need_commentbib)
6234 // We have a bibliography database, but no bibliography with biblatex
6235 // which is completely valid. Insert a bibtex inset in a note.
6236 context.check_layout(os);
6237 begin_inset(os, "Note Note\n");
6238 os << "status open\n";
6239 os << "\\begin_layout Plain Layout\n";
6240 begin_command_inset(os, "bibtex", "bibtex");
6242 for (auto const & bf : preamble.biblatex_bibliographies) {
6243 if (!bibfiles.empty())
6245 bibfiles += normalize_filename(bf);
6247 if (!bibfiles.empty())
6248 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6250 for (auto const & bf : preamble.biblatex_encodings) {
6251 if (!bibfileencs.empty())
6252 bibfileencs += "\t";
6255 if (!bibfileencs.empty())
6256 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6257 end_inset(os);// Bibtex
6258 os << "\\end_layout\n";
6259 end_inset(os);// Note