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 & context, InsetLayout const * layout,
58 string const & rdelim, string const & rdelimesc)
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;
67 // Inherit commands to pass through
68 newcontext.pass_thru_cmds = context.pass_thru_cmds;
70 newcontext.in_table_cell = context.in_table_cell;
72 output_arguments(os, p, outer, false, string(), newcontext,
74 // If we have a latex param, we eat it here.
75 if (!context.latexparam.empty()) {
77 Context dummy(true, context.textclass);
78 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
79 string(1, context.latexparam.back()));
81 parse_text(p, os, flags, outer, newcontext, rdelim, rdelimesc);
83 output_arguments(os, p, outer, false, "post", newcontext,
84 layout->postcommandargs());
85 newcontext.check_end_layout(os);
86 context.cell_align = newcontext.cell_align;
92 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
93 Context const & context, string const & name,
94 string const & rdelim = string(),
95 string const & rdelimesc = string())
97 InsetLayout const * layout = 0;
98 DocumentClass::InsetLayouts::const_iterator it =
99 context.textclass.insetLayouts().find(from_ascii(name));
100 if (it != context.textclass.insetLayouts().end())
101 layout = &(it->second);
102 Context newcontext = context;
103 parse_text_in_inset(p, os, flags, outer, newcontext, layout, rdelim, rdelimesc);
106 /// parses a paragraph snippet, useful for example for \\emph{...}
107 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
108 Context & context, string const & rdelim = string(),
109 string const & rdelimesc = string())
111 Context newcontext(context);
112 // Don't inherit the paragraph-level extra stuff
113 newcontext.par_extra_stuff.clear();
114 parse_text(p, os, flags, outer, newcontext, rdelim, rdelimesc);
115 // Make sure that we don't create invalid .lyx files
116 context.need_layout = newcontext.need_layout;
117 context.need_end_layout = newcontext.need_end_layout;
122 * Thin wrapper around parse_text_snippet() using a string.
124 * We completely ignore \c context.need_layout and \c context.need_end_layout,
125 * because our return value is not used directly (otherwise the stream version
126 * of parse_text_snippet() could be used). That means that the caller needs
127 * to do layout management manually.
128 * This is intended to parse text that does not create any layout changes.
130 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
133 Context newcontext(context);
134 newcontext.need_layout = false;
135 newcontext.need_end_layout = false;
136 newcontext.new_layout_allowed = false;
137 // Avoid warning by Context::~Context()
138 newcontext.par_extra_stuff.clear();
140 parse_text_snippet(p, os, flags, outer, newcontext);
144 string fboxrule = "";
146 string shadow_size = "";
148 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
149 "vpageref", "prettyref", "nameref", "eqref", 0 };
151 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
152 "vpageref", "formatted", "nameref", "eqref", 0 };
154 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
155 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
156 "secref", "subsecref", "tabref", "thmref", 0 };
158 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
159 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
160 "sec", "subsec", "tab", "thm", 0 };
164 * supported CJK encodings
165 * JIS does not work with LyX's encoding conversion
167 const char * const supported_CJK_encodings[] = {
168 "EUC-JP", "KS", "GB", "UTF8",
169 "Bg5", /*"JIS",*/ "SJIS", 0};
172 * the same as supported_CJK_encodings with their corresponding LyX language name
173 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
175 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
176 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
177 * please keep this in sync with supported_CJK_encodings line by line!
179 const char * const supported_CJK_languages[] = {
180 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
181 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
185 * The starred forms are also known except for "citefullauthor",
186 * "citeyear" and "citeyearpar".
188 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
194 * No starred form other than "cite*" known.
196 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
197 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
198 // jurabib commands not (yet) supported by LyX:
200 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
201 // "footciteauthor", "footciteyear", "footciteyearpar",
202 "citefield", "citetitle", 0 };
206 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
208 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
209 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
210 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
211 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
212 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
214 // Whether we need to insert a bibtex inset in a comment
215 bool need_commentbib = false;
217 /// LaTeX names for quotes
218 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
219 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
220 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
221 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
224 /// the same as known_quotes with .lyx names
225 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
226 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
227 "gld", "eld", "gls", "ers", "ars",
228 "ars", "als", "als", "erd", "qrs", "qrd", 0};
230 /// LaTeX names for font sizes
231 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
232 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
234 /// the same as known_sizes with .lyx names
235 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
236 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
238 /// LaTeX 2.09 names for font families
239 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
241 /// LaTeX names for font families
242 char const * const known_font_families[] = { "rmfamily", "sffamily",
245 /// LaTeX names for font family changing commands
246 char const * const known_text_font_families[] = { "textrm", "textsf",
249 /// The same as known_old_font_families, known_font_families and
250 /// known_text_font_families with .lyx names
251 char const * const known_coded_font_families[] = { "roman", "sans",
254 /// LaTeX 2.09 names for font series
255 char const * const known_old_font_series[] = { "bf", 0};
257 /// LaTeX names for font series
258 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
260 /// LaTeX names for font series changing commands
261 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
263 /// The same as known_old_font_series, known_font_series and
264 /// known_text_font_series with .lyx names
265 char const * const known_coded_font_series[] = { "bold", "medium", 0};
267 /// LaTeX 2.09 names for font shapes
268 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
270 /// LaTeX names for font shapes
271 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
274 /// LaTeX names for font shape changing commands
275 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
278 /// The same as known_old_font_shapes, known_font_shapes and
279 /// known_text_font_shapes with .lyx names
280 char const * const known_coded_font_shapes[] = { "italic", "slanted",
281 "smallcaps", "up", 0};
283 /// Known special characters which need skip_spaces_braces() afterwards
284 char const * const known_special_chars[] = {"ldots",
285 "lyxarrow", "textcompwordmark",
286 "slash", "textasciitilde", "textasciicircum", "textbackslash",
287 "LyX", "TeX", "LaTeXe",
290 /// special characters from known_special_chars which may have a \\protect before
291 char const * const known_special_protect_chars[] = {"LyX", "TeX",
292 "LaTeXe", "LaTeX", 0};
294 /// the same as known_special_chars with .lyx names
295 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
296 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
297 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
298 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
299 "\\SpecialChar LaTeX\n", 0};
302 * Graphics file extensions known by the dvips driver of the graphics package.
303 * These extensions are used to complete the filename of an included
304 * graphics file if it does not contain an extension.
305 * The order must be the same that latex uses to find a file, because we
306 * will use the first extension that matches.
307 * This is only an approximation for the common cases. If we would want to
308 * do it right in all cases, we would need to know which graphics driver is
309 * used and know the extensions of every driver of the graphics package.
311 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
312 "ps.gz", "eps.Z", "ps.Z", 0};
315 * Graphics file extensions known by the pdftex driver of the graphics package.
316 * \sa known_dvips_graphics_formats
318 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
322 * Known file extensions for TeX files as used by \\include.
324 char const * const known_tex_extensions[] = {"tex", 0};
326 /// spaces known by InsetSpace
327 char const * const known_spaces[] = { " ", "space",
328 ",", "thinspace",// \\, = \\thinspace
329 "quad", "qquad", "enspace", "enskip",
330 ";", ">", "medspace",// \\; = \\> = \\medspace
331 ":", "thickspace",// \\: = \\thickspace
332 "!", "negthinspace",// \\! = \\negthinspace
333 "negmedspace", "negthickspace",
334 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
335 "rightarrowfill", "upbracefill", "downbracefill", 0};
337 /// the same as known_spaces with .lyx names
338 char const * const known_coded_spaces[] = { "space{}", "space{}",
339 "thinspace{}", "thinspace{}",
340 "quad{}", "qquad{}", "enspace{}", "enskip{}",
341 "medspace{}", "medspace{}", "medspace{}",
342 "thickspace{}", "thickspace{}",
343 "negthinspace{}", "negthinspace{}",
344 "negmedspace{}", "negthickspace{}",
345 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
346 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
348 /// known TIPA combining diacritical marks
349 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
350 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
351 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
352 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
353 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
354 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
355 "textsubring", "textsubbar", 0};
357 /// TIPA tones that need special handling
358 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
360 // string to store the float type to be able to determine the type of subfloats
361 string float_type = "";
363 // string to store the float status of minted listings
364 string minted_float = "";
366 // whether a caption has been parsed for a floating minted listing
367 bool minted_float_has_caption = false;
369 // The caption for non-floating minted listings
370 string minted_nonfloat_caption = "";
372 // Characters that have to be escaped by \\ in LaTeX
373 char const * const known_escaped_chars[] = {
374 "&", "_", "$", "%", "#", "^", "{", "}", 0};
377 /// splits "x=z, y=b" into a map and an ordered keyword vector
378 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
383 keys.resize(v.size());
384 for (size_t i = 0; i < v.size(); ++i) {
385 size_t const pos = v[i].find('=');
386 string const index = trimSpaceAndEol(v[i].substr(0, pos));
387 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
395 * Split a LaTeX length into value and unit.
396 * The latter can be a real unit like "pt", or a latex length variable
397 * like "\textwidth". The unit may contain additional stuff like glue
398 * lengths, but we don't care, because such lengths are ERT anyway.
399 * \returns true if \p value and \p unit are valid.
401 bool splitLatexLength(string const & len, string & value, string & unit)
405 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
406 //'4,5' is a valid LaTeX length number. Change it to '4.5'
407 string const length = subst(len, ',', '.');
408 if (i == string::npos)
411 if (len[0] == '\\') {
412 // We had something like \textwidth without a factor
418 value = trimSpaceAndEol(string(length, 0, i));
422 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
423 if (contains(len, '\\'))
424 unit = trimSpaceAndEol(string(len, i));
426 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
431 /// A simple function to translate a latex length to something LyX can
432 /// understand. Not perfect, but rather best-effort.
433 bool translate_len(string const & length, string & valstring, string & unit)
435 if (!splitLatexLength(length, valstring, unit))
437 // LyX uses percent values
439 istringstream iss(valstring);
444 string const percentval = oss.str();
446 if (unit.empty() || unit[0] != '\\')
448 string::size_type const i = unit.find(' ');
449 string const endlen = (i == string::npos) ? string() : string(unit, i);
450 if (unit == "\\textwidth") {
451 valstring = percentval;
452 unit = "text%" + endlen;
453 } else if (unit == "\\columnwidth") {
454 valstring = percentval;
455 unit = "col%" + endlen;
456 } else if (unit == "\\paperwidth") {
457 valstring = percentval;
458 unit = "page%" + endlen;
459 } else if (unit == "\\linewidth") {
460 valstring = percentval;
461 unit = "line%" + endlen;
462 } else if (unit == "\\paperheight") {
463 valstring = percentval;
464 unit = "pheight%" + endlen;
465 } else if (unit == "\\textheight") {
466 valstring = percentval;
467 unit = "theight%" + endlen;
468 } else if (unit == "\\baselineskip") {
469 valstring = percentval;
470 unit = "baselineskip%" + endlen;
476 /// If we have ambiguous quotation marks, make a smart guess
477 /// based on main quote style
478 string guessQuoteStyle(string const & in, bool const opening)
481 if (prefixIs(in, "qr")) {// straight quote
483 res = subst(res, "r", "l");
484 } else if (in == "eld") {// ``
485 if (preamble.quotesStyle() == "german")
487 else if (preamble.quotesStyle() == "british")
489 else if (preamble.quotesStyle() == "french")
491 else if (preamble.quotesStyle() == "russian")
493 } else if (in == "erd") {// ''
494 if (preamble.quotesStyle() == "polish")
496 else if (preamble.quotesStyle() == "british")
498 else if (preamble.quotesStyle() == "french")
500 else if (preamble.quotesStyle() == "hungarian")
502 else if (preamble.quotesStyle() == "swedish")
503 res = opening ? "sld" : "srd";
504 } else if (in == "els") {// `
505 if (preamble.quotesStyle() == "german")
507 else if (preamble.quotesStyle() == "british")
509 } else if (in == "ers") {// '
510 if (preamble.quotesStyle() == "polish")
512 else if (preamble.quotesStyle() == "british")
514 else if (preamble.quotesStyle() == "swedish")
515 res = opening ? "sls" : "srs";
516 } else if (in == "ard") {// >>
517 if (preamble.quotesStyle() == "swiss")
519 else if (preamble.quotesStyle() == "french")
521 else if (preamble.quotesStyle() == "russian")
523 else if (preamble.quotesStyle() == "hungarian")
525 } else if (in == "ald") {// <<
526 if (preamble.quotesStyle() == "swiss")
528 else if (preamble.quotesStyle() == "french")
530 else if (preamble.quotesStyle() == "russian")
532 else if (preamble.quotesStyle() == "hungarian")
534 } else if (in == "ars") {// >
535 if (preamble.quotesStyle() == "swiss")
537 } else if (in == "als") {// <
538 if (preamble.quotesStyle() == "swiss")
540 } else if (in == "gld") {// ,,
541 if (preamble.quotesStyle() == "polish")
543 else if (preamble.quotesStyle() == "hungarian")
545 else if (preamble.quotesStyle() == "russian")
547 } else if (in == "gls") {// ,
548 if (preamble.quotesStyle() == "polish")
555 string const fromPolyglossiaEnvironment(string const & s)
557 // Since \arabic is taken by the LaTeX kernel,
558 // the Arabic polyglossia environment is upcased
566 string uncapitalize(string const & s)
568 docstring in = from_ascii(s);
569 char_type t = lowercase(s[0]);
575 bool isCapitalized(string const & s)
577 docstring in = from_ascii(s);
578 char_type t = uppercase(s[0]);
580 return to_ascii(in) == s;
587 string translate_len(string const & length)
591 if (translate_len(length, value, unit))
593 // If the input is invalid, return what we have.
601 * Translates a LaTeX length into \p value, \p unit and
602 * \p special parts suitable for a box inset.
603 * The difference from translate_len() is that a box inset knows about
604 * some special "units" that are stored in \p special.
606 void translate_box_len(string const & length, string & value, string & unit, string & special)
608 if (translate_len(length, value, unit)) {
609 if (unit == "\\height" || unit == "\\depth" ||
610 unit == "\\totalheight" || unit == "\\width") {
611 special = unit.substr(1);
612 // The unit is not used, but LyX requires a dummy setting
624 void begin_inset(ostream & os, string const & name)
626 os << "\n\\begin_inset " << name;
630 void begin_command_inset(ostream & os, string const & name,
631 string const & latexname)
633 begin_inset(os, "CommandInset ");
634 os << name << "\nLatexCommand " << latexname << '\n';
638 void end_inset(ostream & os)
640 os << "\n\\end_inset\n\n";
644 bool skip_braces(Parser & p)
646 if (p.next_token().cat() != catBegin)
649 if (p.next_token().cat() == catEnd) {
658 /// replace LaTeX commands in \p s from the unicodesymbols file with their
660 pair<bool, docstring> convert_unicodesymbols(docstring s)
664 for (size_t i = 0; i < s.size();) {
673 docstring parsed = normalize_c(Encodings::fromLaTeXCommand(s,
674 Encodings::TEXT_CMD, termination, rem, &req));
675 set<string>::const_iterator it = req.begin();
676 set<string>::const_iterator en = req.end();
677 for (; it != en; ++it)
678 preamble.registerAutomaticallyLoadedPackage(*it);
681 if (s.empty() || s[0] != '\\')
685 for (auto const & c : known_escaped_chars)
686 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
691 return make_pair(res, os.str());
695 /// try to convert \p s to a valid InsetCommand argument
696 /// return whether this succeeded. If not, these command insets
697 /// get the "literate" flag.
698 pair<bool, string> convert_latexed_command_inset_arg(string s)
700 bool success = false;
702 // since we don't know the input encoding we can't use from_utf8
703 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
705 s = to_utf8(res.second);
707 // LyX cannot handle newlines in a latex command
708 return make_pair(success, subst(s, "\n", " "));
711 /// try to convert \p s to a valid InsetCommand argument
712 /// without trying to recode macros.
713 string convert_literate_command_inset_arg(string const & s)
715 // LyX cannot handle newlines in a latex command
716 return subst(s, "\n", " ");
719 void output_ert(ostream & os, string const & s, Context & context)
721 context.check_layout(os);
722 for (char const c : s) {
724 os << "\n\\backslash\n";
725 else if (c == '\n') {
726 context.new_paragraph(os);
727 context.check_layout(os);
731 context.check_end_layout(os);
735 void output_ert_inset(ostream & os, string const & s, Context & context)
737 // We must have a valid layout before outputting the ERT inset.
738 context.check_layout(os);
739 Context newcontext(true, context.textclass);
740 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
741 if (layout.forcePlainLayout())
742 newcontext.layout = &context.textclass.plainLayout();
743 begin_inset(os, "ERT");
744 os << "\nstatus collapsed\n";
745 output_ert(os, s, newcontext);
750 void output_comment(Parser & p, ostream & os, string const & s,
753 if (p.next_token().cat() == catNewline)
754 output_ert_inset(os, '%' + s, context);
756 output_ert_inset(os, '%' + s + '\n', context);
760 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
761 string const & latexparam = string())
763 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
766 if (checkModule(name, command))
767 return findLayoutWithoutModule(textclass, name, command, latexparam);
772 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
773 string const & latexparam = string())
775 InsetLayout const * insetlayout =
776 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
779 if (checkModule(name, command))
780 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
785 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
786 bool eatNewline = true);
790 * Skips whitespace and braces.
791 * This should be called after a command has been parsed that is not put into
792 * ERT, and where LyX adds "{}" if needed.
794 void skip_spaces_braces(Parser & p, bool keepws = false)
796 /* The following four examples produce the same typeset output and
797 should be handled by this function:
805 // Unfortunately we need to skip comments, too.
806 // We can't use eat_whitespace since writing them after the {}
807 // results in different output in some cases.
808 bool const skipped_spaces = p.skip_spaces(true);
809 bool const skipped_braces = skip_braces(p);
810 if (keepws && skipped_spaces && !skipped_braces)
811 // put back the space (it is better handled by check_space)
812 p.unskip_spaces(true);
816 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
817 Context & context, Layout::LaTeXArgMap const & latexargs)
819 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
821 context.check_layout(os);
827 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
828 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
829 for (; lait != laend; ++lait) {
831 eat_whitespace(p, os, context, false);
832 if (lait->second.mandatory) {
833 if (p.next_token().cat() != catBegin)
835 string ldelim = to_utf8(lait->second.ldelim);
836 string rdelim = to_utf8(lait->second.rdelim);
841 p.get_token(); // eat ldelim
842 if (ldelim.size() > 1)
843 p.get_token(); // eat ldelim
845 context.check_layout(os);
848 begin_inset(os, "Argument ");
851 os << i << "\nstatus collapsed\n\n";
852 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
855 string ldelim = to_utf8(lait->second.ldelim);
856 string rdelim = to_utf8(lait->second.rdelim);
861 string tok = p.next_token().asInput();
862 // we only support delimiters with max 2 chars for now.
863 if (ldelim.size() > 1)
864 tok += p.next_next_token().asInput();
865 if (p.next_token().cat() == catEscape || tok != ldelim)
867 p.get_token(); // eat ldelim
868 if (ldelim.size() > 1)
869 p.get_token(); // eat ldelim
871 context.check_layout(os);
874 begin_inset(os, "Argument ");
877 os << i << "\nstatus collapsed\n\n";
878 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
881 eat_whitespace(p, os, context, false);
886 void output_command_layout(ostream & os, Parser & p, bool outer,
887 Context & parent_context,
888 Layout const * newlayout)
890 TeXFont const oldFont = parent_context.font;
891 // save the current font size
892 string const size = oldFont.size;
893 // reset the font size to default, because the font size switches
894 // don't affect section headings and the like
895 parent_context.font.size = Context::normalfont.size;
896 // we only need to write the font change if we have an open layout
897 if (!parent_context.atParagraphStart())
898 output_font_change(os, oldFont, parent_context.font);
899 parent_context.check_end_layout(os);
900 Context context(true, parent_context.textclass, newlayout,
901 parent_context.layout, parent_context.font);
902 if (parent_context.deeper_paragraph) {
903 // We are beginning a nested environment after a
904 // deeper paragraph inside the outer list environment.
905 // Therefore we don't need to output a "begin deeper".
906 context.need_end_deeper = true;
908 context.check_deeper(os);
909 output_arguments(os, p, outer, true, string(), context,
910 context.layout->latexargs());
911 // If we have a latex param, we eat it here.
912 if (!parent_context.latexparam.empty()) {
914 Context dummy(true, parent_context.textclass);
915 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
916 string(1, parent_context.latexparam.back()));
918 parse_text(p, os, FLAG_ITEM, outer, context);
919 output_arguments(os, p, outer, false, "post", context,
920 context.layout->postcommandargs());
921 context.check_end_layout(os);
922 if (parent_context.deeper_paragraph) {
923 // We must suppress the "end deeper" because we
924 // suppressed the "begin deeper" above.
925 context.need_end_deeper = false;
927 context.check_end_deeper(os);
928 // We don't need really a new paragraph, but
929 // we must make sure that the next item gets a \begin_layout.
930 parent_context.new_paragraph(os);
931 // Set the font size to the original value. No need to output it here
932 // (Context::begin_layout() will do that if needed)
933 parent_context.font.size = size;
938 * Output a space if necessary.
939 * This function gets called for every whitespace token.
941 * We have three cases here:
942 * 1. A space must be suppressed. Example: The lyxcode case below
943 * 2. A space may be suppressed. Example: Spaces before "\par"
944 * 3. A space must not be suppressed. Example: A space between two words
946 * We currently handle only 1. and 3 and from 2. only the case of
947 * spaces before newlines as a side effect.
949 * 2. could be used to suppress as many spaces as possible. This has two effects:
950 * - Reimporting LyX generated LaTeX files changes almost no whitespace
951 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
952 * The drawback is that the logic inside the function becomes
953 * complicated, and that is the reason why it is not implemented.
955 void check_space(Parser & p, ostream & os, Context & context)
957 Token const next = p.next_token();
958 Token const curr = p.curr_token();
959 // A space before a single newline and vice versa must be ignored
960 // LyX emits a newline before \end{lyxcode}.
961 // This newline must be ignored,
962 // otherwise LyX will add an additional protected space.
963 if (next.cat() == catSpace ||
964 next.cat() == catNewline ||
965 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
968 context.check_layout(os);
974 * Parse all arguments of \p command
976 void parse_arguments(string const & command,
977 vector<ArgumentType> const & template_arguments,
978 Parser & p, ostream & os, bool outer, Context & context)
980 string ert = command;
981 size_t no_arguments = template_arguments.size();
982 for (size_t i = 0; i < no_arguments; ++i) {
983 switch (template_arguments[i]) {
986 // This argument contains regular LaTeX
987 output_ert_inset(os, ert + '{', context);
988 eat_whitespace(p, os, context, false);
989 if (template_arguments[i] == required)
990 parse_text(p, os, FLAG_ITEM, outer, context);
992 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
996 // This argument consists only of a single item.
997 // The presence of '{' or not must be preserved.
999 if (p.next_token().cat() == catBegin)
1000 ert += '{' + p.verbatim_item() + '}';
1002 ert += p.verbatim_item();
1006 // This argument may contain special characters
1007 ert += '{' + p.verbatim_item() + '}';
1011 // true because we must not eat whitespace
1012 // if an optional arg follows we must not strip the
1013 // brackets from this one
1014 if (i < no_arguments - 1 &&
1015 template_arguments[i+1] == optional)
1016 ert += p.getFullOpt(true);
1018 ert += p.getOpt(true);
1022 output_ert_inset(os, ert, context);
1027 * Check whether \p command is a known command. If yes,
1028 * handle the command with all arguments.
1029 * \return true if the command was parsed, false otherwise.
1031 bool parse_command(string const & command, Parser & p, ostream & os,
1032 bool outer, Context & context)
1034 if (known_commands.find(command) != known_commands.end()) {
1035 parse_arguments(command, known_commands[command], p, os,
1043 /// Parses a minipage or parbox
1044 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1045 unsigned inner_flags, bool outer, Context & parent_context,
1046 string const & outer_type, string const & special,
1047 string inner_type, string const & frame_color,
1048 string const & background_color)
1052 string hor_pos = "l";
1053 // We need to set the height to the LaTeX default of 1\\totalheight
1054 // for the case when no height argument is given
1055 string height_value = "1";
1056 string height_unit = "in";
1057 string height_special = "totalheight";
1058 string latex_height;
1062 string width_special = "none";
1063 string thickness = "0.4pt";
1064 if (!fboxrule.empty())
1065 thickness = fboxrule;
1067 thickness = "0.4pt";
1069 if (!fboxsep.empty())
1070 separation = fboxsep;
1074 if (!shadow_size.empty())
1075 shadowsize = shadow_size;
1078 string framecolor = "black";
1079 string backgroundcolor = "none";
1080 if (!frame_color.empty())
1081 framecolor = frame_color;
1082 if (!background_color.empty())
1083 backgroundcolor = background_color;
1084 // if there is a color box around the \begin statements have not yet been parsed
1086 if (!frame_color.empty() || !background_color.empty()) {
1087 eat_whitespace(p, os, parent_context, false);
1088 p.get_token().asInput(); // the '{'
1090 if (p.next_token().asInput() == "\\begin") {
1091 p.get_token().asInput();
1093 inner_type = "minipage";
1094 inner_flags = FLAG_END;
1095 active_environments.push_back("minipage");
1098 else if (p.next_token().asInput() == "\\parbox") {
1099 p.get_token().asInput();
1100 inner_type = "parbox";
1101 inner_flags = FLAG_ITEM;
1104 else if (p.next_token().asInput() == "\\makebox") {
1105 p.get_token().asInput();
1106 inner_type = "makebox";
1107 inner_flags = FLAG_ITEM;
1109 // in case there is just \colorbox{color}{text}
1112 inner_type = "makebox";
1113 inner_flags = FLAG_BRACE_LAST;
1118 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1120 if (!inner_type.empty() && p.hasOpt()) {
1121 if (inner_type != "makebox")
1122 position = p.getArg('[', ']');
1124 latex_width = p.getArg('[', ']');
1125 translate_box_len(latex_width, width_value, width_unit, width_special);
1128 if (position != "t" && position != "c" && position != "b") {
1129 cerr << "invalid position " << position << " for "
1130 << inner_type << endl;
1134 if (inner_type != "makebox") {
1135 latex_height = p.getArg('[', ']');
1136 translate_box_len(latex_height, height_value, height_unit, height_special);
1138 string const opt = p.getArg('[', ']');
1141 if (hor_pos != "l" && hor_pos != "c" &&
1142 hor_pos != "r" && hor_pos != "s") {
1143 cerr << "invalid hor_pos " << hor_pos
1144 << " for " << inner_type << endl;
1151 inner_pos = p.getArg('[', ']');
1152 if (inner_pos != "c" && inner_pos != "t" &&
1153 inner_pos != "b" && inner_pos != "s") {
1154 cerr << "invalid inner_pos "
1155 << inner_pos << " for "
1156 << inner_type << endl;
1157 inner_pos = position;
1161 if (inner_type == "makebox")
1165 if (inner_type.empty()) {
1166 if (special.empty() && outer_type != "framebox")
1167 latex_width = "1\\columnwidth";
1170 latex_width = p2.getArg('[', ']');
1171 string const opt = p2.getArg('[', ']');
1174 if (hor_pos != "l" && hor_pos != "c" &&
1175 hor_pos != "r" && hor_pos != "s") {
1176 cerr << "invalid hor_pos " << hor_pos
1177 << " for " << outer_type << endl;
1181 if (outer_type == "framebox")
1185 } else if (inner_type != "makebox")
1186 latex_width = p.verbatim_item();
1187 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1188 // as this is LyX's standard for such cases (except for makebox)
1189 // \framebox is more special and handled below
1190 if (latex_width.empty() && inner_type != "makebox"
1191 && outer_type != "framebox")
1192 latex_width = "1\\columnwidth";
1194 translate_len(latex_width, width_value, width_unit);
1196 bool shadedparbox = false;
1197 if (inner_type == "shaded") {
1198 eat_whitespace(p, os, parent_context, false);
1199 if (outer_type == "parbox") {
1201 if (p.next_token().cat() == catBegin)
1203 eat_whitespace(p, os, parent_context, false);
1204 shadedparbox = true;
1209 // If we already read the inner box we have to push the inner env
1210 if (!outer_type.empty() && !inner_type.empty() &&
1211 (inner_flags & FLAG_END))
1212 active_environments.push_back(inner_type);
1213 bool use_ert = false;
1214 if (!outer_type.empty() && !inner_type.empty()) {
1215 // Look whether there is some content after the end of the
1216 // inner box, but before the end of the outer box.
1217 // If yes, we need to output ERT.
1219 if (inner_flags & FLAG_END)
1220 p.ertEnvironment(inner_type);
1223 p.skip_spaces(true);
1224 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1225 if ((outer_env && p.next_token().asInput() != "\\end") ||
1226 (!outer_env && p.next_token().cat() != catEnd)) {
1227 // something is between the end of the inner box and
1228 // the end of the outer box, so we need to use ERT.
1236 if (!outer_type.empty()) {
1237 if (outer_flags & FLAG_END)
1238 ss << "\\begin{" << outer_type << '}';
1240 ss << '\\' << outer_type << '{';
1241 if (!special.empty())
1245 if (!inner_type.empty()) {
1246 if (inner_type != "shaded") {
1247 if (inner_flags & FLAG_END)
1248 ss << "\\begin{" << inner_type << '}';
1250 ss << '\\' << inner_type;
1252 if (!position.empty())
1253 ss << '[' << position << ']';
1254 if (!latex_height.empty())
1255 ss << '[' << latex_height << ']';
1256 if (!inner_pos.empty())
1257 ss << '[' << inner_pos << ']';
1258 ss << '{' << latex_width << '}';
1259 if (!(inner_flags & FLAG_END))
1262 if (inner_type == "shaded")
1263 ss << "\\begin{shaded}";
1264 output_ert_inset(os, ss.str(), parent_context);
1265 if (!inner_type.empty()) {
1266 parse_text(p, os, inner_flags, outer, parent_context);
1267 if (inner_flags & FLAG_END)
1268 output_ert_inset(os, "\\end{" + inner_type + '}',
1271 output_ert_inset(os, "}", parent_context);
1273 if (!outer_type.empty()) {
1274 // If we already read the inner box we have to pop
1276 if (!inner_type.empty() && (inner_flags & FLAG_END))
1277 active_environments.pop_back();
1279 // Ensure that the end of the outer box is parsed correctly:
1280 // The opening brace has been eaten by parse_outer_box()
1281 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1282 outer_flags &= ~FLAG_ITEM;
1283 outer_flags |= FLAG_BRACE_LAST;
1285 parse_text(p, os, outer_flags, outer, parent_context);
1286 if (outer_flags & FLAG_END)
1287 output_ert_inset(os, "\\end{" + outer_type + '}',
1290 output_ert_inset(os, "}", parent_context);
1293 // LyX does not like empty positions, so we have
1294 // to set them to the LaTeX default values here.
1295 if (position.empty())
1297 if (inner_pos.empty())
1298 inner_pos = position;
1299 parent_context.check_layout(os);
1300 begin_inset(os, "Box ");
1301 if (outer_type == "framed")
1303 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1305 else if (outer_type == "shadowbox")
1306 os << "Shadowbox\n";
1307 else if ((outer_type == "shaded" && inner_type.empty()) ||
1308 (outer_type == "minipage" && inner_type == "shaded") ||
1309 (outer_type == "parbox" && inner_type == "shaded")) {
1311 preamble.registerAutomaticallyLoadedPackage("color");
1312 } else if (outer_type == "doublebox")
1313 os << "Doublebox\n";
1314 else if (outer_type.empty() || outer_type == "mbox")
1315 os << "Frameless\n";
1317 os << outer_type << '\n';
1318 os << "position \"" << position << "\"\n";
1319 os << "hor_pos \"" << hor_pos << "\"\n";
1320 if (outer_type == "mbox")
1321 os << "has_inner_box 1\n";
1322 else if (!frame_color.empty() && inner_type == "makebox")
1323 os << "has_inner_box 0\n";
1325 os << "has_inner_box " << !inner_type.empty() << "\n";
1326 os << "inner_pos \"" << inner_pos << "\"\n";
1327 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1329 if (outer_type == "mbox")
1330 os << "use_makebox 1\n";
1331 else if (!frame_color.empty())
1332 os << "use_makebox 0\n";
1334 os << "use_makebox " << (inner_type == "makebox") << '\n';
1335 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1336 os << "width \"\"\n";
1337 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1338 else if (contains(width_unit, '\\'))
1339 os << "width \"" << width_value << "in" << "\"\n";
1341 os << "width \"" << width_value << width_unit << "\"\n";
1342 if (contains(width_unit, '\\')) {
1343 width_unit.erase (0,1); // remove the leading '\'
1344 os << "special \"" << width_unit << "\"\n";
1346 os << "special \"" << width_special << "\"\n";
1347 if (contains(height_unit, '\\'))
1348 os << "height \"" << height_value << "in" << "\"\n";
1350 os << "height \"" << height_value << height_unit << "\"\n";
1351 os << "height_special \"" << height_special << "\"\n";
1352 os << "thickness \"" << thickness << "\"\n";
1353 os << "separation \"" << separation << "\"\n";
1354 os << "shadowsize \"" << shadowsize << "\"\n";
1355 os << "framecolor \"" << framecolor << "\"\n";
1356 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1357 os << "status open\n\n";
1359 // Unfortunately we can't use parse_text_in_inset:
1360 // InsetBox::forcePlainLayout() is hard coded and does not
1361 // use the inset layout. Apart from that do we call parse_text
1362 // up to two times, but need only one check_end_layout.
1363 bool const forcePlainLayout =
1364 (!inner_type.empty() || inner_type == "makebox") &&
1365 outer_type != "shaded" && outer_type != "framed";
1366 Context context(true, parent_context.textclass);
1367 if (forcePlainLayout)
1368 context.layout = &context.textclass.plainLayout();
1370 context.font = parent_context.font;
1372 // If we have no inner box the contents will be read with the outer box
1373 if (!inner_type.empty())
1374 parse_text(p, os, inner_flags, outer, context);
1376 // Ensure that the end of the outer box is parsed correctly:
1377 // The opening brace has been eaten by parse_outer_box()
1378 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1379 outer_flags &= ~FLAG_ITEM;
1380 outer_flags |= FLAG_BRACE_LAST;
1383 // Find end of outer box, output contents if inner_type is
1384 // empty and output possible comments
1385 if (!outer_type.empty()) {
1386 // If we already read the inner box we have to pop
1388 if (!inner_type.empty() && (inner_flags & FLAG_END))
1389 active_environments.pop_back();
1390 // This does not output anything but comments if
1391 // inner_type is not empty (see use_ert)
1392 parse_text(p, os, outer_flags, outer, context);
1395 context.check_end_layout(os);
1397 #ifdef PRESERVE_LAYOUT
1398 // LyX puts a % after the end of the minipage
1399 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1401 //output_comment(p, os, "dummy", parent_context);
1404 parent_context.new_paragraph(os);
1406 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1407 //output_comment(p, os, "dummy", parent_context);
1410 // We add a protected space if something real follows
1411 if (p.good() && p.next_token().cat() != catComment) {
1412 begin_inset(os, "space ~\n");
1418 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1419 active_environments.pop_back();
1420 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1421 // in this case we have to eat the the closing brace of the color box
1422 p.get_token().asInput(); // the '}'
1424 if (p.next_token().asInput() == "}") {
1425 // in this case we assume that the closing brace is from the box settings
1426 // therefore reset these values for the next box
1432 // all boxes except of Frameless and Shaded require calc
1433 if (!(outer_type.empty() || outer_type == "mbox") &&
1434 !((outer_type == "shaded" && inner_type.empty()) ||
1435 (outer_type == "minipage" && inner_type == "shaded") ||
1436 (outer_type == "parbox" && inner_type == "shaded")))
1437 preamble.registerAutomaticallyLoadedPackage("calc");
1441 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1442 Context & parent_context, string const & outer_type,
1443 string const & special)
1445 eat_whitespace(p, os, parent_context, false);
1446 if (flags & FLAG_ITEM) {
1448 if (p.next_token().cat() == catBegin)
1451 cerr << "Warning: Ignoring missing '{' after \\"
1452 << outer_type << '.' << endl;
1453 eat_whitespace(p, os, parent_context, false);
1456 unsigned int inner_flags = 0;
1458 if (outer_type == "minipage" || outer_type == "parbox") {
1459 p.skip_spaces(true);
1460 while (p.hasOpt()) {
1462 p.skip_spaces(true);
1465 p.skip_spaces(true);
1466 if (outer_type == "parbox") {
1468 if (p.next_token().cat() == catBegin)
1470 p.skip_spaces(true);
1473 if (outer_type == "shaded" || outer_type == "mbox") {
1474 // These boxes never have an inner box
1476 } else if (p.next_token().asInput() == "\\parbox") {
1477 inner = p.get_token().cs();
1478 inner_flags = FLAG_ITEM;
1479 } else if (p.next_token().asInput() == "\\begin") {
1480 // Is this a minipage or shaded box?
1483 inner = p.getArg('{', '}');
1485 if (inner == "minipage" || inner == "shaded")
1486 inner_flags = FLAG_END;
1491 if (inner_flags == FLAG_END) {
1492 if (inner != "shaded")
1496 eat_whitespace(p, os, parent_context, false);
1498 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1499 outer_type, special, inner, "", "");
1501 if (inner_flags == FLAG_ITEM) {
1503 eat_whitespace(p, os, parent_context, false);
1505 parse_box(p, os, flags, inner_flags, outer, parent_context,
1506 outer_type, special, inner, "", "");
1511 void parse_index_entry(Parser & p, ostream & os, Context & context, string const & kind)
1513 // write inset header
1514 begin_inset(os, "Index ");
1517 // Parse for post argument (|...)
1519 string const marg = p.getArg('{', '}');
1522 bool inpost = false;
1523 bool startrange = false;
1524 bool endrange = false;
1526 for (string::const_iterator it = marg.begin(), et = marg.end(); it != et; ++it) {
1529 if (post.empty() && c == '(')
1531 else if (post.empty() && c == ')')
1536 if (!inpost && (c == '|' && lc != '"'))
1541 os << "\nrange start";
1543 os << "\nrange end";
1545 os << "\nrange none";
1546 bool const see = prefixIs(post, "see{");
1547 bool const seealso = prefixIs(post, "seealso{");
1548 if (!post.empty() && !see && !seealso)
1549 os << "\npageformat " << post;
1551 os << "\npageformat default";
1552 os << "\nstatus collapsed\n";
1558 if (p.hasIdxMacros("!")) {
1559 // Index entry with levels
1560 while (p.hasIdxMacros("!")) {
1564 os << "\\begin_layout Plain Layout\n";
1566 begin_inset(os, "IndexMacro subentry");
1567 os << "\nstatus collapsed\n";
1569 // Check for (level-specific) sortkey
1570 if (p.hasIdxMacros("@", "!")) {
1572 os << "\\begin_layout Plain Layout\n";
1573 begin_inset(os, "IndexMacro sortkey");
1574 os << "\nstatus collapsed\n";
1575 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1578 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "!", "\"");
1580 os << "\n\\end_layout\n";
1586 begin_inset(os, "IndexMacro subentry");
1587 os << "\nstatus collapsed\n";
1590 // Check for (level-specific) sortkey
1591 if (p.hasIdxMacros("@", "!")) {
1596 os << "\\begin_layout Plain Layout\n";
1597 begin_inset(os, "IndexMacro sortkey");
1598 os << "\nstatus collapsed\n";
1599 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1601 if (post.empty() && !startrange && !endrange) {
1602 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1605 // Handle post-argument
1606 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1607 if (see || seealso) {
1608 while (p.next_token().character() != '{' && p.good())
1610 // this ends the subinset, as the see[also] insets
1611 // must come at main index inset
1612 os << "\n\\end_layout\n";
1615 begin_inset(os, "IndexMacro see");
1617 begin_inset(os, "IndexMacro seealso");
1618 os << "\nstatus collapsed\n";
1619 os << "\\begin_layout Plain Layout\n";
1620 parse_text_snippet(p, os, FLAG_ITEM, false, context);
1626 os << "\n\\end_layout\n";
1628 if (post.empty() && !startrange && !endrange) {
1629 parse_text_in_inset(p, os, FLAG_BRACE_LAST, false, context, "IndexMacro subentry");
1632 // Handle post-argument
1633 if (see || seealso) {
1634 os << "\\begin_layout Plain Layout\n";
1635 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1636 while (p.next_token().character() != '{' && p.good())
1638 // this ends the subinset, as the see[also] insets
1639 // must come at main index inset
1640 os << "\n\\end_layout\n";
1643 begin_inset(os, "IndexMacro see");
1645 begin_inset(os, "IndexMacro seealso");
1646 os << "\nstatus collapsed\n";
1647 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1649 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1657 os << "\n\\end_layout\n";
1659 // Index without any levels
1660 // Check for sortkey
1661 if (p.hasIdxMacros("@", "!")) {
1664 os << "\\begin_layout Plain Layout\n";
1665 begin_inset(os, "IndexMacro sortkey");
1666 os << "\nstatus collapsed\n";
1667 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1669 if (post.empty() && !startrange && !endrange) {
1670 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1673 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1674 if (see || seealso) {
1675 while (p.next_token().character() != '{' && p.good())
1678 begin_inset(os, "IndexMacro see");
1680 begin_inset(os, "IndexMacro seealso");
1681 os << "\nstatus collapsed\n";
1682 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1689 os << "\n\\end_layout\n";
1691 if (post.empty() && !startrange && !endrange) {
1692 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
1695 // Handle post-argument
1698 if (see || seealso) {
1699 os << "\\begin_layout Plain Layout\n";
1700 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1701 while (p.next_token().character() != '{' && p.good())
1704 begin_inset(os, "IndexMacro see");
1706 begin_inset(os, "IndexMacro seealso");
1707 os << "\nstatus collapsed\n";
1708 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1710 os << "\n\\end_layout\n";
1712 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1723 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1724 bool in_line, bool use_minted)
1726 parent_context.check_layout(os);
1727 begin_inset(os, "listings\n");
1728 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1730 while ((i = arg.find(", ")) != string::npos
1731 || (i = arg.find(",\t")) != string::npos)
1732 arg.erase(i + 1, 1);
1735 string const language = p.getArg('{', '}');
1736 p.skip_spaces(true);
1737 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1738 if (!minted_float.empty()) {
1739 arg += string(arg.empty() ? "" : ",") + minted_float;
1740 minted_nonfloat_caption.clear();
1744 os << "lstparams " << '"' << arg << '"' << '\n';
1745 if (arg.find("\\color") != string::npos)
1746 preamble.registerAutomaticallyLoadedPackage("color");
1749 os << "inline true\n";
1751 os << "inline false\n";
1752 os << "status open\n";
1753 Context context(true, parent_context.textclass);
1754 context.layout = &parent_context.textclass.plainLayout();
1755 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1756 minted_nonfloat_caption.erase(0,3);
1757 os << "\n\\begin_layout Plain Layout\n";
1758 begin_inset(os, "Caption Standard\n");
1759 Context newcontext(true, context.textclass,
1760 context.layout, 0, context.font);
1761 newcontext.check_layout(os);
1762 os << minted_nonfloat_caption << "\n";
1763 newcontext.check_end_layout(os);
1765 os << "\n\\end_layout\n";
1766 minted_nonfloat_caption.clear();
1770 // set catcodes to verbatim early, just in case.
1771 p.setCatcodes(VERBATIM_CATCODES);
1772 string delim = p.get_token().asInput();
1773 //FIXME: handler error condition
1774 s = p.verbatimStuff(delim).second;
1775 // context.new_paragraph(os);
1776 } else if (use_minted) {
1777 s = p.verbatimEnvironment("minted");
1779 s = p.verbatimEnvironment("lstlisting");
1781 output_ert(os, s, context);
1782 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1783 minted_nonfloat_caption.erase(0,3);
1784 os << "\n\\begin_layout Plain Layout\n";
1785 begin_inset(os, "Caption Standard\n");
1786 Context newcontext(true, context.textclass,
1787 context.layout, 0, context.font);
1788 newcontext.check_layout(os);
1789 os << minted_nonfloat_caption << "\n";
1790 newcontext.check_end_layout(os);
1792 os << "\n\\end_layout\n";
1793 minted_nonfloat_caption.clear();
1795 // Don't close the inset here for floating minted listings.
1796 // It will be closed at the end of the listing environment.
1797 if (!use_minted || minted_float.empty())
1800 eat_whitespace(p, os, parent_context, true);
1801 Token t = p.get_token();
1802 if (t.asInput() != "\\end") {
1803 // If anything follows, collect it into a caption.
1804 minted_float_has_caption = true;
1805 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1806 begin_inset(os, "Caption Standard\n");
1807 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1814 /// parse an unknown environment
1815 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1816 unsigned flags, bool outer,
1817 Context & parent_context)
1819 if (name == "tabbing")
1820 // We need to remember that we have to handle '\=' specially
1821 flags |= FLAG_TABBING;
1823 // We need to translate font changes and paragraphs inside the
1824 // environment to ERT if we have a non standard font.
1825 // Otherwise things like
1826 // \large\begin{foo}\huge bar\end{foo}
1828 bool const specialfont =
1829 (parent_context.font != parent_context.normalfont);
1830 bool const new_layout_allowed = parent_context.new_layout_allowed;
1832 parent_context.new_layout_allowed = false;
1833 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1834 // Try to handle options: Look if we have optional arguments,
1835 // and if so, put the brackets in ERT.
1836 while (p.hasOpt()) {
1837 p.get_token(); // eat '['
1838 output_ert_inset(os, "[", parent_context);
1839 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1840 output_ert_inset(os, "]", parent_context);
1842 parse_text_snippet(p, os, flags, outer, parent_context);
1843 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1845 parent_context.new_layout_allowed = new_layout_allowed;
1849 void parse_environment(Parser & p, ostream & os, bool outer,
1850 string & last_env, Context & parent_context)
1852 Layout const * newlayout;
1853 InsetLayout const * newinsetlayout = 0;
1854 string const name = p.getArg('{', '}');
1855 const bool is_starred = suffixIs(name, '*');
1856 string const unstarred_name = rtrim(name, "*");
1857 active_environments.push_back(name);
1859 // We use this loop and break out after a condition is met
1860 // rather than a huge else-if-chain.
1862 if (is_math_env(name)) {
1863 parent_context.check_layout(os);
1864 begin_inset(os, "Formula ");
1865 os << "\\begin{" << name << "}";
1866 parse_math(p, os, FLAG_END, MATH_MODE);
1867 os << "\\end{" << name << "}";
1869 if (is_display_math_env(name)) {
1870 // Prevent the conversion of a line break to a space
1871 // (bug 7668). This does not change the output, but
1872 // looks ugly in LyX.
1873 eat_whitespace(p, os, parent_context, false);
1878 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1879 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1880 // We must begin a new paragraph if not already done
1881 if (!parent_context.atParagraphStart()) {
1882 parent_context.check_end_layout(os);
1883 parent_context.new_paragraph(os);
1885 // store previous language because we must reset it at the end
1886 string const lang_old = parent_context.font.language;
1887 // save new language in context so that it is
1888 // handled by parse_text
1889 parent_context.font.language =
1890 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1891 parse_text(p, os, FLAG_END, outer, parent_context);
1892 // reset previous language
1893 parent_context.font.language = lang_old;
1894 // Just in case the environment is empty
1895 parent_context.extra_stuff.erase();
1896 // We must begin a new paragraph to reset the language
1897 parent_context.new_paragraph(os);
1902 if (unstarred_name == "tabular" || name == "longtable"
1903 || name == "tabularx" || name == "xltabular") {
1904 eat_whitespace(p, os, parent_context, false);
1905 string width = "0pt";
1907 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1908 string const opt = p.getArg('[', ']');
1911 else if (opt == "l")
1913 else if (opt == "r")
1916 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1917 width = lyx::translate_len(p.getArg('{', '}'));
1918 eat_whitespace(p, os, parent_context, false);
1920 parent_context.check_layout(os);
1921 begin_inset(os, "Tabular ");
1922 handle_tabular(p, os, name, width, halign, parent_context);
1928 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1929 eat_whitespace(p, os, parent_context, false);
1930 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1931 eat_whitespace(p, os, parent_context, false);
1932 parent_context.check_layout(os);
1933 begin_inset(os, "Float " + unstarred_name + "\n");
1934 // store the float type for subfloats
1935 // subfloats only work with figures and tables
1936 if (unstarred_name == "figure")
1937 float_type = unstarred_name;
1938 else if (unstarred_name == "table")
1939 float_type = unstarred_name;
1943 os << "placement " << opt << '\n';
1944 if (contains(opt, "H"))
1945 preamble.registerAutomaticallyLoadedPackage("float");
1947 Floating const & fl = parent_context.textclass.floats()
1948 .getType(unstarred_name);
1949 if (!fl.floattype().empty() && fl.usesFloatPkg())
1950 preamble.registerAutomaticallyLoadedPackage("float");
1953 os << "wide " << convert<string>(is_starred)
1954 << "\nsideways false"
1955 << "\nstatus open\n\n";
1956 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1957 if (unstarred_name == "algorithm")
1958 // in algorithm, \; has special meaning
1959 parent_context.pass_thru_cmds.insert(";");
1960 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1961 if (unstarred_name == "algorithm")
1962 parent_context.pass_thru_cmds = pass_thru_cmds;
1964 // We don't need really a new paragraph, but
1965 // we must make sure that the next item gets a \begin_layout.
1966 parent_context.new_paragraph(os);
1968 // the float is parsed thus delete the type
1973 if (unstarred_name == "sidewaysfigure"
1974 || unstarred_name == "sidewaystable"
1975 || unstarred_name == "sidewaysalgorithm") {
1976 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1977 eat_whitespace(p, os, parent_context, false);
1978 parent_context.check_layout(os);
1979 if (unstarred_name == "sidewaysfigure")
1980 begin_inset(os, "Float figure\n");
1981 else if (unstarred_name == "sidewaystable")
1982 begin_inset(os, "Float table\n");
1983 else if (unstarred_name == "sidewaysalgorithm")
1984 begin_inset(os, "Float algorithm\n");
1986 os << "placement " << opt << '\n';
1987 if (contains(opt, "H"))
1988 preamble.registerAutomaticallyLoadedPackage("float");
1989 os << "wide " << convert<string>(is_starred)
1990 << "\nsideways true"
1991 << "\nstatus open\n\n";
1992 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1994 // We don't need really a new paragraph, but
1995 // we must make sure that the next item gets a \begin_layout.
1996 parent_context.new_paragraph(os);
1998 preamble.registerAutomaticallyLoadedPackage("rotfloat");
2002 if (name == "wrapfigure" || name == "wraptable") {
2003 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
2004 eat_whitespace(p, os, parent_context, false);
2005 parent_context.check_layout(os);
2008 string overhang = "0col%";
2011 lines = p.getArg('[', ']');
2012 string const placement = p.getArg('{', '}');
2014 overhang = p.getArg('[', ']');
2015 string const width = p.getArg('{', '}');
2017 if (name == "wrapfigure")
2018 begin_inset(os, "Wrap figure\n");
2020 begin_inset(os, "Wrap table\n");
2021 os << "lines " << lines
2022 << "\nplacement " << placement
2023 << "\noverhang " << lyx::translate_len(overhang)
2024 << "\nwidth " << lyx::translate_len(width)
2025 << "\nstatus open\n\n";
2026 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2028 // We don't need really a new paragraph, but
2029 // we must make sure that the next item gets a \begin_layout.
2030 parent_context.new_paragraph(os);
2032 preamble.registerAutomaticallyLoadedPackage("wrapfig");
2036 if (name == "minipage") {
2037 eat_whitespace(p, os, parent_context, false);
2038 // Test whether this is an outer box of a shaded box
2040 // swallow arguments
2041 while (p.hasOpt()) {
2043 p.skip_spaces(true);
2046 p.skip_spaces(true);
2047 Token t = p.get_token();
2048 bool shaded = false;
2049 if (t.asInput() == "\\begin") {
2050 p.skip_spaces(true);
2051 if (p.getArg('{', '}') == "shaded")
2056 parse_outer_box(p, os, FLAG_END, outer,
2057 parent_context, name, "shaded");
2059 parse_box(p, os, 0, FLAG_END, outer, parent_context,
2060 "", "", name, "", "");
2065 if (name == "comment") {
2066 eat_whitespace(p, os, parent_context, false);
2067 parent_context.check_layout(os);
2068 begin_inset(os, "Note Comment\n");
2069 os << "status open\n";
2070 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2073 skip_braces(p); // eat {} that might by set by LyX behind comments
2074 preamble.registerAutomaticallyLoadedPackage("verbatim");
2078 if (unstarred_name == "verbatim") {
2079 // FIXME: this should go in the generic code that
2080 // handles environments defined in layout file that
2081 // have "PassThru 1". However, the code over there is
2082 // already too complicated for my taste.
2083 string const ascii_name =
2084 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
2085 parent_context.new_paragraph(os);
2086 Context context(true, parent_context.textclass,
2087 &parent_context.textclass[from_ascii(ascii_name)]);
2088 string s = p.verbatimEnvironment(name);
2089 output_ert(os, s, context);
2094 if (name == "IPA") {
2095 eat_whitespace(p, os, parent_context, false);
2096 parent_context.check_layout(os);
2097 begin_inset(os, "IPA\n");
2098 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
2099 // These commands have special meanings in IPA
2100 parent_context.pass_thru_cmds.insert("!");
2101 parent_context.pass_thru_cmds.insert(";");
2102 parent_context.pass_thru_cmds.insert(":");
2103 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2104 parent_context.pass_thru_cmds = pass_thru_cmds;
2107 preamble.registerAutomaticallyLoadedPackage("tipa");
2108 preamble.registerAutomaticallyLoadedPackage("tipx");
2112 if (name == parent_context.textclass.titlename()
2113 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
2114 parse_text(p, os, FLAG_END, outer, parent_context);
2115 // Just in case the environment is empty
2116 parent_context.extra_stuff.erase();
2117 // We must begin a new paragraph
2118 parent_context.new_paragraph(os);
2123 if (name == "CJK") {
2124 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
2125 // It is impossible to decide if a CJK environment was in its own paragraph or within
2126 // a line. We therefore always assume a paragraph since the latter is a rare case.
2127 eat_whitespace(p, os, parent_context, false);
2128 parent_context.check_end_layout(os);
2129 // store the encoding to be able to reset it
2130 string const encoding_old = p.getEncoding();
2131 string const encoding = p.getArg('{', '}');
2132 // FIXME: For some reason JIS does not work. Although the text
2133 // in tests/CJK.tex is identical with the SJIS version if you
2134 // convert both snippets using the recode command line utility,
2135 // the resulting .lyx file contains some extra characters if
2136 // you set buggy_encoding to false for JIS.
2137 bool const buggy_encoding = encoding == "JIS";
2138 if (!buggy_encoding)
2139 p.setEncoding(encoding, Encoding::CJK);
2141 // FIXME: This will read garbage, since the data is not encoded in utf8.
2142 p.setEncoding("UTF-8");
2144 // LyX only supports the same mapping for all CJK
2145 // environments, so we might need to output everything as ERT
2146 string const mapping = trim(p.getArg('{', '}'));
2147 char const * const * const where =
2148 is_known(encoding, supported_CJK_encodings);
2149 if (!buggy_encoding && !preamble.fontCJKSet())
2150 preamble.fontCJK(mapping);
2151 bool knownMapping = mapping == preamble.fontCJK();
2152 if (buggy_encoding || !knownMapping || !where) {
2153 parent_context.check_layout(os);
2154 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
2156 // we must parse the content as verbatim because e.g. JIS can contain
2157 // normally invalid characters
2158 // FIXME: This works only for the most simple cases.
2159 // Since TeX control characters are not parsed,
2160 // things like comments are completely wrong.
2161 string const s = p.plainEnvironment("CJK");
2162 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
2165 if (snip == "\\" || is_known(snip, known_escaped_chars))
2166 output_ert_inset(os, snip, parent_context);
2167 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
2172 output_ert_inset(os, "\\end{" + name + "}",
2176 supported_CJK_languages[where - supported_CJK_encodings];
2177 // store the language because we must reset it at the end
2178 string const lang_old = parent_context.font.language;
2179 parent_context.font.language = lang;
2180 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2181 parent_context.font.language = lang_old;
2182 parent_context.new_paragraph(os);
2184 p.setEncoding(encoding_old);
2189 if (name == "lyxgreyedout") {
2190 eat_whitespace(p, os, parent_context, false);
2191 parent_context.check_layout(os);
2192 begin_inset(os, "Note Greyedout\n");
2193 os << "status open\n";
2194 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2197 if (!preamble.notefontcolor().empty())
2198 preamble.registerAutomaticallyLoadedPackage("color");
2202 if (name == "btSect") {
2203 eat_whitespace(p, os, parent_context, false);
2204 parent_context.check_layout(os);
2205 begin_command_inset(os, "bibtex", "bibtex");
2206 string bibstyle = "plain";
2208 bibstyle = p.getArg('[', ']');
2209 p.skip_spaces(true);
2211 string const bibfile = p.getArg('{', '}');
2212 eat_whitespace(p, os, parent_context, false);
2213 Token t = p.get_token();
2214 if (t.asInput() == "\\btPrintCited") {
2215 p.skip_spaces(true);
2216 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2218 if (t.asInput() == "\\btPrintNotCited") {
2219 p.skip_spaces(true);
2220 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2222 if (t.asInput() == "\\btPrintAll") {
2223 p.skip_spaces(true);
2224 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2226 os << "bibfiles " << '"' << bibfile << "\"\n"
2227 << "options " << '"' << bibstyle << "\"\n";
2228 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2234 if (name == "btUnit") {
2235 string const nt = p.next_next_token().cs();
2236 // Do not attempt to overwrite a former diverging multibib.
2237 // Those are output as ERT instead.
2238 if ((nt == "part" || nt == "chapter"
2239 || nt == "section" || nt == "subsection")
2240 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2241 parse_text(p, os, FLAG_END, outer, parent_context);
2242 preamble.multibib(nt);
2244 parse_unknown_environment(p, name, os, FLAG_END, outer,
2249 // This is only attempted at turn environments that consist only
2250 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2251 // Thus we will fall through in other cases.
2252 if (name == "turn") {
2253 // We check if the next thing is a tabular[*|x]
2255 p.getArg('{', '}');// eat turn argument
2256 bool found_end = false;
2257 bool only_table = false;
2258 bool end_table = false;
2261 string envname = p.getArg('{', '}');
2262 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2263 // Now we check if the table is the only content
2264 // of the turn environment
2265 string const tenv = envname;
2266 while (!found_end && !end_table && p.good()) {
2267 envname = p.next_token().cat() == catBegin
2268 ? p.getArg('{', '}') : string();
2269 Token const & t = p.get_token();
2271 end_table = t.asInput() != "\\end"
2273 found_end = t.asInput() == "\\end"
2274 && envname == "turn";
2278 envname = p.getArg('{', '}');
2279 only_table = p.next_next_token().asInput() == "\\end"
2280 && envname == "turn";
2284 string const angle = p.getArg('{', '}');
2286 int const save_tablerotation = parent_context.tablerotation;
2287 parent_context.tablerotation = convert<int>(angle);
2288 parse_text(p, os, FLAG_END, outer, parent_context);
2289 parent_context.tablerotation = save_tablerotation;
2299 // This is only attempted at landscape environments that consist only
2300 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2301 // Other landscape environment is handled via the landscape module, thus
2302 // we will fall through in that case.
2303 if (name == "landscape") {
2304 // We check if the next thing is a longtable
2306 bool found_end = false;
2307 bool only_longtable = false;
2308 bool end_longtable = false;
2311 string envname = p.getArg('{', '}');
2312 if (envname == "longtable" || envname == "xltabular") {
2313 // Now we check if the longtable is the only content
2314 // of the landscape environment
2315 string const ltenv = envname;
2316 while (!found_end && !end_longtable && p.good()) {
2317 envname = p.next_token().cat() == catBegin
2318 ? p.getArg('{', '}') : string();
2319 Token const & t = p.get_token();
2321 end_longtable = t.asInput() != "\\end"
2322 && envname == ltenv;
2323 found_end = t.asInput() == "\\end"
2324 && envname == "landscape";
2326 if (end_longtable) {
2328 envname = p.getArg('{', '}');
2329 only_longtable = p.next_next_token().asInput() == "\\end"
2330 && envname == "landscape";
2332 if (only_longtable) {
2335 int const save_tablerotation = parent_context.tablerotation;
2336 parent_context.tablerotation = 90;
2337 parse_text(p, os, FLAG_END, outer, parent_context);
2338 parent_context.tablerotation = save_tablerotation;
2348 if (name == "framed" || name == "shaded") {
2349 eat_whitespace(p, os, parent_context, false);
2350 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2352 preamble.registerAutomaticallyLoadedPackage("framed");
2356 if (name == "listing") {
2357 minted_float = "float";
2358 eat_whitespace(p, os, parent_context, false);
2359 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2361 minted_float += "=" + opt;
2362 // If something precedes \begin{minted}, we output it at the end
2363 // as a caption, in order to keep it inside the listings inset.
2364 eat_whitespace(p, os, parent_context, true);
2366 Token const & t = p.get_token();
2367 p.skip_spaces(true);
2368 string const envname = p.next_token().cat() == catBegin
2369 ? p.getArg('{', '}') : string();
2370 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2372 minted_float_has_caption = false;
2373 string content = parse_text_snippet(p, FLAG_END, outer,
2375 size_t i = content.find("\\begin_inset listings");
2376 bool minted_env = i != string::npos;
2379 caption = content.substr(0, i);
2380 content.erase(0, i);
2382 parent_context.check_layout(os);
2383 if (minted_env && minted_float_has_caption) {
2384 eat_whitespace(p, os, parent_context, true);
2385 os << content << "\n";
2386 if (!caption.empty())
2387 os << caption << "\n";
2388 os << "\n\\end_layout\n"; // close inner layout
2389 end_inset(os); // close caption inset
2390 os << "\n\\end_layout\n"; // close outer layout
2391 } else if (!caption.empty()) {
2393 begin_inset(os, "listings\n");
2394 os << "lstparams " << '"' << minted_float << '"' << '\n';
2395 os << "inline false\n";
2396 os << "status collapsed\n";
2398 os << "\n\\begin_layout Plain Layout\n";
2399 begin_inset(os, "Caption Standard\n");
2400 Context newcontext(true, parent_context.textclass,
2401 0, 0, parent_context.font);
2402 newcontext.check_layout(os);
2403 os << caption << "\n";
2404 newcontext.check_end_layout(os);
2406 os << "\n\\end_layout\n";
2407 } else if (content.empty()) {
2408 begin_inset(os, "listings\n");
2409 os << "lstparams " << '"' << minted_float << '"' << '\n';
2410 os << "inline false\n";
2411 os << "status collapsed\n";
2413 os << content << "\n";
2415 end_inset(os); // close listings inset
2416 parent_context.check_end_layout(os);
2417 parent_context.new_paragraph(os);
2419 minted_float.clear();
2420 minted_float_has_caption = false;
2424 if (name == "lstlisting" || name == "minted") {
2425 bool use_minted = name == "minted";
2426 // with listings, we do not eat newlines here since
2427 // \begin{lstlistings}
2430 // // \begin{lstlistings}%
2433 // reads [foo] as content, whereas
2434 // // \begin{lstlistings}%
2437 // \begin{lstlistings}[foo,
2439 // reads [foo...] as argument.
2440 eat_whitespace(p, os, parent_context, false, use_minted);
2441 if (use_minted && minted_float.empty()) {
2442 // look ahead for a bottom caption
2444 bool found_end_minted = false;
2445 while (!found_end_minted && p.good()) {
2446 Token const & t = p.get_token();
2448 string const envname =
2449 p.next_token().cat() == catBegin
2450 ? p.getArg('{', '}') : string();
2451 found_end_minted = t.asInput() == "\\end"
2452 && envname == "minted";
2454 eat_whitespace(p, os, parent_context, true);
2455 Token const & t = p.get_token();
2456 p.skip_spaces(true);
2457 if (t.asInput() == "\\lyxmintcaption") {
2458 string const pos = p.getArg('[', ']');
2460 string const caption =
2461 parse_text_snippet(p, FLAG_ITEM,
2462 false, parent_context);
2463 minted_nonfloat_caption = "[b]" + caption;
2464 eat_whitespace(p, os, parent_context, true);
2469 parse_listings(p, os, parent_context, false, use_minted);
2474 if (!parent_context.new_layout_allowed) {
2475 parse_unknown_environment(p, name, os, FLAG_END, outer,
2480 // Alignment and spacing settings
2481 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2482 // therefore are totally broken!
2483 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2484 // they are commands not environments. They are furthermore switches that
2485 // can be ended by another switches, but also by commands like \footnote or
2486 // \parbox. So the only safe way is to leave them untouched.
2487 // However, we support the pseudo-environments
2488 // \begin{centering} ... \end{centering}
2489 // \begin{raggedright} ... \end{raggedright}
2490 // \begin{raggedleft} ... \end{raggedleft}
2491 // since they are used by LyX in floats (for spacing reasons)
2492 if (name == "center" || name == "centering"
2493 || name == "flushleft" || name == "raggedright"
2494 || name == "flushright" || name == "raggedleft"
2495 || name == "singlespace" || name == "onehalfspace"
2496 || name == "doublespace" || name == "spacing") {
2497 eat_whitespace(p, os, parent_context, false);
2498 // We must begin a new paragraph if not already done
2499 if (! parent_context.atParagraphStart()) {
2500 parent_context.check_end_layout(os);
2501 parent_context.new_paragraph(os);
2503 if (name == "flushleft" || name == "raggedright")
2504 parent_context.add_extra_stuff("\\align left\n");
2505 else if (name == "flushright" || name == "raggedleft")
2506 parent_context.add_extra_stuff("\\align right\n");
2507 else if (name == "center" || name == "centering")
2508 parent_context.add_extra_stuff("\\align center\n");
2509 else if (name == "singlespace")
2510 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2511 else if (name == "onehalfspace") {
2512 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2513 preamble.registerAutomaticallyLoadedPackage("setspace");
2514 } else if (name == "doublespace") {
2515 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2516 preamble.registerAutomaticallyLoadedPackage("setspace");
2517 } else if (name == "spacing") {
2518 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2519 preamble.registerAutomaticallyLoadedPackage("setspace");
2521 parse_text(p, os, FLAG_END, outer, parent_context);
2522 // Just in case the environment is empty
2523 parent_context.extra_stuff.erase();
2524 // We must begin a new paragraph to reset the alignment
2525 parent_context.new_paragraph(os);
2530 // The single '=' is meant here.
2531 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2532 eat_whitespace(p, os, parent_context, false);
2533 Context context(true, parent_context.textclass, newlayout,
2534 parent_context.layout, parent_context.font);
2535 if (parent_context.deeper_paragraph) {
2536 // We are beginning a nested environment after a
2537 // deeper paragraph inside the outer list environment.
2538 // Therefore we don't need to output a "begin deeper".
2539 context.need_end_deeper = true;
2541 parent_context.check_end_layout(os);
2542 if (last_env == name) {
2543 // we need to output a separator since LyX would export
2544 // the two environments as one otherwise (bug 5716)
2545 TeX2LyXDocClass const & textclass(parent_context.textclass);
2546 Context newcontext(true, textclass,
2547 &(textclass.defaultLayout()));
2548 newcontext.check_layout(os);
2549 begin_inset(os, "Separator plain\n");
2551 newcontext.check_end_layout(os);
2553 switch (context.layout->latextype) {
2554 case LATEX_LIST_ENVIRONMENT:
2555 context.in_list_preamble =
2556 !context.layout->listpreamble().empty()
2557 && p.hasListPreamble(context.layout->itemcommand());
2558 context.add_par_extra_stuff("\\labelwidthstring "
2559 + p.verbatim_item() + '\n');
2562 case LATEX_BIB_ENVIRONMENT:
2563 p.verbatim_item(); // swallow next arg
2569 context.check_deeper(os);
2570 if (newlayout->keepempty) {
2571 // We need to start a new paragraph
2572 // even if it is empty.
2573 context.new_paragraph(os);
2574 context.check_layout(os);
2576 // handle known optional and required arguments
2577 if (context.layout->latextype == LATEX_ENVIRONMENT)
2578 output_arguments(os, p, outer, false, string(), context,
2579 context.layout->latexargs());
2580 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2581 context.in_list_preamble =
2582 !context.layout->listpreamble().empty()
2583 && p.hasListPreamble(context.layout->itemcommand());
2585 output_arguments(oss, p, outer, false, string(), context,
2586 context.layout->latexargs());
2587 context.list_extra_stuff = oss.str();
2589 if (context.in_list_preamble) {
2590 // Collect the stuff between \begin and first \item
2591 context.list_preamble =
2592 parse_text_snippet(p, FLAG_END, outer, context);
2593 context.in_list_preamble = false;
2595 parse_text(p, os, FLAG_END, outer, context);
2596 if (context.layout->latextype == LATEX_ENVIRONMENT)
2597 output_arguments(os, p, outer, false, "post", context,
2598 context.layout->postcommandargs());
2599 context.check_end_layout(os);
2600 if (parent_context.deeper_paragraph) {
2601 // We must suppress the "end deeper" because we
2602 // suppressed the "begin deeper" above.
2603 context.need_end_deeper = false;
2605 context.check_end_deeper(os);
2606 parent_context.new_paragraph(os);
2608 if (!preamble.titleLayoutFound())
2609 preamble.titleLayoutFound(newlayout->intitle);
2610 set<string> const & req = newlayout->required();
2611 set<string>::const_iterator it = req.begin();
2612 set<string>::const_iterator en = req.end();
2613 for (; it != en; ++it)
2614 preamble.registerAutomaticallyLoadedPackage(*it);
2618 // The single '=' is meant here.
2619 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2620 eat_whitespace(p, os, parent_context, false);
2621 parent_context.check_layout(os);
2622 begin_inset(os, "Flex ");
2623 docstring flex_name = newinsetlayout->name();
2624 // FIXME: what do we do if the prefix is not Flex: ?
2625 if (prefixIs(flex_name, from_ascii("Flex:")))
2626 flex_name.erase(0, 5);
2627 os << to_utf8(flex_name) << '\n'
2628 << "status collapsed\n";
2629 if (newinsetlayout->isPassThru()) {
2630 string const arg = p.verbatimEnvironment(name);
2631 Context context(true, parent_context.textclass,
2632 &parent_context.textclass.plainLayout(),
2633 parent_context.layout);
2634 output_ert(os, arg, parent_context);
2636 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2641 if (name == "appendix") {
2642 // This is no good latex style, but it works and is used in some documents...
2643 eat_whitespace(p, os, parent_context, false);
2644 parent_context.check_end_layout(os);
2645 Context context(true, parent_context.textclass, parent_context.layout,
2646 parent_context.layout, parent_context.font);
2647 context.check_layout(os);
2648 os << "\\start_of_appendix\n";
2649 parse_text(p, os, FLAG_END, outer, context);
2650 context.check_end_layout(os);
2655 if (known_environments.find(name) != known_environments.end()) {
2656 vector<ArgumentType> arguments = known_environments[name];
2657 // The last "argument" denotes whether we may translate the
2658 // environment contents to LyX
2659 // The default required if no argument is given makes us
2660 // compatible with the reLyXre environment.
2661 ArgumentType contents = arguments.empty() ?
2664 if (!arguments.empty())
2665 arguments.pop_back();
2666 // See comment in parse_unknown_environment()
2667 bool const specialfont =
2668 (parent_context.font != parent_context.normalfont);
2669 bool const new_layout_allowed =
2670 parent_context.new_layout_allowed;
2672 parent_context.new_layout_allowed = false;
2673 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2674 outer, parent_context);
2675 if (contents == verbatim)
2676 output_ert_inset(os, p.ertEnvironment(name),
2679 parse_text_snippet(p, os, FLAG_END, outer,
2681 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2683 parent_context.new_layout_allowed = new_layout_allowed;
2687 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2692 active_environments.pop_back();
2696 /// parses a comment and outputs it to \p os.
2697 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2698 bool skipNewlines = false)
2700 LASSERT(t.cat() == catComment, return);
2701 if (!t.cs().empty()) {
2702 context.check_layout(os);
2703 output_comment(p, os, t.cs(), context);
2704 if (p.next_token().cat() == catNewline) {
2705 // A newline after a comment line starts a new
2707 if (context.new_layout_allowed) {
2708 if(!context.atParagraphStart())
2709 // Only start a new paragraph if not already
2710 // done (we might get called recursively)
2711 context.new_paragraph(os);
2713 output_ert_inset(os, "\n", context);
2714 eat_whitespace(p, os, context, true);
2716 } else if (!skipNewlines) {
2717 // "%\n" combination
2724 * Reads spaces and comments until the first non-space, non-comment token.
2725 * New paragraphs (double newlines or \\par) are handled like simple spaces
2726 * if \p eatParagraph is true.
2727 * If \p eatNewline is false, newlines won't be treated as whitespace.
2728 * Spaces are skipped, but comments are written to \p os.
2730 void eat_whitespace(Parser & p, ostream & os, Context & context,
2731 bool eatParagraph, bool eatNewline)
2734 Token const & t = p.get_token();
2735 if (t.cat() == catComment)
2736 parse_comment(p, os, t, context, !eatNewline);
2737 else if ((!eatParagraph && p.isParagraph()) ||
2738 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2747 * Set a font attribute, parse text and reset the font attribute.
2748 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2749 * \param currentvalue Current value of the attribute. Is set to the new
2750 * value during parsing.
2751 * \param newvalue New value of the attribute
2753 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2754 Context & context, string const & attribute,
2755 string & currentvalue, string const & newvalue)
2757 context.check_layout(os);
2758 string const oldvalue = currentvalue;
2759 currentvalue = newvalue;
2760 os << '\n' << attribute << ' ' << newvalue << "\n";
2761 parse_text_snippet(p, os, flags, outer, context);
2762 context.check_layout(os);
2763 os << '\n' << attribute << ' ' << oldvalue << "\n";
2764 currentvalue = oldvalue;
2768 /// get the arguments of a natbib or jurabib citation command
2769 void get_cite_arguments(Parser & p, bool natbibOrder,
2770 string & before, string & after, bool const qualified = false)
2772 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2774 // text before the citation
2776 // text after the citation
2777 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2779 if (!after.empty()) {
2780 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2781 if (natbibOrder && !before.empty())
2782 swap(before, after);
2787 void copy_file(FileName const & src, string const & dstname)
2791 string const absParent = getParentFilePath(false);
2793 if (FileName::isAbsolute(dstname))
2794 dst = FileName(dstname);
2796 dst = makeAbsPath(dstname, absParent);
2797 FileName const srcpath = src.onlyPath();
2798 FileName const dstpath = dst.onlyPath();
2799 if (equivalent(srcpath, dstpath))
2801 if (!dstpath.isDirectory()) {
2802 if (!dstpath.createPath()) {
2803 cerr << "Warning: Could not create directory for file `"
2804 << dst.absFileName() << "´." << endl;
2808 if (dst.isReadableFile()) {
2809 if (overwriteFiles())
2810 cerr << "Warning: Overwriting existing file `"
2811 << dst.absFileName() << "´." << endl;
2813 cerr << "Warning: Not overwriting existing file `"
2814 << dst.absFileName() << "´." << endl;
2818 if (!src.copyTo(dst))
2819 cerr << "Warning: Could not copy file `" << src.absFileName()
2820 << "´ to `" << dst.absFileName() << "´." << endl;
2824 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2825 bool parse_chunk(Parser & p, ostream & os, Context & context)
2827 // check whether a chunk is possible here.
2828 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2834 // read the parameters
2835 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2836 if (!params.first) {
2841 Parser::Arg const code = p.verbatimStuff("\n@");
2846 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2847 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2851 // The last newline read is important for paragraph handling
2855 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2856 // We must have a valid layout before outputting the Chunk inset.
2857 context.check_layout(os);
2858 Context chunkcontext(true, context.textclass);
2859 chunkcontext.layout = &context.textclass.plainLayout();
2860 begin_inset(os, "Flex Chunk");
2861 os << "\nstatus open\n";
2862 if (!params.second.empty()) {
2863 chunkcontext.check_layout(os);
2864 Context paramscontext(true, context.textclass);
2865 paramscontext.layout = &context.textclass.plainLayout();
2866 begin_inset(os, "Argument 1");
2867 os << "\nstatus open\n";
2868 output_ert(os, params.second, paramscontext);
2871 output_ert(os, code.second, chunkcontext);
2879 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2880 bool is_macro(Parser & p)
2882 Token first = p.curr_token();
2883 if (first.cat() != catEscape || !p.good())
2885 if (first.cs() == "def")
2887 if (first.cs() != "global" && first.cs() != "long")
2889 Token second = p.get_token();
2891 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2892 second.cat() == catNewline || second.cat() == catComment)) {
2893 second = p.get_token();
2896 bool secondvalid = second.cat() == catEscape;
2898 bool thirdvalid = false;
2899 if (p.good() && first.cs() == "global" && secondvalid &&
2900 second.cs() == "long") {
2901 third = p.get_token();
2903 while (p.good() && !p.isParagraph() &&
2904 (third.cat() == catSpace ||
2905 third.cat() == catNewline ||
2906 third.cat() == catComment)) {
2907 third = p.get_token();
2910 thirdvalid = third.cat() == catEscape;
2912 for (int i = 0; i < pos; ++i)
2917 return (first.cs() == "global" || first.cs() == "long") &&
2918 second.cs() == "def";
2919 return first.cs() == "global" && second.cs() == "long" &&
2920 third.cs() == "def";
2924 /// Parse a macro definition (assumes that is_macro() returned true)
2925 void parse_macro(Parser & p, ostream & os, Context & context)
2927 context.check_layout(os);
2928 Token first = p.curr_token();
2931 string command = first.asInput();
2932 if (first.cs() != "def") {
2934 eat_whitespace(p, os, context, false);
2935 second = p.curr_token();
2936 command += second.asInput();
2937 if (second.cs() != "def") {
2939 eat_whitespace(p, os, context, false);
2940 third = p.curr_token();
2941 command += third.asInput();
2944 eat_whitespace(p, os, context, false);
2945 string const name = p.get_token().cs();
2946 eat_whitespace(p, os, context, false);
2952 while (p.next_token().cat() != catBegin) {
2953 if (p.next_token().cat() == catParameter) {
2958 // followed by number?
2959 if (p.next_token().cat() == catOther) {
2960 string s = p.get_token().asInput();
2962 // number = current arity + 1?
2963 if (s.size() == 1 && s[0] == arity + '0' + 1)
2968 paramtext += p.get_token().cs();
2970 paramtext += p.get_token().cs();
2975 // only output simple (i.e. compatible) macro as FormulaMacros
2976 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2978 context.check_layout(os);
2979 begin_inset(os, "FormulaMacro");
2980 os << "\n\\def" << ert;
2983 output_ert_inset(os, command + ert, context);
2987 void registerExternalTemplatePackages(string const & name)
2989 external::TemplateManager const & etm = external::TemplateManager::get();
2990 external::Template const * const et = etm.getTemplateByName(name);
2993 external::Template::Formats::const_iterator cit = et->formats.end();
2995 cit = et->formats.find("PDFLaTeX");
2996 if (cit == et->formats.end())
2997 // If the template has not specified a PDFLaTeX output,
2998 // we try the LaTeX format.
2999 cit = et->formats.find("LaTeX");
3000 if (cit == et->formats.end())
3002 vector<string>::const_iterator qit = cit->second.requirements.begin();
3003 vector<string>::const_iterator qend = cit->second.requirements.end();
3004 for (; qit != qend; ++qit)
3005 preamble.registerAutomaticallyLoadedPackage(*qit);
3008 } // anonymous namespace
3012 * Find a file with basename \p name in path \p path and an extension
3015 string find_file(string const & name, string const & path,
3016 char const * const * extensions)
3018 for (char const * const * what = extensions; *what; ++what) {
3019 string const trial = addExtension(name, *what);
3020 if (makeAbsPath(trial, path).exists())
3027 /// Convert filenames with TeX macros and/or quotes to something LyX
3029 string const normalize_filename(string const & name)
3034 Token const & t = p.get_token();
3035 if (t.cat() != catEscape)
3037 else if (t.cs() == "lyxdot") {
3038 // This is used by LyX for simple dots in relative
3042 } else if (t.cs() == "space") {
3045 } else if (t.cs() == "string") {
3046 // Convert \string" to " and \string~ to ~
3047 Token const & n = p.next_token();
3048 if (n.asInput() != "\"" && n.asInput() != "~")
3053 // Strip quotes. This is a bit complicated (see latex_path()).
3054 string full = os.str();
3055 if (!full.empty() && full[0] == '"') {
3056 string base = removeExtension(full);
3057 string ext = getExtension(full);
3058 if (!base.empty() && base[base.length()-1] == '"')
3061 return addExtension(trim(base, "\""), ext);
3062 if (full[full.length()-1] == '"')
3065 return trim(full, "\"");
3071 /// Convert \p name from TeX convention (relative to master file) to LyX
3072 /// convention (relative to .lyx file) if it is relative
3073 void fix_child_filename(string & name)
3075 string const absMasterTeX = getMasterFilePath(true);
3076 bool const isabs = FileName::isAbsolute(name);
3077 // convert from "relative to .tex master" to absolute original path
3079 name = makeAbsPath(name, absMasterTeX).absFileName();
3080 bool copyfile = copyFiles();
3081 string const absParentLyX = getParentFilePath(false);
3084 // convert from absolute original path to "relative to master file"
3085 string const rel = to_utf8(makeRelPath(from_utf8(name),
3086 from_utf8(absMasterTeX)));
3087 // re-interpret "relative to .tex file" as "relative to .lyx file"
3088 // (is different if the master .lyx file resides in a
3089 // different path than the master .tex file)
3090 string const absMasterLyX = getMasterFilePath(false);
3091 abs = makeAbsPath(rel, absMasterLyX).absFileName();
3092 // Do not copy if the new path is impossible to create. Example:
3093 // absMasterTeX = "/foo/bar/"
3094 // absMasterLyX = "/bar/"
3095 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
3096 if (contains(name, "/../"))
3103 // convert from absolute original path to
3104 // "relative to .lyx file"
3105 name = to_utf8(makeRelPath(from_utf8(abs),
3106 from_utf8(absParentLyX)));
3110 // convert from absolute original path to "relative to .lyx file"
3111 name = to_utf8(makeRelPath(from_utf8(name),
3112 from_utf8(absParentLyX)));
3117 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
3118 Context & context, string const & rdelim, string const & rdelimesc)
3120 Layout const * newlayout = 0;
3121 InsetLayout const * newinsetlayout = 0;
3122 char const * const * where = 0;
3123 // Store the latest bibliographystyle, addcontentslineContent and
3124 // nocite{*} option (needed for bibtex inset)
3126 string contentslineContent;
3127 // Some classes provide a \bibliographystyle, so do not output
3128 // any if none is explicitly set.
3129 string bibliographystyle;
3130 bool const use_natbib = isProvided("natbib");
3131 bool const use_jurabib = isProvided("jurabib");
3132 bool const use_biblatex = isProvided("biblatex")
3133 && preamble.citeEngine() != "biblatex-natbib";
3134 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
3135 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
3136 need_commentbib = use_biblatex || use_biblatex_natbib;
3139 // it is impossible to determine the correct encoding for non-CJK Japanese.
3140 // Therefore write a note at the beginning of the document
3141 if (is_nonCJKJapanese) {
3142 context.check_layout(os);
3143 begin_inset(os, "Note Note\n");
3144 os << "status open\n\\begin_layout Plain Layout\n"
3145 << "\\series bold\n"
3146 << "Important information:\n"
3147 << "\\end_layout\n\n"
3148 << "\\begin_layout Plain Layout\n"
3149 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
3150 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
3151 << " The iconv encoding " << p.getEncoding() << " was used.\n"
3152 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
3153 << " and specify the encoding using the -e command-line switch.\n"
3154 << " In addition, you might want to double check that the desired output encoding\n"
3155 << " is correctly selected in Document > Settings > Language.\n"
3156 << "\\end_layout\n";
3158 is_nonCJKJapanese = false;
3161 bool have_cycled = false;
3163 // Leave here only after at least one cycle
3164 if (have_cycled && flags & FLAG_LEAVE) {
3165 flags &= ~FLAG_LEAVE;
3169 Token const & t = p.get_token();
3171 debugToken(cerr, t, flags);
3174 if (context.in_list_preamble
3175 && p.next_token().cs() == context.layout->itemcommand()) {
3176 // We are parsing a list preamble. End before first \item.
3177 flags |= FLAG_LEAVE;
3178 context.in_list_preamble = false;
3181 if (flags & FLAG_ITEM) {
3182 if (t.cat() == catSpace)
3185 flags &= ~FLAG_ITEM;
3186 if (t.cat() == catBegin) {
3187 // skip the brace and collect everything to the next matching
3189 flags |= FLAG_BRACE_LAST;
3193 // handle only this single token, leave the loop if done
3194 flags |= FLAG_LEAVE;
3197 if (t.cat() != catEscape && t.character() == ']' &&
3198 (flags & FLAG_BRACK_LAST))
3200 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
3202 string tok = t.asInput();
3203 // we only support delimiters with max 2 chars for now.
3204 if (rdelim.size() > 1)
3205 tok += p.next_token().asInput();
3206 if (t.cat() != catEscape && !rdelim.empty()
3207 && tok == rdelim && (flags & FLAG_RDELIM)
3208 && (rdelimesc.empty() || p.prev_token().asInput() != rdelimesc)) {
3209 if (rdelim.size() > 1)
3210 p.get_token(); // eat rdelim
3214 // If there is anything between \end{env} and \begin{env} we
3215 // don't need to output a separator.
3216 if (t.cat() != catSpace && t.cat() != catNewline &&
3217 t.asInput() != "\\begin")
3224 bool const starred = p.next_token().asInput() == "*";
3225 string const starredname(starred ? (t.cs() + '*') : t.cs());
3226 if (t.cat() == catMath) {
3227 // we are inside some text mode thingy, so opening new math is allowed
3228 context.check_layout(os);
3229 begin_inset(os, "Formula ");
3230 Token const & n = p.get_token();
3231 bool const display(n.cat() == catMath && outer);
3233 // TeX's $$...$$ syntax for displayed math
3235 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3237 p.get_token(); // skip the second '$' token
3239 // simple $...$ stuff
3242 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3247 // Prevent the conversion of a line break to a
3248 // space (bug 7668). This does not change the
3249 // output, but looks ugly in LyX.
3250 eat_whitespace(p, os, context, false);
3255 if (t.cat() == catSuper || t.cat() == catSub) {
3256 cerr << "catcode " << t << " illegal in text mode\n";
3260 // Basic support for quotes. We try to disambiguate
3261 // quotes from the context (e.g., a left english quote is
3262 // the same as a right german quote...).
3263 // Try to make a smart guess about the side
3264 Token const prev = p.prev_token();
3265 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3266 && prev.character() != '\n' && prev.character() != '~');
3267 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3268 context.check_layout(os);
3269 begin_inset(os, "Quotes ");
3270 os << guessQuoteStyle("eld", opening);
3276 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3277 context.check_layout(os);
3278 begin_inset(os, "Quotes ");
3279 os << guessQuoteStyle("erd", opening);
3286 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3287 context.check_layout(os);
3288 begin_inset(os, "Quotes ");
3289 os << guessQuoteStyle("ald", opening);
3296 if (t.asInput() == "<"
3297 && p.next_token().asInput() == "<") {
3298 bool has_chunk = false;
3302 has_chunk = parse_chunk(p, os, context);
3308 context.check_layout(os);
3309 begin_inset(os, "Quotes ");
3310 os << guessQuoteStyle("ard", opening);
3318 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3319 check_space(p, os, context);
3323 // babel shorthands (also used by polyglossia)
3324 // Since these can have different meanings for different languages
3325 // we import them as ERT (but they must be put in ERT to get output
3327 if (t.asInput() == "\"") {
3329 // These are known pairs. We put them together in
3330 // one ERT inset. In other cases (such as "a), only
3331 // the quotation mark is ERTed.
3332 if (p.next_token().asInput() == "\""
3333 || p.next_token().asInput() == "|"
3334 || p.next_token().asInput() == "-"
3335 || p.next_token().asInput() == "~"
3336 || p.next_token().asInput() == "="
3337 || p.next_token().asInput() == "/"
3338 || p.next_token().asInput() == "~"
3339 || p.next_token().asInput() == "'"
3340 || p.next_token().asInput() == "`"
3341 || p.next_token().asInput() == "<"
3342 || p.next_token().asInput() == ">") {
3343 s += p.next_token().asInput();
3346 output_ert_inset(os, s, context);
3350 if (t.character() == '[' && noweb_mode &&
3351 p.next_token().character() == '[') {
3352 // These can contain underscores
3354 string const s = p.getFullOpt() + ']';
3355 if (p.next_token().character() == ']')
3358 cerr << "Warning: Inserting missing ']' in '"
3359 << s << "'." << endl;
3360 output_ert_inset(os, s, context);
3364 if (t.cat() == catLetter) {
3365 context.check_layout(os);
3370 if (t.cat() == catOther ||
3371 t.cat() == catAlign ||
3372 t.cat() == catParameter) {
3373 context.check_layout(os);
3374 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3375 context.merging_hyphens_allowed &&
3376 context.font.family != "ttfamily" &&
3377 !context.layout->pass_thru) {
3378 if (p.next_next_token().asInput() == "-") {
3380 os << to_utf8(docstring(1, 0x2014));
3384 os << to_utf8(docstring(1, 0x2013));
3387 // This translates "&" to "\\&" which may be wrong...
3392 if (p.isParagraph()) {
3393 // In minted floating listings we will collect
3394 // everything into the caption, where multiple
3395 // paragraphs are forbidden.
3396 if (minted_float.empty()) {
3397 if (context.new_layout_allowed)
3398 context.new_paragraph(os);
3400 output_ert_inset(os, "\\par ", context);
3403 eat_whitespace(p, os, context, true);
3407 if (t.cat() == catActive) {
3408 context.check_layout(os);
3409 if (t.character() == '~') {
3410 if (context.layout->free_spacing)
3413 begin_inset(os, "space ~\n");
3421 if (t.cat() == catBegin) {
3422 Token const next = p.next_token();
3423 Token const end = p.next_next_token();
3424 if (next.cat() == catEnd) {
3426 Token const prev = p.prev_token();
3428 if (p.next_token().character() == '`')
3429 ; // ignore it in {}``
3431 output_ert_inset(os, "{}", context);
3432 } else if (next.cat() == catEscape &&
3433 is_known(next.cs(), known_quotes) &&
3434 end.cat() == catEnd) {
3435 // Something like {\textquoteright} (e.g.
3436 // from writer2latex). We may skip the
3437 // braces here for better readability.
3438 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3440 } else if (p.next_token().asInput() == "\\ascii") {
3441 // handle the \ascii characters
3442 // (the case without braces is handled later)
3443 // the code is "{\ascii\xxx}"
3444 p.get_token(); // eat \ascii
3445 string name2 = p.get_token().asInput();
3446 p.get_token(); // eat the final '}'
3447 string const name = "{\\ascii" + name2 + "}";
3451 // get the character from unicodesymbols
3452 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3453 Encodings::TEXT_CMD, termination, rem, &req);
3455 context.check_layout(os);
3458 output_ert_inset(os,
3459 to_utf8(rem), context);
3460 for (set<string>::const_iterator it = req.begin();
3461 it != req.end(); ++it)
3462 preamble.registerAutomaticallyLoadedPackage(*it);
3464 // we did not find a non-ert version
3465 output_ert_inset(os, name, context);
3467 context.check_layout(os);
3468 // special handling of font attribute changes
3469 Token const prev = p.prev_token();
3470 TeXFont const oldFont = context.font;
3471 if (next.character() == '[' ||
3472 next.character() == ']' ||
3473 next.character() == '*') {
3475 if (p.next_token().cat() == catEnd) {
3480 output_ert_inset(os, "{", context);
3481 parse_text_snippet(p, os,
3484 output_ert_inset(os, "}", context);
3486 } else if (! context.new_layout_allowed) {
3487 output_ert_inset(os, "{", context);
3488 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3490 output_ert_inset(os, "}", context);
3491 } else if (is_known(next.cs(), known_sizes)) {
3492 // next will change the size, so we must
3494 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3496 if (!context.atParagraphStart())
3498 << context.font.size << "\n";
3499 } else if (is_known(next.cs(), known_font_families)) {
3500 // next will change the font family, so we
3501 // must reset it here
3502 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3504 if (!context.atParagraphStart())
3506 << context.font.family << "\n";
3507 } else if (is_known(next.cs(), known_font_series)) {
3508 // next will change the font series, so we
3509 // must reset it here
3510 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3512 if (!context.atParagraphStart())
3514 << context.font.series << "\n";
3515 } else if (is_known(next.cs(), known_font_shapes)) {
3516 // next will change the font shape, so we
3517 // must reset it here
3518 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3520 if (!context.atParagraphStart())
3522 << context.font.shape << "\n";
3523 } else if (is_known(next.cs(), known_old_font_families) ||
3524 is_known(next.cs(), known_old_font_series) ||
3525 is_known(next.cs(), known_old_font_shapes)) {
3526 // next will change the font family, series
3527 // and shape, so we must reset it here
3528 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3530 if (!context.atParagraphStart())
3532 << context.font.family
3534 << context.font.series
3536 << context.font.shape << "\n";
3538 output_ert_inset(os, "{", context);
3539 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3541 output_ert_inset(os, "}", context);
3547 if (t.cat() == catEnd) {
3548 if (flags & FLAG_BRACE_LAST) {
3551 cerr << "stray '}' in text\n";
3552 output_ert_inset(os, "}", context);
3556 if (t.cat() == catComment) {
3557 parse_comment(p, os, t, context);
3562 // control sequences
3565 if (t.cs() == "(" || t.cs() == "[") {
3566 bool const simple = t.cs() == "(";
3567 context.check_layout(os);
3568 begin_inset(os, "Formula");
3569 os << " \\" << t.cs();
3570 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3571 os << '\\' << (simple ? ')' : ']');
3574 // Prevent the conversion of a line break to a
3575 // space (bug 7668). This does not change the
3576 // output, but looks ugly in LyX.
3577 eat_whitespace(p, os, context, false);
3582 if (t.cs() == "begin") {
3583 parse_environment(p, os, outer, last_env,
3588 if (t.cs() == "end") {
3589 if (flags & FLAG_END) {
3590 // eat environment name
3591 string const name = p.getArg('{', '}');
3592 if (name != active_environment())
3593 cerr << "\\end{" + name + "} does not match \\begin{"
3594 + active_environment() + "}\n";
3597 p.error("found 'end' unexpectedly");
3601 // "item" by default, but could be something else
3602 if (t.cs() == context.layout->itemcommand()) {
3604 if (context.layout->labeltype == LABEL_MANUAL) {
3605 // FIXME: This swallows comments, but we cannot use
3606 // eat_whitespace() since we must not output
3607 // anything before the item.
3608 p.skip_spaces(true);
3609 s = p.verbatimOption();
3611 p.skip_spaces(false);
3613 context.check_layout(os);
3614 if (context.has_item) {
3615 // An item in an unknown list-like environment
3616 // FIXME: Do this in check_layout()!
3617 context.has_item = false;
3618 string item = "\\" + context.layout->itemcommand();
3621 output_ert_inset(os, item, context);
3623 if (context.layout->labeltype != LABEL_MANUAL)
3624 output_arguments(os, p, outer, false, "item", context,
3625 context.layout->itemargs());
3626 if (!context.list_preamble.empty()) {
3627 // We have a list preamble. Output it here.
3628 begin_inset(os, "Argument listpreamble:1");
3629 os << "\nstatus collapsed\n\n"
3630 << "\\begin_layout Plain Layout\n\n"
3631 << rtrim(context.list_preamble)
3632 << "\n\\end_layout";
3634 context.list_preamble.clear();
3636 if (!context.list_extra_stuff.empty()) {
3637 os << context.list_extra_stuff;
3638 context.list_extra_stuff.clear();
3640 else if (!s.empty()) {
3641 // LyX adds braces around the argument,
3642 // so we need to remove them here.
3643 if (s.size() > 2 && s[0] == '{' &&
3644 s[s.size()-1] == '}')
3645 s = s.substr(1, s.size()-2);
3646 // If the argument contains a space we
3647 // must put it into ERT: Otherwise LyX
3648 // would misinterpret the space as
3649 // item delimiter (bug 7663)
3650 if (contains(s, ' ')) {
3651 output_ert_inset(os, s, context);
3654 os << parse_text_snippet(p2,
3655 FLAG_BRACK_LAST, outer, context);
3657 // The space is needed to separate the
3658 // item from the rest of the sentence.
3660 eat_whitespace(p, os, context, false);
3665 if (t.cs() == "bibitem") {
3667 context.check_layout(os);
3668 eat_whitespace(p, os, context, false);
3669 string label = p.verbatimOption();
3670 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3671 bool const literal = !lbl.first;
3672 label = literal ? subst(label, "\n", " ") : lbl.second;
3673 string lit = literal ? "\"true\"" : "\"false\"";
3674 string key = convert_literate_command_inset_arg(p.verbatim_item());
3675 begin_command_inset(os, "bibitem", "bibitem");
3676 os << "label \"" << label << "\"\n"
3677 << "key \"" << key << "\"\n"
3678 << "literal " << lit << "\n";
3684 // catch the case of \def\inputGnumericTable
3686 if (t.cs() == "def") {
3687 Token second = p.next_token();
3688 if (second.cs() == "inputGnumericTable") {
3692 Token third = p.get_token();
3694 if (third.cs() == "input") {
3698 string name = normalize_filename(p.verbatim_item());
3699 string const path = getMasterFilePath(true);
3700 // We want to preserve relative / absolute filenames,
3701 // therefore path is only used for testing
3702 // The file extension is in every case ".tex".
3703 // So we need to remove this extension and check for
3704 // the original one.
3705 name = removeExtension(name);
3706 if (!makeAbsPath(name, path).exists()) {
3707 char const * const Gnumeric_formats[] = {"gnumeric",
3709 string const Gnumeric_name =
3710 find_file(name, path, Gnumeric_formats);
3711 if (!Gnumeric_name.empty())
3712 name = Gnumeric_name;
3714 FileName const absname = makeAbsPath(name, path);
3715 if (absname.exists()) {
3716 fix_child_filename(name);
3717 copy_file(absname, name);
3719 cerr << "Warning: Could not find file '"
3720 << name << "'." << endl;
3721 context.check_layout(os);
3722 begin_inset(os, "External\n\ttemplate ");
3723 os << "GnumericSpreadsheet\n\tfilename "
3726 context.check_layout(os);
3728 // register the packages that are automatically loaded
3729 // by the Gnumeric template
3730 registerExternalTemplatePackages("GnumericSpreadsheet");
3735 parse_macro(p, os, context);
3739 if (t.cs() == "noindent") {
3741 context.add_par_extra_stuff("\\noindent\n");
3745 if (t.cs() == "appendix") {
3746 context.add_par_extra_stuff("\\start_of_appendix\n");
3747 // We need to start a new paragraph. Otherwise the
3748 // appendix in 'bla\appendix\chapter{' would start
3750 context.new_paragraph(os);
3751 // We need to make sure that the paragraph is
3752 // generated even if it is empty. Otherwise the
3753 // appendix in '\par\appendix\par\chapter{' would
3755 context.check_layout(os);
3756 // FIXME: This is a hack to prevent paragraph
3757 // deletion if it is empty. Handle this better!
3758 output_comment(p, os,
3759 "dummy comment inserted by tex2lyx to "
3760 "ensure that this paragraph is not empty",
3762 // Both measures above may generate an additional
3763 // empty paragraph, but that does not hurt, because
3764 // whitespace does not matter here.
3765 eat_whitespace(p, os, context, true);
3769 // Must catch empty dates before findLayout is called below
3770 if (t.cs() == "date") {
3771 eat_whitespace(p, os, context, false);
3773 string const date = p.verbatim_item();
3776 preamble.suppressDate(true);
3779 preamble.suppressDate(false);
3780 if (context.new_layout_allowed &&
3781 (newlayout = findLayout(context.textclass,
3784 output_command_layout(os, p, outer,
3785 context, newlayout);
3786 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3787 if (!preamble.titleLayoutFound())
3788 preamble.titleLayoutFound(newlayout->intitle);
3789 set<string> const & req = newlayout->required();
3790 set<string>::const_iterator it = req.begin();
3791 set<string>::const_iterator en = req.end();
3792 for (; it != en; ++it)
3793 preamble.registerAutomaticallyLoadedPackage(*it);
3795 output_ert_inset(os,
3796 "\\date{" + p.verbatim_item() + '}',
3802 // Before we look for the layout name with star and alone below, we check the layouts including
3803 // the LateXParam, which might be one or several options or a star.
3804 // The single '=' is meant here.
3805 if (context.new_layout_allowed &&
3806 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3807 // store the latexparam here. This is eaten in output_command_layout
3808 context.latexparam = newlayout->latexparam();
3810 output_command_layout(os, p, outer, context, newlayout);
3811 context.latexparam.clear();
3813 if (!preamble.titleLayoutFound())
3814 preamble.titleLayoutFound(newlayout->intitle);
3815 set<string> const & req = newlayout->required();
3816 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3817 preamble.registerAutomaticallyLoadedPackage(*it);
3821 // Starred section headings
3822 // Must attempt to parse "Section*" before "Section".
3823 if ((p.next_token().asInput() == "*") &&
3824 context.new_layout_allowed &&
3825 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3828 output_command_layout(os, p, outer, context, newlayout);
3830 if (!preamble.titleLayoutFound())
3831 preamble.titleLayoutFound(newlayout->intitle);
3832 set<string> const & req = newlayout->required();
3833 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3834 preamble.registerAutomaticallyLoadedPackage(*it);
3838 // Section headings and the like
3839 if (context.new_layout_allowed &&
3840 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3842 output_command_layout(os, p, outer, context, newlayout);
3844 if (!preamble.titleLayoutFound())
3845 preamble.titleLayoutFound(newlayout->intitle);
3846 set<string> const & req = newlayout->required();
3847 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3848 preamble.registerAutomaticallyLoadedPackage(*it);
3852 if (t.cs() == "subfloat") {
3853 // the syntax is \subfloat[list entry][sub caption]{content}
3854 // if it is a table of figure depends on the surrounding float
3856 // do nothing if there is no outer float
3857 if (!float_type.empty()) {
3858 context.check_layout(os);
3860 begin_inset(os, "Float " + float_type + "\n");
3862 << "\nsideways false"
3863 << "\nstatus collapsed\n\n";
3866 bool has_caption = false;
3867 if (p.next_token().cat() != catEscape &&
3868 p.next_token().character() == '[') {
3869 p.get_token(); // eat '['
3870 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3873 // In case we have two optional args, the second is the caption.
3874 if (p.next_token().cat() != catEscape &&
3875 p.next_token().character() == '[') {
3876 p.get_token(); // eat '['
3877 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3880 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3881 // the caption comes always as the last
3883 // we must make sure that the caption gets a \begin_layout
3884 os << "\n\\begin_layout Plain Layout";
3886 begin_inset(os, "Caption Standard\n");
3887 Context newcontext(true, context.textclass,
3888 0, 0, context.font);
3889 newcontext.check_layout(os);
3890 os << caption << "\n";
3891 newcontext.check_end_layout(os);
3894 // close the layout we opened
3895 os << "\n\\end_layout";
3900 // if the float type is not supported or there is no surrounding float
3905 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3907 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3909 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3910 + "{" + p.verbatim_item() + '}', context);
3915 if (t.cs() == "xymatrix") {
3916 // we must open a new math because LyX's xy support is in math
3917 context.check_layout(os);
3918 begin_inset(os, "Formula ");
3920 os << "\\" << t.cs() << '{';
3921 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3924 preamble.registerAutomaticallyLoadedPackage("xy");
3928 if (t.cs() == "includegraphics") {
3929 bool const clip = p.next_token().asInput() == "*";
3932 string const arg = p.getArg('[', ']');
3933 map<string, string> opts;
3934 vector<string> keys;
3935 split_map(arg, opts, keys);
3937 opts["clip"] = string();
3938 string name = normalize_filename(p.verbatim_item());
3940 string const path = getMasterFilePath(true);
3941 // We want to preserve relative / absolute filenames,
3942 // therefore path is only used for testing
3943 if (!makeAbsPath(name, path).exists()) {
3944 // The file extension is probably missing.
3945 // Now try to find it out.
3946 string const dvips_name =
3947 find_file(name, path,
3948 known_dvips_graphics_formats);
3949 string const pdftex_name =
3950 find_file(name, path,
3951 known_pdftex_graphics_formats);
3952 if (!dvips_name.empty()) {
3953 if (!pdftex_name.empty()) {
3954 cerr << "This file contains the "
3956 "\"\\includegraphics{"
3958 "However, files\n\""
3959 << dvips_name << "\" and\n\""
3960 << pdftex_name << "\"\n"
3961 "both exist, so I had to make a "
3962 "choice and took the first one.\n"
3963 "Please move the unwanted one "
3964 "someplace else and try again\n"
3965 "if my choice was wrong."
3969 } else if (!pdftex_name.empty()) {
3975 FileName const absname = makeAbsPath(name, path);
3976 if (absname.exists()) {
3977 fix_child_filename(name);
3978 copy_file(absname, name);
3980 cerr << "Warning: Could not find graphics file '"
3981 << name << "'." << endl;
3983 context.check_layout(os);
3984 begin_inset(os, "Graphics ");
3985 os << "\n\tfilename " << name << '\n';
3986 if (opts.find("width") != opts.end())
3988 << translate_len(opts["width"]) << '\n';
3989 if (opts.find("totalheight") != opts.end())
3991 << translate_len(opts["totalheight"]) << '\n';
3992 if (opts.find("scale") != opts.end()) {
3993 istringstream iss(opts["scale"]);
3997 os << "\tscale " << val << '\n';
3999 if (opts.find("angle") != opts.end()) {
4000 os << "\trotateAngle "
4001 << opts["angle"] << '\n';
4002 vector<string>::const_iterator a =
4003 find(keys.begin(), keys.end(), "angle");
4004 vector<string>::const_iterator s =
4005 find(keys.begin(), keys.end(), "width");
4006 if (s == keys.end())
4007 s = find(keys.begin(), keys.end(), "totalheight");
4008 if (s == keys.end())
4009 s = find(keys.begin(), keys.end(), "scale");
4010 if (s != keys.end() && distance(s, a) > 0)
4011 os << "\tscaleBeforeRotation\n";
4013 if (opts.find("origin") != opts.end()) {
4015 string const opt = opts["origin"];
4016 if (opt.find('l') != string::npos) ss << "left";
4017 if (opt.find('r') != string::npos) ss << "right";
4018 if (opt.find('c') != string::npos) ss << "center";
4019 if (opt.find('t') != string::npos) ss << "Top";
4020 if (opt.find('b') != string::npos) ss << "Bottom";
4021 if (opt.find('B') != string::npos) ss << "Baseline";
4022 if (!ss.str().empty())
4023 os << "\trotateOrigin " << ss.str() << '\n';
4025 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4027 if (opts.find("keepaspectratio") != opts.end())
4028 os << "\tkeepAspectRatio\n";
4029 if (opts.find("clip") != opts.end())
4031 if (opts.find("draft") != opts.end())
4033 if (opts.find("bb") != opts.end())
4034 os << "\tBoundingBox "
4035 << opts["bb"] << '\n';
4036 int numberOfbbOptions = 0;
4037 if (opts.find("bbllx") != opts.end())
4038 numberOfbbOptions++;
4039 if (opts.find("bblly") != opts.end())
4040 numberOfbbOptions++;
4041 if (opts.find("bburx") != opts.end())
4042 numberOfbbOptions++;
4043 if (opts.find("bbury") != opts.end())
4044 numberOfbbOptions++;
4045 if (numberOfbbOptions == 4)
4046 os << "\tBoundingBox "
4047 << opts["bbllx"] << " " << opts["bblly"] << " "
4048 << opts["bburx"] << " " << opts["bbury"] << '\n';
4049 else if (numberOfbbOptions > 0)
4050 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
4051 numberOfbbOptions = 0;
4052 if (opts.find("natwidth") != opts.end())
4053 numberOfbbOptions++;
4054 if (opts.find("natheight") != opts.end())
4055 numberOfbbOptions++;
4056 if (numberOfbbOptions == 2)
4057 os << "\tBoundingBox 0bp 0bp "
4058 << opts["natwidth"] << " " << opts["natheight"] << '\n';
4059 else if (numberOfbbOptions > 0)
4060 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
4061 ostringstream special;
4062 if (opts.find("hiresbb") != opts.end())
4063 special << "hiresbb,";
4064 if (opts.find("trim") != opts.end())
4066 if (opts.find("viewport") != opts.end())
4067 special << "viewport=" << opts["viewport"] << ',';
4068 if (opts.find("height") != opts.end())
4069 special << "height=" << opts["height"] << ',';
4070 if (opts.find("type") != opts.end())
4071 special << "type=" << opts["type"] << ',';
4072 if (opts.find("ext") != opts.end())
4073 special << "ext=" << opts["ext"] << ',';
4074 if (opts.find("read") != opts.end())
4075 special << "read=" << opts["read"] << ',';
4076 if (opts.find("command") != opts.end())
4077 special << "command=" << opts["command"] << ',';
4078 string s_special = special.str();
4079 if (!s_special.empty()) {
4080 // We had special arguments. Remove the trailing ','.
4081 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
4083 // TODO: Handle the unknown settings better.
4084 // Warn about invalid options.
4085 // Check whether some option was given twice.
4087 preamble.registerAutomaticallyLoadedPackage("graphicx");
4091 if (t.cs() == "footnote" ||
4092 (t.cs() == "thanks" && context.layout->intitle)) {
4094 context.check_layout(os);
4095 begin_inset(os, "Foot\n");
4096 os << "status collapsed\n\n";
4097 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4102 if (t.cs() == "marginpar") {
4104 context.check_layout(os);
4105 begin_inset(os, "Marginal\n");
4106 os << "status collapsed\n\n";
4107 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4112 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
4113 bool const use_minted = t.cs() == "mintinline";
4115 parse_listings(p, os, context, true, use_minted);
4119 if (t.cs() == "ensuremath") {
4121 context.check_layout(os);
4122 string const s = p.verbatim_item();
4123 //FIXME: this never triggers in UTF8
4124 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
4127 output_ert_inset(os, "\\ensuremath{" + s + "}",
4132 else if (t.cs() == "makeindex"
4133 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
4134 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
4135 if (preamble.titleLayoutFound()) {
4137 skip_spaces_braces(p);
4139 output_ert_inset(os, t.asInput(), context);
4143 if (t.cs() == "tableofcontents"
4144 || t.cs() == "lstlistoflistings"
4145 || t.cs() == "listoflistings") {
4146 string name = t.cs();
4147 if (preamble.minted() && name == "listoflistings")
4148 name.insert(0, "lst");
4149 context.check_layout(os);
4150 begin_command_inset(os, "toc", name);
4152 skip_spaces_braces(p);
4153 if (name == "lstlistoflistings") {
4154 if (preamble.minted())
4155 preamble.registerAutomaticallyLoadedPackage("minted");
4157 preamble.registerAutomaticallyLoadedPackage("listings");
4162 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
4163 context.check_layout(os);
4164 if (t.cs() == "listoffigures")
4165 begin_inset(os, "FloatList figure\n");
4167 begin_inset(os, "FloatList table\n");
4169 skip_spaces_braces(p);
4173 if (t.cs() == "listof") {
4174 p.skip_spaces(true);
4175 string const name = p.verbatim_item();
4176 if (context.textclass.floats().typeExist(name)) {
4177 context.check_layout(os);
4178 begin_inset(os, "FloatList ");
4181 p.verbatim_item(); // swallow second arg
4183 output_ert_inset(os, "\\listof{" + name + "}", context);
4187 if (t.cs() == "theendnotes"
4188 || (t.cs() == "printendnotes"
4189 && p.next_token().asInput() != "*"
4191 context.check_layout(os);
4192 begin_inset(os, "FloatList endnote\n");
4194 skip_spaces_braces(p);
4198 if ((where = is_known(t.cs(), known_text_font_families))) {
4199 parse_text_attributes(p, os, FLAG_ITEM, outer,
4200 context, "\\family", context.font.family,
4201 known_coded_font_families[where - known_text_font_families]);
4205 // beamer has a \textbf<overlay>{} inset
4206 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
4207 parse_text_attributes(p, os, FLAG_ITEM, outer,
4208 context, "\\series", context.font.series,
4209 known_coded_font_series[where - known_text_font_series]);
4213 // beamer has a \textit<overlay>{} inset
4214 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4215 parse_text_attributes(p, os, FLAG_ITEM, outer,
4216 context, "\\shape", context.font.shape,
4217 known_coded_font_shapes[where - known_text_font_shapes]);
4221 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4222 context.check_layout(os);
4223 TeXFont oldFont = context.font;
4224 context.font.init();
4225 context.font.size = oldFont.size;
4226 os << "\n\\family " << context.font.family << "\n";
4227 os << "\n\\series " << context.font.series << "\n";
4228 os << "\n\\shape " << context.font.shape << "\n";
4229 if (t.cs() == "textnormal") {
4230 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4231 output_font_change(os, context.font, oldFont);
4232 context.font = oldFont;
4234 eat_whitespace(p, os, context, false);
4238 if (t.cs() == "textcolor") {
4239 // scheme is \textcolor{color name}{text}
4240 string const color = p.verbatim_item();
4241 // we support the predefined colors of the color and the xcolor package
4242 if (color == "black" || color == "blue" || color == "cyan"
4243 || color == "green" || color == "magenta" || color == "red"
4244 || color == "white" || color == "yellow") {
4245 context.check_layout(os);
4246 os << "\n\\color " << color << "\n";
4247 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4248 context.check_layout(os);
4249 os << "\n\\color inherit\n";
4250 preamble.registerAutomaticallyLoadedPackage("color");
4251 } else if (color == "brown" || color == "darkgray" || color == "gray"
4252 || color == "lightgray" || color == "lime" || color == "olive"
4253 || color == "orange" || color == "pink" || color == "purple"
4254 || color == "teal" || color == "violet") {
4255 context.check_layout(os);
4256 os << "\n\\color " << color << "\n";
4257 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4258 context.check_layout(os);
4259 os << "\n\\color inherit\n";
4260 preamble.registerAutomaticallyLoadedPackage("xcolor");
4262 // for custom defined colors
4263 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4267 if (t.cs() == "underbar" || t.cs() == "uline") {
4268 // \underbar is not 100% correct (LyX outputs \uline
4269 // of ulem.sty). The difference is that \ulem allows
4270 // line breaks, and \underbar does not.
4271 // Do NOT handle \underline.
4272 // \underbar cuts through y, g, q, p etc.,
4273 // \underline does not.
4274 context.check_layout(os);
4275 os << "\n\\bar under\n";
4276 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4277 context.check_layout(os);
4278 os << "\n\\bar default\n";
4279 preamble.registerAutomaticallyLoadedPackage("ulem");
4283 if (t.cs() == "sout") {
4284 context.check_layout(os);
4285 os << "\n\\strikeout on\n";
4286 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4287 context.check_layout(os);
4288 os << "\n\\strikeout default\n";
4289 preamble.registerAutomaticallyLoadedPackage("ulem");
4293 // beamer has an \emph<overlay>{} inset
4294 if ((t.cs() == "uuline" || t.cs() == "uwave"
4295 || t.cs() == "emph" || t.cs() == "noun"
4296 || t.cs() == "xout") && !p.hasOpt("<")) {
4297 context.check_layout(os);
4298 os << "\n\\" << t.cs() << " on\n";
4299 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4300 context.check_layout(os);
4301 os << "\n\\" << t.cs() << " default\n";
4302 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4303 preamble.registerAutomaticallyLoadedPackage("ulem");
4307 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4308 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4309 context.check_layout(os);
4312 initials = p.getArg('[', ']');
4314 string name = p.getArg('{', '}');
4315 string localtime = p.getArg('{', '}');
4316 preamble.registerAuthor(name, initials);
4317 Author const & author = preamble.getAuthor(name);
4318 // from_asctime_utc() will fail if LyX decides to output the
4319 // time in the text language.
4320 time_t ptime = from_asctime_utc(localtime);
4321 if (ptime == static_cast<time_t>(-1)) {
4322 cerr << "Warning: Could not parse time `" << localtime
4323 << "´ for change tracking, using current time instead.\n";
4324 ptime = current_time();
4326 if (t.cs() == "lyxadded")
4327 os << "\n\\change_inserted ";
4329 os << "\n\\change_deleted ";
4330 os << author.bufferId() << ' ' << ptime << '\n';
4331 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4332 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4333 LaTeXPackages::isAvailable("xcolor");
4334 // No need to test for luatex, since luatex comes in
4335 // two flavours (dvi and pdf), like latex, and those
4336 // are detected by pdflatex.
4337 if (pdflatex || xetex) {
4339 preamble.registerAutomaticallyLoadedPackage("ulem");
4340 preamble.registerAutomaticallyLoadedPackage("xcolor");
4341 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4345 preamble.registerAutomaticallyLoadedPackage("ulem");
4346 preamble.registerAutomaticallyLoadedPackage("xcolor");
4352 if (t.cs() == "textipa") {
4353 context.check_layout(os);
4354 begin_inset(os, "IPA\n");
4355 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4356 context.merging_hyphens_allowed = false;
4357 set<string> pass_thru_cmds = context.pass_thru_cmds;
4358 // These commands have special meanings in IPA
4359 context.pass_thru_cmds.insert("!");
4360 context.pass_thru_cmds.insert(";");
4361 context.pass_thru_cmds.insert(":");
4362 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4363 context.pass_thru_cmds = pass_thru_cmds;
4364 context.merging_hyphens_allowed = merging_hyphens_allowed;
4366 preamble.registerAutomaticallyLoadedPackage("tipa");
4367 preamble.registerAutomaticallyLoadedPackage("tipx");
4371 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4372 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4373 context.check_layout(os);
4377 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4378 begin_inset(os, "IPADeco " + type + "\n");
4379 os << "status open\n";
4380 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4386 if (t.cs() == "textvertline") {
4387 // FIXME: This is not correct, \textvertline is higher than |
4393 if (t.cs() == "tone" ) {
4394 context.check_layout(os);
4395 // register the tone package
4396 preamble.registerAutomaticallyLoadedPackage("tone");
4397 string content = trimSpaceAndEol(p.verbatim_item());
4398 string command = t.asInput() + "{" + content + "}";
4399 // some tones can be detected by unicodesymbols, some need special code
4400 if (is_known(content, known_tones)) {
4401 os << "\\IPAChar " << command << "\n";
4404 // try to see whether the string is in unicodesymbols
4408 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4409 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4410 termination, rem, &req);
4414 output_ert_inset(os, to_utf8(rem), context);
4415 for (set<string>::const_iterator it = req.begin();
4416 it != req.end(); ++it)
4417 preamble.registerAutomaticallyLoadedPackage(*it);
4419 // we did not find a non-ert version
4420 output_ert_inset(os, command, context);
4424 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4425 t.cs() == "vphantom") {
4426 context.check_layout(os);
4427 if (t.cs() == "phantom")
4428 begin_inset(os, "Phantom Phantom\n");
4429 if (t.cs() == "hphantom")
4430 begin_inset(os, "Phantom HPhantom\n");
4431 if (t.cs() == "vphantom")
4432 begin_inset(os, "Phantom VPhantom\n");
4433 os << "status open\n";
4434 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4440 if (t.cs() == "href") {
4441 context.check_layout(os);
4442 string target = convert_literate_command_inset_arg(p.verbatim_item());
4443 string name = p.verbatim_item();
4444 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4445 bool const literal = !nm.first;
4446 name = literal ? subst(name, "\n", " ") : nm.second;
4447 string lit = literal ? "\"true\"" : "\"false\"";
4449 size_t i = target.find(':');
4450 if (i != string::npos) {
4451 type = target.substr(0, i + 1);
4452 if (type == "mailto:" || type == "file:")
4453 target = target.substr(i + 1);
4454 // handle the case that name is equal to target, except of "http(s)://"
4455 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4458 begin_command_inset(os, "href", "href");
4460 os << "name \"" << name << "\"\n";
4461 os << "target \"" << target << "\"\n";
4462 if (type == "mailto:" || type == "file:")
4463 os << "type \"" << type << "\"\n";
4464 os << "literal " << lit << "\n";
4466 skip_spaces_braces(p);
4470 if (t.cs() == "lyxline") {
4471 // swallow size argument (it is not used anyway)
4473 if (!context.atParagraphStart()) {
4474 // so our line is in the middle of a paragraph
4475 // we need to add a new line, lest this line
4476 // follow the other content on that line and
4477 // run off the side of the page
4478 // FIXME: This may create an empty paragraph,
4479 // but without that it would not be
4480 // possible to set noindent below.
4481 // Fortunately LaTeX does not care
4482 // about the empty paragraph.
4483 context.new_paragraph(os);
4485 if (preamble.indentParagraphs()) {
4486 // we need to unindent, lest the line be too long
4487 context.add_par_extra_stuff("\\noindent\n");
4489 context.check_layout(os);
4490 begin_command_inset(os, "line", "rule");
4491 os << "offset \"0.5ex\"\n"
4492 "width \"100line%\"\n"
4498 if (t.cs() == "rule") {
4499 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4500 string const width = p.getArg('{', '}');
4501 string const thickness = p.getArg('{', '}');
4502 context.check_layout(os);
4503 begin_command_inset(os, "line", "rule");
4504 if (!offset.empty())
4505 os << "offset \"" << translate_len(offset) << "\"\n";
4506 os << "width \"" << translate_len(width) << "\"\n"
4507 "height \"" << translate_len(thickness) << "\"\n";
4512 // Handle refstyle first in order to to catch \eqref, because this
4513 // can also occur without refstyle. Only recognize these commands if
4514 // refstyle.sty was found in the preamble (otherwise \eqref
4515 // and user defined ref commands could be misdetected).
4516 // We uncapitalize the input in order to catch capitalized commands
4518 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4519 && preamble.refstyle()) {
4520 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4521 string plural = "false";
4522 // Catch the plural option [s]
4524 string const opt = p.getOpt();
4528 // LyX does not yet support other optional arguments of ref commands
4529 output_ert_inset(os, t.asInput() + opt + "{" +
4530 p.verbatim_item() + '}', context);
4534 context.check_layout(os);
4535 begin_command_inset(os, "ref", "formatted");
4536 os << "reference \"";
4537 os << known_refstyle_prefixes[where - known_refstyle_commands]
4539 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4541 os << "plural \"" << plural << "\"\n";
4542 os << "caps \"" << cap << "\"\n";
4543 os << "noprefix \"false\"\n";
4545 preamble.registerAutomaticallyLoadedPackage("refstyle");
4549 // if refstyle is used, we must not convert \prettyref to a
4550 // formatted reference, since that would result in a refstyle command.
4551 if ((where = is_known(t.cs(), known_ref_commands)) &&
4552 (t.cs() != "prettyref" || !preamble.refstyle())) {
4553 string const opt = p.getOpt();
4555 context.check_layout(os);
4556 begin_command_inset(os, "ref",
4557 known_coded_ref_commands[where - known_ref_commands]);
4558 os << "reference \""
4559 << convert_literate_command_inset_arg(p.verbatim_item())
4561 os << "plural \"false\"\n";
4562 os << "caps \"false\"\n";
4563 os << "noprefix \"false\"\n";
4565 if (t.cs() == "vref" || t.cs() == "vpageref")
4566 preamble.registerAutomaticallyLoadedPackage("varioref");
4567 else if (t.cs() == "prettyref")
4568 preamble.registerAutomaticallyLoadedPackage("prettyref");
4570 // LyX does not yet support optional arguments of ref commands
4571 output_ert_inset(os, t.asInput() + opt + "{" +
4572 p.verbatim_item() + '}', context);
4578 is_known(t.cs(), known_natbib_commands) &&
4579 ((t.cs() != "citefullauthor" &&
4580 t.cs() != "citeyear" &&
4581 t.cs() != "citeyearpar") ||
4582 p.next_token().asInput() != "*")) {
4583 context.check_layout(os);
4584 string command = t.cs();
4585 if (p.next_token().asInput() == "*") {
4589 if (command == "citefullauthor")
4590 // alternative name for "\\citeauthor*"
4591 command = "citeauthor*";
4593 // text before the citation
4595 // text after the citation
4597 get_cite_arguments(p, true, before, after);
4599 if (command == "cite") {
4600 // \cite without optional argument means
4601 // \citet, \cite with at least one optional
4602 // argument means \citep.
4603 if (before.empty() && after.empty())
4608 if (before.empty() && after == "[]")
4609 // avoid \citet[]{a}
4611 else if (before == "[]" && after == "[]") {
4612 // avoid \citet[][]{a}
4616 bool literal = false;
4617 pair<bool, string> aft;
4618 pair<bool, string> bef;
4619 // remove the brackets around after and before
4620 if (!after.empty()) {
4622 after.erase(after.length() - 1, 1);
4623 aft = convert_latexed_command_inset_arg(after);
4624 literal = !aft.first;
4625 after = literal ? subst(after, "\n", " ") : aft.second;
4627 if (!before.empty()) {
4629 before.erase(before.length() - 1, 1);
4630 bef = convert_latexed_command_inset_arg(before);
4631 literal |= !bef.first;
4632 before = literal ? subst(before, "\n", " ") : bef.second;
4633 if (literal && !after.empty())
4634 after = subst(after, "\n", " ");
4636 string lit = literal ? "\"true\"" : "\"false\"";
4637 begin_command_inset(os, "citation", command);
4638 os << "after " << '"' << after << '"' << "\n";
4639 os << "before " << '"' << before << '"' << "\n";
4641 << convert_literate_command_inset_arg(p.verbatim_item())
4643 << "literal " << lit << "\n";
4645 // Need to set the cite engine if natbib is loaded by
4646 // the document class directly
4647 if (preamble.citeEngine() == "basic")
4648 preamble.citeEngine("natbib");
4653 && is_known(t.cs(), known_biblatex_commands)
4654 && ((t.cs() == "cite"
4655 || t.cs() == "citeauthor"
4656 || t.cs() == "Citeauthor"
4657 || t.cs() == "parencite"
4658 || t.cs() == "citetitle")
4659 || p.next_token().asInput() != "*"))
4660 || (use_biblatex_natbib
4661 && (is_known(t.cs(), known_biblatex_commands)
4662 || is_known(t.cs(), known_natbib_commands))
4663 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4664 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4665 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4666 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4667 || t.cs() == "parencite" || t.cs() == "citetitle")
4668 || p.next_token().asInput() != "*"))){
4669 context.check_layout(os);
4670 string command = t.cs();
4671 if (p.next_token().asInput() == "*") {
4676 bool const qualified = suffixIs(command, "s");
4678 command = rtrim(command, "s");
4680 // text before the citation
4682 // text after the citation
4684 get_cite_arguments(p, true, before, after, qualified);
4686 // These use natbib cmd names in LyX
4687 // for inter-citeengine compativility
4688 if (command == "citeyear")
4689 command = "citebyear";
4690 else if (command == "cite*")
4691 command = "citeyear";
4692 else if (command == "textcite")
4694 else if (command == "Textcite")
4696 else if (command == "parencite")
4698 else if (command == "Parencite")
4700 else if (command == "parencite*")
4701 command = "citeyearpar";
4702 else if (command == "smartcite")
4703 command = "footcite";
4704 else if (command == "Smartcite")
4705 command = "Footcite";
4707 string const emptyarg = qualified ? "()" : "[]";
4708 if (before.empty() && after == emptyarg)
4711 else if (before == emptyarg && after == emptyarg) {
4712 // avoid \cite[][]{a}
4716 bool literal = false;
4717 pair<bool, string> aft;
4718 pair<bool, string> bef;
4719 // remove the brackets around after and before
4720 if (!after.empty()) {
4722 after.erase(after.length() - 1, 1);
4723 aft = convert_latexed_command_inset_arg(after);
4724 literal = !aft.first;
4725 after = literal ? subst(after, "\n", " ") : aft.second;
4727 if (!before.empty()) {
4729 before.erase(before.length() - 1, 1);
4730 bef = convert_latexed_command_inset_arg(before);
4731 literal |= !bef.first;
4732 before = literal ? subst(before, "\n", " ") : bef.second;
4734 string keys, pretextlist, posttextlist;
4736 vector<pair<string, string>> pres, posts, preslit, postslit;
4737 vector<string> lkeys;
4738 // text before the citation
4739 string lbefore, lbeforelit;
4740 // text after the citation
4741 string lafter, lafterlit;
4743 pair<bool, string> laft, lbef;
4745 get_cite_arguments(p, true, lbefore, lafter);
4746 // remove the brackets around after and before
4747 if (!lafter.empty()) {
4749 lafter.erase(lafter.length() - 1, 1);
4750 laft = convert_latexed_command_inset_arg(lafter);
4751 literal |= !laft.first;
4752 lafter = laft.second;
4753 lafterlit = subst(lafter, "\n", " ");
4755 if (!lbefore.empty()) {
4756 lbefore.erase(0, 1);
4757 lbefore.erase(lbefore.length() - 1, 1);
4758 lbef = convert_latexed_command_inset_arg(lbefore);
4759 literal |= !lbef.first;
4760 lbefore = lbef.second;
4761 lbeforelit = subst(lbefore, "\n", " ");
4763 if (lbefore.empty() && lafter == "[]") {
4768 else if (lbefore == "[]" && lafter == "[]") {
4769 // avoid \cite[][]{a}
4775 lkey = p.getArg('{', '}');
4778 pres.push_back(make_pair(lkey, lbefore));
4779 preslit.push_back(make_pair(lkey, lbeforelit));
4780 posts.push_back(make_pair(lkey, lafter));
4781 postslit.push_back(make_pair(lkey, lafterlit));
4782 lkeys.push_back(lkey);
4784 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4789 for (auto const & ptl : pres) {
4790 if (!pretextlist.empty())
4791 pretextlist += '\t';
4792 pretextlist += ptl.first;
4793 if (!ptl.second.empty())
4794 pretextlist += " " + ptl.second;
4796 for (auto const & potl : posts) {
4797 if (!posttextlist.empty())
4798 posttextlist += '\t';
4799 posttextlist += potl.first;
4800 if (!potl.second.empty())
4801 posttextlist += " " + potl.second;
4804 keys = convert_literate_command_inset_arg(p.verbatim_item());
4807 after = subst(after, "\n", " ");
4808 if (!before.empty())
4809 before = subst(after, "\n", " ");
4811 string lit = literal ? "\"true\"" : "\"false\"";
4812 begin_command_inset(os, "citation", command);
4813 os << "after " << '"' << after << '"' << "\n";
4814 os << "before " << '"' << before << '"' << "\n";
4818 if (!pretextlist.empty())
4819 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4820 if (!posttextlist.empty())
4821 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4822 os << "literal " << lit << "\n";
4824 // Need to set the cite engine if biblatex is loaded by
4825 // the document class directly
4826 if (preamble.citeEngine() == "basic")
4827 use_biblatex_natbib ?
4828 preamble.citeEngine("biblatex-natbib")
4829 : preamble.citeEngine("biblatex");
4834 is_known(t.cs(), known_jurabib_commands) &&
4835 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4836 context.check_layout(os);
4837 string command = t.cs();
4838 if (p.next_token().asInput() == "*") {
4842 char argumentOrder = '\0';
4843 vector<string> const options =
4844 preamble.getPackageOptions("jurabib");
4845 if (find(options.begin(), options.end(),
4846 "natbiborder") != options.end())
4847 argumentOrder = 'n';
4848 else if (find(options.begin(), options.end(),
4849 "jurabiborder") != options.end())
4850 argumentOrder = 'j';
4852 // text before the citation
4854 // text after the citation
4856 get_cite_arguments(p, argumentOrder != 'j', before, after);
4858 string const citation = p.verbatim_item();
4859 if (!before.empty() && argumentOrder == '\0') {
4860 cerr << "Warning: Assuming argument order "
4861 "of jurabib version 0.6 for\n'"
4862 << command << before << after << '{'
4863 << citation << "}'.\n"
4864 "Add 'jurabiborder' to the jurabib "
4865 "package options if you used an\n"
4866 "earlier jurabib version." << endl;
4868 bool literal = false;
4869 pair<bool, string> aft;
4870 pair<bool, string> bef;
4871 // remove the brackets around after and before
4872 if (!after.empty()) {
4874 after.erase(after.length() - 1, 1);
4875 aft = convert_latexed_command_inset_arg(after);
4876 literal = !aft.first;
4877 after = literal ? subst(after, "\n", " ") : aft.second;
4879 if (!before.empty()) {
4881 before.erase(before.length() - 1, 1);
4882 bef = convert_latexed_command_inset_arg(before);
4883 literal |= !bef.first;
4884 before = literal ? subst(before, "\n", " ") : bef.second;
4885 if (literal && !after.empty())
4886 after = subst(after, "\n", " ");
4888 string lit = literal ? "\"true\"" : "\"false\"";
4889 begin_command_inset(os, "citation", command);
4890 os << "after " << '"' << after << "\"\n"
4891 << "before " << '"' << before << "\"\n"
4892 << "key " << '"' << citation << "\"\n"
4893 << "literal " << lit << "\n";
4895 // Need to set the cite engine if jurabib is loaded by
4896 // the document class directly
4897 if (preamble.citeEngine() == "basic")
4898 preamble.citeEngine("jurabib");
4902 if (t.cs() == "cite"
4903 || t.cs() == "nocite") {
4904 context.check_layout(os);
4905 string after = p.getArg('[', ']');
4906 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4907 bool const literal = !aft.first;
4908 after = literal ? subst(after, "\n", " ") : aft.second;
4909 string lit = literal ? "\"true\"" : "\"false\"";
4910 string key = convert_literate_command_inset_arg(p.verbatim_item());
4911 // store the case that it is "\nocite{*}" to use it later for
4914 begin_command_inset(os, "citation", t.cs());
4915 os << "after " << '"' << after << "\"\n"
4916 << "key " << '"' << key << "\"\n"
4917 << "literal " << lit << "\n";
4919 } else if (t.cs() == "nocite")
4924 if (t.cs() == "index" ||
4925 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4926 context.check_layout(os);
4927 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4928 p.getArg('[', ']') : "";
4929 string const kind = arg.empty() ? "idx" : arg;
4930 parse_index_entry(p, os, context, kind);
4932 preamble.registerAutomaticallyLoadedPackage("splitidx");
4936 if (t.cs() == "nomenclature") {
4937 context.check_layout(os);
4938 begin_command_inset(os, "nomenclature", "nomenclature");
4939 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4940 if (!prefix.empty())
4941 os << "prefix " << '"' << prefix << '"' << "\n";
4942 string symbol = p.verbatim_item();
4943 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4944 bool literal = !sym.first;
4945 string description = p.verbatim_item();
4946 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4947 literal |= !desc.first;
4949 symbol = subst(symbol, "\n", " ");
4950 description = subst(description, "\n", " ");
4952 symbol = sym.second;
4953 description = desc.second;
4955 string lit = literal ? "\"true\"" : "\"false\"";
4956 os << "symbol " << '"' << symbol;
4957 os << "\"\ndescription \""
4958 << description << "\"\n"
4959 << "literal " << lit << "\n";
4961 preamble.registerAutomaticallyLoadedPackage("nomencl");
4965 if (t.cs() == "label") {
4966 context.check_layout(os);
4967 begin_command_inset(os, "label", "label");
4969 << convert_literate_command_inset_arg(p.verbatim_item())
4975 if (t.cs() == "lyxmintcaption") {
4976 string const pos = p.getArg('[', ']');
4978 string const caption =
4979 parse_text_snippet(p, FLAG_ITEM, false,
4981 minted_nonfloat_caption = "[t]" + caption;
4983 // We already got the caption at the bottom,
4984 // so simply skip it.
4985 parse_text_snippet(p, FLAG_ITEM, false, context);
4987 eat_whitespace(p, os, context, true);
4991 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4992 context.check_layout(os);
4993 string commandname = t.cs();
4995 if (p.next_token().asInput() == "*") {
5000 begin_command_inset(os, "index_print", commandname);
5001 string const indexname = p.getArg('[', ']');
5003 if (indexname.empty())
5004 os << "type \"idx\"\n";
5006 os << "type \"" << indexname << "\"\n";
5007 os << "literal \"true\"\n";
5010 skip_spaces_braces(p);
5011 preamble.registerAutomaticallyLoadedPackage("makeidx");
5012 if (preamble.use_indices() == "true")
5013 preamble.registerAutomaticallyLoadedPackage("splitidx");
5017 if (t.cs() == "printnomenclature") {
5019 string width_type = "";
5020 context.check_layout(os);
5021 begin_command_inset(os, "nomencl_print", "printnomenclature");
5022 // case of a custom width
5024 width = p.getArg('[', ']');
5025 width = translate_len(width);
5026 width_type = "custom";
5028 // case of no custom width
5029 // the case of no custom width but the width set
5030 // via \settowidth{\nomlabelwidth}{***} cannot be supported
5031 // because the user could have set anything, not only the width
5032 // of the longest label (which would be width_type = "auto")
5033 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
5034 if (label.empty() && width_type.empty())
5035 width_type = "none";
5036 os << "set_width \"" << width_type << "\"\n";
5037 if (width_type == "custom")
5038 os << "width \"" << width << '\"';
5040 skip_spaces_braces(p);
5041 preamble.registerAutomaticallyLoadedPackage("nomencl");
5045 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
5046 context.check_layout(os);
5047 begin_inset(os, "script ");
5048 os << t.cs().substr(4) << '\n';
5049 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
5050 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5052 if (t.cs() == "textsubscript")
5053 preamble.registerAutomaticallyLoadedPackage("subscript");
5057 if ((where = is_known(t.cs(), known_quotes))) {
5058 context.check_layout(os);
5059 begin_inset(os, "Quotes ");
5060 string quotetype = known_coded_quotes[where - known_quotes];
5061 // try to make a smart guess about the side
5062 Token const prev = p.prev_token();
5063 bool const opening = (prev.cat() != catSpace && prev.character() != 0
5064 && prev.character() != '\n' && prev.character() != '~');
5065 quotetype = guessQuoteStyle(quotetype, opening);
5068 // LyX adds {} after the quote, so we have to eat
5069 // spaces here if there are any before a possible
5071 eat_whitespace(p, os, context, false);
5076 if ((where = is_known(t.cs(), known_sizes)) &&
5077 context.new_layout_allowed) {
5078 context.check_layout(os);
5079 TeXFont const oldFont = context.font;
5080 context.font.size = known_coded_sizes[where - known_sizes];
5081 output_font_change(os, oldFont, context.font);
5082 eat_whitespace(p, os, context, false);
5086 if ((where = is_known(t.cs(), known_font_families)) &&
5087 context.new_layout_allowed) {
5088 context.check_layout(os);
5089 TeXFont const oldFont = context.font;
5090 context.font.family =
5091 known_coded_font_families[where - known_font_families];
5092 output_font_change(os, oldFont, context.font);
5093 eat_whitespace(p, os, context, false);
5097 if ((where = is_known(t.cs(), known_font_series)) &&
5098 context.new_layout_allowed) {
5099 context.check_layout(os);
5100 TeXFont const oldFont = context.font;
5101 context.font.series =
5102 known_coded_font_series[where - known_font_series];
5103 output_font_change(os, oldFont, context.font);
5104 eat_whitespace(p, os, context, false);
5108 if ((where = is_known(t.cs(), known_font_shapes)) &&
5109 context.new_layout_allowed) {
5110 context.check_layout(os);
5111 TeXFont const oldFont = context.font;
5112 context.font.shape =
5113 known_coded_font_shapes[where - known_font_shapes];
5114 output_font_change(os, oldFont, context.font);
5115 eat_whitespace(p, os, context, false);
5118 if ((where = is_known(t.cs(), known_old_font_families)) &&
5119 context.new_layout_allowed) {
5120 context.check_layout(os);
5121 TeXFont const oldFont = context.font;
5122 context.font.init();
5123 context.font.size = oldFont.size;
5124 context.font.family =
5125 known_coded_font_families[where - known_old_font_families];
5126 output_font_change(os, oldFont, context.font);
5127 eat_whitespace(p, os, context, false);
5131 if ((where = is_known(t.cs(), known_old_font_series)) &&
5132 context.new_layout_allowed) {
5133 context.check_layout(os);
5134 TeXFont const oldFont = context.font;
5135 context.font.init();
5136 context.font.size = oldFont.size;
5137 context.font.series =
5138 known_coded_font_series[where - known_old_font_series];
5139 output_font_change(os, oldFont, context.font);
5140 eat_whitespace(p, os, context, false);
5144 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
5145 context.new_layout_allowed) {
5146 context.check_layout(os);
5147 TeXFont const oldFont = context.font;
5148 context.font.init();
5149 context.font.size = oldFont.size;
5150 context.font.shape =
5151 known_coded_font_shapes[where - known_old_font_shapes];
5152 output_font_change(os, oldFont, context.font);
5153 eat_whitespace(p, os, context, false);
5157 if (t.cs() == "selectlanguage") {
5158 context.check_layout(os);
5159 // save the language for the case that a
5160 // \foreignlanguage is used
5161 context.font.language = babel2lyx(p.verbatim_item());
5162 os << "\n\\lang " << context.font.language << "\n";
5166 if (t.cs() == "foreignlanguage") {
5167 string const lang = babel2lyx(p.verbatim_item());
5168 parse_text_attributes(p, os, FLAG_ITEM, outer,
5170 context.font.language, lang);
5174 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
5175 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
5176 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
5178 // We have to output the whole command if it has an option
5179 // because LyX doesn't support this yet, see bug #8214,
5180 // only if there is a single option specifying a variant, we can handle it.
5182 string langopts = p.getOpt();
5183 // check if the option contains a variant, if yes, extract it
5184 string::size_type pos_var = langopts.find("variant");
5185 string::size_type i = langopts.find(',');
5186 string::size_type k = langopts.find('=', pos_var);
5187 if (pos_var != string::npos && i == string::npos) {
5189 variant = langopts.substr(k + 1, langopts.length() - k - 2);
5190 lang = preamble.polyglossia2lyx(variant);
5191 parse_text_attributes(p, os, FLAG_ITEM, outer,
5193 context.font.language, lang);
5195 output_ert_inset(os, t.asInput() + langopts, context);
5197 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
5198 parse_text_attributes(p, os, FLAG_ITEM, outer,
5200 context.font.language, lang);
5205 if (t.cs() == "inputencoding") {
5206 // nothing to write here
5207 string const enc = subst(p.verbatim_item(), "\n", " ");
5208 p.setEncoding(enc, Encoding::inputenc);
5212 if (is_known(t.cs(), known_special_chars) ||
5213 (t.cs() == "protect" &&
5214 p.next_token().cat() == catEscape &&
5215 is_known(p.next_token().cs(), known_special_protect_chars))) {
5216 // LyX sometimes puts a \protect in front, so we have to ignore it
5218 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5219 known_special_chars);
5220 context.check_layout(os);
5221 os << known_coded_special_chars[where - known_special_chars];
5222 skip_spaces_braces(p);
5226 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5227 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5228 p.next_next_token().asInput() == "-") ||
5229 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5230 // LyX sometimes puts a \protect in front, so we have to ignore it
5231 if (t.cs() == "protect")
5233 context.check_layout(os);
5234 if (t.cs() == "nobreakdash")
5235 os << "\\SpecialChar nobreakdash\n";
5237 os << "\\SpecialChar endofsentence\n";
5242 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5243 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5244 || t.cs() == "%" || t.cs() == "-") {
5245 context.check_layout(os);
5247 os << "\\SpecialChar softhyphen\n";
5253 if (t.cs() == "char") {
5254 context.check_layout(os);
5255 if (p.next_token().character() == '`') {
5257 if (p.next_token().cs() == "\"") {
5262 output_ert_inset(os, "\\char`", context);
5265 output_ert_inset(os, "\\char", context);
5270 if (t.cs() == "verb") {
5271 context.check_layout(os);
5272 // set catcodes to verbatim early, just in case.
5273 p.setCatcodes(VERBATIM_CATCODES);
5274 string delim = p.get_token().asInput();
5275 Parser::Arg arg = p.verbatimStuff(delim);
5277 output_ert_inset(os, "\\verb" + delim
5278 + arg.second + delim, context);
5280 cerr << "invalid \\verb command. Skipping" << endl;
5284 // Problem: \= creates a tabstop inside the tabbing environment
5285 // and else an accent. In the latter case we really would want
5286 // \={o} instead of \= o.
5287 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5288 output_ert_inset(os, t.asInput(), context);
5292 if (t.cs() == "\\") {
5293 context.check_layout(os);
5295 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5296 else if (p.next_token().asInput() == "*") {
5298 // getOpt() eats the following space if there
5299 // is no optional argument, but that is OK
5300 // here since it has no effect in the output.
5301 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5304 begin_inset(os, "Newline newline");
5310 if (t.cs() == "newline" ||
5311 (t.cs() == "linebreak" && !p.hasOpt())) {
5312 context.check_layout(os);
5313 begin_inset(os, "Newline ");
5316 skip_spaces_braces(p);
5320 if (t.cs() == "endgraf" && context.in_table_cell) {
5321 context.new_paragraph(os);
5322 context.check_layout(os);
5323 skip_spaces_braces(p);
5327 if (t.cs() == "input" || t.cs() == "include"
5328 || t.cs() == "verbatiminput"
5329 || t.cs() == "lstinputlisting"
5330 || t.cs() == "inputminted") {
5331 string name = t.cs();
5332 if (name == "verbatiminput"
5333 && p.next_token().asInput() == "*")
5334 name += p.get_token().asInput();
5335 context.check_layout(os);
5337 bool literal = false;
5338 if (name == "lstinputlisting" && p.hasOpt()) {
5339 lstparams = p.getArg('[', ']');
5340 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5341 literal = !oa.first;
5343 lstparams = subst(lstparams, "\n", " ");
5345 lstparams = oa.second;
5346 } else if (name == "inputminted") {
5347 name = "lstinputlisting";
5348 string const lang = p.getArg('{', '}');
5349 if (lang != "tex") {
5350 string cmd = "\\inputminted{" + lang + "}{";
5351 cmd += p.getArg('{', '}') + "}";
5352 output_ert_inset(os, cmd, context);
5355 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5356 minted_nonfloat_caption.erase(0,3);
5357 // extract label and caption from the already produced LyX code
5358 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5359 string const caption = nfc.front();
5361 vector<string>::iterator it =
5362 find(nfc.begin(), nfc.end(), "LatexCommand label");
5363 if (it != nfc.end()) {
5365 if (it != nfc.end())
5367 label = support::split(label, '"');
5370 minted_nonfloat_caption.clear();
5371 lstparams = "caption=" + caption;
5373 lstparams += ",label=" + label;
5374 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5375 literal = !oa.first;
5377 lstparams = subst(lstparams, "\n", " ");
5379 lstparams = oa.second;
5382 string lit = literal ? "\"true\"" : "\"false\"";
5383 string filename(normalize_filename(p.getArg('{', '}')));
5384 string const path = getMasterFilePath(true);
5385 // We want to preserve relative / absolute filenames,
5386 // therefore path is only used for testing
5387 if ((t.cs() == "include" || t.cs() == "input") &&
5388 !makeAbsPath(filename, path).exists()) {
5389 // The file extension is probably missing.
5390 // Now try to find it out.
5391 string const tex_name =
5392 find_file(filename, path,
5393 known_tex_extensions);
5394 if (!tex_name.empty())
5395 filename = tex_name;
5397 bool external = false;
5399 if (makeAbsPath(filename, path).exists()) {
5400 string const abstexname =
5401 makeAbsPath(filename, path).absFileName();
5402 string const absfigname =
5403 changeExtension(abstexname, ".fig");
5404 fix_child_filename(filename);
5405 string const lyxname = changeExtension(filename,
5406 roundtripMode() ? ".lyx.lyx" : ".lyx");
5407 string const abslyxname = makeAbsPath(
5408 lyxname, getParentFilePath(false)).absFileName();
5410 if (!skipChildren())
5411 external = FileName(absfigname).exists();
5412 if (t.cs() == "input" && !skipChildren()) {
5413 string const ext = getExtension(abstexname);
5415 // Combined PS/LaTeX:
5416 // x.eps, x.pstex_t (old xfig)
5417 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5418 FileName const absepsname(
5419 changeExtension(abstexname, ".eps"));
5420 FileName const abspstexname(
5421 changeExtension(abstexname, ".pstex"));
5422 bool const xfigeps =
5423 (absepsname.exists() ||
5424 abspstexname.exists()) &&
5427 // Combined PDF/LaTeX:
5428 // x.pdf, x.pdftex_t (old xfig)
5429 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5430 FileName const abspdfname(
5431 changeExtension(abstexname, ".pdf"));
5432 bool const xfigpdf =
5433 abspdfname.exists() &&
5434 (ext == "pdftex_t" || ext == "pdf_t");
5438 // Combined PS/PDF/LaTeX:
5439 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5440 string const absbase2(
5441 removeExtension(abstexname) + "_pspdftex");
5442 FileName const abseps2name(
5443 addExtension(absbase2, ".eps"));
5444 FileName const abspdf2name(
5445 addExtension(absbase2, ".pdf"));
5446 bool const xfigboth =
5447 abspdf2name.exists() &&
5448 abseps2name.exists() && ext == "pspdftex";
5450 xfig = xfigpdf || xfigeps || xfigboth;
5451 external = external && xfig;
5454 outname = changeExtension(filename, ".fig");
5455 FileName abssrc(changeExtension(abstexname, ".fig"));
5456 copy_file(abssrc, outname);
5458 // Don't try to convert, the result
5459 // would be full of ERT.
5461 FileName abssrc(abstexname);
5462 copy_file(abssrc, outname);
5463 } else if (t.cs() != "verbatiminput" &&
5465 tex2lyx(abstexname, FileName(abslyxname),
5468 // no need to call copy_file
5469 // tex2lyx creates the file
5472 FileName abssrc(abstexname);
5473 copy_file(abssrc, outname);
5476 cerr << "Warning: Could not find included file '"
5477 << filename << "'." << endl;
5481 begin_inset(os, "External\n");
5482 os << "\ttemplate XFig\n"
5483 << "\tfilename " << outname << '\n';
5484 registerExternalTemplatePackages("XFig");
5486 begin_command_inset(os, "include", name);
5487 outname = subst(outname, "\"", "\\\"");
5488 os << "preview false\n"
5489 "filename \"" << outname << "\"\n";
5490 if (!lstparams.empty())
5491 os << "lstparams \"" << lstparams << "\"\n";
5492 os << "literal " << lit << "\n";
5493 if (t.cs() == "verbatiminput")
5494 preamble.registerAutomaticallyLoadedPackage("verbatim");
5500 if (t.cs() == "bibliographystyle") {
5501 // store new bibliographystyle
5502 bibliographystyle = p.verbatim_item();
5503 // If any other command than \bibliography, \addcontentsline
5504 // and \nocite{*} follows, we need to output the style
5505 // (because it might be used by that command).
5506 // Otherwise, it will automatically be output by LyX.
5509 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5510 if (t2.cat() == catBegin)
5512 if (t2.cat() != catEscape)
5514 if (t2.cs() == "nocite") {
5515 if (p.getArg('{', '}') == "*")
5517 } else if (t2.cs() == "bibliography")
5519 else if (t2.cs() == "phantomsection") {
5523 else if (t2.cs() == "addcontentsline") {
5524 // get the 3 arguments of \addcontentsline
5527 contentslineContent = p.getArg('{', '}');
5528 // if the last argument is not \refname we must output
5529 if (contentslineContent == "\\refname")
5536 output_ert_inset(os,
5537 "\\bibliographystyle{" + bibliographystyle + '}',
5543 if (t.cs() == "phantomsection") {
5544 // we only support this if it occurs between
5545 // \bibliographystyle and \bibliography
5546 if (bibliographystyle.empty())
5547 output_ert_inset(os, "\\phantomsection", context);
5551 if (t.cs() == "addcontentsline") {
5552 context.check_layout(os);
5553 // get the 3 arguments of \addcontentsline
5554 string const one = p.getArg('{', '}');
5555 string const two = p.getArg('{', '}');
5556 string const three = p.getArg('{', '}');
5557 // only if it is a \refname, we support if for the bibtex inset
5558 if (contentslineContent != "\\refname") {
5559 output_ert_inset(os,
5560 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5566 else if (t.cs() == "bibliography") {
5567 context.check_layout(os);
5569 begin_command_inset(os, "bibtex", "bibtex");
5570 if (!btprint.empty()) {
5571 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5572 // clear the string because the next BibTeX inset can be without the
5573 // \nocite{*} option
5576 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5577 // Do we have addcontentsline?
5578 if (contentslineContent == "\\refname") {
5579 BibOpts = "bibtotoc";
5580 // clear string because next BibTeX inset can be without addcontentsline
5581 contentslineContent.clear();
5583 // Do we have a bibliographystyle set?
5584 if (!bibliographystyle.empty()) {
5585 if (BibOpts.empty())
5586 BibOpts = normalize_filename(bibliographystyle);
5588 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5589 // clear it because each bibtex entry has its style
5590 // and we need an empty string to handle \phantomsection
5591 bibliographystyle.clear();
5593 os << "options " << '"' << BibOpts << '"' << "\n";
5594 if (p.getEncoding() != preamble.docencoding) {
5595 Encoding const * const enc = encodings.fromIconvName(
5596 p.getEncoding(), Encoding::inputenc, true);
5598 cerr << "Unknown bib encoding " << p.getEncoding()
5599 << ". Ignoring." << std::endl;
5601 os << "encoding " << '"' << enc->name() << '"' << "\n";
5607 if (t.cs() == "printbibliography") {
5608 context.check_layout(os);
5610 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5611 vector<string> opts = getVectorFromString(bbloptions);
5612 vector<string>::iterator it =
5613 find(opts.begin(), opts.end(), "heading=bibintoc");
5614 if (it != opts.end()) {
5616 BibOpts = "bibtotoc";
5618 bbloptions = getStringFromVector(opts);
5619 begin_command_inset(os, "bibtex", "bibtex");
5620 if (!btprint.empty()) {
5621 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5622 // clear the string because the next BibTeX inset can be without the
5623 // \nocite{*} option
5627 for (auto const & bf : preamble.biblatex_bibliographies) {
5628 if (!bibfiles.empty())
5630 bibfiles += normalize_filename(bf);
5632 if (!bibfiles.empty())
5633 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5634 // Do we have addcontentsline?
5635 if (contentslineContent == "\\refname") {
5636 BibOpts = "bibtotoc";
5637 // clear string because next BibTeX inset can be without addcontentsline
5638 contentslineContent.clear();
5640 os << "options " << '"' << BibOpts << '"' << "\n";
5641 if (!bbloptions.empty())
5642 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5643 if (!preamble.bibencoding.empty()) {
5644 Encoding const * const enc = encodings.fromLaTeXName(
5645 preamble.bibencoding, Encoding::inputenc, true);
5647 cerr << "Unknown bib encoding " << preamble.bibencoding
5648 << ". Ignoring." << std::endl;
5650 os << "encoding " << '"' << enc->name() << '"' << "\n";
5653 for (auto const & bf : preamble.biblatex_encodings) {
5654 if (!bibfileencs.empty())
5655 bibfileencs += "\t";
5658 if (!bibfileencs.empty())
5659 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5661 need_commentbib = false;
5665 if (t.cs() == "bibbysection") {
5666 context.check_layout(os);
5668 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5669 vector<string> opts = getVectorFromString(bbloptions);
5670 vector<string>::iterator it =
5671 find(opts.begin(), opts.end(), "heading=bibintoc");
5672 if (it != opts.end()) {
5674 BibOpts = "bibtotoc";
5676 bbloptions = getStringFromVector(opts);
5677 begin_command_inset(os, "bibtex", "bibtex");
5678 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5680 for (auto const & bf : preamble.biblatex_bibliographies) {
5681 if (!bibfiles.empty())
5683 bibfiles += normalize_filename(bf);
5685 if (!bibfiles.empty())
5686 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5687 os << "options " << '"' << BibOpts << '"' << "\n";
5688 if (!bbloptions.empty())
5689 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5691 need_commentbib = false;
5695 if (t.cs() == "parbox") {
5696 // Test whether this is an outer box of a shaded box
5698 // swallow arguments
5699 while (p.hasOpt()) {
5701 p.skip_spaces(true);
5704 p.skip_spaces(true);
5706 if (p.next_token().cat() == catBegin)
5708 p.skip_spaces(true);
5709 Token to = p.get_token();
5710 bool shaded = false;
5711 if (to.asInput() == "\\begin") {
5712 p.skip_spaces(true);
5713 if (p.getArg('{', '}') == "shaded")
5718 parse_outer_box(p, os, FLAG_ITEM, outer,
5719 context, "parbox", "shaded");
5721 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5722 "", "", t.cs(), "", "");
5726 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5727 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5728 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5729 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5733 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5734 string backgroundcolor;
5735 preamble.registerAutomaticallyLoadedPackage("xcolor");
5736 if (t.cs() == "fcolorbox") {
5737 string const framecolor = p.getArg('{', '}');
5738 backgroundcolor = p.getArg('{', '}');
5739 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5741 backgroundcolor = p.getArg('{', '}');
5742 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5747 // FIXME: due to the compiler limit of "if" nestings
5748 // the code for the alignment was put here
5749 // put them in their own if if this is fixed
5750 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5751 || t.cs() == "shadowsize") {
5752 if (t.cs() == "fboxrule")
5754 if (t.cs() == "fboxsep")
5756 if (t.cs() == "shadowsize")
5758 p.skip_spaces(true);
5759 while (p.good() && p.next_token().cat() != catSpace
5760 && p.next_token().cat() != catNewline
5761 && p.next_token().cat() != catEscape) {
5762 if (t.cs() == "fboxrule")
5763 fboxrule = fboxrule + p.get_token().asInput();
5764 if (t.cs() == "fboxsep")
5765 fboxsep = fboxsep + p.get_token().asInput();
5766 if (t.cs() == "shadowsize")
5767 shadow_size = shadow_size + p.get_token().asInput();
5772 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5773 if (context.in_table_cell) {
5774 if (t.cs() == "raggedleft")
5775 context.cell_align = 'r';
5776 else if (t.cs() == "centering")
5777 context.cell_align = 'c';
5778 else if (t.cs() == "raggedright")
5779 context.cell_align = 'l';
5780 p.skip_spaces(true);
5782 output_ert_inset(os, t.asInput(), context);
5787 //\framebox() is part of the picture environment and different from \framebox{}
5788 //\framebox{} will be parsed by parse_outer_box
5789 if (t.cs() == "framebox") {
5790 if (p.next_token().character() == '(') {
5791 //the syntax is: \framebox(x,y)[position]{content}
5792 string arg = t.asInput();
5793 arg += p.getFullParentheseArg();
5794 arg += p.getFullOpt();
5795 eat_whitespace(p, os, context, false);
5796 output_ert_inset(os, arg + '{', context);
5797 parse_text(p, os, FLAG_ITEM, outer, context);
5798 output_ert_inset(os, "}", context);
5800 //the syntax is: \framebox[width][position]{content}
5801 string special = p.getFullOpt();
5802 special += p.getOpt();
5803 parse_outer_box(p, os, FLAG_ITEM, outer,
5804 context, t.cs(), special);
5809 //\makebox() is part of the picture environment and different from \makebox{}
5810 //\makebox{} will be parsed by parse_box
5811 if (t.cs() == "makebox") {
5812 if (p.next_token().character() == '(') {
5813 //the syntax is: \makebox(x,y)[position]{content}
5814 string arg = t.asInput();
5815 arg += p.getFullParentheseArg();
5816 arg += p.getFullOpt();
5817 eat_whitespace(p, os, context, false);
5818 output_ert_inset(os, arg + '{', context);
5819 parse_text(p, os, FLAG_ITEM, outer, context);
5820 output_ert_inset(os, "}", context);
5822 //the syntax is: \makebox[width][position]{content}
5823 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5824 "", "", t.cs(), "", "");
5828 if (t.cs() == "smallskip" ||
5829 t.cs() == "medskip" ||
5830 t.cs() == "bigskip" ||
5831 t.cs() == "vfill") {
5832 context.check_layout(os);
5833 begin_inset(os, "VSpace ");
5836 skip_spaces_braces(p);
5840 if ((where = is_known(t.cs(), known_spaces))
5841 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5842 context.check_layout(os);
5843 begin_inset(os, "space ");
5844 os << '\\' << known_coded_spaces[where - known_spaces]
5847 // LaTeX swallows whitespace after all spaces except
5848 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5849 // We have to do that here, too, because LyX
5850 // adds "{}" which would make the spaces significant.
5851 if (!contains(",>!;:", t.cs()))
5852 eat_whitespace(p, os, context, false);
5853 // LyX adds "{}" after all spaces except "\\ " and
5854 // "\\,", so we have to remove "{}".
5855 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5856 // remove the braces after "\\,", too.
5862 if (t.cs() == "newpage" ||
5863 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5864 t.cs() == "clearpage" ||
5865 t.cs() == "cleardoublepage" ||
5866 t.cs() == "nopagebreak") {
5867 context.check_layout(os);
5868 begin_inset(os, "Newpage ");
5871 skip_spaces_braces(p);
5875 if (t.cs() == "DeclareRobustCommand" ||
5876 t.cs() == "DeclareRobustCommandx" ||
5877 t.cs() == "newcommand" ||
5878 t.cs() == "newcommandx" ||
5879 t.cs() == "providecommand" ||
5880 t.cs() == "providecommandx" ||
5881 t.cs() == "renewcommand" ||
5882 t.cs() == "renewcommandx") {
5883 // DeclareRobustCommand, DeclareRobustCommandx,
5884 // providecommand and providecommandx could be handled
5885 // by parse_command(), but we need to call
5886 // add_known_command() here.
5887 string name = t.asInput();
5888 if (p.next_token().asInput() == "*") {
5889 // Starred form. Eat '*'
5893 string const command = p.verbatim_item();
5894 string const opt1 = p.getFullOpt();
5895 string const opt2 = p.getFullOpt();
5896 add_known_command(command, opt1, !opt2.empty());
5897 string const ert = name + '{' + command + '}' +
5899 '{' + p.verbatim_item() + '}';
5901 if (t.cs() == "DeclareRobustCommand" ||
5902 t.cs() == "DeclareRobustCommandx" ||
5903 t.cs() == "providecommand" ||
5904 t.cs() == "providecommandx" ||
5905 name[name.length()-1] == '*')
5906 output_ert_inset(os, ert, context);
5908 context.check_layout(os);
5909 begin_inset(os, "FormulaMacro");
5916 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5917 // let could be handled by parse_command(),
5918 // but we need to call add_known_command() here.
5919 string ert = t.asInput();
5922 if (p.next_token().cat() == catBegin) {
5923 name = p.verbatim_item();
5924 ert += '{' + name + '}';
5926 name = p.verbatim_item();
5931 if (p.next_token().cat() == catBegin) {
5932 command = p.verbatim_item();
5933 ert += '{' + command + '}';
5935 command = p.verbatim_item();
5938 // If command is known, make name known too, to parse
5939 // its arguments correctly. For this reason we also
5940 // have commands in syntax.default that are hardcoded.
5941 CommandMap::iterator it = known_commands.find(command);
5942 if (it != known_commands.end())
5943 known_commands[t.asInput()] = it->second;
5944 output_ert_inset(os, ert, context);
5948 if (t.cs() == "hspace" || t.cs() == "vspace") {
5951 string name = t.asInput();
5952 string const length = p.verbatim_item();
5955 bool valid = splitLatexLength(length, valstring, unit);
5956 bool known_hspace = false;
5957 bool known_vspace = false;
5958 bool known_unit = false;
5961 istringstream iss(valstring);
5964 if (t.cs()[0] == 'h') {
5965 if (unit == "\\fill") {
5970 known_hspace = true;
5973 if (unit == "\\smallskipamount") {
5975 known_vspace = true;
5976 } else if (unit == "\\medskipamount") {
5978 known_vspace = true;
5979 } else if (unit == "\\bigskipamount") {
5981 known_vspace = true;
5982 } else if (length == "\\baselineskip") {
5984 known_vspace = true;
5985 } else if (unit == "\\fill") {
5987 known_vspace = true;
5991 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5993 known_vspace = true;
5995 if (!known_hspace && !known_vspace) {
5996 switch (unitFromString(unit)) {
6012 //unitFromString(unit) fails for relative units like Length::PCW
6013 // therefore handle them separately
6014 if (unit == "\\paperwidth" || unit == "\\columnwidth"
6015 || unit == "\\textwidth" || unit == "\\linewidth"
6016 || unit == "\\textheight" || unit == "\\paperheight"
6017 || unit == "\\baselineskip")
6025 // check for glue lengths
6026 bool is_gluelength = false;
6027 string gluelength = length;
6028 string::size_type i = length.find(" minus");
6029 if (i == string::npos) {
6030 i = length.find(" plus");
6031 if (i != string::npos)
6032 is_gluelength = true;
6034 is_gluelength = true;
6035 // if yes transform "9xx minus 8yy plus 7zz"
6037 if (is_gluelength) {
6038 i = gluelength.find(" minus");
6039 if (i != string::npos)
6040 gluelength.replace(i, 7, "-");
6041 i = gluelength.find(" plus");
6042 if (i != string::npos)
6043 gluelength.replace(i, 6, "+");
6046 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
6047 // Literal horizontal length or known variable
6048 context.check_layout(os);
6049 begin_inset(os, "space ");
6057 if (known_unit && !known_hspace)
6058 os << "\n\\length " << translate_len(length);
6060 os << "\n\\length " << gluelength;
6062 } else if (known_unit || known_vspace || is_gluelength) {
6063 // Literal vertical length or known variable
6064 context.check_layout(os);
6065 begin_inset(os, "VSpace ");
6068 if (known_unit && !known_vspace)
6069 os << translate_len(length);
6076 // LyX can't handle other length variables in Inset VSpace/space
6081 output_ert_inset(os, name + '{' + unit + '}', context);
6082 else if (value == -1.0)
6083 output_ert_inset(os, name + "{-" + unit + '}', context);
6085 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
6087 output_ert_inset(os, name + '{' + length + '}', context);
6092 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
6093 // might be one or several options or a star.
6094 // The single '=' is meant here.
6095 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
6099 context.check_layout(os);
6100 // store the latexparam here. This is eaten in parse_text_in_inset
6101 context.latexparam = newinsetlayout->latexparam();
6102 docstring name = newinsetlayout->name();
6103 bool const caption = name.find(from_ascii("Caption:")) == 0;
6105 // Already done for floating minted listings.
6106 if (minted_float.empty()) {
6107 begin_inset(os, "Caption ");
6108 os << to_utf8(name.substr(8)) << '\n';
6111 // FIXME: what do we do if the prefix is not Flex: ?
6112 if (prefixIs(name, from_ascii("Flex:")))
6114 begin_inset(os, "Flex ");
6115 os << to_utf8(name) << '\n'
6116 << "status collapsed\n";
6118 if (!minted_float.empty()) {
6119 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6120 } else if (newinsetlayout->isPassThru()) {
6121 // set catcodes to verbatim early, just in case.
6122 p.setCatcodes(VERBATIM_CATCODES);
6123 string delim = p.get_token().asInput();
6125 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
6126 //FIXME: handle error condition
6127 string const arg = p.verbatimStuff("}").second;
6128 Context newcontext(true, context.textclass);
6129 if (newinsetlayout->forcePlainLayout())
6130 newcontext.layout = &context.textclass.plainLayout();
6131 output_ert(os, arg, newcontext);
6133 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6134 context.latexparam.clear();
6137 // Minted caption insets are not closed here because
6138 // we collect everything into the caption.
6139 if (minted_float.empty())
6144 // The single '=' is meant here.
6145 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
6149 context.check_layout(os);
6150 docstring name = newinsetlayout->name();
6151 bool const caption = name.find(from_ascii("Caption:")) == 0;
6153 // Already done for floating minted listings.
6154 if (minted_float.empty()) {
6155 begin_inset(os, "Caption ");
6156 os << to_utf8(name.substr(8)) << '\n';
6159 // FIXME: what do we do if the prefix is not Flex: ?
6160 if (prefixIs(name, from_ascii("Flex:")))
6162 begin_inset(os, "Flex ");
6163 os << to_utf8(name) << '\n'
6164 << "status collapsed\n";
6166 if (!minted_float.empty()) {
6167 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6168 } else if (newinsetlayout->isPassThru()) {
6169 // set catcodes to verbatim early, just in case.
6170 p.setCatcodes(VERBATIM_CATCODES);
6171 string delim = p.get_token().asInput();
6173 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
6174 //FIXME: handle error condition
6175 string const arg = p.verbatimStuff("}").second;
6176 Context newcontext(true, context.textclass);
6177 if (newinsetlayout->forcePlainLayout())
6178 newcontext.layout = &context.textclass.plainLayout();
6179 output_ert(os, arg, newcontext);
6181 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6184 // Minted caption insets are not closed here because
6185 // we collect everything into the caption.
6186 if (minted_float.empty())
6191 if (t.cs() == "includepdf") {
6193 string const arg = p.getArg('[', ']');
6194 map<string, string> opts;
6195 vector<string> keys;
6196 split_map(arg, opts, keys);
6197 string name = normalize_filename(p.verbatim_item());
6198 string const path = getMasterFilePath(true);
6199 // We want to preserve relative / absolute filenames,
6200 // therefore path is only used for testing
6201 if (!makeAbsPath(name, path).exists()) {
6202 // The file extension is probably missing.
6203 // Now try to find it out.
6204 char const * const pdfpages_format[] = {"pdf", 0};
6205 string const pdftex_name =
6206 find_file(name, path, pdfpages_format);
6207 if (!pdftex_name.empty()) {
6212 FileName const absname = makeAbsPath(name, path);
6213 if (absname.exists())
6215 fix_child_filename(name);
6216 copy_file(absname, name);
6218 cerr << "Warning: Could not find file '"
6219 << name << "'." << endl;
6221 context.check_layout(os);
6222 begin_inset(os, "External\n\ttemplate ");
6223 os << "PDFPages\n\tfilename "
6225 // parse the options
6226 if (opts.find("pages") != opts.end())
6227 os << "\textra LaTeX \"pages="
6228 << opts["pages"] << "\"\n";
6229 if (opts.find("angle") != opts.end())
6230 os << "\trotateAngle "
6231 << opts["angle"] << '\n';
6232 if (opts.find("origin") != opts.end()) {
6234 string const opt = opts["origin"];
6235 if (opt == "tl") ss << "topleft";
6236 if (opt == "bl") ss << "bottomleft";
6237 if (opt == "Bl") ss << "baselineleft";
6238 if (opt == "c") ss << "center";
6239 if (opt == "tc") ss << "topcenter";
6240 if (opt == "bc") ss << "bottomcenter";
6241 if (opt == "Bc") ss << "baselinecenter";
6242 if (opt == "tr") ss << "topright";
6243 if (opt == "br") ss << "bottomright";
6244 if (opt == "Br") ss << "baselineright";
6245 if (!ss.str().empty())
6246 os << "\trotateOrigin " << ss.str() << '\n';
6248 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
6250 if (opts.find("width") != opts.end())
6252 << translate_len(opts["width"]) << '\n';
6253 if (opts.find("height") != opts.end())
6255 << translate_len(opts["height"]) << '\n';
6256 if (opts.find("keepaspectratio") != opts.end())
6257 os << "\tkeepAspectRatio\n";
6259 context.check_layout(os);
6260 registerExternalTemplatePackages("PDFPages");
6264 if (t.cs() == "loadgame") {
6266 string name = normalize_filename(p.verbatim_item());
6267 string const path = getMasterFilePath(true);
6268 // We want to preserve relative / absolute filenames,
6269 // therefore path is only used for testing
6270 if (!makeAbsPath(name, path).exists()) {
6271 // The file extension is probably missing.
6272 // Now try to find it out.
6273 char const * const lyxskak_format[] = {"fen", 0};
6274 string const lyxskak_name =
6275 find_file(name, path, lyxskak_format);
6276 if (!lyxskak_name.empty())
6277 name = lyxskak_name;
6279 FileName const absname = makeAbsPath(name, path);
6280 if (absname.exists())
6282 fix_child_filename(name);
6283 copy_file(absname, name);
6285 cerr << "Warning: Could not find file '"
6286 << name << "'." << endl;
6287 context.check_layout(os);
6288 begin_inset(os, "External\n\ttemplate ");
6289 os << "ChessDiagram\n\tfilename "
6292 context.check_layout(os);
6293 // after a \loadgame follows a \showboard
6294 if (p.get_token().asInput() == "showboard")
6296 registerExternalTemplatePackages("ChessDiagram");
6300 // try to see whether the string is in unicodesymbols
6301 // Only use text mode commands, since we are in text mode here,
6302 // and math commands may be invalid (bug 6797)
6303 string name = t.asInput();
6304 // handle the dingbats, cyrillic and greek
6305 if (name == "\\textcyr")
6306 name = "\\textcyrillic";
6307 if (name == "\\ding" || name == "\\textcyrillic" ||
6308 (name == "\\textgreek" && !preamble.usePolyglossia()))
6309 name = name + '{' + p.getArg('{', '}') + '}';
6310 // handle the ifsym characters
6311 else if (name == "\\textifsymbol") {
6312 string const optif = p.getFullOpt();
6313 string const argif = p.getArg('{', '}');
6314 name = name + optif + '{' + argif + '}';
6316 // handle the \ascii characters
6317 // the case of \ascii within braces, as LyX outputs it, is already
6318 // handled for t.cat() == catBegin
6319 else if (name == "\\ascii") {
6320 // the code is "\asci\xxx"
6321 name = "{" + name + p.get_token().asInput() + "}";
6324 // handle some TIPA special characters
6325 else if (preamble.isPackageUsed("tipa")) {
6326 if (name == "\\s") {
6327 // fromLaTeXCommand() does not yet
6328 // recognize tipa short cuts
6329 name = "\\textsyllabic";
6330 } else if (name == "\\=" &&
6331 p.next_token().asInput() == "*") {
6332 // fromLaTeXCommand() does not yet
6333 // recognize tipa short cuts
6335 name = "\\textsubbar";
6336 } else if (name == "\\textdoublevertline") {
6337 // FIXME: This is not correct,
6338 // \textvertline is higher than \textbardbl
6339 name = "\\textbardbl";
6341 } else if (name == "\\!" ) {
6342 if (p.next_token().asInput() == "b") {
6343 p.get_token(); // eat 'b'
6346 } else if (p.next_token().asInput() == "d") {
6350 } else if (p.next_token().asInput() == "g") {
6354 } else if (p.next_token().asInput() == "G") {
6356 name = "\\texthtscg";
6358 } else if (p.next_token().asInput() == "j") {
6360 name = "\\texthtbardotlessj";
6362 } else if (p.next_token().asInput() == "o") {
6364 name = "\\textbullseye";
6367 } else if (name == "\\*" ) {
6368 if (p.next_token().asInput() == "k") {
6370 name = "\\textturnk";
6372 } else if (p.next_token().asInput() == "r") {
6373 p.get_token(); // eat 'b'
6374 name = "\\textturnr";
6376 } else if (p.next_token().asInput() == "t") {
6378 name = "\\textturnt";
6380 } else if (p.next_token().asInput() == "w") {
6382 name = "\\textturnw";
6387 if ((name.size() == 2 &&
6388 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6389 p.next_token().asInput() != "*") ||
6390 is_known(name.substr(1), known_tipa_marks)) {
6391 // name is a command that corresponds to a
6392 // combining character in unicodesymbols.
6393 // Append the argument, fromLaTeXCommand()
6394 // will either convert it to a single
6395 // character or a combining sequence.
6396 name += '{' + p.verbatim_item() + '}';
6398 // now get the character from unicodesymbols
6402 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6403 Encodings::TEXT_CMD, termination, rem, &req));
6405 context.check_layout(os);
6408 output_ert_inset(os, to_utf8(rem), context);
6410 skip_spaces_braces(p);
6411 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6412 preamble.registerAutomaticallyLoadedPackage(*it);
6414 //cerr << "#: " << t << " mode: " << mode << endl;
6415 // heuristic: read up to next non-nested space
6417 string s = t.asInput();
6418 string z = p.verbatim_item();
6419 while (p.good() && z != " " && !z.empty()) {
6420 //cerr << "read: " << z << endl;
6422 z = p.verbatim_item();
6424 cerr << "found ERT: " << s << endl;
6425 output_ert_inset(os, s + ' ', context);
6428 if (t.asInput() == name &&
6429 p.next_token().asInput() == "*") {
6430 // Starred commands like \vspace*{}
6431 p.get_token(); // Eat '*'
6434 if (!parse_command(name, p, os, outer, context)) {
6435 output_ert_inset(os, name, context);
6436 // Try to handle options of unknown commands:
6437 // Look if we have optional arguments,
6438 // and if so, put the brackets in ERT.
6439 while (p.hasOpt()) {
6440 p.get_token(); // eat '['
6441 output_ert_inset(os, "[", context);
6442 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6443 output_ert_inset(os, "]", context);
6451 string guessLanguage(Parser & p, string const & lang)
6453 typedef std::map<std::string, size_t> LangMap;
6454 // map from language names to number of characters
6457 for (char const * const * i = supported_CJK_languages; *i; i++)
6458 used[string(*i)] = 0;
6461 Token const t = p.get_token();
6462 // comments are not counted for any language
6463 if (t.cat() == catComment)
6465 // commands are not counted as well, but we need to detect
6466 // \begin{CJK} and switch encoding if needed
6467 if (t.cat() == catEscape) {
6468 if (t.cs() == "inputencoding") {
6469 string const enc = subst(p.verbatim_item(), "\n", " ");
6470 p.setEncoding(enc, Encoding::inputenc);
6473 if (t.cs() != "begin")
6476 // Non-CJK content is counted for lang.
6477 // We do not care about the real language here:
6478 // If we have more non-CJK contents than CJK contents,
6479 // we simply use the language that was specified as
6480 // babel main language.
6481 used[lang] += t.asInput().length();
6484 // Now we are starting an environment
6486 string const name = p.getArg('{', '}');
6487 if (name != "CJK") {
6491 // It is a CJK environment
6493 /* name = */ p.getArg('{', '}');
6494 string const encoding = p.getArg('{', '}');
6495 /* mapping = */ p.getArg('{', '}');
6496 string const encoding_old = p.getEncoding();
6497 char const * const * const where =
6498 is_known(encoding, supported_CJK_encodings);
6500 p.setEncoding(encoding, Encoding::CJK);
6502 p.setEncoding("UTF-8");
6503 string const text = p.ertEnvironment("CJK");
6504 p.setEncoding(encoding_old);
6507 // ignore contents in unknown CJK encoding
6510 // the language of the text
6512 supported_CJK_languages[where - supported_CJK_encodings];
6513 used[cjk] += text.length();
6515 LangMap::const_iterator use = used.begin();
6516 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6517 if (it->second > use->second)
6524 void check_comment_bib(ostream & os, Context & context)
6526 if (!need_commentbib)
6528 // We have a bibliography database, but no bibliography with biblatex
6529 // which is completely valid. Insert a bibtex inset in a note.
6530 context.check_layout(os);
6531 begin_inset(os, "Note Note\n");
6532 os << "status open\n";
6533 os << "\\begin_layout Plain Layout\n";
6534 begin_command_inset(os, "bibtex", "bibtex");
6536 for (auto const & bf : preamble.biblatex_bibliographies) {
6537 if (!bibfiles.empty())
6539 bibfiles += normalize_filename(bf);
6541 if (!bibfiles.empty())
6542 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6544 for (auto const & bf : preamble.biblatex_encodings) {
6545 if (!bibfileencs.empty())
6546 bibfileencs += "\t";
6549 if (!bibfileencs.empty())
6550 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6551 end_inset(os);// Bibtex
6552 os << "\\end_layout\n";
6553 end_inset(os);// Note