2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
26 #include "insets/ExternalTemplate.h"
28 #include "support/lassert.h"
29 #include "support/convert.h"
30 #include "support/FileName.h"
31 #include "support/filetools.h"
32 #include "support/Length.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, const string &, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
58 string const & rdelim)
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
68 output_arguments(os, p, outer, false, string(), newcontext,
70 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const & rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space",
320 ",", "thinspace",// \\, = \\thinspace
321 "quad", "qquad", "enspace", "enskip",
322 ";", ">", "medspace",// \\; = \\> = \medspace
323 ":", "thickspace",// \\: = \\thickspace
324 "!", "negthinspace",// \\! = \\negthinspace
325 "negmedspace", "negthickspace",
326 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
327 "rightarrowfill", "upbracefill", "downbracefill", 0};
329 /// the same as known_spaces with .lyx names
330 char const * const known_coded_spaces[] = { "space{}", "space{}",
331 "thinspace{}", "thinspace{}",
332 "quad{}", "qquad{}", "enspace{}", "enskip{}",
333 "medspace{}", "medspace{}", "medspace{}",
334 "thickspace{}", "thickspace{}",
335 "negthinspace{}", "negthinspace{}",
336 "negmedspace{}", "negthickspace{}",
337 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
338 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
340 /// known TIPA combining diacritical marks
341 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
342 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
343 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
344 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
345 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
346 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
347 "textsubring", "textsubbar", 0};
349 /// TIPA tones that need special handling
350 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
352 // string to store the float type to be able to determine the type of subfloats
353 string float_type = "";
355 // string to store the float status of minted listings
356 string minted_float = "";
358 // whether a caption has been parsed for a floating minted listing
359 bool minted_float_has_caption = false;
361 // The caption for non-floating minted listings
362 string minted_nonfloat_caption = "";
364 // Characters that have to be escaped by \\ in LaTeX
365 char const * const known_escaped_chars[] = {
366 "&", "_", "$", "%", "#", "^", "{", "}", 0};
369 /// splits "x=z, y=b" into a map and an ordered keyword vector
370 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
375 keys.resize(v.size());
376 for (size_t i = 0; i < v.size(); ++i) {
377 size_t const pos = v[i].find('=');
378 string const index = trimSpaceAndEol(v[i].substr(0, pos));
379 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
387 * Split a LaTeX length into value and unit.
388 * The latter can be a real unit like "pt", or a latex length variable
389 * like "\textwidth". The unit may contain additional stuff like glue
390 * lengths, but we don't care, because such lengths are ERT anyway.
391 * \returns true if \p value and \p unit are valid.
393 bool splitLatexLength(string const & len, string & value, string & unit)
397 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
398 //'4,5' is a valid LaTeX length number. Change it to '4.5'
399 string const length = subst(len, ',', '.');
400 if (i == string::npos)
403 if (len[0] == '\\') {
404 // We had something like \textwidth without a factor
410 value = trimSpaceAndEol(string(length, 0, i));
414 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
415 if (contains(len, '\\'))
416 unit = trimSpaceAndEol(string(len, i));
418 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
423 /// A simple function to translate a latex length to something LyX can
424 /// understand. Not perfect, but rather best-effort.
425 bool translate_len(string const & length, string & valstring, string & unit)
427 if (!splitLatexLength(length, valstring, unit))
429 // LyX uses percent values
431 istringstream iss(valstring);
436 string const percentval = oss.str();
438 if (unit.empty() || unit[0] != '\\')
440 string::size_type const i = unit.find(' ');
441 string const endlen = (i == string::npos) ? string() : string(unit, i);
442 if (unit == "\\textwidth") {
443 valstring = percentval;
444 unit = "text%" + endlen;
445 } else if (unit == "\\columnwidth") {
446 valstring = percentval;
447 unit = "col%" + endlen;
448 } else if (unit == "\\paperwidth") {
449 valstring = percentval;
450 unit = "page%" + endlen;
451 } else if (unit == "\\linewidth") {
452 valstring = percentval;
453 unit = "line%" + endlen;
454 } else if (unit == "\\paperheight") {
455 valstring = percentval;
456 unit = "pheight%" + endlen;
457 } else if (unit == "\\textheight") {
458 valstring = percentval;
459 unit = "theight%" + endlen;
460 } else if (unit == "\\baselineskip") {
461 valstring = percentval;
462 unit = "baselineskip%" + endlen;
468 /// If we have ambiguous quotation marks, make a smart guess
469 /// based on main quote style
470 string guessQuoteStyle(string const & in, bool const opening)
473 if (prefixIs(in, "qr")) {// straight quote
475 res = subst(res, "r", "l");
476 } else if (in == "eld") {// ``
477 if (preamble.quotesStyle() == "german")
479 else if (preamble.quotesStyle() == "british")
481 else if (preamble.quotesStyle() == "french")
483 else if (preamble.quotesStyle() == "russian")
485 } else if (in == "erd") {// ''
486 if (preamble.quotesStyle() == "polish")
488 else if (preamble.quotesStyle() == "british")
490 else if (preamble.quotesStyle() == "french")
492 else if (preamble.quotesStyle() == "hungarian")
494 else if (preamble.quotesStyle() == "swedish")
495 res = opening ? "sld" : "srd";
496 } else if (in == "els") {// `
497 if (preamble.quotesStyle() == "german")
499 else if (preamble.quotesStyle() == "british")
501 } else if (in == "ers") {// '
502 if (preamble.quotesStyle() == "polish")
504 else if (preamble.quotesStyle() == "british")
506 else if (preamble.quotesStyle() == "swedish")
507 res = opening ? "sls" : "srs";
508 } else if (in == "ard") {// >>
509 if (preamble.quotesStyle() == "swiss")
511 else if (preamble.quotesStyle() == "french")
513 else if (preamble.quotesStyle() == "russian")
515 else if (preamble.quotesStyle() == "hungarian")
517 } else if (in == "ald") {// <<
518 if (preamble.quotesStyle() == "swiss")
520 else if (preamble.quotesStyle() == "french")
522 else if (preamble.quotesStyle() == "russian")
524 else if (preamble.quotesStyle() == "hungarian")
526 } else if (in == "ars") {// >
527 if (preamble.quotesStyle() == "swiss")
529 } else if (in == "als") {// <
530 if (preamble.quotesStyle() == "swiss")
532 } else if (in == "gld") {// ,,
533 if (preamble.quotesStyle() == "polish")
535 else if (preamble.quotesStyle() == "hungarian")
537 else if (preamble.quotesStyle() == "russian")
539 } else if (in == "gls") {// ,
540 if (preamble.quotesStyle() == "polish")
547 string const fromPolyglossiaEnvironment(string const & s)
549 // Since \arabic is taken by the LaTeX kernel,
550 // the Arabic polyglossia environment is upcased
558 string uncapitalize(string const & s)
560 docstring in = from_ascii(s);
561 char_type t = lowercase(s[0]);
567 bool isCapitalized(string const & s)
569 docstring in = from_ascii(s);
570 char_type t = uppercase(s[0]);
572 return to_ascii(in) == s;
579 string translate_len(string const & length)
583 if (translate_len(length, value, unit))
585 // If the input is invalid, return what we have.
593 * Translates a LaTeX length into \p value, \p unit and
594 * \p special parts suitable for a box inset.
595 * The difference from translate_len() is that a box inset knows about
596 * some special "units" that are stored in \p special.
598 void translate_box_len(string const & length, string & value, string & unit, string & special)
600 if (translate_len(length, value, unit)) {
601 if (unit == "\\height" || unit == "\\depth" ||
602 unit == "\\totalheight" || unit == "\\width") {
603 special = unit.substr(1);
604 // The unit is not used, but LyX requires a dummy setting
616 void begin_inset(ostream & os, string const & name)
618 os << "\n\\begin_inset " << name;
622 void begin_command_inset(ostream & os, string const & name,
623 string const & latexname)
625 begin_inset(os, "CommandInset ");
626 os << name << "\nLatexCommand " << latexname << '\n';
630 void end_inset(ostream & os)
632 os << "\n\\end_inset\n\n";
636 bool skip_braces(Parser & p)
638 if (p.next_token().cat() != catBegin)
641 if (p.next_token().cat() == catEnd) {
650 /// replace LaTeX commands in \p s from the unicodesymbols file with their
652 pair<bool, docstring> convert_unicodesymbols(docstring s)
656 for (size_t i = 0; i < s.size();) {
665 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
666 Encodings::TEXT_CMD, termination, rem, &req));
667 set<string>::const_iterator it = req.begin();
668 set<string>::const_iterator en = req.end();
669 for (; it != en; ++it)
670 preamble.registerAutomaticallyLoadedPackage(*it);
673 if (s.empty() || s[0] != '\\')
677 for (auto const & c : known_escaped_chars)
678 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
683 return make_pair(res, os.str());
687 /// try to convert \p s to a valid InsetCommand argument
688 /// return whether this succeeded. If not, these command insets
689 /// get the "literate" flag.
690 pair<bool, string> convert_latexed_command_inset_arg(string s)
692 bool success = false;
694 // since we don't know the input encoding we can't use from_utf8
695 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
697 s = to_utf8(res.second);
699 // LyX cannot handle newlines in a latex command
700 return make_pair(success, subst(s, "\n", " "));
703 /// try to convert \p s to a valid InsetCommand argument
704 /// without trying to recode macros.
705 string convert_literate_command_inset_arg(string const & s)
707 // LyX cannot handle newlines in a latex command
708 return subst(s, "\n", " ");
711 void output_ert(ostream & os, string const & s, Context & context)
713 context.check_layout(os);
714 for (char const c : s) {
716 os << "\n\\backslash\n";
717 else if (c == '\n') {
718 context.new_paragraph(os);
719 context.check_layout(os);
723 context.check_end_layout(os);
727 void output_ert_inset(ostream & os, string const & s, Context & context)
729 // We must have a valid layout before outputting the ERT inset.
730 context.check_layout(os);
731 Context newcontext(true, context.textclass);
732 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
733 if (layout.forcePlainLayout())
734 newcontext.layout = &context.textclass.plainLayout();
735 begin_inset(os, "ERT");
736 os << "\nstatus collapsed\n";
737 output_ert(os, s, newcontext);
742 void output_comment(Parser & p, ostream & os, string const & s,
745 if (p.next_token().cat() == catNewline)
746 output_ert_inset(os, '%' + s, context);
748 output_ert_inset(os, '%' + s + '\n', context);
752 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
753 string const & latexparam = string())
755 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
758 if (checkModule(name, command))
759 return findLayoutWithoutModule(textclass, name, command, latexparam);
764 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
765 string const & latexparam = string())
767 InsetLayout const * insetlayout =
768 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
771 if (checkModule(name, command))
772 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
777 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
778 bool eatNewline = true);
782 * Skips whitespace and braces.
783 * This should be called after a command has been parsed that is not put into
784 * ERT, and where LyX adds "{}" if needed.
786 void skip_spaces_braces(Parser & p, bool keepws = false)
788 /* The following four examples produce the same typeset output and
789 should be handled by this function:
797 // Unfortunately we need to skip comments, too.
798 // We can't use eat_whitespace since writing them after the {}
799 // results in different output in some cases.
800 bool const skipped_spaces = p.skip_spaces(true);
801 bool const skipped_braces = skip_braces(p);
802 if (keepws && skipped_spaces && !skipped_braces)
803 // put back the space (it is better handled by check_space)
804 p.unskip_spaces(true);
808 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
809 Context & context, Layout::LaTeXArgMap const & latexargs)
811 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
813 context.check_layout(os);
819 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
820 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
821 for (; lait != laend; ++lait) {
823 eat_whitespace(p, os, context, false);
824 if (lait->second.mandatory) {
825 if (p.next_token().cat() != catBegin)
827 string ldelim = to_utf8(lait->second.ldelim);
828 string rdelim = to_utf8(lait->second.rdelim);
833 p.get_token(); // eat ldelim
834 if (ldelim.size() > 1)
835 p.get_token(); // eat ldelim
837 context.check_layout(os);
840 begin_inset(os, "Argument ");
843 os << i << "\nstatus collapsed\n\n";
844 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
847 string ldelim = to_utf8(lait->second.ldelim);
848 string rdelim = to_utf8(lait->second.rdelim);
853 string tok = p.next_token().asInput();
854 // we only support delimiters with max 2 chars for now.
855 if (ldelim.size() > 1)
856 tok += p.next_next_token().asInput();
857 if (p.next_token().cat() == catEscape || tok != ldelim)
859 p.get_token(); // eat ldelim
860 if (ldelim.size() > 1)
861 p.get_token(); // eat ldelim
863 context.check_layout(os);
866 begin_inset(os, "Argument ");
869 os << i << "\nstatus collapsed\n\n";
870 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
873 eat_whitespace(p, os, context, false);
878 void output_command_layout(ostream & os, Parser & p, bool outer,
879 Context & parent_context,
880 Layout const * newlayout)
882 TeXFont const oldFont = parent_context.font;
883 // save the current font size
884 string const size = oldFont.size;
885 // reset the font size to default, because the font size switches
886 // don't affect section headings and the like
887 parent_context.font.size = Context::normalfont.size;
888 // we only need to write the font change if we have an open layout
889 if (!parent_context.atParagraphStart())
890 output_font_change(os, oldFont, parent_context.font);
891 parent_context.check_end_layout(os);
892 Context context(true, parent_context.textclass, newlayout,
893 parent_context.layout, parent_context.font);
894 if (parent_context.deeper_paragraph) {
895 // We are beginning a nested environment after a
896 // deeper paragraph inside the outer list environment.
897 // Therefore we don't need to output a "begin deeper".
898 context.need_end_deeper = true;
900 context.check_deeper(os);
901 output_arguments(os, p, outer, true, string(), context,
902 context.layout->latexargs());
903 // If we have a latex param, we eat it here.
904 if (!parent_context.latexparam.empty()) {
906 Context dummy(true, parent_context.textclass);
907 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
908 string(1, parent_context.latexparam.back()));
910 parse_text(p, os, FLAG_ITEM, outer, context);
911 output_arguments(os, p, outer, false, "post", context,
912 context.layout->postcommandargs());
913 context.check_end_layout(os);
914 if (parent_context.deeper_paragraph) {
915 // We must suppress the "end deeper" because we
916 // suppressed the "begin deeper" above.
917 context.need_end_deeper = false;
919 context.check_end_deeper(os);
920 // We don't need really a new paragraph, but
921 // we must make sure that the next item gets a \begin_layout.
922 parent_context.new_paragraph(os);
923 // Set the font size to the original value. No need to output it here
924 // (Context::begin_layout() will do that if needed)
925 parent_context.font.size = size;
930 * Output a space if necessary.
931 * This function gets called for every whitespace token.
933 * We have three cases here:
934 * 1. A space must be suppressed. Example: The lyxcode case below
935 * 2. A space may be suppressed. Example: Spaces before "\par"
936 * 3. A space must not be suppressed. Example: A space between two words
938 * We currently handle only 1. and 3 and from 2. only the case of
939 * spaces before newlines as a side effect.
941 * 2. could be used to suppress as many spaces as possible. This has two effects:
942 * - Reimporting LyX generated LaTeX files changes almost no whitespace
943 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
944 * The drawback is that the logic inside the function becomes
945 * complicated, and that is the reason why it is not implemented.
947 void check_space(Parser & p, ostream & os, Context & context)
949 Token const next = p.next_token();
950 Token const curr = p.curr_token();
951 // A space before a single newline and vice versa must be ignored
952 // LyX emits a newline before \end{lyxcode}.
953 // This newline must be ignored,
954 // otherwise LyX will add an additional protected space.
955 if (next.cat() == catSpace ||
956 next.cat() == catNewline ||
957 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
960 context.check_layout(os);
966 * Parse all arguments of \p command
968 void parse_arguments(string const & command,
969 vector<ArgumentType> const & template_arguments,
970 Parser & p, ostream & os, bool outer, Context & context)
972 string ert = command;
973 size_t no_arguments = template_arguments.size();
974 for (size_t i = 0; i < no_arguments; ++i) {
975 switch (template_arguments[i]) {
978 // This argument contains regular LaTeX
979 output_ert_inset(os, ert + '{', context);
980 eat_whitespace(p, os, context, false);
981 if (template_arguments[i] == required)
982 parse_text(p, os, FLAG_ITEM, outer, context);
984 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
988 // This argument consists only of a single item.
989 // The presence of '{' or not must be preserved.
991 if (p.next_token().cat() == catBegin)
992 ert += '{' + p.verbatim_item() + '}';
994 ert += p.verbatim_item();
998 // This argument may contain special characters
999 ert += '{' + p.verbatim_item() + '}';
1003 // true because we must not eat whitespace
1004 // if an optional arg follows we must not strip the
1005 // brackets from this one
1006 if (i < no_arguments - 1 &&
1007 template_arguments[i+1] == optional)
1008 ert += p.getFullOpt(true);
1010 ert += p.getOpt(true);
1014 output_ert_inset(os, ert, context);
1019 * Check whether \p command is a known command. If yes,
1020 * handle the command with all arguments.
1021 * \return true if the command was parsed, false otherwise.
1023 bool parse_command(string const & command, Parser & p, ostream & os,
1024 bool outer, Context & context)
1026 if (known_commands.find(command) != known_commands.end()) {
1027 parse_arguments(command, known_commands[command], p, os,
1035 /// Parses a minipage or parbox
1036 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1037 unsigned inner_flags, bool outer, Context & parent_context,
1038 string const & outer_type, string const & special,
1039 string inner_type, string const & frame_color,
1040 string const & background_color)
1044 string hor_pos = "l";
1045 // We need to set the height to the LaTeX default of 1\\totalheight
1046 // for the case when no height argument is given
1047 string height_value = "1";
1048 string height_unit = "in";
1049 string height_special = "totalheight";
1050 string latex_height;
1054 string width_special = "none";
1055 string thickness = "0.4pt";
1056 if (!fboxrule.empty())
1057 thickness = fboxrule;
1059 thickness = "0.4pt";
1061 if (!fboxsep.empty())
1062 separation = fboxsep;
1066 if (!shadow_size.empty())
1067 shadowsize = shadow_size;
1070 string framecolor = "black";
1071 string backgroundcolor = "none";
1072 if (!frame_color.empty())
1073 framecolor = frame_color;
1074 if (!background_color.empty())
1075 backgroundcolor = background_color;
1076 // if there is a color box around the \begin statements have not yet been parsed
1078 if (!frame_color.empty() || !background_color.empty()) {
1079 eat_whitespace(p, os, parent_context, false);
1080 p.get_token().asInput(); // the '{'
1082 if (p.next_token().asInput() == "\\begin") {
1083 p.get_token().asInput();
1085 inner_type = "minipage";
1086 inner_flags = FLAG_END;
1087 active_environments.push_back("minipage");
1090 else if (p.next_token().asInput() == "\\parbox") {
1091 p.get_token().asInput();
1092 inner_type = "parbox";
1093 inner_flags = FLAG_ITEM;
1096 else if (p.next_token().asInput() == "\\makebox") {
1097 p.get_token().asInput();
1098 inner_type = "makebox";
1099 inner_flags = FLAG_ITEM;
1101 // in case there is just \colorbox{color}{text}
1104 inner_type = "makebox";
1105 inner_flags = FLAG_BRACE_LAST;
1110 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1112 if (!inner_type.empty() && p.hasOpt()) {
1113 if (inner_type != "makebox")
1114 position = p.getArg('[', ']');
1116 latex_width = p.getArg('[', ']');
1117 translate_box_len(latex_width, width_value, width_unit, width_special);
1120 if (position != "t" && position != "c" && position != "b") {
1121 cerr << "invalid position " << position << " for "
1122 << inner_type << endl;
1126 if (inner_type != "makebox") {
1127 latex_height = p.getArg('[', ']');
1128 translate_box_len(latex_height, height_value, height_unit, height_special);
1130 string const opt = p.getArg('[', ']');
1133 if (hor_pos != "l" && hor_pos != "c" &&
1134 hor_pos != "r" && hor_pos != "s") {
1135 cerr << "invalid hor_pos " << hor_pos
1136 << " for " << inner_type << endl;
1143 inner_pos = p.getArg('[', ']');
1144 if (inner_pos != "c" && inner_pos != "t" &&
1145 inner_pos != "b" && inner_pos != "s") {
1146 cerr << "invalid inner_pos "
1147 << inner_pos << " for "
1148 << inner_type << endl;
1149 inner_pos = position;
1153 if (inner_type == "makebox")
1157 if (inner_type.empty()) {
1158 if (special.empty() && outer_type != "framebox")
1159 latex_width = "1\\columnwidth";
1162 latex_width = p2.getArg('[', ']');
1163 string const opt = p2.getArg('[', ']');
1166 if (hor_pos != "l" && hor_pos != "c" &&
1167 hor_pos != "r" && hor_pos != "s") {
1168 cerr << "invalid hor_pos " << hor_pos
1169 << " for " << outer_type << endl;
1173 if (outer_type == "framebox")
1177 } else if (inner_type != "makebox")
1178 latex_width = p.verbatim_item();
1179 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1180 // as this is LyX's standard for such cases (except for makebox)
1181 // \framebox is more special and handled below
1182 if (latex_width.empty() && inner_type != "makebox"
1183 && outer_type != "framebox")
1184 latex_width = "1\\columnwidth";
1186 translate_len(latex_width, width_value, width_unit);
1188 bool shadedparbox = false;
1189 if (inner_type == "shaded") {
1190 eat_whitespace(p, os, parent_context, false);
1191 if (outer_type == "parbox") {
1193 if (p.next_token().cat() == catBegin)
1195 eat_whitespace(p, os, parent_context, false);
1196 shadedparbox = true;
1201 // If we already read the inner box we have to push the inner env
1202 if (!outer_type.empty() && !inner_type.empty() &&
1203 (inner_flags & FLAG_END))
1204 active_environments.push_back(inner_type);
1205 bool use_ert = false;
1206 if (!outer_type.empty() && !inner_type.empty()) {
1207 // Look whether there is some content after the end of the
1208 // inner box, but before the end of the outer box.
1209 // If yes, we need to output ERT.
1211 if (inner_flags & FLAG_END)
1212 p.ertEnvironment(inner_type);
1215 p.skip_spaces(true);
1216 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1217 if ((outer_env && p.next_token().asInput() != "\\end") ||
1218 (!outer_env && p.next_token().cat() != catEnd)) {
1219 // something is between the end of the inner box and
1220 // the end of the outer box, so we need to use ERT.
1228 if (!outer_type.empty()) {
1229 if (outer_flags & FLAG_END)
1230 ss << "\\begin{" << outer_type << '}';
1232 ss << '\\' << outer_type << '{';
1233 if (!special.empty())
1237 if (!inner_type.empty()) {
1238 if (inner_type != "shaded") {
1239 if (inner_flags & FLAG_END)
1240 ss << "\\begin{" << inner_type << '}';
1242 ss << '\\' << inner_type;
1244 if (!position.empty())
1245 ss << '[' << position << ']';
1246 if (!latex_height.empty())
1247 ss << '[' << latex_height << ']';
1248 if (!inner_pos.empty())
1249 ss << '[' << inner_pos << ']';
1250 ss << '{' << latex_width << '}';
1251 if (!(inner_flags & FLAG_END))
1254 if (inner_type == "shaded")
1255 ss << "\\begin{shaded}";
1256 output_ert_inset(os, ss.str(), parent_context);
1257 if (!inner_type.empty()) {
1258 parse_text(p, os, inner_flags, outer, parent_context);
1259 if (inner_flags & FLAG_END)
1260 output_ert_inset(os, "\\end{" + inner_type + '}',
1263 output_ert_inset(os, "}", parent_context);
1265 if (!outer_type.empty()) {
1266 // If we already read the inner box we have to pop
1268 if (!inner_type.empty() && (inner_flags & FLAG_END))
1269 active_environments.pop_back();
1271 // Ensure that the end of the outer box is parsed correctly:
1272 // The opening brace has been eaten by parse_outer_box()
1273 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1274 outer_flags &= ~FLAG_ITEM;
1275 outer_flags |= FLAG_BRACE_LAST;
1277 parse_text(p, os, outer_flags, outer, parent_context);
1278 if (outer_flags & FLAG_END)
1279 output_ert_inset(os, "\\end{" + outer_type + '}',
1282 output_ert_inset(os, "}", parent_context);
1285 // LyX does not like empty positions, so we have
1286 // to set them to the LaTeX default values here.
1287 if (position.empty())
1289 if (inner_pos.empty())
1290 inner_pos = position;
1291 parent_context.check_layout(os);
1292 begin_inset(os, "Box ");
1293 if (outer_type == "framed")
1295 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1297 else if (outer_type == "shadowbox")
1298 os << "Shadowbox\n";
1299 else if ((outer_type == "shaded" && inner_type.empty()) ||
1300 (outer_type == "minipage" && inner_type == "shaded") ||
1301 (outer_type == "parbox" && inner_type == "shaded")) {
1303 preamble.registerAutomaticallyLoadedPackage("color");
1304 } else if (outer_type == "doublebox")
1305 os << "Doublebox\n";
1306 else if (outer_type.empty() || outer_type == "mbox")
1307 os << "Frameless\n";
1309 os << outer_type << '\n';
1310 os << "position \"" << position << "\"\n";
1311 os << "hor_pos \"" << hor_pos << "\"\n";
1312 if (outer_type == "mbox")
1313 os << "has_inner_box 1\n";
1314 else if (!frame_color.empty() && inner_type == "makebox")
1315 os << "has_inner_box 0\n";
1317 os << "has_inner_box " << !inner_type.empty() << "\n";
1318 os << "inner_pos \"" << inner_pos << "\"\n";
1319 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1321 if (outer_type == "mbox")
1322 os << "use_makebox 1\n";
1323 else if (!frame_color.empty())
1324 os << "use_makebox 0\n";
1326 os << "use_makebox " << (inner_type == "makebox") << '\n';
1327 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1328 os << "width \"\"\n";
1329 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1330 else if (contains(width_unit, '\\'))
1331 os << "width \"" << width_value << "in" << "\"\n";
1333 os << "width \"" << width_value << width_unit << "\"\n";
1334 if (contains(width_unit, '\\')) {
1335 width_unit.erase (0,1); // remove the leading '\'
1336 os << "special \"" << width_unit << "\"\n";
1338 os << "special \"" << width_special << "\"\n";
1339 if (contains(height_unit, '\\'))
1340 os << "height \"" << height_value << "in" << "\"\n";
1342 os << "height \"" << height_value << height_unit << "\"\n";
1343 os << "height_special \"" << height_special << "\"\n";
1344 os << "thickness \"" << thickness << "\"\n";
1345 os << "separation \"" << separation << "\"\n";
1346 os << "shadowsize \"" << shadowsize << "\"\n";
1347 os << "framecolor \"" << framecolor << "\"\n";
1348 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1349 os << "status open\n\n";
1351 // Unfortunately we can't use parse_text_in_inset:
1352 // InsetBox::forcePlainLayout() is hard coded and does not
1353 // use the inset layout. Apart from that do we call parse_text
1354 // up to two times, but need only one check_end_layout.
1355 bool const forcePlainLayout =
1356 (!inner_type.empty() || inner_type == "makebox") &&
1357 outer_type != "shaded" && outer_type != "framed";
1358 Context context(true, parent_context.textclass);
1359 if (forcePlainLayout)
1360 context.layout = &context.textclass.plainLayout();
1362 context.font = parent_context.font;
1364 // If we have no inner box the contents will be read with the outer box
1365 if (!inner_type.empty())
1366 parse_text(p, os, inner_flags, outer, context);
1368 // Ensure that the end of the outer box is parsed correctly:
1369 // The opening brace has been eaten by parse_outer_box()
1370 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1371 outer_flags &= ~FLAG_ITEM;
1372 outer_flags |= FLAG_BRACE_LAST;
1375 // Find end of outer box, output contents if inner_type is
1376 // empty and output possible comments
1377 if (!outer_type.empty()) {
1378 // If we already read the inner box we have to pop
1380 if (!inner_type.empty() && (inner_flags & FLAG_END))
1381 active_environments.pop_back();
1382 // This does not output anything but comments if
1383 // inner_type is not empty (see use_ert)
1384 parse_text(p, os, outer_flags, outer, context);
1387 context.check_end_layout(os);
1389 #ifdef PRESERVE_LAYOUT
1390 // LyX puts a % after the end of the minipage
1391 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1393 //output_comment(p, os, "dummy", parent_context);
1396 parent_context.new_paragraph(os);
1398 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1399 //output_comment(p, os, "dummy", parent_context);
1402 // We add a protected space if something real follows
1403 if (p.good() && p.next_token().cat() != catComment) {
1404 begin_inset(os, "space ~\n");
1410 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1411 active_environments.pop_back();
1412 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1413 // in this case we have to eat the the closing brace of the color box
1414 p.get_token().asInput(); // the '}'
1416 if (p.next_token().asInput() == "}") {
1417 // in this case we assume that the closing brace is from the box settings
1418 // therefore reset these values for the next box
1424 // all boxes except of Frameless and Shaded require calc
1425 if (!(outer_type.empty() || outer_type == "mbox") &&
1426 !((outer_type == "shaded" && inner_type.empty()) ||
1427 (outer_type == "minipage" && inner_type == "shaded") ||
1428 (outer_type == "parbox" && inner_type == "shaded")))
1429 preamble.registerAutomaticallyLoadedPackage("calc");
1433 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1434 Context & parent_context, string const & outer_type,
1435 string const & special)
1437 eat_whitespace(p, os, parent_context, false);
1438 if (flags & FLAG_ITEM) {
1440 if (p.next_token().cat() == catBegin)
1443 cerr << "Warning: Ignoring missing '{' after \\"
1444 << outer_type << '.' << endl;
1445 eat_whitespace(p, os, parent_context, false);
1448 unsigned int inner_flags = 0;
1450 if (outer_type == "minipage" || outer_type == "parbox") {
1451 p.skip_spaces(true);
1452 while (p.hasOpt()) {
1454 p.skip_spaces(true);
1457 p.skip_spaces(true);
1458 if (outer_type == "parbox") {
1460 if (p.next_token().cat() == catBegin)
1462 p.skip_spaces(true);
1465 if (outer_type == "shaded" || outer_type == "mbox") {
1466 // These boxes never have an inner box
1468 } else if (p.next_token().asInput() == "\\parbox") {
1469 inner = p.get_token().cs();
1470 inner_flags = FLAG_ITEM;
1471 } else if (p.next_token().asInput() == "\\begin") {
1472 // Is this a minipage or shaded box?
1475 inner = p.getArg('{', '}');
1477 if (inner == "minipage" || inner == "shaded")
1478 inner_flags = FLAG_END;
1483 if (inner_flags == FLAG_END) {
1484 if (inner != "shaded")
1488 eat_whitespace(p, os, parent_context, false);
1490 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1491 outer_type, special, inner, "", "");
1493 if (inner_flags == FLAG_ITEM) {
1495 eat_whitespace(p, os, parent_context, false);
1497 parse_box(p, os, flags, inner_flags, outer, parent_context,
1498 outer_type, special, inner, "", "");
1503 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1504 bool in_line, bool use_minted)
1506 parent_context.check_layout(os);
1507 begin_inset(os, "listings\n");
1508 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1510 while ((i = arg.find(", ")) != string::npos
1511 || (i = arg.find(",\t")) != string::npos)
1512 arg.erase(i + 1, 1);
1515 string const language = p.getArg('{', '}');
1516 p.skip_spaces(true);
1517 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1518 if (!minted_float.empty()) {
1519 arg += string(arg.empty() ? "" : ",") + minted_float;
1520 minted_nonfloat_caption.clear();
1524 os << "lstparams " << '"' << arg << '"' << '\n';
1525 if (arg.find("\\color") != string::npos)
1526 preamble.registerAutomaticallyLoadedPackage("color");
1529 os << "inline true\n";
1531 os << "inline false\n";
1532 os << "status open\n";
1533 Context context(true, parent_context.textclass);
1534 context.layout = &parent_context.textclass.plainLayout();
1535 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1536 minted_nonfloat_caption.erase(0,3);
1537 os << "\n\\begin_layout Plain Layout\n";
1538 begin_inset(os, "Caption Standard\n");
1539 Context newcontext(true, context.textclass,
1540 context.layout, 0, context.font);
1541 newcontext.check_layout(os);
1542 os << minted_nonfloat_caption << "\n";
1543 newcontext.check_end_layout(os);
1545 os << "\n\\end_layout\n";
1546 minted_nonfloat_caption.clear();
1550 // set catcodes to verbatim early, just in case.
1551 p.setCatcodes(VERBATIM_CATCODES);
1552 string delim = p.get_token().asInput();
1553 //FIXME: handler error condition
1554 s = p.verbatimStuff(delim).second;
1555 // context.new_paragraph(os);
1556 } else if (use_minted) {
1557 s = p.verbatimEnvironment("minted");
1559 s = p.verbatimEnvironment("lstlisting");
1561 output_ert(os, s, context);
1562 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1563 minted_nonfloat_caption.erase(0,3);
1564 os << "\n\\begin_layout Plain Layout\n";
1565 begin_inset(os, "Caption Standard\n");
1566 Context newcontext(true, context.textclass,
1567 context.layout, 0, context.font);
1568 newcontext.check_layout(os);
1569 os << minted_nonfloat_caption << "\n";
1570 newcontext.check_end_layout(os);
1572 os << "\n\\end_layout\n";
1573 minted_nonfloat_caption.clear();
1575 // Don't close the inset here for floating minted listings.
1576 // It will be closed at the end of the listing environment.
1577 if (!use_minted || minted_float.empty())
1580 eat_whitespace(p, os, parent_context, true);
1581 Token t = p.get_token();
1582 if (t.asInput() != "\\end") {
1583 // If anything follows, collect it into a caption.
1584 minted_float_has_caption = true;
1585 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1586 begin_inset(os, "Caption Standard\n");
1587 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1594 /// parse an unknown environment
1595 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1596 unsigned flags, bool outer,
1597 Context & parent_context)
1599 if (name == "tabbing")
1600 // We need to remember that we have to handle '\=' specially
1601 flags |= FLAG_TABBING;
1603 // We need to translate font changes and paragraphs inside the
1604 // environment to ERT if we have a non standard font.
1605 // Otherwise things like
1606 // \large\begin{foo}\huge bar\end{foo}
1608 bool const specialfont =
1609 (parent_context.font != parent_context.normalfont);
1610 bool const new_layout_allowed = parent_context.new_layout_allowed;
1612 parent_context.new_layout_allowed = false;
1613 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1614 // Try to handle options: Look if we have optional arguments,
1615 // and if so, put the brackets in ERT.
1616 while (p.hasOpt()) {
1617 p.get_token(); // eat '['
1618 output_ert_inset(os, "[", parent_context);
1619 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1620 output_ert_inset(os, "]", parent_context);
1622 parse_text_snippet(p, os, flags, outer, parent_context);
1623 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1625 parent_context.new_layout_allowed = new_layout_allowed;
1629 void parse_environment(Parser & p, ostream & os, bool outer,
1630 string & last_env, Context & parent_context)
1632 Layout const * newlayout;
1633 InsetLayout const * newinsetlayout = 0;
1634 string const name = p.getArg('{', '}');
1635 const bool is_starred = suffixIs(name, '*');
1636 string const unstarred_name = rtrim(name, "*");
1637 active_environments.push_back(name);
1639 // We use this loop and break out after a condition is met
1640 // rather than a huge else-if-chain.
1642 if (is_math_env(name)) {
1643 parent_context.check_layout(os);
1644 begin_inset(os, "Formula ");
1645 os << "\\begin{" << name << "}";
1646 parse_math(p, os, FLAG_END, MATH_MODE);
1647 os << "\\end{" << name << "}";
1649 if (is_display_math_env(name)) {
1650 // Prevent the conversion of a line break to a space
1651 // (bug 7668). This does not change the output, but
1652 // looks ugly in LyX.
1653 eat_whitespace(p, os, parent_context, false);
1658 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1659 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1660 // We must begin a new paragraph if not already done
1661 if (!parent_context.atParagraphStart()) {
1662 parent_context.check_end_layout(os);
1663 parent_context.new_paragraph(os);
1665 // store previous language because we must reset it at the end
1666 string const lang_old = parent_context.font.language;
1667 // save new language in context so that it is
1668 // handled by parse_text
1669 parent_context.font.language =
1670 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1671 parse_text(p, os, FLAG_END, outer, parent_context);
1672 // reset previous language
1673 parent_context.font.language = lang_old;
1674 // Just in case the environment is empty
1675 parent_context.extra_stuff.erase();
1676 // We must begin a new paragraph to reset the language
1677 parent_context.new_paragraph(os);
1682 if (unstarred_name == "tabular" || name == "longtable"
1683 || name == "tabularx" || name == "xltabular") {
1684 eat_whitespace(p, os, parent_context, false);
1685 string width = "0pt";
1687 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1688 string const opt = p.getArg('[', ']');
1691 else if (opt == "l")
1693 else if (opt == "r")
1696 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1697 width = lyx::translate_len(p.getArg('{', '}'));
1698 eat_whitespace(p, os, parent_context, false);
1700 parent_context.check_layout(os);
1701 begin_inset(os, "Tabular ");
1702 handle_tabular(p, os, name, width, halign, parent_context);
1708 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1709 eat_whitespace(p, os, parent_context, false);
1710 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1711 eat_whitespace(p, os, parent_context, false);
1712 parent_context.check_layout(os);
1713 begin_inset(os, "Float " + unstarred_name + "\n");
1714 // store the float type for subfloats
1715 // subfloats only work with figures and tables
1716 if (unstarred_name == "figure")
1717 float_type = unstarred_name;
1718 else if (unstarred_name == "table")
1719 float_type = unstarred_name;
1723 os << "placement " << opt << '\n';
1724 if (contains(opt, "H"))
1725 preamble.registerAutomaticallyLoadedPackage("float");
1727 Floating const & fl = parent_context.textclass.floats()
1728 .getType(unstarred_name);
1729 if (!fl.floattype().empty() && fl.usesFloatPkg())
1730 preamble.registerAutomaticallyLoadedPackage("float");
1733 os << "wide " << convert<string>(is_starred)
1734 << "\nsideways false"
1735 << "\nstatus open\n\n";
1736 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1738 // We don't need really a new paragraph, but
1739 // we must make sure that the next item gets a \begin_layout.
1740 parent_context.new_paragraph(os);
1742 // the float is parsed thus delete the type
1747 if (unstarred_name == "sidewaysfigure"
1748 || unstarred_name == "sidewaystable"
1749 || unstarred_name == "sidewaysalgorithm") {
1750 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1751 eat_whitespace(p, os, parent_context, false);
1752 parent_context.check_layout(os);
1753 if (unstarred_name == "sidewaysfigure")
1754 begin_inset(os, "Float figure\n");
1755 else if (unstarred_name == "sidewaystable")
1756 begin_inset(os, "Float table\n");
1757 else if (unstarred_name == "sidewaysalgorithm")
1758 begin_inset(os, "Float algorithm\n");
1760 os << "placement " << opt << '\n';
1761 if (contains(opt, "H"))
1762 preamble.registerAutomaticallyLoadedPackage("float");
1763 os << "wide " << convert<string>(is_starred)
1764 << "\nsideways true"
1765 << "\nstatus open\n\n";
1766 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1768 // We don't need really a new paragraph, but
1769 // we must make sure that the next item gets a \begin_layout.
1770 parent_context.new_paragraph(os);
1772 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1776 if (name == "wrapfigure" || name == "wraptable") {
1777 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1778 eat_whitespace(p, os, parent_context, false);
1779 parent_context.check_layout(os);
1782 string overhang = "0col%";
1785 lines = p.getArg('[', ']');
1786 string const placement = p.getArg('{', '}');
1788 overhang = p.getArg('[', ']');
1789 string const width = p.getArg('{', '}');
1791 if (name == "wrapfigure")
1792 begin_inset(os, "Wrap figure\n");
1794 begin_inset(os, "Wrap table\n");
1795 os << "lines " << lines
1796 << "\nplacement " << placement
1797 << "\noverhang " << lyx::translate_len(overhang)
1798 << "\nwidth " << lyx::translate_len(width)
1799 << "\nstatus open\n\n";
1800 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1802 // We don't need really a new paragraph, but
1803 // we must make sure that the next item gets a \begin_layout.
1804 parent_context.new_paragraph(os);
1806 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1810 if (name == "minipage") {
1811 eat_whitespace(p, os, parent_context, false);
1812 // Test whether this is an outer box of a shaded box
1814 // swallow arguments
1815 while (p.hasOpt()) {
1817 p.skip_spaces(true);
1820 p.skip_spaces(true);
1821 Token t = p.get_token();
1822 bool shaded = false;
1823 if (t.asInput() == "\\begin") {
1824 p.skip_spaces(true);
1825 if (p.getArg('{', '}') == "shaded")
1830 parse_outer_box(p, os, FLAG_END, outer,
1831 parent_context, name, "shaded");
1833 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1834 "", "", name, "", "");
1839 if (name == "comment") {
1840 eat_whitespace(p, os, parent_context, false);
1841 parent_context.check_layout(os);
1842 begin_inset(os, "Note Comment\n");
1843 os << "status open\n";
1844 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1847 skip_braces(p); // eat {} that might by set by LyX behind comments
1848 preamble.registerAutomaticallyLoadedPackage("verbatim");
1852 if (unstarred_name == "verbatim") {
1853 // FIXME: this should go in the generic code that
1854 // handles environments defined in layout file that
1855 // have "PassThru 1". However, the code over there is
1856 // already too complicated for my taste.
1857 string const ascii_name =
1858 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1859 parent_context.new_paragraph(os);
1860 Context context(true, parent_context.textclass,
1861 &parent_context.textclass[from_ascii(ascii_name)]);
1862 string s = p.verbatimEnvironment(name);
1863 output_ert(os, s, context);
1868 if (name == "IPA") {
1869 eat_whitespace(p, os, parent_context, false);
1870 parent_context.check_layout(os);
1871 begin_inset(os, "IPA\n");
1872 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1875 preamble.registerAutomaticallyLoadedPackage("tipa");
1876 preamble.registerAutomaticallyLoadedPackage("tipx");
1880 if (name == parent_context.textclass.titlename()
1881 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1882 parse_text(p, os, FLAG_END, outer, parent_context);
1883 // Just in case the environment is empty
1884 parent_context.extra_stuff.erase();
1885 // We must begin a new paragraph
1886 parent_context.new_paragraph(os);
1891 if (name == "CJK") {
1892 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1893 // It is impossible to decide if a CJK environment was in its own paragraph or within
1894 // a line. We therefore always assume a paragraph since the latter is a rare case.
1895 eat_whitespace(p, os, parent_context, false);
1896 parent_context.check_end_layout(os);
1897 // store the encoding to be able to reset it
1898 string const encoding_old = p.getEncoding();
1899 string const encoding = p.getArg('{', '}');
1900 // FIXME: For some reason JIS does not work. Although the text
1901 // in tests/CJK.tex is identical with the SJIS version if you
1902 // convert both snippets using the recode command line utility,
1903 // the resulting .lyx file contains some extra characters if
1904 // you set buggy_encoding to false for JIS.
1905 bool const buggy_encoding = encoding == "JIS";
1906 if (!buggy_encoding)
1907 p.setEncoding(encoding, Encoding::CJK);
1909 // FIXME: This will read garbage, since the data is not encoded in utf8.
1910 p.setEncoding("UTF-8");
1912 // LyX only supports the same mapping for all CJK
1913 // environments, so we might need to output everything as ERT
1914 string const mapping = trim(p.getArg('{', '}'));
1915 char const * const * const where =
1916 is_known(encoding, supported_CJK_encodings);
1917 if (!buggy_encoding && !preamble.fontCJKSet())
1918 preamble.fontCJK(mapping);
1919 bool knownMapping = mapping == preamble.fontCJK();
1920 if (buggy_encoding || !knownMapping || !where) {
1921 parent_context.check_layout(os);
1922 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1924 // we must parse the content as verbatim because e.g. JIS can contain
1925 // normally invalid characters
1926 // FIXME: This works only for the most simple cases.
1927 // Since TeX control characters are not parsed,
1928 // things like comments are completely wrong.
1929 string const s = p.plainEnvironment("CJK");
1930 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1933 if (snip == "\\" || is_known(snip, known_escaped_chars))
1934 output_ert_inset(os, snip, parent_context);
1935 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1940 output_ert_inset(os, "\\end{" + name + "}",
1944 supported_CJK_languages[where - supported_CJK_encodings];
1945 // store the language because we must reset it at the end
1946 string const lang_old = parent_context.font.language;
1947 parent_context.font.language = lang;
1948 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1949 parent_context.font.language = lang_old;
1950 parent_context.new_paragraph(os);
1952 p.setEncoding(encoding_old);
1957 if (name == "lyxgreyedout") {
1958 eat_whitespace(p, os, parent_context, false);
1959 parent_context.check_layout(os);
1960 begin_inset(os, "Note Greyedout\n");
1961 os << "status open\n";
1962 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1965 if (!preamble.notefontcolor().empty())
1966 preamble.registerAutomaticallyLoadedPackage("color");
1970 if (name == "btSect") {
1971 eat_whitespace(p, os, parent_context, false);
1972 parent_context.check_layout(os);
1973 begin_command_inset(os, "bibtex", "bibtex");
1974 string bibstyle = "plain";
1976 bibstyle = p.getArg('[', ']');
1977 p.skip_spaces(true);
1979 string const bibfile = p.getArg('{', '}');
1980 eat_whitespace(p, os, parent_context, false);
1981 Token t = p.get_token();
1982 if (t.asInput() == "\\btPrintCited") {
1983 p.skip_spaces(true);
1984 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1986 if (t.asInput() == "\\btPrintNotCited") {
1987 p.skip_spaces(true);
1988 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1990 if (t.asInput() == "\\btPrintAll") {
1991 p.skip_spaces(true);
1992 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1994 os << "bibfiles " << '"' << bibfile << "\"\n"
1995 << "options " << '"' << bibstyle << "\"\n";
1996 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2002 if (name == "btUnit") {
2003 string const nt = p.next_next_token().cs();
2004 // Do not attempt to overwrite a former diverging multibib.
2005 // Those are output as ERT instead.
2006 if ((nt == "part" || nt == "chapter"
2007 || nt == "section" || nt == "subsection")
2008 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2009 parse_text(p, os, FLAG_END, outer, parent_context);
2010 preamble.multibib(nt);
2012 parse_unknown_environment(p, name, os, FLAG_END, outer,
2017 // This is only attempted at turn environments that consist only
2018 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2019 // Thus we will fall through in other cases.
2020 if (name == "turn") {
2021 // We check if the next thing is a tabular[*|x]
2023 p.getArg('{', '}');// eat turn argument
2024 bool found_end = false;
2025 bool only_table = false;
2026 bool end_table = false;
2029 string envname = p.getArg('{', '}');
2030 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2031 // Now we check if the table is the only content
2032 // of the turn environment
2033 string const tenv = envname;
2034 while (!found_end && !end_table && p.good()) {
2035 envname = p.next_token().cat() == catBegin
2036 ? p.getArg('{', '}') : string();
2037 Token const & t = p.get_token();
2039 end_table = t.asInput() != "\\end"
2041 found_end = t.asInput() == "\\end"
2042 && envname == "turn";
2046 envname = p.getArg('{', '}');
2047 only_table = p.next_next_token().asInput() == "\\end"
2048 && envname == "turn";
2052 string const angle = p.getArg('{', '}');
2054 int const save_tablerotation = parent_context.tablerotation;
2055 parent_context.tablerotation = convert<int>(angle);
2056 parse_text(p, os, FLAG_END, outer, parent_context);
2057 parent_context.tablerotation = save_tablerotation;
2067 // This is only attempted at landscape environments that consist only
2068 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2069 // Other landscape environment is handled via the landscape module, thus
2070 // we will fall through in that case.
2071 if (name == "landscape") {
2072 // We check if the next thing is a longtable
2074 bool found_end = false;
2075 bool only_longtable = false;
2076 bool end_longtable = false;
2079 string envname = p.getArg('{', '}');
2080 if (envname == "longtable" || envname == "xltabular") {
2081 // Now we check if the longtable is the only content
2082 // of the landscape environment
2083 string const ltenv = envname;
2084 while (!found_end && !end_longtable && p.good()) {
2085 envname = p.next_token().cat() == catBegin
2086 ? p.getArg('{', '}') : string();
2087 Token const & t = p.get_token();
2089 end_longtable = t.asInput() != "\\end"
2090 && envname == ltenv;
2091 found_end = t.asInput() == "\\end"
2092 && envname == "landscape";
2094 if (end_longtable) {
2096 envname = p.getArg('{', '}');
2097 only_longtable = p.next_next_token().asInput() == "\\end"
2098 && envname == "landscape";
2100 if (only_longtable) {
2103 int const save_tablerotation = parent_context.tablerotation;
2104 parent_context.tablerotation = 90;
2105 parse_text(p, os, FLAG_END, outer, parent_context);
2106 parent_context.tablerotation = save_tablerotation;
2116 if (name == "framed" || name == "shaded") {
2117 eat_whitespace(p, os, parent_context, false);
2118 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2120 preamble.registerAutomaticallyLoadedPackage("framed");
2124 if (name == "listing") {
2125 minted_float = "float";
2126 eat_whitespace(p, os, parent_context, false);
2127 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2129 minted_float += "=" + opt;
2130 // If something precedes \begin{minted}, we output it at the end
2131 // as a caption, in order to keep it inside the listings inset.
2132 eat_whitespace(p, os, parent_context, true);
2134 Token const & t = p.get_token();
2135 p.skip_spaces(true);
2136 string const envname = p.next_token().cat() == catBegin
2137 ? p.getArg('{', '}') : string();
2138 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2140 minted_float_has_caption = false;
2141 string content = parse_text_snippet(p, FLAG_END, outer,
2143 size_t i = content.find("\\begin_inset listings");
2144 bool minted_env = i != string::npos;
2147 caption = content.substr(0, i);
2148 content.erase(0, i);
2150 parent_context.check_layout(os);
2151 if (minted_env && minted_float_has_caption) {
2152 eat_whitespace(p, os, parent_context, true);
2153 os << content << "\n";
2154 if (!caption.empty())
2155 os << caption << "\n";
2156 os << "\n\\end_layout\n"; // close inner layout
2157 end_inset(os); // close caption inset
2158 os << "\n\\end_layout\n"; // close outer layout
2159 } else if (!caption.empty()) {
2161 begin_inset(os, "listings\n");
2162 os << "lstparams " << '"' << minted_float << '"' << '\n';
2163 os << "inline false\n";
2164 os << "status collapsed\n";
2166 os << "\n\\begin_layout Plain Layout\n";
2167 begin_inset(os, "Caption Standard\n");
2168 Context newcontext(true, parent_context.textclass,
2169 0, 0, parent_context.font);
2170 newcontext.check_layout(os);
2171 os << caption << "\n";
2172 newcontext.check_end_layout(os);
2174 os << "\n\\end_layout\n";
2175 } else if (content.empty()) {
2176 begin_inset(os, "listings\n");
2177 os << "lstparams " << '"' << minted_float << '"' << '\n';
2178 os << "inline false\n";
2179 os << "status collapsed\n";
2181 os << content << "\n";
2183 end_inset(os); // close listings inset
2184 parent_context.check_end_layout(os);
2185 parent_context.new_paragraph(os);
2187 minted_float.clear();
2188 minted_float_has_caption = false;
2192 if (name == "lstlisting" || name == "minted") {
2193 bool use_minted = name == "minted";
2194 // with listings, we do not eat newlines here since
2195 // \begin{lstlistings}
2198 // // \begin{lstlistings}%
2201 // reads [foo] as content, whereas
2202 // // \begin{lstlistings}%
2205 // \begin{lstlistings}[foo,
2207 // reads [foo...] as argument.
2208 eat_whitespace(p, os, parent_context, false, use_minted);
2209 if (use_minted && minted_float.empty()) {
2210 // look ahead for a bottom caption
2212 bool found_end_minted = false;
2213 while (!found_end_minted && p.good()) {
2214 Token const & t = p.get_token();
2216 string const envname =
2217 p.next_token().cat() == catBegin
2218 ? p.getArg('{', '}') : string();
2219 found_end_minted = t.asInput() == "\\end"
2220 && envname == "minted";
2222 eat_whitespace(p, os, parent_context, true);
2223 Token const & t = p.get_token();
2224 p.skip_spaces(true);
2225 if (t.asInput() == "\\lyxmintcaption") {
2226 string const pos = p.getArg('[', ']');
2228 string const caption =
2229 parse_text_snippet(p, FLAG_ITEM,
2230 false, parent_context);
2231 minted_nonfloat_caption = "[b]" + caption;
2232 eat_whitespace(p, os, parent_context, true);
2237 parse_listings(p, os, parent_context, false, use_minted);
2242 if (!parent_context.new_layout_allowed) {
2243 parse_unknown_environment(p, name, os, FLAG_END, outer,
2248 // Alignment and spacing settings
2249 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2250 // therefore are totally broken!
2251 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2252 // they are commands not environments. They are furthermore switches that
2253 // can be ended by another switches, but also by commands like \footnote or
2254 // \parbox. So the only safe way is to leave them untouched.
2255 // However, we support the pseudo-environments
2256 // \begin{centering} ... \end{centering}
2257 // \begin{raggedright} ... \end{raggedright}
2258 // \begin{raggedleft} ... \end{raggedleft}
2259 // since they are used by LyX in floats (for spacing reasons)
2260 if (name == "center" || name == "centering"
2261 || name == "flushleft" || name == "raggedright"
2262 || name == "flushright" || name == "raggedleft"
2263 || name == "singlespace" || name == "onehalfspace"
2264 || name == "doublespace" || name == "spacing") {
2265 eat_whitespace(p, os, parent_context, false);
2266 // We must begin a new paragraph if not already done
2267 if (! parent_context.atParagraphStart()) {
2268 parent_context.check_end_layout(os);
2269 parent_context.new_paragraph(os);
2271 if (name == "flushleft" || name == "raggedright")
2272 parent_context.add_extra_stuff("\\align left\n");
2273 else if (name == "flushright" || name == "raggedleft")
2274 parent_context.add_extra_stuff("\\align right\n");
2275 else if (name == "center" || name == "centering")
2276 parent_context.add_extra_stuff("\\align center\n");
2277 else if (name == "singlespace")
2278 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2279 else if (name == "onehalfspace") {
2280 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2281 preamble.registerAutomaticallyLoadedPackage("setspace");
2282 } else if (name == "doublespace") {
2283 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2284 preamble.registerAutomaticallyLoadedPackage("setspace");
2285 } else if (name == "spacing") {
2286 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2287 preamble.registerAutomaticallyLoadedPackage("setspace");
2289 parse_text(p, os, FLAG_END, outer, parent_context);
2290 // Just in case the environment is empty
2291 parent_context.extra_stuff.erase();
2292 // We must begin a new paragraph to reset the alignment
2293 parent_context.new_paragraph(os);
2298 // The single '=' is meant here.
2299 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2300 eat_whitespace(p, os, parent_context, false);
2301 Context context(true, parent_context.textclass, newlayout,
2302 parent_context.layout, parent_context.font);
2303 if (parent_context.deeper_paragraph) {
2304 // We are beginning a nested environment after a
2305 // deeper paragraph inside the outer list environment.
2306 // Therefore we don't need to output a "begin deeper".
2307 context.need_end_deeper = true;
2309 parent_context.check_end_layout(os);
2310 if (last_env == name) {
2311 // we need to output a separator since LyX would export
2312 // the two environments as one otherwise (bug 5716)
2313 TeX2LyXDocClass const & textclass(parent_context.textclass);
2314 Context newcontext(true, textclass,
2315 &(textclass.defaultLayout()));
2316 newcontext.check_layout(os);
2317 begin_inset(os, "Separator plain\n");
2319 newcontext.check_end_layout(os);
2321 switch (context.layout->latextype) {
2322 case LATEX_LIST_ENVIRONMENT:
2323 context.in_list_preamble =
2324 !context.layout->listpreamble().empty()
2325 && p.hasListPreamble(context.layout->itemcommand());
2326 context.add_par_extra_stuff("\\labelwidthstring "
2327 + p.verbatim_item() + '\n');
2330 case LATEX_BIB_ENVIRONMENT:
2331 p.verbatim_item(); // swallow next arg
2337 context.check_deeper(os);
2338 if (newlayout->keepempty) {
2339 // We need to start a new paragraph
2340 // even if it is empty.
2341 context.new_paragraph(os);
2342 context.check_layout(os);
2344 // handle known optional and required arguments
2345 if (context.layout->latextype == LATEX_ENVIRONMENT)
2346 output_arguments(os, p, outer, false, string(), context,
2347 context.layout->latexargs());
2348 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2349 context.in_list_preamble =
2350 !context.layout->listpreamble().empty()
2351 && p.hasListPreamble(context.layout->itemcommand());
2353 output_arguments(oss, p, outer, false, string(), context,
2354 context.layout->latexargs());
2355 context.list_extra_stuff = oss.str();
2357 if (context.in_list_preamble) {
2358 // Collect the stuff between \begin and first \item
2359 context.list_preamble =
2360 parse_text_snippet(p, FLAG_END, outer, context);
2361 context.in_list_preamble = false;
2363 parse_text(p, os, FLAG_END, outer, context);
2364 if (context.layout->latextype == LATEX_ENVIRONMENT)
2365 output_arguments(os, p, outer, false, "post", context,
2366 context.layout->postcommandargs());
2367 context.check_end_layout(os);
2368 if (parent_context.deeper_paragraph) {
2369 // We must suppress the "end deeper" because we
2370 // suppressed the "begin deeper" above.
2371 context.need_end_deeper = false;
2373 context.check_end_deeper(os);
2374 parent_context.new_paragraph(os);
2376 if (!preamble.titleLayoutFound())
2377 preamble.titleLayoutFound(newlayout->intitle);
2378 set<string> const & req = newlayout->required();
2379 set<string>::const_iterator it = req.begin();
2380 set<string>::const_iterator en = req.end();
2381 for (; it != en; ++it)
2382 preamble.registerAutomaticallyLoadedPackage(*it);
2386 // The single '=' is meant here.
2387 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2388 eat_whitespace(p, os, parent_context, false);
2389 parent_context.check_layout(os);
2390 begin_inset(os, "Flex ");
2391 docstring flex_name = newinsetlayout->name();
2392 // FIXME: what do we do if the prefix is not Flex: ?
2393 if (prefixIs(flex_name, from_ascii("Flex:")))
2394 flex_name.erase(0, 5);
2395 os << to_utf8(flex_name) << '\n'
2396 << "status collapsed\n";
2397 if (newinsetlayout->isPassThru()) {
2398 string const arg = p.verbatimEnvironment(name);
2399 Context context(true, parent_context.textclass,
2400 &parent_context.textclass.plainLayout(),
2401 parent_context.layout);
2402 output_ert(os, arg, parent_context);
2404 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2409 if (name == "appendix") {
2410 // This is no good latex style, but it works and is used in some documents...
2411 eat_whitespace(p, os, parent_context, false);
2412 parent_context.check_end_layout(os);
2413 Context context(true, parent_context.textclass, parent_context.layout,
2414 parent_context.layout, parent_context.font);
2415 context.check_layout(os);
2416 os << "\\start_of_appendix\n";
2417 parse_text(p, os, FLAG_END, outer, context);
2418 context.check_end_layout(os);
2423 if (known_environments.find(name) != known_environments.end()) {
2424 vector<ArgumentType> arguments = known_environments[name];
2425 // The last "argument" denotes whether we may translate the
2426 // environment contents to LyX
2427 // The default required if no argument is given makes us
2428 // compatible with the reLyXre environment.
2429 ArgumentType contents = arguments.empty() ?
2432 if (!arguments.empty())
2433 arguments.pop_back();
2434 // See comment in parse_unknown_environment()
2435 bool const specialfont =
2436 (parent_context.font != parent_context.normalfont);
2437 bool const new_layout_allowed =
2438 parent_context.new_layout_allowed;
2440 parent_context.new_layout_allowed = false;
2441 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2442 outer, parent_context);
2443 if (contents == verbatim)
2444 output_ert_inset(os, p.ertEnvironment(name),
2447 parse_text_snippet(p, os, FLAG_END, outer,
2449 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2451 parent_context.new_layout_allowed = new_layout_allowed;
2455 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2460 active_environments.pop_back();
2464 /// parses a comment and outputs it to \p os.
2465 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2466 bool skipNewlines = false)
2468 LASSERT(t.cat() == catComment, return);
2469 if (!t.cs().empty()) {
2470 context.check_layout(os);
2471 output_comment(p, os, t.cs(), context);
2472 if (p.next_token().cat() == catNewline) {
2473 // A newline after a comment line starts a new
2475 if (context.new_layout_allowed) {
2476 if(!context.atParagraphStart())
2477 // Only start a new paragraph if not already
2478 // done (we might get called recursively)
2479 context.new_paragraph(os);
2481 output_ert_inset(os, "\n", context);
2482 eat_whitespace(p, os, context, true);
2484 } else if (!skipNewlines) {
2485 // "%\n" combination
2492 * Reads spaces and comments until the first non-space, non-comment token.
2493 * New paragraphs (double newlines or \\par) are handled like simple spaces
2494 * if \p eatParagraph is true.
2495 * If \p eatNewline is false, newlines won't be treated as whitespace.
2496 * Spaces are skipped, but comments are written to \p os.
2498 void eat_whitespace(Parser & p, ostream & os, Context & context,
2499 bool eatParagraph, bool eatNewline)
2502 Token const & t = p.get_token();
2503 if (t.cat() == catComment)
2504 parse_comment(p, os, t, context, !eatNewline);
2505 else if ((!eatParagraph && p.isParagraph()) ||
2506 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2515 * Set a font attribute, parse text and reset the font attribute.
2516 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2517 * \param currentvalue Current value of the attribute. Is set to the new
2518 * value during parsing.
2519 * \param newvalue New value of the attribute
2521 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2522 Context & context, string const & attribute,
2523 string & currentvalue, string const & newvalue)
2525 context.check_layout(os);
2526 string const oldvalue = currentvalue;
2527 currentvalue = newvalue;
2528 os << '\n' << attribute << ' ' << newvalue << "\n";
2529 parse_text_snippet(p, os, flags, outer, context);
2530 context.check_layout(os);
2531 os << '\n' << attribute << ' ' << oldvalue << "\n";
2532 currentvalue = oldvalue;
2536 /// get the arguments of a natbib or jurabib citation command
2537 void get_cite_arguments(Parser & p, bool natbibOrder,
2538 string & before, string & after, bool const qualified = false)
2540 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2542 // text before the citation
2544 // text after the citation
2545 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2547 if (!after.empty()) {
2548 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2549 if (natbibOrder && !before.empty())
2550 swap(before, after);
2555 void copy_file(FileName const & src, string const & dstname)
2559 string const absParent = getParentFilePath(false);
2561 if (FileName::isAbsolute(dstname))
2562 dst = FileName(dstname);
2564 dst = makeAbsPath(dstname, absParent);
2565 FileName const srcpath = src.onlyPath();
2566 FileName const dstpath = dst.onlyPath();
2567 if (equivalent(srcpath, dstpath))
2569 if (!dstpath.isDirectory()) {
2570 if (!dstpath.createPath()) {
2571 cerr << "Warning: Could not create directory for file `"
2572 << dst.absFileName() << "´." << endl;
2576 if (dst.isReadableFile()) {
2577 if (overwriteFiles())
2578 cerr << "Warning: Overwriting existing file `"
2579 << dst.absFileName() << "´." << endl;
2581 cerr << "Warning: Not overwriting existing file `"
2582 << dst.absFileName() << "´." << endl;
2586 if (!src.copyTo(dst))
2587 cerr << "Warning: Could not copy file `" << src.absFileName()
2588 << "´ to `" << dst.absFileName() << "´." << endl;
2592 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2593 bool parse_chunk(Parser & p, ostream & os, Context & context)
2595 // check whether a chunk is possible here.
2596 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2602 // read the parameters
2603 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2604 if (!params.first) {
2609 Parser::Arg const code = p.verbatimStuff("\n@");
2614 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2615 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2619 // The last newline read is important for paragraph handling
2623 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2624 // We must have a valid layout before outputting the Chunk inset.
2625 context.check_layout(os);
2626 Context chunkcontext(true, context.textclass);
2627 chunkcontext.layout = &context.textclass.plainLayout();
2628 begin_inset(os, "Flex Chunk");
2629 os << "\nstatus open\n";
2630 if (!params.second.empty()) {
2631 chunkcontext.check_layout(os);
2632 Context paramscontext(true, context.textclass);
2633 paramscontext.layout = &context.textclass.plainLayout();
2634 begin_inset(os, "Argument 1");
2635 os << "\nstatus open\n";
2636 output_ert(os, params.second, paramscontext);
2639 output_ert(os, code.second, chunkcontext);
2647 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2648 bool is_macro(Parser & p)
2650 Token first = p.curr_token();
2651 if (first.cat() != catEscape || !p.good())
2653 if (first.cs() == "def")
2655 if (first.cs() != "global" && first.cs() != "long")
2657 Token second = p.get_token();
2659 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2660 second.cat() == catNewline || second.cat() == catComment)) {
2661 second = p.get_token();
2664 bool secondvalid = second.cat() == catEscape;
2666 bool thirdvalid = false;
2667 if (p.good() && first.cs() == "global" && secondvalid &&
2668 second.cs() == "long") {
2669 third = p.get_token();
2671 while (p.good() && !p.isParagraph() &&
2672 (third.cat() == catSpace ||
2673 third.cat() == catNewline ||
2674 third.cat() == catComment)) {
2675 third = p.get_token();
2678 thirdvalid = third.cat() == catEscape;
2680 for (int i = 0; i < pos; ++i)
2685 return (first.cs() == "global" || first.cs() == "long") &&
2686 second.cs() == "def";
2687 return first.cs() == "global" && second.cs() == "long" &&
2688 third.cs() == "def";
2692 /// Parse a macro definition (assumes that is_macro() returned true)
2693 void parse_macro(Parser & p, ostream & os, Context & context)
2695 context.check_layout(os);
2696 Token first = p.curr_token();
2699 string command = first.asInput();
2700 if (first.cs() != "def") {
2702 eat_whitespace(p, os, context, false);
2703 second = p.curr_token();
2704 command += second.asInput();
2705 if (second.cs() != "def") {
2707 eat_whitespace(p, os, context, false);
2708 third = p.curr_token();
2709 command += third.asInput();
2712 eat_whitespace(p, os, context, false);
2713 string const name = p.get_token().cs();
2714 eat_whitespace(p, os, context, false);
2720 while (p.next_token().cat() != catBegin) {
2721 if (p.next_token().cat() == catParameter) {
2726 // followed by number?
2727 if (p.next_token().cat() == catOther) {
2728 string s = p.get_token().asInput();
2730 // number = current arity + 1?
2731 if (s.size() == 1 && s[0] == arity + '0' + 1)
2736 paramtext += p.get_token().cs();
2738 paramtext += p.get_token().cs();
2743 // only output simple (i.e. compatible) macro as FormulaMacros
2744 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2746 context.check_layout(os);
2747 begin_inset(os, "FormulaMacro");
2748 os << "\n\\def" << ert;
2751 output_ert_inset(os, command + ert, context);
2755 void registerExternalTemplatePackages(string const & name)
2757 external::TemplateManager const & etm = external::TemplateManager::get();
2758 external::Template const * const et = etm.getTemplateByName(name);
2761 external::Template::Formats::const_iterator cit = et->formats.end();
2763 cit = et->formats.find("PDFLaTeX");
2764 if (cit == et->formats.end())
2765 // If the template has not specified a PDFLaTeX output,
2766 // we try the LaTeX format.
2767 cit = et->formats.find("LaTeX");
2768 if (cit == et->formats.end())
2770 vector<string>::const_iterator qit = cit->second.requirements.begin();
2771 vector<string>::const_iterator qend = cit->second.requirements.end();
2772 for (; qit != qend; ++qit)
2773 preamble.registerAutomaticallyLoadedPackage(*qit);
2776 } // anonymous namespace
2780 * Find a file with basename \p name in path \p path and an extension
2783 string find_file(string const & name, string const & path,
2784 char const * const * extensions)
2786 for (char const * const * what = extensions; *what; ++what) {
2787 string const trial = addExtension(name, *what);
2788 if (makeAbsPath(trial, path).exists())
2795 /// Convert filenames with TeX macros and/or quotes to something LyX
2797 string const normalize_filename(string const & name)
2802 Token const & t = p.get_token();
2803 if (t.cat() != catEscape)
2805 else if (t.cs() == "lyxdot") {
2806 // This is used by LyX for simple dots in relative
2810 } else if (t.cs() == "space") {
2813 } else if (t.cs() == "string") {
2814 // Convert \string" to " and \string~ to ~
2815 Token const & n = p.next_token();
2816 if (n.asInput() != "\"" && n.asInput() != "~")
2821 // Strip quotes. This is a bit complicated (see latex_path()).
2822 string full = os.str();
2823 if (!full.empty() && full[0] == '"') {
2824 string base = removeExtension(full);
2825 string ext = getExtension(full);
2826 if (!base.empty() && base[base.length()-1] == '"')
2829 return addExtension(trim(base, "\""), ext);
2830 if (full[full.length()-1] == '"')
2833 return trim(full, "\"");
2839 /// Convert \p name from TeX convention (relative to master file) to LyX
2840 /// convention (relative to .lyx file) if it is relative
2841 void fix_child_filename(string & name)
2843 string const absMasterTeX = getMasterFilePath(true);
2844 bool const isabs = FileName::isAbsolute(name);
2845 // convert from "relative to .tex master" to absolute original path
2847 name = makeAbsPath(name, absMasterTeX).absFileName();
2848 bool copyfile = copyFiles();
2849 string const absParentLyX = getParentFilePath(false);
2852 // convert from absolute original path to "relative to master file"
2853 string const rel = to_utf8(makeRelPath(from_utf8(name),
2854 from_utf8(absMasterTeX)));
2855 // re-interpret "relative to .tex file" as "relative to .lyx file"
2856 // (is different if the master .lyx file resides in a
2857 // different path than the master .tex file)
2858 string const absMasterLyX = getMasterFilePath(false);
2859 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2860 // Do not copy if the new path is impossible to create. Example:
2861 // absMasterTeX = "/foo/bar/"
2862 // absMasterLyX = "/bar/"
2863 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2864 if (contains(name, "/../"))
2871 // convert from absolute original path to
2872 // "relative to .lyx file"
2873 name = to_utf8(makeRelPath(from_utf8(abs),
2874 from_utf8(absParentLyX)));
2878 // convert from absolute original path to "relative to .lyx file"
2879 name = to_utf8(makeRelPath(from_utf8(name),
2880 from_utf8(absParentLyX)));
2885 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2886 Context & context, string const & rdelim)
2888 Layout const * newlayout = 0;
2889 InsetLayout const * newinsetlayout = 0;
2890 char const * const * where = 0;
2891 // Store the latest bibliographystyle, addcontentslineContent and
2892 // nocite{*} option (needed for bibtex inset)
2894 string contentslineContent;
2895 // Some classes provide a \bibliographystyle, so do not output
2896 // any if none is explicitly set.
2897 string bibliographystyle;
2898 bool const use_natbib = isProvided("natbib");
2899 bool const use_jurabib = isProvided("jurabib");
2900 bool const use_biblatex = isProvided("biblatex")
2901 && preamble.citeEngine() != "biblatex-natbib";
2902 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2903 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2904 need_commentbib = use_biblatex || use_biblatex_natbib;
2907 // it is impossible to determine the correct encoding for non-CJK Japanese.
2908 // Therefore write a note at the beginning of the document
2909 if (is_nonCJKJapanese) {
2910 context.check_layout(os);
2911 begin_inset(os, "Note Note\n");
2912 os << "status open\n\\begin_layout Plain Layout\n"
2913 << "\\series bold\n"
2914 << "Important information:\n"
2915 << "\\end_layout\n\n"
2916 << "\\begin_layout Plain Layout\n"
2917 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2918 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2919 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2920 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2921 << " and specify the encoding using the -e command-line switch.\n"
2922 << " In addition, you might want to double check that the desired output encoding\n"
2923 << " is correctly selected in Document > Settings > Language.\n"
2924 << "\\end_layout\n";
2926 is_nonCJKJapanese = false;
2929 bool have_cycled = false;
2931 // Leave here only after at least one cycle
2932 if (have_cycled && flags & FLAG_LEAVE) {
2933 flags &= ~FLAG_LEAVE;
2937 Token const & t = p.get_token();
2939 debugToken(cerr, t, flags);
2942 if (context.in_list_preamble
2943 && p.next_token().cs() == context.layout->itemcommand()) {
2944 // We are parsing a list preamble. End before first \item.
2945 flags |= FLAG_LEAVE;
2946 context.in_list_preamble = false;
2949 if (flags & FLAG_ITEM) {
2950 if (t.cat() == catSpace)
2953 flags &= ~FLAG_ITEM;
2954 if (t.cat() == catBegin) {
2955 // skip the brace and collect everything to the next matching
2957 flags |= FLAG_BRACE_LAST;
2961 // handle only this single token, leave the loop if done
2962 flags |= FLAG_LEAVE;
2965 if (t.cat() != catEscape && t.character() == ']' &&
2966 (flags & FLAG_BRACK_LAST))
2968 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2970 string tok = t.asInput();
2971 // we only support delimiters with max 2 chars for now.
2972 if (rdelim.size() > 1)
2973 tok += p.next_token().asInput();
2974 if (t.cat() != catEscape && !rdelim.empty()
2975 && tok == rdelim && (flags & FLAG_RDELIM)) {
2976 if (rdelim.size() > 1)
2977 p.get_token(); // eat rdelim
2981 // If there is anything between \end{env} and \begin{env} we
2982 // don't need to output a separator.
2983 if (t.cat() != catSpace && t.cat() != catNewline &&
2984 t.asInput() != "\\begin")
2991 bool const starred = p.next_token().asInput() == "*";
2992 string const starredname(starred ? (t.cs() + '*') : t.cs());
2993 if (t.cat() == catMath) {
2994 // we are inside some text mode thingy, so opening new math is allowed
2995 context.check_layout(os);
2996 begin_inset(os, "Formula ");
2997 Token const & n = p.get_token();
2998 bool const display(n.cat() == catMath && outer);
3000 // TeX's $$...$$ syntax for displayed math
3002 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3004 p.get_token(); // skip the second '$' token
3006 // simple $...$ stuff
3009 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3014 // Prevent the conversion of a line break to a
3015 // space (bug 7668). This does not change the
3016 // output, but looks ugly in LyX.
3017 eat_whitespace(p, os, context, false);
3022 if (t.cat() == catSuper || t.cat() == catSub) {
3023 cerr << "catcode " << t << " illegal in text mode\n";
3027 // Basic support for quotes. We try to disambiguate
3028 // quotes from the context (e.g., a left english quote is
3029 // the same as a right german quote...).
3030 // Try to make a smart guess about the side
3031 Token const prev = p.prev_token();
3032 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3033 && prev.character() != '\n' && prev.character() != '~');
3034 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3035 context.check_layout(os);
3036 begin_inset(os, "Quotes ");
3037 os << guessQuoteStyle("eld", opening);
3043 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3044 context.check_layout(os);
3045 begin_inset(os, "Quotes ");
3046 os << guessQuoteStyle("erd", opening);
3053 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3054 context.check_layout(os);
3055 begin_inset(os, "Quotes ");
3056 os << guessQuoteStyle("ald", opening);
3063 if (t.asInput() == "<"
3064 && p.next_token().asInput() == "<") {
3065 bool has_chunk = false;
3069 has_chunk = parse_chunk(p, os, context);
3075 context.check_layout(os);
3076 begin_inset(os, "Quotes ");
3077 os << guessQuoteStyle("ard", opening);
3085 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3086 check_space(p, os, context);
3090 // babel shorthands (also used by polyglossia)
3091 // Since these can have different meanings for different languages
3092 // we import them as ERT (but they must be put in ERT to get output
3094 if (t.asInput() == "\"") {
3096 // These are known pairs. We put them together in
3097 // one ERT inset. In other cases (such as "a), only
3098 // the quotation mark is ERTed.
3099 if (p.next_token().asInput() == "\""
3100 || p.next_token().asInput() == "|"
3101 || p.next_token().asInput() == "-"
3102 || p.next_token().asInput() == "~"
3103 || p.next_token().asInput() == "="
3104 || p.next_token().asInput() == "/"
3105 || p.next_token().asInput() == "~"
3106 || p.next_token().asInput() == "'"
3107 || p.next_token().asInput() == "`"
3108 || p.next_token().asInput() == "<"
3109 || p.next_token().asInput() == ">") {
3110 s += p.next_token().asInput();
3113 output_ert_inset(os, s, context);
3117 if (t.character() == '[' && noweb_mode &&
3118 p.next_token().character() == '[') {
3119 // These can contain underscores
3121 string const s = p.getFullOpt() + ']';
3122 if (p.next_token().character() == ']')
3125 cerr << "Warning: Inserting missing ']' in '"
3126 << s << "'." << endl;
3127 output_ert_inset(os, s, context);
3131 if (t.cat() == catLetter) {
3132 context.check_layout(os);
3137 if (t.cat() == catOther ||
3138 t.cat() == catAlign ||
3139 t.cat() == catParameter) {
3140 context.check_layout(os);
3141 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3142 context.merging_hyphens_allowed &&
3143 context.font.family != "ttfamily" &&
3144 !context.layout->pass_thru) {
3145 if (p.next_next_token().asInput() == "-") {
3147 os << to_utf8(docstring(1, 0x2014));
3151 os << to_utf8(docstring(1, 0x2013));
3154 // This translates "&" to "\\&" which may be wrong...
3159 if (p.isParagraph()) {
3160 // In minted floating listings we will collect
3161 // everything into the caption, where multiple
3162 // paragraphs are forbidden.
3163 if (minted_float.empty()) {
3164 if (context.new_layout_allowed)
3165 context.new_paragraph(os);
3167 output_ert_inset(os, "\\par ", context);
3170 eat_whitespace(p, os, context, true);
3174 if (t.cat() == catActive) {
3175 context.check_layout(os);
3176 if (t.character() == '~') {
3177 if (context.layout->free_spacing)
3180 begin_inset(os, "space ~\n");
3188 if (t.cat() == catBegin) {
3189 Token const next = p.next_token();
3190 Token const end = p.next_next_token();
3191 if (next.cat() == catEnd) {
3193 Token const prev = p.prev_token();
3195 if (p.next_token().character() == '`')
3196 ; // ignore it in {}``
3198 output_ert_inset(os, "{}", context);
3199 } else if (next.cat() == catEscape &&
3200 is_known(next.cs(), known_quotes) &&
3201 end.cat() == catEnd) {
3202 // Something like {\textquoteright} (e.g.
3203 // from writer2latex). We may skip the
3204 // braces here for better readability.
3205 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3207 } else if (p.next_token().asInput() == "\\ascii") {
3208 // handle the \ascii characters
3209 // (the case without braces is handled later)
3210 // the code is "{\ascii\xxx}"
3211 p.get_token(); // eat \ascii
3212 string name2 = p.get_token().asInput();
3213 p.get_token(); // eat the final '}'
3214 string const name = "{\\ascii" + name2 + "}";
3218 // get the character from unicodesymbols
3219 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3220 Encodings::TEXT_CMD, termination, rem, &req);
3222 context.check_layout(os);
3225 output_ert_inset(os,
3226 to_utf8(rem), context);
3227 for (set<string>::const_iterator it = req.begin();
3228 it != req.end(); ++it)
3229 preamble.registerAutomaticallyLoadedPackage(*it);
3231 // we did not find a non-ert version
3232 output_ert_inset(os, name, context);
3234 context.check_layout(os);
3235 // special handling of font attribute changes
3236 Token const prev = p.prev_token();
3237 TeXFont const oldFont = context.font;
3238 if (next.character() == '[' ||
3239 next.character() == ']' ||
3240 next.character() == '*') {
3242 if (p.next_token().cat() == catEnd) {
3247 output_ert_inset(os, "{", context);
3248 parse_text_snippet(p, os,
3251 output_ert_inset(os, "}", context);
3253 } else if (! context.new_layout_allowed) {
3254 output_ert_inset(os, "{", context);
3255 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3257 output_ert_inset(os, "}", context);
3258 } else if (is_known(next.cs(), known_sizes)) {
3259 // next will change the size, so we must
3261 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3263 if (!context.atParagraphStart())
3265 << context.font.size << "\n";
3266 } else if (is_known(next.cs(), known_font_families)) {
3267 // next will change the font family, so we
3268 // must reset it here
3269 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3271 if (!context.atParagraphStart())
3273 << context.font.family << "\n";
3274 } else if (is_known(next.cs(), known_font_series)) {
3275 // next will change the font series, so we
3276 // must reset it here
3277 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3279 if (!context.atParagraphStart())
3281 << context.font.series << "\n";
3282 } else if (is_known(next.cs(), known_font_shapes)) {
3283 // next will change the font shape, so we
3284 // must reset it here
3285 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3287 if (!context.atParagraphStart())
3289 << context.font.shape << "\n";
3290 } else if (is_known(next.cs(), known_old_font_families) ||
3291 is_known(next.cs(), known_old_font_series) ||
3292 is_known(next.cs(), known_old_font_shapes)) {
3293 // next will change the font family, series
3294 // and shape, so we must reset it here
3295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3297 if (!context.atParagraphStart())
3299 << context.font.family
3301 << context.font.series
3303 << context.font.shape << "\n";
3305 output_ert_inset(os, "{", context);
3306 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3308 output_ert_inset(os, "}", context);
3314 if (t.cat() == catEnd) {
3315 if (flags & FLAG_BRACE_LAST) {
3318 cerr << "stray '}' in text\n";
3319 output_ert_inset(os, "}", context);
3323 if (t.cat() == catComment) {
3324 parse_comment(p, os, t, context);
3329 // control sequences
3332 if (t.cs() == "(" || t.cs() == "[") {
3333 bool const simple = t.cs() == "(";
3334 context.check_layout(os);
3335 begin_inset(os, "Formula");
3336 os << " \\" << t.cs();
3337 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3338 os << '\\' << (simple ? ')' : ']');
3341 // Prevent the conversion of a line break to a
3342 // space (bug 7668). This does not change the
3343 // output, but looks ugly in LyX.
3344 eat_whitespace(p, os, context, false);
3349 if (t.cs() == "begin") {
3350 parse_environment(p, os, outer, last_env,
3355 if (t.cs() == "end") {
3356 if (flags & FLAG_END) {
3357 // eat environment name
3358 string const name = p.getArg('{', '}');
3359 if (name != active_environment())
3360 cerr << "\\end{" + name + "} does not match \\begin{"
3361 + active_environment() + "}\n";
3364 p.error("found 'end' unexpectedly");
3368 // "item" by default, but could be something else
3369 if (t.cs() == context.layout->itemcommand()) {
3371 if (context.layout->labeltype == LABEL_MANUAL) {
3372 // FIXME: This swallows comments, but we cannot use
3373 // eat_whitespace() since we must not output
3374 // anything before the item.
3375 p.skip_spaces(true);
3376 s = p.verbatimOption();
3378 p.skip_spaces(false);
3380 context.check_layout(os);
3381 if (context.has_item) {
3382 // An item in an unknown list-like environment
3383 // FIXME: Do this in check_layout()!
3384 context.has_item = false;
3385 string item = "\\" + context.layout->itemcommand();
3388 output_ert_inset(os, item, context);
3390 if (context.layout->labeltype != LABEL_MANUAL)
3391 output_arguments(os, p, outer, false, "item", context,
3392 context.layout->itemargs());
3393 if (!context.list_preamble.empty()) {
3394 // We have a list preamble. Output it here.
3395 begin_inset(os, "Argument listpreamble:1");
3396 os << "\nstatus collapsed\n\n"
3397 << "\\begin_layout Plain Layout\n\n"
3398 << rtrim(context.list_preamble)
3399 << "\n\\end_layout";
3401 context.list_preamble.clear();
3403 if (!context.list_extra_stuff.empty()) {
3404 os << context.list_extra_stuff;
3405 context.list_extra_stuff.clear();
3407 else if (!s.empty()) {
3408 // LyX adds braces around the argument,
3409 // so we need to remove them here.
3410 if (s.size() > 2 && s[0] == '{' &&
3411 s[s.size()-1] == '}')
3412 s = s.substr(1, s.size()-2);
3413 // If the argument contains a space we
3414 // must put it into ERT: Otherwise LyX
3415 // would misinterpret the space as
3416 // item delimiter (bug 7663)
3417 if (contains(s, ' ')) {
3418 output_ert_inset(os, s, context);
3421 os << parse_text_snippet(p2,
3422 FLAG_BRACK_LAST, outer, context);
3424 // The space is needed to separate the
3425 // item from the rest of the sentence.
3427 eat_whitespace(p, os, context, false);
3432 if (t.cs() == "bibitem") {
3434 context.check_layout(os);
3435 eat_whitespace(p, os, context, false);
3436 string label = p.verbatimOption();
3437 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3438 bool const literal = !lbl.first;
3439 label = literal ? subst(label, "\n", " ") : lbl.second;
3440 string lit = literal ? "\"true\"" : "\"false\"";
3441 string key = convert_literate_command_inset_arg(p.verbatim_item());
3442 begin_command_inset(os, "bibitem", "bibitem");
3443 os << "label \"" << label << "\"\n"
3444 << "key \"" << key << "\"\n"
3445 << "literal " << lit << "\n";
3451 // catch the case of \def\inputGnumericTable
3453 if (t.cs() == "def") {
3454 Token second = p.next_token();
3455 if (second.cs() == "inputGnumericTable") {
3459 Token third = p.get_token();
3461 if (third.cs() == "input") {
3465 string name = normalize_filename(p.verbatim_item());
3466 string const path = getMasterFilePath(true);
3467 // We want to preserve relative / absolute filenames,
3468 // therefore path is only used for testing
3469 // The file extension is in every case ".tex".
3470 // So we need to remove this extension and check for
3471 // the original one.
3472 name = removeExtension(name);
3473 if (!makeAbsPath(name, path).exists()) {
3474 char const * const Gnumeric_formats[] = {"gnumeric",
3476 string const Gnumeric_name =
3477 find_file(name, path, Gnumeric_formats);
3478 if (!Gnumeric_name.empty())
3479 name = Gnumeric_name;
3481 FileName const absname = makeAbsPath(name, path);
3482 if (absname.exists()) {
3483 fix_child_filename(name);
3484 copy_file(absname, name);
3486 cerr << "Warning: Could not find file '"
3487 << name << "'." << endl;
3488 context.check_layout(os);
3489 begin_inset(os, "External\n\ttemplate ");
3490 os << "GnumericSpreadsheet\n\tfilename "
3493 context.check_layout(os);
3495 // register the packages that are automatically loaded
3496 // by the Gnumeric template
3497 registerExternalTemplatePackages("GnumericSpreadsheet");
3502 parse_macro(p, os, context);
3506 if (t.cs() == "noindent") {
3508 context.add_par_extra_stuff("\\noindent\n");
3512 if (t.cs() == "appendix") {
3513 context.add_par_extra_stuff("\\start_of_appendix\n");
3514 // We need to start a new paragraph. Otherwise the
3515 // appendix in 'bla\appendix\chapter{' would start
3517 context.new_paragraph(os);
3518 // We need to make sure that the paragraph is
3519 // generated even if it is empty. Otherwise the
3520 // appendix in '\par\appendix\par\chapter{' would
3522 context.check_layout(os);
3523 // FIXME: This is a hack to prevent paragraph
3524 // deletion if it is empty. Handle this better!
3525 output_comment(p, os,
3526 "dummy comment inserted by tex2lyx to "
3527 "ensure that this paragraph is not empty",
3529 // Both measures above may generate an additional
3530 // empty paragraph, but that does not hurt, because
3531 // whitespace does not matter here.
3532 eat_whitespace(p, os, context, true);
3536 // Must catch empty dates before findLayout is called below
3537 if (t.cs() == "date") {
3538 eat_whitespace(p, os, context, false);
3540 string const date = p.verbatim_item();
3543 preamble.suppressDate(true);
3546 preamble.suppressDate(false);
3547 if (context.new_layout_allowed &&
3548 (newlayout = findLayout(context.textclass,
3551 output_command_layout(os, p, outer,
3552 context, newlayout);
3553 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3554 if (!preamble.titleLayoutFound())
3555 preamble.titleLayoutFound(newlayout->intitle);
3556 set<string> const & req = newlayout->required();
3557 set<string>::const_iterator it = req.begin();
3558 set<string>::const_iterator en = req.end();
3559 for (; it != en; ++it)
3560 preamble.registerAutomaticallyLoadedPackage(*it);
3562 output_ert_inset(os,
3563 "\\date{" + p.verbatim_item() + '}',
3569 // Before we look for the layout name with star and alone below, we check the layouts including
3570 // the LateXParam, which might be one or several options or a star.
3571 // The single '=' is meant here.
3572 if (context.new_layout_allowed &&
3573 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3574 // store the latexparam here. This is eaten in output_command_layout
3575 context.latexparam = newlayout->latexparam();
3577 output_command_layout(os, p, outer, context, newlayout);
3578 context.latexparam.clear();
3580 if (!preamble.titleLayoutFound())
3581 preamble.titleLayoutFound(newlayout->intitle);
3582 set<string> const & req = newlayout->required();
3583 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3584 preamble.registerAutomaticallyLoadedPackage(*it);
3588 // Starred section headings
3589 // Must attempt to parse "Section*" before "Section".
3590 if ((p.next_token().asInput() == "*") &&
3591 context.new_layout_allowed &&
3592 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3595 output_command_layout(os, p, outer, context, newlayout);
3597 if (!preamble.titleLayoutFound())
3598 preamble.titleLayoutFound(newlayout->intitle);
3599 set<string> const & req = newlayout->required();
3600 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3601 preamble.registerAutomaticallyLoadedPackage(*it);
3605 // Section headings and the like
3606 if (context.new_layout_allowed &&
3607 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3609 output_command_layout(os, p, outer, context, newlayout);
3611 if (!preamble.titleLayoutFound())
3612 preamble.titleLayoutFound(newlayout->intitle);
3613 set<string> const & req = newlayout->required();
3614 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3615 preamble.registerAutomaticallyLoadedPackage(*it);
3619 if (t.cs() == "subfloat") {
3620 // the syntax is \subfloat[list entry][sub caption]{content}
3621 // if it is a table of figure depends on the surrounding float
3623 // do nothing if there is no outer float
3624 if (!float_type.empty()) {
3625 context.check_layout(os);
3627 begin_inset(os, "Float " + float_type + "\n");
3629 << "\nsideways false"
3630 << "\nstatus collapsed\n\n";
3633 bool has_caption = false;
3634 if (p.next_token().cat() != catEscape &&
3635 p.next_token().character() == '[') {
3636 p.get_token(); // eat '['
3637 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3640 // In case we have two optional args, the second is the caption.
3641 if (p.next_token().cat() != catEscape &&
3642 p.next_token().character() == '[') {
3643 p.get_token(); // eat '['
3644 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3647 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3648 // the caption comes always as the last
3650 // we must make sure that the caption gets a \begin_layout
3651 os << "\n\\begin_layout Plain Layout";
3653 begin_inset(os, "Caption Standard\n");
3654 Context newcontext(true, context.textclass,
3655 0, 0, context.font);
3656 newcontext.check_layout(os);
3657 os << caption << "\n";
3658 newcontext.check_end_layout(os);
3661 // close the layout we opened
3662 os << "\n\\end_layout";
3667 // if the float type is not supported or there is no surrounding float
3672 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3674 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3676 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3677 + "{" + p.verbatim_item() + '}', context);
3682 if (t.cs() == "xymatrix") {
3683 // we must open a new math because LyX's xy support is in math
3684 context.check_layout(os);
3685 begin_inset(os, "Formula ");
3687 os << "\\" << t.cs() << '{';
3688 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3691 preamble.registerAutomaticallyLoadedPackage("xy");
3695 if (t.cs() == "includegraphics") {
3696 bool const clip = p.next_token().asInput() == "*";
3699 string const arg = p.getArg('[', ']');
3700 map<string, string> opts;
3701 vector<string> keys;
3702 split_map(arg, opts, keys);
3704 opts["clip"] = string();
3705 string name = normalize_filename(p.verbatim_item());
3707 string const path = getMasterFilePath(true);
3708 // We want to preserve relative / absolute filenames,
3709 // therefore path is only used for testing
3710 if (!makeAbsPath(name, path).exists()) {
3711 // The file extension is probably missing.
3712 // Now try to find it out.
3713 string const dvips_name =
3714 find_file(name, path,
3715 known_dvips_graphics_formats);
3716 string const pdftex_name =
3717 find_file(name, path,
3718 known_pdftex_graphics_formats);
3719 if (!dvips_name.empty()) {
3720 if (!pdftex_name.empty()) {
3721 cerr << "This file contains the "
3723 "\"\\includegraphics{"
3725 "However, files\n\""
3726 << dvips_name << "\" and\n\""
3727 << pdftex_name << "\"\n"
3728 "both exist, so I had to make a "
3729 "choice and took the first one.\n"
3730 "Please move the unwanted one "
3731 "someplace else and try again\n"
3732 "if my choice was wrong."
3736 } else if (!pdftex_name.empty()) {
3742 FileName const absname = makeAbsPath(name, path);
3743 if (absname.exists()) {
3744 fix_child_filename(name);
3745 copy_file(absname, name);
3747 cerr << "Warning: Could not find graphics file '"
3748 << name << "'." << endl;
3750 context.check_layout(os);
3751 begin_inset(os, "Graphics ");
3752 os << "\n\tfilename " << name << '\n';
3753 if (opts.find("width") != opts.end())
3755 << translate_len(opts["width"]) << '\n';
3756 if (opts.find("totalheight") != opts.end())
3758 << translate_len(opts["totalheight"]) << '\n';
3759 if (opts.find("scale") != opts.end()) {
3760 istringstream iss(opts["scale"]);
3764 os << "\tscale " << val << '\n';
3766 if (opts.find("angle") != opts.end()) {
3767 os << "\trotateAngle "
3768 << opts["angle"] << '\n';
3769 vector<string>::const_iterator a =
3770 find(keys.begin(), keys.end(), "angle");
3771 vector<string>::const_iterator s =
3772 find(keys.begin(), keys.end(), "width");
3773 if (s == keys.end())
3774 s = find(keys.begin(), keys.end(), "totalheight");
3775 if (s == keys.end())
3776 s = find(keys.begin(), keys.end(), "scale");
3777 if (s != keys.end() && distance(s, a) > 0)
3778 os << "\tscaleBeforeRotation\n";
3780 if (opts.find("origin") != opts.end()) {
3782 string const opt = opts["origin"];
3783 if (opt.find('l') != string::npos) ss << "left";
3784 if (opt.find('r') != string::npos) ss << "right";
3785 if (opt.find('c') != string::npos) ss << "center";
3786 if (opt.find('t') != string::npos) ss << "Top";
3787 if (opt.find('b') != string::npos) ss << "Bottom";
3788 if (opt.find('B') != string::npos) ss << "Baseline";
3789 if (!ss.str().empty())
3790 os << "\trotateOrigin " << ss.str() << '\n';
3792 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3794 if (opts.find("keepaspectratio") != opts.end())
3795 os << "\tkeepAspectRatio\n";
3796 if (opts.find("clip") != opts.end())
3798 if (opts.find("draft") != opts.end())
3800 if (opts.find("bb") != opts.end())
3801 os << "\tBoundingBox "
3802 << opts["bb"] << '\n';
3803 int numberOfbbOptions = 0;
3804 if (opts.find("bbllx") != opts.end())
3805 numberOfbbOptions++;
3806 if (opts.find("bblly") != opts.end())
3807 numberOfbbOptions++;
3808 if (opts.find("bburx") != opts.end())
3809 numberOfbbOptions++;
3810 if (opts.find("bbury") != opts.end())
3811 numberOfbbOptions++;
3812 if (numberOfbbOptions == 4)
3813 os << "\tBoundingBox "
3814 << opts["bbllx"] << " " << opts["bblly"] << " "
3815 << opts["bburx"] << " " << opts["bbury"] << '\n';
3816 else if (numberOfbbOptions > 0)
3817 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3818 numberOfbbOptions = 0;
3819 if (opts.find("natwidth") != opts.end())
3820 numberOfbbOptions++;
3821 if (opts.find("natheight") != opts.end())
3822 numberOfbbOptions++;
3823 if (numberOfbbOptions == 2)
3824 os << "\tBoundingBox 0bp 0bp "
3825 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3826 else if (numberOfbbOptions > 0)
3827 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3828 ostringstream special;
3829 if (opts.find("hiresbb") != opts.end())
3830 special << "hiresbb,";
3831 if (opts.find("trim") != opts.end())
3833 if (opts.find("viewport") != opts.end())
3834 special << "viewport=" << opts["viewport"] << ',';
3835 if (opts.find("height") != opts.end())
3836 special << "height=" << opts["height"] << ',';
3837 if (opts.find("type") != opts.end())
3838 special << "type=" << opts["type"] << ',';
3839 if (opts.find("ext") != opts.end())
3840 special << "ext=" << opts["ext"] << ',';
3841 if (opts.find("read") != opts.end())
3842 special << "read=" << opts["read"] << ',';
3843 if (opts.find("command") != opts.end())
3844 special << "command=" << opts["command"] << ',';
3845 string s_special = special.str();
3846 if (!s_special.empty()) {
3847 // We had special arguments. Remove the trailing ','.
3848 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3850 // TODO: Handle the unknown settings better.
3851 // Warn about invalid options.
3852 // Check whether some option was given twice.
3854 preamble.registerAutomaticallyLoadedPackage("graphicx");
3858 if (t.cs() == "footnote" ||
3859 (t.cs() == "thanks" && context.layout->intitle)) {
3861 context.check_layout(os);
3862 begin_inset(os, "Foot\n");
3863 os << "status collapsed\n\n";
3864 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3869 if (t.cs() == "marginpar") {
3871 context.check_layout(os);
3872 begin_inset(os, "Marginal\n");
3873 os << "status collapsed\n\n";
3874 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3879 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3880 bool const use_minted = t.cs() == "mintinline";
3882 parse_listings(p, os, context, true, use_minted);
3886 if (t.cs() == "ensuremath") {
3888 context.check_layout(os);
3889 string const s = p.verbatim_item();
3890 //FIXME: this never triggers in UTF8
3891 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3894 output_ert_inset(os, "\\ensuremath{" + s + "}",
3899 else if (t.cs() == "makeindex"
3900 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3901 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3902 if (preamble.titleLayoutFound()) {
3904 skip_spaces_braces(p);
3906 output_ert_inset(os, t.asInput(), context);
3910 if (t.cs() == "tableofcontents"
3911 || t.cs() == "lstlistoflistings"
3912 || t.cs() == "listoflistings") {
3913 string name = t.cs();
3914 if (preamble.minted() && name == "listoflistings")
3915 name.insert(0, "lst");
3916 context.check_layout(os);
3917 begin_command_inset(os, "toc", name);
3919 skip_spaces_braces(p);
3920 if (name == "lstlistoflistings") {
3921 if (preamble.minted())
3922 preamble.registerAutomaticallyLoadedPackage("minted");
3924 preamble.registerAutomaticallyLoadedPackage("listings");
3929 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3930 context.check_layout(os);
3931 if (t.cs() == "listoffigures")
3932 begin_inset(os, "FloatList figure\n");
3934 begin_inset(os, "FloatList table\n");
3936 skip_spaces_braces(p);
3940 if (t.cs() == "listof") {
3941 p.skip_spaces(true);
3942 string const name = p.verbatim_item();
3943 if (context.textclass.floats().typeExist(name)) {
3944 context.check_layout(os);
3945 begin_inset(os, "FloatList ");
3948 p.verbatim_item(); // swallow second arg
3950 output_ert_inset(os, "\\listof{" + name + "}", context);
3954 if (t.cs() == "theendnotes"
3955 || (t.cs() == "printendnotes"
3956 && p.next_token().asInput() != "*"
3958 context.check_layout(os);
3959 begin_inset(os, "FloatList endnote\n");
3961 skip_spaces_braces(p);
3965 if ((where = is_known(t.cs(), known_text_font_families))) {
3966 parse_text_attributes(p, os, FLAG_ITEM, outer,
3967 context, "\\family", context.font.family,
3968 known_coded_font_families[where - known_text_font_families]);
3972 // beamer has a \textbf<overlay>{} inset
3973 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3974 parse_text_attributes(p, os, FLAG_ITEM, outer,
3975 context, "\\series", context.font.series,
3976 known_coded_font_series[where - known_text_font_series]);
3980 // beamer has a \textit<overlay>{} inset
3981 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3982 parse_text_attributes(p, os, FLAG_ITEM, outer,
3983 context, "\\shape", context.font.shape,
3984 known_coded_font_shapes[where - known_text_font_shapes]);
3988 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3989 context.check_layout(os);
3990 TeXFont oldFont = context.font;
3991 context.font.init();
3992 context.font.size = oldFont.size;
3993 os << "\n\\family " << context.font.family << "\n";
3994 os << "\n\\series " << context.font.series << "\n";
3995 os << "\n\\shape " << context.font.shape << "\n";
3996 if (t.cs() == "textnormal") {
3997 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3998 output_font_change(os, context.font, oldFont);
3999 context.font = oldFont;
4001 eat_whitespace(p, os, context, false);
4005 if (t.cs() == "textcolor") {
4006 // scheme is \textcolor{color name}{text}
4007 string const color = p.verbatim_item();
4008 // we support the predefined colors of the color and the xcolor package
4009 if (color == "black" || color == "blue" || color == "cyan"
4010 || color == "green" || color == "magenta" || color == "red"
4011 || color == "white" || color == "yellow") {
4012 context.check_layout(os);
4013 os << "\n\\color " << color << "\n";
4014 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4015 context.check_layout(os);
4016 os << "\n\\color inherit\n";
4017 preamble.registerAutomaticallyLoadedPackage("color");
4018 } else if (color == "brown" || color == "darkgray" || color == "gray"
4019 || color == "lightgray" || color == "lime" || color == "olive"
4020 || color == "orange" || color == "pink" || color == "purple"
4021 || color == "teal" || color == "violet") {
4022 context.check_layout(os);
4023 os << "\n\\color " << color << "\n";
4024 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4025 context.check_layout(os);
4026 os << "\n\\color inherit\n";
4027 preamble.registerAutomaticallyLoadedPackage("xcolor");
4029 // for custom defined colors
4030 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4034 if (t.cs() == "underbar" || t.cs() == "uline") {
4035 // \underbar is not 100% correct (LyX outputs \uline
4036 // of ulem.sty). The difference is that \ulem allows
4037 // line breaks, and \underbar does not.
4038 // Do NOT handle \underline.
4039 // \underbar cuts through y, g, q, p etc.,
4040 // \underline does not.
4041 context.check_layout(os);
4042 os << "\n\\bar under\n";
4043 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4044 context.check_layout(os);
4045 os << "\n\\bar default\n";
4046 preamble.registerAutomaticallyLoadedPackage("ulem");
4050 if (t.cs() == "sout") {
4051 context.check_layout(os);
4052 os << "\n\\strikeout on\n";
4053 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4054 context.check_layout(os);
4055 os << "\n\\strikeout default\n";
4056 preamble.registerAutomaticallyLoadedPackage("ulem");
4060 // beamer has an \emph<overlay>{} inset
4061 if ((t.cs() == "uuline" || t.cs() == "uwave"
4062 || t.cs() == "emph" || t.cs() == "noun"
4063 || t.cs() == "xout") && !p.hasOpt("<")) {
4064 context.check_layout(os);
4065 os << "\n\\" << t.cs() << " on\n";
4066 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4067 context.check_layout(os);
4068 os << "\n\\" << t.cs() << " default\n";
4069 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4070 preamble.registerAutomaticallyLoadedPackage("ulem");
4074 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4075 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4076 context.check_layout(os);
4079 initials = p.getArg('[', ']');
4081 string name = p.getArg('{', '}');
4082 string localtime = p.getArg('{', '}');
4083 preamble.registerAuthor(name, initials);
4084 Author const & author = preamble.getAuthor(name);
4085 // from_asctime_utc() will fail if LyX decides to output the
4086 // time in the text language.
4087 time_t ptime = from_asctime_utc(localtime);
4088 if (ptime == static_cast<time_t>(-1)) {
4089 cerr << "Warning: Could not parse time `" << localtime
4090 << "´ for change tracking, using current time instead.\n";
4091 ptime = current_time();
4093 if (t.cs() == "lyxadded")
4094 os << "\n\\change_inserted ";
4096 os << "\n\\change_deleted ";
4097 os << author.bufferId() << ' ' << ptime << '\n';
4098 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4099 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4100 LaTeXPackages::isAvailable("xcolor");
4101 // No need to test for luatex, since luatex comes in
4102 // two flavours (dvi and pdf), like latex, and those
4103 // are detected by pdflatex.
4104 if (pdflatex || xetex) {
4106 preamble.registerAutomaticallyLoadedPackage("ulem");
4107 preamble.registerAutomaticallyLoadedPackage("xcolor");
4108 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4112 preamble.registerAutomaticallyLoadedPackage("ulem");
4113 preamble.registerAutomaticallyLoadedPackage("xcolor");
4119 if (t.cs() == "textipa") {
4120 context.check_layout(os);
4121 begin_inset(os, "IPA\n");
4122 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4123 context.merging_hyphens_allowed = false;
4124 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4125 context.merging_hyphens_allowed = merging_hyphens_allowed;
4127 preamble.registerAutomaticallyLoadedPackage("tipa");
4128 preamble.registerAutomaticallyLoadedPackage("tipx");
4132 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4133 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4134 context.check_layout(os);
4138 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4139 begin_inset(os, "IPADeco " + type + "\n");
4140 os << "status open\n";
4141 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4147 if (t.cs() == "textvertline") {
4148 // FIXME: This is not correct, \textvertline is higher than |
4154 if (t.cs() == "tone" ) {
4155 context.check_layout(os);
4156 // register the tone package
4157 preamble.registerAutomaticallyLoadedPackage("tone");
4158 string content = trimSpaceAndEol(p.verbatim_item());
4159 string command = t.asInput() + "{" + content + "}";
4160 // some tones can be detected by unicodesymbols, some need special code
4161 if (is_known(content, known_tones)) {
4162 os << "\\IPAChar " << command << "\n";
4165 // try to see whether the string is in unicodesymbols
4169 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4170 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4171 termination, rem, &req);
4175 output_ert_inset(os, to_utf8(rem), context);
4176 for (set<string>::const_iterator it = req.begin();
4177 it != req.end(); ++it)
4178 preamble.registerAutomaticallyLoadedPackage(*it);
4180 // we did not find a non-ert version
4181 output_ert_inset(os, command, context);
4185 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4186 t.cs() == "vphantom") {
4187 context.check_layout(os);
4188 if (t.cs() == "phantom")
4189 begin_inset(os, "Phantom Phantom\n");
4190 if (t.cs() == "hphantom")
4191 begin_inset(os, "Phantom HPhantom\n");
4192 if (t.cs() == "vphantom")
4193 begin_inset(os, "Phantom VPhantom\n");
4194 os << "status open\n";
4195 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4201 if (t.cs() == "href") {
4202 context.check_layout(os);
4203 string target = convert_literate_command_inset_arg(p.verbatim_item());
4204 string name = p.verbatim_item();
4205 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4206 bool const literal = !nm.first;
4207 name = literal ? subst(name, "\n", " ") : nm.second;
4208 string lit = literal ? "\"true\"" : "\"false\"";
4210 size_t i = target.find(':');
4211 if (i != string::npos) {
4212 type = target.substr(0, i + 1);
4213 if (type == "mailto:" || type == "file:")
4214 target = target.substr(i + 1);
4215 // handle the case that name is equal to target, except of "http(s)://"
4216 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4219 begin_command_inset(os, "href", "href");
4221 os << "name \"" << name << "\"\n";
4222 os << "target \"" << target << "\"\n";
4223 if (type == "mailto:" || type == "file:")
4224 os << "type \"" << type << "\"\n";
4225 os << "literal " << lit << "\n";
4227 skip_spaces_braces(p);
4231 if (t.cs() == "lyxline") {
4232 // swallow size argument (it is not used anyway)
4234 if (!context.atParagraphStart()) {
4235 // so our line is in the middle of a paragraph
4236 // we need to add a new line, lest this line
4237 // follow the other content on that line and
4238 // run off the side of the page
4239 // FIXME: This may create an empty paragraph,
4240 // but without that it would not be
4241 // possible to set noindent below.
4242 // Fortunately LaTeX does not care
4243 // about the empty paragraph.
4244 context.new_paragraph(os);
4246 if (preamble.indentParagraphs()) {
4247 // we need to unindent, lest the line be too long
4248 context.add_par_extra_stuff("\\noindent\n");
4250 context.check_layout(os);
4251 begin_command_inset(os, "line", "rule");
4252 os << "offset \"0.5ex\"\n"
4253 "width \"100line%\"\n"
4259 if (t.cs() == "rule") {
4260 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4261 string const width = p.getArg('{', '}');
4262 string const thickness = p.getArg('{', '}');
4263 context.check_layout(os);
4264 begin_command_inset(os, "line", "rule");
4265 if (!offset.empty())
4266 os << "offset \"" << translate_len(offset) << "\"\n";
4267 os << "width \"" << translate_len(width) << "\"\n"
4268 "height \"" << translate_len(thickness) << "\"\n";
4273 // Handle refstyle first in order to to catch \eqref, because this
4274 // can also occur without refstyle. Only recognize these commands if
4275 // refstyle.sty was found in the preamble (otherwise \eqref
4276 // and user defined ref commands could be misdetected).
4277 // We uncapitalize the input in order to catch capitalized commands
4279 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4280 && preamble.refstyle()) {
4281 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4282 string plural = "false";
4283 // Catch the plural option [s]
4285 string const opt = p.getOpt();
4289 // LyX does not yet support other optional arguments of ref commands
4290 output_ert_inset(os, t.asInput() + opt + "{" +
4291 p.verbatim_item() + '}', context);
4295 context.check_layout(os);
4296 begin_command_inset(os, "ref", "formatted");
4297 os << "reference \"";
4298 os << known_refstyle_prefixes[where - known_refstyle_commands]
4300 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4302 os << "plural \"" << plural << "\"\n";
4303 os << "caps \"" << cap << "\"\n";
4304 os << "noprefix \"false\"\n";
4306 preamble.registerAutomaticallyLoadedPackage("refstyle");
4310 // if refstyle is used, we must not convert \prettyref to a
4311 // formatted reference, since that would result in a refstyle command.
4312 if ((where = is_known(t.cs(), known_ref_commands)) &&
4313 (t.cs() != "prettyref" || !preamble.refstyle())) {
4314 string const opt = p.getOpt();
4316 context.check_layout(os);
4317 begin_command_inset(os, "ref",
4318 known_coded_ref_commands[where - known_ref_commands]);
4319 os << "reference \""
4320 << convert_literate_command_inset_arg(p.verbatim_item())
4322 os << "plural \"false\"\n";
4323 os << "caps \"false\"\n";
4324 os << "noprefix \"false\"\n";
4326 if (t.cs() == "vref" || t.cs() == "vpageref")
4327 preamble.registerAutomaticallyLoadedPackage("varioref");
4328 else if (t.cs() == "prettyref")
4329 preamble.registerAutomaticallyLoadedPackage("prettyref");
4331 // LyX does not yet support optional arguments of ref commands
4332 output_ert_inset(os, t.asInput() + opt + "{" +
4333 p.verbatim_item() + '}', context);
4339 is_known(t.cs(), known_natbib_commands) &&
4340 ((t.cs() != "citefullauthor" &&
4341 t.cs() != "citeyear" &&
4342 t.cs() != "citeyearpar") ||
4343 p.next_token().asInput() != "*")) {
4344 context.check_layout(os);
4345 string command = t.cs();
4346 if (p.next_token().asInput() == "*") {
4350 if (command == "citefullauthor")
4351 // alternative name for "\\citeauthor*"
4352 command = "citeauthor*";
4354 // text before the citation
4356 // text after the citation
4358 get_cite_arguments(p, true, before, after);
4360 if (command == "cite") {
4361 // \cite without optional argument means
4362 // \citet, \cite with at least one optional
4363 // argument means \citep.
4364 if (before.empty() && after.empty())
4369 if (before.empty() && after == "[]")
4370 // avoid \citet[]{a}
4372 else if (before == "[]" && after == "[]") {
4373 // avoid \citet[][]{a}
4377 bool literal = false;
4378 pair<bool, string> aft;
4379 pair<bool, string> bef;
4380 // remove the brackets around after and before
4381 if (!after.empty()) {
4383 after.erase(after.length() - 1, 1);
4384 aft = convert_latexed_command_inset_arg(after);
4385 literal = !aft.first;
4386 after = literal ? subst(after, "\n", " ") : aft.second;
4388 if (!before.empty()) {
4390 before.erase(before.length() - 1, 1);
4391 bef = convert_latexed_command_inset_arg(before);
4392 literal |= !bef.first;
4393 before = literal ? subst(before, "\n", " ") : bef.second;
4394 if (literal && !after.empty())
4395 after = subst(after, "\n", " ");
4397 string lit = literal ? "\"true\"" : "\"false\"";
4398 begin_command_inset(os, "citation", command);
4399 os << "after " << '"' << after << '"' << "\n";
4400 os << "before " << '"' << before << '"' << "\n";
4402 << convert_literate_command_inset_arg(p.verbatim_item())
4404 << "literal " << lit << "\n";
4406 // Need to set the cite engine if natbib is loaded by
4407 // the document class directly
4408 if (preamble.citeEngine() == "basic")
4409 preamble.citeEngine("natbib");
4414 && is_known(t.cs(), known_biblatex_commands)
4415 && ((t.cs() == "cite"
4416 || t.cs() == "citeauthor"
4417 || t.cs() == "Citeauthor"
4418 || t.cs() == "parencite"
4419 || t.cs() == "citetitle")
4420 || p.next_token().asInput() != "*"))
4421 || (use_biblatex_natbib
4422 && (is_known(t.cs(), known_biblatex_commands)
4423 || is_known(t.cs(), known_natbib_commands))
4424 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4425 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4426 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4427 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4428 || t.cs() == "parencite" || t.cs() == "citetitle")
4429 || p.next_token().asInput() != "*"))){
4430 context.check_layout(os);
4431 string command = t.cs();
4432 if (p.next_token().asInput() == "*") {
4437 bool const qualified = suffixIs(command, "s");
4439 command = rtrim(command, "s");
4441 // text before the citation
4443 // text after the citation
4445 get_cite_arguments(p, true, before, after, qualified);
4447 // These use natbib cmd names in LyX
4448 // for inter-citeengine compativility
4449 if (command == "citeyear")
4450 command = "citebyear";
4451 else if (command == "cite*")
4452 command = "citeyear";
4453 else if (command == "textcite")
4455 else if (command == "Textcite")
4457 else if (command == "parencite")
4459 else if (command == "Parencite")
4461 else if (command == "parencite*")
4462 command = "citeyearpar";
4463 else if (command == "smartcite")
4464 command = "footcite";
4465 else if (command == "Smartcite")
4466 command = "Footcite";
4468 string const emptyarg = qualified ? "()" : "[]";
4469 if (before.empty() && after == emptyarg)
4472 else if (before == emptyarg && after == emptyarg) {
4473 // avoid \cite[][]{a}
4477 bool literal = false;
4478 pair<bool, string> aft;
4479 pair<bool, string> bef;
4480 // remove the brackets around after and before
4481 if (!after.empty()) {
4483 after.erase(after.length() - 1, 1);
4484 aft = convert_latexed_command_inset_arg(after);
4485 literal = !aft.first;
4486 after = literal ? subst(after, "\n", " ") : aft.second;
4488 if (!before.empty()) {
4490 before.erase(before.length() - 1, 1);
4491 bef = convert_latexed_command_inset_arg(before);
4492 literal |= !bef.first;
4493 before = literal ? subst(before, "\n", " ") : bef.second;
4495 string keys, pretextlist, posttextlist;
4497 vector<pair<string, string>> pres, posts, preslit, postslit;
4498 vector<string> lkeys;
4499 // text before the citation
4500 string lbefore, lbeforelit;
4501 // text after the citation
4502 string lafter, lafterlit;
4504 pair<bool, string> laft, lbef;
4506 get_cite_arguments(p, true, lbefore, lafter);
4507 // remove the brackets around after and before
4508 if (!lafter.empty()) {
4510 lafter.erase(lafter.length() - 1, 1);
4511 laft = convert_latexed_command_inset_arg(lafter);
4512 literal |= !laft.first;
4513 lafter = laft.second;
4514 lafterlit = subst(lafter, "\n", " ");
4516 if (!lbefore.empty()) {
4517 lbefore.erase(0, 1);
4518 lbefore.erase(lbefore.length() - 1, 1);
4519 lbef = convert_latexed_command_inset_arg(lbefore);
4520 literal |= !lbef.first;
4521 lbefore = lbef.second;
4522 lbeforelit = subst(lbefore, "\n", " ");
4524 if (lbefore.empty() && lafter == "[]") {
4529 else if (lbefore == "[]" && lafter == "[]") {
4530 // avoid \cite[][]{a}
4536 lkey = p.getArg('{', '}');
4539 pres.push_back(make_pair(lkey, lbefore));
4540 preslit.push_back(make_pair(lkey, lbeforelit));
4541 posts.push_back(make_pair(lkey, lafter));
4542 postslit.push_back(make_pair(lkey, lafterlit));
4543 lkeys.push_back(lkey);
4545 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4550 for (auto const & ptl : pres) {
4551 if (!pretextlist.empty())
4552 pretextlist += '\t';
4553 pretextlist += ptl.first;
4554 if (!ptl.second.empty())
4555 pretextlist += " " + ptl.second;
4557 for (auto const & potl : posts) {
4558 if (!posttextlist.empty())
4559 posttextlist += '\t';
4560 posttextlist += potl.first;
4561 if (!potl.second.empty())
4562 posttextlist += " " + potl.second;
4565 keys = convert_literate_command_inset_arg(p.verbatim_item());
4568 after = subst(after, "\n", " ");
4569 if (!before.empty())
4570 before = subst(after, "\n", " ");
4572 string lit = literal ? "\"true\"" : "\"false\"";
4573 begin_command_inset(os, "citation", command);
4574 os << "after " << '"' << after << '"' << "\n";
4575 os << "before " << '"' << before << '"' << "\n";
4579 if (!pretextlist.empty())
4580 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4581 if (!posttextlist.empty())
4582 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4583 os << "literal " << lit << "\n";
4585 // Need to set the cite engine if biblatex is loaded by
4586 // the document class directly
4587 if (preamble.citeEngine() == "basic")
4588 use_biblatex_natbib ?
4589 preamble.citeEngine("biblatex-natbib")
4590 : preamble.citeEngine("biblatex");
4595 is_known(t.cs(), known_jurabib_commands) &&
4596 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4597 context.check_layout(os);
4598 string command = t.cs();
4599 if (p.next_token().asInput() == "*") {
4603 char argumentOrder = '\0';
4604 vector<string> const options =
4605 preamble.getPackageOptions("jurabib");
4606 if (find(options.begin(), options.end(),
4607 "natbiborder") != options.end())
4608 argumentOrder = 'n';
4609 else if (find(options.begin(), options.end(),
4610 "jurabiborder") != options.end())
4611 argumentOrder = 'j';
4613 // text before the citation
4615 // text after the citation
4617 get_cite_arguments(p, argumentOrder != 'j', before, after);
4619 string const citation = p.verbatim_item();
4620 if (!before.empty() && argumentOrder == '\0') {
4621 cerr << "Warning: Assuming argument order "
4622 "of jurabib version 0.6 for\n'"
4623 << command << before << after << '{'
4624 << citation << "}'.\n"
4625 "Add 'jurabiborder' to the jurabib "
4626 "package options if you used an\n"
4627 "earlier jurabib version." << endl;
4629 bool literal = false;
4630 pair<bool, string> aft;
4631 pair<bool, string> bef;
4632 // remove the brackets around after and before
4633 if (!after.empty()) {
4635 after.erase(after.length() - 1, 1);
4636 aft = convert_latexed_command_inset_arg(after);
4637 literal = !aft.first;
4638 after = literal ? subst(after, "\n", " ") : aft.second;
4640 if (!before.empty()) {
4642 before.erase(before.length() - 1, 1);
4643 bef = convert_latexed_command_inset_arg(before);
4644 literal |= !bef.first;
4645 before = literal ? subst(before, "\n", " ") : bef.second;
4646 if (literal && !after.empty())
4647 after = subst(after, "\n", " ");
4649 string lit = literal ? "\"true\"" : "\"false\"";
4650 begin_command_inset(os, "citation", command);
4651 os << "after " << '"' << after << "\"\n"
4652 << "before " << '"' << before << "\"\n"
4653 << "key " << '"' << citation << "\"\n"
4654 << "literal " << lit << "\n";
4656 // Need to set the cite engine if jurabib is loaded by
4657 // the document class directly
4658 if (preamble.citeEngine() == "basic")
4659 preamble.citeEngine("jurabib");
4663 if (t.cs() == "cite"
4664 || t.cs() == "nocite") {
4665 context.check_layout(os);
4666 string after = p.getArg('[', ']');
4667 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4668 bool const literal = !aft.first;
4669 after = literal ? subst(after, "\n", " ") : aft.second;
4670 string lit = literal ? "\"true\"" : "\"false\"";
4671 string key = convert_literate_command_inset_arg(p.verbatim_item());
4672 // store the case that it is "\nocite{*}" to use it later for
4675 begin_command_inset(os, "citation", t.cs());
4676 os << "after " << '"' << after << "\"\n"
4677 << "key " << '"' << key << "\"\n"
4678 << "literal " << lit << "\n";
4680 } else if (t.cs() == "nocite")
4685 if (t.cs() == "index" ||
4686 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4687 context.check_layout(os);
4688 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4689 p.getArg('[', ']') : "";
4690 string const kind = arg.empty() ? "idx" : arg;
4691 begin_inset(os, "Index ");
4692 os << kind << "\nstatus collapsed\n";
4693 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4696 preamble.registerAutomaticallyLoadedPackage("splitidx");
4700 if (t.cs() == "nomenclature") {
4701 context.check_layout(os);
4702 begin_command_inset(os, "nomenclature", "nomenclature");
4703 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4704 if (!prefix.empty())
4705 os << "prefix " << '"' << prefix << '"' << "\n";
4706 string symbol = p.verbatim_item();
4707 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4708 bool literal = !sym.first;
4709 string description = p.verbatim_item();
4710 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4711 literal |= !desc.first;
4713 symbol = subst(symbol, "\n", " ");
4714 description = subst(description, "\n", " ");
4716 symbol = sym.second;
4717 description = desc.second;
4719 string lit = literal ? "\"true\"" : "\"false\"";
4720 os << "symbol " << '"' << symbol;
4721 os << "\"\ndescription \""
4722 << description << "\"\n"
4723 << "literal " << lit << "\n";
4725 preamble.registerAutomaticallyLoadedPackage("nomencl");
4729 if (t.cs() == "label") {
4730 context.check_layout(os);
4731 begin_command_inset(os, "label", "label");
4733 << convert_literate_command_inset_arg(p.verbatim_item())
4739 if (t.cs() == "lyxmintcaption") {
4740 string const pos = p.getArg('[', ']');
4742 string const caption =
4743 parse_text_snippet(p, FLAG_ITEM, false,
4745 minted_nonfloat_caption = "[t]" + caption;
4747 // We already got the caption at the bottom,
4748 // so simply skip it.
4749 parse_text_snippet(p, FLAG_ITEM, false, context);
4751 eat_whitespace(p, os, context, true);
4755 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4756 context.check_layout(os);
4757 string commandname = t.cs();
4759 if (p.next_token().asInput() == "*") {
4764 begin_command_inset(os, "index_print", commandname);
4765 string const indexname = p.getArg('[', ']');
4767 if (indexname.empty())
4768 os << "type \"idx\"\n";
4770 os << "type \"" << indexname << "\"\n";
4771 os << "literal \"true\"\n";
4774 skip_spaces_braces(p);
4775 preamble.registerAutomaticallyLoadedPackage("makeidx");
4776 if (preamble.use_indices() == "true")
4777 preamble.registerAutomaticallyLoadedPackage("splitidx");
4781 if (t.cs() == "printnomenclature") {
4783 string width_type = "";
4784 context.check_layout(os);
4785 begin_command_inset(os, "nomencl_print", "printnomenclature");
4786 // case of a custom width
4788 width = p.getArg('[', ']');
4789 width = translate_len(width);
4790 width_type = "custom";
4792 // case of no custom width
4793 // the case of no custom width but the width set
4794 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4795 // because the user could have set anything, not only the width
4796 // of the longest label (which would be width_type = "auto")
4797 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4798 if (label.empty() && width_type.empty())
4799 width_type = "none";
4800 os << "set_width \"" << width_type << "\"\n";
4801 if (width_type == "custom")
4802 os << "width \"" << width << '\"';
4804 skip_spaces_braces(p);
4805 preamble.registerAutomaticallyLoadedPackage("nomencl");
4809 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4810 context.check_layout(os);
4811 begin_inset(os, "script ");
4812 os << t.cs().substr(4) << '\n';
4813 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4814 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4816 if (t.cs() == "textsubscript")
4817 preamble.registerAutomaticallyLoadedPackage("subscript");
4821 if ((where = is_known(t.cs(), known_quotes))) {
4822 context.check_layout(os);
4823 begin_inset(os, "Quotes ");
4824 string quotetype = known_coded_quotes[where - known_quotes];
4825 // try to make a smart guess about the side
4826 Token const prev = p.prev_token();
4827 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4828 && prev.character() != '\n' && prev.character() != '~');
4829 quotetype = guessQuoteStyle(quotetype, opening);
4832 // LyX adds {} after the quote, so we have to eat
4833 // spaces here if there are any before a possible
4835 eat_whitespace(p, os, context, false);
4840 if ((where = is_known(t.cs(), known_sizes)) &&
4841 context.new_layout_allowed) {
4842 context.check_layout(os);
4843 TeXFont const oldFont = context.font;
4844 context.font.size = known_coded_sizes[where - known_sizes];
4845 output_font_change(os, oldFont, context.font);
4846 eat_whitespace(p, os, context, false);
4850 if ((where = is_known(t.cs(), known_font_families)) &&
4851 context.new_layout_allowed) {
4852 context.check_layout(os);
4853 TeXFont const oldFont = context.font;
4854 context.font.family =
4855 known_coded_font_families[where - known_font_families];
4856 output_font_change(os, oldFont, context.font);
4857 eat_whitespace(p, os, context, false);
4861 if ((where = is_known(t.cs(), known_font_series)) &&
4862 context.new_layout_allowed) {
4863 context.check_layout(os);
4864 TeXFont const oldFont = context.font;
4865 context.font.series =
4866 known_coded_font_series[where - known_font_series];
4867 output_font_change(os, oldFont, context.font);
4868 eat_whitespace(p, os, context, false);
4872 if ((where = is_known(t.cs(), known_font_shapes)) &&
4873 context.new_layout_allowed) {
4874 context.check_layout(os);
4875 TeXFont const oldFont = context.font;
4876 context.font.shape =
4877 known_coded_font_shapes[where - known_font_shapes];
4878 output_font_change(os, oldFont, context.font);
4879 eat_whitespace(p, os, context, false);
4882 if ((where = is_known(t.cs(), known_old_font_families)) &&
4883 context.new_layout_allowed) {
4884 context.check_layout(os);
4885 TeXFont const oldFont = context.font;
4886 context.font.init();
4887 context.font.size = oldFont.size;
4888 context.font.family =
4889 known_coded_font_families[where - known_old_font_families];
4890 output_font_change(os, oldFont, context.font);
4891 eat_whitespace(p, os, context, false);
4895 if ((where = is_known(t.cs(), known_old_font_series)) &&
4896 context.new_layout_allowed) {
4897 context.check_layout(os);
4898 TeXFont const oldFont = context.font;
4899 context.font.init();
4900 context.font.size = oldFont.size;
4901 context.font.series =
4902 known_coded_font_series[where - known_old_font_series];
4903 output_font_change(os, oldFont, context.font);
4904 eat_whitespace(p, os, context, false);
4908 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4909 context.new_layout_allowed) {
4910 context.check_layout(os);
4911 TeXFont const oldFont = context.font;
4912 context.font.init();
4913 context.font.size = oldFont.size;
4914 context.font.shape =
4915 known_coded_font_shapes[where - known_old_font_shapes];
4916 output_font_change(os, oldFont, context.font);
4917 eat_whitespace(p, os, context, false);
4921 if (t.cs() == "selectlanguage") {
4922 context.check_layout(os);
4923 // save the language for the case that a
4924 // \foreignlanguage is used
4925 context.font.language = babel2lyx(p.verbatim_item());
4926 os << "\n\\lang " << context.font.language << "\n";
4930 if (t.cs() == "foreignlanguage") {
4931 string const lang = babel2lyx(p.verbatim_item());
4932 parse_text_attributes(p, os, FLAG_ITEM, outer,
4934 context.font.language, lang);
4938 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4939 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4940 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4942 // We have to output the whole command if it has an option
4943 // because LyX doesn't support this yet, see bug #8214,
4944 // only if there is a single option specifying a variant, we can handle it.
4946 string langopts = p.getOpt();
4947 // check if the option contains a variant, if yes, extract it
4948 string::size_type pos_var = langopts.find("variant");
4949 string::size_type i = langopts.find(',');
4950 string::size_type k = langopts.find('=', pos_var);
4951 if (pos_var != string::npos && i == string::npos) {
4953 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4954 lang = preamble.polyglossia2lyx(variant);
4955 parse_text_attributes(p, os, FLAG_ITEM, outer,
4957 context.font.language, lang);
4959 output_ert_inset(os, t.asInput() + langopts, context);
4961 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4962 parse_text_attributes(p, os, FLAG_ITEM, outer,
4964 context.font.language, lang);
4969 if (t.cs() == "inputencoding") {
4970 // nothing to write here
4971 string const enc = subst(p.verbatim_item(), "\n", " ");
4972 p.setEncoding(enc, Encoding::inputenc);
4976 if (is_known(t.cs(), known_special_chars) ||
4977 (t.cs() == "protect" &&
4978 p.next_token().cat() == catEscape &&
4979 is_known(p.next_token().cs(), known_special_protect_chars))) {
4980 // LyX sometimes puts a \protect in front, so we have to ignore it
4982 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4983 known_special_chars);
4984 context.check_layout(os);
4985 os << known_coded_special_chars[where - known_special_chars];
4986 skip_spaces_braces(p);
4990 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4991 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4992 p.next_next_token().asInput() == "-") ||
4993 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4994 // LyX sometimes puts a \protect in front, so we have to ignore it
4995 if (t.cs() == "protect")
4997 context.check_layout(os);
4998 if (t.cs() == "nobreakdash")
4999 os << "\\SpecialChar nobreakdash\n";
5001 os << "\\SpecialChar endofsentence\n";
5006 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5007 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5008 || t.cs() == "%" || t.cs() == "-") {
5009 context.check_layout(os);
5011 os << "\\SpecialChar softhyphen\n";
5017 if (t.cs() == "char") {
5018 context.check_layout(os);
5019 if (p.next_token().character() == '`') {
5021 if (p.next_token().cs() == "\"") {
5026 output_ert_inset(os, "\\char`", context);
5029 output_ert_inset(os, "\\char", context);
5034 if (t.cs() == "verb") {
5035 context.check_layout(os);
5036 // set catcodes to verbatim early, just in case.
5037 p.setCatcodes(VERBATIM_CATCODES);
5038 string delim = p.get_token().asInput();
5039 Parser::Arg arg = p.verbatimStuff(delim);
5041 output_ert_inset(os, "\\verb" + delim
5042 + arg.second + delim, context);
5044 cerr << "invalid \\verb command. Skipping" << endl;
5048 // Problem: \= creates a tabstop inside the tabbing environment
5049 // and else an accent. In the latter case we really would want
5050 // \={o} instead of \= o.
5051 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5052 output_ert_inset(os, t.asInput(), context);
5056 if (t.cs() == "\\") {
5057 context.check_layout(os);
5059 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5060 else if (p.next_token().asInput() == "*") {
5062 // getOpt() eats the following space if there
5063 // is no optional argument, but that is OK
5064 // here since it has no effect in the output.
5065 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5068 begin_inset(os, "Newline newline");
5074 if (t.cs() == "newline" ||
5075 (t.cs() == "linebreak" && !p.hasOpt())) {
5076 context.check_layout(os);
5077 begin_inset(os, "Newline ");
5080 skip_spaces_braces(p);
5084 if (t.cs() == "input" || t.cs() == "include"
5085 || t.cs() == "verbatiminput"
5086 || t.cs() == "lstinputlisting"
5087 || t.cs() == "inputminted") {
5088 string name = t.cs();
5089 if (name == "verbatiminput"
5090 && p.next_token().asInput() == "*")
5091 name += p.get_token().asInput();
5092 context.check_layout(os);
5094 bool literal = false;
5095 if (name == "lstinputlisting" && p.hasOpt()) {
5096 lstparams = p.getArg('[', ']');
5097 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5098 literal = !oa.first;
5100 lstparams = subst(lstparams, "\n", " ");
5102 lstparams = oa.second;
5103 } else if (name == "inputminted") {
5104 name = "lstinputlisting";
5105 string const lang = p.getArg('{', '}');
5106 if (lang != "tex") {
5107 string cmd = "\\inputminted{" + lang + "}{";
5108 cmd += p.getArg('{', '}') + "}";
5109 output_ert_inset(os, cmd, context);
5112 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5113 minted_nonfloat_caption.erase(0,3);
5114 // extract label and caption from the already produced LyX code
5115 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5116 string const caption = nfc.front();
5118 vector<string>::iterator it =
5119 find(nfc.begin(), nfc.end(), "LatexCommand label");
5120 if (it != nfc.end()) {
5122 if (it != nfc.end())
5124 label = support::split(label, '"');
5127 minted_nonfloat_caption.clear();
5128 lstparams = "caption=" + caption;
5130 lstparams += ",label=" + label;
5131 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5132 literal = !oa.first;
5134 lstparams = subst(lstparams, "\n", " ");
5136 lstparams = oa.second;
5139 string lit = literal ? "\"true\"" : "\"false\"";
5140 string filename(normalize_filename(p.getArg('{', '}')));
5141 string const path = getMasterFilePath(true);
5142 // We want to preserve relative / absolute filenames,
5143 // therefore path is only used for testing
5144 if ((t.cs() == "include" || t.cs() == "input") &&
5145 !makeAbsPath(filename, path).exists()) {
5146 // The file extension is probably missing.
5147 // Now try to find it out.
5148 string const tex_name =
5149 find_file(filename, path,
5150 known_tex_extensions);
5151 if (!tex_name.empty())
5152 filename = tex_name;
5154 bool external = false;
5156 if (makeAbsPath(filename, path).exists()) {
5157 string const abstexname =
5158 makeAbsPath(filename, path).absFileName();
5159 string const absfigname =
5160 changeExtension(abstexname, ".fig");
5161 fix_child_filename(filename);
5162 string const lyxname = changeExtension(filename,
5163 roundtripMode() ? ".lyx.lyx" : ".lyx");
5164 string const abslyxname = makeAbsPath(
5165 lyxname, getParentFilePath(false)).absFileName();
5167 if (!skipChildren())
5168 external = FileName(absfigname).exists();
5169 if (t.cs() == "input" && !skipChildren()) {
5170 string const ext = getExtension(abstexname);
5172 // Combined PS/LaTeX:
5173 // x.eps, x.pstex_t (old xfig)
5174 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5175 FileName const absepsname(
5176 changeExtension(abstexname, ".eps"));
5177 FileName const abspstexname(
5178 changeExtension(abstexname, ".pstex"));
5179 bool const xfigeps =
5180 (absepsname.exists() ||
5181 abspstexname.exists()) &&
5184 // Combined PDF/LaTeX:
5185 // x.pdf, x.pdftex_t (old xfig)
5186 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5187 FileName const abspdfname(
5188 changeExtension(abstexname, ".pdf"));
5189 bool const xfigpdf =
5190 abspdfname.exists() &&
5191 (ext == "pdftex_t" || ext == "pdf_t");
5195 // Combined PS/PDF/LaTeX:
5196 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5197 string const absbase2(
5198 removeExtension(abstexname) + "_pspdftex");
5199 FileName const abseps2name(
5200 addExtension(absbase2, ".eps"));
5201 FileName const abspdf2name(
5202 addExtension(absbase2, ".pdf"));
5203 bool const xfigboth =
5204 abspdf2name.exists() &&
5205 abseps2name.exists() && ext == "pspdftex";
5207 xfig = xfigpdf || xfigeps || xfigboth;
5208 external = external && xfig;
5211 outname = changeExtension(filename, ".fig");
5212 FileName abssrc(changeExtension(abstexname, ".fig"));
5213 copy_file(abssrc, outname);
5215 // Don't try to convert, the result
5216 // would be full of ERT.
5218 FileName abssrc(abstexname);
5219 copy_file(abssrc, outname);
5220 } else if (t.cs() != "verbatiminput" &&
5222 tex2lyx(abstexname, FileName(abslyxname),
5225 // no need to call copy_file
5226 // tex2lyx creates the file
5229 FileName abssrc(abstexname);
5230 copy_file(abssrc, outname);
5233 cerr << "Warning: Could not find included file '"
5234 << filename << "'." << endl;
5238 begin_inset(os, "External\n");
5239 os << "\ttemplate XFig\n"
5240 << "\tfilename " << outname << '\n';
5241 registerExternalTemplatePackages("XFig");
5243 begin_command_inset(os, "include", name);
5244 outname = subst(outname, "\"", "\\\"");
5245 os << "preview false\n"
5246 "filename \"" << outname << "\"\n";
5247 if (!lstparams.empty())
5248 os << "lstparams \"" << lstparams << "\"\n";
5249 os << "literal " << lit << "\n";
5250 if (t.cs() == "verbatiminput")
5251 preamble.registerAutomaticallyLoadedPackage("verbatim");
5257 if (t.cs() == "bibliographystyle") {
5258 // store new bibliographystyle
5259 bibliographystyle = p.verbatim_item();
5260 // If any other command than \bibliography, \addcontentsline
5261 // and \nocite{*} follows, we need to output the style
5262 // (because it might be used by that command).
5263 // Otherwise, it will automatically be output by LyX.
5266 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5267 if (t2.cat() == catBegin)
5269 if (t2.cat() != catEscape)
5271 if (t2.cs() == "nocite") {
5272 if (p.getArg('{', '}') == "*")
5274 } else if (t2.cs() == "bibliography")
5276 else if (t2.cs() == "phantomsection") {
5280 else if (t2.cs() == "addcontentsline") {
5281 // get the 3 arguments of \addcontentsline
5284 contentslineContent = p.getArg('{', '}');
5285 // if the last argument is not \refname we must output
5286 if (contentslineContent == "\\refname")
5293 output_ert_inset(os,
5294 "\\bibliographystyle{" + bibliographystyle + '}',
5300 if (t.cs() == "phantomsection") {
5301 // we only support this if it occurs between
5302 // \bibliographystyle and \bibliography
5303 if (bibliographystyle.empty())
5304 output_ert_inset(os, "\\phantomsection", context);
5308 if (t.cs() == "addcontentsline") {
5309 context.check_layout(os);
5310 // get the 3 arguments of \addcontentsline
5311 string const one = p.getArg('{', '}');
5312 string const two = p.getArg('{', '}');
5313 string const three = p.getArg('{', '}');
5314 // only if it is a \refname, we support if for the bibtex inset
5315 if (contentslineContent != "\\refname") {
5316 output_ert_inset(os,
5317 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5323 else if (t.cs() == "bibliography") {
5324 context.check_layout(os);
5326 begin_command_inset(os, "bibtex", "bibtex");
5327 if (!btprint.empty()) {
5328 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5329 // clear the string because the next BibTeX inset can be without the
5330 // \nocite{*} option
5333 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5334 // Do we have addcontentsline?
5335 if (contentslineContent == "\\refname") {
5336 BibOpts = "bibtotoc";
5337 // clear string because next BibTeX inset can be without addcontentsline
5338 contentslineContent.clear();
5340 // Do we have a bibliographystyle set?
5341 if (!bibliographystyle.empty()) {
5342 if (BibOpts.empty())
5343 BibOpts = normalize_filename(bibliographystyle);
5345 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5346 // clear it because each bibtex entry has its style
5347 // and we need an empty string to handle \phantomsection
5348 bibliographystyle.clear();
5350 os << "options " << '"' << BibOpts << '"' << "\n";
5351 if (p.getEncoding() != preamble.docencoding) {
5352 Encoding const * const enc = encodings.fromIconvName(
5353 p.getEncoding(), Encoding::inputenc, true);
5355 cerr << "Unknown bib encoding " << p.getEncoding()
5356 << ". Ignoring." << std::endl;
5358 os << "encoding " << '"' << enc->name() << '"' << "\n";
5364 if (t.cs() == "printbibliography") {
5365 context.check_layout(os);
5367 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5368 vector<string> opts = getVectorFromString(bbloptions);
5369 vector<string>::iterator it =
5370 find(opts.begin(), opts.end(), "heading=bibintoc");
5371 if (it != opts.end()) {
5373 BibOpts = "bibtotoc";
5375 bbloptions = getStringFromVector(opts);
5376 begin_command_inset(os, "bibtex", "bibtex");
5377 if (!btprint.empty()) {
5378 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5379 // clear the string because the next BibTeX inset can be without the
5380 // \nocite{*} option
5384 for (auto const & bf : preamble.biblatex_bibliographies) {
5385 if (!bibfiles.empty())
5387 bibfiles += normalize_filename(bf);
5389 if (!bibfiles.empty())
5390 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5391 // Do we have addcontentsline?
5392 if (contentslineContent == "\\refname") {
5393 BibOpts = "bibtotoc";
5394 // clear string because next BibTeX inset can be without addcontentsline
5395 contentslineContent.clear();
5397 os << "options " << '"' << BibOpts << '"' << "\n";
5398 if (!bbloptions.empty())
5399 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5400 if (!preamble.bibencoding.empty()) {
5401 Encoding const * const enc = encodings.fromLaTeXName(
5402 preamble.bibencoding, Encoding::inputenc, true);
5404 cerr << "Unknown bib encoding " << preamble.bibencoding
5405 << ". Ignoring." << std::endl;
5407 os << "encoding " << '"' << enc->name() << '"' << "\n";
5410 for (auto const & bf : preamble.biblatex_encodings) {
5411 if (!bibfileencs.empty())
5412 bibfileencs += "\t";
5415 if (!bibfileencs.empty())
5416 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5418 need_commentbib = false;
5422 if (t.cs() == "bibbysection") {
5423 context.check_layout(os);
5425 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5426 vector<string> opts = getVectorFromString(bbloptions);
5427 vector<string>::iterator it =
5428 find(opts.begin(), opts.end(), "heading=bibintoc");
5429 if (it != opts.end()) {
5431 BibOpts = "bibtotoc";
5433 bbloptions = getStringFromVector(opts);
5434 begin_command_inset(os, "bibtex", "bibtex");
5435 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5437 for (auto const & bf : preamble.biblatex_bibliographies) {
5438 if (!bibfiles.empty())
5440 bibfiles += normalize_filename(bf);
5442 if (!bibfiles.empty())
5443 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5444 os << "options " << '"' << BibOpts << '"' << "\n";
5445 if (!bbloptions.empty())
5446 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5448 need_commentbib = false;
5452 if (t.cs() == "parbox") {
5453 // Test whether this is an outer box of a shaded box
5455 // swallow arguments
5456 while (p.hasOpt()) {
5458 p.skip_spaces(true);
5461 p.skip_spaces(true);
5463 if (p.next_token().cat() == catBegin)
5465 p.skip_spaces(true);
5466 Token to = p.get_token();
5467 bool shaded = false;
5468 if (to.asInput() == "\\begin") {
5469 p.skip_spaces(true);
5470 if (p.getArg('{', '}') == "shaded")
5475 parse_outer_box(p, os, FLAG_ITEM, outer,
5476 context, "parbox", "shaded");
5478 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5479 "", "", t.cs(), "", "");
5483 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5484 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5485 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5486 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5490 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5491 string backgroundcolor;
5492 preamble.registerAutomaticallyLoadedPackage("xcolor");
5493 if (t.cs() == "fcolorbox") {
5494 string const framecolor = p.getArg('{', '}');
5495 backgroundcolor = p.getArg('{', '}');
5496 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5498 backgroundcolor = p.getArg('{', '}');
5499 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5504 // FIXME: due to the compiler limit of "if" nestings
5505 // the code for the alignment was put here
5506 // put them in their own if if this is fixed
5507 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5508 || t.cs() == "shadowsize"
5509 || t.cs() == "raggedleft" || t.cs() == "centering"
5510 || t.cs() == "raggedright") {
5511 if (t.cs() == "fboxrule")
5513 if (t.cs() == "fboxsep")
5515 if (t.cs() == "shadowsize")
5517 if (t.cs() != "raggedleft" && t.cs() != "centering"
5518 && t.cs() != "raggedright") {
5519 p.skip_spaces(true);
5520 while (p.good() && p.next_token().cat() != catSpace
5521 && p.next_token().cat() != catNewline
5522 && p.next_token().cat() != catEscape) {
5523 if (t.cs() == "fboxrule")
5524 fboxrule = fboxrule + p.get_token().asInput();
5525 if (t.cs() == "fboxsep")
5526 fboxsep = fboxsep + p.get_token().asInput();
5527 if (t.cs() == "shadowsize")
5528 shadow_size = shadow_size + p.get_token().asInput();
5531 output_ert_inset(os, t.asInput(), context);
5536 //\framebox() is part of the picture environment and different from \framebox{}
5537 //\framebox{} will be parsed by parse_outer_box
5538 if (t.cs() == "framebox") {
5539 if (p.next_token().character() == '(') {
5540 //the syntax is: \framebox(x,y)[position]{content}
5541 string arg = t.asInput();
5542 arg += p.getFullParentheseArg();
5543 arg += p.getFullOpt();
5544 eat_whitespace(p, os, context, false);
5545 output_ert_inset(os, arg + '{', context);
5546 parse_text(p, os, FLAG_ITEM, outer, context);
5547 output_ert_inset(os, "}", context);
5549 //the syntax is: \framebox[width][position]{content}
5550 string special = p.getFullOpt();
5551 special += p.getOpt();
5552 parse_outer_box(p, os, FLAG_ITEM, outer,
5553 context, t.cs(), special);
5558 //\makebox() is part of the picture environment and different from \makebox{}
5559 //\makebox{} will be parsed by parse_box
5560 if (t.cs() == "makebox") {
5561 if (p.next_token().character() == '(') {
5562 //the syntax is: \makebox(x,y)[position]{content}
5563 string arg = t.asInput();
5564 arg += p.getFullParentheseArg();
5565 arg += p.getFullOpt();
5566 eat_whitespace(p, os, context, false);
5567 output_ert_inset(os, arg + '{', context);
5568 parse_text(p, os, FLAG_ITEM, outer, context);
5569 output_ert_inset(os, "}", context);
5571 //the syntax is: \makebox[width][position]{content}
5572 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5573 "", "", t.cs(), "", "");
5577 if (t.cs() == "smallskip" ||
5578 t.cs() == "medskip" ||
5579 t.cs() == "bigskip" ||
5580 t.cs() == "vfill") {
5581 context.check_layout(os);
5582 begin_inset(os, "VSpace ");
5585 skip_spaces_braces(p);
5589 if ((where = is_known(t.cs(), known_spaces))) {
5590 context.check_layout(os);
5591 begin_inset(os, "space ");
5592 os << '\\' << known_coded_spaces[where - known_spaces]
5595 // LaTeX swallows whitespace after all spaces except
5596 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5597 // We have to do that here, too, because LyX
5598 // adds "{}" which would make the spaces significant.
5599 if (!contains(",>!;:", t.cs()))
5600 eat_whitespace(p, os, context, false);
5601 // LyX adds "{}" after all spaces except "\\ " and
5602 // "\\,", so we have to remove "{}".
5603 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5604 // remove the braces after "\\,", too.
5610 if (t.cs() == "newpage" ||
5611 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5612 t.cs() == "clearpage" ||
5613 t.cs() == "cleardoublepage" ||
5614 t.cs() == "nopagebreak") {
5615 context.check_layout(os);
5616 begin_inset(os, "Newpage ");
5619 skip_spaces_braces(p);
5623 if (t.cs() == "DeclareRobustCommand" ||
5624 t.cs() == "DeclareRobustCommandx" ||
5625 t.cs() == "newcommand" ||
5626 t.cs() == "newcommandx" ||
5627 t.cs() == "providecommand" ||
5628 t.cs() == "providecommandx" ||
5629 t.cs() == "renewcommand" ||
5630 t.cs() == "renewcommandx") {
5631 // DeclareRobustCommand, DeclareRobustCommandx,
5632 // providecommand and providecommandx could be handled
5633 // by parse_command(), but we need to call
5634 // add_known_command() here.
5635 string name = t.asInput();
5636 if (p.next_token().asInput() == "*") {
5637 // Starred form. Eat '*'
5641 string const command = p.verbatim_item();
5642 string const opt1 = p.getFullOpt();
5643 string const opt2 = p.getFullOpt();
5644 add_known_command(command, opt1, !opt2.empty());
5645 string const ert = name + '{' + command + '}' +
5647 '{' + p.verbatim_item() + '}';
5649 if (t.cs() == "DeclareRobustCommand" ||
5650 t.cs() == "DeclareRobustCommandx" ||
5651 t.cs() == "providecommand" ||
5652 t.cs() == "providecommandx" ||
5653 name[name.length()-1] == '*')
5654 output_ert_inset(os, ert, context);
5656 context.check_layout(os);
5657 begin_inset(os, "FormulaMacro");
5664 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5665 // let could be handled by parse_command(),
5666 // but we need to call add_known_command() here.
5667 string ert = t.asInput();
5670 if (p.next_token().cat() == catBegin) {
5671 name = p.verbatim_item();
5672 ert += '{' + name + '}';
5674 name = p.verbatim_item();
5679 if (p.next_token().cat() == catBegin) {
5680 command = p.verbatim_item();
5681 ert += '{' + command + '}';
5683 command = p.verbatim_item();
5686 // If command is known, make name known too, to parse
5687 // its arguments correctly. For this reason we also
5688 // have commands in syntax.default that are hardcoded.
5689 CommandMap::iterator it = known_commands.find(command);
5690 if (it != known_commands.end())
5691 known_commands[t.asInput()] = it->second;
5692 output_ert_inset(os, ert, context);
5696 if (t.cs() == "hspace" || t.cs() == "vspace") {
5699 string name = t.asInput();
5700 string const length = p.verbatim_item();
5703 bool valid = splitLatexLength(length, valstring, unit);
5704 bool known_hspace = false;
5705 bool known_vspace = false;
5706 bool known_unit = false;
5709 istringstream iss(valstring);
5712 if (t.cs()[0] == 'h') {
5713 if (unit == "\\fill") {
5718 known_hspace = true;
5721 if (unit == "\\smallskipamount") {
5723 known_vspace = true;
5724 } else if (unit == "\\medskipamount") {
5726 known_vspace = true;
5727 } else if (unit == "\\bigskipamount") {
5729 known_vspace = true;
5730 } else if (length == "\\baselineskip") {
5732 known_vspace = true;
5733 } else if (unit == "\\fill") {
5735 known_vspace = true;
5739 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5741 known_vspace = true;
5743 if (!known_hspace && !known_vspace) {
5744 switch (unitFromString(unit)) {
5760 //unitFromString(unit) fails for relative units like Length::PCW
5761 // therefore handle them separately
5762 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5763 || unit == "\\textwidth" || unit == "\\linewidth"
5764 || unit == "\\textheight" || unit == "\\paperheight"
5765 || unit == "\\baselineskip")
5773 // check for glue lengths
5774 bool is_gluelength = false;
5775 string gluelength = length;
5776 string::size_type i = length.find(" minus");
5777 if (i == string::npos) {
5778 i = length.find(" plus");
5779 if (i != string::npos)
5780 is_gluelength = true;
5782 is_gluelength = true;
5783 // if yes transform "9xx minus 8yy plus 7zz"
5785 if (is_gluelength) {
5786 i = gluelength.find(" minus");
5787 if (i != string::npos)
5788 gluelength.replace(i, 7, "-");
5789 i = gluelength.find(" plus");
5790 if (i != string::npos)
5791 gluelength.replace(i, 6, "+");
5794 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5795 // Literal horizontal length or known variable
5796 context.check_layout(os);
5797 begin_inset(os, "space ");
5805 if (known_unit && !known_hspace)
5806 os << "\n\\length " << translate_len(length);
5808 os << "\n\\length " << gluelength;
5810 } else if (known_unit || known_vspace || is_gluelength) {
5811 // Literal vertical length or known variable
5812 context.check_layout(os);
5813 begin_inset(os, "VSpace ");
5816 if (known_unit && !known_vspace)
5817 os << translate_len(length);
5824 // LyX can't handle other length variables in Inset VSpace/space
5829 output_ert_inset(os, name + '{' + unit + '}', context);
5830 else if (value == -1.0)
5831 output_ert_inset(os, name + "{-" + unit + '}', context);
5833 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5835 output_ert_inset(os, name + '{' + length + '}', context);
5840 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5841 // might be one or several options or a star.
5842 // The single '=' is meant here.
5843 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5847 context.check_layout(os);
5848 // store the latexparam here. This is eaten in parse_text_in_inset
5849 context.latexparam = newinsetlayout->latexparam();
5850 docstring name = newinsetlayout->name();
5851 bool const caption = name.find(from_ascii("Caption:")) == 0;
5853 // Already done for floating minted listings.
5854 if (minted_float.empty()) {
5855 begin_inset(os, "Caption ");
5856 os << to_utf8(name.substr(8)) << '\n';
5859 // FIXME: what do we do if the prefix is not Flex: ?
5860 if (prefixIs(name, from_ascii("Flex:")))
5862 begin_inset(os, "Flex ");
5863 os << to_utf8(name) << '\n'
5864 << "status collapsed\n";
5866 if (!minted_float.empty()) {
5867 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5868 } else if (newinsetlayout->isPassThru()) {
5869 // set catcodes to verbatim early, just in case.
5870 p.setCatcodes(VERBATIM_CATCODES);
5871 string delim = p.get_token().asInput();
5873 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5874 //FIXME: handle error condition
5875 string const arg = p.verbatimStuff("}").second;
5876 Context newcontext(true, context.textclass);
5877 if (newinsetlayout->forcePlainLayout())
5878 newcontext.layout = &context.textclass.plainLayout();
5879 output_ert(os, arg, newcontext);
5881 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5882 context.latexparam.clear();
5885 // Minted caption insets are not closed here because
5886 // we collect everything into the caption.
5887 if (minted_float.empty())
5892 // The single '=' is meant here.
5893 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5897 context.check_layout(os);
5898 docstring name = newinsetlayout->name();
5899 bool const caption = name.find(from_ascii("Caption:")) == 0;
5901 // Already done for floating minted listings.
5902 if (minted_float.empty()) {
5903 begin_inset(os, "Caption ");
5904 os << to_utf8(name.substr(8)) << '\n';
5907 // FIXME: what do we do if the prefix is not Flex: ?
5908 if (prefixIs(name, from_ascii("Flex:")))
5910 begin_inset(os, "Flex ");
5911 os << to_utf8(name) << '\n'
5912 << "status collapsed\n";
5914 if (!minted_float.empty()) {
5915 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5916 } else if (newinsetlayout->isPassThru()) {
5917 // set catcodes to verbatim early, just in case.
5918 p.setCatcodes(VERBATIM_CATCODES);
5919 string delim = p.get_token().asInput();
5921 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5922 //FIXME: handle error condition
5923 string const arg = p.verbatimStuff("}").second;
5924 Context newcontext(true, context.textclass);
5925 if (newinsetlayout->forcePlainLayout())
5926 newcontext.layout = &context.textclass.plainLayout();
5927 output_ert(os, arg, newcontext);
5929 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5932 // Minted caption insets are not closed here because
5933 // we collect everything into the caption.
5934 if (minted_float.empty())
5939 if (t.cs() == "includepdf") {
5941 string const arg = p.getArg('[', ']');
5942 map<string, string> opts;
5943 vector<string> keys;
5944 split_map(arg, opts, keys);
5945 string name = normalize_filename(p.verbatim_item());
5946 string const path = getMasterFilePath(true);
5947 // We want to preserve relative / absolute filenames,
5948 // therefore path is only used for testing
5949 if (!makeAbsPath(name, path).exists()) {
5950 // The file extension is probably missing.
5951 // Now try to find it out.
5952 char const * const pdfpages_format[] = {"pdf", 0};
5953 string const pdftex_name =
5954 find_file(name, path, pdfpages_format);
5955 if (!pdftex_name.empty()) {
5960 FileName const absname = makeAbsPath(name, path);
5961 if (absname.exists())
5963 fix_child_filename(name);
5964 copy_file(absname, name);
5966 cerr << "Warning: Could not find file '"
5967 << name << "'." << endl;
5969 context.check_layout(os);
5970 begin_inset(os, "External\n\ttemplate ");
5971 os << "PDFPages\n\tfilename "
5973 // parse the options
5974 if (opts.find("pages") != opts.end())
5975 os << "\textra LaTeX \"pages="
5976 << opts["pages"] << "\"\n";
5977 if (opts.find("angle") != opts.end())
5978 os << "\trotateAngle "
5979 << opts["angle"] << '\n';
5980 if (opts.find("origin") != opts.end()) {
5982 string const opt = opts["origin"];
5983 if (opt == "tl") ss << "topleft";
5984 if (opt == "bl") ss << "bottomleft";
5985 if (opt == "Bl") ss << "baselineleft";
5986 if (opt == "c") ss << "center";
5987 if (opt == "tc") ss << "topcenter";
5988 if (opt == "bc") ss << "bottomcenter";
5989 if (opt == "Bc") ss << "baselinecenter";
5990 if (opt == "tr") ss << "topright";
5991 if (opt == "br") ss << "bottomright";
5992 if (opt == "Br") ss << "baselineright";
5993 if (!ss.str().empty())
5994 os << "\trotateOrigin " << ss.str() << '\n';
5996 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5998 if (opts.find("width") != opts.end())
6000 << translate_len(opts["width"]) << '\n';
6001 if (opts.find("height") != opts.end())
6003 << translate_len(opts["height"]) << '\n';
6004 if (opts.find("keepaspectratio") != opts.end())
6005 os << "\tkeepAspectRatio\n";
6007 context.check_layout(os);
6008 registerExternalTemplatePackages("PDFPages");
6012 if (t.cs() == "loadgame") {
6014 string name = normalize_filename(p.verbatim_item());
6015 string const path = getMasterFilePath(true);
6016 // We want to preserve relative / absolute filenames,
6017 // therefore path is only used for testing
6018 if (!makeAbsPath(name, path).exists()) {
6019 // The file extension is probably missing.
6020 // Now try to find it out.
6021 char const * const lyxskak_format[] = {"fen", 0};
6022 string const lyxskak_name =
6023 find_file(name, path, lyxskak_format);
6024 if (!lyxskak_name.empty())
6025 name = lyxskak_name;
6027 FileName const absname = makeAbsPath(name, path);
6028 if (absname.exists())
6030 fix_child_filename(name);
6031 copy_file(absname, name);
6033 cerr << "Warning: Could not find file '"
6034 << name << "'." << endl;
6035 context.check_layout(os);
6036 begin_inset(os, "External\n\ttemplate ");
6037 os << "ChessDiagram\n\tfilename "
6040 context.check_layout(os);
6041 // after a \loadgame follows a \showboard
6042 if (p.get_token().asInput() == "showboard")
6044 registerExternalTemplatePackages("ChessDiagram");
6048 // try to see whether the string is in unicodesymbols
6049 // Only use text mode commands, since we are in text mode here,
6050 // and math commands may be invalid (bug 6797)
6051 string name = t.asInput();
6052 // handle the dingbats, cyrillic and greek
6053 if (name == "\\textcyr")
6054 name = "\\textcyrillic";
6055 if (name == "\\ding" || name == "\\textcyrillic" ||
6056 (name == "\\textgreek" && !preamble.usePolyglossia()))
6057 name = name + '{' + p.getArg('{', '}') + '}';
6058 // handle the ifsym characters
6059 else if (name == "\\textifsymbol") {
6060 string const optif = p.getFullOpt();
6061 string const argif = p.getArg('{', '}');
6062 name = name + optif + '{' + argif + '}';
6064 // handle the \ascii characters
6065 // the case of \ascii within braces, as LyX outputs it, is already
6066 // handled for t.cat() == catBegin
6067 else if (name == "\\ascii") {
6068 // the code is "\asci\xxx"
6069 name = "{" + name + p.get_token().asInput() + "}";
6072 // handle some TIPA special characters
6073 else if (preamble.isPackageUsed("tipa")) {
6074 if (name == "\\s") {
6075 // fromLaTeXCommand() does not yet
6076 // recognize tipa short cuts
6077 name = "\\textsyllabic";
6078 } else if (name == "\\=" &&
6079 p.next_token().asInput() == "*") {
6080 // fromLaTeXCommand() does not yet
6081 // recognize tipa short cuts
6083 name = "\\textsubbar";
6084 } else if (name == "\\textdoublevertline") {
6085 // FIXME: This is not correct,
6086 // \textvertline is higher than \textbardbl
6087 name = "\\textbardbl";
6089 } else if (name == "\\!" ) {
6090 if (p.next_token().asInput() == "b") {
6091 p.get_token(); // eat 'b'
6094 } else if (p.next_token().asInput() == "d") {
6098 } else if (p.next_token().asInput() == "g") {
6102 } else if (p.next_token().asInput() == "G") {
6104 name = "\\texthtscg";
6106 } else if (p.next_token().asInput() == "j") {
6108 name = "\\texthtbardotlessj";
6110 } else if (p.next_token().asInput() == "o") {
6112 name = "\\textbullseye";
6115 } else if (name == "\\*" ) {
6116 if (p.next_token().asInput() == "k") {
6118 name = "\\textturnk";
6120 } else if (p.next_token().asInput() == "r") {
6121 p.get_token(); // eat 'b'
6122 name = "\\textturnr";
6124 } else if (p.next_token().asInput() == "t") {
6126 name = "\\textturnt";
6128 } else if (p.next_token().asInput() == "w") {
6130 name = "\\textturnw";
6135 if ((name.size() == 2 &&
6136 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6137 p.next_token().asInput() != "*") ||
6138 is_known(name.substr(1), known_tipa_marks)) {
6139 // name is a command that corresponds to a
6140 // combining character in unicodesymbols.
6141 // Append the argument, fromLaTeXCommand()
6142 // will either convert it to a single
6143 // character or a combining sequence.
6144 name += '{' + p.verbatim_item() + '}';
6146 // now get the character from unicodesymbols
6150 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6151 Encodings::TEXT_CMD, termination, rem, &req));
6153 context.check_layout(os);
6156 output_ert_inset(os, to_utf8(rem), context);
6158 skip_spaces_braces(p);
6159 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6160 preamble.registerAutomaticallyLoadedPackage(*it);
6162 //cerr << "#: " << t << " mode: " << mode << endl;
6163 // heuristic: read up to next non-nested space
6165 string s = t.asInput();
6166 string z = p.verbatim_item();
6167 while (p.good() && z != " " && !z.empty()) {
6168 //cerr << "read: " << z << endl;
6170 z = p.verbatim_item();
6172 cerr << "found ERT: " << s << endl;
6173 output_ert_inset(os, s + ' ', context);
6176 if (t.asInput() == name &&
6177 p.next_token().asInput() == "*") {
6178 // Starred commands like \vspace*{}
6179 p.get_token(); // Eat '*'
6182 if (!parse_command(name, p, os, outer, context)) {
6183 output_ert_inset(os, name, context);
6184 // Try to handle options of unknown commands:
6185 // Look if we have optional arguments,
6186 // and if so, put the brackets in ERT.
6187 while (p.hasOpt()) {
6188 p.get_token(); // eat '['
6189 output_ert_inset(os, "[", context);
6190 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6191 output_ert_inset(os, "]", context);
6199 string guessLanguage(Parser & p, string const & lang)
6201 typedef std::map<std::string, size_t> LangMap;
6202 // map from language names to number of characters
6205 for (char const * const * i = supported_CJK_languages; *i; i++)
6206 used[string(*i)] = 0;
6209 Token const t = p.get_token();
6210 // comments are not counted for any language
6211 if (t.cat() == catComment)
6213 // commands are not counted as well, but we need to detect
6214 // \begin{CJK} and switch encoding if needed
6215 if (t.cat() == catEscape) {
6216 if (t.cs() == "inputencoding") {
6217 string const enc = subst(p.verbatim_item(), "\n", " ");
6218 p.setEncoding(enc, Encoding::inputenc);
6221 if (t.cs() != "begin")
6224 // Non-CJK content is counted for lang.
6225 // We do not care about the real language here:
6226 // If we have more non-CJK contents than CJK contents,
6227 // we simply use the language that was specified as
6228 // babel main language.
6229 used[lang] += t.asInput().length();
6232 // Now we are starting an environment
6234 string const name = p.getArg('{', '}');
6235 if (name != "CJK") {
6239 // It is a CJK environment
6241 /* name = */ p.getArg('{', '}');
6242 string const encoding = p.getArg('{', '}');
6243 /* mapping = */ p.getArg('{', '}');
6244 string const encoding_old = p.getEncoding();
6245 char const * const * const where =
6246 is_known(encoding, supported_CJK_encodings);
6248 p.setEncoding(encoding, Encoding::CJK);
6250 p.setEncoding("UTF-8");
6251 string const text = p.ertEnvironment("CJK");
6252 p.setEncoding(encoding_old);
6255 // ignore contents in unknown CJK encoding
6258 // the language of the text
6260 supported_CJK_languages[where - supported_CJK_encodings];
6261 used[cjk] += text.length();
6263 LangMap::const_iterator use = used.begin();
6264 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6265 if (it->second > use->second)
6272 void check_comment_bib(ostream & os, Context & context)
6274 if (!need_commentbib)
6276 // We have a bibliography database, but no bibliography with biblatex
6277 // which is completely valid. Insert a bibtex inset in a note.
6278 context.check_layout(os);
6279 begin_inset(os, "Note Note\n");
6280 os << "status open\n";
6281 os << "\\begin_layout Plain Layout\n";
6282 begin_command_inset(os, "bibtex", "bibtex");
6284 for (auto const & bf : preamble.biblatex_bibliographies) {
6285 if (!bibfiles.empty())
6287 bibfiles += normalize_filename(bf);
6289 if (!bibfiles.empty())
6290 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6292 for (auto const & bf : preamble.biblatex_encodings) {
6293 if (!bibfileencs.empty())
6294 bibfileencs += "\t";
6297 if (!bibfileencs.empty())
6298 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6299 end_inset(os);// Bibtex
6300 os << "\\end_layout\n";
6301 end_inset(os);// Note