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_starref_commands[] = { "ref", "pageref", "vref",
155 "vpageref", "nameref", "eqref", 0 };
157 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
158 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
159 "secref", "subsecref", "tabref", "thmref", 0 };
161 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
162 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
163 "sec", "subsec", "tab", "thm", 0 };
167 * supported CJK encodings
168 * JIS does not work with LyX's encoding conversion
170 const char * const supported_CJK_encodings[] = {
171 "EUC-JP", "KS", "GB", "UTF8",
172 "Bg5", /*"JIS",*/ "SJIS", 0};
175 * the same as supported_CJK_encodings with their corresponding LyX language name
176 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
178 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
179 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
180 * please keep this in sync with supported_CJK_encodings line by line!
182 const char * const supported_CJK_languages[] = {
183 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
184 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
188 * The starred forms are also known except for "citefullauthor",
189 * "citeyear" and "citeyearpar".
191 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
192 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
193 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
197 * No starred form other than "cite*" known.
199 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
200 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
201 // jurabib commands not (yet) supported by LyX:
203 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
204 // "footciteauthor", "footciteyear", "footciteyearpar",
205 "citefield", "citetitle", 0 };
209 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
211 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
212 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
213 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
214 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
215 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
217 // Whether we need to insert a bibtex inset in a comment
218 bool need_commentbib = false;
220 /// LaTeX names for quotes
221 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
222 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
223 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
224 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
227 /// the same as known_quotes with .lyx names
228 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
229 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
230 "gld", "eld", "gls", "ers", "ars",
231 "ars", "als", "als", "erd", "qrs", "qrd", 0};
233 /// LaTeX names for font sizes
234 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
235 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
237 /// the same as known_sizes with .lyx names
238 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
239 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
241 /// LaTeX 2.09 names for font families
242 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
244 /// LaTeX names for font families
245 char const * const known_font_families[] = { "rmfamily", "sffamily",
248 /// LaTeX names for font family changing commands
249 char const * const known_text_font_families[] = { "textrm", "textsf",
252 /// The same as known_old_font_families, known_font_families and
253 /// known_text_font_families with .lyx names
254 char const * const known_coded_font_families[] = { "roman", "sans",
257 /// LaTeX 2.09 names for font series
258 char const * const known_old_font_series[] = { "bf", 0};
260 /// LaTeX names for font series
261 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
263 /// LaTeX names for font series changing commands
264 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
266 /// The same as known_old_font_series, known_font_series and
267 /// known_text_font_series with .lyx names
268 char const * const known_coded_font_series[] = { "bold", "medium", 0};
270 /// LaTeX 2.09 names for font shapes
271 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
273 /// LaTeX names for font shapes
274 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
277 /// LaTeX names for font shape changing commands
278 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
281 /// The same as known_old_font_shapes, known_font_shapes and
282 /// known_text_font_shapes with .lyx names
283 char const * const known_coded_font_shapes[] = { "italic", "slanted",
284 "smallcaps", "up", 0};
286 /// Known special characters which need skip_spaces_braces() afterwards
287 char const * const known_special_chars[] = {"ldots",
288 "lyxarrow", "textcompwordmark",
289 "slash", "textasciitilde", "textasciicircum", "textbackslash",
290 "LyX", "TeX", "LaTeXe",
293 /// special characters from known_special_chars which may have a \\protect before
294 char const * const known_special_protect_chars[] = {"LyX", "TeX",
295 "LaTeXe", "LaTeX", 0};
297 /// the same as known_special_chars with .lyx names
298 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
299 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
300 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
301 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
302 "\\SpecialChar LaTeX\n", 0};
305 * Graphics file extensions known by the dvips driver of the graphics package.
306 * These extensions are used to complete the filename of an included
307 * graphics file if it does not contain an extension.
308 * The order must be the same that latex uses to find a file, because we
309 * will use the first extension that matches.
310 * This is only an approximation for the common cases. If we would want to
311 * do it right in all cases, we would need to know which graphics driver is
312 * used and know the extensions of every driver of the graphics package.
314 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
315 "ps.gz", "eps.Z", "ps.Z", 0};
318 * Graphics file extensions known by the pdftex driver of the graphics package.
319 * \sa known_dvips_graphics_formats
321 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
325 * Known file extensions for TeX files as used by \\include.
327 char const * const known_tex_extensions[] = {"tex", 0};
329 /// spaces known by InsetSpace
330 char const * const known_spaces[] = { " ", "space",
331 ",", "thinspace",// \\, = \\thinspace
332 "quad", "qquad", "enspace", "enskip",
333 ";", ">", "medspace",// \\; = \\> = \\medspace
334 ":", "thickspace",// \\: = \\thickspace
335 "!", "negthinspace",// \\! = \\negthinspace
336 "negmedspace", "negthickspace",
337 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
338 "rightarrowfill", "upbracefill", "downbracefill", 0};
340 /// the same as known_spaces with .lyx names
341 char const * const known_coded_spaces[] = { "space{}", "space{}",
342 "thinspace{}", "thinspace{}",
343 "quad{}", "qquad{}", "enspace{}", "enskip{}",
344 "medspace{}", "medspace{}", "medspace{}",
345 "thickspace{}", "thickspace{}",
346 "negthinspace{}", "negthinspace{}",
347 "negmedspace{}", "negthickspace{}",
348 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
349 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
351 /// known TIPA combining diacritical marks
352 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
353 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
354 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
355 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
356 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
357 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
358 "textsubring", "textsubbar", 0};
360 /// TIPA tones that need special handling
361 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
363 // string to store the float type to be able to determine the type of subfloats
364 string float_type = "";
366 // string to store the float status of minted listings
367 string minted_float = "";
369 // whether a caption has been parsed for a floating minted listing
370 bool minted_float_has_caption = false;
372 // The caption for non-floating minted listings
373 string minted_nonfloat_caption = "";
375 // Characters that have to be escaped by \\ in LaTeX
376 char const * const known_escaped_chars[] = {
377 "&", "_", "$", "%", "#", "^", "{", "}", 0};
380 /// splits "x=z, y=b" into a map and an ordered keyword vector
381 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
386 keys.resize(v.size());
387 for (size_t i = 0; i < v.size(); ++i) {
388 size_t const pos = v[i].find('=');
389 string const index = trimSpaceAndEol(v[i].substr(0, pos));
390 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
398 * Split a LaTeX length into value and unit.
399 * The latter can be a real unit like "pt", or a latex length variable
400 * like "\textwidth". The unit may contain additional stuff like glue
401 * lengths, but we don't care, because such lengths are ERT anyway.
402 * \returns true if \p value and \p unit are valid.
404 bool splitLatexLength(string const & len, string & value, string & unit)
408 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
409 //'4,5' is a valid LaTeX length number. Change it to '4.5'
410 string const length = subst(len, ',', '.');
411 if (i == string::npos)
414 if (len[0] == '\\') {
415 // We had something like \textwidth without a factor
421 value = trimSpaceAndEol(string(length, 0, i));
425 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
426 if (contains(len, '\\'))
427 unit = trimSpaceAndEol(string(len, i));
429 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
434 /// A simple function to translate a latex length to something LyX can
435 /// understand. Not perfect, but rather best-effort.
436 bool translate_len(string const & length, string & valstring, string & unit)
438 if (!splitLatexLength(length, valstring, unit))
440 // LyX uses percent values
442 istringstream iss(valstring);
447 string const percentval = oss.str();
449 if (unit.empty() || unit[0] != '\\')
451 string::size_type const i = unit.find(' ');
452 string const endlen = (i == string::npos) ? string() : string(unit, i);
453 if (unit == "\\textwidth") {
454 valstring = percentval;
455 unit = "text%" + endlen;
456 } else if (unit == "\\columnwidth") {
457 valstring = percentval;
458 unit = "col%" + endlen;
459 } else if (unit == "\\paperwidth") {
460 valstring = percentval;
461 unit = "page%" + endlen;
462 } else if (unit == "\\linewidth") {
463 valstring = percentval;
464 unit = "line%" + endlen;
465 } else if (unit == "\\paperheight") {
466 valstring = percentval;
467 unit = "pheight%" + endlen;
468 } else if (unit == "\\textheight") {
469 valstring = percentval;
470 unit = "theight%" + endlen;
471 } else if (unit == "\\baselineskip") {
472 valstring = percentval;
473 unit = "baselineskip%" + endlen;
479 /// If we have ambiguous quotation marks, make a smart guess
480 /// based on main quote style
481 string guessQuoteStyle(string const & in, bool const opening)
484 if (prefixIs(in, "qr")) {// straight quote
486 res = subst(res, "r", "l");
487 } else if (in == "eld") {// ``
488 if (preamble.quotesStyle() == "german")
490 else if (preamble.quotesStyle() == "british")
492 else if (preamble.quotesStyle() == "french")
494 else if (preamble.quotesStyle() == "russian")
496 } else if (in == "erd") {// ''
497 if (preamble.quotesStyle() == "polish")
499 else if (preamble.quotesStyle() == "british")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "hungarian")
505 else if (preamble.quotesStyle() == "swedish")
506 res = opening ? "sld" : "srd";
507 } else if (in == "els") {// `
508 if (preamble.quotesStyle() == "german")
510 else if (preamble.quotesStyle() == "british")
512 } else if (in == "ers") {// '
513 if (preamble.quotesStyle() == "polish")
515 else if (preamble.quotesStyle() == "british")
517 else if (preamble.quotesStyle() == "swedish")
518 res = opening ? "sls" : "srs";
519 } else if (in == "ard") {// >>
520 if (preamble.quotesStyle() == "swiss")
522 else if (preamble.quotesStyle() == "french")
524 else if (preamble.quotesStyle() == "russian")
526 else if (preamble.quotesStyle() == "hungarian")
528 } else if (in == "ald") {// <<
529 if (preamble.quotesStyle() == "swiss")
531 else if (preamble.quotesStyle() == "french")
533 else if (preamble.quotesStyle() == "russian")
535 else if (preamble.quotesStyle() == "hungarian")
537 } else if (in == "ars") {// >
538 if (preamble.quotesStyle() == "swiss")
540 } else if (in == "als") {// <
541 if (preamble.quotesStyle() == "swiss")
543 } else if (in == "gld") {// ,,
544 if (preamble.quotesStyle() == "polish")
546 else if (preamble.quotesStyle() == "hungarian")
548 else if (preamble.quotesStyle() == "russian")
550 } else if (in == "gls") {// ,
551 if (preamble.quotesStyle() == "polish")
558 string const fromPolyglossiaEnvironment(string const & s)
560 // Since \arabic is taken by the LaTeX kernel,
561 // the Arabic polyglossia environment is upcased
569 string uncapitalize(string const & s)
571 docstring in = from_ascii(s);
572 char_type t = lowercase(s[0]);
578 bool isCapitalized(string const & s)
580 docstring in = from_ascii(s);
581 char_type t = uppercase(s[0]);
583 return to_ascii(in) == s;
590 string translate_len(string const & length)
594 if (translate_len(length, value, unit))
596 // If the input is invalid, return what we have.
604 * Translates a LaTeX length into \p value, \p unit and
605 * \p special parts suitable for a box inset.
606 * The difference from translate_len() is that a box inset knows about
607 * some special "units" that are stored in \p special.
609 void translate_box_len(string const & length, string & value, string & unit, string & special)
611 if (translate_len(length, value, unit)) {
612 if (unit == "\\height" || unit == "\\depth" ||
613 unit == "\\totalheight" || unit == "\\width") {
614 special = unit.substr(1);
615 // The unit is not used, but LyX requires a dummy setting
627 void begin_inset(ostream & os, string const & name)
629 os << "\n\\begin_inset " << name;
633 void begin_command_inset(ostream & os, string const & name,
634 string const & latexname)
636 begin_inset(os, "CommandInset ");
637 os << name << "\nLatexCommand " << latexname << '\n';
641 void end_inset(ostream & os)
643 os << "\n\\end_inset\n\n";
647 bool skip_braces(Parser & p)
649 if (p.next_token().cat() != catBegin)
652 if (p.next_token().cat() == catEnd) {
661 /// replace LaTeX commands in \p s from the unicodesymbols file with their
663 pair<bool, docstring> convert_unicodesymbols(docstring s)
667 for (size_t i = 0; i < s.size();) {
676 docstring parsed = normalize_c(Encodings::fromLaTeXCommand(s,
677 Encodings::TEXT_CMD, termination, rem, &req));
678 set<string>::const_iterator it = req.begin();
679 set<string>::const_iterator en = req.end();
680 for (; it != en; ++it)
681 preamble.registerAutomaticallyLoadedPackage(*it);
684 if (s.empty() || s[0] != '\\')
688 for (auto const & c : known_escaped_chars)
689 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
694 return make_pair(res, os.str());
698 /// try to convert \p s to a valid InsetCommand argument
699 /// return whether this succeeded. If not, these command insets
700 /// get the "literate" flag.
701 pair<bool, string> convert_latexed_command_inset_arg(string s)
703 bool success = false;
705 // since we don't know the input encoding we can't use from_utf8
706 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
708 s = to_utf8(res.second);
710 // LyX cannot handle newlines in a latex command
711 return make_pair(success, subst(s, "\n", " "));
714 /// try to convert \p s to a valid InsetCommand argument
715 /// without trying to recode macros.
716 string convert_literate_command_inset_arg(string const & s)
718 // LyX cannot handle newlines in a latex command
719 return subst(s, "\n", " ");
722 void output_ert(ostream & os, string const & s, Context & context)
724 context.check_layout(os);
725 for (char const c : s) {
727 os << "\n\\backslash\n";
728 else if (c == '\n') {
729 context.new_paragraph(os);
730 context.check_layout(os);
734 context.check_end_layout(os);
738 void output_ert_inset(ostream & os, string const & s, Context & context)
740 // We must have a valid layout before outputting the ERT inset.
741 context.check_layout(os);
742 Context newcontext(true, context.textclass);
743 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
744 if (layout.forcePlainLayout())
745 newcontext.layout = &context.textclass.plainLayout();
746 begin_inset(os, "ERT");
747 os << "\nstatus collapsed\n";
748 output_ert(os, s, newcontext);
753 void output_comment(Parser & p, ostream & os, string const & s,
756 if (p.next_token().cat() == catNewline)
757 output_ert_inset(os, '%' + s, context);
759 output_ert_inset(os, '%' + s + '\n', context);
763 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
764 string const & latexparam = string())
766 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
769 if (checkModule(name, command))
770 return findLayoutWithoutModule(textclass, name, command, latexparam);
775 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
776 string const & latexparam = string())
778 InsetLayout const * insetlayout =
779 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
782 if (checkModule(name, command))
783 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
788 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
789 bool eatNewline = true);
793 * Skips whitespace and braces.
794 * This should be called after a command has been parsed that is not put into
795 * ERT, and where LyX adds "{}" if needed.
797 void skip_spaces_braces(Parser & p, bool keepws = false)
799 /* The following four examples produce the same typeset output and
800 should be handled by this function:
808 // Unfortunately we need to skip comments, too.
809 // We can't use eat_whitespace since writing them after the {}
810 // results in different output in some cases.
811 bool const skipped_spaces = p.skip_spaces(true);
812 bool const skipped_braces = skip_braces(p);
813 if (keepws && skipped_spaces && !skipped_braces)
814 // put back the space (it is better handled by check_space)
815 p.unskip_spaces(true);
819 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
820 Context & context, Layout::LaTeXArgMap const & latexargs)
822 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
824 context.check_layout(os);
830 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
831 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
832 for (; lait != laend; ++lait) {
834 eat_whitespace(p, os, context, false);
835 if (lait->second.mandatory) {
836 if (p.next_token().cat() != catBegin)
838 string ldelim = to_utf8(lait->second.ldelim);
839 string rdelim = to_utf8(lait->second.rdelim);
844 p.get_token(); // eat ldelim
845 if (ldelim.size() > 1)
846 p.get_token(); // eat ldelim
848 context.check_layout(os);
851 begin_inset(os, "Argument ");
854 os << i << "\nstatus collapsed\n\n";
855 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
858 string ldelim = to_utf8(lait->second.ldelim);
859 string rdelim = to_utf8(lait->second.rdelim);
864 string tok = p.next_token().asInput();
865 // we only support delimiters with max 2 chars for now.
866 if (ldelim.size() > 1)
867 tok += p.next_next_token().asInput();
868 if (p.next_token().cat() == catEscape || tok != ldelim)
870 p.get_token(); // eat ldelim
871 if (ldelim.size() > 1)
872 p.get_token(); // eat ldelim
874 context.check_layout(os);
877 begin_inset(os, "Argument ");
880 os << i << "\nstatus collapsed\n\n";
881 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
884 eat_whitespace(p, os, context, false);
889 void output_command_layout(ostream & os, Parser & p, bool outer,
890 Context & parent_context,
891 Layout const * newlayout)
893 TeXFont const oldFont = parent_context.font;
894 // save the current font size
895 string const size = oldFont.size;
896 // reset the font size to default, because the font size switches
897 // don't affect section headings and the like
898 parent_context.font.size = Context::normalfont.size;
899 // we only need to write the font change if we have an open layout
900 if (!parent_context.atParagraphStart())
901 output_font_change(os, oldFont, parent_context.font);
902 parent_context.check_end_layout(os);
903 Context context(true, parent_context.textclass, newlayout,
904 parent_context.layout, parent_context.font);
905 if (parent_context.deeper_paragraph) {
906 // We are beginning a nested environment after a
907 // deeper paragraph inside the outer list environment.
908 // Therefore we don't need to output a "begin deeper".
909 context.need_end_deeper = true;
911 context.check_deeper(os);
912 output_arguments(os, p, outer, true, string(), context,
913 context.layout->latexargs());
914 // If we have a latex param, we eat it here.
915 if (!parent_context.latexparam.empty()) {
917 Context dummy(true, parent_context.textclass);
918 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
919 string(1, parent_context.latexparam.back()));
921 parse_text(p, os, FLAG_ITEM, outer, context);
922 output_arguments(os, p, outer, false, "post", context,
923 context.layout->postcommandargs());
924 context.check_end_layout(os);
925 if (parent_context.deeper_paragraph) {
926 // We must suppress the "end deeper" because we
927 // suppressed the "begin deeper" above.
928 context.need_end_deeper = false;
930 context.check_end_deeper(os);
931 // We don't need really a new paragraph, but
932 // we must make sure that the next item gets a \begin_layout.
933 parent_context.new_paragraph(os);
934 // Set the font size to the original value. No need to output it here
935 // (Context::begin_layout() will do that if needed)
936 parent_context.font.size = size;
941 * Output a space if necessary.
942 * This function gets called for every whitespace token.
944 * We have three cases here:
945 * 1. A space must be suppressed. Example: The lyxcode case below
946 * 2. A space may be suppressed. Example: Spaces before "\par"
947 * 3. A space must not be suppressed. Example: A space between two words
949 * We currently handle only 1. and 3 and from 2. only the case of
950 * spaces before newlines as a side effect.
952 * 2. could be used to suppress as many spaces as possible. This has two effects:
953 * - Reimporting LyX generated LaTeX files changes almost no whitespace
954 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
955 * The drawback is that the logic inside the function becomes
956 * complicated, and that is the reason why it is not implemented.
958 void check_space(Parser & p, ostream & os, Context & context)
960 Token const next = p.next_token();
961 Token const curr = p.curr_token();
962 // A space before a single newline and vice versa must be ignored
963 // LyX emits a newline before \end{lyxcode}.
964 // This newline must be ignored,
965 // otherwise LyX will add an additional protected space.
966 if (next.cat() == catSpace ||
967 next.cat() == catNewline ||
968 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
971 context.check_layout(os);
977 * Parse all arguments of \p command
979 void parse_arguments(string const & command,
980 vector<ArgumentType> const & template_arguments,
981 Parser & p, ostream & os, bool outer, Context & context)
983 string ert = command;
984 size_t no_arguments = template_arguments.size();
985 for (size_t i = 0; i < no_arguments; ++i) {
986 switch (template_arguments[i]) {
989 // This argument contains regular LaTeX
990 output_ert_inset(os, ert + '{', context);
991 eat_whitespace(p, os, context, false);
992 if (template_arguments[i] == required)
993 parse_text(p, os, FLAG_ITEM, outer, context);
995 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
999 // This argument consists only of a single item.
1000 // The presence of '{' or not must be preserved.
1002 if (p.next_token().cat() == catBegin)
1003 ert += '{' + p.verbatim_item() + '}';
1005 ert += p.verbatim_item();
1009 // This argument may contain special characters
1010 ert += '{' + p.verbatim_item() + '}';
1014 // true because we must not eat whitespace
1015 // if an optional arg follows we must not strip the
1016 // brackets from this one
1017 if (i < no_arguments - 1 &&
1018 template_arguments[i+1] == optional)
1019 ert += p.getFullOpt(true);
1021 ert += p.getOpt(true);
1025 output_ert_inset(os, ert, context);
1030 * Check whether \p command is a known command. If yes,
1031 * handle the command with all arguments.
1032 * \return true if the command was parsed, false otherwise.
1034 bool parse_command(string const & command, Parser & p, ostream & os,
1035 bool outer, Context & context)
1037 if (known_commands.find(command) != known_commands.end()) {
1038 parse_arguments(command, known_commands[command], p, os,
1046 /// Parses a minipage or parbox
1047 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1048 unsigned inner_flags, bool outer, Context & parent_context,
1049 string const & outer_type, string const & special,
1050 string inner_type, string const & frame_color,
1051 string const & background_color)
1055 string hor_pos = "l";
1056 // We need to set the height to the LaTeX default of 1\\totalheight
1057 // for the case when no height argument is given
1058 string height_value = "1";
1059 string height_unit = "in";
1060 string height_special = "totalheight";
1061 string latex_height;
1065 string width_special = "none";
1066 string thickness = "0.4pt";
1067 if (!fboxrule.empty())
1068 thickness = fboxrule;
1070 thickness = "0.4pt";
1072 if (!fboxsep.empty())
1073 separation = fboxsep;
1077 if (!shadow_size.empty())
1078 shadowsize = shadow_size;
1081 string framecolor = "black";
1082 string backgroundcolor = "none";
1083 if (!frame_color.empty())
1084 framecolor = frame_color;
1085 if (!background_color.empty())
1086 backgroundcolor = background_color;
1087 // if there is a color box around the \begin statements have not yet been parsed
1089 if (!frame_color.empty() || !background_color.empty()) {
1090 eat_whitespace(p, os, parent_context, false);
1091 p.get_token().asInput(); // the '{'
1093 if (p.next_token().asInput() == "\\begin") {
1094 p.get_token().asInput();
1096 inner_type = "minipage";
1097 inner_flags = FLAG_END;
1098 active_environments.push_back("minipage");
1101 else if (p.next_token().asInput() == "\\parbox") {
1102 p.get_token().asInput();
1103 inner_type = "parbox";
1104 inner_flags = FLAG_ITEM;
1107 else if (p.next_token().asInput() == "\\makebox") {
1108 p.get_token().asInput();
1109 inner_type = "makebox";
1110 inner_flags = FLAG_ITEM;
1112 // in case there is just \colorbox{color}{text}
1115 inner_type = "makebox";
1116 inner_flags = FLAG_BRACE_LAST;
1121 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1123 if (!inner_type.empty() && p.hasOpt()) {
1124 if (inner_type != "makebox")
1125 position = p.getArg('[', ']');
1127 latex_width = p.getArg('[', ']');
1128 translate_box_len(latex_width, width_value, width_unit, width_special);
1131 if (position != "t" && position != "c" && position != "b") {
1132 cerr << "invalid position " << position << " for "
1133 << inner_type << endl;
1137 if (inner_type != "makebox") {
1138 latex_height = p.getArg('[', ']');
1139 translate_box_len(latex_height, height_value, height_unit, height_special);
1141 string const opt = p.getArg('[', ']');
1144 if (hor_pos != "l" && hor_pos != "c" &&
1145 hor_pos != "r" && hor_pos != "s") {
1146 cerr << "invalid hor_pos " << hor_pos
1147 << " for " << inner_type << endl;
1154 inner_pos = p.getArg('[', ']');
1155 if (inner_pos != "c" && inner_pos != "t" &&
1156 inner_pos != "b" && inner_pos != "s") {
1157 cerr << "invalid inner_pos "
1158 << inner_pos << " for "
1159 << inner_type << endl;
1160 inner_pos = position;
1164 if (inner_type == "makebox")
1168 if (inner_type.empty()) {
1169 if (special.empty() && outer_type != "framebox")
1170 latex_width = "1\\columnwidth";
1173 latex_width = p2.getArg('[', ']');
1174 string const opt = p2.getArg('[', ']');
1177 if (hor_pos != "l" && hor_pos != "c" &&
1178 hor_pos != "r" && hor_pos != "s") {
1179 cerr << "invalid hor_pos " << hor_pos
1180 << " for " << outer_type << endl;
1184 if (outer_type == "framebox")
1188 } else if (inner_type != "makebox")
1189 latex_width = p.verbatim_item();
1190 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1191 // as this is LyX's standard for such cases (except for makebox)
1192 // \framebox is more special and handled below
1193 if (latex_width.empty() && inner_type != "makebox"
1194 && outer_type != "framebox")
1195 latex_width = "1\\columnwidth";
1197 translate_len(latex_width, width_value, width_unit);
1199 bool shadedparbox = false;
1200 if (inner_type == "shaded") {
1201 eat_whitespace(p, os, parent_context, false);
1202 if (outer_type == "parbox") {
1204 if (p.next_token().cat() == catBegin)
1206 eat_whitespace(p, os, parent_context, false);
1207 shadedparbox = true;
1212 // If we already read the inner box we have to push the inner env
1213 if (!outer_type.empty() && !inner_type.empty() &&
1214 (inner_flags & FLAG_END))
1215 active_environments.push_back(inner_type);
1216 bool use_ert = false;
1217 if (!outer_type.empty() && !inner_type.empty()) {
1218 // Look whether there is some content after the end of the
1219 // inner box, but before the end of the outer box.
1220 // If yes, we need to output ERT.
1222 if (inner_flags & FLAG_END)
1223 p.ertEnvironment(inner_type);
1226 p.skip_spaces(true);
1227 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1228 if ((outer_env && p.next_token().asInput() != "\\end") ||
1229 (!outer_env && p.next_token().cat() != catEnd)) {
1230 // something is between the end of the inner box and
1231 // the end of the outer box, so we need to use ERT.
1239 if (!outer_type.empty()) {
1240 if (outer_flags & FLAG_END)
1241 ss << "\\begin{" << outer_type << '}';
1243 ss << '\\' << outer_type << '{';
1244 if (!special.empty())
1248 if (!inner_type.empty()) {
1249 if (inner_type != "shaded") {
1250 if (inner_flags & FLAG_END)
1251 ss << "\\begin{" << inner_type << '}';
1253 ss << '\\' << inner_type;
1255 if (!position.empty())
1256 ss << '[' << position << ']';
1257 if (!latex_height.empty())
1258 ss << '[' << latex_height << ']';
1259 if (!inner_pos.empty())
1260 ss << '[' << inner_pos << ']';
1261 ss << '{' << latex_width << '}';
1262 if (!(inner_flags & FLAG_END))
1265 if (inner_type == "shaded")
1266 ss << "\\begin{shaded}";
1267 output_ert_inset(os, ss.str(), parent_context);
1268 if (!inner_type.empty()) {
1269 parse_text(p, os, inner_flags, outer, parent_context);
1270 if (inner_flags & FLAG_END)
1271 output_ert_inset(os, "\\end{" + inner_type + '}',
1274 output_ert_inset(os, "}", parent_context);
1276 if (!outer_type.empty()) {
1277 // If we already read the inner box we have to pop
1279 if (!inner_type.empty() && (inner_flags & FLAG_END))
1280 active_environments.pop_back();
1282 // Ensure that the end of the outer box is parsed correctly:
1283 // The opening brace has been eaten by parse_outer_box()
1284 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1285 outer_flags &= ~FLAG_ITEM;
1286 outer_flags |= FLAG_BRACE_LAST;
1288 parse_text(p, os, outer_flags, outer, parent_context);
1289 if (outer_flags & FLAG_END)
1290 output_ert_inset(os, "\\end{" + outer_type + '}',
1293 output_ert_inset(os, "}", parent_context);
1296 // LyX does not like empty positions, so we have
1297 // to set them to the LaTeX default values here.
1298 if (position.empty())
1300 if (inner_pos.empty())
1301 inner_pos = position;
1302 parent_context.check_layout(os);
1303 begin_inset(os, "Box ");
1304 if (outer_type == "framed")
1306 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1308 else if (outer_type == "shadowbox")
1309 os << "Shadowbox\n";
1310 else if ((outer_type == "shaded" && inner_type.empty()) ||
1311 (outer_type == "minipage" && inner_type == "shaded") ||
1312 (outer_type == "parbox" && inner_type == "shaded")) {
1314 preamble.registerAutomaticallyLoadedPackage("color");
1315 } else if (outer_type == "doublebox")
1316 os << "Doublebox\n";
1317 else if (outer_type.empty() || outer_type == "mbox")
1318 os << "Frameless\n";
1320 os << outer_type << '\n';
1321 os << "position \"" << position << "\"\n";
1322 os << "hor_pos \"" << hor_pos << "\"\n";
1323 if (outer_type == "mbox")
1324 os << "has_inner_box 1\n";
1325 else if (!frame_color.empty() && inner_type == "makebox")
1326 os << "has_inner_box 0\n";
1328 os << "has_inner_box " << !inner_type.empty() << "\n";
1329 os << "inner_pos \"" << inner_pos << "\"\n";
1330 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1332 if (outer_type == "mbox")
1333 os << "use_makebox 1\n";
1334 else if (!frame_color.empty())
1335 os << "use_makebox 0\n";
1337 os << "use_makebox " << (inner_type == "makebox") << '\n';
1338 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1339 os << "width \"\"\n";
1340 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1341 else if (contains(width_unit, '\\'))
1342 os << "width \"" << width_value << "in" << "\"\n";
1344 os << "width \"" << width_value << width_unit << "\"\n";
1345 if (contains(width_unit, '\\')) {
1346 width_unit.erase (0,1); // remove the leading '\'
1347 os << "special \"" << width_unit << "\"\n";
1349 os << "special \"" << width_special << "\"\n";
1350 if (contains(height_unit, '\\'))
1351 os << "height \"" << height_value << "in" << "\"\n";
1353 os << "height \"" << height_value << height_unit << "\"\n";
1354 os << "height_special \"" << height_special << "\"\n";
1355 os << "thickness \"" << thickness << "\"\n";
1356 os << "separation \"" << separation << "\"\n";
1357 os << "shadowsize \"" << shadowsize << "\"\n";
1358 os << "framecolor \"" << framecolor << "\"\n";
1359 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1360 os << "status open\n\n";
1362 // Unfortunately we can't use parse_text_in_inset:
1363 // InsetBox::forcePlainLayout() is hard coded and does not
1364 // use the inset layout. Apart from that do we call parse_text
1365 // up to two times, but need only one check_end_layout.
1366 bool const forcePlainLayout =
1367 (!inner_type.empty() || inner_type == "makebox") &&
1368 outer_type != "shaded" && outer_type != "framed";
1369 Context context(true, parent_context.textclass);
1370 if (forcePlainLayout)
1371 context.layout = &context.textclass.plainLayout();
1373 context.font = parent_context.font;
1375 // If we have no inner box the contents will be read with the outer box
1376 if (!inner_type.empty())
1377 parse_text(p, os, inner_flags, outer, context);
1379 // Ensure that the end of the outer box is parsed correctly:
1380 // The opening brace has been eaten by parse_outer_box()
1381 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1382 outer_flags &= ~FLAG_ITEM;
1383 outer_flags |= FLAG_BRACE_LAST;
1386 // Find end of outer box, output contents if inner_type is
1387 // empty and output possible comments
1388 if (!outer_type.empty()) {
1389 // If we already read the inner box we have to pop
1391 if (!inner_type.empty() && (inner_flags & FLAG_END))
1392 active_environments.pop_back();
1393 // This does not output anything but comments if
1394 // inner_type is not empty (see use_ert)
1395 parse_text(p, os, outer_flags, outer, context);
1398 context.check_end_layout(os);
1400 #ifdef PRESERVE_LAYOUT
1401 // LyX puts a % after the end of the minipage
1402 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1404 //output_comment(p, os, "dummy", parent_context);
1407 parent_context.new_paragraph(os);
1409 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1410 //output_comment(p, os, "dummy", parent_context);
1413 // We add a protected space if something real follows
1414 if (p.good() && p.next_token().cat() != catComment) {
1415 begin_inset(os, "space ~\n");
1421 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1422 active_environments.pop_back();
1423 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1424 // in this case we have to eat the the closing brace of the color box
1425 p.get_token().asInput(); // the '}'
1427 if (p.next_token().asInput() == "}") {
1428 // in this case we assume that the closing brace is from the box settings
1429 // therefore reset these values for the next box
1435 // all boxes except of Frameless and Shaded require calc
1436 if (!(outer_type.empty() || outer_type == "mbox") &&
1437 !((outer_type == "shaded" && inner_type.empty()) ||
1438 (outer_type == "minipage" && inner_type == "shaded") ||
1439 (outer_type == "parbox" && inner_type == "shaded")))
1440 preamble.registerAutomaticallyLoadedPackage("calc");
1444 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1445 Context & parent_context, string const & outer_type,
1446 string const & special)
1448 eat_whitespace(p, os, parent_context, false);
1449 if (flags & FLAG_ITEM) {
1451 if (p.next_token().cat() == catBegin)
1454 cerr << "Warning: Ignoring missing '{' after \\"
1455 << outer_type << '.' << endl;
1456 eat_whitespace(p, os, parent_context, false);
1459 unsigned int inner_flags = 0;
1461 if (outer_type == "minipage" || outer_type == "parbox") {
1462 p.skip_spaces(true);
1463 while (p.hasOpt()) {
1465 p.skip_spaces(true);
1468 p.skip_spaces(true);
1469 if (outer_type == "parbox") {
1471 if (p.next_token().cat() == catBegin)
1473 p.skip_spaces(true);
1476 if (outer_type == "shaded" || outer_type == "mbox") {
1477 // These boxes never have an inner box
1479 } else if (p.next_token().asInput() == "\\parbox") {
1480 inner = p.get_token().cs();
1481 inner_flags = FLAG_ITEM;
1482 } else if (p.next_token().asInput() == "\\begin") {
1483 // Is this a minipage or shaded box?
1486 inner = p.getArg('{', '}');
1488 if (inner == "minipage" || inner == "shaded")
1489 inner_flags = FLAG_END;
1494 if (inner_flags == FLAG_END) {
1495 if (inner != "shaded")
1499 eat_whitespace(p, os, parent_context, false);
1501 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1502 outer_type, special, inner, "", "");
1504 if (inner_flags == FLAG_ITEM) {
1506 eat_whitespace(p, os, parent_context, false);
1508 parse_box(p, os, flags, inner_flags, outer, parent_context,
1509 outer_type, special, inner, "", "");
1514 void parse_index_entry(Parser & p, ostream & os, Context & context, string const & kind)
1516 // write inset header
1517 begin_inset(os, "Index ");
1520 // Parse for post argument (|...)
1522 string const marg = p.getArg('{', '}');
1525 bool inpost = false;
1526 bool startrange = false;
1527 bool endrange = false;
1529 for (string::const_iterator it = marg.begin(), et = marg.end(); it != et; ++it) {
1532 if (post.empty() && c == '(')
1534 else if (post.empty() && c == ')')
1539 if (!inpost && (c == '|' && lc != '"'))
1544 os << "\nrange start";
1546 os << "\nrange end";
1548 os << "\nrange none";
1549 bool const see = prefixIs(post, "see{");
1550 bool const seealso = prefixIs(post, "seealso{");
1551 if (!post.empty() && !see && !seealso)
1552 os << "\npageformat " << post;
1554 os << "\npageformat default";
1555 os << "\nstatus collapsed\n";
1561 if (p.hasIdxMacros("!")) {
1562 // Index entry with levels
1563 while (p.hasIdxMacros("!")) {
1567 os << "\\begin_layout Plain Layout\n";
1569 begin_inset(os, "IndexMacro subentry");
1570 os << "\nstatus collapsed\n";
1572 // Check for (level-specific) sortkey
1573 if (p.hasIdxMacros("@", "!")) {
1575 os << "\\begin_layout Plain Layout\n";
1576 begin_inset(os, "IndexMacro sortkey");
1577 os << "\nstatus collapsed\n";
1578 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1581 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "!", "\"");
1583 os << "\n\\end_layout\n";
1589 begin_inset(os, "IndexMacro subentry");
1590 os << "\nstatus collapsed\n";
1593 // Check for (level-specific) sortkey
1594 if (p.hasIdxMacros("@", "!")) {
1599 os << "\\begin_layout Plain Layout\n";
1600 begin_inset(os, "IndexMacro sortkey");
1601 os << "\nstatus collapsed\n";
1602 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1604 if (post.empty() && !startrange && !endrange) {
1605 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1608 // Handle post-argument
1609 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1610 if (see || seealso) {
1611 while (p.next_token().character() != '{' && p.good())
1613 // this ends the subinset, as the see[also] insets
1614 // must come at main index inset
1615 os << "\n\\end_layout\n";
1618 begin_inset(os, "IndexMacro see");
1620 begin_inset(os, "IndexMacro seealso");
1621 os << "\nstatus collapsed\n";
1622 os << "\\begin_layout Plain Layout\n";
1623 parse_text_snippet(p, os, FLAG_ITEM, false, context);
1629 os << "\n\\end_layout\n";
1631 if (post.empty() && !startrange && !endrange) {
1632 parse_text_in_inset(p, os, FLAG_BRACE_LAST, false, context, "IndexMacro subentry");
1635 // Handle post-argument
1636 if (see || seealso) {
1637 os << "\\begin_layout Plain Layout\n";
1638 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1639 while (p.next_token().character() != '{' && p.good())
1641 // this ends the subinset, as the see[also] insets
1642 // must come at main index inset
1643 os << "\n\\end_layout\n";
1646 begin_inset(os, "IndexMacro see");
1648 begin_inset(os, "IndexMacro seealso");
1649 os << "\nstatus collapsed\n";
1650 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1652 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1660 os << "\n\\end_layout\n";
1662 // Index without any levels
1663 // Check for sortkey
1664 if (p.hasIdxMacros("@", "!")) {
1667 os << "\\begin_layout Plain Layout\n";
1668 begin_inset(os, "IndexMacro sortkey");
1669 os << "\nstatus collapsed\n";
1670 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1672 if (post.empty() && !startrange && !endrange) {
1673 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1676 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1677 if (see || seealso) {
1678 while (p.next_token().character() != '{' && p.good())
1681 begin_inset(os, "IndexMacro see");
1683 begin_inset(os, "IndexMacro seealso");
1684 os << "\nstatus collapsed\n";
1685 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1692 os << "\n\\end_layout\n";
1694 if (post.empty() && !startrange && !endrange) {
1695 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
1698 // Handle post-argument
1701 if (see || seealso) {
1702 os << "\\begin_layout Plain Layout\n";
1703 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1704 while (p.next_token().character() != '{' && p.good())
1707 begin_inset(os, "IndexMacro see");
1709 begin_inset(os, "IndexMacro seealso");
1710 os << "\nstatus collapsed\n";
1711 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1713 os << "\n\\end_layout\n";
1715 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1726 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1727 bool in_line, bool use_minted)
1729 parent_context.check_layout(os);
1730 begin_inset(os, "listings\n");
1731 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1733 while ((i = arg.find(", ")) != string::npos
1734 || (i = arg.find(",\t")) != string::npos)
1735 arg.erase(i + 1, 1);
1738 string const language = p.getArg('{', '}');
1739 p.skip_spaces(true);
1740 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1741 if (!minted_float.empty()) {
1742 arg += string(arg.empty() ? "" : ",") + minted_float;
1743 minted_nonfloat_caption.clear();
1747 os << "lstparams " << '"' << arg << '"' << '\n';
1748 if (arg.find("\\color") != string::npos)
1749 preamble.registerAutomaticallyLoadedPackage("color");
1752 os << "inline true\n";
1754 os << "inline false\n";
1755 os << "status open\n";
1756 Context context(true, parent_context.textclass);
1757 context.layout = &parent_context.textclass.plainLayout();
1758 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1759 minted_nonfloat_caption.erase(0,3);
1760 os << "\n\\begin_layout Plain Layout\n";
1761 begin_inset(os, "Caption Standard\n");
1762 Context newcontext(true, context.textclass,
1763 context.layout, 0, context.font);
1764 newcontext.check_layout(os);
1765 os << minted_nonfloat_caption << "\n";
1766 newcontext.check_end_layout(os);
1768 os << "\n\\end_layout\n";
1769 minted_nonfloat_caption.clear();
1773 // set catcodes to verbatim early, just in case.
1774 p.setCatcodes(VERBATIM_CATCODES);
1775 string delim = p.get_token().asInput();
1776 //FIXME: handler error condition
1777 s = p.verbatimStuff(delim).second;
1778 // context.new_paragraph(os);
1779 } else if (use_minted) {
1780 s = p.verbatimEnvironment("minted");
1782 s = p.verbatimEnvironment("lstlisting");
1784 output_ert(os, s, context);
1785 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1786 minted_nonfloat_caption.erase(0,3);
1787 os << "\n\\begin_layout Plain Layout\n";
1788 begin_inset(os, "Caption Standard\n");
1789 Context newcontext(true, context.textclass,
1790 context.layout, 0, context.font);
1791 newcontext.check_layout(os);
1792 os << minted_nonfloat_caption << "\n";
1793 newcontext.check_end_layout(os);
1795 os << "\n\\end_layout\n";
1796 minted_nonfloat_caption.clear();
1798 // Don't close the inset here for floating minted listings.
1799 // It will be closed at the end of the listing environment.
1800 if (!use_minted || minted_float.empty())
1803 eat_whitespace(p, os, parent_context, true);
1804 Token t = p.get_token();
1805 if (t.asInput() != "\\end") {
1806 // If anything follows, collect it into a caption.
1807 minted_float_has_caption = true;
1808 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1809 begin_inset(os, "Caption Standard\n");
1810 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1817 /// parse an unknown environment
1818 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1819 unsigned flags, bool outer,
1820 Context & parent_context)
1822 if (name == "tabbing")
1823 // We need to remember that we have to handle '\=' specially
1824 flags |= FLAG_TABBING;
1826 // We need to translate font changes and paragraphs inside the
1827 // environment to ERT if we have a non standard font.
1828 // Otherwise things like
1829 // \large\begin{foo}\huge bar\end{foo}
1831 bool const specialfont =
1832 (parent_context.font != parent_context.normalfont);
1833 bool const new_layout_allowed = parent_context.new_layout_allowed;
1835 parent_context.new_layout_allowed = false;
1836 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1837 // Try to handle options: Look if we have optional arguments,
1838 // and if so, put the brackets in ERT.
1839 while (p.hasOpt()) {
1840 p.get_token(); // eat '['
1841 output_ert_inset(os, "[", parent_context);
1842 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1843 output_ert_inset(os, "]", parent_context);
1845 parse_text_snippet(p, os, flags, outer, parent_context);
1846 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1848 parent_context.new_layout_allowed = new_layout_allowed;
1852 void parse_environment(Parser & p, ostream & os, bool outer,
1853 string & last_env, Context & parent_context)
1855 Layout const * newlayout;
1856 InsetLayout const * newinsetlayout = 0;
1857 string const name = p.getArg('{', '}');
1858 const bool is_starred = suffixIs(name, '*');
1859 string const unstarred_name = rtrim(name, "*");
1860 active_environments.push_back(name);
1862 // We use this loop and break out after a condition is met
1863 // rather than a huge else-if-chain.
1865 if (is_math_env(name)) {
1866 parent_context.check_layout(os);
1867 begin_inset(os, "Formula ");
1868 os << "\\begin{" << name << "}";
1869 parse_math(p, os, FLAG_END, MATH_MODE);
1870 os << "\\end{" << name << "}";
1872 if (is_display_math_env(name)) {
1873 // Prevent the conversion of a line break to a space
1874 // (bug 7668). This does not change the output, but
1875 // looks ugly in LyX.
1876 eat_whitespace(p, os, parent_context, false);
1881 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1882 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1883 // We must begin a new paragraph if not already done
1884 if (!parent_context.atParagraphStart()) {
1885 parent_context.check_end_layout(os);
1886 parent_context.new_paragraph(os);
1888 // store previous language because we must reset it at the end
1889 string const lang_old = parent_context.font.language;
1890 // save new language in context so that it is
1891 // handled by parse_text
1892 parent_context.font.language =
1893 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1894 parse_text(p, os, FLAG_END, outer, parent_context);
1895 // reset previous language
1896 parent_context.font.language = lang_old;
1897 // Just in case the environment is empty
1898 parent_context.extra_stuff.erase();
1899 // We must begin a new paragraph to reset the language
1900 parent_context.new_paragraph(os);
1905 if (unstarred_name == "tabular" || name == "longtable"
1906 || name == "tabularx" || name == "xltabular") {
1907 eat_whitespace(p, os, parent_context, false);
1908 string width = "0pt";
1910 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1911 string const opt = p.getArg('[', ']');
1914 else if (opt == "l")
1916 else if (opt == "r")
1919 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1920 width = lyx::translate_len(p.getArg('{', '}'));
1921 eat_whitespace(p, os, parent_context, false);
1923 parent_context.check_layout(os);
1924 begin_inset(os, "Tabular ");
1925 handle_tabular(p, os, name, width, halign, parent_context);
1931 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1932 eat_whitespace(p, os, parent_context, false);
1933 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1934 eat_whitespace(p, os, parent_context, false);
1935 parent_context.check_layout(os);
1936 begin_inset(os, "Float " + unstarred_name + "\n");
1937 // store the float type for subfloats
1938 // subfloats only work with figures and tables
1939 if (unstarred_name == "figure")
1940 float_type = unstarred_name;
1941 else if (unstarred_name == "table")
1942 float_type = unstarred_name;
1946 os << "placement " << opt << '\n';
1947 if (contains(opt, "H"))
1948 preamble.registerAutomaticallyLoadedPackage("float");
1950 Floating const & fl = parent_context.textclass.floats()
1951 .getType(unstarred_name);
1952 if (!fl.floattype().empty() && fl.usesFloatPkg())
1953 preamble.registerAutomaticallyLoadedPackage("float");
1956 os << "wide " << convert<string>(is_starred)
1957 << "\nsideways false"
1958 << "\nstatus open\n\n";
1959 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1960 if (unstarred_name == "algorithm")
1961 // in algorithm, \; has special meaning
1962 parent_context.pass_thru_cmds.insert(";");
1963 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1964 if (unstarred_name == "algorithm")
1965 parent_context.pass_thru_cmds = pass_thru_cmds;
1967 // We don't need really a new paragraph, but
1968 // we must make sure that the next item gets a \begin_layout.
1969 parent_context.new_paragraph(os);
1971 // the float is parsed thus delete the type
1976 if (unstarred_name == "sidewaysfigure"
1977 || unstarred_name == "sidewaystable"
1978 || unstarred_name == "sidewaysalgorithm") {
1979 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1980 eat_whitespace(p, os, parent_context, false);
1981 parent_context.check_layout(os);
1982 if (unstarred_name == "sidewaysfigure")
1983 begin_inset(os, "Float figure\n");
1984 else if (unstarred_name == "sidewaystable")
1985 begin_inset(os, "Float table\n");
1986 else if (unstarred_name == "sidewaysalgorithm")
1987 begin_inset(os, "Float algorithm\n");
1989 os << "placement " << opt << '\n';
1990 if (contains(opt, "H"))
1991 preamble.registerAutomaticallyLoadedPackage("float");
1992 os << "wide " << convert<string>(is_starred)
1993 << "\nsideways true"
1994 << "\nstatus open\n\n";
1995 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1997 // We don't need really a new paragraph, but
1998 // we must make sure that the next item gets a \begin_layout.
1999 parent_context.new_paragraph(os);
2001 preamble.registerAutomaticallyLoadedPackage("rotfloat");
2005 if (name == "wrapfigure" || name == "wraptable") {
2006 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
2007 eat_whitespace(p, os, parent_context, false);
2008 parent_context.check_layout(os);
2011 string overhang = "0col%";
2014 lines = p.getArg('[', ']');
2015 string const placement = p.getArg('{', '}');
2017 overhang = p.getArg('[', ']');
2018 string const width = p.getArg('{', '}');
2020 if (name == "wrapfigure")
2021 begin_inset(os, "Wrap figure\n");
2023 begin_inset(os, "Wrap table\n");
2024 os << "lines " << lines
2025 << "\nplacement " << placement
2026 << "\noverhang " << lyx::translate_len(overhang)
2027 << "\nwidth " << lyx::translate_len(width)
2028 << "\nstatus open\n\n";
2029 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2031 // We don't need really a new paragraph, but
2032 // we must make sure that the next item gets a \begin_layout.
2033 parent_context.new_paragraph(os);
2035 preamble.registerAutomaticallyLoadedPackage("wrapfig");
2039 if (name == "minipage") {
2040 eat_whitespace(p, os, parent_context, false);
2041 // Test whether this is an outer box of a shaded box
2043 // swallow arguments
2044 while (p.hasOpt()) {
2046 p.skip_spaces(true);
2049 p.skip_spaces(true);
2050 Token t = p.get_token();
2051 bool shaded = false;
2052 if (t.asInput() == "\\begin") {
2053 p.skip_spaces(true);
2054 if (p.getArg('{', '}') == "shaded")
2059 parse_outer_box(p, os, FLAG_END, outer,
2060 parent_context, name, "shaded");
2062 parse_box(p, os, 0, FLAG_END, outer, parent_context,
2063 "", "", name, "", "");
2068 if (name == "comment") {
2069 eat_whitespace(p, os, parent_context, false);
2070 parent_context.check_layout(os);
2071 begin_inset(os, "Note Comment\n");
2072 os << "status open\n";
2073 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2076 skip_braces(p); // eat {} that might by set by LyX behind comments
2077 preamble.registerAutomaticallyLoadedPackage("verbatim");
2081 if (unstarred_name == "verbatim") {
2082 // FIXME: this should go in the generic code that
2083 // handles environments defined in layout file that
2084 // have "PassThru 1". However, the code over there is
2085 // already too complicated for my taste.
2086 string const ascii_name =
2087 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
2088 parent_context.new_paragraph(os);
2089 Context context(true, parent_context.textclass,
2090 &parent_context.textclass[from_ascii(ascii_name)]);
2091 string s = p.verbatimEnvironment(name);
2092 output_ert(os, s, context);
2097 if (name == "IPA") {
2098 eat_whitespace(p, os, parent_context, false);
2099 parent_context.check_layout(os);
2100 begin_inset(os, "IPA\n");
2101 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
2102 // These commands have special meanings in IPA
2103 parent_context.pass_thru_cmds.insert("!");
2104 parent_context.pass_thru_cmds.insert(";");
2105 parent_context.pass_thru_cmds.insert(":");
2106 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2107 parent_context.pass_thru_cmds = pass_thru_cmds;
2110 preamble.registerAutomaticallyLoadedPackage("tipa");
2111 preamble.registerAutomaticallyLoadedPackage("tipx");
2115 if (name == parent_context.textclass.titlename()
2116 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
2117 parse_text(p, os, FLAG_END, outer, parent_context);
2118 // Just in case the environment is empty
2119 parent_context.extra_stuff.erase();
2120 // We must begin a new paragraph
2121 parent_context.new_paragraph(os);
2126 if (name == "CJK") {
2127 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
2128 // It is impossible to decide if a CJK environment was in its own paragraph or within
2129 // a line. We therefore always assume a paragraph since the latter is a rare case.
2130 eat_whitespace(p, os, parent_context, false);
2131 parent_context.check_end_layout(os);
2132 // store the encoding to be able to reset it
2133 string const encoding_old = p.getEncoding();
2134 string const encoding = p.getArg('{', '}');
2135 // FIXME: For some reason JIS does not work. Although the text
2136 // in tests/CJK.tex is identical with the SJIS version if you
2137 // convert both snippets using the recode command line utility,
2138 // the resulting .lyx file contains some extra characters if
2139 // you set buggy_encoding to false for JIS.
2140 bool const buggy_encoding = encoding == "JIS";
2141 if (!buggy_encoding)
2142 p.setEncoding(encoding, Encoding::CJK);
2144 // FIXME: This will read garbage, since the data is not encoded in utf8.
2145 p.setEncoding("UTF-8");
2147 // LyX only supports the same mapping for all CJK
2148 // environments, so we might need to output everything as ERT
2149 string const mapping = trim(p.getArg('{', '}'));
2150 char const * const * const where =
2151 is_known(encoding, supported_CJK_encodings);
2152 if (!buggy_encoding && !preamble.fontCJKSet())
2153 preamble.fontCJK(mapping);
2154 bool knownMapping = mapping == preamble.fontCJK();
2155 if (buggy_encoding || !knownMapping || !where) {
2156 parent_context.check_layout(os);
2157 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
2159 // we must parse the content as verbatim because e.g. JIS can contain
2160 // normally invalid characters
2161 // FIXME: This works only for the most simple cases.
2162 // Since TeX control characters are not parsed,
2163 // things like comments are completely wrong.
2164 string const s = p.plainEnvironment("CJK");
2165 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
2168 if (snip == "\\" || is_known(snip, known_escaped_chars))
2169 output_ert_inset(os, snip, parent_context);
2170 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
2175 output_ert_inset(os, "\\end{" + name + "}",
2179 supported_CJK_languages[where - supported_CJK_encodings];
2180 // store the language because we must reset it at the end
2181 string const lang_old = parent_context.font.language;
2182 parent_context.font.language = lang;
2183 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2184 parent_context.font.language = lang_old;
2185 parent_context.new_paragraph(os);
2187 p.setEncoding(encoding_old);
2192 if (name == "lyxgreyedout") {
2193 eat_whitespace(p, os, parent_context, false);
2194 parent_context.check_layout(os);
2195 begin_inset(os, "Note Greyedout\n");
2196 os << "status open\n";
2197 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2200 if (!preamble.notefontcolor().empty())
2201 preamble.registerAutomaticallyLoadedPackage("color");
2205 if (name == "btSect") {
2206 eat_whitespace(p, os, parent_context, false);
2207 parent_context.check_layout(os);
2208 begin_command_inset(os, "bibtex", "bibtex");
2209 string bibstyle = "plain";
2211 bibstyle = p.getArg('[', ']');
2212 p.skip_spaces(true);
2214 string const bibfile = p.getArg('{', '}');
2215 eat_whitespace(p, os, parent_context, false);
2216 Token t = p.get_token();
2217 if (t.asInput() == "\\btPrintCited") {
2218 p.skip_spaces(true);
2219 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2221 if (t.asInput() == "\\btPrintNotCited") {
2222 p.skip_spaces(true);
2223 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2225 if (t.asInput() == "\\btPrintAll") {
2226 p.skip_spaces(true);
2227 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2229 os << "bibfiles " << '"' << bibfile << "\"\n"
2230 << "options " << '"' << bibstyle << "\"\n";
2231 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2237 if (name == "btUnit") {
2238 string const nt = p.next_next_token().cs();
2239 // Do not attempt to overwrite a former diverging multibib.
2240 // Those are output as ERT instead.
2241 if ((nt == "part" || nt == "chapter"
2242 || nt == "section" || nt == "subsection")
2243 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2244 parse_text(p, os, FLAG_END, outer, parent_context);
2245 preamble.multibib(nt);
2247 parse_unknown_environment(p, name, os, FLAG_END, outer,
2252 // This is only attempted at turn environments that consist only
2253 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2254 // Thus we will fall through in other cases.
2255 if (name == "turn") {
2256 // We check if the next thing is a tabular[*|x]
2258 p.getArg('{', '}');// eat turn argument
2259 bool found_end = false;
2260 bool only_table = false;
2261 bool end_table = false;
2264 string envname = p.getArg('{', '}');
2265 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2266 // Now we check if the table is the only content
2267 // of the turn environment
2268 string const tenv = envname;
2269 while (!found_end && !end_table && p.good()) {
2270 envname = p.next_token().cat() == catBegin
2271 ? p.getArg('{', '}') : string();
2272 Token const & t = p.get_token();
2274 end_table = t.asInput() != "\\end"
2276 found_end = t.asInput() == "\\end"
2277 && envname == "turn";
2281 envname = p.getArg('{', '}');
2282 only_table = p.next_next_token().asInput() == "\\end"
2283 && envname == "turn";
2287 string const angle = p.getArg('{', '}');
2289 int const save_tablerotation = parent_context.tablerotation;
2290 parent_context.tablerotation = convert<int>(angle);
2291 parse_text(p, os, FLAG_END, outer, parent_context);
2292 parent_context.tablerotation = save_tablerotation;
2302 // This is only attempted at landscape environments that consist only
2303 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2304 // Other landscape environment is handled via the landscape module, thus
2305 // we will fall through in that case.
2306 if (name == "landscape") {
2307 // We check if the next thing is a longtable
2309 bool found_end = false;
2310 bool only_longtable = false;
2311 bool end_longtable = false;
2314 string envname = p.getArg('{', '}');
2315 if (envname == "longtable" || envname == "xltabular") {
2316 // Now we check if the longtable is the only content
2317 // of the landscape environment
2318 string const ltenv = envname;
2319 while (!found_end && !end_longtable && p.good()) {
2320 envname = p.next_token().cat() == catBegin
2321 ? p.getArg('{', '}') : string();
2322 Token const & t = p.get_token();
2324 end_longtable = t.asInput() != "\\end"
2325 && envname == ltenv;
2326 found_end = t.asInput() == "\\end"
2327 && envname == "landscape";
2329 if (end_longtable) {
2331 envname = p.getArg('{', '}');
2332 only_longtable = p.next_next_token().asInput() == "\\end"
2333 && envname == "landscape";
2335 if (only_longtable) {
2338 int const save_tablerotation = parent_context.tablerotation;
2339 parent_context.tablerotation = 90;
2340 parse_text(p, os, FLAG_END, outer, parent_context);
2341 parent_context.tablerotation = save_tablerotation;
2351 if (name == "framed" || name == "shaded") {
2352 eat_whitespace(p, os, parent_context, false);
2353 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2355 preamble.registerAutomaticallyLoadedPackage("framed");
2359 if (name == "listing") {
2360 minted_float = "float";
2361 eat_whitespace(p, os, parent_context, false);
2362 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2364 minted_float += "=" + opt;
2365 // If something precedes \begin{minted}, we output it at the end
2366 // as a caption, in order to keep it inside the listings inset.
2367 eat_whitespace(p, os, parent_context, true);
2369 Token const & t = p.get_token();
2370 p.skip_spaces(true);
2371 string const envname = p.next_token().cat() == catBegin
2372 ? p.getArg('{', '}') : string();
2373 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2375 minted_float_has_caption = false;
2376 string content = parse_text_snippet(p, FLAG_END, outer,
2378 size_t i = content.find("\\begin_inset listings");
2379 bool minted_env = i != string::npos;
2382 caption = content.substr(0, i);
2383 content.erase(0, i);
2385 parent_context.check_layout(os);
2386 if (minted_env && minted_float_has_caption) {
2387 eat_whitespace(p, os, parent_context, true);
2388 os << content << "\n";
2389 if (!caption.empty())
2390 os << caption << "\n";
2391 os << "\n\\end_layout\n"; // close inner layout
2392 end_inset(os); // close caption inset
2393 os << "\n\\end_layout\n"; // close outer layout
2394 } else if (!caption.empty()) {
2396 begin_inset(os, "listings\n");
2397 os << "lstparams " << '"' << minted_float << '"' << '\n';
2398 os << "inline false\n";
2399 os << "status collapsed\n";
2401 os << "\n\\begin_layout Plain Layout\n";
2402 begin_inset(os, "Caption Standard\n");
2403 Context newcontext(true, parent_context.textclass,
2404 0, 0, parent_context.font);
2405 newcontext.check_layout(os);
2406 os << caption << "\n";
2407 newcontext.check_end_layout(os);
2409 os << "\n\\end_layout\n";
2410 } else if (content.empty()) {
2411 begin_inset(os, "listings\n");
2412 os << "lstparams " << '"' << minted_float << '"' << '\n';
2413 os << "inline false\n";
2414 os << "status collapsed\n";
2416 os << content << "\n";
2418 end_inset(os); // close listings inset
2419 parent_context.check_end_layout(os);
2420 parent_context.new_paragraph(os);
2422 minted_float.clear();
2423 minted_float_has_caption = false;
2427 if (name == "lstlisting" || name == "minted") {
2428 bool use_minted = name == "minted";
2429 // with listings, we do not eat newlines here since
2430 // \begin{lstlistings}
2433 // // \begin{lstlistings}%
2436 // reads [foo] as content, whereas
2437 // // \begin{lstlistings}%
2440 // \begin{lstlistings}[foo,
2442 // reads [foo...] as argument.
2443 eat_whitespace(p, os, parent_context, false, use_minted);
2444 if (use_minted && minted_float.empty()) {
2445 // look ahead for a bottom caption
2447 bool found_end_minted = false;
2448 while (!found_end_minted && p.good()) {
2449 Token const & t = p.get_token();
2451 string const envname =
2452 p.next_token().cat() == catBegin
2453 ? p.getArg('{', '}') : string();
2454 found_end_minted = t.asInput() == "\\end"
2455 && envname == "minted";
2457 eat_whitespace(p, os, parent_context, true);
2458 Token const & t = p.get_token();
2459 p.skip_spaces(true);
2460 if (t.asInput() == "\\lyxmintcaption") {
2461 string const pos = p.getArg('[', ']');
2463 string const caption =
2464 parse_text_snippet(p, FLAG_ITEM,
2465 false, parent_context);
2466 minted_nonfloat_caption = "[b]" + caption;
2467 eat_whitespace(p, os, parent_context, true);
2472 parse_listings(p, os, parent_context, false, use_minted);
2477 if (!parent_context.new_layout_allowed) {
2478 parse_unknown_environment(p, name, os, FLAG_END, outer,
2483 // Alignment and spacing settings
2484 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2485 // therefore are totally broken!
2486 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2487 // they are commands not environments. They are furthermore switches that
2488 // can be ended by another switches, but also by commands like \footnote or
2489 // \parbox. So the only safe way is to leave them untouched.
2490 // However, we support the pseudo-environments
2491 // \begin{centering} ... \end{centering}
2492 // \begin{raggedright} ... \end{raggedright}
2493 // \begin{raggedleft} ... \end{raggedleft}
2494 // since they are used by LyX in floats (for spacing reasons)
2495 if (name == "center" || name == "centering"
2496 || name == "flushleft" || name == "raggedright"
2497 || name == "flushright" || name == "raggedleft"
2498 || name == "singlespace" || name == "onehalfspace"
2499 || name == "doublespace" || name == "spacing") {
2500 eat_whitespace(p, os, parent_context, false);
2501 // We must begin a new paragraph if not already done
2502 if (! parent_context.atParagraphStart()) {
2503 parent_context.check_end_layout(os);
2504 parent_context.new_paragraph(os);
2506 if (name == "flushleft" || name == "raggedright")
2507 parent_context.add_extra_stuff("\\align left\n");
2508 else if (name == "flushright" || name == "raggedleft")
2509 parent_context.add_extra_stuff("\\align right\n");
2510 else if (name == "center" || name == "centering")
2511 parent_context.add_extra_stuff("\\align center\n");
2512 else if (name == "singlespace")
2513 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2514 else if (name == "onehalfspace") {
2515 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2516 preamble.registerAutomaticallyLoadedPackage("setspace");
2517 } else if (name == "doublespace") {
2518 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2519 preamble.registerAutomaticallyLoadedPackage("setspace");
2520 } else if (name == "spacing") {
2521 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2522 preamble.registerAutomaticallyLoadedPackage("setspace");
2524 parse_text(p, os, FLAG_END, outer, parent_context);
2525 // Just in case the environment is empty
2526 parent_context.extra_stuff.erase();
2527 // We must begin a new paragraph to reset the alignment
2528 parent_context.new_paragraph(os);
2533 // The single '=' is meant here.
2534 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2535 eat_whitespace(p, os, parent_context, false);
2536 Context context(true, parent_context.textclass, newlayout,
2537 parent_context.layout, parent_context.font);
2538 if (parent_context.deeper_paragraph) {
2539 // We are beginning a nested environment after a
2540 // deeper paragraph inside the outer list environment.
2541 // Therefore we don't need to output a "begin deeper".
2542 context.need_end_deeper = true;
2544 parent_context.check_end_layout(os);
2545 if (last_env == name) {
2546 // we need to output a separator since LyX would export
2547 // the two environments as one otherwise (bug 5716)
2548 TeX2LyXDocClass const & textclass(parent_context.textclass);
2549 Context newcontext(true, textclass,
2550 &(textclass.defaultLayout()));
2551 newcontext.check_layout(os);
2552 begin_inset(os, "Separator plain\n");
2554 newcontext.check_end_layout(os);
2556 switch (context.layout->latextype) {
2557 case LATEX_LIST_ENVIRONMENT:
2558 context.in_list_preamble =
2559 !context.layout->listpreamble().empty()
2560 && p.hasListPreamble(context.layout->itemcommand());
2561 context.add_par_extra_stuff("\\labelwidthstring "
2562 + p.verbatim_item() + '\n');
2565 case LATEX_BIB_ENVIRONMENT:
2566 p.verbatim_item(); // swallow next arg
2572 context.check_deeper(os);
2573 if (newlayout->keepempty) {
2574 // We need to start a new paragraph
2575 // even if it is empty.
2576 context.new_paragraph(os);
2577 context.check_layout(os);
2579 // handle known optional and required arguments
2580 if (context.layout->latextype == LATEX_ENVIRONMENT)
2581 output_arguments(os, p, outer, false, string(), context,
2582 context.layout->latexargs());
2583 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2584 context.in_list_preamble =
2585 !context.layout->listpreamble().empty()
2586 && p.hasListPreamble(context.layout->itemcommand());
2588 output_arguments(oss, p, outer, false, string(), context,
2589 context.layout->latexargs());
2590 context.list_extra_stuff = oss.str();
2592 if (context.in_list_preamble) {
2593 // Collect the stuff between \begin and first \item
2594 context.list_preamble =
2595 parse_text_snippet(p, FLAG_END, outer, context);
2596 context.in_list_preamble = false;
2598 parse_text(p, os, FLAG_END, outer, context);
2599 if (context.layout->latextype == LATEX_ENVIRONMENT)
2600 output_arguments(os, p, outer, false, "post", context,
2601 context.layout->postcommandargs());
2602 context.check_end_layout(os);
2603 if (parent_context.deeper_paragraph) {
2604 // We must suppress the "end deeper" because we
2605 // suppressed the "begin deeper" above.
2606 context.need_end_deeper = false;
2608 context.check_end_deeper(os);
2609 parent_context.new_paragraph(os);
2611 if (!preamble.titleLayoutFound())
2612 preamble.titleLayoutFound(newlayout->intitle);
2613 set<string> const & req = newlayout->required();
2614 set<string>::const_iterator it = req.begin();
2615 set<string>::const_iterator en = req.end();
2616 for (; it != en; ++it)
2617 preamble.registerAutomaticallyLoadedPackage(*it);
2621 // The single '=' is meant here.
2622 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2623 eat_whitespace(p, os, parent_context, false);
2624 parent_context.check_layout(os);
2625 begin_inset(os, "Flex ");
2626 docstring flex_name = newinsetlayout->name();
2627 // FIXME: what do we do if the prefix is not Flex: ?
2628 if (prefixIs(flex_name, from_ascii("Flex:")))
2629 flex_name.erase(0, 5);
2630 os << to_utf8(flex_name) << '\n'
2631 << "status collapsed\n";
2632 if (newinsetlayout->isPassThru()) {
2633 string const arg = p.verbatimEnvironment(name);
2634 Context context(true, parent_context.textclass,
2635 &parent_context.textclass.plainLayout(),
2636 parent_context.layout);
2637 output_ert(os, arg, parent_context);
2639 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2644 if (name == "appendix") {
2645 // This is no good latex style, but it works and is used in some documents...
2646 eat_whitespace(p, os, parent_context, false);
2647 parent_context.check_end_layout(os);
2648 Context context(true, parent_context.textclass, parent_context.layout,
2649 parent_context.layout, parent_context.font);
2650 context.check_layout(os);
2651 os << "\\start_of_appendix\n";
2652 parse_text(p, os, FLAG_END, outer, context);
2653 context.check_end_layout(os);
2658 if (known_environments.find(name) != known_environments.end()) {
2659 vector<ArgumentType> arguments = known_environments[name];
2660 // The last "argument" denotes whether we may translate the
2661 // environment contents to LyX
2662 // The default required if no argument is given makes us
2663 // compatible with the reLyXre environment.
2664 ArgumentType contents = arguments.empty() ?
2667 if (!arguments.empty())
2668 arguments.pop_back();
2669 // See comment in parse_unknown_environment()
2670 bool const specialfont =
2671 (parent_context.font != parent_context.normalfont);
2672 bool const new_layout_allowed =
2673 parent_context.new_layout_allowed;
2675 parent_context.new_layout_allowed = false;
2676 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2677 outer, parent_context);
2678 if (contents == verbatim)
2679 output_ert_inset(os, p.ertEnvironment(name),
2682 parse_text_snippet(p, os, FLAG_END, outer,
2684 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2686 parent_context.new_layout_allowed = new_layout_allowed;
2690 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2695 active_environments.pop_back();
2699 /// parses a comment and outputs it to \p os.
2700 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2701 bool skipNewlines = false)
2703 LASSERT(t.cat() == catComment, return);
2704 if (!t.cs().empty()) {
2705 context.check_layout(os);
2706 output_comment(p, os, t.cs(), context);
2707 if (p.next_token().cat() == catNewline) {
2708 // A newline after a comment line starts a new
2710 if (context.new_layout_allowed) {
2711 if(!context.atParagraphStart())
2712 // Only start a new paragraph if not already
2713 // done (we might get called recursively)
2714 context.new_paragraph(os);
2716 output_ert_inset(os, "\n", context);
2717 eat_whitespace(p, os, context, true);
2719 } else if (!skipNewlines) {
2720 // "%\n" combination
2727 * Reads spaces and comments until the first non-space, non-comment token.
2728 * New paragraphs (double newlines or \\par) are handled like simple spaces
2729 * if \p eatParagraph is true.
2730 * If \p eatNewline is false, newlines won't be treated as whitespace.
2731 * Spaces are skipped, but comments are written to \p os.
2733 void eat_whitespace(Parser & p, ostream & os, Context & context,
2734 bool eatParagraph, bool eatNewline)
2737 Token const & t = p.get_token();
2738 if (t.cat() == catComment)
2739 parse_comment(p, os, t, context, !eatNewline);
2740 else if ((!eatParagraph && p.isParagraph()) ||
2741 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2750 * Set a font attribute, parse text and reset the font attribute.
2751 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2752 * \param currentvalue Current value of the attribute. Is set to the new
2753 * value during parsing.
2754 * \param newvalue New value of the attribute
2756 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2757 Context & context, string const & attribute,
2758 string & currentvalue, string const & newvalue)
2760 context.check_layout(os);
2761 string const oldvalue = currentvalue;
2762 currentvalue = newvalue;
2763 os << '\n' << attribute << ' ' << newvalue << "\n";
2764 parse_text_snippet(p, os, flags, outer, context);
2765 context.check_layout(os);
2766 os << '\n' << attribute << ' ' << oldvalue << "\n";
2767 currentvalue = oldvalue;
2771 /// get the arguments of a natbib or jurabib citation command
2772 void get_cite_arguments(Parser & p, bool natbibOrder,
2773 string & before, string & after, bool const qualified = false)
2775 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2777 // text before the citation
2779 // text after the citation
2780 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2782 if (!after.empty()) {
2783 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2784 if (natbibOrder && !before.empty())
2785 swap(before, after);
2790 void copy_file(FileName const & src, string const & dstname)
2794 string const absParent = getParentFilePath(false);
2796 if (FileName::isAbsolute(dstname))
2797 dst = FileName(dstname);
2799 dst = makeAbsPath(dstname, absParent);
2800 FileName const srcpath = src.onlyPath();
2801 FileName const dstpath = dst.onlyPath();
2802 if (equivalent(srcpath, dstpath))
2804 if (!dstpath.isDirectory()) {
2805 if (!dstpath.createPath()) {
2806 cerr << "Warning: Could not create directory for file `"
2807 << dst.absFileName() << "´." << endl;
2811 if (dst.isReadableFile()) {
2812 if (overwriteFiles())
2813 cerr << "Warning: Overwriting existing file `"
2814 << dst.absFileName() << "´." << endl;
2816 cerr << "Warning: Not overwriting existing file `"
2817 << dst.absFileName() << "´." << endl;
2821 if (!src.copyTo(dst))
2822 cerr << "Warning: Could not copy file `" << src.absFileName()
2823 << "´ to `" << dst.absFileName() << "´." << endl;
2827 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2828 bool parse_chunk(Parser & p, ostream & os, Context & context)
2830 // check whether a chunk is possible here.
2831 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2837 // read the parameters
2838 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2839 if (!params.first) {
2844 Parser::Arg const code = p.verbatimStuff("\n@");
2849 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2850 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2854 // The last newline read is important for paragraph handling
2858 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2859 // We must have a valid layout before outputting the Chunk inset.
2860 context.check_layout(os);
2861 Context chunkcontext(true, context.textclass);
2862 chunkcontext.layout = &context.textclass.plainLayout();
2863 begin_inset(os, "Flex Chunk");
2864 os << "\nstatus open\n";
2865 if (!params.second.empty()) {
2866 chunkcontext.check_layout(os);
2867 Context paramscontext(true, context.textclass);
2868 paramscontext.layout = &context.textclass.plainLayout();
2869 begin_inset(os, "Argument 1");
2870 os << "\nstatus open\n";
2871 output_ert(os, params.second, paramscontext);
2874 output_ert(os, code.second, chunkcontext);
2882 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2883 bool is_macro(Parser & p)
2885 Token first = p.curr_token();
2886 if (first.cat() != catEscape || !p.good())
2888 if (first.cs() == "def")
2890 if (first.cs() != "global" && first.cs() != "long")
2892 Token second = p.get_token();
2894 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2895 second.cat() == catNewline || second.cat() == catComment)) {
2896 second = p.get_token();
2899 bool secondvalid = second.cat() == catEscape;
2901 bool thirdvalid = false;
2902 if (p.good() && first.cs() == "global" && secondvalid &&
2903 second.cs() == "long") {
2904 third = p.get_token();
2906 while (p.good() && !p.isParagraph() &&
2907 (third.cat() == catSpace ||
2908 third.cat() == catNewline ||
2909 third.cat() == catComment)) {
2910 third = p.get_token();
2913 thirdvalid = third.cat() == catEscape;
2915 for (int i = 0; i < pos; ++i)
2920 return (first.cs() == "global" || first.cs() == "long") &&
2921 second.cs() == "def";
2922 return first.cs() == "global" && second.cs() == "long" &&
2923 third.cs() == "def";
2927 /// Parse a macro definition (assumes that is_macro() returned true)
2928 void parse_macro(Parser & p, ostream & os, Context & context)
2930 context.check_layout(os);
2931 Token first = p.curr_token();
2934 string command = first.asInput();
2935 if (first.cs() != "def") {
2937 eat_whitespace(p, os, context, false);
2938 second = p.curr_token();
2939 command += second.asInput();
2940 if (second.cs() != "def") {
2942 eat_whitespace(p, os, context, false);
2943 third = p.curr_token();
2944 command += third.asInput();
2947 eat_whitespace(p, os, context, false);
2948 string const name = p.get_token().cs();
2949 eat_whitespace(p, os, context, false);
2955 while (p.next_token().cat() != catBegin) {
2956 if (p.next_token().cat() == catParameter) {
2961 // followed by number?
2962 if (p.next_token().cat() == catOther) {
2963 string s = p.get_token().asInput();
2965 // number = current arity + 1?
2966 if (s.size() == 1 && s[0] == arity + '0' + 1)
2971 paramtext += p.get_token().cs();
2973 paramtext += p.get_token().cs();
2978 // only output simple (i.e. compatible) macro as FormulaMacros
2979 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2981 context.check_layout(os);
2982 begin_inset(os, "FormulaMacro");
2983 os << "\n\\def" << ert;
2986 output_ert_inset(os, command + ert, context);
2990 void registerExternalTemplatePackages(string const & name)
2992 external::TemplateManager const & etm = external::TemplateManager::get();
2993 external::Template const * const et = etm.getTemplateByName(name);
2996 external::Template::Formats::const_iterator cit = et->formats.end();
2998 cit = et->formats.find("PDFLaTeX");
2999 if (cit == et->formats.end())
3000 // If the template has not specified a PDFLaTeX output,
3001 // we try the LaTeX format.
3002 cit = et->formats.find("LaTeX");
3003 if (cit == et->formats.end())
3005 vector<string>::const_iterator qit = cit->second.requirements.begin();
3006 vector<string>::const_iterator qend = cit->second.requirements.end();
3007 for (; qit != qend; ++qit)
3008 preamble.registerAutomaticallyLoadedPackage(*qit);
3011 } // anonymous namespace
3015 * Find a file with basename \p name in path \p path and an extension
3018 string find_file(string const & name, string const & path,
3019 char const * const * extensions)
3021 for (char const * const * what = extensions; *what; ++what) {
3022 string const trial = addExtension(name, *what);
3023 if (makeAbsPath(trial, path).exists())
3030 /// Convert filenames with TeX macros and/or quotes to something LyX
3032 string const normalize_filename(string const & name)
3037 Token const & t = p.get_token();
3038 if (t.cat() != catEscape)
3040 else if (t.cs() == "lyxdot") {
3041 // This is used by LyX for simple dots in relative
3045 } else if (t.cs() == "space") {
3048 } else if (t.cs() == "string") {
3049 // Convert \string" to " and \string~ to ~
3050 Token const & n = p.next_token();
3051 if (n.asInput() != "\"" && n.asInput() != "~")
3056 // Strip quotes. This is a bit complicated (see latex_path()).
3057 string full = os.str();
3058 if (!full.empty() && full[0] == '"') {
3059 string base = removeExtension(full);
3060 string ext = getExtension(full);
3061 if (!base.empty() && base[base.length()-1] == '"')
3064 return addExtension(trim(base, "\""), ext);
3065 if (full[full.length()-1] == '"')
3068 return trim(full, "\"");
3074 /// Convert \p name from TeX convention (relative to master file) to LyX
3075 /// convention (relative to .lyx file) if it is relative
3076 void fix_child_filename(string & name)
3078 string const absMasterTeX = getMasterFilePath(true);
3079 bool const isabs = FileName::isAbsolute(name);
3080 // convert from "relative to .tex master" to absolute original path
3082 name = makeAbsPath(name, absMasterTeX).absFileName();
3083 bool copyfile = copyFiles();
3084 string const absParentLyX = getParentFilePath(false);
3087 // convert from absolute original path to "relative to master file"
3088 string const rel = to_utf8(makeRelPath(from_utf8(name),
3089 from_utf8(absMasterTeX)));
3090 // re-interpret "relative to .tex file" as "relative to .lyx file"
3091 // (is different if the master .lyx file resides in a
3092 // different path than the master .tex file)
3093 string const absMasterLyX = getMasterFilePath(false);
3094 abs = makeAbsPath(rel, absMasterLyX).absFileName();
3095 // Do not copy if the new path is impossible to create. Example:
3096 // absMasterTeX = "/foo/bar/"
3097 // absMasterLyX = "/bar/"
3098 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
3099 if (contains(name, "/../"))
3106 // convert from absolute original path to
3107 // "relative to .lyx file"
3108 name = to_utf8(makeRelPath(from_utf8(abs),
3109 from_utf8(absParentLyX)));
3113 // convert from absolute original path to "relative to .lyx file"
3114 name = to_utf8(makeRelPath(from_utf8(name),
3115 from_utf8(absParentLyX)));
3120 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
3121 Context & context, string const & rdelim, string const & rdelimesc)
3123 Layout const * newlayout = 0;
3124 InsetLayout const * newinsetlayout = 0;
3125 char const * const * where = 0;
3126 // Store the latest bibliographystyle, addcontentslineContent and
3127 // nocite{*} option (needed for bibtex inset)
3129 string contentslineContent;
3130 // Some classes provide a \bibliographystyle, so do not output
3131 // any if none is explicitly set.
3132 string bibliographystyle;
3133 bool const use_natbib = isProvided("natbib");
3134 bool const use_jurabib = isProvided("jurabib");
3135 bool const use_biblatex = isProvided("biblatex")
3136 && preamble.citeEngine() != "biblatex-natbib";
3137 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
3138 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
3139 need_commentbib = use_biblatex || use_biblatex_natbib;
3142 // it is impossible to determine the correct encoding for non-CJK Japanese.
3143 // Therefore write a note at the beginning of the document
3144 if (is_nonCJKJapanese) {
3145 context.check_layout(os);
3146 begin_inset(os, "Note Note\n");
3147 os << "status open\n\\begin_layout Plain Layout\n"
3148 << "\\series bold\n"
3149 << "Important information:\n"
3150 << "\\end_layout\n\n"
3151 << "\\begin_layout Plain Layout\n"
3152 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
3153 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
3154 << " The iconv encoding " << p.getEncoding() << " was used.\n"
3155 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
3156 << " and specify the encoding using the -e command-line switch.\n"
3157 << " In addition, you might want to double check that the desired output encoding\n"
3158 << " is correctly selected in Document > Settings > Language.\n"
3159 << "\\end_layout\n";
3161 is_nonCJKJapanese = false;
3164 bool have_cycled = false;
3166 // Leave here only after at least one cycle
3167 if (have_cycled && flags & FLAG_LEAVE) {
3168 flags &= ~FLAG_LEAVE;
3172 Token const & t = p.get_token();
3174 debugToken(cerr, t, flags);
3177 if (context.in_list_preamble
3178 && p.next_token().cs() == context.layout->itemcommand()) {
3179 // We are parsing a list preamble. End before first \item.
3180 flags |= FLAG_LEAVE;
3181 context.in_list_preamble = false;
3184 if (flags & FLAG_ITEM) {
3185 if (t.cat() == catSpace)
3188 flags &= ~FLAG_ITEM;
3189 if (t.cat() == catBegin) {
3190 // skip the brace and collect everything to the next matching
3192 flags |= FLAG_BRACE_LAST;
3196 // handle only this single token, leave the loop if done
3197 flags |= FLAG_LEAVE;
3200 if (t.cat() != catEscape && t.character() == ']' &&
3201 (flags & FLAG_BRACK_LAST))
3203 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
3205 string tok = t.asInput();
3206 // we only support delimiters with max 2 chars for now.
3207 if (rdelim.size() > 1)
3208 tok += p.next_token().asInput();
3209 if (t.cat() != catEscape && !rdelim.empty()
3210 && tok == rdelim && (flags & FLAG_RDELIM)
3211 && (rdelimesc.empty() || p.prev_token().asInput() != rdelimesc)) {
3212 if (rdelim.size() > 1)
3213 p.get_token(); // eat rdelim
3217 // If there is anything between \end{env} and \begin{env} we
3218 // don't need to output a separator.
3219 if (t.cat() != catSpace && t.cat() != catNewline &&
3220 t.asInput() != "\\begin")
3227 bool const starred = p.next_token().asInput() == "*";
3228 string const starredname(starred ? (t.cs() + '*') : t.cs());
3229 if (t.cat() == catMath) {
3230 // we are inside some text mode thingy, so opening new math is allowed
3231 context.check_layout(os);
3232 begin_inset(os, "Formula ");
3233 Token const & n = p.get_token();
3234 bool const display(n.cat() == catMath && outer);
3236 // TeX's $$...$$ syntax for displayed math
3238 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3240 p.get_token(); // skip the second '$' token
3242 // simple $...$ stuff
3245 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3250 // Prevent the conversion of a line break to a
3251 // space (bug 7668). This does not change the
3252 // output, but looks ugly in LyX.
3253 eat_whitespace(p, os, context, false);
3258 if (t.cat() == catSuper || t.cat() == catSub) {
3259 cerr << "catcode " << t << " illegal in text mode\n";
3263 // Basic support for quotes. We try to disambiguate
3264 // quotes from the context (e.g., a left english quote is
3265 // the same as a right german quote...).
3266 // Try to make a smart guess about the side
3267 Token const prev = p.prev_token();
3268 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3269 && prev.character() != '\n' && prev.character() != '~');
3270 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3271 context.check_layout(os);
3272 begin_inset(os, "Quotes ");
3273 os << guessQuoteStyle("eld", opening);
3279 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3280 context.check_layout(os);
3281 begin_inset(os, "Quotes ");
3282 os << guessQuoteStyle("erd", opening);
3289 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3290 context.check_layout(os);
3291 begin_inset(os, "Quotes ");
3292 os << guessQuoteStyle("ald", opening);
3299 if (t.asInput() == "<"
3300 && p.next_token().asInput() == "<") {
3301 bool has_chunk = false;
3305 has_chunk = parse_chunk(p, os, context);
3311 context.check_layout(os);
3312 begin_inset(os, "Quotes ");
3313 os << guessQuoteStyle("ard", opening);
3321 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3322 check_space(p, os, context);
3326 // babel shorthands (also used by polyglossia)
3327 // Since these can have different meanings for different languages
3328 // we import them as ERT (but they must be put in ERT to get output
3330 if (t.asInput() == "\"") {
3332 // These are known pairs. We put them together in
3333 // one ERT inset. In other cases (such as "a), only
3334 // the quotation mark is ERTed.
3335 if (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 || p.next_token().asInput() == "`"
3344 || p.next_token().asInput() == "<"
3345 || p.next_token().asInput() == ">") {
3346 s += p.next_token().asInput();
3349 output_ert_inset(os, s, context);
3353 if (t.character() == '[' && noweb_mode &&
3354 p.next_token().character() == '[') {
3355 // These can contain underscores
3357 string const s = p.getFullOpt() + ']';
3358 if (p.next_token().character() == ']')
3361 cerr << "Warning: Inserting missing ']' in '"
3362 << s << "'." << endl;
3363 output_ert_inset(os, s, context);
3367 if (t.cat() == catLetter) {
3368 context.check_layout(os);
3373 if (t.cat() == catOther ||
3374 t.cat() == catAlign ||
3375 t.cat() == catParameter) {
3376 context.check_layout(os);
3377 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3378 context.merging_hyphens_allowed &&
3379 context.font.family != "ttfamily" &&
3380 !context.layout->pass_thru) {
3381 if (p.next_next_token().asInput() == "-") {
3383 os << to_utf8(docstring(1, 0x2014));
3387 os << to_utf8(docstring(1, 0x2013));
3390 // This translates "&" to "\\&" which may be wrong...
3395 if (p.isParagraph()) {
3396 // In minted floating listings we will collect
3397 // everything into the caption, where multiple
3398 // paragraphs are forbidden.
3399 if (minted_float.empty()) {
3400 if (context.new_layout_allowed)
3401 context.new_paragraph(os);
3403 output_ert_inset(os, "\\par ", context);
3406 eat_whitespace(p, os, context, true);
3410 if (t.cat() == catActive) {
3411 context.check_layout(os);
3412 if (t.character() == '~') {
3413 if (context.layout->free_spacing)
3416 begin_inset(os, "space ~\n");
3424 if (t.cat() == catBegin) {
3425 Token const next = p.next_token();
3426 Token const end = p.next_next_token();
3427 if (next.cat() == catEnd) {
3429 Token const prev = p.prev_token();
3431 if (p.next_token().character() == '`')
3432 ; // ignore it in {}``
3434 output_ert_inset(os, "{}", context);
3435 } else if (next.cat() == catEscape &&
3436 is_known(next.cs(), known_quotes) &&
3437 end.cat() == catEnd) {
3438 // Something like {\textquoteright} (e.g.
3439 // from writer2latex). We may skip the
3440 // braces here for better readability.
3441 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3443 } else if (p.next_token().asInput() == "\\ascii") {
3444 // handle the \ascii characters
3445 // (the case without braces is handled later)
3446 // the code is "{\ascii\xxx}"
3447 p.get_token(); // eat \ascii
3448 string name2 = p.get_token().asInput();
3449 p.get_token(); // eat the final '}'
3450 string const name = "{\\ascii" + name2 + "}";
3454 // get the character from unicodesymbols
3455 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3456 Encodings::TEXT_CMD, termination, rem, &req);
3458 context.check_layout(os);
3461 output_ert_inset(os,
3462 to_utf8(rem), context);
3463 for (set<string>::const_iterator it = req.begin();
3464 it != req.end(); ++it)
3465 preamble.registerAutomaticallyLoadedPackage(*it);
3467 // we did not find a non-ert version
3468 output_ert_inset(os, name, context);
3470 context.check_layout(os);
3471 // special handling of font attribute changes
3472 Token const prev = p.prev_token();
3473 TeXFont const oldFont = context.font;
3474 if (next.character() == '[' ||
3475 next.character() == ']' ||
3476 next.character() == '*') {
3478 if (p.next_token().cat() == catEnd) {
3483 output_ert_inset(os, "{", context);
3484 parse_text_snippet(p, os,
3487 output_ert_inset(os, "}", context);
3489 } else if (! context.new_layout_allowed) {
3490 output_ert_inset(os, "{", context);
3491 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3493 output_ert_inset(os, "}", context);
3494 } else if (is_known(next.cs(), known_sizes)) {
3495 // next will change the size, so we must
3497 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3499 if (!context.atParagraphStart())
3501 << context.font.size << "\n";
3502 } else if (is_known(next.cs(), known_font_families)) {
3503 // next will change the font family, so we
3504 // must reset it here
3505 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3507 if (!context.atParagraphStart())
3509 << context.font.family << "\n";
3510 } else if (is_known(next.cs(), known_font_series)) {
3511 // next will change the font series, so we
3512 // must reset it here
3513 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3515 if (!context.atParagraphStart())
3517 << context.font.series << "\n";
3518 } else if (is_known(next.cs(), known_font_shapes)) {
3519 // next will change the font shape, so we
3520 // must reset it here
3521 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3523 if (!context.atParagraphStart())
3525 << context.font.shape << "\n";
3526 } else if (is_known(next.cs(), known_old_font_families) ||
3527 is_known(next.cs(), known_old_font_series) ||
3528 is_known(next.cs(), known_old_font_shapes)) {
3529 // next will change the font family, series
3530 // and shape, so we must reset it here
3531 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3533 if (!context.atParagraphStart())
3535 << context.font.family
3537 << context.font.series
3539 << context.font.shape << "\n";
3541 output_ert_inset(os, "{", context);
3542 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3544 output_ert_inset(os, "}", context);
3550 if (t.cat() == catEnd) {
3551 if (flags & FLAG_BRACE_LAST) {
3554 cerr << "stray '}' in text\n";
3555 output_ert_inset(os, "}", context);
3559 if (t.cat() == catComment) {
3560 parse_comment(p, os, t, context);
3565 // control sequences
3568 if (t.cs() == "(" || t.cs() == "[") {
3569 bool const simple = t.cs() == "(";
3570 context.check_layout(os);
3571 begin_inset(os, "Formula");
3572 os << " \\" << t.cs();
3573 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3574 os << '\\' << (simple ? ')' : ']');
3577 // Prevent the conversion of a line break to a
3578 // space (bug 7668). This does not change the
3579 // output, but looks ugly in LyX.
3580 eat_whitespace(p, os, context, false);
3585 if (t.cs() == "begin") {
3586 parse_environment(p, os, outer, last_env,
3591 if (t.cs() == "end") {
3592 if (flags & FLAG_END) {
3593 // eat environment name
3594 string const name = p.getArg('{', '}');
3595 if (name != active_environment())
3596 cerr << "\\end{" + name + "} does not match \\begin{"
3597 + active_environment() + "}\n";
3600 p.error("found 'end' unexpectedly");
3604 // "item" by default, but could be something else
3605 if (t.cs() == context.layout->itemcommand()) {
3607 if (context.layout->labeltype == LABEL_MANUAL) {
3608 // FIXME: This swallows comments, but we cannot use
3609 // eat_whitespace() since we must not output
3610 // anything before the item.
3611 p.skip_spaces(true);
3612 s = p.verbatimOption();
3614 p.skip_spaces(false);
3616 context.check_layout(os);
3617 if (context.has_item) {
3618 // An item in an unknown list-like environment
3619 // FIXME: Do this in check_layout()!
3620 context.has_item = false;
3621 string item = "\\" + context.layout->itemcommand();
3624 output_ert_inset(os, item, context);
3626 if (context.layout->labeltype != LABEL_MANUAL)
3627 output_arguments(os, p, outer, false, "item", context,
3628 context.layout->itemargs());
3629 if (!context.list_preamble.empty()) {
3630 // We have a list preamble. Output it here.
3631 begin_inset(os, "Argument listpreamble:1");
3632 os << "\nstatus collapsed\n\n"
3633 << "\\begin_layout Plain Layout\n\n"
3634 << rtrim(context.list_preamble)
3635 << "\n\\end_layout";
3637 context.list_preamble.clear();
3639 if (!context.list_extra_stuff.empty()) {
3640 os << context.list_extra_stuff;
3641 context.list_extra_stuff.clear();
3643 else if (!s.empty()) {
3644 // LyX adds braces around the argument,
3645 // so we need to remove them here.
3646 if (s.size() > 2 && s[0] == '{' &&
3647 s[s.size()-1] == '}')
3648 s = s.substr(1, s.size()-2);
3649 // If the argument contains a space we
3650 // must put it into ERT: Otherwise LyX
3651 // would misinterpret the space as
3652 // item delimiter (bug 7663)
3653 if (contains(s, ' ')) {
3654 output_ert_inset(os, s, context);
3657 os << parse_text_snippet(p2,
3658 FLAG_BRACK_LAST, outer, context);
3660 // The space is needed to separate the
3661 // item from the rest of the sentence.
3663 eat_whitespace(p, os, context, false);
3668 if (t.cs() == "bibitem") {
3670 context.check_layout(os);
3671 eat_whitespace(p, os, context, false);
3672 string label = p.verbatimOption();
3673 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3674 bool const literal = !lbl.first;
3675 label = literal ? subst(label, "\n", " ") : lbl.second;
3676 string lit = literal ? "\"true\"" : "\"false\"";
3677 string key = convert_literate_command_inset_arg(p.verbatim_item());
3678 begin_command_inset(os, "bibitem", "bibitem");
3679 os << "label \"" << label << "\"\n"
3680 << "key \"" << key << "\"\n"
3681 << "literal " << lit << "\n";
3687 // catch the case of \def\inputGnumericTable
3689 if (t.cs() == "def") {
3690 Token second = p.next_token();
3691 if (second.cs() == "inputGnumericTable") {
3695 Token third = p.get_token();
3697 if (third.cs() == "input") {
3701 string name = normalize_filename(p.verbatim_item());
3702 string const path = getMasterFilePath(true);
3703 // We want to preserve relative / absolute filenames,
3704 // therefore path is only used for testing
3705 // The file extension is in every case ".tex".
3706 // So we need to remove this extension and check for
3707 // the original one.
3708 name = removeExtension(name);
3709 if (!makeAbsPath(name, path).exists()) {
3710 char const * const Gnumeric_formats[] = {"gnumeric",
3712 string const Gnumeric_name =
3713 find_file(name, path, Gnumeric_formats);
3714 if (!Gnumeric_name.empty())
3715 name = Gnumeric_name;
3717 FileName const absname = makeAbsPath(name, path);
3718 if (absname.exists()) {
3719 fix_child_filename(name);
3720 copy_file(absname, name);
3722 cerr << "Warning: Could not find file '"
3723 << name << "'." << endl;
3724 context.check_layout(os);
3725 begin_inset(os, "External\n\ttemplate ");
3726 os << "GnumericSpreadsheet\n\tfilename "
3729 context.check_layout(os);
3731 // register the packages that are automatically loaded
3732 // by the Gnumeric template
3733 registerExternalTemplatePackages("GnumericSpreadsheet");
3738 parse_macro(p, os, context);
3742 if (t.cs() == "noindent") {
3744 context.add_par_extra_stuff("\\noindent\n");
3748 if (t.cs() == "appendix" && !context.in_list_preamble) {
3749 context.add_par_extra_stuff("\\start_of_appendix\n");
3750 // We need to start a new paragraph. Otherwise the
3751 // appendix in 'bla\appendix\chapter{' would start
3753 context.new_paragraph(os);
3754 // We need to make sure that the paragraph is
3755 // generated even if it is empty. Otherwise the
3756 // appendix in '\par\appendix\par\chapter{' would
3758 context.check_layout(os);
3759 // FIXME: This is a hack to prevent paragraph
3760 // deletion if it is empty. Handle this better!
3761 output_comment(p, os,
3762 "dummy comment inserted by tex2lyx to "
3763 "ensure that this paragraph is not empty",
3765 // Both measures above may generate an additional
3766 // empty paragraph, but that does not hurt, because
3767 // whitespace does not matter here.
3768 eat_whitespace(p, os, context, true);
3772 // Must catch empty dates before findLayout is called below
3773 if (t.cs() == "date") {
3774 eat_whitespace(p, os, context, false);
3776 string const date = p.verbatim_item();
3779 preamble.suppressDate(true);
3782 preamble.suppressDate(false);
3783 if (context.new_layout_allowed &&
3784 (newlayout = findLayout(context.textclass,
3787 output_command_layout(os, p, outer,
3788 context, newlayout);
3789 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3790 if (!preamble.titleLayoutFound())
3791 preamble.titleLayoutFound(newlayout->intitle);
3792 set<string> const & req = newlayout->required();
3793 set<string>::const_iterator it = req.begin();
3794 set<string>::const_iterator en = req.end();
3795 for (; it != en; ++it)
3796 preamble.registerAutomaticallyLoadedPackage(*it);
3798 output_ert_inset(os,
3799 "\\date{" + p.verbatim_item() + '}',
3805 // Before we look for the layout name with star and alone below, we check the layouts including
3806 // the LateXParam, which might be one or several options or a star.
3807 // The single '=' is meant here.
3808 if (context.new_layout_allowed &&
3809 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3810 // store the latexparam here. This is eaten in output_command_layout
3811 context.latexparam = newlayout->latexparam();
3813 output_command_layout(os, p, outer, context, newlayout);
3814 context.latexparam.clear();
3816 if (!preamble.titleLayoutFound())
3817 preamble.titleLayoutFound(newlayout->intitle);
3818 set<string> const & req = newlayout->required();
3819 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3820 preamble.registerAutomaticallyLoadedPackage(*it);
3824 // Starred section headings
3825 // Must attempt to parse "Section*" before "Section".
3826 if ((p.next_token().asInput() == "*") &&
3827 context.new_layout_allowed &&
3828 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3831 output_command_layout(os, p, outer, context, newlayout);
3833 if (!preamble.titleLayoutFound())
3834 preamble.titleLayoutFound(newlayout->intitle);
3835 set<string> const & req = newlayout->required();
3836 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3837 preamble.registerAutomaticallyLoadedPackage(*it);
3841 // Section headings and the like
3842 if (context.new_layout_allowed &&
3843 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3845 output_command_layout(os, p, outer, context, newlayout);
3847 if (!preamble.titleLayoutFound())
3848 preamble.titleLayoutFound(newlayout->intitle);
3849 set<string> const & req = newlayout->required();
3850 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3851 preamble.registerAutomaticallyLoadedPackage(*it);
3855 if (t.cs() == "subfloat") {
3856 // the syntax is \subfloat[list entry][sub caption]{content}
3857 // if it is a table of figure depends on the surrounding float
3859 // do nothing if there is no outer float
3860 if (!float_type.empty()) {
3861 context.check_layout(os);
3863 begin_inset(os, "Float " + float_type + "\n");
3865 << "\nsideways false"
3866 << "\nstatus collapsed\n\n";
3869 bool has_caption = false;
3870 if (p.next_token().cat() != catEscape &&
3871 p.next_token().character() == '[') {
3872 p.get_token(); // eat '['
3873 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3876 // In case we have two optional args, the second is the caption.
3877 if (p.next_token().cat() != catEscape &&
3878 p.next_token().character() == '[') {
3879 p.get_token(); // eat '['
3880 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3883 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3884 // the caption comes always as the last
3886 // we must make sure that the caption gets a \begin_layout
3887 os << "\n\\begin_layout Plain Layout";
3889 begin_inset(os, "Caption Standard\n");
3890 Context newcontext(true, context.textclass,
3891 0, 0, context.font);
3892 newcontext.check_layout(os);
3893 os << caption << "\n";
3894 newcontext.check_end_layout(os);
3897 // close the layout we opened
3898 os << "\n\\end_layout";
3903 // if the float type is not supported or there is no surrounding float
3908 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3910 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3912 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3913 + "{" + p.verbatim_item() + '}', context);
3918 if (t.cs() == "xymatrix") {
3919 // we must open a new math because LyX's xy support is in math
3920 context.check_layout(os);
3921 begin_inset(os, "Formula ");
3923 os << "\\" << t.cs() << '{';
3924 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3927 preamble.registerAutomaticallyLoadedPackage("xy");
3931 if (t.cs() == "includegraphics") {
3932 bool const clip = p.next_token().asInput() == "*";
3935 string const arg = p.getArg('[', ']');
3936 map<string, string> opts;
3937 vector<string> keys;
3938 split_map(arg, opts, keys);
3940 opts["clip"] = string();
3941 string name = normalize_filename(p.verbatim_item());
3943 string const path = getMasterFilePath(true);
3944 // We want to preserve relative / absolute filenames,
3945 // therefore path is only used for testing
3946 if (!makeAbsPath(name, path).exists()) {
3947 // The file extension is probably missing.
3948 // Now try to find it out.
3949 string const dvips_name =
3950 find_file(name, path,
3951 known_dvips_graphics_formats);
3952 string const pdftex_name =
3953 find_file(name, path,
3954 known_pdftex_graphics_formats);
3955 if (!dvips_name.empty()) {
3956 if (!pdftex_name.empty()) {
3957 cerr << "This file contains the "
3959 "\"\\includegraphics{"
3961 "However, files\n\""
3962 << dvips_name << "\" and\n\""
3963 << pdftex_name << "\"\n"
3964 "both exist, so I had to make a "
3965 "choice and took the first one.\n"
3966 "Please move the unwanted one "
3967 "someplace else and try again\n"
3968 "if my choice was wrong."
3972 } else if (!pdftex_name.empty()) {
3978 FileName const absname = makeAbsPath(name, path);
3979 if (absname.exists()) {
3980 fix_child_filename(name);
3981 copy_file(absname, name);
3983 cerr << "Warning: Could not find graphics file '"
3984 << name << "'." << endl;
3986 context.check_layout(os);
3987 begin_inset(os, "Graphics ");
3988 os << "\n\tfilename " << name << '\n';
3989 if (opts.find("width") != opts.end())
3991 << translate_len(opts["width"]) << '\n';
3992 if (opts.find("totalheight") != opts.end())
3994 << translate_len(opts["totalheight"]) << '\n';
3995 if (opts.find("scale") != opts.end()) {
3996 istringstream iss(opts["scale"]);
4000 os << "\tscale " << val << '\n';
4002 if (opts.find("angle") != opts.end()) {
4003 os << "\trotateAngle "
4004 << opts["angle"] << '\n';
4005 vector<string>::const_iterator a =
4006 find(keys.begin(), keys.end(), "angle");
4007 vector<string>::const_iterator s =
4008 find(keys.begin(), keys.end(), "width");
4009 if (s == keys.end())
4010 s = find(keys.begin(), keys.end(), "totalheight");
4011 if (s == keys.end())
4012 s = find(keys.begin(), keys.end(), "scale");
4013 if (s != keys.end() && distance(s, a) > 0)
4014 os << "\tscaleBeforeRotation\n";
4016 if (opts.find("origin") != opts.end()) {
4018 string const opt = opts["origin"];
4019 if (opt.find('l') != string::npos) ss << "left";
4020 if (opt.find('r') != string::npos) ss << "right";
4021 if (opt.find('c') != string::npos) ss << "center";
4022 if (opt.find('t') != string::npos) ss << "Top";
4023 if (opt.find('b') != string::npos) ss << "Bottom";
4024 if (opt.find('B') != string::npos) ss << "Baseline";
4025 if (!ss.str().empty())
4026 os << "\trotateOrigin " << ss.str() << '\n';
4028 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
4030 if (opts.find("keepaspectratio") != opts.end())
4031 os << "\tkeepAspectRatio\n";
4032 if (opts.find("clip") != opts.end())
4034 if (opts.find("draft") != opts.end())
4036 if (opts.find("bb") != opts.end())
4037 os << "\tBoundingBox "
4038 << opts["bb"] << '\n';
4039 int numberOfbbOptions = 0;
4040 if (opts.find("bbllx") != opts.end())
4041 numberOfbbOptions++;
4042 if (opts.find("bblly") != opts.end())
4043 numberOfbbOptions++;
4044 if (opts.find("bburx") != opts.end())
4045 numberOfbbOptions++;
4046 if (opts.find("bbury") != opts.end())
4047 numberOfbbOptions++;
4048 if (numberOfbbOptions == 4)
4049 os << "\tBoundingBox "
4050 << opts["bbllx"] << " " << opts["bblly"] << " "
4051 << opts["bburx"] << " " << opts["bbury"] << '\n';
4052 else if (numberOfbbOptions > 0)
4053 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
4054 numberOfbbOptions = 0;
4055 if (opts.find("natwidth") != opts.end())
4056 numberOfbbOptions++;
4057 if (opts.find("natheight") != opts.end())
4058 numberOfbbOptions++;
4059 if (numberOfbbOptions == 2)
4060 os << "\tBoundingBox 0bp 0bp "
4061 << opts["natwidth"] << " " << opts["natheight"] << '\n';
4062 else if (numberOfbbOptions > 0)
4063 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
4064 ostringstream special;
4065 if (opts.find("hiresbb") != opts.end())
4066 special << "hiresbb,";
4067 if (opts.find("trim") != opts.end())
4069 if (opts.find("viewport") != opts.end())
4070 special << "viewport=" << opts["viewport"] << ',';
4071 if (opts.find("height") != opts.end())
4072 special << "height=" << opts["height"] << ',';
4073 if (opts.find("type") != opts.end())
4074 special << "type=" << opts["type"] << ',';
4075 if (opts.find("ext") != opts.end())
4076 special << "ext=" << opts["ext"] << ',';
4077 if (opts.find("read") != opts.end())
4078 special << "read=" << opts["read"] << ',';
4079 if (opts.find("command") != opts.end())
4080 special << "command=" << opts["command"] << ',';
4081 string s_special = special.str();
4082 if (!s_special.empty()) {
4083 // We had special arguments. Remove the trailing ','.
4084 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
4086 // TODO: Handle the unknown settings better.
4087 // Warn about invalid options.
4088 // Check whether some option was given twice.
4090 preamble.registerAutomaticallyLoadedPackage("graphicx");
4094 if (t.cs() == "footnote" ||
4095 (t.cs() == "thanks" && context.layout->intitle)) {
4097 context.check_layout(os);
4098 begin_inset(os, "Foot\n");
4099 os << "status collapsed\n\n";
4100 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4105 if (t.cs() == "marginpar") {
4107 context.check_layout(os);
4108 begin_inset(os, "Marginal\n");
4109 os << "status collapsed\n\n";
4110 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4115 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
4116 bool const use_minted = t.cs() == "mintinline";
4118 parse_listings(p, os, context, true, use_minted);
4122 if (t.cs() == "ensuremath") {
4124 context.check_layout(os);
4125 string const s = p.verbatim_item();
4126 //FIXME: this never triggers in UTF8
4127 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
4130 output_ert_inset(os, "\\ensuremath{" + s + "}",
4135 else if (t.cs() == "makeindex"
4136 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
4137 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
4138 if (preamble.titleLayoutFound()) {
4140 skip_spaces_braces(p);
4142 output_ert_inset(os, t.asInput(), context);
4146 if (t.cs() == "tableofcontents"
4147 || t.cs() == "lstlistoflistings"
4148 || t.cs() == "listoflistings") {
4149 string name = t.cs();
4150 if (preamble.minted() && name == "listoflistings")
4151 name.insert(0, "lst");
4152 context.check_layout(os);
4153 begin_command_inset(os, "toc", name);
4155 skip_spaces_braces(p);
4156 if (name == "lstlistoflistings") {
4157 if (preamble.minted())
4158 preamble.registerAutomaticallyLoadedPackage("minted");
4160 preamble.registerAutomaticallyLoadedPackage("listings");
4165 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
4166 context.check_layout(os);
4167 if (t.cs() == "listoffigures")
4168 begin_inset(os, "FloatList figure\n");
4170 begin_inset(os, "FloatList table\n");
4172 skip_spaces_braces(p);
4176 if (t.cs() == "listof") {
4177 p.skip_spaces(true);
4178 string const name = p.verbatim_item();
4179 if (context.textclass.floats().typeExist(name)) {
4180 context.check_layout(os);
4181 begin_inset(os, "FloatList ");
4184 p.verbatim_item(); // swallow second arg
4186 output_ert_inset(os, "\\listof{" + name + "}", context);
4190 if (t.cs() == "theendnotes"
4191 || (t.cs() == "printendnotes"
4192 && p.next_token().asInput() != "*"
4194 context.check_layout(os);
4195 begin_inset(os, "FloatList endnote\n");
4197 skip_spaces_braces(p);
4201 if ((where = is_known(t.cs(), known_text_font_families))) {
4202 parse_text_attributes(p, os, FLAG_ITEM, outer,
4203 context, "\\family", context.font.family,
4204 known_coded_font_families[where - known_text_font_families]);
4208 // beamer has a \textbf<overlay>{} inset
4209 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
4210 parse_text_attributes(p, os, FLAG_ITEM, outer,
4211 context, "\\series", context.font.series,
4212 known_coded_font_series[where - known_text_font_series]);
4216 // beamer has a \textit<overlay>{} inset
4217 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4218 parse_text_attributes(p, os, FLAG_ITEM, outer,
4219 context, "\\shape", context.font.shape,
4220 known_coded_font_shapes[where - known_text_font_shapes]);
4224 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4225 context.check_layout(os);
4226 TeXFont oldFont = context.font;
4227 context.font.init();
4228 context.font.size = oldFont.size;
4229 os << "\n\\family " << context.font.family << "\n";
4230 os << "\n\\series " << context.font.series << "\n";
4231 os << "\n\\shape " << context.font.shape << "\n";
4232 if (t.cs() == "textnormal") {
4233 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4234 output_font_change(os, context.font, oldFont);
4235 context.font = oldFont;
4237 eat_whitespace(p, os, context, false);
4241 if (t.cs() == "textcolor") {
4242 // scheme is \textcolor{color name}{text}
4243 string const color = p.verbatim_item();
4244 // we support the predefined colors of the color and the xcolor package
4245 if (color == "black" || color == "blue" || color == "cyan"
4246 || color == "green" || color == "magenta" || color == "red"
4247 || color == "white" || color == "yellow") {
4248 context.check_layout(os);
4249 os << "\n\\color " << color << "\n";
4250 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4251 context.check_layout(os);
4252 os << "\n\\color inherit\n";
4253 preamble.registerAutomaticallyLoadedPackage("color");
4254 } else if (color == "brown" || color == "darkgray" || color == "gray"
4255 || color == "lightgray" || color == "lime" || color == "olive"
4256 || color == "orange" || color == "pink" || color == "purple"
4257 || color == "teal" || color == "violet") {
4258 context.check_layout(os);
4259 os << "\n\\color " << color << "\n";
4260 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4261 context.check_layout(os);
4262 os << "\n\\color inherit\n";
4263 preamble.registerAutomaticallyLoadedPackage("xcolor");
4265 // for custom defined colors
4266 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4270 if (t.cs() == "underbar" || t.cs() == "uline") {
4271 // \underbar is not 100% correct (LyX outputs \uline
4272 // of ulem.sty). The difference is that \ulem allows
4273 // line breaks, and \underbar does not.
4274 // Do NOT handle \underline.
4275 // \underbar cuts through y, g, q, p etc.,
4276 // \underline does not.
4277 context.check_layout(os);
4278 os << "\n\\bar under\n";
4279 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4280 context.check_layout(os);
4281 os << "\n\\bar default\n";
4282 preamble.registerAutomaticallyLoadedPackage("ulem");
4286 if (t.cs() == "sout") {
4287 context.check_layout(os);
4288 os << "\n\\strikeout on\n";
4289 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4290 context.check_layout(os);
4291 os << "\n\\strikeout default\n";
4292 preamble.registerAutomaticallyLoadedPackage("ulem");
4296 // beamer has an \emph<overlay>{} inset
4297 if ((t.cs() == "uuline" || t.cs() == "uwave"
4298 || t.cs() == "emph" || t.cs() == "noun"
4299 || t.cs() == "xout") && !p.hasOpt("<")) {
4300 context.check_layout(os);
4301 os << "\n\\" << t.cs() << " on\n";
4302 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4303 context.check_layout(os);
4304 os << "\n\\" << t.cs() << " default\n";
4305 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4306 preamble.registerAutomaticallyLoadedPackage("ulem");
4310 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4311 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4312 context.check_layout(os);
4315 initials = p.getArg('[', ']');
4317 string name = p.getArg('{', '}');
4318 string localtime = p.getArg('{', '}');
4319 preamble.registerAuthor(name, initials);
4320 Author const & author = preamble.getAuthor(name);
4321 // from_asctime_utc() will fail if LyX decides to output the
4322 // time in the text language.
4323 time_t ptime = from_asctime_utc(localtime);
4324 if (ptime == static_cast<time_t>(-1)) {
4325 cerr << "Warning: Could not parse time `" << localtime
4326 << "´ for change tracking, using current time instead.\n";
4327 ptime = current_time();
4329 if (t.cs() == "lyxadded")
4330 os << "\n\\change_inserted ";
4332 os << "\n\\change_deleted ";
4333 os << author.bufferId() << ' ' << ptime << '\n';
4334 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4335 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4336 LaTeXPackages::isAvailable("xcolor");
4337 // No need to test for luatex, since luatex comes in
4338 // two flavours (dvi and pdf), like latex, and those
4339 // are detected by pdflatex.
4340 if (pdflatex || xetex) {
4342 preamble.registerAutomaticallyLoadedPackage("ulem");
4343 preamble.registerAutomaticallyLoadedPackage("xcolor");
4344 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4348 preamble.registerAutomaticallyLoadedPackage("ulem");
4349 preamble.registerAutomaticallyLoadedPackage("xcolor");
4355 if (t.cs() == "textipa") {
4356 context.check_layout(os);
4357 begin_inset(os, "IPA\n");
4358 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4359 context.merging_hyphens_allowed = false;
4360 set<string> pass_thru_cmds = context.pass_thru_cmds;
4361 // These commands have special meanings in IPA
4362 context.pass_thru_cmds.insert("!");
4363 context.pass_thru_cmds.insert(";");
4364 context.pass_thru_cmds.insert(":");
4365 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4366 context.pass_thru_cmds = pass_thru_cmds;
4367 context.merging_hyphens_allowed = merging_hyphens_allowed;
4369 preamble.registerAutomaticallyLoadedPackage("tipa");
4370 preamble.registerAutomaticallyLoadedPackage("tipx");
4374 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4375 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4376 context.check_layout(os);
4380 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4381 begin_inset(os, "IPADeco " + type + "\n");
4382 os << "status open\n";
4383 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4389 if (t.cs() == "textvertline") {
4390 // FIXME: This is not correct, \textvertline is higher than |
4396 if (t.cs() == "tone" ) {
4397 context.check_layout(os);
4398 // register the tone package
4399 preamble.registerAutomaticallyLoadedPackage("tone");
4400 string content = trimSpaceAndEol(p.verbatim_item());
4401 string command = t.asInput() + "{" + content + "}";
4402 // some tones can be detected by unicodesymbols, some need special code
4403 if (is_known(content, known_tones)) {
4404 os << "\\IPAChar " << command << "\n";
4407 // try to see whether the string is in unicodesymbols
4411 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4412 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4413 termination, rem, &req);
4417 output_ert_inset(os, to_utf8(rem), context);
4418 for (set<string>::const_iterator it = req.begin();
4419 it != req.end(); ++it)
4420 preamble.registerAutomaticallyLoadedPackage(*it);
4422 // we did not find a non-ert version
4423 output_ert_inset(os, command, context);
4427 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4428 t.cs() == "vphantom") {
4429 context.check_layout(os);
4430 if (t.cs() == "phantom")
4431 begin_inset(os, "Phantom Phantom\n");
4432 if (t.cs() == "hphantom")
4433 begin_inset(os, "Phantom HPhantom\n");
4434 if (t.cs() == "vphantom")
4435 begin_inset(os, "Phantom VPhantom\n");
4436 os << "status open\n";
4437 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4443 if (t.cs() == "href") {
4444 context.check_layout(os);
4445 string target = convert_literate_command_inset_arg(p.verbatim_item());
4446 string name = p.verbatim_item();
4447 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4448 bool const literal = !nm.first;
4449 name = literal ? subst(name, "\n", " ") : nm.second;
4450 string lit = literal ? "\"true\"" : "\"false\"";
4452 size_t i = target.find(':');
4453 if (i != string::npos) {
4454 type = target.substr(0, i + 1);
4455 if (type == "mailto:" || type == "file:")
4456 target = target.substr(i + 1);
4457 // handle the case that name is equal to target, except of "http(s)://"
4458 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4461 begin_command_inset(os, "href", "href");
4463 os << "name \"" << name << "\"\n";
4464 os << "target \"" << target << "\"\n";
4465 if (type == "mailto:" || type == "file:")
4466 os << "type \"" << type << "\"\n";
4467 os << "literal " << lit << "\n";
4469 skip_spaces_braces(p);
4473 if (t.cs() == "lyxline") {
4474 // swallow size argument (it is not used anyway)
4476 if (!context.atParagraphStart()) {
4477 // so our line is in the middle of a paragraph
4478 // we need to add a new line, lest this line
4479 // follow the other content on that line and
4480 // run off the side of the page
4481 // FIXME: This may create an empty paragraph,
4482 // but without that it would not be
4483 // possible to set noindent below.
4484 // Fortunately LaTeX does not care
4485 // about the empty paragraph.
4486 context.new_paragraph(os);
4488 if (preamble.indentParagraphs()) {
4489 // we need to unindent, lest the line be too long
4490 context.add_par_extra_stuff("\\noindent\n");
4492 context.check_layout(os);
4493 begin_command_inset(os, "line", "rule");
4494 os << "offset \"0.5ex\"\n"
4495 "width \"100line%\"\n"
4501 if (t.cs() == "rule") {
4502 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4503 string const width = p.getArg('{', '}');
4504 string const thickness = p.getArg('{', '}');
4505 context.check_layout(os);
4506 begin_command_inset(os, "line", "rule");
4507 if (!offset.empty())
4508 os << "offset \"" << translate_len(offset) << "\"\n";
4509 os << "width \"" << translate_len(width) << "\"\n"
4510 "height \"" << translate_len(thickness) << "\"\n";
4515 // Handle refstyle first in order to to catch \eqref, because this
4516 // can also occur without refstyle. Only recognize these commands if
4517 // refstyle.sty was found in the preamble (otherwise \eqref
4518 // and user defined ref commands could be misdetected).
4519 // We uncapitalize the input in order to catch capitalized commands
4521 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4522 && preamble.refstyle()) {
4523 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4524 string plural = "false";
4525 // Catch the plural option [s]
4527 string const opt = p.getOpt();
4531 // LyX does not yet support other optional arguments of ref commands
4532 output_ert_inset(os, t.asInput() + opt + "{" +
4533 p.verbatim_item() + '}', context);
4537 context.check_layout(os);
4538 begin_command_inset(os, "ref", "formatted");
4539 os << "reference \"";
4540 os << known_refstyle_prefixes[where - known_refstyle_commands]
4542 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4544 os << "plural \"" << plural << "\"\n";
4545 os << "caps \"" << cap << "\"\n";
4546 os << "noprefix \"false\"\n";
4548 preamble.registerAutomaticallyLoadedPackage("refstyle");
4552 // if refstyle is used, we must not convert \prettyref to a
4553 // formatted reference, since that would result in a refstyle command.
4554 if ((where = is_known(t.cs(), known_ref_commands))
4555 && (t.cs() != "prettyref" || !preamble.refstyle())
4556 && (p.next_token().asInput() != "*" || is_known(t.cs(), known_starref_commands))) {
4557 bool starred = false;
4558 if (p.next_token().asInput() == "*") {
4562 string const opt = p.getOpt();
4564 context.check_layout(os);
4565 begin_command_inset(os, "ref",
4566 known_coded_ref_commands[where - known_ref_commands]);
4567 os << "reference \""
4568 << convert_literate_command_inset_arg(p.verbatim_item())
4570 os << "plural \"false\"\n";
4571 os << "caps \"false\"\n";
4572 os << "noprefix \"false\"\n";
4574 os << "nolink \"true\"\n";
4576 os << "nolink \"false\"\n";
4578 if (t.cs() == "vref" || t.cs() == "vpageref")
4579 preamble.registerAutomaticallyLoadedPackage("varioref");
4580 else if (t.cs() == "prettyref")
4581 preamble.registerAutomaticallyLoadedPackage("prettyref");
4583 // LyX does not yet support optional arguments of ref commands
4584 output_ert_inset(os, t.asInput() + opt + "{" +
4585 p.verbatim_item() + '}', context);
4591 is_known(t.cs(), known_natbib_commands) &&
4592 ((t.cs() != "citefullauthor" &&
4593 t.cs() != "citeyear" &&
4594 t.cs() != "citeyearpar") ||
4595 p.next_token().asInput() != "*")) {
4596 context.check_layout(os);
4597 string command = t.cs();
4598 if (p.next_token().asInput() == "*") {
4602 if (command == "citefullauthor")
4603 // alternative name for "\\citeauthor*"
4604 command = "citeauthor*";
4606 // text before the citation
4608 // text after the citation
4610 get_cite_arguments(p, true, before, after);
4612 if (command == "cite") {
4613 // \cite without optional argument means
4614 // \citet, \cite with at least one optional
4615 // argument means \citep.
4616 if (before.empty() && after.empty())
4621 if (before.empty() && after == "[]")
4622 // avoid \citet[]{a}
4624 else if (before == "[]" && after == "[]") {
4625 // avoid \citet[][]{a}
4629 bool literal = false;
4630 pair<bool, string> aft;
4631 pair<bool, string> bef;
4632 // remove the brackets around after and before
4633 if (!after.empty()) {
4635 after.erase(after.length() - 1, 1);
4636 aft = convert_latexed_command_inset_arg(after);
4637 literal = !aft.first;
4638 after = literal ? subst(after, "\n", " ") : aft.second;
4640 if (!before.empty()) {
4642 before.erase(before.length() - 1, 1);
4643 bef = convert_latexed_command_inset_arg(before);
4644 literal |= !bef.first;
4645 before = literal ? subst(before, "\n", " ") : bef.second;
4646 if (literal && !after.empty())
4647 after = subst(after, "\n", " ");
4649 string lit = literal ? "\"true\"" : "\"false\"";
4650 begin_command_inset(os, "citation", command);
4651 os << "after " << '"' << after << '"' << "\n";
4652 os << "before " << '"' << before << '"' << "\n";
4654 << convert_literate_command_inset_arg(p.verbatim_item())
4656 << "literal " << lit << "\n";
4658 // Need to set the cite engine if natbib is loaded by
4659 // the document class directly
4660 if (preamble.citeEngine() == "basic")
4661 preamble.citeEngine("natbib");
4666 && is_known(t.cs(), known_biblatex_commands)
4667 && ((t.cs() == "cite"
4668 || t.cs() == "citeauthor"
4669 || t.cs() == "Citeauthor"
4670 || t.cs() == "parencite"
4671 || t.cs() == "citetitle")
4672 || p.next_token().asInput() != "*"))
4673 || (use_biblatex_natbib
4674 && (is_known(t.cs(), known_biblatex_commands)
4675 || is_known(t.cs(), known_natbib_commands))
4676 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4677 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4678 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4679 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4680 || t.cs() == "parencite" || t.cs() == "citetitle")
4681 || p.next_token().asInput() != "*"))){
4682 context.check_layout(os);
4683 string command = t.cs();
4684 if (p.next_token().asInput() == "*") {
4689 bool const qualified = suffixIs(command, "s");
4691 command = rtrim(command, "s");
4693 // text before the citation
4695 // text after the citation
4697 get_cite_arguments(p, true, before, after, qualified);
4699 // These use natbib cmd names in LyX
4700 // for inter-citeengine compativility
4701 if (command == "citeyear")
4702 command = "citebyear";
4703 else if (command == "cite*")
4704 command = "citeyear";
4705 else if (command == "textcite")
4707 else if (command == "Textcite")
4709 else if (command == "parencite")
4711 else if (command == "Parencite")
4713 else if (command == "parencite*")
4714 command = "citeyearpar";
4715 else if (command == "smartcite")
4716 command = "footcite";
4717 else if (command == "Smartcite")
4718 command = "Footcite";
4720 string const emptyarg = qualified ? "()" : "[]";
4721 if (before.empty() && after == emptyarg)
4724 else if (before == emptyarg && after == emptyarg) {
4725 // avoid \cite[][]{a}
4729 bool literal = false;
4730 pair<bool, string> aft;
4731 pair<bool, string> bef;
4732 // remove the brackets around after and before
4733 if (!after.empty()) {
4735 after.erase(after.length() - 1, 1);
4736 aft = convert_latexed_command_inset_arg(after);
4737 literal = !aft.first;
4738 after = literal ? subst(after, "\n", " ") : aft.second;
4740 if (!before.empty()) {
4742 before.erase(before.length() - 1, 1);
4743 bef = convert_latexed_command_inset_arg(before);
4744 literal |= !bef.first;
4745 before = literal ? subst(before, "\n", " ") : bef.second;
4747 string keys, pretextlist, posttextlist;
4749 vector<pair<string, string>> pres, posts, preslit, postslit;
4750 vector<string> lkeys;
4751 // text before the citation
4752 string lbefore, lbeforelit;
4753 // text after the citation
4754 string lafter, lafterlit;
4756 pair<bool, string> laft, lbef;
4758 get_cite_arguments(p, true, lbefore, lafter);
4759 // remove the brackets around after and before
4760 if (!lafter.empty()) {
4762 lafter.erase(lafter.length() - 1, 1);
4763 laft = convert_latexed_command_inset_arg(lafter);
4764 literal |= !laft.first;
4765 lafter = laft.second;
4766 lafterlit = subst(lafter, "\n", " ");
4768 if (!lbefore.empty()) {
4769 lbefore.erase(0, 1);
4770 lbefore.erase(lbefore.length() - 1, 1);
4771 lbef = convert_latexed_command_inset_arg(lbefore);
4772 literal |= !lbef.first;
4773 lbefore = lbef.second;
4774 lbeforelit = subst(lbefore, "\n", " ");
4776 if (lbefore.empty() && lafter == "[]") {
4781 else if (lbefore == "[]" && lafter == "[]") {
4782 // avoid \cite[][]{a}
4788 lkey = p.getArg('{', '}');
4791 pres.push_back(make_pair(lkey, lbefore));
4792 preslit.push_back(make_pair(lkey, lbeforelit));
4793 posts.push_back(make_pair(lkey, lafter));
4794 postslit.push_back(make_pair(lkey, lafterlit));
4795 lkeys.push_back(lkey);
4797 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4802 for (auto const & ptl : pres) {
4803 if (!pretextlist.empty())
4804 pretextlist += '\t';
4805 pretextlist += ptl.first;
4806 if (!ptl.second.empty())
4807 pretextlist += " " + ptl.second;
4809 for (auto const & potl : posts) {
4810 if (!posttextlist.empty())
4811 posttextlist += '\t';
4812 posttextlist += potl.first;
4813 if (!potl.second.empty())
4814 posttextlist += " " + potl.second;
4817 keys = convert_literate_command_inset_arg(p.verbatim_item());
4820 after = subst(after, "\n", " ");
4821 if (!before.empty())
4822 before = subst(after, "\n", " ");
4824 string lit = literal ? "\"true\"" : "\"false\"";
4825 begin_command_inset(os, "citation", command);
4826 os << "after " << '"' << after << '"' << "\n";
4827 os << "before " << '"' << before << '"' << "\n";
4831 if (!pretextlist.empty())
4832 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4833 if (!posttextlist.empty())
4834 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4835 os << "literal " << lit << "\n";
4837 // Need to set the cite engine if biblatex is loaded by
4838 // the document class directly
4839 if (preamble.citeEngine() == "basic")
4840 use_biblatex_natbib ?
4841 preamble.citeEngine("biblatex-natbib")
4842 : preamble.citeEngine("biblatex");
4847 is_known(t.cs(), known_jurabib_commands) &&
4848 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4849 context.check_layout(os);
4850 string command = t.cs();
4851 if (p.next_token().asInput() == "*") {
4855 char argumentOrder = '\0';
4856 vector<string> const options =
4857 preamble.getPackageOptions("jurabib");
4858 if (find(options.begin(), options.end(),
4859 "natbiborder") != options.end())
4860 argumentOrder = 'n';
4861 else if (find(options.begin(), options.end(),
4862 "jurabiborder") != options.end())
4863 argumentOrder = 'j';
4865 // text before the citation
4867 // text after the citation
4869 get_cite_arguments(p, argumentOrder != 'j', before, after);
4871 string const citation = p.verbatim_item();
4872 if (!before.empty() && argumentOrder == '\0') {
4873 cerr << "Warning: Assuming argument order "
4874 "of jurabib version 0.6 for\n'"
4875 << command << before << after << '{'
4876 << citation << "}'.\n"
4877 "Add 'jurabiborder' to the jurabib "
4878 "package options if you used an\n"
4879 "earlier jurabib version." << endl;
4881 bool literal = false;
4882 pair<bool, string> aft;
4883 pair<bool, string> bef;
4884 // remove the brackets around after and before
4885 if (!after.empty()) {
4887 after.erase(after.length() - 1, 1);
4888 aft = convert_latexed_command_inset_arg(after);
4889 literal = !aft.first;
4890 after = literal ? subst(after, "\n", " ") : aft.second;
4892 if (!before.empty()) {
4894 before.erase(before.length() - 1, 1);
4895 bef = convert_latexed_command_inset_arg(before);
4896 literal |= !bef.first;
4897 before = literal ? subst(before, "\n", " ") : bef.second;
4898 if (literal && !after.empty())
4899 after = subst(after, "\n", " ");
4901 string lit = literal ? "\"true\"" : "\"false\"";
4902 begin_command_inset(os, "citation", command);
4903 os << "after " << '"' << after << "\"\n"
4904 << "before " << '"' << before << "\"\n"
4905 << "key " << '"' << citation << "\"\n"
4906 << "literal " << lit << "\n";
4908 // Need to set the cite engine if jurabib is loaded by
4909 // the document class directly
4910 if (preamble.citeEngine() == "basic")
4911 preamble.citeEngine("jurabib");
4915 if (t.cs() == "cite"
4916 || t.cs() == "nocite") {
4917 context.check_layout(os);
4918 string after = p.getArg('[', ']');
4919 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4920 bool const literal = !aft.first;
4921 after = literal ? subst(after, "\n", " ") : aft.second;
4922 string lit = literal ? "\"true\"" : "\"false\"";
4923 string key = convert_literate_command_inset_arg(p.verbatim_item());
4924 // store the case that it is "\nocite{*}" to use it later for
4927 begin_command_inset(os, "citation", t.cs());
4928 os << "after " << '"' << after << "\"\n"
4929 << "key " << '"' << key << "\"\n"
4930 << "literal " << lit << "\n";
4932 } else if (t.cs() == "nocite")
4937 if (t.cs() == "index" ||
4938 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4939 context.check_layout(os);
4940 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4941 p.getArg('[', ']') : "";
4942 string const kind = arg.empty() ? "idx" : arg;
4943 parse_index_entry(p, os, context, kind);
4945 preamble.registerAutomaticallyLoadedPackage("splitidx");
4949 if (t.cs() == "nomenclature") {
4950 context.check_layout(os);
4951 begin_command_inset(os, "nomenclature", "nomenclature");
4952 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4953 if (!prefix.empty())
4954 os << "prefix " << '"' << prefix << '"' << "\n";
4955 string symbol = p.verbatim_item();
4956 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4957 bool literal = !sym.first;
4958 string description = p.verbatim_item();
4959 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4960 literal |= !desc.first;
4962 symbol = subst(symbol, "\n", " ");
4963 description = subst(description, "\n", " ");
4965 symbol = sym.second;
4966 description = desc.second;
4968 string lit = literal ? "\"true\"" : "\"false\"";
4969 os << "symbol " << '"' << symbol;
4970 os << "\"\ndescription \""
4971 << description << "\"\n"
4972 << "literal " << lit << "\n";
4974 preamble.registerAutomaticallyLoadedPackage("nomencl");
4978 if (t.cs() == "label") {
4979 context.check_layout(os);
4980 begin_command_inset(os, "label", "label");
4982 << convert_literate_command_inset_arg(p.verbatim_item())
4988 if (t.cs() == "lyxmintcaption") {
4989 string const pos = p.getArg('[', ']');
4991 string const caption =
4992 parse_text_snippet(p, FLAG_ITEM, false,
4994 minted_nonfloat_caption = "[t]" + caption;
4996 // We already got the caption at the bottom,
4997 // so simply skip it.
4998 parse_text_snippet(p, FLAG_ITEM, false, context);
5000 eat_whitespace(p, os, context, true);
5004 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
5005 context.check_layout(os);
5006 string commandname = t.cs();
5008 if (p.next_token().asInput() == "*") {
5013 begin_command_inset(os, "index_print", commandname);
5014 string const indexname = p.getArg('[', ']');
5016 if (indexname.empty())
5017 os << "type \"idx\"\n";
5019 os << "type \"" << indexname << "\"\n";
5020 os << "literal \"true\"\n";
5023 skip_spaces_braces(p);
5024 preamble.registerAutomaticallyLoadedPackage("makeidx");
5025 if (preamble.use_indices() == "true")
5026 preamble.registerAutomaticallyLoadedPackage("splitidx");
5030 if (t.cs() == "printnomenclature") {
5032 string width_type = "";
5033 context.check_layout(os);
5034 begin_command_inset(os, "nomencl_print", "printnomenclature");
5035 // case of a custom width
5037 width = p.getArg('[', ']');
5038 width = translate_len(width);
5039 width_type = "custom";
5041 // case of no custom width
5042 // the case of no custom width but the width set
5043 // via \settowidth{\nomlabelwidth}{***} cannot be supported
5044 // because the user could have set anything, not only the width
5045 // of the longest label (which would be width_type = "auto")
5046 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
5047 if (label.empty() && width_type.empty())
5048 width_type = "none";
5049 os << "set_width \"" << width_type << "\"\n";
5050 if (width_type == "custom")
5051 os << "width \"" << width << '\"';
5053 skip_spaces_braces(p);
5054 preamble.registerAutomaticallyLoadedPackage("nomencl");
5058 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
5059 context.check_layout(os);
5060 begin_inset(os, "script ");
5061 os << t.cs().substr(4) << '\n';
5062 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
5063 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5065 if (t.cs() == "textsubscript")
5066 preamble.registerAutomaticallyLoadedPackage("subscript");
5070 if ((where = is_known(t.cs(), known_quotes))) {
5071 context.check_layout(os);
5072 begin_inset(os, "Quotes ");
5073 string quotetype = known_coded_quotes[where - known_quotes];
5074 // try to make a smart guess about the side
5075 Token const prev = p.prev_token();
5076 bool const opening = (prev.cat() != catSpace && prev.character() != 0
5077 && prev.character() != '\n' && prev.character() != '~');
5078 quotetype = guessQuoteStyle(quotetype, opening);
5081 // LyX adds {} after the quote, so we have to eat
5082 // spaces here if there are any before a possible
5084 eat_whitespace(p, os, context, false);
5089 if ((where = is_known(t.cs(), known_sizes)) &&
5090 context.new_layout_allowed) {
5091 context.check_layout(os);
5092 TeXFont const oldFont = context.font;
5093 context.font.size = known_coded_sizes[where - known_sizes];
5094 output_font_change(os, oldFont, context.font);
5095 eat_whitespace(p, os, context, false);
5099 if ((where = is_known(t.cs(), known_font_families)) &&
5100 context.new_layout_allowed) {
5101 context.check_layout(os);
5102 TeXFont const oldFont = context.font;
5103 context.font.family =
5104 known_coded_font_families[where - known_font_families];
5105 output_font_change(os, oldFont, context.font);
5106 eat_whitespace(p, os, context, false);
5110 if ((where = is_known(t.cs(), known_font_series)) &&
5111 context.new_layout_allowed) {
5112 context.check_layout(os);
5113 TeXFont const oldFont = context.font;
5114 context.font.series =
5115 known_coded_font_series[where - known_font_series];
5116 output_font_change(os, oldFont, context.font);
5117 eat_whitespace(p, os, context, false);
5121 if ((where = is_known(t.cs(), known_font_shapes)) &&
5122 context.new_layout_allowed) {
5123 context.check_layout(os);
5124 TeXFont const oldFont = context.font;
5125 context.font.shape =
5126 known_coded_font_shapes[where - known_font_shapes];
5127 output_font_change(os, oldFont, context.font);
5128 eat_whitespace(p, os, context, false);
5131 if ((where = is_known(t.cs(), known_old_font_families)) &&
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.family =
5138 known_coded_font_families[where - known_old_font_families];
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_series)) &&
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.series =
5151 known_coded_font_series[where - known_old_font_series];
5152 output_font_change(os, oldFont, context.font);
5153 eat_whitespace(p, os, context, false);
5157 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
5158 context.new_layout_allowed) {
5159 context.check_layout(os);
5160 TeXFont const oldFont = context.font;
5161 context.font.init();
5162 context.font.size = oldFont.size;
5163 context.font.shape =
5164 known_coded_font_shapes[where - known_old_font_shapes];
5165 output_font_change(os, oldFont, context.font);
5166 eat_whitespace(p, os, context, false);
5170 if (t.cs() == "selectlanguage") {
5171 context.check_layout(os);
5172 // save the language for the case that a
5173 // \foreignlanguage is used
5174 context.font.language = babel2lyx(p.verbatim_item());
5175 os << "\n\\lang " << context.font.language << "\n";
5179 if (t.cs() == "foreignlanguage") {
5180 string const lang = babel2lyx(p.verbatim_item());
5181 parse_text_attributes(p, os, FLAG_ITEM, outer,
5183 context.font.language, lang);
5187 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
5188 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
5189 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
5191 // We have to output the whole command if it has an option
5192 // because LyX doesn't support this yet, see bug #8214,
5193 // only if there is a single option specifying a variant, we can handle it.
5195 string langopts = p.getOpt();
5196 // check if the option contains a variant, if yes, extract it
5197 string::size_type pos_var = langopts.find("variant");
5198 string::size_type i = langopts.find(',');
5199 string::size_type k = langopts.find('=', pos_var);
5200 if (pos_var != string::npos && i == string::npos) {
5202 variant = langopts.substr(k + 1, langopts.length() - k - 2);
5203 lang = preamble.polyglossia2lyx(variant);
5204 parse_text_attributes(p, os, FLAG_ITEM, outer,
5206 context.font.language, lang);
5208 output_ert_inset(os, t.asInput() + langopts, context);
5210 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
5211 parse_text_attributes(p, os, FLAG_ITEM, outer,
5213 context.font.language, lang);
5218 if (t.cs() == "inputencoding") {
5219 // nothing to write here
5220 string const enc = subst(p.verbatim_item(), "\n", " ");
5221 p.setEncoding(enc, Encoding::inputenc);
5225 if (is_known(t.cs(), known_special_chars) ||
5226 (t.cs() == "protect" &&
5227 p.next_token().cat() == catEscape &&
5228 is_known(p.next_token().cs(), known_special_protect_chars))) {
5229 // LyX sometimes puts a \protect in front, so we have to ignore it
5231 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5232 known_special_chars);
5233 context.check_layout(os);
5234 os << known_coded_special_chars[where - known_special_chars];
5235 skip_spaces_braces(p);
5239 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5240 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5241 p.next_next_token().asInput() == "-") ||
5242 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5243 // LyX sometimes puts a \protect in front, so we have to ignore it
5244 if (t.cs() == "protect")
5246 context.check_layout(os);
5247 if (t.cs() == "nobreakdash")
5248 os << "\\SpecialChar nobreakdash\n";
5250 os << "\\SpecialChar endofsentence\n";
5255 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5256 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5257 || t.cs() == "%" || t.cs() == "-") {
5258 context.check_layout(os);
5260 os << "\\SpecialChar softhyphen\n";
5266 if (t.cs() == "char") {
5267 context.check_layout(os);
5268 if (p.next_token().character() == '`') {
5270 if (p.next_token().cs() == "\"") {
5275 output_ert_inset(os, "\\char`", context);
5278 output_ert_inset(os, "\\char", context);
5283 if (t.cs() == "verb") {
5284 context.check_layout(os);
5285 // set catcodes to verbatim early, just in case.
5286 p.setCatcodes(VERBATIM_CATCODES);
5287 string delim = p.get_token().asInput();
5288 Parser::Arg arg = p.verbatimStuff(delim);
5290 output_ert_inset(os, "\\verb" + delim
5291 + arg.second + delim, context);
5293 cerr << "invalid \\verb command. Skipping" << endl;
5297 // Problem: \= creates a tabstop inside the tabbing environment
5298 // and else an accent. In the latter case we really would want
5299 // \={o} instead of \= o.
5300 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5301 output_ert_inset(os, t.asInput(), context);
5305 if (t.cs() == "\\") {
5306 context.check_layout(os);
5308 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5309 else if (p.next_token().asInput() == "*") {
5311 // getOpt() eats the following space if there
5312 // is no optional argument, but that is OK
5313 // here since it has no effect in the output.
5314 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5317 begin_inset(os, "Newline newline");
5323 if (t.cs() == "newline" ||
5324 (t.cs() == "linebreak" && !p.hasOpt())) {
5325 context.check_layout(os);
5326 begin_inset(os, "Newline ");
5329 skip_spaces_braces(p);
5333 if (t.cs() == "endgraf" && context.in_table_cell) {
5334 context.new_paragraph(os);
5335 context.check_layout(os);
5336 skip_spaces_braces(p);
5340 if (t.cs() == "input" || t.cs() == "include"
5341 || t.cs() == "verbatiminput"
5342 || t.cs() == "lstinputlisting"
5343 || t.cs() == "inputminted") {
5344 string name = t.cs();
5345 if (name == "verbatiminput"
5346 && p.next_token().asInput() == "*")
5347 name += p.get_token().asInput();
5348 context.check_layout(os);
5350 bool literal = false;
5351 if (name == "lstinputlisting" && p.hasOpt()) {
5352 lstparams = p.getArg('[', ']');
5353 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5354 literal = !oa.first;
5356 lstparams = subst(lstparams, "\n", " ");
5358 lstparams = oa.second;
5359 } else if (name == "inputminted") {
5360 name = "lstinputlisting";
5361 string const lang = p.getArg('{', '}');
5362 if (lang != "tex") {
5363 string cmd = "\\inputminted{" + lang + "}{";
5364 cmd += p.getArg('{', '}') + "}";
5365 output_ert_inset(os, cmd, context);
5368 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5369 minted_nonfloat_caption.erase(0,3);
5370 // extract label and caption from the already produced LyX code
5371 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5372 string const caption = nfc.front();
5374 vector<string>::iterator it =
5375 find(nfc.begin(), nfc.end(), "LatexCommand label");
5376 if (it != nfc.end()) {
5378 if (it != nfc.end())
5380 label = support::split(label, '"');
5383 minted_nonfloat_caption.clear();
5384 lstparams = "caption=" + caption;
5386 lstparams += ",label=" + label;
5387 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5388 literal = !oa.first;
5390 lstparams = subst(lstparams, "\n", " ");
5392 lstparams = oa.second;
5395 string lit = literal ? "\"true\"" : "\"false\"";
5396 string filename(normalize_filename(p.getArg('{', '}')));
5397 string const path = getMasterFilePath(true);
5398 // We want to preserve relative / absolute filenames,
5399 // therefore path is only used for testing
5400 if ((t.cs() == "include" || t.cs() == "input") &&
5401 !makeAbsPath(filename, path).exists()) {
5402 // The file extension is probably missing.
5403 // Now try to find it out.
5404 string const tex_name =
5405 find_file(filename, path,
5406 known_tex_extensions);
5407 if (!tex_name.empty())
5408 filename = tex_name;
5410 bool external = false;
5412 if (makeAbsPath(filename, path).exists()) {
5413 string const abstexname =
5414 makeAbsPath(filename, path).absFileName();
5415 string const absfigname =
5416 changeExtension(abstexname, ".fig");
5417 fix_child_filename(filename);
5418 string const lyxname = changeExtension(filename,
5419 roundtripMode() ? ".lyx.lyx" : ".lyx");
5420 string const abslyxname = makeAbsPath(
5421 lyxname, getParentFilePath(false)).absFileName();
5423 if (!skipChildren())
5424 external = FileName(absfigname).exists();
5425 if (t.cs() == "input" && !skipChildren()) {
5426 string const ext = getExtension(abstexname);
5428 // Combined PS/LaTeX:
5429 // x.eps, x.pstex_t (old xfig)
5430 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5431 FileName const absepsname(
5432 changeExtension(abstexname, ".eps"));
5433 FileName const abspstexname(
5434 changeExtension(abstexname, ".pstex"));
5435 bool const xfigeps =
5436 (absepsname.exists() ||
5437 abspstexname.exists()) &&
5440 // Combined PDF/LaTeX:
5441 // x.pdf, x.pdftex_t (old xfig)
5442 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5443 FileName const abspdfname(
5444 changeExtension(abstexname, ".pdf"));
5445 bool const xfigpdf =
5446 abspdfname.exists() &&
5447 (ext == "pdftex_t" || ext == "pdf_t");
5451 // Combined PS/PDF/LaTeX:
5452 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5453 string const absbase2(
5454 removeExtension(abstexname) + "_pspdftex");
5455 FileName const abseps2name(
5456 addExtension(absbase2, ".eps"));
5457 FileName const abspdf2name(
5458 addExtension(absbase2, ".pdf"));
5459 bool const xfigboth =
5460 abspdf2name.exists() &&
5461 abseps2name.exists() && ext == "pspdftex";
5463 xfig = xfigpdf || xfigeps || xfigboth;
5464 external = external && xfig;
5467 outname = changeExtension(filename, ".fig");
5468 FileName abssrc(changeExtension(abstexname, ".fig"));
5469 copy_file(abssrc, outname);
5471 // Don't try to convert, the result
5472 // would be full of ERT.
5474 FileName abssrc(abstexname);
5475 copy_file(abssrc, outname);
5476 } else if (t.cs() != "verbatiminput" &&
5478 tex2lyx(abstexname, FileName(abslyxname),
5481 // no need to call copy_file
5482 // tex2lyx creates the file
5485 FileName abssrc(abstexname);
5486 copy_file(abssrc, outname);
5489 cerr << "Warning: Could not find included file '"
5490 << filename << "'." << endl;
5494 begin_inset(os, "External\n");
5495 os << "\ttemplate XFig\n"
5496 << "\tfilename " << outname << '\n';
5497 registerExternalTemplatePackages("XFig");
5499 begin_command_inset(os, "include", name);
5500 outname = subst(outname, "\"", "\\\"");
5501 os << "preview false\n"
5502 "filename \"" << outname << "\"\n";
5503 if (!lstparams.empty())
5504 os << "lstparams \"" << lstparams << "\"\n";
5505 os << "literal " << lit << "\n";
5506 if (t.cs() == "verbatiminput")
5507 preamble.registerAutomaticallyLoadedPackage("verbatim");
5513 if (t.cs() == "bibliographystyle") {
5514 // store new bibliographystyle
5515 bibliographystyle = p.verbatim_item();
5516 // If any other command than \bibliography, \addcontentsline
5517 // and \nocite{*} follows, we need to output the style
5518 // (because it might be used by that command).
5519 // Otherwise, it will automatically be output by LyX.
5522 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5523 if (t2.cat() == catBegin)
5525 if (t2.cat() != catEscape)
5527 if (t2.cs() == "nocite") {
5528 if (p.getArg('{', '}') == "*")
5530 } else if (t2.cs() == "bibliography")
5532 else if (t2.cs() == "phantomsection") {
5536 else if (t2.cs() == "addcontentsline") {
5537 // get the 3 arguments of \addcontentsline
5540 contentslineContent = p.getArg('{', '}');
5541 // if the last argument is not \refname we must output
5542 if (contentslineContent == "\\refname")
5549 output_ert_inset(os,
5550 "\\bibliographystyle{" + bibliographystyle + '}',
5556 if (t.cs() == "phantomsection") {
5557 // we only support this if it occurs between
5558 // \bibliographystyle and \bibliography
5559 if (bibliographystyle.empty())
5560 output_ert_inset(os, "\\phantomsection", context);
5564 if (t.cs() == "addcontentsline") {
5565 context.check_layout(os);
5566 // get the 3 arguments of \addcontentsline
5567 string const one = p.getArg('{', '}');
5568 string const two = p.getArg('{', '}');
5569 string const three = p.getArg('{', '}');
5570 // only if it is a \refname, we support if for the bibtex inset
5571 if (contentslineContent != "\\refname") {
5572 output_ert_inset(os,
5573 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5579 else if (t.cs() == "bibliography") {
5580 context.check_layout(os);
5582 begin_command_inset(os, "bibtex", "bibtex");
5583 if (!btprint.empty()) {
5584 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5585 // clear the string because the next BibTeX inset can be without the
5586 // \nocite{*} option
5589 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5590 // Do we have addcontentsline?
5591 if (contentslineContent == "\\refname") {
5592 BibOpts = "bibtotoc";
5593 // clear string because next BibTeX inset can be without addcontentsline
5594 contentslineContent.clear();
5596 // Do we have a bibliographystyle set?
5597 if (!bibliographystyle.empty()) {
5598 if (BibOpts.empty())
5599 BibOpts = normalize_filename(bibliographystyle);
5601 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5602 // clear it because each bibtex entry has its style
5603 // and we need an empty string to handle \phantomsection
5604 bibliographystyle.clear();
5606 os << "options " << '"' << BibOpts << '"' << "\n";
5607 if (p.getEncoding() != preamble.docencoding) {
5608 Encoding const * const enc = encodings.fromIconvName(
5609 p.getEncoding(), Encoding::inputenc, true);
5611 cerr << "Unknown bib encoding " << p.getEncoding()
5612 << ". Ignoring." << std::endl;
5614 os << "encoding " << '"' << enc->name() << '"' << "\n";
5620 if (t.cs() == "printbibliography") {
5621 context.check_layout(os);
5623 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5624 vector<string> opts = getVectorFromString(bbloptions);
5625 vector<string>::iterator it =
5626 find(opts.begin(), opts.end(), "heading=bibintoc");
5627 if (it != opts.end()) {
5629 BibOpts = "bibtotoc";
5631 bbloptions = getStringFromVector(opts);
5632 begin_command_inset(os, "bibtex", "bibtex");
5633 if (!btprint.empty()) {
5634 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5635 // clear the string because the next BibTeX inset can be without the
5636 // \nocite{*} option
5640 for (auto const & bf : preamble.biblatex_bibliographies) {
5641 if (!bibfiles.empty())
5643 bibfiles += normalize_filename(bf);
5645 if (!bibfiles.empty())
5646 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5647 // Do we have addcontentsline?
5648 if (contentslineContent == "\\refname") {
5649 BibOpts = "bibtotoc";
5650 // clear string because next BibTeX inset can be without addcontentsline
5651 contentslineContent.clear();
5653 os << "options " << '"' << BibOpts << '"' << "\n";
5654 if (!bbloptions.empty())
5655 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5656 if (!preamble.bibencoding.empty()) {
5657 Encoding const * const enc = encodings.fromLaTeXName(
5658 preamble.bibencoding, Encoding::inputenc, true);
5660 cerr << "Unknown bib encoding " << preamble.bibencoding
5661 << ". Ignoring." << std::endl;
5663 os << "encoding " << '"' << enc->name() << '"' << "\n";
5666 for (auto const & bf : preamble.biblatex_encodings) {
5667 if (!bibfileencs.empty())
5668 bibfileencs += "\t";
5671 if (!bibfileencs.empty())
5672 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5674 need_commentbib = false;
5678 if (t.cs() == "bibbysection") {
5679 context.check_layout(os);
5681 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5682 vector<string> opts = getVectorFromString(bbloptions);
5683 vector<string>::iterator it =
5684 find(opts.begin(), opts.end(), "heading=bibintoc");
5685 if (it != opts.end()) {
5687 BibOpts = "bibtotoc";
5689 bbloptions = getStringFromVector(opts);
5690 begin_command_inset(os, "bibtex", "bibtex");
5691 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5693 for (auto const & bf : preamble.biblatex_bibliographies) {
5694 if (!bibfiles.empty())
5696 bibfiles += normalize_filename(bf);
5698 if (!bibfiles.empty())
5699 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5700 os << "options " << '"' << BibOpts << '"' << "\n";
5701 if (!bbloptions.empty())
5702 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5704 need_commentbib = false;
5708 if (t.cs() == "parbox") {
5709 // Test whether this is an outer box of a shaded box
5711 // swallow arguments
5712 while (p.hasOpt()) {
5714 p.skip_spaces(true);
5717 p.skip_spaces(true);
5719 if (p.next_token().cat() == catBegin)
5721 p.skip_spaces(true);
5722 Token to = p.get_token();
5723 bool shaded = false;
5724 if (to.asInput() == "\\begin") {
5725 p.skip_spaces(true);
5726 if (p.getArg('{', '}') == "shaded")
5731 parse_outer_box(p, os, FLAG_ITEM, outer,
5732 context, "parbox", "shaded");
5734 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5735 "", "", t.cs(), "", "");
5739 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5740 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5741 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5742 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5746 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5747 string backgroundcolor;
5748 preamble.registerAutomaticallyLoadedPackage("xcolor");
5749 if (t.cs() == "fcolorbox") {
5750 string const framecolor = p.getArg('{', '}');
5751 backgroundcolor = p.getArg('{', '}');
5752 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5754 backgroundcolor = p.getArg('{', '}');
5755 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5760 // FIXME: due to the compiler limit of "if" nestings
5761 // the code for the alignment was put here
5762 // put them in their own if if this is fixed
5763 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5764 || t.cs() == "shadowsize") {
5765 if (t.cs() == "fboxrule")
5767 if (t.cs() == "fboxsep")
5769 if (t.cs() == "shadowsize")
5771 p.skip_spaces(true);
5772 while (p.good() && p.next_token().cat() != catSpace
5773 && p.next_token().cat() != catNewline
5774 && p.next_token().cat() != catEscape) {
5775 if (t.cs() == "fboxrule")
5776 fboxrule = fboxrule + p.get_token().asInput();
5777 if (t.cs() == "fboxsep")
5778 fboxsep = fboxsep + p.get_token().asInput();
5779 if (t.cs() == "shadowsize")
5780 shadow_size = shadow_size + p.get_token().asInput();
5785 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5786 if (context.in_table_cell) {
5787 if (t.cs() == "raggedleft")
5788 context.cell_align = 'r';
5789 else if (t.cs() == "centering")
5790 context.cell_align = 'c';
5791 else if (t.cs() == "raggedright")
5792 context.cell_align = 'l';
5793 p.skip_spaces(true);
5795 output_ert_inset(os, t.asInput(), context);
5800 //\framebox() is part of the picture environment and different from \framebox{}
5801 //\framebox{} will be parsed by parse_outer_box
5802 if (t.cs() == "framebox") {
5803 if (p.next_token().character() == '(') {
5804 //the syntax is: \framebox(x,y)[position]{content}
5805 string arg = t.asInput();
5806 arg += p.getFullParentheseArg();
5807 arg += p.getFullOpt();
5808 eat_whitespace(p, os, context, false);
5809 output_ert_inset(os, arg + '{', context);
5810 parse_text(p, os, FLAG_ITEM, outer, context);
5811 output_ert_inset(os, "}", context);
5813 //the syntax is: \framebox[width][position]{content}
5814 string special = p.getFullOpt();
5815 special += p.getOpt();
5816 parse_outer_box(p, os, FLAG_ITEM, outer,
5817 context, t.cs(), special);
5822 //\makebox() is part of the picture environment and different from \makebox{}
5823 //\makebox{} will be parsed by parse_box
5824 if (t.cs() == "makebox") {
5825 if (p.next_token().character() == '(') {
5826 //the syntax is: \makebox(x,y)[position]{content}
5827 string arg = t.asInput();
5828 arg += p.getFullParentheseArg();
5829 arg += p.getFullOpt();
5830 eat_whitespace(p, os, context, false);
5831 output_ert_inset(os, arg + '{', context);
5832 parse_text(p, os, FLAG_ITEM, outer, context);
5833 output_ert_inset(os, "}", context);
5835 //the syntax is: \makebox[width][position]{content}
5836 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5837 "", "", t.cs(), "", "");
5841 if (t.cs() == "smallskip" ||
5842 t.cs() == "medskip" ||
5843 t.cs() == "bigskip" ||
5844 t.cs() == "vfill") {
5845 context.check_layout(os);
5846 begin_inset(os, "VSpace ");
5849 skip_spaces_braces(p);
5853 if ((where = is_known(t.cs(), known_spaces))
5854 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5855 context.check_layout(os);
5856 begin_inset(os, "space ");
5857 os << '\\' << known_coded_spaces[where - known_spaces]
5860 // LaTeX swallows whitespace after all spaces except
5861 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5862 // We have to do that here, too, because LyX
5863 // adds "{}" which would make the spaces significant.
5864 if (!contains(",>!;:", t.cs()))
5865 eat_whitespace(p, os, context, false);
5866 // LyX adds "{}" after all spaces except "\\ " and
5867 // "\\,", so we have to remove "{}".
5868 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5869 // remove the braces after "\\,", too.
5875 if (t.cs() == "newpage" ||
5876 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5877 t.cs() == "clearpage" ||
5878 t.cs() == "cleardoublepage" ||
5879 t.cs() == "nopagebreak") {
5880 context.check_layout(os);
5881 begin_inset(os, "Newpage ");
5884 skip_spaces_braces(p);
5888 if (t.cs() == "DeclareRobustCommand" ||
5889 t.cs() == "DeclareRobustCommandx" ||
5890 t.cs() == "newcommand" ||
5891 t.cs() == "newcommandx" ||
5892 t.cs() == "providecommand" ||
5893 t.cs() == "providecommandx" ||
5894 t.cs() == "renewcommand" ||
5895 t.cs() == "renewcommandx") {
5896 // DeclareRobustCommand, DeclareRobustCommandx,
5897 // providecommand and providecommandx could be handled
5898 // by parse_command(), but we need to call
5899 // add_known_command() here.
5900 string name = t.asInput();
5901 if (p.next_token().asInput() == "*") {
5902 // Starred form. Eat '*'
5906 string const command = p.verbatim_item();
5907 string const opt1 = p.getFullOpt();
5908 string const opt2 = p.getFullOpt();
5909 add_known_command(command, opt1, !opt2.empty());
5910 string const ert = name + '{' + command + '}' +
5912 '{' + p.verbatim_item() + '}';
5914 if (t.cs() == "DeclareRobustCommand" ||
5915 t.cs() == "DeclareRobustCommandx" ||
5916 t.cs() == "providecommand" ||
5917 t.cs() == "providecommandx" ||
5918 name[name.length()-1] == '*')
5919 output_ert_inset(os, ert, context);
5921 context.check_layout(os);
5922 begin_inset(os, "FormulaMacro");
5929 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5930 // let could be handled by parse_command(),
5931 // but we need to call add_known_command() here.
5932 string ert = t.asInput();
5935 if (p.next_token().cat() == catBegin) {
5936 name = p.verbatim_item();
5937 ert += '{' + name + '}';
5939 name = p.verbatim_item();
5944 if (p.next_token().cat() == catBegin) {
5945 command = p.verbatim_item();
5946 ert += '{' + command + '}';
5948 command = p.verbatim_item();
5951 // If command is known, make name known too, to parse
5952 // its arguments correctly. For this reason we also
5953 // have commands in syntax.default that are hardcoded.
5954 CommandMap::iterator it = known_commands.find(command);
5955 if (it != known_commands.end())
5956 known_commands[t.asInput()] = it->second;
5957 output_ert_inset(os, ert, context);
5961 if (t.cs() == "hspace" || t.cs() == "vspace") {
5964 string name = t.asInput();
5965 string const length = p.verbatim_item();
5968 bool valid = splitLatexLength(length, valstring, unit);
5969 bool known_hspace = false;
5970 bool known_vspace = false;
5971 bool known_unit = false;
5974 istringstream iss(valstring);
5977 if (t.cs()[0] == 'h') {
5978 if (unit == "\\fill") {
5983 known_hspace = true;
5986 if (unit == "\\smallskipamount") {
5988 known_vspace = true;
5989 } else if (unit == "\\medskipamount") {
5991 known_vspace = true;
5992 } else if (unit == "\\bigskipamount") {
5994 known_vspace = true;
5995 } else if (length == "\\baselineskip") {
5997 known_vspace = true;
5998 } else if (unit == "\\fill") {
6000 known_vspace = true;
6004 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
6006 known_vspace = true;
6008 if (!known_hspace && !known_vspace) {
6009 switch (unitFromString(unit)) {
6025 //unitFromString(unit) fails for relative units like Length::PCW
6026 // therefore handle them separately
6027 if (unit == "\\paperwidth" || unit == "\\columnwidth"
6028 || unit == "\\textwidth" || unit == "\\linewidth"
6029 || unit == "\\textheight" || unit == "\\paperheight"
6030 || unit == "\\baselineskip")
6038 // check for glue lengths
6039 bool is_gluelength = false;
6040 string gluelength = length;
6041 string::size_type i = length.find(" minus");
6042 if (i == string::npos) {
6043 i = length.find(" plus");
6044 if (i != string::npos)
6045 is_gluelength = true;
6047 is_gluelength = true;
6048 // if yes transform "9xx minus 8yy plus 7zz"
6050 if (is_gluelength) {
6051 i = gluelength.find(" minus");
6052 if (i != string::npos)
6053 gluelength.replace(i, 7, "-");
6054 i = gluelength.find(" plus");
6055 if (i != string::npos)
6056 gluelength.replace(i, 6, "+");
6059 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
6060 // Literal horizontal length or known variable
6061 context.check_layout(os);
6062 begin_inset(os, "space ");
6070 if (known_unit && !known_hspace)
6071 os << "\n\\length " << translate_len(length);
6073 os << "\n\\length " << gluelength;
6075 } else if (known_unit || known_vspace || is_gluelength) {
6076 // Literal vertical length or known variable
6077 context.check_layout(os);
6078 begin_inset(os, "VSpace ");
6081 if (known_unit && !known_vspace)
6082 os << translate_len(length);
6089 // LyX can't handle other length variables in Inset VSpace/space
6094 output_ert_inset(os, name + '{' + unit + '}', context);
6095 else if (value == -1.0)
6096 output_ert_inset(os, name + "{-" + unit + '}', context);
6098 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
6100 output_ert_inset(os, name + '{' + length + '}', context);
6105 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
6106 // might be one or several options or a star.
6107 // The single '=' is meant here.
6108 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
6112 context.check_layout(os);
6113 // store the latexparam here. This is eaten in parse_text_in_inset
6114 context.latexparam = newinsetlayout->latexparam();
6115 docstring name = newinsetlayout->name();
6116 bool const caption = name.find(from_ascii("Caption:")) == 0;
6118 // Already done for floating minted listings.
6119 if (minted_float.empty()) {
6120 begin_inset(os, "Caption ");
6121 os << to_utf8(name.substr(8)) << '\n';
6124 // FIXME: what do we do if the prefix is not Flex: ?
6125 if (prefixIs(name, from_ascii("Flex:")))
6127 begin_inset(os, "Flex ");
6128 os << to_utf8(name) << '\n'
6129 << "status collapsed\n";
6131 if (!minted_float.empty()) {
6132 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6133 } else if (newinsetlayout->isPassThru()) {
6134 // set catcodes to verbatim early, just in case.
6135 p.setCatcodes(VERBATIM_CATCODES);
6136 string delim = p.get_token().asInput();
6138 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
6139 //FIXME: handle error condition
6140 string const arg = p.verbatimStuff("}").second;
6141 Context newcontext(true, context.textclass);
6142 if (newinsetlayout->forcePlainLayout())
6143 newcontext.layout = &context.textclass.plainLayout();
6144 output_ert(os, arg, newcontext);
6146 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6147 context.latexparam.clear();
6150 // Minted caption insets are not closed here because
6151 // we collect everything into the caption.
6152 if (minted_float.empty())
6157 // The single '=' is meant here.
6158 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
6162 context.check_layout(os);
6163 docstring name = newinsetlayout->name();
6164 bool const caption = name.find(from_ascii("Caption:")) == 0;
6166 // Already done for floating minted listings.
6167 if (minted_float.empty()) {
6168 begin_inset(os, "Caption ");
6169 os << to_utf8(name.substr(8)) << '\n';
6172 // FIXME: what do we do if the prefix is not Flex: ?
6173 if (prefixIs(name, from_ascii("Flex:")))
6175 begin_inset(os, "Flex ");
6176 os << to_utf8(name) << '\n'
6177 << "status collapsed\n";
6179 if (!minted_float.empty()) {
6180 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6181 } else if (newinsetlayout->isPassThru()) {
6182 // set catcodes to verbatim early, just in case.
6183 p.setCatcodes(VERBATIM_CATCODES);
6184 string delim = p.get_token().asInput();
6186 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
6187 //FIXME: handle error condition
6188 string const arg = p.verbatimStuff("}").second;
6189 Context newcontext(true, context.textclass);
6190 if (newinsetlayout->forcePlainLayout())
6191 newcontext.layout = &context.textclass.plainLayout();
6192 output_ert(os, arg, newcontext);
6194 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6197 // Minted caption insets are not closed here because
6198 // we collect everything into the caption.
6199 if (minted_float.empty())
6204 if (t.cs() == "includepdf") {
6206 string const arg = p.getArg('[', ']');
6207 map<string, string> opts;
6208 vector<string> keys;
6209 split_map(arg, opts, keys);
6210 string name = normalize_filename(p.verbatim_item());
6211 string const path = getMasterFilePath(true);
6212 // We want to preserve relative / absolute filenames,
6213 // therefore path is only used for testing
6214 if (!makeAbsPath(name, path).exists()) {
6215 // The file extension is probably missing.
6216 // Now try to find it out.
6217 char const * const pdfpages_format[] = {"pdf", 0};
6218 string const pdftex_name =
6219 find_file(name, path, pdfpages_format);
6220 if (!pdftex_name.empty()) {
6225 FileName const absname = makeAbsPath(name, path);
6226 if (absname.exists())
6228 fix_child_filename(name);
6229 copy_file(absname, name);
6231 cerr << "Warning: Could not find file '"
6232 << name << "'." << endl;
6234 context.check_layout(os);
6235 begin_inset(os, "External\n\ttemplate ");
6236 os << "PDFPages\n\tfilename "
6238 // parse the options
6239 if (opts.find("pages") != opts.end())
6240 os << "\textra LaTeX \"pages="
6241 << opts["pages"] << "\"\n";
6242 if (opts.find("angle") != opts.end())
6243 os << "\trotateAngle "
6244 << opts["angle"] << '\n';
6245 if (opts.find("origin") != opts.end()) {
6247 string const opt = opts["origin"];
6248 if (opt == "tl") ss << "topleft";
6249 if (opt == "bl") ss << "bottomleft";
6250 if (opt == "Bl") ss << "baselineleft";
6251 if (opt == "c") ss << "center";
6252 if (opt == "tc") ss << "topcenter";
6253 if (opt == "bc") ss << "bottomcenter";
6254 if (opt == "Bc") ss << "baselinecenter";
6255 if (opt == "tr") ss << "topright";
6256 if (opt == "br") ss << "bottomright";
6257 if (opt == "Br") ss << "baselineright";
6258 if (!ss.str().empty())
6259 os << "\trotateOrigin " << ss.str() << '\n';
6261 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
6263 if (opts.find("width") != opts.end())
6265 << translate_len(opts["width"]) << '\n';
6266 if (opts.find("height") != opts.end())
6268 << translate_len(opts["height"]) << '\n';
6269 if (opts.find("keepaspectratio") != opts.end())
6270 os << "\tkeepAspectRatio\n";
6272 context.check_layout(os);
6273 registerExternalTemplatePackages("PDFPages");
6277 if (t.cs() == "loadgame") {
6279 string name = normalize_filename(p.verbatim_item());
6280 string const path = getMasterFilePath(true);
6281 // We want to preserve relative / absolute filenames,
6282 // therefore path is only used for testing
6283 if (!makeAbsPath(name, path).exists()) {
6284 // The file extension is probably missing.
6285 // Now try to find it out.
6286 char const * const lyxskak_format[] = {"fen", 0};
6287 string const lyxskak_name =
6288 find_file(name, path, lyxskak_format);
6289 if (!lyxskak_name.empty())
6290 name = lyxskak_name;
6292 FileName const absname = makeAbsPath(name, path);
6293 if (absname.exists())
6295 fix_child_filename(name);
6296 copy_file(absname, name);
6298 cerr << "Warning: Could not find file '"
6299 << name << "'." << endl;
6300 context.check_layout(os);
6301 begin_inset(os, "External\n\ttemplate ");
6302 os << "ChessDiagram\n\tfilename "
6305 context.check_layout(os);
6306 // after a \loadgame follows a \showboard
6307 if (p.get_token().asInput() == "showboard")
6309 registerExternalTemplatePackages("ChessDiagram");
6313 // try to see whether the string is in unicodesymbols
6314 // Only use text mode commands, since we are in text mode here,
6315 // and math commands may be invalid (bug 6797)
6316 string name = t.asInput();
6317 // handle the dingbats, cyrillic and greek
6318 if (name == "\\textcyr")
6319 name = "\\textcyrillic";
6320 if (name == "\\ding" || name == "\\textcyrillic" ||
6321 (name == "\\textgreek" && !preamble.usePolyglossia()))
6322 name = name + '{' + p.getArg('{', '}') + '}';
6323 // handle the ifsym characters
6324 else if (name == "\\textifsymbol") {
6325 string const optif = p.getFullOpt();
6326 string const argif = p.getArg('{', '}');
6327 name = name + optif + '{' + argif + '}';
6329 // handle the \ascii characters
6330 // the case of \ascii within braces, as LyX outputs it, is already
6331 // handled for t.cat() == catBegin
6332 else if (name == "\\ascii") {
6333 // the code is "\asci\xxx"
6334 name = "{" + name + p.get_token().asInput() + "}";
6337 // handle some TIPA special characters
6338 else if (preamble.isPackageUsed("tipa")) {
6339 if (name == "\\s") {
6340 // fromLaTeXCommand() does not yet
6341 // recognize tipa short cuts
6342 name = "\\textsyllabic";
6343 } else if (name == "\\=" &&
6344 p.next_token().asInput() == "*") {
6345 // fromLaTeXCommand() does not yet
6346 // recognize tipa short cuts
6348 name = "\\textsubbar";
6349 } else if (name == "\\textdoublevertline") {
6350 // FIXME: This is not correct,
6351 // \textvertline is higher than \textbardbl
6352 name = "\\textbardbl";
6354 } else if (name == "\\!" ) {
6355 if (p.next_token().asInput() == "b") {
6356 p.get_token(); // eat 'b'
6359 } else if (p.next_token().asInput() == "d") {
6363 } else if (p.next_token().asInput() == "g") {
6367 } else if (p.next_token().asInput() == "G") {
6369 name = "\\texthtscg";
6371 } else if (p.next_token().asInput() == "j") {
6373 name = "\\texthtbardotlessj";
6375 } else if (p.next_token().asInput() == "o") {
6377 name = "\\textbullseye";
6380 } else if (name == "\\*" ) {
6381 if (p.next_token().asInput() == "k") {
6383 name = "\\textturnk";
6385 } else if (p.next_token().asInput() == "r") {
6386 p.get_token(); // eat 'b'
6387 name = "\\textturnr";
6389 } else if (p.next_token().asInput() == "t") {
6391 name = "\\textturnt";
6393 } else if (p.next_token().asInput() == "w") {
6395 name = "\\textturnw";
6400 if ((name.size() == 2 &&
6401 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6402 p.next_token().asInput() != "*") ||
6403 is_known(name.substr(1), known_tipa_marks)) {
6404 // name is a command that corresponds to a
6405 // combining character in unicodesymbols.
6406 // Append the argument, fromLaTeXCommand()
6407 // will either convert it to a single
6408 // character or a combining sequence.
6409 name += '{' + p.verbatim_item() + '}';
6411 // now get the character from unicodesymbols
6415 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6416 Encodings::TEXT_CMD, termination, rem, &req));
6418 context.check_layout(os);
6421 output_ert_inset(os, to_utf8(rem), context);
6423 skip_spaces_braces(p);
6424 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6425 preamble.registerAutomaticallyLoadedPackage(*it);
6427 //cerr << "#: " << t << " mode: " << mode << endl;
6428 // heuristic: read up to next non-nested space
6430 string s = t.asInput();
6431 string z = p.verbatim_item();
6432 while (p.good() && z != " " && !z.empty()) {
6433 //cerr << "read: " << z << endl;
6435 z = p.verbatim_item();
6437 cerr << "found ERT: " << s << endl;
6438 output_ert_inset(os, s + ' ', context);
6441 if (t.asInput() == name &&
6442 p.next_token().asInput() == "*") {
6443 // Starred commands like \vspace*{}
6444 p.get_token(); // Eat '*'
6447 if (!parse_command(name, p, os, outer, context)) {
6448 output_ert_inset(os, name, context);
6449 // Try to handle options of unknown commands:
6450 // Look if we have optional arguments,
6451 // and if so, put the brackets in ERT.
6452 while (p.hasOpt()) {
6453 p.get_token(); // eat '['
6454 output_ert_inset(os, "[", context);
6455 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6456 output_ert_inset(os, "]", context);
6464 string guessLanguage(Parser & p, string const & lang)
6466 typedef std::map<std::string, size_t> LangMap;
6467 // map from language names to number of characters
6470 for (char const * const * i = supported_CJK_languages; *i; i++)
6471 used[string(*i)] = 0;
6474 Token const t = p.get_token();
6475 // comments are not counted for any language
6476 if (t.cat() == catComment)
6478 // commands are not counted as well, but we need to detect
6479 // \begin{CJK} and switch encoding if needed
6480 if (t.cat() == catEscape) {
6481 if (t.cs() == "inputencoding") {
6482 string const enc = subst(p.verbatim_item(), "\n", " ");
6483 p.setEncoding(enc, Encoding::inputenc);
6486 if (t.cs() != "begin")
6489 // Non-CJK content is counted for lang.
6490 // We do not care about the real language here:
6491 // If we have more non-CJK contents than CJK contents,
6492 // we simply use the language that was specified as
6493 // babel main language.
6494 used[lang] += t.asInput().length();
6497 // Now we are starting an environment
6499 string const name = p.getArg('{', '}');
6500 if (name != "CJK") {
6504 // It is a CJK environment
6506 /* name = */ p.getArg('{', '}');
6507 string const encoding = p.getArg('{', '}');
6508 /* mapping = */ p.getArg('{', '}');
6509 string const encoding_old = p.getEncoding();
6510 char const * const * const where =
6511 is_known(encoding, supported_CJK_encodings);
6513 p.setEncoding(encoding, Encoding::CJK);
6515 p.setEncoding("UTF-8");
6516 string const text = p.ertEnvironment("CJK");
6517 p.setEncoding(encoding_old);
6520 // ignore contents in unknown CJK encoding
6523 // the language of the text
6525 supported_CJK_languages[where - supported_CJK_encodings];
6526 used[cjk] += text.length();
6528 LangMap::const_iterator use = used.begin();
6529 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6530 if (it->second > use->second)
6537 void check_comment_bib(ostream & os, Context & context)
6539 if (!need_commentbib)
6541 // We have a bibliography database, but no bibliography with biblatex
6542 // which is completely valid. Insert a bibtex inset in a note.
6543 context.check_layout(os);
6544 begin_inset(os, "Note Note\n");
6545 os << "status open\n";
6546 os << "\\begin_layout Plain Layout\n";
6547 begin_command_inset(os, "bibtex", "bibtex");
6549 for (auto const & bf : preamble.biblatex_bibliographies) {
6550 if (!bibfiles.empty())
6552 bibfiles += normalize_filename(bf);
6554 if (!bibfiles.empty())
6555 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6557 for (auto const & bf : preamble.biblatex_encodings) {
6558 if (!bibfileencs.empty())
6559 bibfileencs += "\t";
6562 if (!bibfileencs.empty())
6563 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6564 end_inset(os);// Bibtex
6565 os << "\\end_layout\n";
6566 end_inset(os);// Note