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.
611 bool is_glue_length(string & length)
613 // check for glue lengths
614 bool is_gluelength = false;
615 string gluelength = length;
616 string::size_type i = length.find(" minus");
617 if (i == string::npos) {
618 i = length.find(" plus");
619 if (i != string::npos)
620 is_gluelength = true;
622 is_gluelength = true;
623 // if yes transform "9xx minus 8yy plus 7zz"
626 i = gluelength.find(" minus");
627 if (i != string::npos)
628 gluelength.replace(i, 7, "-");
629 i = gluelength.find(" plus");
630 if (i != string::npos)
631 gluelength.replace(i, 6, "+");
634 return is_gluelength;
641 * Translates a LaTeX length into \p value, \p unit and
642 * \p special parts suitable for a box inset.
643 * The difference from translate_len() is that a box inset knows about
644 * some special "units" that are stored in \p special.
646 void translate_box_len(string const & length, string & value, string & unit, string & special)
648 if (translate_len(length, value, unit)) {
649 if (unit == "\\height" || unit == "\\depth" ||
650 unit == "\\totalheight" || unit == "\\width") {
651 special = unit.substr(1);
652 // The unit is not used, but LyX requires a dummy setting
664 void begin_inset(ostream & os, string const & name)
666 os << "\n\\begin_inset " << name;
670 void begin_command_inset(ostream & os, string const & name,
671 string const & latexname)
673 begin_inset(os, "CommandInset ");
674 os << name << "\nLatexCommand " << latexname << '\n';
678 void end_inset(ostream & os)
680 os << "\n\\end_inset\n\n";
684 bool skip_braces(Parser & p)
686 if (p.next_token().cat() != catBegin)
689 if (p.next_token().cat() == catEnd) {
698 /// replace LaTeX commands in \p s from the unicodesymbols file with their
700 pair<bool, docstring> convert_unicodesymbols(docstring s)
704 for (size_t i = 0; i < s.size();) {
713 docstring parsed = normalize_c(Encodings::fromLaTeXCommand(s,
714 Encodings::TEXT_CMD, termination, rem, &req));
715 set<string>::const_iterator it = req.begin();
716 set<string>::const_iterator en = req.end();
717 for (; it != en; ++it)
718 preamble.registerAutomaticallyLoadedPackage(*it);
721 if (s.empty() || s[0] != '\\')
725 for (auto const & c : known_escaped_chars)
726 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
731 return make_pair(res, os.str());
735 /// try to convert \p s to a valid InsetCommand argument
736 /// return whether this succeeded. If not, these command insets
737 /// get the "literate" flag.
738 pair<bool, string> convert_latexed_command_inset_arg(string s)
740 bool success = false;
742 // since we don't know the input encoding we can't use from_utf8
743 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
745 s = to_utf8(res.second);
747 // LyX cannot handle newlines in a latex command
748 return make_pair(success, subst(s, "\n", " "));
751 /// try to convert \p s to a valid InsetCommand argument
752 /// without trying to recode macros.
753 string convert_literate_command_inset_arg(string const & s)
755 // LyX cannot handle newlines in a latex command
756 return subst(s, "\n", " ");
759 void output_ert(ostream & os, string const & s, Context & context)
761 context.check_layout(os);
762 for (char const c : s) {
764 os << "\n\\backslash\n";
765 else if (c == '\n') {
766 context.new_paragraph(os);
767 context.check_layout(os);
771 context.check_end_layout(os);
775 void output_ert_inset(ostream & os, string const & s, Context & context)
777 // We must have a valid layout before outputting the ERT inset.
778 context.check_layout(os);
779 Context newcontext(true, context.textclass);
780 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
781 if (layout.forcePlainLayout())
782 newcontext.layout = &context.textclass.plainLayout();
783 begin_inset(os, "ERT");
784 os << "\nstatus collapsed\n";
785 output_ert(os, s, newcontext);
790 void output_comment(Parser & p, ostream & os, string const & s,
793 if (p.next_token().cat() == catNewline)
794 output_ert_inset(os, '%' + s, context);
796 output_ert_inset(os, '%' + s + '\n', context);
800 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
801 string const & latexparam = string())
803 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
806 if (checkModule(name, command))
807 return findLayoutWithoutModule(textclass, name, command, latexparam);
812 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
813 string const & latexparam = string())
815 InsetLayout const * insetlayout =
816 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
819 if (checkModule(name, command))
820 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
825 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
826 bool eatNewline = true);
830 * Skips whitespace and braces.
831 * This should be called after a command has been parsed that is not put into
832 * ERT, and where LyX adds "{}" if needed.
834 void skip_spaces_braces(Parser & p, bool keepws = false)
836 /* The following four examples produce the same typeset output and
837 should be handled by this function:
845 // Unfortunately we need to skip comments, too.
846 // We can't use eat_whitespace since writing them after the {}
847 // results in different output in some cases.
848 bool const skipped_spaces = p.skip_spaces(true);
849 bool const skipped_braces = skip_braces(p);
850 if (keepws && skipped_spaces && !skipped_braces)
851 // put back the space (it is better handled by check_space)
852 p.unskip_spaces(true);
856 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
857 Context & context, Layout::LaTeXArgMap const & latexargs)
859 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
861 context.check_layout(os);
867 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
868 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
869 for (; lait != laend; ++lait) {
871 eat_whitespace(p, os, context, false);
872 if (lait->second.mandatory) {
873 if (p.next_token().cat() != catBegin)
875 string ldelim = to_utf8(lait->second.ldelim);
876 string rdelim = to_utf8(lait->second.rdelim);
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 string ldelim = to_utf8(lait->second.ldelim);
896 string rdelim = to_utf8(lait->second.rdelim);
901 string tok = p.next_token().asInput();
902 // we only support delimiters with max 2 chars for now.
903 if (ldelim.size() > 1)
904 tok += p.next_next_token().asInput();
905 if (p.next_token().cat() == catEscape || tok != ldelim)
907 p.get_token(); // eat ldelim
908 if (ldelim.size() > 1)
909 p.get_token(); // eat ldelim
911 context.check_layout(os);
914 begin_inset(os, "Argument ");
917 os << i << "\nstatus collapsed\n\n";
918 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
921 eat_whitespace(p, os, context, false);
926 void output_command_layout(ostream & os, Parser & p, bool outer,
927 Context & parent_context,
928 Layout const * newlayout)
930 TeXFont const oldFont = parent_context.font;
931 // save the current font size
932 string const size = oldFont.size;
933 // reset the font size to default, because the font size switches
934 // don't affect section headings and the like
935 parent_context.font.size = Context::normalfont.size;
936 // we only need to write the font change if we have an open layout
937 if (!parent_context.atParagraphStart())
938 output_font_change(os, oldFont, parent_context.font);
939 parent_context.check_end_layout(os);
940 Context context(true, parent_context.textclass, newlayout,
941 parent_context.layout, parent_context.font);
942 if (parent_context.deeper_paragraph) {
943 // We are beginning a nested environment after a
944 // deeper paragraph inside the outer list environment.
945 // Therefore we don't need to output a "begin deeper".
946 context.need_end_deeper = true;
948 context.check_deeper(os);
949 output_arguments(os, p, outer, true, string(), context,
950 context.layout->latexargs());
951 // If we have a latex param, we eat it here.
952 if (!parent_context.latexparam.empty()) {
954 Context dummy(true, parent_context.textclass);
955 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
956 string(1, parent_context.latexparam.back()));
958 parse_text(p, os, FLAG_ITEM, outer, context);
959 output_arguments(os, p, outer, false, "post", context,
960 context.layout->postcommandargs());
961 context.check_end_layout(os);
962 if (parent_context.deeper_paragraph) {
963 // We must suppress the "end deeper" because we
964 // suppressed the "begin deeper" above.
965 context.need_end_deeper = false;
967 context.check_end_deeper(os);
968 // We don't need really a new paragraph, but
969 // we must make sure that the next item gets a \begin_layout.
970 parent_context.new_paragraph(os);
971 // Set the font size to the original value. No need to output it here
972 // (Context::begin_layout() will do that if needed)
973 parent_context.font.size = size;
978 * Output a space if necessary.
979 * This function gets called for every whitespace token.
981 * We have three cases here:
982 * 1. A space must be suppressed. Example: The lyxcode case below
983 * 2. A space may be suppressed. Example: Spaces before "\par"
984 * 3. A space must not be suppressed. Example: A space between two words
986 * We currently handle only 1. and 3 and from 2. only the case of
987 * spaces before newlines as a side effect.
989 * 2. could be used to suppress as many spaces as possible. This has two effects:
990 * - Reimporting LyX generated LaTeX files changes almost no whitespace
991 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
992 * The drawback is that the logic inside the function becomes
993 * complicated, and that is the reason why it is not implemented.
995 void check_space(Parser & p, ostream & os, Context & context)
997 Token const next = p.next_token();
998 Token const curr = p.curr_token();
999 // A space before a single newline and vice versa must be ignored
1000 // LyX emits a newline before \end{lyxcode}.
1001 // This newline must be ignored,
1002 // otherwise LyX will add an additional protected space.
1003 if (next.cat() == catSpace ||
1004 next.cat() == catNewline ||
1005 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
1008 context.check_layout(os);
1014 * Parse all arguments of \p command
1016 void parse_arguments(string const & command,
1017 vector<ArgumentType> const & template_arguments,
1018 Parser & p, ostream & os, bool outer, Context & context)
1020 string ert = command;
1021 size_t no_arguments = template_arguments.size();
1022 for (size_t i = 0; i < no_arguments; ++i) {
1023 switch (template_arguments[i]) {
1026 // This argument contains regular LaTeX
1027 output_ert_inset(os, ert + '{', context);
1028 eat_whitespace(p, os, context, false);
1029 if (template_arguments[i] == required)
1030 parse_text(p, os, FLAG_ITEM, outer, context);
1032 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1036 // This argument consists only of a single item.
1037 // The presence of '{' or not must be preserved.
1039 if (p.next_token().cat() == catBegin)
1040 ert += '{' + p.verbatim_item() + '}';
1042 ert += p.verbatim_item();
1046 // This argument may contain special characters
1047 ert += '{' + p.verbatim_item() + '}';
1051 // true because we must not eat whitespace
1052 // if an optional arg follows we must not strip the
1053 // brackets from this one
1054 if (i < no_arguments - 1 &&
1055 template_arguments[i+1] == optional)
1056 ert += p.getFullOpt(true);
1058 ert += p.getOpt(true);
1062 output_ert_inset(os, ert, context);
1067 * Check whether \p command is a known command. If yes,
1068 * handle the command with all arguments.
1069 * \return true if the command was parsed, false otherwise.
1071 bool parse_command(string const & command, Parser & p, ostream & os,
1072 bool outer, Context & context)
1074 if (known_commands.find(command) != known_commands.end()) {
1075 parse_arguments(command, known_commands[command], p, os,
1083 /// Parses a minipage or parbox
1084 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1085 unsigned inner_flags, bool outer, Context & parent_context,
1086 string const & outer_type, string const & special,
1087 string inner_type, string const & frame_color,
1088 string const & background_color)
1092 string hor_pos = "l";
1093 // We need to set the height to the LaTeX default of 1\\totalheight
1094 // for the case when no height argument is given
1095 string height_value = "1";
1096 string height_unit = "in";
1097 string height_special = "totalheight";
1098 string latex_height;
1102 string width_special = "none";
1103 string thickness = "0.4pt";
1104 if (!fboxrule.empty())
1105 thickness = fboxrule;
1107 thickness = "0.4pt";
1109 if (!fboxsep.empty())
1110 separation = fboxsep;
1114 if (!shadow_size.empty())
1115 shadowsize = shadow_size;
1118 string framecolor = "black";
1119 string backgroundcolor = "none";
1120 if (!frame_color.empty())
1121 framecolor = frame_color;
1122 if (!background_color.empty())
1123 backgroundcolor = background_color;
1124 // if there is a color box around the \begin statements have not yet been parsed
1126 if (!frame_color.empty() || !background_color.empty()) {
1127 eat_whitespace(p, os, parent_context, false);
1128 p.get_token().asInput(); // the '{'
1130 if (p.next_token().asInput() == "\\begin") {
1131 p.get_token().asInput();
1133 inner_type = "minipage";
1134 inner_flags = FLAG_END;
1135 active_environments.push_back("minipage");
1138 else if (p.next_token().asInput() == "\\parbox") {
1139 p.get_token().asInput();
1140 inner_type = "parbox";
1141 inner_flags = FLAG_ITEM;
1144 else if (p.next_token().asInput() == "\\makebox") {
1145 p.get_token().asInput();
1146 inner_type = "makebox";
1147 inner_flags = FLAG_ITEM;
1149 // in case there is just \colorbox{color}{text}
1152 inner_type = "makebox";
1153 inner_flags = FLAG_BRACE_LAST;
1158 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1160 if (!inner_type.empty() && p.hasOpt()) {
1161 if (inner_type != "makebox")
1162 position = p.getArg('[', ']');
1164 latex_width = p.getArg('[', ']');
1165 translate_box_len(latex_width, width_value, width_unit, width_special);
1168 if (position != "t" && position != "c" && position != "b") {
1169 warning_message("invalid position " + position
1170 + " for " + inner_type);
1174 if (inner_type != "makebox") {
1175 latex_height = p.getArg('[', ']');
1176 translate_box_len(latex_height, height_value, height_unit, height_special);
1178 string const opt = p.getArg('[', ']');
1181 if (hor_pos != "l" && hor_pos != "c" &&
1182 hor_pos != "r" && hor_pos != "s") {
1183 warning_message("invalid hor_pos "
1192 inner_pos = p.getArg('[', ']');
1193 if (inner_pos != "c" && inner_pos != "t" &&
1194 inner_pos != "b" && inner_pos != "s") {
1195 warning_message("invalid inner_pos "
1196 + inner_pos + " for "
1198 inner_pos = position;
1202 if (inner_type == "makebox")
1206 if (inner_type.empty()) {
1207 if (special.empty() && outer_type != "framebox")
1208 latex_width = "1\\columnwidth";
1211 latex_width = p2.getArg('[', ']');
1212 string const opt = p2.getArg('[', ']');
1215 if (hor_pos != "l" && hor_pos != "c" &&
1216 hor_pos != "r" && hor_pos != "s") {
1217 warning_message("invalid hor_pos "
1223 if (outer_type == "framebox")
1227 } else if (inner_type != "makebox")
1228 latex_width = p.verbatim_item();
1229 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1230 // as this is LyX's standard for such cases (except for makebox)
1231 // \framebox is more special and handled below
1232 if (latex_width.empty() && inner_type != "makebox"
1233 && outer_type != "framebox")
1234 latex_width = "1\\columnwidth";
1236 translate_len(latex_width, width_value, width_unit);
1238 bool shadedparbox = false;
1239 if (inner_type == "shaded") {
1240 eat_whitespace(p, os, parent_context, false);
1241 if (outer_type == "parbox") {
1243 if (p.next_token().cat() == catBegin)
1245 eat_whitespace(p, os, parent_context, false);
1246 shadedparbox = true;
1251 // If we already read the inner box we have to push the inner env
1252 if (!outer_type.empty() && !inner_type.empty() &&
1253 (inner_flags & FLAG_END))
1254 active_environments.push_back(inner_type);
1255 bool use_ert = false;
1256 if (!outer_type.empty() && !inner_type.empty()) {
1257 // Look whether there is some content after the end of the
1258 // inner box, but before the end of the outer box.
1259 // If yes, we need to output ERT.
1261 if (inner_flags & FLAG_END)
1262 p.ertEnvironment(inner_type);
1265 p.skip_spaces(true);
1266 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1267 if ((outer_env && p.next_token().asInput() != "\\end") ||
1268 (!outer_env && p.next_token().cat() != catEnd)) {
1269 // something is between the end of the inner box and
1270 // the end of the outer box, so we need to use ERT.
1278 if (!outer_type.empty()) {
1279 if (outer_flags & FLAG_END)
1280 ss << "\\begin{" << outer_type << '}';
1282 ss << '\\' << outer_type << '{';
1283 if (!special.empty())
1287 if (!inner_type.empty()) {
1288 if (inner_type != "shaded") {
1289 if (inner_flags & FLAG_END)
1290 ss << "\\begin{" << inner_type << '}';
1292 ss << '\\' << inner_type;
1294 if (!position.empty())
1295 ss << '[' << position << ']';
1296 if (!latex_height.empty())
1297 ss << '[' << latex_height << ']';
1298 if (!inner_pos.empty())
1299 ss << '[' << inner_pos << ']';
1300 ss << '{' << latex_width << '}';
1301 if (!(inner_flags & FLAG_END))
1304 if (inner_type == "shaded")
1305 ss << "\\begin{shaded}";
1306 output_ert_inset(os, ss.str(), parent_context);
1307 if (!inner_type.empty()) {
1308 parse_text(p, os, inner_flags, outer, parent_context);
1309 if (inner_flags & FLAG_END)
1310 output_ert_inset(os, "\\end{" + inner_type + '}',
1313 output_ert_inset(os, "}", parent_context);
1315 if (!outer_type.empty()) {
1316 // If we already read the inner box we have to pop
1318 if (!inner_type.empty() && (inner_flags & FLAG_END))
1319 active_environments.pop_back();
1321 // Ensure that the end of the outer box is parsed correctly:
1322 // The opening brace has been eaten by parse_outer_box()
1323 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1324 outer_flags &= ~FLAG_ITEM;
1325 outer_flags |= FLAG_BRACE_LAST;
1327 parse_text(p, os, outer_flags, outer, parent_context);
1328 if (outer_flags & FLAG_END)
1329 output_ert_inset(os, "\\end{" + outer_type + '}',
1332 output_ert_inset(os, "}", parent_context);
1335 // LyX does not like empty positions, so we have
1336 // to set them to the LaTeX default values here.
1337 if (position.empty())
1339 if (inner_pos.empty())
1340 inner_pos = position;
1341 parent_context.check_layout(os);
1342 begin_inset(os, "Box ");
1343 if (outer_type == "framed")
1345 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1347 else if (outer_type == "shadowbox")
1348 os << "Shadowbox\n";
1349 else if ((outer_type == "shaded" && inner_type.empty()) ||
1350 (outer_type == "minipage" && inner_type == "shaded") ||
1351 (outer_type == "parbox" && inner_type == "shaded")) {
1353 preamble.registerAutomaticallyLoadedPackage("color");
1354 } else if (outer_type == "doublebox")
1355 os << "Doublebox\n";
1356 else if (outer_type.empty() || outer_type == "mbox")
1357 os << "Frameless\n";
1359 os << outer_type << '\n';
1360 os << "position \"" << position << "\"\n";
1361 os << "hor_pos \"" << hor_pos << "\"\n";
1362 if (outer_type == "mbox")
1363 os << "has_inner_box 1\n";
1364 else if (!frame_color.empty() && inner_type == "makebox")
1365 os << "has_inner_box 0\n";
1367 os << "has_inner_box " << !inner_type.empty() << "\n";
1368 os << "inner_pos \"" << inner_pos << "\"\n";
1369 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1371 if (outer_type == "mbox")
1372 os << "use_makebox 1\n";
1373 else if (!frame_color.empty())
1374 os << "use_makebox 0\n";
1376 os << "use_makebox " << (inner_type == "makebox") << '\n';
1377 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1378 os << "width \"\"\n";
1379 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1380 else if (contains(width_unit, '\\'))
1381 os << "width \"" << width_value << "in" << "\"\n";
1383 os << "width \"" << width_value << width_unit << "\"\n";
1384 if (contains(width_unit, '\\')) {
1385 width_unit.erase (0,1); // remove the leading '\'
1386 os << "special \"" << width_unit << "\"\n";
1388 os << "special \"" << width_special << "\"\n";
1389 if (contains(height_unit, '\\'))
1390 os << "height \"" << height_value << "in" << "\"\n";
1392 os << "height \"" << height_value << height_unit << "\"\n";
1393 os << "height_special \"" << height_special << "\"\n";
1394 os << "thickness \"" << thickness << "\"\n";
1395 os << "separation \"" << separation << "\"\n";
1396 os << "shadowsize \"" << shadowsize << "\"\n";
1397 os << "framecolor \"" << framecolor << "\"\n";
1398 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1399 os << "status open\n\n";
1401 // Unfortunately we can't use parse_text_in_inset:
1402 // InsetBox::forcePlainLayout() is hard coded and does not
1403 // use the inset layout. Apart from that do we call parse_text
1404 // up to two times, but need only one check_end_layout.
1405 bool const forcePlainLayout =
1406 (!inner_type.empty() || inner_type == "makebox") &&
1407 outer_type != "shaded" && outer_type != "framed";
1408 Context context(true, parent_context.textclass);
1409 if (forcePlainLayout)
1410 context.layout = &context.textclass.plainLayout();
1412 context.font = parent_context.font;
1414 // If we have no inner box the contents will be read with the outer box
1415 if (!inner_type.empty())
1416 parse_text(p, os, inner_flags, outer, context);
1418 // Ensure that the end of the outer box is parsed correctly:
1419 // The opening brace has been eaten by parse_outer_box()
1420 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1421 outer_flags &= ~FLAG_ITEM;
1422 outer_flags |= FLAG_BRACE_LAST;
1425 // Find end of outer box, output contents if inner_type is
1426 // empty and output possible comments
1427 if (!outer_type.empty()) {
1428 // If we already read the inner box we have to pop
1430 if (!inner_type.empty() && (inner_flags & FLAG_END))
1431 active_environments.pop_back();
1432 // This does not output anything but comments if
1433 // inner_type is not empty (see use_ert)
1434 parse_text(p, os, outer_flags, outer, context);
1437 context.check_end_layout(os);
1439 #ifdef PRESERVE_LAYOUT
1440 // LyX puts a % after the end of the minipage
1441 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1443 //output_comment(p, os, "dummy", parent_context);
1446 parent_context.new_paragraph(os);
1448 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1449 //output_comment(p, os, "dummy", parent_context);
1452 // We add a protected space if something real follows
1453 if (p.good() && p.next_token().cat() != catComment) {
1454 begin_inset(os, "space ~\n");
1460 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1461 active_environments.pop_back();
1462 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1463 // in this case we have to eat the the closing brace of the color box
1464 p.get_token().asInput(); // the '}'
1466 if (p.next_token().asInput() == "}") {
1467 // in this case we assume that the closing brace is from the box settings
1468 // therefore reset these values for the next box
1474 // all boxes except of Frameless and Shaded require calc
1475 if (!(outer_type.empty() || outer_type == "mbox") &&
1476 !((outer_type == "shaded" && inner_type.empty()) ||
1477 (outer_type == "minipage" && inner_type == "shaded") ||
1478 (outer_type == "parbox" && inner_type == "shaded")))
1479 preamble.registerAutomaticallyLoadedPackage("calc");
1483 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1484 Context & parent_context, string const & outer_type,
1485 string const & special)
1487 eat_whitespace(p, os, parent_context, false);
1488 if (flags & FLAG_ITEM) {
1490 if (p.next_token().cat() == catBegin)
1493 warning_message("Ignoring missing '{' after \\"
1494 + outer_type + '.');
1495 eat_whitespace(p, os, parent_context, false);
1498 unsigned int inner_flags = 0;
1500 if (outer_type == "minipage" || outer_type == "parbox") {
1501 p.skip_spaces(true);
1502 while (p.hasOpt()) {
1504 p.skip_spaces(true);
1507 p.skip_spaces(true);
1508 if (outer_type == "parbox") {
1510 if (p.next_token().cat() == catBegin)
1512 p.skip_spaces(true);
1515 if (outer_type == "shaded" || outer_type == "mbox") {
1516 // These boxes never have an inner box
1518 } else if (p.next_token().asInput() == "\\parbox") {
1519 inner = p.get_token().cs();
1520 inner_flags = FLAG_ITEM;
1521 } else if (p.next_token().asInput() == "\\begin") {
1522 // Is this a minipage or shaded box?
1525 inner = p.getArg('{', '}');
1527 if (inner == "minipage" || inner == "shaded")
1528 inner_flags = FLAG_END;
1533 if (inner_flags == FLAG_END) {
1534 if (inner != "shaded")
1538 eat_whitespace(p, os, parent_context, false);
1540 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1541 outer_type, special, inner, "", "");
1543 if (inner_flags == FLAG_ITEM) {
1545 eat_whitespace(p, os, parent_context, false);
1547 parse_box(p, os, flags, inner_flags, outer, parent_context,
1548 outer_type, special, inner, "", "");
1553 void parse_index_entry(Parser & p, ostream & os, Context & context, string const & kind)
1555 // write inset header
1556 begin_inset(os, "Index ");
1559 // Parse for post argument (|...)
1561 string const marg = p.getArg('{', '}');
1564 bool inpost = false;
1565 bool startrange = false;
1566 bool endrange = false;
1568 for (string::const_iterator it = marg.begin(), et = marg.end(); it != et; ++it) {
1571 if (post.empty() && c == '(')
1573 else if (post.empty() && c == ')')
1578 if (!inpost && (c == '|' && lc != '"'))
1583 os << "\nrange start";
1585 os << "\nrange end";
1587 os << "\nrange none";
1588 bool const see = prefixIs(post, "see{");
1589 bool const seealso = prefixIs(post, "seealso{");
1590 if (!post.empty() && !see && !seealso)
1591 os << "\npageformat " << post;
1593 os << "\npageformat default";
1594 os << "\nstatus collapsed\n";
1600 if (p.hasIdxMacros("!")) {
1601 // Index entry with levels
1602 while (p.hasIdxMacros("!")) {
1606 os << "\\begin_layout Plain Layout\n";
1608 begin_inset(os, "IndexMacro subentry");
1609 os << "\nstatus collapsed\n";
1611 // Check for (level-specific) sortkey
1612 if (p.hasIdxMacros("@", "!")) {
1614 os << "\\begin_layout Plain Layout\n";
1615 begin_inset(os, "IndexMacro sortkey");
1616 os << "\nstatus collapsed\n";
1617 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1620 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "!", "\"");
1622 os << "\n\\end_layout\n";
1628 begin_inset(os, "IndexMacro subentry");
1629 os << "\nstatus collapsed\n";
1632 // Check for (level-specific) sortkey
1633 if (p.hasIdxMacros("@", "!")) {
1638 os << "\\begin_layout Plain Layout\n";
1639 begin_inset(os, "IndexMacro sortkey");
1640 os << "\nstatus collapsed\n";
1641 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1643 if (post.empty() && !startrange && !endrange) {
1644 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1647 // Handle post-argument
1648 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1649 if (see || seealso) {
1650 while (p.next_token().character() != '{' && p.good())
1652 // this ends the subinset, as the see[also] insets
1653 // must come at main index inset
1654 os << "\n\\end_layout\n";
1657 begin_inset(os, "IndexMacro see");
1659 begin_inset(os, "IndexMacro seealso");
1660 os << "\nstatus collapsed\n";
1661 os << "\\begin_layout Plain Layout\n";
1662 parse_text_snippet(p, os, FLAG_ITEM, false, context);
1668 os << "\n\\end_layout\n";
1670 if (post.empty() && !startrange && !endrange) {
1671 parse_text_in_inset(p, os, FLAG_BRACE_LAST, false, context, "IndexMacro subentry");
1674 // Handle post-argument
1675 if (see || seealso) {
1676 os << "\\begin_layout Plain Layout\n";
1677 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1678 while (p.next_token().character() != '{' && p.good())
1680 // this ends the subinset, as the see[also] insets
1681 // must come at main index inset
1682 os << "\n\\end_layout\n";
1685 begin_inset(os, "IndexMacro see");
1687 begin_inset(os, "IndexMacro seealso");
1688 os << "\nstatus collapsed\n";
1689 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1691 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1699 os << "\n\\end_layout\n";
1701 // Index without any levels
1702 // Check for sortkey
1703 if (p.hasIdxMacros("@", "!")) {
1706 os << "\\begin_layout Plain Layout\n";
1707 begin_inset(os, "IndexMacro sortkey");
1708 os << "\nstatus collapsed\n";
1709 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "IndexMacro sortkey", "@", "\"");
1711 if (post.empty() && !startrange && !endrange) {
1712 parse_text_snippet(p, os, FLAG_BRACE_LAST, false, context);
1715 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1716 if (see || seealso) {
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");
1731 os << "\n\\end_layout\n";
1733 if (post.empty() && !startrange && !endrange) {
1734 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
1737 // Handle post-argument
1740 if (see || seealso) {
1741 os << "\\begin_layout Plain Layout\n";
1742 parse_text_snippet(p, os, FLAG_RDELIM, false, context, "|", "\"");
1743 while (p.next_token().character() != '{' && p.good())
1746 begin_inset(os, "IndexMacro see");
1748 begin_inset(os, "IndexMacro seealso");
1749 os << "\nstatus collapsed\n";
1750 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "IndexMacro see");
1752 os << "\n\\end_layout\n";
1754 parse_text_in_inset(p, os, FLAG_RDELIM, false, context, "Index", "|", "\"");
1765 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1766 bool in_line, bool use_minted)
1768 parent_context.check_layout(os);
1769 begin_inset(os, "listings\n");
1770 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1772 while ((i = arg.find(", ")) != string::npos
1773 || (i = arg.find(",\t")) != string::npos)
1774 arg.erase(i + 1, 1);
1777 string const language = p.getArg('{', '}');
1778 p.skip_spaces(true);
1779 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1780 if (!minted_float.empty()) {
1781 arg += string(arg.empty() ? "" : ",") + minted_float;
1782 minted_nonfloat_caption.clear();
1786 os << "lstparams " << '"' << arg << '"' << '\n';
1787 if (arg.find("\\color") != string::npos)
1788 preamble.registerAutomaticallyLoadedPackage("color");
1791 os << "inline true\n";
1793 os << "inline false\n";
1794 os << "status open\n";
1795 Context context(true, parent_context.textclass);
1796 context.layout = &parent_context.textclass.plainLayout();
1797 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1798 minted_nonfloat_caption.erase(0,3);
1799 os << "\n\\begin_layout Plain Layout\n";
1800 begin_inset(os, "Caption Standard\n");
1801 Context newcontext(true, context.textclass,
1802 context.layout, 0, context.font);
1803 newcontext.check_layout(os);
1804 os << minted_nonfloat_caption << "\n";
1805 newcontext.check_end_layout(os);
1807 os << "\n\\end_layout\n";
1808 minted_nonfloat_caption.clear();
1812 // set catcodes to verbatim early, just in case.
1813 p.setCatcodes(VERBATIM_CATCODES);
1814 string delim = p.get_token().asInput();
1815 //FIXME: handler error condition
1816 s = p.verbatimStuff(delim).second;
1817 // context.new_paragraph(os);
1818 } else if (use_minted) {
1819 s = p.verbatimEnvironment("minted");
1821 s = p.verbatimEnvironment("lstlisting");
1823 output_ert(os, s, context);
1824 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1825 minted_nonfloat_caption.erase(0,3);
1826 os << "\n\\begin_layout Plain Layout\n";
1827 begin_inset(os, "Caption Standard\n");
1828 Context newcontext(true, context.textclass,
1829 context.layout, 0, context.font);
1830 newcontext.check_layout(os);
1831 os << minted_nonfloat_caption << "\n";
1832 newcontext.check_end_layout(os);
1834 os << "\n\\end_layout\n";
1835 minted_nonfloat_caption.clear();
1837 // Don't close the inset here for floating minted listings.
1838 // It will be closed at the end of the listing environment.
1839 if (!use_minted || minted_float.empty())
1842 eat_whitespace(p, os, parent_context, true);
1843 Token t = p.get_token();
1844 if (t.asInput() != "\\end") {
1845 // If anything follows, collect it into a caption.
1846 minted_float_has_caption = true;
1847 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1848 begin_inset(os, "Caption Standard\n");
1849 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1856 /// parse an unknown environment
1857 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1858 unsigned flags, bool outer,
1859 Context & parent_context)
1861 if (name == "tabbing")
1862 // We need to remember that we have to handle '\=' specially
1863 flags |= FLAG_TABBING;
1865 // We need to translate font changes and paragraphs inside the
1866 // environment to ERT if we have a non standard font.
1867 // Otherwise things like
1868 // \large\begin{foo}\huge bar\end{foo}
1870 bool const specialfont =
1871 (parent_context.font != parent_context.normalfont);
1872 bool const new_layout_allowed = parent_context.new_layout_allowed;
1874 parent_context.new_layout_allowed = false;
1875 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1876 // Try to handle options: Look if we have optional arguments,
1877 // and if so, put the brackets in ERT.
1878 while (p.hasOpt()) {
1879 p.get_token(); // eat '['
1880 output_ert_inset(os, "[", parent_context);
1881 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1882 output_ert_inset(os, "]", parent_context);
1884 parse_text_snippet(p, os, flags, outer, parent_context);
1885 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1887 parent_context.new_layout_allowed = new_layout_allowed;
1891 void parse_environment(Parser & p, ostream & os, bool outer,
1892 string & last_env, Context & parent_context)
1894 Layout const * newlayout;
1895 InsetLayout const * newinsetlayout = 0;
1896 string const name = p.getArg('{', '}');
1897 const bool is_starred = suffixIs(name, '*');
1898 string const unstarred_name = rtrim(name, "*");
1899 active_environments.push_back(name);
1901 // We use this loop and break out after a condition is met
1902 // rather than a huge else-if-chain.
1904 if (is_math_env(name)) {
1905 parent_context.check_layout(os);
1906 begin_inset(os, "Formula ");
1907 os << "\\begin{" << name << "}";
1908 parse_math(p, os, FLAG_END, MATH_MODE);
1909 os << "\\end{" << name << "}";
1911 if (is_display_math_env(name)) {
1912 // Prevent the conversion of a line break to a space
1913 // (bug 7668). This does not change the output, but
1914 // looks ugly in LyX.
1915 eat_whitespace(p, os, parent_context, false);
1920 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1921 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1922 // We must begin a new paragraph if not already done
1923 if (!parent_context.atParagraphStart()) {
1924 parent_context.check_end_layout(os);
1925 parent_context.new_paragraph(os);
1927 // store previous language because we must reset it at the end
1928 string const lang_old = parent_context.font.language;
1929 // save new language in context so that it is
1930 // handled by parse_text
1931 parent_context.font.language =
1932 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1933 parse_text(p, os, FLAG_END, outer, parent_context);
1934 // reset previous language
1935 parent_context.font.language = lang_old;
1936 // Just in case the environment is empty
1937 parent_context.extra_stuff.erase();
1938 // We must begin a new paragraph to reset the language
1939 parent_context.new_paragraph(os);
1944 if (unstarred_name == "tabular" || name == "longtable"
1945 || name == "tabularx" || name == "xltabular") {
1946 eat_whitespace(p, os, parent_context, false);
1947 string width = "0pt";
1949 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1950 string const opt = p.getArg('[', ']');
1953 else if (opt == "l")
1955 else if (opt == "r")
1958 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1959 width = lyx::translate_len(p.getArg('{', '}'));
1960 eat_whitespace(p, os, parent_context, false);
1962 parent_context.check_layout(os);
1963 begin_inset(os, "Tabular ");
1964 handle_tabular(p, os, name, width, halign, parent_context);
1970 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1971 eat_whitespace(p, os, parent_context, false);
1972 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1973 eat_whitespace(p, os, parent_context, false);
1974 parent_context.check_layout(os);
1975 begin_inset(os, "Float " + unstarred_name + "\n");
1976 // store the float type for subfloats
1977 // subfloats only work with figures and tables
1978 if (unstarred_name == "figure")
1979 float_type = unstarred_name;
1980 else if (unstarred_name == "table")
1981 float_type = unstarred_name;
1985 os << "placement " << opt << '\n';
1986 if (contains(opt, "H"))
1987 preamble.registerAutomaticallyLoadedPackage("float");
1989 Floating const & fl = parent_context.textclass.floats()
1990 .getType(unstarred_name);
1991 if (!fl.floattype().empty() && fl.usesFloatPkg())
1992 preamble.registerAutomaticallyLoadedPackage("float");
1995 os << "wide " << convert<string>(is_starred)
1996 << "\nsideways false"
1997 << "\nstatus open\n\n";
1998 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1999 if (unstarred_name == "algorithm")
2000 // in algorithm, \; has special meaning
2001 parent_context.pass_thru_cmds.insert(";");
2002 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2003 if (unstarred_name == "algorithm")
2004 parent_context.pass_thru_cmds = pass_thru_cmds;
2006 // We don't need really a new paragraph, but
2007 // we must make sure that the next item gets a \begin_layout.
2008 parent_context.new_paragraph(os);
2010 // the float is parsed thus delete the type
2015 if (unstarred_name == "sidewaysfigure"
2016 || unstarred_name == "sidewaystable"
2017 || unstarred_name == "sidewaysalgorithm") {
2018 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2019 eat_whitespace(p, os, parent_context, false);
2020 parent_context.check_layout(os);
2021 if (unstarred_name == "sidewaysfigure")
2022 begin_inset(os, "Float figure\n");
2023 else if (unstarred_name == "sidewaystable")
2024 begin_inset(os, "Float table\n");
2025 else if (unstarred_name == "sidewaysalgorithm")
2026 begin_inset(os, "Float algorithm\n");
2028 os << "placement " << opt << '\n';
2029 if (contains(opt, "H"))
2030 preamble.registerAutomaticallyLoadedPackage("float");
2031 os << "wide " << convert<string>(is_starred)
2032 << "\nsideways true"
2033 << "\nstatus open\n\n";
2034 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2036 // We don't need really a new paragraph, but
2037 // we must make sure that the next item gets a \begin_layout.
2038 parent_context.new_paragraph(os);
2040 preamble.registerAutomaticallyLoadedPackage("rotfloat");
2044 if (name == "wrapfigure" || name == "wraptable") {
2045 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
2046 eat_whitespace(p, os, parent_context, false);
2047 parent_context.check_layout(os);
2050 string overhang = "0col%";
2053 lines = p.getArg('[', ']');
2054 string const placement = p.getArg('{', '}');
2056 overhang = p.getArg('[', ']');
2057 string const width = p.getArg('{', '}');
2059 if (name == "wrapfigure")
2060 begin_inset(os, "Wrap figure\n");
2062 begin_inset(os, "Wrap table\n");
2063 os << "lines " << lines
2064 << "\nplacement " << placement
2065 << "\noverhang " << lyx::translate_len(overhang)
2066 << "\nwidth " << lyx::translate_len(width)
2067 << "\nstatus open\n\n";
2068 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2070 // We don't need really a new paragraph, but
2071 // we must make sure that the next item gets a \begin_layout.
2072 parent_context.new_paragraph(os);
2074 preamble.registerAutomaticallyLoadedPackage("wrapfig");
2078 if (name == "minipage") {
2079 eat_whitespace(p, os, parent_context, false);
2080 // Test whether this is an outer box of a shaded box
2082 // swallow arguments
2083 while (p.hasOpt()) {
2085 p.skip_spaces(true);
2088 p.skip_spaces(true);
2089 Token t = p.get_token();
2090 bool shaded = false;
2091 if (t.asInput() == "\\begin") {
2092 p.skip_spaces(true);
2093 if (p.getArg('{', '}') == "shaded")
2098 parse_outer_box(p, os, FLAG_END, outer,
2099 parent_context, name, "shaded");
2101 parse_box(p, os, 0, FLAG_END, outer, parent_context,
2102 "", "", name, "", "");
2107 if (name == "comment") {
2108 eat_whitespace(p, os, parent_context, false);
2109 parent_context.check_layout(os);
2110 begin_inset(os, "Note Comment\n");
2111 os << "status open\n";
2112 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2115 skip_braces(p); // eat {} that might by set by LyX behind comments
2116 preamble.registerAutomaticallyLoadedPackage("verbatim");
2120 if (unstarred_name == "verbatim") {
2121 // FIXME: this should go in the generic code that
2122 // handles environments defined in layout file that
2123 // have "PassThru 1". However, the code over there is
2124 // already too complicated for my taste.
2125 string const ascii_name =
2126 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
2127 parent_context.new_paragraph(os);
2128 Context context(true, parent_context.textclass,
2129 &parent_context.textclass[from_ascii(ascii_name)]);
2130 string s = p.verbatimEnvironment(name);
2131 output_ert(os, s, context);
2136 if (name == "IPA") {
2137 eat_whitespace(p, os, parent_context, false);
2138 parent_context.check_layout(os);
2139 begin_inset(os, "IPA\n");
2140 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
2141 // These commands have special meanings in IPA
2142 parent_context.pass_thru_cmds.insert("!");
2143 parent_context.pass_thru_cmds.insert(";");
2144 parent_context.pass_thru_cmds.insert(":");
2145 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2146 parent_context.pass_thru_cmds = pass_thru_cmds;
2149 preamble.registerAutomaticallyLoadedPackage("tipa");
2150 preamble.registerAutomaticallyLoadedPackage("tipx");
2154 if (name == parent_context.textclass.titlename()
2155 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
2156 parse_text(p, os, FLAG_END, outer, parent_context);
2157 // Just in case the environment is empty
2158 parent_context.extra_stuff.erase();
2159 // We must begin a new paragraph
2160 parent_context.new_paragraph(os);
2165 if (name == "CJK") {
2166 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
2167 // It is impossible to decide if a CJK environment was in its own paragraph or within
2168 // a line. We therefore always assume a paragraph since the latter is a rare case.
2169 eat_whitespace(p, os, parent_context, false);
2170 parent_context.check_end_layout(os);
2171 // store the encoding to be able to reset it
2172 string const encoding_old = p.getEncoding();
2173 string const encoding = p.getArg('{', '}');
2174 // FIXME: For some reason JIS does not work. Although the text
2175 // in tests/CJK.tex is identical with the SJIS version if you
2176 // convert both snippets using the recode command line utility,
2177 // the resulting .lyx file contains some extra characters if
2178 // you set buggy_encoding to false for JIS.
2179 bool const buggy_encoding = encoding == "JIS";
2180 if (!buggy_encoding)
2181 p.setEncoding(encoding, Encoding::CJK);
2183 // FIXME: This will read garbage, since the data is not encoded in utf8.
2184 p.setEncoding("UTF-8");
2186 // LyX only supports the same mapping for all CJK
2187 // environments, so we might need to output everything as ERT
2188 string const mapping = trim(p.getArg('{', '}'));
2189 char const * const * const where =
2190 is_known(encoding, supported_CJK_encodings);
2191 if (!buggy_encoding && !preamble.fontCJKSet())
2192 preamble.fontCJK(mapping);
2193 bool knownMapping = mapping == preamble.fontCJK();
2194 if (buggy_encoding || !knownMapping || !where) {
2195 parent_context.check_layout(os);
2196 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
2198 // we must parse the content as verbatim because e.g. JIS can contain
2199 // normally invalid characters
2200 // FIXME: This works only for the most simple cases.
2201 // Since TeX control characters are not parsed,
2202 // things like comments are completely wrong.
2203 string const s = p.plainEnvironment("CJK");
2204 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
2207 if (snip == "\\" || is_known(snip, known_escaped_chars))
2208 output_ert_inset(os, snip, parent_context);
2209 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
2214 output_ert_inset(os, "\\end{" + name + "}",
2218 supported_CJK_languages[where - supported_CJK_encodings];
2219 // store the language because we must reset it at the end
2220 string const lang_old = parent_context.font.language;
2221 parent_context.font.language = lang;
2222 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2223 parent_context.font.language = lang_old;
2224 parent_context.new_paragraph(os);
2226 p.setEncoding(encoding_old);
2231 if (name == "lyxgreyedout") {
2232 eat_whitespace(p, os, parent_context, false);
2233 parent_context.check_layout(os);
2234 begin_inset(os, "Note Greyedout\n");
2235 os << "status open\n";
2236 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2239 if (!preamble.notefontcolor().empty())
2240 preamble.registerAutomaticallyLoadedPackage("color");
2244 if (name == "btSect") {
2245 eat_whitespace(p, os, parent_context, false);
2246 parent_context.check_layout(os);
2247 begin_command_inset(os, "bibtex", "bibtex");
2248 string bibstyle = "plain";
2250 bibstyle = p.getArg('[', ']');
2251 p.skip_spaces(true);
2253 string const bibfile = p.getArg('{', '}');
2254 eat_whitespace(p, os, parent_context, false);
2255 Token t = p.get_token();
2256 if (t.asInput() == "\\btPrintCited") {
2257 p.skip_spaces(true);
2258 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2260 if (t.asInput() == "\\btPrintNotCited") {
2261 p.skip_spaces(true);
2262 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2264 if (t.asInput() == "\\btPrintAll") {
2265 p.skip_spaces(true);
2266 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2268 os << "bibfiles " << '"' << bibfile << "\"\n"
2269 << "options " << '"' << bibstyle << "\"\n";
2270 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2276 if (name == "btUnit") {
2277 string const nt = p.next_next_token().cs();
2278 // Do not attempt to overwrite a former diverging multibib.
2279 // Those are output as ERT instead.
2280 if ((nt == "part" || nt == "chapter"
2281 || nt == "section" || nt == "subsection")
2282 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2283 parse_text(p, os, FLAG_END, outer, parent_context);
2284 preamble.multibib(nt);
2286 parse_unknown_environment(p, name, os, FLAG_END, outer,
2291 // This is only attempted at turn environments that consist only
2292 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2293 // Thus we will fall through in other cases.
2294 if (name == "turn") {
2295 // We check if the next thing is a tabular[*|x]
2297 p.getArg('{', '}');// eat turn argument
2298 bool found_end = false;
2299 bool only_table = false;
2300 bool end_table = false;
2303 string envname = p.getArg('{', '}');
2304 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2305 // Now we check if the table is the only content
2306 // of the turn environment
2307 string const tenv = envname;
2308 while (!found_end && !end_table && p.good()) {
2309 envname = p.next_token().cat() == catBegin
2310 ? p.getArg('{', '}') : string();
2311 Token const & t = p.get_token();
2313 end_table = t.asInput() != "\\end"
2315 found_end = t.asInput() == "\\end"
2316 && envname == "turn";
2320 envname = p.getArg('{', '}');
2321 only_table = p.next_next_token().asInput() == "\\end"
2322 && envname == "turn";
2326 string const angle = p.getArg('{', '}');
2328 int const save_tablerotation = parent_context.tablerotation;
2329 parent_context.tablerotation = convert<int>(angle);
2330 parse_text(p, os, FLAG_END, outer, parent_context);
2331 parent_context.tablerotation = save_tablerotation;
2341 // This is only attempted at landscape environments that consist only
2342 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2343 // Other landscape environment is handled via the landscape module, thus
2344 // we will fall through in that case.
2345 if (name == "landscape") {
2346 // We check if the next thing is a longtable
2348 bool found_end = false;
2349 bool only_longtable = false;
2350 bool end_longtable = false;
2353 string envname = p.getArg('{', '}');
2354 if (envname == "longtable" || envname == "xltabular") {
2355 // Now we check if the longtable is the only content
2356 // of the landscape environment
2357 string const ltenv = envname;
2358 while (!found_end && !end_longtable && p.good()) {
2359 envname = p.next_token().cat() == catBegin
2360 ? p.getArg('{', '}') : string();
2361 Token const & t = p.get_token();
2363 end_longtable = t.asInput() != "\\end"
2364 && envname == ltenv;
2365 found_end = t.asInput() == "\\end"
2366 && envname == "landscape";
2368 if (end_longtable) {
2370 envname = p.getArg('{', '}');
2371 only_longtable = p.next_next_token().asInput() == "\\end"
2372 && envname == "landscape";
2374 if (only_longtable) {
2377 int const save_tablerotation = parent_context.tablerotation;
2378 parent_context.tablerotation = 90;
2379 parse_text(p, os, FLAG_END, outer, parent_context);
2380 parent_context.tablerotation = save_tablerotation;
2390 if (name == "framed" || name == "shaded") {
2391 eat_whitespace(p, os, parent_context, false);
2392 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2394 preamble.registerAutomaticallyLoadedPackage("framed");
2398 if (name == "listing") {
2399 minted_float = "float";
2400 eat_whitespace(p, os, parent_context, false);
2401 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2403 minted_float += "=" + opt;
2404 // If something precedes \begin{minted}, we output it at the end
2405 // as a caption, in order to keep it inside the listings inset.
2406 eat_whitespace(p, os, parent_context, true);
2408 Token const & t = p.get_token();
2409 p.skip_spaces(true);
2410 string const envname = p.next_token().cat() == catBegin
2411 ? p.getArg('{', '}') : string();
2412 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2414 minted_float_has_caption = false;
2415 string content = parse_text_snippet(p, FLAG_END, outer,
2417 size_t i = content.find("\\begin_inset listings");
2418 bool minted_env = i != string::npos;
2421 caption = content.substr(0, i);
2422 content.erase(0, i);
2424 parent_context.check_layout(os);
2425 if (minted_env && minted_float_has_caption) {
2426 eat_whitespace(p, os, parent_context, true);
2427 os << content << "\n";
2428 if (!caption.empty())
2429 os << caption << "\n";
2430 os << "\n\\end_layout\n"; // close inner layout
2431 end_inset(os); // close caption inset
2432 os << "\n\\end_layout\n"; // close outer layout
2433 } else if (!caption.empty()) {
2435 begin_inset(os, "listings\n");
2436 os << "lstparams " << '"' << minted_float << '"' << '\n';
2437 os << "inline false\n";
2438 os << "status collapsed\n";
2440 os << "\n\\begin_layout Plain Layout\n";
2441 begin_inset(os, "Caption Standard\n");
2442 Context newcontext(true, parent_context.textclass,
2443 0, 0, parent_context.font);
2444 newcontext.check_layout(os);
2445 os << caption << "\n";
2446 newcontext.check_end_layout(os);
2448 os << "\n\\end_layout\n";
2449 } else if (content.empty()) {
2450 begin_inset(os, "listings\n");
2451 os << "lstparams " << '"' << minted_float << '"' << '\n';
2452 os << "inline false\n";
2453 os << "status collapsed\n";
2455 os << content << "\n";
2457 end_inset(os); // close listings inset
2458 parent_context.check_end_layout(os);
2459 parent_context.new_paragraph(os);
2461 minted_float.clear();
2462 minted_float_has_caption = false;
2466 if (name == "lstlisting" || name == "minted") {
2467 bool use_minted = name == "minted";
2468 // with listings, we do not eat newlines here since
2469 // \begin{lstlistings}
2472 // // \begin{lstlistings}%
2475 // reads [foo] as content, whereas
2476 // // \begin{lstlistings}%
2479 // \begin{lstlistings}[foo,
2481 // reads [foo...] as argument.
2482 eat_whitespace(p, os, parent_context, false, use_minted);
2483 if (use_minted && minted_float.empty()) {
2484 // look ahead for a bottom caption
2486 bool found_end_minted = false;
2487 while (!found_end_minted && p.good()) {
2488 Token const & t = p.get_token();
2490 string const envname =
2491 p.next_token().cat() == catBegin
2492 ? p.getArg('{', '}') : string();
2493 found_end_minted = t.asInput() == "\\end"
2494 && envname == "minted";
2496 eat_whitespace(p, os, parent_context, true);
2497 Token const & t = p.get_token();
2498 p.skip_spaces(true);
2499 if (t.asInput() == "\\lyxmintcaption") {
2500 string const pos = p.getArg('[', ']');
2502 string const caption =
2503 parse_text_snippet(p, FLAG_ITEM,
2504 false, parent_context);
2505 minted_nonfloat_caption = "[b]" + caption;
2506 eat_whitespace(p, os, parent_context, true);
2511 parse_listings(p, os, parent_context, false, use_minted);
2516 if (!parent_context.new_layout_allowed) {
2517 parse_unknown_environment(p, name, os, FLAG_END, outer,
2522 // Alignment and spacing settings
2523 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2524 // therefore are totally broken!
2525 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2526 // they are commands not environments. They are furthermore switches that
2527 // can be ended by another switches, but also by commands like \footnote or
2528 // \parbox. So the only safe way is to leave them untouched.
2529 // However, we support the pseudo-environments
2530 // \begin{centering} ... \end{centering}
2531 // \begin{raggedright} ... \end{raggedright}
2532 // \begin{raggedleft} ... \end{raggedleft}
2533 // since they are used by LyX in floats (for spacing reasons)
2534 if (name == "center" || name == "centering"
2535 || name == "flushleft" || name == "raggedright"
2536 || name == "flushright" || name == "raggedleft"
2537 || name == "singlespace" || name == "onehalfspace"
2538 || name == "doublespace" || name == "spacing") {
2539 eat_whitespace(p, os, parent_context, false);
2540 // We must begin a new paragraph if not already done
2541 if (! parent_context.atParagraphStart()) {
2542 parent_context.check_end_layout(os);
2543 parent_context.new_paragraph(os);
2545 if (name == "flushleft" || name == "raggedright")
2546 parent_context.add_extra_stuff("\\align left\n");
2547 else if (name == "flushright" || name == "raggedleft")
2548 parent_context.add_extra_stuff("\\align right\n");
2549 else if (name == "center" || name == "centering")
2550 parent_context.add_extra_stuff("\\align center\n");
2551 else if (name == "singlespace")
2552 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2553 else if (name == "onehalfspace") {
2554 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2555 preamble.registerAutomaticallyLoadedPackage("setspace");
2556 } else if (name == "doublespace") {
2557 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2558 preamble.registerAutomaticallyLoadedPackage("setspace");
2559 } else if (name == "spacing") {
2560 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2561 preamble.registerAutomaticallyLoadedPackage("setspace");
2563 parse_text(p, os, FLAG_END, outer, parent_context);
2564 // Just in case the environment is empty
2565 parent_context.extra_stuff.erase();
2566 // We must begin a new paragraph to reset the alignment
2567 parent_context.new_paragraph(os);
2572 // The single '=' is meant here.
2573 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2574 eat_whitespace(p, os, parent_context, false);
2575 Context context(true, parent_context.textclass, newlayout,
2576 parent_context.layout, parent_context.font);
2577 if (parent_context.deeper_paragraph) {
2578 // We are beginning a nested environment after a
2579 // deeper paragraph inside the outer list environment.
2580 // Therefore we don't need to output a "begin deeper".
2581 context.need_end_deeper = true;
2583 parent_context.check_end_layout(os);
2584 if (last_env == name) {
2585 // we need to output a separator since LyX would export
2586 // the two environments as one otherwise (bug 5716)
2587 TeX2LyXDocClass const & textclass(parent_context.textclass);
2588 Context newcontext(true, textclass,
2589 &(textclass.defaultLayout()));
2590 newcontext.check_layout(os);
2591 begin_inset(os, "Separator plain\n");
2593 newcontext.check_end_layout(os);
2595 switch (context.layout->latextype) {
2596 case LATEX_LIST_ENVIRONMENT:
2597 context.in_list_preamble =
2598 !context.layout->listpreamble().empty()
2599 && p.hasListPreamble(context.layout->itemcommand());
2600 context.add_par_extra_stuff("\\labelwidthstring "
2601 + p.verbatim_item() + '\n');
2604 case LATEX_BIB_ENVIRONMENT:
2605 p.verbatim_item(); // swallow next arg
2611 context.check_deeper(os);
2612 if (newlayout->keepempty) {
2613 // We need to start a new paragraph
2614 // even if it is empty.
2615 context.new_paragraph(os);
2616 context.check_layout(os);
2618 // handle known optional and required arguments
2619 if (context.layout->latextype == LATEX_ENVIRONMENT)
2620 output_arguments(os, p, outer, false, string(), context,
2621 context.layout->latexargs());
2622 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2623 context.in_list_preamble =
2624 !context.layout->listpreamble().empty()
2625 && p.hasListPreamble(context.layout->itemcommand());
2627 output_arguments(oss, p, outer, false, string(), context,
2628 context.layout->latexargs());
2629 context.list_extra_stuff = oss.str();
2631 if (context.in_list_preamble) {
2632 // Collect the stuff between \begin and first \item
2633 context.list_preamble =
2634 parse_text_snippet(p, FLAG_END, outer, context);
2635 context.in_list_preamble = false;
2637 parse_text(p, os, FLAG_END, outer, context);
2638 if (context.layout->latextype == LATEX_ENVIRONMENT)
2639 output_arguments(os, p, outer, false, "post", context,
2640 context.layout->postcommandargs());
2641 context.check_end_layout(os);
2642 if (parent_context.deeper_paragraph) {
2643 // We must suppress the "end deeper" because we
2644 // suppressed the "begin deeper" above.
2645 context.need_end_deeper = false;
2647 context.check_end_deeper(os);
2648 parent_context.new_paragraph(os);
2650 if (!preamble.titleLayoutFound())
2651 preamble.titleLayoutFound(newlayout->intitle);
2652 set<string> const & req = newlayout->required();
2653 set<string>::const_iterator it = req.begin();
2654 set<string>::const_iterator en = req.end();
2655 for (; it != en; ++it)
2656 preamble.registerAutomaticallyLoadedPackage(*it);
2660 // The single '=' is meant here.
2661 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2662 eat_whitespace(p, os, parent_context, false);
2663 parent_context.check_layout(os);
2664 begin_inset(os, "Flex ");
2665 docstring flex_name = newinsetlayout->name();
2666 // FIXME: what do we do if the prefix is not Flex: ?
2667 if (prefixIs(flex_name, from_ascii("Flex:")))
2668 flex_name.erase(0, 5);
2669 os << to_utf8(flex_name) << '\n'
2670 << "status collapsed\n";
2671 if (newinsetlayout->isPassThru()) {
2672 string const arg = p.verbatimEnvironment(name);
2673 Context context(true, parent_context.textclass,
2674 &parent_context.textclass.plainLayout(),
2675 parent_context.layout);
2676 output_ert(os, arg, parent_context);
2678 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2683 if (name == "appendix") {
2684 // This is no good latex style, but it works and is used in some documents...
2685 eat_whitespace(p, os, parent_context, false);
2686 parent_context.check_end_layout(os);
2687 Context context(true, parent_context.textclass, parent_context.layout,
2688 parent_context.layout, parent_context.font);
2689 context.check_layout(os);
2690 os << "\\start_of_appendix\n";
2691 parse_text(p, os, FLAG_END, outer, context);
2692 context.check_end_layout(os);
2697 if (known_environments.find(name) != known_environments.end()) {
2698 vector<ArgumentType> arguments = known_environments[name];
2699 // The last "argument" denotes whether we may translate the
2700 // environment contents to LyX
2701 // The default required if no argument is given makes us
2702 // compatible with the reLyXre environment.
2703 ArgumentType contents = arguments.empty() ?
2706 if (!arguments.empty())
2707 arguments.pop_back();
2708 // See comment in parse_unknown_environment()
2709 bool const specialfont =
2710 (parent_context.font != parent_context.normalfont);
2711 bool const new_layout_allowed =
2712 parent_context.new_layout_allowed;
2714 parent_context.new_layout_allowed = false;
2715 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2716 outer, parent_context);
2717 if (contents == verbatim)
2718 output_ert_inset(os, p.ertEnvironment(name),
2721 parse_text_snippet(p, os, FLAG_END, outer,
2723 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2725 parent_context.new_layout_allowed = new_layout_allowed;
2729 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2734 active_environments.pop_back();
2738 /// parses a comment and outputs it to \p os.
2739 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2740 bool skipNewlines = false)
2742 LASSERT(t.cat() == catComment, return);
2743 string comment = t.cs();
2744 // Join multiple consecutive comment lines into one ERT inset
2745 while (p.next_token().cat() == catComment)
2746 comment += "\n%" + p.get_token().cs();
2748 if (!comment.empty()) {
2749 context.check_layout(os);
2750 output_comment(p, os, comment, context);
2751 if (p.next_token().cat() == catNewline) {
2752 // A newline after a comment line starts a new
2754 if (context.new_layout_allowed) {
2755 if(!context.atParagraphStart())
2756 // Only start a new paragraph if not already
2757 // done (we might get called recursively)
2758 context.new_paragraph(os);
2760 output_ert_inset(os, "\n", context);
2761 eat_whitespace(p, os, context, true);
2763 } else if (!skipNewlines) {
2764 // "%\n" combination
2771 * Reads spaces and comments until the first non-space, non-comment token.
2772 * New paragraphs (double newlines or \\par) are handled like simple spaces
2773 * if \p eatParagraph is true.
2774 * If \p eatNewline is false, newlines won't be treated as whitespace.
2775 * Spaces are skipped, but comments are written to \p os.
2777 void eat_whitespace(Parser & p, ostream & os, Context & context,
2778 bool eatParagraph, bool eatNewline)
2781 Token const & t = p.get_token();
2782 if (t.cat() == catComment)
2783 parse_comment(p, os, t, context, !eatNewline);
2784 else if ((!eatParagraph && p.isParagraph()) ||
2785 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2794 * Set a font attribute, parse text and reset the font attribute.
2795 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2796 * \param currentvalue Current value of the attribute. Is set to the new
2797 * value during parsing.
2798 * \param newvalue New value of the attribute
2800 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2801 Context & context, string const & attribute,
2802 string & currentvalue, string const & newvalue)
2804 context.check_layout(os);
2805 string const oldvalue = currentvalue;
2806 currentvalue = newvalue;
2807 os << '\n' << attribute << ' ' << newvalue << "\n";
2808 parse_text_snippet(p, os, flags, outer, context);
2809 context.check_layout(os);
2810 os << '\n' << attribute << ' ' << oldvalue << "\n";
2811 currentvalue = oldvalue;
2815 /// get the arguments of a natbib or jurabib citation command
2816 void get_cite_arguments(Parser & p, bool natbibOrder,
2817 string & before, string & after, bool const qualified = false)
2819 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2821 // text before the citation
2823 // text after the citation
2824 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2826 if (!after.empty()) {
2827 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2828 if (natbibOrder && !before.empty())
2829 swap(before, after);
2834 void copy_file(FileName const & src, string const & dstname)
2838 string const absParent = getParentFilePath(false);
2840 if (FileName::isAbsolute(dstname))
2841 dst = FileName(dstname);
2843 dst = makeAbsPath(dstname, absParent);
2844 FileName const srcpath = src.onlyPath();
2845 FileName const dstpath = dst.onlyPath();
2846 if (equivalent(srcpath, dstpath))
2848 if (!dstpath.isDirectory()) {
2849 if (!dstpath.createPath()) {
2850 warning_message("Could not create directory for file `"
2851 + dst.absFileName() + "´.");
2855 if (dst.isReadableFile()) {
2856 if (overwriteFiles())
2857 warning_message("Overwriting existing file `"
2858 + dst.absFileName() + "´.");
2860 warning_message("Not overwriting existing file `"
2861 + dst.absFileName() + "´.");
2865 if (!src.copyTo(dst))
2866 warning_message("Could not copy file `" + src.absFileName()
2867 + "´ to `" + dst.absFileName() + "´.");
2871 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2872 bool parse_chunk(Parser & p, ostream & os, Context & context)
2874 // check whether a chunk is possible here.
2875 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2881 // read the parameters
2882 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2883 if (!params.first) {
2888 Parser::Arg const code = p.verbatimStuff("\n@");
2893 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2894 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2898 // The last newline read is important for paragraph handling
2902 //warning_message("params=[" + params.second + "], code=[" + code.second + "]");
2903 // We must have a valid layout before outputting the Chunk inset.
2904 context.check_layout(os);
2905 Context chunkcontext(true, context.textclass);
2906 chunkcontext.layout = &context.textclass.plainLayout();
2907 begin_inset(os, "Flex Chunk");
2908 os << "\nstatus open\n";
2909 if (!params.second.empty()) {
2910 chunkcontext.check_layout(os);
2911 Context paramscontext(true, context.textclass);
2912 paramscontext.layout = &context.textclass.plainLayout();
2913 begin_inset(os, "Argument 1");
2914 os << "\nstatus open\n";
2915 output_ert(os, params.second, paramscontext);
2918 output_ert(os, code.second, chunkcontext);
2926 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2927 bool is_macro(Parser & p)
2929 Token first = p.curr_token();
2930 if (first.cat() != catEscape || !p.good())
2932 if (first.cs() == "def")
2934 if (first.cs() != "global" && first.cs() != "long")
2936 Token second = p.get_token();
2938 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2939 second.cat() == catNewline || second.cat() == catComment)) {
2940 second = p.get_token();
2943 bool secondvalid = second.cat() == catEscape;
2945 bool thirdvalid = false;
2946 if (p.good() && first.cs() == "global" && secondvalid &&
2947 second.cs() == "long") {
2948 third = p.get_token();
2950 while (p.good() && !p.isParagraph() &&
2951 (third.cat() == catSpace ||
2952 third.cat() == catNewline ||
2953 third.cat() == catComment)) {
2954 third = p.get_token();
2957 thirdvalid = third.cat() == catEscape;
2959 for (int i = 0; i < pos; ++i)
2964 return (first.cs() == "global" || first.cs() == "long") &&
2965 second.cs() == "def";
2966 return first.cs() == "global" && second.cs() == "long" &&
2967 third.cs() == "def";
2971 /// Parse a macro definition (assumes that is_macro() returned true)
2972 void parse_macro(Parser & p, ostream & os, Context & context)
2974 context.check_layout(os);
2975 Token first = p.curr_token();
2978 string command = first.asInput();
2979 if (first.cs() != "def") {
2981 eat_whitespace(p, os, context, false);
2982 second = p.curr_token();
2983 command += second.asInput();
2984 if (second.cs() != "def") {
2986 eat_whitespace(p, os, context, false);
2987 third = p.curr_token();
2988 command += third.asInput();
2991 eat_whitespace(p, os, context, false);
2992 string const name = p.get_token().cs();
2993 eat_whitespace(p, os, context, false);
2999 while (p.next_token().cat() != catBegin) {
3000 if (p.next_token().cat() == catParameter) {
3005 // followed by number?
3006 if (p.next_token().cat() == catOther) {
3007 string s = p.get_token().asInput();
3009 // number = current arity + 1?
3010 if (s.size() == 1 && s[0] == arity + '0' + 1)
3015 paramtext += p.get_token().cs();
3017 paramtext += p.get_token().cs();
3022 // only output simple (i.e. compatible) macro as FormulaMacros
3023 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
3025 context.check_layout(os);
3026 begin_inset(os, "FormulaMacro");
3027 os << "\n\\def" << ert;
3030 output_ert_inset(os, command + ert, context);
3034 void registerExternalTemplatePackages(string const & name)
3036 external::TemplateManager const & etm = external::TemplateManager::get();
3037 external::Template const * const et = etm.getTemplateByName(name);
3040 external::Template::Formats::const_iterator cit = et->formats.end();
3042 cit = et->formats.find("PDFLaTeX");
3043 if (cit == et->formats.end())
3044 // If the template has not specified a PDFLaTeX output,
3045 // we try the LaTeX format.
3046 cit = et->formats.find("LaTeX");
3047 if (cit == et->formats.end())
3049 vector<string>::const_iterator qit = cit->second.requirements.begin();
3050 vector<string>::const_iterator qend = cit->second.requirements.end();
3051 for (; qit != qend; ++qit)
3052 preamble.registerAutomaticallyLoadedPackage(*qit);
3055 } // anonymous namespace
3059 * Find a file with basename \p name in path \p path and an extension
3062 string find_file(string const & name, string const & path,
3063 char const * const * extensions)
3065 for (char const * const * what = extensions; *what; ++what) {
3066 string const trial = addExtension(name, *what);
3067 if (makeAbsPath(trial, path).exists())
3074 /// Convert filenames with TeX macros and/or quotes to something LyX
3076 string const normalize_filename(string const & name)
3081 Token const & t = p.get_token();
3082 if (t.cat() != catEscape)
3084 else if (t.cs() == "lyxdot") {
3085 // This is used by LyX for simple dots in relative
3089 } else if (t.cs() == "space") {
3092 } else if (t.cs() == "string") {
3093 // Convert \string" to " and \string~ to ~
3094 Token const & n = p.next_token();
3095 if (n.asInput() != "\"" && n.asInput() != "~")
3100 // Strip quotes. This is a bit complicated (see latex_path()).
3101 string full = os.str();
3102 if (!full.empty() && full[0] == '"') {
3103 string base = removeExtension(full);
3104 string ext = getExtension(full);
3105 if (!base.empty() && base[base.length()-1] == '"')
3108 return addExtension(trim(base, "\""), ext);
3109 if (full[full.length()-1] == '"')
3112 return trim(full, "\"");
3118 /// Convert \p name from TeX convention (relative to master file) to LyX
3119 /// convention (relative to .lyx file) if it is relative
3120 void fix_child_filename(string & name)
3122 string const absMasterTeX = getMasterFilePath(true);
3123 bool const isabs = FileName::isAbsolute(name);
3124 // convert from "relative to .tex master" to absolute original path
3126 name = makeAbsPath(name, absMasterTeX).absFileName();
3127 bool copyfile = copyFiles();
3128 string const absParentLyX = getParentFilePath(false);
3131 // convert from absolute original path to "relative to master file"
3132 string const rel = to_utf8(makeRelPath(from_utf8(name),
3133 from_utf8(absMasterTeX)));
3134 // re-interpret "relative to .tex file" as "relative to .lyx file"
3135 // (is different if the master .lyx file resides in a
3136 // different path than the master .tex file)
3137 string const absMasterLyX = getMasterFilePath(false);
3138 abs = makeAbsPath(rel, absMasterLyX).absFileName();
3139 // Do not copy if the new path is impossible to create. Example:
3140 // absMasterTeX = "/foo/bar/"
3141 // absMasterLyX = "/bar/"
3142 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
3143 if (contains(name, "/../"))
3150 // convert from absolute original path to
3151 // "relative to .lyx file"
3152 name = to_utf8(makeRelPath(from_utf8(abs),
3153 from_utf8(absParentLyX)));
3157 // convert from absolute original path to "relative to .lyx file"
3158 name = to_utf8(makeRelPath(from_utf8(name),
3159 from_utf8(absParentLyX)));
3164 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
3165 Context & context, string const & rdelim, string const & rdelimesc)
3167 Layout const * newlayout = 0;
3168 InsetLayout const * newinsetlayout = 0;
3169 char const * const * where = 0;
3170 // Store the latest bibliographystyle, addcontentslineContent and
3171 // nocite{*} option (needed for bibtex inset)
3173 string contentslineContent;
3174 // Some classes provide a \bibliographystyle, so do not output
3175 // any if none is explicitly set.
3176 string bibliographystyle;
3177 bool const use_natbib = isProvided("natbib");
3178 bool const use_jurabib = isProvided("jurabib");
3179 bool const use_biblatex = isProvided("biblatex")
3180 && preamble.citeEngine() != "biblatex-natbib";
3181 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
3182 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
3183 need_commentbib = use_biblatex || use_biblatex_natbib;
3186 // it is impossible to determine the correct encoding for non-CJK Japanese.
3187 // Therefore write a note at the beginning of the document
3188 if (is_nonCJKJapanese) {
3189 context.check_layout(os);
3190 begin_inset(os, "Note Note\n");
3191 os << "status open\n\\begin_layout Plain Layout\n"
3192 << "\\series bold\n"
3193 << "Important information:\n"
3194 << "\\end_layout\n\n"
3195 << "\\begin_layout Plain Layout\n"
3196 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
3197 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
3198 << " The iconv encoding " << p.getEncoding() << " was used.\n"
3199 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
3200 << " and specify the encoding using the -e command-line switch.\n"
3201 << " In addition, you might want to double check that the desired output encoding\n"
3202 << " is correctly selected in Document > Settings > Language.\n"
3203 << "\\end_layout\n";
3205 is_nonCJKJapanese = false;
3208 bool have_cycled = false;
3210 // Leave here only after at least one cycle
3211 if (have_cycled && flags & FLAG_LEAVE) {
3212 flags &= ~FLAG_LEAVE;
3216 Token const & t = p.get_token();
3218 debugToken(cerr, t, flags);
3221 if (context.in_list_preamble
3222 && p.next_token().cs() == context.layout->itemcommand()) {
3223 // We are parsing a list preamble. End before first \item.
3224 flags |= FLAG_LEAVE;
3225 context.in_list_preamble = false;
3228 if (flags & FLAG_ITEM) {
3229 if (t.cat() == catSpace)
3232 flags &= ~FLAG_ITEM;
3233 if (t.cat() == catBegin) {
3234 // skip the brace and collect everything to the next matching
3236 flags |= FLAG_BRACE_LAST;
3240 // handle only this single token, leave the loop if done
3241 flags |= FLAG_LEAVE;
3244 if (t.cat() != catEscape && t.character() == ']' &&
3245 (flags & FLAG_BRACK_LAST))
3247 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
3249 string tok = t.asInput();
3250 // we only support delimiters with max 2 chars for now.
3251 if (rdelim.size() > 1)
3252 tok += p.next_token().asInput();
3253 if (t.cat() != catEscape && !rdelim.empty()
3254 && tok == rdelim && (flags & FLAG_RDELIM)
3255 && (rdelimesc.empty() || p.prev_token().asInput() != rdelimesc)) {
3256 if (rdelim.size() > 1)
3257 p.get_token(); // eat rdelim
3261 // If there is anything between \end{env} and \begin{env} we
3262 // don't need to output a separator.
3263 if (t.cat() != catSpace && t.cat() != catNewline &&
3264 t.asInput() != "\\begin")
3271 bool const starred = p.next_token().asInput() == "*";
3272 string const starredname(starred ? (t.cs() + '*') : t.cs());
3273 if (t.cat() == catMath) {
3274 // we are inside some text mode thingy, so opening new math is allowed
3275 context.check_layout(os);
3276 begin_inset(os, "Formula ");
3277 Token const & n = p.get_token();
3278 bool const display(n.cat() == catMath && outer);
3280 // TeX's $$...$$ syntax for displayed math
3282 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3284 p.get_token(); // skip the second '$' token
3286 // simple $...$ stuff
3289 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3294 // Prevent the conversion of a line break to a
3295 // space (bug 7668). This does not change the
3296 // output, but looks ugly in LyX.
3297 eat_whitespace(p, os, context, false);
3302 if (t.cat() == catSuper || t.cat() == catSub) {
3303 string const cc = (t.cat() == catSuper) ? "catSuper" : "catSub";
3304 warning_message("catcode " + cc + " illegal in text mode");
3308 // Basic support for quotes. We try to disambiguate
3309 // quotes from the context (e.g., a left english quote is
3310 // the same as a right german quote...).
3311 // Try to make a smart guess about the side
3312 Token const prev = p.prev_token();
3313 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3314 && prev.character() != '\n' && prev.character() != '~');
3315 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3316 context.check_layout(os);
3317 begin_inset(os, "Quotes ");
3318 os << guessQuoteStyle("eld", opening);
3324 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3325 context.check_layout(os);
3326 begin_inset(os, "Quotes ");
3327 os << guessQuoteStyle("erd", opening);
3334 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3335 context.check_layout(os);
3336 begin_inset(os, "Quotes ");
3337 os << guessQuoteStyle("ald", opening);
3344 if (t.asInput() == "<"
3345 && p.next_token().asInput() == "<") {
3346 bool has_chunk = false;
3350 has_chunk = parse_chunk(p, os, context);
3356 context.check_layout(os);
3357 begin_inset(os, "Quotes ");
3358 os << guessQuoteStyle("ard", opening);
3366 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3367 check_space(p, os, context);
3371 // babel shorthands (also used by polyglossia)
3372 // Since these can have different meanings for different languages
3373 // we import them as ERT (but they must be put in ERT to get output
3375 if (t.asInput() == "\"") {
3377 // We put the known shorthand pairs together in
3378 // one ERT inset. In other cases (such as "a), only
3379 // the quotation mark is ERTed.
3380 if (is_known(p.next_token().asInput(), known_babel_shorthands)) {
3381 s += p.next_token().asInput();
3384 output_ert_inset(os, s, context);
3388 if (t.character() == '[' && noweb_mode &&
3389 p.next_token().character() == '[') {
3390 // These can contain underscores
3392 string const s = p.getFullOpt() + ']';
3393 if (p.next_token().character() == ']')
3396 warning_message("Inserting missing ']' in '" + s + "'.");
3397 output_ert_inset(os, s, context);
3401 if (t.cat() == catLetter) {
3402 context.check_layout(os);
3407 if (t.cat() == catOther ||
3408 t.cat() == catAlign ||
3409 t.cat() == catParameter) {
3410 context.check_layout(os);
3411 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3412 context.merging_hyphens_allowed &&
3413 context.font.family != "ttfamily" &&
3414 !context.layout->pass_thru) {
3415 if (p.next_next_token().asInput() == "-") {
3417 os << to_utf8(docstring(1, 0x2014));
3421 os << to_utf8(docstring(1, 0x2013));
3424 // This translates "&" to "\\&" which may be wrong...
3429 if (p.isParagraph()) {
3430 // In minted floating listings we will collect
3431 // everything into the caption, where multiple
3432 // paragraphs are forbidden.
3433 if (minted_float.empty()) {
3434 if (context.new_layout_allowed)
3435 context.new_paragraph(os);
3437 output_ert_inset(os, "\\par ", context);
3440 eat_whitespace(p, os, context, true);
3444 if (t.cat() == catActive) {
3445 context.check_layout(os);
3446 if (t.character() == '~') {
3447 if (context.layout->free_spacing)
3450 begin_inset(os, "space ~\n");
3458 if (t.cat() == catBegin) {
3459 Token const next = p.next_token();
3460 Token const end = p.next_next_token();
3461 if (next.cat() == catEnd) {
3463 Token const prev = p.prev_token();
3465 if (p.next_token().character() == '`')
3466 ; // ignore it in {}``
3468 output_ert_inset(os, "{}", context);
3469 } else if (next.cat() == catEscape &&
3470 is_known(next.cs(), known_quotes) &&
3471 end.cat() == catEnd) {
3472 // Something like {\textquoteright} (e.g.
3473 // from writer2latex). We may skip the
3474 // braces here for better readability.
3475 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3477 } else if (p.next_token().asInput() == "\\ascii") {
3478 // handle the \ascii characters
3479 // (the case without braces is handled later)
3480 // the code is "{\ascii\xxx}"
3481 p.get_token(); // eat \ascii
3482 string name2 = p.get_token().asInput();
3483 p.get_token(); // eat the final '}'
3484 string const name = "{\\ascii" + name2 + "}";
3488 // get the character from unicodesymbols
3489 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3490 Encodings::TEXT_CMD, termination, rem, &req);
3492 context.check_layout(os);
3495 output_ert_inset(os,
3496 to_utf8(rem), context);
3497 for (set<string>::const_iterator it = req.begin();
3498 it != req.end(); ++it)
3499 preamble.registerAutomaticallyLoadedPackage(*it);
3501 // we did not find a non-ert version
3502 output_ert_inset(os, name, context);
3504 context.check_layout(os);
3505 // special handling of font attribute changes
3506 Token const prev = p.prev_token();
3507 TeXFont const oldFont = context.font;
3508 if (next.character() == '[' ||
3509 next.character() == ']' ||
3510 next.character() == '*') {
3512 if (p.next_token().cat() == catEnd) {
3517 output_ert_inset(os, "{", context);
3518 parse_text_snippet(p, os,
3521 output_ert_inset(os, "}", context);
3523 } else if (! context.new_layout_allowed) {
3524 output_ert_inset(os, "{", context);
3525 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3527 output_ert_inset(os, "}", context);
3528 } else if (is_known(next.cs(), known_sizes)) {
3529 // next will change the size, so we must
3531 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3533 if (!context.atParagraphStart())
3535 << context.font.size << "\n";
3536 } else if (is_known(next.cs(), known_font_families)) {
3537 // next will change the font family, so we
3538 // must reset it here
3539 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3541 if (!context.atParagraphStart())
3543 << context.font.family << "\n";
3544 } else if (is_known(next.cs(), known_font_series)) {
3545 // next will change the font series, so we
3546 // must reset it here
3547 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3549 if (!context.atParagraphStart())
3551 << context.font.series << "\n";
3552 } else if (is_known(next.cs(), known_font_shapes)) {
3553 // next will change the font shape, so we
3554 // must reset it here
3555 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3557 if (!context.atParagraphStart())
3559 << context.font.shape << "\n";
3560 } else if (is_known(next.cs(), known_old_font_families) ||
3561 is_known(next.cs(), known_old_font_series) ||
3562 is_known(next.cs(), known_old_font_shapes)) {
3563 // next will change the font family, series
3564 // and shape, so we must reset it here
3565 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3567 if (!context.atParagraphStart())
3569 << context.font.family
3571 << context.font.series
3573 << context.font.shape << "\n";
3575 output_ert_inset(os, "{", context);
3576 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3578 output_ert_inset(os, "}", context);
3584 if (t.cat() == catEnd) {
3585 if (flags & FLAG_BRACE_LAST) {
3588 warning_message("stray '}' in text");
3589 output_ert_inset(os, "}", context);
3593 if (t.cat() == catComment) {
3594 parse_comment(p, os, t, context);
3599 // control sequences
3602 if (t.cs() == "(" || t.cs() == "[") {
3603 bool const simple = t.cs() == "(";
3604 context.check_layout(os);
3605 begin_inset(os, "Formula");
3606 os << " \\" << t.cs();
3607 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3608 os << '\\' << (simple ? ')' : ']');
3611 // Prevent the conversion of a line break to a
3612 // space (bug 7668). This does not change the
3613 // output, but looks ugly in LyX.
3614 eat_whitespace(p, os, context, false);
3619 if (t.cs() == "begin") {
3620 parse_environment(p, os, outer, last_env,
3625 if (t.cs() == "end") {
3626 if (flags & FLAG_END) {
3627 // eat environment name
3628 string const name = p.getArg('{', '}');
3629 if (name != active_environment())
3630 warning_message("\\end{" + name + "} does not match \\begin{"
3631 + active_environment() + "}");
3634 p.error("found 'end' unexpectedly");
3638 // "item" by default, but could be something else
3639 if (t.cs() == context.layout->itemcommand()) {
3641 if (context.layout->labeltype == LABEL_MANUAL) {
3642 // FIXME: This swallows comments, but we cannot use
3643 // eat_whitespace() since we must not output
3644 // anything before the item.
3645 p.skip_spaces(true);
3646 s = p.verbatimOption();
3648 p.skip_spaces(false);
3650 context.check_layout(os);
3651 if (context.has_item) {
3652 // An item in an unknown list-like environment
3653 // FIXME: Do this in check_layout()!
3654 context.has_item = false;
3655 string item = "\\" + context.layout->itemcommand();
3658 output_ert_inset(os, item, context);
3660 if (context.layout->labeltype != LABEL_MANUAL)
3661 output_arguments(os, p, outer, false, "item", context,
3662 context.layout->itemargs());
3663 if (!context.list_preamble.empty()) {
3664 // We have a list preamble. Output it here.
3665 begin_inset(os, "Argument listpreamble:1");
3666 os << "\nstatus collapsed\n\n"
3667 << "\\begin_layout Plain Layout\n\n"
3668 << rtrim(context.list_preamble)
3669 << "\n\\end_layout";
3671 context.list_preamble.clear();
3673 if (!context.list_extra_stuff.empty()) {
3674 os << context.list_extra_stuff;
3675 context.list_extra_stuff.clear();
3677 else if (!s.empty()) {
3678 // LyX adds braces around the argument,
3679 // so we need to remove them here.
3680 if (s.size() > 2 && s[0] == '{' &&
3681 s[s.size()-1] == '}')
3682 s = s.substr(1, s.size()-2);
3683 // If the argument contains a space we
3684 // must put it into ERT: Otherwise LyX
3685 // would misinterpret the space as
3686 // item delimiter (bug 7663)
3687 if (contains(s, ' ')) {
3688 output_ert_inset(os, s, context);
3691 os << parse_text_snippet(p2,
3692 FLAG_BRACK_LAST, outer, context);
3694 // The space is needed to separate the
3695 // item from the rest of the sentence.
3697 eat_whitespace(p, os, context, false);
3702 if (t.cs() == "bibitem") {
3704 context.check_layout(os);
3705 eat_whitespace(p, os, context, false);
3706 string label = p.verbatimOption();
3707 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3708 bool const literal = !lbl.first;
3709 label = literal ? subst(label, "\n", " ") : lbl.second;
3710 string lit = literal ? "\"true\"" : "\"false\"";
3711 string key = convert_literate_command_inset_arg(p.verbatim_item());
3712 begin_command_inset(os, "bibitem", "bibitem");
3713 os << "label \"" << label << "\"\n"
3714 << "key \"" << key << "\"\n"
3715 << "literal " << lit << "\n";
3721 // catch the case of \def\inputGnumericTable
3723 if (t.cs() == "def") {
3724 Token second = p.next_token();
3725 if (second.cs() == "inputGnumericTable") {
3729 Token third = p.get_token();
3731 if (third.cs() == "input") {
3735 string name = normalize_filename(p.verbatim_item());
3736 string const path = getMasterFilePath(true);
3737 // We want to preserve relative / absolute filenames,
3738 // therefore path is only used for testing
3739 // The file extension is in every case ".tex".
3740 // So we need to remove this extension and check for
3741 // the original one.
3742 name = removeExtension(name);
3743 if (!makeAbsPath(name, path).exists()) {
3744 char const * const Gnumeric_formats[] = {"gnumeric",
3746 string const Gnumeric_name =
3747 find_file(name, path, Gnumeric_formats);
3748 if (!Gnumeric_name.empty())
3749 name = Gnumeric_name;
3751 FileName const absname = makeAbsPath(name, path);
3752 if (absname.exists()) {
3753 fix_child_filename(name);
3754 copy_file(absname, name);
3756 warning_message("Could not find file '" + name + "'.");
3757 context.check_layout(os);
3758 begin_inset(os, "External\n\ttemplate ");
3759 os << "GnumericSpreadsheet\n\tfilename "
3762 context.check_layout(os);
3764 // register the packages that are automatically loaded
3765 // by the Gnumeric template
3766 registerExternalTemplatePackages("GnumericSpreadsheet");
3771 parse_macro(p, os, context);
3775 if (t.cs() == "noindent") {
3777 context.add_par_extra_stuff("\\noindent\n");
3781 if (t.cs() == "appendix" && !context.in_list_preamble) {
3782 context.add_par_extra_stuff("\\start_of_appendix\n");
3783 // We need to start a new paragraph. Otherwise the
3784 // appendix in 'bla\appendix\chapter{' would start
3786 context.new_paragraph(os);
3787 // We need to make sure that the paragraph is
3788 // generated even if it is empty. Otherwise the
3789 // appendix in '\par\appendix\par\chapter{' would
3791 context.check_layout(os);
3792 // FIXME: This is a hack to prevent paragraph
3793 // deletion if it is empty. Handle this better!
3794 output_comment(p, os,
3795 "dummy comment inserted by tex2lyx to "
3796 "ensure that this paragraph is not empty",
3798 // Both measures above may generate an additional
3799 // empty paragraph, but that does not hurt, because
3800 // whitespace does not matter here.
3801 eat_whitespace(p, os, context, true);
3805 // Must catch empty dates before findLayout is called below
3806 if (t.cs() == "date") {
3807 eat_whitespace(p, os, context, false);
3809 string const date = p.verbatim_item();
3812 preamble.suppressDate(true);
3815 preamble.suppressDate(false);
3816 if (context.new_layout_allowed &&
3817 (newlayout = findLayout(context.textclass,
3820 output_command_layout(os, p, outer,
3821 context, newlayout);
3822 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3823 if (!preamble.titleLayoutFound())
3824 preamble.titleLayoutFound(newlayout->intitle);
3825 set<string> const & req = newlayout->required();
3826 set<string>::const_iterator it = req.begin();
3827 set<string>::const_iterator en = req.end();
3828 for (; it != en; ++it)
3829 preamble.registerAutomaticallyLoadedPackage(*it);
3831 output_ert_inset(os,
3832 "\\date{" + p.verbatim_item() + '}',
3838 // Before we look for the layout name with star and alone below, we check the layouts including
3839 // the LateXParam, which might be one or several options or a star.
3840 // The single '=' is meant here.
3841 if (context.new_layout_allowed &&
3842 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3843 // store the latexparam here. This is eaten in output_command_layout
3844 context.latexparam = newlayout->latexparam();
3846 output_command_layout(os, p, outer, context, newlayout);
3847 context.latexparam.clear();
3849 if (!preamble.titleLayoutFound())
3850 preamble.titleLayoutFound(newlayout->intitle);
3851 set<string> const & req = newlayout->required();
3852 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3853 preamble.registerAutomaticallyLoadedPackage(*it);
3857 // Starred section headings
3858 // Must attempt to parse "Section*" before "Section".
3859 if ((p.next_token().asInput() == "*") &&
3860 context.new_layout_allowed &&
3861 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3864 output_command_layout(os, p, outer, context, newlayout);
3866 if (!preamble.titleLayoutFound())
3867 preamble.titleLayoutFound(newlayout->intitle);
3868 set<string> const & req = newlayout->required();
3869 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3870 preamble.registerAutomaticallyLoadedPackage(*it);
3874 // Section headings and the like
3875 if (context.new_layout_allowed &&
3876 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3878 output_command_layout(os, p, outer, context, newlayout);
3880 if (!preamble.titleLayoutFound())
3881 preamble.titleLayoutFound(newlayout->intitle);
3882 set<string> const & req = newlayout->required();
3883 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3884 preamble.registerAutomaticallyLoadedPackage(*it);
3888 if (t.cs() == "subfloat") {
3889 // the syntax is \subfloat[list entry][sub caption]{content}
3890 // if it is a table of figure depends on the surrounding float
3892 // do nothing if there is no outer float
3893 if (!float_type.empty()) {
3894 context.check_layout(os);
3896 begin_inset(os, "Float " + float_type + "\n");
3898 << "\nsideways false"
3899 << "\nstatus collapsed\n\n";
3902 bool has_caption = false;
3903 if (p.next_token().cat() != catEscape &&
3904 p.next_token().character() == '[') {
3905 p.get_token(); // eat '['
3906 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3909 // In case we have two optional args, the second is the caption.
3910 if (p.next_token().cat() != catEscape &&
3911 p.next_token().character() == '[') {
3912 p.get_token(); // eat '['
3913 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3916 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3917 // the caption comes always as the last
3919 // we must make sure that the caption gets a \begin_layout
3920 os << "\n\\begin_layout Plain Layout";
3922 begin_inset(os, "Caption Standard\n");
3923 Context newcontext(true, context.textclass,
3924 0, 0, context.font);
3925 newcontext.check_layout(os);
3926 os << caption << "\n";
3927 newcontext.check_end_layout(os);
3930 // close the layout we opened
3931 os << "\n\\end_layout";
3936 // if the float type is not supported or there is no surrounding float
3941 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3943 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3945 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3946 + "{" + p.verbatim_item() + '}', context);
3951 if (t.cs() == "xymatrix") {
3952 // we must open a new math because LyX's xy support is in math
3953 context.check_layout(os);
3954 begin_inset(os, "Formula ");
3956 os << "\\" << t.cs() << '{';
3957 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3960 preamble.registerAutomaticallyLoadedPackage("xy");
3964 if (t.cs() == "includegraphics") {
3965 bool const clip = p.next_token().asInput() == "*";
3968 string const arg = p.getArg('[', ']');
3969 map<string, string> opts;
3970 vector<string> keys;
3971 split_map(arg, opts, keys);
3973 opts["clip"] = string();
3974 string name = normalize_filename(p.verbatim_item());
3976 string const path = getMasterFilePath(true);
3977 // We want to preserve relative / absolute filenames,
3978 // therefore path is only used for testing
3979 if (!makeAbsPath(name, path).exists()) {
3980 // The file extension is probably missing.
3981 // Now try to find it out.
3982 string const dvips_name =
3983 find_file(name, path,
3984 known_dvips_graphics_formats);
3985 string const pdftex_name =
3986 find_file(name, path,
3987 known_pdftex_graphics_formats);
3988 if (!dvips_name.empty()) {
3989 if (!pdftex_name.empty()) {
3990 warning_message("This file contains the "
3992 "\"\\includegraphics{" + name + "}\".\n"
3993 "However, files\n\""
3994 + dvips_name + "\" and\n\""
3995 + pdftex_name + "\"\n"
3996 "both exist, so I had to make a "
3997 "choice and took the first one.\n"
3998 "Please move the unwanted one "
3999 "someplace else and try again\n"
4000 "if my choice was wrong.");
4003 } else if (!pdftex_name.empty()) {
4009 FileName const absname = makeAbsPath(name, path);
4010 if (absname.exists()) {
4011 fix_child_filename(name);
4012 copy_file(absname, name);
4014 warning_message("Could not find graphics file '" + name + "'.");
4016 context.check_layout(os);
4017 begin_inset(os, "Graphics ");
4018 os << "\n\tfilename " << name << '\n';
4019 if (opts.find("width") != opts.end())
4021 << translate_len(opts["width"]) << '\n';
4022 if (opts.find("totalheight") != opts.end())
4024 << translate_len(opts["totalheight"]) << '\n';
4025 if (opts.find("scale") != opts.end()) {
4026 istringstream iss(opts["scale"]);
4030 os << "\tscale " << val << '\n';
4032 if (opts.find("angle") != opts.end()) {
4033 os << "\trotateAngle "
4034 << opts["angle"] << '\n';
4035 vector<string>::const_iterator a =
4036 find(keys.begin(), keys.end(), "angle");
4037 vector<string>::const_iterator s =
4038 find(keys.begin(), keys.end(), "width");
4039 if (s == keys.end())
4040 s = find(keys.begin(), keys.end(), "totalheight");
4041 if (s == keys.end())
4042 s = find(keys.begin(), keys.end(), "scale");
4043 if (s != keys.end() && distance(s, a) > 0)
4044 os << "\tscaleBeforeRotation\n";
4046 if (opts.find("origin") != opts.end()) {
4048 string const opt = opts["origin"];
4049 if (opt.find('l') != string::npos) ss << "left";
4050 if (opt.find('r') != string::npos) ss << "right";
4051 if (opt.find('c') != string::npos) ss << "center";
4052 if (opt.find('t') != string::npos) ss << "Top";
4053 if (opt.find('b') != string::npos) ss << "Bottom";
4054 if (opt.find('B') != string::npos) ss << "Baseline";
4055 if (!ss.str().empty())
4056 os << "\trotateOrigin " << ss.str() << '\n';
4058 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
4060 if (opts.find("keepaspectratio") != opts.end())
4061 os << "\tkeepAspectRatio\n";
4062 if (opts.find("clip") != opts.end())
4064 if (opts.find("draft") != opts.end())
4066 if (opts.find("bb") != opts.end())
4067 os << "\tBoundingBox "
4068 << opts["bb"] << '\n';
4069 int numberOfbbOptions = 0;
4070 if (opts.find("bbllx") != opts.end())
4071 numberOfbbOptions++;
4072 if (opts.find("bblly") != opts.end())
4073 numberOfbbOptions++;
4074 if (opts.find("bburx") != opts.end())
4075 numberOfbbOptions++;
4076 if (opts.find("bbury") != opts.end())
4077 numberOfbbOptions++;
4078 if (numberOfbbOptions == 4)
4079 os << "\tBoundingBox "
4080 << opts["bbllx"] << " " << opts["bblly"] << " "
4081 << opts["bburx"] << " " << opts["bbury"] << '\n';
4082 else if (numberOfbbOptions > 0)
4083 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4084 numberOfbbOptions = 0;
4085 if (opts.find("natwidth") != opts.end())
4086 numberOfbbOptions++;
4087 if (opts.find("natheight") != opts.end())
4088 numberOfbbOptions++;
4089 if (numberOfbbOptions == 2)
4090 os << "\tBoundingBox 0bp 0bp "
4091 << opts["natwidth"] << " " << opts["natheight"] << '\n';
4092 else if (numberOfbbOptions > 0)
4093 warning_message("Ignoring incomplete includegraphics boundingbox arguments.");
4094 ostringstream special;
4095 if (opts.find("hiresbb") != opts.end())
4096 special << "hiresbb,";
4097 if (opts.find("trim") != opts.end())
4099 if (opts.find("viewport") != opts.end())
4100 special << "viewport=" << opts["viewport"] << ',';
4101 if (opts.find("height") != opts.end())
4102 special << "height=" << opts["height"] << ',';
4103 if (opts.find("type") != opts.end())
4104 special << "type=" << opts["type"] << ',';
4105 if (opts.find("ext") != opts.end())
4106 special << "ext=" << opts["ext"] << ',';
4107 if (opts.find("read") != opts.end())
4108 special << "read=" << opts["read"] << ',';
4109 if (opts.find("command") != opts.end())
4110 special << "command=" << opts["command"] << ',';
4111 string s_special = special.str();
4112 if (!s_special.empty()) {
4113 // We had special arguments. Remove the trailing ','.
4114 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
4116 // TODO: Handle the unknown settings better.
4117 // Warn about invalid options.
4118 // Check whether some option was given twice.
4120 preamble.registerAutomaticallyLoadedPackage("graphicx");
4124 if (t.cs() == "footnote" ||
4125 (t.cs() == "thanks" && context.layout->intitle)) {
4127 context.check_layout(os);
4128 begin_inset(os, "Foot\n");
4129 os << "status collapsed\n\n";
4130 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4135 if (t.cs() == "marginpar") {
4137 context.check_layout(os);
4138 begin_inset(os, "Marginal\n");
4139 os << "status collapsed\n\n";
4140 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
4145 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
4146 bool const use_minted = t.cs() == "mintinline";
4148 parse_listings(p, os, context, true, use_minted);
4152 if (t.cs() == "ensuremath") {
4154 context.check_layout(os);
4155 string const s = p.verbatim_item();
4156 //FIXME: this never triggers in UTF8
4157 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
4160 output_ert_inset(os, "\\ensuremath{" + s + "}",
4165 else if (t.cs() == "makeindex"
4166 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
4167 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
4168 if (preamble.titleLayoutFound()) {
4170 skip_spaces_braces(p);
4172 output_ert_inset(os, t.asInput(), context);
4176 if (t.cs() == "tableofcontents"
4177 || t.cs() == "lstlistoflistings"
4178 || t.cs() == "listoflistings") {
4179 string name = t.cs();
4180 if (preamble.minted() && name == "listoflistings")
4181 name.insert(0, "lst");
4182 context.check_layout(os);
4183 begin_command_inset(os, "toc", name);
4185 skip_spaces_braces(p);
4186 if (name == "lstlistoflistings") {
4187 if (preamble.minted())
4188 preamble.registerAutomaticallyLoadedPackage("minted");
4190 preamble.registerAutomaticallyLoadedPackage("listings");
4195 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
4196 context.check_layout(os);
4197 if (t.cs() == "listoffigures")
4198 begin_inset(os, "FloatList figure\n");
4200 begin_inset(os, "FloatList table\n");
4202 skip_spaces_braces(p);
4206 if (t.cs() == "listof") {
4207 p.skip_spaces(true);
4208 string const name = p.verbatim_item();
4209 if (context.textclass.floats().typeExist(name)) {
4210 context.check_layout(os);
4211 begin_inset(os, "FloatList ");
4214 p.verbatim_item(); // swallow second arg
4216 output_ert_inset(os, "\\listof{" + name + "}", context);
4220 if (t.cs() == "theendnotes"
4221 || (t.cs() == "printendnotes"
4222 && p.next_token().asInput() != "*"
4224 context.check_layout(os);
4225 begin_inset(os, "FloatList endnote\n");
4227 skip_spaces_braces(p);
4231 if ((where = is_known(t.cs(), known_text_font_families))) {
4232 parse_text_attributes(p, os, FLAG_ITEM, outer,
4233 context, "\\family", context.font.family,
4234 known_coded_font_families[where - known_text_font_families]);
4238 // beamer has a \textbf<overlay>{} inset
4239 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
4240 parse_text_attributes(p, os, FLAG_ITEM, outer,
4241 context, "\\series", context.font.series,
4242 known_coded_font_series[where - known_text_font_series]);
4246 // beamer has a \textit<overlay>{} inset
4247 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4248 parse_text_attributes(p, os, FLAG_ITEM, outer,
4249 context, "\\shape", context.font.shape,
4250 known_coded_font_shapes[where - known_text_font_shapes]);
4254 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4255 context.check_layout(os);
4256 TeXFont oldFont = context.font;
4257 context.font.init();
4258 context.font.size = oldFont.size;
4259 os << "\n\\family " << context.font.family << "\n";
4260 os << "\n\\series " << context.font.series << "\n";
4261 os << "\n\\shape " << context.font.shape << "\n";
4262 if (t.cs() == "textnormal") {
4263 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4264 output_font_change(os, context.font, oldFont);
4265 context.font = oldFont;
4267 eat_whitespace(p, os, context, false);
4271 if (t.cs() == "textcolor") {
4272 // scheme is \textcolor{color name}{text}
4273 string const color = p.verbatim_item();
4274 // we support the predefined colors of the color and the xcolor package
4275 if (color == "black" || color == "blue" || color == "cyan"
4276 || color == "green" || color == "magenta" || color == "red"
4277 || color == "white" || color == "yellow") {
4278 context.check_layout(os);
4279 os << "\n\\color " << color << "\n";
4280 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4281 context.check_layout(os);
4282 os << "\n\\color inherit\n";
4283 preamble.registerAutomaticallyLoadedPackage("color");
4284 } else if (color == "brown" || color == "darkgray" || color == "gray"
4285 || color == "lightgray" || color == "lime" || color == "olive"
4286 || color == "orange" || color == "pink" || color == "purple"
4287 || color == "teal" || color == "violet") {
4288 context.check_layout(os);
4289 os << "\n\\color " << color << "\n";
4290 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4291 context.check_layout(os);
4292 os << "\n\\color inherit\n";
4293 preamble.registerAutomaticallyLoadedPackage("xcolor");
4295 // for custom defined colors
4296 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4300 if (t.cs() == "underbar" || t.cs() == "uline") {
4301 // \underbar is not 100% correct (LyX outputs \uline
4302 // of ulem.sty). The difference is that \ulem allows
4303 // line breaks, and \underbar does not.
4304 // Do NOT handle \underline.
4305 // \underbar cuts through y, g, q, p etc.,
4306 // \underline does not.
4307 context.check_layout(os);
4308 os << "\n\\bar under\n";
4309 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4310 context.check_layout(os);
4311 os << "\n\\bar default\n";
4312 preamble.registerAutomaticallyLoadedPackage("ulem");
4316 if (t.cs() == "sout") {
4317 context.check_layout(os);
4318 os << "\n\\strikeout on\n";
4319 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4320 context.check_layout(os);
4321 os << "\n\\strikeout default\n";
4322 preamble.registerAutomaticallyLoadedPackage("ulem");
4326 // beamer has an \emph<overlay>{} inset
4327 if ((t.cs() == "uuline" || t.cs() == "uwave"
4328 || t.cs() == "emph" || t.cs() == "noun"
4329 || t.cs() == "xout") && !p.hasOpt("<")) {
4330 context.check_layout(os);
4331 os << "\n\\" << t.cs() << " on\n";
4332 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4333 context.check_layout(os);
4334 os << "\n\\" << t.cs() << " default\n";
4335 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4336 preamble.registerAutomaticallyLoadedPackage("ulem");
4340 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4341 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4342 context.check_layout(os);
4345 initials = p.getArg('[', ']');
4347 string name = p.getArg('{', '}');
4348 string localtime = p.getArg('{', '}');
4349 preamble.registerAuthor(name, initials);
4350 Author const & author = preamble.getAuthor(name);
4351 // from_asctime_utc() will fail if LyX decides to output the
4352 // time in the text language.
4353 time_t ptime = from_asctime_utc(localtime);
4354 if (ptime == static_cast<time_t>(-1)) {
4355 warning_message("Could not parse time `" + localtime
4356 + "´ for change tracking, using current time instead.");
4357 ptime = current_time();
4359 if (t.cs() == "lyxadded")
4360 os << "\n\\change_inserted ";
4362 os << "\n\\change_deleted ";
4363 os << author.bufferId() << ' ' << ptime << '\n';
4364 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4365 if (LaTeXPackages::isAvailable("ulem")
4366 && LaTeXPackages::isAvailable("xcolor")) {
4367 preamble.registerAutomaticallyLoadedPackage("ulem");
4368 preamble.registerAutomaticallyLoadedPackage("xcolor");
4373 if (t.cs() == "textipa") {
4374 context.check_layout(os);
4375 begin_inset(os, "IPA\n");
4376 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4377 context.merging_hyphens_allowed = false;
4378 set<string> pass_thru_cmds = context.pass_thru_cmds;
4379 // These commands have special meanings in IPA
4380 context.pass_thru_cmds.insert("!");
4381 context.pass_thru_cmds.insert(";");
4382 context.pass_thru_cmds.insert(":");
4383 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4384 context.pass_thru_cmds = pass_thru_cmds;
4385 context.merging_hyphens_allowed = merging_hyphens_allowed;
4387 preamble.registerAutomaticallyLoadedPackage("tipa");
4388 preamble.registerAutomaticallyLoadedPackage("tipx");
4392 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4393 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4394 context.check_layout(os);
4398 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4399 begin_inset(os, "IPADeco " + type + "\n");
4400 os << "status open\n";
4401 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4407 if (t.cs() == "textvertline") {
4408 // FIXME: This is not correct, \textvertline is higher than |
4414 if (t.cs() == "tone" ) {
4415 context.check_layout(os);
4416 // register the tone package
4417 preamble.registerAutomaticallyLoadedPackage("tone");
4418 string content = trimSpaceAndEol(p.verbatim_item());
4419 string command = t.asInput() + "{" + content + "}";
4420 // some tones can be detected by unicodesymbols, some need special code
4421 if (is_known(content, known_tones)) {
4422 os << "\\IPAChar " << command << "\n";
4425 // try to see whether the string is in unicodesymbols
4429 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4430 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4431 termination, rem, &req);
4435 output_ert_inset(os, to_utf8(rem), context);
4436 for (set<string>::const_iterator it = req.begin();
4437 it != req.end(); ++it)
4438 preamble.registerAutomaticallyLoadedPackage(*it);
4440 // we did not find a non-ert version
4441 output_ert_inset(os, command, context);
4445 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4446 t.cs() == "vphantom") {
4447 context.check_layout(os);
4448 if (t.cs() == "phantom")
4449 begin_inset(os, "Phantom Phantom\n");
4450 if (t.cs() == "hphantom")
4451 begin_inset(os, "Phantom HPhantom\n");
4452 if (t.cs() == "vphantom")
4453 begin_inset(os, "Phantom VPhantom\n");
4454 os << "status open\n";
4455 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4461 if (t.cs() == "href") {
4462 context.check_layout(os);
4463 string target = convert_literate_command_inset_arg(p.verbatim_item());
4464 string name = p.verbatim_item();
4465 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4466 bool const literal = !nm.first;
4467 name = literal ? subst(name, "\n", " ") : nm.second;
4468 string lit = literal ? "\"true\"" : "\"false\"";
4470 size_t i = target.find(':');
4471 if (i != string::npos) {
4472 type = target.substr(0, i + 1);
4473 if (type == "mailto:" || type == "file:")
4474 target = target.substr(i + 1);
4475 else if (target.find("://") == string::npos)
4477 // handle the case that name is equal to target, except of "http(s)://"
4478 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4481 begin_command_inset(os, "href", "href");
4483 os << "name \"" << name << "\"\n";
4484 os << "target \"" << target << "\"\n";
4485 if (type == "mailto:" || type == "file:" || type == "other")
4486 os << "type \"" << type << "\"\n";
4487 os << "literal " << lit << "\n";
4489 skip_spaces_braces(p);
4493 if (t.cs() == "lyxline") {
4494 // swallow size argument (it is not used anyway)
4496 if (!context.atParagraphStart()) {
4497 // so our line is in the middle of a paragraph
4498 // we need to add a new line, lest this line
4499 // follow the other content on that line and
4500 // run off the side of the page
4501 // FIXME: This may create an empty paragraph,
4502 // but without that it would not be
4503 // possible to set noindent below.
4504 // Fortunately LaTeX does not care
4505 // about the empty paragraph.
4506 context.new_paragraph(os);
4508 if (preamble.indentParagraphs()) {
4509 // we need to unindent, lest the line be too long
4510 context.add_par_extra_stuff("\\noindent\n");
4512 context.check_layout(os);
4513 begin_command_inset(os, "line", "rule");
4514 os << "offset \"0.5ex\"\n"
4515 "width \"100line%\"\n"
4521 if (t.cs() == "rule") {
4522 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4523 string const width = p.getArg('{', '}');
4524 string const thickness = p.getArg('{', '}');
4525 context.check_layout(os);
4526 begin_command_inset(os, "line", "rule");
4527 if (!offset.empty())
4528 os << "offset \"" << translate_len(offset) << "\"\n";
4529 os << "width \"" << translate_len(width) << "\"\n"
4530 "height \"" << translate_len(thickness) << "\"\n";
4535 // Handle refstyle first in order to to catch \eqref, because this
4536 // can also occur without refstyle. Only recognize these commands if
4537 // refstyle.sty was found in the preamble (otherwise \eqref
4538 // and user defined ref commands could be misdetected).
4539 // We uncapitalize the input in order to catch capitalized commands
4541 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4542 && preamble.refstyle()) {
4543 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4544 string plural = "false";
4545 // Catch the plural option [s]
4547 string const opt = p.getOpt();
4551 // LyX does not yet support other optional arguments of ref commands
4552 output_ert_inset(os, t.asInput() + opt + "{" +
4553 p.verbatim_item() + '}', context);
4557 context.check_layout(os);
4558 begin_command_inset(os, "ref", "formatted");
4559 os << "reference \"";
4560 os << known_refstyle_prefixes[where - known_refstyle_commands]
4562 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4564 os << "plural \"" << plural << "\"\n";
4565 os << "caps \"" << cap << "\"\n";
4566 os << "noprefix \"false\"\n";
4568 preamble.registerAutomaticallyLoadedPackage("refstyle");
4572 // if refstyle is used, we must not convert \prettyref to a
4573 // formatted reference, since that would result in a refstyle command.
4574 if ((where = is_known(t.cs(), known_ref_commands))
4575 && (t.cs() != "prettyref" || !preamble.refstyle())
4576 && (p.next_token().asInput() != "*" || is_known(t.cs(), known_starref_commands))) {
4577 bool starred = false;
4578 if (p.next_token().asInput() == "*") {
4582 string const opt = p.getOpt();
4584 context.check_layout(os);
4585 begin_command_inset(os, "ref",
4586 known_coded_ref_commands[where - known_ref_commands]);
4587 os << "reference \""
4588 << convert_literate_command_inset_arg(p.verbatim_item())
4590 os << "plural \"false\"\n";
4591 os << "caps \"false\"\n";
4592 os << "noprefix \"false\"\n";
4594 os << "nolink \"true\"\n";
4596 os << "nolink \"false\"\n";
4598 if (t.cs() == "vref" || t.cs() == "vpageref")
4599 preamble.registerAutomaticallyLoadedPackage("varioref");
4600 else if (t.cs() == "prettyref")
4601 preamble.registerAutomaticallyLoadedPackage("prettyref");
4603 // LyX does not yet support optional arguments of ref commands
4604 output_ert_inset(os, t.asInput() + opt + "{" +
4605 p.verbatim_item() + '}', context);
4611 is_known(t.cs(), known_natbib_commands) &&
4612 ((t.cs() != "citefullauthor" &&
4613 t.cs() != "citeyear" &&
4614 t.cs() != "citeyearpar") ||
4615 p.next_token().asInput() != "*")) {
4616 context.check_layout(os);
4617 string command = t.cs();
4618 if (p.next_token().asInput() == "*") {
4622 if (command == "citefullauthor")
4623 // alternative name for "\\citeauthor*"
4624 command = "citeauthor*";
4626 // text before the citation
4628 // text after the citation
4630 get_cite_arguments(p, true, before, after);
4632 if (command == "cite") {
4633 // \cite without optional argument means
4634 // \citet, \cite with at least one optional
4635 // argument means \citep.
4636 if (before.empty() && after.empty())
4641 if (before.empty() && after == "[]")
4642 // avoid \citet[]{a}
4644 else if (before == "[]" && after == "[]") {
4645 // avoid \citet[][]{a}
4649 bool literal = false;
4650 pair<bool, string> aft;
4651 pair<bool, string> bef;
4652 // remove the brackets around after and before
4653 if (!after.empty()) {
4655 after.erase(after.length() - 1, 1);
4656 aft = convert_latexed_command_inset_arg(after);
4657 literal = !aft.first;
4658 after = literal ? subst(after, "\n", " ") : aft.second;
4660 if (!before.empty()) {
4662 before.erase(before.length() - 1, 1);
4663 bef = convert_latexed_command_inset_arg(before);
4664 literal |= !bef.first;
4665 before = literal ? subst(before, "\n", " ") : bef.second;
4666 if (literal && !after.empty())
4667 after = subst(after, "\n", " ");
4669 string lit = literal ? "\"true\"" : "\"false\"";
4670 begin_command_inset(os, "citation", command);
4671 os << "after " << '"' << after << '"' << "\n";
4672 os << "before " << '"' << before << '"' << "\n";
4674 << convert_literate_command_inset_arg(p.verbatim_item())
4676 << "literal " << lit << "\n";
4678 // Need to set the cite engine if natbib is loaded by
4679 // the document class directly
4680 if (preamble.citeEngine() == "basic")
4681 preamble.citeEngine("natbib");
4686 && is_known(t.cs(), known_biblatex_commands)
4687 && ((t.cs() == "cite"
4688 || t.cs() == "citeauthor"
4689 || t.cs() == "Citeauthor"
4690 || t.cs() == "parencite"
4691 || t.cs() == "citetitle")
4692 || p.next_token().asInput() != "*"))
4693 || (use_biblatex_natbib
4694 && (is_known(t.cs(), known_biblatex_commands)
4695 || is_known(t.cs(), known_natbib_commands))
4696 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4697 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4698 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4699 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4700 || t.cs() == "parencite" || t.cs() == "citetitle")
4701 || p.next_token().asInput() != "*"))){
4702 context.check_layout(os);
4703 string command = t.cs();
4704 if (p.next_token().asInput() == "*") {
4709 bool const qualified = suffixIs(command, "s");
4711 command = rtrim(command, "s");
4713 // text before the citation
4715 // text after the citation
4717 get_cite_arguments(p, true, before, after, qualified);
4719 // These use natbib cmd names in LyX
4720 // for inter-citeengine compativility
4721 if (command == "citeyear")
4722 command = "citebyear";
4723 else if (command == "cite*")
4724 command = "citeyear";
4725 else if (command == "textcite")
4727 else if (command == "Textcite")
4729 else if (command == "parencite")
4731 else if (command == "Parencite")
4733 else if (command == "parencite*")
4734 command = "citeyearpar";
4735 else if (command == "smartcite")
4736 command = "footcite";
4737 else if (command == "Smartcite")
4738 command = "Footcite";
4740 string const emptyarg = qualified ? "()" : "[]";
4741 if (before.empty() && after == emptyarg)
4744 else if (before == emptyarg && after == emptyarg) {
4745 // avoid \cite[][]{a}
4749 bool literal = false;
4750 pair<bool, string> aft;
4751 pair<bool, string> bef;
4752 // remove the brackets around after and before
4753 if (!after.empty()) {
4755 after.erase(after.length() - 1, 1);
4756 aft = convert_latexed_command_inset_arg(after);
4757 literal = !aft.first;
4758 after = literal ? subst(after, "\n", " ") : aft.second;
4760 if (!before.empty()) {
4762 before.erase(before.length() - 1, 1);
4763 bef = convert_latexed_command_inset_arg(before);
4764 literal |= !bef.first;
4765 before = literal ? subst(before, "\n", " ") : bef.second;
4767 string keys, pretextlist, posttextlist;
4769 vector<pair<string, string>> pres, posts, preslit, postslit;
4770 vector<string> lkeys;
4771 // text before the citation
4772 string lbefore, lbeforelit;
4773 // text after the citation
4774 string lafter, lafterlit;
4776 pair<bool, string> laft, lbef;
4778 get_cite_arguments(p, true, lbefore, lafter);
4779 // remove the brackets around after and before
4780 if (!lafter.empty()) {
4782 lafter.erase(lafter.length() - 1, 1);
4783 laft = convert_latexed_command_inset_arg(lafter);
4784 literal |= !laft.first;
4785 lafter = laft.second;
4786 lafterlit = subst(lafter, "\n", " ");
4788 if (!lbefore.empty()) {
4789 lbefore.erase(0, 1);
4790 lbefore.erase(lbefore.length() - 1, 1);
4791 lbef = convert_latexed_command_inset_arg(lbefore);
4792 literal |= !lbef.first;
4793 lbefore = lbef.second;
4794 lbeforelit = subst(lbefore, "\n", " ");
4796 if (lbefore.empty() && lafter == "[]") {
4801 else if (lbefore == "[]" && lafter == "[]") {
4802 // avoid \cite[][]{a}
4808 lkey = p.getArg('{', '}');
4811 pres.push_back(make_pair(lkey, lbefore));
4812 preslit.push_back(make_pair(lkey, lbeforelit));
4813 posts.push_back(make_pair(lkey, lafter));
4814 postslit.push_back(make_pair(lkey, lafterlit));
4815 lkeys.push_back(lkey);
4817 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4822 for (auto const & ptl : pres) {
4823 if (!pretextlist.empty())
4824 pretextlist += '\t';
4825 pretextlist += ptl.first;
4826 if (!ptl.second.empty())
4827 pretextlist += " " + ptl.second;
4829 for (auto const & potl : posts) {
4830 if (!posttextlist.empty())
4831 posttextlist += '\t';
4832 posttextlist += potl.first;
4833 if (!potl.second.empty())
4834 posttextlist += " " + potl.second;
4837 keys = convert_literate_command_inset_arg(p.verbatim_item());
4840 after = subst(after, "\n", " ");
4841 if (!before.empty())
4842 before = subst(after, "\n", " ");
4844 string lit = literal ? "\"true\"" : "\"false\"";
4845 begin_command_inset(os, "citation", command);
4846 os << "after " << '"' << after << '"' << "\n";
4847 os << "before " << '"' << before << '"' << "\n";
4851 if (!pretextlist.empty())
4852 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4853 if (!posttextlist.empty())
4854 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4855 os << "literal " << lit << "\n";
4857 // Need to set the cite engine if biblatex is loaded by
4858 // the document class directly
4859 if (preamble.citeEngine() == "basic")
4860 use_biblatex_natbib ?
4861 preamble.citeEngine("biblatex-natbib")
4862 : preamble.citeEngine("biblatex");
4867 is_known(t.cs(), known_jurabib_commands) &&
4868 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4869 context.check_layout(os);
4870 string command = t.cs();
4871 if (p.next_token().asInput() == "*") {
4875 char argumentOrder = '\0';
4876 vector<string> const options =
4877 preamble.getPackageOptions("jurabib");
4878 if (find(options.begin(), options.end(),
4879 "natbiborder") != options.end())
4880 argumentOrder = 'n';
4881 else if (find(options.begin(), options.end(),
4882 "jurabiborder") != options.end())
4883 argumentOrder = 'j';
4885 // text before the citation
4887 // text after the citation
4889 get_cite_arguments(p, argumentOrder != 'j', before, after);
4891 string const citation = p.verbatim_item();
4892 if (!before.empty() && argumentOrder == '\0') {
4893 warning_message("Assuming argument order "
4894 "of jurabib version 0.6 for\n'"
4895 + command + before + after + '{'
4896 + citation + "}'.\n"
4897 "Add 'jurabiborder' to the jurabib "
4898 "package options if you used an\n"
4899 "earlier jurabib version.");
4901 bool literal = false;
4902 pair<bool, string> aft;
4903 pair<bool, string> bef;
4904 // remove the brackets around after and before
4905 if (!after.empty()) {
4907 after.erase(after.length() - 1, 1);
4908 aft = convert_latexed_command_inset_arg(after);
4909 literal = !aft.first;
4910 after = literal ? subst(after, "\n", " ") : aft.second;
4912 if (!before.empty()) {
4914 before.erase(before.length() - 1, 1);
4915 bef = convert_latexed_command_inset_arg(before);
4916 literal |= !bef.first;
4917 before = literal ? subst(before, "\n", " ") : bef.second;
4918 if (literal && !after.empty())
4919 after = subst(after, "\n", " ");
4921 string lit = literal ? "\"true\"" : "\"false\"";
4922 begin_command_inset(os, "citation", command);
4923 os << "after " << '"' << after << "\"\n"
4924 << "before " << '"' << before << "\"\n"
4925 << "key " << '"' << citation << "\"\n"
4926 << "literal " << lit << "\n";
4928 // Need to set the cite engine if jurabib is loaded by
4929 // the document class directly
4930 if (preamble.citeEngine() == "basic")
4931 preamble.citeEngine("jurabib");
4935 if (t.cs() == "cite"
4936 || t.cs() == "nocite") {
4937 context.check_layout(os);
4938 string after = p.getArg('[', ']');
4939 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4940 bool const literal = !aft.first;
4941 after = literal ? subst(after, "\n", " ") : aft.second;
4942 string lit = literal ? "\"true\"" : "\"false\"";
4943 string key = convert_literate_command_inset_arg(p.verbatim_item());
4944 // store the case that it is "\nocite{*}" to use it later for
4947 begin_command_inset(os, "citation", t.cs());
4948 os << "after " << '"' << after << "\"\n"
4949 << "key " << '"' << key << "\"\n"
4950 << "literal " << lit << "\n";
4952 } else if (t.cs() == "nocite")
4957 if (t.cs() == "index" ||
4958 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4959 context.check_layout(os);
4960 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4961 p.getArg('[', ']') : "";
4962 string const kind = arg.empty() ? "idx" : arg;
4963 parse_index_entry(p, os, context, kind);
4965 preamble.registerAutomaticallyLoadedPackage("splitidx");
4969 if (t.cs() == "nomenclature") {
4970 context.check_layout(os);
4971 begin_command_inset(os, "nomenclature", "nomenclature");
4972 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4973 if (!prefix.empty())
4974 os << "prefix " << '"' << prefix << '"' << "\n";
4975 string symbol = p.verbatim_item();
4976 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4977 bool literal = !sym.first;
4978 string description = p.verbatim_item();
4979 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4980 literal |= !desc.first;
4982 symbol = subst(symbol, "\n", " ");
4983 description = subst(description, "\n", " ");
4985 symbol = sym.second;
4986 description = desc.second;
4988 string lit = literal ? "\"true\"" : "\"false\"";
4989 os << "symbol " << '"' << symbol;
4990 os << "\"\ndescription \""
4991 << description << "\"\n"
4992 << "literal " << lit << "\n";
4994 preamble.registerAutomaticallyLoadedPackage("nomencl");
4998 if (t.cs() == "label") {
4999 context.check_layout(os);
5000 begin_command_inset(os, "label", "label");
5002 << convert_literate_command_inset_arg(p.verbatim_item())
5008 if (t.cs() == "lyxmintcaption") {
5009 string const pos = p.getArg('[', ']');
5011 string const caption =
5012 parse_text_snippet(p, FLAG_ITEM, false,
5014 minted_nonfloat_caption = "[t]" + caption;
5016 // We already got the caption at the bottom,
5017 // so simply skip it.
5018 parse_text_snippet(p, FLAG_ITEM, false, context);
5020 eat_whitespace(p, os, context, true);
5024 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
5025 context.check_layout(os);
5026 string commandname = t.cs();
5028 if (p.next_token().asInput() == "*") {
5033 begin_command_inset(os, "index_print", commandname);
5034 string const indexname = p.getArg('[', ']');
5036 if (indexname.empty())
5037 os << "type \"idx\"\n";
5039 os << "type \"" << indexname << "\"\n";
5040 os << "literal \"true\"\n";
5043 skip_spaces_braces(p);
5044 preamble.registerAutomaticallyLoadedPackage("makeidx");
5045 if (preamble.use_indices() == "true")
5046 preamble.registerAutomaticallyLoadedPackage("splitidx");
5050 if (t.cs() == "printnomenclature") {
5052 string width_type = "";
5053 context.check_layout(os);
5054 begin_command_inset(os, "nomencl_print", "printnomenclature");
5055 // case of a custom width
5057 width = p.getArg('[', ']');
5058 width = translate_len(width);
5059 width_type = "custom";
5061 // case of no custom width
5062 // the case of no custom width but the width set
5063 // via \settowidth{\nomlabelwidth}{***} cannot be supported
5064 // because the user could have set anything, not only the width
5065 // of the longest label (which would be width_type = "auto")
5066 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
5067 if (label.empty() && width_type.empty())
5068 width_type = "none";
5069 os << "set_width \"" << width_type << "\"\n";
5070 if (width_type == "custom")
5071 os << "width \"" << width << '\"';
5073 skip_spaces_braces(p);
5074 preamble.registerAutomaticallyLoadedPackage("nomencl");
5078 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
5079 context.check_layout(os);
5080 begin_inset(os, "script ");
5081 os << t.cs().substr(4) << '\n';
5082 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
5083 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5085 if (t.cs() == "textsubscript")
5086 preamble.registerAutomaticallyLoadedPackage("subscript");
5090 if ((where = is_known(t.cs(), known_quotes))) {
5091 context.check_layout(os);
5092 begin_inset(os, "Quotes ");
5093 string quotetype = known_coded_quotes[where - known_quotes];
5094 // try to make a smart guess about the side
5095 Token const prev = p.prev_token();
5096 bool const opening = (prev.cat() != catSpace && prev.character() != 0
5097 && prev.character() != '\n' && prev.character() != '~');
5098 quotetype = guessQuoteStyle(quotetype, opening);
5101 // LyX adds {} after the quote, so we have to eat
5102 // spaces here if there are any before a possible
5104 eat_whitespace(p, os, context, false);
5109 if ((where = is_known(t.cs(), known_sizes)) &&
5110 context.new_layout_allowed) {
5111 context.check_layout(os);
5112 TeXFont const oldFont = context.font;
5113 context.font.size = known_coded_sizes[where - known_sizes];
5114 output_font_change(os, oldFont, context.font);
5115 eat_whitespace(p, os, context, false);
5119 if ((where = is_known(t.cs(), known_font_families)) &&
5120 context.new_layout_allowed) {
5121 context.check_layout(os);
5122 TeXFont const oldFont = context.font;
5123 context.font.family =
5124 known_coded_font_families[where - known_font_families];
5125 output_font_change(os, oldFont, context.font);
5126 eat_whitespace(p, os, context, false);
5130 if ((where = is_known(t.cs(), known_font_series)) &&
5131 context.new_layout_allowed) {
5132 context.check_layout(os);
5133 TeXFont const oldFont = context.font;
5134 context.font.series =
5135 known_coded_font_series[where - known_font_series];
5136 output_font_change(os, oldFont, context.font);
5137 eat_whitespace(p, os, context, false);
5141 if ((where = is_known(t.cs(), known_font_shapes)) &&
5142 context.new_layout_allowed) {
5143 context.check_layout(os);
5144 TeXFont const oldFont = context.font;
5145 context.font.shape =
5146 known_coded_font_shapes[where - known_font_shapes];
5147 output_font_change(os, oldFont, context.font);
5148 eat_whitespace(p, os, context, false);
5151 if ((where = is_known(t.cs(), known_old_font_families)) &&
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.family =
5158 known_coded_font_families[where - known_old_font_families];
5159 output_font_change(os, oldFont, context.font);
5160 eat_whitespace(p, os, context, false);
5164 if ((where = is_known(t.cs(), known_old_font_series)) &&
5165 context.new_layout_allowed) {
5166 context.check_layout(os);
5167 TeXFont const oldFont = context.font;
5168 context.font.init();
5169 context.font.size = oldFont.size;
5170 context.font.series =
5171 known_coded_font_series[where - known_old_font_series];
5172 output_font_change(os, oldFont, context.font);
5173 eat_whitespace(p, os, context, false);
5177 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
5178 context.new_layout_allowed) {
5179 context.check_layout(os);
5180 TeXFont const oldFont = context.font;
5181 context.font.init();
5182 context.font.size = oldFont.size;
5183 context.font.shape =
5184 known_coded_font_shapes[where - known_old_font_shapes];
5185 output_font_change(os, oldFont, context.font);
5186 eat_whitespace(p, os, context, false);
5190 if (t.cs() == "selectlanguage") {
5191 context.check_layout(os);
5192 // save the language for the case that a
5193 // \foreignlanguage is used
5194 context.font.language = babel2lyx(p.verbatim_item());
5195 os << "\n\\lang " << context.font.language << "\n";
5199 if (t.cs() == "foreignlanguage") {
5200 string const lang = babel2lyx(p.verbatim_item());
5201 parse_text_attributes(p, os, FLAG_ITEM, outer,
5203 context.font.language, lang);
5207 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
5208 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
5209 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
5211 // We have to output the whole command if it has an option
5212 // because LyX doesn't support this yet, see bug #8214,
5213 // only if there is a single option specifying a variant, we can handle it.
5215 string langopts = p.getOpt();
5216 // check if the option contains a variant, if yes, extract it
5217 string::size_type pos_var = langopts.find("variant");
5218 string::size_type i = langopts.find(',');
5219 string::size_type k = langopts.find('=', pos_var);
5220 if (pos_var != string::npos && i == string::npos) {
5222 variant = langopts.substr(k + 1, langopts.length() - k - 2);
5223 lang = preamble.polyglossia2lyx(variant);
5224 parse_text_attributes(p, os, FLAG_ITEM, outer,
5226 context.font.language, lang);
5228 output_ert_inset(os, t.asInput() + langopts, context);
5230 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
5231 parse_text_attributes(p, os, FLAG_ITEM, outer,
5233 context.font.language, lang);
5238 if (t.cs() == "inputencoding") {
5239 // nothing to write here
5240 string const enc = subst(p.verbatim_item(), "\n", " ");
5241 p.setEncoding(enc, Encoding::inputenc);
5245 if (is_known(t.cs(), known_special_chars) ||
5246 (t.cs() == "protect" &&
5247 p.next_token().cat() == catEscape &&
5248 is_known(p.next_token().cs(), known_special_protect_chars))) {
5249 // LyX sometimes puts a \protect in front, so we have to ignore it
5251 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5252 known_special_chars);
5253 context.check_layout(os);
5254 os << known_coded_special_chars[where - known_special_chars];
5255 skip_spaces_braces(p);
5259 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5260 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5261 p.next_next_token().asInput() == "-") ||
5262 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5263 // LyX sometimes puts a \protect in front, so we have to ignore it
5264 if (t.cs() == "protect")
5266 context.check_layout(os);
5267 if (t.cs() == "nobreakdash")
5268 os << "\\SpecialChar nobreakdash\n";
5270 os << "\\SpecialChar endofsentence\n";
5275 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5276 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5277 || t.cs() == "%" || t.cs() == "-") {
5278 context.check_layout(os);
5280 os << "\\SpecialChar softhyphen\n";
5286 if (t.cs() == "char") {
5287 context.check_layout(os);
5288 if (p.next_token().character() == '`') {
5290 if (p.next_token().cs() == "\"") {
5295 output_ert_inset(os, "\\char`", context);
5298 output_ert_inset(os, "\\char", context);
5303 if (t.cs() == "verb") {
5304 context.check_layout(os);
5305 // set catcodes to verbatim early, just in case.
5306 p.setCatcodes(VERBATIM_CATCODES);
5307 string delim = p.get_token().asInput();
5308 Parser::Arg arg = p.verbatimStuff(delim);
5310 output_ert_inset(os, "\\verb" + delim
5311 + arg.second + delim, context);
5313 warning_message("invalid \\verb command. Skipping");
5317 // Problem: \= creates a tabstop inside the tabbing environment
5318 // and else an accent. In the latter case we really would want
5319 // \={o} instead of \= o.
5320 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5321 output_ert_inset(os, t.asInput(), context);
5325 if (t.cs() == "\\") {
5326 context.check_layout(os);
5328 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5329 else if (p.next_token().asInput() == "*") {
5331 // getOpt() eats the following space if there
5332 // is no optional argument, but that is OK
5333 // here since it has no effect in the output.
5334 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5337 begin_inset(os, "Newline newline");
5343 if (t.cs() == "newline" ||
5344 (t.cs() == "linebreak" && !p.hasOpt())) {
5345 context.check_layout(os);
5346 begin_inset(os, "Newline ");
5349 skip_spaces_braces(p);
5353 if (t.cs() == "endgraf" && context.in_table_cell) {
5354 context.new_paragraph(os);
5355 context.check_layout(os);
5356 skip_spaces_braces(p);
5360 if (t.cs() == "input" || t.cs() == "include"
5361 || t.cs() == "verbatiminput"
5362 || t.cs() == "lstinputlisting"
5363 || t.cs() == "inputminted") {
5364 string name = t.cs();
5365 if (name == "verbatiminput"
5366 && p.next_token().asInput() == "*")
5367 name += p.get_token().asInput();
5368 context.check_layout(os);
5370 bool literal = false;
5371 if (name == "lstinputlisting" && p.hasOpt()) {
5372 lstparams = p.getArg('[', ']');
5373 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5374 literal = !oa.first;
5376 lstparams = subst(lstparams, "\n", " ");
5378 lstparams = oa.second;
5379 } else if (name == "inputminted") {
5380 name = "lstinputlisting";
5381 string const lang = p.getArg('{', '}');
5382 if (lang != "tex") {
5383 string cmd = "\\inputminted{" + lang + "}{";
5384 cmd += p.getArg('{', '}') + "}";
5385 output_ert_inset(os, cmd, context);
5388 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5389 minted_nonfloat_caption.erase(0,3);
5390 // extract label and caption from the already produced LyX code
5391 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5392 string const caption = nfc.front();
5394 vector<string>::iterator it =
5395 find(nfc.begin(), nfc.end(), "LatexCommand label");
5396 if (it != nfc.end()) {
5398 if (it != nfc.end())
5400 label = support::split(label, '"');
5403 minted_nonfloat_caption.clear();
5404 lstparams = "caption=" + caption;
5406 lstparams += ",label=" + label;
5407 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5408 literal = !oa.first;
5410 lstparams = subst(lstparams, "\n", " ");
5412 lstparams = oa.second;
5415 string lit = literal ? "\"true\"" : "\"false\"";
5416 string filename(normalize_filename(p.getArg('{', '}')));
5417 string const path = getMasterFilePath(true);
5418 // We want to preserve relative / absolute filenames,
5419 // therefore path is only used for testing
5420 if ((t.cs() == "include" || t.cs() == "input") &&
5421 !makeAbsPath(filename, path).exists()) {
5422 // The file extension is probably missing.
5423 // Now try to find it out.
5424 string const tex_name =
5425 find_file(filename, path,
5426 known_tex_extensions);
5427 if (!tex_name.empty())
5428 filename = tex_name;
5430 bool external = false;
5432 if (makeAbsPath(filename, path).exists()) {
5433 string const abstexname =
5434 makeAbsPath(filename, path).absFileName();
5435 string const absfigname =
5436 changeExtension(abstexname, ".fig");
5437 fix_child_filename(filename);
5438 string const lyxname = changeExtension(filename,
5439 roundtripMode() ? ".lyx.lyx" : ".lyx");
5440 string const abslyxname = makeAbsPath(
5441 lyxname, getParentFilePath(false)).absFileName();
5443 if (!skipChildren())
5444 external = FileName(absfigname).exists();
5445 if (t.cs() == "input" && !skipChildren()) {
5446 string const ext = getExtension(abstexname);
5448 // Combined PS/LaTeX:
5449 // x.eps, x.pstex_t (old xfig)
5450 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5451 FileName const absepsname(
5452 changeExtension(abstexname, ".eps"));
5453 FileName const abspstexname(
5454 changeExtension(abstexname, ".pstex"));
5455 bool const xfigeps =
5456 (absepsname.exists() ||
5457 abspstexname.exists()) &&
5460 // Combined PDF/LaTeX:
5461 // x.pdf, x.pdftex_t (old xfig)
5462 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5463 FileName const abspdfname(
5464 changeExtension(abstexname, ".pdf"));
5465 bool const xfigpdf =
5466 abspdfname.exists() &&
5467 (ext == "pdftex_t" || ext == "pdf_t");
5471 // Combined PS/PDF/LaTeX:
5472 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5473 string const absbase2(
5474 removeExtension(abstexname) + "_pspdftex");
5475 FileName const abseps2name(
5476 addExtension(absbase2, ".eps"));
5477 FileName const abspdf2name(
5478 addExtension(absbase2, ".pdf"));
5479 bool const xfigboth =
5480 abspdf2name.exists() &&
5481 abseps2name.exists() && ext == "pspdftex";
5483 xfig = xfigpdf || xfigeps || xfigboth;
5484 external = external && xfig;
5487 outname = changeExtension(filename, ".fig");
5488 FileName abssrc(changeExtension(abstexname, ".fig"));
5489 copy_file(abssrc, outname);
5491 // Don't try to convert, the result
5492 // would be full of ERT.
5494 FileName abssrc(abstexname);
5495 copy_file(abssrc, outname);
5496 } else if (t.cs() != "verbatiminput" &&
5498 tex2lyx(abstexname, FileName(abslyxname),
5501 // no need to call copy_file
5502 // tex2lyx creates the file
5505 FileName abssrc(abstexname);
5506 copy_file(abssrc, outname);
5509 warning_message("Could not find included file '" + filename + "'.");
5513 begin_inset(os, "External\n");
5514 os << "\ttemplate XFig\n"
5515 << "\tfilename " << outname << '\n';
5516 registerExternalTemplatePackages("XFig");
5518 begin_command_inset(os, "include", name);
5519 outname = subst(outname, "\"", "\\\"");
5520 os << "preview false\n"
5521 "filename \"" << outname << "\"\n";
5522 if (!lstparams.empty())
5523 os << "lstparams \"" << lstparams << "\"\n";
5524 os << "literal " << lit << "\n";
5525 if (t.cs() == "verbatiminput")
5526 preamble.registerAutomaticallyLoadedPackage("verbatim");
5532 if (t.cs() == "bibliographystyle") {
5533 // store new bibliographystyle
5534 bibliographystyle = p.verbatim_item();
5535 // If any other command than \bibliography, \addcontentsline
5536 // and \nocite{*} follows, we need to output the style
5537 // (because it might be used by that command).
5538 // Otherwise, it will automatically be output by LyX.
5541 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5542 if (t2.cat() == catBegin)
5544 if (t2.cat() != catEscape)
5546 if (t2.cs() == "nocite") {
5547 if (p.getArg('{', '}') == "*")
5549 } else if (t2.cs() == "bibliography")
5551 else if (t2.cs() == "phantomsection") {
5555 else if (t2.cs() == "addcontentsline") {
5556 // get the 3 arguments of \addcontentsline
5559 contentslineContent = p.getArg('{', '}');
5560 // if the last argument is not \refname we must output
5561 if (contentslineContent == "\\refname")
5568 output_ert_inset(os,
5569 "\\bibliographystyle{" + bibliographystyle + '}',
5575 if (t.cs() == "phantomsection") {
5576 // we only support this if it occurs between
5577 // \bibliographystyle and \bibliography
5578 if (bibliographystyle.empty())
5579 output_ert_inset(os, "\\phantomsection", context);
5583 if (t.cs() == "addcontentsline") {
5584 context.check_layout(os);
5585 // get the 3 arguments of \addcontentsline
5586 string const one = p.getArg('{', '}');
5587 string const two = p.getArg('{', '}');
5588 string const three = p.getArg('{', '}');
5589 // only if it is a \refname, we support if for the bibtex inset
5590 if (contentslineContent != "\\refname") {
5591 output_ert_inset(os,
5592 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5598 if (t.cs() == "tikzset") {
5599 context.check_layout(os);
5600 // we catch the argument and output it verbatim in an ERT
5601 string const arg = p.getArg('{', '}');
5602 output_ert_inset(os,
5603 "\\tikzset{" + arg + "}",
5608 else if (t.cs() == "bibliography") {
5609 context.check_layout(os);
5611 begin_command_inset(os, "bibtex", "bibtex");
5612 if (!btprint.empty()) {
5613 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5614 // clear the string because the next BibTeX inset can be without the
5615 // \nocite{*} option
5618 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5619 // Do we have addcontentsline?
5620 if (contentslineContent == "\\refname") {
5621 BibOpts = "bibtotoc";
5622 // clear string because next BibTeX inset can be without addcontentsline
5623 contentslineContent.clear();
5625 // Do we have a bibliographystyle set?
5626 if (!bibliographystyle.empty()) {
5627 if (BibOpts.empty())
5628 BibOpts = normalize_filename(bibliographystyle);
5630 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5631 // clear it because each bibtex entry has its style
5632 // and we need an empty string to handle \phantomsection
5633 bibliographystyle.clear();
5635 os << "options " << '"' << BibOpts << '"' << "\n";
5636 if (p.getEncoding() != preamble.docencoding) {
5637 Encoding const * const enc = encodings.fromIconvName(
5638 p.getEncoding(), Encoding::inputenc, true);
5640 warning_message("Unknown bib encoding " + p.getEncoding()
5643 os << "encoding " << '"' << enc->name() << '"' << "\n";
5649 if (t.cs() == "printbibliography") {
5650 context.check_layout(os);
5652 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5653 vector<string> opts = getVectorFromString(bbloptions);
5654 vector<string>::iterator it =
5655 find(opts.begin(), opts.end(), "heading=bibintoc");
5656 if (it != opts.end()) {
5658 BibOpts = "bibtotoc";
5660 bbloptions = getStringFromVector(opts);
5661 begin_command_inset(os, "bibtex", "bibtex");
5662 if (!btprint.empty()) {
5663 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5664 // clear the string because the next BibTeX inset can be without the
5665 // \nocite{*} option
5669 for (auto const & bf : preamble.biblatex_bibliographies) {
5670 if (!bibfiles.empty())
5672 bibfiles += normalize_filename(bf);
5674 if (!bibfiles.empty())
5675 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5676 // Do we have addcontentsline?
5677 if (contentslineContent == "\\refname") {
5678 BibOpts = "bibtotoc";
5679 // clear string because next BibTeX inset can be without addcontentsline
5680 contentslineContent.clear();
5682 os << "options " << '"' << BibOpts << '"' << "\n";
5683 if (!bbloptions.empty())
5684 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5685 if (!preamble.bibencoding.empty()) {
5686 Encoding const * const enc = encodings.fromLaTeXName(
5687 preamble.bibencoding, Encoding::inputenc, true);
5689 warning_message("Unknown bib encoding " + preamble.bibencoding
5692 os << "encoding " << '"' << enc->name() << '"' << "\n";
5695 for (auto const & bf : preamble.biblatex_encodings) {
5696 if (!bibfileencs.empty())
5697 bibfileencs += "\t";
5700 if (!bibfileencs.empty())
5701 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5703 need_commentbib = false;
5707 if (t.cs() == "bibbysection") {
5708 context.check_layout(os);
5710 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5711 vector<string> opts = getVectorFromString(bbloptions);
5712 vector<string>::iterator it =
5713 find(opts.begin(), opts.end(), "heading=bibintoc");
5714 if (it != opts.end()) {
5716 BibOpts = "bibtotoc";
5718 bbloptions = getStringFromVector(opts);
5719 begin_command_inset(os, "bibtex", "bibtex");
5720 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5722 for (auto const & bf : preamble.biblatex_bibliographies) {
5723 if (!bibfiles.empty())
5725 bibfiles += normalize_filename(bf);
5727 if (!bibfiles.empty())
5728 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5729 os << "options " << '"' << BibOpts << '"' << "\n";
5730 if (!bbloptions.empty())
5731 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5733 need_commentbib = false;
5737 if (t.cs() == "parbox") {
5738 // Test whether this is an outer box of a shaded box
5740 // swallow arguments
5741 while (p.hasOpt()) {
5743 p.skip_spaces(true);
5746 p.skip_spaces(true);
5748 if (p.next_token().cat() == catBegin)
5750 p.skip_spaces(true);
5751 Token to = p.get_token();
5752 bool shaded = false;
5753 if (to.asInput() == "\\begin") {
5754 p.skip_spaces(true);
5755 if (p.getArg('{', '}') == "shaded")
5760 parse_outer_box(p, os, FLAG_ITEM, outer,
5761 context, "parbox", "shaded");
5763 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5764 "", "", t.cs(), "", "");
5768 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5769 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5770 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5771 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5775 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5776 string backgroundcolor;
5777 preamble.registerAutomaticallyLoadedPackage("xcolor");
5778 if (t.cs() == "fcolorbox") {
5779 string const framecolor = p.getArg('{', '}');
5780 backgroundcolor = p.getArg('{', '}');
5781 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5783 backgroundcolor = p.getArg('{', '}');
5784 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5789 // FIXME: due to the compiler limit of "if" nestings
5790 // the code for the alignment was put here
5791 // put them in their own if if this is fixed
5792 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5793 || t.cs() == "shadowsize") {
5794 if (t.cs() == "fboxrule")
5796 if (t.cs() == "fboxsep")
5798 if (t.cs() == "shadowsize")
5800 p.skip_spaces(true);
5801 while (p.good() && p.next_token().cat() != catSpace
5802 && p.next_token().cat() != catNewline
5803 && p.next_token().cat() != catEscape) {
5804 if (t.cs() == "fboxrule")
5805 fboxrule = fboxrule + p.get_token().asInput();
5806 if (t.cs() == "fboxsep")
5807 fboxsep = fboxsep + p.get_token().asInput();
5808 if (t.cs() == "shadowsize")
5809 shadow_size = shadow_size + p.get_token().asInput();
5814 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5815 if (context.in_table_cell) {
5816 if (t.cs() == "raggedleft")
5817 context.cell_align = 'r';
5818 else if (t.cs() == "centering")
5819 context.cell_align = 'c';
5820 else if (t.cs() == "raggedright")
5821 context.cell_align = 'l';
5822 p.skip_spaces(true);
5824 output_ert_inset(os, t.asInput(), context);
5829 //\framebox() is part of the picture environment and different from \framebox{}
5830 //\framebox{} will be parsed by parse_outer_box
5831 if (t.cs() == "framebox") {
5832 if (p.next_token().character() == '(') {
5833 //the syntax is: \framebox(x,y)[position]{content}
5834 string arg = t.asInput();
5835 arg += p.getFullParentheseArg();
5836 arg += p.getFullOpt();
5837 eat_whitespace(p, os, context, false);
5838 output_ert_inset(os, arg + '{', context);
5839 parse_text(p, os, FLAG_ITEM, outer, context);
5840 output_ert_inset(os, "}", context);
5842 //the syntax is: \framebox[width][position]{content}
5843 string special = p.getFullOpt();
5844 special += p.getOpt();
5845 parse_outer_box(p, os, FLAG_ITEM, outer,
5846 context, t.cs(), special);
5851 //\makebox() is part of the picture environment and different from \makebox{}
5852 //\makebox{} will be parsed by parse_box
5853 if (t.cs() == "makebox") {
5854 if (p.next_token().character() == '(') {
5855 //the syntax is: \makebox(x,y)[position]{content}
5856 string arg = t.asInput();
5857 arg += p.getFullParentheseArg();
5858 arg += p.getFullOpt();
5859 eat_whitespace(p, os, context, false);
5860 output_ert_inset(os, arg + '{', context);
5861 parse_text(p, os, FLAG_ITEM, outer, context);
5862 output_ert_inset(os, "}", context);
5864 //the syntax is: \makebox[width][position]{content}
5865 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5866 "", "", t.cs(), "", "");
5870 if (t.cs() == "smallskip" ||
5871 t.cs() == "medskip" ||
5872 t.cs() == "bigskip" ||
5873 t.cs() == "vfill") {
5874 context.check_layout(os);
5875 begin_inset(os, "VSpace ");
5878 skip_spaces_braces(p);
5882 if ((where = is_known(t.cs(), known_spaces))
5883 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5884 context.check_layout(os);
5885 begin_inset(os, "space ");
5886 os << '\\' << known_coded_spaces[where - known_spaces]
5889 // LaTeX swallows whitespace after all spaces except
5890 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5891 // We have to do that here, too, because LyX
5892 // adds "{}" which would make the spaces significant.
5893 if (!contains(",>!;:", t.cs()))
5894 eat_whitespace(p, os, context, false);
5895 // LyX adds "{}" after all spaces except "\\ " and
5896 // "\\,", so we have to remove "{}".
5897 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5898 // remove the braces after "\\,", too.
5904 if (t.cs() == "newpage" ||
5905 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5906 t.cs() == "clearpage" ||
5907 t.cs() == "cleardoublepage" ||
5908 t.cs() == "nopagebreak") {
5909 context.check_layout(os);
5910 begin_inset(os, "Newpage ");
5913 skip_spaces_braces(p);
5917 if (t.cs() == "DeclareRobustCommand" ||
5918 t.cs() == "DeclareRobustCommandx" ||
5919 t.cs() == "newcommand" ||
5920 t.cs() == "newcommandx" ||
5921 t.cs() == "providecommand" ||
5922 t.cs() == "providecommandx" ||
5923 t.cs() == "renewcommand" ||
5924 t.cs() == "renewcommandx") {
5925 // DeclareRobustCommand, DeclareRobustCommandx,
5926 // providecommand and providecommandx could be handled
5927 // by parse_command(), but we need to call
5928 // add_known_command() here.
5929 string name = t.asInput();
5930 if (p.next_token().asInput() == "*") {
5931 // Starred form. Eat '*'
5935 string const command = p.verbatim_item();
5936 string const opt1 = p.getFullOpt();
5937 string const opt2 = p.getFullOpt();
5938 add_known_command(command, opt1, !opt2.empty());
5939 string const ert = name + '{' + command + '}' +
5941 '{' + p.verbatim_item() + '}';
5943 if (t.cs() == "DeclareRobustCommand" ||
5944 t.cs() == "DeclareRobustCommandx" ||
5945 t.cs() == "providecommand" ||
5946 t.cs() == "providecommandx" ||
5947 name[name.length()-1] == '*')
5948 output_ert_inset(os, ert, context);
5950 context.check_layout(os);
5951 begin_inset(os, "FormulaMacro");
5958 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5959 // let could be handled by parse_command(),
5960 // but we need to call add_known_command() here.
5961 string ert = t.asInput();
5964 if (p.next_token().cat() == catBegin) {
5965 name = p.verbatim_item();
5966 ert += '{' + name + '}';
5968 name = p.verbatim_item();
5973 if (p.next_token().cat() == catBegin) {
5974 command = p.verbatim_item();
5975 ert += '{' + command + '}';
5977 command = p.verbatim_item();
5980 // If command is known, make name known too, to parse
5981 // its arguments correctly. For this reason we also
5982 // have commands in syntax.default that are hardcoded.
5983 CommandMap::iterator it = known_commands.find(command);
5984 if (it != known_commands.end())
5985 known_commands[t.asInput()] = it->second;
5986 output_ert_inset(os, ert, context);
5990 if (t.cs() == "hspace" || t.cs() == "vspace") {
5993 string name = t.asInput();
5994 string const length = p.verbatim_item();
5997 bool valid = splitLatexLength(length, valstring, unit);
5998 bool known_hspace = false;
5999 bool known_vspace = false;
6000 bool known_unit = false;
6003 istringstream iss(valstring);
6006 if (t.cs()[0] == 'h') {
6007 if (unit == "\\fill") {
6012 known_hspace = true;
6015 if (unit == "\\smallskipamount") {
6017 known_vspace = true;
6018 } else if (unit == "\\medskipamount") {
6020 known_vspace = true;
6021 } else if (unit == "\\bigskipamount") {
6023 known_vspace = true;
6024 } else if (length == "\\baselineskip") {
6026 known_vspace = true;
6027 } else if (unit == "\\fill") {
6029 known_vspace = true;
6033 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
6035 known_vspace = true;
6037 if (!known_hspace && !known_vspace) {
6038 switch (unitFromString(unit)) {
6054 //unitFromString(unit) fails for relative units like Length::PCW
6055 // therefore handle them separately
6056 if (unit == "\\paperwidth" || unit == "\\columnwidth"
6057 || unit == "\\textwidth" || unit == "\\linewidth"
6058 || unit == "\\textheight" || unit == "\\paperheight"
6059 || unit == "\\baselineskip")
6067 // check for glue lengths
6068 string gluelength = length;
6069 bool is_gluelength = is_glue_length(gluelength);
6071 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
6072 // Literal horizontal length or known variable
6073 context.check_layout(os);
6074 begin_inset(os, "space ");
6082 if (known_unit && !known_hspace)
6083 os << "\n\\length " << translate_len(length);
6085 os << "\n\\length " << gluelength;
6087 } else if (known_unit || known_vspace || is_gluelength) {
6088 // Literal vertical length or known variable
6089 context.check_layout(os);
6090 begin_inset(os, "VSpace ");
6093 if (known_unit && !known_vspace)
6094 os << translate_len(length);
6101 // LyX can't handle other length variables in Inset VSpace/space
6106 output_ert_inset(os, name + '{' + unit + '}', context);
6107 else if (value == -1.0)
6108 output_ert_inset(os, name + "{-" + unit + '}', context);
6110 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
6112 output_ert_inset(os, name + '{' + length + '}', context);
6117 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
6118 // might be one or several options or a star.
6119 // The single '=' is meant here.
6120 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
6124 context.check_layout(os);
6125 // store the latexparam here. This is eaten in parse_text_in_inset
6126 context.latexparam = newinsetlayout->latexparam();
6127 docstring name = newinsetlayout->name();
6128 bool const caption = name.find(from_ascii("Caption:")) == 0;
6130 // Already done for floating minted listings.
6131 if (minted_float.empty()) {
6132 begin_inset(os, "Caption ");
6133 os << to_utf8(name.substr(8)) << '\n';
6136 // FIXME: what do we do if the prefix is not Flex: ?
6137 if (prefixIs(name, from_ascii("Flex:")))
6139 begin_inset(os, "Flex ");
6140 os << to_utf8(name) << '\n'
6141 << "status collapsed\n";
6143 if (!minted_float.empty()) {
6144 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6145 } else if (newinsetlayout->isPassThru()) {
6146 // set catcodes to verbatim early, just in case.
6147 p.setCatcodes(VERBATIM_CATCODES);
6148 string delim = p.get_token().asInput();
6150 warning_message("bad delimiter for command " + t.asInput());
6151 //FIXME: handle error condition
6152 string const arg = p.verbatimStuff("}").second;
6153 Context newcontext(true, context.textclass);
6154 if (newinsetlayout->forcePlainLayout())
6155 newcontext.layout = &context.textclass.plainLayout();
6156 output_ert(os, arg, newcontext);
6158 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6159 context.latexparam.clear();
6162 // Minted caption insets are not closed here because
6163 // we collect everything into the caption.
6164 if (minted_float.empty())
6169 // The single '=' is meant here.
6170 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
6174 context.check_layout(os);
6175 docstring name = newinsetlayout->name();
6176 bool const caption = name.find(from_ascii("Caption:")) == 0;
6178 // Already done for floating minted listings.
6179 if (minted_float.empty()) {
6180 begin_inset(os, "Caption ");
6181 os << to_utf8(name.substr(8)) << '\n';
6184 // FIXME: what do we do if the prefix is not Flex: ?
6185 if (prefixIs(name, from_ascii("Flex:")))
6187 begin_inset(os, "Flex ");
6188 os << to_utf8(name) << '\n'
6189 << "status collapsed\n";
6191 if (!minted_float.empty()) {
6192 parse_text_snippet(p, os, FLAG_ITEM, false, context);
6193 } else if (newinsetlayout->isPassThru()) {
6194 // set catcodes to verbatim early, just in case.
6195 p.setCatcodes(VERBATIM_CATCODES);
6196 string delim = p.get_token().asInput();
6198 warning_message("bad delimiter for command " + t.asInput());
6199 //FIXME: handle error condition
6200 string const arg = p.verbatimStuff("}").second;
6201 Context newcontext(true, context.textclass);
6202 if (newinsetlayout->forcePlainLayout())
6203 newcontext.layout = &context.textclass.plainLayout();
6204 output_ert(os, arg, newcontext);
6206 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
6209 // Minted caption insets are not closed here because
6210 // we collect everything into the caption.
6211 if (minted_float.empty())
6216 if (t.cs() == "includepdf") {
6218 string const arg = p.getArg('[', ']');
6219 map<string, string> opts;
6220 vector<string> keys;
6221 split_map(arg, opts, keys);
6222 string name = normalize_filename(p.verbatim_item());
6223 string const path = getMasterFilePath(true);
6224 // We want to preserve relative / absolute filenames,
6225 // therefore path is only used for testing
6226 if (!makeAbsPath(name, path).exists()) {
6227 // The file extension is probably missing.
6228 // Now try to find it out.
6229 char const * const pdfpages_format[] = {"pdf", 0};
6230 string const pdftex_name =
6231 find_file(name, path, pdfpages_format);
6232 if (!pdftex_name.empty()) {
6237 FileName const absname = makeAbsPath(name, path);
6238 if (absname.exists())
6240 fix_child_filename(name);
6241 copy_file(absname, name);
6243 warning_message("Could not find file '" + name + "'.");
6245 context.check_layout(os);
6246 begin_inset(os, "External\n\ttemplate ");
6247 os << "PDFPages\n\tfilename "
6249 // parse the options
6250 if (opts.find("pages") != opts.end())
6251 os << "\textra LaTeX \"pages="
6252 << opts["pages"] << "\"\n";
6253 if (opts.find("angle") != opts.end())
6254 os << "\trotateAngle "
6255 << opts["angle"] << '\n';
6256 if (opts.find("origin") != opts.end()) {
6258 string const opt = opts["origin"];
6259 if (opt == "tl") ss << "topleft";
6260 if (opt == "bl") ss << "bottomleft";
6261 if (opt == "Bl") ss << "baselineleft";
6262 if (opt == "c") ss << "center";
6263 if (opt == "tc") ss << "topcenter";
6264 if (opt == "bc") ss << "bottomcenter";
6265 if (opt == "Bc") ss << "baselinecenter";
6266 if (opt == "tr") ss << "topright";
6267 if (opt == "br") ss << "bottomright";
6268 if (opt == "Br") ss << "baselineright";
6269 if (!ss.str().empty())
6270 os << "\trotateOrigin " << ss.str() << '\n';
6272 warning_message("Ignoring unknown includegraphics origin argument '" + opt + "'");
6274 if (opts.find("width") != opts.end())
6276 << translate_len(opts["width"]) << '\n';
6277 if (opts.find("height") != opts.end())
6279 << translate_len(opts["height"]) << '\n';
6280 if (opts.find("keepaspectratio") != opts.end())
6281 os << "\tkeepAspectRatio\n";
6283 context.check_layout(os);
6284 registerExternalTemplatePackages("PDFPages");
6288 if (t.cs() == "loadgame") {
6290 string name = normalize_filename(p.verbatim_item());
6291 string const path = getMasterFilePath(true);
6292 // We want to preserve relative / absolute filenames,
6293 // therefore path is only used for testing
6294 if (!makeAbsPath(name, path).exists()) {
6295 // The file extension is probably missing.
6296 // Now try to find it out.
6297 char const * const lyxskak_format[] = {"fen", 0};
6298 string const lyxskak_name =
6299 find_file(name, path, lyxskak_format);
6300 if (!lyxskak_name.empty())
6301 name = lyxskak_name;
6303 FileName const absname = makeAbsPath(name, path);
6304 if (absname.exists())
6306 fix_child_filename(name);
6307 copy_file(absname, name);
6309 warning_message("Could not find file '" + name + "'.");
6310 context.check_layout(os);
6311 begin_inset(os, "External\n\ttemplate ");
6312 os << "ChessDiagram\n\tfilename "
6315 context.check_layout(os);
6316 // after a \loadgame follows a \showboard
6317 if (p.get_token().asInput() == "showboard")
6319 registerExternalTemplatePackages("ChessDiagram");
6323 // try to see whether the string is in unicodesymbols
6324 // Only use text mode commands, since we are in text mode here,
6325 // and math commands may be invalid (bug 6797)
6326 string name = t.asInput();
6327 // handle the dingbats, cyrillic and greek
6328 if (name == "\\textcyr")
6329 name = "\\textcyrillic";
6330 if (name == "\\ding" || name == "\\textcyrillic" ||
6331 (name == "\\textgreek" && !preamble.usePolyglossia()))
6332 name = name + '{' + p.getArg('{', '}') + '}';
6333 // handle the ifsym characters
6334 else if (name == "\\textifsymbol") {
6335 string const optif = p.getFullOpt();
6336 string const argif = p.getArg('{', '}');
6337 name = name + optif + '{' + argif + '}';
6339 // handle the \ascii characters
6340 // the case of \ascii within braces, as LyX outputs it, is already
6341 // handled for t.cat() == catBegin
6342 else if (name == "\\ascii") {
6343 // the code is "\asci\xxx"
6344 name = "{" + name + p.get_token().asInput() + "}";
6347 // handle some TIPA special characters
6348 else if (preamble.isPackageUsed("tipa")) {
6349 if (name == "\\s") {
6350 // fromLaTeXCommand() does not yet
6351 // recognize tipa short cuts
6352 name = "\\textsyllabic";
6353 } else if (name == "\\=" &&
6354 p.next_token().asInput() == "*") {
6355 // fromLaTeXCommand() does not yet
6356 // recognize tipa short cuts
6358 name = "\\textsubbar";
6359 } else if (name == "\\textdoublevertline") {
6360 // FIXME: This is not correct,
6361 // \textvertline is higher than \textbardbl
6362 name = "\\textbardbl";
6364 } else if (name == "\\!" ) {
6365 if (p.next_token().asInput() == "b") {
6366 p.get_token(); // eat 'b'
6369 } else if (p.next_token().asInput() == "d") {
6373 } else if (p.next_token().asInput() == "g") {
6377 } else if (p.next_token().asInput() == "G") {
6379 name = "\\texthtscg";
6381 } else if (p.next_token().asInput() == "j") {
6383 name = "\\texthtbardotlessj";
6385 } else if (p.next_token().asInput() == "o") {
6387 name = "\\textbullseye";
6390 } else if (name == "\\*" ) {
6391 if (p.next_token().asInput() == "k") {
6393 name = "\\textturnk";
6395 } else if (p.next_token().asInput() == "r") {
6396 p.get_token(); // eat 'b'
6397 name = "\\textturnr";
6399 } else if (p.next_token().asInput() == "t") {
6401 name = "\\textturnt";
6403 } else if (p.next_token().asInput() == "w") {
6405 name = "\\textturnw";
6410 if ((name.size() == 2 &&
6411 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6412 p.next_token().asInput() != "*") ||
6413 is_known(name.substr(1), known_tipa_marks)) {
6414 // name is a command that corresponds to a
6415 // combining character in unicodesymbols.
6416 // Append the argument, fromLaTeXCommand()
6417 // will either convert it to a single
6418 // character or a combining sequence.
6419 name += '{' + p.verbatim_item() + '}';
6421 // now get the character from unicodesymbols
6425 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6426 Encodings::TEXT_CMD, termination, rem, &req));
6428 context.check_layout(os);
6431 output_ert_inset(os, to_utf8(rem), context);
6433 skip_spaces_braces(p);
6434 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6435 preamble.registerAutomaticallyLoadedPackage(*it);
6437 //warning_message("#: " + t + " mode: " + mode);
6438 // heuristic: read up to next non-nested space
6440 string s = t.asInput();
6441 string z = p.verbatim_item();
6442 while (p.good() && z != " " && !z.empty()) {
6443 //warning_message("read: " + z);
6445 z = p.verbatim_item();
6447 warning_message("found ERT: " + s);
6448 output_ert_inset(os, s + ' ', context);
6451 if (t.asInput() == name &&
6452 p.next_token().asInput() == "*") {
6453 // Starred commands like \vspace*{}
6454 p.get_token(); // Eat '*'
6457 if (!parse_command(name, p, os, outer, context)) {
6458 output_ert_inset(os, name, context);
6459 // Try to handle options of unknown commands:
6460 // Look if we have optional arguments,
6461 // and if so, put the brackets in ERT.
6462 while (p.hasOpt()) {
6463 p.get_token(); // eat '['
6464 output_ert_inset(os, "[", context);
6465 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6466 output_ert_inset(os, "]", context);
6474 string guessLanguage(Parser & p, string const & lang)
6476 typedef std::map<std::string, size_t> LangMap;
6477 // map from language names to number of characters
6480 for (char const * const * i = supported_CJK_languages; *i; i++)
6481 used[string(*i)] = 0;
6484 Token const t = p.get_token();
6485 // comments are not counted for any language
6486 if (t.cat() == catComment)
6488 // commands are not counted as well, but we need to detect
6489 // \begin{CJK} and switch encoding if needed
6490 if (t.cat() == catEscape) {
6491 if (t.cs() == "inputencoding") {
6492 string const enc = subst(p.verbatim_item(), "\n", " ");
6493 p.setEncoding(enc, Encoding::inputenc);
6496 if (t.cs() != "begin")
6499 // Non-CJK content is counted for lang.
6500 // We do not care about the real language here:
6501 // If we have more non-CJK contents than CJK contents,
6502 // we simply use the language that was specified as
6503 // babel main language.
6504 used[lang] += t.asInput().length();
6507 // Now we are starting an environment
6509 string const name = p.getArg('{', '}');
6510 if (name != "CJK") {
6514 // It is a CJK environment
6516 /* name = */ p.getArg('{', '}');
6517 string const encoding = p.getArg('{', '}');
6518 /* mapping = */ p.getArg('{', '}');
6519 string const encoding_old = p.getEncoding();
6520 char const * const * const where =
6521 is_known(encoding, supported_CJK_encodings);
6523 p.setEncoding(encoding, Encoding::CJK);
6525 p.setEncoding("UTF-8");
6526 string const text = p.ertEnvironment("CJK");
6527 p.setEncoding(encoding_old);
6530 // ignore contents in unknown CJK encoding
6533 // the language of the text
6535 supported_CJK_languages[where - supported_CJK_encodings];
6536 used[cjk] += text.length();
6538 LangMap::const_iterator use = used.begin();
6539 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6540 if (it->second > use->second)
6547 void check_comment_bib(ostream & os, Context & context)
6549 if (!need_commentbib)
6551 // We have a bibliography database, but no bibliography with biblatex
6552 // which is completely valid. Insert a bibtex inset in a note.
6553 context.check_layout(os);
6554 begin_inset(os, "Note Note\n");
6555 os << "status open\n";
6556 os << "\\begin_layout Plain Layout\n";
6557 begin_command_inset(os, "bibtex", "bibtex");
6559 for (auto const & bf : preamble.biblatex_bibliographies) {
6560 if (!bibfiles.empty())
6562 bibfiles += normalize_filename(bf);
6564 if (!bibfiles.empty())
6565 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6567 for (auto const & bf : preamble.biblatex_encodings) {
6568 if (!bibfileencs.empty())
6569 bibfileencs += "\t";
6572 if (!bibfileencs.empty())
6573 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6574 end_inset(os);// Bibtex
6575 os << "\\end_layout\n";
6576 end_inset(os);// Note