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, string, 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, string(), newcontext,
70 parse_text(p, os, flags, outer, newcontext, rdelim);
72 output_arguments(os, p, outer, false, "post", 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 (c != 0 && 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, string const prefix,
753 Context & context, Layout::LaTeXArgMap const & latexargs)
755 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
757 context.check_layout(os);
763 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
764 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
765 for (; lait != laend; ++lait) {
767 eat_whitespace(p, os, context, false);
768 if (lait->second.mandatory) {
769 if (p.next_token().cat() != catBegin)
771 string ldelim = to_utf8(lait->second.ldelim);
772 string rdelim = to_utf8(lait->second.rdelim);
777 p.get_token(); // eat ldelim
778 if (ldelim.size() > 1)
779 p.get_token(); // eat ldelim
781 context.check_layout(os);
784 begin_inset(os, "Argument ");
787 os << i << "\nstatus collapsed\n\n";
788 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
791 string ldelim = to_utf8(lait->second.ldelim);
792 string rdelim = to_utf8(lait->second.rdelim);
797 string tok = p.next_token().asInput();
798 // we only support delimiters with max 2 chars for now.
799 if (ldelim.size() > 1)
800 tok += p.next_next_token().asInput();
801 if (p.next_token().cat() == catEscape || tok != ldelim)
803 p.get_token(); // eat ldelim
804 if (ldelim.size() > 1)
805 p.get_token(); // eat ldelim
807 context.check_layout(os);
810 begin_inset(os, "Argument ");
813 os << i << "\nstatus collapsed\n\n";
814 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
817 eat_whitespace(p, os, context, false);
822 void output_command_layout(ostream & os, Parser & p, bool outer,
823 Context & parent_context,
824 Layout const * newlayout)
826 TeXFont const oldFont = parent_context.font;
827 // save the current font size
828 string const size = oldFont.size;
829 // reset the font size to default, because the font size switches
830 // don't affect section headings and the like
831 parent_context.font.size = Context::normalfont.size;
832 // we only need to write the font change if we have an open layout
833 if (!parent_context.atParagraphStart())
834 output_font_change(os, oldFont, parent_context.font);
835 parent_context.check_end_layout(os);
836 Context context(true, parent_context.textclass, newlayout,
837 parent_context.layout, parent_context.font);
838 if (parent_context.deeper_paragraph) {
839 // We are beginning a nested environment after a
840 // deeper paragraph inside the outer list environment.
841 // Therefore we don't need to output a "begin deeper".
842 context.need_end_deeper = true;
844 context.check_deeper(os);
845 output_arguments(os, p, outer, true, string(), context,
846 context.layout->latexargs());
847 parse_text(p, os, FLAG_ITEM, outer, context);
848 output_arguments(os, p, outer, false, "post", context,
849 context.layout->postcommandargs());
850 context.check_end_layout(os);
851 if (parent_context.deeper_paragraph) {
852 // We must suppress the "end deeper" because we
853 // suppressed the "begin deeper" above.
854 context.need_end_deeper = false;
856 context.check_end_deeper(os);
857 // We don't need really a new paragraph, but
858 // we must make sure that the next item gets a \begin_layout.
859 parent_context.new_paragraph(os);
860 // Set the font size to the original value. No need to output it here
861 // (Context::begin_layout() will do that if needed)
862 parent_context.font.size = size;
867 * Output a space if necessary.
868 * This function gets called for every whitespace token.
870 * We have three cases here:
871 * 1. A space must be suppressed. Example: The lyxcode case below
872 * 2. A space may be suppressed. Example: Spaces before "\par"
873 * 3. A space must not be suppressed. Example: A space between two words
875 * We currently handle only 1. and 3 and from 2. only the case of
876 * spaces before newlines as a side effect.
878 * 2. could be used to suppress as many spaces as possible. This has two effects:
879 * - Reimporting LyX generated LaTeX files changes almost no whitespace
880 * - Superflous whitespace from non LyX generated LaTeX files is removed.
881 * The drawback is that the logic inside the function becomes
882 * complicated, and that is the reason why it is not implemented.
884 void check_space(Parser & p, ostream & os, Context & context)
886 Token const next = p.next_token();
887 Token const curr = p.curr_token();
888 // A space before a single newline and vice versa must be ignored
889 // LyX emits a newline before \end{lyxcode}.
890 // This newline must be ignored,
891 // otherwise LyX will add an additional protected space.
892 if (next.cat() == catSpace ||
893 next.cat() == catNewline ||
894 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
897 context.check_layout(os);
903 * Parse all arguments of \p command
905 void parse_arguments(string const & command,
906 vector<ArgumentType> const & template_arguments,
907 Parser & p, ostream & os, bool outer, Context & context)
909 string ert = command;
910 size_t no_arguments = template_arguments.size();
911 for (size_t i = 0; i < no_arguments; ++i) {
912 switch (template_arguments[i]) {
915 // This argument contains regular LaTeX
916 output_ert_inset(os, ert + '{', context);
917 eat_whitespace(p, os, context, false);
918 if (template_arguments[i] == required)
919 parse_text(p, os, FLAG_ITEM, outer, context);
921 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
925 // This argument consists only of a single item.
926 // The presence of '{' or not must be preserved.
928 if (p.next_token().cat() == catBegin)
929 ert += '{' + p.verbatim_item() + '}';
931 ert += p.verbatim_item();
935 // This argument may contain special characters
936 ert += '{' + p.verbatim_item() + '}';
940 // true because we must not eat whitespace
941 // if an optional arg follows we must not strip the
942 // brackets from this one
943 if (i < no_arguments - 1 &&
944 template_arguments[i+1] == optional)
945 ert += p.getFullOpt(true);
947 ert += p.getOpt(true);
951 output_ert_inset(os, ert, context);
956 * Check whether \p command is a known command. If yes,
957 * handle the command with all arguments.
958 * \return true if the command was parsed, false otherwise.
960 bool parse_command(string const & command, Parser & p, ostream & os,
961 bool outer, Context & context)
963 if (known_commands.find(command) != known_commands.end()) {
964 parse_arguments(command, known_commands[command], p, os,
972 /// Parses a minipage or parbox
973 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
974 unsigned inner_flags, bool outer, Context & parent_context,
975 string const & outer_type, string const & special,
976 string inner_type, string const & frame_color,
977 string const & background_color)
981 string hor_pos = "l";
982 // We need to set the height to the LaTeX default of 1\\totalheight
983 // for the case when no height argument is given
984 string height_value = "1";
985 string height_unit = "in";
986 string height_special = "totalheight";
991 string width_special = "none";
992 string thickness = "0.4pt";
993 if (!fboxrule.empty())
994 thickness = fboxrule;
998 if (!fboxsep.empty())
999 separation = fboxsep;
1003 if (!shadow_size.empty())
1004 shadowsize = shadow_size;
1007 string framecolor = "black";
1008 string backgroundcolor = "none";
1009 if (!frame_color.empty())
1010 framecolor = frame_color;
1011 if (!background_color.empty())
1012 backgroundcolor = background_color;
1013 // if there is a color box around the \begin statements have not yet been parsed
1015 if (!frame_color.empty() || !background_color.empty()) {
1016 eat_whitespace(p, os, parent_context, false);
1017 p.get_token().asInput(); // the '{'
1019 if (p.next_token().asInput() == "\\begin") {
1020 p.get_token().asInput();
1022 inner_type = "minipage";
1023 inner_flags = FLAG_END;
1024 active_environments.push_back("minipage");
1027 else if (p.next_token().asInput() == "\\parbox") {
1028 p.get_token().asInput();
1029 inner_type = "parbox";
1030 inner_flags = FLAG_ITEM;
1033 else if (p.next_token().asInput() == "\\makebox") {
1034 p.get_token().asInput();
1035 inner_type = "makebox";
1036 inner_flags = FLAG_ITEM;
1038 // in case there is just \colorbox{color}{text}
1041 inner_type = "makebox";
1042 inner_flags = FLAG_BRACE_LAST;
1047 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1049 if (!inner_type.empty() && p.hasOpt()) {
1050 if (inner_type != "makebox")
1051 position = p.getArg('[', ']');
1053 latex_width = p.getArg('[', ']');
1054 translate_box_len(latex_width, width_value, width_unit, width_special);
1057 if (position != "t" && position != "c" && position != "b") {
1058 cerr << "invalid position " << position << " for "
1059 << inner_type << endl;
1063 if (inner_type != "makebox") {
1064 latex_height = p.getArg('[', ']');
1065 translate_box_len(latex_height, height_value, height_unit, height_special);
1067 string const opt = p.getArg('[', ']');
1070 if (hor_pos != "l" && hor_pos != "c" &&
1071 hor_pos != "r" && hor_pos != "s") {
1072 cerr << "invalid hor_pos " << hor_pos
1073 << " for " << inner_type << endl;
1080 inner_pos = p.getArg('[', ']');
1081 if (inner_pos != "c" && inner_pos != "t" &&
1082 inner_pos != "b" && inner_pos != "s") {
1083 cerr << "invalid inner_pos "
1084 << inner_pos << " for "
1085 << inner_type << endl;
1086 inner_pos = position;
1090 if (inner_type == "makebox")
1094 if (inner_type.empty()) {
1095 if (special.empty() && outer_type != "framebox")
1096 latex_width = "1\\columnwidth";
1099 latex_width = p2.getArg('[', ']');
1100 string const opt = p2.getArg('[', ']');
1103 if (hor_pos != "l" && hor_pos != "c" &&
1104 hor_pos != "r" && hor_pos != "s") {
1105 cerr << "invalid hor_pos " << hor_pos
1106 << " for " << outer_type << endl;
1110 if (outer_type == "framebox")
1114 } else if (inner_type != "makebox")
1115 latex_width = p.verbatim_item();
1116 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1117 // as this is LyX's standard for such cases (except for makebox)
1118 // \framebox is more special and handled below
1119 if (latex_width.empty() && inner_type != "makebox"
1120 && outer_type != "framebox")
1121 latex_width = "1\\columnwidth";
1123 translate_len(latex_width, width_value, width_unit);
1125 bool shadedparbox = false;
1126 if (inner_type == "shaded") {
1127 eat_whitespace(p, os, parent_context, false);
1128 if (outer_type == "parbox") {
1130 if (p.next_token().cat() == catBegin)
1132 eat_whitespace(p, os, parent_context, false);
1133 shadedparbox = true;
1138 // If we already read the inner box we have to push the inner env
1139 if (!outer_type.empty() && !inner_type.empty() &&
1140 (inner_flags & FLAG_END))
1141 active_environments.push_back(inner_type);
1142 bool use_ert = false;
1143 if (!outer_type.empty() && !inner_type.empty()) {
1144 // Look whether there is some content after the end of the
1145 // inner box, but before the end of the outer box.
1146 // If yes, we need to output ERT.
1148 if (inner_flags & FLAG_END)
1149 p.ertEnvironment(inner_type);
1152 p.skip_spaces(true);
1153 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1154 if ((outer_env && p.next_token().asInput() != "\\end") ||
1155 (!outer_env && p.next_token().cat() != catEnd)) {
1156 // something is between the end of the inner box and
1157 // the end of the outer box, so we need to use ERT.
1165 if (!outer_type.empty()) {
1166 if (outer_flags & FLAG_END)
1167 ss << "\\begin{" << outer_type << '}';
1169 ss << '\\' << outer_type << '{';
1170 if (!special.empty())
1174 if (!inner_type.empty()) {
1175 if (inner_type != "shaded") {
1176 if (inner_flags & FLAG_END)
1177 ss << "\\begin{" << inner_type << '}';
1179 ss << '\\' << inner_type;
1181 if (!position.empty())
1182 ss << '[' << position << ']';
1183 if (!latex_height.empty())
1184 ss << '[' << latex_height << ']';
1185 if (!inner_pos.empty())
1186 ss << '[' << inner_pos << ']';
1187 ss << '{' << latex_width << '}';
1188 if (!(inner_flags & FLAG_END))
1191 if (inner_type == "shaded")
1192 ss << "\\begin{shaded}";
1193 output_ert_inset(os, ss.str(), parent_context);
1194 if (!inner_type.empty()) {
1195 parse_text(p, os, inner_flags, outer, parent_context);
1196 if (inner_flags & FLAG_END)
1197 output_ert_inset(os, "\\end{" + inner_type + '}',
1200 output_ert_inset(os, "}", parent_context);
1202 if (!outer_type.empty()) {
1203 // If we already read the inner box we have to pop
1205 if (!inner_type.empty() && (inner_flags & FLAG_END))
1206 active_environments.pop_back();
1208 // Ensure that the end of the outer box is parsed correctly:
1209 // The opening brace has been eaten by parse_outer_box()
1210 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1211 outer_flags &= ~FLAG_ITEM;
1212 outer_flags |= FLAG_BRACE_LAST;
1214 parse_text(p, os, outer_flags, outer, parent_context);
1215 if (outer_flags & FLAG_END)
1216 output_ert_inset(os, "\\end{" + outer_type + '}',
1219 output_ert_inset(os, "}", parent_context);
1222 // LyX does not like empty positions, so we have
1223 // to set them to the LaTeX default values here.
1224 if (position.empty())
1226 if (inner_pos.empty())
1227 inner_pos = position;
1228 parent_context.check_layout(os);
1229 begin_inset(os, "Box ");
1230 if (outer_type == "framed")
1232 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1234 else if (outer_type == "shadowbox")
1235 os << "Shadowbox\n";
1236 else if ((outer_type == "shaded" && inner_type.empty()) ||
1237 (outer_type == "minipage" && inner_type == "shaded") ||
1238 (outer_type == "parbox" && inner_type == "shaded")) {
1240 preamble.registerAutomaticallyLoadedPackage("color");
1241 } else if (outer_type == "doublebox")
1242 os << "Doublebox\n";
1243 else if (outer_type.empty() || outer_type == "mbox")
1244 os << "Frameless\n";
1246 os << outer_type << '\n';
1247 os << "position \"" << position << "\"\n";
1248 os << "hor_pos \"" << hor_pos << "\"\n";
1249 if (outer_type == "mbox")
1250 os << "has_inner_box 1\n";
1251 else if (!frame_color.empty() && inner_type == "makebox")
1252 os << "has_inner_box 0\n";
1254 os << "has_inner_box " << !inner_type.empty() << "\n";
1255 os << "inner_pos \"" << inner_pos << "\"\n";
1256 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1258 if (outer_type == "mbox")
1259 os << "use_makebox 1\n";
1260 else if (!frame_color.empty())
1261 os << "use_makebox 0\n";
1263 os << "use_makebox " << (inner_type == "makebox") << '\n';
1264 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1265 os << "width \"\"\n";
1266 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1267 else if (contains(width_unit, '\\'))
1268 os << "width \"" << width_value << "in" << "\"\n";
1270 os << "width \"" << width_value << width_unit << "\"\n";
1271 if (contains(width_unit, '\\')) {
1272 width_unit.erase (0,1); // remove the leading '\'
1273 os << "special \"" << width_unit << "\"\n";
1275 os << "special \"" << width_special << "\"\n";
1276 if (contains(height_unit, '\\'))
1277 os << "height \"" << height_value << "in" << "\"\n";
1279 os << "height \"" << height_value << height_unit << "\"\n";
1280 os << "height_special \"" << height_special << "\"\n";
1281 os << "thickness \"" << thickness << "\"\n";
1282 os << "separation \"" << separation << "\"\n";
1283 os << "shadowsize \"" << shadowsize << "\"\n";
1284 os << "framecolor \"" << framecolor << "\"\n";
1285 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1286 os << "status open\n\n";
1288 // Unfortunately we can't use parse_text_in_inset:
1289 // InsetBox::forcePlainLayout() is hard coded and does not
1290 // use the inset layout. Apart from that do we call parse_text
1291 // up to two times, but need only one check_end_layout.
1292 bool const forcePlainLayout =
1293 (!inner_type.empty() || inner_type == "makebox") &&
1294 outer_type != "shaded" && outer_type != "framed";
1295 Context context(true, parent_context.textclass);
1296 if (forcePlainLayout)
1297 context.layout = &context.textclass.plainLayout();
1299 context.font = parent_context.font;
1301 // If we have no inner box the contents will be read with the outer box
1302 if (!inner_type.empty())
1303 parse_text(p, os, inner_flags, outer, context);
1305 // Ensure that the end of the outer box is parsed correctly:
1306 // The opening brace has been eaten by parse_outer_box()
1307 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1308 outer_flags &= ~FLAG_ITEM;
1309 outer_flags |= FLAG_BRACE_LAST;
1312 // Find end of outer box, output contents if inner_type is
1313 // empty and output possible comments
1314 if (!outer_type.empty()) {
1315 // If we already read the inner box we have to pop
1317 if (!inner_type.empty() && (inner_flags & FLAG_END))
1318 active_environments.pop_back();
1319 // This does not output anything but comments if
1320 // inner_type is not empty (see use_ert)
1321 parse_text(p, os, outer_flags, outer, context);
1324 context.check_end_layout(os);
1326 #ifdef PRESERVE_LAYOUT
1327 // LyX puts a % after the end of the minipage
1328 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1330 //output_comment(p, os, "dummy", parent_context);
1333 parent_context.new_paragraph(os);
1335 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1336 //output_comment(p, os, "dummy", parent_context);
1339 // We add a protected space if something real follows
1340 if (p.good() && p.next_token().cat() != catComment) {
1341 begin_inset(os, "space ~\n");
1347 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1348 active_environments.pop_back();
1349 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1350 // in this case we have to eat the the closing brace of the color box
1351 p.get_token().asInput(); // the '}'
1353 if (p.next_token().asInput() == "}") {
1354 // in this case we assume that the closing brace is from the box settings
1355 // therefore reset these values for the next box
1361 // all boxes except of Frameless and Shaded require calc
1362 if (!(outer_type.empty() || outer_type == "mbox") &&
1363 !((outer_type == "shaded" && inner_type.empty()) ||
1364 (outer_type == "minipage" && inner_type == "shaded") ||
1365 (outer_type == "parbox" && inner_type == "shaded")))
1366 preamble.registerAutomaticallyLoadedPackage("calc");
1370 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1371 Context & parent_context, string const & outer_type,
1372 string const & special)
1374 eat_whitespace(p, os, parent_context, false);
1375 if (flags & FLAG_ITEM) {
1377 if (p.next_token().cat() == catBegin)
1380 cerr << "Warning: Ignoring missing '{' after \\"
1381 << outer_type << '.' << endl;
1382 eat_whitespace(p, os, parent_context, false);
1385 unsigned int inner_flags = 0;
1387 if (outer_type == "minipage" || outer_type == "parbox") {
1388 p.skip_spaces(true);
1389 while (p.hasOpt()) {
1391 p.skip_spaces(true);
1394 p.skip_spaces(true);
1395 if (outer_type == "parbox") {
1397 if (p.next_token().cat() == catBegin)
1399 p.skip_spaces(true);
1402 if (outer_type == "shaded" || outer_type == "mbox") {
1403 // These boxes never have an inner box
1405 } else if (p.next_token().asInput() == "\\parbox") {
1406 inner = p.get_token().cs();
1407 inner_flags = FLAG_ITEM;
1408 } else if (p.next_token().asInput() == "\\begin") {
1409 // Is this a minipage or shaded box?
1412 inner = p.getArg('{', '}');
1414 if (inner == "minipage" || inner == "shaded")
1415 inner_flags = FLAG_END;
1420 if (inner_flags == FLAG_END) {
1421 if (inner != "shaded")
1425 eat_whitespace(p, os, parent_context, false);
1427 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1428 outer_type, special, inner, "", "");
1430 if (inner_flags == FLAG_ITEM) {
1432 eat_whitespace(p, os, parent_context, false);
1434 parse_box(p, os, flags, inner_flags, outer, parent_context,
1435 outer_type, special, inner, "", "");
1440 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1441 bool in_line, bool use_minted)
1443 parent_context.check_layout(os);
1444 begin_inset(os, "listings\n");
1445 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1447 while ((i = arg.find(", ")) != string::npos
1448 || (i = arg.find(",\t")) != string::npos)
1449 arg.erase(i + 1, 1);
1452 string const language = p.getArg('{', '}');
1453 p.skip_spaces(true);
1454 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1455 if (!minted_float.empty()) {
1456 arg += string(arg.empty() ? "" : ",") + minted_float;
1457 minted_nonfloat_caption.clear();
1461 os << "lstparams " << '"' << arg << '"' << '\n';
1462 if (arg.find("\\color") != string::npos)
1463 preamble.registerAutomaticallyLoadedPackage("color");
1466 os << "inline true\n";
1468 os << "inline false\n";
1469 os << "status collapsed\n";
1470 Context context(true, parent_context.textclass);
1471 context.layout = &parent_context.textclass.plainLayout();
1472 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1473 minted_nonfloat_caption.erase(0,3);
1474 os << "\n\\begin_layout Plain Layout\n";
1475 begin_inset(os, "Caption Standard\n");
1476 Context newcontext(true, context.textclass,
1477 context.layout, 0, context.font);
1478 newcontext.check_layout(os);
1479 os << minted_nonfloat_caption << "\n";
1480 newcontext.check_end_layout(os);
1482 os << "\n\\end_layout\n";
1483 minted_nonfloat_caption.clear();
1487 // set catcodes to verbatim early, just in case.
1488 p.setCatcodes(VERBATIM_CATCODES);
1489 string delim = p.get_token().asInput();
1490 //FIXME: handler error condition
1491 s = p.verbatimStuff(delim).second;
1492 // context.new_paragraph(os);
1493 } else if (use_minted) {
1494 s = p.verbatimEnvironment("minted");
1496 s = p.verbatimEnvironment("lstlisting");
1498 output_ert(os, s, context);
1499 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1500 minted_nonfloat_caption.erase(0,3);
1501 os << "\n\\begin_layout Plain Layout\n";
1502 begin_inset(os, "Caption Standard\n");
1503 Context newcontext(true, context.textclass,
1504 context.layout, 0, context.font);
1505 newcontext.check_layout(os);
1506 os << minted_nonfloat_caption << "\n";
1507 newcontext.check_end_layout(os);
1509 os << "\n\\end_layout\n";
1510 minted_nonfloat_caption.clear();
1512 // Don't close the inset here for floating minted listings.
1513 // It will be closed at the end of the listing environment.
1514 if (!use_minted || minted_float.empty())
1517 eat_whitespace(p, os, parent_context, true);
1518 Token t = p.get_token();
1519 if (t.asInput() != "\\end") {
1520 // If anything follows, collect it into a caption.
1521 minted_float_has_caption = true;
1522 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1523 begin_inset(os, "Caption Standard\n");
1524 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1531 /// parse an unknown environment
1532 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1533 unsigned flags, bool outer,
1534 Context & parent_context)
1536 if (name == "tabbing")
1537 // We need to remember that we have to handle '\=' specially
1538 flags |= FLAG_TABBING;
1540 // We need to translate font changes and paragraphs inside the
1541 // environment to ERT if we have a non standard font.
1542 // Otherwise things like
1543 // \large\begin{foo}\huge bar\end{foo}
1545 bool const specialfont =
1546 (parent_context.font != parent_context.normalfont);
1547 bool const new_layout_allowed = parent_context.new_layout_allowed;
1549 parent_context.new_layout_allowed = false;
1550 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1551 parse_text_snippet(p, os, flags, outer, parent_context);
1552 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1554 parent_context.new_layout_allowed = new_layout_allowed;
1558 void parse_environment(Parser & p, ostream & os, bool outer,
1559 string & last_env, Context & parent_context)
1561 Layout const * newlayout;
1562 InsetLayout const * newinsetlayout = 0;
1563 string const name = p.getArg('{', '}');
1564 const bool is_starred = suffixIs(name, '*');
1565 string const unstarred_name = rtrim(name, "*");
1566 active_environments.push_back(name);
1568 if (is_math_env(name)) {
1569 parent_context.check_layout(os);
1570 begin_inset(os, "Formula ");
1571 os << "\\begin{" << name << "}";
1572 parse_math(p, os, FLAG_END, MATH_MODE);
1573 os << "\\end{" << name << "}";
1575 if (is_display_math_env(name)) {
1576 // Prevent the conversion of a line break to a space
1577 // (bug 7668). This does not change the output, but
1578 // looks ugly in LyX.
1579 eat_whitespace(p, os, parent_context, false);
1583 else if (is_known(name, preamble.polyglossia_languages)) {
1584 // We must begin a new paragraph if not already done
1585 if (! parent_context.atParagraphStart()) {
1586 parent_context.check_end_layout(os);
1587 parent_context.new_paragraph(os);
1589 // save the language in the context so that it is
1590 // handled by parse_text
1591 parent_context.font.language = preamble.polyglossia2lyx(name);
1592 parse_text(p, os, FLAG_END, outer, parent_context);
1593 // Just in case the environment is empty
1594 parent_context.extra_stuff.erase();
1595 // We must begin a new paragraph to reset the language
1596 parent_context.new_paragraph(os);
1600 else if (unstarred_name == "tabular" || name == "longtable") {
1601 eat_whitespace(p, os, parent_context, false);
1602 string width = "0pt";
1603 if (name == "tabular*") {
1604 width = lyx::translate_len(p.getArg('{', '}'));
1605 eat_whitespace(p, os, parent_context, false);
1607 parent_context.check_layout(os);
1608 begin_inset(os, "Tabular ");
1609 handle_tabular(p, os, name, width, parent_context);
1614 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1615 eat_whitespace(p, os, parent_context, false);
1616 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1617 eat_whitespace(p, os, parent_context, false);
1618 parent_context.check_layout(os);
1619 begin_inset(os, "Float " + unstarred_name + "\n");
1620 // store the float type for subfloats
1621 // subfloats only work with figures and tables
1622 if (unstarred_name == "figure")
1623 float_type = unstarred_name;
1624 else if (unstarred_name == "table")
1625 float_type = unstarred_name;
1629 os << "placement " << opt << '\n';
1630 if (contains(opt, "H"))
1631 preamble.registerAutomaticallyLoadedPackage("float");
1633 Floating const & fl = parent_context.textclass.floats()
1634 .getType(unstarred_name);
1635 if (!fl.floattype().empty() && fl.usesFloatPkg())
1636 preamble.registerAutomaticallyLoadedPackage("float");
1639 os << "wide " << convert<string>(is_starred)
1640 << "\nsideways false"
1641 << "\nstatus open\n\n";
1642 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1644 // We don't need really a new paragraph, but
1645 // we must make sure that the next item gets a \begin_layout.
1646 parent_context.new_paragraph(os);
1648 // the float is parsed thus delete the type
1652 else if (unstarred_name == "sidewaysfigure"
1653 || unstarred_name == "sidewaystable"
1654 || unstarred_name == "sidewaysalgorithm") {
1655 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1656 eat_whitespace(p, os, parent_context, false);
1657 parent_context.check_layout(os);
1658 if (unstarred_name == "sidewaysfigure")
1659 begin_inset(os, "Float figure\n");
1660 else if (unstarred_name == "sidewaystable")
1661 begin_inset(os, "Float table\n");
1662 else if (unstarred_name == "sidewaysalgorithm")
1663 begin_inset(os, "Float algorithm\n");
1665 os << "placement " << opt << '\n';
1666 if (contains(opt, "H"))
1667 preamble.registerAutomaticallyLoadedPackage("float");
1668 os << "wide " << convert<string>(is_starred)
1669 << "\nsideways true"
1670 << "\nstatus open\n\n";
1671 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1673 // We don't need really a new paragraph, but
1674 // we must make sure that the next item gets a \begin_layout.
1675 parent_context.new_paragraph(os);
1677 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1680 else if (name == "wrapfigure" || name == "wraptable") {
1681 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1682 eat_whitespace(p, os, parent_context, false);
1683 parent_context.check_layout(os);
1686 string overhang = "0col%";
1689 lines = p.getArg('[', ']');
1690 string const placement = p.getArg('{', '}');
1692 overhang = p.getArg('[', ']');
1693 string const width = p.getArg('{', '}');
1695 if (name == "wrapfigure")
1696 begin_inset(os, "Wrap figure\n");
1698 begin_inset(os, "Wrap table\n");
1699 os << "lines " << lines
1700 << "\nplacement " << placement
1701 << "\noverhang " << lyx::translate_len(overhang)
1702 << "\nwidth " << lyx::translate_len(width)
1703 << "\nstatus open\n\n";
1704 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1706 // We don't need really a new paragraph, but
1707 // we must make sure that the next item gets a \begin_layout.
1708 parent_context.new_paragraph(os);
1710 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1713 else if (name == "minipage") {
1714 eat_whitespace(p, os, parent_context, false);
1715 // Test whether this is an outer box of a shaded box
1717 // swallow arguments
1718 while (p.hasOpt()) {
1720 p.skip_spaces(true);
1723 p.skip_spaces(true);
1724 Token t = p.get_token();
1725 bool shaded = false;
1726 if (t.asInput() == "\\begin") {
1727 p.skip_spaces(true);
1728 if (p.getArg('{', '}') == "shaded")
1733 parse_outer_box(p, os, FLAG_END, outer,
1734 parent_context, name, "shaded");
1736 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1737 "", "", name, "", "");
1741 else if (name == "comment") {
1742 eat_whitespace(p, os, parent_context, false);
1743 parent_context.check_layout(os);
1744 begin_inset(os, "Note Comment\n");
1745 os << "status open\n";
1746 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1749 skip_braces(p); // eat {} that might by set by LyX behind comments
1750 preamble.registerAutomaticallyLoadedPackage("verbatim");
1753 else if (unstarred_name == "verbatim") {
1754 // FIXME: this should go in the generic code that
1755 // handles environments defined in layout file that
1756 // have "PassThru 1". However, the code over there is
1757 // already too complicated for my taste.
1758 string const ascii_name =
1759 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1760 parent_context.new_paragraph(os);
1761 Context context(true, parent_context.textclass,
1762 &parent_context.textclass[from_ascii(ascii_name)]);
1763 string s = p.verbatimEnvironment(name);
1764 output_ert(os, s, context);
1768 else if (name == "IPA") {
1769 eat_whitespace(p, os, parent_context, false);
1770 parent_context.check_layout(os);
1771 begin_inset(os, "IPA\n");
1772 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1775 preamble.registerAutomaticallyLoadedPackage("tipa");
1776 preamble.registerAutomaticallyLoadedPackage("tipx");
1779 else if (name == "CJK") {
1780 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1781 // It is impossible to decide if a CJK environment was in its own paragraph or within
1782 // a line. We therefore always assume a paragraph since the latter is a rare case.
1783 eat_whitespace(p, os, parent_context, false);
1784 parent_context.check_end_layout(os);
1785 // store the encoding to be able to reset it
1786 string const encoding_old = p.getEncoding();
1787 string const encoding = p.getArg('{', '}');
1788 // FIXME: For some reason JIS does not work. Although the text
1789 // in tests/CJK.tex is identical with the SJIS version if you
1790 // convert both snippets using the recode command line utility,
1791 // the resulting .lyx file contains some extra characters if
1792 // you set buggy_encoding to false for JIS.
1793 bool const buggy_encoding = encoding == "JIS";
1794 if (!buggy_encoding)
1795 p.setEncoding(encoding, Encoding::CJK);
1797 // FIXME: This will read garbage, since the data is not encoded in utf8.
1798 p.setEncoding("UTF-8");
1800 // LyX only supports the same mapping for all CJK
1801 // environments, so we might need to output everything as ERT
1802 string const mapping = trim(p.getArg('{', '}'));
1803 char const * const * const where =
1804 is_known(encoding, supported_CJK_encodings);
1805 if (!buggy_encoding && !preamble.fontCJKSet())
1806 preamble.fontCJK(mapping);
1807 bool knownMapping = mapping == preamble.fontCJK();
1808 if (buggy_encoding || !knownMapping || !where) {
1809 parent_context.check_layout(os);
1810 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1812 // we must parse the content as verbatim because e.g. JIS can contain
1813 // normally invalid characters
1814 // FIXME: This works only for the most simple cases.
1815 // Since TeX control characters are not parsed,
1816 // things like comments are completely wrong.
1817 string const s = p.plainEnvironment("CJK");
1818 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1821 if (snip == "\\" || is_known(snip, known_escaped_chars))
1822 output_ert_inset(os, snip, parent_context);
1823 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1828 output_ert_inset(os, "\\end{" + name + "}",
1832 supported_CJK_languages[where - supported_CJK_encodings];
1833 // store the language because we must reset it at the end
1834 string const lang_old = parent_context.font.language;
1835 parent_context.font.language = lang;
1836 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1837 parent_context.font.language = lang_old;
1838 parent_context.new_paragraph(os);
1840 p.setEncoding(encoding_old);
1844 else if (name == "lyxgreyedout") {
1845 eat_whitespace(p, os, parent_context, false);
1846 parent_context.check_layout(os);
1847 begin_inset(os, "Note Greyedout\n");
1848 os << "status open\n";
1849 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1852 if (!preamble.notefontcolor().empty())
1853 preamble.registerAutomaticallyLoadedPackage("color");
1856 else if (name == "btSect") {
1857 eat_whitespace(p, os, parent_context, false);
1858 parent_context.check_layout(os);
1859 begin_command_inset(os, "bibtex", "bibtex");
1860 string bibstyle = "plain";
1862 bibstyle = p.getArg('[', ']');
1863 p.skip_spaces(true);
1865 string const bibfile = p.getArg('{', '}');
1866 eat_whitespace(p, os, parent_context, false);
1867 Token t = p.get_token();
1868 if (t.asInput() == "\\btPrintCited") {
1869 p.skip_spaces(true);
1870 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1872 if (t.asInput() == "\\btPrintNotCited") {
1873 p.skip_spaces(true);
1874 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1876 if (t.asInput() == "\\btPrintAll") {
1877 p.skip_spaces(true);
1878 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1880 os << "bibfiles " << '"' << bibfile << "\"\n"
1881 << "options " << '"' << bibstyle << "\"\n";
1882 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1887 else if (name == "framed" || name == "shaded") {
1888 eat_whitespace(p, os, parent_context, false);
1889 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1891 preamble.registerAutomaticallyLoadedPackage("framed");
1894 else if (name == "listing") {
1895 minted_float = "float";
1896 eat_whitespace(p, os, parent_context, false);
1897 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1899 minted_float += "=" + opt;
1900 // If something precedes \begin{minted}, we output it at the end
1901 // as a caption, in order to keep it inside the listings inset.
1902 eat_whitespace(p, os, parent_context, true);
1904 Token const & t = p.get_token();
1905 p.skip_spaces(true);
1906 string const envname = p.next_token().cat() == catBegin
1907 ? p.getArg('{', '}') : string();
1908 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1910 minted_float_has_caption = false;
1911 string content = parse_text_snippet(p, FLAG_END, outer,
1913 size_t i = content.find("\\begin_inset listings");
1914 bool minted_env = i != string::npos;
1917 caption = content.substr(0, i);
1918 content.erase(0, i);
1920 parent_context.check_layout(os);
1921 if (minted_env && minted_float_has_caption) {
1922 eat_whitespace(p, os, parent_context, true);
1923 os << content << "\n";
1924 if (!caption.empty())
1925 os << caption << "\n";
1926 os << "\n\\end_layout\n"; // close inner layout
1927 end_inset(os); // close caption inset
1928 os << "\n\\end_layout\n"; // close outer layout
1929 } else if (!caption.empty()) {
1931 begin_inset(os, "listings\n");
1932 os << "lstparams " << '"' << minted_float << '"' << '\n';
1933 os << "inline false\n";
1934 os << "status collapsed\n";
1936 os << "\n\\begin_layout Plain Layout\n";
1937 begin_inset(os, "Caption Standard\n");
1938 Context newcontext(true, parent_context.textclass,
1939 0, 0, parent_context.font);
1940 newcontext.check_layout(os);
1941 os << caption << "\n";
1942 newcontext.check_end_layout(os);
1944 os << "\n\\end_layout\n";
1945 } else if (content.empty()) {
1946 begin_inset(os, "listings\n");
1947 os << "lstparams " << '"' << minted_float << '"' << '\n';
1948 os << "inline false\n";
1949 os << "status collapsed\n";
1951 os << content << "\n";
1953 end_inset(os); // close listings inset
1954 parent_context.check_end_layout(os);
1955 parent_context.new_paragraph(os);
1957 minted_float.clear();
1958 minted_float_has_caption = false;
1961 else if (name == "lstlisting" || name == "minted") {
1962 bool use_minted = name == "minted";
1963 eat_whitespace(p, os, parent_context, false);
1964 if (use_minted && minted_float.empty()) {
1965 // look ahead for a bottom caption
1967 bool found_end_minted = false;
1968 while (!found_end_minted && p.good()) {
1969 Token const & t = p.get_token();
1971 string const envname =
1972 p.next_token().cat() == catBegin
1973 ? p.getArg('{', '}') : string();
1974 found_end_minted = t.asInput() == "\\end"
1975 && envname == "minted";
1977 eat_whitespace(p, os, parent_context, true);
1978 Token const & t = p.get_token();
1979 p.skip_spaces(true);
1980 if (t.asInput() == "\\lyxmintcaption") {
1981 string const pos = p.getArg('[', ']');
1983 string const caption =
1984 parse_text_snippet(p, FLAG_ITEM,
1985 false, parent_context);
1986 minted_nonfloat_caption = "[b]" + caption;
1991 parse_listings(p, os, parent_context, false, use_minted);
1995 else if (!parent_context.new_layout_allowed)
1996 parse_unknown_environment(p, name, os, FLAG_END, outer,
1999 // Alignment and spacing settings
2000 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2001 // therefore are totally broken!
2002 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2003 // they are commands not environments. They are furthermore switches that
2004 // can be ended by another switches, but also by commands like \footnote or
2005 // \parbox. So the only safe way is to leave them untouched.
2006 // However, we support the pseudo-environments
2007 // \begin{centering} ... \end{centering}
2008 // \begin{raggedright} ... \end{raggedright}
2009 // \begin{raggedleft} ... \end{raggedleft}
2010 // since they are used by LyX in floats (for spacing reasons)
2011 else if (name == "center" || name == "centering" ||
2012 name == "flushleft" || name == "raggedright" ||
2013 name == "flushright" || name == "raggedleft" ||
2014 name == "singlespace" || name == "onehalfspace" ||
2015 name == "doublespace" || name == "spacing") {
2016 eat_whitespace(p, os, parent_context, false);
2017 // We must begin a new paragraph if not already done
2018 if (! parent_context.atParagraphStart()) {
2019 parent_context.check_end_layout(os);
2020 parent_context.new_paragraph(os);
2022 if (name == "flushleft" || name == "raggedright")
2023 parent_context.add_extra_stuff("\\align left\n");
2024 else if (name == "flushright" || name == "raggedleft")
2025 parent_context.add_extra_stuff("\\align right\n");
2026 else if (name == "center" || name == "centering")
2027 parent_context.add_extra_stuff("\\align center\n");
2028 else if (name == "singlespace")
2029 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2030 else if (name == "onehalfspace") {
2031 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2032 preamble.registerAutomaticallyLoadedPackage("setspace");
2033 } else if (name == "doublespace") {
2034 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2035 preamble.registerAutomaticallyLoadedPackage("setspace");
2036 } else if (name == "spacing") {
2037 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2038 preamble.registerAutomaticallyLoadedPackage("setspace");
2040 parse_text(p, os, FLAG_END, outer, parent_context);
2041 // Just in case the environment is empty
2042 parent_context.extra_stuff.erase();
2043 // We must begin a new paragraph to reset the alignment
2044 parent_context.new_paragraph(os);
2048 // The single '=' is meant here.
2049 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2050 eat_whitespace(p, os, parent_context, false);
2051 Context context(true, parent_context.textclass, newlayout,
2052 parent_context.layout, parent_context.font);
2053 if (parent_context.deeper_paragraph) {
2054 // We are beginning a nested environment after a
2055 // deeper paragraph inside the outer list environment.
2056 // Therefore we don't need to output a "begin deeper".
2057 context.need_end_deeper = true;
2059 parent_context.check_end_layout(os);
2060 if (last_env == name) {
2061 // we need to output a separator since LyX would export
2062 // the two environments as one otherwise (bug 5716)
2063 TeX2LyXDocClass const & textclass(parent_context.textclass);
2064 Context newcontext(true, textclass,
2065 &(textclass.defaultLayout()));
2066 newcontext.check_layout(os);
2067 begin_inset(os, "Separator plain\n");
2069 newcontext.check_end_layout(os);
2071 switch (context.layout->latextype) {
2072 case LATEX_LIST_ENVIRONMENT:
2073 context.add_par_extra_stuff("\\labelwidthstring "
2074 + p.verbatim_item() + '\n');
2077 case LATEX_BIB_ENVIRONMENT:
2078 p.verbatim_item(); // swallow next arg
2084 context.check_deeper(os);
2085 // handle known optional and required arguments
2086 if (context.layout->latextype == LATEX_ENVIRONMENT)
2087 output_arguments(os, p, outer, false, string(), context,
2088 context.layout->latexargs());
2089 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2091 output_arguments(oss, p, outer, false, string(), context,
2092 context.layout->latexargs());
2093 context.list_extra_stuff = oss.str();
2095 parse_text(p, os, FLAG_END, outer, context);
2096 if (context.layout->latextype == LATEX_ENVIRONMENT)
2097 output_arguments(os, p, outer, false, "post", context,
2098 context.layout->postcommandargs());
2099 context.check_end_layout(os);
2100 if (parent_context.deeper_paragraph) {
2101 // We must suppress the "end deeper" because we
2102 // suppressed the "begin deeper" above.
2103 context.need_end_deeper = false;
2105 context.check_end_deeper(os);
2106 parent_context.new_paragraph(os);
2108 if (!preamble.titleLayoutFound())
2109 preamble.titleLayoutFound(newlayout->intitle);
2110 set<string> const & req = newlayout->requires();
2111 set<string>::const_iterator it = req.begin();
2112 set<string>::const_iterator en = req.end();
2113 for (; it != en; ++it)
2114 preamble.registerAutomaticallyLoadedPackage(*it);
2117 // The single '=' is meant here.
2118 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2119 eat_whitespace(p, os, parent_context, false);
2120 parent_context.check_layout(os);
2121 begin_inset(os, "Flex ");
2122 os << to_utf8(newinsetlayout->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 string bibliographystyle = "default";
2618 bool const use_natbib = isProvided("natbib");
2619 bool const use_jurabib = isProvided("jurabib");
2620 bool const use_biblatex = isProvided("biblatex")
2621 && preamble.citeEngine() != "biblatex-natbib";
2622 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2623 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2624 need_commentbib = use_biblatex || use_biblatex_natbib;
2627 // it is impossible to determine the correct encoding for non-CJK Japanese.
2628 // Therefore write a note at the beginning of the document
2629 if (is_nonCJKJapanese) {
2630 context.check_layout(os);
2631 begin_inset(os, "Note Note\n");
2632 os << "status open\n\\begin_layout Plain Layout\n"
2633 << "\\series bold\n"
2634 << "Important information:\n"
2635 << "\\end_layout\n\n"
2636 << "\\begin_layout Plain Layout\n"
2637 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2638 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2639 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2640 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2641 << " and specify the encoding using the -e command-line switch.\n"
2642 << " In addition, you might want to double check that the desired output encoding\n"
2643 << " is correctly selected in Document > Settings > Language.\n"
2644 << "\\end_layout\n";
2646 is_nonCJKJapanese = false;
2649 bool have_cycled = false;
2651 // Leave here only after at least one cycle
2652 if (have_cycled && flags & FLAG_LEAVE) {
2653 flags &= ~FLAG_LEAVE;
2657 Token const & t = p.get_token();
2659 debugToken(cerr, t, flags);
2662 if (flags & FLAG_ITEM) {
2663 if (t.cat() == catSpace)
2666 flags &= ~FLAG_ITEM;
2667 if (t.cat() == catBegin) {
2668 // skip the brace and collect everything to the next matching
2670 flags |= FLAG_BRACE_LAST;
2674 // handle only this single token, leave the loop if done
2675 flags |= FLAG_LEAVE;
2678 if (t.cat() != catEscape && t.character() == ']' &&
2679 (flags & FLAG_BRACK_LAST))
2681 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2683 string tok = t.asInput();
2684 // we only support delimiters with max 2 chars for now.
2685 if (rdelim.size() > 1)
2686 tok += p.next_token().asInput();
2687 if (t.cat() != catEscape && !rdelim.empty()
2688 && tok == rdelim && (flags & FLAG_RDELIM)) {
2689 if (rdelim.size() > 1)
2690 p.get_token(); // eat rdelim
2694 // If there is anything between \end{env} and \begin{env} we
2695 // don't need to output a separator.
2696 if (t.cat() != catSpace && t.cat() != catNewline &&
2697 t.asInput() != "\\begin")
2704 bool const starred = p.next_token().asInput() == "*";
2705 string const starredname(starred ? (t.cs() + '*') : t.cs());
2706 if (t.cat() == catMath) {
2707 // we are inside some text mode thingy, so opening new math is allowed
2708 context.check_layout(os);
2709 begin_inset(os, "Formula ");
2710 Token const & n = p.get_token();
2711 bool const display(n.cat() == catMath && outer);
2713 // TeX's $$...$$ syntax for displayed math
2715 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2717 p.get_token(); // skip the second '$' token
2719 // simple $...$ stuff
2722 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2727 // Prevent the conversion of a line break to a
2728 // space (bug 7668). This does not change the
2729 // output, but looks ugly in LyX.
2730 eat_whitespace(p, os, context, false);
2735 if (t.cat() == catSuper || t.cat() == catSub) {
2736 cerr << "catcode " << t << " illegal in text mode\n";
2740 // Basic support for quotes. We try to disambiguate
2741 // quotes from the context (e.g., a left english quote is
2742 // the same as a right german quote...).
2743 // Try to make a smart guess about the side
2744 Token const prev = p.prev_token();
2745 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2746 && prev.character() != '\n' && prev.character() != '~');
2747 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2748 context.check_layout(os);
2749 begin_inset(os, "Quotes ");
2750 os << guessQuoteStyle("eld", opening);
2756 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2757 context.check_layout(os);
2758 begin_inset(os, "Quotes ");
2759 os << guessQuoteStyle("erd", opening);
2766 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2767 context.check_layout(os);
2768 begin_inset(os, "Quotes ");
2769 os << guessQuoteStyle("ald", opening);
2776 if (t.asInput() == "<"
2777 && p.next_token().asInput() == "<") {
2778 bool has_chunk = false;
2782 has_chunk = parse_chunk(p, os, context);
2788 context.check_layout(os);
2789 begin_inset(os, "Quotes ");
2790 os << guessQuoteStyle("ard", opening);
2798 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2799 check_space(p, os, context);
2803 // babel shorthands (also used by polyglossia)
2804 // Since these can have different meanings for different languages
2805 // we import them as ERT (but they must be put in ERT to get output
2807 if (t.asInput() == "\"") {
2809 // These are known pairs. We put them together in
2810 // one ERT inset. In other cases (such as "a), only
2811 // the quotation mark is ERTed.
2812 if (p.next_token().asInput() == "\""
2813 || p.next_token().asInput() == "|"
2814 || 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 s += p.next_token().asInput();
2826 output_ert_inset(os, s, context);
2830 if (t.character() == '[' && noweb_mode &&
2831 p.next_token().character() == '[') {
2832 // These can contain underscores
2834 string const s = p.getFullOpt() + ']';
2835 if (p.next_token().character() == ']')
2838 cerr << "Warning: Inserting missing ']' in '"
2839 << s << "'." << endl;
2840 output_ert_inset(os, s, context);
2844 if (t.cat() == catLetter) {
2845 context.check_layout(os);
2850 if (t.cat() == catOther ||
2851 t.cat() == catAlign ||
2852 t.cat() == catParameter) {
2853 context.check_layout(os);
2854 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2855 context.merging_hyphens_allowed &&
2856 context.font.family != "ttfamily" &&
2857 !context.layout->pass_thru) {
2858 if (p.next_next_token().asInput() == "-") {
2860 os << to_utf8(docstring(1, 0x2014));
2864 os << to_utf8(docstring(1, 0x2013));
2867 // This translates "&" to "\\&" which may be wrong...
2872 if (p.isParagraph()) {
2873 // In minted floating listings we will collect
2874 // everything into the caption, where multiple
2875 // paragraphs are forbidden.
2876 if (minted_float.empty()) {
2877 if (context.new_layout_allowed)
2878 context.new_paragraph(os);
2880 output_ert_inset(os, "\\par ", context);
2883 eat_whitespace(p, os, context, true);
2887 if (t.cat() == catActive) {
2888 context.check_layout(os);
2889 if (t.character() == '~') {
2890 if (context.layout->free_spacing)
2893 begin_inset(os, "space ~\n");
2901 if (t.cat() == catBegin) {
2902 Token const next = p.next_token();
2903 Token const end = p.next_next_token();
2904 if (next.cat() == catEnd) {
2906 Token const prev = p.prev_token();
2908 if (p.next_token().character() == '`')
2909 ; // ignore it in {}``
2911 output_ert_inset(os, "{}", context);
2912 } else if (next.cat() == catEscape &&
2913 is_known(next.cs(), known_quotes) &&
2914 end.cat() == catEnd) {
2915 // Something like {\textquoteright} (e.g.
2916 // from writer2latex). We may skip the
2917 // braces here for better readability.
2918 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2920 } else if (p.next_token().asInput() == "\\ascii") {
2921 // handle the \ascii characters
2922 // (the case without braces is handled later)
2923 // the code is "{\ascii\xxx}"
2924 p.get_token(); // eat \ascii
2925 string name2 = p.get_token().asInput();
2926 p.get_token(); // eat the final '}'
2927 string const name = "{\\ascii" + name2 + "}";
2931 // get the character from unicodesymbols
2932 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2933 Encodings::TEXT_CMD, termination, rem, &req);
2935 context.check_layout(os);
2938 output_ert_inset(os,
2939 to_utf8(rem), context);
2940 for (set<string>::const_iterator it = req.begin();
2941 it != req.end(); ++it)
2942 preamble.registerAutomaticallyLoadedPackage(*it);
2944 // we did not find a non-ert version
2945 output_ert_inset(os, name, context);
2947 context.check_layout(os);
2948 // special handling of font attribute changes
2949 Token const prev = p.prev_token();
2950 TeXFont const oldFont = context.font;
2951 if (next.character() == '[' ||
2952 next.character() == ']' ||
2953 next.character() == '*') {
2955 if (p.next_token().cat() == catEnd) {
2960 output_ert_inset(os, "{", context);
2961 parse_text_snippet(p, os,
2964 output_ert_inset(os, "}", context);
2966 } else if (! context.new_layout_allowed) {
2967 output_ert_inset(os, "{", context);
2968 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2970 output_ert_inset(os, "}", context);
2971 } else if (is_known(next.cs(), known_sizes)) {
2972 // next will change the size, so we must
2974 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2976 if (!context.atParagraphStart())
2978 << context.font.size << "\n";
2979 } else if (is_known(next.cs(), known_font_families)) {
2980 // next will change the font family, so we
2981 // must reset it here
2982 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2984 if (!context.atParagraphStart())
2986 << context.font.family << "\n";
2987 } else if (is_known(next.cs(), known_font_series)) {
2988 // next will change the font series, so we
2989 // must reset it here
2990 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2992 if (!context.atParagraphStart())
2994 << context.font.series << "\n";
2995 } else if (is_known(next.cs(), known_font_shapes)) {
2996 // next will change the font shape, so we
2997 // must reset it here
2998 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3000 if (!context.atParagraphStart())
3002 << context.font.shape << "\n";
3003 } else if (is_known(next.cs(), known_old_font_families) ||
3004 is_known(next.cs(), known_old_font_series) ||
3005 is_known(next.cs(), known_old_font_shapes)) {
3006 // next will change the font family, series
3007 // and shape, so we must reset it here
3008 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3010 if (!context.atParagraphStart())
3012 << context.font.family
3014 << context.font.series
3016 << context.font.shape << "\n";
3018 output_ert_inset(os, "{", context);
3019 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3021 output_ert_inset(os, "}", context);
3027 if (t.cat() == catEnd) {
3028 if (flags & FLAG_BRACE_LAST) {
3031 cerr << "stray '}' in text\n";
3032 output_ert_inset(os, "}", context);
3036 if (t.cat() == catComment) {
3037 parse_comment(p, os, t, context);
3042 // control sequences
3045 if (t.cs() == "(" || t.cs() == "[") {
3046 bool const simple = t.cs() == "(";
3047 context.check_layout(os);
3048 begin_inset(os, "Formula");
3049 os << " \\" << t.cs();
3050 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3051 os << '\\' << (simple ? ')' : ']');
3054 // Prevent the conversion of a line break to a
3055 // space (bug 7668). This does not change the
3056 // output, but looks ugly in LyX.
3057 eat_whitespace(p, os, context, false);
3062 if (t.cs() == "begin") {
3063 parse_environment(p, os, outer, last_env,
3068 if (t.cs() == "end") {
3069 if (flags & FLAG_END) {
3070 // eat environment name
3071 string const name = p.getArg('{', '}');
3072 if (name != active_environment())
3073 cerr << "\\end{" + name + "} does not match \\begin{"
3074 + active_environment() + "}\n";
3077 p.error("found 'end' unexpectedly");
3081 // "item" by default, but could be something else
3082 if (t.cs() == context.layout->itemcommand()) {
3084 if (context.layout->labeltype == LABEL_MANUAL) {
3085 // FIXME: This swallows comments, but we cannot use
3086 // eat_whitespace() since we must not output
3087 // anything before the item.
3088 p.skip_spaces(true);
3089 s = p.verbatimOption();
3091 p.skip_spaces(false);
3093 context.check_layout(os);
3094 if (context.has_item) {
3095 // An item in an unknown list-like environment
3096 // FIXME: Do this in check_layout()!
3097 context.has_item = false;
3098 string item = "\\" + context.layout->itemcommand();
3101 output_ert_inset(os, item, context);
3103 if (context.layout->labeltype != LABEL_MANUAL)
3104 output_arguments(os, p, outer, false, "item", context,
3105 context.layout->itemargs());
3106 if (!context.list_extra_stuff.empty()) {
3107 os << context.list_extra_stuff;
3108 context.list_extra_stuff.clear();
3110 else if (!s.empty()) {
3111 // LyX adds braces around the argument,
3112 // so we need to remove them here.
3113 if (s.size() > 2 && s[0] == '{' &&
3114 s[s.size()-1] == '}')
3115 s = s.substr(1, s.size()-2);
3116 // If the argument contains a space we
3117 // must put it into ERT: Otherwise LyX
3118 // would misinterpret the space as
3119 // item delimiter (bug 7663)
3120 if (contains(s, ' ')) {
3121 output_ert_inset(os, s, context);
3124 os << parse_text_snippet(p2,
3125 FLAG_BRACK_LAST, outer, context);
3127 // The space is needed to separate the
3128 // item from the rest of the sentence.
3130 eat_whitespace(p, os, context, false);
3135 if (t.cs() == "bibitem") {
3137 context.check_layout(os);
3138 eat_whitespace(p, os, context, false);
3139 string label = p.verbatimOption();
3140 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3141 bool const literal = !lbl.first;
3142 label = literal ? subst(label, "\n", " ") : lbl.second;
3143 string lit = literal ? "\"true\"" : "\"false\"";
3144 string key = convert_literate_command_inset_arg(p.verbatim_item());
3145 begin_command_inset(os, "bibitem", "bibitem");
3146 os << "label \"" << label << "\"\n"
3147 << "key \"" << key << "\"\n"
3148 << "literal " << lit << "\n";
3154 // catch the case of \def\inputGnumericTable
3156 if (t.cs() == "def") {
3157 Token second = p.next_token();
3158 if (second.cs() == "inputGnumericTable") {
3162 Token third = p.get_token();
3164 if (third.cs() == "input") {
3168 string name = normalize_filename(p.verbatim_item());
3169 string const path = getMasterFilePath(true);
3170 // We want to preserve relative / absolute filenames,
3171 // therefore path is only used for testing
3172 // The file extension is in every case ".tex".
3173 // So we need to remove this extension and check for
3174 // the original one.
3175 name = removeExtension(name);
3176 if (!makeAbsPath(name, path).exists()) {
3177 char const * const Gnumeric_formats[] = {"gnumeric",
3179 string const Gnumeric_name =
3180 find_file(name, path, Gnumeric_formats);
3181 if (!Gnumeric_name.empty())
3182 name = Gnumeric_name;
3184 FileName const absname = makeAbsPath(name, path);
3185 if (absname.exists()) {
3186 fix_child_filename(name);
3187 copy_file(absname, name);
3189 cerr << "Warning: Could not find file '"
3190 << name << "'." << endl;
3191 context.check_layout(os);
3192 begin_inset(os, "External\n\ttemplate ");
3193 os << "GnumericSpreadsheet\n\tfilename "
3196 context.check_layout(os);
3198 // register the packages that are automatically loaded
3199 // by the Gnumeric template
3200 registerExternalTemplatePackages("GnumericSpreadsheet");
3205 parse_macro(p, os, context);
3209 if (t.cs() == "noindent") {
3211 context.add_par_extra_stuff("\\noindent\n");
3215 if (t.cs() == "appendix") {
3216 context.add_par_extra_stuff("\\start_of_appendix\n");
3217 // We need to start a new paragraph. Otherwise the
3218 // appendix in 'bla\appendix\chapter{' would start
3220 context.new_paragraph(os);
3221 // We need to make sure that the paragraph is
3222 // generated even if it is empty. Otherwise the
3223 // appendix in '\par\appendix\par\chapter{' would
3225 context.check_layout(os);
3226 // FIXME: This is a hack to prevent paragraph
3227 // deletion if it is empty. Handle this better!
3228 output_comment(p, os,
3229 "dummy comment inserted by tex2lyx to "
3230 "ensure that this paragraph is not empty",
3232 // Both measures above may generate an additional
3233 // empty paragraph, but that does not hurt, because
3234 // whitespace does not matter here.
3235 eat_whitespace(p, os, context, true);
3239 // Must catch empty dates before findLayout is called below
3240 if (t.cs() == "date") {
3241 eat_whitespace(p, os, context, false);
3243 string const date = p.verbatim_item();
3246 preamble.suppressDate(true);
3249 preamble.suppressDate(false);
3250 if (context.new_layout_allowed &&
3251 (newlayout = findLayout(context.textclass,
3254 output_command_layout(os, p, outer,
3255 context, newlayout);
3256 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3257 if (!preamble.titleLayoutFound())
3258 preamble.titleLayoutFound(newlayout->intitle);
3259 set<string> const & req = newlayout->requires();
3260 set<string>::const_iterator it = req.begin();
3261 set<string>::const_iterator en = req.end();
3262 for (; it != en; ++it)
3263 preamble.registerAutomaticallyLoadedPackage(*it);
3265 output_ert_inset(os,
3266 "\\date{" + p.verbatim_item() + '}',
3272 // Starred section headings
3273 // Must attempt to parse "Section*" before "Section".
3274 if ((p.next_token().asInput() == "*") &&
3275 context.new_layout_allowed &&
3276 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3279 output_command_layout(os, p, outer, context, newlayout);
3281 if (!preamble.titleLayoutFound())
3282 preamble.titleLayoutFound(newlayout->intitle);
3283 set<string> const & req = newlayout->requires();
3284 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3285 preamble.registerAutomaticallyLoadedPackage(*it);
3289 // Section headings and the like
3290 if (context.new_layout_allowed &&
3291 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3293 output_command_layout(os, p, outer, context, newlayout);
3295 if (!preamble.titleLayoutFound())
3296 preamble.titleLayoutFound(newlayout->intitle);
3297 set<string> const & req = newlayout->requires();
3298 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3299 preamble.registerAutomaticallyLoadedPackage(*it);
3303 if (t.cs() == "subfloat") {
3304 // the syntax is \subfloat[list entry][sub caption]{content}
3305 // if it is a table of figure depends on the surrounding float
3307 // do nothing if there is no outer float
3308 if (!float_type.empty()) {
3309 context.check_layout(os);
3311 begin_inset(os, "Float " + float_type + "\n");
3313 << "\nsideways false"
3314 << "\nstatus collapsed\n\n";
3317 bool has_caption = false;
3318 if (p.next_token().cat() != catEscape &&
3319 p.next_token().character() == '[') {
3320 p.get_token(); // eat '['
3321 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3324 // In case we have two optional args, the second is the caption.
3325 if (p.next_token().cat() != catEscape &&
3326 p.next_token().character() == '[') {
3327 p.get_token(); // eat '['
3328 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3331 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3332 // the caption comes always as the last
3334 // we must make sure that the caption gets a \begin_layout
3335 os << "\n\\begin_layout Plain Layout";
3337 begin_inset(os, "Caption Standard\n");
3338 Context newcontext(true, context.textclass,
3339 0, 0, context.font);
3340 newcontext.check_layout(os);
3341 os << caption << "\n";
3342 newcontext.check_end_layout(os);
3345 // close the layout we opened
3346 os << "\n\\end_layout";
3351 // if the float type is not supported or there is no surrounding float
3356 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3358 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3360 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3361 + "{" + p.verbatim_item() + '}', context);
3366 if (t.cs() == "includegraphics") {
3367 bool const clip = p.next_token().asInput() == "*";
3370 string const arg = p.getArg('[', ']');
3371 map<string, string> opts;
3372 vector<string> keys;
3373 split_map(arg, opts, keys);
3375 opts["clip"] = string();
3376 string name = normalize_filename(p.verbatim_item());
3378 string const path = getMasterFilePath(true);
3379 // We want to preserve relative / absolute filenames,
3380 // therefore path is only used for testing
3381 if (!makeAbsPath(name, path).exists()) {
3382 // The file extension is probably missing.
3383 // Now try to find it out.
3384 string const dvips_name =
3385 find_file(name, path,
3386 known_dvips_graphics_formats);
3387 string const pdftex_name =
3388 find_file(name, path,
3389 known_pdftex_graphics_formats);
3390 if (!dvips_name.empty()) {
3391 if (!pdftex_name.empty()) {
3392 cerr << "This file contains the "
3394 "\"\\includegraphics{"
3396 "However, files\n\""
3397 << dvips_name << "\" and\n\""
3398 << pdftex_name << "\"\n"
3399 "both exist, so I had to make a "
3400 "choice and took the first one.\n"
3401 "Please move the unwanted one "
3402 "someplace else and try again\n"
3403 "if my choice was wrong."
3407 } else if (!pdftex_name.empty()) {
3413 FileName const absname = makeAbsPath(name, path);
3414 if (absname.exists()) {
3415 fix_child_filename(name);
3416 copy_file(absname, name);
3418 cerr << "Warning: Could not find graphics file '"
3419 << name << "'." << endl;
3421 context.check_layout(os);
3422 begin_inset(os, "Graphics ");
3423 os << "\n\tfilename " << name << '\n';
3424 if (opts.find("width") != opts.end())
3426 << translate_len(opts["width"]) << '\n';
3427 if (opts.find("height") != opts.end())
3429 << translate_len(opts["height"]) << '\n';
3430 if (opts.find("scale") != opts.end()) {
3431 istringstream iss(opts["scale"]);
3435 os << "\tscale " << val << '\n';
3437 if (opts.find("angle") != opts.end()) {
3438 os << "\trotateAngle "
3439 << opts["angle"] << '\n';
3440 vector<string>::const_iterator a =
3441 find(keys.begin(), keys.end(), "angle");
3442 vector<string>::const_iterator s =
3443 find(keys.begin(), keys.end(), "width");
3444 if (s == keys.end())
3445 s = find(keys.begin(), keys.end(), "height");
3446 if (s == keys.end())
3447 s = find(keys.begin(), keys.end(), "scale");
3448 if (s != keys.end() && distance(s, a) > 0)
3449 os << "\tscaleBeforeRotation\n";
3451 if (opts.find("origin") != opts.end()) {
3453 string const opt = opts["origin"];
3454 if (opt.find('l') != string::npos) ss << "left";
3455 if (opt.find('r') != string::npos) ss << "right";
3456 if (opt.find('c') != string::npos) ss << "center";
3457 if (opt.find('t') != string::npos) ss << "Top";
3458 if (opt.find('b') != string::npos) ss << "Bottom";
3459 if (opt.find('B') != string::npos) ss << "Baseline";
3460 if (!ss.str().empty())
3461 os << "\trotateOrigin " << ss.str() << '\n';
3463 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3465 if (opts.find("keepaspectratio") != opts.end())
3466 os << "\tkeepAspectRatio\n";
3467 if (opts.find("clip") != opts.end())
3469 if (opts.find("draft") != opts.end())
3471 if (opts.find("bb") != opts.end())
3472 os << "\tBoundingBox "
3473 << opts["bb"] << '\n';
3474 int numberOfbbOptions = 0;
3475 if (opts.find("bbllx") != opts.end())
3476 numberOfbbOptions++;
3477 if (opts.find("bblly") != opts.end())
3478 numberOfbbOptions++;
3479 if (opts.find("bburx") != opts.end())
3480 numberOfbbOptions++;
3481 if (opts.find("bbury") != opts.end())
3482 numberOfbbOptions++;
3483 if (numberOfbbOptions == 4)
3484 os << "\tBoundingBox "
3485 << opts["bbllx"] << " " << opts["bblly"] << " "
3486 << opts["bburx"] << " " << opts["bbury"] << '\n';
3487 else if (numberOfbbOptions > 0)
3488 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3489 numberOfbbOptions = 0;
3490 if (opts.find("natwidth") != opts.end())
3491 numberOfbbOptions++;
3492 if (opts.find("natheight") != opts.end())
3493 numberOfbbOptions++;
3494 if (numberOfbbOptions == 2)
3495 os << "\tBoundingBox 0bp 0bp "
3496 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3497 else if (numberOfbbOptions > 0)
3498 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3499 ostringstream special;
3500 if (opts.find("hiresbb") != opts.end())
3501 special << "hiresbb,";
3502 if (opts.find("trim") != opts.end())
3504 if (opts.find("viewport") != opts.end())
3505 special << "viewport=" << opts["viewport"] << ',';
3506 if (opts.find("totalheight") != opts.end())
3507 special << "totalheight=" << opts["totalheight"] << ',';
3508 if (opts.find("type") != opts.end())
3509 special << "type=" << opts["type"] << ',';
3510 if (opts.find("ext") != opts.end())
3511 special << "ext=" << opts["ext"] << ',';
3512 if (opts.find("read") != opts.end())
3513 special << "read=" << opts["read"] << ',';
3514 if (opts.find("command") != opts.end())
3515 special << "command=" << opts["command"] << ',';
3516 string s_special = special.str();
3517 if (!s_special.empty()) {
3518 // We had special arguments. Remove the trailing ','.
3519 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3521 // TODO: Handle the unknown settings better.
3522 // Warn about invalid options.
3523 // Check whether some option was given twice.
3525 preamble.registerAutomaticallyLoadedPackage("graphicx");
3529 if (t.cs() == "footnote" ||
3530 (t.cs() == "thanks" && context.layout->intitle)) {
3532 context.check_layout(os);
3533 begin_inset(os, "Foot\n");
3534 os << "status collapsed\n\n";
3535 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3540 if (t.cs() == "marginpar") {
3542 context.check_layout(os);
3543 begin_inset(os, "Marginal\n");
3544 os << "status collapsed\n\n";
3545 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3550 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3551 bool const use_minted = t.cs() == "mintinline";
3553 parse_listings(p, os, context, true, use_minted);
3557 if (t.cs() == "ensuremath") {
3559 context.check_layout(os);
3560 string const s = p.verbatim_item();
3561 //FIXME: this never triggers in UTF8
3562 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3565 output_ert_inset(os, "\\ensuremath{" + s + "}",
3570 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3571 if (preamble.titleLayoutFound()) {
3573 skip_spaces_braces(p);
3575 output_ert_inset(os, t.asInput(), context);
3579 if (t.cs() == "tableofcontents"
3580 || t.cs() == "lstlistoflistings"
3581 || t.cs() == "listoflistings") {
3582 string name = t.cs();
3583 if (preamble.minted() && name == "listoflistings")
3584 name.insert(0, "lst");
3585 context.check_layout(os);
3586 begin_command_inset(os, "toc", name);
3588 skip_spaces_braces(p);
3589 if (name == "lstlistoflistings") {
3590 if (preamble.minted())
3591 preamble.registerAutomaticallyLoadedPackage("minted");
3593 preamble.registerAutomaticallyLoadedPackage("listings");
3598 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3599 context.check_layout(os);
3600 if (t.cs() == "listoffigures")
3601 begin_inset(os, "FloatList figure\n");
3603 begin_inset(os, "FloatList table\n");
3605 skip_spaces_braces(p);
3609 if (t.cs() == "listof") {
3610 p.skip_spaces(true);
3611 string const name = p.get_token().cs();
3612 if (context.textclass.floats().typeExist(name)) {
3613 context.check_layout(os);
3614 begin_inset(os, "FloatList ");
3617 p.get_token(); // swallow second arg
3619 output_ert_inset(os, "\\listof{" + name + "}", context);
3623 if ((where = is_known(t.cs(), known_text_font_families))) {
3624 parse_text_attributes(p, os, FLAG_ITEM, outer,
3625 context, "\\family", context.font.family,
3626 known_coded_font_families[where - known_text_font_families]);
3630 // beamer has a \textbf<overlay>{} inset
3631 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3632 parse_text_attributes(p, os, FLAG_ITEM, outer,
3633 context, "\\series", context.font.series,
3634 known_coded_font_series[where - known_text_font_series]);
3638 // beamer has a \textit<overlay>{} inset
3639 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3640 parse_text_attributes(p, os, FLAG_ITEM, outer,
3641 context, "\\shape", context.font.shape,
3642 known_coded_font_shapes[where - known_text_font_shapes]);
3646 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3647 context.check_layout(os);
3648 TeXFont oldFont = context.font;
3649 context.font.init();
3650 context.font.size = oldFont.size;
3651 os << "\n\\family " << context.font.family << "\n";
3652 os << "\n\\series " << context.font.series << "\n";
3653 os << "\n\\shape " << context.font.shape << "\n";
3654 if (t.cs() == "textnormal") {
3655 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3656 output_font_change(os, context.font, oldFont);
3657 context.font = oldFont;
3659 eat_whitespace(p, os, context, false);
3663 if (t.cs() == "textcolor") {
3664 // scheme is \textcolor{color name}{text}
3665 string const color = p.verbatim_item();
3666 // we support the predefined colors of the color and the xcolor package
3667 if (color == "black" || color == "blue" || color == "cyan"
3668 || color == "green" || color == "magenta" || color == "red"
3669 || color == "white" || color == "yellow") {
3670 context.check_layout(os);
3671 os << "\n\\color " << color << "\n";
3672 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3673 context.check_layout(os);
3674 os << "\n\\color inherit\n";
3675 preamble.registerAutomaticallyLoadedPackage("color");
3676 } else if (color == "brown" || color == "darkgray" || color == "gray"
3677 || color == "lightgray" || color == "lime" || color == "olive"
3678 || color == "orange" || color == "pink" || color == "purple"
3679 || color == "teal" || color == "violet") {
3680 context.check_layout(os);
3681 os << "\n\\color " << color << "\n";
3682 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3683 context.check_layout(os);
3684 os << "\n\\color inherit\n";
3685 preamble.registerAutomaticallyLoadedPackage("xcolor");
3687 // for custom defined colors
3688 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3692 if (t.cs() == "underbar" || t.cs() == "uline") {
3693 // \underbar is not 100% correct (LyX outputs \uline
3694 // of ulem.sty). The difference is that \ulem allows
3695 // line breaks, and \underbar does not.
3696 // Do NOT handle \underline.
3697 // \underbar cuts through y, g, q, p etc.,
3698 // \underline does not.
3699 context.check_layout(os);
3700 os << "\n\\bar under\n";
3701 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3702 context.check_layout(os);
3703 os << "\n\\bar default\n";
3704 preamble.registerAutomaticallyLoadedPackage("ulem");
3708 if (t.cs() == "sout") {
3709 context.check_layout(os);
3710 os << "\n\\strikeout on\n";
3711 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3712 context.check_layout(os);
3713 os << "\n\\strikeout default\n";
3714 preamble.registerAutomaticallyLoadedPackage("ulem");
3718 // beamer has an \emph<overlay>{} inset
3719 if ((t.cs() == "uuline" || t.cs() == "uwave"
3720 || t.cs() == "emph" || t.cs() == "noun"
3721 || t.cs() == "xout") && !p.hasOpt("<")) {
3722 context.check_layout(os);
3723 os << "\n\\" << t.cs() << " on\n";
3724 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3725 context.check_layout(os);
3726 os << "\n\\" << t.cs() << " default\n";
3727 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3728 preamble.registerAutomaticallyLoadedPackage("ulem");
3732 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3733 context.check_layout(os);
3734 string name = p.getArg('{', '}');
3735 string localtime = p.getArg('{', '}');
3736 preamble.registerAuthor(name);
3737 Author const & author = preamble.getAuthor(name);
3738 // from_asctime_utc() will fail if LyX decides to output the
3739 // time in the text language.
3740 time_t ptime = from_asctime_utc(localtime);
3741 if (ptime == static_cast<time_t>(-1)) {
3742 cerr << "Warning: Could not parse time `" << localtime
3743 << "´ for change tracking, using current time instead.\n";
3744 ptime = current_time();
3746 if (t.cs() == "lyxadded")
3747 os << "\n\\change_inserted ";
3749 os << "\n\\change_deleted ";
3750 os << author.bufferId() << ' ' << ptime << '\n';
3751 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3752 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3753 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3754 LaTeXPackages::isAvailable("xcolor");
3755 // No need to test for luatex, since luatex comes in
3756 // two flavours (dvi and pdf), like latex, and those
3757 // are detected by pdflatex.
3758 if (pdflatex || xetex) {
3760 preamble.registerAutomaticallyLoadedPackage("ulem");
3761 preamble.registerAutomaticallyLoadedPackage("xcolor");
3762 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3766 preamble.registerAutomaticallyLoadedPackage("dvipost");
3767 } else if (xcolorulem) {
3768 preamble.registerAutomaticallyLoadedPackage("ulem");
3769 preamble.registerAutomaticallyLoadedPackage("xcolor");
3775 if (t.cs() == "textipa") {
3776 context.check_layout(os);
3777 begin_inset(os, "IPA\n");
3778 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3779 context.merging_hyphens_allowed = false;
3780 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3781 context.merging_hyphens_allowed = merging_hyphens_allowed;
3783 preamble.registerAutomaticallyLoadedPackage("tipa");
3784 preamble.registerAutomaticallyLoadedPackage("tipx");
3788 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3789 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3790 context.check_layout(os);
3794 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3795 begin_inset(os, "IPADeco " + type + "\n");
3796 os << "status open\n";
3797 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3803 if (t.cs() == "textvertline") {
3804 // FIXME: This is not correct, \textvertline is higher than |
3810 if (t.cs() == "tone" ) {
3811 context.check_layout(os);
3812 // register the tone package
3813 preamble.registerAutomaticallyLoadedPackage("tone");
3814 string content = trimSpaceAndEol(p.verbatim_item());
3815 string command = t.asInput() + "{" + content + "}";
3816 // some tones can be detected by unicodesymbols, some need special code
3817 if (is_known(content, known_tones)) {
3818 os << "\\IPAChar " << command << "\n";
3821 // try to see whether the string is in unicodesymbols
3825 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3826 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3827 termination, rem, &req);
3831 output_ert_inset(os, to_utf8(rem), context);
3832 for (set<string>::const_iterator it = req.begin();
3833 it != req.end(); ++it)
3834 preamble.registerAutomaticallyLoadedPackage(*it);
3836 // we did not find a non-ert version
3837 output_ert_inset(os, command, context);
3841 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3842 t.cs() == "vphantom") {
3843 context.check_layout(os);
3844 if (t.cs() == "phantom")
3845 begin_inset(os, "Phantom Phantom\n");
3846 if (t.cs() == "hphantom")
3847 begin_inset(os, "Phantom HPhantom\n");
3848 if (t.cs() == "vphantom")
3849 begin_inset(os, "Phantom VPhantom\n");
3850 os << "status open\n";
3851 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3857 if (t.cs() == "href") {
3858 context.check_layout(os);
3859 string target = convert_literate_command_inset_arg(p.verbatim_item());
3860 string name = p.verbatim_item();
3861 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3862 bool const literal = !nm.first;
3863 name = literal ? subst(name, "\n", " ") : nm.second;
3864 string lit = literal ? "\"true\"" : "\"false\"";
3866 size_t i = target.find(':');
3867 if (i != string::npos) {
3868 type = target.substr(0, i + 1);
3869 if (type == "mailto:" || type == "file:")
3870 target = target.substr(i + 1);
3871 // handle the case that name is equal to target, except of "http(s)://"
3872 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3875 begin_command_inset(os, "href", "href");
3877 os << "name \"" << name << "\"\n";
3878 os << "target \"" << target << "\"\n";
3879 if (type == "mailto:" || type == "file:")
3880 os << "type \"" << type << "\"\n";
3881 os << "literal " << lit << "\n";
3883 skip_spaces_braces(p);
3887 if (t.cs() == "lyxline") {
3888 // swallow size argument (it is not used anyway)
3890 if (!context.atParagraphStart()) {
3891 // so our line is in the middle of a paragraph
3892 // we need to add a new line, lest this line
3893 // follow the other content on that line and
3894 // run off the side of the page
3895 // FIXME: This may create an empty paragraph,
3896 // but without that it would not be
3897 // possible to set noindent below.
3898 // Fortunately LaTeX does not care
3899 // about the empty paragraph.
3900 context.new_paragraph(os);
3902 if (preamble.indentParagraphs()) {
3903 // we need to unindent, lest the line be too long
3904 context.add_par_extra_stuff("\\noindent\n");
3906 context.check_layout(os);
3907 begin_command_inset(os, "line", "rule");
3908 os << "offset \"0.5ex\"\n"
3909 "width \"100line%\"\n"
3915 if (t.cs() == "rule") {
3916 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3917 string const width = p.getArg('{', '}');
3918 string const thickness = p.getArg('{', '}');
3919 context.check_layout(os);
3920 begin_command_inset(os, "line", "rule");
3921 if (!offset.empty())
3922 os << "offset \"" << translate_len(offset) << "\"\n";
3923 os << "width \"" << translate_len(width) << "\"\n"
3924 "height \"" << translate_len(thickness) << "\"\n";
3929 // handle refstyle first to catch \eqref which can also occur
3930 // without refstyle. Only recognize these commands if
3931 // refstyle.sty was found in the preamble (otherwise \eqref
3932 // and user defined ref commands could be misdetected).
3933 if ((where = is_known(t.cs(), known_refstyle_commands))
3934 && preamble.refstyle()) {
3935 context.check_layout(os);
3936 begin_command_inset(os, "ref", "formatted");
3937 os << "reference \"";
3938 os << known_refstyle_prefixes[where - known_refstyle_commands]
3940 os << convert_literate_command_inset_arg(p.verbatim_item())
3942 os << "plural \"false\"\n";
3943 os << "caps \"false\"\n";
3944 os << "noprefix \"false\"\n";
3946 preamble.registerAutomaticallyLoadedPackage("refstyle");
3950 // if refstyle is used, we must not convert \prettyref to a
3951 // formatted reference, since that would result in a refstyle command.
3952 if ((where = is_known(t.cs(), known_ref_commands)) &&
3953 (t.cs() != "prettyref" || !preamble.refstyle())) {
3954 string const opt = p.getOpt();
3956 context.check_layout(os);
3957 begin_command_inset(os, "ref",
3958 known_coded_ref_commands[where - known_ref_commands]);
3959 os << "reference \""
3960 << convert_literate_command_inset_arg(p.verbatim_item())
3962 os << "plural \"false\"\n";
3963 os << "caps \"false\"\n";
3964 os << "noprefix \"false\"\n";
3966 if (t.cs() == "vref" || t.cs() == "vpageref")
3967 preamble.registerAutomaticallyLoadedPackage("varioref");
3968 else if (t.cs() == "prettyref")
3969 preamble.registerAutomaticallyLoadedPackage("prettyref");
3971 // LyX does not yet support optional arguments of ref commands
3972 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3973 p.verbatim_item() + '}', context);
3979 is_known(t.cs(), known_natbib_commands) &&
3980 ((t.cs() != "citefullauthor" &&
3981 t.cs() != "citeyear" &&
3982 t.cs() != "citeyearpar") ||
3983 p.next_token().asInput() != "*")) {
3984 context.check_layout(os);
3985 string command = t.cs();
3986 if (p.next_token().asInput() == "*") {
3990 if (command == "citefullauthor")
3991 // alternative name for "\\citeauthor*"
3992 command = "citeauthor*";
3994 // text before the citation
3996 // text after the citation
3998 get_cite_arguments(p, true, before, after);
4000 if (command == "cite") {
4001 // \cite without optional argument means
4002 // \citet, \cite with at least one optional
4003 // argument means \citep.
4004 if (before.empty() && after.empty())
4009 if (before.empty() && after == "[]")
4010 // avoid \citet[]{a}
4012 else if (before == "[]" && after == "[]") {
4013 // avoid \citet[][]{a}
4017 bool literal = false;
4018 pair<bool, string> aft;
4019 pair<bool, string> bef;
4020 // remove the brackets around after and before
4021 if (!after.empty()) {
4023 after.erase(after.length() - 1, 1);
4024 aft = convert_latexed_command_inset_arg(after);
4025 literal = !aft.first;
4026 after = literal ? subst(after, "\n", " ") : aft.second;
4028 if (!before.empty()) {
4030 before.erase(before.length() - 1, 1);
4031 bef = convert_latexed_command_inset_arg(before);
4032 literal |= !bef.first;
4033 before = literal ? subst(before, "\n", " ") : bef.second;
4034 if (literal && !after.empty())
4035 after = subst(after, "\n", " ");
4037 string lit = literal ? "\"true\"" : "\"false\"";
4038 begin_command_inset(os, "citation", command);
4039 os << "after " << '"' << after << '"' << "\n";
4040 os << "before " << '"' << before << '"' << "\n";
4042 << convert_literate_command_inset_arg(p.verbatim_item())
4044 << "literal " << lit << "\n";
4046 // Need to set the cite engine if natbib is loaded by
4047 // the document class directly
4048 if (preamble.citeEngine() == "basic")
4049 preamble.citeEngine("natbib");
4054 && is_known(t.cs(), known_biblatex_commands)
4055 && ((t.cs() == "cite"
4056 || t.cs() == "citeauthor"
4057 || t.cs() == "Citeauthor"
4058 || t.cs() == "parencite"
4059 || t.cs() == "citetitle")
4060 || p.next_token().asInput() != "*"))
4061 || (use_biblatex_natbib
4062 && (is_known(t.cs(), known_biblatex_commands)
4063 || is_known(t.cs(), known_natbib_commands))
4064 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4065 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4066 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4067 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4068 || t.cs() == "parencite" || t.cs() == "citetitle")
4069 || p.next_token().asInput() != "*"))){
4070 context.check_layout(os);
4071 string command = t.cs();
4072 if (p.next_token().asInput() == "*") {
4077 bool const qualified = suffixIs(command, "s");
4079 command = rtrim(command, "s");
4081 // text before the citation
4083 // text after the citation
4085 get_cite_arguments(p, true, before, after, qualified);
4087 // These use natbib cmd names in LyX
4088 // for inter-citeengine compativility
4089 if (command == "citeyear")
4090 command = "citebyear";
4091 else if (command == "cite*")
4092 command = "citeyear";
4093 else if (command == "textcite")
4095 else if (command == "Textcite")
4097 else if (command == "parencite")
4099 else if (command == "Parencite")
4101 else if (command == "parencite*")
4102 command = "citeyearpar";
4103 else if (command == "smartcite")
4104 command = "footcite";
4105 else if (command == "Smartcite")
4106 command = "Footcite";
4108 string const emptyarg = qualified ? "()" : "[]";
4109 if (before.empty() && after == emptyarg)
4112 else if (before == emptyarg && after == emptyarg) {
4113 // avoid \cite[][]{a}
4117 bool literal = false;
4118 pair<bool, string> aft;
4119 pair<bool, string> bef;
4120 // remove the brackets around after and before
4121 if (!after.empty()) {
4123 after.erase(after.length() - 1, 1);
4124 aft = convert_latexed_command_inset_arg(after);
4125 literal = !aft.first;
4126 after = literal ? subst(after, "\n", " ") : aft.second;
4128 if (!before.empty()) {
4130 before.erase(before.length() - 1, 1);
4131 bef = convert_latexed_command_inset_arg(before);
4132 literal |= !bef.first;
4133 before = literal ? subst(before, "\n", " ") : bef.second;
4135 string keys, pretextlist, posttextlist;
4137 map<string, string> pres, posts, preslit, postslit;
4138 vector<string> lkeys;
4139 // text before the citation
4140 string lbefore, lbeforelit;
4141 // text after the citation
4142 string lafter, lafterlit;
4144 pair<bool, string> laft, lbef;
4146 get_cite_arguments(p, true, lbefore, lafter);
4147 // remove the brackets around after and before
4148 if (!lafter.empty()) {
4150 lafter.erase(lafter.length() - 1, 1);
4151 laft = convert_latexed_command_inset_arg(lafter);
4152 literal |= !laft.first;
4153 lafter = laft.second;
4154 lafterlit = subst(lbefore, "\n", " ");
4156 if (!lbefore.empty()) {
4157 lbefore.erase(0, 1);
4158 lbefore.erase(lbefore.length() - 1, 1);
4159 lbef = convert_latexed_command_inset_arg(lbefore);
4160 literal |= !lbef.first;
4161 lbefore = lbef.second;
4162 lbeforelit = subst(lbefore, "\n", " ");
4164 if (lbefore.empty() && lafter == "[]") {
4169 else if (lbefore == "[]" && lafter == "[]") {
4170 // avoid \cite[][]{a}
4176 lkey = p.getArg('{', '}');
4179 if (!lbefore.empty()) {
4180 pres.insert(make_pair(lkey, lbefore));
4181 preslit.insert(make_pair(lkey, lbeforelit));
4183 if (!lafter.empty()) {
4184 posts.insert(make_pair(lkey, lafter));
4185 postslit.insert(make_pair(lkey, lafterlit));
4187 lkeys.push_back(lkey);
4189 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4194 for (auto const & ptl : pres) {
4195 if (!pretextlist.empty())
4196 pretextlist += '\t';
4197 pretextlist += ptl.first + " " + ptl.second;
4199 for (auto const & potl : posts) {
4200 if (!posttextlist.empty())
4201 posttextlist += '\t';
4202 posttextlist += potl.first + " " + potl.second;
4205 keys = convert_literate_command_inset_arg(p.verbatim_item());
4208 after = subst(after, "\n", " ");
4209 if (!before.empty())
4210 before = subst(after, "\n", " ");
4212 string lit = literal ? "\"true\"" : "\"false\"";
4213 begin_command_inset(os, "citation", command);
4214 os << "after " << '"' << after << '"' << "\n";
4215 os << "before " << '"' << before << '"' << "\n";
4219 if (!pretextlist.empty())
4220 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4221 if (!posttextlist.empty())
4222 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4223 os << "literal " << lit << "\n";
4225 // Need to set the cite engine if biblatex is loaded by
4226 // the document class directly
4227 if (preamble.citeEngine() == "basic")
4228 use_biblatex_natbib ?
4229 preamble.citeEngine("biblatex-natbib")
4230 : preamble.citeEngine("biblatex");
4235 is_known(t.cs(), known_jurabib_commands) &&
4236 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4237 context.check_layout(os);
4238 string command = t.cs();
4239 if (p.next_token().asInput() == "*") {
4243 char argumentOrder = '\0';
4244 vector<string> const options =
4245 preamble.getPackageOptions("jurabib");
4246 if (find(options.begin(), options.end(),
4247 "natbiborder") != options.end())
4248 argumentOrder = 'n';
4249 else if (find(options.begin(), options.end(),
4250 "jurabiborder") != options.end())
4251 argumentOrder = 'j';
4253 // text before the citation
4255 // text after the citation
4257 get_cite_arguments(p, argumentOrder != 'j', before, after);
4259 string const citation = p.verbatim_item();
4260 if (!before.empty() && argumentOrder == '\0') {
4261 cerr << "Warning: Assuming argument order "
4262 "of jurabib version 0.6 for\n'"
4263 << command << before << after << '{'
4264 << citation << "}'.\n"
4265 "Add 'jurabiborder' to the jurabib "
4266 "package options if you used an\n"
4267 "earlier jurabib version." << endl;
4269 bool literal = false;
4270 pair<bool, string> aft;
4271 pair<bool, string> bef;
4272 // remove the brackets around after and before
4273 if (!after.empty()) {
4275 after.erase(after.length() - 1, 1);
4276 aft = convert_latexed_command_inset_arg(after);
4277 literal = !aft.first;
4278 after = literal ? subst(after, "\n", " ") : aft.second;
4280 if (!before.empty()) {
4282 before.erase(before.length() - 1, 1);
4283 bef = convert_latexed_command_inset_arg(before);
4284 literal |= !bef.first;
4285 before = literal ? subst(before, "\n", " ") : bef.second;
4286 if (literal && !after.empty())
4287 after = subst(after, "\n", " ");
4289 string lit = literal ? "\"true\"" : "\"false\"";
4290 begin_command_inset(os, "citation", command);
4291 os << "after " << '"' << after << "\"\n"
4292 << "before " << '"' << before << "\"\n"
4293 << "key " << '"' << citation << "\"\n"
4294 << "literal " << lit << "\n";
4296 // Need to set the cite engine if jurabib is loaded by
4297 // the document class directly
4298 if (preamble.citeEngine() == "basic")
4299 preamble.citeEngine("jurabib");
4303 if (t.cs() == "cite"
4304 || t.cs() == "nocite") {
4305 context.check_layout(os);
4306 string after = p.getArg('[', ']');
4307 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4308 bool const literal = !aft.first;
4309 after = literal ? subst(after, "\n", " ") : aft.second;
4310 string lit = literal ? "\"true\"" : "\"false\"";
4311 string key = convert_literate_command_inset_arg(p.verbatim_item());
4312 // store the case that it is "\nocite{*}" to use it later for
4315 begin_command_inset(os, "citation", t.cs());
4316 os << "after " << '"' << after << "\"\n"
4317 << "key " << '"' << key << "\"\n"
4318 << "literal " << lit << "\n";
4320 } else if (t.cs() == "nocite")
4325 if (t.cs() == "index" ||
4326 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4327 context.check_layout(os);
4328 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4329 p.getArg('[', ']') : "";
4330 string const kind = arg.empty() ? "idx" : arg;
4331 begin_inset(os, "Index ");
4332 os << kind << "\nstatus collapsed\n";
4333 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4336 preamble.registerAutomaticallyLoadedPackage("splitidx");
4340 if (t.cs() == "nomenclature") {
4341 context.check_layout(os);
4342 begin_command_inset(os, "nomenclature", "nomenclature");
4343 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4344 if (!prefix.empty())
4345 os << "prefix " << '"' << prefix << '"' << "\n";
4346 string symbol = p.verbatim_item();
4347 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4348 bool literal = !sym.first;
4349 string description = p.verbatim_item();
4350 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4351 literal |= !desc.first;
4353 symbol = subst(symbol, "\n", " ");
4354 description = subst(description, "\n", " ");
4356 symbol = sym.second;
4357 description = desc.second;
4359 string lit = literal ? "\"true\"" : "\"false\"";
4360 os << "symbol " << '"' << symbol;
4361 os << "\"\ndescription \""
4362 << description << "\"\n"
4363 << "literal " << lit << "\n";
4365 preamble.registerAutomaticallyLoadedPackage("nomencl");
4369 if (t.cs() == "label") {
4370 context.check_layout(os);
4371 begin_command_inset(os, "label", "label");
4373 << convert_literate_command_inset_arg(p.verbatim_item())
4379 if (t.cs() == "lyxmintcaption") {
4380 string const pos = p.getArg('[', ']');
4382 string const caption =
4383 parse_text_snippet(p, FLAG_ITEM, false,
4385 minted_nonfloat_caption = "[t]" + caption;
4387 // We already got the caption at the bottom,
4388 // so simply skip it.
4389 parse_text_snippet(p, FLAG_ITEM, false, context);
4394 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4395 context.check_layout(os);
4396 string commandname = t.cs();
4398 if (p.next_token().asInput() == "*") {
4403 begin_command_inset(os, "index_print", commandname);
4404 string const indexname = p.getArg('[', ']');
4406 if (indexname.empty())
4407 os << "type \"idx\"\n";
4409 os << "type \"" << indexname << "\"\n";
4410 os << "literal \"true\"\n";
4413 skip_spaces_braces(p);
4414 preamble.registerAutomaticallyLoadedPackage("makeidx");
4415 if (preamble.use_indices() == "true")
4416 preamble.registerAutomaticallyLoadedPackage("splitidx");
4420 if (t.cs() == "printnomenclature") {
4422 string width_type = "";
4423 context.check_layout(os);
4424 begin_command_inset(os, "nomencl_print", "printnomenclature");
4425 // case of a custom width
4427 width = p.getArg('[', ']');
4428 width = translate_len(width);
4429 width_type = "custom";
4431 // case of no custom width
4432 // the case of no custom width but the width set
4433 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4434 // because the user could have set anything, not only the width
4435 // of the longest label (which would be width_type = "auto")
4436 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4437 if (label.empty() && width_type.empty())
4438 width_type = "none";
4439 os << "set_width \"" << width_type << "\"\n";
4440 if (width_type == "custom")
4441 os << "width \"" << width << '\"';
4443 skip_spaces_braces(p);
4444 preamble.registerAutomaticallyLoadedPackage("nomencl");
4448 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4449 context.check_layout(os);
4450 begin_inset(os, "script ");
4451 os << t.cs().substr(4) << '\n';
4452 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4453 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4455 if (t.cs() == "textsubscript")
4456 preamble.registerAutomaticallyLoadedPackage("subscript");
4460 if ((where = is_known(t.cs(), known_quotes))) {
4461 context.check_layout(os);
4462 begin_inset(os, "Quotes ");
4463 string quotetype = known_coded_quotes[where - known_quotes];
4464 // try to make a smart guess about the side
4465 Token const prev = p.prev_token();
4466 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4467 && prev.character() != '\n' && prev.character() != '~');
4468 quotetype = guessQuoteStyle(quotetype, opening);
4471 // LyX adds {} after the quote, so we have to eat
4472 // spaces here if there are any before a possible
4474 eat_whitespace(p, os, context, false);
4479 if ((where = is_known(t.cs(), known_sizes)) &&
4480 context.new_layout_allowed) {
4481 context.check_layout(os);
4482 TeXFont const oldFont = context.font;
4483 context.font.size = known_coded_sizes[where - known_sizes];
4484 output_font_change(os, oldFont, context.font);
4485 eat_whitespace(p, os, context, false);
4489 if ((where = is_known(t.cs(), known_font_families)) &&
4490 context.new_layout_allowed) {
4491 context.check_layout(os);
4492 TeXFont const oldFont = context.font;
4493 context.font.family =
4494 known_coded_font_families[where - known_font_families];
4495 output_font_change(os, oldFont, context.font);
4496 eat_whitespace(p, os, context, false);
4500 if ((where = is_known(t.cs(), known_font_series)) &&
4501 context.new_layout_allowed) {
4502 context.check_layout(os);
4503 TeXFont const oldFont = context.font;
4504 context.font.series =
4505 known_coded_font_series[where - known_font_series];
4506 output_font_change(os, oldFont, context.font);
4507 eat_whitespace(p, os, context, false);
4511 if ((where = is_known(t.cs(), known_font_shapes)) &&
4512 context.new_layout_allowed) {
4513 context.check_layout(os);
4514 TeXFont const oldFont = context.font;
4515 context.font.shape =
4516 known_coded_font_shapes[where - known_font_shapes];
4517 output_font_change(os, oldFont, context.font);
4518 eat_whitespace(p, os, context, false);
4521 if ((where = is_known(t.cs(), known_old_font_families)) &&
4522 context.new_layout_allowed) {
4523 context.check_layout(os);
4524 TeXFont const oldFont = context.font;
4525 context.font.init();
4526 context.font.size = oldFont.size;
4527 context.font.family =
4528 known_coded_font_families[where - known_old_font_families];
4529 output_font_change(os, oldFont, context.font);
4530 eat_whitespace(p, os, context, false);
4534 if ((where = is_known(t.cs(), known_old_font_series)) &&
4535 context.new_layout_allowed) {
4536 context.check_layout(os);
4537 TeXFont const oldFont = context.font;
4538 context.font.init();
4539 context.font.size = oldFont.size;
4540 context.font.series =
4541 known_coded_font_series[where - known_old_font_series];
4542 output_font_change(os, oldFont, context.font);
4543 eat_whitespace(p, os, context, false);
4547 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4548 context.new_layout_allowed) {
4549 context.check_layout(os);
4550 TeXFont const oldFont = context.font;
4551 context.font.init();
4552 context.font.size = oldFont.size;
4553 context.font.shape =
4554 known_coded_font_shapes[where - known_old_font_shapes];
4555 output_font_change(os, oldFont, context.font);
4556 eat_whitespace(p, os, context, false);
4560 if (t.cs() == "selectlanguage") {
4561 context.check_layout(os);
4562 // save the language for the case that a
4563 // \foreignlanguage is used
4564 context.font.language = babel2lyx(p.verbatim_item());
4565 os << "\n\\lang " << context.font.language << "\n";
4569 if (t.cs() == "foreignlanguage") {
4570 string const lang = babel2lyx(p.verbatim_item());
4571 parse_text_attributes(p, os, FLAG_ITEM, outer,
4573 context.font.language, lang);
4577 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4578 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4579 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4581 // We have to output the whole command if it has an option
4582 // because LyX doesn't support this yet, see bug #8214,
4583 // only if there is a single option specifying a variant, we can handle it.
4585 string langopts = p.getOpt();
4586 // check if the option contains a variant, if yes, extract it
4587 string::size_type pos_var = langopts.find("variant");
4588 string::size_type i = langopts.find(',');
4589 string::size_type k = langopts.find('=', pos_var);
4590 if (pos_var != string::npos && i == string::npos) {
4592 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4593 lang = preamble.polyglossia2lyx(variant);
4594 parse_text_attributes(p, os, FLAG_ITEM, outer,
4596 context.font.language, lang);
4598 output_ert_inset(os, t.asInput() + langopts, context);
4600 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4601 parse_text_attributes(p, os, FLAG_ITEM, outer,
4603 context.font.language, lang);
4608 if (t.cs() == "inputencoding") {
4609 // nothing to write here
4610 string const enc = subst(p.verbatim_item(), "\n", " ");
4611 p.setEncoding(enc, Encoding::inputenc);
4615 if (is_known(t.cs(), known_special_chars) ||
4616 (t.cs() == "protect" &&
4617 p.next_token().cat() == catEscape &&
4618 is_known(p.next_token().cs(), known_special_protect_chars))) {
4619 // LyX sometimes puts a \protect in front, so we have to ignore it
4621 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4622 known_special_chars);
4623 context.check_layout(os);
4624 os << known_coded_special_chars[where - known_special_chars];
4625 skip_spaces_braces(p);
4629 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4630 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4631 p.next_next_token().asInput() == "-") ||
4632 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4633 // LyX sometimes puts a \protect in front, so we have to ignore it
4634 if (t.cs() == "protect")
4636 context.check_layout(os);
4637 if (t.cs() == "nobreakdash")
4638 os << "\\SpecialChar nobreakdash\n";
4640 os << "\\SpecialChar endofsentence\n";
4645 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4646 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4647 || t.cs() == "%" || t.cs() == "-") {
4648 context.check_layout(os);
4650 os << "\\SpecialChar softhyphen\n";
4656 if (t.cs() == "char") {
4657 context.check_layout(os);
4658 if (p.next_token().character() == '`') {
4660 if (p.next_token().cs() == "\"") {
4665 output_ert_inset(os, "\\char`", context);
4668 output_ert_inset(os, "\\char", context);
4673 if (t.cs() == "verb") {
4674 context.check_layout(os);
4675 // set catcodes to verbatim early, just in case.
4676 p.setCatcodes(VERBATIM_CATCODES);
4677 string delim = p.get_token().asInput();
4678 Parser::Arg arg = p.verbatimStuff(delim);
4680 output_ert_inset(os, "\\verb" + delim
4681 + arg.second + delim, context);
4683 cerr << "invalid \\verb command. Skipping" << endl;
4687 // Problem: \= creates a tabstop inside the tabbing environment
4688 // and else an accent. In the latter case we really would want
4689 // \={o} instead of \= o.
4690 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4691 output_ert_inset(os, t.asInput(), context);
4695 if (t.cs() == "\\") {
4696 context.check_layout(os);
4698 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4699 else if (p.next_token().asInput() == "*") {
4701 // getOpt() eats the following space if there
4702 // is no optional argument, but that is OK
4703 // here since it has no effect in the output.
4704 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4707 begin_inset(os, "Newline newline");
4713 if (t.cs() == "newline" ||
4714 (t.cs() == "linebreak" && !p.hasOpt())) {
4715 context.check_layout(os);
4716 begin_inset(os, "Newline ");
4719 skip_spaces_braces(p);
4723 if (t.cs() == "input" || t.cs() == "include"
4724 || t.cs() == "verbatiminput") {
4725 string name = t.cs();
4726 if (t.cs() == "verbatiminput"
4727 && p.next_token().asInput() == "*")
4728 name += p.get_token().asInput();
4729 context.check_layout(os);
4730 string filename(normalize_filename(p.getArg('{', '}')));
4731 string const path = getMasterFilePath(true);
4732 // We want to preserve relative / absolute filenames,
4733 // therefore path is only used for testing
4734 if ((t.cs() == "include" || t.cs() == "input") &&
4735 !makeAbsPath(filename, path).exists()) {
4736 // The file extension is probably missing.
4737 // Now try to find it out.
4738 string const tex_name =
4739 find_file(filename, path,
4740 known_tex_extensions);
4741 if (!tex_name.empty())
4742 filename = tex_name;
4744 bool external = false;
4746 if (makeAbsPath(filename, path).exists()) {
4747 string const abstexname =
4748 makeAbsPath(filename, path).absFileName();
4749 string const absfigname =
4750 changeExtension(abstexname, ".fig");
4751 fix_child_filename(filename);
4752 string const lyxname = changeExtension(filename,
4753 roundtripMode() ? ".lyx.lyx" : ".lyx");
4754 string const abslyxname = makeAbsPath(
4755 lyxname, getParentFilePath(false)).absFileName();
4757 if (!skipChildren())
4758 external = FileName(absfigname).exists();
4759 if (t.cs() == "input" && !skipChildren()) {
4760 string const ext = getExtension(abstexname);
4762 // Combined PS/LaTeX:
4763 // x.eps, x.pstex_t (old xfig)
4764 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4765 FileName const absepsname(
4766 changeExtension(abstexname, ".eps"));
4767 FileName const abspstexname(
4768 changeExtension(abstexname, ".pstex"));
4769 bool const xfigeps =
4770 (absepsname.exists() ||
4771 abspstexname.exists()) &&
4774 // Combined PDF/LaTeX:
4775 // x.pdf, x.pdftex_t (old xfig)
4776 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4777 FileName const abspdfname(
4778 changeExtension(abstexname, ".pdf"));
4779 bool const xfigpdf =
4780 abspdfname.exists() &&
4781 (ext == "pdftex_t" || ext == "pdf_t");
4785 // Combined PS/PDF/LaTeX:
4786 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4787 string const absbase2(
4788 removeExtension(abstexname) + "_pspdftex");
4789 FileName const abseps2name(
4790 addExtension(absbase2, ".eps"));
4791 FileName const abspdf2name(
4792 addExtension(absbase2, ".pdf"));
4793 bool const xfigboth =
4794 abspdf2name.exists() &&
4795 abseps2name.exists() && ext == "pspdftex";
4797 xfig = xfigpdf || xfigeps || xfigboth;
4798 external = external && xfig;
4801 outname = changeExtension(filename, ".fig");
4802 FileName abssrc(changeExtension(abstexname, ".fig"));
4803 copy_file(abssrc, outname);
4805 // Don't try to convert, the result
4806 // would be full of ERT.
4808 FileName abssrc(abstexname);
4809 copy_file(abssrc, outname);
4810 } else if (t.cs() != "verbatiminput" &&
4812 tex2lyx(abstexname, FileName(abslyxname),
4815 // no need to call copy_file
4816 // tex2lyx creates the file
4819 FileName abssrc(abstexname);
4820 copy_file(abssrc, outname);
4823 cerr << "Warning: Could not find included file '"
4824 << filename << "'." << endl;
4828 begin_inset(os, "External\n");
4829 os << "\ttemplate XFig\n"
4830 << "\tfilename " << outname << '\n';
4831 registerExternalTemplatePackages("XFig");
4833 begin_command_inset(os, "include", name);
4834 outname = subst(outname, "\"", "\\\"");
4835 os << "preview false\n"
4836 "filename \"" << outname << "\"\n";
4837 if (t.cs() == "verbatiminput")
4838 preamble.registerAutomaticallyLoadedPackage("verbatim");
4844 if (t.cs() == "bibliographystyle") {
4845 // store new bibliographystyle
4846 bibliographystyle = p.verbatim_item();
4847 // If any other command than \bibliography, \addcontentsline
4848 // and \nocite{*} follows, we need to output the style
4849 // (because it might be used by that command).
4850 // Otherwise, it will automatically be output by LyX.
4853 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4854 if (t2.cat() == catBegin)
4856 if (t2.cat() != catEscape)
4858 if (t2.cs() == "nocite") {
4859 if (p.getArg('{', '}') == "*")
4861 } else if (t2.cs() == "bibliography")
4863 else if (t2.cs() == "phantomsection") {
4867 else if (t2.cs() == "addcontentsline") {
4868 // get the 3 arguments of \addcontentsline
4871 contentslineContent = p.getArg('{', '}');
4872 // if the last argument is not \refname we must output
4873 if (contentslineContent == "\\refname")
4880 output_ert_inset(os,
4881 "\\bibliographystyle{" + bibliographystyle + '}',
4887 if (t.cs() == "phantomsection") {
4888 // we only support this if it occurs between
4889 // \bibliographystyle and \bibliography
4890 if (bibliographystyle.empty())
4891 output_ert_inset(os, "\\phantomsection", context);
4895 if (t.cs() == "addcontentsline") {
4896 context.check_layout(os);
4897 // get the 3 arguments of \addcontentsline
4898 string const one = p.getArg('{', '}');
4899 string const two = p.getArg('{', '}');
4900 string const three = p.getArg('{', '}');
4901 // only if it is a \refname, we support if for the bibtex inset
4902 if (contentslineContent != "\\refname") {
4903 output_ert_inset(os,
4904 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4910 else if (t.cs() == "bibliography") {
4911 context.check_layout(os);
4913 begin_command_inset(os, "bibtex", "bibtex");
4914 if (!btprint.empty()) {
4915 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4916 // clear the string because the next BibTeX inset can be without the
4917 // \nocite{*} option
4920 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4921 // Do we have addcontentsline?
4922 if (contentslineContent == "\\refname") {
4923 BibOpts = "bibtotoc";
4924 // clear string because next BibTeX inset can be without addcontentsline
4925 contentslineContent.clear();
4927 // Do we have a bibliographystyle set?
4928 if (!bibliographystyle.empty()) {
4929 if (BibOpts.empty())
4930 BibOpts = normalize_filename(bibliographystyle);
4932 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4933 // clear it because each bibtex entry has its style
4934 // and we need an empty string to handle \phantomsection
4935 bibliographystyle.clear();
4937 os << "options " << '"' << BibOpts << '"' << "\n";
4942 if (t.cs() == "printbibliography") {
4943 context.check_layout(os);
4945 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4946 vector<string> opts = getVectorFromString(bbloptions);
4947 vector<string>::iterator it =
4948 find(opts.begin(), opts.end(), "heading=bibintoc");
4949 if (it != opts.end()) {
4951 BibOpts = "bibtotoc";
4953 bbloptions = getStringFromVector(opts);
4954 begin_command_inset(os, "bibtex", "bibtex");
4955 if (!btprint.empty()) {
4956 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4957 // clear the string because the next BibTeX inset can be without the
4958 // \nocite{*} option
4962 for (auto const & bf : preamble.biblatex_bibliographies) {
4963 if (!bibfiles.empty())
4965 bibfiles += normalize_filename(bf);
4967 if (!bibfiles.empty())
4968 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4969 // Do we have addcontentsline?
4970 if (contentslineContent == "\\refname") {
4971 BibOpts = "bibtotoc";
4972 // clear string because next BibTeX inset can be without addcontentsline
4973 contentslineContent.clear();
4975 os << "options " << '"' << BibOpts << '"' << "\n";
4976 if (!bbloptions.empty())
4977 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4979 need_commentbib = false;
4983 if (t.cs() == "bibbysection") {
4984 context.check_layout(os);
4986 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4987 vector<string> opts = getVectorFromString(bbloptions);
4988 vector<string>::iterator it =
4989 find(opts.begin(), opts.end(), "heading=bibintoc");
4990 if (it != opts.end()) {
4992 BibOpts = "bibtotoc";
4994 bbloptions = getStringFromVector(opts);
4995 begin_command_inset(os, "bibtex", "bibtex");
4996 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4998 for (auto const & bf : preamble.biblatex_bibliographies) {
4999 if (!bibfiles.empty())
5001 bibfiles += normalize_filename(bf);
5003 if (!bibfiles.empty())
5004 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5005 os << "options " << '"' << BibOpts << '"' << "\n";
5006 if (!bbloptions.empty())
5007 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5009 need_commentbib = false;
5013 if (t.cs() == "parbox") {
5014 // Test whether this is an outer box of a shaded box
5016 // swallow arguments
5017 while (p.hasOpt()) {
5019 p.skip_spaces(true);
5022 p.skip_spaces(true);
5024 if (p.next_token().cat() == catBegin)
5026 p.skip_spaces(true);
5027 Token to = p.get_token();
5028 bool shaded = false;
5029 if (to.asInput() == "\\begin") {
5030 p.skip_spaces(true);
5031 if (p.getArg('{', '}') == "shaded")
5036 parse_outer_box(p, os, FLAG_ITEM, outer,
5037 context, "parbox", "shaded");
5039 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5040 "", "", t.cs(), "", "");
5044 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5045 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5046 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5047 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5051 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5052 string backgroundcolor;
5053 preamble.registerAutomaticallyLoadedPackage("xcolor");
5054 if (t.cs() == "fcolorbox") {
5055 string const framecolor = p.getArg('{', '}');
5056 backgroundcolor = p.getArg('{', '}');
5057 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5059 backgroundcolor = p.getArg('{', '}');
5060 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5065 // FIXME: due to the compiler limit of "if" nestings
5066 // the code for the alignment was put here
5067 // put them in their own if if this is fixed
5068 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5069 || t.cs() == "shadowsize"
5070 || t.cs() == "raggedleft" || t.cs() == "centering"
5071 || t.cs() == "raggedright") {
5072 if (t.cs() == "fboxrule")
5074 if (t.cs() == "fboxsep")
5076 if (t.cs() == "shadowsize")
5078 if (t.cs() != "raggedleft" && t.cs() != "centering"
5079 && t.cs() != "raggedright") {
5080 p.skip_spaces(true);
5081 while (p.good() && p.next_token().cat() != catSpace
5082 && p.next_token().cat() != catNewline
5083 && p.next_token().cat() != catEscape) {
5084 if (t.cs() == "fboxrule")
5085 fboxrule = fboxrule + p.get_token().asInput();
5086 if (t.cs() == "fboxsep")
5087 fboxsep = fboxsep + p.get_token().asInput();
5088 if (t.cs() == "shadowsize")
5089 shadow_size = shadow_size + p.get_token().asInput();
5092 output_ert_inset(os, t.asInput(), context);
5097 //\framebox() is part of the picture environment and different from \framebox{}
5098 //\framebox{} will be parsed by parse_outer_box
5099 if (t.cs() == "framebox") {
5100 if (p.next_token().character() == '(') {
5101 //the syntax is: \framebox(x,y)[position]{content}
5102 string arg = t.asInput();
5103 arg += p.getFullParentheseArg();
5104 arg += p.getFullOpt();
5105 eat_whitespace(p, os, context, false);
5106 output_ert_inset(os, arg + '{', context);
5107 parse_text(p, os, FLAG_ITEM, outer, context);
5108 output_ert_inset(os, "}", context);
5110 //the syntax is: \framebox[width][position]{content}
5111 string special = p.getFullOpt();
5112 special += p.getOpt();
5113 parse_outer_box(p, os, FLAG_ITEM, outer,
5114 context, t.cs(), special);
5119 //\makebox() is part of the picture environment and different from \makebox{}
5120 //\makebox{} will be parsed by parse_box
5121 if (t.cs() == "makebox") {
5122 if (p.next_token().character() == '(') {
5123 //the syntax is: \makebox(x,y)[position]{content}
5124 string arg = t.asInput();
5125 arg += p.getFullParentheseArg();
5126 arg += p.getFullOpt();
5127 eat_whitespace(p, os, context, false);
5128 output_ert_inset(os, arg + '{', context);
5129 parse_text(p, os, FLAG_ITEM, outer, context);
5130 output_ert_inset(os, "}", context);
5132 //the syntax is: \makebox[width][position]{content}
5133 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5134 "", "", t.cs(), "", "");
5138 if (t.cs() == "smallskip" ||
5139 t.cs() == "medskip" ||
5140 t.cs() == "bigskip" ||
5141 t.cs() == "vfill") {
5142 context.check_layout(os);
5143 begin_inset(os, "VSpace ");
5146 skip_spaces_braces(p);
5150 if ((where = is_known(t.cs(), known_spaces))) {
5151 context.check_layout(os);
5152 begin_inset(os, "space ");
5153 os << '\\' << known_coded_spaces[where - known_spaces]
5156 // LaTeX swallows whitespace after all spaces except
5157 // "\\,". We have to do that here, too, because LyX
5158 // adds "{}" which would make the spaces significant.
5160 eat_whitespace(p, os, context, false);
5161 // LyX adds "{}" after all spaces except "\\ " and
5162 // "\\,", so we have to remove "{}".
5163 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5164 // remove the braces after "\\,", too.
5170 if (t.cs() == "newpage" ||
5171 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5172 t.cs() == "clearpage" ||
5173 t.cs() == "cleardoublepage") {
5174 context.check_layout(os);
5175 begin_inset(os, "Newpage ");
5178 skip_spaces_braces(p);
5182 if (t.cs() == "DeclareRobustCommand" ||
5183 t.cs() == "DeclareRobustCommandx" ||
5184 t.cs() == "newcommand" ||
5185 t.cs() == "newcommandx" ||
5186 t.cs() == "providecommand" ||
5187 t.cs() == "providecommandx" ||
5188 t.cs() == "renewcommand" ||
5189 t.cs() == "renewcommandx") {
5190 // DeclareRobustCommand, DeclareRobustCommandx,
5191 // providecommand and providecommandx could be handled
5192 // by parse_command(), but we need to call
5193 // add_known_command() here.
5194 string name = t.asInput();
5195 if (p.next_token().asInput() == "*") {
5196 // Starred form. Eat '*'
5200 string const command = p.verbatim_item();
5201 string const opt1 = p.getFullOpt();
5202 string const opt2 = p.getFullOpt();
5203 add_known_command(command, opt1, !opt2.empty());
5204 string const ert = name + '{' + command + '}' +
5206 '{' + p.verbatim_item() + '}';
5208 if (t.cs() == "DeclareRobustCommand" ||
5209 t.cs() == "DeclareRobustCommandx" ||
5210 t.cs() == "providecommand" ||
5211 t.cs() == "providecommandx" ||
5212 name[name.length()-1] == '*')
5213 output_ert_inset(os, ert, context);
5215 context.check_layout(os);
5216 begin_inset(os, "FormulaMacro");
5223 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5224 // let could be handled by parse_command(),
5225 // but we need to call add_known_command() here.
5226 string ert = t.asInput();
5229 if (p.next_token().cat() == catBegin) {
5230 name = p.verbatim_item();
5231 ert += '{' + name + '}';
5233 name = p.verbatim_item();
5238 if (p.next_token().cat() == catBegin) {
5239 command = p.verbatim_item();
5240 ert += '{' + command + '}';
5242 command = p.verbatim_item();
5245 // If command is known, make name known too, to parse
5246 // its arguments correctly. For this reason we also
5247 // have commands in syntax.default that are hardcoded.
5248 CommandMap::iterator it = known_commands.find(command);
5249 if (it != known_commands.end())
5250 known_commands[t.asInput()] = it->second;
5251 output_ert_inset(os, ert, context);
5255 if (t.cs() == "hspace" || t.cs() == "vspace") {
5258 string name = t.asInput();
5259 string const length = p.verbatim_item();
5262 bool valid = splitLatexLength(length, valstring, unit);
5263 bool known_hspace = false;
5264 bool known_vspace = false;
5265 bool known_unit = false;
5268 istringstream iss(valstring);
5271 if (t.cs()[0] == 'h') {
5272 if (unit == "\\fill") {
5277 known_hspace = true;
5280 if (unit == "\\smallskipamount") {
5282 known_vspace = true;
5283 } else if (unit == "\\medskipamount") {
5285 known_vspace = true;
5286 } else if (unit == "\\bigskipamount") {
5288 known_vspace = true;
5289 } else if (unit == "\\fill") {
5291 known_vspace = true;
5295 if (!known_hspace && !known_vspace) {
5296 switch (unitFromString(unit)) {
5312 //unitFromString(unit) fails for relative units like Length::PCW
5313 // therefore handle them separately
5314 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5315 || unit == "\\textwidth" || unit == "\\linewidth"
5316 || unit == "\\textheight" || unit == "\\paperheight"
5317 || unit == "\\baselineskip")
5325 // check for glue lengths
5326 bool is_gluelength = false;
5327 string gluelength = length;
5328 string::size_type i = length.find(" minus");
5329 if (i == string::npos) {
5330 i = length.find(" plus");
5331 if (i != string::npos)
5332 is_gluelength = true;
5334 is_gluelength = true;
5335 // if yes transform "9xx minus 8yy plus 7zz"
5337 if (is_gluelength) {
5338 i = gluelength.find(" minus");
5339 if (i != string::npos)
5340 gluelength.replace(i, 7, "-");
5341 i = gluelength.find(" plus");
5342 if (i != string::npos)
5343 gluelength.replace(i, 6, "+");
5346 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5347 // Literal horizontal length or known variable
5348 context.check_layout(os);
5349 begin_inset(os, "space ");
5357 if (known_unit && !known_hspace)
5358 os << "\n\\length " << translate_len(length);
5360 os << "\n\\length " << gluelength;
5362 } else if (known_unit || known_vspace || is_gluelength) {
5363 // Literal vertical length or known variable
5364 context.check_layout(os);
5365 begin_inset(os, "VSpace ");
5368 if (known_unit && !known_vspace)
5369 os << translate_len(length);
5376 // LyX can't handle other length variables in Inset VSpace/space
5381 output_ert_inset(os, name + '{' + unit + '}', context);
5382 else if (value == -1.0)
5383 output_ert_inset(os, name + "{-" + unit + '}', context);
5385 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5387 output_ert_inset(os, name + '{' + length + '}', context);
5392 // The single '=' is meant here.
5393 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5397 context.check_layout(os);
5398 docstring const name = newinsetlayout->name();
5399 bool const caption = name.find(from_ascii("Caption:")) == 0;
5401 // Already done for floating minted listings.
5402 if (minted_float.empty()) {
5403 begin_inset(os, "Caption ");
5404 os << to_utf8(name.substr(8)) << '\n';
5407 begin_inset(os, "Flex ");
5408 os << to_utf8(name) << '\n'
5409 << "status collapsed\n";
5411 if (!minted_float.empty()) {
5412 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5413 } else if (newinsetlayout->isPassThru()) {
5414 // set catcodes to verbatim early, just in case.
5415 p.setCatcodes(VERBATIM_CATCODES);
5416 string delim = p.get_token().asInput();
5418 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5419 //FIXME: handle error condition
5420 string const arg = p.verbatimStuff("}").second;
5421 Context newcontext(true, context.textclass);
5422 if (newinsetlayout->forcePlainLayout())
5423 newcontext.layout = &context.textclass.plainLayout();
5424 output_ert(os, arg, newcontext);
5426 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5429 // Minted caption insets are not closed here because
5430 // we collect everything into the caption.
5431 if (minted_float.empty())
5436 if (t.cs() == "includepdf") {
5438 string const arg = p.getArg('[', ']');
5439 map<string, string> opts;
5440 vector<string> keys;
5441 split_map(arg, opts, keys);
5442 string name = normalize_filename(p.verbatim_item());
5443 string const path = getMasterFilePath(true);
5444 // We want to preserve relative / absolute filenames,
5445 // therefore path is only used for testing
5446 if (!makeAbsPath(name, path).exists()) {
5447 // The file extension is probably missing.
5448 // Now try to find it out.
5449 char const * const pdfpages_format[] = {"pdf", 0};
5450 string const pdftex_name =
5451 find_file(name, path, pdfpages_format);
5452 if (!pdftex_name.empty()) {
5457 FileName const absname = makeAbsPath(name, path);
5458 if (absname.exists())
5460 fix_child_filename(name);
5461 copy_file(absname, name);
5463 cerr << "Warning: Could not find file '"
5464 << name << "'." << endl;
5466 context.check_layout(os);
5467 begin_inset(os, "External\n\ttemplate ");
5468 os << "PDFPages\n\tfilename "
5470 // parse the options
5471 if (opts.find("pages") != opts.end())
5472 os << "\textra LaTeX \"pages="
5473 << opts["pages"] << "\"\n";
5474 if (opts.find("angle") != opts.end())
5475 os << "\trotateAngle "
5476 << opts["angle"] << '\n';
5477 if (opts.find("origin") != opts.end()) {
5479 string const opt = opts["origin"];
5480 if (opt == "tl") ss << "topleft";
5481 if (opt == "bl") ss << "bottomleft";
5482 if (opt == "Bl") ss << "baselineleft";
5483 if (opt == "c") ss << "center";
5484 if (opt == "tc") ss << "topcenter";
5485 if (opt == "bc") ss << "bottomcenter";
5486 if (opt == "Bc") ss << "baselinecenter";
5487 if (opt == "tr") ss << "topright";
5488 if (opt == "br") ss << "bottomright";
5489 if (opt == "Br") ss << "baselineright";
5490 if (!ss.str().empty())
5491 os << "\trotateOrigin " << ss.str() << '\n';
5493 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5495 if (opts.find("width") != opts.end())
5497 << translate_len(opts["width"]) << '\n';
5498 if (opts.find("height") != opts.end())
5500 << translate_len(opts["height"]) << '\n';
5501 if (opts.find("keepaspectratio") != opts.end())
5502 os << "\tkeepAspectRatio\n";
5504 context.check_layout(os);
5505 registerExternalTemplatePackages("PDFPages");
5509 if (t.cs() == "loadgame") {
5511 string name = normalize_filename(p.verbatim_item());
5512 string const path = getMasterFilePath(true);
5513 // We want to preserve relative / absolute filenames,
5514 // therefore path is only used for testing
5515 if (!makeAbsPath(name, path).exists()) {
5516 // The file extension is probably missing.
5517 // Now try to find it out.
5518 char const * const lyxskak_format[] = {"fen", 0};
5519 string const lyxskak_name =
5520 find_file(name, path, lyxskak_format);
5521 if (!lyxskak_name.empty())
5522 name = lyxskak_name;
5524 FileName const absname = makeAbsPath(name, path);
5525 if (absname.exists())
5527 fix_child_filename(name);
5528 copy_file(absname, name);
5530 cerr << "Warning: Could not find file '"
5531 << name << "'." << endl;
5532 context.check_layout(os);
5533 begin_inset(os, "External\n\ttemplate ");
5534 os << "ChessDiagram\n\tfilename "
5537 context.check_layout(os);
5538 // after a \loadgame follows a \showboard
5539 if (p.get_token().asInput() == "showboard")
5541 registerExternalTemplatePackages("ChessDiagram");
5545 // try to see whether the string is in unicodesymbols
5546 // Only use text mode commands, since we are in text mode here,
5547 // and math commands may be invalid (bug 6797)
5548 string name = t.asInput();
5549 // handle the dingbats, cyrillic and greek
5550 if (name == "\\ding" || name == "\\textcyr" ||
5551 (name == "\\textgreek" && !preamble.usePolyglossia()))
5552 name = name + '{' + p.getArg('{', '}') + '}';
5553 // handle the ifsym characters
5554 else if (name == "\\textifsymbol") {
5555 string const optif = p.getFullOpt();
5556 string const argif = p.getArg('{', '}');
5557 name = name + optif + '{' + argif + '}';
5559 // handle the \ascii characters
5560 // the case of \ascii within braces, as LyX outputs it, is already
5561 // handled for t.cat() == catBegin
5562 else if (name == "\\ascii") {
5563 // the code is "\asci\xxx"
5564 name = "{" + name + p.get_token().asInput() + "}";
5567 // handle some TIPA special characters
5568 else if (preamble.isPackageUsed("tipa")) {
5569 if (name == "\\s") {
5570 // fromLaTeXCommand() does not yet
5571 // recognize tipa short cuts
5572 name = "\\textsyllabic";
5573 } else if (name == "\\=" &&
5574 p.next_token().asInput() == "*") {
5575 // fromLaTeXCommand() does not yet
5576 // recognize tipa short cuts
5578 name = "\\textsubbar";
5579 } else if (name == "\\textdoublevertline") {
5580 // FIXME: This is not correct,
5581 // \textvertline is higher than \textbardbl
5582 name = "\\textbardbl";
5584 } else if (name == "\\!" ) {
5585 if (p.next_token().asInput() == "b") {
5586 p.get_token(); // eat 'b'
5589 } else if (p.next_token().asInput() == "d") {
5593 } else if (p.next_token().asInput() == "g") {
5597 } else if (p.next_token().asInput() == "G") {
5599 name = "\\texthtscg";
5601 } else if (p.next_token().asInput() == "j") {
5603 name = "\\texthtbardotlessj";
5605 } else if (p.next_token().asInput() == "o") {
5607 name = "\\textbullseye";
5610 } else if (name == "\\*" ) {
5611 if (p.next_token().asInput() == "k") {
5613 name = "\\textturnk";
5615 } else if (p.next_token().asInput() == "r") {
5616 p.get_token(); // eat 'b'
5617 name = "\\textturnr";
5619 } else if (p.next_token().asInput() == "t") {
5621 name = "\\textturnt";
5623 } else if (p.next_token().asInput() == "w") {
5625 name = "\\textturnw";
5630 if ((name.size() == 2 &&
5631 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5632 p.next_token().asInput() != "*") ||
5633 is_known(name.substr(1), known_tipa_marks)) {
5634 // name is a command that corresponds to a
5635 // combining character in unicodesymbols.
5636 // Append the argument, fromLaTeXCommand()
5637 // will either convert it to a single
5638 // character or a combining sequence.
5639 name += '{' + p.verbatim_item() + '}';
5641 // now get the character from unicodesymbols
5645 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5646 Encodings::TEXT_CMD, termination, rem, &req));
5648 context.check_layout(os);
5651 output_ert_inset(os, to_utf8(rem), context);
5653 skip_spaces_braces(p);
5654 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5655 preamble.registerAutomaticallyLoadedPackage(*it);
5657 //cerr << "#: " << t << " mode: " << mode << endl;
5658 // heuristic: read up to next non-nested space
5660 string s = t.asInput();
5661 string z = p.verbatim_item();
5662 while (p.good() && z != " " && !z.empty()) {
5663 //cerr << "read: " << z << endl;
5665 z = p.verbatim_item();
5667 cerr << "found ERT: " << s << endl;
5668 output_ert_inset(os, s + ' ', context);
5671 if (t.asInput() == name &&
5672 p.next_token().asInput() == "*") {
5673 // Starred commands like \vspace*{}
5674 p.get_token(); // Eat '*'
5677 if (!parse_command(name, p, os, outer, context))
5678 output_ert_inset(os, name, context);
5684 string guessLanguage(Parser & p, string const & lang)
5686 typedef std::map<std::string, size_t> LangMap;
5687 // map from language names to number of characters
5690 for (char const * const * i = supported_CJK_languages; *i; i++)
5691 used[string(*i)] = 0;
5694 Token const t = p.get_token();
5695 // comments are not counted for any language
5696 if (t.cat() == catComment)
5698 // commands are not counted as well, but we need to detect
5699 // \begin{CJK} and switch encoding if needed
5700 if (t.cat() == catEscape) {
5701 if (t.cs() == "inputencoding") {
5702 string const enc = subst(p.verbatim_item(), "\n", " ");
5703 p.setEncoding(enc, Encoding::inputenc);
5706 if (t.cs() != "begin")
5709 // Non-CJK content is counted for lang.
5710 // We do not care about the real language here:
5711 // If we have more non-CJK contents than CJK contents,
5712 // we simply use the language that was specified as
5713 // babel main language.
5714 used[lang] += t.asInput().length();
5717 // Now we are starting an environment
5719 string const name = p.getArg('{', '}');
5720 if (name != "CJK") {
5724 // It is a CJK environment
5726 /* name = */ p.getArg('{', '}');
5727 string const encoding = p.getArg('{', '}');
5728 /* mapping = */ p.getArg('{', '}');
5729 string const encoding_old = p.getEncoding();
5730 char const * const * const where =
5731 is_known(encoding, supported_CJK_encodings);
5733 p.setEncoding(encoding, Encoding::CJK);
5735 p.setEncoding("UTF-8");
5736 string const text = p.ertEnvironment("CJK");
5737 p.setEncoding(encoding_old);
5740 // ignore contents in unknown CJK encoding
5743 // the language of the text
5745 supported_CJK_languages[where - supported_CJK_encodings];
5746 used[cjk] += text.length();
5748 LangMap::const_iterator use = used.begin();
5749 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5750 if (it->second > use->second)
5757 void check_comment_bib(ostream & os, Context & context)
5759 if (!need_commentbib)
5761 // We have a bibliography database, but no bibliography with biblatex
5762 // which is completely valid. Insert a bibtex inset in a note.
5763 context.check_layout(os);
5764 begin_inset(os, "Note Note\n");
5765 os << "status open\n";
5766 os << "\\begin_layout Plain Layout\n";
5767 begin_command_inset(os, "bibtex", "bibtex");
5769 for (auto const & bf : preamble.biblatex_bibliographies) {
5770 if (!bibfiles.empty())
5772 bibfiles += normalize_filename(bf);
5774 if (!bibfiles.empty())
5775 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5776 end_inset(os);// Bibtex
5777 os << "\\end_layout\n";
5778 end_inset(os);// Note