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_babel_shorthands[] = { "\"", "|", "-", "~", "=", "/",
149 "~", "*", ":", "_", "x", "'", "`", "<", ">", 0 };
151 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
152 "vpageref", "prettyref", "nameref", "eqref", 0 };
154 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
155 "vpageref", "formatted", "nameref", "eqref", 0 };
157 char const * const known_starref_commands[] = { "ref", "pageref", "vref",
158 "vpageref", "nameref", "eqref", 0 };
160 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
161 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
162 "secref", "subsecref", "tabref", "thmref", 0 };
164 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
165 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
166 "sec", "subsec", "tab", "thm", 0 };
170 * supported CJK encodings
171 * JIS does not work with LyX's encoding conversion
173 const char * const supported_CJK_encodings[] = {
174 "EUC-JP", "KS", "GB", "UTF8",
175 "Bg5", /*"JIS",*/ "SJIS", 0};
178 * the same as supported_CJK_encodings with their corresponding LyX language name
179 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
181 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
182 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
183 * please keep this in sync with supported_CJK_encodings line by line!
185 const char * const supported_CJK_languages[] = {
186 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
187 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
191 * The starred forms are also known except for "citefullauthor",
192 * "citeyear" and "citeyearpar".
194 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
195 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
196 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
200 * No starred form other than "cite*" known.
202 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
203 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
204 // jurabib commands not (yet) supported by LyX:
206 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
207 // "footciteauthor", "footciteyear", "footciteyearpar",
208 "citefield", "citetitle", 0 };
212 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
214 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
215 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
216 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
217 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
218 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
220 // Whether we need to insert a bibtex inset in a comment
221 bool need_commentbib = false;
223 /// LaTeX names for quotes
224 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
225 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
226 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
227 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
230 /// the same as known_quotes with .lyx names
231 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
232 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
233 "gld", "eld", "gls", "ers", "ars",
234 "ars", "als", "als", "erd", "qrs", "qrd", 0};
236 /// LaTeX names for font sizes
237 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
238 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
240 /// the same as known_sizes with .lyx names
241 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
242 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
244 /// LaTeX 2.09 names for font families
245 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
247 /// LaTeX names for font families
248 char const * const known_font_families[] = { "rmfamily", "sffamily",
251 /// LaTeX names for font family changing commands
252 char const * const known_text_font_families[] = { "textrm", "textsf",
255 /// The same as known_old_font_families, known_font_families and
256 /// known_text_font_families with .lyx names
257 char const * const known_coded_font_families[] = { "roman", "sans",
260 /// LaTeX 2.09 names for font series
261 char const * const known_old_font_series[] = { "bf", 0};
263 /// LaTeX names for font series
264 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
266 /// LaTeX names for font series changing commands
267 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
269 /// The same as known_old_font_series, known_font_series and
270 /// known_text_font_series with .lyx names
271 char const * const known_coded_font_series[] = { "bold", "medium", 0};
273 /// LaTeX 2.09 names for font shapes
274 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
276 /// LaTeX names for font shapes
277 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
280 /// LaTeX names for font shape changing commands
281 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
284 /// The same as known_old_font_shapes, known_font_shapes and
285 /// known_text_font_shapes with .lyx names
286 char const * const known_coded_font_shapes[] = { "italic", "slanted",
287 "smallcaps", "up", 0};
289 /// Known special characters which need skip_spaces_braces() afterwards
290 char const * const known_special_chars[] = {"ldots",
291 "lyxarrow", "textcompwordmark",
292 "slash", "textasciitilde", "textasciicircum", "textbackslash",
293 "LyX", "TeX", "LaTeXe",
296 /// special characters from known_special_chars which may have a \\protect before
297 char const * const known_special_protect_chars[] = {"LyX", "TeX",
298 "LaTeXe", "LaTeX", 0};
300 /// the same as known_special_chars with .lyx names
301 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
302 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
303 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
304 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
305 "\\SpecialChar LaTeX\n", 0};
308 * Graphics file extensions known by the dvips driver of the graphics package.
309 * These extensions are used to complete the filename of an included
310 * graphics file if it does not contain an extension.
311 * The order must be the same that latex uses to find a file, because we
312 * will use the first extension that matches.
313 * This is only an approximation for the common cases. If we would want to
314 * do it right in all cases, we would need to know which graphics driver is
315 * used and know the extensions of every driver of the graphics package.
317 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
318 "ps.gz", "eps.Z", "ps.Z", 0};
321 * Graphics file extensions known by the pdftex driver of the graphics package.
322 * \sa known_dvips_graphics_formats
324 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
328 * Known file extensions for TeX files as used by \\include.
330 char const * const known_tex_extensions[] = {"tex", 0};
332 /// spaces known by InsetSpace
333 char const * const known_spaces[] = { " ", "space",
334 ",", "thinspace",// \\, = \\thinspace
335 "quad", "qquad", "enspace", "enskip",
336 ";", ">", "medspace",// \\; = \\> = \\medspace
337 ":", "thickspace",// \\: = \\thickspace
338 "!", "negthinspace",// \\! = \\negthinspace
339 "negmedspace", "negthickspace",
340 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
341 "rightarrowfill", "upbracefill", "downbracefill", 0};
343 /// the same as known_spaces with .lyx names
344 char const * const known_coded_spaces[] = { "space{}", "space{}",
345 "thinspace{}", "thinspace{}",
346 "quad{}", "qquad{}", "enspace{}", "enskip{}",
347 "medspace{}", "medspace{}", "medspace{}",
348 "thickspace{}", "thickspace{}",
349 "negthinspace{}", "negthinspace{}",
350 "negmedspace{}", "negthickspace{}",
351 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
352 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
354 /// known TIPA combining diacritical marks
355 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
356 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
357 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
358 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
359 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
360 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
361 "textsubring", "textsubbar", 0};
363 /// TIPA tones that need special handling
364 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
366 // string to store the float type to be able to determine the type of subfloats
367 string float_type = "";
369 // string to store the float status of minted listings
370 string minted_float = "";
372 // whether a caption has been parsed for a floating minted listing
373 bool minted_float_has_caption = false;
375 // The caption for non-floating minted listings
376 string minted_nonfloat_caption = "";
378 // Characters that have to be escaped by \\ in LaTeX
379 char const * const known_escaped_chars[] = {
380 "&", "_", "$", "%", "#", "^", "{", "}", 0};
383 /// splits "x=z, y=b" into a map and an ordered keyword vector
384 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
389 keys.resize(v.size());
390 for (size_t i = 0; i < v.size(); ++i) {
391 size_t const pos = v[i].find('=');
392 string const index = trimSpaceAndEol(v[i].substr(0, pos));
393 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
401 * Split a LaTeX length into value and unit.
402 * The latter can be a real unit like "pt", or a latex length variable
403 * like "\textwidth". The unit may contain additional stuff like glue
404 * lengths, but we don't care, because such lengths are ERT anyway.
405 * \returns true if \p value and \p unit are valid.
407 bool splitLatexLength(string const & len, string & value, string & unit)
411 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
412 //'4,5' is a valid LaTeX length number. Change it to '4.5'
413 string const length = subst(len, ',', '.');
414 if (i == string::npos)
417 if (len[0] == '\\') {
418 // We had something like \textwidth without a factor
424 value = trimSpaceAndEol(string(length, 0, i));
428 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
429 if (contains(len, '\\'))
430 unit = trimSpaceAndEol(string(len, i));
432 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
437 /// A simple function to translate a latex length to something LyX can
438 /// understand. Not perfect, but rather best-effort.
439 bool translate_len(string const & length, string & valstring, string & unit)
441 if (!splitLatexLength(length, valstring, unit))
443 // LyX uses percent values
445 istringstream iss(valstring);
450 string const percentval = oss.str();
452 if (unit.empty() || unit[0] != '\\')
454 string::size_type const i = unit.find(' ');
455 string const endlen = (i == string::npos) ? string() : string(unit, i);
456 if (unit == "\\textwidth") {
457 valstring = percentval;
458 unit = "text%" + endlen;
459 } else if (unit == "\\columnwidth") {
460 valstring = percentval;
461 unit = "col%" + endlen;
462 } else if (unit == "\\paperwidth") {
463 valstring = percentval;
464 unit = "page%" + endlen;
465 } else if (unit == "\\linewidth") {
466 valstring = percentval;
467 unit = "line%" + endlen;
468 } else if (unit == "\\paperheight") {
469 valstring = percentval;
470 unit = "pheight%" + endlen;
471 } else if (unit == "\\textheight") {
472 valstring = percentval;
473 unit = "theight%" + endlen;
474 } else if (unit == "\\baselineskip") {
475 valstring = percentval;
476 unit = "baselineskip%" + endlen;
482 /// If we have ambiguous quotation marks, make a smart guess
483 /// based on main quote style
484 string guessQuoteStyle(string const & in, bool const opening)
487 if (prefixIs(in, "qr")) {// straight quote
489 res = subst(res, "r", "l");
490 } else if (in == "eld") {// ``
491 if (preamble.quotesStyle() == "german")
493 else if (preamble.quotesStyle() == "british")
495 else if (preamble.quotesStyle() == "french")
497 else if (preamble.quotesStyle() == "russian")
499 } else if (in == "erd") {// ''
500 if (preamble.quotesStyle() == "polish")
502 else if (preamble.quotesStyle() == "british")
504 else if (preamble.quotesStyle() == "french")
506 else if (preamble.quotesStyle() == "hungarian")
508 else if (preamble.quotesStyle() == "swedish")
509 res = opening ? "sld" : "srd";
510 else if (preamble.quotesStyle() == "hebrew")
512 } else if (in == "els") {// `
513 if (preamble.quotesStyle() == "german")
515 else if (preamble.quotesStyle() == "british")
517 } else if (in == "ers") {// '
518 if (preamble.quotesStyle() == "polish")
520 else if (preamble.quotesStyle() == "british")
522 else if (preamble.quotesStyle() == "swedish")
523 res = opening ? "sls" : "srs";
524 else if (preamble.quotesStyle() == "hebrew")
526 } else if (in == "ard") {// >>
527 if (preamble.quotesStyle() == "swiss")
529 else if (preamble.quotesStyle() == "french")
531 else if (preamble.quotesStyle() == "russian")
533 else if (preamble.quotesStyle() == "hungarian")
535 } else if (in == "ald") {// <<
536 if (preamble.quotesStyle() == "swiss")
538 else if (preamble.quotesStyle() == "french")
540 else if (preamble.quotesStyle() == "russian")
542 else if (preamble.quotesStyle() == "hungarian")
544 } else if (in == "ars") {// >
545 if (preamble.quotesStyle() == "swiss")
547 } else if (in == "als") {// <
548 if (preamble.quotesStyle() == "swiss")
550 } else if (in == "gld") {// ,,
551 if (preamble.quotesStyle() == "polish")
553 else if (preamble.quotesStyle() == "hungarian")
555 else if (preamble.quotesStyle() == "russian")
557 else if (preamble.quotesStyle() == "hebrew")
559 } else if (in == "gls") {// ,
560 if (preamble.quotesStyle() == "polish")
562 else if (preamble.quotesStyle() == "hebrew")
569 string const fromPolyglossiaEnvironment(string const & s)
571 // Since \arabic is taken by the LaTeX kernel,
572 // the Arabic polyglossia environment is upcased
580 string uncapitalize(string const & s)
582 docstring in = from_ascii(s);
583 char_type t = lowercase(s[0]);
589 bool isCapitalized(string const & s)
591 docstring in = from_ascii(s);
592 char_type t = uppercase(s[0]);
594 return to_ascii(in) == s;
601 string translate_len(string const & length)
605 if (translate_len(length, value, unit))
607 // If the input is invalid, return what we have.
615 * Translates a LaTeX length into \p value, \p unit and
616 * \p special parts suitable for a box inset.
617 * The difference from translate_len() is that a box inset knows about
618 * some special "units" that are stored in \p special.
620 void translate_box_len(string const & length, string & value, string & unit, string & special)
622 if (translate_len(length, value, unit)) {
623 if (unit == "\\height" || unit == "\\depth" ||
624 unit == "\\totalheight" || unit == "\\width") {
625 special = unit.substr(1);
626 // The unit is not used, but LyX requires a dummy setting
638 void begin_inset(ostream & os, string const & name)
640 os << "\n\\begin_inset " << name;
644 void begin_command_inset(ostream & os, string const & name,
645 string const & latexname)
647 begin_inset(os, "CommandInset ");
648 os << name << "\nLatexCommand " << latexname << '\n';
652 void end_inset(ostream & os)
654 os << "\n\\end_inset\n\n";
658 bool skip_braces(Parser & p)
660 if (p.next_token().cat() != catBegin)
663 if (p.next_token().cat() == catEnd) {
672 /// replace LaTeX commands in \p s from the unicodesymbols file with their
674 pair<bool, docstring> convert_unicodesymbols(docstring s)
678 for (size_t i = 0; i < s.size();) {
687 docstring parsed = normalize_c(Encodings::fromLaTeXCommand(s,
688 Encodings::TEXT_CMD, termination, rem, &req));
689 set<string>::const_iterator it = req.begin();
690 set<string>::const_iterator en = req.end();
691 for (; it != en; ++it)
692 preamble.registerAutomaticallyLoadedPackage(*it);
695 if (s.empty() || s[0] != '\\')
699 for (auto const & c : known_escaped_chars)
700 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
705 return make_pair(res, os.str());
709 /// try to convert \p s to a valid InsetCommand argument
710 /// return whether this succeeded. If not, these command insets
711 /// get the "literate" flag.
712 pair<bool, string> convert_latexed_command_inset_arg(string s)
714 bool success = false;
716 // since we don't know the input encoding we can't use from_utf8
717 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
719 s = to_utf8(res.second);
721 // LyX cannot handle newlines in a latex command
722 return make_pair(success, subst(s, "\n", " "));
725 /// try to convert \p s to a valid InsetCommand argument
726 /// without trying to recode macros.
727 string convert_literate_command_inset_arg(string const & s)
729 // LyX cannot handle newlines in a latex command
730 return subst(s, "\n", " ");
733 void output_ert(ostream & os, string const & s, Context & context)
735 context.check_layout(os);
736 for (char const c : s) {
738 os << "\n\\backslash\n";
739 else if (c == '\n') {
740 context.new_paragraph(os);
741 context.check_layout(os);
745 context.check_end_layout(os);
749 void output_ert_inset(ostream & os, string const & s, Context & context)
751 // We must have a valid layout before outputting the ERT inset.
752 context.check_layout(os);
753 Context newcontext(true, context.textclass);
754 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
755 if (layout.forcePlainLayout())
756 newcontext.layout = &context.textclass.plainLayout();
757 begin_inset(os, "ERT");
758 os << "\nstatus collapsed\n";
759 output_ert(os, s, newcontext);
764 void output_comment(Parser & p, ostream & os, string const & s,
767 if (p.next_token().cat() == catNewline)
768 output_ert_inset(os, '%' + s, context);
770 output_ert_inset(os, '%' + s + '\n', context);
774 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
775 string const & latexparam = string())
777 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
780 if (checkModule(name, command))
781 return findLayoutWithoutModule(textclass, name, command, latexparam);
786 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
787 string const & latexparam = string())
789 InsetLayout const * insetlayout =
790 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
793 if (checkModule(name, command))
794 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
799 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
800 bool eatNewline = true);
804 * Skips whitespace and braces.
805 * This should be called after a command has been parsed that is not put into
806 * ERT, and where LyX adds "{}" if needed.
808 void skip_spaces_braces(Parser & p, bool keepws = false)
810 /* The following four examples produce the same typeset output and
811 should be handled by this function:
819 // Unfortunately we need to skip comments, too.
820 // We can't use eat_whitespace since writing them after the {}
821 // results in different output in some cases.
822 bool const skipped_spaces = p.skip_spaces(true);
823 bool const skipped_braces = skip_braces(p);
824 if (keepws && skipped_spaces && !skipped_braces)
825 // put back the space (it is better handled by check_space)
826 p.unskip_spaces(true);
830 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
831 Context & context, Layout::LaTeXArgMap const & latexargs)
833 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
835 context.check_layout(os);
841 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
842 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
843 for (; lait != laend; ++lait) {
845 eat_whitespace(p, os, context, false);
846 if (lait->second.mandatory) {
847 if (p.next_token().cat() != catBegin)
849 string ldelim = to_utf8(lait->second.ldelim);
850 string rdelim = to_utf8(lait->second.rdelim);
855 p.get_token(); // eat ldelim
856 if (ldelim.size() > 1)
857 p.get_token(); // eat ldelim
859 context.check_layout(os);
862 begin_inset(os, "Argument ");
865 os << i << "\nstatus collapsed\n\n";
866 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
869 string ldelim = to_utf8(lait->second.ldelim);
870 string rdelim = to_utf8(lait->second.rdelim);
875 string tok = p.next_token().asInput();
876 // we only support delimiters with max 2 chars for now.
877 if (ldelim.size() > 1)
878 tok += p.next_next_token().asInput();
879 if (p.next_token().cat() == catEscape || tok != ldelim)
881 p.get_token(); // eat ldelim
882 if (ldelim.size() > 1)
883 p.get_token(); // eat ldelim
885 context.check_layout(os);
888 begin_inset(os, "Argument ");
891 os << i << "\nstatus collapsed\n\n";
892 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
895 eat_whitespace(p, os, context, false);
900 void output_command_layout(ostream & os, Parser & p, bool outer,
901 Context & parent_context,
902 Layout const * newlayout)
904 TeXFont const oldFont = parent_context.font;
905 // save the current font size
906 string const size = oldFont.size;
907 // reset the font size to default, because the font size switches
908 // don't affect section headings and the like
909 parent_context.font.size = Context::normalfont.size;
910 // we only need to write the font change if we have an open layout
911 if (!parent_context.atParagraphStart())
912 output_font_change(os, oldFont, parent_context.font);
913 parent_context.check_end_layout(os);
914 Context context(true, parent_context.textclass, newlayout,
915 parent_context.layout, parent_context.font);
916 if (parent_context.deeper_paragraph) {
917 // We are beginning a nested environment after a
918 // deeper paragraph inside the outer list environment.
919 // Therefore we don't need to output a "begin deeper".
920 context.need_end_deeper = true;
922 context.check_deeper(os);
923 output_arguments(os, p, outer, true, string(), context,
924 context.layout->latexargs());
925 // If we have a latex param, we eat it here.
926 if (!parent_context.latexparam.empty()) {
928 Context dummy(true, parent_context.textclass);
929 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
930 string(1, parent_context.latexparam.back()));
932 parse_text(p, os, FLAG_ITEM, outer, context);
933 output_arguments(os, p, outer, false, "post", context,
934 context.layout->postcommandargs());
935 context.check_end_layout(os);
936 if (parent_context.deeper_paragraph) {
937 // We must suppress the "end deeper" because we
938 // suppressed the "begin deeper" above.
939 context.need_end_deeper = false;
941 context.check_end_deeper(os);
942 // We don't need really a new paragraph, but
943 // we must make sure that the next item gets a \begin_layout.
944 parent_context.new_paragraph(os);
945 // Set the font size to the original value. No need to output it here
946 // (Context::begin_layout() will do that if needed)
947 parent_context.font.size = size;
952 * Output a space if necessary.
953 * This function gets called for every whitespace token.
955 * We have three cases here:
956 * 1. A space must be suppressed. Example: The lyxcode case below
957 * 2. A space may be suppressed. Example: Spaces before "\par"
958 * 3. A space must not be suppressed. Example: A space between two words
960 * We currently handle only 1. and 3 and from 2. only the case of
961 * spaces before newlines as a side effect.
963 * 2. could be used to suppress as many spaces as possible. This has two effects:
964 * - Reimporting LyX generated LaTeX files changes almost no whitespace
965 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
966 * The drawback is that the logic inside the function becomes
967 * complicated, and that is the reason why it is not implemented.
969 void check_space(Parser & p, ostream & os, Context & context)
971 Token const next = p.next_token();
972 Token const curr = p.curr_token();
973 // A space before a single newline and vice versa must be ignored
974 // LyX emits a newline before \end{lyxcode}.
975 // This newline must be ignored,
976 // otherwise LyX will add an additional protected space.
977 if (next.cat() == catSpace ||
978 next.cat() == catNewline ||
979 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
982 context.check_layout(os);
988 * Parse all arguments of \p command
990 void parse_arguments(string const & command,
991 vector<ArgumentType> const & template_arguments,
992 Parser & p, ostream & os, bool outer, Context & context)
994 string ert = command;
995 size_t no_arguments = template_arguments.size();
996 for (size_t i = 0; i < no_arguments; ++i) {
997 switch (template_arguments[i]) {
1000 // This argument contains regular LaTeX
1001 output_ert_inset(os, ert + '{', context);
1002 eat_whitespace(p, os, context, false);
1003 if (template_arguments[i] == required)
1004 parse_text(p, os, FLAG_ITEM, outer, context);
1006 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1010 // This argument consists only of a single item.
1011 // The presence of '{' or not must be preserved.
1013 if (p.next_token().cat() == catBegin)
1014 ert += '{' + p.verbatim_item() + '}';
1016 ert += p.verbatim_item();
1020 // This argument may contain special characters
1021 ert += '{' + p.verbatim_item() + '}';
1025 // true because we must not eat whitespace
1026 // if an optional arg follows we must not strip the
1027 // brackets from this one
1028 if (i < no_arguments - 1 &&
1029 template_arguments[i+1] == optional)
1030 ert += p.getFullOpt(true);
1032 ert += p.getOpt(true);
1036 output_ert_inset(os, ert, context);
1041 * Check whether \p command is a known command. If yes,
1042 * handle the command with all arguments.
1043 * \return true if the command was parsed, false otherwise.
1045 bool parse_command(string const & command, Parser & p, ostream & os,
1046 bool outer, Context & context)
1048 if (known_commands.find(command) != known_commands.end()) {
1049 parse_arguments(command, known_commands[command], p, os,
1057 /// Parses a minipage or parbox
1058 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1059 unsigned inner_flags, bool outer, Context & parent_context,
1060 string const & outer_type, string const & special,
1061 string inner_type, string const & frame_color,
1062 string const & background_color)
1066 string hor_pos = "l";
1067 // We need to set the height to the LaTeX default of 1\\totalheight
1068 // for the case when no height argument is given
1069 string height_value = "1";
1070 string height_unit = "in";
1071 string height_special = "totalheight";
1072 string latex_height;
1076 string width_special = "none";
1077 string thickness = "0.4pt";
1078 if (!fboxrule.empty())
1079 thickness = fboxrule;
1081 thickness = "0.4pt";
1083 if (!fboxsep.empty())
1084 separation = fboxsep;
1088 if (!shadow_size.empty())
1089 shadowsize = shadow_size;
1092 string framecolor = "black";
1093 string backgroundcolor = "none";
1094 if (!frame_color.empty())
1095 framecolor = frame_color;
1096 if (!background_color.empty())
1097 backgroundcolor = background_color;
1098 // if there is a color box around the \begin statements have not yet been parsed
1100 if (!frame_color.empty() || !background_color.empty()) {
1101 eat_whitespace(p, os, parent_context, false);
1102 p.get_token().asInput(); // the '{'
1104 if (p.next_token().asInput() == "\\begin") {
1105 p.get_token().asInput();
1107 inner_type = "minipage";
1108 inner_flags = FLAG_END;
1109 active_environments.push_back("minipage");
1112 else if (p.next_token().asInput() == "\\parbox") {
1113 p.get_token().asInput();
1114 inner_type = "parbox";
1115 inner_flags = FLAG_ITEM;
1118 else if (p.next_token().asInput() == "\\makebox") {
1119 p.get_token().asInput();
1120 inner_type = "makebox";
1121 inner_flags = FLAG_ITEM;
1123 // in case there is just \colorbox{color}{text}
1126 inner_type = "makebox";
1127 inner_flags = FLAG_BRACE_LAST;
1132 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1134 if (!inner_type.empty() && p.hasOpt()) {
1135 if (inner_type != "makebox")
1136 position = p.getArg('[', ']');
1138 latex_width = p.getArg('[', ']');
1139 translate_box_len(latex_width, width_value, width_unit, width_special);
1142 if (position != "t" && position != "c" && position != "b") {
1143 warning_message("invalid position " + position
1144 + " for " + inner_type);
1148 if (inner_type != "makebox") {
1149 latex_height = p.getArg('[', ']');
1150 translate_box_len(latex_height, height_value, height_unit, height_special);
1152 string const opt = p.getArg('[', ']');
1155 if (hor_pos != "l" && hor_pos != "c" &&
1156 hor_pos != "r" && hor_pos != "s") {
1157 warning_message("invalid hor_pos "
1166 inner_pos = p.getArg('[', ']');
1167 if (inner_pos != "c" && inner_pos != "t" &&
1168 inner_pos != "b" && inner_pos != "s") {
1169 warning_message("invalid inner_pos "
1170 + inner_pos + " for "
1172 inner_pos = position;
1176 if (inner_type == "makebox")
1180 if (inner_type.empty()) {
1181 if (special.empty() && outer_type != "framebox")
1182 latex_width = "1\\columnwidth";
1185 latex_width = p2.getArg('[', ']');
1186 string const opt = p2.getArg('[', ']');
1189 if (hor_pos != "l" && hor_pos != "c" &&
1190 hor_pos != "r" && hor_pos != "s") {
1191 warning_message("invalid hor_pos "
1197 if (outer_type == "framebox")
1201 } else if (inner_type != "makebox")
1202 latex_width = p.verbatim_item();
1203 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1204 // as this is LyX's standard for such cases (except for makebox)
1205 // \framebox is more special and handled below
1206 if (latex_width.empty() && inner_type != "makebox"
1207 && outer_type != "framebox")
1208 latex_width = "1\\columnwidth";
1210 translate_len(latex_width, width_value, width_unit);
1212 bool shadedparbox = false;
1213 if (inner_type == "shaded") {
1214 eat_whitespace(p, os, parent_context, false);
1215 if (outer_type == "parbox") {
1217 if (p.next_token().cat() == catBegin)
1219 eat_whitespace(p, os, parent_context, false);
1220 shadedparbox = true;
1225 // If we already read the inner box we have to push the inner env
1226 if (!outer_type.empty() && !inner_type.empty() &&
1227 (inner_flags & FLAG_END))
1228 active_environments.push_back(inner_type);
1229 bool use_ert = false;
1230 if (!outer_type.empty() && !inner_type.empty()) {
1231 // Look whether there is some content after the end of the
1232 // inner box, but before the end of the outer box.
1233 // If yes, we need to output ERT.
1235 if (inner_flags & FLAG_END)
1236 p.ertEnvironment(inner_type);
1239 p.skip_spaces(true);
1240 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1241 if ((outer_env && p.next_token().asInput() != "\\end") ||
1242 (!outer_env && p.next_token().cat() != catEnd)) {
1243 // something is between the end of the inner box and
1244 // the end of the outer box, so we need to use ERT.
1252 if (!outer_type.empty()) {
1253 if (outer_flags & FLAG_END)
1254 ss << "\\begin{" << outer_type << '}';
1256 ss << '\\' << outer_type << '{';
1257 if (!special.empty())
1261 if (!inner_type.empty()) {
1262 if (inner_type != "shaded") {
1263 if (inner_flags & FLAG_END)
1264 ss << "\\begin{" << inner_type << '}';
1266 ss << '\\' << inner_type;
1268 if (!position.empty())
1269 ss << '[' << position << ']';
1270 if (!latex_height.empty())
1271 ss << '[' << latex_height << ']';
1272 if (!inner_pos.empty())
1273 ss << '[' << inner_pos << ']';
1274 ss << '{' << latex_width << '}';
1275 if (!(inner_flags & FLAG_END))
1278 if (inner_type == "shaded")
1279 ss << "\\begin{shaded}";
1280 output_ert_inset(os, ss.str(), parent_context);
1281 if (!inner_type.empty()) {
1282 parse_text(p, os, inner_flags, outer, parent_context);
1283 if (inner_flags & FLAG_END)
1284 output_ert_inset(os, "\\end{" + inner_type + '}',
1287 output_ert_inset(os, "}", parent_context);
1289 if (!outer_type.empty()) {
1290 // If we already read the inner box we have to pop
1292 if (!inner_type.empty() && (inner_flags & FLAG_END))
1293 active_environments.pop_back();
1295 // Ensure that the end of the outer box is parsed correctly:
1296 // The opening brace has been eaten by parse_outer_box()
1297 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1298 outer_flags &= ~FLAG_ITEM;
1299 outer_flags |= FLAG_BRACE_LAST;
1301 parse_text(p, os, outer_flags, outer, parent_context);
1302 if (outer_flags & FLAG_END)
1303 output_ert_inset(os, "\\end{" + outer_type + '}',
1306 output_ert_inset(os, "}", parent_context);
1309 // LyX does not like empty positions, so we have
1310 // to set them to the LaTeX default values here.
1311 if (position.empty())
1313 if (inner_pos.empty())
1314 inner_pos = position;
1315 parent_context.check_layout(os);
1316 begin_inset(os, "Box ");
1317 if (outer_type == "framed")
1319 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1321 else if (outer_type == "shadowbox")
1322 os << "Shadowbox\n";
1323 else if ((outer_type == "shaded" && inner_type.empty()) ||
1324 (outer_type == "minipage" && inner_type == "shaded") ||
1325 (outer_type == "parbox" && inner_type == "shaded")) {
1327 preamble.registerAutomaticallyLoadedPackage("color");
1328 } else if (outer_type == "doublebox")
1329 os << "Doublebox\n";
1330 else if (outer_type.empty() || outer_type == "mbox")
1331 os << "Frameless\n";
1333 os << outer_type << '\n';
1334 os << "position \"" << position << "\"\n";
1335 os << "hor_pos \"" << hor_pos << "\"\n";
1336 if (outer_type == "mbox")
1337 os << "has_inner_box 1\n";
1338 else if (!frame_color.empty() && inner_type == "makebox")
1339 os << "has_inner_box 0\n";
1341 os << "has_inner_box " << !inner_type.empty() << "\n";
1342 os << "inner_pos \"" << inner_pos << "\"\n";
1343 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1345 if (outer_type == "mbox")
1346 os << "use_makebox 1\n";
1347 else if (!frame_color.empty())
1348 os << "use_makebox 0\n";
1350 os << "use_makebox " << (inner_type == "makebox") << '\n';
1351 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1352 os << "width \"\"\n";
1353 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1354 else if (contains(width_unit, '\\'))
1355 os << "width \"" << width_value << "in" << "\"\n";
1357 os << "width \"" << width_value << width_unit << "\"\n";
1358 if (contains(width_unit, '\\')) {
1359 width_unit.erase (0,1); // remove the leading '\'
1360 os << "special \"" << width_unit << "\"\n";
1362 os << "special \"" << width_special << "\"\n";
1363 if (contains(height_unit, '\\'))
1364 os << "height \"" << height_value << "in" << "\"\n";
1366 os << "height \"" << height_value << height_unit << "\"\n";
1367 os << "height_special \"" << height_special << "\"\n";
1368 os << "thickness \"" << thickness << "\"\n";
1369 os << "separation \"" << separation << "\"\n";
1370 os << "shadowsize \"" << shadowsize << "\"\n";
1371 os << "framecolor \"" << framecolor << "\"\n";
1372 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1373 os << "status open\n\n";
1375 // Unfortunately we can't use parse_text_in_inset:
1376 // InsetBox::forcePlainLayout() is hard coded and does not
1377 // use the inset layout. Apart from that do we call parse_text
1378 // up to two times, but need only one check_end_layout.
1379 bool const forcePlainLayout =
1380 (!inner_type.empty() || inner_type == "makebox") &&
1381 outer_type != "shaded" && outer_type != "framed";
1382 Context context(true, parent_context.textclass);
1383 if (forcePlainLayout)
1384 context.layout = &context.textclass.plainLayout();
1386 context.font = parent_context.font;
1388 // If we have no inner box the contents will be read with the outer box
1389 if (!inner_type.empty())
1390 parse_text(p, os, inner_flags, outer, context);
1392 // Ensure that the end of the outer box is parsed correctly:
1393 // The opening brace has been eaten by parse_outer_box()
1394 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1395 outer_flags &= ~FLAG_ITEM;
1396 outer_flags |= FLAG_BRACE_LAST;
1399 // Find end of outer box, output contents if inner_type is
1400 // empty and output possible comments
1401 if (!outer_type.empty()) {
1402 // If we already read the inner box we have to pop
1404 if (!inner_type.empty() && (inner_flags & FLAG_END))
1405 active_environments.pop_back();
1406 // This does not output anything but comments if
1407 // inner_type is not empty (see use_ert)
1408 parse_text(p, os, outer_flags, outer, context);
1411 context.check_end_layout(os);
1413 #ifdef PRESERVE_LAYOUT
1414 // LyX puts a % after the end of the minipage
1415 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1417 //output_comment(p, os, "dummy", parent_context);
1420 parent_context.new_paragraph(os);
1422 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1423 //output_comment(p, os, "dummy", parent_context);
1426 // We add a protected space if something real follows
1427 if (p.good() && p.next_token().cat() != catComment) {
1428 begin_inset(os, "space ~\n");
1434 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1435 active_environments.pop_back();
1436 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1437 // in this case we have to eat the the closing brace of the color box
1438 p.get_token().asInput(); // the '}'
1440 if (p.next_token().asInput() == "}") {
1441 // in this case we assume that the closing brace is from the box settings
1442 // therefore reset these values for the next box
1448 // all boxes except of Frameless and Shaded require calc
1449 if (!(outer_type.empty() || outer_type == "mbox") &&
1450 !((outer_type == "shaded" && inner_type.empty()) ||
1451 (outer_type == "minipage" && inner_type == "shaded") ||
1452 (outer_type == "parbox" && inner_type == "shaded")))
1453 preamble.registerAutomaticallyLoadedPackage("calc");
1457 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1458 Context & parent_context, string const & outer_type,
1459 string const & special)
1461 eat_whitespace(p, os, parent_context, false);
1462 if (flags & FLAG_ITEM) {
1464 if (p.next_token().cat() == catBegin)
1467 warning_message("Ignoring missing '{' after \\"
1468 + outer_type + '.');
1469 eat_whitespace(p, os, parent_context, false);
1472 unsigned int inner_flags = 0;
1474 if (outer_type == "minipage" || outer_type == "parbox") {
1475 p.skip_spaces(true);
1476 while (p.hasOpt()) {
1478 p.skip_spaces(true);
1481 p.skip_spaces(true);
1482 if (outer_type == "parbox") {
1484 if (p.next_token().cat() == catBegin)
1486 p.skip_spaces(true);
1489 if (outer_type == "shaded" || outer_type == "mbox") {
1490 // These boxes never have an inner box
1492 } else if (p.next_token().asInput() == "\\parbox") {
1493 inner = p.get_token().cs();
1494 inner_flags = FLAG_ITEM;
1495 } else if (p.next_token().asInput() == "\\begin") {
1496 // Is this a minipage or shaded box?
1499 inner = p.getArg('{', '}');
1501 if (inner == "minipage" || inner == "shaded")
1502 inner_flags = FLAG_END;
1507 if (inner_flags == FLAG_END) {
1508 if (inner != "shaded")
1512 eat_whitespace(p, os, parent_context, false);
1514 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1515 outer_type, special, inner, "", "");
1517 if (inner_flags == FLAG_ITEM) {
1519 eat_whitespace(p, os, parent_context, false);
1521 parse_box(p, os, flags, inner_flags, outer, parent_context,
1522 outer_type, special, inner, "", "");
1527 void parse_index_entry(Parser & p, ostream & os, Context & context, string const & kind)
1529 // write inset header
1530 begin_inset(os, "Index ");
1533 // Parse for post argument (|...)
1535 string const marg = p.getArg('{', '}');
1538 bool inpost = false;
1539 bool startrange = false;
1540 bool endrange = false;
1542 for (string::const_iterator it = marg.begin(), et = marg.end(); it != et; ++it) {
1545 if (post.empty() && c == '(')
1547 else if (post.empty() && c == ')')
1552 if (!inpost && (c == '|' && lc != '"'))
1557 os << "\nrange start";
1559 os << "\nrange end";
1561 os << "\nrange none";
1562 bool const see = prefixIs(post, "see{");
1563 bool const seealso = prefixIs(post, "seealso{");
1564 if (!post.empty() && !see && !seealso)
1565 os << "\npageformat " << post;
1567 os << "\npageformat default";
1568 os << "\nstatus collapsed\n";
1574 if (p.hasIdxMacros("!")) {
1575 // Index entry with levels
1576 while (p.hasIdxMacros("!")) {
1580 os << "\\begin_layout Plain Layout\n";
1582 begin_inset(os, "IndexMacro subentry");
1583 os << "\nstatus collapsed\n";
1585 // Check for (level-specific) sortkey
1586 if (p.hasIdxMacros("@", "!")) {
1588 os << "\\begin_layout Plain Layout\n";
1589 begin_inset(os, "IndexMacro sortkey");
1590 os << "\nstatus collapsed\n";
1591 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1594 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "!", "\"");
1596 os << "\n\\end_layout\n";
1602 begin_inset(os, "IndexMacro subentry");
1603 os << "\nstatus collapsed\n";
1606 // Check for (level-specific) sortkey
1607 if (p.hasIdxMacros("@", "!")) {
1612 os << "\\begin_layout Plain Layout\n";
1613 begin_inset(os, "IndexMacro sortkey");
1614 os << "\nstatus collapsed\n";
1615 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1617 if (post.empty() && !startrange && !endrange) {
1618 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1621 // Handle post-argument
1622 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1623 if (see || seealso) {
1624 while (p.next_token().character() != '{' && p.good())
1626 // this ends the subinset, as the see[also] insets
1627 // must come at main index inset
1628 os << "\n\\end_layout\n";
1631 begin_inset(os, "IndexMacro see");
1633 begin_inset(os, "IndexMacro seealso");
1634 os << "\nstatus collapsed\n";
1635 os << "\\begin_layout Plain Layout\n";
1636 parse_text_snippet(p, os, FLAG_ITEM, false, context);
1642 os << "\n\\end_layout\n";
1644 if (post.empty() && !startrange && !endrange) {
1645 parse_text_in_inset(p, os, FLAG_BRACE_LAST, false, context, "IndexMacro subentry");
1648 // Handle post-argument
1649 if (see || seealso) {
1650 os << "\\begin_layout Plain Layout\n";
1651 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1652 while (p.next_token().character() != '{' && p.good())
1654 // this ends the subinset, as the see[also] insets
1655 // must come at main index inset
1656 os << "\n\\end_layout\n";
1659 begin_inset(os, "IndexMacro see");
1661 begin_inset(os, "IndexMacro seealso");
1662 os << "\nstatus collapsed\n";
1663 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1665 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1673 os << "\n\\end_layout\n";
1675 // Index without any levels
1676 // Check for sortkey
1677 if (p.hasIdxMacros("@", "!")) {
1680 os << "\\begin_layout Plain Layout\n";
1681 begin_inset(os, "IndexMacro sortkey");
1682 os << "\nstatus collapsed\n";
1683 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1685 if (post.empty() && !startrange && !endrange) {
1686 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1689 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1690 if (see || seealso) {
1691 while (p.next_token().character() != '{' && p.good())
1694 begin_inset(os, "IndexMacro see");
1696 begin_inset(os, "IndexMacro seealso");
1697 os << "\nstatus collapsed\n";
1698 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1705 os << "\n\\end_layout\n";
1707 if (post.empty() && !startrange && !endrange) {
1708 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
1711 // Handle post-argument
1714 if (see || seealso) {
1715 os << "\\begin_layout Plain Layout\n";
1716 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1717 while (p.next_token().character() != '{' && p.good())
1720 begin_inset(os, "IndexMacro see");
1722 begin_inset(os, "IndexMacro seealso");
1723 os << "\nstatus collapsed\n";
1724 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1726 os << "\n\\end_layout\n";
1728 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1739 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1740 bool in_line, bool use_minted)
1742 parent_context.check_layout(os);
1743 begin_inset(os, "listings\n");
1744 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1746 while ((i = arg.find(", ")) != string::npos
1747 || (i = arg.find(",\t")) != string::npos)
1748 arg.erase(i + 1, 1);
1751 string const language = p.getArg('{', '}');
1752 p.skip_spaces(true);
1753 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1754 if (!minted_float.empty()) {
1755 arg += string(arg.empty() ? "" : ",") + minted_float;
1756 minted_nonfloat_caption.clear();
1760 os << "lstparams " << '"' << arg << '"' << '\n';
1761 if (arg.find("\\color") != string::npos)
1762 preamble.registerAutomaticallyLoadedPackage("color");
1765 os << "inline true\n";
1767 os << "inline false\n";
1768 os << "status open\n";
1769 Context context(true, parent_context.textclass);
1770 context.layout = &parent_context.textclass.plainLayout();
1771 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1772 minted_nonfloat_caption.erase(0,3);
1773 os << "\n\\begin_layout Plain Layout\n";
1774 begin_inset(os, "Caption Standard\n");
1775 Context newcontext(true, context.textclass,
1776 context.layout, 0, context.font);
1777 newcontext.check_layout(os);
1778 os << minted_nonfloat_caption << "\n";
1779 newcontext.check_end_layout(os);
1781 os << "\n\\end_layout\n";
1782 minted_nonfloat_caption.clear();
1786 // set catcodes to verbatim early, just in case.
1787 p.setCatcodes(VERBATIM_CATCODES);
1788 string delim = p.get_token().asInput();
1789 //FIXME: handler error condition
1790 s = p.verbatimStuff(delim).second;
1791 // context.new_paragraph(os);
1792 } else if (use_minted) {
1793 s = p.verbatimEnvironment("minted");
1795 s = p.verbatimEnvironment("lstlisting");
1797 output_ert(os, s, context);
1798 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1799 minted_nonfloat_caption.erase(0,3);
1800 os << "\n\\begin_layout Plain Layout\n";
1801 begin_inset(os, "Caption Standard\n");
1802 Context newcontext(true, context.textclass,
1803 context.layout, 0, context.font);
1804 newcontext.check_layout(os);
1805 os << minted_nonfloat_caption << "\n";
1806 newcontext.check_end_layout(os);
1808 os << "\n\\end_layout\n";
1809 minted_nonfloat_caption.clear();
1811 // Don't close the inset here for floating minted listings.
1812 // It will be closed at the end of the listing environment.
1813 if (!use_minted || minted_float.empty())
1816 eat_whitespace(p, os, parent_context, true);
1817 Token t = p.get_token();
1818 if (t.asInput() != "\\end") {
1819 // If anything follows, collect it into a caption.
1820 minted_float_has_caption = true;
1821 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1822 begin_inset(os, "Caption Standard\n");
1823 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1830 /// parse an unknown environment
1831 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1832 unsigned flags, bool outer,
1833 Context & parent_context)
1835 if (name == "tabbing")
1836 // We need to remember that we have to handle '\=' specially
1837 flags |= FLAG_TABBING;
1839 // We need to translate font changes and paragraphs inside the
1840 // environment to ERT if we have a non standard font.
1841 // Otherwise things like
1842 // \large\begin{foo}\huge bar\end{foo}
1844 bool const specialfont =
1845 (parent_context.font != parent_context.normalfont);
1846 bool const new_layout_allowed = parent_context.new_layout_allowed;
1848 parent_context.new_layout_allowed = false;
1849 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1850 // Try to handle options: Look if we have optional arguments,
1851 // and if so, put the brackets in ERT.
1852 while (p.hasOpt()) {
1853 p.get_token(); // eat '['
1854 output_ert_inset(os, "[", parent_context);
1855 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1856 output_ert_inset(os, "]", parent_context);
1858 parse_text_snippet(p, os, flags, outer, parent_context);
1859 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1861 parent_context.new_layout_allowed = new_layout_allowed;
1865 void parse_environment(Parser & p, ostream & os, bool outer,
1866 string & last_env, Context & parent_context)
1868 Layout const * newlayout;
1869 InsetLayout const * newinsetlayout = 0;
1870 string const name = p.getArg('{', '}');
1871 const bool is_starred = suffixIs(name, '*');
1872 string const unstarred_name = rtrim(name, "*");
1873 active_environments.push_back(name);
1875 // We use this loop and break out after a condition is met
1876 // rather than a huge else-if-chain.
1878 if (is_math_env(name)) {
1879 parent_context.check_layout(os);
1880 begin_inset(os, "Formula ");
1881 os << "\\begin{" << name << "}";
1882 parse_math(p, os, FLAG_END, MATH_MODE);
1883 os << "\\end{" << name << "}";
1885 if (is_display_math_env(name)) {
1886 // Prevent the conversion of a line break to a space
1887 // (bug 7668). This does not change the output, but
1888 // looks ugly in LyX.
1889 eat_whitespace(p, os, parent_context, false);
1894 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1895 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1896 // We must begin a new paragraph if not already done
1897 if (!parent_context.atParagraphStart()) {
1898 parent_context.check_end_layout(os);
1899 parent_context.new_paragraph(os);
1901 // store previous language because we must reset it at the end
1902 string const lang_old = parent_context.font.language;
1903 // save new language in context so that it is
1904 // handled by parse_text
1905 parent_context.font.language =
1906 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1907 parse_text(p, os, FLAG_END, outer, parent_context);
1908 // reset previous language
1909 parent_context.font.language = lang_old;
1910 // Just in case the environment is empty
1911 parent_context.extra_stuff.erase();
1912 // We must begin a new paragraph to reset the language
1913 parent_context.new_paragraph(os);
1918 if (unstarred_name == "tabular" || name == "longtable"
1919 || name == "tabularx" || name == "xltabular") {
1920 eat_whitespace(p, os, parent_context, false);
1921 string width = "0pt";
1923 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1924 string const opt = p.getArg('[', ']');
1927 else if (opt == "l")
1929 else if (opt == "r")
1932 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1933 width = lyx::translate_len(p.getArg('{', '}'));
1934 eat_whitespace(p, os, parent_context, false);
1936 parent_context.check_layout(os);
1937 begin_inset(os, "Tabular ");
1938 handle_tabular(p, os, name, width, halign, parent_context);
1944 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1945 eat_whitespace(p, os, parent_context, false);
1946 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1947 eat_whitespace(p, os, parent_context, false);
1948 parent_context.check_layout(os);
1949 begin_inset(os, "Float " + unstarred_name + "\n");
1950 // store the float type for subfloats
1951 // subfloats only work with figures and tables
1952 if (unstarred_name == "figure")
1953 float_type = unstarred_name;
1954 else if (unstarred_name == "table")
1955 float_type = unstarred_name;
1959 os << "placement " << opt << '\n';
1960 if (contains(opt, "H"))
1961 preamble.registerAutomaticallyLoadedPackage("float");
1963 Floating const & fl = parent_context.textclass.floats()
1964 .getType(unstarred_name);
1965 if (!fl.floattype().empty() && fl.usesFloatPkg())
1966 preamble.registerAutomaticallyLoadedPackage("float");
1969 os << "wide " << convert<string>(is_starred)
1970 << "\nsideways false"
1971 << "\nstatus open\n\n";
1972 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1973 if (unstarred_name == "algorithm")
1974 // in algorithm, \; has special meaning
1975 parent_context.pass_thru_cmds.insert(";");
1976 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1977 if (unstarred_name == "algorithm")
1978 parent_context.pass_thru_cmds = pass_thru_cmds;
1980 // We don't need really a new paragraph, but
1981 // we must make sure that the next item gets a \begin_layout.
1982 parent_context.new_paragraph(os);
1984 // the float is parsed thus delete the type
1989 if (unstarred_name == "sidewaysfigure"
1990 || unstarred_name == "sidewaystable"
1991 || unstarred_name == "sidewaysalgorithm") {
1992 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1993 eat_whitespace(p, os, parent_context, false);
1994 parent_context.check_layout(os);
1995 if (unstarred_name == "sidewaysfigure")
1996 begin_inset(os, "Float figure\n");
1997 else if (unstarred_name == "sidewaystable")
1998 begin_inset(os, "Float table\n");
1999 else if (unstarred_name == "sidewaysalgorithm")
2000 begin_inset(os, "Float algorithm\n");
2002 os << "placement " << opt << '\n';
2003 if (contains(opt, "H"))
2004 preamble.registerAutomaticallyLoadedPackage("float");
2005 os << "wide " << convert<string>(is_starred)
2006 << "\nsideways true"
2007 << "\nstatus open\n\n";
2008 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2010 // We don't need really a new paragraph, but
2011 // we must make sure that the next item gets a \begin_layout.
2012 parent_context.new_paragraph(os);
2014 preamble.registerAutomaticallyLoadedPackage("rotfloat");
2018 if (name == "wrapfigure" || name == "wraptable") {
2019 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
2020 eat_whitespace(p, os, parent_context, false);
2021 parent_context.check_layout(os);
2024 string overhang = "0col%";
2027 lines = p.getArg('[', ']');
2028 string const placement = p.getArg('{', '}');
2030 overhang = p.getArg('[', ']');
2031 string const width = p.getArg('{', '}');
2033 if (name == "wrapfigure")
2034 begin_inset(os, "Wrap figure\n");
2036 begin_inset(os, "Wrap table\n");
2037 os << "lines " << lines
2038 << "\nplacement " << placement
2039 << "\noverhang " << lyx::translate_len(overhang)
2040 << "\nwidth " << lyx::translate_len(width)
2041 << "\nstatus open\n\n";
2042 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2044 // We don't need really a new paragraph, but
2045 // we must make sure that the next item gets a \begin_layout.
2046 parent_context.new_paragraph(os);
2048 preamble.registerAutomaticallyLoadedPackage("wrapfig");
2052 if (name == "minipage") {
2053 eat_whitespace(p, os, parent_context, false);
2054 // Test whether this is an outer box of a shaded box
2056 // swallow arguments
2057 while (p.hasOpt()) {
2059 p.skip_spaces(true);
2062 p.skip_spaces(true);
2063 Token t = p.get_token();
2064 bool shaded = false;
2065 if (t.asInput() == "\\begin") {
2066 p.skip_spaces(true);
2067 if (p.getArg('{', '}') == "shaded")
2072 parse_outer_box(p, os, FLAG_END, outer,
2073 parent_context, name, "shaded");
2075 parse_box(p, os, 0, FLAG_END, outer, parent_context,
2076 "", "", name, "", "");
2081 if (name == "comment") {
2082 eat_whitespace(p, os, parent_context, false);
2083 parent_context.check_layout(os);
2084 begin_inset(os, "Note Comment\n");
2085 os << "status open\n";
2086 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2089 skip_braces(p); // eat {} that might by set by LyX behind comments
2090 preamble.registerAutomaticallyLoadedPackage("verbatim");
2094 if (unstarred_name == "verbatim") {
2095 // FIXME: this should go in the generic code that
2096 // handles environments defined in layout file that
2097 // have "PassThru 1". However, the code over there is
2098 // already too complicated for my taste.
2099 string const ascii_name =
2100 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
2101 parent_context.new_paragraph(os);
2102 Context context(true, parent_context.textclass,
2103 &parent_context.textclass[from_ascii(ascii_name)]);
2104 string s = p.verbatimEnvironment(name);
2105 output_ert(os, s, context);
2110 if (name == "IPA") {
2111 eat_whitespace(p, os, parent_context, false);
2112 parent_context.check_layout(os);
2113 begin_inset(os, "IPA\n");
2114 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
2115 // These commands have special meanings in IPA
2116 parent_context.pass_thru_cmds.insert("!");
2117 parent_context.pass_thru_cmds.insert(";");
2118 parent_context.pass_thru_cmds.insert(":");
2119 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2120 parent_context.pass_thru_cmds = pass_thru_cmds;
2123 preamble.registerAutomaticallyLoadedPackage("tipa");
2124 preamble.registerAutomaticallyLoadedPackage("tipx");
2128 if (name == parent_context.textclass.titlename()
2129 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
2130 parse_text(p, os, FLAG_END, outer, parent_context);
2131 // Just in case the environment is empty
2132 parent_context.extra_stuff.erase();
2133 // We must begin a new paragraph
2134 parent_context.new_paragraph(os);
2139 if (name == "CJK") {
2140 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
2141 // It is impossible to decide if a CJK environment was in its own paragraph or within
2142 // a line. We therefore always assume a paragraph since the latter is a rare case.
2143 eat_whitespace(p, os, parent_context, false);
2144 parent_context.check_end_layout(os);
2145 // store the encoding to be able to reset it
2146 string const encoding_old = p.getEncoding();
2147 string const encoding = p.getArg('{', '}');
2148 // FIXME: For some reason JIS does not work. Although the text
2149 // in tests/CJK.tex is identical with the SJIS version if you
2150 // convert both snippets using the recode command line utility,
2151 // the resulting .lyx file contains some extra characters if
2152 // you set buggy_encoding to false for JIS.
2153 bool const buggy_encoding = encoding == "JIS";
2154 if (!buggy_encoding)
2155 p.setEncoding(encoding, Encoding::CJK);
2157 // FIXME: This will read garbage, since the data is not encoded in utf8.
2158 p.setEncoding("UTF-8");
2160 // LyX only supports the same mapping for all CJK
2161 // environments, so we might need to output everything as ERT
2162 string const mapping = trim(p.getArg('{', '}'));
2163 char const * const * const where =
2164 is_known(encoding, supported_CJK_encodings);
2165 if (!buggy_encoding && !preamble.fontCJKSet())
2166 preamble.fontCJK(mapping);
2167 bool knownMapping = mapping == preamble.fontCJK();
2168 if (buggy_encoding || !knownMapping || !where) {
2169 parent_context.check_layout(os);
2170 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
2172 // we must parse the content as verbatim because e.g. JIS can contain
2173 // normally invalid characters
2174 // FIXME: This works only for the most simple cases.
2175 // Since TeX control characters are not parsed,
2176 // things like comments are completely wrong.
2177 string const s = p.plainEnvironment("CJK");
2178 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
2181 if (snip == "\\" || is_known(snip, known_escaped_chars))
2182 output_ert_inset(os, snip, parent_context);
2183 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
2188 output_ert_inset(os, "\\end{" + name + "}",
2192 supported_CJK_languages[where - supported_CJK_encodings];
2193 // store the language because we must reset it at the end
2194 string const lang_old = parent_context.font.language;
2195 parent_context.font.language = lang;
2196 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2197 parent_context.font.language = lang_old;
2198 parent_context.new_paragraph(os);
2200 p.setEncoding(encoding_old);
2205 if (name == "lyxgreyedout") {
2206 eat_whitespace(p, os, parent_context, false);
2207 parent_context.check_layout(os);
2208 begin_inset(os, "Note Greyedout\n");
2209 os << "status open\n";
2210 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2213 if (!preamble.notefontcolor().empty())
2214 preamble.registerAutomaticallyLoadedPackage("color");
2218 if (name == "btSect") {
2219 eat_whitespace(p, os, parent_context, false);
2220 parent_context.check_layout(os);
2221 begin_command_inset(os, "bibtex", "bibtex");
2222 string bibstyle = "plain";
2224 bibstyle = p.getArg('[', ']');
2225 p.skip_spaces(true);
2227 string const bibfile = p.getArg('{', '}');
2228 eat_whitespace(p, os, parent_context, false);
2229 Token t = p.get_token();
2230 if (t.asInput() == "\\btPrintCited") {
2231 p.skip_spaces(true);
2232 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2234 if (t.asInput() == "\\btPrintNotCited") {
2235 p.skip_spaces(true);
2236 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2238 if (t.asInput() == "\\btPrintAll") {
2239 p.skip_spaces(true);
2240 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2242 os << "bibfiles " << '"' << bibfile << "\"\n"
2243 << "options " << '"' << bibstyle << "\"\n";
2244 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2250 if (name == "btUnit") {
2251 string const nt = p.next_next_token().cs();
2252 // Do not attempt to overwrite a former diverging multibib.
2253 // Those are output as ERT instead.
2254 if ((nt == "part" || nt == "chapter"
2255 || nt == "section" || nt == "subsection")
2256 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2257 parse_text(p, os, FLAG_END, outer, parent_context);
2258 preamble.multibib(nt);
2260 parse_unknown_environment(p, name, os, FLAG_END, outer,
2265 // This is only attempted at turn environments that consist only
2266 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2267 // Thus we will fall through in other cases.
2268 if (name == "turn") {
2269 // We check if the next thing is a tabular[*|x]
2271 p.getArg('{', '}');// eat turn argument
2272 bool found_end = false;
2273 bool only_table = false;
2274 bool end_table = false;
2277 string envname = p.getArg('{', '}');
2278 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2279 // Now we check if the table is the only content
2280 // of the turn environment
2281 string const tenv = envname;
2282 while (!found_end && !end_table && p.good()) {
2283 envname = p.next_token().cat() == catBegin
2284 ? p.getArg('{', '}') : string();
2285 Token const & t = p.get_token();
2287 end_table = t.asInput() != "\\end"
2289 found_end = t.asInput() == "\\end"
2290 && envname == "turn";
2294 envname = p.getArg('{', '}');
2295 only_table = p.next_next_token().asInput() == "\\end"
2296 && envname == "turn";
2300 string const angle = p.getArg('{', '}');
2302 int const save_tablerotation = parent_context.tablerotation;
2303 parent_context.tablerotation = convert<int>(angle);
2304 parse_text(p, os, FLAG_END, outer, parent_context);
2305 parent_context.tablerotation = save_tablerotation;
2315 // This is only attempted at landscape environments that consist only
2316 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2317 // Other landscape environment is handled via the landscape module, thus
2318 // we will fall through in that case.
2319 if (name == "landscape") {
2320 // We check if the next thing is a longtable
2322 bool found_end = false;
2323 bool only_longtable = false;
2324 bool end_longtable = false;
2327 string envname = p.getArg('{', '}');
2328 if (envname == "longtable" || envname == "xltabular") {
2329 // Now we check if the longtable is the only content
2330 // of the landscape environment
2331 string const ltenv = envname;
2332 while (!found_end && !end_longtable && p.good()) {
2333 envname = p.next_token().cat() == catBegin
2334 ? p.getArg('{', '}') : string();
2335 Token const & t = p.get_token();
2337 end_longtable = t.asInput() != "\\end"
2338 && envname == ltenv;
2339 found_end = t.asInput() == "\\end"
2340 && envname == "landscape";
2342 if (end_longtable) {
2344 envname = p.getArg('{', '}');
2345 only_longtable = p.next_next_token().asInput() == "\\end"
2346 && envname == "landscape";
2348 if (only_longtable) {
2351 int const save_tablerotation = parent_context.tablerotation;
2352 parent_context.tablerotation = 90;
2353 parse_text(p, os, FLAG_END, outer, parent_context);
2354 parent_context.tablerotation = save_tablerotation;
2364 if (name == "framed" || name == "shaded") {
2365 eat_whitespace(p, os, parent_context, false);
2366 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2368 preamble.registerAutomaticallyLoadedPackage("framed");
2372 if (name == "listing") {
2373 minted_float = "float";
2374 eat_whitespace(p, os, parent_context, false);
2375 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2377 minted_float += "=" + opt;
2378 // If something precedes \begin{minted}, we output it at the end
2379 // as a caption, in order to keep it inside the listings inset.
2380 eat_whitespace(p, os, parent_context, true);
2382 Token const & t = p.get_token();
2383 p.skip_spaces(true);
2384 string const envname = p.next_token().cat() == catBegin
2385 ? p.getArg('{', '}') : string();
2386 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2388 minted_float_has_caption = false;
2389 string content = parse_text_snippet(p, FLAG_END, outer,
2391 size_t i = content.find("\\begin_inset listings");
2392 bool minted_env = i != string::npos;
2395 caption = content.substr(0, i);
2396 content.erase(0, i);
2398 parent_context.check_layout(os);
2399 if (minted_env && minted_float_has_caption) {
2400 eat_whitespace(p, os, parent_context, true);
2401 os << content << "\n";
2402 if (!caption.empty())
2403 os << caption << "\n";
2404 os << "\n\\end_layout\n"; // close inner layout
2405 end_inset(os); // close caption inset
2406 os << "\n\\end_layout\n"; // close outer layout
2407 } else if (!caption.empty()) {
2409 begin_inset(os, "listings\n");
2410 os << "lstparams " << '"' << minted_float << '"' << '\n';
2411 os << "inline false\n";
2412 os << "status collapsed\n";
2414 os << "\n\\begin_layout Plain Layout\n";
2415 begin_inset(os, "Caption Standard\n");
2416 Context newcontext(true, parent_context.textclass,
2417 0, 0, parent_context.font);
2418 newcontext.check_layout(os);
2419 os << caption << "\n";
2420 newcontext.check_end_layout(os);
2422 os << "\n\\end_layout\n";
2423 } else if (content.empty()) {
2424 begin_inset(os, "listings\n");
2425 os << "lstparams " << '"' << minted_float << '"' << '\n';
2426 os << "inline false\n";
2427 os << "status collapsed\n";
2429 os << content << "\n";
2431 end_inset(os); // close listings inset
2432 parent_context.check_end_layout(os);
2433 parent_context.new_paragraph(os);
2435 minted_float.clear();
2436 minted_float_has_caption = false;
2440 if (name == "lstlisting" || name == "minted") {
2441 bool use_minted = name == "minted";
2442 // with listings, we do not eat newlines here since
2443 // \begin{lstlistings}
2446 // // \begin{lstlistings}%
2449 // reads [foo] as content, whereas
2450 // // \begin{lstlistings}%
2453 // \begin{lstlistings}[foo,
2455 // reads [foo...] as argument.
2456 eat_whitespace(p, os, parent_context, false, use_minted);
2457 if (use_minted && minted_float.empty()) {
2458 // look ahead for a bottom caption
2460 bool found_end_minted = false;
2461 while (!found_end_minted && p.good()) {
2462 Token const & t = p.get_token();
2464 string const envname =
2465 p.next_token().cat() == catBegin
2466 ? p.getArg('{', '}') : string();
2467 found_end_minted = t.asInput() == "\\end"
2468 && envname == "minted";
2470 eat_whitespace(p, os, parent_context, true);
2471 Token const & t = p.get_token();
2472 p.skip_spaces(true);
2473 if (t.asInput() == "\\lyxmintcaption") {
2474 string const pos = p.getArg('[', ']');
2476 string const caption =
2477 parse_text_snippet(p, FLAG_ITEM,
2478 false, parent_context);
2479 minted_nonfloat_caption = "[b]" + caption;
2480 eat_whitespace(p, os, parent_context, true);
2485 parse_listings(p, os, parent_context, false, use_minted);
2490 if (!parent_context.new_layout_allowed) {
2491 parse_unknown_environment(p, name, os, FLAG_END, outer,
2496 // Alignment and spacing settings
2497 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2498 // therefore are totally broken!
2499 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2500 // they are commands not environments. They are furthermore switches that
2501 // can be ended by another switches, but also by commands like \footnote or
2502 // \parbox. So the only safe way is to leave them untouched.
2503 // However, we support the pseudo-environments
2504 // \begin{centering} ... \end{centering}
2505 // \begin{raggedright} ... \end{raggedright}
2506 // \begin{raggedleft} ... \end{raggedleft}
2507 // since they are used by LyX in floats (for spacing reasons)
2508 if (name == "center" || name == "centering"
2509 || name == "flushleft" || name == "raggedright"
2510 || name == "flushright" || name == "raggedleft"
2511 || name == "singlespace" || name == "onehalfspace"
2512 || name == "doublespace" || name == "spacing") {
2513 eat_whitespace(p, os, parent_context, false);
2514 // We must begin a new paragraph if not already done
2515 if (! parent_context.atParagraphStart()) {
2516 parent_context.check_end_layout(os);
2517 parent_context.new_paragraph(os);
2519 if (name == "flushleft" || name == "raggedright")
2520 parent_context.add_extra_stuff("\\align left\n");
2521 else if (name == "flushright" || name == "raggedleft")
2522 parent_context.add_extra_stuff("\\align right\n");
2523 else if (name == "center" || name == "centering")
2524 parent_context.add_extra_stuff("\\align center\n");
2525 else if (name == "singlespace")
2526 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2527 else if (name == "onehalfspace") {
2528 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2529 preamble.registerAutomaticallyLoadedPackage("setspace");
2530 } else if (name == "doublespace") {
2531 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2532 preamble.registerAutomaticallyLoadedPackage("setspace");
2533 } else if (name == "spacing") {
2534 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2535 preamble.registerAutomaticallyLoadedPackage("setspace");
2537 parse_text(p, os, FLAG_END, outer, parent_context);
2538 // Just in case the environment is empty
2539 parent_context.extra_stuff.erase();
2540 // We must begin a new paragraph to reset the alignment
2541 parent_context.new_paragraph(os);
2546 // The single '=' is meant here.
2547 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2548 eat_whitespace(p, os, parent_context, false);
2549 Context context(true, parent_context.textclass, newlayout,
2550 parent_context.layout, parent_context.font);
2551 if (parent_context.deeper_paragraph) {
2552 // We are beginning a nested environment after a
2553 // deeper paragraph inside the outer list environment.
2554 // Therefore we don't need to output a "begin deeper".
2555 context.need_end_deeper = true;
2557 parent_context.check_end_layout(os);
2558 if (last_env == name) {
2559 // we need to output a separator since LyX would export
2560 // the two environments as one otherwise (bug 5716)
2561 TeX2LyXDocClass const & textclass(parent_context.textclass);
2562 Context newcontext(true, textclass,
2563 &(textclass.defaultLayout()));
2564 newcontext.check_layout(os);
2565 begin_inset(os, "Separator plain\n");
2567 newcontext.check_end_layout(os);
2569 switch (context.layout->latextype) {
2570 case LATEX_LIST_ENVIRONMENT:
2571 context.in_list_preamble =
2572 !context.layout->listpreamble().empty()
2573 && p.hasListPreamble(context.layout->itemcommand());
2574 context.add_par_extra_stuff("\\labelwidthstring "
2575 + p.verbatim_item() + '\n');
2578 case LATEX_BIB_ENVIRONMENT:
2579 p.verbatim_item(); // swallow next arg
2585 context.check_deeper(os);
2586 if (newlayout->keepempty) {
2587 // We need to start a new paragraph
2588 // even if it is empty.
2589 context.new_paragraph(os);
2590 context.check_layout(os);
2592 // handle known optional and required arguments
2593 if (context.layout->latextype == LATEX_ENVIRONMENT)
2594 output_arguments(os, p, outer, false, string(), context,
2595 context.layout->latexargs());
2596 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2597 context.in_list_preamble =
2598 !context.layout->listpreamble().empty()
2599 && p.hasListPreamble(context.layout->itemcommand());
2601 output_arguments(oss, p, outer, false, string(), context,
2602 context.layout->latexargs());
2603 context.list_extra_stuff = oss.str();
2605 if (context.in_list_preamble) {
2606 // Collect the stuff between \begin and first \item
2607 context.list_preamble =
2608 parse_text_snippet(p, FLAG_END, outer, context);
2609 context.in_list_preamble = false;
2611 parse_text(p, os, FLAG_END, outer, context);
2612 if (context.layout->latextype == LATEX_ENVIRONMENT)
2613 output_arguments(os, p, outer, false, "post", context,
2614 context.layout->postcommandargs());
2615 context.check_end_layout(os);
2616 if (parent_context.deeper_paragraph) {
2617 // We must suppress the "end deeper" because we
2618 // suppressed the "begin deeper" above.
2619 context.need_end_deeper = false;
2621 context.check_end_deeper(os);
2622 parent_context.new_paragraph(os);
2624 if (!preamble.titleLayoutFound())
2625 preamble.titleLayoutFound(newlayout->intitle);
2626 set<string> const & req = newlayout->required();
2627 set<string>::const_iterator it = req.begin();
2628 set<string>::const_iterator en = req.end();
2629 for (; it != en; ++it)
2630 preamble.registerAutomaticallyLoadedPackage(*it);
2634 // The single '=' is meant here.
2635 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2636 eat_whitespace(p, os, parent_context, false);
2637 parent_context.check_layout(os);
2638 begin_inset(os, "Flex ");
2639 docstring flex_name = newinsetlayout->name();
2640 // FIXME: what do we do if the prefix is not Flex: ?
2641 if (prefixIs(flex_name, from_ascii("Flex:")))
2642 flex_name.erase(0, 5);
2643 os << to_utf8(flex_name) << '\n'
2644 << "status collapsed\n";
2645 if (newinsetlayout->isPassThru()) {
2646 string const arg = p.verbatimEnvironment(name);
2647 Context context(true, parent_context.textclass,
2648 &parent_context.textclass.plainLayout(),
2649 parent_context.layout);
2650 output_ert(os, arg, parent_context);
2652 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2657 if (name == "appendix") {
2658 // This is no good latex style, but it works and is used in some documents...
2659 eat_whitespace(p, os, parent_context, false);
2660 parent_context.check_end_layout(os);
2661 Context context(true, parent_context.textclass, parent_context.layout,
2662 parent_context.layout, parent_context.font);
2663 context.check_layout(os);
2664 os << "\\start_of_appendix\n";
2665 parse_text(p, os, FLAG_END, outer, context);
2666 context.check_end_layout(os);
2671 if (known_environments.find(name) != known_environments.end()) {
2672 vector<ArgumentType> arguments = known_environments[name];
2673 // The last "argument" denotes whether we may translate the
2674 // environment contents to LyX
2675 // The default required if no argument is given makes us
2676 // compatible with the reLyXre environment.
2677 ArgumentType contents = arguments.empty() ?
2680 if (!arguments.empty())
2681 arguments.pop_back();
2682 // See comment in parse_unknown_environment()
2683 bool const specialfont =
2684 (parent_context.font != parent_context.normalfont);
2685 bool const new_layout_allowed =
2686 parent_context.new_layout_allowed;
2688 parent_context.new_layout_allowed = false;
2689 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2690 outer, parent_context);
2691 if (contents == verbatim)
2692 output_ert_inset(os, p.ertEnvironment(name),
2695 parse_text_snippet(p, os, FLAG_END, outer,
2697 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2699 parent_context.new_layout_allowed = new_layout_allowed;
2703 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2708 active_environments.pop_back();
2712 /// parses a comment and outputs it to \p os.
2713 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2714 bool skipNewlines = false)
2716 LASSERT(t.cat() == catComment, return);
2717 string comment = t.cs();
2718 // Join multiple consecutive comment lines into one ERT inset
2719 while (p.next_token().cat() == catComment)
2720 comment += "\n%" + p.get_token().cs();
2722 if (!comment.empty()) {
2723 context.check_layout(os);
2724 output_comment(p, os, comment, context);
2725 if (p.next_token().cat() == catNewline) {
2726 // A newline after a comment line starts a new
2728 if (context.new_layout_allowed) {
2729 if(!context.atParagraphStart())
2730 // Only start a new paragraph if not already
2731 // done (we might get called recursively)
2732 context.new_paragraph(os);
2734 output_ert_inset(os, "\n", context);
2735 eat_whitespace(p, os, context, true);
2737 } else if (!skipNewlines) {
2738 // "%\n" combination
2745 * Reads spaces and comments until the first non-space, non-comment token.
2746 * New paragraphs (double newlines or \\par) are handled like simple spaces
2747 * if \p eatParagraph is true.
2748 * If \p eatNewline is false, newlines won't be treated as whitespace.
2749 * Spaces are skipped, but comments are written to \p os.
2751 void eat_whitespace(Parser & p, ostream & os, Context & context,
2752 bool eatParagraph, bool eatNewline)
2755 Token const & t = p.get_token();
2756 if (t.cat() == catComment)
2757 parse_comment(p, os, t, context, !eatNewline);
2758 else if ((!eatParagraph && p.isParagraph()) ||
2759 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2768 * Set a font attribute, parse text and reset the font attribute.
2769 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2770 * \param currentvalue Current value of the attribute. Is set to the new
2771 * value during parsing.
2772 * \param newvalue New value of the attribute
2774 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2775 Context & context, string const & attribute,
2776 string & currentvalue, string const & newvalue)
2778 context.check_layout(os);
2779 string const oldvalue = currentvalue;
2780 currentvalue = newvalue;
2781 os << '\n' << attribute << ' ' << newvalue << "\n";
2782 parse_text_snippet(p, os, flags, outer, context);
2783 context.check_layout(os);
2784 os << '\n' << attribute << ' ' << oldvalue << "\n";
2785 currentvalue = oldvalue;
2789 /// get the arguments of a natbib or jurabib citation command
2790 void get_cite_arguments(Parser & p, bool natbibOrder,
2791 string & before, string & after, bool const qualified = false)
2793 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2795 // text before the citation
2797 // text after the citation
2798 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2800 if (!after.empty()) {
2801 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2802 if (natbibOrder && !before.empty())
2803 swap(before, after);
2808 void copy_file(FileName const & src, string const & dstname)
2812 string const absParent = getParentFilePath(false);
2814 if (FileName::isAbsolute(dstname))
2815 dst = FileName(dstname);
2817 dst = makeAbsPath(dstname, absParent);
2818 FileName const srcpath = src.onlyPath();
2819 FileName const dstpath = dst.onlyPath();
2820 if (equivalent(srcpath, dstpath))
2822 if (!dstpath.isDirectory()) {
2823 if (!dstpath.createPath()) {
2824 warning_message("Could not create directory for file `"
2825 + dst.absFileName() + "´.");
2829 if (dst.isReadableFile()) {
2830 if (overwriteFiles())
2831 warning_message("Overwriting existing file `"
2832 + dst.absFileName() + "´.");
2834 warning_message("Not overwriting existing file `"
2835 + dst.absFileName() + "´.");
2839 if (!src.copyTo(dst))
2840 warning_message("Could not copy file `" + src.absFileName()
2841 + "´ to `" + dst.absFileName() + "´.");
2845 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2846 bool parse_chunk(Parser & p, ostream & os, Context & context)
2848 // check whether a chunk is possible here.
2849 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2855 // read the parameters
2856 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2857 if (!params.first) {
2862 Parser::Arg const code = p.verbatimStuff("\n@");
2867 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2868 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2872 // The last newline read is important for paragraph handling
2876 //warning_message("params=[" + params.second + "], code=[" + code.second + "]");
2877 // We must have a valid layout before outputting the Chunk inset.
2878 context.check_layout(os);
2879 Context chunkcontext(true, context.textclass);
2880 chunkcontext.layout = &context.textclass.plainLayout();
2881 begin_inset(os, "Flex Chunk");
2882 os << "\nstatus open\n";
2883 if (!params.second.empty()) {
2884 chunkcontext.check_layout(os);
2885 Context paramscontext(true, context.textclass);
2886 paramscontext.layout = &context.textclass.plainLayout();
2887 begin_inset(os, "Argument 1");
2888 os << "\nstatus open\n";
2889 output_ert(os, params.second, paramscontext);
2892 output_ert(os, code.second, chunkcontext);
2900 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2901 bool is_macro(Parser & p)
2903 Token first = p.curr_token();
2904 if (first.cat() != catEscape || !p.good())
2906 if (first.cs() == "def")
2908 if (first.cs() != "global" && first.cs() != "long")
2910 Token second = p.get_token();
2912 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2913 second.cat() == catNewline || second.cat() == catComment)) {
2914 second = p.get_token();
2917 bool secondvalid = second.cat() == catEscape;
2919 bool thirdvalid = false;
2920 if (p.good() && first.cs() == "global" && secondvalid &&
2921 second.cs() == "long") {
2922 third = p.get_token();
2924 while (p.good() && !p.isParagraph() &&
2925 (third.cat() == catSpace ||
2926 third.cat() == catNewline ||
2927 third.cat() == catComment)) {
2928 third = p.get_token();
2931 thirdvalid = third.cat() == catEscape;
2933 for (int i = 0; i < pos; ++i)
2938 return (first.cs() == "global" || first.cs() == "long") &&
2939 second.cs() == "def";
2940 return first.cs() == "global" && second.cs() == "long" &&
2941 third.cs() == "def";
2945 /// Parse a macro definition (assumes that is_macro() returned true)
2946 void parse_macro(Parser & p, ostream & os, Context & context)
2948 context.check_layout(os);
2949 Token first = p.curr_token();
2952 string command = first.asInput();
2953 if (first.cs() != "def") {
2955 eat_whitespace(p, os, context, false);
2956 second = p.curr_token();
2957 command += second.asInput();
2958 if (second.cs() != "def") {
2960 eat_whitespace(p, os, context, false);
2961 third = p.curr_token();
2962 command += third.asInput();
2965 eat_whitespace(p, os, context, false);
2966 string const name = p.get_token().cs();
2967 eat_whitespace(p, os, context, false);
2973 while (p.next_token().cat() != catBegin) {
2974 if (p.next_token().cat() == catParameter) {
2979 // followed by number?
2980 if (p.next_token().cat() == catOther) {
2981 string s = p.get_token().asInput();
2983 // number = current arity + 1?
2984 if (s.size() == 1 && s[0] == arity + '0' + 1)
2989 paramtext += p.get_token().cs();
2991 paramtext += p.get_token().cs();
2996 // only output simple (i.e. compatible) macro as FormulaMacros
2997 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2999 context.check_layout(os);
3000 begin_inset(os, "FormulaMacro");
3001 os << "\n\\def" << ert;
3004 output_ert_inset(os, command + ert, context);
3008 void registerExternalTemplatePackages(string const & name)
3010 external::TemplateManager const & etm = external::TemplateManager::get();
3011 external::Template const * const et = etm.getTemplateByName(name);
3014 external::Template::Formats::const_iterator cit = et->formats.end();
3016 cit = et->formats.find("PDFLaTeX");
3017 if (cit == et->formats.end())
3018 // If the template has not specified a PDFLaTeX output,
3019 // we try the LaTeX format.
3020 cit = et->formats.find("LaTeX");
3021 if (cit == et->formats.end())
3023 vector<string>::const_iterator qit = cit->second.requirements.begin();
3024 vector<string>::const_iterator qend = cit->second.requirements.end();
3025 for (; qit != qend; ++qit)
3026 preamble.registerAutomaticallyLoadedPackage(*qit);
3029 } // anonymous namespace
3033 * Find a file with basename \p name in path \p path and an extension
3036 string find_file(string const & name, string const & path,
3037 char const * const * extensions)
3039 for (char const * const * what = extensions; *what; ++what) {
3040 string const trial = addExtension(name, *what);
3041 if (makeAbsPath(trial, path).exists())
3048 /// Convert filenames with TeX macros and/or quotes to something LyX
3050 string const normalize_filename(string const & name)
3055 Token const & t = p.get_token();
3056 if (t.cat() != catEscape)
3058 else if (t.cs() == "lyxdot") {
3059 // This is used by LyX for simple dots in relative
3063 } else if (t.cs() == "space") {
3066 } else if (t.cs() == "string") {
3067 // Convert \string" to " and \string~ to ~
3068 Token const & n = p.next_token();
3069 if (n.asInput() != "\"" && n.asInput() != "~")
3074 // Strip quotes. This is a bit complicated (see latex_path()).
3075 string full = os.str();
3076 if (!full.empty() && full[0] == '"') {
3077 string base = removeExtension(full);
3078 string ext = getExtension(full);
3079 if (!base.empty() && base[base.length()-1] == '"')
3082 return addExtension(trim(base, "\""), ext);
3083 if (full[full.length()-1] == '"')
3086 return trim(full, "\"");
3092 /// Convert \p name from TeX convention (relative to master file) to LyX
3093 /// convention (relative to .lyx file) if it is relative
3094 void fix_child_filename(string & name)
3096 string const absMasterTeX = getMasterFilePath(true);
3097 bool const isabs = FileName::isAbsolute(name);
3098 // convert from "relative to .tex master" to absolute original path
3100 name = makeAbsPath(name, absMasterTeX).absFileName();
3101 bool copyfile = copyFiles();
3102 string const absParentLyX = getParentFilePath(false);
3105 // convert from absolute original path to "relative to master file"
3106 string const rel = to_utf8(makeRelPath(from_utf8(name),
3107 from_utf8(absMasterTeX)));
3108 // re-interpret "relative to .tex file" as "relative to .lyx file"
3109 // (is different if the master .lyx file resides in a
3110 // different path than the master .tex file)
3111 string const absMasterLyX = getMasterFilePath(false);
3112 abs = makeAbsPath(rel, absMasterLyX).absFileName();
3113 // Do not copy if the new path is impossible to create. Example:
3114 // absMasterTeX = "/foo/bar/"
3115 // absMasterLyX = "/bar/"
3116 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
3117 if (contains(name, "/../"))
3124 // convert from absolute original path to
3125 // "relative to .lyx file"
3126 name = to_utf8(makeRelPath(from_utf8(abs),
3127 from_utf8(absParentLyX)));
3131 // convert from absolute original path to "relative to .lyx file"
3132 name = to_utf8(makeRelPath(from_utf8(name),
3133 from_utf8(absParentLyX)));
3138 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
3139 Context & context, string const & rdelim, string const & rdelimesc)
3141 Layout const * newlayout = 0;
3142 InsetLayout const * newinsetlayout = 0;
3143 char const * const * where = 0;
3144 // Store the latest bibliographystyle, addcontentslineContent and
3145 // nocite{*} option (needed for bibtex inset)
3147 string contentslineContent;
3148 // Some classes provide a \bibliographystyle, so do not output
3149 // any if none is explicitly set.
3150 string bibliographystyle;
3151 bool const use_natbib = isProvided("natbib");
3152 bool const use_jurabib = isProvided("jurabib");
3153 bool const use_biblatex = isProvided("biblatex")
3154 && preamble.citeEngine() != "biblatex-natbib";
3155 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
3156 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
3157 need_commentbib = use_biblatex || use_biblatex_natbib;
3160 // it is impossible to determine the correct encoding for non-CJK Japanese.
3161 // Therefore write a note at the beginning of the document
3162 if (is_nonCJKJapanese) {
3163 context.check_layout(os);
3164 begin_inset(os, "Note Note\n");
3165 os << "status open\n\\begin_layout Plain Layout\n"
3166 << "\\series bold\n"
3167 << "Important information:\n"
3168 << "\\end_layout\n\n"
3169 << "\\begin_layout Plain Layout\n"
3170 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
3171 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
3172 << " The iconv encoding " << p.getEncoding() << " was used.\n"
3173 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
3174 << " and specify the encoding using the -e command-line switch.\n"
3175 << " In addition, you might want to double check that the desired output encoding\n"
3176 << " is correctly selected in Document > Settings > Language.\n"
3177 << "\\end_layout\n";
3179 is_nonCJKJapanese = false;
3182 bool have_cycled = false;
3184 // Leave here only after at least one cycle
3185 if (have_cycled && flags & FLAG_LEAVE) {
3186 flags &= ~FLAG_LEAVE;
3190 Token const & t = p.get_token();
3192 debugToken(cerr, t, flags);
3195 if (context.in_list_preamble
3196 && p.next_token().cs() == context.layout->itemcommand()) {
3197 // We are parsing a list preamble. End before first \item.
3198 flags |= FLAG_LEAVE;
3199 context.in_list_preamble = false;
3202 if (flags & FLAG_ITEM) {
3203 if (t.cat() == catSpace)
3206 flags &= ~FLAG_ITEM;
3207 if (t.cat() == catBegin) {
3208 // skip the brace and collect everything to the next matching
3210 flags |= FLAG_BRACE_LAST;
3214 // handle only this single token, leave the loop if done
3215 flags |= FLAG_LEAVE;
3218 if (t.cat() != catEscape && t.character() == ']' &&
3219 (flags & FLAG_BRACK_LAST))
3221 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
3223 string tok = t.asInput();
3224 // we only support delimiters with max 2 chars for now.
3225 if (rdelim.size() > 1)
3226 tok += p.next_token().asInput();
3227 if (t.cat() != catEscape && !rdelim.empty()
3228 && tok == rdelim && (flags & FLAG_RDELIM)
3229 && (rdelimesc.empty() || p.prev_token().asInput() != rdelimesc)) {
3230 if (rdelim.size() > 1)
3231 p.get_token(); // eat rdelim
3235 // If there is anything between \end{env} and \begin{env} we
3236 // don't need to output a separator.
3237 if (t.cat() != catSpace && t.cat() != catNewline &&
3238 t.asInput() != "\\begin")
3245 bool const starred = p.next_token().asInput() == "*";
3246 string const starredname(starred ? (t.cs() + '*') : t.cs());
3247 if (t.cat() == catMath) {
3248 // we are inside some text mode thingy, so opening new math is allowed
3249 context.check_layout(os);
3250 begin_inset(os, "Formula ");
3251 Token const & n = p.get_token();
3252 bool const display(n.cat() == catMath && outer);
3254 // TeX's $$...$$ syntax for displayed math
3256 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3258 p.get_token(); // skip the second '$' token
3260 // simple $...$ stuff
3263 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3268 // Prevent the conversion of a line break to a
3269 // space (bug 7668). This does not change the
3270 // output, but looks ugly in LyX.
3271 eat_whitespace(p, os, context, false);
3276 if (t.cat() == catSuper || t.cat() == catSub) {
3277 string const cc = (t.cat() == catSuper) ? "catSuper" : "catSub";
3278 warning_message("catcode " + cc + " illegal in text mode");
3282 // Basic support for quotes. We try to disambiguate
3283 // quotes from the context (e.g., a left english quote is
3284 // the same as a right german quote...).
3285 // Try to make a smart guess about the side
3286 Token const prev = p.prev_token();
3287 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3288 && prev.character() != '\n' && prev.character() != '~');
3289 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3290 context.check_layout(os);
3291 begin_inset(os, "Quotes ");
3292 os << guessQuoteStyle("eld", opening);
3298 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3299 context.check_layout(os);
3300 begin_inset(os, "Quotes ");
3301 os << guessQuoteStyle("erd", opening);
3308 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3309 context.check_layout(os);
3310 begin_inset(os, "Quotes ");
3311 os << guessQuoteStyle("ald", opening);
3318 if (t.asInput() == "<"
3319 && p.next_token().asInput() == "<") {
3320 bool has_chunk = false;
3324 has_chunk = parse_chunk(p, os, context);
3330 context.check_layout(os);
3331 begin_inset(os, "Quotes ");
3332 os << guessQuoteStyle("ard", opening);
3340 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3341 check_space(p, os, context);
3345 // babel shorthands (also used by polyglossia)
3346 // Since these can have different meanings for different languages
3347 // we import them as ERT (but they must be put in ERT to get output
3349 if (t.asInput() == "\"") {
3351 // We put the known shorthand pairs together in
3352 // one ERT inset. In other cases (such as "a), only
3353 // the quotation mark is ERTed.
3354 if (is_known(p.next_token().asInput(), known_babel_shorthands)) {
3355 s += p.next_token().asInput();
3358 output_ert_inset(os, s, context);
3362 if (t.character() == '[' && noweb_mode &&
3363 p.next_token().character() == '[') {
3364 // These can contain underscores
3366 string const s = p.getFullOpt() + ']';
3367 if (p.next_token().character() == ']')
3370 warning_message("Inserting missing ']' in '" + s + "'.");
3371 output_ert_inset(os, s, context);
3375 if (t.cat() == catLetter) {
3376 context.check_layout(os);
3381 if (t.cat() == catOther ||
3382 t.cat() == catAlign ||
3383 t.cat() == catParameter) {
3384 context.check_layout(os);
3385 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3386 context.merging_hyphens_allowed &&
3387 context.font.family != "ttfamily" &&
3388 !context.layout->pass_thru) {
3389 if (p.next_next_token().asInput() == "-") {
3391 os << to_utf8(docstring(1, 0x2014));
3395 os << to_utf8(docstring(1, 0x2013));
3398 // This translates "&" to "\\&" which may be wrong...
3403 if (p.isParagraph()) {
3404 // In minted floating listings we will collect
3405 // everything into the caption, where multiple
3406 // paragraphs are forbidden.
3407 if (minted_float.empty()) {
3408 if (context.new_layout_allowed)
3409 context.new_paragraph(os);
3411 output_ert_inset(os, "\\par ", context);
3414 eat_whitespace(p, os, context, true);
3418 if (t.cat() == catActive) {
3419 context.check_layout(os);
3420 if (t.character() == '~') {
3421 if (context.layout->free_spacing)
3424 begin_inset(os, "space ~\n");
3432 if (t.cat() == catBegin) {
3433 Token const next = p.next_token();
3434 Token const end = p.next_next_token();
3435 if (next.cat() == catEnd) {
3437 Token const prev = p.prev_token();
3439 if (p.next_token().character() == '`')
3440 ; // ignore it in {}``
3442 output_ert_inset(os, "{}", context);
3443 } else if (next.cat() == catEscape &&
3444 is_known(next.cs(), known_quotes) &&
3445 end.cat() == catEnd) {
3446 // Something like {\textquoteright} (e.g.
3447 // from writer2latex). We may skip the
3448 // braces here for better readability.
3449 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3451 } else if (p.next_token().asInput() == "\\ascii") {
3452 // handle the \ascii characters
3453 // (the case without braces is handled later)
3454 // the code is "{\ascii\xxx}"
3455 p.get_token(); // eat \ascii
3456 string name2 = p.get_token().asInput();
3457 p.get_token(); // eat the final '}'
3458 string const name = "{\\ascii" + name2 + "}";
3462 // get the character from unicodesymbols
3463 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3464 Encodings::TEXT_CMD, termination, rem, &req);
3466 context.check_layout(os);
3469 output_ert_inset(os,
3470 to_utf8(rem), context);
3471 for (set<string>::const_iterator it = req.begin();
3472 it != req.end(); ++it)
3473 preamble.registerAutomaticallyLoadedPackage(*it);
3475 // we did not find a non-ert version
3476 output_ert_inset(os, name, context);
3478 context.check_layout(os);
3479 // special handling of font attribute changes
3480 Token const prev = p.prev_token();
3481 TeXFont const oldFont = context.font;
3482 if (next.character() == '[' ||
3483 next.character() == ']' ||
3484 next.character() == '*') {
3486 if (p.next_token().cat() == catEnd) {
3491 output_ert_inset(os, "{", context);
3492 parse_text_snippet(p, os,
3495 output_ert_inset(os, "}", context);
3497 } else if (! context.new_layout_allowed) {
3498 output_ert_inset(os, "{", context);
3499 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3501 output_ert_inset(os, "}", context);
3502 } else if (is_known(next.cs(), known_sizes)) {
3503 // next will change the size, so we must
3505 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3507 if (!context.atParagraphStart())
3509 << context.font.size << "\n";
3510 } else if (is_known(next.cs(), known_font_families)) {
3511 // next will change the font family, so we
3512 // must reset it here
3513 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3515 if (!context.atParagraphStart())
3517 << context.font.family << "\n";
3518 } else if (is_known(next.cs(), known_font_series)) {
3519 // next will change the font series, so we
3520 // must reset it here
3521 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3523 if (!context.atParagraphStart())
3525 << context.font.series << "\n";
3526 } else if (is_known(next.cs(), known_font_shapes)) {
3527 // next will change the font shape, so we
3528 // must reset it here
3529 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3531 if (!context.atParagraphStart())
3533 << context.font.shape << "\n";
3534 } else if (is_known(next.cs(), known_old_font_families) ||
3535 is_known(next.cs(), known_old_font_series) ||
3536 is_known(next.cs(), known_old_font_shapes)) {
3537 // next will change the font family, series
3538 // and shape, so we must reset it here
3539 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3541 if (!context.atParagraphStart())
3543 << context.font.family
3545 << context.font.series
3547 << context.font.shape << "\n";
3549 output_ert_inset(os, "{", context);
3550 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3552 output_ert_inset(os, "}", context);
3558 if (t.cat() == catEnd) {
3559 if (flags & FLAG_BRACE_LAST) {
3562 warning_message("stray '}' in text");
3563 output_ert_inset(os, "}", context);
3567 if (t.cat() == catComment) {
3568 parse_comment(p, os, t, context);
3573 // control sequences
3576 if (t.cs() == "(" || t.cs() == "[") {
3577 bool const simple = t.cs() == "(";
3578 context.check_layout(os);
3579 begin_inset(os, "Formula");
3580 os << " \\" << t.cs();
3581 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3582 os << '\\' << (simple ? ')' : ']');
3585 // Prevent the conversion of a line break to a
3586 // space (bug 7668). This does not change the
3587 // output, but looks ugly in LyX.
3588 eat_whitespace(p, os, context, false);
3593 if (t.cs() == "begin") {
3594 parse_environment(p, os, outer, last_env,
3599 if (t.cs() == "end") {
3600 if (flags & FLAG_END) {
3601 // eat environment name
3602 string const name = p.getArg('{', '}');
3603 if (name != active_environment())
3604 warning_message("\\end{" + name + "} does not match \\begin{"
3605 + active_environment() + "}");
3608 p.error("found 'end' unexpectedly");
3612 // "item" by default, but could be something else
3613 if (t.cs() == context.layout->itemcommand()) {
3615 if (context.layout->labeltype == LABEL_MANUAL) {
3616 // FIXME: This swallows comments, but we cannot use
3617 // eat_whitespace() since we must not output
3618 // anything before the item.
3619 p.skip_spaces(true);
3620 s = p.verbatimOption();
3622 p.skip_spaces(false);
3624 context.check_layout(os);
3625 if (context.has_item) {
3626 // An item in an unknown list-like environment
3627 // FIXME: Do this in check_layout()!
3628 context.has_item = false;
3629 string item = "\\" + context.layout->itemcommand();
3632 output_ert_inset(os, item, context);
3634 if (context.layout->labeltype != LABEL_MANUAL)
3635 output_arguments(os, p, outer, false, "item", context,
3636 context.layout->itemargs());
3637 if (!context.list_preamble.empty()) {
3638 // We have a list preamble. Output it here.
3639 begin_inset(os, "Argument listpreamble:1");
3640 os << "\nstatus collapsed\n\n"
3641 << "\\begin_layout Plain Layout\n\n"
3642 << rtrim(context.list_preamble)
3643 << "\n\\end_layout";
3645 context.list_preamble.clear();
3647 if (!context.list_extra_stuff.empty()) {
3648 os << context.list_extra_stuff;
3649 context.list_extra_stuff.clear();
3651 else if (!s.empty()) {
3652 // LyX adds braces around the argument,
3653 // so we need to remove them here.
3654 if (s.size() > 2 && s[0] == '{' &&
3655 s[s.size()-1] == '}')
3656 s = s.substr(1, s.size()-2);
3657 // If the argument contains a space we
3658 // must put it into ERT: Otherwise LyX
3659 // would misinterpret the space as
3660 // item delimiter (bug 7663)
3661 if (contains(s, ' ')) {
3662 output_ert_inset(os, s, context);
3665 os << parse_text_snippet(p2,
3666 FLAG_BRACK_LAST, outer, context);
3668 // The space is needed to separate the
3669 // item from the rest of the sentence.
3671 eat_whitespace(p, os, context, false);
3676 if (t.cs() == "bibitem") {
3678 context.check_layout(os);
3679 eat_whitespace(p, os, context, false);
3680 string label = p.verbatimOption();
3681 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3682 bool const literal = !lbl.first;
3683 label = literal ? subst(label, "\n", " ") : lbl.second;
3684 string lit = literal ? "\"true\"" : "\"false\"";
3685 string key = convert_literate_command_inset_arg(p.verbatim_item());
3686 begin_command_inset(os, "bibitem", "bibitem");
3687 os << "label \"" << label << "\"\n"
3688 << "key \"" << key << "\"\n"
3689 << "literal " << lit << "\n";
3695 // catch the case of \def\inputGnumericTable
3697 if (t.cs() == "def") {
3698 Token second = p.next_token();
3699 if (second.cs() == "inputGnumericTable") {
3703 Token third = p.get_token();
3705 if (third.cs() == "input") {
3709 string name = normalize_filename(p.verbatim_item());
3710 string const path = getMasterFilePath(true);
3711 // We want to preserve relative / absolute filenames,
3712 // therefore path is only used for testing
3713 // The file extension is in every case ".tex".
3714 // So we need to remove this extension and check for
3715 // the original one.
3716 name = removeExtension(name);
3717 if (!makeAbsPath(name, path).exists()) {
3718 char const * const Gnumeric_formats[] = {"gnumeric",
3720 string const Gnumeric_name =
3721 find_file(name, path, Gnumeric_formats);
3722 if (!Gnumeric_name.empty())
3723 name = Gnumeric_name;
3725 FileName const absname = makeAbsPath(name, path);
3726 if (absname.exists()) {
3727 fix_child_filename(name);
3728 copy_file(absname, name);
3730 warning_message("Could not find file '" + name + "'.");
3731 context.check_layout(os);
3732 begin_inset(os, "External\n\ttemplate ");
3733 os << "GnumericSpreadsheet\n\tfilename "
3736 context.check_layout(os);
3738 // register the packages that are automatically loaded
3739 // by the Gnumeric template
3740 registerExternalTemplatePackages("GnumericSpreadsheet");
3745 parse_macro(p, os, context);
3749 if (t.cs() == "noindent") {
3751 context.add_par_extra_stuff("\\noindent\n");
3755 if (t.cs() == "appendix" && !context.in_list_preamble) {
3756 context.add_par_extra_stuff("\\start_of_appendix\n");
3757 // We need to start a new paragraph. Otherwise the
3758 // appendix in 'bla\appendix\chapter{' would start
3760 context.new_paragraph(os);
3761 // We need to make sure that the paragraph is
3762 // generated even if it is empty. Otherwise the
3763 // appendix in '\par\appendix\par\chapter{' would
3765 context.check_layout(os);
3766 // FIXME: This is a hack to prevent paragraph
3767 // deletion if it is empty. Handle this better!
3768 output_comment(p, os,
3769 "dummy comment inserted by tex2lyx to "
3770 "ensure that this paragraph is not empty",
3772 // Both measures above may generate an additional
3773 // empty paragraph, but that does not hurt, because
3774 // whitespace does not matter here.
3775 eat_whitespace(p, os, context, true);
3779 // Must catch empty dates before findLayout is called below
3780 if (t.cs() == "date") {
3781 eat_whitespace(p, os, context, false);
3783 string const date = p.verbatim_item();
3786 preamble.suppressDate(true);
3789 preamble.suppressDate(false);
3790 if (context.new_layout_allowed &&
3791 (newlayout = findLayout(context.textclass,
3794 output_command_layout(os, p, outer,
3795 context, newlayout);
3796 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3797 if (!preamble.titleLayoutFound())
3798 preamble.titleLayoutFound(newlayout->intitle);
3799 set<string> const & req = newlayout->required();
3800 set<string>::const_iterator it = req.begin();
3801 set<string>::const_iterator en = req.end();
3802 for (; it != en; ++it)
3803 preamble.registerAutomaticallyLoadedPackage(*it);
3805 output_ert_inset(os,
3806 "\\date{" + p.verbatim_item() + '}',
3812 // Before we look for the layout name with star and alone below, we check the layouts including
3813 // the LateXParam, which might be one or several options or a star.
3814 // The single '=' is meant here.
3815 if (context.new_layout_allowed &&
3816 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3817 // store the latexparam here. This is eaten in output_command_layout
3818 context.latexparam = newlayout->latexparam();
3820 output_command_layout(os, p, outer, context, newlayout);
3821 context.latexparam.clear();
3823 if (!preamble.titleLayoutFound())
3824 preamble.titleLayoutFound(newlayout->intitle);
3825 set<string> const & req = newlayout->required();
3826 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3827 preamble.registerAutomaticallyLoadedPackage(*it);
3831 // Starred section headings
3832 // Must attempt to parse "Section*" before "Section".
3833 if ((p.next_token().asInput() == "*") &&
3834 context.new_layout_allowed &&
3835 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3838 output_command_layout(os, p, outer, context, newlayout);
3840 if (!preamble.titleLayoutFound())
3841 preamble.titleLayoutFound(newlayout->intitle);
3842 set<string> const & req = newlayout->required();
3843 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3844 preamble.registerAutomaticallyLoadedPackage(*it);
3848 // Section headings and the like
3849 if (context.new_layout_allowed &&
3850 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3852 output_command_layout(os, p, outer, context, newlayout);
3854 if (!preamble.titleLayoutFound())
3855 preamble.titleLayoutFound(newlayout->intitle);
3856 set<string> const & req = newlayout->required();
3857 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3858 preamble.registerAutomaticallyLoadedPackage(*it);
3862 if (t.cs() == "subfloat") {
3863 // the syntax is \subfloat[list entry][sub caption]{content}
3864 // if it is a table of figure depends on the surrounding float
3866 // do nothing if there is no outer float
3867 if (!float_type.empty()) {
3868 context.check_layout(os);
3870 begin_inset(os, "Float " + float_type + "\n");
3872 << "\nsideways false"
3873 << "\nstatus collapsed\n\n";
3876 bool has_caption = false;
3877 if (p.next_token().cat() != catEscape &&
3878 p.next_token().character() == '[') {
3879 p.get_token(); // eat '['
3880 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3883 // In case we have two optional args, the second is the caption.
3884 if (p.next_token().cat() != catEscape &&
3885 p.next_token().character() == '[') {
3886 p.get_token(); // eat '['
3887 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3890 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3891 // the caption comes always as the last
3893 // we must make sure that the caption gets a \begin_layout
3894 os << "\n\\begin_layout Plain Layout";
3896 begin_inset(os, "Caption Standard\n");
3897 Context newcontext(true, context.textclass,
3898 0, 0, context.font);
3899 newcontext.check_layout(os);
3900 os << caption << "\n";
3901 newcontext.check_end_layout(os);
3904 // close the layout we opened
3905 os << "\n\\end_layout";
3910 // if the float type is not supported or there is no surrounding float
3915 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3917 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3919 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3920 + "{" + p.verbatim_item() + '}', context);
3925 if (t.cs() == "xymatrix") {
3926 // we must open a new math because LyX's xy support is in math
3927 context.check_layout(os);
3928 begin_inset(os, "Formula ");
3930 os << "\\" << t.cs() << '{';
3931 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3934 preamble.registerAutomaticallyLoadedPackage("xy");
3938 if (t.cs() == "includegraphics") {
3939 bool const clip = p.next_token().asInput() == "*";
3942 string const arg = p.getArg('[', ']');
3943 map<string, string> opts;
3944 vector<string> keys;
3945 split_map(arg, opts, keys);
3947 opts["clip"] = string();
3948 string name = normalize_filename(p.verbatim_item());
3950 string const path = getMasterFilePath(true);
3951 // We want to preserve relative / absolute filenames,
3952 // therefore path is only used for testing
3953 if (!makeAbsPath(name, path).exists()) {
3954 // The file extension is probably missing.
3955 // Now try to find it out.
3956 string const dvips_name =
3957 find_file(name, path,
3958 known_dvips_graphics_formats);
3959 string const pdftex_name =
3960 find_file(name, path,
3961 known_pdftex_graphics_formats);
3962 if (!dvips_name.empty()) {
3963 if (!pdftex_name.empty()) {
3964 warning_message("This file contains the "
3966 "\"\\includegraphics{" + name + "}\".\n"
3967 "However, files\n\""
3968 + dvips_name + "\" and\n\""
3969 + pdftex_name + "\"\n"
3970 "both exist, so I had to make a "
3971 "choice and took the first one.\n"
3972 "Please move the unwanted one "
3973 "someplace else and try again\n"
3974 "if my choice was wrong.");
3977 } else if (!pdftex_name.empty()) {
3983 FileName const absname = makeAbsPath(name, path);
3984 if (absname.exists()) {
3985 fix_child_filename(name);
3986 copy_file(absname, name);
3988 warning_message("Could not find graphics file '" + name + "'.");
3990 context.check_layout(os);
3991 begin_inset(os, "Graphics ");
3992 os << "\n\tfilename " << name << '\n';
3993 if (opts.find("width") != opts.end())
3995 << translate_len(opts["width"]) << '\n';
3996 if (opts.find("totalheight") != opts.end())
3998 << translate_len(opts["totalheight"]) << '\n';
3999 if (opts.find("scale") != opts.end()) {
4000 istringstream iss(opts["scale"]);
4004 os << "\tscale " << val << '\n';
4006 if (opts.find("angle") != opts.end()) {
4007 os << "\trotateAngle "
4008 << opts["angle"] << '\n';
4009 vector<string>::const_iterator a =
4010 find(keys.begin(), keys.end(), "angle");
4011 vector<string>::const_iterator s =
4012 find(keys.begin(), keys.end(), "width");
4013 if (s == keys.end())
4014 s = find(keys.begin(), keys.end(), "totalheight");
4015 if (s == keys.end())
4016 s = find(keys.begin(), keys.end(), "scale");
4017 if (s != keys.end() && distance(s, a) > 0)
4018 os << "\tscaleBeforeRotation\n";
4020 if (opts.find("origin") != opts.end()) {
4022 string const opt = opts["origin"];
4023 if (opt.find('l') != string::npos) ss << "left";
4024 if (opt.find('r') != string::npos) ss << "right";
4025 if (opt.find('c') != string::npos) ss << "center";
4026 if (opt.find('t') != string::npos) ss << "Top";
4027 if (opt.find('b') != string::npos) ss << "Bottom";
4028 if (opt.find('B') != string::npos) ss << "Baseline";
4029 if (!ss.str().empty())
4030 os << "\trotateOrigin " << ss.str() << '\n';
4032 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
4034 if (opts.find("keepaspectratio") != opts.end())
4035 os << "\tkeepAspectRatio\n";
4036 if (opts.find("clip") != opts.end())
4038 if (opts.find("draft") != opts.end())
4040 if (opts.find("bb") != opts.end())
4041 os << "\tBoundingBox "
4042 << opts["bb"] << '\n';
4043 int numberOfbbOptions = 0;
4044 if (opts.find("bbllx") != opts.end())
4045 numberOfbbOptions++;
4046 if (opts.find("bblly") != opts.end())
4047 numberOfbbOptions++;
4048 if (opts.find("bburx") != opts.end())
4049 numberOfbbOptions++;
4050 if (opts.find("bbury") != opts.end())
4051 numberOfbbOptions++;
4052 if (numberOfbbOptions == 4)
4053 os << "\tBoundingBox "
4054 << opts["bbllx"] << " " << opts["bblly"] << " "
4055 << opts["bburx"] << " " << opts["bbury"] << '\n';
4056 else if (numberOfbbOptions > 0)
4057 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4058 numberOfbbOptions = 0;
4059 if (opts.find("natwidth") != opts.end())
4060 numberOfbbOptions++;
4061 if (opts.find("natheight") != opts.end())
4062 numberOfbbOptions++;
4063 if (numberOfbbOptions == 2)
4064 os << "\tBoundingBox 0bp 0bp "
4065 << opts["natwidth"] << " " << opts["natheight"] << '\n';
4066 else if (numberOfbbOptions > 0)
4067 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4068 ostringstream special;
4069 if (opts.find("hiresbb") != opts.end())
4070 special << "hiresbb,";
4071 if (opts.find("trim") != opts.end())
4073 if (opts.find("viewport") != opts.end())
4074 special << "viewport=" << opts["viewport"] << ',';
4075 if (opts.find("height") != opts.end())
4076 special << "height=" << opts["height"] << ',';
4077 if (opts.find("type") != opts.end())
4078 special << "type=" << opts["type"] << ',';
4079 if (opts.find("ext") != opts.end())
4080 special << "ext=" << opts["ext"] << ',';
4081 if (opts.find("read") != opts.end())
4082 special << "read=" << opts["read"] << ',';
4083 if (opts.find("command") != opts.end())
4084 special << "command=" << opts["command"] << ',';
4085 string s_special = special.str();
4086 if (!s_special.empty()) {
4087 // We had special arguments. Remove the trailing ','.
4088 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
4090 // TODO: Handle the unknown settings better.
4091 // Warn about invalid options.
4092 // Check whether some option was given twice.
4094 preamble.registerAutomaticallyLoadedPackage("graphicx");
4098 if (t.cs() == "footnote" ||
4099 (t.cs() == "thanks" && context.layout->intitle)) {
4101 context.check_layout(os);
4102 begin_inset(os, "Foot\n");
4103 os << "status collapsed\n\n";
4104 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4109 if (t.cs() == "marginpar") {
4111 context.check_layout(os);
4112 begin_inset(os, "Marginal\n");
4113 os << "status collapsed\n\n";
4114 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4119 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
4120 bool const use_minted = t.cs() == "mintinline";
4122 parse_listings(p, os, context, true, use_minted);
4126 if (t.cs() == "ensuremath") {
4128 context.check_layout(os);
4129 string const s = p.verbatim_item();
4130 //FIXME: this never triggers in UTF8
4131 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
4134 output_ert_inset(os, "\\ensuremath{" + s + "}",
4139 else if (t.cs() == "makeindex"
4140 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
4141 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
4142 if (preamble.titleLayoutFound()) {
4144 skip_spaces_braces(p);
4146 output_ert_inset(os, t.asInput(), context);
4150 if (t.cs() == "tableofcontents"
4151 || t.cs() == "lstlistoflistings"
4152 || t.cs() == "listoflistings") {
4153 string name = t.cs();
4154 if (preamble.minted() && name == "listoflistings")
4155 name.insert(0, "lst");
4156 context.check_layout(os);
4157 begin_command_inset(os, "toc", name);
4159 skip_spaces_braces(p);
4160 if (name == "lstlistoflistings") {
4161 if (preamble.minted())
4162 preamble.registerAutomaticallyLoadedPackage("minted");
4164 preamble.registerAutomaticallyLoadedPackage("listings");
4169 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
4170 context.check_layout(os);
4171 if (t.cs() == "listoffigures")
4172 begin_inset(os, "FloatList figure\n");
4174 begin_inset(os, "FloatList table\n");
4176 skip_spaces_braces(p);
4180 if (t.cs() == "listof") {
4181 p.skip_spaces(true);
4182 string const name = p.verbatim_item();
4183 if (context.textclass.floats().typeExist(name)) {
4184 context.check_layout(os);
4185 begin_inset(os, "FloatList ");
4188 p.verbatim_item(); // swallow second arg
4190 output_ert_inset(os, "\\listof{" + name + "}", context);
4194 if (t.cs() == "theendnotes"
4195 || (t.cs() == "printendnotes"
4196 && p.next_token().asInput() != "*"
4198 context.check_layout(os);
4199 begin_inset(os, "FloatList endnote\n");
4201 skip_spaces_braces(p);
4205 if ((where = is_known(t.cs(), known_text_font_families))) {
4206 parse_text_attributes(p, os, FLAG_ITEM, outer,
4207 context, "\\family", context.font.family,
4208 known_coded_font_families[where - known_text_font_families]);
4212 // beamer has a \textbf<overlay>{} inset
4213 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
4214 parse_text_attributes(p, os, FLAG_ITEM, outer,
4215 context, "\\series", context.font.series,
4216 known_coded_font_series[where - known_text_font_series]);
4220 // beamer has a \textit<overlay>{} inset
4221 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4222 parse_text_attributes(p, os, FLAG_ITEM, outer,
4223 context, "\\shape", context.font.shape,
4224 known_coded_font_shapes[where - known_text_font_shapes]);
4228 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4229 context.check_layout(os);
4230 TeXFont oldFont = context.font;
4231 context.font.init();
4232 context.font.size = oldFont.size;
4233 os << "\n\\family " << context.font.family << "\n";
4234 os << "\n\\series " << context.font.series << "\n";
4235 os << "\n\\shape " << context.font.shape << "\n";
4236 if (t.cs() == "textnormal") {
4237 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4238 output_font_change(os, context.font, oldFont);
4239 context.font = oldFont;
4241 eat_whitespace(p, os, context, false);
4245 if (t.cs() == "textcolor") {
4246 // scheme is \textcolor{color name}{text}
4247 string const color = p.verbatim_item();
4248 // we support the predefined colors of the color and the xcolor package
4249 if (color == "black" || color == "blue" || color == "cyan"
4250 || color == "green" || color == "magenta" || color == "red"
4251 || color == "white" || color == "yellow") {
4252 context.check_layout(os);
4253 os << "\n\\color " << color << "\n";
4254 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4255 context.check_layout(os);
4256 os << "\n\\color inherit\n";
4257 preamble.registerAutomaticallyLoadedPackage("color");
4258 } else if (color == "brown" || color == "darkgray" || color == "gray"
4259 || color == "lightgray" || color == "lime" || color == "olive"
4260 || color == "orange" || color == "pink" || color == "purple"
4261 || color == "teal" || color == "violet") {
4262 context.check_layout(os);
4263 os << "\n\\color " << color << "\n";
4264 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4265 context.check_layout(os);
4266 os << "\n\\color inherit\n";
4267 preamble.registerAutomaticallyLoadedPackage("xcolor");
4269 // for custom defined colors
4270 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4274 if (t.cs() == "underbar" || t.cs() == "uline") {
4275 // \underbar is not 100% correct (LyX outputs \uline
4276 // of ulem.sty). The difference is that \ulem allows
4277 // line breaks, and \underbar does not.
4278 // Do NOT handle \underline.
4279 // \underbar cuts through y, g, q, p etc.,
4280 // \underline does not.
4281 context.check_layout(os);
4282 os << "\n\\bar under\n";
4283 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4284 context.check_layout(os);
4285 os << "\n\\bar default\n";
4286 preamble.registerAutomaticallyLoadedPackage("ulem");
4290 if (t.cs() == "sout") {
4291 context.check_layout(os);
4292 os << "\n\\strikeout on\n";
4293 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4294 context.check_layout(os);
4295 os << "\n\\strikeout default\n";
4296 preamble.registerAutomaticallyLoadedPackage("ulem");
4300 // beamer has an \emph<overlay>{} inset
4301 if ((t.cs() == "uuline" || t.cs() == "uwave"
4302 || t.cs() == "emph" || t.cs() == "noun"
4303 || t.cs() == "xout") && !p.hasOpt("<")) {
4304 context.check_layout(os);
4305 os << "\n\\" << t.cs() << " on\n";
4306 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4307 context.check_layout(os);
4308 os << "\n\\" << t.cs() << " default\n";
4309 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4310 preamble.registerAutomaticallyLoadedPackage("ulem");
4314 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4315 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4316 context.check_layout(os);
4319 initials = p.getArg('[', ']');
4321 string name = p.getArg('{', '}');
4322 string localtime = p.getArg('{', '}');
4323 preamble.registerAuthor(name, initials);
4324 Author const & author = preamble.getAuthor(name);
4325 // from_asctime_utc() will fail if LyX decides to output the
4326 // time in the text language.
4327 time_t ptime = from_asctime_utc(localtime);
4328 if (ptime == static_cast<time_t>(-1)) {
4329 warning_message("Could not parse time `" + localtime
4330 + "´ for change tracking, using current time instead.");
4331 ptime = current_time();
4333 if (t.cs() == "lyxadded")
4334 os << "\n\\change_inserted ";
4336 os << "\n\\change_deleted ";
4337 os << author.bufferId() << ' ' << ptime << '\n';
4338 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4339 if (LaTeXPackages::isAvailable("ulem")
4340 && LaTeXPackages::isAvailable("xcolor")) {
4341 preamble.registerAutomaticallyLoadedPackage("ulem");
4342 preamble.registerAutomaticallyLoadedPackage("xcolor");
4347 if (t.cs() == "textipa") {
4348 context.check_layout(os);
4349 begin_inset(os, "IPA\n");
4350 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4351 context.merging_hyphens_allowed = false;
4352 set<string> pass_thru_cmds = context.pass_thru_cmds;
4353 // These commands have special meanings in IPA
4354 context.pass_thru_cmds.insert("!");
4355 context.pass_thru_cmds.insert(";");
4356 context.pass_thru_cmds.insert(":");
4357 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4358 context.pass_thru_cmds = pass_thru_cmds;
4359 context.merging_hyphens_allowed = merging_hyphens_allowed;
4361 preamble.registerAutomaticallyLoadedPackage("tipa");
4362 preamble.registerAutomaticallyLoadedPackage("tipx");
4366 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4367 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4368 context.check_layout(os);
4372 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4373 begin_inset(os, "IPADeco " + type + "\n");
4374 os << "status open\n";
4375 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4381 if (t.cs() == "textvertline") {
4382 // FIXME: This is not correct, \textvertline is higher than |
4388 if (t.cs() == "tone" ) {
4389 context.check_layout(os);
4390 // register the tone package
4391 preamble.registerAutomaticallyLoadedPackage("tone");
4392 string content = trimSpaceAndEol(p.verbatim_item());
4393 string command = t.asInput() + "{" + content + "}";
4394 // some tones can be detected by unicodesymbols, some need special code
4395 if (is_known(content, known_tones)) {
4396 os << "\\IPAChar " << command << "\n";
4399 // try to see whether the string is in unicodesymbols
4403 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4404 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4405 termination, rem, &req);
4409 output_ert_inset(os, to_utf8(rem), context);
4410 for (set<string>::const_iterator it = req.begin();
4411 it != req.end(); ++it)
4412 preamble.registerAutomaticallyLoadedPackage(*it);
4414 // we did not find a non-ert version
4415 output_ert_inset(os, command, context);
4419 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4420 t.cs() == "vphantom") {
4421 context.check_layout(os);
4422 if (t.cs() == "phantom")
4423 begin_inset(os, "Phantom Phantom\n");
4424 if (t.cs() == "hphantom")
4425 begin_inset(os, "Phantom HPhantom\n");
4426 if (t.cs() == "vphantom")
4427 begin_inset(os, "Phantom VPhantom\n");
4428 os << "status open\n";
4429 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4435 if (t.cs() == "href") {
4436 context.check_layout(os);
4437 string target = convert_literate_command_inset_arg(p.verbatim_item());
4438 string name = p.verbatim_item();
4439 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4440 bool const literal = !nm.first;
4441 name = literal ? subst(name, "\n", " ") : nm.second;
4442 string lit = literal ? "\"true\"" : "\"false\"";
4444 size_t i = target.find(':');
4445 if (i != string::npos) {
4446 type = target.substr(0, i + 1);
4447 if (type == "mailto:" || type == "file:")
4448 target = target.substr(i + 1);
4449 else if (target.find("://") == string::npos)
4451 // handle the case that name is equal to target, except of "http(s)://"
4452 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4455 begin_command_inset(os, "href", "href");
4457 os << "name \"" << name << "\"\n";
4458 os << "target \"" << target << "\"\n";
4459 if (type == "mailto:" || type == "file:" || type == "other")
4460 os << "type \"" << type << "\"\n";
4461 os << "literal " << lit << "\n";
4463 skip_spaces_braces(p);
4467 if (t.cs() == "lyxline") {
4468 // swallow size argument (it is not used anyway)
4470 if (!context.atParagraphStart()) {
4471 // so our line is in the middle of a paragraph
4472 // we need to add a new line, lest this line
4473 // follow the other content on that line and
4474 // run off the side of the page
4475 // FIXME: This may create an empty paragraph,
4476 // but without that it would not be
4477 // possible to set noindent below.
4478 // Fortunately LaTeX does not care
4479 // about the empty paragraph.
4480 context.new_paragraph(os);
4482 if (preamble.indentParagraphs()) {
4483 // we need to unindent, lest the line be too long
4484 context.add_par_extra_stuff("\\noindent\n");
4486 context.check_layout(os);
4487 begin_command_inset(os, "line", "rule");
4488 os << "offset \"0.5ex\"\n"
4489 "width \"100line%\"\n"
4495 if (t.cs() == "rule") {
4496 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4497 string const width = p.getArg('{', '}');
4498 string const thickness = p.getArg('{', '}');
4499 context.check_layout(os);
4500 begin_command_inset(os, "line", "rule");
4501 if (!offset.empty())
4502 os << "offset \"" << translate_len(offset) << "\"\n";
4503 os << "width \"" << translate_len(width) << "\"\n"
4504 "height \"" << translate_len(thickness) << "\"\n";
4509 // Handle refstyle first in order to to catch \eqref, because this
4510 // can also occur without refstyle. Only recognize these commands if
4511 // refstyle.sty was found in the preamble (otherwise \eqref
4512 // and user defined ref commands could be misdetected).
4513 // We uncapitalize the input in order to catch capitalized commands
4515 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4516 && preamble.refstyle()) {
4517 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4518 string plural = "false";
4519 // Catch the plural option [s]
4521 string const opt = p.getOpt();
4525 // LyX does not yet support other optional arguments of ref commands
4526 output_ert_inset(os, t.asInput() + opt + "{" +
4527 p.verbatim_item() + '}', context);
4531 context.check_layout(os);
4532 begin_command_inset(os, "ref", "formatted");
4533 os << "reference \"";
4534 os << known_refstyle_prefixes[where - known_refstyle_commands]
4536 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4538 os << "plural \"" << plural << "\"\n";
4539 os << "caps \"" << cap << "\"\n";
4540 os << "noprefix \"false\"\n";
4542 preamble.registerAutomaticallyLoadedPackage("refstyle");
4546 // if refstyle is used, we must not convert \prettyref to a
4547 // formatted reference, since that would result in a refstyle command.
4548 if ((where = is_known(t.cs(), known_ref_commands))
4549 && (t.cs() != "prettyref" || !preamble.refstyle())
4550 && (p.next_token().asInput() != "*" || is_known(t.cs(), known_starref_commands))) {
4551 bool starred = false;
4552 if (p.next_token().asInput() == "*") {
4556 string const opt = p.getOpt();
4558 context.check_layout(os);
4559 begin_command_inset(os, "ref",
4560 known_coded_ref_commands[where - known_ref_commands]);
4561 os << "reference \""
4562 << convert_literate_command_inset_arg(p.verbatim_item())
4564 os << "plural \"false\"\n";
4565 os << "caps \"false\"\n";
4566 os << "noprefix \"false\"\n";
4568 os << "nolink \"true\"\n";
4570 os << "nolink \"false\"\n";
4572 if (t.cs() == "vref" || t.cs() == "vpageref")
4573 preamble.registerAutomaticallyLoadedPackage("varioref");
4574 else if (t.cs() == "prettyref")
4575 preamble.registerAutomaticallyLoadedPackage("prettyref");
4577 // LyX does not yet support optional arguments of ref commands
4578 output_ert_inset(os, t.asInput() + opt + "{" +
4579 p.verbatim_item() + '}', context);
4585 is_known(t.cs(), known_natbib_commands) &&
4586 ((t.cs() != "citefullauthor" &&
4587 t.cs() != "citeyear" &&
4588 t.cs() != "citeyearpar") ||
4589 p.next_token().asInput() != "*")) {
4590 context.check_layout(os);
4591 string command = t.cs();
4592 if (p.next_token().asInput() == "*") {
4596 if (command == "citefullauthor")
4597 // alternative name for "\\citeauthor*"
4598 command = "citeauthor*";
4600 // text before the citation
4602 // text after the citation
4604 get_cite_arguments(p, true, before, after);
4606 if (command == "cite") {
4607 // \cite without optional argument means
4608 // \citet, \cite with at least one optional
4609 // argument means \citep.
4610 if (before.empty() && after.empty())
4615 if (before.empty() && after == "[]")
4616 // avoid \citet[]{a}
4618 else if (before == "[]" && after == "[]") {
4619 // avoid \citet[][]{a}
4623 bool literal = false;
4624 pair<bool, string> aft;
4625 pair<bool, string> bef;
4626 // remove the brackets around after and before
4627 if (!after.empty()) {
4629 after.erase(after.length() - 1, 1);
4630 aft = convert_latexed_command_inset_arg(after);
4631 literal = !aft.first;
4632 after = literal ? subst(after, "\n", " ") : aft.second;
4634 if (!before.empty()) {
4636 before.erase(before.length() - 1, 1);
4637 bef = convert_latexed_command_inset_arg(before);
4638 literal |= !bef.first;
4639 before = literal ? subst(before, "\n", " ") : bef.second;
4640 if (literal && !after.empty())
4641 after = subst(after, "\n", " ");
4643 string lit = literal ? "\"true\"" : "\"false\"";
4644 begin_command_inset(os, "citation", command);
4645 os << "after " << '"' << after << '"' << "\n";
4646 os << "before " << '"' << before << '"' << "\n";
4648 << convert_literate_command_inset_arg(p.verbatim_item())
4650 << "literal " << lit << "\n";
4652 // Need to set the cite engine if natbib is loaded by
4653 // the document class directly
4654 if (preamble.citeEngine() == "basic")
4655 preamble.citeEngine("natbib");
4660 && is_known(t.cs(), known_biblatex_commands)
4661 && ((t.cs() == "cite"
4662 || t.cs() == "citeauthor"
4663 || t.cs() == "Citeauthor"
4664 || t.cs() == "parencite"
4665 || t.cs() == "citetitle")
4666 || p.next_token().asInput() != "*"))
4667 || (use_biblatex_natbib
4668 && (is_known(t.cs(), known_biblatex_commands)
4669 || is_known(t.cs(), known_natbib_commands))
4670 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4671 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4672 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4673 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4674 || t.cs() == "parencite" || t.cs() == "citetitle")
4675 || p.next_token().asInput() != "*"))){
4676 context.check_layout(os);
4677 string command = t.cs();
4678 if (p.next_token().asInput() == "*") {
4683 bool const qualified = suffixIs(command, "s");
4685 command = rtrim(command, "s");
4687 // text before the citation
4689 // text after the citation
4691 get_cite_arguments(p, true, before, after, qualified);
4693 // These use natbib cmd names in LyX
4694 // for inter-citeengine compativility
4695 if (command == "citeyear")
4696 command = "citebyear";
4697 else if (command == "cite*")
4698 command = "citeyear";
4699 else if (command == "textcite")
4701 else if (command == "Textcite")
4703 else if (command == "parencite")
4705 else if (command == "Parencite")
4707 else if (command == "parencite*")
4708 command = "citeyearpar";
4709 else if (command == "smartcite")
4710 command = "footcite";
4711 else if (command == "Smartcite")
4712 command = "Footcite";
4714 string const emptyarg = qualified ? "()" : "[]";
4715 if (before.empty() && after == emptyarg)
4718 else if (before == emptyarg && after == emptyarg) {
4719 // avoid \cite[][]{a}
4723 bool literal = false;
4724 pair<bool, string> aft;
4725 pair<bool, string> bef;
4726 // remove the brackets around after and before
4727 if (!after.empty()) {
4729 after.erase(after.length() - 1, 1);
4730 aft = convert_latexed_command_inset_arg(after);
4731 literal = !aft.first;
4732 after = literal ? subst(after, "\n", " ") : aft.second;
4734 if (!before.empty()) {
4736 before.erase(before.length() - 1, 1);
4737 bef = convert_latexed_command_inset_arg(before);
4738 literal |= !bef.first;
4739 before = literal ? subst(before, "\n", " ") : bef.second;
4741 string keys, pretextlist, posttextlist;
4743 vector<pair<string, string>> pres, posts, preslit, postslit;
4744 vector<string> lkeys;
4745 // text before the citation
4746 string lbefore, lbeforelit;
4747 // text after the citation
4748 string lafter, lafterlit;
4750 pair<bool, string> laft, lbef;
4752 get_cite_arguments(p, true, lbefore, lafter);
4753 // remove the brackets around after and before
4754 if (!lafter.empty()) {
4756 lafter.erase(lafter.length() - 1, 1);
4757 laft = convert_latexed_command_inset_arg(lafter);
4758 literal |= !laft.first;
4759 lafter = laft.second;
4760 lafterlit = subst(lafter, "\n", " ");
4762 if (!lbefore.empty()) {
4763 lbefore.erase(0, 1);
4764 lbefore.erase(lbefore.length() - 1, 1);
4765 lbef = convert_latexed_command_inset_arg(lbefore);
4766 literal |= !lbef.first;
4767 lbefore = lbef.second;
4768 lbeforelit = subst(lbefore, "\n", " ");
4770 if (lbefore.empty() && lafter == "[]") {
4775 else if (lbefore == "[]" && lafter == "[]") {
4776 // avoid \cite[][]{a}
4782 lkey = p.getArg('{', '}');
4785 pres.push_back(make_pair(lkey, lbefore));
4786 preslit.push_back(make_pair(lkey, lbeforelit));
4787 posts.push_back(make_pair(lkey, lafter));
4788 postslit.push_back(make_pair(lkey, lafterlit));
4789 lkeys.push_back(lkey);
4791 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4796 for (auto const & ptl : pres) {
4797 if (!pretextlist.empty())
4798 pretextlist += '\t';
4799 pretextlist += ptl.first;
4800 if (!ptl.second.empty())
4801 pretextlist += " " + ptl.second;
4803 for (auto const & potl : posts) {
4804 if (!posttextlist.empty())
4805 posttextlist += '\t';
4806 posttextlist += potl.first;
4807 if (!potl.second.empty())
4808 posttextlist += " " + potl.second;
4811 keys = convert_literate_command_inset_arg(p.verbatim_item());
4814 after = subst(after, "\n", " ");
4815 if (!before.empty())
4816 before = subst(after, "\n", " ");
4818 string lit = literal ? "\"true\"" : "\"false\"";
4819 begin_command_inset(os, "citation", command);
4820 os << "after " << '"' << after << '"' << "\n";
4821 os << "before " << '"' << before << '"' << "\n";
4825 if (!pretextlist.empty())
4826 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4827 if (!posttextlist.empty())
4828 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4829 os << "literal " << lit << "\n";
4831 // Need to set the cite engine if biblatex is loaded by
4832 // the document class directly
4833 if (preamble.citeEngine() == "basic")
4834 use_biblatex_natbib ?
4835 preamble.citeEngine("biblatex-natbib")
4836 : preamble.citeEngine("biblatex");
4841 is_known(t.cs(), known_jurabib_commands) &&
4842 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4843 context.check_layout(os);
4844 string command = t.cs();
4845 if (p.next_token().asInput() == "*") {
4849 char argumentOrder = '\0';
4850 vector<string> const options =
4851 preamble.getPackageOptions("jurabib");
4852 if (find(options.begin(), options.end(),
4853 "natbiborder") != options.end())
4854 argumentOrder = 'n';
4855 else if (find(options.begin(), options.end(),
4856 "jurabiborder") != options.end())
4857 argumentOrder = 'j';
4859 // text before the citation
4861 // text after the citation
4863 get_cite_arguments(p, argumentOrder != 'j', before, after);
4865 string const citation = p.verbatim_item();
4866 if (!before.empty() && argumentOrder == '\0') {
4867 warning_message("Assuming argument order "
4868 "of jurabib version 0.6 for\n'"
4869 + command + before + after + '{'
4870 + citation + "}'.\n"
4871 "Add 'jurabiborder' to the jurabib "
4872 "package options if you used an\n"
4873 "earlier jurabib version.");
4875 bool literal = false;
4876 pair<bool, string> aft;
4877 pair<bool, string> bef;
4878 // remove the brackets around after and before
4879 if (!after.empty()) {
4881 after.erase(after.length() - 1, 1);
4882 aft = convert_latexed_command_inset_arg(after);
4883 literal = !aft.first;
4884 after = literal ? subst(after, "\n", " ") : aft.second;
4886 if (!before.empty()) {
4888 before.erase(before.length() - 1, 1);
4889 bef = convert_latexed_command_inset_arg(before);
4890 literal |= !bef.first;
4891 before = literal ? subst(before, "\n", " ") : bef.second;
4892 if (literal && !after.empty())
4893 after = subst(after, "\n", " ");
4895 string lit = literal ? "\"true\"" : "\"false\"";
4896 begin_command_inset(os, "citation", command);
4897 os << "after " << '"' << after << "\"\n"
4898 << "before " << '"' << before << "\"\n"
4899 << "key " << '"' << citation << "\"\n"
4900 << "literal " << lit << "\n";
4902 // Need to set the cite engine if jurabib is loaded by
4903 // the document class directly
4904 if (preamble.citeEngine() == "basic")
4905 preamble.citeEngine("jurabib");
4909 if (t.cs() == "cite"
4910 || t.cs() == "nocite") {
4911 context.check_layout(os);
4912 string after = p.getArg('[', ']');
4913 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4914 bool const literal = !aft.first;
4915 after = literal ? subst(after, "\n", " ") : aft.second;
4916 string lit = literal ? "\"true\"" : "\"false\"";
4917 string key = convert_literate_command_inset_arg(p.verbatim_item());
4918 // store the case that it is "\nocite{*}" to use it later for
4921 begin_command_inset(os, "citation", t.cs());
4922 os << "after " << '"' << after << "\"\n"
4923 << "key " << '"' << key << "\"\n"
4924 << "literal " << lit << "\n";
4926 } else if (t.cs() == "nocite")
4931 if (t.cs() == "index" ||
4932 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4933 context.check_layout(os);
4934 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4935 p.getArg('[', ']') : "";
4936 string const kind = arg.empty() ? "idx" : arg;
4937 parse_index_entry(p, os, context, kind);
4939 preamble.registerAutomaticallyLoadedPackage("splitidx");
4943 if (t.cs() == "nomenclature") {
4944 context.check_layout(os);
4945 begin_command_inset(os, "nomenclature", "nomenclature");
4946 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4947 if (!prefix.empty())
4948 os << "prefix " << '"' << prefix << '"' << "\n";
4949 string symbol = p.verbatim_item();
4950 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4951 bool literal = !sym.first;
4952 string description = p.verbatim_item();
4953 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4954 literal |= !desc.first;
4956 symbol = subst(symbol, "\n", " ");
4957 description = subst(description, "\n", " ");
4959 symbol = sym.second;
4960 description = desc.second;
4962 string lit = literal ? "\"true\"" : "\"false\"";
4963 os << "symbol " << '"' << symbol;
4964 os << "\"\ndescription \""
4965 << description << "\"\n"
4966 << "literal " << lit << "\n";
4968 preamble.registerAutomaticallyLoadedPackage("nomencl");
4972 if (t.cs() == "label") {
4973 context.check_layout(os);
4974 begin_command_inset(os, "label", "label");
4976 << convert_literate_command_inset_arg(p.verbatim_item())
4982 if (t.cs() == "lyxmintcaption") {
4983 string const pos = p.getArg('[', ']');
4985 string const caption =
4986 parse_text_snippet(p, FLAG_ITEM, false,
4988 minted_nonfloat_caption = "[t]" + caption;
4990 // We already got the caption at the bottom,
4991 // so simply skip it.
4992 parse_text_snippet(p, FLAG_ITEM, false, context);
4994 eat_whitespace(p, os, context, true);
4998 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4999 context.check_layout(os);
5000 string commandname = t.cs();
5002 if (p.next_token().asInput() == "*") {
5007 begin_command_inset(os, "index_print", commandname);
5008 string const indexname = p.getArg('[', ']');
5010 if (indexname.empty())
5011 os << "type \"idx\"\n";
5013 os << "type \"" << indexname << "\"\n";
5014 os << "literal \"true\"\n";
5017 skip_spaces_braces(p);
5018 preamble.registerAutomaticallyLoadedPackage("makeidx");
5019 if (preamble.use_indices() == "true")
5020 preamble.registerAutomaticallyLoadedPackage("splitidx");
5024 if (t.cs() == "printnomenclature") {
5026 string width_type = "";
5027 context.check_layout(os);
5028 begin_command_inset(os, "nomencl_print", "printnomenclature");
5029 // case of a custom width
5031 width = p.getArg('[', ']');
5032 width = translate_len(width);
5033 width_type = "custom";
5035 // case of no custom width
5036 // the case of no custom width but the width set
5037 // via \settowidth{\nomlabelwidth}{***} cannot be supported
5038 // because the user could have set anything, not only the width
5039 // of the longest label (which would be width_type = "auto")
5040 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
5041 if (label.empty() && width_type.empty())
5042 width_type = "none";
5043 os << "set_width \"" << width_type << "\"\n";
5044 if (width_type == "custom")
5045 os << "width \"" << width << '\"';
5047 skip_spaces_braces(p);
5048 preamble.registerAutomaticallyLoadedPackage("nomencl");
5052 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
5053 context.check_layout(os);
5054 begin_inset(os, "script ");
5055 os << t.cs().substr(4) << '\n';
5056 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
5057 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5059 if (t.cs() == "textsubscript")
5060 preamble.registerAutomaticallyLoadedPackage("subscript");
5064 if ((where = is_known(t.cs(), known_quotes))) {
5065 context.check_layout(os);
5066 begin_inset(os, "Quotes ");
5067 string quotetype = known_coded_quotes[where - known_quotes];
5068 // try to make a smart guess about the side
5069 Token const prev = p.prev_token();
5070 bool const opening = (prev.cat() != catSpace && prev.character() != 0
5071 && prev.character() != '\n' && prev.character() != '~');
5072 quotetype = guessQuoteStyle(quotetype, opening);
5075 // LyX adds {} after the quote, so we have to eat
5076 // spaces here if there are any before a possible
5078 eat_whitespace(p, os, context, false);
5083 if ((where = is_known(t.cs(), known_sizes)) &&
5084 context.new_layout_allowed) {
5085 context.check_layout(os);
5086 TeXFont const oldFont = context.font;
5087 context.font.size = known_coded_sizes[where - known_sizes];
5088 output_font_change(os, oldFont, context.font);
5089 eat_whitespace(p, os, context, false);
5093 if ((where = is_known(t.cs(), known_font_families)) &&
5094 context.new_layout_allowed) {
5095 context.check_layout(os);
5096 TeXFont const oldFont = context.font;
5097 context.font.family =
5098 known_coded_font_families[where - known_font_families];
5099 output_font_change(os, oldFont, context.font);
5100 eat_whitespace(p, os, context, false);
5104 if ((where = is_known(t.cs(), known_font_series)) &&
5105 context.new_layout_allowed) {
5106 context.check_layout(os);
5107 TeXFont const oldFont = context.font;
5108 context.font.series =
5109 known_coded_font_series[where - known_font_series];
5110 output_font_change(os, oldFont, context.font);
5111 eat_whitespace(p, os, context, false);
5115 if ((where = is_known(t.cs(), known_font_shapes)) &&
5116 context.new_layout_allowed) {
5117 context.check_layout(os);
5118 TeXFont const oldFont = context.font;
5119 context.font.shape =
5120 known_coded_font_shapes[where - known_font_shapes];
5121 output_font_change(os, oldFont, context.font);
5122 eat_whitespace(p, os, context, false);
5125 if ((where = is_known(t.cs(), known_old_font_families)) &&
5126 context.new_layout_allowed) {
5127 context.check_layout(os);
5128 TeXFont const oldFont = context.font;
5129 context.font.init();
5130 context.font.size = oldFont.size;
5131 context.font.family =
5132 known_coded_font_families[where - known_old_font_families];
5133 output_font_change(os, oldFont, context.font);
5134 eat_whitespace(p, os, context, false);
5138 if ((where = is_known(t.cs(), known_old_font_series)) &&
5139 context.new_layout_allowed) {
5140 context.check_layout(os);
5141 TeXFont const oldFont = context.font;
5142 context.font.init();
5143 context.font.size = oldFont.size;
5144 context.font.series =
5145 known_coded_font_series[where - known_old_font_series];
5146 output_font_change(os, oldFont, context.font);
5147 eat_whitespace(p, os, context, false);
5151 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
5152 context.new_layout_allowed) {
5153 context.check_layout(os);
5154 TeXFont const oldFont = context.font;
5155 context.font.init();
5156 context.font.size = oldFont.size;
5157 context.font.shape =
5158 known_coded_font_shapes[where - known_old_font_shapes];
5159 output_font_change(os, oldFont, context.font);
5160 eat_whitespace(p, os, context, false);
5164 if (t.cs() == "selectlanguage") {
5165 context.check_layout(os);
5166 // save the language for the case that a
5167 // \foreignlanguage is used
5168 context.font.language = babel2lyx(p.verbatim_item());
5169 os << "\n\\lang " << context.font.language << "\n";
5173 if (t.cs() == "foreignlanguage") {
5174 string const lang = babel2lyx(p.verbatim_item());
5175 parse_text_attributes(p, os, FLAG_ITEM, outer,
5177 context.font.language, lang);
5181 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
5182 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
5183 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
5185 // We have to output the whole command if it has an option
5186 // because LyX doesn't support this yet, see bug #8214,
5187 // only if there is a single option specifying a variant, we can handle it.
5189 string langopts = p.getOpt();
5190 // check if the option contains a variant, if yes, extract it
5191 string::size_type pos_var = langopts.find("variant");
5192 string::size_type i = langopts.find(',');
5193 string::size_type k = langopts.find('=', pos_var);
5194 if (pos_var != string::npos && i == string::npos) {
5196 variant = langopts.substr(k + 1, langopts.length() - k - 2);
5197 lang = preamble.polyglossia2lyx(variant);
5198 parse_text_attributes(p, os, FLAG_ITEM, outer,
5200 context.font.language, lang);
5202 output_ert_inset(os, t.asInput() + langopts, context);
5204 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
5205 parse_text_attributes(p, os, FLAG_ITEM, outer,
5207 context.font.language, lang);
5212 if (t.cs() == "inputencoding") {
5213 // nothing to write here
5214 string const enc = subst(p.verbatim_item(), "\n", " ");
5215 p.setEncoding(enc, Encoding::inputenc);
5219 if (is_known(t.cs(), known_special_chars) ||
5220 (t.cs() == "protect" &&
5221 p.next_token().cat() == catEscape &&
5222 is_known(p.next_token().cs(), known_special_protect_chars))) {
5223 // LyX sometimes puts a \protect in front, so we have to ignore it
5225 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5226 known_special_chars);
5227 context.check_layout(os);
5228 os << known_coded_special_chars[where - known_special_chars];
5229 skip_spaces_braces(p);
5233 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5234 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5235 p.next_next_token().asInput() == "-") ||
5236 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5237 // LyX sometimes puts a \protect in front, so we have to ignore it
5238 if (t.cs() == "protect")
5240 context.check_layout(os);
5241 if (t.cs() == "nobreakdash")
5242 os << "\\SpecialChar nobreakdash\n";
5244 os << "\\SpecialChar endofsentence\n";
5249 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5250 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5251 || t.cs() == "%" || t.cs() == "-") {
5252 context.check_layout(os);
5254 os << "\\SpecialChar softhyphen\n";
5260 if (t.cs() == "char") {
5261 context.check_layout(os);
5262 if (p.next_token().character() == '`') {
5264 if (p.next_token().cs() == "\"") {
5269 output_ert_inset(os, "\\char`", context);
5272 output_ert_inset(os, "\\char", context);
5277 if (t.cs() == "verb") {
5278 context.check_layout(os);
5279 // set catcodes to verbatim early, just in case.
5280 p.setCatcodes(VERBATIM_CATCODES);
5281 string delim = p.get_token().asInput();
5282 Parser::Arg arg = p.verbatimStuff(delim);
5284 output_ert_inset(os, "\\verb" + delim
5285 + arg.second + delim, context);
5287 warning_message("invalid \\verb command. Skipping");
5291 // Problem: \= creates a tabstop inside the tabbing environment
5292 // and else an accent. In the latter case we really would want
5293 // \={o} instead of \= o.
5294 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5295 output_ert_inset(os, t.asInput(), context);
5299 if (t.cs() == "\\") {
5300 context.check_layout(os);
5302 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5303 else if (p.next_token().asInput() == "*") {
5305 // getOpt() eats the following space if there
5306 // is no optional argument, but that is OK
5307 // here since it has no effect in the output.
5308 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5311 begin_inset(os, "Newline newline");
5317 if (t.cs() == "newline" ||
5318 (t.cs() == "linebreak" && !p.hasOpt())) {
5319 context.check_layout(os);
5320 begin_inset(os, "Newline ");
5323 skip_spaces_braces(p);
5327 if (t.cs() == "endgraf" && context.in_table_cell) {
5328 context.new_paragraph(os);
5329 context.check_layout(os);
5330 skip_spaces_braces(p);
5334 if (t.cs() == "input" || t.cs() == "include"
5335 || t.cs() == "verbatiminput"
5336 || t.cs() == "lstinputlisting"
5337 || t.cs() == "inputminted") {
5338 string name = t.cs();
5339 if (name == "verbatiminput"
5340 && p.next_token().asInput() == "*")
5341 name += p.get_token().asInput();
5342 context.check_layout(os);
5344 bool literal = false;
5345 if (name == "lstinputlisting" && p.hasOpt()) {
5346 lstparams = p.getArg('[', ']');
5347 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5348 literal = !oa.first;
5350 lstparams = subst(lstparams, "\n", " ");
5352 lstparams = oa.second;
5353 } else if (name == "inputminted") {
5354 name = "lstinputlisting";
5355 string const lang = p.getArg('{', '}');
5356 if (lang != "tex") {
5357 string cmd = "\\inputminted{" + lang + "}{";
5358 cmd += p.getArg('{', '}') + "}";
5359 output_ert_inset(os, cmd, context);
5362 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5363 minted_nonfloat_caption.erase(0,3);
5364 // extract label and caption from the already produced LyX code
5365 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5366 string const caption = nfc.front();
5368 vector<string>::iterator it =
5369 find(nfc.begin(), nfc.end(), "LatexCommand label");
5370 if (it != nfc.end()) {
5372 if (it != nfc.end())
5374 label = support::split(label, '"');
5377 minted_nonfloat_caption.clear();
5378 lstparams = "caption=" + caption;
5380 lstparams += ",label=" + label;
5381 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5382 literal = !oa.first;
5384 lstparams = subst(lstparams, "\n", " ");
5386 lstparams = oa.second;
5389 string lit = literal ? "\"true\"" : "\"false\"";
5390 string filename(normalize_filename(p.getArg('{', '}')));
5391 string const path = getMasterFilePath(true);
5392 // We want to preserve relative / absolute filenames,
5393 // therefore path is only used for testing
5394 if ((t.cs() == "include" || t.cs() == "input") &&
5395 !makeAbsPath(filename, path).exists()) {
5396 // The file extension is probably missing.
5397 // Now try to find it out.
5398 string const tex_name =
5399 find_file(filename, path,
5400 known_tex_extensions);
5401 if (!tex_name.empty())
5402 filename = tex_name;
5404 bool external = false;
5406 if (makeAbsPath(filename, path).exists()) {
5407 string const abstexname =
5408 makeAbsPath(filename, path).absFileName();
5409 string const absfigname =
5410 changeExtension(abstexname, ".fig");
5411 fix_child_filename(filename);
5412 string const lyxname = changeExtension(filename,
5413 roundtripMode() ? ".lyx.lyx" : ".lyx");
5414 string const abslyxname = makeAbsPath(
5415 lyxname, getParentFilePath(false)).absFileName();
5417 if (!skipChildren())
5418 external = FileName(absfigname).exists();
5419 if (t.cs() == "input" && !skipChildren()) {
5420 string const ext = getExtension(abstexname);
5422 // Combined PS/LaTeX:
5423 // x.eps, x.pstex_t (old xfig)
5424 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5425 FileName const absepsname(
5426 changeExtension(abstexname, ".eps"));
5427 FileName const abspstexname(
5428 changeExtension(abstexname, ".pstex"));
5429 bool const xfigeps =
5430 (absepsname.exists() ||
5431 abspstexname.exists()) &&
5434 // Combined PDF/LaTeX:
5435 // x.pdf, x.pdftex_t (old xfig)
5436 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5437 FileName const abspdfname(
5438 changeExtension(abstexname, ".pdf"));
5439 bool const xfigpdf =
5440 abspdfname.exists() &&
5441 (ext == "pdftex_t" || ext == "pdf_t");
5445 // Combined PS/PDF/LaTeX:
5446 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5447 string const absbase2(
5448 removeExtension(abstexname) + "_pspdftex");
5449 FileName const abseps2name(
5450 addExtension(absbase2, ".eps"));
5451 FileName const abspdf2name(
5452 addExtension(absbase2, ".pdf"));
5453 bool const xfigboth =
5454 abspdf2name.exists() &&
5455 abseps2name.exists() && ext == "pspdftex";
5457 xfig = xfigpdf || xfigeps || xfigboth;
5458 external = external && xfig;
5461 outname = changeExtension(filename, ".fig");
5462 FileName abssrc(changeExtension(abstexname, ".fig"));
5463 copy_file(abssrc, outname);
5465 // Don't try to convert, the result
5466 // would be full of ERT.
5468 FileName abssrc(abstexname);
5469 copy_file(abssrc, outname);
5470 } else if (t.cs() != "verbatiminput" &&
5472 tex2lyx(abstexname, FileName(abslyxname),
5475 // no need to call copy_file
5476 // tex2lyx creates the file
5479 FileName abssrc(abstexname);
5480 copy_file(abssrc, outname);
5483 warning_message("Could not find included file '" + filename + "'.");
5487 begin_inset(os, "External\n");
5488 os << "\ttemplate XFig\n"
5489 << "\tfilename " << outname << '\n';
5490 registerExternalTemplatePackages("XFig");
5492 begin_command_inset(os, "include", name);
5493 outname = subst(outname, "\"", "\\\"");
5494 os << "preview false\n"
5495 "filename \"" << outname << "\"\n";
5496 if (!lstparams.empty())
5497 os << "lstparams \"" << lstparams << "\"\n";
5498 os << "literal " << lit << "\n";
5499 if (t.cs() == "verbatiminput")
5500 preamble.registerAutomaticallyLoadedPackage("verbatim");
5506 if (t.cs() == "bibliographystyle") {
5507 // store new bibliographystyle
5508 bibliographystyle = p.verbatim_item();
5509 // If any other command than \bibliography, \addcontentsline
5510 // and \nocite{*} follows, we need to output the style
5511 // (because it might be used by that command).
5512 // Otherwise, it will automatically be output by LyX.
5515 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5516 if (t2.cat() == catBegin)
5518 if (t2.cat() != catEscape)
5520 if (t2.cs() == "nocite") {
5521 if (p.getArg('{', '}') == "*")
5523 } else if (t2.cs() == "bibliography")
5525 else if (t2.cs() == "phantomsection") {
5529 else if (t2.cs() == "addcontentsline") {
5530 // get the 3 arguments of \addcontentsline
5533 contentslineContent = p.getArg('{', '}');
5534 // if the last argument is not \refname we must output
5535 if (contentslineContent == "\\refname")
5542 output_ert_inset(os,
5543 "\\bibliographystyle{" + bibliographystyle + '}',
5549 if (t.cs() == "phantomsection") {
5550 // we only support this if it occurs between
5551 // \bibliographystyle and \bibliography
5552 if (bibliographystyle.empty())
5553 output_ert_inset(os, "\\phantomsection", context);
5557 if (t.cs() == "addcontentsline") {
5558 context.check_layout(os);
5559 // get the 3 arguments of \addcontentsline
5560 string const one = p.getArg('{', '}');
5561 string const two = p.getArg('{', '}');
5562 string const three = p.getArg('{', '}');
5563 // only if it is a \refname, we support if for the bibtex inset
5564 if (contentslineContent != "\\refname") {
5565 output_ert_inset(os,
5566 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5572 if (t.cs() == "tikzset") {
5573 context.check_layout(os);
5574 // we catch the argument and output it verbatim in an ERT
5575 string const arg = p.getArg('{', '}');
5576 output_ert_inset(os,
5577 "\\tikzset{" + arg + "}",
5582 else if (t.cs() == "bibliography") {
5583 context.check_layout(os);
5585 begin_command_inset(os, "bibtex", "bibtex");
5586 if (!btprint.empty()) {
5587 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5588 // clear the string because the next BibTeX inset can be without the
5589 // \nocite{*} option
5592 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5593 // Do we have addcontentsline?
5594 if (contentslineContent == "\\refname") {
5595 BibOpts = "bibtotoc";
5596 // clear string because next BibTeX inset can be without addcontentsline
5597 contentslineContent.clear();
5599 // Do we have a bibliographystyle set?
5600 if (!bibliographystyle.empty()) {
5601 if (BibOpts.empty())
5602 BibOpts = normalize_filename(bibliographystyle);
5604 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5605 // clear it because each bibtex entry has its style
5606 // and we need an empty string to handle \phantomsection
5607 bibliographystyle.clear();
5609 os << "options " << '"' << BibOpts << '"' << "\n";
5610 if (p.getEncoding() != preamble.docencoding) {
5611 Encoding const * const enc = encodings.fromIconvName(
5612 p.getEncoding(), Encoding::inputenc, true);
5614 warning_message("Unknown bib encoding " + p.getEncoding()
5617 os << "encoding " << '"' << enc->name() << '"' << "\n";
5623 if (t.cs() == "printbibliography") {
5624 context.check_layout(os);
5626 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5627 vector<string> opts = getVectorFromString(bbloptions);
5628 vector<string>::iterator it =
5629 find(opts.begin(), opts.end(), "heading=bibintoc");
5630 if (it != opts.end()) {
5632 BibOpts = "bibtotoc";
5634 bbloptions = getStringFromVector(opts);
5635 begin_command_inset(os, "bibtex", "bibtex");
5636 if (!btprint.empty()) {
5637 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5638 // clear the string because the next BibTeX inset can be without the
5639 // \nocite{*} option
5643 for (auto const & bf : preamble.biblatex_bibliographies) {
5644 if (!bibfiles.empty())
5646 bibfiles += normalize_filename(bf);
5648 if (!bibfiles.empty())
5649 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5650 // Do we have addcontentsline?
5651 if (contentslineContent == "\\refname") {
5652 BibOpts = "bibtotoc";
5653 // clear string because next BibTeX inset can be without addcontentsline
5654 contentslineContent.clear();
5656 os << "options " << '"' << BibOpts << '"' << "\n";
5657 if (!bbloptions.empty())
5658 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5659 if (!preamble.bibencoding.empty()) {
5660 Encoding const * const enc = encodings.fromLaTeXName(
5661 preamble.bibencoding, Encoding::inputenc, true);
5663 warning_message("Unknown bib encoding " + preamble.bibencoding
5666 os << "encoding " << '"' << enc->name() << '"' << "\n";
5669 for (auto const & bf : preamble.biblatex_encodings) {
5670 if (!bibfileencs.empty())
5671 bibfileencs += "\t";
5674 if (!bibfileencs.empty())
5675 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5677 need_commentbib = false;
5681 if (t.cs() == "bibbysection") {
5682 context.check_layout(os);
5684 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5685 vector<string> opts = getVectorFromString(bbloptions);
5686 vector<string>::iterator it =
5687 find(opts.begin(), opts.end(), "heading=bibintoc");
5688 if (it != opts.end()) {
5690 BibOpts = "bibtotoc";
5692 bbloptions = getStringFromVector(opts);
5693 begin_command_inset(os, "bibtex", "bibtex");
5694 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5696 for (auto const & bf : preamble.biblatex_bibliographies) {
5697 if (!bibfiles.empty())
5699 bibfiles += normalize_filename(bf);
5701 if (!bibfiles.empty())
5702 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5703 os << "options " << '"' << BibOpts << '"' << "\n";
5704 if (!bbloptions.empty())
5705 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5707 need_commentbib = false;
5711 if (t.cs() == "parbox") {
5712 // Test whether this is an outer box of a shaded box
5714 // swallow arguments
5715 while (p.hasOpt()) {
5717 p.skip_spaces(true);
5720 p.skip_spaces(true);
5722 if (p.next_token().cat() == catBegin)
5724 p.skip_spaces(true);
5725 Token to = p.get_token();
5726 bool shaded = false;
5727 if (to.asInput() == "\\begin") {
5728 p.skip_spaces(true);
5729 if (p.getArg('{', '}') == "shaded")
5734 parse_outer_box(p, os, FLAG_ITEM, outer,
5735 context, "parbox", "shaded");
5737 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5738 "", "", t.cs(), "", "");
5742 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5743 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5744 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5745 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5749 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5750 string backgroundcolor;
5751 preamble.registerAutomaticallyLoadedPackage("xcolor");
5752 if (t.cs() == "fcolorbox") {
5753 string const framecolor = p.getArg('{', '}');
5754 backgroundcolor = p.getArg('{', '}');
5755 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5757 backgroundcolor = p.getArg('{', '}');
5758 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5763 // FIXME: due to the compiler limit of "if" nestings
5764 // the code for the alignment was put here
5765 // put them in their own if if this is fixed
5766 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5767 || t.cs() == "shadowsize") {
5768 if (t.cs() == "fboxrule")
5770 if (t.cs() == "fboxsep")
5772 if (t.cs() == "shadowsize")
5774 p.skip_spaces(true);
5775 while (p.good() && p.next_token().cat() != catSpace
5776 && p.next_token().cat() != catNewline
5777 && p.next_token().cat() != catEscape) {
5778 if (t.cs() == "fboxrule")
5779 fboxrule = fboxrule + p.get_token().asInput();
5780 if (t.cs() == "fboxsep")
5781 fboxsep = fboxsep + p.get_token().asInput();
5782 if (t.cs() == "shadowsize")
5783 shadow_size = shadow_size + p.get_token().asInput();
5788 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5789 if (context.in_table_cell) {
5790 if (t.cs() == "raggedleft")
5791 context.cell_align = 'r';
5792 else if (t.cs() == "centering")
5793 context.cell_align = 'c';
5794 else if (t.cs() == "raggedright")
5795 context.cell_align = 'l';
5796 p.skip_spaces(true);
5798 output_ert_inset(os, t.asInput(), context);
5803 //\framebox() is part of the picture environment and different from \framebox{}
5804 //\framebox{} will be parsed by parse_outer_box
5805 if (t.cs() == "framebox") {
5806 if (p.next_token().character() == '(') {
5807 //the syntax is: \framebox(x,y)[position]{content}
5808 string arg = t.asInput();
5809 arg += p.getFullParentheseArg();
5810 arg += p.getFullOpt();
5811 eat_whitespace(p, os, context, false);
5812 output_ert_inset(os, arg + '{', context);
5813 parse_text(p, os, FLAG_ITEM, outer, context);
5814 output_ert_inset(os, "}", context);
5816 //the syntax is: \framebox[width][position]{content}
5817 string special = p.getFullOpt();
5818 special += p.getOpt();
5819 parse_outer_box(p, os, FLAG_ITEM, outer,
5820 context, t.cs(), special);
5825 //\makebox() is part of the picture environment and different from \makebox{}
5826 //\makebox{} will be parsed by parse_box
5827 if (t.cs() == "makebox") {
5828 if (p.next_token().character() == '(') {
5829 //the syntax is: \makebox(x,y)[position]{content}
5830 string arg = t.asInput();
5831 arg += p.getFullParentheseArg();
5832 arg += p.getFullOpt();
5833 eat_whitespace(p, os, context, false);
5834 output_ert_inset(os, arg + '{', context);
5835 parse_text(p, os, FLAG_ITEM, outer, context);
5836 output_ert_inset(os, "}", context);
5838 //the syntax is: \makebox[width][position]{content}
5839 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5840 "", "", t.cs(), "", "");
5844 if (t.cs() == "smallskip" ||
5845 t.cs() == "medskip" ||
5846 t.cs() == "bigskip" ||
5847 t.cs() == "vfill") {
5848 context.check_layout(os);
5849 begin_inset(os, "VSpace ");
5852 skip_spaces_braces(p);
5856 if ((where = is_known(t.cs(), known_spaces))
5857 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5858 context.check_layout(os);
5859 begin_inset(os, "space ");
5860 os << '\\' << known_coded_spaces[where - known_spaces]
5863 // LaTeX swallows whitespace after all spaces except
5864 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5865 // We have to do that here, too, because LyX
5866 // adds "{}" which would make the spaces significant.
5867 if (!contains(",>!;:", t.cs()))
5868 eat_whitespace(p, os, context, false);
5869 // LyX adds "{}" after all spaces except "\\ " and
5870 // "\\,", so we have to remove "{}".
5871 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5872 // remove the braces after "\\,", too.
5878 if (t.cs() == "newpage" ||
5879 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5880 t.cs() == "clearpage" ||
5881 t.cs() == "cleardoublepage" ||
5882 t.cs() == "nopagebreak") {
5883 context.check_layout(os);
5884 begin_inset(os, "Newpage ");
5887 skip_spaces_braces(p);
5891 if (t.cs() == "DeclareRobustCommand" ||
5892 t.cs() == "DeclareRobustCommandx" ||
5893 t.cs() == "newcommand" ||
5894 t.cs() == "newcommandx" ||
5895 t.cs() == "providecommand" ||
5896 t.cs() == "providecommandx" ||
5897 t.cs() == "renewcommand" ||
5898 t.cs() == "renewcommandx") {
5899 // DeclareRobustCommand, DeclareRobustCommandx,
5900 // providecommand and providecommandx could be handled
5901 // by parse_command(), but we need to call
5902 // add_known_command() here.
5903 string name = t.asInput();
5904 if (p.next_token().asInput() == "*") {
5905 // Starred form. Eat '*'
5909 string const command = p.verbatim_item();
5910 string const opt1 = p.getFullOpt();
5911 string const opt2 = p.getFullOpt();
5912 add_known_command(command, opt1, !opt2.empty());
5913 string const ert = name + '{' + command + '}' +
5915 '{' + p.verbatim_item() + '}';
5917 if (t.cs() == "DeclareRobustCommand" ||
5918 t.cs() == "DeclareRobustCommandx" ||
5919 t.cs() == "providecommand" ||
5920 t.cs() == "providecommandx" ||
5921 name[name.length()-1] == '*')
5922 output_ert_inset(os, ert, context);
5924 context.check_layout(os);
5925 begin_inset(os, "FormulaMacro");
5932 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5933 // let could be handled by parse_command(),
5934 // but we need to call add_known_command() here.
5935 string ert = t.asInput();
5938 if (p.next_token().cat() == catBegin) {
5939 name = p.verbatim_item();
5940 ert += '{' + name + '}';
5942 name = p.verbatim_item();
5947 if (p.next_token().cat() == catBegin) {
5948 command = p.verbatim_item();
5949 ert += '{' + command + '}';
5951 command = p.verbatim_item();
5954 // If command is known, make name known too, to parse
5955 // its arguments correctly. For this reason we also
5956 // have commands in syntax.default that are hardcoded.
5957 CommandMap::iterator it = known_commands.find(command);
5958 if (it != known_commands.end())
5959 known_commands[t.asInput()] = it->second;
5960 output_ert_inset(os, ert, context);
5964 if (t.cs() == "hspace" || t.cs() == "vspace") {
5967 string name = t.asInput();
5968 string const length = p.verbatim_item();
5971 bool valid = splitLatexLength(length, valstring, unit);
5972 bool known_hspace = false;
5973 bool known_vspace = false;
5974 bool known_unit = false;
5977 istringstream iss(valstring);
5980 if (t.cs()[0] == 'h') {
5981 if (unit == "\\fill") {
5986 known_hspace = true;
5989 if (unit == "\\smallskipamount") {
5991 known_vspace = true;
5992 } else if (unit == "\\medskipamount") {
5994 known_vspace = true;
5995 } else if (unit == "\\bigskipamount") {
5997 known_vspace = true;
5998 } else if (length == "\\baselineskip") {
6000 known_vspace = true;
6001 } else if (unit == "\\fill") {
6003 known_vspace = true;
6007 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
6009 known_vspace = true;
6011 if (!known_hspace && !known_vspace) {
6012 switch (unitFromString(unit)) {
6028 //unitFromString(unit) fails for relative units like Length::PCW
6029 // therefore handle them separately
6030 if (unit == "\\paperwidth" || unit == "\\columnwidth"
6031 || unit == "\\textwidth" || unit == "\\linewidth"
6032 || unit == "\\textheight" || unit == "\\paperheight"
6033 || unit == "\\baselineskip")
6041 // check for glue lengths
6042 bool is_gluelength = false;
6043 string gluelength = length;
6044 string::size_type i = length.find(" minus");
6045 if (i == string::npos) {
6046 i = length.find(" plus");
6047 if (i != string::npos)
6048 is_gluelength = true;
6050 is_gluelength = true;
6051 // if yes transform "9xx minus 8yy plus 7zz"
6053 if (is_gluelength) {
6054 i = gluelength.find(" minus");
6055 if (i != string::npos)
6056 gluelength.replace(i, 7, "-");
6057 i = gluelength.find(" plus");
6058 if (i != string::npos)
6059 gluelength.replace(i, 6, "+");
6062 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
6063 // Literal horizontal length or known variable
6064 context.check_layout(os);
6065 begin_inset(os, "space ");
6073 if (known_unit && !known_hspace)
6074 os << "\n\\length " << translate_len(length);
6076 os << "\n\\length " << gluelength;
6078 } else if (known_unit || known_vspace || is_gluelength) {
6079 // Literal vertical length or known variable
6080 context.check_layout(os);
6081 begin_inset(os, "VSpace ");
6084 if (known_unit && !known_vspace)
6085 os << translate_len(length);
6092 // LyX can't handle other length variables in Inset VSpace/space
6097 output_ert_inset(os, name + '{' + unit + '}', context);
6098 else if (value == -1.0)
6099 output_ert_inset(os, name + "{-" + unit + '}', context);
6101 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
6103 output_ert_inset(os, name + '{' + length + '}', context);
6108 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
6109 // might be one or several options or a star.
6110 // The single '=' is meant here.
6111 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
6115 context.check_layout(os);
6116 // store the latexparam here. This is eaten in parse_text_in_inset
6117 context.latexparam = newinsetlayout->latexparam();
6118 docstring name = newinsetlayout->name();
6119 bool const caption = name.find(from_ascii("Caption:")) == 0;
6121 // Already done for floating minted listings.
6122 if (minted_float.empty()) {
6123 begin_inset(os, "Caption ");
6124 os << to_utf8(name.substr(8)) << '\n';
6127 // FIXME: what do we do if the prefix is not Flex: ?
6128 if (prefixIs(name, from_ascii("Flex:")))
6130 begin_inset(os, "Flex ");
6131 os << to_utf8(name) << '\n'
6132 << "status collapsed\n";
6134 if (!minted_float.empty()) {
6135 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6136 } else if (newinsetlayout->isPassThru()) {
6137 // set catcodes to verbatim early, just in case.
6138 p.setCatcodes(VERBATIM_CATCODES);
6139 string delim = p.get_token().asInput();
6141 warning_message("bad delimiter for command " + t.asInput());
6142 //FIXME: handle error condition
6143 string const arg = p.verbatimStuff("}").second;
6144 Context newcontext(true, context.textclass);
6145 if (newinsetlayout->forcePlainLayout())
6146 newcontext.layout = &context.textclass.plainLayout();
6147 output_ert(os, arg, newcontext);
6149 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6150 context.latexparam.clear();
6153 // Minted caption insets are not closed here because
6154 // we collect everything into the caption.
6155 if (minted_float.empty())
6160 // The single '=' is meant here.
6161 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
6165 context.check_layout(os);
6166 docstring name = newinsetlayout->name();
6167 bool const caption = name.find(from_ascii("Caption:")) == 0;
6169 // Already done for floating minted listings.
6170 if (minted_float.empty()) {
6171 begin_inset(os, "Caption ");
6172 os << to_utf8(name.substr(8)) << '\n';
6175 // FIXME: what do we do if the prefix is not Flex: ?
6176 if (prefixIs(name, from_ascii("Flex:")))
6178 begin_inset(os, "Flex ");
6179 os << to_utf8(name) << '\n'
6180 << "status collapsed\n";
6182 if (!minted_float.empty()) {
6183 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6184 } else if (newinsetlayout->isPassThru()) {
6185 // set catcodes to verbatim early, just in case.
6186 p.setCatcodes(VERBATIM_CATCODES);
6187 string delim = p.get_token().asInput();
6189 warning_message("bad delimiter for command " + t.asInput());
6190 //FIXME: handle error condition
6191 string const arg = p.verbatimStuff("}").second;
6192 Context newcontext(true, context.textclass);
6193 if (newinsetlayout->forcePlainLayout())
6194 newcontext.layout = &context.textclass.plainLayout();
6195 output_ert(os, arg, newcontext);
6197 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6200 // Minted caption insets are not closed here because
6201 // we collect everything into the caption.
6202 if (minted_float.empty())
6207 if (t.cs() == "includepdf") {
6209 string const arg = p.getArg('[', ']');
6210 map<string, string> opts;
6211 vector<string> keys;
6212 split_map(arg, opts, keys);
6213 string name = normalize_filename(p.verbatim_item());
6214 string const path = getMasterFilePath(true);
6215 // We want to preserve relative / absolute filenames,
6216 // therefore path is only used for testing
6217 if (!makeAbsPath(name, path).exists()) {
6218 // The file extension is probably missing.
6219 // Now try to find it out.
6220 char const * const pdfpages_format[] = {"pdf", 0};
6221 string const pdftex_name =
6222 find_file(name, path, pdfpages_format);
6223 if (!pdftex_name.empty()) {
6228 FileName const absname = makeAbsPath(name, path);
6229 if (absname.exists())
6231 fix_child_filename(name);
6232 copy_file(absname, name);
6234 warning_message("Could not find file '" + name + "'.");
6236 context.check_layout(os);
6237 begin_inset(os, "External\n\ttemplate ");
6238 os << "PDFPages\n\tfilename "
6240 // parse the options
6241 if (opts.find("pages") != opts.end())
6242 os << "\textra LaTeX \"pages="
6243 << opts["pages"] << "\"\n";
6244 if (opts.find("angle") != opts.end())
6245 os << "\trotateAngle "
6246 << opts["angle"] << '\n';
6247 if (opts.find("origin") != opts.end()) {
6249 string const opt = opts["origin"];
6250 if (opt == "tl") ss << "topleft";
6251 if (opt == "bl") ss << "bottomleft";
6252 if (opt == "Bl") ss << "baselineleft";
6253 if (opt == "c") ss << "center";
6254 if (opt == "tc") ss << "topcenter";
6255 if (opt == "bc") ss << "bottomcenter";
6256 if (opt == "Bc") ss << "baselinecenter";
6257 if (opt == "tr") ss << "topright";
6258 if (opt == "br") ss << "bottomright";
6259 if (opt == "Br") ss << "baselineright";
6260 if (!ss.str().empty())
6261 os << "\trotateOrigin " << ss.str() << '\n';
6263 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
6265 if (opts.find("width") != opts.end())
6267 << translate_len(opts["width"]) << '\n';
6268 if (opts.find("height") != opts.end())
6270 << translate_len(opts["height"]) << '\n';
6271 if (opts.find("keepaspectratio") != opts.end())
6272 os << "\tkeepAspectRatio\n";
6274 context.check_layout(os);
6275 registerExternalTemplatePackages("PDFPages");
6279 if (t.cs() == "loadgame") {
6281 string name = normalize_filename(p.verbatim_item());
6282 string const path = getMasterFilePath(true);
6283 // We want to preserve relative / absolute filenames,
6284 // therefore path is only used for testing
6285 if (!makeAbsPath(name, path).exists()) {
6286 // The file extension is probably missing.
6287 // Now try to find it out.
6288 char const * const lyxskak_format[] = {"fen", 0};
6289 string const lyxskak_name =
6290 find_file(name, path, lyxskak_format);
6291 if (!lyxskak_name.empty())
6292 name = lyxskak_name;
6294 FileName const absname = makeAbsPath(name, path);
6295 if (absname.exists())
6297 fix_child_filename(name);
6298 copy_file(absname, name);
6300 warning_message("Could not find file '" + name + "'.");
6301 context.check_layout(os);
6302 begin_inset(os, "External\n\ttemplate ");
6303 os << "ChessDiagram\n\tfilename "
6306 context.check_layout(os);
6307 // after a \loadgame follows a \showboard
6308 if (p.get_token().asInput() == "showboard")
6310 registerExternalTemplatePackages("ChessDiagram");
6314 // try to see whether the string is in unicodesymbols
6315 // Only use text mode commands, since we are in text mode here,
6316 // and math commands may be invalid (bug 6797)
6317 string name = t.asInput();
6318 // handle the dingbats, cyrillic and greek
6319 if (name == "\\textcyr")
6320 name = "\\textcyrillic";
6321 if (name == "\\ding" || name == "\\textcyrillic" ||
6322 (name == "\\textgreek" && !preamble.usePolyglossia()))
6323 name = name + '{' + p.getArg('{', '}') + '}';
6324 // handle the ifsym characters
6325 else if (name == "\\textifsymbol") {
6326 string const optif = p.getFullOpt();
6327 string const argif = p.getArg('{', '}');
6328 name = name + optif + '{' + argif + '}';
6330 // handle the \ascii characters
6331 // the case of \ascii within braces, as LyX outputs it, is already
6332 // handled for t.cat() == catBegin
6333 else if (name == "\\ascii") {
6334 // the code is "\asci\xxx"
6335 name = "{" + name + p.get_token().asInput() + "}";
6338 // handle some TIPA special characters
6339 else if (preamble.isPackageUsed("tipa")) {
6340 if (name == "\\s") {
6341 // fromLaTeXCommand() does not yet
6342 // recognize tipa short cuts
6343 name = "\\textsyllabic";
6344 } else if (name == "\\=" &&
6345 p.next_token().asInput() == "*") {
6346 // fromLaTeXCommand() does not yet
6347 // recognize tipa short cuts
6349 name = "\\textsubbar";
6350 } else if (name == "\\textdoublevertline") {
6351 // FIXME: This is not correct,
6352 // \textvertline is higher than \textbardbl
6353 name = "\\textbardbl";
6355 } else if (name == "\\!" ) {
6356 if (p.next_token().asInput() == "b") {
6357 p.get_token(); // eat 'b'
6360 } else if (p.next_token().asInput() == "d") {
6364 } else if (p.next_token().asInput() == "g") {
6368 } else if (p.next_token().asInput() == "G") {
6370 name = "\\texthtscg";
6372 } else if (p.next_token().asInput() == "j") {
6374 name = "\\texthtbardotlessj";
6376 } else if (p.next_token().asInput() == "o") {
6378 name = "\\textbullseye";
6381 } else if (name == "\\*" ) {
6382 if (p.next_token().asInput() == "k") {
6384 name = "\\textturnk";
6386 } else if (p.next_token().asInput() == "r") {
6387 p.get_token(); // eat 'b'
6388 name = "\\textturnr";
6390 } else if (p.next_token().asInput() == "t") {
6392 name = "\\textturnt";
6394 } else if (p.next_token().asInput() == "w") {
6396 name = "\\textturnw";
6401 if ((name.size() == 2 &&
6402 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6403 p.next_token().asInput() != "*") ||
6404 is_known(name.substr(1), known_tipa_marks)) {
6405 // name is a command that corresponds to a
6406 // combining character in unicodesymbols.
6407 // Append the argument, fromLaTeXCommand()
6408 // will either convert it to a single
6409 // character or a combining sequence.
6410 name += '{' + p.verbatim_item() + '}';
6412 // now get the character from unicodesymbols
6416 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6417 Encodings::TEXT_CMD, termination, rem, &req));
6419 context.check_layout(os);
6422 output_ert_inset(os, to_utf8(rem), context);
6424 skip_spaces_braces(p);
6425 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6426 preamble.registerAutomaticallyLoadedPackage(*it);
6428 //warning_message("#: " + t + " mode: " + mode);
6429 // heuristic: read up to next non-nested space
6431 string s = t.asInput();
6432 string z = p.verbatim_item();
6433 while (p.good() && z != " " && !z.empty()) {
6434 //warning_message("read: " + z);
6436 z = p.verbatim_item();
6438 warning_message("found ERT: " + s);
6439 output_ert_inset(os, s + ' ', context);
6442 if (t.asInput() == name &&
6443 p.next_token().asInput() == "*") {
6444 // Starred commands like \vspace*{}
6445 p.get_token(); // Eat '*'
6448 if (!parse_command(name, p, os, outer, context)) {
6449 output_ert_inset(os, name, context);
6450 // Try to handle options of unknown commands:
6451 // Look if we have optional arguments,
6452 // and if so, put the brackets in ERT.
6453 while (p.hasOpt()) {
6454 p.get_token(); // eat '['
6455 output_ert_inset(os, "[", context);
6456 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6457 output_ert_inset(os, "]", context);
6465 string guessLanguage(Parser & p, string const & lang)
6467 typedef std::map<std::string, size_t> LangMap;
6468 // map from language names to number of characters
6471 for (char const * const * i = supported_CJK_languages; *i; i++)
6472 used[string(*i)] = 0;
6475 Token const t = p.get_token();
6476 // comments are not counted for any language
6477 if (t.cat() == catComment)
6479 // commands are not counted as well, but we need to detect
6480 // \begin{CJK} and switch encoding if needed
6481 if (t.cat() == catEscape) {
6482 if (t.cs() == "inputencoding") {
6483 string const enc = subst(p.verbatim_item(), "\n", " ");
6484 p.setEncoding(enc, Encoding::inputenc);
6487 if (t.cs() != "begin")
6490 // Non-CJK content is counted for lang.
6491 // We do not care about the real language here:
6492 // If we have more non-CJK contents than CJK contents,
6493 // we simply use the language that was specified as
6494 // babel main language.
6495 used[lang] += t.asInput().length();
6498 // Now we are starting an environment
6500 string const name = p.getArg('{', '}');
6501 if (name != "CJK") {
6505 // It is a CJK environment
6507 /* name = */ p.getArg('{', '}');
6508 string const encoding = p.getArg('{', '}');
6509 /* mapping = */ p.getArg('{', '}');
6510 string const encoding_old = p.getEncoding();
6511 char const * const * const where =
6512 is_known(encoding, supported_CJK_encodings);
6514 p.setEncoding(encoding, Encoding::CJK);
6516 p.setEncoding("UTF-8");
6517 string const text = p.ertEnvironment("CJK");
6518 p.setEncoding(encoding_old);
6521 // ignore contents in unknown CJK encoding
6524 // the language of the text
6526 supported_CJK_languages[where - supported_CJK_encodings];
6527 used[cjk] += text.length();
6529 LangMap::const_iterator use = used.begin();
6530 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6531 if (it->second > use->second)
6538 void check_comment_bib(ostream & os, Context & context)
6540 if (!need_commentbib)
6542 // We have a bibliography database, but no bibliography with biblatex
6543 // which is completely valid. Insert a bibtex inset in a note.
6544 context.check_layout(os);
6545 begin_inset(os, "Note Note\n");
6546 os << "status open\n";
6547 os << "\\begin_layout Plain Layout\n";
6548 begin_command_inset(os, "bibtex", "bibtex");
6550 for (auto const & bf : preamble.biblatex_bibliographies) {
6551 if (!bibfiles.empty())
6553 bibfiles += normalize_filename(bf);
6555 if (!bibfiles.empty())
6556 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6558 for (auto const & bf : preamble.biblatex_encodings) {
6559 if (!bibfileencs.empty())
6560 bibfileencs += "\t";
6563 if (!bibfileencs.empty())
6564 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6565 end_inset(os);// Bibtex
6566 os << "\\end_layout\n";
6567 end_inset(os);// Note