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 warning_message("invalid position " + position
1133 + " for " + inner_type);
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 warning_message("invalid hor_pos "
1155 inner_pos = p.getArg('[', ']');
1156 if (inner_pos != "c" && inner_pos != "t" &&
1157 inner_pos != "b" && inner_pos != "s") {
1158 warning_message("invalid inner_pos "
1159 + inner_pos + " for "
1161 inner_pos = position;
1165 if (inner_type == "makebox")
1169 if (inner_type.empty()) {
1170 if (special.empty() && outer_type != "framebox")
1171 latex_width = "1\\columnwidth";
1174 latex_width = p2.getArg('[', ']');
1175 string const opt = p2.getArg('[', ']');
1178 if (hor_pos != "l" && hor_pos != "c" &&
1179 hor_pos != "r" && hor_pos != "s") {
1180 warning_message("invalid hor_pos "
1186 if (outer_type == "framebox")
1190 } else if (inner_type != "makebox")
1191 latex_width = p.verbatim_item();
1192 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1193 // as this is LyX's standard for such cases (except for makebox)
1194 // \framebox is more special and handled below
1195 if (latex_width.empty() && inner_type != "makebox"
1196 && outer_type != "framebox")
1197 latex_width = "1\\columnwidth";
1199 translate_len(latex_width, width_value, width_unit);
1201 bool shadedparbox = false;
1202 if (inner_type == "shaded") {
1203 eat_whitespace(p, os, parent_context, false);
1204 if (outer_type == "parbox") {
1206 if (p.next_token().cat() == catBegin)
1208 eat_whitespace(p, os, parent_context, false);
1209 shadedparbox = true;
1214 // If we already read the inner box we have to push the inner env
1215 if (!outer_type.empty() && !inner_type.empty() &&
1216 (inner_flags & FLAG_END))
1217 active_environments.push_back(inner_type);
1218 bool use_ert = false;
1219 if (!outer_type.empty() && !inner_type.empty()) {
1220 // Look whether there is some content after the end of the
1221 // inner box, but before the end of the outer box.
1222 // If yes, we need to output ERT.
1224 if (inner_flags & FLAG_END)
1225 p.ertEnvironment(inner_type);
1228 p.skip_spaces(true);
1229 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1230 if ((outer_env && p.next_token().asInput() != "\\end") ||
1231 (!outer_env && p.next_token().cat() != catEnd)) {
1232 // something is between the end of the inner box and
1233 // the end of the outer box, so we need to use ERT.
1241 if (!outer_type.empty()) {
1242 if (outer_flags & FLAG_END)
1243 ss << "\\begin{" << outer_type << '}';
1245 ss << '\\' << outer_type << '{';
1246 if (!special.empty())
1250 if (!inner_type.empty()) {
1251 if (inner_type != "shaded") {
1252 if (inner_flags & FLAG_END)
1253 ss << "\\begin{" << inner_type << '}';
1255 ss << '\\' << inner_type;
1257 if (!position.empty())
1258 ss << '[' << position << ']';
1259 if (!latex_height.empty())
1260 ss << '[' << latex_height << ']';
1261 if (!inner_pos.empty())
1262 ss << '[' << inner_pos << ']';
1263 ss << '{' << latex_width << '}';
1264 if (!(inner_flags & FLAG_END))
1267 if (inner_type == "shaded")
1268 ss << "\\begin{shaded}";
1269 output_ert_inset(os, ss.str(), parent_context);
1270 if (!inner_type.empty()) {
1271 parse_text(p, os, inner_flags, outer, parent_context);
1272 if (inner_flags & FLAG_END)
1273 output_ert_inset(os, "\\end{" + inner_type + '}',
1276 output_ert_inset(os, "}", parent_context);
1278 if (!outer_type.empty()) {
1279 // If we already read the inner box we have to pop
1281 if (!inner_type.empty() && (inner_flags & FLAG_END))
1282 active_environments.pop_back();
1284 // Ensure that the end of the outer box is parsed correctly:
1285 // The opening brace has been eaten by parse_outer_box()
1286 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1287 outer_flags &= ~FLAG_ITEM;
1288 outer_flags |= FLAG_BRACE_LAST;
1290 parse_text(p, os, outer_flags, outer, parent_context);
1291 if (outer_flags & FLAG_END)
1292 output_ert_inset(os, "\\end{" + outer_type + '}',
1295 output_ert_inset(os, "}", parent_context);
1298 // LyX does not like empty positions, so we have
1299 // to set them to the LaTeX default values here.
1300 if (position.empty())
1302 if (inner_pos.empty())
1303 inner_pos = position;
1304 parent_context.check_layout(os);
1305 begin_inset(os, "Box ");
1306 if (outer_type == "framed")
1308 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1310 else if (outer_type == "shadowbox")
1311 os << "Shadowbox\n";
1312 else if ((outer_type == "shaded" && inner_type.empty()) ||
1313 (outer_type == "minipage" && inner_type == "shaded") ||
1314 (outer_type == "parbox" && inner_type == "shaded")) {
1316 preamble.registerAutomaticallyLoadedPackage("color");
1317 } else if (outer_type == "doublebox")
1318 os << "Doublebox\n";
1319 else if (outer_type.empty() || outer_type == "mbox")
1320 os << "Frameless\n";
1322 os << outer_type << '\n';
1323 os << "position \"" << position << "\"\n";
1324 os << "hor_pos \"" << hor_pos << "\"\n";
1325 if (outer_type == "mbox")
1326 os << "has_inner_box 1\n";
1327 else if (!frame_color.empty() && inner_type == "makebox")
1328 os << "has_inner_box 0\n";
1330 os << "has_inner_box " << !inner_type.empty() << "\n";
1331 os << "inner_pos \"" << inner_pos << "\"\n";
1332 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1334 if (outer_type == "mbox")
1335 os << "use_makebox 1\n";
1336 else if (!frame_color.empty())
1337 os << "use_makebox 0\n";
1339 os << "use_makebox " << (inner_type == "makebox") << '\n';
1340 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1341 os << "width \"\"\n";
1342 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1343 else if (contains(width_unit, '\\'))
1344 os << "width \"" << width_value << "in" << "\"\n";
1346 os << "width \"" << width_value << width_unit << "\"\n";
1347 if (contains(width_unit, '\\')) {
1348 width_unit.erase (0,1); // remove the leading '\'
1349 os << "special \"" << width_unit << "\"\n";
1351 os << "special \"" << width_special << "\"\n";
1352 if (contains(height_unit, '\\'))
1353 os << "height \"" << height_value << "in" << "\"\n";
1355 os << "height \"" << height_value << height_unit << "\"\n";
1356 os << "height_special \"" << height_special << "\"\n";
1357 os << "thickness \"" << thickness << "\"\n";
1358 os << "separation \"" << separation << "\"\n";
1359 os << "shadowsize \"" << shadowsize << "\"\n";
1360 os << "framecolor \"" << framecolor << "\"\n";
1361 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1362 os << "status open\n\n";
1364 // Unfortunately we can't use parse_text_in_inset:
1365 // InsetBox::forcePlainLayout() is hard coded and does not
1366 // use the inset layout. Apart from that do we call parse_text
1367 // up to two times, but need only one check_end_layout.
1368 bool const forcePlainLayout =
1369 (!inner_type.empty() || inner_type == "makebox") &&
1370 outer_type != "shaded" && outer_type != "framed";
1371 Context context(true, parent_context.textclass);
1372 if (forcePlainLayout)
1373 context.layout = &context.textclass.plainLayout();
1375 context.font = parent_context.font;
1377 // If we have no inner box the contents will be read with the outer box
1378 if (!inner_type.empty())
1379 parse_text(p, os, inner_flags, outer, context);
1381 // Ensure that the end of the outer box is parsed correctly:
1382 // The opening brace has been eaten by parse_outer_box()
1383 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1384 outer_flags &= ~FLAG_ITEM;
1385 outer_flags |= FLAG_BRACE_LAST;
1388 // Find end of outer box, output contents if inner_type is
1389 // empty and output possible comments
1390 if (!outer_type.empty()) {
1391 // If we already read the inner box we have to pop
1393 if (!inner_type.empty() && (inner_flags & FLAG_END))
1394 active_environments.pop_back();
1395 // This does not output anything but comments if
1396 // inner_type is not empty (see use_ert)
1397 parse_text(p, os, outer_flags, outer, context);
1400 context.check_end_layout(os);
1402 #ifdef PRESERVE_LAYOUT
1403 // LyX puts a % after the end of the minipage
1404 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1406 //output_comment(p, os, "dummy", parent_context);
1409 parent_context.new_paragraph(os);
1411 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1412 //output_comment(p, os, "dummy", parent_context);
1415 // We add a protected space if something real follows
1416 if (p.good() && p.next_token().cat() != catComment) {
1417 begin_inset(os, "space ~\n");
1423 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1424 active_environments.pop_back();
1425 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1426 // in this case we have to eat the the closing brace of the color box
1427 p.get_token().asInput(); // the '}'
1429 if (p.next_token().asInput() == "}") {
1430 // in this case we assume that the closing brace is from the box settings
1431 // therefore reset these values for the next box
1437 // all boxes except of Frameless and Shaded require calc
1438 if (!(outer_type.empty() || outer_type == "mbox") &&
1439 !((outer_type == "shaded" && inner_type.empty()) ||
1440 (outer_type == "minipage" && inner_type == "shaded") ||
1441 (outer_type == "parbox" && inner_type == "shaded")))
1442 preamble.registerAutomaticallyLoadedPackage("calc");
1446 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1447 Context & parent_context, string const & outer_type,
1448 string const & special)
1450 eat_whitespace(p, os, parent_context, false);
1451 if (flags & FLAG_ITEM) {
1453 if (p.next_token().cat() == catBegin)
1456 warning_message("Ignoring missing '{' after \\"
1457 + outer_type + '.');
1458 eat_whitespace(p, os, parent_context, false);
1461 unsigned int inner_flags = 0;
1463 if (outer_type == "minipage" || outer_type == "parbox") {
1464 p.skip_spaces(true);
1465 while (p.hasOpt()) {
1467 p.skip_spaces(true);
1470 p.skip_spaces(true);
1471 if (outer_type == "parbox") {
1473 if (p.next_token().cat() == catBegin)
1475 p.skip_spaces(true);
1478 if (outer_type == "shaded" || outer_type == "mbox") {
1479 // These boxes never have an inner box
1481 } else if (p.next_token().asInput() == "\\parbox") {
1482 inner = p.get_token().cs();
1483 inner_flags = FLAG_ITEM;
1484 } else if (p.next_token().asInput() == "\\begin") {
1485 // Is this a minipage or shaded box?
1488 inner = p.getArg('{', '}');
1490 if (inner == "minipage" || inner == "shaded")
1491 inner_flags = FLAG_END;
1496 if (inner_flags == FLAG_END) {
1497 if (inner != "shaded")
1501 eat_whitespace(p, os, parent_context, false);
1503 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1504 outer_type, special, inner, "", "");
1506 if (inner_flags == FLAG_ITEM) {
1508 eat_whitespace(p, os, parent_context, false);
1510 parse_box(p, os, flags, inner_flags, outer, parent_context,
1511 outer_type, special, inner, "", "");
1516 void parse_index_entry(Parser & p, ostream & os, Context & context, string const & kind)
1518 // write inset header
1519 begin_inset(os, "Index ");
1522 // Parse for post argument (|...)
1524 string const marg = p.getArg('{', '}');
1527 bool inpost = false;
1528 bool startrange = false;
1529 bool endrange = false;
1531 for (string::const_iterator it = marg.begin(), et = marg.end(); it != et; ++it) {
1534 if (post.empty() && c == '(')
1536 else if (post.empty() && c == ')')
1541 if (!inpost && (c == '|' && lc != '"'))
1546 os << "\nrange start";
1548 os << "\nrange end";
1550 os << "\nrange none";
1551 bool const see = prefixIs(post, "see{");
1552 bool const seealso = prefixIs(post, "seealso{");
1553 if (!post.empty() && !see && !seealso)
1554 os << "\npageformat " << post;
1556 os << "\npageformat default";
1557 os << "\nstatus collapsed\n";
1563 if (p.hasIdxMacros("!")) {
1564 // Index entry with levels
1565 while (p.hasIdxMacros("!")) {
1569 os << "\\begin_layout Plain Layout\n";
1571 begin_inset(os, "IndexMacro subentry");
1572 os << "\nstatus collapsed\n";
1574 // Check for (level-specific) sortkey
1575 if (p.hasIdxMacros("@", "!")) {
1577 os << "\\begin_layout Plain Layout\n";
1578 begin_inset(os, "IndexMacro sortkey");
1579 os << "\nstatus collapsed\n";
1580 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1583 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "!", "\"");
1585 os << "\n\\end_layout\n";
1591 begin_inset(os, "IndexMacro subentry");
1592 os << "\nstatus collapsed\n";
1595 // Check for (level-specific) sortkey
1596 if (p.hasIdxMacros("@", "!")) {
1601 os << "\\begin_layout Plain Layout\n";
1602 begin_inset(os, "IndexMacro sortkey");
1603 os << "\nstatus collapsed\n";
1604 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1606 if (post.empty() && !startrange && !endrange) {
1607 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1610 // Handle post-argument
1611 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1612 if (see || seealso) {
1613 while (p.next_token().character() != '{' && p.good())
1615 // this ends the subinset, as the see[also] insets
1616 // must come at main index inset
1617 os << "\n\\end_layout\n";
1620 begin_inset(os, "IndexMacro see");
1622 begin_inset(os, "IndexMacro seealso");
1623 os << "\nstatus collapsed\n";
1624 os << "\\begin_layout Plain Layout\n";
1625 parse_text_snippet(p, os, FLAG_ITEM, false, context);
1631 os << "\n\\end_layout\n";
1633 if (post.empty() && !startrange && !endrange) {
1634 parse_text_in_inset(p, os, FLAG_BRACE_LAST, false, context, "IndexMacro subentry");
1637 // Handle post-argument
1638 if (see || seealso) {
1639 os << "\\begin_layout Plain Layout\n";
1640 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1641 while (p.next_token().character() != '{' && p.good())
1643 // this ends the subinset, as the see[also] insets
1644 // must come at main index inset
1645 os << "\n\\end_layout\n";
1648 begin_inset(os, "IndexMacro see");
1650 begin_inset(os, "IndexMacro seealso");
1651 os << "\nstatus collapsed\n";
1652 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1654 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1662 os << "\n\\end_layout\n";
1664 // Index without any levels
1665 // Check for sortkey
1666 if (p.hasIdxMacros("@", "!")) {
1669 os << "\\begin_layout Plain Layout\n";
1670 begin_inset(os, "IndexMacro sortkey");
1671 os << "\nstatus collapsed\n";
1672 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1674 if (post.empty() && !startrange && !endrange) {
1675 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1678 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1679 if (see || seealso) {
1680 while (p.next_token().character() != '{' && p.good())
1683 begin_inset(os, "IndexMacro see");
1685 begin_inset(os, "IndexMacro seealso");
1686 os << "\nstatus collapsed\n";
1687 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1694 os << "\n\\end_layout\n";
1696 if (post.empty() && !startrange && !endrange) {
1697 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
1700 // Handle post-argument
1703 if (see || seealso) {
1704 os << "\\begin_layout Plain Layout\n";
1705 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1706 while (p.next_token().character() != '{' && p.good())
1709 begin_inset(os, "IndexMacro see");
1711 begin_inset(os, "IndexMacro seealso");
1712 os << "\nstatus collapsed\n";
1713 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1715 os << "\n\\end_layout\n";
1717 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1728 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1729 bool in_line, bool use_minted)
1731 parent_context.check_layout(os);
1732 begin_inset(os, "listings\n");
1733 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1735 while ((i = arg.find(", ")) != string::npos
1736 || (i = arg.find(",\t")) != string::npos)
1737 arg.erase(i + 1, 1);
1740 string const language = p.getArg('{', '}');
1741 p.skip_spaces(true);
1742 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1743 if (!minted_float.empty()) {
1744 arg += string(arg.empty() ? "" : ",") + minted_float;
1745 minted_nonfloat_caption.clear();
1749 os << "lstparams " << '"' << arg << '"' << '\n';
1750 if (arg.find("\\color") != string::npos)
1751 preamble.registerAutomaticallyLoadedPackage("color");
1754 os << "inline true\n";
1756 os << "inline false\n";
1757 os << "status open\n";
1758 Context context(true, parent_context.textclass);
1759 context.layout = &parent_context.textclass.plainLayout();
1760 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1761 minted_nonfloat_caption.erase(0,3);
1762 os << "\n\\begin_layout Plain Layout\n";
1763 begin_inset(os, "Caption Standard\n");
1764 Context newcontext(true, context.textclass,
1765 context.layout, 0, context.font);
1766 newcontext.check_layout(os);
1767 os << minted_nonfloat_caption << "\n";
1768 newcontext.check_end_layout(os);
1770 os << "\n\\end_layout\n";
1771 minted_nonfloat_caption.clear();
1775 // set catcodes to verbatim early, just in case.
1776 p.setCatcodes(VERBATIM_CATCODES);
1777 string delim = p.get_token().asInput();
1778 //FIXME: handler error condition
1779 s = p.verbatimStuff(delim).second;
1780 // context.new_paragraph(os);
1781 } else if (use_minted) {
1782 s = p.verbatimEnvironment("minted");
1784 s = p.verbatimEnvironment("lstlisting");
1786 output_ert(os, s, context);
1787 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1788 minted_nonfloat_caption.erase(0,3);
1789 os << "\n\\begin_layout Plain Layout\n";
1790 begin_inset(os, "Caption Standard\n");
1791 Context newcontext(true, context.textclass,
1792 context.layout, 0, context.font);
1793 newcontext.check_layout(os);
1794 os << minted_nonfloat_caption << "\n";
1795 newcontext.check_end_layout(os);
1797 os << "\n\\end_layout\n";
1798 minted_nonfloat_caption.clear();
1800 // Don't close the inset here for floating minted listings.
1801 // It will be closed at the end of the listing environment.
1802 if (!use_minted || minted_float.empty())
1805 eat_whitespace(p, os, parent_context, true);
1806 Token t = p.get_token();
1807 if (t.asInput() != "\\end") {
1808 // If anything follows, collect it into a caption.
1809 minted_float_has_caption = true;
1810 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1811 begin_inset(os, "Caption Standard\n");
1812 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1819 /// parse an unknown environment
1820 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1821 unsigned flags, bool outer,
1822 Context & parent_context)
1824 if (name == "tabbing")
1825 // We need to remember that we have to handle '\=' specially
1826 flags |= FLAG_TABBING;
1828 // We need to translate font changes and paragraphs inside the
1829 // environment to ERT if we have a non standard font.
1830 // Otherwise things like
1831 // \large\begin{foo}\huge bar\end{foo}
1833 bool const specialfont =
1834 (parent_context.font != parent_context.normalfont);
1835 bool const new_layout_allowed = parent_context.new_layout_allowed;
1837 parent_context.new_layout_allowed = false;
1838 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1839 // Try to handle options: Look if we have optional arguments,
1840 // and if so, put the brackets in ERT.
1841 while (p.hasOpt()) {
1842 p.get_token(); // eat '['
1843 output_ert_inset(os, "[", parent_context);
1844 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1845 output_ert_inset(os, "]", parent_context);
1847 parse_text_snippet(p, os, flags, outer, parent_context);
1848 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1850 parent_context.new_layout_allowed = new_layout_allowed;
1854 void parse_environment(Parser & p, ostream & os, bool outer,
1855 string & last_env, Context & parent_context)
1857 Layout const * newlayout;
1858 InsetLayout const * newinsetlayout = 0;
1859 string const name = p.getArg('{', '}');
1860 const bool is_starred = suffixIs(name, '*');
1861 string const unstarred_name = rtrim(name, "*");
1862 active_environments.push_back(name);
1864 // We use this loop and break out after a condition is met
1865 // rather than a huge else-if-chain.
1867 if (is_math_env(name)) {
1868 parent_context.check_layout(os);
1869 begin_inset(os, "Formula ");
1870 os << "\\begin{" << name << "}";
1871 parse_math(p, os, FLAG_END, MATH_MODE);
1872 os << "\\end{" << name << "}";
1874 if (is_display_math_env(name)) {
1875 // Prevent the conversion of a line break to a space
1876 // (bug 7668). This does not change the output, but
1877 // looks ugly in LyX.
1878 eat_whitespace(p, os, parent_context, false);
1883 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1884 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1885 // We must begin a new paragraph if not already done
1886 if (!parent_context.atParagraphStart()) {
1887 parent_context.check_end_layout(os);
1888 parent_context.new_paragraph(os);
1890 // store previous language because we must reset it at the end
1891 string const lang_old = parent_context.font.language;
1892 // save new language in context so that it is
1893 // handled by parse_text
1894 parent_context.font.language =
1895 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1896 parse_text(p, os, FLAG_END, outer, parent_context);
1897 // reset previous language
1898 parent_context.font.language = lang_old;
1899 // Just in case the environment is empty
1900 parent_context.extra_stuff.erase();
1901 // We must begin a new paragraph to reset the language
1902 parent_context.new_paragraph(os);
1907 if (unstarred_name == "tabular" || name == "longtable"
1908 || name == "tabularx" || name == "xltabular") {
1909 eat_whitespace(p, os, parent_context, false);
1910 string width = "0pt";
1912 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1913 string const opt = p.getArg('[', ']');
1916 else if (opt == "l")
1918 else if (opt == "r")
1921 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1922 width = lyx::translate_len(p.getArg('{', '}'));
1923 eat_whitespace(p, os, parent_context, false);
1925 parent_context.check_layout(os);
1926 begin_inset(os, "Tabular ");
1927 handle_tabular(p, os, name, width, halign, parent_context);
1933 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1934 eat_whitespace(p, os, parent_context, false);
1935 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1936 eat_whitespace(p, os, parent_context, false);
1937 parent_context.check_layout(os);
1938 begin_inset(os, "Float " + unstarred_name + "\n");
1939 // store the float type for subfloats
1940 // subfloats only work with figures and tables
1941 if (unstarred_name == "figure")
1942 float_type = unstarred_name;
1943 else if (unstarred_name == "table")
1944 float_type = unstarred_name;
1948 os << "placement " << opt << '\n';
1949 if (contains(opt, "H"))
1950 preamble.registerAutomaticallyLoadedPackage("float");
1952 Floating const & fl = parent_context.textclass.floats()
1953 .getType(unstarred_name);
1954 if (!fl.floattype().empty() && fl.usesFloatPkg())
1955 preamble.registerAutomaticallyLoadedPackage("float");
1958 os << "wide " << convert<string>(is_starred)
1959 << "\nsideways false"
1960 << "\nstatus open\n\n";
1961 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1962 if (unstarred_name == "algorithm")
1963 // in algorithm, \; has special meaning
1964 parent_context.pass_thru_cmds.insert(";");
1965 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1966 if (unstarred_name == "algorithm")
1967 parent_context.pass_thru_cmds = pass_thru_cmds;
1969 // We don't need really a new paragraph, but
1970 // we must make sure that the next item gets a \begin_layout.
1971 parent_context.new_paragraph(os);
1973 // the float is parsed thus delete the type
1978 if (unstarred_name == "sidewaysfigure"
1979 || unstarred_name == "sidewaystable"
1980 || unstarred_name == "sidewaysalgorithm") {
1981 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1982 eat_whitespace(p, os, parent_context, false);
1983 parent_context.check_layout(os);
1984 if (unstarred_name == "sidewaysfigure")
1985 begin_inset(os, "Float figure\n");
1986 else if (unstarred_name == "sidewaystable")
1987 begin_inset(os, "Float table\n");
1988 else if (unstarred_name == "sidewaysalgorithm")
1989 begin_inset(os, "Float algorithm\n");
1991 os << "placement " << opt << '\n';
1992 if (contains(opt, "H"))
1993 preamble.registerAutomaticallyLoadedPackage("float");
1994 os << "wide " << convert<string>(is_starred)
1995 << "\nsideways true"
1996 << "\nstatus open\n\n";
1997 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1999 // We don't need really a new paragraph, but
2000 // we must make sure that the next item gets a \begin_layout.
2001 parent_context.new_paragraph(os);
2003 preamble.registerAutomaticallyLoadedPackage("rotfloat");
2007 if (name == "wrapfigure" || name == "wraptable") {
2008 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
2009 eat_whitespace(p, os, parent_context, false);
2010 parent_context.check_layout(os);
2013 string overhang = "0col%";
2016 lines = p.getArg('[', ']');
2017 string const placement = p.getArg('{', '}');
2019 overhang = p.getArg('[', ']');
2020 string const width = p.getArg('{', '}');
2022 if (name == "wrapfigure")
2023 begin_inset(os, "Wrap figure\n");
2025 begin_inset(os, "Wrap table\n");
2026 os << "lines " << lines
2027 << "\nplacement " << placement
2028 << "\noverhang " << lyx::translate_len(overhang)
2029 << "\nwidth " << lyx::translate_len(width)
2030 << "\nstatus open\n\n";
2031 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2033 // We don't need really a new paragraph, but
2034 // we must make sure that the next item gets a \begin_layout.
2035 parent_context.new_paragraph(os);
2037 preamble.registerAutomaticallyLoadedPackage("wrapfig");
2041 if (name == "minipage") {
2042 eat_whitespace(p, os, parent_context, false);
2043 // Test whether this is an outer box of a shaded box
2045 // swallow arguments
2046 while (p.hasOpt()) {
2048 p.skip_spaces(true);
2051 p.skip_spaces(true);
2052 Token t = p.get_token();
2053 bool shaded = false;
2054 if (t.asInput() == "\\begin") {
2055 p.skip_spaces(true);
2056 if (p.getArg('{', '}') == "shaded")
2061 parse_outer_box(p, os, FLAG_END, outer,
2062 parent_context, name, "shaded");
2064 parse_box(p, os, 0, FLAG_END, outer, parent_context,
2065 "", "", name, "", "");
2070 if (name == "comment") {
2071 eat_whitespace(p, os, parent_context, false);
2072 parent_context.check_layout(os);
2073 begin_inset(os, "Note Comment\n");
2074 os << "status open\n";
2075 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2078 skip_braces(p); // eat {} that might by set by LyX behind comments
2079 preamble.registerAutomaticallyLoadedPackage("verbatim");
2083 if (unstarred_name == "verbatim") {
2084 // FIXME: this should go in the generic code that
2085 // handles environments defined in layout file that
2086 // have "PassThru 1". However, the code over there is
2087 // already too complicated for my taste.
2088 string const ascii_name =
2089 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
2090 parent_context.new_paragraph(os);
2091 Context context(true, parent_context.textclass,
2092 &parent_context.textclass[from_ascii(ascii_name)]);
2093 string s = p.verbatimEnvironment(name);
2094 output_ert(os, s, context);
2099 if (name == "IPA") {
2100 eat_whitespace(p, os, parent_context, false);
2101 parent_context.check_layout(os);
2102 begin_inset(os, "IPA\n");
2103 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
2104 // These commands have special meanings in IPA
2105 parent_context.pass_thru_cmds.insert("!");
2106 parent_context.pass_thru_cmds.insert(";");
2107 parent_context.pass_thru_cmds.insert(":");
2108 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2109 parent_context.pass_thru_cmds = pass_thru_cmds;
2112 preamble.registerAutomaticallyLoadedPackage("tipa");
2113 preamble.registerAutomaticallyLoadedPackage("tipx");
2117 if (name == parent_context.textclass.titlename()
2118 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
2119 parse_text(p, os, FLAG_END, outer, parent_context);
2120 // Just in case the environment is empty
2121 parent_context.extra_stuff.erase();
2122 // We must begin a new paragraph
2123 parent_context.new_paragraph(os);
2128 if (name == "CJK") {
2129 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
2130 // It is impossible to decide if a CJK environment was in its own paragraph or within
2131 // a line. We therefore always assume a paragraph since the latter is a rare case.
2132 eat_whitespace(p, os, parent_context, false);
2133 parent_context.check_end_layout(os);
2134 // store the encoding to be able to reset it
2135 string const encoding_old = p.getEncoding();
2136 string const encoding = p.getArg('{', '}');
2137 // FIXME: For some reason JIS does not work. Although the text
2138 // in tests/CJK.tex is identical with the SJIS version if you
2139 // convert both snippets using the recode command line utility,
2140 // the resulting .lyx file contains some extra characters if
2141 // you set buggy_encoding to false for JIS.
2142 bool const buggy_encoding = encoding == "JIS";
2143 if (!buggy_encoding)
2144 p.setEncoding(encoding, Encoding::CJK);
2146 // FIXME: This will read garbage, since the data is not encoded in utf8.
2147 p.setEncoding("UTF-8");
2149 // LyX only supports the same mapping for all CJK
2150 // environments, so we might need to output everything as ERT
2151 string const mapping = trim(p.getArg('{', '}'));
2152 char const * const * const where =
2153 is_known(encoding, supported_CJK_encodings);
2154 if (!buggy_encoding && !preamble.fontCJKSet())
2155 preamble.fontCJK(mapping);
2156 bool knownMapping = mapping == preamble.fontCJK();
2157 if (buggy_encoding || !knownMapping || !where) {
2158 parent_context.check_layout(os);
2159 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
2161 // we must parse the content as verbatim because e.g. JIS can contain
2162 // normally invalid characters
2163 // FIXME: This works only for the most simple cases.
2164 // Since TeX control characters are not parsed,
2165 // things like comments are completely wrong.
2166 string const s = p.plainEnvironment("CJK");
2167 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
2170 if (snip == "\\" || is_known(snip, known_escaped_chars))
2171 output_ert_inset(os, snip, parent_context);
2172 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
2177 output_ert_inset(os, "\\end{" + name + "}",
2181 supported_CJK_languages[where - supported_CJK_encodings];
2182 // store the language because we must reset it at the end
2183 string const lang_old = parent_context.font.language;
2184 parent_context.font.language = lang;
2185 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2186 parent_context.font.language = lang_old;
2187 parent_context.new_paragraph(os);
2189 p.setEncoding(encoding_old);
2194 if (name == "lyxgreyedout") {
2195 eat_whitespace(p, os, parent_context, false);
2196 parent_context.check_layout(os);
2197 begin_inset(os, "Note Greyedout\n");
2198 os << "status open\n";
2199 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2202 if (!preamble.notefontcolor().empty())
2203 preamble.registerAutomaticallyLoadedPackage("color");
2207 if (name == "btSect") {
2208 eat_whitespace(p, os, parent_context, false);
2209 parent_context.check_layout(os);
2210 begin_command_inset(os, "bibtex", "bibtex");
2211 string bibstyle = "plain";
2213 bibstyle = p.getArg('[', ']');
2214 p.skip_spaces(true);
2216 string const bibfile = p.getArg('{', '}');
2217 eat_whitespace(p, os, parent_context, false);
2218 Token t = p.get_token();
2219 if (t.asInput() == "\\btPrintCited") {
2220 p.skip_spaces(true);
2221 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2223 if (t.asInput() == "\\btPrintNotCited") {
2224 p.skip_spaces(true);
2225 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2227 if (t.asInput() == "\\btPrintAll") {
2228 p.skip_spaces(true);
2229 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2231 os << "bibfiles " << '"' << bibfile << "\"\n"
2232 << "options " << '"' << bibstyle << "\"\n";
2233 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2239 if (name == "btUnit") {
2240 string const nt = p.next_next_token().cs();
2241 // Do not attempt to overwrite a former diverging multibib.
2242 // Those are output as ERT instead.
2243 if ((nt == "part" || nt == "chapter"
2244 || nt == "section" || nt == "subsection")
2245 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2246 parse_text(p, os, FLAG_END, outer, parent_context);
2247 preamble.multibib(nt);
2249 parse_unknown_environment(p, name, os, FLAG_END, outer,
2254 // This is only attempted at turn environments that consist only
2255 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2256 // Thus we will fall through in other cases.
2257 if (name == "turn") {
2258 // We check if the next thing is a tabular[*|x]
2260 p.getArg('{', '}');// eat turn argument
2261 bool found_end = false;
2262 bool only_table = false;
2263 bool end_table = false;
2266 string envname = p.getArg('{', '}');
2267 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2268 // Now we check if the table is the only content
2269 // of the turn environment
2270 string const tenv = envname;
2271 while (!found_end && !end_table && p.good()) {
2272 envname = p.next_token().cat() == catBegin
2273 ? p.getArg('{', '}') : string();
2274 Token const & t = p.get_token();
2276 end_table = t.asInput() != "\\end"
2278 found_end = t.asInput() == "\\end"
2279 && envname == "turn";
2283 envname = p.getArg('{', '}');
2284 only_table = p.next_next_token().asInput() == "\\end"
2285 && envname == "turn";
2289 string const angle = p.getArg('{', '}');
2291 int const save_tablerotation = parent_context.tablerotation;
2292 parent_context.tablerotation = convert<int>(angle);
2293 parse_text(p, os, FLAG_END, outer, parent_context);
2294 parent_context.tablerotation = save_tablerotation;
2304 // This is only attempted at landscape environments that consist only
2305 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2306 // Other landscape environment is handled via the landscape module, thus
2307 // we will fall through in that case.
2308 if (name == "landscape") {
2309 // We check if the next thing is a longtable
2311 bool found_end = false;
2312 bool only_longtable = false;
2313 bool end_longtable = false;
2316 string envname = p.getArg('{', '}');
2317 if (envname == "longtable" || envname == "xltabular") {
2318 // Now we check if the longtable is the only content
2319 // of the landscape environment
2320 string const ltenv = envname;
2321 while (!found_end && !end_longtable && p.good()) {
2322 envname = p.next_token().cat() == catBegin
2323 ? p.getArg('{', '}') : string();
2324 Token const & t = p.get_token();
2326 end_longtable = t.asInput() != "\\end"
2327 && envname == ltenv;
2328 found_end = t.asInput() == "\\end"
2329 && envname == "landscape";
2331 if (end_longtable) {
2333 envname = p.getArg('{', '}');
2334 only_longtable = p.next_next_token().asInput() == "\\end"
2335 && envname == "landscape";
2337 if (only_longtable) {
2340 int const save_tablerotation = parent_context.tablerotation;
2341 parent_context.tablerotation = 90;
2342 parse_text(p, os, FLAG_END, outer, parent_context);
2343 parent_context.tablerotation = save_tablerotation;
2353 if (name == "framed" || name == "shaded") {
2354 eat_whitespace(p, os, parent_context, false);
2355 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2357 preamble.registerAutomaticallyLoadedPackage("framed");
2361 if (name == "listing") {
2362 minted_float = "float";
2363 eat_whitespace(p, os, parent_context, false);
2364 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2366 minted_float += "=" + opt;
2367 // If something precedes \begin{minted}, we output it at the end
2368 // as a caption, in order to keep it inside the listings inset.
2369 eat_whitespace(p, os, parent_context, true);
2371 Token const & t = p.get_token();
2372 p.skip_spaces(true);
2373 string const envname = p.next_token().cat() == catBegin
2374 ? p.getArg('{', '}') : string();
2375 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2377 minted_float_has_caption = false;
2378 string content = parse_text_snippet(p, FLAG_END, outer,
2380 size_t i = content.find("\\begin_inset listings");
2381 bool minted_env = i != string::npos;
2384 caption = content.substr(0, i);
2385 content.erase(0, i);
2387 parent_context.check_layout(os);
2388 if (minted_env && minted_float_has_caption) {
2389 eat_whitespace(p, os, parent_context, true);
2390 os << content << "\n";
2391 if (!caption.empty())
2392 os << caption << "\n";
2393 os << "\n\\end_layout\n"; // close inner layout
2394 end_inset(os); // close caption inset
2395 os << "\n\\end_layout\n"; // close outer layout
2396 } else if (!caption.empty()) {
2398 begin_inset(os, "listings\n");
2399 os << "lstparams " << '"' << minted_float << '"' << '\n';
2400 os << "inline false\n";
2401 os << "status collapsed\n";
2403 os << "\n\\begin_layout Plain Layout\n";
2404 begin_inset(os, "Caption Standard\n");
2405 Context newcontext(true, parent_context.textclass,
2406 0, 0, parent_context.font);
2407 newcontext.check_layout(os);
2408 os << caption << "\n";
2409 newcontext.check_end_layout(os);
2411 os << "\n\\end_layout\n";
2412 } else if (content.empty()) {
2413 begin_inset(os, "listings\n");
2414 os << "lstparams " << '"' << minted_float << '"' << '\n';
2415 os << "inline false\n";
2416 os << "status collapsed\n";
2418 os << content << "\n";
2420 end_inset(os); // close listings inset
2421 parent_context.check_end_layout(os);
2422 parent_context.new_paragraph(os);
2424 minted_float.clear();
2425 minted_float_has_caption = false;
2429 if (name == "lstlisting" || name == "minted") {
2430 bool use_minted = name == "minted";
2431 // with listings, we do not eat newlines here since
2432 // \begin{lstlistings}
2435 // // \begin{lstlistings}%
2438 // reads [foo] as content, whereas
2439 // // \begin{lstlistings}%
2442 // \begin{lstlistings}[foo,
2444 // reads [foo...] as argument.
2445 eat_whitespace(p, os, parent_context, false, use_minted);
2446 if (use_minted && minted_float.empty()) {
2447 // look ahead for a bottom caption
2449 bool found_end_minted = false;
2450 while (!found_end_minted && p.good()) {
2451 Token const & t = p.get_token();
2453 string const envname =
2454 p.next_token().cat() == catBegin
2455 ? p.getArg('{', '}') : string();
2456 found_end_minted = t.asInput() == "\\end"
2457 && envname == "minted";
2459 eat_whitespace(p, os, parent_context, true);
2460 Token const & t = p.get_token();
2461 p.skip_spaces(true);
2462 if (t.asInput() == "\\lyxmintcaption") {
2463 string const pos = p.getArg('[', ']');
2465 string const caption =
2466 parse_text_snippet(p, FLAG_ITEM,
2467 false, parent_context);
2468 minted_nonfloat_caption = "[b]" + caption;
2469 eat_whitespace(p, os, parent_context, true);
2474 parse_listings(p, os, parent_context, false, use_minted);
2479 if (!parent_context.new_layout_allowed) {
2480 parse_unknown_environment(p, name, os, FLAG_END, outer,
2485 // Alignment and spacing settings
2486 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2487 // therefore are totally broken!
2488 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2489 // they are commands not environments. They are furthermore switches that
2490 // can be ended by another switches, but also by commands like \footnote or
2491 // \parbox. So the only safe way is to leave them untouched.
2492 // However, we support the pseudo-environments
2493 // \begin{centering} ... \end{centering}
2494 // \begin{raggedright} ... \end{raggedright}
2495 // \begin{raggedleft} ... \end{raggedleft}
2496 // since they are used by LyX in floats (for spacing reasons)
2497 if (name == "center" || name == "centering"
2498 || name == "flushleft" || name == "raggedright"
2499 || name == "flushright" || name == "raggedleft"
2500 || name == "singlespace" || name == "onehalfspace"
2501 || name == "doublespace" || name == "spacing") {
2502 eat_whitespace(p, os, parent_context, false);
2503 // We must begin a new paragraph if not already done
2504 if (! parent_context.atParagraphStart()) {
2505 parent_context.check_end_layout(os);
2506 parent_context.new_paragraph(os);
2508 if (name == "flushleft" || name == "raggedright")
2509 parent_context.add_extra_stuff("\\align left\n");
2510 else if (name == "flushright" || name == "raggedleft")
2511 parent_context.add_extra_stuff("\\align right\n");
2512 else if (name == "center" || name == "centering")
2513 parent_context.add_extra_stuff("\\align center\n");
2514 else if (name == "singlespace")
2515 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2516 else if (name == "onehalfspace") {
2517 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2518 preamble.registerAutomaticallyLoadedPackage("setspace");
2519 } else if (name == "doublespace") {
2520 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2521 preamble.registerAutomaticallyLoadedPackage("setspace");
2522 } else if (name == "spacing") {
2523 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2524 preamble.registerAutomaticallyLoadedPackage("setspace");
2526 parse_text(p, os, FLAG_END, outer, parent_context);
2527 // Just in case the environment is empty
2528 parent_context.extra_stuff.erase();
2529 // We must begin a new paragraph to reset the alignment
2530 parent_context.new_paragraph(os);
2535 // The single '=' is meant here.
2536 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2537 eat_whitespace(p, os, parent_context, false);
2538 Context context(true, parent_context.textclass, newlayout,
2539 parent_context.layout, parent_context.font);
2540 if (parent_context.deeper_paragraph) {
2541 // We are beginning a nested environment after a
2542 // deeper paragraph inside the outer list environment.
2543 // Therefore we don't need to output a "begin deeper".
2544 context.need_end_deeper = true;
2546 parent_context.check_end_layout(os);
2547 if (last_env == name) {
2548 // we need to output a separator since LyX would export
2549 // the two environments as one otherwise (bug 5716)
2550 TeX2LyXDocClass const & textclass(parent_context.textclass);
2551 Context newcontext(true, textclass,
2552 &(textclass.defaultLayout()));
2553 newcontext.check_layout(os);
2554 begin_inset(os, "Separator plain\n");
2556 newcontext.check_end_layout(os);
2558 switch (context.layout->latextype) {
2559 case LATEX_LIST_ENVIRONMENT:
2560 context.in_list_preamble =
2561 !context.layout->listpreamble().empty()
2562 && p.hasListPreamble(context.layout->itemcommand());
2563 context.add_par_extra_stuff("\\labelwidthstring "
2564 + p.verbatim_item() + '\n');
2567 case LATEX_BIB_ENVIRONMENT:
2568 p.verbatim_item(); // swallow next arg
2574 context.check_deeper(os);
2575 if (newlayout->keepempty) {
2576 // We need to start a new paragraph
2577 // even if it is empty.
2578 context.new_paragraph(os);
2579 context.check_layout(os);
2581 // handle known optional and required arguments
2582 if (context.layout->latextype == LATEX_ENVIRONMENT)
2583 output_arguments(os, p, outer, false, string(), context,
2584 context.layout->latexargs());
2585 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2586 context.in_list_preamble =
2587 !context.layout->listpreamble().empty()
2588 && p.hasListPreamble(context.layout->itemcommand());
2590 output_arguments(oss, p, outer, false, string(), context,
2591 context.layout->latexargs());
2592 context.list_extra_stuff = oss.str();
2594 if (context.in_list_preamble) {
2595 // Collect the stuff between \begin and first \item
2596 context.list_preamble =
2597 parse_text_snippet(p, FLAG_END, outer, context);
2598 context.in_list_preamble = false;
2600 parse_text(p, os, FLAG_END, outer, context);
2601 if (context.layout->latextype == LATEX_ENVIRONMENT)
2602 output_arguments(os, p, outer, false, "post", context,
2603 context.layout->postcommandargs());
2604 context.check_end_layout(os);
2605 if (parent_context.deeper_paragraph) {
2606 // We must suppress the "end deeper" because we
2607 // suppressed the "begin deeper" above.
2608 context.need_end_deeper = false;
2610 context.check_end_deeper(os);
2611 parent_context.new_paragraph(os);
2613 if (!preamble.titleLayoutFound())
2614 preamble.titleLayoutFound(newlayout->intitle);
2615 set<string> const & req = newlayout->required();
2616 set<string>::const_iterator it = req.begin();
2617 set<string>::const_iterator en = req.end();
2618 for (; it != en; ++it)
2619 preamble.registerAutomaticallyLoadedPackage(*it);
2623 // The single '=' is meant here.
2624 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2625 eat_whitespace(p, os, parent_context, false);
2626 parent_context.check_layout(os);
2627 begin_inset(os, "Flex ");
2628 docstring flex_name = newinsetlayout->name();
2629 // FIXME: what do we do if the prefix is not Flex: ?
2630 if (prefixIs(flex_name, from_ascii("Flex:")))
2631 flex_name.erase(0, 5);
2632 os << to_utf8(flex_name) << '\n'
2633 << "status collapsed\n";
2634 if (newinsetlayout->isPassThru()) {
2635 string const arg = p.verbatimEnvironment(name);
2636 Context context(true, parent_context.textclass,
2637 &parent_context.textclass.plainLayout(),
2638 parent_context.layout);
2639 output_ert(os, arg, parent_context);
2641 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2646 if (name == "appendix") {
2647 // This is no good latex style, but it works and is used in some documents...
2648 eat_whitespace(p, os, parent_context, false);
2649 parent_context.check_end_layout(os);
2650 Context context(true, parent_context.textclass, parent_context.layout,
2651 parent_context.layout, parent_context.font);
2652 context.check_layout(os);
2653 os << "\\start_of_appendix\n";
2654 parse_text(p, os, FLAG_END, outer, context);
2655 context.check_end_layout(os);
2660 if (known_environments.find(name) != known_environments.end()) {
2661 vector<ArgumentType> arguments = known_environments[name];
2662 // The last "argument" denotes whether we may translate the
2663 // environment contents to LyX
2664 // The default required if no argument is given makes us
2665 // compatible with the reLyXre environment.
2666 ArgumentType contents = arguments.empty() ?
2669 if (!arguments.empty())
2670 arguments.pop_back();
2671 // See comment in parse_unknown_environment()
2672 bool const specialfont =
2673 (parent_context.font != parent_context.normalfont);
2674 bool const new_layout_allowed =
2675 parent_context.new_layout_allowed;
2677 parent_context.new_layout_allowed = false;
2678 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2679 outer, parent_context);
2680 if (contents == verbatim)
2681 output_ert_inset(os, p.ertEnvironment(name),
2684 parse_text_snippet(p, os, FLAG_END, outer,
2686 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2688 parent_context.new_layout_allowed = new_layout_allowed;
2692 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2697 active_environments.pop_back();
2701 /// parses a comment and outputs it to \p os.
2702 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2703 bool skipNewlines = false)
2705 LASSERT(t.cat() == catComment, return);
2706 string comment = t.cs();
2707 // Join multiple consecutive comment lines into one ERT inset
2708 while (p.next_token().cat() == catComment)
2709 comment += "\n%" + p.get_token().cs();
2711 if (!comment.empty()) {
2712 context.check_layout(os);
2713 output_comment(p, os, comment, context);
2714 if (p.next_token().cat() == catNewline) {
2715 // A newline after a comment line starts a new
2717 if (context.new_layout_allowed) {
2718 if(!context.atParagraphStart())
2719 // Only start a new paragraph if not already
2720 // done (we might get called recursively)
2721 context.new_paragraph(os);
2723 output_ert_inset(os, "\n", context);
2724 eat_whitespace(p, os, context, true);
2726 } else if (!skipNewlines) {
2727 // "%\n" combination
2734 * Reads spaces and comments until the first non-space, non-comment token.
2735 * New paragraphs (double newlines or \\par) are handled like simple spaces
2736 * if \p eatParagraph is true.
2737 * If \p eatNewline is false, newlines won't be treated as whitespace.
2738 * Spaces are skipped, but comments are written to \p os.
2740 void eat_whitespace(Parser & p, ostream & os, Context & context,
2741 bool eatParagraph, bool eatNewline)
2744 Token const & t = p.get_token();
2745 if (t.cat() == catComment)
2746 parse_comment(p, os, t, context, !eatNewline);
2747 else if ((!eatParagraph && p.isParagraph()) ||
2748 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2757 * Set a font attribute, parse text and reset the font attribute.
2758 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2759 * \param currentvalue Current value of the attribute. Is set to the new
2760 * value during parsing.
2761 * \param newvalue New value of the attribute
2763 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2764 Context & context, string const & attribute,
2765 string & currentvalue, string const & newvalue)
2767 context.check_layout(os);
2768 string const oldvalue = currentvalue;
2769 currentvalue = newvalue;
2770 os << '\n' << attribute << ' ' << newvalue << "\n";
2771 parse_text_snippet(p, os, flags, outer, context);
2772 context.check_layout(os);
2773 os << '\n' << attribute << ' ' << oldvalue << "\n";
2774 currentvalue = oldvalue;
2778 /// get the arguments of a natbib or jurabib citation command
2779 void get_cite_arguments(Parser & p, bool natbibOrder,
2780 string & before, string & after, bool const qualified = false)
2782 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2784 // text before the citation
2786 // text after the citation
2787 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2789 if (!after.empty()) {
2790 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2791 if (natbibOrder && !before.empty())
2792 swap(before, after);
2797 void copy_file(FileName const & src, string const & dstname)
2801 string const absParent = getParentFilePath(false);
2803 if (FileName::isAbsolute(dstname))
2804 dst = FileName(dstname);
2806 dst = makeAbsPath(dstname, absParent);
2807 FileName const srcpath = src.onlyPath();
2808 FileName const dstpath = dst.onlyPath();
2809 if (equivalent(srcpath, dstpath))
2811 if (!dstpath.isDirectory()) {
2812 if (!dstpath.createPath()) {
2813 warning_message("Could not create directory for file `"
2814 + dst.absFileName() + "´.");
2818 if (dst.isReadableFile()) {
2819 if (overwriteFiles())
2820 warning_message("Overwriting existing file `"
2821 + dst.absFileName() + "´.");
2823 warning_message("Not overwriting existing file `"
2824 + dst.absFileName() + "´.");
2828 if (!src.copyTo(dst))
2829 warning_message("Could not copy file `" + src.absFileName()
2830 + "´ to `" + dst.absFileName() + "´.");
2834 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2835 bool parse_chunk(Parser & p, ostream & os, Context & context)
2837 // check whether a chunk is possible here.
2838 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2844 // read the parameters
2845 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2846 if (!params.first) {
2851 Parser::Arg const code = p.verbatimStuff("\n@");
2856 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2857 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2861 // The last newline read is important for paragraph handling
2865 //warning_message("params=[" + params.second + "], code=[" + code.second + "]");
2866 // We must have a valid layout before outputting the Chunk inset.
2867 context.check_layout(os);
2868 Context chunkcontext(true, context.textclass);
2869 chunkcontext.layout = &context.textclass.plainLayout();
2870 begin_inset(os, "Flex Chunk");
2871 os << "\nstatus open\n";
2872 if (!params.second.empty()) {
2873 chunkcontext.check_layout(os);
2874 Context paramscontext(true, context.textclass);
2875 paramscontext.layout = &context.textclass.plainLayout();
2876 begin_inset(os, "Argument 1");
2877 os << "\nstatus open\n";
2878 output_ert(os, params.second, paramscontext);
2881 output_ert(os, code.second, chunkcontext);
2889 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2890 bool is_macro(Parser & p)
2892 Token first = p.curr_token();
2893 if (first.cat() != catEscape || !p.good())
2895 if (first.cs() == "def")
2897 if (first.cs() != "global" && first.cs() != "long")
2899 Token second = p.get_token();
2901 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2902 second.cat() == catNewline || second.cat() == catComment)) {
2903 second = p.get_token();
2906 bool secondvalid = second.cat() == catEscape;
2908 bool thirdvalid = false;
2909 if (p.good() && first.cs() == "global" && secondvalid &&
2910 second.cs() == "long") {
2911 third = p.get_token();
2913 while (p.good() && !p.isParagraph() &&
2914 (third.cat() == catSpace ||
2915 third.cat() == catNewline ||
2916 third.cat() == catComment)) {
2917 third = p.get_token();
2920 thirdvalid = third.cat() == catEscape;
2922 for (int i = 0; i < pos; ++i)
2927 return (first.cs() == "global" || first.cs() == "long") &&
2928 second.cs() == "def";
2929 return first.cs() == "global" && second.cs() == "long" &&
2930 third.cs() == "def";
2934 /// Parse a macro definition (assumes that is_macro() returned true)
2935 void parse_macro(Parser & p, ostream & os, Context & context)
2937 context.check_layout(os);
2938 Token first = p.curr_token();
2941 string command = first.asInput();
2942 if (first.cs() != "def") {
2944 eat_whitespace(p, os, context, false);
2945 second = p.curr_token();
2946 command += second.asInput();
2947 if (second.cs() != "def") {
2949 eat_whitespace(p, os, context, false);
2950 third = p.curr_token();
2951 command += third.asInput();
2954 eat_whitespace(p, os, context, false);
2955 string const name = p.get_token().cs();
2956 eat_whitespace(p, os, context, false);
2962 while (p.next_token().cat() != catBegin) {
2963 if (p.next_token().cat() == catParameter) {
2968 // followed by number?
2969 if (p.next_token().cat() == catOther) {
2970 string s = p.get_token().asInput();
2972 // number = current arity + 1?
2973 if (s.size() == 1 && s[0] == arity + '0' + 1)
2978 paramtext += p.get_token().cs();
2980 paramtext += p.get_token().cs();
2985 // only output simple (i.e. compatible) macro as FormulaMacros
2986 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2988 context.check_layout(os);
2989 begin_inset(os, "FormulaMacro");
2990 os << "\n\\def" << ert;
2993 output_ert_inset(os, command + ert, context);
2997 void registerExternalTemplatePackages(string const & name)
2999 external::TemplateManager const & etm = external::TemplateManager::get();
3000 external::Template const * const et = etm.getTemplateByName(name);
3003 external::Template::Formats::const_iterator cit = et->formats.end();
3005 cit = et->formats.find("PDFLaTeX");
3006 if (cit == et->formats.end())
3007 // If the template has not specified a PDFLaTeX output,
3008 // we try the LaTeX format.
3009 cit = et->formats.find("LaTeX");
3010 if (cit == et->formats.end())
3012 vector<string>::const_iterator qit = cit->second.requirements.begin();
3013 vector<string>::const_iterator qend = cit->second.requirements.end();
3014 for (; qit != qend; ++qit)
3015 preamble.registerAutomaticallyLoadedPackage(*qit);
3018 } // anonymous namespace
3022 * Find a file with basename \p name in path \p path and an extension
3025 string find_file(string const & name, string const & path,
3026 char const * const * extensions)
3028 for (char const * const * what = extensions; *what; ++what) {
3029 string const trial = addExtension(name, *what);
3030 if (makeAbsPath(trial, path).exists())
3037 /// Convert filenames with TeX macros and/or quotes to something LyX
3039 string const normalize_filename(string const & name)
3044 Token const & t = p.get_token();
3045 if (t.cat() != catEscape)
3047 else if (t.cs() == "lyxdot") {
3048 // This is used by LyX for simple dots in relative
3052 } else if (t.cs() == "space") {
3055 } else if (t.cs() == "string") {
3056 // Convert \string" to " and \string~ to ~
3057 Token const & n = p.next_token();
3058 if (n.asInput() != "\"" && n.asInput() != "~")
3063 // Strip quotes. This is a bit complicated (see latex_path()).
3064 string full = os.str();
3065 if (!full.empty() && full[0] == '"') {
3066 string base = removeExtension(full);
3067 string ext = getExtension(full);
3068 if (!base.empty() && base[base.length()-1] == '"')
3071 return addExtension(trim(base, "\""), ext);
3072 if (full[full.length()-1] == '"')
3075 return trim(full, "\"");
3081 /// Convert \p name from TeX convention (relative to master file) to LyX
3082 /// convention (relative to .lyx file) if it is relative
3083 void fix_child_filename(string & name)
3085 string const absMasterTeX = getMasterFilePath(true);
3086 bool const isabs = FileName::isAbsolute(name);
3087 // convert from "relative to .tex master" to absolute original path
3089 name = makeAbsPath(name, absMasterTeX).absFileName();
3090 bool copyfile = copyFiles();
3091 string const absParentLyX = getParentFilePath(false);
3094 // convert from absolute original path to "relative to master file"
3095 string const rel = to_utf8(makeRelPath(from_utf8(name),
3096 from_utf8(absMasterTeX)));
3097 // re-interpret "relative to .tex file" as "relative to .lyx file"
3098 // (is different if the master .lyx file resides in a
3099 // different path than the master .tex file)
3100 string const absMasterLyX = getMasterFilePath(false);
3101 abs = makeAbsPath(rel, absMasterLyX).absFileName();
3102 // Do not copy if the new path is impossible to create. Example:
3103 // absMasterTeX = "/foo/bar/"
3104 // absMasterLyX = "/bar/"
3105 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
3106 if (contains(name, "/../"))
3113 // convert from absolute original path to
3114 // "relative to .lyx file"
3115 name = to_utf8(makeRelPath(from_utf8(abs),
3116 from_utf8(absParentLyX)));
3120 // convert from absolute original path to "relative to .lyx file"
3121 name = to_utf8(makeRelPath(from_utf8(name),
3122 from_utf8(absParentLyX)));
3127 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
3128 Context & context, string const & rdelim, string const & rdelimesc)
3130 Layout const * newlayout = 0;
3131 InsetLayout const * newinsetlayout = 0;
3132 char const * const * where = 0;
3133 // Store the latest bibliographystyle, addcontentslineContent and
3134 // nocite{*} option (needed for bibtex inset)
3136 string contentslineContent;
3137 // Some classes provide a \bibliographystyle, so do not output
3138 // any if none is explicitly set.
3139 string bibliographystyle;
3140 bool const use_natbib = isProvided("natbib");
3141 bool const use_jurabib = isProvided("jurabib");
3142 bool const use_biblatex = isProvided("biblatex")
3143 && preamble.citeEngine() != "biblatex-natbib";
3144 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
3145 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
3146 need_commentbib = use_biblatex || use_biblatex_natbib;
3149 // it is impossible to determine the correct encoding for non-CJK Japanese.
3150 // Therefore write a note at the beginning of the document
3151 if (is_nonCJKJapanese) {
3152 context.check_layout(os);
3153 begin_inset(os, "Note Note\n");
3154 os << "status open\n\\begin_layout Plain Layout\n"
3155 << "\\series bold\n"
3156 << "Important information:\n"
3157 << "\\end_layout\n\n"
3158 << "\\begin_layout Plain Layout\n"
3159 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
3160 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
3161 << " The iconv encoding " << p.getEncoding() << " was used.\n"
3162 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
3163 << " and specify the encoding using the -e command-line switch.\n"
3164 << " In addition, you might want to double check that the desired output encoding\n"
3165 << " is correctly selected in Document > Settings > Language.\n"
3166 << "\\end_layout\n";
3168 is_nonCJKJapanese = false;
3171 bool have_cycled = false;
3173 // Leave here only after at least one cycle
3174 if (have_cycled && flags & FLAG_LEAVE) {
3175 flags &= ~FLAG_LEAVE;
3179 Token const & t = p.get_token();
3181 debugToken(cerr, t, flags);
3184 if (context.in_list_preamble
3185 && p.next_token().cs() == context.layout->itemcommand()) {
3186 // We are parsing a list preamble. End before first \item.
3187 flags |= FLAG_LEAVE;
3188 context.in_list_preamble = false;
3191 if (flags & FLAG_ITEM) {
3192 if (t.cat() == catSpace)
3195 flags &= ~FLAG_ITEM;
3196 if (t.cat() == catBegin) {
3197 // skip the brace and collect everything to the next matching
3199 flags |= FLAG_BRACE_LAST;
3203 // handle only this single token, leave the loop if done
3204 flags |= FLAG_LEAVE;
3207 if (t.cat() != catEscape && t.character() == ']' &&
3208 (flags & FLAG_BRACK_LAST))
3210 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
3212 string tok = t.asInput();
3213 // we only support delimiters with max 2 chars for now.
3214 if (rdelim.size() > 1)
3215 tok += p.next_token().asInput();
3216 if (t.cat() != catEscape && !rdelim.empty()
3217 && tok == rdelim && (flags & FLAG_RDELIM)
3218 && (rdelimesc.empty() || p.prev_token().asInput() != rdelimesc)) {
3219 if (rdelim.size() > 1)
3220 p.get_token(); // eat rdelim
3224 // If there is anything between \end{env} and \begin{env} we
3225 // don't need to output a separator.
3226 if (t.cat() != catSpace && t.cat() != catNewline &&
3227 t.asInput() != "\\begin")
3234 bool const starred = p.next_token().asInput() == "*";
3235 string const starredname(starred ? (t.cs() + '*') : t.cs());
3236 if (t.cat() == catMath) {
3237 // we are inside some text mode thingy, so opening new math is allowed
3238 context.check_layout(os);
3239 begin_inset(os, "Formula ");
3240 Token const & n = p.get_token();
3241 bool const display(n.cat() == catMath && outer);
3243 // TeX's $$...$$ syntax for displayed math
3245 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3247 p.get_token(); // skip the second '$' token
3249 // simple $...$ stuff
3252 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3257 // Prevent the conversion of a line break to a
3258 // space (bug 7668). This does not change the
3259 // output, but looks ugly in LyX.
3260 eat_whitespace(p, os, context, false);
3265 if (t.cat() == catSuper || t.cat() == catSub) {
3266 string const cc = (t.cat() == catSuper) ? "catSuper" : "catSub";
3267 warning_message("catcode " + cc + " illegal in text mode");
3271 // Basic support for quotes. We try to disambiguate
3272 // quotes from the context (e.g., a left english quote is
3273 // the same as a right german quote...).
3274 // Try to make a smart guess about the side
3275 Token const prev = p.prev_token();
3276 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3277 && prev.character() != '\n' && prev.character() != '~');
3278 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3279 context.check_layout(os);
3280 begin_inset(os, "Quotes ");
3281 os << guessQuoteStyle("eld", opening);
3287 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3288 context.check_layout(os);
3289 begin_inset(os, "Quotes ");
3290 os << guessQuoteStyle("erd", opening);
3297 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3298 context.check_layout(os);
3299 begin_inset(os, "Quotes ");
3300 os << guessQuoteStyle("ald", opening);
3307 if (t.asInput() == "<"
3308 && p.next_token().asInput() == "<") {
3309 bool has_chunk = false;
3313 has_chunk = parse_chunk(p, os, context);
3319 context.check_layout(os);
3320 begin_inset(os, "Quotes ");
3321 os << guessQuoteStyle("ard", opening);
3329 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3330 check_space(p, os, context);
3334 // babel shorthands (also used by polyglossia)
3335 // Since these can have different meanings for different languages
3336 // we import them as ERT (but they must be put in ERT to get output
3338 if (t.asInput() == "\"") {
3340 // These are known pairs. We put them together in
3341 // one ERT inset. In other cases (such as "a), only
3342 // the quotation mark is ERTed.
3343 if (p.next_token().asInput() == "\""
3344 || p.next_token().asInput() == "|"
3345 || p.next_token().asInput() == "-"
3346 || p.next_token().asInput() == "~"
3347 || p.next_token().asInput() == "="
3348 || p.next_token().asInput() == "/"
3349 || p.next_token().asInput() == "~"
3350 || p.next_token().asInput() == "'"
3351 || p.next_token().asInput() == "`"
3352 || p.next_token().asInput() == "<"
3353 || p.next_token().asInput() == ">") {
3354 s += p.next_token().asInput();
3357 output_ert_inset(os, s, context);
3361 if (t.character() == '[' && noweb_mode &&
3362 p.next_token().character() == '[') {
3363 // These can contain underscores
3365 string const s = p.getFullOpt() + ']';
3366 if (p.next_token().character() == ']')
3369 warning_message("Inserting missing ']' in '" + s + "'.");
3370 output_ert_inset(os, s, context);
3374 if (t.cat() == catLetter) {
3375 context.check_layout(os);
3380 if (t.cat() == catOther ||
3381 t.cat() == catAlign ||
3382 t.cat() == catParameter) {
3383 context.check_layout(os);
3384 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3385 context.merging_hyphens_allowed &&
3386 context.font.family != "ttfamily" &&
3387 !context.layout->pass_thru) {
3388 if (p.next_next_token().asInput() == "-") {
3390 os << to_utf8(docstring(1, 0x2014));
3394 os << to_utf8(docstring(1, 0x2013));
3397 // This translates "&" to "\\&" which may be wrong...
3402 if (p.isParagraph()) {
3403 // In minted floating listings we will collect
3404 // everything into the caption, where multiple
3405 // paragraphs are forbidden.
3406 if (minted_float.empty()) {
3407 if (context.new_layout_allowed)
3408 context.new_paragraph(os);
3410 output_ert_inset(os, "\\par ", context);
3413 eat_whitespace(p, os, context, true);
3417 if (t.cat() == catActive) {
3418 context.check_layout(os);
3419 if (t.character() == '~') {
3420 if (context.layout->free_spacing)
3423 begin_inset(os, "space ~\n");
3431 if (t.cat() == catBegin) {
3432 Token const next = p.next_token();
3433 Token const end = p.next_next_token();
3434 if (next.cat() == catEnd) {
3436 Token const prev = p.prev_token();
3438 if (p.next_token().character() == '`')
3439 ; // ignore it in {}``
3441 output_ert_inset(os, "{}", context);
3442 } else if (next.cat() == catEscape &&
3443 is_known(next.cs(), known_quotes) &&
3444 end.cat() == catEnd) {
3445 // Something like {\textquoteright} (e.g.
3446 // from writer2latex). We may skip the
3447 // braces here for better readability.
3448 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3450 } else if (p.next_token().asInput() == "\\ascii") {
3451 // handle the \ascii characters
3452 // (the case without braces is handled later)
3453 // the code is "{\ascii\xxx}"
3454 p.get_token(); // eat \ascii
3455 string name2 = p.get_token().asInput();
3456 p.get_token(); // eat the final '}'
3457 string const name = "{\\ascii" + name2 + "}";
3461 // get the character from unicodesymbols
3462 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3463 Encodings::TEXT_CMD, termination, rem, &req);
3465 context.check_layout(os);
3468 output_ert_inset(os,
3469 to_utf8(rem), context);
3470 for (set<string>::const_iterator it = req.begin();
3471 it != req.end(); ++it)
3472 preamble.registerAutomaticallyLoadedPackage(*it);
3474 // we did not find a non-ert version
3475 output_ert_inset(os, name, context);
3477 context.check_layout(os);
3478 // special handling of font attribute changes
3479 Token const prev = p.prev_token();
3480 TeXFont const oldFont = context.font;
3481 if (next.character() == '[' ||
3482 next.character() == ']' ||
3483 next.character() == '*') {
3485 if (p.next_token().cat() == catEnd) {
3490 output_ert_inset(os, "{", context);
3491 parse_text_snippet(p, os,
3494 output_ert_inset(os, "}", context);
3496 } else if (! context.new_layout_allowed) {
3497 output_ert_inset(os, "{", context);
3498 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3500 output_ert_inset(os, "}", context);
3501 } else if (is_known(next.cs(), known_sizes)) {
3502 // next will change the size, so we must
3504 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3506 if (!context.atParagraphStart())
3508 << context.font.size << "\n";
3509 } else if (is_known(next.cs(), known_font_families)) {
3510 // next will change the font family, so we
3511 // must reset it here
3512 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3514 if (!context.atParagraphStart())
3516 << context.font.family << "\n";
3517 } else if (is_known(next.cs(), known_font_series)) {
3518 // next will change the font series, so we
3519 // must reset it here
3520 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3522 if (!context.atParagraphStart())
3524 << context.font.series << "\n";
3525 } else if (is_known(next.cs(), known_font_shapes)) {
3526 // next will change the font shape, so we
3527 // must reset it here
3528 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3530 if (!context.atParagraphStart())
3532 << context.font.shape << "\n";
3533 } else if (is_known(next.cs(), known_old_font_families) ||
3534 is_known(next.cs(), known_old_font_series) ||
3535 is_known(next.cs(), known_old_font_shapes)) {
3536 // next will change the font family, series
3537 // and shape, so we must reset it here
3538 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3540 if (!context.atParagraphStart())
3542 << context.font.family
3544 << context.font.series
3546 << context.font.shape << "\n";
3548 output_ert_inset(os, "{", context);
3549 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3551 output_ert_inset(os, "}", context);
3557 if (t.cat() == catEnd) {
3558 if (flags & FLAG_BRACE_LAST) {
3561 warning_message("stray '}' in text");
3562 output_ert_inset(os, "}", context);
3566 if (t.cat() == catComment) {
3567 parse_comment(p, os, t, context);
3572 // control sequences
3575 if (t.cs() == "(" || t.cs() == "[") {
3576 bool const simple = t.cs() == "(";
3577 context.check_layout(os);
3578 begin_inset(os, "Formula");
3579 os << " \\" << t.cs();
3580 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3581 os << '\\' << (simple ? ')' : ']');
3584 // Prevent the conversion of a line break to a
3585 // space (bug 7668). This does not change the
3586 // output, but looks ugly in LyX.
3587 eat_whitespace(p, os, context, false);
3592 if (t.cs() == "begin") {
3593 parse_environment(p, os, outer, last_env,
3598 if (t.cs() == "end") {
3599 if (flags & FLAG_END) {
3600 // eat environment name
3601 string const name = p.getArg('{', '}');
3602 if (name != active_environment())
3603 warning_message("\\end{" + name + "} does not match \\begin{"
3604 + active_environment() + "}");
3607 p.error("found 'end' unexpectedly");
3611 // "item" by default, but could be something else
3612 if (t.cs() == context.layout->itemcommand()) {
3614 if (context.layout->labeltype == LABEL_MANUAL) {
3615 // FIXME: This swallows comments, but we cannot use
3616 // eat_whitespace() since we must not output
3617 // anything before the item.
3618 p.skip_spaces(true);
3619 s = p.verbatimOption();
3621 p.skip_spaces(false);
3623 context.check_layout(os);
3624 if (context.has_item) {
3625 // An item in an unknown list-like environment
3626 // FIXME: Do this in check_layout()!
3627 context.has_item = false;
3628 string item = "\\" + context.layout->itemcommand();
3631 output_ert_inset(os, item, context);
3633 if (context.layout->labeltype != LABEL_MANUAL)
3634 output_arguments(os, p, outer, false, "item", context,
3635 context.layout->itemargs());
3636 if (!context.list_preamble.empty()) {
3637 // We have a list preamble. Output it here.
3638 begin_inset(os, "Argument listpreamble:1");
3639 os << "\nstatus collapsed\n\n"
3640 << "\\begin_layout Plain Layout\n\n"
3641 << rtrim(context.list_preamble)
3642 << "\n\\end_layout";
3644 context.list_preamble.clear();
3646 if (!context.list_extra_stuff.empty()) {
3647 os << context.list_extra_stuff;
3648 context.list_extra_stuff.clear();
3650 else if (!s.empty()) {
3651 // LyX adds braces around the argument,
3652 // so we need to remove them here.
3653 if (s.size() > 2 && s[0] == '{' &&
3654 s[s.size()-1] == '}')
3655 s = s.substr(1, s.size()-2);
3656 // If the argument contains a space we
3657 // must put it into ERT: Otherwise LyX
3658 // would misinterpret the space as
3659 // item delimiter (bug 7663)
3660 if (contains(s, ' ')) {
3661 output_ert_inset(os, s, context);
3664 os << parse_text_snippet(p2,
3665 FLAG_BRACK_LAST, outer, context);
3667 // The space is needed to separate the
3668 // item from the rest of the sentence.
3670 eat_whitespace(p, os, context, false);
3675 if (t.cs() == "bibitem") {
3677 context.check_layout(os);
3678 eat_whitespace(p, os, context, false);
3679 string label = p.verbatimOption();
3680 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3681 bool const literal = !lbl.first;
3682 label = literal ? subst(label, "\n", " ") : lbl.second;
3683 string lit = literal ? "\"true\"" : "\"false\"";
3684 string key = convert_literate_command_inset_arg(p.verbatim_item());
3685 begin_command_inset(os, "bibitem", "bibitem");
3686 os << "label \"" << label << "\"\n"
3687 << "key \"" << key << "\"\n"
3688 << "literal " << lit << "\n";
3694 // catch the case of \def\inputGnumericTable
3696 if (t.cs() == "def") {
3697 Token second = p.next_token();
3698 if (second.cs() == "inputGnumericTable") {
3702 Token third = p.get_token();
3704 if (third.cs() == "input") {
3708 string name = normalize_filename(p.verbatim_item());
3709 string const path = getMasterFilePath(true);
3710 // We want to preserve relative / absolute filenames,
3711 // therefore path is only used for testing
3712 // The file extension is in every case ".tex".
3713 // So we need to remove this extension and check for
3714 // the original one.
3715 name = removeExtension(name);
3716 if (!makeAbsPath(name, path).exists()) {
3717 char const * const Gnumeric_formats[] = {"gnumeric",
3719 string const Gnumeric_name =
3720 find_file(name, path, Gnumeric_formats);
3721 if (!Gnumeric_name.empty())
3722 name = Gnumeric_name;
3724 FileName const absname = makeAbsPath(name, path);
3725 if (absname.exists()) {
3726 fix_child_filename(name);
3727 copy_file(absname, name);
3729 warning_message("Could not find file '" + name + "'.");
3730 context.check_layout(os);
3731 begin_inset(os, "External\n\ttemplate ");
3732 os << "GnumericSpreadsheet\n\tfilename "
3735 context.check_layout(os);
3737 // register the packages that are automatically loaded
3738 // by the Gnumeric template
3739 registerExternalTemplatePackages("GnumericSpreadsheet");
3744 parse_macro(p, os, context);
3748 if (t.cs() == "noindent") {
3750 context.add_par_extra_stuff("\\noindent\n");
3754 if (t.cs() == "appendix" && !context.in_list_preamble) {
3755 context.add_par_extra_stuff("\\start_of_appendix\n");
3756 // We need to start a new paragraph. Otherwise the
3757 // appendix in 'bla\appendix\chapter{' would start
3759 context.new_paragraph(os);
3760 // We need to make sure that the paragraph is
3761 // generated even if it is empty. Otherwise the
3762 // appendix in '\par\appendix\par\chapter{' would
3764 context.check_layout(os);
3765 // FIXME: This is a hack to prevent paragraph
3766 // deletion if it is empty. Handle this better!
3767 output_comment(p, os,
3768 "dummy comment inserted by tex2lyx to "
3769 "ensure that this paragraph is not empty",
3771 // Both measures above may generate an additional
3772 // empty paragraph, but that does not hurt, because
3773 // whitespace does not matter here.
3774 eat_whitespace(p, os, context, true);
3778 // Must catch empty dates before findLayout is called below
3779 if (t.cs() == "date") {
3780 eat_whitespace(p, os, context, false);
3782 string const date = p.verbatim_item();
3785 preamble.suppressDate(true);
3788 preamble.suppressDate(false);
3789 if (context.new_layout_allowed &&
3790 (newlayout = findLayout(context.textclass,
3793 output_command_layout(os, p, outer,
3794 context, newlayout);
3795 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3796 if (!preamble.titleLayoutFound())
3797 preamble.titleLayoutFound(newlayout->intitle);
3798 set<string> const & req = newlayout->required();
3799 set<string>::const_iterator it = req.begin();
3800 set<string>::const_iterator en = req.end();
3801 for (; it != en; ++it)
3802 preamble.registerAutomaticallyLoadedPackage(*it);
3804 output_ert_inset(os,
3805 "\\date{" + p.verbatim_item() + '}',
3811 // Before we look for the layout name with star and alone below, we check the layouts including
3812 // the LateXParam, which might be one or several options or a star.
3813 // The single '=' is meant here.
3814 if (context.new_layout_allowed &&
3815 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3816 // store the latexparam here. This is eaten in output_command_layout
3817 context.latexparam = newlayout->latexparam();
3819 output_command_layout(os, p, outer, context, newlayout);
3820 context.latexparam.clear();
3822 if (!preamble.titleLayoutFound())
3823 preamble.titleLayoutFound(newlayout->intitle);
3824 set<string> const & req = newlayout->required();
3825 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3826 preamble.registerAutomaticallyLoadedPackage(*it);
3830 // Starred section headings
3831 // Must attempt to parse "Section*" before "Section".
3832 if ((p.next_token().asInput() == "*") &&
3833 context.new_layout_allowed &&
3834 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3837 output_command_layout(os, p, outer, context, newlayout);
3839 if (!preamble.titleLayoutFound())
3840 preamble.titleLayoutFound(newlayout->intitle);
3841 set<string> const & req = newlayout->required();
3842 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3843 preamble.registerAutomaticallyLoadedPackage(*it);
3847 // Section headings and the like
3848 if (context.new_layout_allowed &&
3849 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3851 output_command_layout(os, p, outer, context, newlayout);
3853 if (!preamble.titleLayoutFound())
3854 preamble.titleLayoutFound(newlayout->intitle);
3855 set<string> const & req = newlayout->required();
3856 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3857 preamble.registerAutomaticallyLoadedPackage(*it);
3861 if (t.cs() == "subfloat") {
3862 // the syntax is \subfloat[list entry][sub caption]{content}
3863 // if it is a table of figure depends on the surrounding float
3865 // do nothing if there is no outer float
3866 if (!float_type.empty()) {
3867 context.check_layout(os);
3869 begin_inset(os, "Float " + float_type + "\n");
3871 << "\nsideways false"
3872 << "\nstatus collapsed\n\n";
3875 bool has_caption = false;
3876 if (p.next_token().cat() != catEscape &&
3877 p.next_token().character() == '[') {
3878 p.get_token(); // eat '['
3879 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3882 // In case we have two optional args, the second is the caption.
3883 if (p.next_token().cat() != catEscape &&
3884 p.next_token().character() == '[') {
3885 p.get_token(); // eat '['
3886 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3889 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3890 // the caption comes always as the last
3892 // we must make sure that the caption gets a \begin_layout
3893 os << "\n\\begin_layout Plain Layout";
3895 begin_inset(os, "Caption Standard\n");
3896 Context newcontext(true, context.textclass,
3897 0, 0, context.font);
3898 newcontext.check_layout(os);
3899 os << caption << "\n";
3900 newcontext.check_end_layout(os);
3903 // close the layout we opened
3904 os << "\n\\end_layout";
3909 // if the float type is not supported or there is no surrounding float
3914 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3916 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3918 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3919 + "{" + p.verbatim_item() + '}', context);
3924 if (t.cs() == "xymatrix") {
3925 // we must open a new math because LyX's xy support is in math
3926 context.check_layout(os);
3927 begin_inset(os, "Formula ");
3929 os << "\\" << t.cs() << '{';
3930 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3933 preamble.registerAutomaticallyLoadedPackage("xy");
3937 if (t.cs() == "includegraphics") {
3938 bool const clip = p.next_token().asInput() == "*";
3941 string const arg = p.getArg('[', ']');
3942 map<string, string> opts;
3943 vector<string> keys;
3944 split_map(arg, opts, keys);
3946 opts["clip"] = string();
3947 string name = normalize_filename(p.verbatim_item());
3949 string const path = getMasterFilePath(true);
3950 // We want to preserve relative / absolute filenames,
3951 // therefore path is only used for testing
3952 if (!makeAbsPath(name, path).exists()) {
3953 // The file extension is probably missing.
3954 // Now try to find it out.
3955 string const dvips_name =
3956 find_file(name, path,
3957 known_dvips_graphics_formats);
3958 string const pdftex_name =
3959 find_file(name, path,
3960 known_pdftex_graphics_formats);
3961 if (!dvips_name.empty()) {
3962 if (!pdftex_name.empty()) {
3963 warning_message("This file contains the "
3965 "\"\\includegraphics{" + name + "}\".\n"
3966 "However, files\n\""
3967 + dvips_name + "\" and\n\""
3968 + pdftex_name + "\"\n"
3969 "both exist, so I had to make a "
3970 "choice and took the first one.\n"
3971 "Please move the unwanted one "
3972 "someplace else and try again\n"
3973 "if my choice was wrong.");
3976 } else if (!pdftex_name.empty()) {
3982 FileName const absname = makeAbsPath(name, path);
3983 if (absname.exists()) {
3984 fix_child_filename(name);
3985 copy_file(absname, name);
3987 warning_message("Could not find graphics file '" + name + "'.");
3989 context.check_layout(os);
3990 begin_inset(os, "Graphics ");
3991 os << "\n\tfilename " << name << '\n';
3992 if (opts.find("width") != opts.end())
3994 << translate_len(opts["width"]) << '\n';
3995 if (opts.find("totalheight") != opts.end())
3997 << translate_len(opts["totalheight"]) << '\n';
3998 if (opts.find("scale") != opts.end()) {
3999 istringstream iss(opts["scale"]);
4003 os << "\tscale " << val << '\n';
4005 if (opts.find("angle") != opts.end()) {
4006 os << "\trotateAngle "
4007 << opts["angle"] << '\n';
4008 vector<string>::const_iterator a =
4009 find(keys.begin(), keys.end(), "angle");
4010 vector<string>::const_iterator s =
4011 find(keys.begin(), keys.end(), "width");
4012 if (s == keys.end())
4013 s = find(keys.begin(), keys.end(), "totalheight");
4014 if (s == keys.end())
4015 s = find(keys.begin(), keys.end(), "scale");
4016 if (s != keys.end() && distance(s, a) > 0)
4017 os << "\tscaleBeforeRotation\n";
4019 if (opts.find("origin") != opts.end()) {
4021 string const opt = opts["origin"];
4022 if (opt.find('l') != string::npos) ss << "left";
4023 if (opt.find('r') != string::npos) ss << "right";
4024 if (opt.find('c') != string::npos) ss << "center";
4025 if (opt.find('t') != string::npos) ss << "Top";
4026 if (opt.find('b') != string::npos) ss << "Bottom";
4027 if (opt.find('B') != string::npos) ss << "Baseline";
4028 if (!ss.str().empty())
4029 os << "\trotateOrigin " << ss.str() << '\n';
4031 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
4033 if (opts.find("keepaspectratio") != opts.end())
4034 os << "\tkeepAspectRatio\n";
4035 if (opts.find("clip") != opts.end())
4037 if (opts.find("draft") != opts.end())
4039 if (opts.find("bb") != opts.end())
4040 os << "\tBoundingBox "
4041 << opts["bb"] << '\n';
4042 int numberOfbbOptions = 0;
4043 if (opts.find("bbllx") != opts.end())
4044 numberOfbbOptions++;
4045 if (opts.find("bblly") != opts.end())
4046 numberOfbbOptions++;
4047 if (opts.find("bburx") != opts.end())
4048 numberOfbbOptions++;
4049 if (opts.find("bbury") != opts.end())
4050 numberOfbbOptions++;
4051 if (numberOfbbOptions == 4)
4052 os << "\tBoundingBox "
4053 << opts["bbllx"] << " " << opts["bblly"] << " "
4054 << opts["bburx"] << " " << opts["bbury"] << '\n';
4055 else if (numberOfbbOptions > 0)
4056 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4057 numberOfbbOptions = 0;
4058 if (opts.find("natwidth") != opts.end())
4059 numberOfbbOptions++;
4060 if (opts.find("natheight") != opts.end())
4061 numberOfbbOptions++;
4062 if (numberOfbbOptions == 2)
4063 os << "\tBoundingBox 0bp 0bp "
4064 << opts["natwidth"] << " " << opts["natheight"] << '\n';
4065 else if (numberOfbbOptions > 0)
4066 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4067 ostringstream special;
4068 if (opts.find("hiresbb") != opts.end())
4069 special << "hiresbb,";
4070 if (opts.find("trim") != opts.end())
4072 if (opts.find("viewport") != opts.end())
4073 special << "viewport=" << opts["viewport"] << ',';
4074 if (opts.find("height") != opts.end())
4075 special << "height=" << opts["height"] << ',';
4076 if (opts.find("type") != opts.end())
4077 special << "type=" << opts["type"] << ',';
4078 if (opts.find("ext") != opts.end())
4079 special << "ext=" << opts["ext"] << ',';
4080 if (opts.find("read") != opts.end())
4081 special << "read=" << opts["read"] << ',';
4082 if (opts.find("command") != opts.end())
4083 special << "command=" << opts["command"] << ',';
4084 string s_special = special.str();
4085 if (!s_special.empty()) {
4086 // We had special arguments. Remove the trailing ','.
4087 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
4089 // TODO: Handle the unknown settings better.
4090 // Warn about invalid options.
4091 // Check whether some option was given twice.
4093 preamble.registerAutomaticallyLoadedPackage("graphicx");
4097 if (t.cs() == "footnote" ||
4098 (t.cs() == "thanks" && context.layout->intitle)) {
4100 context.check_layout(os);
4101 begin_inset(os, "Foot\n");
4102 os << "status collapsed\n\n";
4103 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4108 if (t.cs() == "marginpar") {
4110 context.check_layout(os);
4111 begin_inset(os, "Marginal\n");
4112 os << "status collapsed\n\n";
4113 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4118 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
4119 bool const use_minted = t.cs() == "mintinline";
4121 parse_listings(p, os, context, true, use_minted);
4125 if (t.cs() == "ensuremath") {
4127 context.check_layout(os);
4128 string const s = p.verbatim_item();
4129 //FIXME: this never triggers in UTF8
4130 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
4133 output_ert_inset(os, "\\ensuremath{" + s + "}",
4138 else if (t.cs() == "makeindex"
4139 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
4140 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
4141 if (preamble.titleLayoutFound()) {
4143 skip_spaces_braces(p);
4145 output_ert_inset(os, t.asInput(), context);
4149 if (t.cs() == "tableofcontents"
4150 || t.cs() == "lstlistoflistings"
4151 || t.cs() == "listoflistings") {
4152 string name = t.cs();
4153 if (preamble.minted() && name == "listoflistings")
4154 name.insert(0, "lst");
4155 context.check_layout(os);
4156 begin_command_inset(os, "toc", name);
4158 skip_spaces_braces(p);
4159 if (name == "lstlistoflistings") {
4160 if (preamble.minted())
4161 preamble.registerAutomaticallyLoadedPackage("minted");
4163 preamble.registerAutomaticallyLoadedPackage("listings");
4168 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
4169 context.check_layout(os);
4170 if (t.cs() == "listoffigures")
4171 begin_inset(os, "FloatList figure\n");
4173 begin_inset(os, "FloatList table\n");
4175 skip_spaces_braces(p);
4179 if (t.cs() == "listof") {
4180 p.skip_spaces(true);
4181 string const name = p.verbatim_item();
4182 if (context.textclass.floats().typeExist(name)) {
4183 context.check_layout(os);
4184 begin_inset(os, "FloatList ");
4187 p.verbatim_item(); // swallow second arg
4189 output_ert_inset(os, "\\listof{" + name + "}", context);
4193 if (t.cs() == "theendnotes"
4194 || (t.cs() == "printendnotes"
4195 && p.next_token().asInput() != "*"
4197 context.check_layout(os);
4198 begin_inset(os, "FloatList endnote\n");
4200 skip_spaces_braces(p);
4204 if ((where = is_known(t.cs(), known_text_font_families))) {
4205 parse_text_attributes(p, os, FLAG_ITEM, outer,
4206 context, "\\family", context.font.family,
4207 known_coded_font_families[where - known_text_font_families]);
4211 // beamer has a \textbf<overlay>{} inset
4212 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
4213 parse_text_attributes(p, os, FLAG_ITEM, outer,
4214 context, "\\series", context.font.series,
4215 known_coded_font_series[where - known_text_font_series]);
4219 // beamer has a \textit<overlay>{} inset
4220 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4221 parse_text_attributes(p, os, FLAG_ITEM, outer,
4222 context, "\\shape", context.font.shape,
4223 known_coded_font_shapes[where - known_text_font_shapes]);
4227 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4228 context.check_layout(os);
4229 TeXFont oldFont = context.font;
4230 context.font.init();
4231 context.font.size = oldFont.size;
4232 os << "\n\\family " << context.font.family << "\n";
4233 os << "\n\\series " << context.font.series << "\n";
4234 os << "\n\\shape " << context.font.shape << "\n";
4235 if (t.cs() == "textnormal") {
4236 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4237 output_font_change(os, context.font, oldFont);
4238 context.font = oldFont;
4240 eat_whitespace(p, os, context, false);
4244 if (t.cs() == "textcolor") {
4245 // scheme is \textcolor{color name}{text}
4246 string const color = p.verbatim_item();
4247 // we support the predefined colors of the color and the xcolor package
4248 if (color == "black" || color == "blue" || color == "cyan"
4249 || color == "green" || color == "magenta" || color == "red"
4250 || color == "white" || color == "yellow") {
4251 context.check_layout(os);
4252 os << "\n\\color " << color << "\n";
4253 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4254 context.check_layout(os);
4255 os << "\n\\color inherit\n";
4256 preamble.registerAutomaticallyLoadedPackage("color");
4257 } else if (color == "brown" || color == "darkgray" || color == "gray"
4258 || color == "lightgray" || color == "lime" || color == "olive"
4259 || color == "orange" || color == "pink" || color == "purple"
4260 || color == "teal" || color == "violet") {
4261 context.check_layout(os);
4262 os << "\n\\color " << color << "\n";
4263 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4264 context.check_layout(os);
4265 os << "\n\\color inherit\n";
4266 preamble.registerAutomaticallyLoadedPackage("xcolor");
4268 // for custom defined colors
4269 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4273 if (t.cs() == "underbar" || t.cs() == "uline") {
4274 // \underbar is not 100% correct (LyX outputs \uline
4275 // of ulem.sty). The difference is that \ulem allows
4276 // line breaks, and \underbar does not.
4277 // Do NOT handle \underline.
4278 // \underbar cuts through y, g, q, p etc.,
4279 // \underline does not.
4280 context.check_layout(os);
4281 os << "\n\\bar under\n";
4282 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4283 context.check_layout(os);
4284 os << "\n\\bar default\n";
4285 preamble.registerAutomaticallyLoadedPackage("ulem");
4289 if (t.cs() == "sout") {
4290 context.check_layout(os);
4291 os << "\n\\strikeout on\n";
4292 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4293 context.check_layout(os);
4294 os << "\n\\strikeout default\n";
4295 preamble.registerAutomaticallyLoadedPackage("ulem");
4299 // beamer has an \emph<overlay>{} inset
4300 if ((t.cs() == "uuline" || t.cs() == "uwave"
4301 || t.cs() == "emph" || t.cs() == "noun"
4302 || t.cs() == "xout") && !p.hasOpt("<")) {
4303 context.check_layout(os);
4304 os << "\n\\" << t.cs() << " on\n";
4305 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4306 context.check_layout(os);
4307 os << "\n\\" << t.cs() << " default\n";
4308 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4309 preamble.registerAutomaticallyLoadedPackage("ulem");
4313 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4314 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4315 context.check_layout(os);
4318 initials = p.getArg('[', ']');
4320 string name = p.getArg('{', '}');
4321 string localtime = p.getArg('{', '}');
4322 preamble.registerAuthor(name, initials);
4323 Author const & author = preamble.getAuthor(name);
4324 // from_asctime_utc() will fail if LyX decides to output the
4325 // time in the text language.
4326 time_t ptime = from_asctime_utc(localtime);
4327 if (ptime == static_cast<time_t>(-1)) {
4328 warning_message("Could not parse time `" + localtime
4329 + "´ for change tracking, using current time instead.");
4330 ptime = current_time();
4332 if (t.cs() == "lyxadded")
4333 os << "\n\\change_inserted ";
4335 os << "\n\\change_deleted ";
4336 os << author.bufferId() << ' ' << ptime << '\n';
4337 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4338 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4339 LaTeXPackages::isAvailable("xcolor");
4340 // No need to test for luatex, since luatex comes in
4341 // two flavours (dvi and pdf), like latex, and those
4342 // are detected by pdflatex.
4343 if (pdflatex || xetex) {
4345 preamble.registerAutomaticallyLoadedPackage("ulem");
4346 preamble.registerAutomaticallyLoadedPackage("xcolor");
4347 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4351 preamble.registerAutomaticallyLoadedPackage("ulem");
4352 preamble.registerAutomaticallyLoadedPackage("xcolor");
4358 if (t.cs() == "textipa") {
4359 context.check_layout(os);
4360 begin_inset(os, "IPA\n");
4361 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4362 context.merging_hyphens_allowed = false;
4363 set<string> pass_thru_cmds = context.pass_thru_cmds;
4364 // These commands have special meanings in IPA
4365 context.pass_thru_cmds.insert("!");
4366 context.pass_thru_cmds.insert(";");
4367 context.pass_thru_cmds.insert(":");
4368 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4369 context.pass_thru_cmds = pass_thru_cmds;
4370 context.merging_hyphens_allowed = merging_hyphens_allowed;
4372 preamble.registerAutomaticallyLoadedPackage("tipa");
4373 preamble.registerAutomaticallyLoadedPackage("tipx");
4377 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4378 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4379 context.check_layout(os);
4383 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4384 begin_inset(os, "IPADeco " + type + "\n");
4385 os << "status open\n";
4386 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4392 if (t.cs() == "textvertline") {
4393 // FIXME: This is not correct, \textvertline is higher than |
4399 if (t.cs() == "tone" ) {
4400 context.check_layout(os);
4401 // register the tone package
4402 preamble.registerAutomaticallyLoadedPackage("tone");
4403 string content = trimSpaceAndEol(p.verbatim_item());
4404 string command = t.asInput() + "{" + content + "}";
4405 // some tones can be detected by unicodesymbols, some need special code
4406 if (is_known(content, known_tones)) {
4407 os << "\\IPAChar " << command << "\n";
4410 // try to see whether the string is in unicodesymbols
4414 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4415 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4416 termination, rem, &req);
4420 output_ert_inset(os, to_utf8(rem), context);
4421 for (set<string>::const_iterator it = req.begin();
4422 it != req.end(); ++it)
4423 preamble.registerAutomaticallyLoadedPackage(*it);
4425 // we did not find a non-ert version
4426 output_ert_inset(os, command, context);
4430 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4431 t.cs() == "vphantom") {
4432 context.check_layout(os);
4433 if (t.cs() == "phantom")
4434 begin_inset(os, "Phantom Phantom\n");
4435 if (t.cs() == "hphantom")
4436 begin_inset(os, "Phantom HPhantom\n");
4437 if (t.cs() == "vphantom")
4438 begin_inset(os, "Phantom VPhantom\n");
4439 os << "status open\n";
4440 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4446 if (t.cs() == "href") {
4447 context.check_layout(os);
4448 string target = convert_literate_command_inset_arg(p.verbatim_item());
4449 string name = p.verbatim_item();
4450 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4451 bool const literal = !nm.first;
4452 name = literal ? subst(name, "\n", " ") : nm.second;
4453 string lit = literal ? "\"true\"" : "\"false\"";
4455 size_t i = target.find(':');
4456 if (i != string::npos) {
4457 type = target.substr(0, i + 1);
4458 if (type == "mailto:" || type == "file:")
4459 target = target.substr(i + 1);
4460 else if (target.find("://") == string::npos)
4462 // handle the case that name is equal to target, except of "http(s)://"
4463 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4466 begin_command_inset(os, "href", "href");
4468 os << "name \"" << name << "\"\n";
4469 os << "target \"" << target << "\"\n";
4470 if (type == "mailto:" || type == "file:" || type == "other")
4471 os << "type \"" << type << "\"\n";
4472 os << "literal " << lit << "\n";
4474 skip_spaces_braces(p);
4478 if (t.cs() == "lyxline") {
4479 // swallow size argument (it is not used anyway)
4481 if (!context.atParagraphStart()) {
4482 // so our line is in the middle of a paragraph
4483 // we need to add a new line, lest this line
4484 // follow the other content on that line and
4485 // run off the side of the page
4486 // FIXME: This may create an empty paragraph,
4487 // but without that it would not be
4488 // possible to set noindent below.
4489 // Fortunately LaTeX does not care
4490 // about the empty paragraph.
4491 context.new_paragraph(os);
4493 if (preamble.indentParagraphs()) {
4494 // we need to unindent, lest the line be too long
4495 context.add_par_extra_stuff("\\noindent\n");
4497 context.check_layout(os);
4498 begin_command_inset(os, "line", "rule");
4499 os << "offset \"0.5ex\"\n"
4500 "width \"100line%\"\n"
4506 if (t.cs() == "rule") {
4507 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4508 string const width = p.getArg('{', '}');
4509 string const thickness = p.getArg('{', '}');
4510 context.check_layout(os);
4511 begin_command_inset(os, "line", "rule");
4512 if (!offset.empty())
4513 os << "offset \"" << translate_len(offset) << "\"\n";
4514 os << "width \"" << translate_len(width) << "\"\n"
4515 "height \"" << translate_len(thickness) << "\"\n";
4520 // Handle refstyle first in order to to catch \eqref, because this
4521 // can also occur without refstyle. Only recognize these commands if
4522 // refstyle.sty was found in the preamble (otherwise \eqref
4523 // and user defined ref commands could be misdetected).
4524 // We uncapitalize the input in order to catch capitalized commands
4526 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4527 && preamble.refstyle()) {
4528 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4529 string plural = "false";
4530 // Catch the plural option [s]
4532 string const opt = p.getOpt();
4536 // LyX does not yet support other optional arguments of ref commands
4537 output_ert_inset(os, t.asInput() + opt + "{" +
4538 p.verbatim_item() + '}', context);
4542 context.check_layout(os);
4543 begin_command_inset(os, "ref", "formatted");
4544 os << "reference \"";
4545 os << known_refstyle_prefixes[where - known_refstyle_commands]
4547 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4549 os << "plural \"" << plural << "\"\n";
4550 os << "caps \"" << cap << "\"\n";
4551 os << "noprefix \"false\"\n";
4553 preamble.registerAutomaticallyLoadedPackage("refstyle");
4557 // if refstyle is used, we must not convert \prettyref to a
4558 // formatted reference, since that would result in a refstyle command.
4559 if ((where = is_known(t.cs(), known_ref_commands))
4560 && (t.cs() != "prettyref" || !preamble.refstyle())
4561 && (p.next_token().asInput() != "*" || is_known(t.cs(), known_starref_commands))) {
4562 bool starred = false;
4563 if (p.next_token().asInput() == "*") {
4567 string const opt = p.getOpt();
4569 context.check_layout(os);
4570 begin_command_inset(os, "ref",
4571 known_coded_ref_commands[where - known_ref_commands]);
4572 os << "reference \""
4573 << convert_literate_command_inset_arg(p.verbatim_item())
4575 os << "plural \"false\"\n";
4576 os << "caps \"false\"\n";
4577 os << "noprefix \"false\"\n";
4579 os << "nolink \"true\"\n";
4581 os << "nolink \"false\"\n";
4583 if (t.cs() == "vref" || t.cs() == "vpageref")
4584 preamble.registerAutomaticallyLoadedPackage("varioref");
4585 else if (t.cs() == "prettyref")
4586 preamble.registerAutomaticallyLoadedPackage("prettyref");
4588 // LyX does not yet support optional arguments of ref commands
4589 output_ert_inset(os, t.asInput() + opt + "{" +
4590 p.verbatim_item() + '}', context);
4596 is_known(t.cs(), known_natbib_commands) &&
4597 ((t.cs() != "citefullauthor" &&
4598 t.cs() != "citeyear" &&
4599 t.cs() != "citeyearpar") ||
4600 p.next_token().asInput() != "*")) {
4601 context.check_layout(os);
4602 string command = t.cs();
4603 if (p.next_token().asInput() == "*") {
4607 if (command == "citefullauthor")
4608 // alternative name for "\\citeauthor*"
4609 command = "citeauthor*";
4611 // text before the citation
4613 // text after the citation
4615 get_cite_arguments(p, true, before, after);
4617 if (command == "cite") {
4618 // \cite without optional argument means
4619 // \citet, \cite with at least one optional
4620 // argument means \citep.
4621 if (before.empty() && after.empty())
4626 if (before.empty() && after == "[]")
4627 // avoid \citet[]{a}
4629 else if (before == "[]" && after == "[]") {
4630 // avoid \citet[][]{a}
4634 bool literal = false;
4635 pair<bool, string> aft;
4636 pair<bool, string> bef;
4637 // remove the brackets around after and before
4638 if (!after.empty()) {
4640 after.erase(after.length() - 1, 1);
4641 aft = convert_latexed_command_inset_arg(after);
4642 literal = !aft.first;
4643 after = literal ? subst(after, "\n", " ") : aft.second;
4645 if (!before.empty()) {
4647 before.erase(before.length() - 1, 1);
4648 bef = convert_latexed_command_inset_arg(before);
4649 literal |= !bef.first;
4650 before = literal ? subst(before, "\n", " ") : bef.second;
4651 if (literal && !after.empty())
4652 after = subst(after, "\n", " ");
4654 string lit = literal ? "\"true\"" : "\"false\"";
4655 begin_command_inset(os, "citation", command);
4656 os << "after " << '"' << after << '"' << "\n";
4657 os << "before " << '"' << before << '"' << "\n";
4659 << convert_literate_command_inset_arg(p.verbatim_item())
4661 << "literal " << lit << "\n";
4663 // Need to set the cite engine if natbib is loaded by
4664 // the document class directly
4665 if (preamble.citeEngine() == "basic")
4666 preamble.citeEngine("natbib");
4671 && is_known(t.cs(), known_biblatex_commands)
4672 && ((t.cs() == "cite"
4673 || t.cs() == "citeauthor"
4674 || t.cs() == "Citeauthor"
4675 || t.cs() == "parencite"
4676 || t.cs() == "citetitle")
4677 || p.next_token().asInput() != "*"))
4678 || (use_biblatex_natbib
4679 && (is_known(t.cs(), known_biblatex_commands)
4680 || is_known(t.cs(), known_natbib_commands))
4681 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4682 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4683 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4684 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4685 || t.cs() == "parencite" || t.cs() == "citetitle")
4686 || p.next_token().asInput() != "*"))){
4687 context.check_layout(os);
4688 string command = t.cs();
4689 if (p.next_token().asInput() == "*") {
4694 bool const qualified = suffixIs(command, "s");
4696 command = rtrim(command, "s");
4698 // text before the citation
4700 // text after the citation
4702 get_cite_arguments(p, true, before, after, qualified);
4704 // These use natbib cmd names in LyX
4705 // for inter-citeengine compativility
4706 if (command == "citeyear")
4707 command = "citebyear";
4708 else if (command == "cite*")
4709 command = "citeyear";
4710 else if (command == "textcite")
4712 else if (command == "Textcite")
4714 else if (command == "parencite")
4716 else if (command == "Parencite")
4718 else if (command == "parencite*")
4719 command = "citeyearpar";
4720 else if (command == "smartcite")
4721 command = "footcite";
4722 else if (command == "Smartcite")
4723 command = "Footcite";
4725 string const emptyarg = qualified ? "()" : "[]";
4726 if (before.empty() && after == emptyarg)
4729 else if (before == emptyarg && after == emptyarg) {
4730 // avoid \cite[][]{a}
4734 bool literal = false;
4735 pair<bool, string> aft;
4736 pair<bool, string> bef;
4737 // remove the brackets around after and before
4738 if (!after.empty()) {
4740 after.erase(after.length() - 1, 1);
4741 aft = convert_latexed_command_inset_arg(after);
4742 literal = !aft.first;
4743 after = literal ? subst(after, "\n", " ") : aft.second;
4745 if (!before.empty()) {
4747 before.erase(before.length() - 1, 1);
4748 bef = convert_latexed_command_inset_arg(before);
4749 literal |= !bef.first;
4750 before = literal ? subst(before, "\n", " ") : bef.second;
4752 string keys, pretextlist, posttextlist;
4754 vector<pair<string, string>> pres, posts, preslit, postslit;
4755 vector<string> lkeys;
4756 // text before the citation
4757 string lbefore, lbeforelit;
4758 // text after the citation
4759 string lafter, lafterlit;
4761 pair<bool, string> laft, lbef;
4763 get_cite_arguments(p, true, lbefore, lafter);
4764 // remove the brackets around after and before
4765 if (!lafter.empty()) {
4767 lafter.erase(lafter.length() - 1, 1);
4768 laft = convert_latexed_command_inset_arg(lafter);
4769 literal |= !laft.first;
4770 lafter = laft.second;
4771 lafterlit = subst(lafter, "\n", " ");
4773 if (!lbefore.empty()) {
4774 lbefore.erase(0, 1);
4775 lbefore.erase(lbefore.length() - 1, 1);
4776 lbef = convert_latexed_command_inset_arg(lbefore);
4777 literal |= !lbef.first;
4778 lbefore = lbef.second;
4779 lbeforelit = subst(lbefore, "\n", " ");
4781 if (lbefore.empty() && lafter == "[]") {
4786 else if (lbefore == "[]" && lafter == "[]") {
4787 // avoid \cite[][]{a}
4793 lkey = p.getArg('{', '}');
4796 pres.push_back(make_pair(lkey, lbefore));
4797 preslit.push_back(make_pair(lkey, lbeforelit));
4798 posts.push_back(make_pair(lkey, lafter));
4799 postslit.push_back(make_pair(lkey, lafterlit));
4800 lkeys.push_back(lkey);
4802 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4807 for (auto const & ptl : pres) {
4808 if (!pretextlist.empty())
4809 pretextlist += '\t';
4810 pretextlist += ptl.first;
4811 if (!ptl.second.empty())
4812 pretextlist += " " + ptl.second;
4814 for (auto const & potl : posts) {
4815 if (!posttextlist.empty())
4816 posttextlist += '\t';
4817 posttextlist += potl.first;
4818 if (!potl.second.empty())
4819 posttextlist += " " + potl.second;
4822 keys = convert_literate_command_inset_arg(p.verbatim_item());
4825 after = subst(after, "\n", " ");
4826 if (!before.empty())
4827 before = subst(after, "\n", " ");
4829 string lit = literal ? "\"true\"" : "\"false\"";
4830 begin_command_inset(os, "citation", command);
4831 os << "after " << '"' << after << '"' << "\n";
4832 os << "before " << '"' << before << '"' << "\n";
4836 if (!pretextlist.empty())
4837 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4838 if (!posttextlist.empty())
4839 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4840 os << "literal " << lit << "\n";
4842 // Need to set the cite engine if biblatex is loaded by
4843 // the document class directly
4844 if (preamble.citeEngine() == "basic")
4845 use_biblatex_natbib ?
4846 preamble.citeEngine("biblatex-natbib")
4847 : preamble.citeEngine("biblatex");
4852 is_known(t.cs(), known_jurabib_commands) &&
4853 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4854 context.check_layout(os);
4855 string command = t.cs();
4856 if (p.next_token().asInput() == "*") {
4860 char argumentOrder = '\0';
4861 vector<string> const options =
4862 preamble.getPackageOptions("jurabib");
4863 if (find(options.begin(), options.end(),
4864 "natbiborder") != options.end())
4865 argumentOrder = 'n';
4866 else if (find(options.begin(), options.end(),
4867 "jurabiborder") != options.end())
4868 argumentOrder = 'j';
4870 // text before the citation
4872 // text after the citation
4874 get_cite_arguments(p, argumentOrder != 'j', before, after);
4876 string const citation = p.verbatim_item();
4877 if (!before.empty() && argumentOrder == '\0') {
4878 warning_message("Assuming argument order "
4879 "of jurabib version 0.6 for\n'"
4880 + command + before + after + '{'
4881 + citation + "}'.\n"
4882 "Add 'jurabiborder' to the jurabib "
4883 "package options if you used an\n"
4884 "earlier jurabib version.");
4886 bool literal = false;
4887 pair<bool, string> aft;
4888 pair<bool, string> bef;
4889 // remove the brackets around after and before
4890 if (!after.empty()) {
4892 after.erase(after.length() - 1, 1);
4893 aft = convert_latexed_command_inset_arg(after);
4894 literal = !aft.first;
4895 after = literal ? subst(after, "\n", " ") : aft.second;
4897 if (!before.empty()) {
4899 before.erase(before.length() - 1, 1);
4900 bef = convert_latexed_command_inset_arg(before);
4901 literal |= !bef.first;
4902 before = literal ? subst(before, "\n", " ") : bef.second;
4903 if (literal && !after.empty())
4904 after = subst(after, "\n", " ");
4906 string lit = literal ? "\"true\"" : "\"false\"";
4907 begin_command_inset(os, "citation", command);
4908 os << "after " << '"' << after << "\"\n"
4909 << "before " << '"' << before << "\"\n"
4910 << "key " << '"' << citation << "\"\n"
4911 << "literal " << lit << "\n";
4913 // Need to set the cite engine if jurabib is loaded by
4914 // the document class directly
4915 if (preamble.citeEngine() == "basic")
4916 preamble.citeEngine("jurabib");
4920 if (t.cs() == "cite"
4921 || t.cs() == "nocite") {
4922 context.check_layout(os);
4923 string after = p.getArg('[', ']');
4924 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4925 bool const literal = !aft.first;
4926 after = literal ? subst(after, "\n", " ") : aft.second;
4927 string lit = literal ? "\"true\"" : "\"false\"";
4928 string key = convert_literate_command_inset_arg(p.verbatim_item());
4929 // store the case that it is "\nocite{*}" to use it later for
4932 begin_command_inset(os, "citation", t.cs());
4933 os << "after " << '"' << after << "\"\n"
4934 << "key " << '"' << key << "\"\n"
4935 << "literal " << lit << "\n";
4937 } else if (t.cs() == "nocite")
4942 if (t.cs() == "index" ||
4943 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4944 context.check_layout(os);
4945 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4946 p.getArg('[', ']') : "";
4947 string const kind = arg.empty() ? "idx" : arg;
4948 parse_index_entry(p, os, context, kind);
4950 preamble.registerAutomaticallyLoadedPackage("splitidx");
4954 if (t.cs() == "nomenclature") {
4955 context.check_layout(os);
4956 begin_command_inset(os, "nomenclature", "nomenclature");
4957 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4958 if (!prefix.empty())
4959 os << "prefix " << '"' << prefix << '"' << "\n";
4960 string symbol = p.verbatim_item();
4961 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4962 bool literal = !sym.first;
4963 string description = p.verbatim_item();
4964 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4965 literal |= !desc.first;
4967 symbol = subst(symbol, "\n", " ");
4968 description = subst(description, "\n", " ");
4970 symbol = sym.second;
4971 description = desc.second;
4973 string lit = literal ? "\"true\"" : "\"false\"";
4974 os << "symbol " << '"' << symbol;
4975 os << "\"\ndescription \""
4976 << description << "\"\n"
4977 << "literal " << lit << "\n";
4979 preamble.registerAutomaticallyLoadedPackage("nomencl");
4983 if (t.cs() == "label") {
4984 context.check_layout(os);
4985 begin_command_inset(os, "label", "label");
4987 << convert_literate_command_inset_arg(p.verbatim_item())
4993 if (t.cs() == "lyxmintcaption") {
4994 string const pos = p.getArg('[', ']');
4996 string const caption =
4997 parse_text_snippet(p, FLAG_ITEM, false,
4999 minted_nonfloat_caption = "[t]" + caption;
5001 // We already got the caption at the bottom,
5002 // so simply skip it.
5003 parse_text_snippet(p, FLAG_ITEM, false, context);
5005 eat_whitespace(p, os, context, true);
5009 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
5010 context.check_layout(os);
5011 string commandname = t.cs();
5013 if (p.next_token().asInput() == "*") {
5018 begin_command_inset(os, "index_print", commandname);
5019 string const indexname = p.getArg('[', ']');
5021 if (indexname.empty())
5022 os << "type \"idx\"\n";
5024 os << "type \"" << indexname << "\"\n";
5025 os << "literal \"true\"\n";
5028 skip_spaces_braces(p);
5029 preamble.registerAutomaticallyLoadedPackage("makeidx");
5030 if (preamble.use_indices() == "true")
5031 preamble.registerAutomaticallyLoadedPackage("splitidx");
5035 if (t.cs() == "printnomenclature") {
5037 string width_type = "";
5038 context.check_layout(os);
5039 begin_command_inset(os, "nomencl_print", "printnomenclature");
5040 // case of a custom width
5042 width = p.getArg('[', ']');
5043 width = translate_len(width);
5044 width_type = "custom";
5046 // case of no custom width
5047 // the case of no custom width but the width set
5048 // via \settowidth{\nomlabelwidth}{***} cannot be supported
5049 // because the user could have set anything, not only the width
5050 // of the longest label (which would be width_type = "auto")
5051 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
5052 if (label.empty() && width_type.empty())
5053 width_type = "none";
5054 os << "set_width \"" << width_type << "\"\n";
5055 if (width_type == "custom")
5056 os << "width \"" << width << '\"';
5058 skip_spaces_braces(p);
5059 preamble.registerAutomaticallyLoadedPackage("nomencl");
5063 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
5064 context.check_layout(os);
5065 begin_inset(os, "script ");
5066 os << t.cs().substr(4) << '\n';
5067 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
5068 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5070 if (t.cs() == "textsubscript")
5071 preamble.registerAutomaticallyLoadedPackage("subscript");
5075 if ((where = is_known(t.cs(), known_quotes))) {
5076 context.check_layout(os);
5077 begin_inset(os, "Quotes ");
5078 string quotetype = known_coded_quotes[where - known_quotes];
5079 // try to make a smart guess about the side
5080 Token const prev = p.prev_token();
5081 bool const opening = (prev.cat() != catSpace && prev.character() != 0
5082 && prev.character() != '\n' && prev.character() != '~');
5083 quotetype = guessQuoteStyle(quotetype, opening);
5086 // LyX adds {} after the quote, so we have to eat
5087 // spaces here if there are any before a possible
5089 eat_whitespace(p, os, context, false);
5094 if ((where = is_known(t.cs(), known_sizes)) &&
5095 context.new_layout_allowed) {
5096 context.check_layout(os);
5097 TeXFont const oldFont = context.font;
5098 context.font.size = known_coded_sizes[where - known_sizes];
5099 output_font_change(os, oldFont, context.font);
5100 eat_whitespace(p, os, context, false);
5104 if ((where = is_known(t.cs(), known_font_families)) &&
5105 context.new_layout_allowed) {
5106 context.check_layout(os);
5107 TeXFont const oldFont = context.font;
5108 context.font.family =
5109 known_coded_font_families[where - known_font_families];
5110 output_font_change(os, oldFont, context.font);
5111 eat_whitespace(p, os, context, false);
5115 if ((where = is_known(t.cs(), known_font_series)) &&
5116 context.new_layout_allowed) {
5117 context.check_layout(os);
5118 TeXFont const oldFont = context.font;
5119 context.font.series =
5120 known_coded_font_series[where - known_font_series];
5121 output_font_change(os, oldFont, context.font);
5122 eat_whitespace(p, os, context, false);
5126 if ((where = is_known(t.cs(), known_font_shapes)) &&
5127 context.new_layout_allowed) {
5128 context.check_layout(os);
5129 TeXFont const oldFont = context.font;
5130 context.font.shape =
5131 known_coded_font_shapes[where - known_font_shapes];
5132 output_font_change(os, oldFont, context.font);
5133 eat_whitespace(p, os, context, false);
5136 if ((where = is_known(t.cs(), known_old_font_families)) &&
5137 context.new_layout_allowed) {
5138 context.check_layout(os);
5139 TeXFont const oldFont = context.font;
5140 context.font.init();
5141 context.font.size = oldFont.size;
5142 context.font.family =
5143 known_coded_font_families[where - known_old_font_families];
5144 output_font_change(os, oldFont, context.font);
5145 eat_whitespace(p, os, context, false);
5149 if ((where = is_known(t.cs(), known_old_font_series)) &&
5150 context.new_layout_allowed) {
5151 context.check_layout(os);
5152 TeXFont const oldFont = context.font;
5153 context.font.init();
5154 context.font.size = oldFont.size;
5155 context.font.series =
5156 known_coded_font_series[where - known_old_font_series];
5157 output_font_change(os, oldFont, context.font);
5158 eat_whitespace(p, os, context, false);
5162 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
5163 context.new_layout_allowed) {
5164 context.check_layout(os);
5165 TeXFont const oldFont = context.font;
5166 context.font.init();
5167 context.font.size = oldFont.size;
5168 context.font.shape =
5169 known_coded_font_shapes[where - known_old_font_shapes];
5170 output_font_change(os, oldFont, context.font);
5171 eat_whitespace(p, os, context, false);
5175 if (t.cs() == "selectlanguage") {
5176 context.check_layout(os);
5177 // save the language for the case that a
5178 // \foreignlanguage is used
5179 context.font.language = babel2lyx(p.verbatim_item());
5180 os << "\n\\lang " << context.font.language << "\n";
5184 if (t.cs() == "foreignlanguage") {
5185 string const lang = babel2lyx(p.verbatim_item());
5186 parse_text_attributes(p, os, FLAG_ITEM, outer,
5188 context.font.language, lang);
5192 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
5193 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
5194 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
5196 // We have to output the whole command if it has an option
5197 // because LyX doesn't support this yet, see bug #8214,
5198 // only if there is a single option specifying a variant, we can handle it.
5200 string langopts = p.getOpt();
5201 // check if the option contains a variant, if yes, extract it
5202 string::size_type pos_var = langopts.find("variant");
5203 string::size_type i = langopts.find(',');
5204 string::size_type k = langopts.find('=', pos_var);
5205 if (pos_var != string::npos && i == string::npos) {
5207 variant = langopts.substr(k + 1, langopts.length() - k - 2);
5208 lang = preamble.polyglossia2lyx(variant);
5209 parse_text_attributes(p, os, FLAG_ITEM, outer,
5211 context.font.language, lang);
5213 output_ert_inset(os, t.asInput() + langopts, context);
5215 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
5216 parse_text_attributes(p, os, FLAG_ITEM, outer,
5218 context.font.language, lang);
5223 if (t.cs() == "inputencoding") {
5224 // nothing to write here
5225 string const enc = subst(p.verbatim_item(), "\n", " ");
5226 p.setEncoding(enc, Encoding::inputenc);
5230 if (is_known(t.cs(), known_special_chars) ||
5231 (t.cs() == "protect" &&
5232 p.next_token().cat() == catEscape &&
5233 is_known(p.next_token().cs(), known_special_protect_chars))) {
5234 // LyX sometimes puts a \protect in front, so we have to ignore it
5236 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5237 known_special_chars);
5238 context.check_layout(os);
5239 os << known_coded_special_chars[where - known_special_chars];
5240 skip_spaces_braces(p);
5244 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5245 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5246 p.next_next_token().asInput() == "-") ||
5247 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5248 // LyX sometimes puts a \protect in front, so we have to ignore it
5249 if (t.cs() == "protect")
5251 context.check_layout(os);
5252 if (t.cs() == "nobreakdash")
5253 os << "\\SpecialChar nobreakdash\n";
5255 os << "\\SpecialChar endofsentence\n";
5260 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5261 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5262 || t.cs() == "%" || t.cs() == "-") {
5263 context.check_layout(os);
5265 os << "\\SpecialChar softhyphen\n";
5271 if (t.cs() == "char") {
5272 context.check_layout(os);
5273 if (p.next_token().character() == '`') {
5275 if (p.next_token().cs() == "\"") {
5280 output_ert_inset(os, "\\char`", context);
5283 output_ert_inset(os, "\\char", context);
5288 if (t.cs() == "verb") {
5289 context.check_layout(os);
5290 // set catcodes to verbatim early, just in case.
5291 p.setCatcodes(VERBATIM_CATCODES);
5292 string delim = p.get_token().asInput();
5293 Parser::Arg arg = p.verbatimStuff(delim);
5295 output_ert_inset(os, "\\verb" + delim
5296 + arg.second + delim, context);
5298 warning_message("invalid \\verb command. Skipping");
5302 // Problem: \= creates a tabstop inside the tabbing environment
5303 // and else an accent. In the latter case we really would want
5304 // \={o} instead of \= o.
5305 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5306 output_ert_inset(os, t.asInput(), context);
5310 if (t.cs() == "\\") {
5311 context.check_layout(os);
5313 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5314 else if (p.next_token().asInput() == "*") {
5316 // getOpt() eats the following space if there
5317 // is no optional argument, but that is OK
5318 // here since it has no effect in the output.
5319 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5322 begin_inset(os, "Newline newline");
5328 if (t.cs() == "newline" ||
5329 (t.cs() == "linebreak" && !p.hasOpt())) {
5330 context.check_layout(os);
5331 begin_inset(os, "Newline ");
5334 skip_spaces_braces(p);
5338 if (t.cs() == "endgraf" && context.in_table_cell) {
5339 context.new_paragraph(os);
5340 context.check_layout(os);
5341 skip_spaces_braces(p);
5345 if (t.cs() == "input" || t.cs() == "include"
5346 || t.cs() == "verbatiminput"
5347 || t.cs() == "lstinputlisting"
5348 || t.cs() == "inputminted") {
5349 string name = t.cs();
5350 if (name == "verbatiminput"
5351 && p.next_token().asInput() == "*")
5352 name += p.get_token().asInput();
5353 context.check_layout(os);
5355 bool literal = false;
5356 if (name == "lstinputlisting" && p.hasOpt()) {
5357 lstparams = p.getArg('[', ']');
5358 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5359 literal = !oa.first;
5361 lstparams = subst(lstparams, "\n", " ");
5363 lstparams = oa.second;
5364 } else if (name == "inputminted") {
5365 name = "lstinputlisting";
5366 string const lang = p.getArg('{', '}');
5367 if (lang != "tex") {
5368 string cmd = "\\inputminted{" + lang + "}{";
5369 cmd += p.getArg('{', '}') + "}";
5370 output_ert_inset(os, cmd, context);
5373 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5374 minted_nonfloat_caption.erase(0,3);
5375 // extract label and caption from the already produced LyX code
5376 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5377 string const caption = nfc.front();
5379 vector<string>::iterator it =
5380 find(nfc.begin(), nfc.end(), "LatexCommand label");
5381 if (it != nfc.end()) {
5383 if (it != nfc.end())
5385 label = support::split(label, '"');
5388 minted_nonfloat_caption.clear();
5389 lstparams = "caption=" + caption;
5391 lstparams += ",label=" + label;
5392 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5393 literal = !oa.first;
5395 lstparams = subst(lstparams, "\n", " ");
5397 lstparams = oa.second;
5400 string lit = literal ? "\"true\"" : "\"false\"";
5401 string filename(normalize_filename(p.getArg('{', '}')));
5402 string const path = getMasterFilePath(true);
5403 // We want to preserve relative / absolute filenames,
5404 // therefore path is only used for testing
5405 if ((t.cs() == "include" || t.cs() == "input") &&
5406 !makeAbsPath(filename, path).exists()) {
5407 // The file extension is probably missing.
5408 // Now try to find it out.
5409 string const tex_name =
5410 find_file(filename, path,
5411 known_tex_extensions);
5412 if (!tex_name.empty())
5413 filename = tex_name;
5415 bool external = false;
5417 if (makeAbsPath(filename, path).exists()) {
5418 string const abstexname =
5419 makeAbsPath(filename, path).absFileName();
5420 string const absfigname =
5421 changeExtension(abstexname, ".fig");
5422 fix_child_filename(filename);
5423 string const lyxname = changeExtension(filename,
5424 roundtripMode() ? ".lyx.lyx" : ".lyx");
5425 string const abslyxname = makeAbsPath(
5426 lyxname, getParentFilePath(false)).absFileName();
5428 if (!skipChildren())
5429 external = FileName(absfigname).exists();
5430 if (t.cs() == "input" && !skipChildren()) {
5431 string const ext = getExtension(abstexname);
5433 // Combined PS/LaTeX:
5434 // x.eps, x.pstex_t (old xfig)
5435 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5436 FileName const absepsname(
5437 changeExtension(abstexname, ".eps"));
5438 FileName const abspstexname(
5439 changeExtension(abstexname, ".pstex"));
5440 bool const xfigeps =
5441 (absepsname.exists() ||
5442 abspstexname.exists()) &&
5445 // Combined PDF/LaTeX:
5446 // x.pdf, x.pdftex_t (old xfig)
5447 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5448 FileName const abspdfname(
5449 changeExtension(abstexname, ".pdf"));
5450 bool const xfigpdf =
5451 abspdfname.exists() &&
5452 (ext == "pdftex_t" || ext == "pdf_t");
5456 // Combined PS/PDF/LaTeX:
5457 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5458 string const absbase2(
5459 removeExtension(abstexname) + "_pspdftex");
5460 FileName const abseps2name(
5461 addExtension(absbase2, ".eps"));
5462 FileName const abspdf2name(
5463 addExtension(absbase2, ".pdf"));
5464 bool const xfigboth =
5465 abspdf2name.exists() &&
5466 abseps2name.exists() && ext == "pspdftex";
5468 xfig = xfigpdf || xfigeps || xfigboth;
5469 external = external && xfig;
5472 outname = changeExtension(filename, ".fig");
5473 FileName abssrc(changeExtension(abstexname, ".fig"));
5474 copy_file(abssrc, outname);
5476 // Don't try to convert, the result
5477 // would be full of ERT.
5479 FileName abssrc(abstexname);
5480 copy_file(abssrc, outname);
5481 } else if (t.cs() != "verbatiminput" &&
5483 tex2lyx(abstexname, FileName(abslyxname),
5486 // no need to call copy_file
5487 // tex2lyx creates the file
5490 FileName abssrc(abstexname);
5491 copy_file(abssrc, outname);
5494 warning_message("Could not find included file '" + filename + "'.");
5498 begin_inset(os, "External\n");
5499 os << "\ttemplate XFig\n"
5500 << "\tfilename " << outname << '\n';
5501 registerExternalTemplatePackages("XFig");
5503 begin_command_inset(os, "include", name);
5504 outname = subst(outname, "\"", "\\\"");
5505 os << "preview false\n"
5506 "filename \"" << outname << "\"\n";
5507 if (!lstparams.empty())
5508 os << "lstparams \"" << lstparams << "\"\n";
5509 os << "literal " << lit << "\n";
5510 if (t.cs() == "verbatiminput")
5511 preamble.registerAutomaticallyLoadedPackage("verbatim");
5517 if (t.cs() == "bibliographystyle") {
5518 // store new bibliographystyle
5519 bibliographystyle = p.verbatim_item();
5520 // If any other command than \bibliography, \addcontentsline
5521 // and \nocite{*} follows, we need to output the style
5522 // (because it might be used by that command).
5523 // Otherwise, it will automatically be output by LyX.
5526 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5527 if (t2.cat() == catBegin)
5529 if (t2.cat() != catEscape)
5531 if (t2.cs() == "nocite") {
5532 if (p.getArg('{', '}') == "*")
5534 } else if (t2.cs() == "bibliography")
5536 else if (t2.cs() == "phantomsection") {
5540 else if (t2.cs() == "addcontentsline") {
5541 // get the 3 arguments of \addcontentsline
5544 contentslineContent = p.getArg('{', '}');
5545 // if the last argument is not \refname we must output
5546 if (contentslineContent == "\\refname")
5553 output_ert_inset(os,
5554 "\\bibliographystyle{" + bibliographystyle + '}',
5560 if (t.cs() == "phantomsection") {
5561 // we only support this if it occurs between
5562 // \bibliographystyle and \bibliography
5563 if (bibliographystyle.empty())
5564 output_ert_inset(os, "\\phantomsection", context);
5568 if (t.cs() == "addcontentsline") {
5569 context.check_layout(os);
5570 // get the 3 arguments of \addcontentsline
5571 string const one = p.getArg('{', '}');
5572 string const two = p.getArg('{', '}');
5573 string const three = p.getArg('{', '}');
5574 // only if it is a \refname, we support if for the bibtex inset
5575 if (contentslineContent != "\\refname") {
5576 output_ert_inset(os,
5577 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5583 else if (t.cs() == "bibliography") {
5584 context.check_layout(os);
5586 begin_command_inset(os, "bibtex", "bibtex");
5587 if (!btprint.empty()) {
5588 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5589 // clear the string because the next BibTeX inset can be without the
5590 // \nocite{*} option
5593 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5594 // Do we have addcontentsline?
5595 if (contentslineContent == "\\refname") {
5596 BibOpts = "bibtotoc";
5597 // clear string because next BibTeX inset can be without addcontentsline
5598 contentslineContent.clear();
5600 // Do we have a bibliographystyle set?
5601 if (!bibliographystyle.empty()) {
5602 if (BibOpts.empty())
5603 BibOpts = normalize_filename(bibliographystyle);
5605 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5606 // clear it because each bibtex entry has its style
5607 // and we need an empty string to handle \phantomsection
5608 bibliographystyle.clear();
5610 os << "options " << '"' << BibOpts << '"' << "\n";
5611 if (p.getEncoding() != preamble.docencoding) {
5612 Encoding const * const enc = encodings.fromIconvName(
5613 p.getEncoding(), Encoding::inputenc, true);
5615 warning_message("Unknown bib encoding " + p.getEncoding()
5618 os << "encoding " << '"' << enc->name() << '"' << "\n";
5624 if (t.cs() == "printbibliography") {
5625 context.check_layout(os);
5627 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5628 vector<string> opts = getVectorFromString(bbloptions);
5629 vector<string>::iterator it =
5630 find(opts.begin(), opts.end(), "heading=bibintoc");
5631 if (it != opts.end()) {
5633 BibOpts = "bibtotoc";
5635 bbloptions = getStringFromVector(opts);
5636 begin_command_inset(os, "bibtex", "bibtex");
5637 if (!btprint.empty()) {
5638 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5639 // clear the string because the next BibTeX inset can be without the
5640 // \nocite{*} option
5644 for (auto const & bf : preamble.biblatex_bibliographies) {
5645 if (!bibfiles.empty())
5647 bibfiles += normalize_filename(bf);
5649 if (!bibfiles.empty())
5650 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5651 // Do we have addcontentsline?
5652 if (contentslineContent == "\\refname") {
5653 BibOpts = "bibtotoc";
5654 // clear string because next BibTeX inset can be without addcontentsline
5655 contentslineContent.clear();
5657 os << "options " << '"' << BibOpts << '"' << "\n";
5658 if (!bbloptions.empty())
5659 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5660 if (!preamble.bibencoding.empty()) {
5661 Encoding const * const enc = encodings.fromLaTeXName(
5662 preamble.bibencoding, Encoding::inputenc, true);
5664 warning_message("Unknown bib encoding " + preamble.bibencoding
5667 os << "encoding " << '"' << enc->name() << '"' << "\n";
5670 for (auto const & bf : preamble.biblatex_encodings) {
5671 if (!bibfileencs.empty())
5672 bibfileencs += "\t";
5675 if (!bibfileencs.empty())
5676 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5678 need_commentbib = false;
5682 if (t.cs() == "bibbysection") {
5683 context.check_layout(os);
5685 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5686 vector<string> opts = getVectorFromString(bbloptions);
5687 vector<string>::iterator it =
5688 find(opts.begin(), opts.end(), "heading=bibintoc");
5689 if (it != opts.end()) {
5691 BibOpts = "bibtotoc";
5693 bbloptions = getStringFromVector(opts);
5694 begin_command_inset(os, "bibtex", "bibtex");
5695 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5697 for (auto const & bf : preamble.biblatex_bibliographies) {
5698 if (!bibfiles.empty())
5700 bibfiles += normalize_filename(bf);
5702 if (!bibfiles.empty())
5703 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5704 os << "options " << '"' << BibOpts << '"' << "\n";
5705 if (!bbloptions.empty())
5706 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5708 need_commentbib = false;
5712 if (t.cs() == "parbox") {
5713 // Test whether this is an outer box of a shaded box
5715 // swallow arguments
5716 while (p.hasOpt()) {
5718 p.skip_spaces(true);
5721 p.skip_spaces(true);
5723 if (p.next_token().cat() == catBegin)
5725 p.skip_spaces(true);
5726 Token to = p.get_token();
5727 bool shaded = false;
5728 if (to.asInput() == "\\begin") {
5729 p.skip_spaces(true);
5730 if (p.getArg('{', '}') == "shaded")
5735 parse_outer_box(p, os, FLAG_ITEM, outer,
5736 context, "parbox", "shaded");
5738 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5739 "", "", t.cs(), "", "");
5743 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5744 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5745 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5746 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5750 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5751 string backgroundcolor;
5752 preamble.registerAutomaticallyLoadedPackage("xcolor");
5753 if (t.cs() == "fcolorbox") {
5754 string const framecolor = p.getArg('{', '}');
5755 backgroundcolor = p.getArg('{', '}');
5756 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5758 backgroundcolor = p.getArg('{', '}');
5759 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5764 // FIXME: due to the compiler limit of "if" nestings
5765 // the code for the alignment was put here
5766 // put them in their own if if this is fixed
5767 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5768 || t.cs() == "shadowsize") {
5769 if (t.cs() == "fboxrule")
5771 if (t.cs() == "fboxsep")
5773 if (t.cs() == "shadowsize")
5775 p.skip_spaces(true);
5776 while (p.good() && p.next_token().cat() != catSpace
5777 && p.next_token().cat() != catNewline
5778 && p.next_token().cat() != catEscape) {
5779 if (t.cs() == "fboxrule")
5780 fboxrule = fboxrule + p.get_token().asInput();
5781 if (t.cs() == "fboxsep")
5782 fboxsep = fboxsep + p.get_token().asInput();
5783 if (t.cs() == "shadowsize")
5784 shadow_size = shadow_size + p.get_token().asInput();
5789 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5790 if (context.in_table_cell) {
5791 if (t.cs() == "raggedleft")
5792 context.cell_align = 'r';
5793 else if (t.cs() == "centering")
5794 context.cell_align = 'c';
5795 else if (t.cs() == "raggedright")
5796 context.cell_align = 'l';
5797 p.skip_spaces(true);
5799 output_ert_inset(os, t.asInput(), context);
5804 //\framebox() is part of the picture environment and different from \framebox{}
5805 //\framebox{} will be parsed by parse_outer_box
5806 if (t.cs() == "framebox") {
5807 if (p.next_token().character() == '(') {
5808 //the syntax is: \framebox(x,y)[position]{content}
5809 string arg = t.asInput();
5810 arg += p.getFullParentheseArg();
5811 arg += p.getFullOpt();
5812 eat_whitespace(p, os, context, false);
5813 output_ert_inset(os, arg + '{', context);
5814 parse_text(p, os, FLAG_ITEM, outer, context);
5815 output_ert_inset(os, "}", context);
5817 //the syntax is: \framebox[width][position]{content}
5818 string special = p.getFullOpt();
5819 special += p.getOpt();
5820 parse_outer_box(p, os, FLAG_ITEM, outer,
5821 context, t.cs(), special);
5826 //\makebox() is part of the picture environment and different from \makebox{}
5827 //\makebox{} will be parsed by parse_box
5828 if (t.cs() == "makebox") {
5829 if (p.next_token().character() == '(') {
5830 //the syntax is: \makebox(x,y)[position]{content}
5831 string arg = t.asInput();
5832 arg += p.getFullParentheseArg();
5833 arg += p.getFullOpt();
5834 eat_whitespace(p, os, context, false);
5835 output_ert_inset(os, arg + '{', context);
5836 parse_text(p, os, FLAG_ITEM, outer, context);
5837 output_ert_inset(os, "}", context);
5839 //the syntax is: \makebox[width][position]{content}
5840 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5841 "", "", t.cs(), "", "");
5845 if (t.cs() == "smallskip" ||
5846 t.cs() == "medskip" ||
5847 t.cs() == "bigskip" ||
5848 t.cs() == "vfill") {
5849 context.check_layout(os);
5850 begin_inset(os, "VSpace ");
5853 skip_spaces_braces(p);
5857 if ((where = is_known(t.cs(), known_spaces))
5858 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5859 context.check_layout(os);
5860 begin_inset(os, "space ");
5861 os << '\\' << known_coded_spaces[where - known_spaces]
5864 // LaTeX swallows whitespace after all spaces except
5865 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5866 // We have to do that here, too, because LyX
5867 // adds "{}" which would make the spaces significant.
5868 if (!contains(",>!;:", t.cs()))
5869 eat_whitespace(p, os, context, false);
5870 // LyX adds "{}" after all spaces except "\\ " and
5871 // "\\,", so we have to remove "{}".
5872 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5873 // remove the braces after "\\,", too.
5879 if (t.cs() == "newpage" ||
5880 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5881 t.cs() == "clearpage" ||
5882 t.cs() == "cleardoublepage" ||
5883 t.cs() == "nopagebreak") {
5884 context.check_layout(os);
5885 begin_inset(os, "Newpage ");
5888 skip_spaces_braces(p);
5892 if (t.cs() == "DeclareRobustCommand" ||
5893 t.cs() == "DeclareRobustCommandx" ||
5894 t.cs() == "newcommand" ||
5895 t.cs() == "newcommandx" ||
5896 t.cs() == "providecommand" ||
5897 t.cs() == "providecommandx" ||
5898 t.cs() == "renewcommand" ||
5899 t.cs() == "renewcommandx") {
5900 // DeclareRobustCommand, DeclareRobustCommandx,
5901 // providecommand and providecommandx could be handled
5902 // by parse_command(), but we need to call
5903 // add_known_command() here.
5904 string name = t.asInput();
5905 if (p.next_token().asInput() == "*") {
5906 // Starred form. Eat '*'
5910 string const command = p.verbatim_item();
5911 string const opt1 = p.getFullOpt();
5912 string const opt2 = p.getFullOpt();
5913 add_known_command(command, opt1, !opt2.empty());
5914 string const ert = name + '{' + command + '}' +
5916 '{' + p.verbatim_item() + '}';
5918 if (t.cs() == "DeclareRobustCommand" ||
5919 t.cs() == "DeclareRobustCommandx" ||
5920 t.cs() == "providecommand" ||
5921 t.cs() == "providecommandx" ||
5922 name[name.length()-1] == '*')
5923 output_ert_inset(os, ert, context);
5925 context.check_layout(os);
5926 begin_inset(os, "FormulaMacro");
5933 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5934 // let could be handled by parse_command(),
5935 // but we need to call add_known_command() here.
5936 string ert = t.asInput();
5939 if (p.next_token().cat() == catBegin) {
5940 name = p.verbatim_item();
5941 ert += '{' + name + '}';
5943 name = p.verbatim_item();
5948 if (p.next_token().cat() == catBegin) {
5949 command = p.verbatim_item();
5950 ert += '{' + command + '}';
5952 command = p.verbatim_item();
5955 // If command is known, make name known too, to parse
5956 // its arguments correctly. For this reason we also
5957 // have commands in syntax.default that are hardcoded.
5958 CommandMap::iterator it = known_commands.find(command);
5959 if (it != known_commands.end())
5960 known_commands[t.asInput()] = it->second;
5961 output_ert_inset(os, ert, context);
5965 if (t.cs() == "hspace" || t.cs() == "vspace") {
5968 string name = t.asInput();
5969 string const length = p.verbatim_item();
5972 bool valid = splitLatexLength(length, valstring, unit);
5973 bool known_hspace = false;
5974 bool known_vspace = false;
5975 bool known_unit = false;
5978 istringstream iss(valstring);
5981 if (t.cs()[0] == 'h') {
5982 if (unit == "\\fill") {
5987 known_hspace = true;
5990 if (unit == "\\smallskipamount") {
5992 known_vspace = true;
5993 } else if (unit == "\\medskipamount") {
5995 known_vspace = true;
5996 } else if (unit == "\\bigskipamount") {
5998 known_vspace = true;
5999 } else if (length == "\\baselineskip") {
6001 known_vspace = true;
6002 } else if (unit == "\\fill") {
6004 known_vspace = true;
6008 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
6010 known_vspace = true;
6012 if (!known_hspace && !known_vspace) {
6013 switch (unitFromString(unit)) {
6029 //unitFromString(unit) fails for relative units like Length::PCW
6030 // therefore handle them separately
6031 if (unit == "\\paperwidth" || unit == "\\columnwidth"
6032 || unit == "\\textwidth" || unit == "\\linewidth"
6033 || unit == "\\textheight" || unit == "\\paperheight"
6034 || unit == "\\baselineskip")
6042 // check for glue lengths
6043 bool is_gluelength = false;
6044 string gluelength = length;
6045 string::size_type i = length.find(" minus");
6046 if (i == string::npos) {
6047 i = length.find(" plus");
6048 if (i != string::npos)
6049 is_gluelength = true;
6051 is_gluelength = true;
6052 // if yes transform "9xx minus 8yy plus 7zz"
6054 if (is_gluelength) {
6055 i = gluelength.find(" minus");
6056 if (i != string::npos)
6057 gluelength.replace(i, 7, "-");
6058 i = gluelength.find(" plus");
6059 if (i != string::npos)
6060 gluelength.replace(i, 6, "+");
6063 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
6064 // Literal horizontal length or known variable
6065 context.check_layout(os);
6066 begin_inset(os, "space ");
6074 if (known_unit && !known_hspace)
6075 os << "\n\\length " << translate_len(length);
6077 os << "\n\\length " << gluelength;
6079 } else if (known_unit || known_vspace || is_gluelength) {
6080 // Literal vertical length or known variable
6081 context.check_layout(os);
6082 begin_inset(os, "VSpace ");
6085 if (known_unit && !known_vspace)
6086 os << translate_len(length);
6093 // LyX can't handle other length variables in Inset VSpace/space
6098 output_ert_inset(os, name + '{' + unit + '}', context);
6099 else if (value == -1.0)
6100 output_ert_inset(os, name + "{-" + unit + '}', context);
6102 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
6104 output_ert_inset(os, name + '{' + length + '}', context);
6109 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
6110 // might be one or several options or a star.
6111 // The single '=' is meant here.
6112 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
6116 context.check_layout(os);
6117 // store the latexparam here. This is eaten in parse_text_in_inset
6118 context.latexparam = newinsetlayout->latexparam();
6119 docstring name = newinsetlayout->name();
6120 bool const caption = name.find(from_ascii("Caption:")) == 0;
6122 // Already done for floating minted listings.
6123 if (minted_float.empty()) {
6124 begin_inset(os, "Caption ");
6125 os << to_utf8(name.substr(8)) << '\n';
6128 // FIXME: what do we do if the prefix is not Flex: ?
6129 if (prefixIs(name, from_ascii("Flex:")))
6131 begin_inset(os, "Flex ");
6132 os << to_utf8(name) << '\n'
6133 << "status collapsed\n";
6135 if (!minted_float.empty()) {
6136 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6137 } else if (newinsetlayout->isPassThru()) {
6138 // set catcodes to verbatim early, just in case.
6139 p.setCatcodes(VERBATIM_CATCODES);
6140 string delim = p.get_token().asInput();
6142 warning_message("bad delimiter for command " + t.asInput());
6143 //FIXME: handle error condition
6144 string const arg = p.verbatimStuff("}").second;
6145 Context newcontext(true, context.textclass);
6146 if (newinsetlayout->forcePlainLayout())
6147 newcontext.layout = &context.textclass.plainLayout();
6148 output_ert(os, arg, newcontext);
6150 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6151 context.latexparam.clear();
6154 // Minted caption insets are not closed here because
6155 // we collect everything into the caption.
6156 if (minted_float.empty())
6161 // The single '=' is meant here.
6162 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
6166 context.check_layout(os);
6167 docstring name = newinsetlayout->name();
6168 bool const caption = name.find(from_ascii("Caption:")) == 0;
6170 // Already done for floating minted listings.
6171 if (minted_float.empty()) {
6172 begin_inset(os, "Caption ");
6173 os << to_utf8(name.substr(8)) << '\n';
6176 // FIXME: what do we do if the prefix is not Flex: ?
6177 if (prefixIs(name, from_ascii("Flex:")))
6179 begin_inset(os, "Flex ");
6180 os << to_utf8(name) << '\n'
6181 << "status collapsed\n";
6183 if (!minted_float.empty()) {
6184 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6185 } else if (newinsetlayout->isPassThru()) {
6186 // set catcodes to verbatim early, just in case.
6187 p.setCatcodes(VERBATIM_CATCODES);
6188 string delim = p.get_token().asInput();
6190 warning_message("bad delimiter for command " + t.asInput());
6191 //FIXME: handle error condition
6192 string const arg = p.verbatimStuff("}").second;
6193 Context newcontext(true, context.textclass);
6194 if (newinsetlayout->forcePlainLayout())
6195 newcontext.layout = &context.textclass.plainLayout();
6196 output_ert(os, arg, newcontext);
6198 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6201 // Minted caption insets are not closed here because
6202 // we collect everything into the caption.
6203 if (minted_float.empty())
6208 if (t.cs() == "includepdf") {
6210 string const arg = p.getArg('[', ']');
6211 map<string, string> opts;
6212 vector<string> keys;
6213 split_map(arg, opts, keys);
6214 string name = normalize_filename(p.verbatim_item());
6215 string const path = getMasterFilePath(true);
6216 // We want to preserve relative / absolute filenames,
6217 // therefore path is only used for testing
6218 if (!makeAbsPath(name, path).exists()) {
6219 // The file extension is probably missing.
6220 // Now try to find it out.
6221 char const * const pdfpages_format[] = {"pdf", 0};
6222 string const pdftex_name =
6223 find_file(name, path, pdfpages_format);
6224 if (!pdftex_name.empty()) {
6229 FileName const absname = makeAbsPath(name, path);
6230 if (absname.exists())
6232 fix_child_filename(name);
6233 copy_file(absname, name);
6235 warning_message("Could not find file '" + name + "'.");
6237 context.check_layout(os);
6238 begin_inset(os, "External\n\ttemplate ");
6239 os << "PDFPages\n\tfilename "
6241 // parse the options
6242 if (opts.find("pages") != opts.end())
6243 os << "\textra LaTeX \"pages="
6244 << opts["pages"] << "\"\n";
6245 if (opts.find("angle") != opts.end())
6246 os << "\trotateAngle "
6247 << opts["angle"] << '\n';
6248 if (opts.find("origin") != opts.end()) {
6250 string const opt = opts["origin"];
6251 if (opt == "tl") ss << "topleft";
6252 if (opt == "bl") ss << "bottomleft";
6253 if (opt == "Bl") ss << "baselineleft";
6254 if (opt == "c") ss << "center";
6255 if (opt == "tc") ss << "topcenter";
6256 if (opt == "bc") ss << "bottomcenter";
6257 if (opt == "Bc") ss << "baselinecenter";
6258 if (opt == "tr") ss << "topright";
6259 if (opt == "br") ss << "bottomright";
6260 if (opt == "Br") ss << "baselineright";
6261 if (!ss.str().empty())
6262 os << "\trotateOrigin " << ss.str() << '\n';
6264 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
6266 if (opts.find("width") != opts.end())
6268 << translate_len(opts["width"]) << '\n';
6269 if (opts.find("height") != opts.end())
6271 << translate_len(opts["height"]) << '\n';
6272 if (opts.find("keepaspectratio") != opts.end())
6273 os << "\tkeepAspectRatio\n";
6275 context.check_layout(os);
6276 registerExternalTemplatePackages("PDFPages");
6280 if (t.cs() == "loadgame") {
6282 string name = normalize_filename(p.verbatim_item());
6283 string const path = getMasterFilePath(true);
6284 // We want to preserve relative / absolute filenames,
6285 // therefore path is only used for testing
6286 if (!makeAbsPath(name, path).exists()) {
6287 // The file extension is probably missing.
6288 // Now try to find it out.
6289 char const * const lyxskak_format[] = {"fen", 0};
6290 string const lyxskak_name =
6291 find_file(name, path, lyxskak_format);
6292 if (!lyxskak_name.empty())
6293 name = lyxskak_name;
6295 FileName const absname = makeAbsPath(name, path);
6296 if (absname.exists())
6298 fix_child_filename(name);
6299 copy_file(absname, name);
6301 warning_message("Could not find file '" + name + "'.");
6302 context.check_layout(os);
6303 begin_inset(os, "External\n\ttemplate ");
6304 os << "ChessDiagram\n\tfilename "
6307 context.check_layout(os);
6308 // after a \loadgame follows a \showboard
6309 if (p.get_token().asInput() == "showboard")
6311 registerExternalTemplatePackages("ChessDiagram");
6315 // try to see whether the string is in unicodesymbols
6316 // Only use text mode commands, since we are in text mode here,
6317 // and math commands may be invalid (bug 6797)
6318 string name = t.asInput();
6319 // handle the dingbats, cyrillic and greek
6320 if (name == "\\textcyr")
6321 name = "\\textcyrillic";
6322 if (name == "\\ding" || name == "\\textcyrillic" ||
6323 (name == "\\textgreek" && !preamble.usePolyglossia()))
6324 name = name + '{' + p.getArg('{', '}') + '}';
6325 // handle the ifsym characters
6326 else if (name == "\\textifsymbol") {
6327 string const optif = p.getFullOpt();
6328 string const argif = p.getArg('{', '}');
6329 name = name + optif + '{' + argif + '}';
6331 // handle the \ascii characters
6332 // the case of \ascii within braces, as LyX outputs it, is already
6333 // handled for t.cat() == catBegin
6334 else if (name == "\\ascii") {
6335 // the code is "\asci\xxx"
6336 name = "{" + name + p.get_token().asInput() + "}";
6339 // handle some TIPA special characters
6340 else if (preamble.isPackageUsed("tipa")) {
6341 if (name == "\\s") {
6342 // fromLaTeXCommand() does not yet
6343 // recognize tipa short cuts
6344 name = "\\textsyllabic";
6345 } else if (name == "\\=" &&
6346 p.next_token().asInput() == "*") {
6347 // fromLaTeXCommand() does not yet
6348 // recognize tipa short cuts
6350 name = "\\textsubbar";
6351 } else if (name == "\\textdoublevertline") {
6352 // FIXME: This is not correct,
6353 // \textvertline is higher than \textbardbl
6354 name = "\\textbardbl";
6356 } else if (name == "\\!" ) {
6357 if (p.next_token().asInput() == "b") {
6358 p.get_token(); // eat 'b'
6361 } else if (p.next_token().asInput() == "d") {
6365 } else if (p.next_token().asInput() == "g") {
6369 } else if (p.next_token().asInput() == "G") {
6371 name = "\\texthtscg";
6373 } else if (p.next_token().asInput() == "j") {
6375 name = "\\texthtbardotlessj";
6377 } else if (p.next_token().asInput() == "o") {
6379 name = "\\textbullseye";
6382 } else if (name == "\\*" ) {
6383 if (p.next_token().asInput() == "k") {
6385 name = "\\textturnk";
6387 } else if (p.next_token().asInput() == "r") {
6388 p.get_token(); // eat 'b'
6389 name = "\\textturnr";
6391 } else if (p.next_token().asInput() == "t") {
6393 name = "\\textturnt";
6395 } else if (p.next_token().asInput() == "w") {
6397 name = "\\textturnw";
6402 if ((name.size() == 2 &&
6403 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6404 p.next_token().asInput() != "*") ||
6405 is_known(name.substr(1), known_tipa_marks)) {
6406 // name is a command that corresponds to a
6407 // combining character in unicodesymbols.
6408 // Append the argument, fromLaTeXCommand()
6409 // will either convert it to a single
6410 // character or a combining sequence.
6411 name += '{' + p.verbatim_item() + '}';
6413 // now get the character from unicodesymbols
6417 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6418 Encodings::TEXT_CMD, termination, rem, &req));
6420 context.check_layout(os);
6423 output_ert_inset(os, to_utf8(rem), context);
6425 skip_spaces_braces(p);
6426 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6427 preamble.registerAutomaticallyLoadedPackage(*it);
6429 //warning_message("#: " + t + " mode: " + mode);
6430 // heuristic: read up to next non-nested space
6432 string s = t.asInput();
6433 string z = p.verbatim_item();
6434 while (p.good() && z != " " && !z.empty()) {
6435 //warning_message("read: " + z);
6437 z = p.verbatim_item();
6439 warning_message("found ERT: " + s);
6440 output_ert_inset(os, s + ' ', context);
6443 if (t.asInput() == name &&
6444 p.next_token().asInput() == "*") {
6445 // Starred commands like \vspace*{}
6446 p.get_token(); // Eat '*'
6449 if (!parse_command(name, p, os, outer, context)) {
6450 output_ert_inset(os, name, context);
6451 // Try to handle options of unknown commands:
6452 // Look if we have optional arguments,
6453 // and if so, put the brackets in ERT.
6454 while (p.hasOpt()) {
6455 p.get_token(); // eat '['
6456 output_ert_inset(os, "[", context);
6457 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6458 output_ert_inset(os, "]", context);
6466 string guessLanguage(Parser & p, string const & lang)
6468 typedef std::map<std::string, size_t> LangMap;
6469 // map from language names to number of characters
6472 for (char const * const * i = supported_CJK_languages; *i; i++)
6473 used[string(*i)] = 0;
6476 Token const t = p.get_token();
6477 // comments are not counted for any language
6478 if (t.cat() == catComment)
6480 // commands are not counted as well, but we need to detect
6481 // \begin{CJK} and switch encoding if needed
6482 if (t.cat() == catEscape) {
6483 if (t.cs() == "inputencoding") {
6484 string const enc = subst(p.verbatim_item(), "\n", " ");
6485 p.setEncoding(enc, Encoding::inputenc);
6488 if (t.cs() != "begin")
6491 // Non-CJK content is counted for lang.
6492 // We do not care about the real language here:
6493 // If we have more non-CJK contents than CJK contents,
6494 // we simply use the language that was specified as
6495 // babel main language.
6496 used[lang] += t.asInput().length();
6499 // Now we are starting an environment
6501 string const name = p.getArg('{', '}');
6502 if (name != "CJK") {
6506 // It is a CJK environment
6508 /* name = */ p.getArg('{', '}');
6509 string const encoding = p.getArg('{', '}');
6510 /* mapping = */ p.getArg('{', '}');
6511 string const encoding_old = p.getEncoding();
6512 char const * const * const where =
6513 is_known(encoding, supported_CJK_encodings);
6515 p.setEncoding(encoding, Encoding::CJK);
6517 p.setEncoding("UTF-8");
6518 string const text = p.ertEnvironment("CJK");
6519 p.setEncoding(encoding_old);
6522 // ignore contents in unknown CJK encoding
6525 // the language of the text
6527 supported_CJK_languages[where - supported_CJK_encodings];
6528 used[cjk] += text.length();
6530 LangMap::const_iterator use = used.begin();
6531 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6532 if (it->second > use->second)
6539 void check_comment_bib(ostream & os, Context & context)
6541 if (!need_commentbib)
6543 // We have a bibliography database, but no bibliography with biblatex
6544 // which is completely valid. Insert a bibtex inset in a note.
6545 context.check_layout(os);
6546 begin_inset(os, "Note Note\n");
6547 os << "status open\n";
6548 os << "\\begin_layout Plain Layout\n";
6549 begin_command_inset(os, "bibtex", "bibtex");
6551 for (auto const & bf : preamble.biblatex_bibliographies) {
6552 if (!bibfiles.empty())
6554 bibfiles += normalize_filename(bf);
6556 if (!bibfiles.empty())
6557 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6559 for (auto const & bf : preamble.biblatex_encodings) {
6560 if (!bibfileencs.empty())
6561 bibfileencs += "\t";
6564 if (!bibfileencs.empty())
6565 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6566 end_inset(os);// Bibtex
6567 os << "\\end_layout\n";
6568 end_inset(os);// Note