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"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
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;
68 output_arguments(os, p, outer, false, false, newcontext,
70 parse_text(p, os, flags, outer, newcontext, rdelim);
72 output_arguments(os, p, outer, false, true, newcontext,
73 layout->postcommandargs());
74 newcontext.check_end_layout(os);
80 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
81 Context const & context, string const & name,
82 string const rdelim = string())
84 InsetLayout const * layout = 0;
85 DocumentClass::InsetLayouts::const_iterator it =
86 context.textclass.insetLayouts().find(from_ascii(name));
87 if (it != context.textclass.insetLayouts().end())
88 layout = &(it->second);
89 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
92 /// parses a paragraph snippet, useful for example for \\emph{...}
93 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
96 Context newcontext(context);
97 // Don't inherit the paragraph-level extra stuff
98 newcontext.par_extra_stuff.clear();
99 parse_text(p, os, flags, outer, newcontext);
100 // Make sure that we don't create invalid .lyx files
101 context.need_layout = newcontext.need_layout;
102 context.need_end_layout = newcontext.need_end_layout;
107 * Thin wrapper around parse_text_snippet() using a string.
109 * We completely ignore \c context.need_layout and \c context.need_end_layout,
110 * because our return value is not used directly (otherwise the stream version
111 * of parse_text_snippet() could be used). That means that the caller needs
112 * to do layout management manually.
113 * This is intended to parse text that does not create any layout changes.
115 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
118 Context newcontext(context);
119 newcontext.need_layout = false;
120 newcontext.need_end_layout = false;
121 newcontext.new_layout_allowed = false;
122 // Avoid warning by Context::~Context()
123 newcontext.par_extra_stuff.clear();
125 parse_text_snippet(p, os, flags, outer, newcontext);
129 string fboxrule = "";
131 string shadow_size = "";
133 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
134 "vpageref", "prettyref", "nameref", "eqref", 0 };
136 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
137 "vpageref", "formatted", "nameref", "eqref", 0 };
139 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
140 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
141 "secref", "subsecref", "tabref", "thmref", 0 };
143 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
144 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
145 "sec", "subsec", "tab", "thm", 0 };
149 * supported CJK encodings
150 * JIS does not work with LyX's encoding conversion
152 const char * const supported_CJK_encodings[] = {
153 "EUC-JP", "KS", "GB", "UTF8",
154 "Bg5", /*"JIS",*/ "SJIS", 0};
157 * the same as supported_CJK_encodings with their corresponding LyX language name
158 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
160 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
161 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
162 * please keep this in sync with supported_CJK_encodings line by line!
164 const char * const supported_CJK_languages[] = {
165 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
166 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
170 * The starred forms are also known except for "citefullauthor",
171 * "citeyear" and "citeyearpar".
173 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
174 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
175 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
179 * No starred form other than "cite*" known.
181 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
182 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
183 // jurabib commands not (yet) supported by LyX:
185 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
186 // "footciteauthor", "footciteyear", "footciteyearpar",
187 "citefield", "citetitle", 0 };
191 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
193 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
194 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
195 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
196 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
197 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
199 // Whether we need to insert a bibtex inset in a comment
200 bool need_commentbib = false;
202 /// LaTeX names for quotes
203 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
204 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
205 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
206 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
209 /// the same as known_quotes with .lyx names
210 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
211 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
212 "gld", "eld", "gls", "ers", "ars",
213 "ars", "als", "als", "erd", "qrs", "qrd", 0};
215 /// LaTeX names for font sizes
216 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
217 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
219 /// the same as known_sizes with .lyx names
220 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
221 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
223 /// LaTeX 2.09 names for font families
224 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
226 /// LaTeX names for font families
227 char const * const known_font_families[] = { "rmfamily", "sffamily",
230 /// LaTeX names for font family changing commands
231 char const * const known_text_font_families[] = { "textrm", "textsf",
234 /// The same as known_old_font_families, known_font_families and
235 /// known_text_font_families with .lyx names
236 char const * const known_coded_font_families[] = { "roman", "sans",
239 /// LaTeX 2.09 names for font series
240 char const * const known_old_font_series[] = { "bf", 0};
242 /// LaTeX names for font series
243 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
245 /// LaTeX names for font series changing commands
246 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
248 /// The same as known_old_font_series, known_font_series and
249 /// known_text_font_series with .lyx names
250 char const * const known_coded_font_series[] = { "bold", "medium", 0};
252 /// LaTeX 2.09 names for font shapes
253 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
255 /// LaTeX names for font shapes
256 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
259 /// LaTeX names for font shape changing commands
260 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
263 /// The same as known_old_font_shapes, known_font_shapes and
264 /// known_text_font_shapes with .lyx names
265 char const * const known_coded_font_shapes[] = { "italic", "slanted",
266 "smallcaps", "up", 0};
268 /// Known special characters which need skip_spaces_braces() afterwards
269 char const * const known_special_chars[] = {"ldots",
270 "lyxarrow", "textcompwordmark",
271 "slash", "textasciitilde", "textasciicircum", "textbackslash",
272 "LyX", "TeX", "LaTeXe",
275 /// special characters from known_special_chars which may have a \\protect before
276 char const * const known_special_protect_chars[] = {"LyX", "TeX",
277 "LaTeXe", "LaTeX", 0};
279 /// the same as known_special_chars with .lyx names
280 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
281 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
282 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
283 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
284 "\\SpecialChar LaTeX\n", 0};
287 * Graphics file extensions known by the dvips driver of the graphics package.
288 * These extensions are used to complete the filename of an included
289 * graphics file if it does not contain an extension.
290 * The order must be the same that latex uses to find a file, because we
291 * will use the first extension that matches.
292 * This is only an approximation for the common cases. If we would want to
293 * do it right in all cases, we would need to know which graphics driver is
294 * used and know the extensions of every driver of the graphics package.
296 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
297 "ps.gz", "eps.Z", "ps.Z", 0};
300 * Graphics file extensions known by the pdftex driver of the graphics package.
301 * \sa known_dvips_graphics_formats
303 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
307 * Known file extensions for TeX files as used by \\include.
309 char const * const known_tex_extensions[] = {"tex", 0};
311 /// spaces known by InsetSpace
312 char const * const known_spaces[] = { " ", "space", ",",
313 "thinspace", "quad", "qquad", "enspace", "enskip",
314 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
315 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
316 "upbracefill", "downbracefill", 0};
318 /// the same as known_spaces with .lyx names
319 char const * const known_coded_spaces[] = { "space{}", "space{}",
320 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
321 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
322 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
323 "upbracefill{}", "downbracefill{}", 0};
325 /// known TIPA combining diacritical marks
326 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
327 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
328 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
329 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
330 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
331 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
332 "textsubring", "textsubbar", 0};
334 /// TIPA tones that need special handling
335 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
337 // string to store the float type to be able to determine the type of subfloats
338 string float_type = "";
340 // string to store the float status of minted listings
341 string minted_float = "";
343 // whether a caption has been parsed for a floating minted listing
344 bool minted_float_has_caption = false;
346 // The caption for non-floating minted listings
347 string minted_nonfloat_caption = "";
349 // Characters that have to be escaped by \\ in LaTeX
350 char const * const known_escaped_chars[] = {
351 "&", "_", "$", "%", "#", "^", "{", "}", 0};
354 /// splits "x=z, y=b" into a map and an ordered keyword vector
355 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
360 keys.resize(v.size());
361 for (size_t i = 0; i < v.size(); ++i) {
362 size_t const pos = v[i].find('=');
363 string const index = trimSpaceAndEol(v[i].substr(0, pos));
364 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
372 * Split a LaTeX length into value and unit.
373 * The latter can be a real unit like "pt", or a latex length variable
374 * like "\textwidth". The unit may contain additional stuff like glue
375 * lengths, but we don't care, because such lengths are ERT anyway.
376 * \returns true if \p value and \p unit are valid.
378 bool splitLatexLength(string const & len, string & value, string & unit)
382 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
383 //'4,5' is a valid LaTeX length number. Change it to '4.5'
384 string const length = subst(len, ',', '.');
385 if (i == string::npos)
388 if (len[0] == '\\') {
389 // We had something like \textwidth without a factor
395 value = trimSpaceAndEol(string(length, 0, i));
399 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
400 if (contains(len, '\\'))
401 unit = trimSpaceAndEol(string(len, i));
403 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
408 /// A simple function to translate a latex length to something LyX can
409 /// understand. Not perfect, but rather best-effort.
410 bool translate_len(string const & length, string & valstring, string & unit)
412 if (!splitLatexLength(length, valstring, unit))
414 // LyX uses percent values
416 istringstream iss(valstring);
421 string const percentval = oss.str();
423 if (unit.empty() || unit[0] != '\\')
425 string::size_type const i = unit.find(' ');
426 string const endlen = (i == string::npos) ? string() : string(unit, i);
427 if (unit == "\\textwidth") {
428 valstring = percentval;
429 unit = "text%" + endlen;
430 } else if (unit == "\\columnwidth") {
431 valstring = percentval;
432 unit = "col%" + endlen;
433 } else if (unit == "\\paperwidth") {
434 valstring = percentval;
435 unit = "page%" + endlen;
436 } else if (unit == "\\linewidth") {
437 valstring = percentval;
438 unit = "line%" + endlen;
439 } else if (unit == "\\paperheight") {
440 valstring = percentval;
441 unit = "pheight%" + endlen;
442 } else if (unit == "\\textheight") {
443 valstring = percentval;
444 unit = "theight%" + endlen;
445 } else if (unit == "\\baselineskip") {
446 valstring = percentval;
447 unit = "baselineskip%" + endlen;
453 /// If we have ambiguous quotation marks, make a smart guess
454 /// based on main quote style
455 string guessQuoteStyle(string in, bool const opening)
458 if (prefixIs(in, "qr")) {// straight quote
460 res = subst(res, "r", "l");
461 } else if (in == "eld") {// ``
462 if (preamble.quotesStyle() == "german")
464 else if (preamble.quotesStyle() == "british")
466 else if (preamble.quotesStyle() == "french")
468 else if (preamble.quotesStyle() == "russian")
470 } else if (in == "erd") {// ''
471 if (preamble.quotesStyle() == "polish")
473 else if (preamble.quotesStyle() == "british")
475 else if (preamble.quotesStyle() == "french")
477 else if (preamble.quotesStyle() == "swedish")
478 res = opening ? "sld" : "srd";
479 } else if (in == "els") {// `
480 if (preamble.quotesStyle() == "german")
482 else if (preamble.quotesStyle() == "british")
484 } else if (in == "ers") {// '
485 if (preamble.quotesStyle() == "polish")
487 else if (preamble.quotesStyle() == "british")
489 else if (preamble.quotesStyle() == "swedish")
490 res = opening ? "sls" : "srs";
491 } else if (in == "ard") {// >>
492 if (preamble.quotesStyle() == "swiss")
494 else if (preamble.quotesStyle() == "french")
496 else if (preamble.quotesStyle() == "russian")
498 } else if (in == "ald") {// <<
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ars") {// >
506 if (preamble.quotesStyle() == "swiss")
508 } else if (in == "als") {// <
509 if (preamble.quotesStyle() == "swiss")
511 } else if (in == "gld") {// ,,
512 if (preamble.quotesStyle() == "polish")
514 else if (preamble.quotesStyle() == "russian")
516 } else if (in == "gls") {// ,
517 if (preamble.quotesStyle() == "polish")
527 string translate_len(string const & length)
531 if (translate_len(length, value, unit))
533 // If the input is invalid, return what we have.
541 * Translates a LaTeX length into \p value, \p unit and
542 * \p special parts suitable for a box inset.
543 * The difference from translate_len() is that a box inset knows about
544 * some special "units" that are stored in \p special.
546 void translate_box_len(string const & length, string & value, string & unit, string & special)
548 if (translate_len(length, value, unit)) {
549 if (unit == "\\height" || unit == "\\depth" ||
550 unit == "\\totalheight" || unit == "\\width") {
551 special = unit.substr(1);
552 // The unit is not used, but LyX requires a dummy setting
564 void begin_inset(ostream & os, string const & name)
566 os << "\n\\begin_inset " << name;
570 void begin_command_inset(ostream & os, string const & name,
571 string const & latexname)
573 begin_inset(os, "CommandInset ");
574 os << name << "\nLatexCommand " << latexname << '\n';
578 void end_inset(ostream & os)
580 os << "\n\\end_inset\n\n";
584 bool skip_braces(Parser & p)
586 if (p.next_token().cat() != catBegin)
589 if (p.next_token().cat() == catEnd) {
598 /// replace LaTeX commands in \p s from the unicodesymbols file with their
600 pair<bool, docstring> convert_unicodesymbols(docstring s)
604 for (size_t i = 0; i < s.size();) {
613 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
614 Encodings::TEXT_CMD, termination, rem, &req));
615 set<string>::const_iterator it = req.begin();
616 set<string>::const_iterator en = req.end();
617 for (; it != en; ++it)
618 preamble.registerAutomaticallyLoadedPackage(*it);
621 if (s.empty() || s[0] != '\\')
625 for (auto const & c : known_escaped_chars)
626 if (prefixIs(s, from_ascii("\\") + c))
631 return make_pair(res, os.str());
635 /// try to convert \p s to a valid InsetCommand argument
636 /// return whether this succeeded. If not, these command insets
637 /// get the "literate" flag.
638 pair<bool, string> convert_latexed_command_inset_arg(string s)
640 bool success = false;
642 // since we don't know the input encoding we can't use from_utf8
643 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
645 s = to_utf8(res.second);
647 // LyX cannot handle newlines in a latex command
648 return make_pair(success, subst(s, "\n", " "));
651 /// try to convert \p s to a valid InsetCommand argument
652 /// without trying to recode macros.
653 string convert_literate_command_inset_arg(string s)
655 // LyX cannot handle newlines in a latex command
656 return subst(s, "\n", " ");
659 void output_ert(ostream & os, string const & s, Context & context)
661 context.check_layout(os);
662 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
664 os << "\n\\backslash\n";
665 else if (*it == '\n') {
666 context.new_paragraph(os);
667 context.check_layout(os);
671 context.check_end_layout(os);
675 void output_ert_inset(ostream & os, string const & s, Context & context)
677 // We must have a valid layout before outputting the ERT inset.
678 context.check_layout(os);
679 Context newcontext(true, context.textclass);
680 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
681 if (layout.forcePlainLayout())
682 newcontext.layout = &context.textclass.plainLayout();
683 begin_inset(os, "ERT");
684 os << "\nstatus collapsed\n";
685 output_ert(os, s, newcontext);
690 void output_comment(Parser & p, ostream & os, string const & s,
693 if (p.next_token().cat() == catNewline)
694 output_ert_inset(os, '%' + s, context);
696 output_ert_inset(os, '%' + s + '\n', context);
700 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
702 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
705 if (checkModule(name, command))
706 return findLayoutWithoutModule(textclass, name, command);
711 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
713 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
716 if (checkModule(name, command))
717 return findInsetLayoutWithoutModule(textclass, name, command);
722 void eat_whitespace(Parser &, ostream &, Context &, bool);
726 * Skips whitespace and braces.
727 * This should be called after a command has been parsed that is not put into
728 * ERT, and where LyX adds "{}" if needed.
730 void skip_spaces_braces(Parser & p, bool keepws = false)
732 /* The following four examples produce the same typeset output and
733 should be handled by this function:
741 // Unfortunately we need to skip comments, too.
742 // We can't use eat_whitespace since writing them after the {}
743 // results in different output in some cases.
744 bool const skipped_spaces = p.skip_spaces(true);
745 bool const skipped_braces = skip_braces(p);
746 if (keepws && skipped_spaces && !skipped_braces)
747 // put back the space (it is better handled by check_space)
748 p.unskip_spaces(true);
752 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
753 Context & context, Layout::LaTeXArgMap const & latexargs)
756 context.check_layout(os);
761 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
762 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
763 for (; lait != laend; ++lait) {
765 eat_whitespace(p, os, context, false);
766 if (lait->second.mandatory) {
767 if (p.next_token().cat() != catBegin)
769 string ldelim = to_utf8(lait->second.ldelim);
770 string rdelim = to_utf8(lait->second.rdelim);
775 p.get_token(); // eat ldelim
776 if (ldelim.size() > 1)
777 p.get_token(); // eat ldelim
779 context.check_layout(os);
782 begin_inset(os, "Argument ");
785 os << i << "\nstatus collapsed\n\n";
786 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
789 string ldelim = to_utf8(lait->second.ldelim);
790 string rdelim = to_utf8(lait->second.rdelim);
795 string tok = p.next_token().asInput();
796 // we only support delimiters with max 2 chars for now.
797 if (ldelim.size() > 1)
798 tok += p.next_next_token().asInput();
799 if (p.next_token().cat() == catEscape || tok != ldelim)
801 p.get_token(); // eat ldelim
802 if (ldelim.size() > 1)
803 p.get_token(); // eat ldelim
805 context.check_layout(os);
808 begin_inset(os, "Argument ");
811 os << i << "\nstatus collapsed\n\n";
812 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
815 eat_whitespace(p, os, context, false);
820 void output_command_layout(ostream & os, Parser & p, bool outer,
821 Context & parent_context,
822 Layout const * newlayout)
824 TeXFont const oldFont = parent_context.font;
825 // save the current font size
826 string const size = oldFont.size;
827 // reset the font size to default, because the font size switches
828 // don't affect section headings and the like
829 parent_context.font.size = Context::normalfont.size;
830 // we only need to write the font change if we have an open layout
831 if (!parent_context.atParagraphStart())
832 output_font_change(os, oldFont, parent_context.font);
833 parent_context.check_end_layout(os);
834 Context context(true, parent_context.textclass, newlayout,
835 parent_context.layout, parent_context.font);
836 if (parent_context.deeper_paragraph) {
837 // We are beginning a nested environment after a
838 // deeper paragraph inside the outer list environment.
839 // Therefore we don't need to output a "begin deeper".
840 context.need_end_deeper = true;
842 context.check_deeper(os);
843 output_arguments(os, p, outer, true, false, context,
844 context.layout->latexargs());
845 parse_text(p, os, FLAG_ITEM, outer, context);
846 output_arguments(os, p, outer, false, true, context,
847 context.layout->postcommandargs());
848 context.check_end_layout(os);
849 if (parent_context.deeper_paragraph) {
850 // We must suppress the "end deeper" because we
851 // suppressed the "begin deeper" above.
852 context.need_end_deeper = false;
854 context.check_end_deeper(os);
855 // We don't need really a new paragraph, but
856 // we must make sure that the next item gets a \begin_layout.
857 parent_context.new_paragraph(os);
858 // Set the font size to the original value. No need to output it here
859 // (Context::begin_layout() will do that if needed)
860 parent_context.font.size = size;
865 * Output a space if necessary.
866 * This function gets called for every whitespace token.
868 * We have three cases here:
869 * 1. A space must be suppressed. Example: The lyxcode case below
870 * 2. A space may be suppressed. Example: Spaces before "\par"
871 * 3. A space must not be suppressed. Example: A space between two words
873 * We currently handle only 1. and 3 and from 2. only the case of
874 * spaces before newlines as a side effect.
876 * 2. could be used to suppress as many spaces as possible. This has two effects:
877 * - Reimporting LyX generated LaTeX files changes almost no whitespace
878 * - Superflous whitespace from non LyX generated LaTeX files is removed.
879 * The drawback is that the logic inside the function becomes
880 * complicated, and that is the reason why it is not implemented.
882 void check_space(Parser & p, ostream & os, Context & context)
884 Token const next = p.next_token();
885 Token const curr = p.curr_token();
886 // A space before a single newline and vice versa must be ignored
887 // LyX emits a newline before \end{lyxcode}.
888 // This newline must be ignored,
889 // otherwise LyX will add an additional protected space.
890 if (next.cat() == catSpace ||
891 next.cat() == catNewline ||
892 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
895 context.check_layout(os);
901 * Parse all arguments of \p command
903 void parse_arguments(string const & command,
904 vector<ArgumentType> const & template_arguments,
905 Parser & p, ostream & os, bool outer, Context & context)
907 string ert = command;
908 size_t no_arguments = template_arguments.size();
909 for (size_t i = 0; i < no_arguments; ++i) {
910 switch (template_arguments[i]) {
913 // This argument contains regular LaTeX
914 output_ert_inset(os, ert + '{', context);
915 eat_whitespace(p, os, context, false);
916 if (template_arguments[i] == required)
917 parse_text(p, os, FLAG_ITEM, outer, context);
919 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
923 // This argument consists only of a single item.
924 // The presence of '{' or not must be preserved.
926 if (p.next_token().cat() == catBegin)
927 ert += '{' + p.verbatim_item() + '}';
929 ert += p.verbatim_item();
933 // This argument may contain special characters
934 ert += '{' + p.verbatim_item() + '}';
938 // true because we must not eat whitespace
939 // if an optional arg follows we must not strip the
940 // brackets from this one
941 if (i < no_arguments - 1 &&
942 template_arguments[i+1] == optional)
943 ert += p.getFullOpt(true);
945 ert += p.getOpt(true);
949 output_ert_inset(os, ert, context);
954 * Check whether \p command is a known command. If yes,
955 * handle the command with all arguments.
956 * \return true if the command was parsed, false otherwise.
958 bool parse_command(string const & command, Parser & p, ostream & os,
959 bool outer, Context & context)
961 if (known_commands.find(command) != known_commands.end()) {
962 parse_arguments(command, known_commands[command], p, os,
970 /// Parses a minipage or parbox
971 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
972 unsigned inner_flags, bool outer, Context & parent_context,
973 string const & outer_type, string const & special,
974 string inner_type, string const & frame_color,
975 string const & background_color)
979 string hor_pos = "l";
980 // We need to set the height to the LaTeX default of 1\\totalheight
981 // for the case when no height argument is given
982 string height_value = "1";
983 string height_unit = "in";
984 string height_special = "totalheight";
989 string width_special = "none";
990 string thickness = "0.4pt";
991 if (!fboxrule.empty())
992 thickness = fboxrule;
996 if (!fboxsep.empty())
997 separation = fboxsep;
1001 if (!shadow_size.empty())
1002 shadowsize = shadow_size;
1005 string framecolor = "black";
1006 string backgroundcolor = "none";
1007 if (!frame_color.empty())
1008 framecolor = frame_color;
1009 if (!background_color.empty())
1010 backgroundcolor = background_color;
1011 // if there is a color box around the \begin statements have not yet been parsed
1013 if (!frame_color.empty() || !background_color.empty()) {
1014 eat_whitespace(p, os, parent_context, false);
1015 p.get_token().asInput(); // the '{'
1017 if (p.next_token().asInput() == "\\begin") {
1018 p.get_token().asInput();
1020 inner_type = "minipage";
1021 inner_flags = FLAG_END;
1022 active_environments.push_back("minipage");
1025 else if (p.next_token().asInput() == "\\parbox") {
1026 p.get_token().asInput();
1027 inner_type = "parbox";
1028 inner_flags = FLAG_ITEM;
1031 else if (p.next_token().asInput() == "\\makebox") {
1032 p.get_token().asInput();
1033 inner_type = "makebox";
1034 inner_flags = FLAG_ITEM;
1036 // in case there is just \colorbox{color}{text}
1039 inner_type = "makebox";
1040 inner_flags = FLAG_BRACE_LAST;
1045 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1047 if (!inner_type.empty() && p.hasOpt()) {
1048 if (inner_type != "makebox")
1049 position = p.getArg('[', ']');
1051 latex_width = p.getArg('[', ']');
1052 translate_box_len(latex_width, width_value, width_unit, width_special);
1055 if (position != "t" && position != "c" && position != "b") {
1056 cerr << "invalid position " << position << " for "
1057 << inner_type << endl;
1061 if (inner_type != "makebox") {
1062 latex_height = p.getArg('[', ']');
1063 translate_box_len(latex_height, height_value, height_unit, height_special);
1065 string const opt = p.getArg('[', ']');
1068 if (hor_pos != "l" && hor_pos != "c" &&
1069 hor_pos != "r" && hor_pos != "s") {
1070 cerr << "invalid hor_pos " << hor_pos
1071 << " for " << inner_type << endl;
1078 inner_pos = p.getArg('[', ']');
1079 if (inner_pos != "c" && inner_pos != "t" &&
1080 inner_pos != "b" && inner_pos != "s") {
1081 cerr << "invalid inner_pos "
1082 << inner_pos << " for "
1083 << inner_type << endl;
1084 inner_pos = position;
1088 if (inner_type == "makebox")
1092 if (inner_type.empty()) {
1093 if (special.empty() && outer_type != "framebox")
1094 latex_width = "1\\columnwidth";
1097 latex_width = p2.getArg('[', ']');
1098 string const opt = p2.getArg('[', ']');
1101 if (hor_pos != "l" && hor_pos != "c" &&
1102 hor_pos != "r" && hor_pos != "s") {
1103 cerr << "invalid hor_pos " << hor_pos
1104 << " for " << outer_type << endl;
1108 if (outer_type == "framebox")
1112 } else if (inner_type != "makebox")
1113 latex_width = p.verbatim_item();
1114 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1115 // as this is LyX's standard for such cases (except for makebox)
1116 // \framebox is more special and handled below
1117 if (latex_width.empty() && inner_type != "makebox"
1118 && outer_type != "framebox")
1119 latex_width = "1\\columnwidth";
1121 translate_len(latex_width, width_value, width_unit);
1123 bool shadedparbox = false;
1124 if (inner_type == "shaded") {
1125 eat_whitespace(p, os, parent_context, false);
1126 if (outer_type == "parbox") {
1128 if (p.next_token().cat() == catBegin)
1130 eat_whitespace(p, os, parent_context, false);
1131 shadedparbox = true;
1136 // If we already read the inner box we have to push the inner env
1137 if (!outer_type.empty() && !inner_type.empty() &&
1138 (inner_flags & FLAG_END))
1139 active_environments.push_back(inner_type);
1140 bool use_ert = false;
1141 if (!outer_type.empty() && !inner_type.empty()) {
1142 // Look whether there is some content after the end of the
1143 // inner box, but before the end of the outer box.
1144 // If yes, we need to output ERT.
1146 if (inner_flags & FLAG_END)
1147 p.ertEnvironment(inner_type);
1150 p.skip_spaces(true);
1151 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1152 if ((outer_env && p.next_token().asInput() != "\\end") ||
1153 (!outer_env && p.next_token().cat() != catEnd)) {
1154 // something is between the end of the inner box and
1155 // the end of the outer box, so we need to use ERT.
1163 if (!outer_type.empty()) {
1164 if (outer_flags & FLAG_END)
1165 ss << "\\begin{" << outer_type << '}';
1167 ss << '\\' << outer_type << '{';
1168 if (!special.empty())
1172 if (!inner_type.empty()) {
1173 if (inner_type != "shaded") {
1174 if (inner_flags & FLAG_END)
1175 ss << "\\begin{" << inner_type << '}';
1177 ss << '\\' << inner_type;
1179 if (!position.empty())
1180 ss << '[' << position << ']';
1181 if (!latex_height.empty())
1182 ss << '[' << latex_height << ']';
1183 if (!inner_pos.empty())
1184 ss << '[' << inner_pos << ']';
1185 ss << '{' << latex_width << '}';
1186 if (!(inner_flags & FLAG_END))
1189 if (inner_type == "shaded")
1190 ss << "\\begin{shaded}";
1191 output_ert_inset(os, ss.str(), parent_context);
1192 if (!inner_type.empty()) {
1193 parse_text(p, os, inner_flags, outer, parent_context);
1194 if (inner_flags & FLAG_END)
1195 output_ert_inset(os, "\\end{" + inner_type + '}',
1198 output_ert_inset(os, "}", parent_context);
1200 if (!outer_type.empty()) {
1201 // If we already read the inner box we have to pop
1203 if (!inner_type.empty() && (inner_flags & FLAG_END))
1204 active_environments.pop_back();
1206 // Ensure that the end of the outer box is parsed correctly:
1207 // The opening brace has been eaten by parse_outer_box()
1208 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1209 outer_flags &= ~FLAG_ITEM;
1210 outer_flags |= FLAG_BRACE_LAST;
1212 parse_text(p, os, outer_flags, outer, parent_context);
1213 if (outer_flags & FLAG_END)
1214 output_ert_inset(os, "\\end{" + outer_type + '}',
1217 output_ert_inset(os, "}", parent_context);
1220 // LyX does not like empty positions, so we have
1221 // to set them to the LaTeX default values here.
1222 if (position.empty())
1224 if (inner_pos.empty())
1225 inner_pos = position;
1226 parent_context.check_layout(os);
1227 begin_inset(os, "Box ");
1228 if (outer_type == "framed")
1230 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1232 else if (outer_type == "shadowbox")
1233 os << "Shadowbox\n";
1234 else if ((outer_type == "shaded" && inner_type.empty()) ||
1235 (outer_type == "minipage" && inner_type == "shaded") ||
1236 (outer_type == "parbox" && inner_type == "shaded")) {
1238 preamble.registerAutomaticallyLoadedPackage("color");
1239 } else if (outer_type == "doublebox")
1240 os << "Doublebox\n";
1241 else if (outer_type.empty() || outer_type == "mbox")
1242 os << "Frameless\n";
1244 os << outer_type << '\n';
1245 os << "position \"" << position << "\"\n";
1246 os << "hor_pos \"" << hor_pos << "\"\n";
1247 if (outer_type == "mbox")
1248 os << "has_inner_box 1\n";
1249 else if (!frame_color.empty() && inner_type == "makebox")
1250 os << "has_inner_box 0\n";
1252 os << "has_inner_box " << !inner_type.empty() << "\n";
1253 os << "inner_pos \"" << inner_pos << "\"\n";
1254 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1256 if (outer_type == "mbox")
1257 os << "use_makebox 1\n";
1258 else if (!frame_color.empty())
1259 os << "use_makebox 0\n";
1261 os << "use_makebox " << (inner_type == "makebox") << '\n';
1262 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1263 os << "width \"\"\n";
1264 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1265 else if (contains(width_unit, '\\'))
1266 os << "width \"" << width_value << "in" << "\"\n";
1268 os << "width \"" << width_value << width_unit << "\"\n";
1269 if (contains(width_unit, '\\')) {
1270 width_unit.erase (0,1); // remove the leading '\'
1271 os << "special \"" << width_unit << "\"\n";
1273 os << "special \"" << width_special << "\"\n";
1274 if (contains(height_unit, '\\'))
1275 os << "height \"" << height_value << "in" << "\"\n";
1277 os << "height \"" << height_value << height_unit << "\"\n";
1278 os << "height_special \"" << height_special << "\"\n";
1279 os << "thickness \"" << thickness << "\"\n";
1280 os << "separation \"" << separation << "\"\n";
1281 os << "shadowsize \"" << shadowsize << "\"\n";
1282 os << "framecolor \"" << framecolor << "\"\n";
1283 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1284 os << "status open\n\n";
1286 // Unfortunately we can't use parse_text_in_inset:
1287 // InsetBox::forcePlainLayout() is hard coded and does not
1288 // use the inset layout. Apart from that do we call parse_text
1289 // up to two times, but need only one check_end_layout.
1290 bool const forcePlainLayout =
1291 (!inner_type.empty() || inner_type == "makebox") &&
1292 outer_type != "shaded" && outer_type != "framed";
1293 Context context(true, parent_context.textclass);
1294 if (forcePlainLayout)
1295 context.layout = &context.textclass.plainLayout();
1297 context.font = parent_context.font;
1299 // If we have no inner box the contents will be read with the outer box
1300 if (!inner_type.empty())
1301 parse_text(p, os, inner_flags, outer, context);
1303 // Ensure that the end of the outer box is parsed correctly:
1304 // The opening brace has been eaten by parse_outer_box()
1305 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1306 outer_flags &= ~FLAG_ITEM;
1307 outer_flags |= FLAG_BRACE_LAST;
1310 // Find end of outer box, output contents if inner_type is
1311 // empty and output possible comments
1312 if (!outer_type.empty()) {
1313 // If we already read the inner box we have to pop
1315 if (!inner_type.empty() && (inner_flags & FLAG_END))
1316 active_environments.pop_back();
1317 // This does not output anything but comments if
1318 // inner_type is not empty (see use_ert)
1319 parse_text(p, os, outer_flags, outer, context);
1322 context.check_end_layout(os);
1324 #ifdef PRESERVE_LAYOUT
1325 // LyX puts a % after the end of the minipage
1326 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1328 //output_comment(p, os, "dummy", parent_context);
1331 parent_context.new_paragraph(os);
1333 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1334 //output_comment(p, os, "dummy", parent_context);
1337 // We add a protected space if something real follows
1338 if (p.good() && p.next_token().cat() != catComment) {
1339 begin_inset(os, "space ~\n");
1345 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1346 active_environments.pop_back();
1347 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1348 // in this case we have to eat the the closing brace of the color box
1349 p.get_token().asInput(); // the '}'
1351 if (p.next_token().asInput() == "}") {
1352 // in this case we assume that the closing brace is from the box settings
1353 // therefore reset these values for the next box
1359 // all boxes except of Frameless and Shaded require calc
1360 if (!(outer_type.empty() || outer_type == "mbox") &&
1361 !((outer_type == "shaded" && inner_type.empty()) ||
1362 (outer_type == "minipage" && inner_type == "shaded") ||
1363 (outer_type == "parbox" && inner_type == "shaded")))
1364 preamble.registerAutomaticallyLoadedPackage("calc");
1368 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1369 Context & parent_context, string const & outer_type,
1370 string const & special)
1372 eat_whitespace(p, os, parent_context, false);
1373 if (flags & FLAG_ITEM) {
1375 if (p.next_token().cat() == catBegin)
1378 cerr << "Warning: Ignoring missing '{' after \\"
1379 << outer_type << '.' << endl;
1380 eat_whitespace(p, os, parent_context, false);
1383 unsigned int inner_flags = 0;
1385 if (outer_type == "minipage" || outer_type == "parbox") {
1386 p.skip_spaces(true);
1387 while (p.hasOpt()) {
1389 p.skip_spaces(true);
1392 p.skip_spaces(true);
1393 if (outer_type == "parbox") {
1395 if (p.next_token().cat() == catBegin)
1397 p.skip_spaces(true);
1400 if (outer_type == "shaded" || outer_type == "mbox") {
1401 // These boxes never have an inner box
1403 } else if (p.next_token().asInput() == "\\parbox") {
1404 inner = p.get_token().cs();
1405 inner_flags = FLAG_ITEM;
1406 } else if (p.next_token().asInput() == "\\begin") {
1407 // Is this a minipage or shaded box?
1410 inner = p.getArg('{', '}');
1412 if (inner == "minipage" || inner == "shaded")
1413 inner_flags = FLAG_END;
1418 if (inner_flags == FLAG_END) {
1419 if (inner != "shaded")
1423 eat_whitespace(p, os, parent_context, false);
1425 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1426 outer_type, special, inner, "", "");
1428 if (inner_flags == FLAG_ITEM) {
1430 eat_whitespace(p, os, parent_context, false);
1432 parse_box(p, os, flags, inner_flags, outer, parent_context,
1433 outer_type, special, inner, "", "");
1438 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1439 bool in_line, bool use_minted)
1441 parent_context.check_layout(os);
1442 begin_inset(os, "listings\n");
1443 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1445 while ((i = arg.find(", ")) != string::npos
1446 || (i = arg.find(",\t")) != string::npos)
1447 arg.erase(i + 1, 1);
1450 string const language = p.getArg('{', '}');
1451 p.skip_spaces(true);
1452 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1453 if (!minted_float.empty()) {
1454 arg += string(arg.empty() ? "" : ",") + minted_float;
1455 minted_nonfloat_caption.clear();
1459 os << "lstparams " << '"' << arg << '"' << '\n';
1460 if (arg.find("\\color") != string::npos)
1461 preamble.registerAutomaticallyLoadedPackage("color");
1464 os << "inline true\n";
1466 os << "inline false\n";
1467 os << "status collapsed\n";
1468 Context context(true, parent_context.textclass);
1469 context.layout = &parent_context.textclass.plainLayout();
1470 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1471 minted_nonfloat_caption.erase(0,3);
1472 os << "\n\\begin_layout Plain Layout\n";
1473 begin_inset(os, "Caption Standard\n");
1474 Context newcontext(true, context.textclass,
1475 context.layout, 0, context.font);
1476 newcontext.check_layout(os);
1477 os << minted_nonfloat_caption << "\n";
1478 newcontext.check_end_layout(os);
1480 os << "\n\\end_layout\n";
1481 minted_nonfloat_caption.clear();
1485 // set catcodes to verbatim early, just in case.
1486 p.setCatcodes(VERBATIM_CATCODES);
1487 string delim = p.get_token().asInput();
1488 //FIXME: handler error condition
1489 s = p.verbatimStuff(delim).second;
1490 // context.new_paragraph(os);
1491 } else if (use_minted) {
1492 s = p.verbatimEnvironment("minted");
1494 s = p.verbatimEnvironment("lstlisting");
1496 output_ert(os, s, context);
1497 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1498 minted_nonfloat_caption.erase(0,3);
1499 os << "\n\\begin_layout Plain Layout\n";
1500 begin_inset(os, "Caption Standard\n");
1501 Context newcontext(true, context.textclass,
1502 context.layout, 0, context.font);
1503 newcontext.check_layout(os);
1504 os << minted_nonfloat_caption << "\n";
1505 newcontext.check_end_layout(os);
1507 os << "\n\\end_layout\n";
1508 minted_nonfloat_caption.clear();
1510 // Don't close the inset here for floating minted listings.
1511 // It will be closed at the end of the listing environment.
1512 if (!use_minted || minted_float.empty())
1515 eat_whitespace(p, os, parent_context, true);
1516 Token t = p.get_token();
1517 if (t.asInput() != "\\end") {
1518 // If anything follows, collect it into a caption.
1519 minted_float_has_caption = true;
1520 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1521 begin_inset(os, "Caption Standard\n");
1522 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1529 /// parse an unknown environment
1530 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1531 unsigned flags, bool outer,
1532 Context & parent_context)
1534 if (name == "tabbing")
1535 // We need to remember that we have to handle '\=' specially
1536 flags |= FLAG_TABBING;
1538 // We need to translate font changes and paragraphs inside the
1539 // environment to ERT if we have a non standard font.
1540 // Otherwise things like
1541 // \large\begin{foo}\huge bar\end{foo}
1543 bool const specialfont =
1544 (parent_context.font != parent_context.normalfont);
1545 bool const new_layout_allowed = parent_context.new_layout_allowed;
1547 parent_context.new_layout_allowed = false;
1548 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1549 parse_text_snippet(p, os, flags, outer, parent_context);
1550 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1552 parent_context.new_layout_allowed = new_layout_allowed;
1556 void parse_environment(Parser & p, ostream & os, bool outer,
1557 string & last_env, Context & parent_context)
1559 Layout const * newlayout;
1560 InsetLayout const * newinsetlayout = 0;
1561 string const name = p.getArg('{', '}');
1562 const bool is_starred = suffixIs(name, '*');
1563 string const unstarred_name = rtrim(name, "*");
1564 active_environments.push_back(name);
1566 if (is_math_env(name)) {
1567 parent_context.check_layout(os);
1568 begin_inset(os, "Formula ");
1569 os << "\\begin{" << name << "}";
1570 parse_math(p, os, FLAG_END, MATH_MODE);
1571 os << "\\end{" << name << "}";
1573 if (is_display_math_env(name)) {
1574 // Prevent the conversion of a line break to a space
1575 // (bug 7668). This does not change the output, but
1576 // looks ugly in LyX.
1577 eat_whitespace(p, os, parent_context, false);
1581 else if (is_known(name, preamble.polyglossia_languages)) {
1582 // We must begin a new paragraph if not already done
1583 if (! parent_context.atParagraphStart()) {
1584 parent_context.check_end_layout(os);
1585 parent_context.new_paragraph(os);
1587 // save the language in the context so that it is
1588 // handled by parse_text
1589 parent_context.font.language = preamble.polyglossia2lyx(name);
1590 parse_text(p, os, FLAG_END, outer, parent_context);
1591 // Just in case the environment is empty
1592 parent_context.extra_stuff.erase();
1593 // We must begin a new paragraph to reset the language
1594 parent_context.new_paragraph(os);
1598 else if (unstarred_name == "tabular" || name == "longtable") {
1599 eat_whitespace(p, os, parent_context, false);
1600 string width = "0pt";
1601 if (name == "tabular*") {
1602 width = lyx::translate_len(p.getArg('{', '}'));
1603 eat_whitespace(p, os, parent_context, false);
1605 parent_context.check_layout(os);
1606 begin_inset(os, "Tabular ");
1607 handle_tabular(p, os, name, width, parent_context);
1612 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1613 eat_whitespace(p, os, parent_context, false);
1614 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1615 eat_whitespace(p, os, parent_context, false);
1616 parent_context.check_layout(os);
1617 begin_inset(os, "Float " + unstarred_name + "\n");
1618 // store the float type for subfloats
1619 // subfloats only work with figures and tables
1620 if (unstarred_name == "figure")
1621 float_type = unstarred_name;
1622 else if (unstarred_name == "table")
1623 float_type = unstarred_name;
1627 os << "placement " << opt << '\n';
1628 if (contains(opt, "H"))
1629 preamble.registerAutomaticallyLoadedPackage("float");
1631 Floating const & fl = parent_context.textclass.floats()
1632 .getType(unstarred_name);
1633 if (!fl.floattype().empty() && fl.usesFloatPkg())
1634 preamble.registerAutomaticallyLoadedPackage("float");
1637 os << "wide " << convert<string>(is_starred)
1638 << "\nsideways false"
1639 << "\nstatus open\n\n";
1640 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1642 // We don't need really a new paragraph, but
1643 // we must make sure that the next item gets a \begin_layout.
1644 parent_context.new_paragraph(os);
1646 // the float is parsed thus delete the type
1650 else if (unstarred_name == "sidewaysfigure"
1651 || unstarred_name == "sidewaystable"
1652 || unstarred_name == "sidewaysalgorithm") {
1653 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1654 eat_whitespace(p, os, parent_context, false);
1655 parent_context.check_layout(os);
1656 if (unstarred_name == "sidewaysfigure")
1657 begin_inset(os, "Float figure\n");
1658 else if (unstarred_name == "sidewaystable")
1659 begin_inset(os, "Float table\n");
1660 else if (unstarred_name == "sidewaysalgorithm")
1661 begin_inset(os, "Float algorithm\n");
1663 os << "placement " << opt << '\n';
1664 if (contains(opt, "H"))
1665 preamble.registerAutomaticallyLoadedPackage("float");
1666 os << "wide " << convert<string>(is_starred)
1667 << "\nsideways true"
1668 << "\nstatus open\n\n";
1669 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1671 // We don't need really a new paragraph, but
1672 // we must make sure that the next item gets a \begin_layout.
1673 parent_context.new_paragraph(os);
1675 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1678 else if (name == "wrapfigure" || name == "wraptable") {
1679 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1680 eat_whitespace(p, os, parent_context, false);
1681 parent_context.check_layout(os);
1684 string overhang = "0col%";
1687 lines = p.getArg('[', ']');
1688 string const placement = p.getArg('{', '}');
1690 overhang = p.getArg('[', ']');
1691 string const width = p.getArg('{', '}');
1693 if (name == "wrapfigure")
1694 begin_inset(os, "Wrap figure\n");
1696 begin_inset(os, "Wrap table\n");
1697 os << "lines " << lines
1698 << "\nplacement " << placement
1699 << "\noverhang " << lyx::translate_len(overhang)
1700 << "\nwidth " << lyx::translate_len(width)
1701 << "\nstatus open\n\n";
1702 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1704 // We don't need really a new paragraph, but
1705 // we must make sure that the next item gets a \begin_layout.
1706 parent_context.new_paragraph(os);
1708 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1711 else if (name == "minipage") {
1712 eat_whitespace(p, os, parent_context, false);
1713 // Test whether this is an outer box of a shaded box
1715 // swallow arguments
1716 while (p.hasOpt()) {
1718 p.skip_spaces(true);
1721 p.skip_spaces(true);
1722 Token t = p.get_token();
1723 bool shaded = false;
1724 if (t.asInput() == "\\begin") {
1725 p.skip_spaces(true);
1726 if (p.getArg('{', '}') == "shaded")
1731 parse_outer_box(p, os, FLAG_END, outer,
1732 parent_context, name, "shaded");
1734 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1735 "", "", name, "", "");
1739 else if (name == "comment") {
1740 eat_whitespace(p, os, parent_context, false);
1741 parent_context.check_layout(os);
1742 begin_inset(os, "Note Comment\n");
1743 os << "status open\n";
1744 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1747 skip_braces(p); // eat {} that might by set by LyX behind comments
1748 preamble.registerAutomaticallyLoadedPackage("verbatim");
1751 else if (unstarred_name == "verbatim") {
1752 // FIXME: this should go in the generic code that
1753 // handles environments defined in layout file that
1754 // have "PassThru 1". However, the code over there is
1755 // already too complicated for my taste.
1756 string const ascii_name =
1757 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1758 parent_context.new_paragraph(os);
1759 Context context(true, parent_context.textclass,
1760 &parent_context.textclass[from_ascii(ascii_name)]);
1761 string s = p.verbatimEnvironment(name);
1762 output_ert(os, s, context);
1766 else if (name == "IPA") {
1767 eat_whitespace(p, os, parent_context, false);
1768 parent_context.check_layout(os);
1769 begin_inset(os, "IPA\n");
1770 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1773 preamble.registerAutomaticallyLoadedPackage("tipa");
1774 preamble.registerAutomaticallyLoadedPackage("tipx");
1777 else if (name == "CJK") {
1778 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1779 // It is impossible to decide if a CJK environment was in its own paragraph or within
1780 // a line. We therefore always assume a paragraph since the latter is a rare case.
1781 eat_whitespace(p, os, parent_context, false);
1782 parent_context.check_end_layout(os);
1783 // store the encoding to be able to reset it
1784 string const encoding_old = p.getEncoding();
1785 string const encoding = p.getArg('{', '}');
1786 // FIXME: For some reason JIS does not work. Although the text
1787 // in tests/CJK.tex is identical with the SJIS version if you
1788 // convert both snippets using the recode command line utility,
1789 // the resulting .lyx file contains some extra characters if
1790 // you set buggy_encoding to false for JIS.
1791 bool const buggy_encoding = encoding == "JIS";
1792 if (!buggy_encoding)
1793 p.setEncoding(encoding, Encoding::CJK);
1795 // FIXME: This will read garbage, since the data is not encoded in utf8.
1796 p.setEncoding("UTF-8");
1798 // LyX only supports the same mapping for all CJK
1799 // environments, so we might need to output everything as ERT
1800 string const mapping = trim(p.getArg('{', '}'));
1801 char const * const * const where =
1802 is_known(encoding, supported_CJK_encodings);
1803 if (!buggy_encoding && !preamble.fontCJKSet())
1804 preamble.fontCJK(mapping);
1805 bool knownMapping = mapping == preamble.fontCJK();
1806 if (buggy_encoding || !knownMapping || !where) {
1807 parent_context.check_layout(os);
1808 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1810 // we must parse the content as verbatim because e.g. JIS can contain
1811 // normally invalid characters
1812 // FIXME: This works only for the most simple cases.
1813 // Since TeX control characters are not parsed,
1814 // things like comments are completely wrong.
1815 string const s = p.plainEnvironment("CJK");
1816 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1819 if (snip == "\\" || is_known(snip, known_escaped_chars))
1820 output_ert_inset(os, snip, parent_context);
1821 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1826 output_ert_inset(os, "\\end{" + name + "}",
1830 supported_CJK_languages[where - supported_CJK_encodings];
1831 // store the language because we must reset it at the end
1832 string const lang_old = parent_context.font.language;
1833 parent_context.font.language = lang;
1834 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1835 parent_context.font.language = lang_old;
1836 parent_context.new_paragraph(os);
1838 p.setEncoding(encoding_old);
1842 else if (name == "lyxgreyedout") {
1843 eat_whitespace(p, os, parent_context, false);
1844 parent_context.check_layout(os);
1845 begin_inset(os, "Note Greyedout\n");
1846 os << "status open\n";
1847 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1850 if (!preamble.notefontcolor().empty())
1851 preamble.registerAutomaticallyLoadedPackage("color");
1854 else if (name == "btSect") {
1855 eat_whitespace(p, os, parent_context, false);
1856 parent_context.check_layout(os);
1857 begin_command_inset(os, "bibtex", "bibtex");
1858 string bibstyle = "plain";
1860 bibstyle = p.getArg('[', ']');
1861 p.skip_spaces(true);
1863 string const bibfile = p.getArg('{', '}');
1864 eat_whitespace(p, os, parent_context, false);
1865 Token t = p.get_token();
1866 if (t.asInput() == "\\btPrintCited") {
1867 p.skip_spaces(true);
1868 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1870 if (t.asInput() == "\\btPrintNotCited") {
1871 p.skip_spaces(true);
1872 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1874 if (t.asInput() == "\\btPrintAll") {
1875 p.skip_spaces(true);
1876 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1878 os << "bibfiles " << '"' << bibfile << "\"\n"
1879 << "options " << '"' << bibstyle << "\"\n";
1880 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1885 else if (name == "framed" || name == "shaded") {
1886 eat_whitespace(p, os, parent_context, false);
1887 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1889 preamble.registerAutomaticallyLoadedPackage("framed");
1892 else if (name == "listing") {
1893 minted_float = "float";
1894 eat_whitespace(p, os, parent_context, false);
1895 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1897 minted_float += "=" + opt;
1898 // If something precedes \begin{minted}, we output it at the end
1899 // as a caption, in order to keep it inside the listings inset.
1900 eat_whitespace(p, os, parent_context, true);
1902 Token const & t = p.get_token();
1903 p.skip_spaces(true);
1904 string const envname = p.next_token().cat() == catBegin
1905 ? p.getArg('{', '}') : string();
1906 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1908 minted_float_has_caption = false;
1909 string content = parse_text_snippet(p, FLAG_END, outer,
1911 size_t i = content.find("\\begin_inset listings");
1912 bool minted_env = i != string::npos;
1915 caption = content.substr(0, i);
1916 content.erase(0, i);
1918 parent_context.check_layout(os);
1919 if (minted_env && minted_float_has_caption) {
1920 eat_whitespace(p, os, parent_context, true);
1921 os << content << "\n";
1922 if (!caption.empty())
1923 os << caption << "\n";
1924 os << "\n\\end_layout\n"; // close inner layout
1925 end_inset(os); // close caption inset
1926 os << "\n\\end_layout\n"; // close outer layout
1927 } else if (!caption.empty()) {
1929 begin_inset(os, "listings\n");
1930 os << "lstparams " << '"' << minted_float << '"' << '\n';
1931 os << "inline false\n";
1932 os << "status collapsed\n";
1934 os << "\n\\begin_layout Plain Layout\n";
1935 begin_inset(os, "Caption Standard\n");
1936 Context newcontext(true, parent_context.textclass,
1937 0, 0, parent_context.font);
1938 newcontext.check_layout(os);
1939 os << caption << "\n";
1940 newcontext.check_end_layout(os);
1942 os << "\n\\end_layout\n";
1943 } else if (content.empty()) {
1944 begin_inset(os, "listings\n");
1945 os << "lstparams " << '"' << minted_float << '"' << '\n';
1946 os << "inline false\n";
1947 os << "status collapsed\n";
1949 os << content << "\n";
1951 end_inset(os); // close listings inset
1952 parent_context.check_end_layout(os);
1953 parent_context.new_paragraph(os);
1955 minted_float.clear();
1956 minted_float_has_caption = false;
1959 else if (name == "lstlisting" || name == "minted") {
1960 bool use_minted = name == "minted";
1961 eat_whitespace(p, os, parent_context, false);
1962 if (use_minted && minted_float.empty()) {
1963 // look ahead for a bottom caption
1965 bool found_end_minted = false;
1966 while (!found_end_minted && p.good()) {
1967 Token const & t = p.get_token();
1969 string const envname =
1970 p.next_token().cat() == catBegin
1971 ? p.getArg('{', '}') : string();
1972 found_end_minted = t.asInput() == "\\end"
1973 && envname == "minted";
1975 eat_whitespace(p, os, parent_context, true);
1976 Token const & t = p.get_token();
1977 p.skip_spaces(true);
1978 if (t.asInput() == "\\lyxmintcaption") {
1979 string const pos = p.getArg('[', ']');
1981 string const caption =
1982 parse_text_snippet(p, FLAG_ITEM,
1983 false, parent_context);
1984 minted_nonfloat_caption = "[b]" + caption;
1989 parse_listings(p, os, parent_context, false, use_minted);
1993 else if (!parent_context.new_layout_allowed)
1994 parse_unknown_environment(p, name, os, FLAG_END, outer,
1997 // Alignment and spacing settings
1998 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1999 // therefore are totally broken!
2000 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2001 // they are commands not environments. They are furthermore switches that
2002 // can be ended by another switches, but also by commands like \footnote or
2003 // \parbox. So the only safe way is to leave them untouched.
2004 // However, we support the pseudo-environments
2005 // \begin{centering} ... \end{centering}
2006 // \begin{raggedright} ... \end{raggedright}
2007 // \begin{raggedleft} ... \end{raggedleft}
2008 // since they are used by LyX in floats (for spacing reasons)
2009 else if (name == "center" || name == "centering" ||
2010 name == "flushleft" || name == "raggedright" ||
2011 name == "flushright" || name == "raggedleft" ||
2012 name == "singlespace" || name == "onehalfspace" ||
2013 name == "doublespace" || name == "spacing") {
2014 eat_whitespace(p, os, parent_context, false);
2015 // We must begin a new paragraph if not already done
2016 if (! parent_context.atParagraphStart()) {
2017 parent_context.check_end_layout(os);
2018 parent_context.new_paragraph(os);
2020 if (name == "flushleft" || name == "raggedright")
2021 parent_context.add_extra_stuff("\\align left\n");
2022 else if (name == "flushright" || name == "raggedleft")
2023 parent_context.add_extra_stuff("\\align right\n");
2024 else if (name == "center" || name == "centering")
2025 parent_context.add_extra_stuff("\\align center\n");
2026 else if (name == "singlespace")
2027 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2028 else if (name == "onehalfspace") {
2029 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2030 preamble.registerAutomaticallyLoadedPackage("setspace");
2031 } else if (name == "doublespace") {
2032 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2033 preamble.registerAutomaticallyLoadedPackage("setspace");
2034 } else if (name == "spacing") {
2035 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2036 preamble.registerAutomaticallyLoadedPackage("setspace");
2038 parse_text(p, os, FLAG_END, outer, parent_context);
2039 // Just in case the environment is empty
2040 parent_context.extra_stuff.erase();
2041 // We must begin a new paragraph to reset the alignment
2042 parent_context.new_paragraph(os);
2046 // The single '=' is meant here.
2047 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2048 eat_whitespace(p, os, parent_context, false);
2049 Context context(true, parent_context.textclass, newlayout,
2050 parent_context.layout, parent_context.font);
2051 if (parent_context.deeper_paragraph) {
2052 // We are beginning a nested environment after a
2053 // deeper paragraph inside the outer list environment.
2054 // Therefore we don't need to output a "begin deeper".
2055 context.need_end_deeper = true;
2057 parent_context.check_end_layout(os);
2058 if (last_env == name) {
2059 // we need to output a separator since LyX would export
2060 // the two environments as one otherwise (bug 5716)
2061 TeX2LyXDocClass const & textclass(parent_context.textclass);
2062 Context newcontext(true, textclass,
2063 &(textclass.defaultLayout()));
2064 newcontext.check_layout(os);
2065 begin_inset(os, "Separator plain\n");
2067 newcontext.check_end_layout(os);
2069 switch (context.layout->latextype) {
2070 case LATEX_LIST_ENVIRONMENT:
2071 context.add_par_extra_stuff("\\labelwidthstring "
2072 + p.verbatim_item() + '\n');
2075 case LATEX_BIB_ENVIRONMENT:
2076 p.verbatim_item(); // swallow next arg
2082 context.check_deeper(os);
2083 // handle known optional and required arguments
2084 // FIXME: for item environments, this is currently
2085 // placed wrongly (in an empty paragraph). It has to go to
2086 // the first \item par instead.
2087 if (context.layout->latextype == LATEX_ENVIRONMENT
2088 || context.layout->latextype == LATEX_ITEM_ENVIRONMENT)
2089 output_arguments(os, p, outer, false, false, context,
2090 context.layout->latexargs());
2091 parse_text(p, os, FLAG_END, outer, context);
2092 if (context.layout->latextype == LATEX_ENVIRONMENT)
2093 output_arguments(os, p, outer, false, true, context,
2094 context.layout->postcommandargs());
2095 context.check_end_layout(os);
2096 if (parent_context.deeper_paragraph) {
2097 // We must suppress the "end deeper" because we
2098 // suppressed the "begin deeper" above.
2099 context.need_end_deeper = false;
2101 context.check_end_deeper(os);
2102 parent_context.new_paragraph(os);
2104 if (!preamble.titleLayoutFound())
2105 preamble.titleLayoutFound(newlayout->intitle);
2106 set<string> const & req = newlayout->requires();
2107 set<string>::const_iterator it = req.begin();
2108 set<string>::const_iterator en = req.end();
2109 for (; it != en; ++it)
2110 preamble.registerAutomaticallyLoadedPackage(*it);
2113 // The single '=' is meant here.
2114 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2115 eat_whitespace(p, os, parent_context, false);
2116 parent_context.check_layout(os);
2117 begin_inset(os, "Flex ");
2118 docstring flex_name = newinsetlayout->name();
2119 // FIXME: what do we do if the prefix is not Flex: ?
2120 if (prefixIs(flex_name, from_ascii("Flex:")))
2121 flex_name.erase(0, 5);
2122 os << to_utf8(flex_name) << '\n'
2123 << "status collapsed\n";
2124 if (newinsetlayout->isPassThru()) {
2125 string const arg = p.verbatimEnvironment(name);
2126 Context context(true, parent_context.textclass,
2127 &parent_context.textclass.plainLayout(),
2128 parent_context.layout);
2129 output_ert(os, arg, parent_context);
2131 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2135 else if (name == "appendix") {
2136 // This is no good latex style, but it works and is used in some documents...
2137 eat_whitespace(p, os, parent_context, false);
2138 parent_context.check_end_layout(os);
2139 Context context(true, parent_context.textclass, parent_context.layout,
2140 parent_context.layout, parent_context.font);
2141 context.check_layout(os);
2142 os << "\\start_of_appendix\n";
2143 parse_text(p, os, FLAG_END, outer, context);
2144 context.check_end_layout(os);
2148 else if (known_environments.find(name) != known_environments.end()) {
2149 vector<ArgumentType> arguments = known_environments[name];
2150 // The last "argument" denotes wether we may translate the
2151 // environment contents to LyX
2152 // The default required if no argument is given makes us
2153 // compatible with the reLyXre environment.
2154 ArgumentType contents = arguments.empty() ?
2157 if (!arguments.empty())
2158 arguments.pop_back();
2159 // See comment in parse_unknown_environment()
2160 bool const specialfont =
2161 (parent_context.font != parent_context.normalfont);
2162 bool const new_layout_allowed =
2163 parent_context.new_layout_allowed;
2165 parent_context.new_layout_allowed = false;
2166 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2167 outer, parent_context);
2168 if (contents == verbatim)
2169 output_ert_inset(os, p.ertEnvironment(name),
2172 parse_text_snippet(p, os, FLAG_END, outer,
2174 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2176 parent_context.new_layout_allowed = new_layout_allowed;
2180 parse_unknown_environment(p, name, os, FLAG_END, outer,
2184 active_environments.pop_back();
2188 /// parses a comment and outputs it to \p os.
2189 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2191 LASSERT(t.cat() == catComment, return);
2192 if (!t.cs().empty()) {
2193 context.check_layout(os);
2194 output_comment(p, os, t.cs(), context);
2195 if (p.next_token().cat() == catNewline) {
2196 // A newline after a comment line starts a new
2198 if (context.new_layout_allowed) {
2199 if(!context.atParagraphStart())
2200 // Only start a new paragraph if not already
2201 // done (we might get called recursively)
2202 context.new_paragraph(os);
2204 output_ert_inset(os, "\n", context);
2205 eat_whitespace(p, os, context, true);
2208 // "%\n" combination
2215 * Reads spaces and comments until the first non-space, non-comment token.
2216 * New paragraphs (double newlines or \\par) are handled like simple spaces
2217 * if \p eatParagraph is true.
2218 * Spaces are skipped, but comments are written to \p os.
2220 void eat_whitespace(Parser & p, ostream & os, Context & context,
2224 Token const & t = p.get_token();
2225 if (t.cat() == catComment)
2226 parse_comment(p, os, t, context);
2227 else if ((! eatParagraph && p.isParagraph()) ||
2228 (t.cat() != catSpace && t.cat() != catNewline)) {
2237 * Set a font attribute, parse text and reset the font attribute.
2238 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2239 * \param currentvalue Current value of the attribute. Is set to the new
2240 * value during parsing.
2241 * \param newvalue New value of the attribute
2243 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2244 Context & context, string const & attribute,
2245 string & currentvalue, string const & newvalue)
2247 context.check_layout(os);
2248 string const oldvalue = currentvalue;
2249 currentvalue = newvalue;
2250 os << '\n' << attribute << ' ' << newvalue << "\n";
2251 parse_text_snippet(p, os, flags, outer, context);
2252 context.check_layout(os);
2253 os << '\n' << attribute << ' ' << oldvalue << "\n";
2254 currentvalue = oldvalue;
2258 /// get the arguments of a natbib or jurabib citation command
2259 void get_cite_arguments(Parser & p, bool natbibOrder,
2260 string & before, string & after, bool const qualified = false)
2262 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2264 // text before the citation
2266 // text after the citation
2267 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2269 if (!after.empty()) {
2270 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2271 if (natbibOrder && !before.empty())
2272 swap(before, after);
2277 void copy_file(FileName const & src, string dstname)
2281 string const absParent = getParentFilePath(false);
2283 if (FileName::isAbsolute(dstname))
2284 dst = FileName(dstname);
2286 dst = makeAbsPath(dstname, absParent);
2287 FileName const srcpath = src.onlyPath();
2288 FileName const dstpath = dst.onlyPath();
2289 if (equivalent(srcpath, dstpath))
2291 if (!dstpath.isDirectory()) {
2292 if (!dstpath.createPath()) {
2293 cerr << "Warning: Could not create directory for file `"
2294 << dst.absFileName() << "´." << endl;
2298 if (dst.isReadableFile()) {
2299 if (overwriteFiles())
2300 cerr << "Warning: Overwriting existing file `"
2301 << dst.absFileName() << "´." << endl;
2303 cerr << "Warning: Not overwriting existing file `"
2304 << dst.absFileName() << "´." << endl;
2308 if (!src.copyTo(dst))
2309 cerr << "Warning: Could not copy file `" << src.absFileName()
2310 << "´ to `" << dst.absFileName() << "´." << endl;
2314 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2315 bool parse_chunk(Parser & p, ostream & os, Context & context)
2317 // check whether a chunk is possible here.
2318 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2324 // read the parameters
2325 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2326 if (!params.first) {
2331 Parser::Arg const code = p.verbatimStuff("\n@");
2336 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2337 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2341 // The last newline read is important for paragraph handling
2345 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2346 // We must have a valid layout before outputting the Chunk inset.
2347 context.check_layout(os);
2348 Context chunkcontext(true, context.textclass);
2349 chunkcontext.layout = &context.textclass.plainLayout();
2350 begin_inset(os, "Flex Chunk");
2351 os << "\nstatus open\n";
2352 if (!params.second.empty()) {
2353 chunkcontext.check_layout(os);
2354 Context paramscontext(true, context.textclass);
2355 paramscontext.layout = &context.textclass.plainLayout();
2356 begin_inset(os, "Argument 1");
2357 os << "\nstatus open\n";
2358 output_ert(os, params.second, paramscontext);
2361 output_ert(os, code.second, chunkcontext);
2369 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2370 bool is_macro(Parser & p)
2372 Token first = p.curr_token();
2373 if (first.cat() != catEscape || !p.good())
2375 if (first.cs() == "def")
2377 if (first.cs() != "global" && first.cs() != "long")
2379 Token second = p.get_token();
2381 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2382 second.cat() == catNewline || second.cat() == catComment)) {
2383 second = p.get_token();
2386 bool secondvalid = second.cat() == catEscape;
2388 bool thirdvalid = false;
2389 if (p.good() && first.cs() == "global" && secondvalid &&
2390 second.cs() == "long") {
2391 third = p.get_token();
2393 while (p.good() && !p.isParagraph() &&
2394 (third.cat() == catSpace ||
2395 third.cat() == catNewline ||
2396 third.cat() == catComment)) {
2397 third = p.get_token();
2400 thirdvalid = third.cat() == catEscape;
2402 for (int i = 0; i < pos; ++i)
2407 return (first.cs() == "global" || first.cs() == "long") &&
2408 second.cs() == "def";
2409 return first.cs() == "global" && second.cs() == "long" &&
2410 third.cs() == "def";
2414 /// Parse a macro definition (assumes that is_macro() returned true)
2415 void parse_macro(Parser & p, ostream & os, Context & context)
2417 context.check_layout(os);
2418 Token first = p.curr_token();
2421 string command = first.asInput();
2422 if (first.cs() != "def") {
2424 eat_whitespace(p, os, context, false);
2425 second = p.curr_token();
2426 command += second.asInput();
2427 if (second.cs() != "def") {
2429 eat_whitespace(p, os, context, false);
2430 third = p.curr_token();
2431 command += third.asInput();
2434 eat_whitespace(p, os, context, false);
2435 string const name = p.get_token().cs();
2436 eat_whitespace(p, os, context, false);
2442 while (p.next_token().cat() != catBegin) {
2443 if (p.next_token().cat() == catParameter) {
2448 // followed by number?
2449 if (p.next_token().cat() == catOther) {
2450 string s = p.get_token().asInput();
2452 // number = current arity + 1?
2453 if (s.size() == 1 && s[0] == arity + '0' + 1)
2458 paramtext += p.get_token().cs();
2460 paramtext += p.get_token().cs();
2465 // only output simple (i.e. compatible) macro as FormulaMacros
2466 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2468 context.check_layout(os);
2469 begin_inset(os, "FormulaMacro");
2470 os << "\n\\def" << ert;
2473 output_ert_inset(os, command + ert, context);
2477 void registerExternalTemplatePackages(string const & name)
2479 external::TemplateManager const & etm = external::TemplateManager::get();
2480 external::Template const * const et = etm.getTemplateByName(name);
2483 external::Template::Formats::const_iterator cit = et->formats.end();
2485 cit = et->formats.find("PDFLaTeX");
2486 if (cit == et->formats.end())
2487 // If the template has not specified a PDFLaTeX output,
2488 // we try the LaTeX format.
2489 cit = et->formats.find("LaTeX");
2490 if (cit == et->formats.end())
2492 vector<string>::const_iterator qit = cit->second.requirements.begin();
2493 vector<string>::const_iterator qend = cit->second.requirements.end();
2494 for (; qit != qend; ++qit)
2495 preamble.registerAutomaticallyLoadedPackage(*qit);
2498 } // anonymous namespace
2502 * Find a file with basename \p name in path \p path and an extension
2505 string find_file(string const & name, string const & path,
2506 char const * const * extensions)
2508 for (char const * const * what = extensions; *what; ++what) {
2509 string const trial = addExtension(name, *what);
2510 if (makeAbsPath(trial, path).exists())
2517 /// Convert filenames with TeX macros and/or quotes to something LyX
2519 string const normalize_filename(string const & name)
2524 Token const & t = p.get_token();
2525 if (t.cat() != catEscape)
2527 else if (t.cs() == "lyxdot") {
2528 // This is used by LyX for simple dots in relative
2532 } else if (t.cs() == "space") {
2535 } else if (t.cs() == "string") {
2536 // Convert \string" to " and \string~ to ~
2537 Token const & n = p.next_token();
2538 if (n.asInput() != "\"" && n.asInput() != "~")
2543 // Strip quotes. This is a bit complicated (see latex_path()).
2544 string full = os.str();
2545 if (!full.empty() && full[0] == '"') {
2546 string base = removeExtension(full);
2547 string ext = getExtension(full);
2548 if (!base.empty() && base[base.length()-1] == '"')
2551 return addExtension(trim(base, "\""), ext);
2552 if (full[full.length()-1] == '"')
2555 return trim(full, "\"");
2561 /// Convert \p name from TeX convention (relative to master file) to LyX
2562 /// convention (relative to .lyx file) if it is relative
2563 void fix_child_filename(string & name)
2565 string const absMasterTeX = getMasterFilePath(true);
2566 bool const isabs = FileName::isAbsolute(name);
2567 // convert from "relative to .tex master" to absolute original path
2569 name = makeAbsPath(name, absMasterTeX).absFileName();
2570 bool copyfile = copyFiles();
2571 string const absParentLyX = getParentFilePath(false);
2574 // convert from absolute original path to "relative to master file"
2575 string const rel = to_utf8(makeRelPath(from_utf8(name),
2576 from_utf8(absMasterTeX)));
2577 // re-interpret "relative to .tex file" as "relative to .lyx file"
2578 // (is different if the master .lyx file resides in a
2579 // different path than the master .tex file)
2580 string const absMasterLyX = getMasterFilePath(false);
2581 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2582 // Do not copy if the new path is impossible to create. Example:
2583 // absMasterTeX = "/foo/bar/"
2584 // absMasterLyX = "/bar/"
2585 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2586 if (contains(name, "/../"))
2593 // convert from absolute original path to
2594 // "relative to .lyx file"
2595 name = to_utf8(makeRelPath(from_utf8(abs),
2596 from_utf8(absParentLyX)));
2600 // convert from absolute original path to "relative to .lyx file"
2601 name = to_utf8(makeRelPath(from_utf8(name),
2602 from_utf8(absParentLyX)));
2607 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2608 Context & context, string const rdelim)
2610 Layout const * newlayout = 0;
2611 InsetLayout const * newinsetlayout = 0;
2612 char const * const * where = 0;
2613 // Store the latest bibliographystyle, addcontentslineContent and
2614 // nocite{*} option (needed for bibtex inset)
2616 string contentslineContent;
2617 // Some classes provide a \bibliographystyle, so do not output
2618 // any if none is explicitly set.
2619 string bibliographystyle;
2620 bool const use_natbib = isProvided("natbib");
2621 bool const use_jurabib = isProvided("jurabib");
2622 bool const use_biblatex = isProvided("biblatex")
2623 && preamble.citeEngine() != "biblatex-natbib";
2624 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2625 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2626 need_commentbib = use_biblatex || use_biblatex_natbib;
2629 // it is impossible to determine the correct encoding for non-CJK Japanese.
2630 // Therefore write a note at the beginning of the document
2631 if (is_nonCJKJapanese) {
2632 context.check_layout(os);
2633 begin_inset(os, "Note Note\n");
2634 os << "status open\n\\begin_layout Plain Layout\n"
2635 << "\\series bold\n"
2636 << "Important information:\n"
2637 << "\\end_layout\n\n"
2638 << "\\begin_layout Plain Layout\n"
2639 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2640 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2641 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2642 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2643 << " and specify the encoding using the -e command-line switch.\n"
2644 << " In addition, you might want to double check that the desired output encoding\n"
2645 << " is correctly selected in Document > Settings > Language.\n"
2646 << "\\end_layout\n";
2648 is_nonCJKJapanese = false;
2651 bool have_cycled = false;
2653 // Leave here only after at least one cycle
2654 if (have_cycled && flags & FLAG_LEAVE) {
2655 flags &= ~FLAG_LEAVE;
2659 Token const & t = p.get_token();
2661 debugToken(cerr, t, flags);
2664 if (flags & FLAG_ITEM) {
2665 if (t.cat() == catSpace)
2668 flags &= ~FLAG_ITEM;
2669 if (t.cat() == catBegin) {
2670 // skip the brace and collect everything to the next matching
2672 flags |= FLAG_BRACE_LAST;
2676 // handle only this single token, leave the loop if done
2677 flags |= FLAG_LEAVE;
2680 if (t.cat() != catEscape && t.character() == ']' &&
2681 (flags & FLAG_BRACK_LAST))
2683 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2685 string tok = t.asInput();
2686 // we only support delimiters with max 2 chars for now.
2687 if (rdelim.size() > 1)
2688 tok += p.next_token().asInput();
2689 if (t.cat() != catEscape && !rdelim.empty()
2690 && tok == rdelim && (flags & FLAG_RDELIM)) {
2691 if (rdelim.size() > 1)
2692 p.get_token(); // eat rdelim
2696 // If there is anything between \end{env} and \begin{env} we
2697 // don't need to output a separator.
2698 if (t.cat() != catSpace && t.cat() != catNewline &&
2699 t.asInput() != "\\begin")
2706 bool const starred = p.next_token().asInput() == "*";
2707 string const starredname(starred ? (t.cs() + '*') : t.cs());
2708 if (t.cat() == catMath) {
2709 // we are inside some text mode thingy, so opening new math is allowed
2710 context.check_layout(os);
2711 begin_inset(os, "Formula ");
2712 Token const & n = p.get_token();
2713 bool const display(n.cat() == catMath && outer);
2715 // TeX's $$...$$ syntax for displayed math
2717 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2719 p.get_token(); // skip the second '$' token
2721 // simple $...$ stuff
2724 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2729 // Prevent the conversion of a line break to a
2730 // space (bug 7668). This does not change the
2731 // output, but looks ugly in LyX.
2732 eat_whitespace(p, os, context, false);
2737 if (t.cat() == catSuper || t.cat() == catSub) {
2738 cerr << "catcode " << t << " illegal in text mode\n";
2742 // Basic support for quotes. We try to disambiguate
2743 // quotes from the context (e.g., a left english quote is
2744 // the same as a right german quote...).
2745 // Try to make a smart guess about the side
2746 Token const prev = p.prev_token();
2747 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2748 && prev.character() != '\n' && prev.character() != '~');
2749 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2750 context.check_layout(os);
2751 begin_inset(os, "Quotes ");
2752 os << guessQuoteStyle("eld", opening);
2758 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2759 context.check_layout(os);
2760 begin_inset(os, "Quotes ");
2761 os << guessQuoteStyle("erd", opening);
2768 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2769 context.check_layout(os);
2770 begin_inset(os, "Quotes ");
2771 os << guessQuoteStyle("ald", opening);
2778 if (t.asInput() == "<"
2779 && p.next_token().asInput() == "<") {
2780 bool has_chunk = false;
2784 has_chunk = parse_chunk(p, os, context);
2790 context.check_layout(os);
2791 begin_inset(os, "Quotes ");
2792 os << guessQuoteStyle("ard", opening);
2800 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2801 check_space(p, os, context);
2805 // babel shorthands (also used by polyglossia)
2806 // Since these can have different meanings for different languages
2807 // we import them as ERT (but they must be put in ERT to get output
2809 if (t.asInput() == "\"") {
2811 // These are known pairs. We put them together in
2812 // one ERT inset. In other cases (such as "a), only
2813 // the quotation mark is ERTed.
2814 if (p.next_token().asInput() == "\""
2815 || p.next_token().asInput() == "|"
2816 || p.next_token().asInput() == "-"
2817 || p.next_token().asInput() == "~"
2818 || p.next_token().asInput() == "="
2819 || p.next_token().asInput() == "/"
2820 || p.next_token().asInput() == "~"
2821 || p.next_token().asInput() == "'"
2822 || p.next_token().asInput() == "`"
2823 || p.next_token().asInput() == "<"
2824 || p.next_token().asInput() == ">") {
2825 s += p.next_token().asInput();
2828 output_ert_inset(os, s, context);
2832 if (t.character() == '[' && noweb_mode &&
2833 p.next_token().character() == '[') {
2834 // These can contain underscores
2836 string const s = p.getFullOpt() + ']';
2837 if (p.next_token().character() == ']')
2840 cerr << "Warning: Inserting missing ']' in '"
2841 << s << "'." << endl;
2842 output_ert_inset(os, s, context);
2846 if (t.cat() == catLetter) {
2847 context.check_layout(os);
2852 if (t.cat() == catOther ||
2853 t.cat() == catAlign ||
2854 t.cat() == catParameter) {
2855 context.check_layout(os);
2856 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2857 context.merging_hyphens_allowed &&
2858 context.font.family != "ttfamily" &&
2859 !context.layout->pass_thru) {
2860 if (p.next_next_token().asInput() == "-") {
2862 os << to_utf8(docstring(1, 0x2014));
2866 os << to_utf8(docstring(1, 0x2013));
2869 // This translates "&" to "\\&" which may be wrong...
2874 if (p.isParagraph()) {
2875 // In minted floating listings we will collect
2876 // everything into the caption, where multiple
2877 // paragraphs are forbidden.
2878 if (minted_float.empty()) {
2879 if (context.new_layout_allowed)
2880 context.new_paragraph(os);
2882 output_ert_inset(os, "\\par ", context);
2885 eat_whitespace(p, os, context, true);
2889 if (t.cat() == catActive) {
2890 context.check_layout(os);
2891 if (t.character() == '~') {
2892 if (context.layout->free_spacing)
2895 begin_inset(os, "space ~\n");
2903 if (t.cat() == catBegin) {
2904 Token const next = p.next_token();
2905 Token const end = p.next_next_token();
2906 if (next.cat() == catEnd) {
2908 Token const prev = p.prev_token();
2910 if (p.next_token().character() == '`')
2911 ; // ignore it in {}``
2913 output_ert_inset(os, "{}", context);
2914 } else if (next.cat() == catEscape &&
2915 is_known(next.cs(), known_quotes) &&
2916 end.cat() == catEnd) {
2917 // Something like {\textquoteright} (e.g.
2918 // from writer2latex). We may skip the
2919 // braces here for better readability.
2920 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2922 } else if (p.next_token().asInput() == "\\ascii") {
2923 // handle the \ascii characters
2924 // (the case without braces is handled later)
2925 // the code is "{\ascii\xxx}"
2926 p.get_token(); // eat \ascii
2927 string name2 = p.get_token().asInput();
2928 p.get_token(); // eat the final '}'
2929 string const name = "{\\ascii" + name2 + "}";
2933 // get the character from unicodesymbols
2934 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2935 Encodings::TEXT_CMD, termination, rem, &req);
2937 context.check_layout(os);
2940 output_ert_inset(os,
2941 to_utf8(rem), context);
2942 for (set<string>::const_iterator it = req.begin();
2943 it != req.end(); ++it)
2944 preamble.registerAutomaticallyLoadedPackage(*it);
2946 // we did not find a non-ert version
2947 output_ert_inset(os, name, context);
2949 context.check_layout(os);
2950 // special handling of font attribute changes
2951 Token const prev = p.prev_token();
2952 TeXFont const oldFont = context.font;
2953 if (next.character() == '[' ||
2954 next.character() == ']' ||
2955 next.character() == '*') {
2957 if (p.next_token().cat() == catEnd) {
2962 output_ert_inset(os, "{", context);
2963 parse_text_snippet(p, os,
2966 output_ert_inset(os, "}", context);
2968 } else if (! context.new_layout_allowed) {
2969 output_ert_inset(os, "{", context);
2970 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2972 output_ert_inset(os, "}", context);
2973 } else if (is_known(next.cs(), known_sizes)) {
2974 // next will change the size, so we must
2976 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2978 if (!context.atParagraphStart())
2980 << context.font.size << "\n";
2981 } else if (is_known(next.cs(), known_font_families)) {
2982 // next will change the font family, so we
2983 // must reset it here
2984 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2986 if (!context.atParagraphStart())
2988 << context.font.family << "\n";
2989 } else if (is_known(next.cs(), known_font_series)) {
2990 // next will change the font series, so we
2991 // must reset it here
2992 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2994 if (!context.atParagraphStart())
2996 << context.font.series << "\n";
2997 } else if (is_known(next.cs(), known_font_shapes)) {
2998 // next will change the font shape, so we
2999 // must reset it here
3000 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3002 if (!context.atParagraphStart())
3004 << context.font.shape << "\n";
3005 } else if (is_known(next.cs(), known_old_font_families) ||
3006 is_known(next.cs(), known_old_font_series) ||
3007 is_known(next.cs(), known_old_font_shapes)) {
3008 // next will change the font family, series
3009 // and shape, so we must reset it here
3010 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3012 if (!context.atParagraphStart())
3014 << context.font.family
3016 << context.font.series
3018 << context.font.shape << "\n";
3020 output_ert_inset(os, "{", context);
3021 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3023 output_ert_inset(os, "}", context);
3029 if (t.cat() == catEnd) {
3030 if (flags & FLAG_BRACE_LAST) {
3033 cerr << "stray '}' in text\n";
3034 output_ert_inset(os, "}", context);
3038 if (t.cat() == catComment) {
3039 parse_comment(p, os, t, context);
3044 // control sequences
3047 if (t.cs() == "(" || t.cs() == "[") {
3048 bool const simple = t.cs() == "(";
3049 context.check_layout(os);
3050 begin_inset(os, "Formula");
3051 os << " \\" << t.cs();
3052 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3053 os << '\\' << (simple ? ')' : ']');
3056 // Prevent the conversion of a line break to a
3057 // space (bug 7668). This does not change the
3058 // output, but looks ugly in LyX.
3059 eat_whitespace(p, os, context, false);
3064 if (t.cs() == "begin") {
3065 parse_environment(p, os, outer, last_env,
3070 if (t.cs() == "end") {
3071 if (flags & FLAG_END) {
3072 // eat environment name
3073 string const name = p.getArg('{', '}');
3074 if (name != active_environment())
3075 cerr << "\\end{" + name + "} does not match \\begin{"
3076 + active_environment() + "}\n";
3079 p.error("found 'end' unexpectedly");
3083 if (t.cs() == "item") {
3085 bool const optarg = p.hasOpt();
3087 // FIXME: This swallows comments, but we cannot use
3088 // eat_whitespace() since we must not output
3089 // anything before the item.
3090 p.skip_spaces(true);
3091 s = p.verbatimOption();
3093 p.skip_spaces(false);
3095 context.check_layout(os);
3096 if (context.has_item) {
3097 // An item in an unknown list-like environment
3098 // FIXME: Do this in check_layout()!
3099 context.has_item = false;
3101 output_ert_inset(os, "\\item", context);
3103 output_ert_inset(os, "\\item ", context);
3106 if (context.layout->labeltype != LABEL_MANUAL) {
3107 // handle option of itemize item
3108 begin_inset(os, "Argument item:1\n");
3109 os << "status open\n";
3110 os << "\n\\begin_layout Plain Layout\n";
3112 os << parse_text_snippet(p2,
3113 FLAG_BRACK_LAST, outer, context);
3114 // we must not use context.check_end_layout(os)
3115 // because that would close the outer itemize layout
3116 os << "\n\\end_layout\n";
3118 eat_whitespace(p, os, context, false);
3119 } else if (!s.empty()) {
3120 // LyX adds braces around the argument,
3121 // so we need to remove them here.
3122 if (s.size() > 2 && s[0] == '{' &&
3123 s[s.size()-1] == '}')
3124 s = s.substr(1, s.size()-2);
3125 // If the argument contains a space we
3126 // must put it into ERT: Otherwise LyX
3127 // would misinterpret the space as
3128 // item delimiter (bug 7663)
3129 if (contains(s, ' ')) {
3130 output_ert_inset(os, s, context);
3133 os << parse_text_snippet(p2,
3134 FLAG_BRACK_LAST, outer, context);
3136 // The space is needed to separate the
3137 // item from the rest of the sentence.
3139 eat_whitespace(p, os, context, false);
3145 if (t.cs() == "bibitem") {
3147 context.check_layout(os);
3148 eat_whitespace(p, os, context, false);
3149 string label = p.verbatimOption();
3150 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3151 bool const literal = !lbl.first;
3152 label = literal ? subst(label, "\n", " ") : lbl.second;
3153 string lit = literal ? "\"true\"" : "\"false\"";
3154 string key = convert_literate_command_inset_arg(p.verbatim_item());
3155 begin_command_inset(os, "bibitem", "bibitem");
3156 os << "label \"" << label << "\"\n"
3157 << "key \"" << key << "\"\n"
3158 << "literal " << lit << "\n";
3164 // catch the case of \def\inputGnumericTable
3166 if (t.cs() == "def") {
3167 Token second = p.next_token();
3168 if (second.cs() == "inputGnumericTable") {
3172 Token third = p.get_token();
3174 if (third.cs() == "input") {
3178 string name = normalize_filename(p.verbatim_item());
3179 string const path = getMasterFilePath(true);
3180 // We want to preserve relative / absolute filenames,
3181 // therefore path is only used for testing
3182 // The file extension is in every case ".tex".
3183 // So we need to remove this extension and check for
3184 // the original one.
3185 name = removeExtension(name);
3186 if (!makeAbsPath(name, path).exists()) {
3187 char const * const Gnumeric_formats[] = {"gnumeric",
3189 string const Gnumeric_name =
3190 find_file(name, path, Gnumeric_formats);
3191 if (!Gnumeric_name.empty())
3192 name = Gnumeric_name;
3194 FileName const absname = makeAbsPath(name, path);
3195 if (absname.exists()) {
3196 fix_child_filename(name);
3197 copy_file(absname, name);
3199 cerr << "Warning: Could not find file '"
3200 << name << "'." << endl;
3201 context.check_layout(os);
3202 begin_inset(os, "External\n\ttemplate ");
3203 os << "GnumericSpreadsheet\n\tfilename "
3206 context.check_layout(os);
3208 // register the packages that are automatically loaded
3209 // by the Gnumeric template
3210 registerExternalTemplatePackages("GnumericSpreadsheet");
3215 parse_macro(p, os, context);
3219 if (t.cs() == "noindent") {
3221 context.add_par_extra_stuff("\\noindent\n");
3225 if (t.cs() == "appendix") {
3226 context.add_par_extra_stuff("\\start_of_appendix\n");
3227 // We need to start a new paragraph. Otherwise the
3228 // appendix in 'bla\appendix\chapter{' would start
3230 context.new_paragraph(os);
3231 // We need to make sure that the paragraph is
3232 // generated even if it is empty. Otherwise the
3233 // appendix in '\par\appendix\par\chapter{' would
3235 context.check_layout(os);
3236 // FIXME: This is a hack to prevent paragraph
3237 // deletion if it is empty. Handle this better!
3238 output_comment(p, os,
3239 "dummy comment inserted by tex2lyx to "
3240 "ensure that this paragraph is not empty",
3242 // Both measures above may generate an additional
3243 // empty paragraph, but that does not hurt, because
3244 // whitespace does not matter here.
3245 eat_whitespace(p, os, context, true);
3249 // Must catch empty dates before findLayout is called below
3250 if (t.cs() == "date") {
3251 eat_whitespace(p, os, context, false);
3253 string const date = p.verbatim_item();
3256 preamble.suppressDate(true);
3259 preamble.suppressDate(false);
3260 if (context.new_layout_allowed &&
3261 (newlayout = findLayout(context.textclass,
3264 output_command_layout(os, p, outer,
3265 context, newlayout);
3266 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3267 if (!preamble.titleLayoutFound())
3268 preamble.titleLayoutFound(newlayout->intitle);
3269 set<string> const & req = newlayout->requires();
3270 set<string>::const_iterator it = req.begin();
3271 set<string>::const_iterator en = req.end();
3272 for (; it != en; ++it)
3273 preamble.registerAutomaticallyLoadedPackage(*it);
3275 output_ert_inset(os,
3276 "\\date{" + p.verbatim_item() + '}',
3282 // Starred section headings
3283 // Must attempt to parse "Section*" before "Section".
3284 if ((p.next_token().asInput() == "*") &&
3285 context.new_layout_allowed &&
3286 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3289 output_command_layout(os, p, outer, context, newlayout);
3291 if (!preamble.titleLayoutFound())
3292 preamble.titleLayoutFound(newlayout->intitle);
3293 set<string> const & req = newlayout->requires();
3294 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3295 preamble.registerAutomaticallyLoadedPackage(*it);
3299 // Section headings and the like
3300 if (context.new_layout_allowed &&
3301 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3303 output_command_layout(os, p, outer, context, newlayout);
3305 if (!preamble.titleLayoutFound())
3306 preamble.titleLayoutFound(newlayout->intitle);
3307 set<string> const & req = newlayout->requires();
3308 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3309 preamble.registerAutomaticallyLoadedPackage(*it);
3313 if (t.cs() == "subfloat") {
3314 // the syntax is \subfloat[list entry][sub caption]{content}
3315 // if it is a table of figure depends on the surrounding float
3317 // do nothing if there is no outer float
3318 if (!float_type.empty()) {
3319 context.check_layout(os);
3321 begin_inset(os, "Float " + float_type + "\n");
3323 << "\nsideways false"
3324 << "\nstatus collapsed\n\n";
3327 bool has_caption = false;
3328 if (p.next_token().cat() != catEscape &&
3329 p.next_token().character() == '[') {
3330 p.get_token(); // eat '['
3331 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3334 // In case we have two optional args, the second is the caption.
3335 if (p.next_token().cat() != catEscape &&
3336 p.next_token().character() == '[') {
3337 p.get_token(); // eat '['
3338 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3341 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3342 // the caption comes always as the last
3344 // we must make sure that the caption gets a \begin_layout
3345 os << "\n\\begin_layout Plain Layout";
3347 begin_inset(os, "Caption Standard\n");
3348 Context newcontext(true, context.textclass,
3349 0, 0, context.font);
3350 newcontext.check_layout(os);
3351 os << caption << "\n";
3352 newcontext.check_end_layout(os);
3355 // close the layout we opened
3356 os << "\n\\end_layout";
3361 // if the float type is not supported or there is no surrounding float
3366 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3368 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3370 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3371 + "{" + p.verbatim_item() + '}', context);
3376 if (t.cs() == "xymatrix") {
3377 // we must open a new math because LyX's xy support is in math
3378 context.check_layout(os);
3379 begin_inset(os, "Formula ");
3381 os << "\\" << t.cs() << '{';
3382 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3385 preamble.registerAutomaticallyLoadedPackage("xy");
3389 if (t.cs() == "includegraphics") {
3390 bool const clip = p.next_token().asInput() == "*";
3393 string const arg = p.getArg('[', ']');
3394 map<string, string> opts;
3395 vector<string> keys;
3396 split_map(arg, opts, keys);
3398 opts["clip"] = string();
3399 string name = normalize_filename(p.verbatim_item());
3401 string const path = getMasterFilePath(true);
3402 // We want to preserve relative / absolute filenames,
3403 // therefore path is only used for testing
3404 if (!makeAbsPath(name, path).exists()) {
3405 // The file extension is probably missing.
3406 // Now try to find it out.
3407 string const dvips_name =
3408 find_file(name, path,
3409 known_dvips_graphics_formats);
3410 string const pdftex_name =
3411 find_file(name, path,
3412 known_pdftex_graphics_formats);
3413 if (!dvips_name.empty()) {
3414 if (!pdftex_name.empty()) {
3415 cerr << "This file contains the "
3417 "\"\\includegraphics{"
3419 "However, files\n\""
3420 << dvips_name << "\" and\n\""
3421 << pdftex_name << "\"\n"
3422 "both exist, so I had to make a "
3423 "choice and took the first one.\n"
3424 "Please move the unwanted one "
3425 "someplace else and try again\n"
3426 "if my choice was wrong."
3430 } else if (!pdftex_name.empty()) {
3436 FileName const absname = makeAbsPath(name, path);
3437 if (absname.exists()) {
3438 fix_child_filename(name);
3439 copy_file(absname, name);
3441 cerr << "Warning: Could not find graphics file '"
3442 << name << "'." << endl;
3444 context.check_layout(os);
3445 begin_inset(os, "Graphics ");
3446 os << "\n\tfilename " << name << '\n';
3447 if (opts.find("width") != opts.end())
3449 << translate_len(opts["width"]) << '\n';
3450 if (opts.find("height") != opts.end())
3452 << translate_len(opts["height"]) << '\n';
3453 if (opts.find("scale") != opts.end()) {
3454 istringstream iss(opts["scale"]);
3458 os << "\tscale " << val << '\n';
3460 if (opts.find("angle") != opts.end()) {
3461 os << "\trotateAngle "
3462 << opts["angle"] << '\n';
3463 vector<string>::const_iterator a =
3464 find(keys.begin(), keys.end(), "angle");
3465 vector<string>::const_iterator s =
3466 find(keys.begin(), keys.end(), "width");
3467 if (s == keys.end())
3468 s = find(keys.begin(), keys.end(), "height");
3469 if (s == keys.end())
3470 s = find(keys.begin(), keys.end(), "scale");
3471 if (s != keys.end() && distance(s, a) > 0)
3472 os << "\tscaleBeforeRotation\n";
3474 if (opts.find("origin") != opts.end()) {
3476 string const opt = opts["origin"];
3477 if (opt.find('l') != string::npos) ss << "left";
3478 if (opt.find('r') != string::npos) ss << "right";
3479 if (opt.find('c') != string::npos) ss << "center";
3480 if (opt.find('t') != string::npos) ss << "Top";
3481 if (opt.find('b') != string::npos) ss << "Bottom";
3482 if (opt.find('B') != string::npos) ss << "Baseline";
3483 if (!ss.str().empty())
3484 os << "\trotateOrigin " << ss.str() << '\n';
3486 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3488 if (opts.find("keepaspectratio") != opts.end())
3489 os << "\tkeepAspectRatio\n";
3490 if (opts.find("clip") != opts.end())
3492 if (opts.find("draft") != opts.end())
3494 if (opts.find("bb") != opts.end())
3495 os << "\tBoundingBox "
3496 << opts["bb"] << '\n';
3497 int numberOfbbOptions = 0;
3498 if (opts.find("bbllx") != opts.end())
3499 numberOfbbOptions++;
3500 if (opts.find("bblly") != opts.end())
3501 numberOfbbOptions++;
3502 if (opts.find("bburx") != opts.end())
3503 numberOfbbOptions++;
3504 if (opts.find("bbury") != opts.end())
3505 numberOfbbOptions++;
3506 if (numberOfbbOptions == 4)
3507 os << "\tBoundingBox "
3508 << opts["bbllx"] << " " << opts["bblly"] << " "
3509 << opts["bburx"] << " " << opts["bbury"] << '\n';
3510 else if (numberOfbbOptions > 0)
3511 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3512 numberOfbbOptions = 0;
3513 if (opts.find("natwidth") != opts.end())
3514 numberOfbbOptions++;
3515 if (opts.find("natheight") != opts.end())
3516 numberOfbbOptions++;
3517 if (numberOfbbOptions == 2)
3518 os << "\tBoundingBox 0bp 0bp "
3519 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3520 else if (numberOfbbOptions > 0)
3521 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3522 ostringstream special;
3523 if (opts.find("hiresbb") != opts.end())
3524 special << "hiresbb,";
3525 if (opts.find("trim") != opts.end())
3527 if (opts.find("viewport") != opts.end())
3528 special << "viewport=" << opts["viewport"] << ',';
3529 if (opts.find("totalheight") != opts.end())
3530 special << "totalheight=" << opts["totalheight"] << ',';
3531 if (opts.find("type") != opts.end())
3532 special << "type=" << opts["type"] << ',';
3533 if (opts.find("ext") != opts.end())
3534 special << "ext=" << opts["ext"] << ',';
3535 if (opts.find("read") != opts.end())
3536 special << "read=" << opts["read"] << ',';
3537 if (opts.find("command") != opts.end())
3538 special << "command=" << opts["command"] << ',';
3539 string s_special = special.str();
3540 if (!s_special.empty()) {
3541 // We had special arguments. Remove the trailing ','.
3542 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3544 // TODO: Handle the unknown settings better.
3545 // Warn about invalid options.
3546 // Check whether some option was given twice.
3548 preamble.registerAutomaticallyLoadedPackage("graphicx");
3552 if (t.cs() == "footnote" ||
3553 (t.cs() == "thanks" && context.layout->intitle)) {
3555 context.check_layout(os);
3556 begin_inset(os, "Foot\n");
3557 os << "status collapsed\n\n";
3558 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3563 if (t.cs() == "marginpar") {
3565 context.check_layout(os);
3566 begin_inset(os, "Marginal\n");
3567 os << "status collapsed\n\n";
3568 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3573 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3574 bool const use_minted = t.cs() == "mintinline";
3576 parse_listings(p, os, context, true, use_minted);
3580 if (t.cs() == "ensuremath") {
3582 context.check_layout(os);
3583 string const s = p.verbatim_item();
3584 //FIXME: this never triggers in UTF8
3585 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3588 output_ert_inset(os, "\\ensuremath{" + s + "}",
3593 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3594 if (preamble.titleLayoutFound()) {
3596 skip_spaces_braces(p);
3598 output_ert_inset(os, t.asInput(), context);
3602 if (t.cs() == "tableofcontents"
3603 || t.cs() == "lstlistoflistings"
3604 || t.cs() == "listoflistings") {
3605 string name = t.cs();
3606 if (preamble.minted() && name == "listoflistings")
3607 name.insert(0, "lst");
3608 context.check_layout(os);
3609 begin_command_inset(os, "toc", name);
3611 skip_spaces_braces(p);
3612 if (name == "lstlistoflistings") {
3613 if (preamble.minted())
3614 preamble.registerAutomaticallyLoadedPackage("minted");
3616 preamble.registerAutomaticallyLoadedPackage("listings");
3621 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3622 context.check_layout(os);
3623 if (t.cs() == "listoffigures")
3624 begin_inset(os, "FloatList figure\n");
3626 begin_inset(os, "FloatList table\n");
3628 skip_spaces_braces(p);
3632 if (t.cs() == "listof") {
3633 p.skip_spaces(true);
3634 string const name = p.get_token().cs();
3635 if (context.textclass.floats().typeExist(name)) {
3636 context.check_layout(os);
3637 begin_inset(os, "FloatList ");
3640 p.get_token(); // swallow second arg
3642 output_ert_inset(os, "\\listof{" + name + "}", context);
3646 if ((where = is_known(t.cs(), known_text_font_families))) {
3647 parse_text_attributes(p, os, FLAG_ITEM, outer,
3648 context, "\\family", context.font.family,
3649 known_coded_font_families[where - known_text_font_families]);
3653 if ((where = is_known(t.cs(), known_text_font_series))) {
3654 parse_text_attributes(p, os, FLAG_ITEM, outer,
3655 context, "\\series", context.font.series,
3656 known_coded_font_series[where - known_text_font_series]);
3660 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3661 parse_text_attributes(p, os, FLAG_ITEM, outer,
3662 context, "\\shape", context.font.shape,
3663 known_coded_font_shapes[where - known_text_font_shapes]);
3667 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3668 context.check_layout(os);
3669 TeXFont oldFont = context.font;
3670 context.font.init();
3671 context.font.size = oldFont.size;
3672 os << "\n\\family " << context.font.family << "\n";
3673 os << "\n\\series " << context.font.series << "\n";
3674 os << "\n\\shape " << context.font.shape << "\n";
3675 if (t.cs() == "textnormal") {
3676 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3677 output_font_change(os, context.font, oldFont);
3678 context.font = oldFont;
3680 eat_whitespace(p, os, context, false);
3684 if (t.cs() == "textcolor") {
3685 // scheme is \textcolor{color name}{text}
3686 string const color = p.verbatim_item();
3687 // we support the predefined colors of the color and the xcolor package
3688 if (color == "black" || color == "blue" || color == "cyan"
3689 || color == "green" || color == "magenta" || color == "red"
3690 || color == "white" || color == "yellow") {
3691 context.check_layout(os);
3692 os << "\n\\color " << color << "\n";
3693 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3694 context.check_layout(os);
3695 os << "\n\\color inherit\n";
3696 preamble.registerAutomaticallyLoadedPackage("color");
3697 } else if (color == "brown" || color == "darkgray" || color == "gray"
3698 || color == "lightgray" || color == "lime" || color == "olive"
3699 || color == "orange" || color == "pink" || color == "purple"
3700 || color == "teal" || color == "violet") {
3701 context.check_layout(os);
3702 os << "\n\\color " << color << "\n";
3703 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3704 context.check_layout(os);
3705 os << "\n\\color inherit\n";
3706 preamble.registerAutomaticallyLoadedPackage("xcolor");
3708 // for custom defined colors
3709 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3713 if (t.cs() == "underbar" || t.cs() == "uline") {
3714 // \underbar is not 100% correct (LyX outputs \uline
3715 // of ulem.sty). The difference is that \ulem allows
3716 // line breaks, and \underbar does not.
3717 // Do NOT handle \underline.
3718 // \underbar cuts through y, g, q, p etc.,
3719 // \underline does not.
3720 context.check_layout(os);
3721 os << "\n\\bar under\n";
3722 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3723 context.check_layout(os);
3724 os << "\n\\bar default\n";
3725 preamble.registerAutomaticallyLoadedPackage("ulem");
3729 if (t.cs() == "sout") {
3730 context.check_layout(os);
3731 os << "\n\\strikeout on\n";
3732 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3733 context.check_layout(os);
3734 os << "\n\\strikeout default\n";
3735 preamble.registerAutomaticallyLoadedPackage("ulem");
3739 if (t.cs() == "uuline" || t.cs() == "uwave"
3740 || t.cs() == "emph" || t.cs() == "noun"
3741 || t.cs() == "xout") {
3742 context.check_layout(os);
3743 os << "\n\\" << t.cs() << " on\n";
3744 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3745 context.check_layout(os);
3746 os << "\n\\" << t.cs() << " default\n";
3747 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3748 preamble.registerAutomaticallyLoadedPackage("ulem");
3752 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3753 context.check_layout(os);
3754 string name = p.getArg('{', '}');
3755 string localtime = p.getArg('{', '}');
3756 preamble.registerAuthor(name);
3757 Author const & author = preamble.getAuthor(name);
3758 // from_asctime_utc() will fail if LyX decides to output the
3759 // time in the text language.
3760 time_t ptime = from_asctime_utc(localtime);
3761 if (ptime == static_cast<time_t>(-1)) {
3762 cerr << "Warning: Could not parse time `" << localtime
3763 << "´ for change tracking, using current time instead.\n";
3764 ptime = current_time();
3766 if (t.cs() == "lyxadded")
3767 os << "\n\\change_inserted ";
3769 os << "\n\\change_deleted ";
3770 os << author.bufferId() << ' ' << ptime << '\n';
3771 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3772 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3773 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3774 LaTeXPackages::isAvailable("xcolor");
3775 // No need to test for luatex, since luatex comes in
3776 // two flavours (dvi and pdf), like latex, and those
3777 // are detected by pdflatex.
3778 if (pdflatex || xetex) {
3780 preamble.registerAutomaticallyLoadedPackage("ulem");
3781 preamble.registerAutomaticallyLoadedPackage("xcolor");
3782 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3786 preamble.registerAutomaticallyLoadedPackage("dvipost");
3787 } else if (xcolorulem) {
3788 preamble.registerAutomaticallyLoadedPackage("ulem");
3789 preamble.registerAutomaticallyLoadedPackage("xcolor");
3795 if (t.cs() == "textipa") {
3796 context.check_layout(os);
3797 begin_inset(os, "IPA\n");
3798 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3799 context.merging_hyphens_allowed = false;
3800 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3801 context.merging_hyphens_allowed = merging_hyphens_allowed;
3803 preamble.registerAutomaticallyLoadedPackage("tipa");
3804 preamble.registerAutomaticallyLoadedPackage("tipx");
3808 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3809 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3810 context.check_layout(os);
3814 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3815 begin_inset(os, "IPADeco " + type + "\n");
3816 os << "status open\n";
3817 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3823 if (t.cs() == "textvertline") {
3824 // FIXME: This is not correct, \textvertline is higher than |
3830 if (t.cs() == "tone" ) {
3831 context.check_layout(os);
3832 // register the tone package
3833 preamble.registerAutomaticallyLoadedPackage("tone");
3834 string content = trimSpaceAndEol(p.verbatim_item());
3835 string command = t.asInput() + "{" + content + "}";
3836 // some tones can be detected by unicodesymbols, some need special code
3837 if (is_known(content, known_tones)) {
3838 os << "\\IPAChar " << command << "\n";
3841 // try to see whether the string is in unicodesymbols
3845 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3846 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3847 termination, rem, &req);
3851 output_ert_inset(os, to_utf8(rem), context);
3852 for (set<string>::const_iterator it = req.begin();
3853 it != req.end(); ++it)
3854 preamble.registerAutomaticallyLoadedPackage(*it);
3856 // we did not find a non-ert version
3857 output_ert_inset(os, command, context);
3861 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3862 t.cs() == "vphantom") {
3863 context.check_layout(os);
3864 if (t.cs() == "phantom")
3865 begin_inset(os, "Phantom Phantom\n");
3866 if (t.cs() == "hphantom")
3867 begin_inset(os, "Phantom HPhantom\n");
3868 if (t.cs() == "vphantom")
3869 begin_inset(os, "Phantom VPhantom\n");
3870 os << "status open\n";
3871 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3877 if (t.cs() == "href") {
3878 context.check_layout(os);
3879 string target = convert_literate_command_inset_arg(p.verbatim_item());
3880 string name = p.verbatim_item();
3881 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3882 bool const literal = !nm.first;
3883 name = literal ? subst(name, "\n", " ") : nm.second;
3884 string lit = literal ? "\"true\"" : "\"false\"";
3886 size_t i = target.find(':');
3887 if (i != string::npos) {
3888 type = target.substr(0, i + 1);
3889 if (type == "mailto:" || type == "file:")
3890 target = target.substr(i + 1);
3891 // handle the case that name is equal to target, except of "http(s)://"
3892 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3895 begin_command_inset(os, "href", "href");
3897 os << "name \"" << name << "\"\n";
3898 os << "target \"" << target << "\"\n";
3899 if (type == "mailto:" || type == "file:")
3900 os << "type \"" << type << "\"\n";
3901 os << "literal " << lit << "\n";
3903 skip_spaces_braces(p);
3907 if (t.cs() == "lyxline") {
3908 // swallow size argument (it is not used anyway)
3910 if (!context.atParagraphStart()) {
3911 // so our line is in the middle of a paragraph
3912 // we need to add a new line, lest this line
3913 // follow the other content on that line and
3914 // run off the side of the page
3915 // FIXME: This may create an empty paragraph,
3916 // but without that it would not be
3917 // possible to set noindent below.
3918 // Fortunately LaTeX does not care
3919 // about the empty paragraph.
3920 context.new_paragraph(os);
3922 if (preamble.indentParagraphs()) {
3923 // we need to unindent, lest the line be too long
3924 context.add_par_extra_stuff("\\noindent\n");
3926 context.check_layout(os);
3927 begin_command_inset(os, "line", "rule");
3928 os << "offset \"0.5ex\"\n"
3929 "width \"100line%\"\n"
3935 if (t.cs() == "rule") {
3936 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3937 string const width = p.getArg('{', '}');
3938 string const thickness = p.getArg('{', '}');
3939 context.check_layout(os);
3940 begin_command_inset(os, "line", "rule");
3941 if (!offset.empty())
3942 os << "offset \"" << translate_len(offset) << "\"\n";
3943 os << "width \"" << translate_len(width) << "\"\n"
3944 "height \"" << translate_len(thickness) << "\"\n";
3949 // handle refstyle first to catch \eqref which can also occur
3950 // without refstyle. Only recognize these commands if
3951 // refstyle.sty was found in the preamble (otherwise \eqref
3952 // and user defined ref commands could be misdetected).
3953 if ((where = is_known(t.cs(), known_refstyle_commands))
3954 && preamble.refstyle()) {
3955 context.check_layout(os);
3956 begin_command_inset(os, "ref", "formatted");
3957 os << "reference \"";
3958 os << known_refstyle_prefixes[where - known_refstyle_commands]
3960 os << convert_literate_command_inset_arg(p.verbatim_item())
3962 os << "plural \"false\"\n";
3963 os << "caps \"false\"\n";
3964 os << "noprefix \"false\"\n";
3966 preamble.registerAutomaticallyLoadedPackage("refstyle");
3970 // if refstyle is used, we must not convert \prettyref to a
3971 // formatted reference, since that would result in a refstyle command.
3972 if ((where = is_known(t.cs(), known_ref_commands)) &&
3973 (t.cs() != "prettyref" || !preamble.refstyle())) {
3974 string const opt = p.getOpt();
3976 context.check_layout(os);
3977 begin_command_inset(os, "ref",
3978 known_coded_ref_commands[where - known_ref_commands]);
3979 os << "reference \""
3980 << convert_literate_command_inset_arg(p.verbatim_item())
3982 os << "plural \"false\"\n";
3983 os << "caps \"false\"\n";
3984 os << "noprefix \"false\"\n";
3986 if (t.cs() == "vref" || t.cs() == "vpageref")
3987 preamble.registerAutomaticallyLoadedPackage("varioref");
3988 else if (t.cs() == "prettyref")
3989 preamble.registerAutomaticallyLoadedPackage("prettyref");
3991 // LyX does not yet support optional arguments of ref commands
3992 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3993 p.verbatim_item() + '}', context);
3999 is_known(t.cs(), known_natbib_commands) &&
4000 ((t.cs() != "citefullauthor" &&
4001 t.cs() != "citeyear" &&
4002 t.cs() != "citeyearpar") ||
4003 p.next_token().asInput() != "*")) {
4004 context.check_layout(os);
4005 string command = t.cs();
4006 if (p.next_token().asInput() == "*") {
4010 if (command == "citefullauthor")
4011 // alternative name for "\\citeauthor*"
4012 command = "citeauthor*";
4014 // text before the citation
4016 // text after the citation
4018 get_cite_arguments(p, true, before, after);
4020 if (command == "cite") {
4021 // \cite without optional argument means
4022 // \citet, \cite with at least one optional
4023 // argument means \citep.
4024 if (before.empty() && after.empty())
4029 if (before.empty() && after == "[]")
4030 // avoid \citet[]{a}
4032 else if (before == "[]" && after == "[]") {
4033 // avoid \citet[][]{a}
4037 bool literal = false;
4038 pair<bool, string> aft;
4039 pair<bool, string> bef;
4040 // remove the brackets around after and before
4041 if (!after.empty()) {
4043 after.erase(after.length() - 1, 1);
4044 aft = convert_latexed_command_inset_arg(after);
4045 literal = !aft.first;
4046 after = literal ? subst(after, "\n", " ") : aft.second;
4048 if (!before.empty()) {
4050 before.erase(before.length() - 1, 1);
4051 bef = convert_latexed_command_inset_arg(before);
4052 literal |= !bef.first;
4053 before = literal ? subst(before, "\n", " ") : bef.second;
4054 if (literal && !after.empty())
4055 after = subst(after, "\n", " ");
4057 string lit = literal ? "\"true\"" : "\"false\"";
4058 begin_command_inset(os, "citation", command);
4059 os << "after " << '"' << after << '"' << "\n";
4060 os << "before " << '"' << before << '"' << "\n";
4062 << convert_literate_command_inset_arg(p.verbatim_item())
4064 << "literal " << lit << "\n";
4066 // Need to set the cite engine if natbib is loaded by
4067 // the document class directly
4068 if (preamble.citeEngine() == "basic")
4069 preamble.citeEngine("natbib");
4074 && is_known(t.cs(), known_biblatex_commands)
4075 && ((t.cs() == "cite"
4076 || t.cs() == "citeauthor"
4077 || t.cs() == "Citeauthor"
4078 || t.cs() == "parencite"
4079 || t.cs() == "citetitle")
4080 || p.next_token().asInput() != "*"))
4081 || (use_biblatex_natbib
4082 && (is_known(t.cs(), known_biblatex_commands)
4083 || is_known(t.cs(), known_natbib_commands))
4084 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4085 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4086 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4087 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4088 || t.cs() == "parencite" || t.cs() == "citetitle")
4089 || p.next_token().asInput() != "*"))){
4090 context.check_layout(os);
4091 string command = t.cs();
4092 if (p.next_token().asInput() == "*") {
4097 bool const qualified = suffixIs(command, "s");
4099 command = rtrim(command, "s");
4101 // text before the citation
4103 // text after the citation
4105 get_cite_arguments(p, true, before, after, qualified);
4107 // These use natbib cmd names in LyX
4108 // for inter-citeengine compativility
4109 if (command == "citeyear")
4110 command = "citebyear";
4111 else if (command == "cite*")
4112 command = "citeyear";
4113 else if (command == "textcite")
4115 else if (command == "Textcite")
4117 else if (command == "parencite")
4119 else if (command == "Parencite")
4121 else if (command == "parencite*")
4122 command = "citeyearpar";
4123 else if (command == "smartcite")
4124 command = "footcite";
4125 else if (command == "Smartcite")
4126 command = "Footcite";
4128 string const emptyarg = qualified ? "()" : "[]";
4129 if (before.empty() && after == emptyarg)
4132 else if (before == emptyarg && after == emptyarg) {
4133 // avoid \cite[][]{a}
4137 bool literal = false;
4138 pair<bool, string> aft;
4139 pair<bool, string> bef;
4140 // remove the brackets around after and before
4141 if (!after.empty()) {
4143 after.erase(after.length() - 1, 1);
4144 aft = convert_latexed_command_inset_arg(after);
4145 literal = !aft.first;
4146 after = literal ? subst(after, "\n", " ") : aft.second;
4148 if (!before.empty()) {
4150 before.erase(before.length() - 1, 1);
4151 bef = convert_latexed_command_inset_arg(before);
4152 literal |= !bef.first;
4153 before = literal ? subst(before, "\n", " ") : bef.second;
4155 string keys, pretextlist, posttextlist;
4157 map<string, string> pres, posts, preslit, postslit;
4158 vector<string> lkeys;
4159 // text before the citation
4160 string lbefore, lbeforelit;
4161 // text after the citation
4162 string lafter, lafterlit;
4164 pair<bool, string> laft, lbef;
4166 get_cite_arguments(p, true, lbefore, lafter);
4167 // remove the brackets around after and before
4168 if (!lafter.empty()) {
4170 lafter.erase(lafter.length() - 1, 1);
4171 laft = convert_latexed_command_inset_arg(lafter);
4172 literal |= !laft.first;
4173 lafter = laft.second;
4174 lafterlit = subst(lbefore, "\n", " ");
4176 if (!lbefore.empty()) {
4177 lbefore.erase(0, 1);
4178 lbefore.erase(lbefore.length() - 1, 1);
4179 lbef = convert_latexed_command_inset_arg(lbefore);
4180 literal |= !lbef.first;
4181 lbefore = lbef.second;
4182 lbeforelit = subst(lbefore, "\n", " ");
4184 if (lbefore.empty() && lafter == "[]") {
4189 else if (lbefore == "[]" && lafter == "[]") {
4190 // avoid \cite[][]{a}
4196 lkey = p.getArg('{', '}');
4199 if (!lbefore.empty()) {
4200 pres.insert(make_pair(lkey, lbefore));
4201 preslit.insert(make_pair(lkey, lbeforelit));
4203 if (!lafter.empty()) {
4204 posts.insert(make_pair(lkey, lafter));
4205 postslit.insert(make_pair(lkey, lafterlit));
4207 lkeys.push_back(lkey);
4209 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4214 for (auto const & ptl : pres) {
4215 if (!pretextlist.empty())
4216 pretextlist += '\t';
4217 pretextlist += ptl.first + " " + ptl.second;
4219 for (auto const & potl : posts) {
4220 if (!posttextlist.empty())
4221 posttextlist += '\t';
4222 posttextlist += potl.first + " " + potl.second;
4225 keys = convert_literate_command_inset_arg(p.verbatim_item());
4228 after = subst(after, "\n", " ");
4229 if (!before.empty())
4230 before = subst(after, "\n", " ");
4232 string lit = literal ? "\"true\"" : "\"false\"";
4233 begin_command_inset(os, "citation", command);
4234 os << "after " << '"' << after << '"' << "\n";
4235 os << "before " << '"' << before << '"' << "\n";
4239 if (!pretextlist.empty())
4240 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4241 if (!posttextlist.empty())
4242 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4243 os << "literal " << lit << "\n";
4245 // Need to set the cite engine if biblatex is loaded by
4246 // the document class directly
4247 if (preamble.citeEngine() == "basic")
4248 use_biblatex_natbib ?
4249 preamble.citeEngine("biblatex-natbib")
4250 : preamble.citeEngine("biblatex");
4255 is_known(t.cs(), known_jurabib_commands) &&
4256 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4257 context.check_layout(os);
4258 string command = t.cs();
4259 if (p.next_token().asInput() == "*") {
4263 char argumentOrder = '\0';
4264 vector<string> const options =
4265 preamble.getPackageOptions("jurabib");
4266 if (find(options.begin(), options.end(),
4267 "natbiborder") != options.end())
4268 argumentOrder = 'n';
4269 else if (find(options.begin(), options.end(),
4270 "jurabiborder") != options.end())
4271 argumentOrder = 'j';
4273 // text before the citation
4275 // text after the citation
4277 get_cite_arguments(p, argumentOrder != 'j', before, after);
4279 string const citation = p.verbatim_item();
4280 if (!before.empty() && argumentOrder == '\0') {
4281 cerr << "Warning: Assuming argument order "
4282 "of jurabib version 0.6 for\n'"
4283 << command << before << after << '{'
4284 << citation << "}'.\n"
4285 "Add 'jurabiborder' to the jurabib "
4286 "package options if you used an\n"
4287 "earlier jurabib version." << endl;
4289 bool literal = false;
4290 pair<bool, string> aft;
4291 pair<bool, string> bef;
4292 // remove the brackets around after and before
4293 if (!after.empty()) {
4295 after.erase(after.length() - 1, 1);
4296 aft = convert_latexed_command_inset_arg(after);
4297 literal = !aft.first;
4298 after = literal ? subst(after, "\n", " ") : aft.second;
4300 if (!before.empty()) {
4302 before.erase(before.length() - 1, 1);
4303 bef = convert_latexed_command_inset_arg(before);
4304 literal |= !bef.first;
4305 before = literal ? subst(before, "\n", " ") : bef.second;
4306 if (literal && !after.empty())
4307 after = subst(after, "\n", " ");
4309 string lit = literal ? "\"true\"" : "\"false\"";
4310 begin_command_inset(os, "citation", command);
4311 os << "after " << '"' << after << "\"\n"
4312 << "before " << '"' << before << "\"\n"
4313 << "key " << '"' << citation << "\"\n"
4314 << "literal " << lit << "\n";
4316 // Need to set the cite engine if jurabib is loaded by
4317 // the document class directly
4318 if (preamble.citeEngine() == "basic")
4319 preamble.citeEngine("jurabib");
4323 if (t.cs() == "cite"
4324 || t.cs() == "nocite") {
4325 context.check_layout(os);
4326 string after = p.getArg('[', ']');
4327 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4328 bool const literal = !aft.first;
4329 after = literal ? subst(after, "\n", " ") : aft.second;
4330 string lit = literal ? "\"true\"" : "\"false\"";
4331 string key = convert_literate_command_inset_arg(p.verbatim_item());
4332 // store the case that it is "\nocite{*}" to use it later for
4335 begin_command_inset(os, "citation", t.cs());
4336 os << "after " << '"' << after << "\"\n"
4337 << "key " << '"' << key << "\"\n"
4338 << "literal " << lit << "\n";
4340 } else if (t.cs() == "nocite")
4345 if (t.cs() == "index" ||
4346 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4347 context.check_layout(os);
4348 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4349 p.getArg('[', ']') : "";
4350 string const kind = arg.empty() ? "idx" : arg;
4351 begin_inset(os, "Index ");
4352 os << kind << "\nstatus collapsed\n";
4353 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4356 preamble.registerAutomaticallyLoadedPackage("splitidx");
4360 if (t.cs() == "nomenclature") {
4361 context.check_layout(os);
4362 begin_command_inset(os, "nomenclature", "nomenclature");
4363 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4364 if (!prefix.empty())
4365 os << "prefix " << '"' << prefix << '"' << "\n";
4366 string symbol = p.verbatim_item();
4367 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4368 bool literal = !sym.first;
4369 string description = p.verbatim_item();
4370 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4371 literal |= !desc.first;
4373 symbol = subst(symbol, "\n", " ");
4374 description = subst(description, "\n", " ");
4376 symbol = sym.second;
4377 description = desc.second;
4379 string lit = literal ? "\"true\"" : "\"false\"";
4380 os << "symbol " << '"' << symbol;
4381 os << "\"\ndescription \""
4382 << description << "\"\n"
4383 << "literal " << lit << "\n";
4385 preamble.registerAutomaticallyLoadedPackage("nomencl");
4389 if (t.cs() == "label") {
4390 context.check_layout(os);
4391 begin_command_inset(os, "label", "label");
4393 << convert_literate_command_inset_arg(p.verbatim_item())
4399 if (t.cs() == "lyxmintcaption") {
4400 string const pos = p.getArg('[', ']');
4402 string const caption =
4403 parse_text_snippet(p, FLAG_ITEM, false,
4405 minted_nonfloat_caption = "[t]" + caption;
4407 // We already got the caption at the bottom,
4408 // so simply skip it.
4409 parse_text_snippet(p, FLAG_ITEM, false, context);
4414 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4415 context.check_layout(os);
4416 string commandname = t.cs();
4418 if (p.next_token().asInput() == "*") {
4423 begin_command_inset(os, "index_print", commandname);
4424 string const indexname = p.getArg('[', ']');
4426 if (indexname.empty())
4427 os << "type \"idx\"\n";
4429 os << "type \"" << indexname << "\"\n";
4430 os << "literal \"true\"\n";
4433 skip_spaces_braces(p);
4434 preamble.registerAutomaticallyLoadedPackage("makeidx");
4435 if (preamble.use_indices() == "true")
4436 preamble.registerAutomaticallyLoadedPackage("splitidx");
4440 if (t.cs() == "printnomenclature") {
4442 string width_type = "";
4443 context.check_layout(os);
4444 begin_command_inset(os, "nomencl_print", "printnomenclature");
4445 // case of a custom width
4447 width = p.getArg('[', ']');
4448 width = translate_len(width);
4449 width_type = "custom";
4451 // case of no custom width
4452 // the case of no custom width but the width set
4453 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4454 // because the user could have set anything, not only the width
4455 // of the longest label (which would be width_type = "auto")
4456 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4457 if (label.empty() && width_type.empty())
4458 width_type = "none";
4459 os << "set_width \"" << width_type << "\"\n";
4460 if (width_type == "custom")
4461 os << "width \"" << width << '\"';
4463 skip_spaces_braces(p);
4464 preamble.registerAutomaticallyLoadedPackage("nomencl");
4468 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4469 context.check_layout(os);
4470 begin_inset(os, "script ");
4471 os << t.cs().substr(4) << '\n';
4472 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4473 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4475 if (t.cs() == "textsubscript")
4476 preamble.registerAutomaticallyLoadedPackage("subscript");
4480 if ((where = is_known(t.cs(), known_quotes))) {
4481 context.check_layout(os);
4482 begin_inset(os, "Quotes ");
4483 string quotetype = known_coded_quotes[where - known_quotes];
4484 // try to make a smart guess about the side
4485 Token const prev = p.prev_token();
4486 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4487 && prev.character() != '\n' && prev.character() != '~');
4488 quotetype = guessQuoteStyle(quotetype, opening);
4491 // LyX adds {} after the quote, so we have to eat
4492 // spaces here if there are any before a possible
4494 eat_whitespace(p, os, context, false);
4499 if ((where = is_known(t.cs(), known_sizes)) &&
4500 context.new_layout_allowed) {
4501 context.check_layout(os);
4502 TeXFont const oldFont = context.font;
4503 context.font.size = known_coded_sizes[where - known_sizes];
4504 output_font_change(os, oldFont, context.font);
4505 eat_whitespace(p, os, context, false);
4509 if ((where = is_known(t.cs(), known_font_families)) &&
4510 context.new_layout_allowed) {
4511 context.check_layout(os);
4512 TeXFont const oldFont = context.font;
4513 context.font.family =
4514 known_coded_font_families[where - known_font_families];
4515 output_font_change(os, oldFont, context.font);
4516 eat_whitespace(p, os, context, false);
4520 if ((where = is_known(t.cs(), known_font_series)) &&
4521 context.new_layout_allowed) {
4522 context.check_layout(os);
4523 TeXFont const oldFont = context.font;
4524 context.font.series =
4525 known_coded_font_series[where - known_font_series];
4526 output_font_change(os, oldFont, context.font);
4527 eat_whitespace(p, os, context, false);
4531 if ((where = is_known(t.cs(), known_font_shapes)) &&
4532 context.new_layout_allowed) {
4533 context.check_layout(os);
4534 TeXFont const oldFont = context.font;
4535 context.font.shape =
4536 known_coded_font_shapes[where - known_font_shapes];
4537 output_font_change(os, oldFont, context.font);
4538 eat_whitespace(p, os, context, false);
4541 if ((where = is_known(t.cs(), known_old_font_families)) &&
4542 context.new_layout_allowed) {
4543 context.check_layout(os);
4544 TeXFont const oldFont = context.font;
4545 context.font.init();
4546 context.font.size = oldFont.size;
4547 context.font.family =
4548 known_coded_font_families[where - known_old_font_families];
4549 output_font_change(os, oldFont, context.font);
4550 eat_whitespace(p, os, context, false);
4554 if ((where = is_known(t.cs(), known_old_font_series)) &&
4555 context.new_layout_allowed) {
4556 context.check_layout(os);
4557 TeXFont const oldFont = context.font;
4558 context.font.init();
4559 context.font.size = oldFont.size;
4560 context.font.series =
4561 known_coded_font_series[where - known_old_font_series];
4562 output_font_change(os, oldFont, context.font);
4563 eat_whitespace(p, os, context, false);
4567 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4568 context.new_layout_allowed) {
4569 context.check_layout(os);
4570 TeXFont const oldFont = context.font;
4571 context.font.init();
4572 context.font.size = oldFont.size;
4573 context.font.shape =
4574 known_coded_font_shapes[where - known_old_font_shapes];
4575 output_font_change(os, oldFont, context.font);
4576 eat_whitespace(p, os, context, false);
4580 if (t.cs() == "selectlanguage") {
4581 context.check_layout(os);
4582 // save the language for the case that a
4583 // \foreignlanguage is used
4584 context.font.language = babel2lyx(p.verbatim_item());
4585 os << "\n\\lang " << context.font.language << "\n";
4589 if (t.cs() == "foreignlanguage") {
4590 string const lang = babel2lyx(p.verbatim_item());
4591 parse_text_attributes(p, os, FLAG_ITEM, outer,
4593 context.font.language, lang);
4597 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4598 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4599 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4601 // We have to output the whole command if it has an option
4602 // because LyX doesn't support this yet, see bug #8214,
4603 // only if there is a single option specifying a variant, we can handle it.
4605 string langopts = p.getOpt();
4606 // check if the option contains a variant, if yes, extract it
4607 string::size_type pos_var = langopts.find("variant");
4608 string::size_type i = langopts.find(',');
4609 string::size_type k = langopts.find('=', pos_var);
4610 if (pos_var != string::npos && i == string::npos) {
4612 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4613 lang = preamble.polyglossia2lyx(variant);
4614 parse_text_attributes(p, os, FLAG_ITEM, outer,
4616 context.font.language, lang);
4618 output_ert_inset(os, t.asInput() + langopts, context);
4620 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4621 parse_text_attributes(p, os, FLAG_ITEM, outer,
4623 context.font.language, lang);
4628 if (t.cs() == "inputencoding") {
4629 // nothing to write here
4630 string const enc = subst(p.verbatim_item(), "\n", " ");
4631 p.setEncoding(enc, Encoding::inputenc);
4635 if (is_known(t.cs(), known_special_chars) ||
4636 (t.cs() == "protect" &&
4637 p.next_token().cat() == catEscape &&
4638 is_known(p.next_token().cs(), known_special_protect_chars))) {
4639 // LyX sometimes puts a \protect in front, so we have to ignore it
4641 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4642 known_special_chars);
4643 context.check_layout(os);
4644 os << known_coded_special_chars[where - known_special_chars];
4645 skip_spaces_braces(p);
4649 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4650 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4651 p.next_next_token().asInput() == "-") ||
4652 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4653 // LyX sometimes puts a \protect in front, so we have to ignore it
4654 if (t.cs() == "protect")
4656 context.check_layout(os);
4657 if (t.cs() == "nobreakdash")
4658 os << "\\SpecialChar nobreakdash\n";
4660 os << "\\SpecialChar endofsentence\n";
4665 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4666 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4667 || t.cs() == "%" || t.cs() == "-") {
4668 context.check_layout(os);
4670 os << "\\SpecialChar softhyphen\n";
4676 if (t.cs() == "char") {
4677 context.check_layout(os);
4678 if (p.next_token().character() == '`') {
4680 if (p.next_token().cs() == "\"") {
4685 output_ert_inset(os, "\\char`", context);
4688 output_ert_inset(os, "\\char", context);
4693 if (t.cs() == "verb") {
4694 context.check_layout(os);
4695 // set catcodes to verbatim early, just in case.
4696 p.setCatcodes(VERBATIM_CATCODES);
4697 string delim = p.get_token().asInput();
4698 Parser::Arg arg = p.verbatimStuff(delim);
4700 output_ert_inset(os, "\\verb" + delim
4701 + arg.second + delim, context);
4703 cerr << "invalid \\verb command. Skipping" << endl;
4707 // Problem: \= creates a tabstop inside the tabbing environment
4708 // and else an accent. In the latter case we really would want
4709 // \={o} instead of \= o.
4710 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4711 output_ert_inset(os, t.asInput(), context);
4715 if (t.cs() == "\\") {
4716 context.check_layout(os);
4718 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4719 else if (p.next_token().asInput() == "*") {
4721 // getOpt() eats the following space if there
4722 // is no optional argument, but that is OK
4723 // here since it has no effect in the output.
4724 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4727 begin_inset(os, "Newline newline");
4733 if (t.cs() == "newline" ||
4734 (t.cs() == "linebreak" && !p.hasOpt())) {
4735 context.check_layout(os);
4736 begin_inset(os, "Newline ");
4739 skip_spaces_braces(p);
4743 if (t.cs() == "input" || t.cs() == "include"
4744 || t.cs() == "verbatiminput"
4745 || t.cs() == "lstinputlisting") {
4746 string name = t.cs();
4747 if (name == "verbatiminput"
4748 && p.next_token().asInput() == "*")
4749 name += p.get_token().asInput();
4750 context.check_layout(os);
4752 bool literal = false;
4753 if (name == "lstinputlisting" && p.hasOpt()) {
4754 lstparams = p.getArg('[', ']');
4755 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4756 literal = !oa.first;
4758 lstparams = subst(lstparams, "\n", " ");
4760 string lit = literal ? "\"true\"" : "\"false\"";
4761 string filename(normalize_filename(p.getArg('{', '}')));
4762 string const path = getMasterFilePath(true);
4763 // We want to preserve relative / absolute filenames,
4764 // therefore path is only used for testing
4765 if ((t.cs() == "include" || t.cs() == "input") &&
4766 !makeAbsPath(filename, path).exists()) {
4767 // The file extension is probably missing.
4768 // Now try to find it out.
4769 string const tex_name =
4770 find_file(filename, path,
4771 known_tex_extensions);
4772 if (!tex_name.empty())
4773 filename = tex_name;
4775 bool external = false;
4777 if (makeAbsPath(filename, path).exists()) {
4778 string const abstexname =
4779 makeAbsPath(filename, path).absFileName();
4780 string const absfigname =
4781 changeExtension(abstexname, ".fig");
4782 fix_child_filename(filename);
4783 string const lyxname = changeExtension(filename,
4784 roundtripMode() ? ".lyx.lyx" : ".lyx");
4785 string const abslyxname = makeAbsPath(
4786 lyxname, getParentFilePath(false)).absFileName();
4788 if (!skipChildren())
4789 external = FileName(absfigname).exists();
4790 if (t.cs() == "input" && !skipChildren()) {
4791 string const ext = getExtension(abstexname);
4793 // Combined PS/LaTeX:
4794 // x.eps, x.pstex_t (old xfig)
4795 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4796 FileName const absepsname(
4797 changeExtension(abstexname, ".eps"));
4798 FileName const abspstexname(
4799 changeExtension(abstexname, ".pstex"));
4800 bool const xfigeps =
4801 (absepsname.exists() ||
4802 abspstexname.exists()) &&
4805 // Combined PDF/LaTeX:
4806 // x.pdf, x.pdftex_t (old xfig)
4807 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4808 FileName const abspdfname(
4809 changeExtension(abstexname, ".pdf"));
4810 bool const xfigpdf =
4811 abspdfname.exists() &&
4812 (ext == "pdftex_t" || ext == "pdf_t");
4816 // Combined PS/PDF/LaTeX:
4817 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4818 string const absbase2(
4819 removeExtension(abstexname) + "_pspdftex");
4820 FileName const abseps2name(
4821 addExtension(absbase2, ".eps"));
4822 FileName const abspdf2name(
4823 addExtension(absbase2, ".pdf"));
4824 bool const xfigboth =
4825 abspdf2name.exists() &&
4826 abseps2name.exists() && ext == "pspdftex";
4828 xfig = xfigpdf || xfigeps || xfigboth;
4829 external = external && xfig;
4832 outname = changeExtension(filename, ".fig");
4833 FileName abssrc(changeExtension(abstexname, ".fig"));
4834 copy_file(abssrc, outname);
4836 // Don't try to convert, the result
4837 // would be full of ERT.
4839 FileName abssrc(abstexname);
4840 copy_file(abssrc, outname);
4841 } else if (t.cs() != "verbatiminput" &&
4843 tex2lyx(abstexname, FileName(abslyxname),
4846 // no need to call copy_file
4847 // tex2lyx creates the file
4850 FileName abssrc(abstexname);
4851 copy_file(abssrc, outname);
4854 cerr << "Warning: Could not find included file '"
4855 << filename << "'." << endl;
4859 begin_inset(os, "External\n");
4860 os << "\ttemplate XFig\n"
4861 << "\tfilename " << outname << '\n';
4862 registerExternalTemplatePackages("XFig");
4864 begin_command_inset(os, "include", name);
4865 outname = subst(outname, "\"", "\\\"");
4866 os << "preview false\n"
4867 "filename \"" << outname << "\"\n";
4868 if (!lstparams.empty())
4869 os << "lstparams \"" << lstparams << "\"\n";
4870 os << "literal " << lit << "\n";
4871 if (t.cs() == "verbatiminput")
4872 preamble.registerAutomaticallyLoadedPackage("verbatim");
4878 if (t.cs() == "bibliographystyle") {
4879 // store new bibliographystyle
4880 bibliographystyle = p.verbatim_item();
4881 // If any other command than \bibliography, \addcontentsline
4882 // and \nocite{*} follows, we need to output the style
4883 // (because it might be used by that command).
4884 // Otherwise, it will automatically be output by LyX.
4887 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4888 if (t2.cat() == catBegin)
4890 if (t2.cat() != catEscape)
4892 if (t2.cs() == "nocite") {
4893 if (p.getArg('{', '}') == "*")
4895 } else if (t2.cs() == "bibliography")
4897 else if (t2.cs() == "phantomsection") {
4901 else if (t2.cs() == "addcontentsline") {
4902 // get the 3 arguments of \addcontentsline
4905 contentslineContent = p.getArg('{', '}');
4906 // if the last argument is not \refname we must output
4907 if (contentslineContent == "\\refname")
4914 output_ert_inset(os,
4915 "\\bibliographystyle{" + bibliographystyle + '}',
4921 if (t.cs() == "phantomsection") {
4922 // we only support this if it occurs between
4923 // \bibliographystyle and \bibliography
4924 if (bibliographystyle.empty())
4925 output_ert_inset(os, "\\phantomsection", context);
4929 if (t.cs() == "addcontentsline") {
4930 context.check_layout(os);
4931 // get the 3 arguments of \addcontentsline
4932 string const one = p.getArg('{', '}');
4933 string const two = p.getArg('{', '}');
4934 string const three = p.getArg('{', '}');
4935 // only if it is a \refname, we support if for the bibtex inset
4936 if (contentslineContent != "\\refname") {
4937 output_ert_inset(os,
4938 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4944 else if (t.cs() == "bibliography") {
4945 context.check_layout(os);
4947 begin_command_inset(os, "bibtex", "bibtex");
4948 if (!btprint.empty()) {
4949 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4950 // clear the string because the next BibTeX inset can be without the
4951 // \nocite{*} option
4954 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4955 // Do we have addcontentsline?
4956 if (contentslineContent == "\\refname") {
4957 BibOpts = "bibtotoc";
4958 // clear string because next BibTeX inset can be without addcontentsline
4959 contentslineContent.clear();
4961 // Do we have a bibliographystyle set?
4962 if (!bibliographystyle.empty()) {
4963 if (BibOpts.empty())
4964 BibOpts = normalize_filename(bibliographystyle);
4966 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4967 // clear it because each bibtex entry has its style
4968 // and we need an empty string to handle \phantomsection
4969 bibliographystyle.clear();
4971 os << "options " << '"' << BibOpts << '"' << "\n";
4976 if (t.cs() == "printbibliography") {
4977 context.check_layout(os);
4979 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4980 vector<string> opts = getVectorFromString(bbloptions);
4981 vector<string>::iterator it =
4982 find(opts.begin(), opts.end(), "heading=bibintoc");
4983 if (it != opts.end()) {
4985 BibOpts = "bibtotoc";
4987 bbloptions = getStringFromVector(opts);
4988 begin_command_inset(os, "bibtex", "bibtex");
4989 if (!btprint.empty()) {
4990 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4991 // clear the string because the next BibTeX inset can be without the
4992 // \nocite{*} option
4996 for (auto const & bf : preamble.biblatex_bibliographies) {
4997 if (!bibfiles.empty())
4999 bibfiles += normalize_filename(bf);
5001 if (!bibfiles.empty())
5002 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5003 // Do we have addcontentsline?
5004 if (contentslineContent == "\\refname") {
5005 BibOpts = "bibtotoc";
5006 // clear string because next BibTeX inset can be without addcontentsline
5007 contentslineContent.clear();
5009 os << "options " << '"' << BibOpts << '"' << "\n";
5010 if (!bbloptions.empty())
5011 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5013 need_commentbib = false;
5017 if (t.cs() == "bibbysection") {
5018 context.check_layout(os);
5020 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5021 vector<string> opts = getVectorFromString(bbloptions);
5022 vector<string>::iterator it =
5023 find(opts.begin(), opts.end(), "heading=bibintoc");
5024 if (it != opts.end()) {
5026 BibOpts = "bibtotoc";
5028 bbloptions = getStringFromVector(opts);
5029 begin_command_inset(os, "bibtex", "bibtex");
5030 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5032 for (auto const & bf : preamble.biblatex_bibliographies) {
5033 if (!bibfiles.empty())
5035 bibfiles += normalize_filename(bf);
5037 if (!bibfiles.empty())
5038 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5039 os << "options " << '"' << BibOpts << '"' << "\n";
5040 if (!bbloptions.empty())
5041 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5043 need_commentbib = false;
5047 if (t.cs() == "parbox") {
5048 // Test whether this is an outer box of a shaded box
5050 // swallow arguments
5051 while (p.hasOpt()) {
5053 p.skip_spaces(true);
5056 p.skip_spaces(true);
5058 if (p.next_token().cat() == catBegin)
5060 p.skip_spaces(true);
5061 Token to = p.get_token();
5062 bool shaded = false;
5063 if (to.asInput() == "\\begin") {
5064 p.skip_spaces(true);
5065 if (p.getArg('{', '}') == "shaded")
5070 parse_outer_box(p, os, FLAG_ITEM, outer,
5071 context, "parbox", "shaded");
5073 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5074 "", "", t.cs(), "", "");
5078 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5079 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5080 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5081 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5085 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5086 string backgroundcolor;
5087 preamble.registerAutomaticallyLoadedPackage("xcolor");
5088 if (t.cs() == "fcolorbox") {
5089 string const framecolor = p.getArg('{', '}');
5090 backgroundcolor = p.getArg('{', '}');
5091 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5093 backgroundcolor = p.getArg('{', '}');
5094 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5099 // FIXME: due to the compiler limit of "if" nestings
5100 // the code for the alignment was put here
5101 // put them in their own if if this is fixed
5102 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5103 || t.cs() == "shadowsize"
5104 || t.cs() == "raggedleft" || t.cs() == "centering"
5105 || t.cs() == "raggedright") {
5106 if (t.cs() == "fboxrule")
5108 if (t.cs() == "fboxsep")
5110 if (t.cs() == "shadowsize")
5112 if (t.cs() != "raggedleft" && t.cs() != "centering"
5113 && t.cs() != "raggedright") {
5114 p.skip_spaces(true);
5115 while (p.good() && p.next_token().cat() != catSpace
5116 && p.next_token().cat() != catNewline
5117 && p.next_token().cat() != catEscape) {
5118 if (t.cs() == "fboxrule")
5119 fboxrule = fboxrule + p.get_token().asInput();
5120 if (t.cs() == "fboxsep")
5121 fboxsep = fboxsep + p.get_token().asInput();
5122 if (t.cs() == "shadowsize")
5123 shadow_size = shadow_size + p.get_token().asInput();
5126 output_ert_inset(os, t.asInput(), context);
5131 //\framebox() is part of the picture environment and different from \framebox{}
5132 //\framebox{} will be parsed by parse_outer_box
5133 if (t.cs() == "framebox") {
5134 if (p.next_token().character() == '(') {
5135 //the syntax is: \framebox(x,y)[position]{content}
5136 string arg = t.asInput();
5137 arg += p.getFullParentheseArg();
5138 arg += p.getFullOpt();
5139 eat_whitespace(p, os, context, false);
5140 output_ert_inset(os, arg + '{', context);
5141 parse_text(p, os, FLAG_ITEM, outer, context);
5142 output_ert_inset(os, "}", context);
5144 //the syntax is: \framebox[width][position]{content}
5145 string special = p.getFullOpt();
5146 special += p.getOpt();
5147 parse_outer_box(p, os, FLAG_ITEM, outer,
5148 context, t.cs(), special);
5153 //\makebox() is part of the picture environment and different from \makebox{}
5154 //\makebox{} will be parsed by parse_box
5155 if (t.cs() == "makebox") {
5156 if (p.next_token().character() == '(') {
5157 //the syntax is: \makebox(x,y)[position]{content}
5158 string arg = t.asInput();
5159 arg += p.getFullParentheseArg();
5160 arg += p.getFullOpt();
5161 eat_whitespace(p, os, context, false);
5162 output_ert_inset(os, arg + '{', context);
5163 parse_text(p, os, FLAG_ITEM, outer, context);
5164 output_ert_inset(os, "}", context);
5166 //the syntax is: \makebox[width][position]{content}
5167 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5168 "", "", t.cs(), "", "");
5172 if (t.cs() == "smallskip" ||
5173 t.cs() == "medskip" ||
5174 t.cs() == "bigskip" ||
5175 t.cs() == "vfill") {
5176 context.check_layout(os);
5177 begin_inset(os, "VSpace ");
5180 skip_spaces_braces(p);
5184 if ((where = is_known(t.cs(), known_spaces))) {
5185 context.check_layout(os);
5186 begin_inset(os, "space ");
5187 os << '\\' << known_coded_spaces[where - known_spaces]
5190 // LaTeX swallows whitespace after all spaces except
5191 // "\\,". We have to do that here, too, because LyX
5192 // adds "{}" which would make the spaces significant.
5194 eat_whitespace(p, os, context, false);
5195 // LyX adds "{}" after all spaces except "\\ " and
5196 // "\\,", so we have to remove "{}".
5197 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5198 // remove the braces after "\\,", too.
5204 if (t.cs() == "newpage" ||
5205 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5206 t.cs() == "clearpage" ||
5207 t.cs() == "cleardoublepage") {
5208 context.check_layout(os);
5209 begin_inset(os, "Newpage ");
5212 skip_spaces_braces(p);
5216 if (t.cs() == "DeclareRobustCommand" ||
5217 t.cs() == "DeclareRobustCommandx" ||
5218 t.cs() == "newcommand" ||
5219 t.cs() == "newcommandx" ||
5220 t.cs() == "providecommand" ||
5221 t.cs() == "providecommandx" ||
5222 t.cs() == "renewcommand" ||
5223 t.cs() == "renewcommandx") {
5224 // DeclareRobustCommand, DeclareRobustCommandx,
5225 // providecommand and providecommandx could be handled
5226 // by parse_command(), but we need to call
5227 // add_known_command() here.
5228 string name = t.asInput();
5229 if (p.next_token().asInput() == "*") {
5230 // Starred form. Eat '*'
5234 string const command = p.verbatim_item();
5235 string const opt1 = p.getFullOpt();
5236 string const opt2 = p.getFullOpt();
5237 add_known_command(command, opt1, !opt2.empty());
5238 string const ert = name + '{' + command + '}' +
5240 '{' + p.verbatim_item() + '}';
5242 if (t.cs() == "DeclareRobustCommand" ||
5243 t.cs() == "DeclareRobustCommandx" ||
5244 t.cs() == "providecommand" ||
5245 t.cs() == "providecommandx" ||
5246 name[name.length()-1] == '*')
5247 output_ert_inset(os, ert, context);
5249 context.check_layout(os);
5250 begin_inset(os, "FormulaMacro");
5257 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5258 // let could be handled by parse_command(),
5259 // but we need to call add_known_command() here.
5260 string ert = t.asInput();
5263 if (p.next_token().cat() == catBegin) {
5264 name = p.verbatim_item();
5265 ert += '{' + name + '}';
5267 name = p.verbatim_item();
5272 if (p.next_token().cat() == catBegin) {
5273 command = p.verbatim_item();
5274 ert += '{' + command + '}';
5276 command = p.verbatim_item();
5279 // If command is known, make name known too, to parse
5280 // its arguments correctly. For this reason we also
5281 // have commands in syntax.default that are hardcoded.
5282 CommandMap::iterator it = known_commands.find(command);
5283 if (it != known_commands.end())
5284 known_commands[t.asInput()] = it->second;
5285 output_ert_inset(os, ert, context);
5289 if (t.cs() == "hspace" || t.cs() == "vspace") {
5292 string name = t.asInput();
5293 string const length = p.verbatim_item();
5296 bool valid = splitLatexLength(length, valstring, unit);
5297 bool known_hspace = false;
5298 bool known_vspace = false;
5299 bool known_unit = false;
5302 istringstream iss(valstring);
5305 if (t.cs()[0] == 'h') {
5306 if (unit == "\\fill") {
5311 known_hspace = true;
5314 if (unit == "\\smallskipamount") {
5316 known_vspace = true;
5317 } else if (unit == "\\medskipamount") {
5319 known_vspace = true;
5320 } else if (unit == "\\bigskipamount") {
5322 known_vspace = true;
5323 } else if (unit == "\\fill") {
5325 known_vspace = true;
5329 if (!known_hspace && !known_vspace) {
5330 switch (unitFromString(unit)) {
5346 //unitFromString(unit) fails for relative units like Length::PCW
5347 // therefore handle them separately
5348 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5349 || unit == "\\textwidth" || unit == "\\linewidth"
5350 || unit == "\\textheight" || unit == "\\paperheight"
5351 || unit == "\\baselineskip")
5359 // check for glue lengths
5360 bool is_gluelength = false;
5361 string gluelength = length;
5362 string::size_type i = length.find(" minus");
5363 if (i == string::npos) {
5364 i = length.find(" plus");
5365 if (i != string::npos)
5366 is_gluelength = true;
5368 is_gluelength = true;
5369 // if yes transform "9xx minus 8yy plus 7zz"
5371 if (is_gluelength) {
5372 i = gluelength.find(" minus");
5373 if (i != string::npos)
5374 gluelength.replace(i, 7, "-");
5375 i = gluelength.find(" plus");
5376 if (i != string::npos)
5377 gluelength.replace(i, 6, "+");
5380 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5381 // Literal horizontal length or known variable
5382 context.check_layout(os);
5383 begin_inset(os, "space ");
5391 if (known_unit && !known_hspace)
5392 os << "\n\\length " << translate_len(length);
5394 os << "\n\\length " << gluelength;
5396 } else if (known_unit || known_vspace || is_gluelength) {
5397 // Literal vertical length or known variable
5398 context.check_layout(os);
5399 begin_inset(os, "VSpace ");
5402 if (known_unit && !known_vspace)
5403 os << translate_len(length);
5410 // LyX can't handle other length variables in Inset VSpace/space
5415 output_ert_inset(os, name + '{' + unit + '}', context);
5416 else if (value == -1.0)
5417 output_ert_inset(os, name + "{-" + unit + '}', context);
5419 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5421 output_ert_inset(os, name + '{' + length + '}', context);
5426 // The single '=' is meant here.
5427 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5431 context.check_layout(os);
5432 docstring name = newinsetlayout->name();
5433 bool const caption = name.find(from_ascii("Caption:")) == 0;
5435 // Already done for floating minted listings.
5436 if (minted_float.empty()) {
5437 begin_inset(os, "Caption ");
5438 os << to_utf8(name.substr(8)) << '\n';
5441 // FIXME: what do we do if the prefix is not Flex: ?
5442 if (prefixIs(name, from_ascii("Flex:")))
5444 begin_inset(os, "Flex ");
5445 os << to_utf8(name) << '\n'
5446 << "status collapsed\n";
5448 if (!minted_float.empty()) {
5449 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5450 } else if (newinsetlayout->isPassThru()) {
5451 // set catcodes to verbatim early, just in case.
5452 p.setCatcodes(VERBATIM_CATCODES);
5453 string delim = p.get_token().asInput();
5455 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5456 //FIXME: handle error condition
5457 string const arg = p.verbatimStuff("}").second;
5458 Context newcontext(true, context.textclass);
5459 if (newinsetlayout->forcePlainLayout())
5460 newcontext.layout = &context.textclass.plainLayout();
5461 output_ert(os, arg, newcontext);
5463 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5466 // Minted caption insets are not closed here because
5467 // we collect everything into the caption.
5468 if (minted_float.empty())
5473 if (t.cs() == "includepdf") {
5475 string const arg = p.getArg('[', ']');
5476 map<string, string> opts;
5477 vector<string> keys;
5478 split_map(arg, opts, keys);
5479 string name = normalize_filename(p.verbatim_item());
5480 string const path = getMasterFilePath(true);
5481 // We want to preserve relative / absolute filenames,
5482 // therefore path is only used for testing
5483 if (!makeAbsPath(name, path).exists()) {
5484 // The file extension is probably missing.
5485 // Now try to find it out.
5486 char const * const pdfpages_format[] = {"pdf", 0};
5487 string const pdftex_name =
5488 find_file(name, path, pdfpages_format);
5489 if (!pdftex_name.empty()) {
5494 FileName const absname = makeAbsPath(name, path);
5495 if (absname.exists())
5497 fix_child_filename(name);
5498 copy_file(absname, name);
5500 cerr << "Warning: Could not find file '"
5501 << name << "'." << endl;
5503 context.check_layout(os);
5504 begin_inset(os, "External\n\ttemplate ");
5505 os << "PDFPages\n\tfilename "
5507 // parse the options
5508 if (opts.find("pages") != opts.end())
5509 os << "\textra LaTeX \"pages="
5510 << opts["pages"] << "\"\n";
5511 if (opts.find("angle") != opts.end())
5512 os << "\trotateAngle "
5513 << opts["angle"] << '\n';
5514 if (opts.find("origin") != opts.end()) {
5516 string const opt = opts["origin"];
5517 if (opt == "tl") ss << "topleft";
5518 if (opt == "bl") ss << "bottomleft";
5519 if (opt == "Bl") ss << "baselineleft";
5520 if (opt == "c") ss << "center";
5521 if (opt == "tc") ss << "topcenter";
5522 if (opt == "bc") ss << "bottomcenter";
5523 if (opt == "Bc") ss << "baselinecenter";
5524 if (opt == "tr") ss << "topright";
5525 if (opt == "br") ss << "bottomright";
5526 if (opt == "Br") ss << "baselineright";
5527 if (!ss.str().empty())
5528 os << "\trotateOrigin " << ss.str() << '\n';
5530 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5532 if (opts.find("width") != opts.end())
5534 << translate_len(opts["width"]) << '\n';
5535 if (opts.find("height") != opts.end())
5537 << translate_len(opts["height"]) << '\n';
5538 if (opts.find("keepaspectratio") != opts.end())
5539 os << "\tkeepAspectRatio\n";
5541 context.check_layout(os);
5542 registerExternalTemplatePackages("PDFPages");
5546 if (t.cs() == "loadgame") {
5548 string name = normalize_filename(p.verbatim_item());
5549 string const path = getMasterFilePath(true);
5550 // We want to preserve relative / absolute filenames,
5551 // therefore path is only used for testing
5552 if (!makeAbsPath(name, path).exists()) {
5553 // The file extension is probably missing.
5554 // Now try to find it out.
5555 char const * const lyxskak_format[] = {"fen", 0};
5556 string const lyxskak_name =
5557 find_file(name, path, lyxskak_format);
5558 if (!lyxskak_name.empty())
5559 name = lyxskak_name;
5561 FileName const absname = makeAbsPath(name, path);
5562 if (absname.exists())
5564 fix_child_filename(name);
5565 copy_file(absname, name);
5567 cerr << "Warning: Could not find file '"
5568 << name << "'." << endl;
5569 context.check_layout(os);
5570 begin_inset(os, "External\n\ttemplate ");
5571 os << "ChessDiagram\n\tfilename "
5574 context.check_layout(os);
5575 // after a \loadgame follows a \showboard
5576 if (p.get_token().asInput() == "showboard")
5578 registerExternalTemplatePackages("ChessDiagram");
5582 // try to see whether the string is in unicodesymbols
5583 // Only use text mode commands, since we are in text mode here,
5584 // and math commands may be invalid (bug 6797)
5585 string name = t.asInput();
5586 // handle the dingbats, cyrillic and greek
5587 if (name == "\\ding" || name == "\\textcyr" ||
5588 (name == "\\textgreek" && !preamble.usePolyglossia()))
5589 name = name + '{' + p.getArg('{', '}') + '}';
5590 // handle the ifsym characters
5591 else if (name == "\\textifsymbol") {
5592 string const optif = p.getFullOpt();
5593 string const argif = p.getArg('{', '}');
5594 name = name + optif + '{' + argif + '}';
5596 // handle the \ascii characters
5597 // the case of \ascii within braces, as LyX outputs it, is already
5598 // handled for t.cat() == catBegin
5599 else if (name == "\\ascii") {
5600 // the code is "\asci\xxx"
5601 name = "{" + name + p.get_token().asInput() + "}";
5604 // handle some TIPA special characters
5605 else if (preamble.isPackageUsed("tipa")) {
5606 if (name == "\\s") {
5607 // fromLaTeXCommand() does not yet
5608 // recognize tipa short cuts
5609 name = "\\textsyllabic";
5610 } else if (name == "\\=" &&
5611 p.next_token().asInput() == "*") {
5612 // fromLaTeXCommand() does not yet
5613 // recognize tipa short cuts
5615 name = "\\textsubbar";
5616 } else if (name == "\\textdoublevertline") {
5617 // FIXME: This is not correct,
5618 // \textvertline is higher than \textbardbl
5619 name = "\\textbardbl";
5621 } else if (name == "\\!" ) {
5622 if (p.next_token().asInput() == "b") {
5623 p.get_token(); // eat 'b'
5626 } else if (p.next_token().asInput() == "d") {
5630 } else if (p.next_token().asInput() == "g") {
5634 } else if (p.next_token().asInput() == "G") {
5636 name = "\\texthtscg";
5638 } else if (p.next_token().asInput() == "j") {
5640 name = "\\texthtbardotlessj";
5642 } else if (p.next_token().asInput() == "o") {
5644 name = "\\textbullseye";
5647 } else if (name == "\\*" ) {
5648 if (p.next_token().asInput() == "k") {
5650 name = "\\textturnk";
5652 } else if (p.next_token().asInput() == "r") {
5653 p.get_token(); // eat 'b'
5654 name = "\\textturnr";
5656 } else if (p.next_token().asInput() == "t") {
5658 name = "\\textturnt";
5660 } else if (p.next_token().asInput() == "w") {
5662 name = "\\textturnw";
5667 if ((name.size() == 2 &&
5668 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5669 p.next_token().asInput() != "*") ||
5670 is_known(name.substr(1), known_tipa_marks)) {
5671 // name is a command that corresponds to a
5672 // combining character in unicodesymbols.
5673 // Append the argument, fromLaTeXCommand()
5674 // will either convert it to a single
5675 // character or a combining sequence.
5676 name += '{' + p.verbatim_item() + '}';
5678 // now get the character from unicodesymbols
5682 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5683 Encodings::TEXT_CMD, termination, rem, &req));
5685 context.check_layout(os);
5688 output_ert_inset(os, to_utf8(rem), context);
5690 skip_spaces_braces(p);
5691 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5692 preamble.registerAutomaticallyLoadedPackage(*it);
5694 //cerr << "#: " << t << " mode: " << mode << endl;
5695 // heuristic: read up to next non-nested space
5697 string s = t.asInput();
5698 string z = p.verbatim_item();
5699 while (p.good() && z != " " && !z.empty()) {
5700 //cerr << "read: " << z << endl;
5702 z = p.verbatim_item();
5704 cerr << "found ERT: " << s << endl;
5705 output_ert_inset(os, s + ' ', context);
5708 if (t.asInput() == name &&
5709 p.next_token().asInput() == "*") {
5710 // Starred commands like \vspace*{}
5711 p.get_token(); // Eat '*'
5714 if (!parse_command(name, p, os, outer, context))
5715 output_ert_inset(os, name, context);
5721 string guessLanguage(Parser & p, string const & lang)
5723 typedef std::map<std::string, size_t> LangMap;
5724 // map from language names to number of characters
5727 for (char const * const * i = supported_CJK_languages; *i; i++)
5728 used[string(*i)] = 0;
5731 Token const t = p.get_token();
5732 // comments are not counted for any language
5733 if (t.cat() == catComment)
5735 // commands are not counted as well, but we need to detect
5736 // \begin{CJK} and switch encoding if needed
5737 if (t.cat() == catEscape) {
5738 if (t.cs() == "inputencoding") {
5739 string const enc = subst(p.verbatim_item(), "\n", " ");
5740 p.setEncoding(enc, Encoding::inputenc);
5743 if (t.cs() != "begin")
5746 // Non-CJK content is counted for lang.
5747 // We do not care about the real language here:
5748 // If we have more non-CJK contents than CJK contents,
5749 // we simply use the language that was specified as
5750 // babel main language.
5751 used[lang] += t.asInput().length();
5754 // Now we are starting an environment
5756 string const name = p.getArg('{', '}');
5757 if (name != "CJK") {
5761 // It is a CJK environment
5763 /* name = */ p.getArg('{', '}');
5764 string const encoding = p.getArg('{', '}');
5765 /* mapping = */ p.getArg('{', '}');
5766 string const encoding_old = p.getEncoding();
5767 char const * const * const where =
5768 is_known(encoding, supported_CJK_encodings);
5770 p.setEncoding(encoding, Encoding::CJK);
5772 p.setEncoding("UTF-8");
5773 string const text = p.ertEnvironment("CJK");
5774 p.setEncoding(encoding_old);
5777 // ignore contents in unknown CJK encoding
5780 // the language of the text
5782 supported_CJK_languages[where - supported_CJK_encodings];
5783 used[cjk] += text.length();
5785 LangMap::const_iterator use = used.begin();
5786 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5787 if (it->second > use->second)
5794 void check_comment_bib(ostream & os, Context & context)
5796 if (!need_commentbib)
5798 // We have a bibliography database, but no bibliography with biblatex
5799 // which is completely valid. Insert a bibtex inset in a note.
5800 context.check_layout(os);
5801 begin_inset(os, "Note Note\n");
5802 os << "status open\n";
5803 os << "\\begin_layout Plain Layout\n";
5804 begin_command_inset(os, "bibtex", "bibtex");
5806 for (auto const & bf : preamble.biblatex_bibliographies) {
5807 if (!bibfiles.empty())
5809 bibfiles += normalize_filename(bf);
5811 if (!bibfiles.empty())
5812 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5813 end_inset(os);// Bibtex
5814 os << "\\end_layout\n";
5815 end_inset(os);// Note