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 // If we have a latex param, we eat it here.
71 if (!context.latexparam.empty()) {
73 Context dummy(true, context.textclass);
74 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
75 string(1, context.latexparam.back()));
77 parse_text(p, os, flags, outer, newcontext, rdelim);
79 output_arguments(os, p, outer, false, "post", newcontext,
80 layout->postcommandargs());
81 newcontext.check_end_layout(os);
87 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
88 Context const & context, string const & name,
89 string const rdelim = string())
91 InsetLayout const * layout = 0;
92 DocumentClass::InsetLayouts::const_iterator it =
93 context.textclass.insetLayouts().find(from_ascii(name));
94 if (it != context.textclass.insetLayouts().end())
95 layout = &(it->second);
96 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
99 /// parses a paragraph snippet, useful for example for \\emph{...}
100 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
103 Context newcontext(context);
104 // Don't inherit the paragraph-level extra stuff
105 newcontext.par_extra_stuff.clear();
106 parse_text(p, os, flags, outer, newcontext);
107 // Make sure that we don't create invalid .lyx files
108 context.need_layout = newcontext.need_layout;
109 context.need_end_layout = newcontext.need_end_layout;
114 * Thin wrapper around parse_text_snippet() using a string.
116 * We completely ignore \c context.need_layout and \c context.need_end_layout,
117 * because our return value is not used directly (otherwise the stream version
118 * of parse_text_snippet() could be used). That means that the caller needs
119 * to do layout management manually.
120 * This is intended to parse text that does not create any layout changes.
122 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
125 Context newcontext(context);
126 newcontext.need_layout = false;
127 newcontext.need_end_layout = false;
128 newcontext.new_layout_allowed = false;
129 // Avoid warning by Context::~Context()
130 newcontext.par_extra_stuff.clear();
132 parse_text_snippet(p, os, flags, outer, newcontext);
136 string fboxrule = "";
138 string shadow_size = "";
140 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
141 "vpageref", "prettyref", "nameref", "eqref", 0 };
143 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
144 "vpageref", "formatted", "nameref", "eqref", 0 };
146 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
147 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
148 "secref", "subsecref", "tabref", "thmref", 0 };
150 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
151 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
152 "sec", "subsec", "tab", "thm", 0 };
156 * supported CJK encodings
157 * JIS does not work with LyX's encoding conversion
159 const char * const supported_CJK_encodings[] = {
160 "EUC-JP", "KS", "GB", "UTF8",
161 "Bg5", /*"JIS",*/ "SJIS", 0};
164 * the same as supported_CJK_encodings with their corresponding LyX language name
165 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
167 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
168 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
169 * please keep this in sync with supported_CJK_encodings line by line!
171 const char * const supported_CJK_languages[] = {
172 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
173 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
177 * The starred forms are also known except for "citefullauthor",
178 * "citeyear" and "citeyearpar".
180 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
181 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
182 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
186 * No starred form other than "cite*" known.
188 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
189 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
190 // jurabib commands not (yet) supported by LyX:
192 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
193 // "footciteauthor", "footciteyear", "footciteyearpar",
194 "citefield", "citetitle", 0 };
198 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
200 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
201 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
202 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
203 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
204 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
206 // Whether we need to insert a bibtex inset in a comment
207 bool need_commentbib = false;
209 /// LaTeX names for quotes
210 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
211 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
212 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
213 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
216 /// the same as known_quotes with .lyx names
217 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
218 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
219 "gld", "eld", "gls", "ers", "ars",
220 "ars", "als", "als", "erd", "qrs", "qrd", 0};
222 /// LaTeX names for font sizes
223 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
224 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
226 /// the same as known_sizes with .lyx names
227 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
228 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
230 /// LaTeX 2.09 names for font families
231 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
233 /// LaTeX names for font families
234 char const * const known_font_families[] = { "rmfamily", "sffamily",
237 /// LaTeX names for font family changing commands
238 char const * const known_text_font_families[] = { "textrm", "textsf",
241 /// The same as known_old_font_families, known_font_families and
242 /// known_text_font_families with .lyx names
243 char const * const known_coded_font_families[] = { "roman", "sans",
246 /// LaTeX 2.09 names for font series
247 char const * const known_old_font_series[] = { "bf", 0};
249 /// LaTeX names for font series
250 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
252 /// LaTeX names for font series changing commands
253 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
255 /// The same as known_old_font_series, known_font_series and
256 /// known_text_font_series with .lyx names
257 char const * const known_coded_font_series[] = { "bold", "medium", 0};
259 /// LaTeX 2.09 names for font shapes
260 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
262 /// LaTeX names for font shapes
263 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
266 /// LaTeX names for font shape changing commands
267 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
270 /// The same as known_old_font_shapes, known_font_shapes and
271 /// known_text_font_shapes with .lyx names
272 char const * const known_coded_font_shapes[] = { "italic", "slanted",
273 "smallcaps", "up", 0};
275 /// Known special characters which need skip_spaces_braces() afterwards
276 char const * const known_special_chars[] = {"ldots",
277 "lyxarrow", "textcompwordmark",
278 "slash", "textasciitilde", "textasciicircum", "textbackslash",
279 "LyX", "TeX", "LaTeXe",
282 /// special characters from known_special_chars which may have a \\protect before
283 char const * const known_special_protect_chars[] = {"LyX", "TeX",
284 "LaTeXe", "LaTeX", 0};
286 /// the same as known_special_chars with .lyx names
287 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
288 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
289 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
290 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
291 "\\SpecialChar LaTeX\n", 0};
294 * Graphics file extensions known by the dvips driver of the graphics package.
295 * These extensions are used to complete the filename of an included
296 * graphics file if it does not contain an extension.
297 * The order must be the same that latex uses to find a file, because we
298 * will use the first extension that matches.
299 * This is only an approximation for the common cases. If we would want to
300 * do it right in all cases, we would need to know which graphics driver is
301 * used and know the extensions of every driver of the graphics package.
303 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
304 "ps.gz", "eps.Z", "ps.Z", 0};
307 * Graphics file extensions known by the pdftex driver of the graphics package.
308 * \sa known_dvips_graphics_formats
310 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
314 * Known file extensions for TeX files as used by \\include.
316 char const * const known_tex_extensions[] = {"tex", 0};
318 /// spaces known by InsetSpace
319 char const * const known_spaces[] = { " ", "space", ",",
320 "thinspace", "quad", "qquad", "enspace", "enskip",
321 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
322 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
323 "upbracefill", "downbracefill", 0};
325 /// the same as known_spaces with .lyx names
326 char const * const known_coded_spaces[] = { "space{}", "space{}",
327 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
328 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
329 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
330 "upbracefill{}", "downbracefill{}", 0};
332 /// known TIPA combining diacritical marks
333 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
334 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
335 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
336 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
337 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
338 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
339 "textsubring", "textsubbar", 0};
341 /// TIPA tones that need special handling
342 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
344 // string to store the float type to be able to determine the type of subfloats
345 string float_type = "";
347 // string to store the float status of minted listings
348 string minted_float = "";
350 // whether a caption has been parsed for a floating minted listing
351 bool minted_float_has_caption = false;
353 // The caption for non-floating minted listings
354 string minted_nonfloat_caption = "";
356 // Characters that have to be escaped by \\ in LaTeX
357 char const * const known_escaped_chars[] = {
358 "&", "_", "$", "%", "#", "^", "{", "}", 0};
361 /// splits "x=z, y=b" into a map and an ordered keyword vector
362 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
367 keys.resize(v.size());
368 for (size_t i = 0; i < v.size(); ++i) {
369 size_t const pos = v[i].find('=');
370 string const index = trimSpaceAndEol(v[i].substr(0, pos));
371 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
379 * Split a LaTeX length into value and unit.
380 * The latter can be a real unit like "pt", or a latex length variable
381 * like "\textwidth". The unit may contain additional stuff like glue
382 * lengths, but we don't care, because such lengths are ERT anyway.
383 * \returns true if \p value and \p unit are valid.
385 bool splitLatexLength(string const & len, string & value, string & unit)
389 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
390 //'4,5' is a valid LaTeX length number. Change it to '4.5'
391 string const length = subst(len, ',', '.');
392 if (i == string::npos)
395 if (len[0] == '\\') {
396 // We had something like \textwidth without a factor
402 value = trimSpaceAndEol(string(length, 0, i));
406 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
407 if (contains(len, '\\'))
408 unit = trimSpaceAndEol(string(len, i));
410 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
415 /// A simple function to translate a latex length to something LyX can
416 /// understand. Not perfect, but rather best-effort.
417 bool translate_len(string const & length, string & valstring, string & unit)
419 if (!splitLatexLength(length, valstring, unit))
421 // LyX uses percent values
423 istringstream iss(valstring);
428 string const percentval = oss.str();
430 if (unit.empty() || unit[0] != '\\')
432 string::size_type const i = unit.find(' ');
433 string const endlen = (i == string::npos) ? string() : string(unit, i);
434 if (unit == "\\textwidth") {
435 valstring = percentval;
436 unit = "text%" + endlen;
437 } else if (unit == "\\columnwidth") {
438 valstring = percentval;
439 unit = "col%" + endlen;
440 } else if (unit == "\\paperwidth") {
441 valstring = percentval;
442 unit = "page%" + endlen;
443 } else if (unit == "\\linewidth") {
444 valstring = percentval;
445 unit = "line%" + endlen;
446 } else if (unit == "\\paperheight") {
447 valstring = percentval;
448 unit = "pheight%" + endlen;
449 } else if (unit == "\\textheight") {
450 valstring = percentval;
451 unit = "theight%" + endlen;
452 } else if (unit == "\\baselineskip") {
453 valstring = percentval;
454 unit = "baselineskip%" + endlen;
460 /// If we have ambiguous quotation marks, make a smart guess
461 /// based on main quote style
462 string guessQuoteStyle(string in, bool const opening)
465 if (prefixIs(in, "qr")) {// straight quote
467 res = subst(res, "r", "l");
468 } else if (in == "eld") {// ``
469 if (preamble.quotesStyle() == "german")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "russian")
477 } else if (in == "erd") {// ''
478 if (preamble.quotesStyle() == "polish")
480 else if (preamble.quotesStyle() == "british")
482 else if (preamble.quotesStyle() == "french")
484 else if (preamble.quotesStyle() == "swedish")
485 res = opening ? "sld" : "srd";
486 } else if (in == "els") {// `
487 if (preamble.quotesStyle() == "german")
489 else if (preamble.quotesStyle() == "british")
491 } else if (in == "ers") {// '
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sls" : "srs";
498 } else if (in == "ard") {// >>
499 if (preamble.quotesStyle() == "swiss")
501 else if (preamble.quotesStyle() == "french")
503 else if (preamble.quotesStyle() == "russian")
505 } else if (in == "ald") {// <<
506 if (preamble.quotesStyle() == "swiss")
508 else if (preamble.quotesStyle() == "french")
510 else if (preamble.quotesStyle() == "russian")
512 } else if (in == "ars") {// >
513 if (preamble.quotesStyle() == "swiss")
515 } else if (in == "als") {// <
516 if (preamble.quotesStyle() == "swiss")
518 } else if (in == "gld") {// ,,
519 if (preamble.quotesStyle() == "polish")
521 else if (preamble.quotesStyle() == "russian")
523 } else if (in == "gls") {// ,
524 if (preamble.quotesStyle() == "polish")
534 string translate_len(string const & length)
538 if (translate_len(length, value, unit))
540 // If the input is invalid, return what we have.
548 * Translates a LaTeX length into \p value, \p unit and
549 * \p special parts suitable for a box inset.
550 * The difference from translate_len() is that a box inset knows about
551 * some special "units" that are stored in \p special.
553 void translate_box_len(string const & length, string & value, string & unit, string & special)
555 if (translate_len(length, value, unit)) {
556 if (unit == "\\height" || unit == "\\depth" ||
557 unit == "\\totalheight" || unit == "\\width") {
558 special = unit.substr(1);
559 // The unit is not used, but LyX requires a dummy setting
571 void begin_inset(ostream & os, string const & name)
573 os << "\n\\begin_inset " << name;
577 void begin_command_inset(ostream & os, string const & name,
578 string const & latexname)
580 begin_inset(os, "CommandInset ");
581 os << name << "\nLatexCommand " << latexname << '\n';
585 void end_inset(ostream & os)
587 os << "\n\\end_inset\n\n";
591 bool skip_braces(Parser & p)
593 if (p.next_token().cat() != catBegin)
596 if (p.next_token().cat() == catEnd) {
605 /// replace LaTeX commands in \p s from the unicodesymbols file with their
607 pair<bool, docstring> convert_unicodesymbols(docstring s)
611 for (size_t i = 0; i < s.size();) {
620 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
621 Encodings::TEXT_CMD, termination, rem, &req));
622 set<string>::const_iterator it = req.begin();
623 set<string>::const_iterator en = req.end();
624 for (; it != en; ++it)
625 preamble.registerAutomaticallyLoadedPackage(*it);
628 if (s.empty() || s[0] != '\\')
632 for (auto const & c : known_escaped_chars)
633 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
638 return make_pair(res, os.str());
642 /// try to convert \p s to a valid InsetCommand argument
643 /// return whether this succeeded. If not, these command insets
644 /// get the "literate" flag.
645 pair<bool, string> convert_latexed_command_inset_arg(string s)
647 bool success = false;
649 // since we don't know the input encoding we can't use from_utf8
650 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
652 s = to_utf8(res.second);
654 // LyX cannot handle newlines in a latex command
655 return make_pair(success, subst(s, "\n", " "));
658 /// try to convert \p s to a valid InsetCommand argument
659 /// without trying to recode macros.
660 string convert_literate_command_inset_arg(string s)
662 // LyX cannot handle newlines in a latex command
663 return subst(s, "\n", " ");
666 void output_ert(ostream & os, string const & s, Context & context)
668 context.check_layout(os);
669 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
671 os << "\n\\backslash\n";
672 else if (*it == '\n') {
673 context.new_paragraph(os);
674 context.check_layout(os);
678 context.check_end_layout(os);
682 void output_ert_inset(ostream & os, string const & s, Context & context)
684 // We must have a valid layout before outputting the ERT inset.
685 context.check_layout(os);
686 Context newcontext(true, context.textclass);
687 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
688 if (layout.forcePlainLayout())
689 newcontext.layout = &context.textclass.plainLayout();
690 begin_inset(os, "ERT");
691 os << "\nstatus collapsed\n";
692 output_ert(os, s, newcontext);
697 void output_comment(Parser & p, ostream & os, string const & s,
700 if (p.next_token().cat() == catNewline)
701 output_ert_inset(os, '%' + s, context);
703 output_ert_inset(os, '%' + s + '\n', context);
707 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
708 string const & latexparam = string())
710 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
713 if (checkModule(name, command))
714 return findLayoutWithoutModule(textclass, name, command, latexparam);
719 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
720 string const & latexparam = string())
722 InsetLayout const * insetlayout =
723 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
726 if (checkModule(name, command))
727 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
732 void eat_whitespace(Parser &, ostream &, Context &, bool);
736 * Skips whitespace and braces.
737 * This should be called after a command has been parsed that is not put into
738 * ERT, and where LyX adds "{}" if needed.
740 void skip_spaces_braces(Parser & p, bool keepws = false)
742 /* The following four examples produce the same typeset output and
743 should be handled by this function:
751 // Unfortunately we need to skip comments, too.
752 // We can't use eat_whitespace since writing them after the {}
753 // results in different output in some cases.
754 bool const skipped_spaces = p.skip_spaces(true);
755 bool const skipped_braces = skip_braces(p);
756 if (keepws && skipped_spaces && !skipped_braces)
757 // put back the space (it is better handled by check_space)
758 p.unskip_spaces(true);
762 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const prefix,
763 Context & context, Layout::LaTeXArgMap const & latexargs)
765 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
767 context.check_layout(os);
773 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
774 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
775 for (; lait != laend; ++lait) {
777 eat_whitespace(p, os, context, false);
778 if (lait->second.mandatory) {
779 if (p.next_token().cat() != catBegin)
781 string ldelim = to_utf8(lait->second.ldelim);
782 string rdelim = to_utf8(lait->second.rdelim);
787 p.get_token(); // eat ldelim
788 if (ldelim.size() > 1)
789 p.get_token(); // eat ldelim
791 context.check_layout(os);
794 begin_inset(os, "Argument ");
797 os << i << "\nstatus collapsed\n\n";
798 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
801 string ldelim = to_utf8(lait->second.ldelim);
802 string rdelim = to_utf8(lait->second.rdelim);
807 string tok = p.next_token().asInput();
808 // we only support delimiters with max 2 chars for now.
809 if (ldelim.size() > 1)
810 tok += p.next_next_token().asInput();
811 if (p.next_token().cat() == catEscape || tok != ldelim)
813 p.get_token(); // eat ldelim
814 if (ldelim.size() > 1)
815 p.get_token(); // eat ldelim
817 context.check_layout(os);
820 begin_inset(os, "Argument ");
823 os << i << "\nstatus collapsed\n\n";
824 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
827 eat_whitespace(p, os, context, false);
832 void output_command_layout(ostream & os, Parser & p, bool outer,
833 Context & parent_context,
834 Layout const * newlayout)
836 TeXFont const oldFont = parent_context.font;
837 // save the current font size
838 string const size = oldFont.size;
839 // reset the font size to default, because the font size switches
840 // don't affect section headings and the like
841 parent_context.font.size = Context::normalfont.size;
842 // we only need to write the font change if we have an open layout
843 if (!parent_context.atParagraphStart())
844 output_font_change(os, oldFont, parent_context.font);
845 parent_context.check_end_layout(os);
846 Context context(true, parent_context.textclass, newlayout,
847 parent_context.layout, parent_context.font);
848 if (parent_context.deeper_paragraph) {
849 // We are beginning a nested environment after a
850 // deeper paragraph inside the outer list environment.
851 // Therefore we don't need to output a "begin deeper".
852 context.need_end_deeper = true;
854 context.check_deeper(os);
855 output_arguments(os, p, outer, true, string(), context,
856 context.layout->latexargs());
857 // If we have a latex param, we eat it here.
858 if (!parent_context.latexparam.empty()) {
860 Context dummy(true, parent_context.textclass);
861 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
862 string(1, parent_context.latexparam.back()));
864 parse_text(p, os, FLAG_ITEM, outer, context);
865 output_arguments(os, p, outer, false, "post", context,
866 context.layout->postcommandargs());
867 context.check_end_layout(os);
868 if (parent_context.deeper_paragraph) {
869 // We must suppress the "end deeper" because we
870 // suppressed the "begin deeper" above.
871 context.need_end_deeper = false;
873 context.check_end_deeper(os);
874 // We don't need really a new paragraph, but
875 // we must make sure that the next item gets a \begin_layout.
876 parent_context.new_paragraph(os);
877 // Set the font size to the original value. No need to output it here
878 // (Context::begin_layout() will do that if needed)
879 parent_context.font.size = size;
884 * Output a space if necessary.
885 * This function gets called for every whitespace token.
887 * We have three cases here:
888 * 1. A space must be suppressed. Example: The lyxcode case below
889 * 2. A space may be suppressed. Example: Spaces before "\par"
890 * 3. A space must not be suppressed. Example: A space between two words
892 * We currently handle only 1. and 3 and from 2. only the case of
893 * spaces before newlines as a side effect.
895 * 2. could be used to suppress as many spaces as possible. This has two effects:
896 * - Reimporting LyX generated LaTeX files changes almost no whitespace
897 * - Superflous whitespace from non LyX generated LaTeX files is removed.
898 * The drawback is that the logic inside the function becomes
899 * complicated, and that is the reason why it is not implemented.
901 void check_space(Parser & p, ostream & os, Context & context)
903 Token const next = p.next_token();
904 Token const curr = p.curr_token();
905 // A space before a single newline and vice versa must be ignored
906 // LyX emits a newline before \end{lyxcode}.
907 // This newline must be ignored,
908 // otherwise LyX will add an additional protected space.
909 if (next.cat() == catSpace ||
910 next.cat() == catNewline ||
911 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
914 context.check_layout(os);
920 * Parse all arguments of \p command
922 void parse_arguments(string const & command,
923 vector<ArgumentType> const & template_arguments,
924 Parser & p, ostream & os, bool outer, Context & context)
926 string ert = command;
927 size_t no_arguments = template_arguments.size();
928 for (size_t i = 0; i < no_arguments; ++i) {
929 switch (template_arguments[i]) {
932 // This argument contains regular LaTeX
933 output_ert_inset(os, ert + '{', context);
934 eat_whitespace(p, os, context, false);
935 if (template_arguments[i] == required)
936 parse_text(p, os, FLAG_ITEM, outer, context);
938 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
942 // This argument consists only of a single item.
943 // The presence of '{' or not must be preserved.
945 if (p.next_token().cat() == catBegin)
946 ert += '{' + p.verbatim_item() + '}';
948 ert += p.verbatim_item();
952 // This argument may contain special characters
953 ert += '{' + p.verbatim_item() + '}';
957 // true because we must not eat whitespace
958 // if an optional arg follows we must not strip the
959 // brackets from this one
960 if (i < no_arguments - 1 &&
961 template_arguments[i+1] == optional)
962 ert += p.getFullOpt(true);
964 ert += p.getOpt(true);
968 output_ert_inset(os, ert, context);
973 * Check whether \p command is a known command. If yes,
974 * handle the command with all arguments.
975 * \return true if the command was parsed, false otherwise.
977 bool parse_command(string const & command, Parser & p, ostream & os,
978 bool outer, Context & context)
980 if (known_commands.find(command) != known_commands.end()) {
981 parse_arguments(command, known_commands[command], p, os,
989 /// Parses a minipage or parbox
990 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
991 unsigned inner_flags, bool outer, Context & parent_context,
992 string const & outer_type, string const & special,
993 string inner_type, string const & frame_color,
994 string const & background_color)
998 string hor_pos = "l";
999 // We need to set the height to the LaTeX default of 1\\totalheight
1000 // for the case when no height argument is given
1001 string height_value = "1";
1002 string height_unit = "in";
1003 string height_special = "totalheight";
1004 string latex_height;
1008 string width_special = "none";
1009 string thickness = "0.4pt";
1010 if (!fboxrule.empty())
1011 thickness = fboxrule;
1013 thickness = "0.4pt";
1015 if (!fboxsep.empty())
1016 separation = fboxsep;
1020 if (!shadow_size.empty())
1021 shadowsize = shadow_size;
1024 string framecolor = "black";
1025 string backgroundcolor = "none";
1026 if (!frame_color.empty())
1027 framecolor = frame_color;
1028 if (!background_color.empty())
1029 backgroundcolor = background_color;
1030 // if there is a color box around the \begin statements have not yet been parsed
1032 if (!frame_color.empty() || !background_color.empty()) {
1033 eat_whitespace(p, os, parent_context, false);
1034 p.get_token().asInput(); // the '{'
1036 if (p.next_token().asInput() == "\\begin") {
1037 p.get_token().asInput();
1039 inner_type = "minipage";
1040 inner_flags = FLAG_END;
1041 active_environments.push_back("minipage");
1044 else if (p.next_token().asInput() == "\\parbox") {
1045 p.get_token().asInput();
1046 inner_type = "parbox";
1047 inner_flags = FLAG_ITEM;
1050 else if (p.next_token().asInput() == "\\makebox") {
1051 p.get_token().asInput();
1052 inner_type = "makebox";
1053 inner_flags = FLAG_ITEM;
1055 // in case there is just \colorbox{color}{text}
1058 inner_type = "makebox";
1059 inner_flags = FLAG_BRACE_LAST;
1064 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1066 if (!inner_type.empty() && p.hasOpt()) {
1067 if (inner_type != "makebox")
1068 position = p.getArg('[', ']');
1070 latex_width = p.getArg('[', ']');
1071 translate_box_len(latex_width, width_value, width_unit, width_special);
1074 if (position != "t" && position != "c" && position != "b") {
1075 cerr << "invalid position " << position << " for "
1076 << inner_type << endl;
1080 if (inner_type != "makebox") {
1081 latex_height = p.getArg('[', ']');
1082 translate_box_len(latex_height, height_value, height_unit, height_special);
1084 string const opt = p.getArg('[', ']');
1087 if (hor_pos != "l" && hor_pos != "c" &&
1088 hor_pos != "r" && hor_pos != "s") {
1089 cerr << "invalid hor_pos " << hor_pos
1090 << " for " << inner_type << endl;
1097 inner_pos = p.getArg('[', ']');
1098 if (inner_pos != "c" && inner_pos != "t" &&
1099 inner_pos != "b" && inner_pos != "s") {
1100 cerr << "invalid inner_pos "
1101 << inner_pos << " for "
1102 << inner_type << endl;
1103 inner_pos = position;
1107 if (inner_type == "makebox")
1111 if (inner_type.empty()) {
1112 if (special.empty() && outer_type != "framebox")
1113 latex_width = "1\\columnwidth";
1116 latex_width = p2.getArg('[', ']');
1117 string const opt = p2.getArg('[', ']');
1120 if (hor_pos != "l" && hor_pos != "c" &&
1121 hor_pos != "r" && hor_pos != "s") {
1122 cerr << "invalid hor_pos " << hor_pos
1123 << " for " << outer_type << endl;
1127 if (outer_type == "framebox")
1131 } else if (inner_type != "makebox")
1132 latex_width = p.verbatim_item();
1133 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1134 // as this is LyX's standard for such cases (except for makebox)
1135 // \framebox is more special and handled below
1136 if (latex_width.empty() && inner_type != "makebox"
1137 && outer_type != "framebox")
1138 latex_width = "1\\columnwidth";
1140 translate_len(latex_width, width_value, width_unit);
1142 bool shadedparbox = false;
1143 if (inner_type == "shaded") {
1144 eat_whitespace(p, os, parent_context, false);
1145 if (outer_type == "parbox") {
1147 if (p.next_token().cat() == catBegin)
1149 eat_whitespace(p, os, parent_context, false);
1150 shadedparbox = true;
1155 // If we already read the inner box we have to push the inner env
1156 if (!outer_type.empty() && !inner_type.empty() &&
1157 (inner_flags & FLAG_END))
1158 active_environments.push_back(inner_type);
1159 bool use_ert = false;
1160 if (!outer_type.empty() && !inner_type.empty()) {
1161 // Look whether there is some content after the end of the
1162 // inner box, but before the end of the outer box.
1163 // If yes, we need to output ERT.
1165 if (inner_flags & FLAG_END)
1166 p.ertEnvironment(inner_type);
1169 p.skip_spaces(true);
1170 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1171 if ((outer_env && p.next_token().asInput() != "\\end") ||
1172 (!outer_env && p.next_token().cat() != catEnd)) {
1173 // something is between the end of the inner box and
1174 // the end of the outer box, so we need to use ERT.
1182 if (!outer_type.empty()) {
1183 if (outer_flags & FLAG_END)
1184 ss << "\\begin{" << outer_type << '}';
1186 ss << '\\' << outer_type << '{';
1187 if (!special.empty())
1191 if (!inner_type.empty()) {
1192 if (inner_type != "shaded") {
1193 if (inner_flags & FLAG_END)
1194 ss << "\\begin{" << inner_type << '}';
1196 ss << '\\' << inner_type;
1198 if (!position.empty())
1199 ss << '[' << position << ']';
1200 if (!latex_height.empty())
1201 ss << '[' << latex_height << ']';
1202 if (!inner_pos.empty())
1203 ss << '[' << inner_pos << ']';
1204 ss << '{' << latex_width << '}';
1205 if (!(inner_flags & FLAG_END))
1208 if (inner_type == "shaded")
1209 ss << "\\begin{shaded}";
1210 output_ert_inset(os, ss.str(), parent_context);
1211 if (!inner_type.empty()) {
1212 parse_text(p, os, inner_flags, outer, parent_context);
1213 if (inner_flags & FLAG_END)
1214 output_ert_inset(os, "\\end{" + inner_type + '}',
1217 output_ert_inset(os, "}", parent_context);
1219 if (!outer_type.empty()) {
1220 // If we already read the inner box we have to pop
1222 if (!inner_type.empty() && (inner_flags & FLAG_END))
1223 active_environments.pop_back();
1225 // Ensure that the end of the outer box is parsed correctly:
1226 // The opening brace has been eaten by parse_outer_box()
1227 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1228 outer_flags &= ~FLAG_ITEM;
1229 outer_flags |= FLAG_BRACE_LAST;
1231 parse_text(p, os, outer_flags, outer, parent_context);
1232 if (outer_flags & FLAG_END)
1233 output_ert_inset(os, "\\end{" + outer_type + '}',
1236 output_ert_inset(os, "}", parent_context);
1239 // LyX does not like empty positions, so we have
1240 // to set them to the LaTeX default values here.
1241 if (position.empty())
1243 if (inner_pos.empty())
1244 inner_pos = position;
1245 parent_context.check_layout(os);
1246 begin_inset(os, "Box ");
1247 if (outer_type == "framed")
1249 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1251 else if (outer_type == "shadowbox")
1252 os << "Shadowbox\n";
1253 else if ((outer_type == "shaded" && inner_type.empty()) ||
1254 (outer_type == "minipage" && inner_type == "shaded") ||
1255 (outer_type == "parbox" && inner_type == "shaded")) {
1257 preamble.registerAutomaticallyLoadedPackage("color");
1258 } else if (outer_type == "doublebox")
1259 os << "Doublebox\n";
1260 else if (outer_type.empty() || outer_type == "mbox")
1261 os << "Frameless\n";
1263 os << outer_type << '\n';
1264 os << "position \"" << position << "\"\n";
1265 os << "hor_pos \"" << hor_pos << "\"\n";
1266 if (outer_type == "mbox")
1267 os << "has_inner_box 1\n";
1268 else if (!frame_color.empty() && inner_type == "makebox")
1269 os << "has_inner_box 0\n";
1271 os << "has_inner_box " << !inner_type.empty() << "\n";
1272 os << "inner_pos \"" << inner_pos << "\"\n";
1273 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1275 if (outer_type == "mbox")
1276 os << "use_makebox 1\n";
1277 else if (!frame_color.empty())
1278 os << "use_makebox 0\n";
1280 os << "use_makebox " << (inner_type == "makebox") << '\n';
1281 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1282 os << "width \"\"\n";
1283 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1284 else if (contains(width_unit, '\\'))
1285 os << "width \"" << width_value << "in" << "\"\n";
1287 os << "width \"" << width_value << width_unit << "\"\n";
1288 if (contains(width_unit, '\\')) {
1289 width_unit.erase (0,1); // remove the leading '\'
1290 os << "special \"" << width_unit << "\"\n";
1292 os << "special \"" << width_special << "\"\n";
1293 if (contains(height_unit, '\\'))
1294 os << "height \"" << height_value << "in" << "\"\n";
1296 os << "height \"" << height_value << height_unit << "\"\n";
1297 os << "height_special \"" << height_special << "\"\n";
1298 os << "thickness \"" << thickness << "\"\n";
1299 os << "separation \"" << separation << "\"\n";
1300 os << "shadowsize \"" << shadowsize << "\"\n";
1301 os << "framecolor \"" << framecolor << "\"\n";
1302 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1303 os << "status open\n\n";
1305 // Unfortunately we can't use parse_text_in_inset:
1306 // InsetBox::forcePlainLayout() is hard coded and does not
1307 // use the inset layout. Apart from that do we call parse_text
1308 // up to two times, but need only one check_end_layout.
1309 bool const forcePlainLayout =
1310 (!inner_type.empty() || inner_type == "makebox") &&
1311 outer_type != "shaded" && outer_type != "framed";
1312 Context context(true, parent_context.textclass);
1313 if (forcePlainLayout)
1314 context.layout = &context.textclass.plainLayout();
1316 context.font = parent_context.font;
1318 // If we have no inner box the contents will be read with the outer box
1319 if (!inner_type.empty())
1320 parse_text(p, os, inner_flags, outer, context);
1322 // Ensure that the end of the outer box is parsed correctly:
1323 // The opening brace has been eaten by parse_outer_box()
1324 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1325 outer_flags &= ~FLAG_ITEM;
1326 outer_flags |= FLAG_BRACE_LAST;
1329 // Find end of outer box, output contents if inner_type is
1330 // empty and output possible comments
1331 if (!outer_type.empty()) {
1332 // If we already read the inner box we have to pop
1334 if (!inner_type.empty() && (inner_flags & FLAG_END))
1335 active_environments.pop_back();
1336 // This does not output anything but comments if
1337 // inner_type is not empty (see use_ert)
1338 parse_text(p, os, outer_flags, outer, context);
1341 context.check_end_layout(os);
1343 #ifdef PRESERVE_LAYOUT
1344 // LyX puts a % after the end of the minipage
1345 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1347 //output_comment(p, os, "dummy", parent_context);
1350 parent_context.new_paragraph(os);
1352 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1353 //output_comment(p, os, "dummy", parent_context);
1356 // We add a protected space if something real follows
1357 if (p.good() && p.next_token().cat() != catComment) {
1358 begin_inset(os, "space ~\n");
1364 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1365 active_environments.pop_back();
1366 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1367 // in this case we have to eat the the closing brace of the color box
1368 p.get_token().asInput(); // the '}'
1370 if (p.next_token().asInput() == "}") {
1371 // in this case we assume that the closing brace is from the box settings
1372 // therefore reset these values for the next box
1378 // all boxes except of Frameless and Shaded require calc
1379 if (!(outer_type.empty() || outer_type == "mbox") &&
1380 !((outer_type == "shaded" && inner_type.empty()) ||
1381 (outer_type == "minipage" && inner_type == "shaded") ||
1382 (outer_type == "parbox" && inner_type == "shaded")))
1383 preamble.registerAutomaticallyLoadedPackage("calc");
1387 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1388 Context & parent_context, string const & outer_type,
1389 string const & special)
1391 eat_whitespace(p, os, parent_context, false);
1392 if (flags & FLAG_ITEM) {
1394 if (p.next_token().cat() == catBegin)
1397 cerr << "Warning: Ignoring missing '{' after \\"
1398 << outer_type << '.' << endl;
1399 eat_whitespace(p, os, parent_context, false);
1402 unsigned int inner_flags = 0;
1404 if (outer_type == "minipage" || outer_type == "parbox") {
1405 p.skip_spaces(true);
1406 while (p.hasOpt()) {
1408 p.skip_spaces(true);
1411 p.skip_spaces(true);
1412 if (outer_type == "parbox") {
1414 if (p.next_token().cat() == catBegin)
1416 p.skip_spaces(true);
1419 if (outer_type == "shaded" || outer_type == "mbox") {
1420 // These boxes never have an inner box
1422 } else if (p.next_token().asInput() == "\\parbox") {
1423 inner = p.get_token().cs();
1424 inner_flags = FLAG_ITEM;
1425 } else if (p.next_token().asInput() == "\\begin") {
1426 // Is this a minipage or shaded box?
1429 inner = p.getArg('{', '}');
1431 if (inner == "minipage" || inner == "shaded")
1432 inner_flags = FLAG_END;
1437 if (inner_flags == FLAG_END) {
1438 if (inner != "shaded")
1442 eat_whitespace(p, os, parent_context, false);
1444 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1445 outer_type, special, inner, "", "");
1447 if (inner_flags == FLAG_ITEM) {
1449 eat_whitespace(p, os, parent_context, false);
1451 parse_box(p, os, flags, inner_flags, outer, parent_context,
1452 outer_type, special, inner, "", "");
1457 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1458 bool in_line, bool use_minted)
1460 parent_context.check_layout(os);
1461 begin_inset(os, "listings\n");
1462 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1464 while ((i = arg.find(", ")) != string::npos
1465 || (i = arg.find(",\t")) != string::npos)
1466 arg.erase(i + 1, 1);
1469 string const language = p.getArg('{', '}');
1470 p.skip_spaces(true);
1471 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1472 if (!minted_float.empty()) {
1473 arg += string(arg.empty() ? "" : ",") + minted_float;
1474 minted_nonfloat_caption.clear();
1478 os << "lstparams " << '"' << arg << '"' << '\n';
1479 if (arg.find("\\color") != string::npos)
1480 preamble.registerAutomaticallyLoadedPackage("color");
1483 os << "inline true\n";
1485 os << "inline false\n";
1486 os << "status collapsed\n";
1487 Context context(true, parent_context.textclass);
1488 context.layout = &parent_context.textclass.plainLayout();
1489 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1490 minted_nonfloat_caption.erase(0,3);
1491 os << "\n\\begin_layout Plain Layout\n";
1492 begin_inset(os, "Caption Standard\n");
1493 Context newcontext(true, context.textclass,
1494 context.layout, 0, context.font);
1495 newcontext.check_layout(os);
1496 os << minted_nonfloat_caption << "\n";
1497 newcontext.check_end_layout(os);
1499 os << "\n\\end_layout\n";
1500 minted_nonfloat_caption.clear();
1504 // set catcodes to verbatim early, just in case.
1505 p.setCatcodes(VERBATIM_CATCODES);
1506 string delim = p.get_token().asInput();
1507 //FIXME: handler error condition
1508 s = p.verbatimStuff(delim).second;
1509 // context.new_paragraph(os);
1510 } else if (use_minted) {
1511 s = p.verbatimEnvironment("minted");
1513 s = p.verbatimEnvironment("lstlisting");
1515 output_ert(os, s, context);
1516 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1517 minted_nonfloat_caption.erase(0,3);
1518 os << "\n\\begin_layout Plain Layout\n";
1519 begin_inset(os, "Caption Standard\n");
1520 Context newcontext(true, context.textclass,
1521 context.layout, 0, context.font);
1522 newcontext.check_layout(os);
1523 os << minted_nonfloat_caption << "\n";
1524 newcontext.check_end_layout(os);
1526 os << "\n\\end_layout\n";
1527 minted_nonfloat_caption.clear();
1529 // Don't close the inset here for floating minted listings.
1530 // It will be closed at the end of the listing environment.
1531 if (!use_minted || minted_float.empty())
1534 eat_whitespace(p, os, parent_context, true);
1535 Token t = p.get_token();
1536 if (t.asInput() != "\\end") {
1537 // If anything follows, collect it into a caption.
1538 minted_float_has_caption = true;
1539 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1540 begin_inset(os, "Caption Standard\n");
1541 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1548 /// parse an unknown environment
1549 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1550 unsigned flags, bool outer,
1551 Context & parent_context)
1553 if (name == "tabbing")
1554 // We need to remember that we have to handle '\=' specially
1555 flags |= FLAG_TABBING;
1557 // We need to translate font changes and paragraphs inside the
1558 // environment to ERT if we have a non standard font.
1559 // Otherwise things like
1560 // \large\begin{foo}\huge bar\end{foo}
1562 bool const specialfont =
1563 (parent_context.font != parent_context.normalfont);
1564 bool const new_layout_allowed = parent_context.new_layout_allowed;
1566 parent_context.new_layout_allowed = false;
1567 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1568 parse_text_snippet(p, os, flags, outer, parent_context);
1569 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1571 parent_context.new_layout_allowed = new_layout_allowed;
1575 void parse_environment(Parser & p, ostream & os, bool outer,
1576 string & last_env, Context & parent_context)
1578 Layout const * newlayout;
1579 InsetLayout const * newinsetlayout = 0;
1580 string const name = p.getArg('{', '}');
1581 const bool is_starred = suffixIs(name, '*');
1582 string const unstarred_name = rtrim(name, "*");
1583 active_environments.push_back(name);
1585 if (is_math_env(name)) {
1586 parent_context.check_layout(os);
1587 begin_inset(os, "Formula ");
1588 os << "\\begin{" << name << "}";
1589 parse_math(p, os, FLAG_END, MATH_MODE);
1590 os << "\\end{" << name << "}";
1592 if (is_display_math_env(name)) {
1593 // Prevent the conversion of a line break to a space
1594 // (bug 7668). This does not change the output, but
1595 // looks ugly in LyX.
1596 eat_whitespace(p, os, parent_context, false);
1600 else if (is_known(name, preamble.polyglossia_languages)) {
1601 // We must begin a new paragraph if not already done
1602 if (! parent_context.atParagraphStart()) {
1603 parent_context.check_end_layout(os);
1604 parent_context.new_paragraph(os);
1606 // save the language in the context so that it is
1607 // handled by parse_text
1608 parent_context.font.language = preamble.polyglossia2lyx(name);
1609 parse_text(p, os, FLAG_END, outer, parent_context);
1610 // Just in case the environment is empty
1611 parent_context.extra_stuff.erase();
1612 // We must begin a new paragraph to reset the language
1613 parent_context.new_paragraph(os);
1617 else if (unstarred_name == "tabular" || name == "longtable") {
1618 eat_whitespace(p, os, parent_context, false);
1619 string width = "0pt";
1620 if (name == "tabular*") {
1621 width = lyx::translate_len(p.getArg('{', '}'));
1622 eat_whitespace(p, os, parent_context, false);
1624 parent_context.check_layout(os);
1625 begin_inset(os, "Tabular ");
1626 handle_tabular(p, os, name, width, parent_context);
1631 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1632 eat_whitespace(p, os, parent_context, false);
1633 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1634 eat_whitespace(p, os, parent_context, false);
1635 parent_context.check_layout(os);
1636 begin_inset(os, "Float " + unstarred_name + "\n");
1637 // store the float type for subfloats
1638 // subfloats only work with figures and tables
1639 if (unstarred_name == "figure")
1640 float_type = unstarred_name;
1641 else if (unstarred_name == "table")
1642 float_type = unstarred_name;
1646 os << "placement " << opt << '\n';
1647 if (contains(opt, "H"))
1648 preamble.registerAutomaticallyLoadedPackage("float");
1650 Floating const & fl = parent_context.textclass.floats()
1651 .getType(unstarred_name);
1652 if (!fl.floattype().empty() && fl.usesFloatPkg())
1653 preamble.registerAutomaticallyLoadedPackage("float");
1656 os << "wide " << convert<string>(is_starred)
1657 << "\nsideways false"
1658 << "\nstatus open\n\n";
1659 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1661 // We don't need really a new paragraph, but
1662 // we must make sure that the next item gets a \begin_layout.
1663 parent_context.new_paragraph(os);
1665 // the float is parsed thus delete the type
1669 else if (unstarred_name == "sidewaysfigure"
1670 || unstarred_name == "sidewaystable"
1671 || unstarred_name == "sidewaysalgorithm") {
1672 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1673 eat_whitespace(p, os, parent_context, false);
1674 parent_context.check_layout(os);
1675 if (unstarred_name == "sidewaysfigure")
1676 begin_inset(os, "Float figure\n");
1677 else if (unstarred_name == "sidewaystable")
1678 begin_inset(os, "Float table\n");
1679 else if (unstarred_name == "sidewaysalgorithm")
1680 begin_inset(os, "Float algorithm\n");
1682 os << "placement " << opt << '\n';
1683 if (contains(opt, "H"))
1684 preamble.registerAutomaticallyLoadedPackage("float");
1685 os << "wide " << convert<string>(is_starred)
1686 << "\nsideways true"
1687 << "\nstatus open\n\n";
1688 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1690 // We don't need really a new paragraph, but
1691 // we must make sure that the next item gets a \begin_layout.
1692 parent_context.new_paragraph(os);
1694 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1697 else if (name == "wrapfigure" || name == "wraptable") {
1698 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1699 eat_whitespace(p, os, parent_context, false);
1700 parent_context.check_layout(os);
1703 string overhang = "0col%";
1706 lines = p.getArg('[', ']');
1707 string const placement = p.getArg('{', '}');
1709 overhang = p.getArg('[', ']');
1710 string const width = p.getArg('{', '}');
1712 if (name == "wrapfigure")
1713 begin_inset(os, "Wrap figure\n");
1715 begin_inset(os, "Wrap table\n");
1716 os << "lines " << lines
1717 << "\nplacement " << placement
1718 << "\noverhang " << lyx::translate_len(overhang)
1719 << "\nwidth " << lyx::translate_len(width)
1720 << "\nstatus open\n\n";
1721 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1723 // We don't need really a new paragraph, but
1724 // we must make sure that the next item gets a \begin_layout.
1725 parent_context.new_paragraph(os);
1727 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1730 else if (name == "minipage") {
1731 eat_whitespace(p, os, parent_context, false);
1732 // Test whether this is an outer box of a shaded box
1734 // swallow arguments
1735 while (p.hasOpt()) {
1737 p.skip_spaces(true);
1740 p.skip_spaces(true);
1741 Token t = p.get_token();
1742 bool shaded = false;
1743 if (t.asInput() == "\\begin") {
1744 p.skip_spaces(true);
1745 if (p.getArg('{', '}') == "shaded")
1750 parse_outer_box(p, os, FLAG_END, outer,
1751 parent_context, name, "shaded");
1753 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1754 "", "", name, "", "");
1758 else if (name == "comment") {
1759 eat_whitespace(p, os, parent_context, false);
1760 parent_context.check_layout(os);
1761 begin_inset(os, "Note Comment\n");
1762 os << "status open\n";
1763 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1766 skip_braces(p); // eat {} that might by set by LyX behind comments
1767 preamble.registerAutomaticallyLoadedPackage("verbatim");
1770 else if (unstarred_name == "verbatim") {
1771 // FIXME: this should go in the generic code that
1772 // handles environments defined in layout file that
1773 // have "PassThru 1". However, the code over there is
1774 // already too complicated for my taste.
1775 string const ascii_name =
1776 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1777 parent_context.new_paragraph(os);
1778 Context context(true, parent_context.textclass,
1779 &parent_context.textclass[from_ascii(ascii_name)]);
1780 string s = p.verbatimEnvironment(name);
1781 output_ert(os, s, context);
1785 else if (name == "IPA") {
1786 eat_whitespace(p, os, parent_context, false);
1787 parent_context.check_layout(os);
1788 begin_inset(os, "IPA\n");
1789 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1792 preamble.registerAutomaticallyLoadedPackage("tipa");
1793 preamble.registerAutomaticallyLoadedPackage("tipx");
1796 else if (name == "CJK") {
1797 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1798 // It is impossible to decide if a CJK environment was in its own paragraph or within
1799 // a line. We therefore always assume a paragraph since the latter is a rare case.
1800 eat_whitespace(p, os, parent_context, false);
1801 parent_context.check_end_layout(os);
1802 // store the encoding to be able to reset it
1803 string const encoding_old = p.getEncoding();
1804 string const encoding = p.getArg('{', '}');
1805 // FIXME: For some reason JIS does not work. Although the text
1806 // in tests/CJK.tex is identical with the SJIS version if you
1807 // convert both snippets using the recode command line utility,
1808 // the resulting .lyx file contains some extra characters if
1809 // you set buggy_encoding to false for JIS.
1810 bool const buggy_encoding = encoding == "JIS";
1811 if (!buggy_encoding)
1812 p.setEncoding(encoding, Encoding::CJK);
1814 // FIXME: This will read garbage, since the data is not encoded in utf8.
1815 p.setEncoding("UTF-8");
1817 // LyX only supports the same mapping for all CJK
1818 // environments, so we might need to output everything as ERT
1819 string const mapping = trim(p.getArg('{', '}'));
1820 char const * const * const where =
1821 is_known(encoding, supported_CJK_encodings);
1822 if (!buggy_encoding && !preamble.fontCJKSet())
1823 preamble.fontCJK(mapping);
1824 bool knownMapping = mapping == preamble.fontCJK();
1825 if (buggy_encoding || !knownMapping || !where) {
1826 parent_context.check_layout(os);
1827 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1829 // we must parse the content as verbatim because e.g. JIS can contain
1830 // normally invalid characters
1831 // FIXME: This works only for the most simple cases.
1832 // Since TeX control characters are not parsed,
1833 // things like comments are completely wrong.
1834 string const s = p.plainEnvironment("CJK");
1835 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1838 if (snip == "\\" || is_known(snip, known_escaped_chars))
1839 output_ert_inset(os, snip, parent_context);
1840 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1845 output_ert_inset(os, "\\end{" + name + "}",
1849 supported_CJK_languages[where - supported_CJK_encodings];
1850 // store the language because we must reset it at the end
1851 string const lang_old = parent_context.font.language;
1852 parent_context.font.language = lang;
1853 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1854 parent_context.font.language = lang_old;
1855 parent_context.new_paragraph(os);
1857 p.setEncoding(encoding_old);
1861 else if (name == "lyxgreyedout") {
1862 eat_whitespace(p, os, parent_context, false);
1863 parent_context.check_layout(os);
1864 begin_inset(os, "Note Greyedout\n");
1865 os << "status open\n";
1866 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1869 if (!preamble.notefontcolor().empty())
1870 preamble.registerAutomaticallyLoadedPackage("color");
1873 else if (name == "btSect") {
1874 eat_whitespace(p, os, parent_context, false);
1875 parent_context.check_layout(os);
1876 begin_command_inset(os, "bibtex", "bibtex");
1877 string bibstyle = "plain";
1879 bibstyle = p.getArg('[', ']');
1880 p.skip_spaces(true);
1882 string const bibfile = p.getArg('{', '}');
1883 eat_whitespace(p, os, parent_context, false);
1884 Token t = p.get_token();
1885 if (t.asInput() == "\\btPrintCited") {
1886 p.skip_spaces(true);
1887 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1889 if (t.asInput() == "\\btPrintNotCited") {
1890 p.skip_spaces(true);
1891 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1893 if (t.asInput() == "\\btPrintAll") {
1894 p.skip_spaces(true);
1895 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1897 os << "bibfiles " << '"' << bibfile << "\"\n"
1898 << "options " << '"' << bibstyle << "\"\n";
1899 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1904 else if (name == "framed" || name == "shaded") {
1905 eat_whitespace(p, os, parent_context, false);
1906 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1908 preamble.registerAutomaticallyLoadedPackage("framed");
1911 else if (name == "listing") {
1912 minted_float = "float";
1913 eat_whitespace(p, os, parent_context, false);
1914 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1916 minted_float += "=" + opt;
1917 // If something precedes \begin{minted}, we output it at the end
1918 // as a caption, in order to keep it inside the listings inset.
1919 eat_whitespace(p, os, parent_context, true);
1921 Token const & t = p.get_token();
1922 p.skip_spaces(true);
1923 string const envname = p.next_token().cat() == catBegin
1924 ? p.getArg('{', '}') : string();
1925 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1927 minted_float_has_caption = false;
1928 string content = parse_text_snippet(p, FLAG_END, outer,
1930 size_t i = content.find("\\begin_inset listings");
1931 bool minted_env = i != string::npos;
1934 caption = content.substr(0, i);
1935 content.erase(0, i);
1937 parent_context.check_layout(os);
1938 if (minted_env && minted_float_has_caption) {
1939 eat_whitespace(p, os, parent_context, true);
1940 os << content << "\n";
1941 if (!caption.empty())
1942 os << caption << "\n";
1943 os << "\n\\end_layout\n"; // close inner layout
1944 end_inset(os); // close caption inset
1945 os << "\n\\end_layout\n"; // close outer layout
1946 } else if (!caption.empty()) {
1948 begin_inset(os, "listings\n");
1949 os << "lstparams " << '"' << minted_float << '"' << '\n';
1950 os << "inline false\n";
1951 os << "status collapsed\n";
1953 os << "\n\\begin_layout Plain Layout\n";
1954 begin_inset(os, "Caption Standard\n");
1955 Context newcontext(true, parent_context.textclass,
1956 0, 0, parent_context.font);
1957 newcontext.check_layout(os);
1958 os << caption << "\n";
1959 newcontext.check_end_layout(os);
1961 os << "\n\\end_layout\n";
1962 } else if (content.empty()) {
1963 begin_inset(os, "listings\n");
1964 os << "lstparams " << '"' << minted_float << '"' << '\n';
1965 os << "inline false\n";
1966 os << "status collapsed\n";
1968 os << content << "\n";
1970 end_inset(os); // close listings inset
1971 parent_context.check_end_layout(os);
1972 parent_context.new_paragraph(os);
1974 minted_float.clear();
1975 minted_float_has_caption = false;
1978 else if (name == "lstlisting" || name == "minted") {
1979 bool use_minted = name == "minted";
1980 eat_whitespace(p, os, parent_context, false);
1981 if (use_minted && minted_float.empty()) {
1982 // look ahead for a bottom caption
1984 bool found_end_minted = false;
1985 while (!found_end_minted && p.good()) {
1986 Token const & t = p.get_token();
1988 string const envname =
1989 p.next_token().cat() == catBegin
1990 ? p.getArg('{', '}') : string();
1991 found_end_minted = t.asInput() == "\\end"
1992 && envname == "minted";
1994 eat_whitespace(p, os, parent_context, true);
1995 Token const & t = p.get_token();
1996 p.skip_spaces(true);
1997 if (t.asInput() == "\\lyxmintcaption") {
1998 string const pos = p.getArg('[', ']');
2000 string const caption =
2001 parse_text_snippet(p, FLAG_ITEM,
2002 false, parent_context);
2003 minted_nonfloat_caption = "[b]" + caption;
2008 parse_listings(p, os, parent_context, false, use_minted);
2012 else if (!parent_context.new_layout_allowed)
2013 parse_unknown_environment(p, name, os, FLAG_END, outer,
2016 // Alignment and spacing settings
2017 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2018 // therefore are totally broken!
2019 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2020 // they are commands not environments. They are furthermore switches that
2021 // can be ended by another switches, but also by commands like \footnote or
2022 // \parbox. So the only safe way is to leave them untouched.
2023 // However, we support the pseudo-environments
2024 // \begin{centering} ... \end{centering}
2025 // \begin{raggedright} ... \end{raggedright}
2026 // \begin{raggedleft} ... \end{raggedleft}
2027 // since they are used by LyX in floats (for spacing reasons)
2028 else if (name == "center" || name == "centering" ||
2029 name == "flushleft" || name == "raggedright" ||
2030 name == "flushright" || name == "raggedleft" ||
2031 name == "singlespace" || name == "onehalfspace" ||
2032 name == "doublespace" || name == "spacing") {
2033 eat_whitespace(p, os, parent_context, false);
2034 // We must begin a new paragraph if not already done
2035 if (! parent_context.atParagraphStart()) {
2036 parent_context.check_end_layout(os);
2037 parent_context.new_paragraph(os);
2039 if (name == "flushleft" || name == "raggedright")
2040 parent_context.add_extra_stuff("\\align left\n");
2041 else if (name == "flushright" || name == "raggedleft")
2042 parent_context.add_extra_stuff("\\align right\n");
2043 else if (name == "center" || name == "centering")
2044 parent_context.add_extra_stuff("\\align center\n");
2045 else if (name == "singlespace")
2046 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2047 else if (name == "onehalfspace") {
2048 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2049 preamble.registerAutomaticallyLoadedPackage("setspace");
2050 } else if (name == "doublespace") {
2051 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2052 preamble.registerAutomaticallyLoadedPackage("setspace");
2053 } else if (name == "spacing") {
2054 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2055 preamble.registerAutomaticallyLoadedPackage("setspace");
2057 parse_text(p, os, FLAG_END, outer, parent_context);
2058 // Just in case the environment is empty
2059 parent_context.extra_stuff.erase();
2060 // We must begin a new paragraph to reset the alignment
2061 parent_context.new_paragraph(os);
2065 // The single '=' is meant here.
2066 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2067 eat_whitespace(p, os, parent_context, false);
2068 Context context(true, parent_context.textclass, newlayout,
2069 parent_context.layout, parent_context.font);
2070 if (parent_context.deeper_paragraph) {
2071 // We are beginning a nested environment after a
2072 // deeper paragraph inside the outer list environment.
2073 // Therefore we don't need to output a "begin deeper".
2074 context.need_end_deeper = true;
2076 parent_context.check_end_layout(os);
2077 if (last_env == name) {
2078 // we need to output a separator since LyX would export
2079 // the two environments as one otherwise (bug 5716)
2080 TeX2LyXDocClass const & textclass(parent_context.textclass);
2081 Context newcontext(true, textclass,
2082 &(textclass.defaultLayout()));
2083 newcontext.check_layout(os);
2084 begin_inset(os, "Separator plain\n");
2086 newcontext.check_end_layout(os);
2088 switch (context.layout->latextype) {
2089 case LATEX_LIST_ENVIRONMENT:
2090 context.add_par_extra_stuff("\\labelwidthstring "
2091 + p.verbatim_item() + '\n');
2094 case LATEX_BIB_ENVIRONMENT:
2095 p.verbatim_item(); // swallow next arg
2101 context.check_deeper(os);
2102 if (newlayout->keepempty) {
2103 // We need to start a new paragraph
2104 // even if it is empty.
2105 context.new_paragraph(os);
2106 context.check_layout(os);
2108 // handle known optional and required arguments
2109 if (context.layout->latextype == LATEX_ENVIRONMENT)
2110 output_arguments(os, p, outer, false, string(), context,
2111 context.layout->latexargs());
2112 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2114 output_arguments(oss, p, outer, false, string(), context,
2115 context.layout->latexargs());
2116 context.list_extra_stuff = oss.str();
2118 parse_text(p, os, FLAG_END, outer, context);
2119 if (context.layout->latextype == LATEX_ENVIRONMENT)
2120 output_arguments(os, p, outer, false, "post", context,
2121 context.layout->postcommandargs());
2122 context.check_end_layout(os);
2123 if (parent_context.deeper_paragraph) {
2124 // We must suppress the "end deeper" because we
2125 // suppressed the "begin deeper" above.
2126 context.need_end_deeper = false;
2128 context.check_end_deeper(os);
2129 parent_context.new_paragraph(os);
2131 if (!preamble.titleLayoutFound())
2132 preamble.titleLayoutFound(newlayout->intitle);
2133 set<string> const & req = newlayout->requires();
2134 set<string>::const_iterator it = req.begin();
2135 set<string>::const_iterator en = req.end();
2136 for (; it != en; ++it)
2137 preamble.registerAutomaticallyLoadedPackage(*it);
2140 // The single '=' is meant here.
2141 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2142 eat_whitespace(p, os, parent_context, false);
2143 parent_context.check_layout(os);
2144 begin_inset(os, "Flex ");
2145 os << to_utf8(newinsetlayout->name()) << '\n'
2146 << "status collapsed\n";
2147 if (newinsetlayout->isPassThru()) {
2148 string const arg = p.verbatimEnvironment(name);
2149 Context context(true, parent_context.textclass,
2150 &parent_context.textclass.plainLayout(),
2151 parent_context.layout);
2152 output_ert(os, arg, parent_context);
2154 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2158 else if (name == "appendix") {
2159 // This is no good latex style, but it works and is used in some documents...
2160 eat_whitespace(p, os, parent_context, false);
2161 parent_context.check_end_layout(os);
2162 Context context(true, parent_context.textclass, parent_context.layout,
2163 parent_context.layout, parent_context.font);
2164 context.check_layout(os);
2165 os << "\\start_of_appendix\n";
2166 parse_text(p, os, FLAG_END, outer, context);
2167 context.check_end_layout(os);
2171 else if (known_environments.find(name) != known_environments.end()) {
2172 vector<ArgumentType> arguments = known_environments[name];
2173 // The last "argument" denotes wether we may translate the
2174 // environment contents to LyX
2175 // The default required if no argument is given makes us
2176 // compatible with the reLyXre environment.
2177 ArgumentType contents = arguments.empty() ?
2180 if (!arguments.empty())
2181 arguments.pop_back();
2182 // See comment in parse_unknown_environment()
2183 bool const specialfont =
2184 (parent_context.font != parent_context.normalfont);
2185 bool const new_layout_allowed =
2186 parent_context.new_layout_allowed;
2188 parent_context.new_layout_allowed = false;
2189 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2190 outer, parent_context);
2191 if (contents == verbatim)
2192 output_ert_inset(os, p.ertEnvironment(name),
2195 parse_text_snippet(p, os, FLAG_END, outer,
2197 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2199 parent_context.new_layout_allowed = new_layout_allowed;
2203 parse_unknown_environment(p, name, os, FLAG_END, outer,
2207 active_environments.pop_back();
2211 /// parses a comment and outputs it to \p os.
2212 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2214 LASSERT(t.cat() == catComment, return);
2215 if (!t.cs().empty()) {
2216 context.check_layout(os);
2217 output_comment(p, os, t.cs(), context);
2218 if (p.next_token().cat() == catNewline) {
2219 // A newline after a comment line starts a new
2221 if (context.new_layout_allowed) {
2222 if(!context.atParagraphStart())
2223 // Only start a new paragraph if not already
2224 // done (we might get called recursively)
2225 context.new_paragraph(os);
2227 output_ert_inset(os, "\n", context);
2228 eat_whitespace(p, os, context, true);
2231 // "%\n" combination
2238 * Reads spaces and comments until the first non-space, non-comment token.
2239 * New paragraphs (double newlines or \\par) are handled like simple spaces
2240 * if \p eatParagraph is true.
2241 * Spaces are skipped, but comments are written to \p os.
2243 void eat_whitespace(Parser & p, ostream & os, Context & context,
2247 Token const & t = p.get_token();
2248 if (t.cat() == catComment)
2249 parse_comment(p, os, t, context);
2250 else if ((! eatParagraph && p.isParagraph()) ||
2251 (t.cat() != catSpace && t.cat() != catNewline)) {
2260 * Set a font attribute, parse text and reset the font attribute.
2261 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2262 * \param currentvalue Current value of the attribute. Is set to the new
2263 * value during parsing.
2264 * \param newvalue New value of the attribute
2266 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2267 Context & context, string const & attribute,
2268 string & currentvalue, string const & newvalue)
2270 context.check_layout(os);
2271 string const oldvalue = currentvalue;
2272 currentvalue = newvalue;
2273 os << '\n' << attribute << ' ' << newvalue << "\n";
2274 parse_text_snippet(p, os, flags, outer, context);
2275 context.check_layout(os);
2276 os << '\n' << attribute << ' ' << oldvalue << "\n";
2277 currentvalue = oldvalue;
2281 /// get the arguments of a natbib or jurabib citation command
2282 void get_cite_arguments(Parser & p, bool natbibOrder,
2283 string & before, string & after, bool const qualified = false)
2285 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2287 // text before the citation
2289 // text after the citation
2290 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2292 if (!after.empty()) {
2293 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2294 if (natbibOrder && !before.empty())
2295 swap(before, after);
2300 void copy_file(FileName const & src, string dstname)
2304 string const absParent = getParentFilePath(false);
2306 if (FileName::isAbsolute(dstname))
2307 dst = FileName(dstname);
2309 dst = makeAbsPath(dstname, absParent);
2310 FileName const srcpath = src.onlyPath();
2311 FileName const dstpath = dst.onlyPath();
2312 if (equivalent(srcpath, dstpath))
2314 if (!dstpath.isDirectory()) {
2315 if (!dstpath.createPath()) {
2316 cerr << "Warning: Could not create directory for file `"
2317 << dst.absFileName() << "´." << endl;
2321 if (dst.isReadableFile()) {
2322 if (overwriteFiles())
2323 cerr << "Warning: Overwriting existing file `"
2324 << dst.absFileName() << "´." << endl;
2326 cerr << "Warning: Not overwriting existing file `"
2327 << dst.absFileName() << "´." << endl;
2331 if (!src.copyTo(dst))
2332 cerr << "Warning: Could not copy file `" << src.absFileName()
2333 << "´ to `" << dst.absFileName() << "´." << endl;
2337 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2338 bool parse_chunk(Parser & p, ostream & os, Context & context)
2340 // check whether a chunk is possible here.
2341 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2347 // read the parameters
2348 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2349 if (!params.first) {
2354 Parser::Arg const code = p.verbatimStuff("\n@");
2359 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2360 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2364 // The last newline read is important for paragraph handling
2368 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2369 // We must have a valid layout before outputting the Chunk inset.
2370 context.check_layout(os);
2371 Context chunkcontext(true, context.textclass);
2372 chunkcontext.layout = &context.textclass.plainLayout();
2373 begin_inset(os, "Flex Chunk");
2374 os << "\nstatus open\n";
2375 if (!params.second.empty()) {
2376 chunkcontext.check_layout(os);
2377 Context paramscontext(true, context.textclass);
2378 paramscontext.layout = &context.textclass.plainLayout();
2379 begin_inset(os, "Argument 1");
2380 os << "\nstatus open\n";
2381 output_ert(os, params.second, paramscontext);
2384 output_ert(os, code.second, chunkcontext);
2392 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2393 bool is_macro(Parser & p)
2395 Token first = p.curr_token();
2396 if (first.cat() != catEscape || !p.good())
2398 if (first.cs() == "def")
2400 if (first.cs() != "global" && first.cs() != "long")
2402 Token second = p.get_token();
2404 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2405 second.cat() == catNewline || second.cat() == catComment)) {
2406 second = p.get_token();
2409 bool secondvalid = second.cat() == catEscape;
2411 bool thirdvalid = false;
2412 if (p.good() && first.cs() == "global" && secondvalid &&
2413 second.cs() == "long") {
2414 third = p.get_token();
2416 while (p.good() && !p.isParagraph() &&
2417 (third.cat() == catSpace ||
2418 third.cat() == catNewline ||
2419 third.cat() == catComment)) {
2420 third = p.get_token();
2423 thirdvalid = third.cat() == catEscape;
2425 for (int i = 0; i < pos; ++i)
2430 return (first.cs() == "global" || first.cs() == "long") &&
2431 second.cs() == "def";
2432 return first.cs() == "global" && second.cs() == "long" &&
2433 third.cs() == "def";
2437 /// Parse a macro definition (assumes that is_macro() returned true)
2438 void parse_macro(Parser & p, ostream & os, Context & context)
2440 context.check_layout(os);
2441 Token first = p.curr_token();
2444 string command = first.asInput();
2445 if (first.cs() != "def") {
2447 eat_whitespace(p, os, context, false);
2448 second = p.curr_token();
2449 command += second.asInput();
2450 if (second.cs() != "def") {
2452 eat_whitespace(p, os, context, false);
2453 third = p.curr_token();
2454 command += third.asInput();
2457 eat_whitespace(p, os, context, false);
2458 string const name = p.get_token().cs();
2459 eat_whitespace(p, os, context, false);
2465 while (p.next_token().cat() != catBegin) {
2466 if (p.next_token().cat() == catParameter) {
2471 // followed by number?
2472 if (p.next_token().cat() == catOther) {
2473 string s = p.get_token().asInput();
2475 // number = current arity + 1?
2476 if (s.size() == 1 && s[0] == arity + '0' + 1)
2481 paramtext += p.get_token().cs();
2483 paramtext += p.get_token().cs();
2488 // only output simple (i.e. compatible) macro as FormulaMacros
2489 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2491 context.check_layout(os);
2492 begin_inset(os, "FormulaMacro");
2493 os << "\n\\def" << ert;
2496 output_ert_inset(os, command + ert, context);
2500 void registerExternalTemplatePackages(string const & name)
2502 external::TemplateManager const & etm = external::TemplateManager::get();
2503 external::Template const * const et = etm.getTemplateByName(name);
2506 external::Template::Formats::const_iterator cit = et->formats.end();
2508 cit = et->formats.find("PDFLaTeX");
2509 if (cit == et->formats.end())
2510 // If the template has not specified a PDFLaTeX output,
2511 // we try the LaTeX format.
2512 cit = et->formats.find("LaTeX");
2513 if (cit == et->formats.end())
2515 vector<string>::const_iterator qit = cit->second.requirements.begin();
2516 vector<string>::const_iterator qend = cit->second.requirements.end();
2517 for (; qit != qend; ++qit)
2518 preamble.registerAutomaticallyLoadedPackage(*qit);
2521 } // anonymous namespace
2525 * Find a file with basename \p name in path \p path and an extension
2528 string find_file(string const & name, string const & path,
2529 char const * const * extensions)
2531 for (char const * const * what = extensions; *what; ++what) {
2532 string const trial = addExtension(name, *what);
2533 if (makeAbsPath(trial, path).exists())
2540 /// Convert filenames with TeX macros and/or quotes to something LyX
2542 string const normalize_filename(string const & name)
2547 Token const & t = p.get_token();
2548 if (t.cat() != catEscape)
2550 else if (t.cs() == "lyxdot") {
2551 // This is used by LyX for simple dots in relative
2555 } else if (t.cs() == "space") {
2558 } else if (t.cs() == "string") {
2559 // Convert \string" to " and \string~ to ~
2560 Token const & n = p.next_token();
2561 if (n.asInput() != "\"" && n.asInput() != "~")
2566 // Strip quotes. This is a bit complicated (see latex_path()).
2567 string full = os.str();
2568 if (!full.empty() && full[0] == '"') {
2569 string base = removeExtension(full);
2570 string ext = getExtension(full);
2571 if (!base.empty() && base[base.length()-1] == '"')
2574 return addExtension(trim(base, "\""), ext);
2575 if (full[full.length()-1] == '"')
2578 return trim(full, "\"");
2584 /// Convert \p name from TeX convention (relative to master file) to LyX
2585 /// convention (relative to .lyx file) if it is relative
2586 void fix_child_filename(string & name)
2588 string const absMasterTeX = getMasterFilePath(true);
2589 bool const isabs = FileName::isAbsolute(name);
2590 // convert from "relative to .tex master" to absolute original path
2592 name = makeAbsPath(name, absMasterTeX).absFileName();
2593 bool copyfile = copyFiles();
2594 string const absParentLyX = getParentFilePath(false);
2597 // convert from absolute original path to "relative to master file"
2598 string const rel = to_utf8(makeRelPath(from_utf8(name),
2599 from_utf8(absMasterTeX)));
2600 // re-interpret "relative to .tex file" as "relative to .lyx file"
2601 // (is different if the master .lyx file resides in a
2602 // different path than the master .tex file)
2603 string const absMasterLyX = getMasterFilePath(false);
2604 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2605 // Do not copy if the new path is impossible to create. Example:
2606 // absMasterTeX = "/foo/bar/"
2607 // absMasterLyX = "/bar/"
2608 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2609 if (contains(name, "/../"))
2616 // convert from absolute original path to
2617 // "relative to .lyx file"
2618 name = to_utf8(makeRelPath(from_utf8(abs),
2619 from_utf8(absParentLyX)));
2623 // convert from absolute original path to "relative to .lyx file"
2624 name = to_utf8(makeRelPath(from_utf8(name),
2625 from_utf8(absParentLyX)));
2630 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2631 Context & context, string const rdelim)
2633 Layout const * newlayout = 0;
2634 InsetLayout const * newinsetlayout = 0;
2635 char const * const * where = 0;
2636 // Store the latest bibliographystyle, addcontentslineContent and
2637 // nocite{*} option (needed for bibtex inset)
2639 string contentslineContent;
2640 string bibliographystyle = "default";
2641 bool const use_natbib = isProvided("natbib");
2642 bool const use_jurabib = isProvided("jurabib");
2643 bool const use_biblatex = isProvided("biblatex")
2644 && preamble.citeEngine() != "biblatex-natbib";
2645 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2646 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2647 need_commentbib = use_biblatex || use_biblatex_natbib;
2650 // it is impossible to determine the correct encoding for non-CJK Japanese.
2651 // Therefore write a note at the beginning of the document
2652 if (is_nonCJKJapanese) {
2653 context.check_layout(os);
2654 begin_inset(os, "Note Note\n");
2655 os << "status open\n\\begin_layout Plain Layout\n"
2656 << "\\series bold\n"
2657 << "Important information:\n"
2658 << "\\end_layout\n\n"
2659 << "\\begin_layout Plain Layout\n"
2660 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2661 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2662 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2663 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2664 << " and specify the encoding using the -e command-line switch.\n"
2665 << " In addition, you might want to double check that the desired output encoding\n"
2666 << " is correctly selected in Document > Settings > Language.\n"
2667 << "\\end_layout\n";
2669 is_nonCJKJapanese = false;
2672 bool have_cycled = false;
2674 // Leave here only after at least one cycle
2675 if (have_cycled && flags & FLAG_LEAVE) {
2676 flags &= ~FLAG_LEAVE;
2680 Token const & t = p.get_token();
2682 debugToken(cerr, t, flags);
2685 if (flags & FLAG_ITEM) {
2686 if (t.cat() == catSpace)
2689 flags &= ~FLAG_ITEM;
2690 if (t.cat() == catBegin) {
2691 // skip the brace and collect everything to the next matching
2693 flags |= FLAG_BRACE_LAST;
2697 // handle only this single token, leave the loop if done
2698 flags |= FLAG_LEAVE;
2701 if (t.cat() != catEscape && t.character() == ']' &&
2702 (flags & FLAG_BRACK_LAST))
2704 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2706 string tok = t.asInput();
2707 // we only support delimiters with max 2 chars for now.
2708 if (rdelim.size() > 1)
2709 tok += p.next_token().asInput();
2710 if (t.cat() != catEscape && !rdelim.empty()
2711 && tok == rdelim && (flags & FLAG_RDELIM)) {
2712 if (rdelim.size() > 1)
2713 p.get_token(); // eat rdelim
2717 // If there is anything between \end{env} and \begin{env} we
2718 // don't need to output a separator.
2719 if (t.cat() != catSpace && t.cat() != catNewline &&
2720 t.asInput() != "\\begin")
2727 bool const starred = p.next_token().asInput() == "*";
2728 string const starredname(starred ? (t.cs() + '*') : t.cs());
2729 if (t.cat() == catMath) {
2730 // we are inside some text mode thingy, so opening new math is allowed
2731 context.check_layout(os);
2732 begin_inset(os, "Formula ");
2733 Token const & n = p.get_token();
2734 bool const display(n.cat() == catMath && outer);
2736 // TeX's $$...$$ syntax for displayed math
2738 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2740 p.get_token(); // skip the second '$' token
2742 // simple $...$ stuff
2745 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2750 // Prevent the conversion of a line break to a
2751 // space (bug 7668). This does not change the
2752 // output, but looks ugly in LyX.
2753 eat_whitespace(p, os, context, false);
2758 if (t.cat() == catSuper || t.cat() == catSub) {
2759 cerr << "catcode " << t << " illegal in text mode\n";
2763 // Basic support for quotes. We try to disambiguate
2764 // quotes from the context (e.g., a left english quote is
2765 // the same as a right german quote...).
2766 // Try to make a smart guess about the side
2767 Token const prev = p.prev_token();
2768 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2769 && prev.character() != '\n' && prev.character() != '~');
2770 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2771 context.check_layout(os);
2772 begin_inset(os, "Quotes ");
2773 os << guessQuoteStyle("eld", opening);
2779 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2780 context.check_layout(os);
2781 begin_inset(os, "Quotes ");
2782 os << guessQuoteStyle("erd", opening);
2789 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2790 context.check_layout(os);
2791 begin_inset(os, "Quotes ");
2792 os << guessQuoteStyle("ald", opening);
2799 if (t.asInput() == "<"
2800 && p.next_token().asInput() == "<") {
2801 bool has_chunk = false;
2805 has_chunk = parse_chunk(p, os, context);
2811 context.check_layout(os);
2812 begin_inset(os, "Quotes ");
2813 os << guessQuoteStyle("ard", opening);
2821 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2822 check_space(p, os, context);
2826 // babel shorthands (also used by polyglossia)
2827 // Since these can have different meanings for different languages
2828 // we import them as ERT (but they must be put in ERT to get output
2830 if (t.asInput() == "\"") {
2832 // These are known pairs. We put them together in
2833 // one ERT inset. In other cases (such as "a), only
2834 // the quotation mark is ERTed.
2835 if (p.next_token().asInput() == "\""
2836 || p.next_token().asInput() == "|"
2837 || p.next_token().asInput() == "-"
2838 || p.next_token().asInput() == "~"
2839 || p.next_token().asInput() == "="
2840 || p.next_token().asInput() == "/"
2841 || p.next_token().asInput() == "~"
2842 || p.next_token().asInput() == "'"
2843 || p.next_token().asInput() == "`"
2844 || p.next_token().asInput() == "<"
2845 || p.next_token().asInput() == ">") {
2846 s += p.next_token().asInput();
2849 output_ert_inset(os, s, context);
2853 if (t.character() == '[' && noweb_mode &&
2854 p.next_token().character() == '[') {
2855 // These can contain underscores
2857 string const s = p.getFullOpt() + ']';
2858 if (p.next_token().character() == ']')
2861 cerr << "Warning: Inserting missing ']' in '"
2862 << s << "'." << endl;
2863 output_ert_inset(os, s, context);
2867 if (t.cat() == catLetter) {
2868 context.check_layout(os);
2873 if (t.cat() == catOther ||
2874 t.cat() == catAlign ||
2875 t.cat() == catParameter) {
2876 context.check_layout(os);
2877 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2878 context.merging_hyphens_allowed &&
2879 context.font.family != "ttfamily" &&
2880 !context.layout->pass_thru) {
2881 if (p.next_next_token().asInput() == "-") {
2883 os << to_utf8(docstring(1, 0x2014));
2887 os << to_utf8(docstring(1, 0x2013));
2890 // This translates "&" to "\\&" which may be wrong...
2895 if (p.isParagraph()) {
2896 // In minted floating listings we will collect
2897 // everything into the caption, where multiple
2898 // paragraphs are forbidden.
2899 if (minted_float.empty()) {
2900 if (context.new_layout_allowed)
2901 context.new_paragraph(os);
2903 output_ert_inset(os, "\\par ", context);
2906 eat_whitespace(p, os, context, true);
2910 if (t.cat() == catActive) {
2911 context.check_layout(os);
2912 if (t.character() == '~') {
2913 if (context.layout->free_spacing)
2916 begin_inset(os, "space ~\n");
2924 if (t.cat() == catBegin) {
2925 Token const next = p.next_token();
2926 Token const end = p.next_next_token();
2927 if (next.cat() == catEnd) {
2929 Token const prev = p.prev_token();
2931 if (p.next_token().character() == '`')
2932 ; // ignore it in {}``
2934 output_ert_inset(os, "{}", context);
2935 } else if (next.cat() == catEscape &&
2936 is_known(next.cs(), known_quotes) &&
2937 end.cat() == catEnd) {
2938 // Something like {\textquoteright} (e.g.
2939 // from writer2latex). We may skip the
2940 // braces here for better readability.
2941 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2943 } else if (p.next_token().asInput() == "\\ascii") {
2944 // handle the \ascii characters
2945 // (the case without braces is handled later)
2946 // the code is "{\ascii\xxx}"
2947 p.get_token(); // eat \ascii
2948 string name2 = p.get_token().asInput();
2949 p.get_token(); // eat the final '}'
2950 string const name = "{\\ascii" + name2 + "}";
2954 // get the character from unicodesymbols
2955 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2956 Encodings::TEXT_CMD, termination, rem, &req);
2958 context.check_layout(os);
2961 output_ert_inset(os,
2962 to_utf8(rem), context);
2963 for (set<string>::const_iterator it = req.begin();
2964 it != req.end(); ++it)
2965 preamble.registerAutomaticallyLoadedPackage(*it);
2967 // we did not find a non-ert version
2968 output_ert_inset(os, name, context);
2970 context.check_layout(os);
2971 // special handling of font attribute changes
2972 Token const prev = p.prev_token();
2973 TeXFont const oldFont = context.font;
2974 if (next.character() == '[' ||
2975 next.character() == ']' ||
2976 next.character() == '*') {
2978 if (p.next_token().cat() == catEnd) {
2983 output_ert_inset(os, "{", context);
2984 parse_text_snippet(p, os,
2987 output_ert_inset(os, "}", context);
2989 } else if (! context.new_layout_allowed) {
2990 output_ert_inset(os, "{", context);
2991 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2993 output_ert_inset(os, "}", context);
2994 } else if (is_known(next.cs(), known_sizes)) {
2995 // next will change the size, so we must
2997 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2999 if (!context.atParagraphStart())
3001 << context.font.size << "\n";
3002 } else if (is_known(next.cs(), known_font_families)) {
3003 // next will change the font family, so we
3004 // must reset it here
3005 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3007 if (!context.atParagraphStart())
3009 << context.font.family << "\n";
3010 } else if (is_known(next.cs(), known_font_series)) {
3011 // next will change the font series, so we
3012 // must reset it here
3013 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3015 if (!context.atParagraphStart())
3017 << context.font.series << "\n";
3018 } else if (is_known(next.cs(), known_font_shapes)) {
3019 // next will change the font shape, so we
3020 // must reset it here
3021 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3023 if (!context.atParagraphStart())
3025 << context.font.shape << "\n";
3026 } else if (is_known(next.cs(), known_old_font_families) ||
3027 is_known(next.cs(), known_old_font_series) ||
3028 is_known(next.cs(), known_old_font_shapes)) {
3029 // next will change the font family, series
3030 // and shape, so we must reset it here
3031 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3033 if (!context.atParagraphStart())
3035 << context.font.family
3037 << context.font.series
3039 << context.font.shape << "\n";
3041 output_ert_inset(os, "{", context);
3042 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3044 output_ert_inset(os, "}", context);
3050 if (t.cat() == catEnd) {
3051 if (flags & FLAG_BRACE_LAST) {
3054 cerr << "stray '}' in text\n";
3055 output_ert_inset(os, "}", context);
3059 if (t.cat() == catComment) {
3060 parse_comment(p, os, t, context);
3065 // control sequences
3068 if (t.cs() == "(" || t.cs() == "[") {
3069 bool const simple = t.cs() == "(";
3070 context.check_layout(os);
3071 begin_inset(os, "Formula");
3072 os << " \\" << t.cs();
3073 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3074 os << '\\' << (simple ? ')' : ']');
3077 // Prevent the conversion of a line break to a
3078 // space (bug 7668). This does not change the
3079 // output, but looks ugly in LyX.
3080 eat_whitespace(p, os, context, false);
3085 if (t.cs() == "begin") {
3086 parse_environment(p, os, outer, last_env,
3091 if (t.cs() == "end") {
3092 if (flags & FLAG_END) {
3093 // eat environment name
3094 string const name = p.getArg('{', '}');
3095 if (name != active_environment())
3096 cerr << "\\end{" + name + "} does not match \\begin{"
3097 + active_environment() + "}\n";
3100 p.error("found 'end' unexpectedly");
3104 // "item" by default, but could be something else
3105 if (t.cs() == context.layout->itemcommand()) {
3107 if (context.layout->labeltype == LABEL_MANUAL) {
3108 // FIXME: This swallows comments, but we cannot use
3109 // eat_whitespace() since we must not output
3110 // anything before the item.
3111 p.skip_spaces(true);
3112 s = p.verbatimOption();
3114 p.skip_spaces(false);
3116 context.check_layout(os);
3117 if (context.has_item) {
3118 // An item in an unknown list-like environment
3119 // FIXME: Do this in check_layout()!
3120 context.has_item = false;
3121 string item = "\\" + context.layout->itemcommand();
3124 output_ert_inset(os, item, context);
3126 if (context.layout->labeltype != LABEL_MANUAL)
3127 output_arguments(os, p, outer, false, "item", context,
3128 context.layout->itemargs());
3129 if (!context.list_extra_stuff.empty()) {
3130 os << context.list_extra_stuff;
3131 context.list_extra_stuff.clear();
3133 else if (!s.empty()) {
3134 // LyX adds braces around the argument,
3135 // so we need to remove them here.
3136 if (s.size() > 2 && s[0] == '{' &&
3137 s[s.size()-1] == '}')
3138 s = s.substr(1, s.size()-2);
3139 // If the argument contains a space we
3140 // must put it into ERT: Otherwise LyX
3141 // would misinterpret the space as
3142 // item delimiter (bug 7663)
3143 if (contains(s, ' ')) {
3144 output_ert_inset(os, s, context);
3147 os << parse_text_snippet(p2,
3148 FLAG_BRACK_LAST, outer, context);
3150 // The space is needed to separate the
3151 // item from the rest of the sentence.
3153 eat_whitespace(p, os, context, false);
3158 if (t.cs() == "bibitem") {
3160 context.check_layout(os);
3161 eat_whitespace(p, os, context, false);
3162 string label = p.verbatimOption();
3163 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3164 bool const literal = !lbl.first;
3165 label = literal ? subst(label, "\n", " ") : lbl.second;
3166 string lit = literal ? "\"true\"" : "\"false\"";
3167 string key = convert_literate_command_inset_arg(p.verbatim_item());
3168 begin_command_inset(os, "bibitem", "bibitem");
3169 os << "label \"" << label << "\"\n"
3170 << "key \"" << key << "\"\n"
3171 << "literal " << lit << "\n";
3177 // catch the case of \def\inputGnumericTable
3179 if (t.cs() == "def") {
3180 Token second = p.next_token();
3181 if (second.cs() == "inputGnumericTable") {
3185 Token third = p.get_token();
3187 if (third.cs() == "input") {
3191 string name = normalize_filename(p.verbatim_item());
3192 string const path = getMasterFilePath(true);
3193 // We want to preserve relative / absolute filenames,
3194 // therefore path is only used for testing
3195 // The file extension is in every case ".tex".
3196 // So we need to remove this extension and check for
3197 // the original one.
3198 name = removeExtension(name);
3199 if (!makeAbsPath(name, path).exists()) {
3200 char const * const Gnumeric_formats[] = {"gnumeric",
3202 string const Gnumeric_name =
3203 find_file(name, path, Gnumeric_formats);
3204 if (!Gnumeric_name.empty())
3205 name = Gnumeric_name;
3207 FileName const absname = makeAbsPath(name, path);
3208 if (absname.exists()) {
3209 fix_child_filename(name);
3210 copy_file(absname, name);
3212 cerr << "Warning: Could not find file '"
3213 << name << "'." << endl;
3214 context.check_layout(os);
3215 begin_inset(os, "External\n\ttemplate ");
3216 os << "GnumericSpreadsheet\n\tfilename "
3219 context.check_layout(os);
3221 // register the packages that are automatically loaded
3222 // by the Gnumeric template
3223 registerExternalTemplatePackages("GnumericSpreadsheet");
3228 parse_macro(p, os, context);
3232 if (t.cs() == "noindent") {
3234 context.add_par_extra_stuff("\\noindent\n");
3238 if (t.cs() == "appendix") {
3239 context.add_par_extra_stuff("\\start_of_appendix\n");
3240 // We need to start a new paragraph. Otherwise the
3241 // appendix in 'bla\appendix\chapter{' would start
3243 context.new_paragraph(os);
3244 // We need to make sure that the paragraph is
3245 // generated even if it is empty. Otherwise the
3246 // appendix in '\par\appendix\par\chapter{' would
3248 context.check_layout(os);
3249 // FIXME: This is a hack to prevent paragraph
3250 // deletion if it is empty. Handle this better!
3251 output_comment(p, os,
3252 "dummy comment inserted by tex2lyx to "
3253 "ensure that this paragraph is not empty",
3255 // Both measures above may generate an additional
3256 // empty paragraph, but that does not hurt, because
3257 // whitespace does not matter here.
3258 eat_whitespace(p, os, context, true);
3262 // Must catch empty dates before findLayout is called below
3263 if (t.cs() == "date") {
3264 eat_whitespace(p, os, context, false);
3266 string const date = p.verbatim_item();
3269 preamble.suppressDate(true);
3272 preamble.suppressDate(false);
3273 if (context.new_layout_allowed &&
3274 (newlayout = findLayout(context.textclass,
3277 output_command_layout(os, p, outer,
3278 context, newlayout);
3279 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3280 if (!preamble.titleLayoutFound())
3281 preamble.titleLayoutFound(newlayout->intitle);
3282 set<string> const & req = newlayout->requires();
3283 set<string>::const_iterator it = req.begin();
3284 set<string>::const_iterator en = req.end();
3285 for (; it != en; ++it)
3286 preamble.registerAutomaticallyLoadedPackage(*it);
3288 output_ert_inset(os,
3289 "\\date{" + p.verbatim_item() + '}',
3295 // Before we look for the layout name with star and alone below, we check the layouts including
3296 // the LateXParam, which might be one or several options or a star.
3297 // The single '=' is meant here.
3298 if (context.new_layout_allowed &&
3299 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3300 // store the latexparam here. This is eaten in output_command_layout
3301 context.latexparam = newlayout->latexparam();
3303 output_command_layout(os, p, outer, context, newlayout);
3304 context.latexparam.clear();
3306 if (!preamble.titleLayoutFound())
3307 preamble.titleLayoutFound(newlayout->intitle);
3308 set<string> const & req = newlayout->requires();
3309 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3310 preamble.registerAutomaticallyLoadedPackage(*it);
3315 // Starred section headings
3316 // Must attempt to parse "Section*" before "Section".
3317 if ((p.next_token().asInput() == "*") &&
3318 context.new_layout_allowed &&
3319 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3322 output_command_layout(os, p, outer, context, newlayout);
3324 if (!preamble.titleLayoutFound())
3325 preamble.titleLayoutFound(newlayout->intitle);
3326 set<string> const & req = newlayout->requires();
3327 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3328 preamble.registerAutomaticallyLoadedPackage(*it);
3332 // Section headings and the like
3333 if (context.new_layout_allowed &&
3334 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3336 output_command_layout(os, p, outer, context, newlayout);
3338 if (!preamble.titleLayoutFound())
3339 preamble.titleLayoutFound(newlayout->intitle);
3340 set<string> const & req = newlayout->requires();
3341 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3342 preamble.registerAutomaticallyLoadedPackage(*it);
3346 if (t.cs() == "subfloat") {
3347 // the syntax is \subfloat[list entry][sub caption]{content}
3348 // if it is a table of figure depends on the surrounding float
3350 // do nothing if there is no outer float
3351 if (!float_type.empty()) {
3352 context.check_layout(os);
3354 begin_inset(os, "Float " + float_type + "\n");
3356 << "\nsideways false"
3357 << "\nstatus collapsed\n\n";
3360 bool has_caption = false;
3361 if (p.next_token().cat() != catEscape &&
3362 p.next_token().character() == '[') {
3363 p.get_token(); // eat '['
3364 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3367 // In case we have two optional args, the second is the caption.
3368 if (p.next_token().cat() != catEscape &&
3369 p.next_token().character() == '[') {
3370 p.get_token(); // eat '['
3371 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3374 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3375 // the caption comes always as the last
3377 // we must make sure that the caption gets a \begin_layout
3378 os << "\n\\begin_layout Plain Layout";
3380 begin_inset(os, "Caption Standard\n");
3381 Context newcontext(true, context.textclass,
3382 0, 0, context.font);
3383 newcontext.check_layout(os);
3384 os << caption << "\n";
3385 newcontext.check_end_layout(os);
3388 // close the layout we opened
3389 os << "\n\\end_layout";
3394 // if the float type is not supported or there is no surrounding float
3399 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3401 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3403 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3404 + "{" + p.verbatim_item() + '}', context);
3409 if (t.cs() == "includegraphics") {
3410 bool const clip = p.next_token().asInput() == "*";
3413 string const arg = p.getArg('[', ']');
3414 map<string, string> opts;
3415 vector<string> keys;
3416 split_map(arg, opts, keys);
3418 opts["clip"] = string();
3419 string name = normalize_filename(p.verbatim_item());
3421 string const path = getMasterFilePath(true);
3422 // We want to preserve relative / absolute filenames,
3423 // therefore path is only used for testing
3424 if (!makeAbsPath(name, path).exists()) {
3425 // The file extension is probably missing.
3426 // Now try to find it out.
3427 string const dvips_name =
3428 find_file(name, path,
3429 known_dvips_graphics_formats);
3430 string const pdftex_name =
3431 find_file(name, path,
3432 known_pdftex_graphics_formats);
3433 if (!dvips_name.empty()) {
3434 if (!pdftex_name.empty()) {
3435 cerr << "This file contains the "
3437 "\"\\includegraphics{"
3439 "However, files\n\""
3440 << dvips_name << "\" and\n\""
3441 << pdftex_name << "\"\n"
3442 "both exist, so I had to make a "
3443 "choice and took the first one.\n"
3444 "Please move the unwanted one "
3445 "someplace else and try again\n"
3446 "if my choice was wrong."
3450 } else if (!pdftex_name.empty()) {
3456 FileName const absname = makeAbsPath(name, path);
3457 if (absname.exists()) {
3458 fix_child_filename(name);
3459 copy_file(absname, name);
3461 cerr << "Warning: Could not find graphics file '"
3462 << name << "'." << endl;
3464 context.check_layout(os);
3465 begin_inset(os, "Graphics ");
3466 os << "\n\tfilename " << name << '\n';
3467 if (opts.find("width") != opts.end())
3469 << translate_len(opts["width"]) << '\n';
3470 if (opts.find("height") != opts.end())
3472 << translate_len(opts["height"]) << '\n';
3473 if (opts.find("scale") != opts.end()) {
3474 istringstream iss(opts["scale"]);
3478 os << "\tscale " << val << '\n';
3480 if (opts.find("angle") != opts.end()) {
3481 os << "\trotateAngle "
3482 << opts["angle"] << '\n';
3483 vector<string>::const_iterator a =
3484 find(keys.begin(), keys.end(), "angle");
3485 vector<string>::const_iterator s =
3486 find(keys.begin(), keys.end(), "width");
3487 if (s == keys.end())
3488 s = find(keys.begin(), keys.end(), "height");
3489 if (s == keys.end())
3490 s = find(keys.begin(), keys.end(), "scale");
3491 if (s != keys.end() && distance(s, a) > 0)
3492 os << "\tscaleBeforeRotation\n";
3494 if (opts.find("origin") != opts.end()) {
3496 string const opt = opts["origin"];
3497 if (opt.find('l') != string::npos) ss << "left";
3498 if (opt.find('r') != string::npos) ss << "right";
3499 if (opt.find('c') != string::npos) ss << "center";
3500 if (opt.find('t') != string::npos) ss << "Top";
3501 if (opt.find('b') != string::npos) ss << "Bottom";
3502 if (opt.find('B') != string::npos) ss << "Baseline";
3503 if (!ss.str().empty())
3504 os << "\trotateOrigin " << ss.str() << '\n';
3506 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3508 if (opts.find("keepaspectratio") != opts.end())
3509 os << "\tkeepAspectRatio\n";
3510 if (opts.find("clip") != opts.end())
3512 if (opts.find("draft") != opts.end())
3514 if (opts.find("bb") != opts.end())
3515 os << "\tBoundingBox "
3516 << opts["bb"] << '\n';
3517 int numberOfbbOptions = 0;
3518 if (opts.find("bbllx") != opts.end())
3519 numberOfbbOptions++;
3520 if (opts.find("bblly") != opts.end())
3521 numberOfbbOptions++;
3522 if (opts.find("bburx") != opts.end())
3523 numberOfbbOptions++;
3524 if (opts.find("bbury") != opts.end())
3525 numberOfbbOptions++;
3526 if (numberOfbbOptions == 4)
3527 os << "\tBoundingBox "
3528 << opts["bbllx"] << " " << opts["bblly"] << " "
3529 << opts["bburx"] << " " << opts["bbury"] << '\n';
3530 else if (numberOfbbOptions > 0)
3531 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3532 numberOfbbOptions = 0;
3533 if (opts.find("natwidth") != opts.end())
3534 numberOfbbOptions++;
3535 if (opts.find("natheight") != opts.end())
3536 numberOfbbOptions++;
3537 if (numberOfbbOptions == 2)
3538 os << "\tBoundingBox 0bp 0bp "
3539 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3540 else if (numberOfbbOptions > 0)
3541 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3542 ostringstream special;
3543 if (opts.find("hiresbb") != opts.end())
3544 special << "hiresbb,";
3545 if (opts.find("trim") != opts.end())
3547 if (opts.find("viewport") != opts.end())
3548 special << "viewport=" << opts["viewport"] << ',';
3549 if (opts.find("totalheight") != opts.end())
3550 special << "totalheight=" << opts["totalheight"] << ',';
3551 if (opts.find("type") != opts.end())
3552 special << "type=" << opts["type"] << ',';
3553 if (opts.find("ext") != opts.end())
3554 special << "ext=" << opts["ext"] << ',';
3555 if (opts.find("read") != opts.end())
3556 special << "read=" << opts["read"] << ',';
3557 if (opts.find("command") != opts.end())
3558 special << "command=" << opts["command"] << ',';
3559 string s_special = special.str();
3560 if (!s_special.empty()) {
3561 // We had special arguments. Remove the trailing ','.
3562 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3564 // TODO: Handle the unknown settings better.
3565 // Warn about invalid options.
3566 // Check whether some option was given twice.
3568 preamble.registerAutomaticallyLoadedPackage("graphicx");
3572 if (t.cs() == "footnote" ||
3573 (t.cs() == "thanks" && context.layout->intitle)) {
3575 context.check_layout(os);
3576 begin_inset(os, "Foot\n");
3577 os << "status collapsed\n\n";
3578 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3583 if (t.cs() == "marginpar") {
3585 context.check_layout(os);
3586 begin_inset(os, "Marginal\n");
3587 os << "status collapsed\n\n";
3588 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3593 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3594 bool const use_minted = t.cs() == "mintinline";
3596 parse_listings(p, os, context, true, use_minted);
3600 if (t.cs() == "ensuremath") {
3602 context.check_layout(os);
3603 string const s = p.verbatim_item();
3604 //FIXME: this never triggers in UTF8
3605 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3608 output_ert_inset(os, "\\ensuremath{" + s + "}",
3613 else if (t.cs() == "makeindex" || t.cs() == "maketitle" || t.cs() == "makebeamertitle") {
3614 if (preamble.titleLayoutFound()) {
3616 skip_spaces_braces(p);
3618 output_ert_inset(os, t.asInput(), context);
3622 if (t.cs() == "tableofcontents"
3623 || t.cs() == "lstlistoflistings"
3624 || t.cs() == "listoflistings") {
3625 string name = t.cs();
3626 if (preamble.minted() && name == "listoflistings")
3627 name.insert(0, "lst");
3628 context.check_layout(os);
3629 begin_command_inset(os, "toc", name);
3631 skip_spaces_braces(p);
3632 if (name == "lstlistoflistings") {
3633 if (preamble.minted())
3634 preamble.registerAutomaticallyLoadedPackage("minted");
3636 preamble.registerAutomaticallyLoadedPackage("listings");
3641 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3642 context.check_layout(os);
3643 if (t.cs() == "listoffigures")
3644 begin_inset(os, "FloatList figure\n");
3646 begin_inset(os, "FloatList table\n");
3648 skip_spaces_braces(p);
3652 if (t.cs() == "listof") {
3653 p.skip_spaces(true);
3654 string const name = p.get_token().cs();
3655 if (context.textclass.floats().typeExist(name)) {
3656 context.check_layout(os);
3657 begin_inset(os, "FloatList ");
3660 p.get_token(); // swallow second arg
3662 output_ert_inset(os, "\\listof{" + name + "}", context);
3666 if ((where = is_known(t.cs(), known_text_font_families))) {
3667 parse_text_attributes(p, os, FLAG_ITEM, outer,
3668 context, "\\family", context.font.family,
3669 known_coded_font_families[where - known_text_font_families]);
3673 // beamer has a \textbf<overlay>{} inset
3674 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3675 parse_text_attributes(p, os, FLAG_ITEM, outer,
3676 context, "\\series", context.font.series,
3677 known_coded_font_series[where - known_text_font_series]);
3681 // beamer has a \textit<overlay>{} inset
3682 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3683 parse_text_attributes(p, os, FLAG_ITEM, outer,
3684 context, "\\shape", context.font.shape,
3685 known_coded_font_shapes[where - known_text_font_shapes]);
3689 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3690 context.check_layout(os);
3691 TeXFont oldFont = context.font;
3692 context.font.init();
3693 context.font.size = oldFont.size;
3694 os << "\n\\family " << context.font.family << "\n";
3695 os << "\n\\series " << context.font.series << "\n";
3696 os << "\n\\shape " << context.font.shape << "\n";
3697 if (t.cs() == "textnormal") {
3698 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3699 output_font_change(os, context.font, oldFont);
3700 context.font = oldFont;
3702 eat_whitespace(p, os, context, false);
3706 if (t.cs() == "textcolor") {
3707 // scheme is \textcolor{color name}{text}
3708 string const color = p.verbatim_item();
3709 // we support the predefined colors of the color and the xcolor package
3710 if (color == "black" || color == "blue" || color == "cyan"
3711 || color == "green" || color == "magenta" || color == "red"
3712 || color == "white" || color == "yellow") {
3713 context.check_layout(os);
3714 os << "\n\\color " << color << "\n";
3715 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3716 context.check_layout(os);
3717 os << "\n\\color inherit\n";
3718 preamble.registerAutomaticallyLoadedPackage("color");
3719 } else if (color == "brown" || color == "darkgray" || color == "gray"
3720 || color == "lightgray" || color == "lime" || color == "olive"
3721 || color == "orange" || color == "pink" || color == "purple"
3722 || color == "teal" || color == "violet") {
3723 context.check_layout(os);
3724 os << "\n\\color " << color << "\n";
3725 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3726 context.check_layout(os);
3727 os << "\n\\color inherit\n";
3728 preamble.registerAutomaticallyLoadedPackage("xcolor");
3730 // for custom defined colors
3731 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3735 if (t.cs() == "underbar" || t.cs() == "uline") {
3736 // \underbar is not 100% correct (LyX outputs \uline
3737 // of ulem.sty). The difference is that \ulem allows
3738 // line breaks, and \underbar does not.
3739 // Do NOT handle \underline.
3740 // \underbar cuts through y, g, q, p etc.,
3741 // \underline does not.
3742 context.check_layout(os);
3743 os << "\n\\bar under\n";
3744 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3745 context.check_layout(os);
3746 os << "\n\\bar default\n";
3747 preamble.registerAutomaticallyLoadedPackage("ulem");
3751 if (t.cs() == "sout") {
3752 context.check_layout(os);
3753 os << "\n\\strikeout on\n";
3754 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3755 context.check_layout(os);
3756 os << "\n\\strikeout default\n";
3757 preamble.registerAutomaticallyLoadedPackage("ulem");
3761 // beamer has an \emph<overlay>{} inset
3762 if ((t.cs() == "uuline" || t.cs() == "uwave"
3763 || t.cs() == "emph" || t.cs() == "noun"
3764 || t.cs() == "xout") && !p.hasOpt("<")) {
3765 context.check_layout(os);
3766 os << "\n\\" << t.cs() << " on\n";
3767 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3768 context.check_layout(os);
3769 os << "\n\\" << t.cs() << " default\n";
3770 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3771 preamble.registerAutomaticallyLoadedPackage("ulem");
3775 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3776 context.check_layout(os);
3777 string name = p.getArg('{', '}');
3778 string localtime = p.getArg('{', '}');
3779 preamble.registerAuthor(name);
3780 Author const & author = preamble.getAuthor(name);
3781 // from_asctime_utc() will fail if LyX decides to output the
3782 // time in the text language.
3783 time_t ptime = from_asctime_utc(localtime);
3784 if (ptime == static_cast<time_t>(-1)) {
3785 cerr << "Warning: Could not parse time `" << localtime
3786 << "´ for change tracking, using current time instead.\n";
3787 ptime = current_time();
3789 if (t.cs() == "lyxadded")
3790 os << "\n\\change_inserted ";
3792 os << "\n\\change_deleted ";
3793 os << author.bufferId() << ' ' << ptime << '\n';
3794 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3795 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3796 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3797 LaTeXPackages::isAvailable("xcolor");
3798 // No need to test for luatex, since luatex comes in
3799 // two flavours (dvi and pdf), like latex, and those
3800 // are detected by pdflatex.
3801 if (pdflatex || xetex) {
3803 preamble.registerAutomaticallyLoadedPackage("ulem");
3804 preamble.registerAutomaticallyLoadedPackage("xcolor");
3805 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3809 preamble.registerAutomaticallyLoadedPackage("dvipost");
3810 } else if (xcolorulem) {
3811 preamble.registerAutomaticallyLoadedPackage("ulem");
3812 preamble.registerAutomaticallyLoadedPackage("xcolor");
3818 if (t.cs() == "textipa") {
3819 context.check_layout(os);
3820 begin_inset(os, "IPA\n");
3821 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3822 context.merging_hyphens_allowed = false;
3823 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3824 context.merging_hyphens_allowed = merging_hyphens_allowed;
3826 preamble.registerAutomaticallyLoadedPackage("tipa");
3827 preamble.registerAutomaticallyLoadedPackage("tipx");
3831 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3832 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3833 context.check_layout(os);
3837 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3838 begin_inset(os, "IPADeco " + type + "\n");
3839 os << "status open\n";
3840 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3846 if (t.cs() == "textvertline") {
3847 // FIXME: This is not correct, \textvertline is higher than |
3853 if (t.cs() == "tone" ) {
3854 context.check_layout(os);
3855 // register the tone package
3856 preamble.registerAutomaticallyLoadedPackage("tone");
3857 string content = trimSpaceAndEol(p.verbatim_item());
3858 string command = t.asInput() + "{" + content + "}";
3859 // some tones can be detected by unicodesymbols, some need special code
3860 if (is_known(content, known_tones)) {
3861 os << "\\IPAChar " << command << "\n";
3864 // try to see whether the string is in unicodesymbols
3868 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3869 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3870 termination, rem, &req);
3874 output_ert_inset(os, to_utf8(rem), context);
3875 for (set<string>::const_iterator it = req.begin();
3876 it != req.end(); ++it)
3877 preamble.registerAutomaticallyLoadedPackage(*it);
3879 // we did not find a non-ert version
3880 output_ert_inset(os, command, context);
3884 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3885 t.cs() == "vphantom") {
3886 context.check_layout(os);
3887 if (t.cs() == "phantom")
3888 begin_inset(os, "Phantom Phantom\n");
3889 if (t.cs() == "hphantom")
3890 begin_inset(os, "Phantom HPhantom\n");
3891 if (t.cs() == "vphantom")
3892 begin_inset(os, "Phantom VPhantom\n");
3893 os << "status open\n";
3894 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3900 if (t.cs() == "href") {
3901 context.check_layout(os);
3902 string target = convert_literate_command_inset_arg(p.verbatim_item());
3903 string name = p.verbatim_item();
3904 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3905 bool const literal = !nm.first;
3906 name = literal ? subst(name, "\n", " ") : nm.second;
3907 string lit = literal ? "\"true\"" : "\"false\"";
3909 size_t i = target.find(':');
3910 if (i != string::npos) {
3911 type = target.substr(0, i + 1);
3912 if (type == "mailto:" || type == "file:")
3913 target = target.substr(i + 1);
3914 // handle the case that name is equal to target, except of "http(s)://"
3915 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3918 begin_command_inset(os, "href", "href");
3920 os << "name \"" << name << "\"\n";
3921 os << "target \"" << target << "\"\n";
3922 if (type == "mailto:" || type == "file:")
3923 os << "type \"" << type << "\"\n";
3924 os << "literal " << lit << "\n";
3926 skip_spaces_braces(p);
3930 if (t.cs() == "lyxline") {
3931 // swallow size argument (it is not used anyway)
3933 if (!context.atParagraphStart()) {
3934 // so our line is in the middle of a paragraph
3935 // we need to add a new line, lest this line
3936 // follow the other content on that line and
3937 // run off the side of the page
3938 // FIXME: This may create an empty paragraph,
3939 // but without that it would not be
3940 // possible to set noindent below.
3941 // Fortunately LaTeX does not care
3942 // about the empty paragraph.
3943 context.new_paragraph(os);
3945 if (preamble.indentParagraphs()) {
3946 // we need to unindent, lest the line be too long
3947 context.add_par_extra_stuff("\\noindent\n");
3949 context.check_layout(os);
3950 begin_command_inset(os, "line", "rule");
3951 os << "offset \"0.5ex\"\n"
3952 "width \"100line%\"\n"
3958 if (t.cs() == "rule") {
3959 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3960 string const width = p.getArg('{', '}');
3961 string const thickness = p.getArg('{', '}');
3962 context.check_layout(os);
3963 begin_command_inset(os, "line", "rule");
3964 if (!offset.empty())
3965 os << "offset \"" << translate_len(offset) << "\"\n";
3966 os << "width \"" << translate_len(width) << "\"\n"
3967 "height \"" << translate_len(thickness) << "\"\n";
3972 // handle refstyle first to catch \eqref which can also occur
3973 // without refstyle. Only recognize these commands if
3974 // refstyle.sty was found in the preamble (otherwise \eqref
3975 // and user defined ref commands could be misdetected).
3976 if ((where = is_known(t.cs(), known_refstyle_commands))
3977 && preamble.refstyle()) {
3978 context.check_layout(os);
3979 begin_command_inset(os, "ref", "formatted");
3980 os << "reference \"";
3981 os << known_refstyle_prefixes[where - known_refstyle_commands]
3983 os << convert_literate_command_inset_arg(p.verbatim_item())
3985 os << "plural \"false\"\n";
3986 os << "caps \"false\"\n";
3987 os << "noprefix \"false\"\n";
3989 preamble.registerAutomaticallyLoadedPackage("refstyle");
3993 // if refstyle is used, we must not convert \prettyref to a
3994 // formatted reference, since that would result in a refstyle command.
3995 if ((where = is_known(t.cs(), known_ref_commands)) &&
3996 (t.cs() != "prettyref" || !preamble.refstyle())) {
3997 string const opt = p.getOpt();
3999 context.check_layout(os);
4000 begin_command_inset(os, "ref",
4001 known_coded_ref_commands[where - known_ref_commands]);
4002 os << "reference \""
4003 << convert_literate_command_inset_arg(p.verbatim_item())
4005 os << "plural \"false\"\n";
4006 os << "caps \"false\"\n";
4007 os << "noprefix \"false\"\n";
4009 if (t.cs() == "vref" || t.cs() == "vpageref")
4010 preamble.registerAutomaticallyLoadedPackage("varioref");
4011 else if (t.cs() == "prettyref")
4012 preamble.registerAutomaticallyLoadedPackage("prettyref");
4014 // LyX does not yet support optional arguments of ref commands
4015 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
4016 p.verbatim_item() + '}', context);
4022 is_known(t.cs(), known_natbib_commands) &&
4023 ((t.cs() != "citefullauthor" &&
4024 t.cs() != "citeyear" &&
4025 t.cs() != "citeyearpar") ||
4026 p.next_token().asInput() != "*")) {
4027 context.check_layout(os);
4028 string command = t.cs();
4029 if (p.next_token().asInput() == "*") {
4033 if (command == "citefullauthor")
4034 // alternative name for "\\citeauthor*"
4035 command = "citeauthor*";
4037 // text before the citation
4039 // text after the citation
4041 get_cite_arguments(p, true, before, after);
4043 if (command == "cite") {
4044 // \cite without optional argument means
4045 // \citet, \cite with at least one optional
4046 // argument means \citep.
4047 if (before.empty() && after.empty())
4052 if (before.empty() && after == "[]")
4053 // avoid \citet[]{a}
4055 else if (before == "[]" && after == "[]") {
4056 // avoid \citet[][]{a}
4060 bool literal = false;
4061 pair<bool, string> aft;
4062 pair<bool, string> bef;
4063 // remove the brackets around after and before
4064 if (!after.empty()) {
4066 after.erase(after.length() - 1, 1);
4067 aft = convert_latexed_command_inset_arg(after);
4068 literal = !aft.first;
4069 after = literal ? subst(after, "\n", " ") : aft.second;
4071 if (!before.empty()) {
4073 before.erase(before.length() - 1, 1);
4074 bef = convert_latexed_command_inset_arg(before);
4075 literal |= !bef.first;
4076 before = literal ? subst(before, "\n", " ") : bef.second;
4077 if (literal && !after.empty())
4078 after = subst(after, "\n", " ");
4080 string lit = literal ? "\"true\"" : "\"false\"";
4081 begin_command_inset(os, "citation", command);
4082 os << "after " << '"' << after << '"' << "\n";
4083 os << "before " << '"' << before << '"' << "\n";
4085 << convert_literate_command_inset_arg(p.verbatim_item())
4087 << "literal " << lit << "\n";
4089 // Need to set the cite engine if natbib is loaded by
4090 // the document class directly
4091 if (preamble.citeEngine() == "basic")
4092 preamble.citeEngine("natbib");
4097 && is_known(t.cs(), known_biblatex_commands)
4098 && ((t.cs() == "cite"
4099 || t.cs() == "citeauthor"
4100 || t.cs() == "Citeauthor"
4101 || t.cs() == "parencite"
4102 || t.cs() == "citetitle")
4103 || p.next_token().asInput() != "*"))
4104 || (use_biblatex_natbib
4105 && (is_known(t.cs(), known_biblatex_commands)
4106 || is_known(t.cs(), known_natbib_commands))
4107 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4108 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4109 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4110 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4111 || t.cs() == "parencite" || t.cs() == "citetitle")
4112 || p.next_token().asInput() != "*"))){
4113 context.check_layout(os);
4114 string command = t.cs();
4115 if (p.next_token().asInput() == "*") {
4120 bool const qualified = suffixIs(command, "s");
4122 command = rtrim(command, "s");
4124 // text before the citation
4126 // text after the citation
4128 get_cite_arguments(p, true, before, after, qualified);
4130 // These use natbib cmd names in LyX
4131 // for inter-citeengine compativility
4132 if (command == "citeyear")
4133 command = "citebyear";
4134 else if (command == "cite*")
4135 command = "citeyear";
4136 else if (command == "textcite")
4138 else if (command == "Textcite")
4140 else if (command == "parencite")
4142 else if (command == "Parencite")
4144 else if (command == "parencite*")
4145 command = "citeyearpar";
4146 else if (command == "smartcite")
4147 command = "footcite";
4148 else if (command == "Smartcite")
4149 command = "Footcite";
4151 string const emptyarg = qualified ? "()" : "[]";
4152 if (before.empty() && after == emptyarg)
4155 else if (before == emptyarg && after == emptyarg) {
4156 // avoid \cite[][]{a}
4160 bool literal = false;
4161 pair<bool, string> aft;
4162 pair<bool, string> bef;
4163 // remove the brackets around after and before
4164 if (!after.empty()) {
4166 after.erase(after.length() - 1, 1);
4167 aft = convert_latexed_command_inset_arg(after);
4168 literal = !aft.first;
4169 after = literal ? subst(after, "\n", " ") : aft.second;
4171 if (!before.empty()) {
4173 before.erase(before.length() - 1, 1);
4174 bef = convert_latexed_command_inset_arg(before);
4175 literal |= !bef.first;
4176 before = literal ? subst(before, "\n", " ") : bef.second;
4178 string keys, pretextlist, posttextlist;
4180 map<string, string> pres, posts, preslit, postslit;
4181 vector<string> lkeys;
4182 // text before the citation
4183 string lbefore, lbeforelit;
4184 // text after the citation
4185 string lafter, lafterlit;
4187 pair<bool, string> laft, lbef;
4189 get_cite_arguments(p, true, lbefore, lafter);
4190 // remove the brackets around after and before
4191 if (!lafter.empty()) {
4193 lafter.erase(lafter.length() - 1, 1);
4194 laft = convert_latexed_command_inset_arg(lafter);
4195 literal |= !laft.first;
4196 lafter = laft.second;
4197 lafterlit = subst(lbefore, "\n", " ");
4199 if (!lbefore.empty()) {
4200 lbefore.erase(0, 1);
4201 lbefore.erase(lbefore.length() - 1, 1);
4202 lbef = convert_latexed_command_inset_arg(lbefore);
4203 literal |= !lbef.first;
4204 lbefore = lbef.second;
4205 lbeforelit = subst(lbefore, "\n", " ");
4207 if (lbefore.empty() && lafter == "[]") {
4212 else if (lbefore == "[]" && lafter == "[]") {
4213 // avoid \cite[][]{a}
4219 lkey = p.getArg('{', '}');
4222 if (!lbefore.empty()) {
4223 pres.insert(make_pair(lkey, lbefore));
4224 preslit.insert(make_pair(lkey, lbeforelit));
4226 if (!lafter.empty()) {
4227 posts.insert(make_pair(lkey, lafter));
4228 postslit.insert(make_pair(lkey, lafterlit));
4230 lkeys.push_back(lkey);
4232 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4237 for (auto const & ptl : pres) {
4238 if (!pretextlist.empty())
4239 pretextlist += '\t';
4240 pretextlist += ptl.first + " " + ptl.second;
4242 for (auto const & potl : posts) {
4243 if (!posttextlist.empty())
4244 posttextlist += '\t';
4245 posttextlist += potl.first + " " + potl.second;
4248 keys = convert_literate_command_inset_arg(p.verbatim_item());
4251 after = subst(after, "\n", " ");
4252 if (!before.empty())
4253 before = subst(after, "\n", " ");
4255 string lit = literal ? "\"true\"" : "\"false\"";
4256 begin_command_inset(os, "citation", command);
4257 os << "after " << '"' << after << '"' << "\n";
4258 os << "before " << '"' << before << '"' << "\n";
4262 if (!pretextlist.empty())
4263 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4264 if (!posttextlist.empty())
4265 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4266 os << "literal " << lit << "\n";
4268 // Need to set the cite engine if biblatex is loaded by
4269 // the document class directly
4270 if (preamble.citeEngine() == "basic")
4271 use_biblatex_natbib ?
4272 preamble.citeEngine("biblatex-natbib")
4273 : preamble.citeEngine("biblatex");
4278 is_known(t.cs(), known_jurabib_commands) &&
4279 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4280 context.check_layout(os);
4281 string command = t.cs();
4282 if (p.next_token().asInput() == "*") {
4286 char argumentOrder = '\0';
4287 vector<string> const options =
4288 preamble.getPackageOptions("jurabib");
4289 if (find(options.begin(), options.end(),
4290 "natbiborder") != options.end())
4291 argumentOrder = 'n';
4292 else if (find(options.begin(), options.end(),
4293 "jurabiborder") != options.end())
4294 argumentOrder = 'j';
4296 // text before the citation
4298 // text after the citation
4300 get_cite_arguments(p, argumentOrder != 'j', before, after);
4302 string const citation = p.verbatim_item();
4303 if (!before.empty() && argumentOrder == '\0') {
4304 cerr << "Warning: Assuming argument order "
4305 "of jurabib version 0.6 for\n'"
4306 << command << before << after << '{'
4307 << citation << "}'.\n"
4308 "Add 'jurabiborder' to the jurabib "
4309 "package options if you used an\n"
4310 "earlier jurabib version." << endl;
4312 bool literal = false;
4313 pair<bool, string> aft;
4314 pair<bool, string> bef;
4315 // remove the brackets around after and before
4316 if (!after.empty()) {
4318 after.erase(after.length() - 1, 1);
4319 aft = convert_latexed_command_inset_arg(after);
4320 literal = !aft.first;
4321 after = literal ? subst(after, "\n", " ") : aft.second;
4323 if (!before.empty()) {
4325 before.erase(before.length() - 1, 1);
4326 bef = convert_latexed_command_inset_arg(before);
4327 literal |= !bef.first;
4328 before = literal ? subst(before, "\n", " ") : bef.second;
4329 if (literal && !after.empty())
4330 after = subst(after, "\n", " ");
4332 string lit = literal ? "\"true\"" : "\"false\"";
4333 begin_command_inset(os, "citation", command);
4334 os << "after " << '"' << after << "\"\n"
4335 << "before " << '"' << before << "\"\n"
4336 << "key " << '"' << citation << "\"\n"
4337 << "literal " << lit << "\n";
4339 // Need to set the cite engine if jurabib is loaded by
4340 // the document class directly
4341 if (preamble.citeEngine() == "basic")
4342 preamble.citeEngine("jurabib");
4346 if (t.cs() == "cite"
4347 || t.cs() == "nocite") {
4348 context.check_layout(os);
4349 string after = p.getArg('[', ']');
4350 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4351 bool const literal = !aft.first;
4352 after = literal ? subst(after, "\n", " ") : aft.second;
4353 string lit = literal ? "\"true\"" : "\"false\"";
4354 string key = convert_literate_command_inset_arg(p.verbatim_item());
4355 // store the case that it is "\nocite{*}" to use it later for
4358 begin_command_inset(os, "citation", t.cs());
4359 os << "after " << '"' << after << "\"\n"
4360 << "key " << '"' << key << "\"\n"
4361 << "literal " << lit << "\n";
4363 } else if (t.cs() == "nocite")
4368 if (t.cs() == "index" ||
4369 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4370 context.check_layout(os);
4371 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4372 p.getArg('[', ']') : "";
4373 string const kind = arg.empty() ? "idx" : arg;
4374 begin_inset(os, "Index ");
4375 os << kind << "\nstatus collapsed\n";
4376 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4379 preamble.registerAutomaticallyLoadedPackage("splitidx");
4383 if (t.cs() == "nomenclature") {
4384 context.check_layout(os);
4385 begin_command_inset(os, "nomenclature", "nomenclature");
4386 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4387 if (!prefix.empty())
4388 os << "prefix " << '"' << prefix << '"' << "\n";
4389 string symbol = p.verbatim_item();
4390 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4391 bool literal = !sym.first;
4392 string description = p.verbatim_item();
4393 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4394 literal |= !desc.first;
4396 symbol = subst(symbol, "\n", " ");
4397 description = subst(description, "\n", " ");
4399 symbol = sym.second;
4400 description = desc.second;
4402 string lit = literal ? "\"true\"" : "\"false\"";
4403 os << "symbol " << '"' << symbol;
4404 os << "\"\ndescription \""
4405 << description << "\"\n"
4406 << "literal " << lit << "\n";
4408 preamble.registerAutomaticallyLoadedPackage("nomencl");
4412 if (t.cs() == "label") {
4413 context.check_layout(os);
4414 begin_command_inset(os, "label", "label");
4416 << convert_literate_command_inset_arg(p.verbatim_item())
4422 if (t.cs() == "lyxmintcaption") {
4423 string const pos = p.getArg('[', ']');
4425 string const caption =
4426 parse_text_snippet(p, FLAG_ITEM, false,
4428 minted_nonfloat_caption = "[t]" + caption;
4430 // We already got the caption at the bottom,
4431 // so simply skip it.
4432 parse_text_snippet(p, FLAG_ITEM, false, context);
4437 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4438 context.check_layout(os);
4439 string commandname = t.cs();
4441 if (p.next_token().asInput() == "*") {
4446 begin_command_inset(os, "index_print", commandname);
4447 string const indexname = p.getArg('[', ']');
4449 if (indexname.empty())
4450 os << "type \"idx\"\n";
4452 os << "type \"" << indexname << "\"\n";
4453 os << "literal \"true\"\n";
4456 skip_spaces_braces(p);
4457 preamble.registerAutomaticallyLoadedPackage("makeidx");
4458 if (preamble.use_indices() == "true")
4459 preamble.registerAutomaticallyLoadedPackage("splitidx");
4463 if (t.cs() == "printnomenclature") {
4465 string width_type = "";
4466 context.check_layout(os);
4467 begin_command_inset(os, "nomencl_print", "printnomenclature");
4468 // case of a custom width
4470 width = p.getArg('[', ']');
4471 width = translate_len(width);
4472 width_type = "custom";
4474 // case of no custom width
4475 // the case of no custom width but the width set
4476 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4477 // because the user could have set anything, not only the width
4478 // of the longest label (which would be width_type = "auto")
4479 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4480 if (label.empty() && width_type.empty())
4481 width_type = "none";
4482 os << "set_width \"" << width_type << "\"\n";
4483 if (width_type == "custom")
4484 os << "width \"" << width << '\"';
4486 skip_spaces_braces(p);
4487 preamble.registerAutomaticallyLoadedPackage("nomencl");
4491 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4492 context.check_layout(os);
4493 begin_inset(os, "script ");
4494 os << t.cs().substr(4) << '\n';
4495 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4496 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4498 if (t.cs() == "textsubscript")
4499 preamble.registerAutomaticallyLoadedPackage("subscript");
4503 if ((where = is_known(t.cs(), known_quotes))) {
4504 context.check_layout(os);
4505 begin_inset(os, "Quotes ");
4506 string quotetype = known_coded_quotes[where - known_quotes];
4507 // try to make a smart guess about the side
4508 Token const prev = p.prev_token();
4509 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4510 && prev.character() != '\n' && prev.character() != '~');
4511 quotetype = guessQuoteStyle(quotetype, opening);
4514 // LyX adds {} after the quote, so we have to eat
4515 // spaces here if there are any before a possible
4517 eat_whitespace(p, os, context, false);
4522 if ((where = is_known(t.cs(), known_sizes)) &&
4523 context.new_layout_allowed) {
4524 context.check_layout(os);
4525 TeXFont const oldFont = context.font;
4526 context.font.size = known_coded_sizes[where - known_sizes];
4527 output_font_change(os, oldFont, context.font);
4528 eat_whitespace(p, os, context, false);
4532 if ((where = is_known(t.cs(), known_font_families)) &&
4533 context.new_layout_allowed) {
4534 context.check_layout(os);
4535 TeXFont const oldFont = context.font;
4536 context.font.family =
4537 known_coded_font_families[where - known_font_families];
4538 output_font_change(os, oldFont, context.font);
4539 eat_whitespace(p, os, context, false);
4543 if ((where = is_known(t.cs(), known_font_series)) &&
4544 context.new_layout_allowed) {
4545 context.check_layout(os);
4546 TeXFont const oldFont = context.font;
4547 context.font.series =
4548 known_coded_font_series[where - known_font_series];
4549 output_font_change(os, oldFont, context.font);
4550 eat_whitespace(p, os, context, false);
4554 if ((where = is_known(t.cs(), known_font_shapes)) &&
4555 context.new_layout_allowed) {
4556 context.check_layout(os);
4557 TeXFont const oldFont = context.font;
4558 context.font.shape =
4559 known_coded_font_shapes[where - known_font_shapes];
4560 output_font_change(os, oldFont, context.font);
4561 eat_whitespace(p, os, context, false);
4564 if ((where = is_known(t.cs(), known_old_font_families)) &&
4565 context.new_layout_allowed) {
4566 context.check_layout(os);
4567 TeXFont const oldFont = context.font;
4568 context.font.init();
4569 context.font.size = oldFont.size;
4570 context.font.family =
4571 known_coded_font_families[where - known_old_font_families];
4572 output_font_change(os, oldFont, context.font);
4573 eat_whitespace(p, os, context, false);
4577 if ((where = is_known(t.cs(), known_old_font_series)) &&
4578 context.new_layout_allowed) {
4579 context.check_layout(os);
4580 TeXFont const oldFont = context.font;
4581 context.font.init();
4582 context.font.size = oldFont.size;
4583 context.font.series =
4584 known_coded_font_series[where - known_old_font_series];
4585 output_font_change(os, oldFont, context.font);
4586 eat_whitespace(p, os, context, false);
4590 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4591 context.new_layout_allowed) {
4592 context.check_layout(os);
4593 TeXFont const oldFont = context.font;
4594 context.font.init();
4595 context.font.size = oldFont.size;
4596 context.font.shape =
4597 known_coded_font_shapes[where - known_old_font_shapes];
4598 output_font_change(os, oldFont, context.font);
4599 eat_whitespace(p, os, context, false);
4603 if (t.cs() == "selectlanguage") {
4604 context.check_layout(os);
4605 // save the language for the case that a
4606 // \foreignlanguage is used
4607 context.font.language = babel2lyx(p.verbatim_item());
4608 os << "\n\\lang " << context.font.language << "\n";
4612 if (t.cs() == "foreignlanguage") {
4613 string const lang = babel2lyx(p.verbatim_item());
4614 parse_text_attributes(p, os, FLAG_ITEM, outer,
4616 context.font.language, lang);
4620 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4621 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4622 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4624 // We have to output the whole command if it has an option
4625 // because LyX doesn't support this yet, see bug #8214,
4626 // only if there is a single option specifying a variant, we can handle it.
4628 string langopts = p.getOpt();
4629 // check if the option contains a variant, if yes, extract it
4630 string::size_type pos_var = langopts.find("variant");
4631 string::size_type i = langopts.find(',');
4632 string::size_type k = langopts.find('=', pos_var);
4633 if (pos_var != string::npos && i == string::npos) {
4635 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4636 lang = preamble.polyglossia2lyx(variant);
4637 parse_text_attributes(p, os, FLAG_ITEM, outer,
4639 context.font.language, lang);
4641 output_ert_inset(os, t.asInput() + langopts, context);
4643 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4644 parse_text_attributes(p, os, FLAG_ITEM, outer,
4646 context.font.language, lang);
4651 if (t.cs() == "inputencoding") {
4652 // nothing to write here
4653 string const enc = subst(p.verbatim_item(), "\n", " ");
4654 p.setEncoding(enc, Encoding::inputenc);
4658 if (is_known(t.cs(), known_special_chars) ||
4659 (t.cs() == "protect" &&
4660 p.next_token().cat() == catEscape &&
4661 is_known(p.next_token().cs(), known_special_protect_chars))) {
4662 // LyX sometimes puts a \protect in front, so we have to ignore it
4664 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4665 known_special_chars);
4666 context.check_layout(os);
4667 os << known_coded_special_chars[where - known_special_chars];
4668 skip_spaces_braces(p);
4672 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4673 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4674 p.next_next_token().asInput() == "-") ||
4675 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4676 // LyX sometimes puts a \protect in front, so we have to ignore it
4677 if (t.cs() == "protect")
4679 context.check_layout(os);
4680 if (t.cs() == "nobreakdash")
4681 os << "\\SpecialChar nobreakdash\n";
4683 os << "\\SpecialChar endofsentence\n";
4688 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4689 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4690 || t.cs() == "%" || t.cs() == "-") {
4691 context.check_layout(os);
4693 os << "\\SpecialChar softhyphen\n";
4699 if (t.cs() == "char") {
4700 context.check_layout(os);
4701 if (p.next_token().character() == '`') {
4703 if (p.next_token().cs() == "\"") {
4708 output_ert_inset(os, "\\char`", context);
4711 output_ert_inset(os, "\\char", context);
4716 if (t.cs() == "verb") {
4717 context.check_layout(os);
4718 // set catcodes to verbatim early, just in case.
4719 p.setCatcodes(VERBATIM_CATCODES);
4720 string delim = p.get_token().asInput();
4721 Parser::Arg arg = p.verbatimStuff(delim);
4723 output_ert_inset(os, "\\verb" + delim
4724 + arg.second + delim, context);
4726 cerr << "invalid \\verb command. Skipping" << endl;
4730 // Problem: \= creates a tabstop inside the tabbing environment
4731 // and else an accent. In the latter case we really would want
4732 // \={o} instead of \= o.
4733 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4734 output_ert_inset(os, t.asInput(), context);
4738 if (t.cs() == "\\") {
4739 context.check_layout(os);
4741 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4742 else if (p.next_token().asInput() == "*") {
4744 // getOpt() eats the following space if there
4745 // is no optional argument, but that is OK
4746 // here since it has no effect in the output.
4747 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4750 begin_inset(os, "Newline newline");
4756 if (t.cs() == "newline" ||
4757 (t.cs() == "linebreak" && !p.hasOpt())) {
4758 context.check_layout(os);
4759 begin_inset(os, "Newline ");
4762 skip_spaces_braces(p);
4766 if (t.cs() == "input" || t.cs() == "include"
4767 || t.cs() == "verbatiminput"
4768 || t.cs() == "lstinputlisting") {
4769 string name = t.cs();
4770 if (name == "verbatiminput"
4771 && p.next_token().asInput() == "*")
4772 name += p.get_token().asInput();
4773 context.check_layout(os);
4775 bool literal = false;
4776 if (name == "lstinputlisting" && p.hasOpt()) {
4777 lstparams = p.getArg('[', ']');
4778 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4779 literal = !oa.first;
4781 lstparams = subst(lstparams, "\n", " ");
4783 string lit = literal ? "\"true\"" : "\"false\"";
4784 string filename(normalize_filename(p.getArg('{', '}')));
4785 string const path = getMasterFilePath(true);
4786 // We want to preserve relative / absolute filenames,
4787 // therefore path is only used for testing
4788 if ((t.cs() == "include" || t.cs() == "input") &&
4789 !makeAbsPath(filename, path).exists()) {
4790 // The file extension is probably missing.
4791 // Now try to find it out.
4792 string const tex_name =
4793 find_file(filename, path,
4794 known_tex_extensions);
4795 if (!tex_name.empty())
4796 filename = tex_name;
4798 bool external = false;
4800 if (makeAbsPath(filename, path).exists()) {
4801 string const abstexname =
4802 makeAbsPath(filename, path).absFileName();
4803 string const absfigname =
4804 changeExtension(abstexname, ".fig");
4805 fix_child_filename(filename);
4806 string const lyxname = changeExtension(filename,
4807 roundtripMode() ? ".lyx.lyx" : ".lyx");
4808 string const abslyxname = makeAbsPath(
4809 lyxname, getParentFilePath(false)).absFileName();
4811 if (!skipChildren())
4812 external = FileName(absfigname).exists();
4813 if (t.cs() == "input" && !skipChildren()) {
4814 string const ext = getExtension(abstexname);
4816 // Combined PS/LaTeX:
4817 // x.eps, x.pstex_t (old xfig)
4818 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4819 FileName const absepsname(
4820 changeExtension(abstexname, ".eps"));
4821 FileName const abspstexname(
4822 changeExtension(abstexname, ".pstex"));
4823 bool const xfigeps =
4824 (absepsname.exists() ||
4825 abspstexname.exists()) &&
4828 // Combined PDF/LaTeX:
4829 // x.pdf, x.pdftex_t (old xfig)
4830 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4831 FileName const abspdfname(
4832 changeExtension(abstexname, ".pdf"));
4833 bool const xfigpdf =
4834 abspdfname.exists() &&
4835 (ext == "pdftex_t" || ext == "pdf_t");
4839 // Combined PS/PDF/LaTeX:
4840 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4841 string const absbase2(
4842 removeExtension(abstexname) + "_pspdftex");
4843 FileName const abseps2name(
4844 addExtension(absbase2, ".eps"));
4845 FileName const abspdf2name(
4846 addExtension(absbase2, ".pdf"));
4847 bool const xfigboth =
4848 abspdf2name.exists() &&
4849 abseps2name.exists() && ext == "pspdftex";
4851 xfig = xfigpdf || xfigeps || xfigboth;
4852 external = external && xfig;
4855 outname = changeExtension(filename, ".fig");
4856 FileName abssrc(changeExtension(abstexname, ".fig"));
4857 copy_file(abssrc, outname);
4859 // Don't try to convert, the result
4860 // would be full of ERT.
4862 FileName abssrc(abstexname);
4863 copy_file(abssrc, outname);
4864 } else if (t.cs() != "verbatiminput" &&
4866 tex2lyx(abstexname, FileName(abslyxname),
4869 // no need to call copy_file
4870 // tex2lyx creates the file
4873 FileName abssrc(abstexname);
4874 copy_file(abssrc, outname);
4877 cerr << "Warning: Could not find included file '"
4878 << filename << "'." << endl;
4882 begin_inset(os, "External\n");
4883 os << "\ttemplate XFig\n"
4884 << "\tfilename " << outname << '\n';
4885 registerExternalTemplatePackages("XFig");
4887 begin_command_inset(os, "include", name);
4888 outname = subst(outname, "\"", "\\\"");
4889 os << "preview false\n"
4890 "filename \"" << outname << "\"\n";
4891 if (!lstparams.empty())
4892 os << "lstparams \"" << lstparams << "\"\n";
4893 os << "literal " << lit << "\n";
4894 if (t.cs() == "verbatiminput")
4895 preamble.registerAutomaticallyLoadedPackage("verbatim");
4901 if (t.cs() == "bibliographystyle") {
4902 // store new bibliographystyle
4903 bibliographystyle = p.verbatim_item();
4904 // If any other command than \bibliography, \addcontentsline
4905 // and \nocite{*} follows, we need to output the style
4906 // (because it might be used by that command).
4907 // Otherwise, it will automatically be output by LyX.
4910 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4911 if (t2.cat() == catBegin)
4913 if (t2.cat() != catEscape)
4915 if (t2.cs() == "nocite") {
4916 if (p.getArg('{', '}') == "*")
4918 } else if (t2.cs() == "bibliography")
4920 else if (t2.cs() == "phantomsection") {
4924 else if (t2.cs() == "addcontentsline") {
4925 // get the 3 arguments of \addcontentsline
4928 contentslineContent = p.getArg('{', '}');
4929 // if the last argument is not \refname we must output
4930 if (contentslineContent == "\\refname")
4937 output_ert_inset(os,
4938 "\\bibliographystyle{" + bibliographystyle + '}',
4944 if (t.cs() == "phantomsection") {
4945 // we only support this if it occurs between
4946 // \bibliographystyle and \bibliography
4947 if (bibliographystyle.empty())
4948 output_ert_inset(os, "\\phantomsection", context);
4952 if (t.cs() == "addcontentsline") {
4953 context.check_layout(os);
4954 // get the 3 arguments of \addcontentsline
4955 string const one = p.getArg('{', '}');
4956 string const two = p.getArg('{', '}');
4957 string const three = p.getArg('{', '}');
4958 // only if it is a \refname, we support if for the bibtex inset
4959 if (contentslineContent != "\\refname") {
4960 output_ert_inset(os,
4961 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4967 else if (t.cs() == "bibliography") {
4968 context.check_layout(os);
4970 begin_command_inset(os, "bibtex", "bibtex");
4971 if (!btprint.empty()) {
4972 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4973 // clear the string because the next BibTeX inset can be without the
4974 // \nocite{*} option
4977 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4978 // Do we have addcontentsline?
4979 if (contentslineContent == "\\refname") {
4980 BibOpts = "bibtotoc";
4981 // clear string because next BibTeX inset can be without addcontentsline
4982 contentslineContent.clear();
4984 // Do we have a bibliographystyle set?
4985 if (!bibliographystyle.empty()) {
4986 if (BibOpts.empty())
4987 BibOpts = normalize_filename(bibliographystyle);
4989 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4990 // clear it because each bibtex entry has its style
4991 // and we need an empty string to handle \phantomsection
4992 bibliographystyle.clear();
4994 os << "options " << '"' << BibOpts << '"' << "\n";
4999 if (t.cs() == "printbibliography") {
5000 context.check_layout(os);
5002 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5003 vector<string> opts = getVectorFromString(bbloptions);
5004 vector<string>::iterator it =
5005 find(opts.begin(), opts.end(), "heading=bibintoc");
5006 if (it != opts.end()) {
5008 BibOpts = "bibtotoc";
5010 bbloptions = getStringFromVector(opts);
5011 begin_command_inset(os, "bibtex", "bibtex");
5012 if (!btprint.empty()) {
5013 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5014 // clear the string because the next BibTeX inset can be without the
5015 // \nocite{*} option
5019 for (auto const & bf : preamble.biblatex_bibliographies) {
5020 if (!bibfiles.empty())
5022 bibfiles += normalize_filename(bf);
5024 if (!bibfiles.empty())
5025 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5026 // Do we have addcontentsline?
5027 if (contentslineContent == "\\refname") {
5028 BibOpts = "bibtotoc";
5029 // clear string because next BibTeX inset can be without addcontentsline
5030 contentslineContent.clear();
5032 os << "options " << '"' << BibOpts << '"' << "\n";
5033 if (!bbloptions.empty())
5034 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5036 need_commentbib = false;
5040 if (t.cs() == "bibbysection") {
5041 context.check_layout(os);
5043 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5044 vector<string> opts = getVectorFromString(bbloptions);
5045 vector<string>::iterator it =
5046 find(opts.begin(), opts.end(), "heading=bibintoc");
5047 if (it != opts.end()) {
5049 BibOpts = "bibtotoc";
5051 bbloptions = getStringFromVector(opts);
5052 begin_command_inset(os, "bibtex", "bibtex");
5053 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5055 for (auto const & bf : preamble.biblatex_bibliographies) {
5056 if (!bibfiles.empty())
5058 bibfiles += normalize_filename(bf);
5060 if (!bibfiles.empty())
5061 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5062 os << "options " << '"' << BibOpts << '"' << "\n";
5063 if (!bbloptions.empty())
5064 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5066 need_commentbib = false;
5070 if (t.cs() == "parbox") {
5071 // Test whether this is an outer box of a shaded box
5073 // swallow arguments
5074 while (p.hasOpt()) {
5076 p.skip_spaces(true);
5079 p.skip_spaces(true);
5081 if (p.next_token().cat() == catBegin)
5083 p.skip_spaces(true);
5084 Token to = p.get_token();
5085 bool shaded = false;
5086 if (to.asInput() == "\\begin") {
5087 p.skip_spaces(true);
5088 if (p.getArg('{', '}') == "shaded")
5093 parse_outer_box(p, os, FLAG_ITEM, outer,
5094 context, "parbox", "shaded");
5096 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5097 "", "", t.cs(), "", "");
5101 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5102 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5103 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5104 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5108 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5109 string backgroundcolor;
5110 preamble.registerAutomaticallyLoadedPackage("xcolor");
5111 if (t.cs() == "fcolorbox") {
5112 string const framecolor = p.getArg('{', '}');
5113 backgroundcolor = p.getArg('{', '}');
5114 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5116 backgroundcolor = p.getArg('{', '}');
5117 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5122 // FIXME: due to the compiler limit of "if" nestings
5123 // the code for the alignment was put here
5124 // put them in their own if if this is fixed
5125 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5126 || t.cs() == "shadowsize"
5127 || t.cs() == "raggedleft" || t.cs() == "centering"
5128 || t.cs() == "raggedright") {
5129 if (t.cs() == "fboxrule")
5131 if (t.cs() == "fboxsep")
5133 if (t.cs() == "shadowsize")
5135 if (t.cs() != "raggedleft" && t.cs() != "centering"
5136 && t.cs() != "raggedright") {
5137 p.skip_spaces(true);
5138 while (p.good() && p.next_token().cat() != catSpace
5139 && p.next_token().cat() != catNewline
5140 && p.next_token().cat() != catEscape) {
5141 if (t.cs() == "fboxrule")
5142 fboxrule = fboxrule + p.get_token().asInput();
5143 if (t.cs() == "fboxsep")
5144 fboxsep = fboxsep + p.get_token().asInput();
5145 if (t.cs() == "shadowsize")
5146 shadow_size = shadow_size + p.get_token().asInput();
5149 output_ert_inset(os, t.asInput(), context);
5154 //\framebox() is part of the picture environment and different from \framebox{}
5155 //\framebox{} will be parsed by parse_outer_box
5156 if (t.cs() == "framebox") {
5157 if (p.next_token().character() == '(') {
5158 //the syntax is: \framebox(x,y)[position]{content}
5159 string arg = t.asInput();
5160 arg += p.getFullParentheseArg();
5161 arg += p.getFullOpt();
5162 eat_whitespace(p, os, context, false);
5163 output_ert_inset(os, arg + '{', context);
5164 parse_text(p, os, FLAG_ITEM, outer, context);
5165 output_ert_inset(os, "}", context);
5167 //the syntax is: \framebox[width][position]{content}
5168 string special = p.getFullOpt();
5169 special += p.getOpt();
5170 parse_outer_box(p, os, FLAG_ITEM, outer,
5171 context, t.cs(), special);
5176 //\makebox() is part of the picture environment and different from \makebox{}
5177 //\makebox{} will be parsed by parse_box
5178 if (t.cs() == "makebox") {
5179 if (p.next_token().character() == '(') {
5180 //the syntax is: \makebox(x,y)[position]{content}
5181 string arg = t.asInput();
5182 arg += p.getFullParentheseArg();
5183 arg += p.getFullOpt();
5184 eat_whitespace(p, os, context, false);
5185 output_ert_inset(os, arg + '{', context);
5186 parse_text(p, os, FLAG_ITEM, outer, context);
5187 output_ert_inset(os, "}", context);
5189 //the syntax is: \makebox[width][position]{content}
5190 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5191 "", "", t.cs(), "", "");
5195 if (t.cs() == "smallskip" ||
5196 t.cs() == "medskip" ||
5197 t.cs() == "bigskip" ||
5198 t.cs() == "vfill") {
5199 context.check_layout(os);
5200 begin_inset(os, "VSpace ");
5203 skip_spaces_braces(p);
5207 if ((where = is_known(t.cs(), known_spaces))) {
5208 context.check_layout(os);
5209 begin_inset(os, "space ");
5210 os << '\\' << known_coded_spaces[where - known_spaces]
5213 // LaTeX swallows whitespace after all spaces except
5214 // "\\,". We have to do that here, too, because LyX
5215 // adds "{}" which would make the spaces significant.
5217 eat_whitespace(p, os, context, false);
5218 // LyX adds "{}" after all spaces except "\\ " and
5219 // "\\,", so we have to remove "{}".
5220 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5221 // remove the braces after "\\,", too.
5227 if (t.cs() == "newpage" ||
5228 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5229 t.cs() == "clearpage" ||
5230 t.cs() == "cleardoublepage") {
5231 context.check_layout(os);
5232 begin_inset(os, "Newpage ");
5235 skip_spaces_braces(p);
5239 if (t.cs() == "DeclareRobustCommand" ||
5240 t.cs() == "DeclareRobustCommandx" ||
5241 t.cs() == "newcommand" ||
5242 t.cs() == "newcommandx" ||
5243 t.cs() == "providecommand" ||
5244 t.cs() == "providecommandx" ||
5245 t.cs() == "renewcommand" ||
5246 t.cs() == "renewcommandx") {
5247 // DeclareRobustCommand, DeclareRobustCommandx,
5248 // providecommand and providecommandx could be handled
5249 // by parse_command(), but we need to call
5250 // add_known_command() here.
5251 string name = t.asInput();
5252 if (p.next_token().asInput() == "*") {
5253 // Starred form. Eat '*'
5257 string const command = p.verbatim_item();
5258 string const opt1 = p.getFullOpt();
5259 string const opt2 = p.getFullOpt();
5260 add_known_command(command, opt1, !opt2.empty());
5261 string const ert = name + '{' + command + '}' +
5263 '{' + p.verbatim_item() + '}';
5265 if (t.cs() == "DeclareRobustCommand" ||
5266 t.cs() == "DeclareRobustCommandx" ||
5267 t.cs() == "providecommand" ||
5268 t.cs() == "providecommandx" ||
5269 name[name.length()-1] == '*')
5270 output_ert_inset(os, ert, context);
5272 context.check_layout(os);
5273 begin_inset(os, "FormulaMacro");
5280 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5281 // let could be handled by parse_command(),
5282 // but we need to call add_known_command() here.
5283 string ert = t.asInput();
5286 if (p.next_token().cat() == catBegin) {
5287 name = p.verbatim_item();
5288 ert += '{' + name + '}';
5290 name = p.verbatim_item();
5295 if (p.next_token().cat() == catBegin) {
5296 command = p.verbatim_item();
5297 ert += '{' + command + '}';
5299 command = p.verbatim_item();
5302 // If command is known, make name known too, to parse
5303 // its arguments correctly. For this reason we also
5304 // have commands in syntax.default that are hardcoded.
5305 CommandMap::iterator it = known_commands.find(command);
5306 if (it != known_commands.end())
5307 known_commands[t.asInput()] = it->second;
5308 output_ert_inset(os, ert, context);
5312 if (t.cs() == "hspace" || t.cs() == "vspace") {
5315 string name = t.asInput();
5316 string const length = p.verbatim_item();
5319 bool valid = splitLatexLength(length, valstring, unit);
5320 bool known_hspace = false;
5321 bool known_vspace = false;
5322 bool known_unit = false;
5325 istringstream iss(valstring);
5328 if (t.cs()[0] == 'h') {
5329 if (unit == "\\fill") {
5334 known_hspace = true;
5337 if (unit == "\\smallskipamount") {
5339 known_vspace = true;
5340 } else if (unit == "\\medskipamount") {
5342 known_vspace = true;
5343 } else if (unit == "\\bigskipamount") {
5345 known_vspace = true;
5346 } else if (unit == "\\fill") {
5348 known_vspace = true;
5352 if (!known_hspace && !known_vspace) {
5353 switch (unitFromString(unit)) {
5369 //unitFromString(unit) fails for relative units like Length::PCW
5370 // therefore handle them separately
5371 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5372 || unit == "\\textwidth" || unit == "\\linewidth"
5373 || unit == "\\textheight" || unit == "\\paperheight"
5374 || unit == "\\baselineskip")
5382 // check for glue lengths
5383 bool is_gluelength = false;
5384 string gluelength = length;
5385 string::size_type i = length.find(" minus");
5386 if (i == string::npos) {
5387 i = length.find(" plus");
5388 if (i != string::npos)
5389 is_gluelength = true;
5391 is_gluelength = true;
5392 // if yes transform "9xx minus 8yy plus 7zz"
5394 if (is_gluelength) {
5395 i = gluelength.find(" minus");
5396 if (i != string::npos)
5397 gluelength.replace(i, 7, "-");
5398 i = gluelength.find(" plus");
5399 if (i != string::npos)
5400 gluelength.replace(i, 6, "+");
5403 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5404 // Literal horizontal length or known variable
5405 context.check_layout(os);
5406 begin_inset(os, "space ");
5414 if (known_unit && !known_hspace)
5415 os << "\n\\length " << translate_len(length);
5417 os << "\n\\length " << gluelength;
5419 } else if (known_unit || known_vspace || is_gluelength) {
5420 // Literal vertical length or known variable
5421 context.check_layout(os);
5422 begin_inset(os, "VSpace ");
5425 if (known_unit && !known_vspace)
5426 os << translate_len(length);
5433 // LyX can't handle other length variables in Inset VSpace/space
5438 output_ert_inset(os, name + '{' + unit + '}', context);
5439 else if (value == -1.0)
5440 output_ert_inset(os, name + "{-" + unit + '}', context);
5442 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5444 output_ert_inset(os, name + '{' + length + '}', context);
5449 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5450 // might be one or several options or a star.
5451 // The single '=' is meant here.
5452 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5456 context.check_layout(os);
5457 // store the latexparam here. This is eaten in parse_text_in_inset
5458 context.latexparam = newinsetlayout->latexparam();
5459 docstring name = newinsetlayout->name();
5460 bool const caption = name.find(from_ascii("Caption:")) == 0;
5462 // Already done for floating minted listings.
5463 if (minted_float.empty()) {
5464 begin_inset(os, "Caption ");
5465 os << to_utf8(name.substr(8)) << '\n';
5468 // FIXME: what do we do if the prefix is not Flex: ?
5469 if (prefixIs(name, from_ascii("Flex:")))
5471 begin_inset(os, "Flex ");
5472 os << to_utf8(name) << '\n'
5473 << "status collapsed\n";
5475 if (!minted_float.empty()) {
5476 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5477 } else if (newinsetlayout->isPassThru()) {
5478 // set catcodes to verbatim early, just in case.
5479 p.setCatcodes(VERBATIM_CATCODES);
5480 string delim = p.get_token().asInput();
5482 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5483 //FIXME: handle error condition
5484 string const arg = p.verbatimStuff("}").second;
5485 Context newcontext(true, context.textclass);
5486 if (newinsetlayout->forcePlainLayout())
5487 newcontext.layout = &context.textclass.plainLayout();
5488 output_ert(os, arg, newcontext);
5490 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5491 context.latexparam.clear();
5494 // Minted caption insets are not closed here because
5495 // we collect everything into the caption.
5496 if (minted_float.empty())
5501 // The single '=' is meant here.
5502 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5506 context.check_layout(os);
5507 docstring const name = newinsetlayout->name();
5508 bool const caption = name.find(from_ascii("Caption:")) == 0;
5510 // Already done for floating minted listings.
5511 if (minted_float.empty()) {
5512 begin_inset(os, "Caption ");
5513 os << to_utf8(name.substr(8)) << '\n';
5516 begin_inset(os, "Flex ");
5517 os << to_utf8(name) << '\n'
5518 << "status collapsed\n";
5520 if (!minted_float.empty()) {
5521 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5522 } else if (newinsetlayout->isPassThru()) {
5523 // set catcodes to verbatim early, just in case.
5524 p.setCatcodes(VERBATIM_CATCODES);
5525 string delim = p.get_token().asInput();
5527 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5528 //FIXME: handle error condition
5529 string const arg = p.verbatimStuff("}").second;
5530 Context newcontext(true, context.textclass);
5531 if (newinsetlayout->forcePlainLayout())
5532 newcontext.layout = &context.textclass.plainLayout();
5533 output_ert(os, arg, newcontext);
5535 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5538 // Minted caption insets are not closed here because
5539 // we collect everything into the caption.
5540 if (minted_float.empty())
5545 if (t.cs() == "includepdf") {
5547 string const arg = p.getArg('[', ']');
5548 map<string, string> opts;
5549 vector<string> keys;
5550 split_map(arg, opts, keys);
5551 string name = normalize_filename(p.verbatim_item());
5552 string const path = getMasterFilePath(true);
5553 // We want to preserve relative / absolute filenames,
5554 // therefore path is only used for testing
5555 if (!makeAbsPath(name, path).exists()) {
5556 // The file extension is probably missing.
5557 // Now try to find it out.
5558 char const * const pdfpages_format[] = {"pdf", 0};
5559 string const pdftex_name =
5560 find_file(name, path, pdfpages_format);
5561 if (!pdftex_name.empty()) {
5566 FileName const absname = makeAbsPath(name, path);
5567 if (absname.exists())
5569 fix_child_filename(name);
5570 copy_file(absname, name);
5572 cerr << "Warning: Could not find file '"
5573 << name << "'." << endl;
5575 context.check_layout(os);
5576 begin_inset(os, "External\n\ttemplate ");
5577 os << "PDFPages\n\tfilename "
5579 // parse the options
5580 if (opts.find("pages") != opts.end())
5581 os << "\textra LaTeX \"pages="
5582 << opts["pages"] << "\"\n";
5583 if (opts.find("angle") != opts.end())
5584 os << "\trotateAngle "
5585 << opts["angle"] << '\n';
5586 if (opts.find("origin") != opts.end()) {
5588 string const opt = opts["origin"];
5589 if (opt == "tl") ss << "topleft";
5590 if (opt == "bl") ss << "bottomleft";
5591 if (opt == "Bl") ss << "baselineleft";
5592 if (opt == "c") ss << "center";
5593 if (opt == "tc") ss << "topcenter";
5594 if (opt == "bc") ss << "bottomcenter";
5595 if (opt == "Bc") ss << "baselinecenter";
5596 if (opt == "tr") ss << "topright";
5597 if (opt == "br") ss << "bottomright";
5598 if (opt == "Br") ss << "baselineright";
5599 if (!ss.str().empty())
5600 os << "\trotateOrigin " << ss.str() << '\n';
5602 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5604 if (opts.find("width") != opts.end())
5606 << translate_len(opts["width"]) << '\n';
5607 if (opts.find("height") != opts.end())
5609 << translate_len(opts["height"]) << '\n';
5610 if (opts.find("keepaspectratio") != opts.end())
5611 os << "\tkeepAspectRatio\n";
5613 context.check_layout(os);
5614 registerExternalTemplatePackages("PDFPages");
5618 if (t.cs() == "loadgame") {
5620 string name = normalize_filename(p.verbatim_item());
5621 string const path = getMasterFilePath(true);
5622 // We want to preserve relative / absolute filenames,
5623 // therefore path is only used for testing
5624 if (!makeAbsPath(name, path).exists()) {
5625 // The file extension is probably missing.
5626 // Now try to find it out.
5627 char const * const lyxskak_format[] = {"fen", 0};
5628 string const lyxskak_name =
5629 find_file(name, path, lyxskak_format);
5630 if (!lyxskak_name.empty())
5631 name = lyxskak_name;
5633 FileName const absname = makeAbsPath(name, path);
5634 if (absname.exists())
5636 fix_child_filename(name);
5637 copy_file(absname, name);
5639 cerr << "Warning: Could not find file '"
5640 << name << "'." << endl;
5641 context.check_layout(os);
5642 begin_inset(os, "External\n\ttemplate ");
5643 os << "ChessDiagram\n\tfilename "
5646 context.check_layout(os);
5647 // after a \loadgame follows a \showboard
5648 if (p.get_token().asInput() == "showboard")
5650 registerExternalTemplatePackages("ChessDiagram");
5654 // try to see whether the string is in unicodesymbols
5655 // Only use text mode commands, since we are in text mode here,
5656 // and math commands may be invalid (bug 6797)
5657 string name = t.asInput();
5658 // handle the dingbats, cyrillic and greek
5659 if (name == "\\ding" || name == "\\textcyr" ||
5660 (name == "\\textgreek" && !preamble.usePolyglossia()))
5661 name = name + '{' + p.getArg('{', '}') + '}';
5662 // handle the ifsym characters
5663 else if (name == "\\textifsymbol") {
5664 string const optif = p.getFullOpt();
5665 string const argif = p.getArg('{', '}');
5666 name = name + optif + '{' + argif + '}';
5668 // handle the \ascii characters
5669 // the case of \ascii within braces, as LyX outputs it, is already
5670 // handled for t.cat() == catBegin
5671 else if (name == "\\ascii") {
5672 // the code is "\asci\xxx"
5673 name = "{" + name + p.get_token().asInput() + "}";
5676 // handle some TIPA special characters
5677 else if (preamble.isPackageUsed("tipa")) {
5678 if (name == "\\s") {
5679 // fromLaTeXCommand() does not yet
5680 // recognize tipa short cuts
5681 name = "\\textsyllabic";
5682 } else if (name == "\\=" &&
5683 p.next_token().asInput() == "*") {
5684 // fromLaTeXCommand() does not yet
5685 // recognize tipa short cuts
5687 name = "\\textsubbar";
5688 } else if (name == "\\textdoublevertline") {
5689 // FIXME: This is not correct,
5690 // \textvertline is higher than \textbardbl
5691 name = "\\textbardbl";
5693 } else if (name == "\\!" ) {
5694 if (p.next_token().asInput() == "b") {
5695 p.get_token(); // eat 'b'
5698 } else if (p.next_token().asInput() == "d") {
5702 } else if (p.next_token().asInput() == "g") {
5706 } else if (p.next_token().asInput() == "G") {
5708 name = "\\texthtscg";
5710 } else if (p.next_token().asInput() == "j") {
5712 name = "\\texthtbardotlessj";
5714 } else if (p.next_token().asInput() == "o") {
5716 name = "\\textbullseye";
5719 } else if (name == "\\*" ) {
5720 if (p.next_token().asInput() == "k") {
5722 name = "\\textturnk";
5724 } else if (p.next_token().asInput() == "r") {
5725 p.get_token(); // eat 'b'
5726 name = "\\textturnr";
5728 } else if (p.next_token().asInput() == "t") {
5730 name = "\\textturnt";
5732 } else if (p.next_token().asInput() == "w") {
5734 name = "\\textturnw";
5739 if ((name.size() == 2 &&
5740 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5741 p.next_token().asInput() != "*") ||
5742 is_known(name.substr(1), known_tipa_marks)) {
5743 // name is a command that corresponds to a
5744 // combining character in unicodesymbols.
5745 // Append the argument, fromLaTeXCommand()
5746 // will either convert it to a single
5747 // character or a combining sequence.
5748 name += '{' + p.verbatim_item() + '}';
5750 // now get the character from unicodesymbols
5754 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5755 Encodings::TEXT_CMD, termination, rem, &req));
5757 context.check_layout(os);
5760 output_ert_inset(os, to_utf8(rem), context);
5762 skip_spaces_braces(p);
5763 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5764 preamble.registerAutomaticallyLoadedPackage(*it);
5766 //cerr << "#: " << t << " mode: " << mode << endl;
5767 // heuristic: read up to next non-nested space
5769 string s = t.asInput();
5770 string z = p.verbatim_item();
5771 while (p.good() && z != " " && !z.empty()) {
5772 //cerr << "read: " << z << endl;
5774 z = p.verbatim_item();
5776 cerr << "found ERT: " << s << endl;
5777 output_ert_inset(os, s + ' ', context);
5780 if (t.asInput() == name &&
5781 p.next_token().asInput() == "*") {
5782 // Starred commands like \vspace*{}
5783 p.get_token(); // Eat '*'
5786 if (!parse_command(name, p, os, outer, context))
5787 output_ert_inset(os, name, context);
5793 string guessLanguage(Parser & p, string const & lang)
5795 typedef std::map<std::string, size_t> LangMap;
5796 // map from language names to number of characters
5799 for (char const * const * i = supported_CJK_languages; *i; i++)
5800 used[string(*i)] = 0;
5803 Token const t = p.get_token();
5804 // comments are not counted for any language
5805 if (t.cat() == catComment)
5807 // commands are not counted as well, but we need to detect
5808 // \begin{CJK} and switch encoding if needed
5809 if (t.cat() == catEscape) {
5810 if (t.cs() == "inputencoding") {
5811 string const enc = subst(p.verbatim_item(), "\n", " ");
5812 p.setEncoding(enc, Encoding::inputenc);
5815 if (t.cs() != "begin")
5818 // Non-CJK content is counted for lang.
5819 // We do not care about the real language here:
5820 // If we have more non-CJK contents than CJK contents,
5821 // we simply use the language that was specified as
5822 // babel main language.
5823 used[lang] += t.asInput().length();
5826 // Now we are starting an environment
5828 string const name = p.getArg('{', '}');
5829 if (name != "CJK") {
5833 // It is a CJK environment
5835 /* name = */ p.getArg('{', '}');
5836 string const encoding = p.getArg('{', '}');
5837 /* mapping = */ p.getArg('{', '}');
5838 string const encoding_old = p.getEncoding();
5839 char const * const * const where =
5840 is_known(encoding, supported_CJK_encodings);
5842 p.setEncoding(encoding, Encoding::CJK);
5844 p.setEncoding("UTF-8");
5845 string const text = p.ertEnvironment("CJK");
5846 p.setEncoding(encoding_old);
5849 // ignore contents in unknown CJK encoding
5852 // the language of the text
5854 supported_CJK_languages[where - supported_CJK_encodings];
5855 used[cjk] += text.length();
5857 LangMap::const_iterator use = used.begin();
5858 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5859 if (it->second > use->second)
5866 void check_comment_bib(ostream & os, Context & context)
5868 if (!need_commentbib)
5870 // We have a bibliography database, but no bibliography with biblatex
5871 // which is completely valid. Insert a bibtex inset in a note.
5872 context.check_layout(os);
5873 begin_inset(os, "Note Note\n");
5874 os << "status open\n";
5875 os << "\\begin_layout Plain Layout\n";
5876 begin_command_inset(os, "bibtex", "bibtex");
5878 for (auto const & bf : preamble.biblatex_bibliographies) {
5879 if (!bibfiles.empty())
5881 bibfiles += normalize_filename(bf);
5883 if (!bibfiles.empty())
5884 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5885 end_inset(os);// Bibtex
5886 os << "\\end_layout\n";
5887 end_inset(os);// Note