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 docstring flex_name = newinsetlayout->name();
2123 // FIXME: what do we do if the prefix is not Flex: ?
2124 if (prefixIs(flex_name, from_ascii("Flex:")))
2125 flex_name.erase(0, 5);
2126 os << to_utf8(flex_name) << '\n'
2127 << "status collapsed\n";
2128 if (newinsetlayout->isPassThru()) {
2129 string const arg = p.verbatimEnvironment(name);
2130 Context context(true, parent_context.textclass,
2131 &parent_context.textclass.plainLayout(),
2132 parent_context.layout);
2133 output_ert(os, arg, parent_context);
2135 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2139 else if (name == "appendix") {
2140 // This is no good latex style, but it works and is used in some documents...
2141 eat_whitespace(p, os, parent_context, false);
2142 parent_context.check_end_layout(os);
2143 Context context(true, parent_context.textclass, parent_context.layout,
2144 parent_context.layout, parent_context.font);
2145 context.check_layout(os);
2146 os << "\\start_of_appendix\n";
2147 parse_text(p, os, FLAG_END, outer, context);
2148 context.check_end_layout(os);
2152 else if (known_environments.find(name) != known_environments.end()) {
2153 vector<ArgumentType> arguments = known_environments[name];
2154 // The last "argument" denotes wether we may translate the
2155 // environment contents to LyX
2156 // The default required if no argument is given makes us
2157 // compatible with the reLyXre environment.
2158 ArgumentType contents = arguments.empty() ?
2161 if (!arguments.empty())
2162 arguments.pop_back();
2163 // See comment in parse_unknown_environment()
2164 bool const specialfont =
2165 (parent_context.font != parent_context.normalfont);
2166 bool const new_layout_allowed =
2167 parent_context.new_layout_allowed;
2169 parent_context.new_layout_allowed = false;
2170 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2171 outer, parent_context);
2172 if (contents == verbatim)
2173 output_ert_inset(os, p.ertEnvironment(name),
2176 parse_text_snippet(p, os, FLAG_END, outer,
2178 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2180 parent_context.new_layout_allowed = new_layout_allowed;
2184 parse_unknown_environment(p, name, os, FLAG_END, outer,
2188 active_environments.pop_back();
2192 /// parses a comment and outputs it to \p os.
2193 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2195 LASSERT(t.cat() == catComment, return);
2196 if (!t.cs().empty()) {
2197 context.check_layout(os);
2198 output_comment(p, os, t.cs(), context);
2199 if (p.next_token().cat() == catNewline) {
2200 // A newline after a comment line starts a new
2202 if (context.new_layout_allowed) {
2203 if(!context.atParagraphStart())
2204 // Only start a new paragraph if not already
2205 // done (we might get called recursively)
2206 context.new_paragraph(os);
2208 output_ert_inset(os, "\n", context);
2209 eat_whitespace(p, os, context, true);
2212 // "%\n" combination
2219 * Reads spaces and comments until the first non-space, non-comment token.
2220 * New paragraphs (double newlines or \\par) are handled like simple spaces
2221 * if \p eatParagraph is true.
2222 * Spaces are skipped, but comments are written to \p os.
2224 void eat_whitespace(Parser & p, ostream & os, Context & context,
2228 Token const & t = p.get_token();
2229 if (t.cat() == catComment)
2230 parse_comment(p, os, t, context);
2231 else if ((! eatParagraph && p.isParagraph()) ||
2232 (t.cat() != catSpace && t.cat() != catNewline)) {
2241 * Set a font attribute, parse text and reset the font attribute.
2242 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2243 * \param currentvalue Current value of the attribute. Is set to the new
2244 * value during parsing.
2245 * \param newvalue New value of the attribute
2247 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2248 Context & context, string const & attribute,
2249 string & currentvalue, string const & newvalue)
2251 context.check_layout(os);
2252 string const oldvalue = currentvalue;
2253 currentvalue = newvalue;
2254 os << '\n' << attribute << ' ' << newvalue << "\n";
2255 parse_text_snippet(p, os, flags, outer, context);
2256 context.check_layout(os);
2257 os << '\n' << attribute << ' ' << oldvalue << "\n";
2258 currentvalue = oldvalue;
2262 /// get the arguments of a natbib or jurabib citation command
2263 void get_cite_arguments(Parser & p, bool natbibOrder,
2264 string & before, string & after, bool const qualified = false)
2266 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2268 // text before the citation
2270 // text after the citation
2271 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2273 if (!after.empty()) {
2274 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2275 if (natbibOrder && !before.empty())
2276 swap(before, after);
2281 void copy_file(FileName const & src, string dstname)
2285 string const absParent = getParentFilePath(false);
2287 if (FileName::isAbsolute(dstname))
2288 dst = FileName(dstname);
2290 dst = makeAbsPath(dstname, absParent);
2291 FileName const srcpath = src.onlyPath();
2292 FileName const dstpath = dst.onlyPath();
2293 if (equivalent(srcpath, dstpath))
2295 if (!dstpath.isDirectory()) {
2296 if (!dstpath.createPath()) {
2297 cerr << "Warning: Could not create directory for file `"
2298 << dst.absFileName() << "´." << endl;
2302 if (dst.isReadableFile()) {
2303 if (overwriteFiles())
2304 cerr << "Warning: Overwriting existing file `"
2305 << dst.absFileName() << "´." << endl;
2307 cerr << "Warning: Not overwriting existing file `"
2308 << dst.absFileName() << "´." << endl;
2312 if (!src.copyTo(dst))
2313 cerr << "Warning: Could not copy file `" << src.absFileName()
2314 << "´ to `" << dst.absFileName() << "´." << endl;
2318 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2319 bool parse_chunk(Parser & p, ostream & os, Context & context)
2321 // check whether a chunk is possible here.
2322 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2328 // read the parameters
2329 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2330 if (!params.first) {
2335 Parser::Arg const code = p.verbatimStuff("\n@");
2340 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2341 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2345 // The last newline read is important for paragraph handling
2349 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2350 // We must have a valid layout before outputting the Chunk inset.
2351 context.check_layout(os);
2352 Context chunkcontext(true, context.textclass);
2353 chunkcontext.layout = &context.textclass.plainLayout();
2354 begin_inset(os, "Flex Chunk");
2355 os << "\nstatus open\n";
2356 if (!params.second.empty()) {
2357 chunkcontext.check_layout(os);
2358 Context paramscontext(true, context.textclass);
2359 paramscontext.layout = &context.textclass.plainLayout();
2360 begin_inset(os, "Argument 1");
2361 os << "\nstatus open\n";
2362 output_ert(os, params.second, paramscontext);
2365 output_ert(os, code.second, chunkcontext);
2373 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2374 bool is_macro(Parser & p)
2376 Token first = p.curr_token();
2377 if (first.cat() != catEscape || !p.good())
2379 if (first.cs() == "def")
2381 if (first.cs() != "global" && first.cs() != "long")
2383 Token second = p.get_token();
2385 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2386 second.cat() == catNewline || second.cat() == catComment)) {
2387 second = p.get_token();
2390 bool secondvalid = second.cat() == catEscape;
2392 bool thirdvalid = false;
2393 if (p.good() && first.cs() == "global" && secondvalid &&
2394 second.cs() == "long") {
2395 third = p.get_token();
2397 while (p.good() && !p.isParagraph() &&
2398 (third.cat() == catSpace ||
2399 third.cat() == catNewline ||
2400 third.cat() == catComment)) {
2401 third = p.get_token();
2404 thirdvalid = third.cat() == catEscape;
2406 for (int i = 0; i < pos; ++i)
2411 return (first.cs() == "global" || first.cs() == "long") &&
2412 second.cs() == "def";
2413 return first.cs() == "global" && second.cs() == "long" &&
2414 third.cs() == "def";
2418 /// Parse a macro definition (assumes that is_macro() returned true)
2419 void parse_macro(Parser & p, ostream & os, Context & context)
2421 context.check_layout(os);
2422 Token first = p.curr_token();
2425 string command = first.asInput();
2426 if (first.cs() != "def") {
2428 eat_whitespace(p, os, context, false);
2429 second = p.curr_token();
2430 command += second.asInput();
2431 if (second.cs() != "def") {
2433 eat_whitespace(p, os, context, false);
2434 third = p.curr_token();
2435 command += third.asInput();
2438 eat_whitespace(p, os, context, false);
2439 string const name = p.get_token().cs();
2440 eat_whitespace(p, os, context, false);
2446 while (p.next_token().cat() != catBegin) {
2447 if (p.next_token().cat() == catParameter) {
2452 // followed by number?
2453 if (p.next_token().cat() == catOther) {
2454 string s = p.get_token().asInput();
2456 // number = current arity + 1?
2457 if (s.size() == 1 && s[0] == arity + '0' + 1)
2462 paramtext += p.get_token().cs();
2464 paramtext += p.get_token().cs();
2469 // only output simple (i.e. compatible) macro as FormulaMacros
2470 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2472 context.check_layout(os);
2473 begin_inset(os, "FormulaMacro");
2474 os << "\n\\def" << ert;
2477 output_ert_inset(os, command + ert, context);
2481 void registerExternalTemplatePackages(string const & name)
2483 external::TemplateManager const & etm = external::TemplateManager::get();
2484 external::Template const * const et = etm.getTemplateByName(name);
2487 external::Template::Formats::const_iterator cit = et->formats.end();
2489 cit = et->formats.find("PDFLaTeX");
2490 if (cit == et->formats.end())
2491 // If the template has not specified a PDFLaTeX output,
2492 // we try the LaTeX format.
2493 cit = et->formats.find("LaTeX");
2494 if (cit == et->formats.end())
2496 vector<string>::const_iterator qit = cit->second.requirements.begin();
2497 vector<string>::const_iterator qend = cit->second.requirements.end();
2498 for (; qit != qend; ++qit)
2499 preamble.registerAutomaticallyLoadedPackage(*qit);
2502 } // anonymous namespace
2506 * Find a file with basename \p name in path \p path and an extension
2509 string find_file(string const & name, string const & path,
2510 char const * const * extensions)
2512 for (char const * const * what = extensions; *what; ++what) {
2513 string const trial = addExtension(name, *what);
2514 if (makeAbsPath(trial, path).exists())
2521 /// Convert filenames with TeX macros and/or quotes to something LyX
2523 string const normalize_filename(string const & name)
2528 Token const & t = p.get_token();
2529 if (t.cat() != catEscape)
2531 else if (t.cs() == "lyxdot") {
2532 // This is used by LyX for simple dots in relative
2536 } else if (t.cs() == "space") {
2539 } else if (t.cs() == "string") {
2540 // Convert \string" to " and \string~ to ~
2541 Token const & n = p.next_token();
2542 if (n.asInput() != "\"" && n.asInput() != "~")
2547 // Strip quotes. This is a bit complicated (see latex_path()).
2548 string full = os.str();
2549 if (!full.empty() && full[0] == '"') {
2550 string base = removeExtension(full);
2551 string ext = getExtension(full);
2552 if (!base.empty() && base[base.length()-1] == '"')
2555 return addExtension(trim(base, "\""), ext);
2556 if (full[full.length()-1] == '"')
2559 return trim(full, "\"");
2565 /// Convert \p name from TeX convention (relative to master file) to LyX
2566 /// convention (relative to .lyx file) if it is relative
2567 void fix_child_filename(string & name)
2569 string const absMasterTeX = getMasterFilePath(true);
2570 bool const isabs = FileName::isAbsolute(name);
2571 // convert from "relative to .tex master" to absolute original path
2573 name = makeAbsPath(name, absMasterTeX).absFileName();
2574 bool copyfile = copyFiles();
2575 string const absParentLyX = getParentFilePath(false);
2578 // convert from absolute original path to "relative to master file"
2579 string const rel = to_utf8(makeRelPath(from_utf8(name),
2580 from_utf8(absMasterTeX)));
2581 // re-interpret "relative to .tex file" as "relative to .lyx file"
2582 // (is different if the master .lyx file resides in a
2583 // different path than the master .tex file)
2584 string const absMasterLyX = getMasterFilePath(false);
2585 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2586 // Do not copy if the new path is impossible to create. Example:
2587 // absMasterTeX = "/foo/bar/"
2588 // absMasterLyX = "/bar/"
2589 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2590 if (contains(name, "/../"))
2597 // convert from absolute original path to
2598 // "relative to .lyx file"
2599 name = to_utf8(makeRelPath(from_utf8(abs),
2600 from_utf8(absParentLyX)));
2604 // convert from absolute original path to "relative to .lyx file"
2605 name = to_utf8(makeRelPath(from_utf8(name),
2606 from_utf8(absParentLyX)));
2611 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2612 Context & context, string const rdelim)
2614 Layout const * newlayout = 0;
2615 InsetLayout const * newinsetlayout = 0;
2616 char const * const * where = 0;
2617 // Store the latest bibliographystyle, addcontentslineContent and
2618 // nocite{*} option (needed for bibtex inset)
2620 string contentslineContent;
2621 // Some classes provide a \bibliographystyle, so do not output
2622 // any if none is explicitly set.
2623 string bibliographystyle;
2624 bool const use_natbib = isProvided("natbib");
2625 bool const use_jurabib = isProvided("jurabib");
2626 bool const use_biblatex = isProvided("biblatex")
2627 && preamble.citeEngine() != "biblatex-natbib";
2628 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2629 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2630 need_commentbib = use_biblatex || use_biblatex_natbib;
2633 // it is impossible to determine the correct encoding for non-CJK Japanese.
2634 // Therefore write a note at the beginning of the document
2635 if (is_nonCJKJapanese) {
2636 context.check_layout(os);
2637 begin_inset(os, "Note Note\n");
2638 os << "status open\n\\begin_layout Plain Layout\n"
2639 << "\\series bold\n"
2640 << "Important information:\n"
2641 << "\\end_layout\n\n"
2642 << "\\begin_layout Plain Layout\n"
2643 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2644 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2645 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2646 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2647 << " and specify the encoding using the -e command-line switch.\n"
2648 << " In addition, you might want to double check that the desired output encoding\n"
2649 << " is correctly selected in Document > Settings > Language.\n"
2650 << "\\end_layout\n";
2652 is_nonCJKJapanese = false;
2655 bool have_cycled = false;
2657 // Leave here only after at least one cycle
2658 if (have_cycled && flags & FLAG_LEAVE) {
2659 flags &= ~FLAG_LEAVE;
2663 Token const & t = p.get_token();
2665 debugToken(cerr, t, flags);
2668 if (flags & FLAG_ITEM) {
2669 if (t.cat() == catSpace)
2672 flags &= ~FLAG_ITEM;
2673 if (t.cat() == catBegin) {
2674 // skip the brace and collect everything to the next matching
2676 flags |= FLAG_BRACE_LAST;
2680 // handle only this single token, leave the loop if done
2681 flags |= FLAG_LEAVE;
2684 if (t.cat() != catEscape && t.character() == ']' &&
2685 (flags & FLAG_BRACK_LAST))
2687 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2689 string tok = t.asInput();
2690 // we only support delimiters with max 2 chars for now.
2691 if (rdelim.size() > 1)
2692 tok += p.next_token().asInput();
2693 if (t.cat() != catEscape && !rdelim.empty()
2694 && tok == rdelim && (flags & FLAG_RDELIM)) {
2695 if (rdelim.size() > 1)
2696 p.get_token(); // eat rdelim
2700 // If there is anything between \end{env} and \begin{env} we
2701 // don't need to output a separator.
2702 if (t.cat() != catSpace && t.cat() != catNewline &&
2703 t.asInput() != "\\begin")
2710 bool const starred = p.next_token().asInput() == "*";
2711 string const starredname(starred ? (t.cs() + '*') : t.cs());
2712 if (t.cat() == catMath) {
2713 // we are inside some text mode thingy, so opening new math is allowed
2714 context.check_layout(os);
2715 begin_inset(os, "Formula ");
2716 Token const & n = p.get_token();
2717 bool const display(n.cat() == catMath && outer);
2719 // TeX's $$...$$ syntax for displayed math
2721 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2723 p.get_token(); // skip the second '$' token
2725 // simple $...$ stuff
2728 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2733 // Prevent the conversion of a line break to a
2734 // space (bug 7668). This does not change the
2735 // output, but looks ugly in LyX.
2736 eat_whitespace(p, os, context, false);
2741 if (t.cat() == catSuper || t.cat() == catSub) {
2742 cerr << "catcode " << t << " illegal in text mode\n";
2746 // Basic support for quotes. We try to disambiguate
2747 // quotes from the context (e.g., a left english quote is
2748 // the same as a right german quote...).
2749 // Try to make a smart guess about the side
2750 Token const prev = p.prev_token();
2751 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2752 && prev.character() != '\n' && prev.character() != '~');
2753 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2754 context.check_layout(os);
2755 begin_inset(os, "Quotes ");
2756 os << guessQuoteStyle("eld", opening);
2762 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2763 context.check_layout(os);
2764 begin_inset(os, "Quotes ");
2765 os << guessQuoteStyle("erd", opening);
2772 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2773 context.check_layout(os);
2774 begin_inset(os, "Quotes ");
2775 os << guessQuoteStyle("ald", opening);
2782 if (t.asInput() == "<"
2783 && p.next_token().asInput() == "<") {
2784 bool has_chunk = false;
2788 has_chunk = parse_chunk(p, os, context);
2794 context.check_layout(os);
2795 begin_inset(os, "Quotes ");
2796 os << guessQuoteStyle("ard", opening);
2804 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2805 check_space(p, os, context);
2809 // babel shorthands (also used by polyglossia)
2810 // Since these can have different meanings for different languages
2811 // we import them as ERT (but they must be put in ERT to get output
2813 if (t.asInput() == "\"") {
2815 // These are known pairs. We put them together in
2816 // one ERT inset. In other cases (such as "a), only
2817 // the quotation mark is ERTed.
2818 if (p.next_token().asInput() == "\""
2819 || p.next_token().asInput() == "|"
2820 || p.next_token().asInput() == "-"
2821 || p.next_token().asInput() == "~"
2822 || p.next_token().asInput() == "="
2823 || p.next_token().asInput() == "/"
2824 || p.next_token().asInput() == "~"
2825 || p.next_token().asInput() == "'"
2826 || p.next_token().asInput() == "`"
2827 || p.next_token().asInput() == "<"
2828 || p.next_token().asInput() == ">") {
2829 s += p.next_token().asInput();
2832 output_ert_inset(os, s, context);
2836 if (t.character() == '[' && noweb_mode &&
2837 p.next_token().character() == '[') {
2838 // These can contain underscores
2840 string const s = p.getFullOpt() + ']';
2841 if (p.next_token().character() == ']')
2844 cerr << "Warning: Inserting missing ']' in '"
2845 << s << "'." << endl;
2846 output_ert_inset(os, s, context);
2850 if (t.cat() == catLetter) {
2851 context.check_layout(os);
2856 if (t.cat() == catOther ||
2857 t.cat() == catAlign ||
2858 t.cat() == catParameter) {
2859 context.check_layout(os);
2860 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2861 context.merging_hyphens_allowed &&
2862 context.font.family != "ttfamily" &&
2863 !context.layout->pass_thru) {
2864 if (p.next_next_token().asInput() == "-") {
2866 os << to_utf8(docstring(1, 0x2014));
2870 os << to_utf8(docstring(1, 0x2013));
2873 // This translates "&" to "\\&" which may be wrong...
2878 if (p.isParagraph()) {
2879 // In minted floating listings we will collect
2880 // everything into the caption, where multiple
2881 // paragraphs are forbidden.
2882 if (minted_float.empty()) {
2883 if (context.new_layout_allowed)
2884 context.new_paragraph(os);
2886 output_ert_inset(os, "\\par ", context);
2889 eat_whitespace(p, os, context, true);
2893 if (t.cat() == catActive) {
2894 context.check_layout(os);
2895 if (t.character() == '~') {
2896 if (context.layout->free_spacing)
2899 begin_inset(os, "space ~\n");
2907 if (t.cat() == catBegin) {
2908 Token const next = p.next_token();
2909 Token const end = p.next_next_token();
2910 if (next.cat() == catEnd) {
2912 Token const prev = p.prev_token();
2914 if (p.next_token().character() == '`')
2915 ; // ignore it in {}``
2917 output_ert_inset(os, "{}", context);
2918 } else if (next.cat() == catEscape &&
2919 is_known(next.cs(), known_quotes) &&
2920 end.cat() == catEnd) {
2921 // Something like {\textquoteright} (e.g.
2922 // from writer2latex). We may skip the
2923 // braces here for better readability.
2924 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2926 } else if (p.next_token().asInput() == "\\ascii") {
2927 // handle the \ascii characters
2928 // (the case without braces is handled later)
2929 // the code is "{\ascii\xxx}"
2930 p.get_token(); // eat \ascii
2931 string name2 = p.get_token().asInput();
2932 p.get_token(); // eat the final '}'
2933 string const name = "{\\ascii" + name2 + "}";
2937 // get the character from unicodesymbols
2938 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2939 Encodings::TEXT_CMD, termination, rem, &req);
2941 context.check_layout(os);
2944 output_ert_inset(os,
2945 to_utf8(rem), context);
2946 for (set<string>::const_iterator it = req.begin();
2947 it != req.end(); ++it)
2948 preamble.registerAutomaticallyLoadedPackage(*it);
2950 // we did not find a non-ert version
2951 output_ert_inset(os, name, context);
2953 context.check_layout(os);
2954 // special handling of font attribute changes
2955 Token const prev = p.prev_token();
2956 TeXFont const oldFont = context.font;
2957 if (next.character() == '[' ||
2958 next.character() == ']' ||
2959 next.character() == '*') {
2961 if (p.next_token().cat() == catEnd) {
2966 output_ert_inset(os, "{", context);
2967 parse_text_snippet(p, os,
2970 output_ert_inset(os, "}", context);
2972 } else if (! context.new_layout_allowed) {
2973 output_ert_inset(os, "{", context);
2974 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2976 output_ert_inset(os, "}", context);
2977 } else if (is_known(next.cs(), known_sizes)) {
2978 // next will change the size, so we must
2980 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2982 if (!context.atParagraphStart())
2984 << context.font.size << "\n";
2985 } else if (is_known(next.cs(), known_font_families)) {
2986 // next will change the font family, so we
2987 // must reset it here
2988 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2990 if (!context.atParagraphStart())
2992 << context.font.family << "\n";
2993 } else if (is_known(next.cs(), known_font_series)) {
2994 // next will change the font series, so we
2995 // must reset it here
2996 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2998 if (!context.atParagraphStart())
3000 << context.font.series << "\n";
3001 } else if (is_known(next.cs(), known_font_shapes)) {
3002 // next will change the font shape, so we
3003 // must reset it here
3004 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3006 if (!context.atParagraphStart())
3008 << context.font.shape << "\n";
3009 } else if (is_known(next.cs(), known_old_font_families) ||
3010 is_known(next.cs(), known_old_font_series) ||
3011 is_known(next.cs(), known_old_font_shapes)) {
3012 // next will change the font family, series
3013 // and shape, so we must reset it here
3014 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3016 if (!context.atParagraphStart())
3018 << context.font.family
3020 << context.font.series
3022 << context.font.shape << "\n";
3024 output_ert_inset(os, "{", context);
3025 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3027 output_ert_inset(os, "}", context);
3033 if (t.cat() == catEnd) {
3034 if (flags & FLAG_BRACE_LAST) {
3037 cerr << "stray '}' in text\n";
3038 output_ert_inset(os, "}", context);
3042 if (t.cat() == catComment) {
3043 parse_comment(p, os, t, context);
3048 // control sequences
3051 if (t.cs() == "(" || t.cs() == "[") {
3052 bool const simple = t.cs() == "(";
3053 context.check_layout(os);
3054 begin_inset(os, "Formula");
3055 os << " \\" << t.cs();
3056 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3057 os << '\\' << (simple ? ')' : ']');
3060 // Prevent the conversion of a line break to a
3061 // space (bug 7668). This does not change the
3062 // output, but looks ugly in LyX.
3063 eat_whitespace(p, os, context, false);
3068 if (t.cs() == "begin") {
3069 parse_environment(p, os, outer, last_env,
3074 if (t.cs() == "end") {
3075 if (flags & FLAG_END) {
3076 // eat environment name
3077 string const name = p.getArg('{', '}');
3078 if (name != active_environment())
3079 cerr << "\\end{" + name + "} does not match \\begin{"
3080 + active_environment() + "}\n";
3083 p.error("found 'end' unexpectedly");
3087 // "item" by default, but could be something else
3088 if (t.cs() == context.layout->itemcommand()) {
3090 if (context.layout->labeltype == LABEL_MANUAL) {
3091 // FIXME: This swallows comments, but we cannot use
3092 // eat_whitespace() since we must not output
3093 // anything before the item.
3094 p.skip_spaces(true);
3095 s = p.verbatimOption();
3097 p.skip_spaces(false);
3099 context.check_layout(os);
3100 if (context.has_item) {
3101 // An item in an unknown list-like environment
3102 // FIXME: Do this in check_layout()!
3103 context.has_item = false;
3104 string item = "\\" + context.layout->itemcommand();
3107 output_ert_inset(os, item, context);
3109 if (context.layout->labeltype != LABEL_MANUAL)
3110 output_arguments(os, p, outer, false, "item", context,
3111 context.layout->itemargs());
3112 if (!context.list_extra_stuff.empty()) {
3113 os << context.list_extra_stuff;
3114 context.list_extra_stuff.clear();
3116 else if (!s.empty()) {
3117 // LyX adds braces around the argument,
3118 // so we need to remove them here.
3119 if (s.size() > 2 && s[0] == '{' &&
3120 s[s.size()-1] == '}')
3121 s = s.substr(1, s.size()-2);
3122 // If the argument contains a space we
3123 // must put it into ERT: Otherwise LyX
3124 // would misinterpret the space as
3125 // item delimiter (bug 7663)
3126 if (contains(s, ' ')) {
3127 output_ert_inset(os, s, context);
3130 os << parse_text_snippet(p2,
3131 FLAG_BRACK_LAST, outer, context);
3133 // The space is needed to separate the
3134 // item from the rest of the sentence.
3136 eat_whitespace(p, os, context, false);
3141 if (t.cs() == "bibitem") {
3143 context.check_layout(os);
3144 eat_whitespace(p, os, context, false);
3145 string label = p.verbatimOption();
3146 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3147 bool const literal = !lbl.first;
3148 label = literal ? subst(label, "\n", " ") : lbl.second;
3149 string lit = literal ? "\"true\"" : "\"false\"";
3150 string key = convert_literate_command_inset_arg(p.verbatim_item());
3151 begin_command_inset(os, "bibitem", "bibitem");
3152 os << "label \"" << label << "\"\n"
3153 << "key \"" << key << "\"\n"
3154 << "literal " << lit << "\n";
3160 // catch the case of \def\inputGnumericTable
3162 if (t.cs() == "def") {
3163 Token second = p.next_token();
3164 if (second.cs() == "inputGnumericTable") {
3168 Token third = p.get_token();
3170 if (third.cs() == "input") {
3174 string name = normalize_filename(p.verbatim_item());
3175 string const path = getMasterFilePath(true);
3176 // We want to preserve relative / absolute filenames,
3177 // therefore path is only used for testing
3178 // The file extension is in every case ".tex".
3179 // So we need to remove this extension and check for
3180 // the original one.
3181 name = removeExtension(name);
3182 if (!makeAbsPath(name, path).exists()) {
3183 char const * const Gnumeric_formats[] = {"gnumeric",
3185 string const Gnumeric_name =
3186 find_file(name, path, Gnumeric_formats);
3187 if (!Gnumeric_name.empty())
3188 name = Gnumeric_name;
3190 FileName const absname = makeAbsPath(name, path);
3191 if (absname.exists()) {
3192 fix_child_filename(name);
3193 copy_file(absname, name);
3195 cerr << "Warning: Could not find file '"
3196 << name << "'." << endl;
3197 context.check_layout(os);
3198 begin_inset(os, "External\n\ttemplate ");
3199 os << "GnumericSpreadsheet\n\tfilename "
3202 context.check_layout(os);
3204 // register the packages that are automatically loaded
3205 // by the Gnumeric template
3206 registerExternalTemplatePackages("GnumericSpreadsheet");
3211 parse_macro(p, os, context);
3215 if (t.cs() == "noindent") {
3217 context.add_par_extra_stuff("\\noindent\n");
3221 if (t.cs() == "appendix") {
3222 context.add_par_extra_stuff("\\start_of_appendix\n");
3223 // We need to start a new paragraph. Otherwise the
3224 // appendix in 'bla\appendix\chapter{' would start
3226 context.new_paragraph(os);
3227 // We need to make sure that the paragraph is
3228 // generated even if it is empty. Otherwise the
3229 // appendix in '\par\appendix\par\chapter{' would
3231 context.check_layout(os);
3232 // FIXME: This is a hack to prevent paragraph
3233 // deletion if it is empty. Handle this better!
3234 output_comment(p, os,
3235 "dummy comment inserted by tex2lyx to "
3236 "ensure that this paragraph is not empty",
3238 // Both measures above may generate an additional
3239 // empty paragraph, but that does not hurt, because
3240 // whitespace does not matter here.
3241 eat_whitespace(p, os, context, true);
3245 // Must catch empty dates before findLayout is called below
3246 if (t.cs() == "date") {
3247 eat_whitespace(p, os, context, false);
3249 string const date = p.verbatim_item();
3252 preamble.suppressDate(true);
3255 preamble.suppressDate(false);
3256 if (context.new_layout_allowed &&
3257 (newlayout = findLayout(context.textclass,
3260 output_command_layout(os, p, outer,
3261 context, newlayout);
3262 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3263 if (!preamble.titleLayoutFound())
3264 preamble.titleLayoutFound(newlayout->intitle);
3265 set<string> const & req = newlayout->requires();
3266 set<string>::const_iterator it = req.begin();
3267 set<string>::const_iterator en = req.end();
3268 for (; it != en; ++it)
3269 preamble.registerAutomaticallyLoadedPackage(*it);
3271 output_ert_inset(os,
3272 "\\date{" + p.verbatim_item() + '}',
3278 // Starred section headings
3279 // Must attempt to parse "Section*" before "Section".
3280 if ((p.next_token().asInput() == "*") &&
3281 context.new_layout_allowed &&
3282 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3285 output_command_layout(os, p, outer, context, newlayout);
3287 if (!preamble.titleLayoutFound())
3288 preamble.titleLayoutFound(newlayout->intitle);
3289 set<string> const & req = newlayout->requires();
3290 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3291 preamble.registerAutomaticallyLoadedPackage(*it);
3295 // Section headings and the like
3296 if (context.new_layout_allowed &&
3297 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3299 output_command_layout(os, p, outer, context, newlayout);
3301 if (!preamble.titleLayoutFound())
3302 preamble.titleLayoutFound(newlayout->intitle);
3303 set<string> const & req = newlayout->requires();
3304 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3305 preamble.registerAutomaticallyLoadedPackage(*it);
3309 if (t.cs() == "subfloat") {
3310 // the syntax is \subfloat[list entry][sub caption]{content}
3311 // if it is a table of figure depends on the surrounding float
3313 // do nothing if there is no outer float
3314 if (!float_type.empty()) {
3315 context.check_layout(os);
3317 begin_inset(os, "Float " + float_type + "\n");
3319 << "\nsideways false"
3320 << "\nstatus collapsed\n\n";
3323 bool has_caption = false;
3324 if (p.next_token().cat() != catEscape &&
3325 p.next_token().character() == '[') {
3326 p.get_token(); // eat '['
3327 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3330 // In case we have two optional args, the second is the caption.
3331 if (p.next_token().cat() != catEscape &&
3332 p.next_token().character() == '[') {
3333 p.get_token(); // eat '['
3334 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3337 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3338 // the caption comes always as the last
3340 // we must make sure that the caption gets a \begin_layout
3341 os << "\n\\begin_layout Plain Layout";
3343 begin_inset(os, "Caption Standard\n");
3344 Context newcontext(true, context.textclass,
3345 0, 0, context.font);
3346 newcontext.check_layout(os);
3347 os << caption << "\n";
3348 newcontext.check_end_layout(os);
3351 // close the layout we opened
3352 os << "\n\\end_layout";
3357 // if the float type is not supported or there is no surrounding float
3362 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3364 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3366 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3367 + "{" + p.verbatim_item() + '}', context);
3372 if (t.cs() == "xymatrix") {
3373 // we must open a new math because LyX's xy support is in math
3374 context.check_layout(os);
3375 begin_inset(os, "Formula ");
3377 os << "\\" << t.cs() << '{';
3378 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3381 preamble.registerAutomaticallyLoadedPackage("xy");
3385 if (t.cs() == "includegraphics") {
3386 bool const clip = p.next_token().asInput() == "*";
3389 string const arg = p.getArg('[', ']');
3390 map<string, string> opts;
3391 vector<string> keys;
3392 split_map(arg, opts, keys);
3394 opts["clip"] = string();
3395 string name = normalize_filename(p.verbatim_item());
3397 string const path = getMasterFilePath(true);
3398 // We want to preserve relative / absolute filenames,
3399 // therefore path is only used for testing
3400 if (!makeAbsPath(name, path).exists()) {
3401 // The file extension is probably missing.
3402 // Now try to find it out.
3403 string const dvips_name =
3404 find_file(name, path,
3405 known_dvips_graphics_formats);
3406 string const pdftex_name =
3407 find_file(name, path,
3408 known_pdftex_graphics_formats);
3409 if (!dvips_name.empty()) {
3410 if (!pdftex_name.empty()) {
3411 cerr << "This file contains the "
3413 "\"\\includegraphics{"
3415 "However, files\n\""
3416 << dvips_name << "\" and\n\""
3417 << pdftex_name << "\"\n"
3418 "both exist, so I had to make a "
3419 "choice and took the first one.\n"
3420 "Please move the unwanted one "
3421 "someplace else and try again\n"
3422 "if my choice was wrong."
3426 } else if (!pdftex_name.empty()) {
3432 FileName const absname = makeAbsPath(name, path);
3433 if (absname.exists()) {
3434 fix_child_filename(name);
3435 copy_file(absname, name);
3437 cerr << "Warning: Could not find graphics file '"
3438 << name << "'." << endl;
3440 context.check_layout(os);
3441 begin_inset(os, "Graphics ");
3442 os << "\n\tfilename " << name << '\n';
3443 if (opts.find("width") != opts.end())
3445 << translate_len(opts["width"]) << '\n';
3446 if (opts.find("height") != opts.end())
3448 << translate_len(opts["height"]) << '\n';
3449 if (opts.find("scale") != opts.end()) {
3450 istringstream iss(opts["scale"]);
3454 os << "\tscale " << val << '\n';
3456 if (opts.find("angle") != opts.end()) {
3457 os << "\trotateAngle "
3458 << opts["angle"] << '\n';
3459 vector<string>::const_iterator a =
3460 find(keys.begin(), keys.end(), "angle");
3461 vector<string>::const_iterator s =
3462 find(keys.begin(), keys.end(), "width");
3463 if (s == keys.end())
3464 s = find(keys.begin(), keys.end(), "height");
3465 if (s == keys.end())
3466 s = find(keys.begin(), keys.end(), "scale");
3467 if (s != keys.end() && distance(s, a) > 0)
3468 os << "\tscaleBeforeRotation\n";
3470 if (opts.find("origin") != opts.end()) {
3472 string const opt = opts["origin"];
3473 if (opt.find('l') != string::npos) ss << "left";
3474 if (opt.find('r') != string::npos) ss << "right";
3475 if (opt.find('c') != string::npos) ss << "center";
3476 if (opt.find('t') != string::npos) ss << "Top";
3477 if (opt.find('b') != string::npos) ss << "Bottom";
3478 if (opt.find('B') != string::npos) ss << "Baseline";
3479 if (!ss.str().empty())
3480 os << "\trotateOrigin " << ss.str() << '\n';
3482 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3484 if (opts.find("keepaspectratio") != opts.end())
3485 os << "\tkeepAspectRatio\n";
3486 if (opts.find("clip") != opts.end())
3488 if (opts.find("draft") != opts.end())
3490 if (opts.find("bb") != opts.end())
3491 os << "\tBoundingBox "
3492 << opts["bb"] << '\n';
3493 int numberOfbbOptions = 0;
3494 if (opts.find("bbllx") != opts.end())
3495 numberOfbbOptions++;
3496 if (opts.find("bblly") != opts.end())
3497 numberOfbbOptions++;
3498 if (opts.find("bburx") != opts.end())
3499 numberOfbbOptions++;
3500 if (opts.find("bbury") != opts.end())
3501 numberOfbbOptions++;
3502 if (numberOfbbOptions == 4)
3503 os << "\tBoundingBox "
3504 << opts["bbllx"] << " " << opts["bblly"] << " "
3505 << opts["bburx"] << " " << opts["bbury"] << '\n';
3506 else if (numberOfbbOptions > 0)
3507 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3508 numberOfbbOptions = 0;
3509 if (opts.find("natwidth") != opts.end())
3510 numberOfbbOptions++;
3511 if (opts.find("natheight") != opts.end())
3512 numberOfbbOptions++;
3513 if (numberOfbbOptions == 2)
3514 os << "\tBoundingBox 0bp 0bp "
3515 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3516 else if (numberOfbbOptions > 0)
3517 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3518 ostringstream special;
3519 if (opts.find("hiresbb") != opts.end())
3520 special << "hiresbb,";
3521 if (opts.find("trim") != opts.end())
3523 if (opts.find("viewport") != opts.end())
3524 special << "viewport=" << opts["viewport"] << ',';
3525 if (opts.find("totalheight") != opts.end())
3526 special << "totalheight=" << opts["totalheight"] << ',';
3527 if (opts.find("type") != opts.end())
3528 special << "type=" << opts["type"] << ',';
3529 if (opts.find("ext") != opts.end())
3530 special << "ext=" << opts["ext"] << ',';
3531 if (opts.find("read") != opts.end())
3532 special << "read=" << opts["read"] << ',';
3533 if (opts.find("command") != opts.end())
3534 special << "command=" << opts["command"] << ',';
3535 string s_special = special.str();
3536 if (!s_special.empty()) {
3537 // We had special arguments. Remove the trailing ','.
3538 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3540 // TODO: Handle the unknown settings better.
3541 // Warn about invalid options.
3542 // Check whether some option was given twice.
3544 preamble.registerAutomaticallyLoadedPackage("graphicx");
3548 if (t.cs() == "footnote" ||
3549 (t.cs() == "thanks" && context.layout->intitle)) {
3551 context.check_layout(os);
3552 begin_inset(os, "Foot\n");
3553 os << "status collapsed\n\n";
3554 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3559 if (t.cs() == "marginpar") {
3561 context.check_layout(os);
3562 begin_inset(os, "Marginal\n");
3563 os << "status collapsed\n\n";
3564 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3569 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3570 bool const use_minted = t.cs() == "mintinline";
3572 parse_listings(p, os, context, true, use_minted);
3576 if (t.cs() == "ensuremath") {
3578 context.check_layout(os);
3579 string const s = p.verbatim_item();
3580 //FIXME: this never triggers in UTF8
3581 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3584 output_ert_inset(os, "\\ensuremath{" + s + "}",
3589 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3590 if (preamble.titleLayoutFound()) {
3592 skip_spaces_braces(p);
3594 output_ert_inset(os, t.asInput(), context);
3598 if (t.cs() == "tableofcontents"
3599 || t.cs() == "lstlistoflistings"
3600 || t.cs() == "listoflistings") {
3601 string name = t.cs();
3602 if (preamble.minted() && name == "listoflistings")
3603 name.insert(0, "lst");
3604 context.check_layout(os);
3605 begin_command_inset(os, "toc", name);
3607 skip_spaces_braces(p);
3608 if (name == "lstlistoflistings") {
3609 if (preamble.minted())
3610 preamble.registerAutomaticallyLoadedPackage("minted");
3612 preamble.registerAutomaticallyLoadedPackage("listings");
3617 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3618 context.check_layout(os);
3619 if (t.cs() == "listoffigures")
3620 begin_inset(os, "FloatList figure\n");
3622 begin_inset(os, "FloatList table\n");
3624 skip_spaces_braces(p);
3628 if (t.cs() == "listof") {
3629 p.skip_spaces(true);
3630 string const name = p.get_token().cs();
3631 if (context.textclass.floats().typeExist(name)) {
3632 context.check_layout(os);
3633 begin_inset(os, "FloatList ");
3636 p.get_token(); // swallow second arg
3638 output_ert_inset(os, "\\listof{" + name + "}", context);
3642 if ((where = is_known(t.cs(), known_text_font_families))) {
3643 parse_text_attributes(p, os, FLAG_ITEM, outer,
3644 context, "\\family", context.font.family,
3645 known_coded_font_families[where - known_text_font_families]);
3649 // beamer has a \textbf<overlay>{} inset
3650 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3651 parse_text_attributes(p, os, FLAG_ITEM, outer,
3652 context, "\\series", context.font.series,
3653 known_coded_font_series[where - known_text_font_series]);
3657 // beamer has a \textit<overlay>{} inset
3658 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3659 parse_text_attributes(p, os, FLAG_ITEM, outer,
3660 context, "\\shape", context.font.shape,
3661 known_coded_font_shapes[where - known_text_font_shapes]);
3665 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3666 context.check_layout(os);
3667 TeXFont oldFont = context.font;
3668 context.font.init();
3669 context.font.size = oldFont.size;
3670 os << "\n\\family " << context.font.family << "\n";
3671 os << "\n\\series " << context.font.series << "\n";
3672 os << "\n\\shape " << context.font.shape << "\n";
3673 if (t.cs() == "textnormal") {
3674 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3675 output_font_change(os, context.font, oldFont);
3676 context.font = oldFont;
3678 eat_whitespace(p, os, context, false);
3682 if (t.cs() == "textcolor") {
3683 // scheme is \textcolor{color name}{text}
3684 string const color = p.verbatim_item();
3685 // we support the predefined colors of the color and the xcolor package
3686 if (color == "black" || color == "blue" || color == "cyan"
3687 || color == "green" || color == "magenta" || color == "red"
3688 || color == "white" || color == "yellow") {
3689 context.check_layout(os);
3690 os << "\n\\color " << color << "\n";
3691 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3692 context.check_layout(os);
3693 os << "\n\\color inherit\n";
3694 preamble.registerAutomaticallyLoadedPackage("color");
3695 } else if (color == "brown" || color == "darkgray" || color == "gray"
3696 || color == "lightgray" || color == "lime" || color == "olive"
3697 || color == "orange" || color == "pink" || color == "purple"
3698 || color == "teal" || color == "violet") {
3699 context.check_layout(os);
3700 os << "\n\\color " << color << "\n";
3701 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3702 context.check_layout(os);
3703 os << "\n\\color inherit\n";
3704 preamble.registerAutomaticallyLoadedPackage("xcolor");
3706 // for custom defined colors
3707 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3711 if (t.cs() == "underbar" || t.cs() == "uline") {
3712 // \underbar is not 100% correct (LyX outputs \uline
3713 // of ulem.sty). The difference is that \ulem allows
3714 // line breaks, and \underbar does not.
3715 // Do NOT handle \underline.
3716 // \underbar cuts through y, g, q, p etc.,
3717 // \underline does not.
3718 context.check_layout(os);
3719 os << "\n\\bar under\n";
3720 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3721 context.check_layout(os);
3722 os << "\n\\bar default\n";
3723 preamble.registerAutomaticallyLoadedPackage("ulem");
3727 if (t.cs() == "sout") {
3728 context.check_layout(os);
3729 os << "\n\\strikeout on\n";
3730 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3731 context.check_layout(os);
3732 os << "\n\\strikeout default\n";
3733 preamble.registerAutomaticallyLoadedPackage("ulem");
3737 // beamer has an \emph<overlay>{} inset
3738 if ((t.cs() == "uuline" || t.cs() == "uwave"
3739 || t.cs() == "emph" || t.cs() == "noun"
3740 || t.cs() == "xout") && !p.hasOpt("<")) {
3741 context.check_layout(os);
3742 os << "\n\\" << t.cs() << " on\n";
3743 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3744 context.check_layout(os);
3745 os << "\n\\" << t.cs() << " default\n";
3746 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3747 preamble.registerAutomaticallyLoadedPackage("ulem");
3751 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3752 context.check_layout(os);
3753 string name = p.getArg('{', '}');
3754 string localtime = p.getArg('{', '}');
3755 preamble.registerAuthor(name);
3756 Author const & author = preamble.getAuthor(name);
3757 // from_asctime_utc() will fail if LyX decides to output the
3758 // time in the text language.
3759 time_t ptime = from_asctime_utc(localtime);
3760 if (ptime == static_cast<time_t>(-1)) {
3761 cerr << "Warning: Could not parse time `" << localtime
3762 << "´ for change tracking, using current time instead.\n";
3763 ptime = current_time();
3765 if (t.cs() == "lyxadded")
3766 os << "\n\\change_inserted ";
3768 os << "\n\\change_deleted ";
3769 os << author.bufferId() << ' ' << ptime << '\n';
3770 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3771 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3772 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3773 LaTeXPackages::isAvailable("xcolor");
3774 // No need to test for luatex, since luatex comes in
3775 // two flavours (dvi and pdf), like latex, and those
3776 // are detected by pdflatex.
3777 if (pdflatex || xetex) {
3779 preamble.registerAutomaticallyLoadedPackage("ulem");
3780 preamble.registerAutomaticallyLoadedPackage("xcolor");
3781 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3785 preamble.registerAutomaticallyLoadedPackage("dvipost");
3786 } else if (xcolorulem) {
3787 preamble.registerAutomaticallyLoadedPackage("ulem");
3788 preamble.registerAutomaticallyLoadedPackage("xcolor");
3794 if (t.cs() == "textipa") {
3795 context.check_layout(os);
3796 begin_inset(os, "IPA\n");
3797 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3798 context.merging_hyphens_allowed = false;
3799 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3800 context.merging_hyphens_allowed = merging_hyphens_allowed;
3802 preamble.registerAutomaticallyLoadedPackage("tipa");
3803 preamble.registerAutomaticallyLoadedPackage("tipx");
3807 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3808 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3809 context.check_layout(os);
3813 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3814 begin_inset(os, "IPADeco " + type + "\n");
3815 os << "status open\n";
3816 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3822 if (t.cs() == "textvertline") {
3823 // FIXME: This is not correct, \textvertline is higher than |
3829 if (t.cs() == "tone" ) {
3830 context.check_layout(os);
3831 // register the tone package
3832 preamble.registerAutomaticallyLoadedPackage("tone");
3833 string content = trimSpaceAndEol(p.verbatim_item());
3834 string command = t.asInput() + "{" + content + "}";
3835 // some tones can be detected by unicodesymbols, some need special code
3836 if (is_known(content, known_tones)) {
3837 os << "\\IPAChar " << command << "\n";
3840 // try to see whether the string is in unicodesymbols
3844 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3845 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3846 termination, rem, &req);
3850 output_ert_inset(os, to_utf8(rem), context);
3851 for (set<string>::const_iterator it = req.begin();
3852 it != req.end(); ++it)
3853 preamble.registerAutomaticallyLoadedPackage(*it);
3855 // we did not find a non-ert version
3856 output_ert_inset(os, command, context);
3860 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3861 t.cs() == "vphantom") {
3862 context.check_layout(os);
3863 if (t.cs() == "phantom")
3864 begin_inset(os, "Phantom Phantom\n");
3865 if (t.cs() == "hphantom")
3866 begin_inset(os, "Phantom HPhantom\n");
3867 if (t.cs() == "vphantom")
3868 begin_inset(os, "Phantom VPhantom\n");
3869 os << "status open\n";
3870 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3876 if (t.cs() == "href") {
3877 context.check_layout(os);
3878 string target = convert_literate_command_inset_arg(p.verbatim_item());
3879 string name = p.verbatim_item();
3880 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3881 bool const literal = !nm.first;
3882 name = literal ? subst(name, "\n", " ") : nm.second;
3883 string lit = literal ? "\"true\"" : "\"false\"";
3885 size_t i = target.find(':');
3886 if (i != string::npos) {
3887 type = target.substr(0, i + 1);
3888 if (type == "mailto:" || type == "file:")
3889 target = target.substr(i + 1);
3890 // handle the case that name is equal to target, except of "http(s)://"
3891 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3894 begin_command_inset(os, "href", "href");
3896 os << "name \"" << name << "\"\n";
3897 os << "target \"" << target << "\"\n";
3898 if (type == "mailto:" || type == "file:")
3899 os << "type \"" << type << "\"\n";
3900 os << "literal " << lit << "\n";
3902 skip_spaces_braces(p);
3906 if (t.cs() == "lyxline") {
3907 // swallow size argument (it is not used anyway)
3909 if (!context.atParagraphStart()) {
3910 // so our line is in the middle of a paragraph
3911 // we need to add a new line, lest this line
3912 // follow the other content on that line and
3913 // run off the side of the page
3914 // FIXME: This may create an empty paragraph,
3915 // but without that it would not be
3916 // possible to set noindent below.
3917 // Fortunately LaTeX does not care
3918 // about the empty paragraph.
3919 context.new_paragraph(os);
3921 if (preamble.indentParagraphs()) {
3922 // we need to unindent, lest the line be too long
3923 context.add_par_extra_stuff("\\noindent\n");
3925 context.check_layout(os);
3926 begin_command_inset(os, "line", "rule");
3927 os << "offset \"0.5ex\"\n"
3928 "width \"100line%\"\n"
3934 if (t.cs() == "rule") {
3935 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3936 string const width = p.getArg('{', '}');
3937 string const thickness = p.getArg('{', '}');
3938 context.check_layout(os);
3939 begin_command_inset(os, "line", "rule");
3940 if (!offset.empty())
3941 os << "offset \"" << translate_len(offset) << "\"\n";
3942 os << "width \"" << translate_len(width) << "\"\n"
3943 "height \"" << translate_len(thickness) << "\"\n";
3948 // handle refstyle first to catch \eqref which can also occur
3949 // without refstyle. Only recognize these commands if
3950 // refstyle.sty was found in the preamble (otherwise \eqref
3951 // and user defined ref commands could be misdetected).
3952 if ((where = is_known(t.cs(), known_refstyle_commands))
3953 && preamble.refstyle()) {
3954 context.check_layout(os);
3955 begin_command_inset(os, "ref", "formatted");
3956 os << "reference \"";
3957 os << known_refstyle_prefixes[where - known_refstyle_commands]
3959 os << convert_literate_command_inset_arg(p.verbatim_item())
3961 os << "plural \"false\"\n";
3962 os << "caps \"false\"\n";
3963 os << "noprefix \"false\"\n";
3965 preamble.registerAutomaticallyLoadedPackage("refstyle");
3969 // if refstyle is used, we must not convert \prettyref to a
3970 // formatted reference, since that would result in a refstyle command.
3971 if ((where = is_known(t.cs(), known_ref_commands)) &&
3972 (t.cs() != "prettyref" || !preamble.refstyle())) {
3973 string const opt = p.getOpt();
3975 context.check_layout(os);
3976 begin_command_inset(os, "ref",
3977 known_coded_ref_commands[where - known_ref_commands]);
3978 os << "reference \""
3979 << convert_literate_command_inset_arg(p.verbatim_item())
3981 os << "plural \"false\"\n";
3982 os << "caps \"false\"\n";
3983 os << "noprefix \"false\"\n";
3985 if (t.cs() == "vref" || t.cs() == "vpageref")
3986 preamble.registerAutomaticallyLoadedPackage("varioref");
3987 else if (t.cs() == "prettyref")
3988 preamble.registerAutomaticallyLoadedPackage("prettyref");
3990 // LyX does not yet support optional arguments of ref commands
3991 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3992 p.verbatim_item() + '}', context);
3998 is_known(t.cs(), known_natbib_commands) &&
3999 ((t.cs() != "citefullauthor" &&
4000 t.cs() != "citeyear" &&
4001 t.cs() != "citeyearpar") ||
4002 p.next_token().asInput() != "*")) {
4003 context.check_layout(os);
4004 string command = t.cs();
4005 if (p.next_token().asInput() == "*") {
4009 if (command == "citefullauthor")
4010 // alternative name for "\\citeauthor*"
4011 command = "citeauthor*";
4013 // text before the citation
4015 // text after the citation
4017 get_cite_arguments(p, true, before, after);
4019 if (command == "cite") {
4020 // \cite without optional argument means
4021 // \citet, \cite with at least one optional
4022 // argument means \citep.
4023 if (before.empty() && after.empty())
4028 if (before.empty() && after == "[]")
4029 // avoid \citet[]{a}
4031 else if (before == "[]" && after == "[]") {
4032 // avoid \citet[][]{a}
4036 bool literal = false;
4037 pair<bool, string> aft;
4038 pair<bool, string> bef;
4039 // remove the brackets around after and before
4040 if (!after.empty()) {
4042 after.erase(after.length() - 1, 1);
4043 aft = convert_latexed_command_inset_arg(after);
4044 literal = !aft.first;
4045 after = literal ? subst(after, "\n", " ") : aft.second;
4047 if (!before.empty()) {
4049 before.erase(before.length() - 1, 1);
4050 bef = convert_latexed_command_inset_arg(before);
4051 literal |= !bef.first;
4052 before = literal ? subst(before, "\n", " ") : bef.second;
4053 if (literal && !after.empty())
4054 after = subst(after, "\n", " ");
4056 string lit = literal ? "\"true\"" : "\"false\"";
4057 begin_command_inset(os, "citation", command);
4058 os << "after " << '"' << after << '"' << "\n";
4059 os << "before " << '"' << before << '"' << "\n";
4061 << convert_literate_command_inset_arg(p.verbatim_item())
4063 << "literal " << lit << "\n";
4065 // Need to set the cite engine if natbib is loaded by
4066 // the document class directly
4067 if (preamble.citeEngine() == "basic")
4068 preamble.citeEngine("natbib");
4073 && is_known(t.cs(), known_biblatex_commands)
4074 && ((t.cs() == "cite"
4075 || t.cs() == "citeauthor"
4076 || t.cs() == "Citeauthor"
4077 || t.cs() == "parencite"
4078 || t.cs() == "citetitle")
4079 || p.next_token().asInput() != "*"))
4080 || (use_biblatex_natbib
4081 && (is_known(t.cs(), known_biblatex_commands)
4082 || is_known(t.cs(), known_natbib_commands))
4083 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4084 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4085 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4086 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4087 || t.cs() == "parencite" || t.cs() == "citetitle")
4088 || p.next_token().asInput() != "*"))){
4089 context.check_layout(os);
4090 string command = t.cs();
4091 if (p.next_token().asInput() == "*") {
4096 bool const qualified = suffixIs(command, "s");
4098 command = rtrim(command, "s");
4100 // text before the citation
4102 // text after the citation
4104 get_cite_arguments(p, true, before, after, qualified);
4106 // These use natbib cmd names in LyX
4107 // for inter-citeengine compativility
4108 if (command == "citeyear")
4109 command = "citebyear";
4110 else if (command == "cite*")
4111 command = "citeyear";
4112 else if (command == "textcite")
4114 else if (command == "Textcite")
4116 else if (command == "parencite")
4118 else if (command == "Parencite")
4120 else if (command == "parencite*")
4121 command = "citeyearpar";
4122 else if (command == "smartcite")
4123 command = "footcite";
4124 else if (command == "Smartcite")
4125 command = "Footcite";
4127 string const emptyarg = qualified ? "()" : "[]";
4128 if (before.empty() && after == emptyarg)
4131 else if (before == emptyarg && after == emptyarg) {
4132 // avoid \cite[][]{a}
4136 bool literal = false;
4137 pair<bool, string> aft;
4138 pair<bool, string> bef;
4139 // remove the brackets around after and before
4140 if (!after.empty()) {
4142 after.erase(after.length() - 1, 1);
4143 aft = convert_latexed_command_inset_arg(after);
4144 literal = !aft.first;
4145 after = literal ? subst(after, "\n", " ") : aft.second;
4147 if (!before.empty()) {
4149 before.erase(before.length() - 1, 1);
4150 bef = convert_latexed_command_inset_arg(before);
4151 literal |= !bef.first;
4152 before = literal ? subst(before, "\n", " ") : bef.second;
4154 string keys, pretextlist, posttextlist;
4156 map<string, string> pres, posts, preslit, postslit;
4157 vector<string> lkeys;
4158 // text before the citation
4159 string lbefore, lbeforelit;
4160 // text after the citation
4161 string lafter, lafterlit;
4163 pair<bool, string> laft, lbef;
4165 get_cite_arguments(p, true, lbefore, lafter);
4166 // remove the brackets around after and before
4167 if (!lafter.empty()) {
4169 lafter.erase(lafter.length() - 1, 1);
4170 laft = convert_latexed_command_inset_arg(lafter);
4171 literal |= !laft.first;
4172 lafter = laft.second;
4173 lafterlit = subst(lbefore, "\n", " ");
4175 if (!lbefore.empty()) {
4176 lbefore.erase(0, 1);
4177 lbefore.erase(lbefore.length() - 1, 1);
4178 lbef = convert_latexed_command_inset_arg(lbefore);
4179 literal |= !lbef.first;
4180 lbefore = lbef.second;
4181 lbeforelit = subst(lbefore, "\n", " ");
4183 if (lbefore.empty() && lafter == "[]") {
4188 else if (lbefore == "[]" && lafter == "[]") {
4189 // avoid \cite[][]{a}
4195 lkey = p.getArg('{', '}');
4198 if (!lbefore.empty()) {
4199 pres.insert(make_pair(lkey, lbefore));
4200 preslit.insert(make_pair(lkey, lbeforelit));
4202 if (!lafter.empty()) {
4203 posts.insert(make_pair(lkey, lafter));
4204 postslit.insert(make_pair(lkey, lafterlit));
4206 lkeys.push_back(lkey);
4208 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4213 for (auto const & ptl : pres) {
4214 if (!pretextlist.empty())
4215 pretextlist += '\t';
4216 pretextlist += ptl.first + " " + ptl.second;
4218 for (auto const & potl : posts) {
4219 if (!posttextlist.empty())
4220 posttextlist += '\t';
4221 posttextlist += potl.first + " " + potl.second;
4224 keys = convert_literate_command_inset_arg(p.verbatim_item());
4227 after = subst(after, "\n", " ");
4228 if (!before.empty())
4229 before = subst(after, "\n", " ");
4231 string lit = literal ? "\"true\"" : "\"false\"";
4232 begin_command_inset(os, "citation", command);
4233 os << "after " << '"' << after << '"' << "\n";
4234 os << "before " << '"' << before << '"' << "\n";
4238 if (!pretextlist.empty())
4239 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4240 if (!posttextlist.empty())
4241 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4242 os << "literal " << lit << "\n";
4244 // Need to set the cite engine if biblatex is loaded by
4245 // the document class directly
4246 if (preamble.citeEngine() == "basic")
4247 use_biblatex_natbib ?
4248 preamble.citeEngine("biblatex-natbib")
4249 : preamble.citeEngine("biblatex");
4254 is_known(t.cs(), known_jurabib_commands) &&
4255 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4256 context.check_layout(os);
4257 string command = t.cs();
4258 if (p.next_token().asInput() == "*") {
4262 char argumentOrder = '\0';
4263 vector<string> const options =
4264 preamble.getPackageOptions("jurabib");
4265 if (find(options.begin(), options.end(),
4266 "natbiborder") != options.end())
4267 argumentOrder = 'n';
4268 else if (find(options.begin(), options.end(),
4269 "jurabiborder") != options.end())
4270 argumentOrder = 'j';
4272 // text before the citation
4274 // text after the citation
4276 get_cite_arguments(p, argumentOrder != 'j', before, after);
4278 string const citation = p.verbatim_item();
4279 if (!before.empty() && argumentOrder == '\0') {
4280 cerr << "Warning: Assuming argument order "
4281 "of jurabib version 0.6 for\n'"
4282 << command << before << after << '{'
4283 << citation << "}'.\n"
4284 "Add 'jurabiborder' to the jurabib "
4285 "package options if you used an\n"
4286 "earlier jurabib version." << endl;
4288 bool literal = false;
4289 pair<bool, string> aft;
4290 pair<bool, string> bef;
4291 // remove the brackets around after and before
4292 if (!after.empty()) {
4294 after.erase(after.length() - 1, 1);
4295 aft = convert_latexed_command_inset_arg(after);
4296 literal = !aft.first;
4297 after = literal ? subst(after, "\n", " ") : aft.second;
4299 if (!before.empty()) {
4301 before.erase(before.length() - 1, 1);
4302 bef = convert_latexed_command_inset_arg(before);
4303 literal |= !bef.first;
4304 before = literal ? subst(before, "\n", " ") : bef.second;
4305 if (literal && !after.empty())
4306 after = subst(after, "\n", " ");
4308 string lit = literal ? "\"true\"" : "\"false\"";
4309 begin_command_inset(os, "citation", command);
4310 os << "after " << '"' << after << "\"\n"
4311 << "before " << '"' << before << "\"\n"
4312 << "key " << '"' << citation << "\"\n"
4313 << "literal " << lit << "\n";
4315 // Need to set the cite engine if jurabib is loaded by
4316 // the document class directly
4317 if (preamble.citeEngine() == "basic")
4318 preamble.citeEngine("jurabib");
4322 if (t.cs() == "cite"
4323 || t.cs() == "nocite") {
4324 context.check_layout(os);
4325 string after = p.getArg('[', ']');
4326 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4327 bool const literal = !aft.first;
4328 after = literal ? subst(after, "\n", " ") : aft.second;
4329 string lit = literal ? "\"true\"" : "\"false\"";
4330 string key = convert_literate_command_inset_arg(p.verbatim_item());
4331 // store the case that it is "\nocite{*}" to use it later for
4334 begin_command_inset(os, "citation", t.cs());
4335 os << "after " << '"' << after << "\"\n"
4336 << "key " << '"' << key << "\"\n"
4337 << "literal " << lit << "\n";
4339 } else if (t.cs() == "nocite")
4344 if (t.cs() == "index" ||
4345 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4346 context.check_layout(os);
4347 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4348 p.getArg('[', ']') : "";
4349 string const kind = arg.empty() ? "idx" : arg;
4350 begin_inset(os, "Index ");
4351 os << kind << "\nstatus collapsed\n";
4352 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4355 preamble.registerAutomaticallyLoadedPackage("splitidx");
4359 if (t.cs() == "nomenclature") {
4360 context.check_layout(os);
4361 begin_command_inset(os, "nomenclature", "nomenclature");
4362 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4363 if (!prefix.empty())
4364 os << "prefix " << '"' << prefix << '"' << "\n";
4365 string symbol = p.verbatim_item();
4366 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4367 bool literal = !sym.first;
4368 string description = p.verbatim_item();
4369 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4370 literal |= !desc.first;
4372 symbol = subst(symbol, "\n", " ");
4373 description = subst(description, "\n", " ");
4375 symbol = sym.second;
4376 description = desc.second;
4378 string lit = literal ? "\"true\"" : "\"false\"";
4379 os << "symbol " << '"' << symbol;
4380 os << "\"\ndescription \""
4381 << description << "\"\n"
4382 << "literal " << lit << "\n";
4384 preamble.registerAutomaticallyLoadedPackage("nomencl");
4388 if (t.cs() == "label") {
4389 context.check_layout(os);
4390 begin_command_inset(os, "label", "label");
4392 << convert_literate_command_inset_arg(p.verbatim_item())
4398 if (t.cs() == "lyxmintcaption") {
4399 string const pos = p.getArg('[', ']');
4401 string const caption =
4402 parse_text_snippet(p, FLAG_ITEM, false,
4404 minted_nonfloat_caption = "[t]" + caption;
4406 // We already got the caption at the bottom,
4407 // so simply skip it.
4408 parse_text_snippet(p, FLAG_ITEM, false, context);
4413 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4414 context.check_layout(os);
4415 string commandname = t.cs();
4417 if (p.next_token().asInput() == "*") {
4422 begin_command_inset(os, "index_print", commandname);
4423 string const indexname = p.getArg('[', ']');
4425 if (indexname.empty())
4426 os << "type \"idx\"\n";
4428 os << "type \"" << indexname << "\"\n";
4429 os << "literal \"true\"\n";
4432 skip_spaces_braces(p);
4433 preamble.registerAutomaticallyLoadedPackage("makeidx");
4434 if (preamble.use_indices() == "true")
4435 preamble.registerAutomaticallyLoadedPackage("splitidx");
4439 if (t.cs() == "printnomenclature") {
4441 string width_type = "";
4442 context.check_layout(os);
4443 begin_command_inset(os, "nomencl_print", "printnomenclature");
4444 // case of a custom width
4446 width = p.getArg('[', ']');
4447 width = translate_len(width);
4448 width_type = "custom";
4450 // case of no custom width
4451 // the case of no custom width but the width set
4452 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4453 // because the user could have set anything, not only the width
4454 // of the longest label (which would be width_type = "auto")
4455 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4456 if (label.empty() && width_type.empty())
4457 width_type = "none";
4458 os << "set_width \"" << width_type << "\"\n";
4459 if (width_type == "custom")
4460 os << "width \"" << width << '\"';
4462 skip_spaces_braces(p);
4463 preamble.registerAutomaticallyLoadedPackage("nomencl");
4467 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4468 context.check_layout(os);
4469 begin_inset(os, "script ");
4470 os << t.cs().substr(4) << '\n';
4471 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4472 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4474 if (t.cs() == "textsubscript")
4475 preamble.registerAutomaticallyLoadedPackage("subscript");
4479 if ((where = is_known(t.cs(), known_quotes))) {
4480 context.check_layout(os);
4481 begin_inset(os, "Quotes ");
4482 string quotetype = known_coded_quotes[where - known_quotes];
4483 // try to make a smart guess about the side
4484 Token const prev = p.prev_token();
4485 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4486 && prev.character() != '\n' && prev.character() != '~');
4487 quotetype = guessQuoteStyle(quotetype, opening);
4490 // LyX adds {} after the quote, so we have to eat
4491 // spaces here if there are any before a possible
4493 eat_whitespace(p, os, context, false);
4498 if ((where = is_known(t.cs(), known_sizes)) &&
4499 context.new_layout_allowed) {
4500 context.check_layout(os);
4501 TeXFont const oldFont = context.font;
4502 context.font.size = known_coded_sizes[where - known_sizes];
4503 output_font_change(os, oldFont, context.font);
4504 eat_whitespace(p, os, context, false);
4508 if ((where = is_known(t.cs(), known_font_families)) &&
4509 context.new_layout_allowed) {
4510 context.check_layout(os);
4511 TeXFont const oldFont = context.font;
4512 context.font.family =
4513 known_coded_font_families[where - known_font_families];
4514 output_font_change(os, oldFont, context.font);
4515 eat_whitespace(p, os, context, false);
4519 if ((where = is_known(t.cs(), known_font_series)) &&
4520 context.new_layout_allowed) {
4521 context.check_layout(os);
4522 TeXFont const oldFont = context.font;
4523 context.font.series =
4524 known_coded_font_series[where - known_font_series];
4525 output_font_change(os, oldFont, context.font);
4526 eat_whitespace(p, os, context, false);
4530 if ((where = is_known(t.cs(), known_font_shapes)) &&
4531 context.new_layout_allowed) {
4532 context.check_layout(os);
4533 TeXFont const oldFont = context.font;
4534 context.font.shape =
4535 known_coded_font_shapes[where - known_font_shapes];
4536 output_font_change(os, oldFont, context.font);
4537 eat_whitespace(p, os, context, false);
4540 if ((where = is_known(t.cs(), known_old_font_families)) &&
4541 context.new_layout_allowed) {
4542 context.check_layout(os);
4543 TeXFont const oldFont = context.font;
4544 context.font.init();
4545 context.font.size = oldFont.size;
4546 context.font.family =
4547 known_coded_font_families[where - known_old_font_families];
4548 output_font_change(os, oldFont, context.font);
4549 eat_whitespace(p, os, context, false);
4553 if ((where = is_known(t.cs(), known_old_font_series)) &&
4554 context.new_layout_allowed) {
4555 context.check_layout(os);
4556 TeXFont const oldFont = context.font;
4557 context.font.init();
4558 context.font.size = oldFont.size;
4559 context.font.series =
4560 known_coded_font_series[where - known_old_font_series];
4561 output_font_change(os, oldFont, context.font);
4562 eat_whitespace(p, os, context, false);
4566 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4567 context.new_layout_allowed) {
4568 context.check_layout(os);
4569 TeXFont const oldFont = context.font;
4570 context.font.init();
4571 context.font.size = oldFont.size;
4572 context.font.shape =
4573 known_coded_font_shapes[where - known_old_font_shapes];
4574 output_font_change(os, oldFont, context.font);
4575 eat_whitespace(p, os, context, false);
4579 if (t.cs() == "selectlanguage") {
4580 context.check_layout(os);
4581 // save the language for the case that a
4582 // \foreignlanguage is used
4583 context.font.language = babel2lyx(p.verbatim_item());
4584 os << "\n\\lang " << context.font.language << "\n";
4588 if (t.cs() == "foreignlanguage") {
4589 string const lang = babel2lyx(p.verbatim_item());
4590 parse_text_attributes(p, os, FLAG_ITEM, outer,
4592 context.font.language, lang);
4596 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4597 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4598 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4600 // We have to output the whole command if it has an option
4601 // because LyX doesn't support this yet, see bug #8214,
4602 // only if there is a single option specifying a variant, we can handle it.
4604 string langopts = p.getOpt();
4605 // check if the option contains a variant, if yes, extract it
4606 string::size_type pos_var = langopts.find("variant");
4607 string::size_type i = langopts.find(',');
4608 string::size_type k = langopts.find('=', pos_var);
4609 if (pos_var != string::npos && i == string::npos) {
4611 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4612 lang = preamble.polyglossia2lyx(variant);
4613 parse_text_attributes(p, os, FLAG_ITEM, outer,
4615 context.font.language, lang);
4617 output_ert_inset(os, t.asInput() + langopts, context);
4619 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4620 parse_text_attributes(p, os, FLAG_ITEM, outer,
4622 context.font.language, lang);
4627 if (t.cs() == "inputencoding") {
4628 // nothing to write here
4629 string const enc = subst(p.verbatim_item(), "\n", " ");
4630 p.setEncoding(enc, Encoding::inputenc);
4634 if (is_known(t.cs(), known_special_chars) ||
4635 (t.cs() == "protect" &&
4636 p.next_token().cat() == catEscape &&
4637 is_known(p.next_token().cs(), known_special_protect_chars))) {
4638 // LyX sometimes puts a \protect in front, so we have to ignore it
4640 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4641 known_special_chars);
4642 context.check_layout(os);
4643 os << known_coded_special_chars[where - known_special_chars];
4644 skip_spaces_braces(p);
4648 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4649 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4650 p.next_next_token().asInput() == "-") ||
4651 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4652 // LyX sometimes puts a \protect in front, so we have to ignore it
4653 if (t.cs() == "protect")
4655 context.check_layout(os);
4656 if (t.cs() == "nobreakdash")
4657 os << "\\SpecialChar nobreakdash\n";
4659 os << "\\SpecialChar endofsentence\n";
4664 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4665 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4666 || t.cs() == "%" || t.cs() == "-") {
4667 context.check_layout(os);
4669 os << "\\SpecialChar softhyphen\n";
4675 if (t.cs() == "char") {
4676 context.check_layout(os);
4677 if (p.next_token().character() == '`') {
4679 if (p.next_token().cs() == "\"") {
4684 output_ert_inset(os, "\\char`", context);
4687 output_ert_inset(os, "\\char", context);
4692 if (t.cs() == "verb") {
4693 context.check_layout(os);
4694 // set catcodes to verbatim early, just in case.
4695 p.setCatcodes(VERBATIM_CATCODES);
4696 string delim = p.get_token().asInput();
4697 Parser::Arg arg = p.verbatimStuff(delim);
4699 output_ert_inset(os, "\\verb" + delim
4700 + arg.second + delim, context);
4702 cerr << "invalid \\verb command. Skipping" << endl;
4706 // Problem: \= creates a tabstop inside the tabbing environment
4707 // and else an accent. In the latter case we really would want
4708 // \={o} instead of \= o.
4709 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4710 output_ert_inset(os, t.asInput(), context);
4714 if (t.cs() == "\\") {
4715 context.check_layout(os);
4717 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4718 else if (p.next_token().asInput() == "*") {
4720 // getOpt() eats the following space if there
4721 // is no optional argument, but that is OK
4722 // here since it has no effect in the output.
4723 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4726 begin_inset(os, "Newline newline");
4732 if (t.cs() == "newline" ||
4733 (t.cs() == "linebreak" && !p.hasOpt())) {
4734 context.check_layout(os);
4735 begin_inset(os, "Newline ");
4738 skip_spaces_braces(p);
4742 if (t.cs() == "input" || t.cs() == "include"
4743 || t.cs() == "verbatiminput"
4744 || t.cs() == "lstinputlisting") {
4745 string name = t.cs();
4746 if (name == "verbatiminput"
4747 && p.next_token().asInput() == "*")
4748 name += p.get_token().asInput();
4749 context.check_layout(os);
4751 bool literal = false;
4752 if (name == "lstinputlisting" && p.hasOpt()) {
4753 lstparams = p.getArg('[', ']');
4754 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4755 literal = !oa.first;
4757 lstparams = subst(lstparams, "\n", " ");
4759 string lit = literal ? "\"true\"" : "\"false\"";
4760 string filename(normalize_filename(p.getArg('{', '}')));
4761 string const path = getMasterFilePath(true);
4762 // We want to preserve relative / absolute filenames,
4763 // therefore path is only used for testing
4764 if ((t.cs() == "include" || t.cs() == "input") &&
4765 !makeAbsPath(filename, path).exists()) {
4766 // The file extension is probably missing.
4767 // Now try to find it out.
4768 string const tex_name =
4769 find_file(filename, path,
4770 known_tex_extensions);
4771 if (!tex_name.empty())
4772 filename = tex_name;
4774 bool external = false;
4776 if (makeAbsPath(filename, path).exists()) {
4777 string const abstexname =
4778 makeAbsPath(filename, path).absFileName();
4779 string const absfigname =
4780 changeExtension(abstexname, ".fig");
4781 fix_child_filename(filename);
4782 string const lyxname = changeExtension(filename,
4783 roundtripMode() ? ".lyx.lyx" : ".lyx");
4784 string const abslyxname = makeAbsPath(
4785 lyxname, getParentFilePath(false)).absFileName();
4787 if (!skipChildren())
4788 external = FileName(absfigname).exists();
4789 if (t.cs() == "input" && !skipChildren()) {
4790 string const ext = getExtension(abstexname);
4792 // Combined PS/LaTeX:
4793 // x.eps, x.pstex_t (old xfig)
4794 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4795 FileName const absepsname(
4796 changeExtension(abstexname, ".eps"));
4797 FileName const abspstexname(
4798 changeExtension(abstexname, ".pstex"));
4799 bool const xfigeps =
4800 (absepsname.exists() ||
4801 abspstexname.exists()) &&
4804 // Combined PDF/LaTeX:
4805 // x.pdf, x.pdftex_t (old xfig)
4806 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4807 FileName const abspdfname(
4808 changeExtension(abstexname, ".pdf"));
4809 bool const xfigpdf =
4810 abspdfname.exists() &&
4811 (ext == "pdftex_t" || ext == "pdf_t");
4815 // Combined PS/PDF/LaTeX:
4816 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4817 string const absbase2(
4818 removeExtension(abstexname) + "_pspdftex");
4819 FileName const abseps2name(
4820 addExtension(absbase2, ".eps"));
4821 FileName const abspdf2name(
4822 addExtension(absbase2, ".pdf"));
4823 bool const xfigboth =
4824 abspdf2name.exists() &&
4825 abseps2name.exists() && ext == "pspdftex";
4827 xfig = xfigpdf || xfigeps || xfigboth;
4828 external = external && xfig;
4831 outname = changeExtension(filename, ".fig");
4832 FileName abssrc(changeExtension(abstexname, ".fig"));
4833 copy_file(abssrc, outname);
4835 // Don't try to convert, the result
4836 // would be full of ERT.
4838 FileName abssrc(abstexname);
4839 copy_file(abssrc, outname);
4840 } else if (t.cs() != "verbatiminput" &&
4842 tex2lyx(abstexname, FileName(abslyxname),
4845 // no need to call copy_file
4846 // tex2lyx creates the file
4849 FileName abssrc(abstexname);
4850 copy_file(abssrc, outname);
4853 cerr << "Warning: Could not find included file '"
4854 << filename << "'." << endl;
4858 begin_inset(os, "External\n");
4859 os << "\ttemplate XFig\n"
4860 << "\tfilename " << outname << '\n';
4861 registerExternalTemplatePackages("XFig");
4863 begin_command_inset(os, "include", name);
4864 outname = subst(outname, "\"", "\\\"");
4865 os << "preview false\n"
4866 "filename \"" << outname << "\"\n";
4867 if (!lstparams.empty())
4868 os << "lstparams \"" << lstparams << "\"\n";
4869 os << "literal " << lit << "\n";
4870 if (t.cs() == "verbatiminput")
4871 preamble.registerAutomaticallyLoadedPackage("verbatim");
4877 if (t.cs() == "bibliographystyle") {
4878 // store new bibliographystyle
4879 bibliographystyle = p.verbatim_item();
4880 // If any other command than \bibliography, \addcontentsline
4881 // and \nocite{*} follows, we need to output the style
4882 // (because it might be used by that command).
4883 // Otherwise, it will automatically be output by LyX.
4886 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4887 if (t2.cat() == catBegin)
4889 if (t2.cat() != catEscape)
4891 if (t2.cs() == "nocite") {
4892 if (p.getArg('{', '}') == "*")
4894 } else if (t2.cs() == "bibliography")
4896 else if (t2.cs() == "phantomsection") {
4900 else if (t2.cs() == "addcontentsline") {
4901 // get the 3 arguments of \addcontentsline
4904 contentslineContent = p.getArg('{', '}');
4905 // if the last argument is not \refname we must output
4906 if (contentslineContent == "\\refname")
4913 output_ert_inset(os,
4914 "\\bibliographystyle{" + bibliographystyle + '}',
4920 if (t.cs() == "phantomsection") {
4921 // we only support this if it occurs between
4922 // \bibliographystyle and \bibliography
4923 if (bibliographystyle.empty())
4924 output_ert_inset(os, "\\phantomsection", context);
4928 if (t.cs() == "addcontentsline") {
4929 context.check_layout(os);
4930 // get the 3 arguments of \addcontentsline
4931 string const one = p.getArg('{', '}');
4932 string const two = p.getArg('{', '}');
4933 string const three = p.getArg('{', '}');
4934 // only if it is a \refname, we support if for the bibtex inset
4935 if (contentslineContent != "\\refname") {
4936 output_ert_inset(os,
4937 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4943 else if (t.cs() == "bibliography") {
4944 context.check_layout(os);
4946 begin_command_inset(os, "bibtex", "bibtex");
4947 if (!btprint.empty()) {
4948 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4949 // clear the string because the next BibTeX inset can be without the
4950 // \nocite{*} option
4953 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4954 // Do we have addcontentsline?
4955 if (contentslineContent == "\\refname") {
4956 BibOpts = "bibtotoc";
4957 // clear string because next BibTeX inset can be without addcontentsline
4958 contentslineContent.clear();
4960 // Do we have a bibliographystyle set?
4961 if (!bibliographystyle.empty()) {
4962 if (BibOpts.empty())
4963 BibOpts = normalize_filename(bibliographystyle);
4965 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4966 // clear it because each bibtex entry has its style
4967 // and we need an empty string to handle \phantomsection
4968 bibliographystyle.clear();
4970 os << "options " << '"' << BibOpts << '"' << "\n";
4975 if (t.cs() == "printbibliography") {
4976 context.check_layout(os);
4978 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4979 vector<string> opts = getVectorFromString(bbloptions);
4980 vector<string>::iterator it =
4981 find(opts.begin(), opts.end(), "heading=bibintoc");
4982 if (it != opts.end()) {
4984 BibOpts = "bibtotoc";
4986 bbloptions = getStringFromVector(opts);
4987 begin_command_inset(os, "bibtex", "bibtex");
4988 if (!btprint.empty()) {
4989 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4990 // clear the string because the next BibTeX inset can be without the
4991 // \nocite{*} option
4995 for (auto const & bf : preamble.biblatex_bibliographies) {
4996 if (!bibfiles.empty())
4998 bibfiles += normalize_filename(bf);
5000 if (!bibfiles.empty())
5001 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5002 // Do we have addcontentsline?
5003 if (contentslineContent == "\\refname") {
5004 BibOpts = "bibtotoc";
5005 // clear string because next BibTeX inset can be without addcontentsline
5006 contentslineContent.clear();
5008 os << "options " << '"' << BibOpts << '"' << "\n";
5009 if (!bbloptions.empty())
5010 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5012 need_commentbib = false;
5016 if (t.cs() == "bibbysection") {
5017 context.check_layout(os);
5019 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5020 vector<string> opts = getVectorFromString(bbloptions);
5021 vector<string>::iterator it =
5022 find(opts.begin(), opts.end(), "heading=bibintoc");
5023 if (it != opts.end()) {
5025 BibOpts = "bibtotoc";
5027 bbloptions = getStringFromVector(opts);
5028 begin_command_inset(os, "bibtex", "bibtex");
5029 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5031 for (auto const & bf : preamble.biblatex_bibliographies) {
5032 if (!bibfiles.empty())
5034 bibfiles += normalize_filename(bf);
5036 if (!bibfiles.empty())
5037 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5038 os << "options " << '"' << BibOpts << '"' << "\n";
5039 if (!bbloptions.empty())
5040 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5042 need_commentbib = false;
5046 if (t.cs() == "parbox") {
5047 // Test whether this is an outer box of a shaded box
5049 // swallow arguments
5050 while (p.hasOpt()) {
5052 p.skip_spaces(true);
5055 p.skip_spaces(true);
5057 if (p.next_token().cat() == catBegin)
5059 p.skip_spaces(true);
5060 Token to = p.get_token();
5061 bool shaded = false;
5062 if (to.asInput() == "\\begin") {
5063 p.skip_spaces(true);
5064 if (p.getArg('{', '}') == "shaded")
5069 parse_outer_box(p, os, FLAG_ITEM, outer,
5070 context, "parbox", "shaded");
5072 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5073 "", "", t.cs(), "", "");
5077 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5078 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5079 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5080 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5084 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5085 string backgroundcolor;
5086 preamble.registerAutomaticallyLoadedPackage("xcolor");
5087 if (t.cs() == "fcolorbox") {
5088 string const framecolor = p.getArg('{', '}');
5089 backgroundcolor = p.getArg('{', '}');
5090 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5092 backgroundcolor = p.getArg('{', '}');
5093 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5098 // FIXME: due to the compiler limit of "if" nestings
5099 // the code for the alignment was put here
5100 // put them in their own if if this is fixed
5101 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5102 || t.cs() == "shadowsize"
5103 || t.cs() == "raggedleft" || t.cs() == "centering"
5104 || t.cs() == "raggedright") {
5105 if (t.cs() == "fboxrule")
5107 if (t.cs() == "fboxsep")
5109 if (t.cs() == "shadowsize")
5111 if (t.cs() != "raggedleft" && t.cs() != "centering"
5112 && t.cs() != "raggedright") {
5113 p.skip_spaces(true);
5114 while (p.good() && p.next_token().cat() != catSpace
5115 && p.next_token().cat() != catNewline
5116 && p.next_token().cat() != catEscape) {
5117 if (t.cs() == "fboxrule")
5118 fboxrule = fboxrule + p.get_token().asInput();
5119 if (t.cs() == "fboxsep")
5120 fboxsep = fboxsep + p.get_token().asInput();
5121 if (t.cs() == "shadowsize")
5122 shadow_size = shadow_size + p.get_token().asInput();
5125 output_ert_inset(os, t.asInput(), context);
5130 //\framebox() is part of the picture environment and different from \framebox{}
5131 //\framebox{} will be parsed by parse_outer_box
5132 if (t.cs() == "framebox") {
5133 if (p.next_token().character() == '(') {
5134 //the syntax is: \framebox(x,y)[position]{content}
5135 string arg = t.asInput();
5136 arg += p.getFullParentheseArg();
5137 arg += p.getFullOpt();
5138 eat_whitespace(p, os, context, false);
5139 output_ert_inset(os, arg + '{', context);
5140 parse_text(p, os, FLAG_ITEM, outer, context);
5141 output_ert_inset(os, "}", context);
5143 //the syntax is: \framebox[width][position]{content}
5144 string special = p.getFullOpt();
5145 special += p.getOpt();
5146 parse_outer_box(p, os, FLAG_ITEM, outer,
5147 context, t.cs(), special);
5152 //\makebox() is part of the picture environment and different from \makebox{}
5153 //\makebox{} will be parsed by parse_box
5154 if (t.cs() == "makebox") {
5155 if (p.next_token().character() == '(') {
5156 //the syntax is: \makebox(x,y)[position]{content}
5157 string arg = t.asInput();
5158 arg += p.getFullParentheseArg();
5159 arg += p.getFullOpt();
5160 eat_whitespace(p, os, context, false);
5161 output_ert_inset(os, arg + '{', context);
5162 parse_text(p, os, FLAG_ITEM, outer, context);
5163 output_ert_inset(os, "}", context);
5165 //the syntax is: \makebox[width][position]{content}
5166 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5167 "", "", t.cs(), "", "");
5171 if (t.cs() == "smallskip" ||
5172 t.cs() == "medskip" ||
5173 t.cs() == "bigskip" ||
5174 t.cs() == "vfill") {
5175 context.check_layout(os);
5176 begin_inset(os, "VSpace ");
5179 skip_spaces_braces(p);
5183 if ((where = is_known(t.cs(), known_spaces))) {
5184 context.check_layout(os);
5185 begin_inset(os, "space ");
5186 os << '\\' << known_coded_spaces[where - known_spaces]
5189 // LaTeX swallows whitespace after all spaces except
5190 // "\\,". We have to do that here, too, because LyX
5191 // adds "{}" which would make the spaces significant.
5193 eat_whitespace(p, os, context, false);
5194 // LyX adds "{}" after all spaces except "\\ " and
5195 // "\\,", so we have to remove "{}".
5196 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5197 // remove the braces after "\\,", too.
5203 if (t.cs() == "newpage" ||
5204 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5205 t.cs() == "clearpage" ||
5206 t.cs() == "cleardoublepage") {
5207 context.check_layout(os);
5208 begin_inset(os, "Newpage ");
5211 skip_spaces_braces(p);
5215 if (t.cs() == "DeclareRobustCommand" ||
5216 t.cs() == "DeclareRobustCommandx" ||
5217 t.cs() == "newcommand" ||
5218 t.cs() == "newcommandx" ||
5219 t.cs() == "providecommand" ||
5220 t.cs() == "providecommandx" ||
5221 t.cs() == "renewcommand" ||
5222 t.cs() == "renewcommandx") {
5223 // DeclareRobustCommand, DeclareRobustCommandx,
5224 // providecommand and providecommandx could be handled
5225 // by parse_command(), but we need to call
5226 // add_known_command() here.
5227 string name = t.asInput();
5228 if (p.next_token().asInput() == "*") {
5229 // Starred form. Eat '*'
5233 string const command = p.verbatim_item();
5234 string const opt1 = p.getFullOpt();
5235 string const opt2 = p.getFullOpt();
5236 add_known_command(command, opt1, !opt2.empty());
5237 string const ert = name + '{' + command + '}' +
5239 '{' + p.verbatim_item() + '}';
5241 if (t.cs() == "DeclareRobustCommand" ||
5242 t.cs() == "DeclareRobustCommandx" ||
5243 t.cs() == "providecommand" ||
5244 t.cs() == "providecommandx" ||
5245 name[name.length()-1] == '*')
5246 output_ert_inset(os, ert, context);
5248 context.check_layout(os);
5249 begin_inset(os, "FormulaMacro");
5256 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5257 // let could be handled by parse_command(),
5258 // but we need to call add_known_command() here.
5259 string ert = t.asInput();
5262 if (p.next_token().cat() == catBegin) {
5263 name = p.verbatim_item();
5264 ert += '{' + name + '}';
5266 name = p.verbatim_item();
5271 if (p.next_token().cat() == catBegin) {
5272 command = p.verbatim_item();
5273 ert += '{' + command + '}';
5275 command = p.verbatim_item();
5278 // If command is known, make name known too, to parse
5279 // its arguments correctly. For this reason we also
5280 // have commands in syntax.default that are hardcoded.
5281 CommandMap::iterator it = known_commands.find(command);
5282 if (it != known_commands.end())
5283 known_commands[t.asInput()] = it->second;
5284 output_ert_inset(os, ert, context);
5288 if (t.cs() == "hspace" || t.cs() == "vspace") {
5291 string name = t.asInput();
5292 string const length = p.verbatim_item();
5295 bool valid = splitLatexLength(length, valstring, unit);
5296 bool known_hspace = false;
5297 bool known_vspace = false;
5298 bool known_unit = false;
5301 istringstream iss(valstring);
5304 if (t.cs()[0] == 'h') {
5305 if (unit == "\\fill") {
5310 known_hspace = true;
5313 if (unit == "\\smallskipamount") {
5315 known_vspace = true;
5316 } else if (unit == "\\medskipamount") {
5318 known_vspace = true;
5319 } else if (unit == "\\bigskipamount") {
5321 known_vspace = true;
5322 } else if (unit == "\\fill") {
5324 known_vspace = true;
5328 if (!known_hspace && !known_vspace) {
5329 switch (unitFromString(unit)) {
5345 //unitFromString(unit) fails for relative units like Length::PCW
5346 // therefore handle them separately
5347 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5348 || unit == "\\textwidth" || unit == "\\linewidth"
5349 || unit == "\\textheight" || unit == "\\paperheight"
5350 || unit == "\\baselineskip")
5358 // check for glue lengths
5359 bool is_gluelength = false;
5360 string gluelength = length;
5361 string::size_type i = length.find(" minus");
5362 if (i == string::npos) {
5363 i = length.find(" plus");
5364 if (i != string::npos)
5365 is_gluelength = true;
5367 is_gluelength = true;
5368 // if yes transform "9xx minus 8yy plus 7zz"
5370 if (is_gluelength) {
5371 i = gluelength.find(" minus");
5372 if (i != string::npos)
5373 gluelength.replace(i, 7, "-");
5374 i = gluelength.find(" plus");
5375 if (i != string::npos)
5376 gluelength.replace(i, 6, "+");
5379 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5380 // Literal horizontal length or known variable
5381 context.check_layout(os);
5382 begin_inset(os, "space ");
5390 if (known_unit && !known_hspace)
5391 os << "\n\\length " << translate_len(length);
5393 os << "\n\\length " << gluelength;
5395 } else if (known_unit || known_vspace || is_gluelength) {
5396 // Literal vertical length or known variable
5397 context.check_layout(os);
5398 begin_inset(os, "VSpace ");
5401 if (known_unit && !known_vspace)
5402 os << translate_len(length);
5409 // LyX can't handle other length variables in Inset VSpace/space
5414 output_ert_inset(os, name + '{' + unit + '}', context);
5415 else if (value == -1.0)
5416 output_ert_inset(os, name + "{-" + unit + '}', context);
5418 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5420 output_ert_inset(os, name + '{' + length + '}', context);
5425 // The single '=' is meant here.
5426 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5430 context.check_layout(os);
5431 docstring name = newinsetlayout->name();
5432 bool const caption = name.find(from_ascii("Caption:")) == 0;
5434 // Already done for floating minted listings.
5435 if (minted_float.empty()) {
5436 begin_inset(os, "Caption ");
5437 os << to_utf8(name.substr(8)) << '\n';
5440 // FIXME: what do we do if the prefix is not Flex: ?
5441 if (prefixIs(name, from_ascii("Flex:")))
5443 begin_inset(os, "Flex ");
5444 os << to_utf8(name) << '\n'
5445 << "status collapsed\n";
5447 if (!minted_float.empty()) {
5448 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5449 } else if (newinsetlayout->isPassThru()) {
5450 // set catcodes to verbatim early, just in case.
5451 p.setCatcodes(VERBATIM_CATCODES);
5452 string delim = p.get_token().asInput();
5454 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5455 //FIXME: handle error condition
5456 string const arg = p.verbatimStuff("}").second;
5457 Context newcontext(true, context.textclass);
5458 if (newinsetlayout->forcePlainLayout())
5459 newcontext.layout = &context.textclass.plainLayout();
5460 output_ert(os, arg, newcontext);
5462 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5465 // Minted caption insets are not closed here because
5466 // we collect everything into the caption.
5467 if (minted_float.empty())
5472 if (t.cs() == "includepdf") {
5474 string const arg = p.getArg('[', ']');
5475 map<string, string> opts;
5476 vector<string> keys;
5477 split_map(arg, opts, keys);
5478 string name = normalize_filename(p.verbatim_item());
5479 string const path = getMasterFilePath(true);
5480 // We want to preserve relative / absolute filenames,
5481 // therefore path is only used for testing
5482 if (!makeAbsPath(name, path).exists()) {
5483 // The file extension is probably missing.
5484 // Now try to find it out.
5485 char const * const pdfpages_format[] = {"pdf", 0};
5486 string const pdftex_name =
5487 find_file(name, path, pdfpages_format);
5488 if (!pdftex_name.empty()) {
5493 FileName const absname = makeAbsPath(name, path);
5494 if (absname.exists())
5496 fix_child_filename(name);
5497 copy_file(absname, name);
5499 cerr << "Warning: Could not find file '"
5500 << name << "'." << endl;
5502 context.check_layout(os);
5503 begin_inset(os, "External\n\ttemplate ");
5504 os << "PDFPages\n\tfilename "
5506 // parse the options
5507 if (opts.find("pages") != opts.end())
5508 os << "\textra LaTeX \"pages="
5509 << opts["pages"] << "\"\n";
5510 if (opts.find("angle") != opts.end())
5511 os << "\trotateAngle "
5512 << opts["angle"] << '\n';
5513 if (opts.find("origin") != opts.end()) {
5515 string const opt = opts["origin"];
5516 if (opt == "tl") ss << "topleft";
5517 if (opt == "bl") ss << "bottomleft";
5518 if (opt == "Bl") ss << "baselineleft";
5519 if (opt == "c") ss << "center";
5520 if (opt == "tc") ss << "topcenter";
5521 if (opt == "bc") ss << "bottomcenter";
5522 if (opt == "Bc") ss << "baselinecenter";
5523 if (opt == "tr") ss << "topright";
5524 if (opt == "br") ss << "bottomright";
5525 if (opt == "Br") ss << "baselineright";
5526 if (!ss.str().empty())
5527 os << "\trotateOrigin " << ss.str() << '\n';
5529 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5531 if (opts.find("width") != opts.end())
5533 << translate_len(opts["width"]) << '\n';
5534 if (opts.find("height") != opts.end())
5536 << translate_len(opts["height"]) << '\n';
5537 if (opts.find("keepaspectratio") != opts.end())
5538 os << "\tkeepAspectRatio\n";
5540 context.check_layout(os);
5541 registerExternalTemplatePackages("PDFPages");
5545 if (t.cs() == "loadgame") {
5547 string name = normalize_filename(p.verbatim_item());
5548 string const path = getMasterFilePath(true);
5549 // We want to preserve relative / absolute filenames,
5550 // therefore path is only used for testing
5551 if (!makeAbsPath(name, path).exists()) {
5552 // The file extension is probably missing.
5553 // Now try to find it out.
5554 char const * const lyxskak_format[] = {"fen", 0};
5555 string const lyxskak_name =
5556 find_file(name, path, lyxskak_format);
5557 if (!lyxskak_name.empty())
5558 name = lyxskak_name;
5560 FileName const absname = makeAbsPath(name, path);
5561 if (absname.exists())
5563 fix_child_filename(name);
5564 copy_file(absname, name);
5566 cerr << "Warning: Could not find file '"
5567 << name << "'." << endl;
5568 context.check_layout(os);
5569 begin_inset(os, "External\n\ttemplate ");
5570 os << "ChessDiagram\n\tfilename "
5573 context.check_layout(os);
5574 // after a \loadgame follows a \showboard
5575 if (p.get_token().asInput() == "showboard")
5577 registerExternalTemplatePackages("ChessDiagram");
5581 // try to see whether the string is in unicodesymbols
5582 // Only use text mode commands, since we are in text mode here,
5583 // and math commands may be invalid (bug 6797)
5584 string name = t.asInput();
5585 // handle the dingbats, cyrillic and greek
5586 if (name == "\\ding" || name == "\\textcyr" ||
5587 (name == "\\textgreek" && !preamble.usePolyglossia()))
5588 name = name + '{' + p.getArg('{', '}') + '}';
5589 // handle the ifsym characters
5590 else if (name == "\\textifsymbol") {
5591 string const optif = p.getFullOpt();
5592 string const argif = p.getArg('{', '}');
5593 name = name + optif + '{' + argif + '}';
5595 // handle the \ascii characters
5596 // the case of \ascii within braces, as LyX outputs it, is already
5597 // handled for t.cat() == catBegin
5598 else if (name == "\\ascii") {
5599 // the code is "\asci\xxx"
5600 name = "{" + name + p.get_token().asInput() + "}";
5603 // handle some TIPA special characters
5604 else if (preamble.isPackageUsed("tipa")) {
5605 if (name == "\\s") {
5606 // fromLaTeXCommand() does not yet
5607 // recognize tipa short cuts
5608 name = "\\textsyllabic";
5609 } else if (name == "\\=" &&
5610 p.next_token().asInput() == "*") {
5611 // fromLaTeXCommand() does not yet
5612 // recognize tipa short cuts
5614 name = "\\textsubbar";
5615 } else if (name == "\\textdoublevertline") {
5616 // FIXME: This is not correct,
5617 // \textvertline is higher than \textbardbl
5618 name = "\\textbardbl";
5620 } else if (name == "\\!" ) {
5621 if (p.next_token().asInput() == "b") {
5622 p.get_token(); // eat 'b'
5625 } else if (p.next_token().asInput() == "d") {
5629 } else if (p.next_token().asInput() == "g") {
5633 } else if (p.next_token().asInput() == "G") {
5635 name = "\\texthtscg";
5637 } else if (p.next_token().asInput() == "j") {
5639 name = "\\texthtbardotlessj";
5641 } else if (p.next_token().asInput() == "o") {
5643 name = "\\textbullseye";
5646 } else if (name == "\\*" ) {
5647 if (p.next_token().asInput() == "k") {
5649 name = "\\textturnk";
5651 } else if (p.next_token().asInput() == "r") {
5652 p.get_token(); // eat 'b'
5653 name = "\\textturnr";
5655 } else if (p.next_token().asInput() == "t") {
5657 name = "\\textturnt";
5659 } else if (p.next_token().asInput() == "w") {
5661 name = "\\textturnw";
5666 if ((name.size() == 2 &&
5667 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5668 p.next_token().asInput() != "*") ||
5669 is_known(name.substr(1), known_tipa_marks)) {
5670 // name is a command that corresponds to a
5671 // combining character in unicodesymbols.
5672 // Append the argument, fromLaTeXCommand()
5673 // will either convert it to a single
5674 // character or a combining sequence.
5675 name += '{' + p.verbatim_item() + '}';
5677 // now get the character from unicodesymbols
5681 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5682 Encodings::TEXT_CMD, termination, rem, &req));
5684 context.check_layout(os);
5687 output_ert_inset(os, to_utf8(rem), context);
5689 skip_spaces_braces(p);
5690 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5691 preamble.registerAutomaticallyLoadedPackage(*it);
5693 //cerr << "#: " << t << " mode: " << mode << endl;
5694 // heuristic: read up to next non-nested space
5696 string s = t.asInput();
5697 string z = p.verbatim_item();
5698 while (p.good() && z != " " && !z.empty()) {
5699 //cerr << "read: " << z << endl;
5701 z = p.verbatim_item();
5703 cerr << "found ERT: " << s << endl;
5704 output_ert_inset(os, s + ' ', context);
5707 if (t.asInput() == name &&
5708 p.next_token().asInput() == "*") {
5709 // Starred commands like \vspace*{}
5710 p.get_token(); // Eat '*'
5713 if (!parse_command(name, p, os, outer, context))
5714 output_ert_inset(os, name, context);
5720 string guessLanguage(Parser & p, string const & lang)
5722 typedef std::map<std::string, size_t> LangMap;
5723 // map from language names to number of characters
5726 for (char const * const * i = supported_CJK_languages; *i; i++)
5727 used[string(*i)] = 0;
5730 Token const t = p.get_token();
5731 // comments are not counted for any language
5732 if (t.cat() == catComment)
5734 // commands are not counted as well, but we need to detect
5735 // \begin{CJK} and switch encoding if needed
5736 if (t.cat() == catEscape) {
5737 if (t.cs() == "inputencoding") {
5738 string const enc = subst(p.verbatim_item(), "\n", " ");
5739 p.setEncoding(enc, Encoding::inputenc);
5742 if (t.cs() != "begin")
5745 // Non-CJK content is counted for lang.
5746 // We do not care about the real language here:
5747 // If we have more non-CJK contents than CJK contents,
5748 // we simply use the language that was specified as
5749 // babel main language.
5750 used[lang] += t.asInput().length();
5753 // Now we are starting an environment
5755 string const name = p.getArg('{', '}');
5756 if (name != "CJK") {
5760 // It is a CJK environment
5762 /* name = */ p.getArg('{', '}');
5763 string const encoding = p.getArg('{', '}');
5764 /* mapping = */ p.getArg('{', '}');
5765 string const encoding_old = p.getEncoding();
5766 char const * const * const where =
5767 is_known(encoding, supported_CJK_encodings);
5769 p.setEncoding(encoding, Encoding::CJK);
5771 p.setEncoding("UTF-8");
5772 string const text = p.ertEnvironment("CJK");
5773 p.setEncoding(encoding_old);
5776 // ignore contents in unknown CJK encoding
5779 // the language of the text
5781 supported_CJK_languages[where - supported_CJK_encodings];
5782 used[cjk] += text.length();
5784 LangMap::const_iterator use = used.begin();
5785 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5786 if (it->second > use->second)
5793 void check_comment_bib(ostream & os, Context & context)
5795 if (!need_commentbib)
5797 // We have a bibliography database, but no bibliography with biblatex
5798 // which is completely valid. Insert a bibtex inset in a note.
5799 context.check_layout(os);
5800 begin_inset(os, "Note Note\n");
5801 os << "status open\n";
5802 os << "\\begin_layout Plain Layout\n";
5803 begin_command_inset(os, "bibtex", "bibtex");
5805 for (auto const & bf : preamble.biblatex_bibliographies) {
5806 if (!bibfiles.empty())
5808 bibfiles += normalize_filename(bf);
5810 if (!bibfiles.empty())
5811 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5812 end_inset(os);// Bibtex
5813 os << "\\end_layout\n";
5814 end_inset(os);// Note