2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
26 #include "insets/ExternalTemplate.h"
28 #include "support/lassert.h"
29 #include "support/convert.h"
30 #include "support/FileName.h"
31 #include "support/filetools.h"
32 #include "support/Length.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, const string &, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout,
58 string const & rdelim)
60 bool const forcePlainLayout =
61 layout ? layout->forcePlainLayout() : false;
62 Context newcontext(true, context.textclass);
64 newcontext.layout = &context.textclass.plainLayout();
66 newcontext.font = context.font;
67 // Inherit commands to pass through
68 newcontext.pass_thru_cmds = context.pass_thru_cmds;
70 output_arguments(os, p, outer, false, string(), newcontext,
72 // If we have a latex param, we eat it here.
73 if (!context.latexparam.empty()) {
75 Context dummy(true, context.textclass);
76 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
77 string(1, context.latexparam.back()));
79 parse_text(p, os, flags, outer, newcontext, rdelim);
81 output_arguments(os, p, outer, false, "post", newcontext,
82 layout->postcommandargs());
83 newcontext.check_end_layout(os);
89 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
90 Context const & context, string const & name,
91 string const & rdelim = string())
93 InsetLayout const * layout = 0;
94 DocumentClass::InsetLayouts::const_iterator it =
95 context.textclass.insetLayouts().find(from_ascii(name));
96 if (it != context.textclass.insetLayouts().end())
97 layout = &(it->second);
98 parse_text_in_inset(p, os, flags, outer, context, layout, rdelim);
101 /// parses a paragraph snippet, useful for example for \\emph{...}
102 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
105 Context newcontext(context);
106 // Don't inherit the paragraph-level extra stuff
107 newcontext.par_extra_stuff.clear();
108 parse_text(p, os, flags, outer, newcontext);
109 // Make sure that we don't create invalid .lyx files
110 context.need_layout = newcontext.need_layout;
111 context.need_end_layout = newcontext.need_end_layout;
116 * Thin wrapper around parse_text_snippet() using a string.
118 * We completely ignore \c context.need_layout and \c context.need_end_layout,
119 * because our return value is not used directly (otherwise the stream version
120 * of parse_text_snippet() could be used). That means that the caller needs
121 * to do layout management manually.
122 * This is intended to parse text that does not create any layout changes.
124 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
127 Context newcontext(context);
128 newcontext.need_layout = false;
129 newcontext.need_end_layout = false;
130 newcontext.new_layout_allowed = false;
131 // Avoid warning by Context::~Context()
132 newcontext.par_extra_stuff.clear();
134 parse_text_snippet(p, os, flags, outer, newcontext);
138 string fboxrule = "";
140 string shadow_size = "";
142 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
143 "vpageref", "prettyref", "nameref", "eqref", 0 };
145 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
146 "vpageref", "formatted", "nameref", "eqref", 0 };
148 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
149 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
150 "secref", "subsecref", "tabref", "thmref", 0 };
152 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
153 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
154 "sec", "subsec", "tab", "thm", 0 };
158 * supported CJK encodings
159 * JIS does not work with LyX's encoding conversion
161 const char * const supported_CJK_encodings[] = {
162 "EUC-JP", "KS", "GB", "UTF8",
163 "Bg5", /*"JIS",*/ "SJIS", 0};
166 * the same as supported_CJK_encodings with their corresponding LyX language name
167 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
169 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
170 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
171 * please keep this in sync with supported_CJK_encodings line by line!
173 const char * const supported_CJK_languages[] = {
174 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
175 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
179 * The starred forms are also known except for "citefullauthor",
180 * "citeyear" and "citeyearpar".
182 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
183 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
184 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
188 * No starred form other than "cite*" known.
190 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
191 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
192 // jurabib commands not (yet) supported by LyX:
194 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
195 // "footciteauthor", "footciteyear", "footciteyearpar",
196 "citefield", "citetitle", 0 };
200 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
202 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
203 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
204 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
205 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
206 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
208 // Whether we need to insert a bibtex inset in a comment
209 bool need_commentbib = false;
211 /// LaTeX names for quotes
212 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
213 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
214 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
215 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
218 /// the same as known_quotes with .lyx names
219 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
220 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
221 "gld", "eld", "gls", "ers", "ars",
222 "ars", "als", "als", "erd", "qrs", "qrd", 0};
224 /// LaTeX names for font sizes
225 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
226 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
228 /// the same as known_sizes with .lyx names
229 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
230 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
232 /// LaTeX 2.09 names for font families
233 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
235 /// LaTeX names for font families
236 char const * const known_font_families[] = { "rmfamily", "sffamily",
239 /// LaTeX names for font family changing commands
240 char const * const known_text_font_families[] = { "textrm", "textsf",
243 /// The same as known_old_font_families, known_font_families and
244 /// known_text_font_families with .lyx names
245 char const * const known_coded_font_families[] = { "roman", "sans",
248 /// LaTeX 2.09 names for font series
249 char const * const known_old_font_series[] = { "bf", 0};
251 /// LaTeX names for font series
252 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
254 /// LaTeX names for font series changing commands
255 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
257 /// The same as known_old_font_series, known_font_series and
258 /// known_text_font_series with .lyx names
259 char const * const known_coded_font_series[] = { "bold", "medium", 0};
261 /// LaTeX 2.09 names for font shapes
262 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
264 /// LaTeX names for font shapes
265 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
268 /// LaTeX names for font shape changing commands
269 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
272 /// The same as known_old_font_shapes, known_font_shapes and
273 /// known_text_font_shapes with .lyx names
274 char const * const known_coded_font_shapes[] = { "italic", "slanted",
275 "smallcaps", "up", 0};
277 /// Known special characters which need skip_spaces_braces() afterwards
278 char const * const known_special_chars[] = {"ldots",
279 "lyxarrow", "textcompwordmark",
280 "slash", "textasciitilde", "textasciicircum", "textbackslash",
281 "LyX", "TeX", "LaTeXe",
284 /// special characters from known_special_chars which may have a \\protect before
285 char const * const known_special_protect_chars[] = {"LyX", "TeX",
286 "LaTeXe", "LaTeX", 0};
288 /// the same as known_special_chars with .lyx names
289 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
290 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
291 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
292 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
293 "\\SpecialChar LaTeX\n", 0};
296 * Graphics file extensions known by the dvips driver of the graphics package.
297 * These extensions are used to complete the filename of an included
298 * graphics file if it does not contain an extension.
299 * The order must be the same that latex uses to find a file, because we
300 * will use the first extension that matches.
301 * This is only an approximation for the common cases. If we would want to
302 * do it right in all cases, we would need to know which graphics driver is
303 * used and know the extensions of every driver of the graphics package.
305 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
306 "ps.gz", "eps.Z", "ps.Z", 0};
309 * Graphics file extensions known by the pdftex driver of the graphics package.
310 * \sa known_dvips_graphics_formats
312 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
316 * Known file extensions for TeX files as used by \\include.
318 char const * const known_tex_extensions[] = {"tex", 0};
320 /// spaces known by InsetSpace
321 char const * const known_spaces[] = { " ", "space",
322 ",", "thinspace",// \\, = \\thinspace
323 "quad", "qquad", "enspace", "enskip",
324 ";", ">", "medspace",// \\; = \\> = \\medspace
325 ":", "thickspace",// \\: = \\thickspace
326 "!", "negthinspace",// \\! = \\negthinspace
327 "negmedspace", "negthickspace",
328 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
329 "rightarrowfill", "upbracefill", "downbracefill", 0};
331 /// the same as known_spaces with .lyx names
332 char const * const known_coded_spaces[] = { "space{}", "space{}",
333 "thinspace{}", "thinspace{}",
334 "quad{}", "qquad{}", "enspace{}", "enskip{}",
335 "medspace{}", "medspace{}", "medspace{}",
336 "thickspace{}", "thickspace{}",
337 "negthinspace{}", "negthinspace{}",
338 "negmedspace{}", "negthickspace{}",
339 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
340 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
342 /// known TIPA combining diacritical marks
343 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
344 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
345 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
346 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
347 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
348 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
349 "textsubring", "textsubbar", 0};
351 /// TIPA tones that need special handling
352 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
354 // string to store the float type to be able to determine the type of subfloats
355 string float_type = "";
357 // string to store the float status of minted listings
358 string minted_float = "";
360 // whether a caption has been parsed for a floating minted listing
361 bool minted_float_has_caption = false;
363 // The caption for non-floating minted listings
364 string minted_nonfloat_caption = "";
366 // Characters that have to be escaped by \\ in LaTeX
367 char const * const known_escaped_chars[] = {
368 "&", "_", "$", "%", "#", "^", "{", "}", 0};
371 /// splits "x=z, y=b" into a map and an ordered keyword vector
372 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
377 keys.resize(v.size());
378 for (size_t i = 0; i < v.size(); ++i) {
379 size_t const pos = v[i].find('=');
380 string const index = trimSpaceAndEol(v[i].substr(0, pos));
381 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
389 * Split a LaTeX length into value and unit.
390 * The latter can be a real unit like "pt", or a latex length variable
391 * like "\textwidth". The unit may contain additional stuff like glue
392 * lengths, but we don't care, because such lengths are ERT anyway.
393 * \returns true if \p value and \p unit are valid.
395 bool splitLatexLength(string const & len, string & value, string & unit)
399 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
400 //'4,5' is a valid LaTeX length number. Change it to '4.5'
401 string const length = subst(len, ',', '.');
402 if (i == string::npos)
405 if (len[0] == '\\') {
406 // We had something like \textwidth without a factor
412 value = trimSpaceAndEol(string(length, 0, i));
416 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
417 if (contains(len, '\\'))
418 unit = trimSpaceAndEol(string(len, i));
420 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
425 /// A simple function to translate a latex length to something LyX can
426 /// understand. Not perfect, but rather best-effort.
427 bool translate_len(string const & length, string & valstring, string & unit)
429 if (!splitLatexLength(length, valstring, unit))
431 // LyX uses percent values
433 istringstream iss(valstring);
438 string const percentval = oss.str();
440 if (unit.empty() || unit[0] != '\\')
442 string::size_type const i = unit.find(' ');
443 string const endlen = (i == string::npos) ? string() : string(unit, i);
444 if (unit == "\\textwidth") {
445 valstring = percentval;
446 unit = "text%" + endlen;
447 } else if (unit == "\\columnwidth") {
448 valstring = percentval;
449 unit = "col%" + endlen;
450 } else if (unit == "\\paperwidth") {
451 valstring = percentval;
452 unit = "page%" + endlen;
453 } else if (unit == "\\linewidth") {
454 valstring = percentval;
455 unit = "line%" + endlen;
456 } else if (unit == "\\paperheight") {
457 valstring = percentval;
458 unit = "pheight%" + endlen;
459 } else if (unit == "\\textheight") {
460 valstring = percentval;
461 unit = "theight%" + endlen;
462 } else if (unit == "\\baselineskip") {
463 valstring = percentval;
464 unit = "baselineskip%" + endlen;
470 /// If we have ambiguous quotation marks, make a smart guess
471 /// based on main quote style
472 string guessQuoteStyle(string const & in, bool const opening)
475 if (prefixIs(in, "qr")) {// straight quote
477 res = subst(res, "r", "l");
478 } else if (in == "eld") {// ``
479 if (preamble.quotesStyle() == "german")
481 else if (preamble.quotesStyle() == "british")
483 else if (preamble.quotesStyle() == "french")
485 else if (preamble.quotesStyle() == "russian")
487 } else if (in == "erd") {// ''
488 if (preamble.quotesStyle() == "polish")
490 else if (preamble.quotesStyle() == "british")
492 else if (preamble.quotesStyle() == "french")
494 else if (preamble.quotesStyle() == "hungarian")
496 else if (preamble.quotesStyle() == "swedish")
497 res = opening ? "sld" : "srd";
498 } else if (in == "els") {// `
499 if (preamble.quotesStyle() == "german")
501 else if (preamble.quotesStyle() == "british")
503 } else if (in == "ers") {// '
504 if (preamble.quotesStyle() == "polish")
506 else if (preamble.quotesStyle() == "british")
508 else if (preamble.quotesStyle() == "swedish")
509 res = opening ? "sls" : "srs";
510 } else if (in == "ard") {// >>
511 if (preamble.quotesStyle() == "swiss")
513 else if (preamble.quotesStyle() == "french")
515 else if (preamble.quotesStyle() == "russian")
517 else if (preamble.quotesStyle() == "hungarian")
519 } else if (in == "ald") {// <<
520 if (preamble.quotesStyle() == "swiss")
522 else if (preamble.quotesStyle() == "french")
524 else if (preamble.quotesStyle() == "russian")
526 else if (preamble.quotesStyle() == "hungarian")
528 } else if (in == "ars") {// >
529 if (preamble.quotesStyle() == "swiss")
531 } else if (in == "als") {// <
532 if (preamble.quotesStyle() == "swiss")
534 } else if (in == "gld") {// ,,
535 if (preamble.quotesStyle() == "polish")
537 else if (preamble.quotesStyle() == "hungarian")
539 else if (preamble.quotesStyle() == "russian")
541 } else if (in == "gls") {// ,
542 if (preamble.quotesStyle() == "polish")
549 string const fromPolyglossiaEnvironment(string const & s)
551 // Since \arabic is taken by the LaTeX kernel,
552 // the Arabic polyglossia environment is upcased
560 string uncapitalize(string const & s)
562 docstring in = from_ascii(s);
563 char_type t = lowercase(s[0]);
569 bool isCapitalized(string const & s)
571 docstring in = from_ascii(s);
572 char_type t = uppercase(s[0]);
574 return to_ascii(in) == s;
581 string translate_len(string const & length)
585 if (translate_len(length, value, unit))
587 // If the input is invalid, return what we have.
595 * Translates a LaTeX length into \p value, \p unit and
596 * \p special parts suitable for a box inset.
597 * The difference from translate_len() is that a box inset knows about
598 * some special "units" that are stored in \p special.
600 void translate_box_len(string const & length, string & value, string & unit, string & special)
602 if (translate_len(length, value, unit)) {
603 if (unit == "\\height" || unit == "\\depth" ||
604 unit == "\\totalheight" || unit == "\\width") {
605 special = unit.substr(1);
606 // The unit is not used, but LyX requires a dummy setting
618 void begin_inset(ostream & os, string const & name)
620 os << "\n\\begin_inset " << name;
624 void begin_command_inset(ostream & os, string const & name,
625 string const & latexname)
627 begin_inset(os, "CommandInset ");
628 os << name << "\nLatexCommand " << latexname << '\n';
632 void end_inset(ostream & os)
634 os << "\n\\end_inset\n\n";
638 bool skip_braces(Parser & p)
640 if (p.next_token().cat() != catBegin)
643 if (p.next_token().cat() == catEnd) {
652 /// replace LaTeX commands in \p s from the unicodesymbols file with their
654 pair<bool, docstring> convert_unicodesymbols(docstring s)
658 for (size_t i = 0; i < s.size();) {
667 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
668 Encodings::TEXT_CMD, termination, rem, &req));
669 set<string>::const_iterator it = req.begin();
670 set<string>::const_iterator en = req.end();
671 for (; it != en; ++it)
672 preamble.registerAutomaticallyLoadedPackage(*it);
675 if (s.empty() || s[0] != '\\')
679 for (auto const & c : known_escaped_chars)
680 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
685 return make_pair(res, os.str());
689 /// try to convert \p s to a valid InsetCommand argument
690 /// return whether this succeeded. If not, these command insets
691 /// get the "literate" flag.
692 pair<bool, string> convert_latexed_command_inset_arg(string s)
694 bool success = false;
696 // since we don't know the input encoding we can't use from_utf8
697 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
699 s = to_utf8(res.second);
701 // LyX cannot handle newlines in a latex command
702 return make_pair(success, subst(s, "\n", " "));
705 /// try to convert \p s to a valid InsetCommand argument
706 /// without trying to recode macros.
707 string convert_literate_command_inset_arg(string const & s)
709 // LyX cannot handle newlines in a latex command
710 return subst(s, "\n", " ");
713 void output_ert(ostream & os, string const & s, Context & context)
715 context.check_layout(os);
716 for (char const c : s) {
718 os << "\n\\backslash\n";
719 else if (c == '\n') {
720 context.new_paragraph(os);
721 context.check_layout(os);
725 context.check_end_layout(os);
729 void output_ert_inset(ostream & os, string const & s, Context & context)
731 // We must have a valid layout before outputting the ERT inset.
732 context.check_layout(os);
733 Context newcontext(true, context.textclass);
734 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
735 if (layout.forcePlainLayout())
736 newcontext.layout = &context.textclass.plainLayout();
737 begin_inset(os, "ERT");
738 os << "\nstatus collapsed\n";
739 output_ert(os, s, newcontext);
744 void output_comment(Parser & p, ostream & os, string const & s,
747 if (p.next_token().cat() == catNewline)
748 output_ert_inset(os, '%' + s, context);
750 output_ert_inset(os, '%' + s + '\n', context);
754 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
755 string const & latexparam = string())
757 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
760 if (checkModule(name, command))
761 return findLayoutWithoutModule(textclass, name, command, latexparam);
766 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
767 string const & latexparam = string())
769 InsetLayout const * insetlayout =
770 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
773 if (checkModule(name, command))
774 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
779 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
780 bool eatNewline = true);
784 * Skips whitespace and braces.
785 * This should be called after a command has been parsed that is not put into
786 * ERT, and where LyX adds "{}" if needed.
788 void skip_spaces_braces(Parser & p, bool keepws = false)
790 /* The following four examples produce the same typeset output and
791 should be handled by this function:
799 // Unfortunately we need to skip comments, too.
800 // We can't use eat_whitespace since writing them after the {}
801 // results in different output in some cases.
802 bool const skipped_spaces = p.skip_spaces(true);
803 bool const skipped_braces = skip_braces(p);
804 if (keepws && skipped_spaces && !skipped_braces)
805 // put back the space (it is better handled by check_space)
806 p.unskip_spaces(true);
810 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
811 Context & context, Layout::LaTeXArgMap const & latexargs)
813 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
815 context.check_layout(os);
821 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
822 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
823 for (; lait != laend; ++lait) {
825 eat_whitespace(p, os, context, false);
826 if (lait->second.mandatory) {
827 if (p.next_token().cat() != catBegin)
829 string ldelim = to_utf8(lait->second.ldelim);
830 string rdelim = to_utf8(lait->second.rdelim);
835 p.get_token(); // eat ldelim
836 if (ldelim.size() > 1)
837 p.get_token(); // eat ldelim
839 context.check_layout(os);
842 begin_inset(os, "Argument ");
845 os << i << "\nstatus collapsed\n\n";
846 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
849 string ldelim = to_utf8(lait->second.ldelim);
850 string rdelim = to_utf8(lait->second.rdelim);
855 string tok = p.next_token().asInput();
856 // we only support delimiters with max 2 chars for now.
857 if (ldelim.size() > 1)
858 tok += p.next_next_token().asInput();
859 if (p.next_token().cat() == catEscape || tok != ldelim)
861 p.get_token(); // eat ldelim
862 if (ldelim.size() > 1)
863 p.get_token(); // eat ldelim
865 context.check_layout(os);
868 begin_inset(os, "Argument ");
871 os << i << "\nstatus collapsed\n\n";
872 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
875 eat_whitespace(p, os, context, false);
880 void output_command_layout(ostream & os, Parser & p, bool outer,
881 Context & parent_context,
882 Layout const * newlayout)
884 TeXFont const oldFont = parent_context.font;
885 // save the current font size
886 string const size = oldFont.size;
887 // reset the font size to default, because the font size switches
888 // don't affect section headings and the like
889 parent_context.font.size = Context::normalfont.size;
890 // we only need to write the font change if we have an open layout
891 if (!parent_context.atParagraphStart())
892 output_font_change(os, oldFont, parent_context.font);
893 parent_context.check_end_layout(os);
894 Context context(true, parent_context.textclass, newlayout,
895 parent_context.layout, parent_context.font);
896 if (parent_context.deeper_paragraph) {
897 // We are beginning a nested environment after a
898 // deeper paragraph inside the outer list environment.
899 // Therefore we don't need to output a "begin deeper".
900 context.need_end_deeper = true;
902 context.check_deeper(os);
903 output_arguments(os, p, outer, true, string(), context,
904 context.layout->latexargs());
905 // If we have a latex param, we eat it here.
906 if (!parent_context.latexparam.empty()) {
908 Context dummy(true, parent_context.textclass);
909 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
910 string(1, parent_context.latexparam.back()));
912 parse_text(p, os, FLAG_ITEM, outer, context);
913 output_arguments(os, p, outer, false, "post", context,
914 context.layout->postcommandargs());
915 context.check_end_layout(os);
916 if (parent_context.deeper_paragraph) {
917 // We must suppress the "end deeper" because we
918 // suppressed the "begin deeper" above.
919 context.need_end_deeper = false;
921 context.check_end_deeper(os);
922 // We don't need really a new paragraph, but
923 // we must make sure that the next item gets a \begin_layout.
924 parent_context.new_paragraph(os);
925 // Set the font size to the original value. No need to output it here
926 // (Context::begin_layout() will do that if needed)
927 parent_context.font.size = size;
932 * Output a space if necessary.
933 * This function gets called for every whitespace token.
935 * We have three cases here:
936 * 1. A space must be suppressed. Example: The lyxcode case below
937 * 2. A space may be suppressed. Example: Spaces before "\par"
938 * 3. A space must not be suppressed. Example: A space between two words
940 * We currently handle only 1. and 3 and from 2. only the case of
941 * spaces before newlines as a side effect.
943 * 2. could be used to suppress as many spaces as possible. This has two effects:
944 * - Reimporting LyX generated LaTeX files changes almost no whitespace
945 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
946 * The drawback is that the logic inside the function becomes
947 * complicated, and that is the reason why it is not implemented.
949 void check_space(Parser & p, ostream & os, Context & context)
951 Token const next = p.next_token();
952 Token const curr = p.curr_token();
953 // A space before a single newline and vice versa must be ignored
954 // LyX emits a newline before \end{lyxcode}.
955 // This newline must be ignored,
956 // otherwise LyX will add an additional protected space.
957 if (next.cat() == catSpace ||
958 next.cat() == catNewline ||
959 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
962 context.check_layout(os);
968 * Parse all arguments of \p command
970 void parse_arguments(string const & command,
971 vector<ArgumentType> const & template_arguments,
972 Parser & p, ostream & os, bool outer, Context & context)
974 string ert = command;
975 size_t no_arguments = template_arguments.size();
976 for (size_t i = 0; i < no_arguments; ++i) {
977 switch (template_arguments[i]) {
980 // This argument contains regular LaTeX
981 output_ert_inset(os, ert + '{', context);
982 eat_whitespace(p, os, context, false);
983 if (template_arguments[i] == required)
984 parse_text(p, os, FLAG_ITEM, outer, context);
986 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
990 // This argument consists only of a single item.
991 // The presence of '{' or not must be preserved.
993 if (p.next_token().cat() == catBegin)
994 ert += '{' + p.verbatim_item() + '}';
996 ert += p.verbatim_item();
1000 // This argument may contain special characters
1001 ert += '{' + p.verbatim_item() + '}';
1005 // true because we must not eat whitespace
1006 // if an optional arg follows we must not strip the
1007 // brackets from this one
1008 if (i < no_arguments - 1 &&
1009 template_arguments[i+1] == optional)
1010 ert += p.getFullOpt(true);
1012 ert += p.getOpt(true);
1016 output_ert_inset(os, ert, context);
1021 * Check whether \p command is a known command. If yes,
1022 * handle the command with all arguments.
1023 * \return true if the command was parsed, false otherwise.
1025 bool parse_command(string const & command, Parser & p, ostream & os,
1026 bool outer, Context & context)
1028 if (known_commands.find(command) != known_commands.end()) {
1029 parse_arguments(command, known_commands[command], p, os,
1037 /// Parses a minipage or parbox
1038 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1039 unsigned inner_flags, bool outer, Context & parent_context,
1040 string const & outer_type, string const & special,
1041 string inner_type, string const & frame_color,
1042 string const & background_color)
1046 string hor_pos = "l";
1047 // We need to set the height to the LaTeX default of 1\\totalheight
1048 // for the case when no height argument is given
1049 string height_value = "1";
1050 string height_unit = "in";
1051 string height_special = "totalheight";
1052 string latex_height;
1056 string width_special = "none";
1057 string thickness = "0.4pt";
1058 if (!fboxrule.empty())
1059 thickness = fboxrule;
1061 thickness = "0.4pt";
1063 if (!fboxsep.empty())
1064 separation = fboxsep;
1068 if (!shadow_size.empty())
1069 shadowsize = shadow_size;
1072 string framecolor = "black";
1073 string backgroundcolor = "none";
1074 if (!frame_color.empty())
1075 framecolor = frame_color;
1076 if (!background_color.empty())
1077 backgroundcolor = background_color;
1078 // if there is a color box around the \begin statements have not yet been parsed
1080 if (!frame_color.empty() || !background_color.empty()) {
1081 eat_whitespace(p, os, parent_context, false);
1082 p.get_token().asInput(); // the '{'
1084 if (p.next_token().asInput() == "\\begin") {
1085 p.get_token().asInput();
1087 inner_type = "minipage";
1088 inner_flags = FLAG_END;
1089 active_environments.push_back("minipage");
1092 else if (p.next_token().asInput() == "\\parbox") {
1093 p.get_token().asInput();
1094 inner_type = "parbox";
1095 inner_flags = FLAG_ITEM;
1098 else if (p.next_token().asInput() == "\\makebox") {
1099 p.get_token().asInput();
1100 inner_type = "makebox";
1101 inner_flags = FLAG_ITEM;
1103 // in case there is just \colorbox{color}{text}
1106 inner_type = "makebox";
1107 inner_flags = FLAG_BRACE_LAST;
1112 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1114 if (!inner_type.empty() && p.hasOpt()) {
1115 if (inner_type != "makebox")
1116 position = p.getArg('[', ']');
1118 latex_width = p.getArg('[', ']');
1119 translate_box_len(latex_width, width_value, width_unit, width_special);
1122 if (position != "t" && position != "c" && position != "b") {
1123 cerr << "invalid position " << position << " for "
1124 << inner_type << endl;
1128 if (inner_type != "makebox") {
1129 latex_height = p.getArg('[', ']');
1130 translate_box_len(latex_height, height_value, height_unit, height_special);
1132 string const opt = p.getArg('[', ']');
1135 if (hor_pos != "l" && hor_pos != "c" &&
1136 hor_pos != "r" && hor_pos != "s") {
1137 cerr << "invalid hor_pos " << hor_pos
1138 << " for " << inner_type << endl;
1145 inner_pos = p.getArg('[', ']');
1146 if (inner_pos != "c" && inner_pos != "t" &&
1147 inner_pos != "b" && inner_pos != "s") {
1148 cerr << "invalid inner_pos "
1149 << inner_pos << " for "
1150 << inner_type << endl;
1151 inner_pos = position;
1155 if (inner_type == "makebox")
1159 if (inner_type.empty()) {
1160 if (special.empty() && outer_type != "framebox")
1161 latex_width = "1\\columnwidth";
1164 latex_width = p2.getArg('[', ']');
1165 string const opt = p2.getArg('[', ']');
1168 if (hor_pos != "l" && hor_pos != "c" &&
1169 hor_pos != "r" && hor_pos != "s") {
1170 cerr << "invalid hor_pos " << hor_pos
1171 << " for " << outer_type << endl;
1175 if (outer_type == "framebox")
1179 } else if (inner_type != "makebox")
1180 latex_width = p.verbatim_item();
1181 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1182 // as this is LyX's standard for such cases (except for makebox)
1183 // \framebox is more special and handled below
1184 if (latex_width.empty() && inner_type != "makebox"
1185 && outer_type != "framebox")
1186 latex_width = "1\\columnwidth";
1188 translate_len(latex_width, width_value, width_unit);
1190 bool shadedparbox = false;
1191 if (inner_type == "shaded") {
1192 eat_whitespace(p, os, parent_context, false);
1193 if (outer_type == "parbox") {
1195 if (p.next_token().cat() == catBegin)
1197 eat_whitespace(p, os, parent_context, false);
1198 shadedparbox = true;
1203 // If we already read the inner box we have to push the inner env
1204 if (!outer_type.empty() && !inner_type.empty() &&
1205 (inner_flags & FLAG_END))
1206 active_environments.push_back(inner_type);
1207 bool use_ert = false;
1208 if (!outer_type.empty() && !inner_type.empty()) {
1209 // Look whether there is some content after the end of the
1210 // inner box, but before the end of the outer box.
1211 // If yes, we need to output ERT.
1213 if (inner_flags & FLAG_END)
1214 p.ertEnvironment(inner_type);
1217 p.skip_spaces(true);
1218 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1219 if ((outer_env && p.next_token().asInput() != "\\end") ||
1220 (!outer_env && p.next_token().cat() != catEnd)) {
1221 // something is between the end of the inner box and
1222 // the end of the outer box, so we need to use ERT.
1230 if (!outer_type.empty()) {
1231 if (outer_flags & FLAG_END)
1232 ss << "\\begin{" << outer_type << '}';
1234 ss << '\\' << outer_type << '{';
1235 if (!special.empty())
1239 if (!inner_type.empty()) {
1240 if (inner_type != "shaded") {
1241 if (inner_flags & FLAG_END)
1242 ss << "\\begin{" << inner_type << '}';
1244 ss << '\\' << inner_type;
1246 if (!position.empty())
1247 ss << '[' << position << ']';
1248 if (!latex_height.empty())
1249 ss << '[' << latex_height << ']';
1250 if (!inner_pos.empty())
1251 ss << '[' << inner_pos << ']';
1252 ss << '{' << latex_width << '}';
1253 if (!(inner_flags & FLAG_END))
1256 if (inner_type == "shaded")
1257 ss << "\\begin{shaded}";
1258 output_ert_inset(os, ss.str(), parent_context);
1259 if (!inner_type.empty()) {
1260 parse_text(p, os, inner_flags, outer, parent_context);
1261 if (inner_flags & FLAG_END)
1262 output_ert_inset(os, "\\end{" + inner_type + '}',
1265 output_ert_inset(os, "}", parent_context);
1267 if (!outer_type.empty()) {
1268 // If we already read the inner box we have to pop
1270 if (!inner_type.empty() && (inner_flags & FLAG_END))
1271 active_environments.pop_back();
1273 // Ensure that the end of the outer box is parsed correctly:
1274 // The opening brace has been eaten by parse_outer_box()
1275 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1276 outer_flags &= ~FLAG_ITEM;
1277 outer_flags |= FLAG_BRACE_LAST;
1279 parse_text(p, os, outer_flags, outer, parent_context);
1280 if (outer_flags & FLAG_END)
1281 output_ert_inset(os, "\\end{" + outer_type + '}',
1284 output_ert_inset(os, "}", parent_context);
1287 // LyX does not like empty positions, so we have
1288 // to set them to the LaTeX default values here.
1289 if (position.empty())
1291 if (inner_pos.empty())
1292 inner_pos = position;
1293 parent_context.check_layout(os);
1294 begin_inset(os, "Box ");
1295 if (outer_type == "framed")
1297 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1299 else if (outer_type == "shadowbox")
1300 os << "Shadowbox\n";
1301 else if ((outer_type == "shaded" && inner_type.empty()) ||
1302 (outer_type == "minipage" && inner_type == "shaded") ||
1303 (outer_type == "parbox" && inner_type == "shaded")) {
1305 preamble.registerAutomaticallyLoadedPackage("color");
1306 } else if (outer_type == "doublebox")
1307 os << "Doublebox\n";
1308 else if (outer_type.empty() || outer_type == "mbox")
1309 os << "Frameless\n";
1311 os << outer_type << '\n';
1312 os << "position \"" << position << "\"\n";
1313 os << "hor_pos \"" << hor_pos << "\"\n";
1314 if (outer_type == "mbox")
1315 os << "has_inner_box 1\n";
1316 else if (!frame_color.empty() && inner_type == "makebox")
1317 os << "has_inner_box 0\n";
1319 os << "has_inner_box " << !inner_type.empty() << "\n";
1320 os << "inner_pos \"" << inner_pos << "\"\n";
1321 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1323 if (outer_type == "mbox")
1324 os << "use_makebox 1\n";
1325 else if (!frame_color.empty())
1326 os << "use_makebox 0\n";
1328 os << "use_makebox " << (inner_type == "makebox") << '\n';
1329 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1330 os << "width \"\"\n";
1331 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1332 else if (contains(width_unit, '\\'))
1333 os << "width \"" << width_value << "in" << "\"\n";
1335 os << "width \"" << width_value << width_unit << "\"\n";
1336 if (contains(width_unit, '\\')) {
1337 width_unit.erase (0,1); // remove the leading '\'
1338 os << "special \"" << width_unit << "\"\n";
1340 os << "special \"" << width_special << "\"\n";
1341 if (contains(height_unit, '\\'))
1342 os << "height \"" << height_value << "in" << "\"\n";
1344 os << "height \"" << height_value << height_unit << "\"\n";
1345 os << "height_special \"" << height_special << "\"\n";
1346 os << "thickness \"" << thickness << "\"\n";
1347 os << "separation \"" << separation << "\"\n";
1348 os << "shadowsize \"" << shadowsize << "\"\n";
1349 os << "framecolor \"" << framecolor << "\"\n";
1350 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1351 os << "status open\n\n";
1353 // Unfortunately we can't use parse_text_in_inset:
1354 // InsetBox::forcePlainLayout() is hard coded and does not
1355 // use the inset layout. Apart from that do we call parse_text
1356 // up to two times, but need only one check_end_layout.
1357 bool const forcePlainLayout =
1358 (!inner_type.empty() || inner_type == "makebox") &&
1359 outer_type != "shaded" && outer_type != "framed";
1360 Context context(true, parent_context.textclass);
1361 if (forcePlainLayout)
1362 context.layout = &context.textclass.plainLayout();
1364 context.font = parent_context.font;
1366 // If we have no inner box the contents will be read with the outer box
1367 if (!inner_type.empty())
1368 parse_text(p, os, inner_flags, outer, context);
1370 // Ensure that the end of the outer box is parsed correctly:
1371 // The opening brace has been eaten by parse_outer_box()
1372 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1373 outer_flags &= ~FLAG_ITEM;
1374 outer_flags |= FLAG_BRACE_LAST;
1377 // Find end of outer box, output contents if inner_type is
1378 // empty and output possible comments
1379 if (!outer_type.empty()) {
1380 // If we already read the inner box we have to pop
1382 if (!inner_type.empty() && (inner_flags & FLAG_END))
1383 active_environments.pop_back();
1384 // This does not output anything but comments if
1385 // inner_type is not empty (see use_ert)
1386 parse_text(p, os, outer_flags, outer, context);
1389 context.check_end_layout(os);
1391 #ifdef PRESERVE_LAYOUT
1392 // LyX puts a % after the end of the minipage
1393 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1395 //output_comment(p, os, "dummy", parent_context);
1398 parent_context.new_paragraph(os);
1400 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1401 //output_comment(p, os, "dummy", parent_context);
1404 // We add a protected space if something real follows
1405 if (p.good() && p.next_token().cat() != catComment) {
1406 begin_inset(os, "space ~\n");
1412 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1413 active_environments.pop_back();
1414 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1415 // in this case we have to eat the the closing brace of the color box
1416 p.get_token().asInput(); // the '}'
1418 if (p.next_token().asInput() == "}") {
1419 // in this case we assume that the closing brace is from the box settings
1420 // therefore reset these values for the next box
1426 // all boxes except of Frameless and Shaded require calc
1427 if (!(outer_type.empty() || outer_type == "mbox") &&
1428 !((outer_type == "shaded" && inner_type.empty()) ||
1429 (outer_type == "minipage" && inner_type == "shaded") ||
1430 (outer_type == "parbox" && inner_type == "shaded")))
1431 preamble.registerAutomaticallyLoadedPackage("calc");
1435 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1436 Context & parent_context, string const & outer_type,
1437 string const & special)
1439 eat_whitespace(p, os, parent_context, false);
1440 if (flags & FLAG_ITEM) {
1442 if (p.next_token().cat() == catBegin)
1445 cerr << "Warning: Ignoring missing '{' after \\"
1446 << outer_type << '.' << endl;
1447 eat_whitespace(p, os, parent_context, false);
1450 unsigned int inner_flags = 0;
1452 if (outer_type == "minipage" || outer_type == "parbox") {
1453 p.skip_spaces(true);
1454 while (p.hasOpt()) {
1456 p.skip_spaces(true);
1459 p.skip_spaces(true);
1460 if (outer_type == "parbox") {
1462 if (p.next_token().cat() == catBegin)
1464 p.skip_spaces(true);
1467 if (outer_type == "shaded" || outer_type == "mbox") {
1468 // These boxes never have an inner box
1470 } else if (p.next_token().asInput() == "\\parbox") {
1471 inner = p.get_token().cs();
1472 inner_flags = FLAG_ITEM;
1473 } else if (p.next_token().asInput() == "\\begin") {
1474 // Is this a minipage or shaded box?
1477 inner = p.getArg('{', '}');
1479 if (inner == "minipage" || inner == "shaded")
1480 inner_flags = FLAG_END;
1485 if (inner_flags == FLAG_END) {
1486 if (inner != "shaded")
1490 eat_whitespace(p, os, parent_context, false);
1492 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1493 outer_type, special, inner, "", "");
1495 if (inner_flags == FLAG_ITEM) {
1497 eat_whitespace(p, os, parent_context, false);
1499 parse_box(p, os, flags, inner_flags, outer, parent_context,
1500 outer_type, special, inner, "", "");
1505 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1506 bool in_line, bool use_minted)
1508 parent_context.check_layout(os);
1509 begin_inset(os, "listings\n");
1510 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1512 while ((i = arg.find(", ")) != string::npos
1513 || (i = arg.find(",\t")) != string::npos)
1514 arg.erase(i + 1, 1);
1517 string const language = p.getArg('{', '}');
1518 p.skip_spaces(true);
1519 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1520 if (!minted_float.empty()) {
1521 arg += string(arg.empty() ? "" : ",") + minted_float;
1522 minted_nonfloat_caption.clear();
1526 os << "lstparams " << '"' << arg << '"' << '\n';
1527 if (arg.find("\\color") != string::npos)
1528 preamble.registerAutomaticallyLoadedPackage("color");
1531 os << "inline true\n";
1533 os << "inline false\n";
1534 os << "status open\n";
1535 Context context(true, parent_context.textclass);
1536 context.layout = &parent_context.textclass.plainLayout();
1537 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1538 minted_nonfloat_caption.erase(0,3);
1539 os << "\n\\begin_layout Plain Layout\n";
1540 begin_inset(os, "Caption Standard\n");
1541 Context newcontext(true, context.textclass,
1542 context.layout, 0, context.font);
1543 newcontext.check_layout(os);
1544 os << minted_nonfloat_caption << "\n";
1545 newcontext.check_end_layout(os);
1547 os << "\n\\end_layout\n";
1548 minted_nonfloat_caption.clear();
1552 // set catcodes to verbatim early, just in case.
1553 p.setCatcodes(VERBATIM_CATCODES);
1554 string delim = p.get_token().asInput();
1555 //FIXME: handler error condition
1556 s = p.verbatimStuff(delim).second;
1557 // context.new_paragraph(os);
1558 } else if (use_minted) {
1559 s = p.verbatimEnvironment("minted");
1561 s = p.verbatimEnvironment("lstlisting");
1563 output_ert(os, s, context);
1564 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1565 minted_nonfloat_caption.erase(0,3);
1566 os << "\n\\begin_layout Plain Layout\n";
1567 begin_inset(os, "Caption Standard\n");
1568 Context newcontext(true, context.textclass,
1569 context.layout, 0, context.font);
1570 newcontext.check_layout(os);
1571 os << minted_nonfloat_caption << "\n";
1572 newcontext.check_end_layout(os);
1574 os << "\n\\end_layout\n";
1575 minted_nonfloat_caption.clear();
1577 // Don't close the inset here for floating minted listings.
1578 // It will be closed at the end of the listing environment.
1579 if (!use_minted || minted_float.empty())
1582 eat_whitespace(p, os, parent_context, true);
1583 Token t = p.get_token();
1584 if (t.asInput() != "\\end") {
1585 // If anything follows, collect it into a caption.
1586 minted_float_has_caption = true;
1587 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1588 begin_inset(os, "Caption Standard\n");
1589 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1596 /// parse an unknown environment
1597 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1598 unsigned flags, bool outer,
1599 Context & parent_context)
1601 if (name == "tabbing")
1602 // We need to remember that we have to handle '\=' specially
1603 flags |= FLAG_TABBING;
1605 // We need to translate font changes and paragraphs inside the
1606 // environment to ERT if we have a non standard font.
1607 // Otherwise things like
1608 // \large\begin{foo}\huge bar\end{foo}
1610 bool const specialfont =
1611 (parent_context.font != parent_context.normalfont);
1612 bool const new_layout_allowed = parent_context.new_layout_allowed;
1614 parent_context.new_layout_allowed = false;
1615 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1616 // Try to handle options: Look if we have optional arguments,
1617 // and if so, put the brackets in ERT.
1618 while (p.hasOpt()) {
1619 p.get_token(); // eat '['
1620 output_ert_inset(os, "[", parent_context);
1621 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1622 output_ert_inset(os, "]", parent_context);
1624 parse_text_snippet(p, os, flags, outer, parent_context);
1625 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1627 parent_context.new_layout_allowed = new_layout_allowed;
1631 void parse_environment(Parser & p, ostream & os, bool outer,
1632 string & last_env, Context & parent_context)
1634 Layout const * newlayout;
1635 InsetLayout const * newinsetlayout = 0;
1636 string const name = p.getArg('{', '}');
1637 const bool is_starred = suffixIs(name, '*');
1638 string const unstarred_name = rtrim(name, "*");
1639 active_environments.push_back(name);
1641 // We use this loop and break out after a condition is met
1642 // rather than a huge else-if-chain.
1644 if (is_math_env(name)) {
1645 parent_context.check_layout(os);
1646 begin_inset(os, "Formula ");
1647 os << "\\begin{" << name << "}";
1648 parse_math(p, os, FLAG_END, MATH_MODE);
1649 os << "\\end{" << name << "}";
1651 if (is_display_math_env(name)) {
1652 // Prevent the conversion of a line break to a space
1653 // (bug 7668). This does not change the output, but
1654 // looks ugly in LyX.
1655 eat_whitespace(p, os, parent_context, false);
1660 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1661 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1662 // We must begin a new paragraph if not already done
1663 if (!parent_context.atParagraphStart()) {
1664 parent_context.check_end_layout(os);
1665 parent_context.new_paragraph(os);
1667 // store previous language because we must reset it at the end
1668 string const lang_old = parent_context.font.language;
1669 // save new language in context so that it is
1670 // handled by parse_text
1671 parent_context.font.language =
1672 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1673 parse_text(p, os, FLAG_END, outer, parent_context);
1674 // reset previous language
1675 parent_context.font.language = lang_old;
1676 // Just in case the environment is empty
1677 parent_context.extra_stuff.erase();
1678 // We must begin a new paragraph to reset the language
1679 parent_context.new_paragraph(os);
1684 if (unstarred_name == "tabular" || name == "longtable"
1685 || name == "tabularx" || name == "xltabular") {
1686 eat_whitespace(p, os, parent_context, false);
1687 string width = "0pt";
1689 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1690 string const opt = p.getArg('[', ']');
1693 else if (opt == "l")
1695 else if (opt == "r")
1698 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1699 width = lyx::translate_len(p.getArg('{', '}'));
1700 eat_whitespace(p, os, parent_context, false);
1702 parent_context.check_layout(os);
1703 begin_inset(os, "Tabular ");
1704 handle_tabular(p, os, name, width, halign, parent_context);
1710 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1711 eat_whitespace(p, os, parent_context, false);
1712 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1713 eat_whitespace(p, os, parent_context, false);
1714 parent_context.check_layout(os);
1715 begin_inset(os, "Float " + unstarred_name + "\n");
1716 // store the float type for subfloats
1717 // subfloats only work with figures and tables
1718 if (unstarred_name == "figure")
1719 float_type = unstarred_name;
1720 else if (unstarred_name == "table")
1721 float_type = unstarred_name;
1725 os << "placement " << opt << '\n';
1726 if (contains(opt, "H"))
1727 preamble.registerAutomaticallyLoadedPackage("float");
1729 Floating const & fl = parent_context.textclass.floats()
1730 .getType(unstarred_name);
1731 if (!fl.floattype().empty() && fl.usesFloatPkg())
1732 preamble.registerAutomaticallyLoadedPackage("float");
1735 os << "wide " << convert<string>(is_starred)
1736 << "\nsideways false"
1737 << "\nstatus open\n\n";
1738 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1739 if (unstarred_name == "algorithm")
1740 // in algorithm, \; has special meaning
1741 parent_context.pass_thru_cmds.insert(";");
1742 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1743 if (unstarred_name == "algorithm")
1744 parent_context.pass_thru_cmds = pass_thru_cmds;
1746 // We don't need really a new paragraph, but
1747 // we must make sure that the next item gets a \begin_layout.
1748 parent_context.new_paragraph(os);
1750 // the float is parsed thus delete the type
1755 if (unstarred_name == "sidewaysfigure"
1756 || unstarred_name == "sidewaystable"
1757 || unstarred_name == "sidewaysalgorithm") {
1758 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1759 eat_whitespace(p, os, parent_context, false);
1760 parent_context.check_layout(os);
1761 if (unstarred_name == "sidewaysfigure")
1762 begin_inset(os, "Float figure\n");
1763 else if (unstarred_name == "sidewaystable")
1764 begin_inset(os, "Float table\n");
1765 else if (unstarred_name == "sidewaysalgorithm")
1766 begin_inset(os, "Float algorithm\n");
1768 os << "placement " << opt << '\n';
1769 if (contains(opt, "H"))
1770 preamble.registerAutomaticallyLoadedPackage("float");
1771 os << "wide " << convert<string>(is_starred)
1772 << "\nsideways true"
1773 << "\nstatus open\n\n";
1774 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1776 // We don't need really a new paragraph, but
1777 // we must make sure that the next item gets a \begin_layout.
1778 parent_context.new_paragraph(os);
1780 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1784 if (name == "wrapfigure" || name == "wraptable") {
1785 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1786 eat_whitespace(p, os, parent_context, false);
1787 parent_context.check_layout(os);
1790 string overhang = "0col%";
1793 lines = p.getArg('[', ']');
1794 string const placement = p.getArg('{', '}');
1796 overhang = p.getArg('[', ']');
1797 string const width = p.getArg('{', '}');
1799 if (name == "wrapfigure")
1800 begin_inset(os, "Wrap figure\n");
1802 begin_inset(os, "Wrap table\n");
1803 os << "lines " << lines
1804 << "\nplacement " << placement
1805 << "\noverhang " << lyx::translate_len(overhang)
1806 << "\nwidth " << lyx::translate_len(width)
1807 << "\nstatus open\n\n";
1808 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1810 // We don't need really a new paragraph, but
1811 // we must make sure that the next item gets a \begin_layout.
1812 parent_context.new_paragraph(os);
1814 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1818 if (name == "minipage") {
1819 eat_whitespace(p, os, parent_context, false);
1820 // Test whether this is an outer box of a shaded box
1822 // swallow arguments
1823 while (p.hasOpt()) {
1825 p.skip_spaces(true);
1828 p.skip_spaces(true);
1829 Token t = p.get_token();
1830 bool shaded = false;
1831 if (t.asInput() == "\\begin") {
1832 p.skip_spaces(true);
1833 if (p.getArg('{', '}') == "shaded")
1838 parse_outer_box(p, os, FLAG_END, outer,
1839 parent_context, name, "shaded");
1841 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1842 "", "", name, "", "");
1847 if (name == "comment") {
1848 eat_whitespace(p, os, parent_context, false);
1849 parent_context.check_layout(os);
1850 begin_inset(os, "Note Comment\n");
1851 os << "status open\n";
1852 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1855 skip_braces(p); // eat {} that might by set by LyX behind comments
1856 preamble.registerAutomaticallyLoadedPackage("verbatim");
1860 if (unstarred_name == "verbatim") {
1861 // FIXME: this should go in the generic code that
1862 // handles environments defined in layout file that
1863 // have "PassThru 1". However, the code over there is
1864 // already too complicated for my taste.
1865 string const ascii_name =
1866 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1867 parent_context.new_paragraph(os);
1868 Context context(true, parent_context.textclass,
1869 &parent_context.textclass[from_ascii(ascii_name)]);
1870 string s = p.verbatimEnvironment(name);
1871 output_ert(os, s, context);
1876 if (name == "IPA") {
1877 eat_whitespace(p, os, parent_context, false);
1878 parent_context.check_layout(os);
1879 begin_inset(os, "IPA\n");
1880 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1881 // These commands have special meanings in IPA
1882 parent_context.pass_thru_cmds.insert("!");
1883 parent_context.pass_thru_cmds.insert(";");
1884 parent_context.pass_thru_cmds.insert(":");
1885 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1886 parent_context.pass_thru_cmds = pass_thru_cmds;
1889 preamble.registerAutomaticallyLoadedPackage("tipa");
1890 preamble.registerAutomaticallyLoadedPackage("tipx");
1894 if (name == parent_context.textclass.titlename()
1895 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1896 parse_text(p, os, FLAG_END, outer, parent_context);
1897 // Just in case the environment is empty
1898 parent_context.extra_stuff.erase();
1899 // We must begin a new paragraph
1900 parent_context.new_paragraph(os);
1905 if (name == "CJK") {
1906 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1907 // It is impossible to decide if a CJK environment was in its own paragraph or within
1908 // a line. We therefore always assume a paragraph since the latter is a rare case.
1909 eat_whitespace(p, os, parent_context, false);
1910 parent_context.check_end_layout(os);
1911 // store the encoding to be able to reset it
1912 string const encoding_old = p.getEncoding();
1913 string const encoding = p.getArg('{', '}');
1914 // FIXME: For some reason JIS does not work. Although the text
1915 // in tests/CJK.tex is identical with the SJIS version if you
1916 // convert both snippets using the recode command line utility,
1917 // the resulting .lyx file contains some extra characters if
1918 // you set buggy_encoding to false for JIS.
1919 bool const buggy_encoding = encoding == "JIS";
1920 if (!buggy_encoding)
1921 p.setEncoding(encoding, Encoding::CJK);
1923 // FIXME: This will read garbage, since the data is not encoded in utf8.
1924 p.setEncoding("UTF-8");
1926 // LyX only supports the same mapping for all CJK
1927 // environments, so we might need to output everything as ERT
1928 string const mapping = trim(p.getArg('{', '}'));
1929 char const * const * const where =
1930 is_known(encoding, supported_CJK_encodings);
1931 if (!buggy_encoding && !preamble.fontCJKSet())
1932 preamble.fontCJK(mapping);
1933 bool knownMapping = mapping == preamble.fontCJK();
1934 if (buggy_encoding || !knownMapping || !where) {
1935 parent_context.check_layout(os);
1936 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1938 // we must parse the content as verbatim because e.g. JIS can contain
1939 // normally invalid characters
1940 // FIXME: This works only for the most simple cases.
1941 // Since TeX control characters are not parsed,
1942 // things like comments are completely wrong.
1943 string const s = p.plainEnvironment("CJK");
1944 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1947 if (snip == "\\" || is_known(snip, known_escaped_chars))
1948 output_ert_inset(os, snip, parent_context);
1949 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1954 output_ert_inset(os, "\\end{" + name + "}",
1958 supported_CJK_languages[where - supported_CJK_encodings];
1959 // store the language because we must reset it at the end
1960 string const lang_old = parent_context.font.language;
1961 parent_context.font.language = lang;
1962 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1963 parent_context.font.language = lang_old;
1964 parent_context.new_paragraph(os);
1966 p.setEncoding(encoding_old);
1971 if (name == "lyxgreyedout") {
1972 eat_whitespace(p, os, parent_context, false);
1973 parent_context.check_layout(os);
1974 begin_inset(os, "Note Greyedout\n");
1975 os << "status open\n";
1976 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1979 if (!preamble.notefontcolor().empty())
1980 preamble.registerAutomaticallyLoadedPackage("color");
1984 if (name == "btSect") {
1985 eat_whitespace(p, os, parent_context, false);
1986 parent_context.check_layout(os);
1987 begin_command_inset(os, "bibtex", "bibtex");
1988 string bibstyle = "plain";
1990 bibstyle = p.getArg('[', ']');
1991 p.skip_spaces(true);
1993 string const bibfile = p.getArg('{', '}');
1994 eat_whitespace(p, os, parent_context, false);
1995 Token t = p.get_token();
1996 if (t.asInput() == "\\btPrintCited") {
1997 p.skip_spaces(true);
1998 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2000 if (t.asInput() == "\\btPrintNotCited") {
2001 p.skip_spaces(true);
2002 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2004 if (t.asInput() == "\\btPrintAll") {
2005 p.skip_spaces(true);
2006 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2008 os << "bibfiles " << '"' << bibfile << "\"\n"
2009 << "options " << '"' << bibstyle << "\"\n";
2010 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2016 if (name == "btUnit") {
2017 string const nt = p.next_next_token().cs();
2018 // Do not attempt to overwrite a former diverging multibib.
2019 // Those are output as ERT instead.
2020 if ((nt == "part" || nt == "chapter"
2021 || nt == "section" || nt == "subsection")
2022 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2023 parse_text(p, os, FLAG_END, outer, parent_context);
2024 preamble.multibib(nt);
2026 parse_unknown_environment(p, name, os, FLAG_END, outer,
2031 // This is only attempted at turn environments that consist only
2032 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2033 // Thus we will fall through in other cases.
2034 if (name == "turn") {
2035 // We check if the next thing is a tabular[*|x]
2037 p.getArg('{', '}');// eat turn argument
2038 bool found_end = false;
2039 bool only_table = false;
2040 bool end_table = false;
2043 string envname = p.getArg('{', '}');
2044 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2045 // Now we check if the table is the only content
2046 // of the turn environment
2047 string const tenv = envname;
2048 while (!found_end && !end_table && p.good()) {
2049 envname = p.next_token().cat() == catBegin
2050 ? p.getArg('{', '}') : string();
2051 Token const & t = p.get_token();
2053 end_table = t.asInput() != "\\end"
2055 found_end = t.asInput() == "\\end"
2056 && envname == "turn";
2060 envname = p.getArg('{', '}');
2061 only_table = p.next_next_token().asInput() == "\\end"
2062 && envname == "turn";
2066 string const angle = p.getArg('{', '}');
2068 int const save_tablerotation = parent_context.tablerotation;
2069 parent_context.tablerotation = convert<int>(angle);
2070 parse_text(p, os, FLAG_END, outer, parent_context);
2071 parent_context.tablerotation = save_tablerotation;
2081 // This is only attempted at landscape environments that consist only
2082 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2083 // Other landscape environment is handled via the landscape module, thus
2084 // we will fall through in that case.
2085 if (name == "landscape") {
2086 // We check if the next thing is a longtable
2088 bool found_end = false;
2089 bool only_longtable = false;
2090 bool end_longtable = false;
2093 string envname = p.getArg('{', '}');
2094 if (envname == "longtable" || envname == "xltabular") {
2095 // Now we check if the longtable is the only content
2096 // of the landscape environment
2097 string const ltenv = envname;
2098 while (!found_end && !end_longtable && p.good()) {
2099 envname = p.next_token().cat() == catBegin
2100 ? p.getArg('{', '}') : string();
2101 Token const & t = p.get_token();
2103 end_longtable = t.asInput() != "\\end"
2104 && envname == ltenv;
2105 found_end = t.asInput() == "\\end"
2106 && envname == "landscape";
2108 if (end_longtable) {
2110 envname = p.getArg('{', '}');
2111 only_longtable = p.next_next_token().asInput() == "\\end"
2112 && envname == "landscape";
2114 if (only_longtable) {
2117 int const save_tablerotation = parent_context.tablerotation;
2118 parent_context.tablerotation = 90;
2119 parse_text(p, os, FLAG_END, outer, parent_context);
2120 parent_context.tablerotation = save_tablerotation;
2130 if (name == "framed" || name == "shaded") {
2131 eat_whitespace(p, os, parent_context, false);
2132 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2134 preamble.registerAutomaticallyLoadedPackage("framed");
2138 if (name == "listing") {
2139 minted_float = "float";
2140 eat_whitespace(p, os, parent_context, false);
2141 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2143 minted_float += "=" + opt;
2144 // If something precedes \begin{minted}, we output it at the end
2145 // as a caption, in order to keep it inside the listings inset.
2146 eat_whitespace(p, os, parent_context, true);
2148 Token const & t = p.get_token();
2149 p.skip_spaces(true);
2150 string const envname = p.next_token().cat() == catBegin
2151 ? p.getArg('{', '}') : string();
2152 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2154 minted_float_has_caption = false;
2155 string content = parse_text_snippet(p, FLAG_END, outer,
2157 size_t i = content.find("\\begin_inset listings");
2158 bool minted_env = i != string::npos;
2161 caption = content.substr(0, i);
2162 content.erase(0, i);
2164 parent_context.check_layout(os);
2165 if (minted_env && minted_float_has_caption) {
2166 eat_whitespace(p, os, parent_context, true);
2167 os << content << "\n";
2168 if (!caption.empty())
2169 os << caption << "\n";
2170 os << "\n\\end_layout\n"; // close inner layout
2171 end_inset(os); // close caption inset
2172 os << "\n\\end_layout\n"; // close outer layout
2173 } else if (!caption.empty()) {
2175 begin_inset(os, "listings\n");
2176 os << "lstparams " << '"' << minted_float << '"' << '\n';
2177 os << "inline false\n";
2178 os << "status collapsed\n";
2180 os << "\n\\begin_layout Plain Layout\n";
2181 begin_inset(os, "Caption Standard\n");
2182 Context newcontext(true, parent_context.textclass,
2183 0, 0, parent_context.font);
2184 newcontext.check_layout(os);
2185 os << caption << "\n";
2186 newcontext.check_end_layout(os);
2188 os << "\n\\end_layout\n";
2189 } else if (content.empty()) {
2190 begin_inset(os, "listings\n");
2191 os << "lstparams " << '"' << minted_float << '"' << '\n';
2192 os << "inline false\n";
2193 os << "status collapsed\n";
2195 os << content << "\n";
2197 end_inset(os); // close listings inset
2198 parent_context.check_end_layout(os);
2199 parent_context.new_paragraph(os);
2201 minted_float.clear();
2202 minted_float_has_caption = false;
2206 if (name == "lstlisting" || name == "minted") {
2207 bool use_minted = name == "minted";
2208 // with listings, we do not eat newlines here since
2209 // \begin{lstlistings}
2212 // // \begin{lstlistings}%
2215 // reads [foo] as content, whereas
2216 // // \begin{lstlistings}%
2219 // \begin{lstlistings}[foo,
2221 // reads [foo...] as argument.
2222 eat_whitespace(p, os, parent_context, false, use_minted);
2223 if (use_minted && minted_float.empty()) {
2224 // look ahead for a bottom caption
2226 bool found_end_minted = false;
2227 while (!found_end_minted && p.good()) {
2228 Token const & t = p.get_token();
2230 string const envname =
2231 p.next_token().cat() == catBegin
2232 ? p.getArg('{', '}') : string();
2233 found_end_minted = t.asInput() == "\\end"
2234 && envname == "minted";
2236 eat_whitespace(p, os, parent_context, true);
2237 Token const & t = p.get_token();
2238 p.skip_spaces(true);
2239 if (t.asInput() == "\\lyxmintcaption") {
2240 string const pos = p.getArg('[', ']');
2242 string const caption =
2243 parse_text_snippet(p, FLAG_ITEM,
2244 false, parent_context);
2245 minted_nonfloat_caption = "[b]" + caption;
2246 eat_whitespace(p, os, parent_context, true);
2251 parse_listings(p, os, parent_context, false, use_minted);
2256 if (!parent_context.new_layout_allowed) {
2257 parse_unknown_environment(p, name, os, FLAG_END, outer,
2262 // Alignment and spacing settings
2263 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2264 // therefore are totally broken!
2265 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2266 // they are commands not environments. They are furthermore switches that
2267 // can be ended by another switches, but also by commands like \footnote or
2268 // \parbox. So the only safe way is to leave them untouched.
2269 // However, we support the pseudo-environments
2270 // \begin{centering} ... \end{centering}
2271 // \begin{raggedright} ... \end{raggedright}
2272 // \begin{raggedleft} ... \end{raggedleft}
2273 // since they are used by LyX in floats (for spacing reasons)
2274 if (name == "center" || name == "centering"
2275 || name == "flushleft" || name == "raggedright"
2276 || name == "flushright" || name == "raggedleft"
2277 || name == "singlespace" || name == "onehalfspace"
2278 || name == "doublespace" || name == "spacing") {
2279 eat_whitespace(p, os, parent_context, false);
2280 // We must begin a new paragraph if not already done
2281 if (! parent_context.atParagraphStart()) {
2282 parent_context.check_end_layout(os);
2283 parent_context.new_paragraph(os);
2285 if (name == "flushleft" || name == "raggedright")
2286 parent_context.add_extra_stuff("\\align left\n");
2287 else if (name == "flushright" || name == "raggedleft")
2288 parent_context.add_extra_stuff("\\align right\n");
2289 else if (name == "center" || name == "centering")
2290 parent_context.add_extra_stuff("\\align center\n");
2291 else if (name == "singlespace")
2292 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2293 else if (name == "onehalfspace") {
2294 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2295 preamble.registerAutomaticallyLoadedPackage("setspace");
2296 } else if (name == "doublespace") {
2297 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2298 preamble.registerAutomaticallyLoadedPackage("setspace");
2299 } else if (name == "spacing") {
2300 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2301 preamble.registerAutomaticallyLoadedPackage("setspace");
2303 parse_text(p, os, FLAG_END, outer, parent_context);
2304 // Just in case the environment is empty
2305 parent_context.extra_stuff.erase();
2306 // We must begin a new paragraph to reset the alignment
2307 parent_context.new_paragraph(os);
2312 // The single '=' is meant here.
2313 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2314 eat_whitespace(p, os, parent_context, false);
2315 Context context(true, parent_context.textclass, newlayout,
2316 parent_context.layout, parent_context.font);
2317 if (parent_context.deeper_paragraph) {
2318 // We are beginning a nested environment after a
2319 // deeper paragraph inside the outer list environment.
2320 // Therefore we don't need to output a "begin deeper".
2321 context.need_end_deeper = true;
2323 parent_context.check_end_layout(os);
2324 if (last_env == name) {
2325 // we need to output a separator since LyX would export
2326 // the two environments as one otherwise (bug 5716)
2327 TeX2LyXDocClass const & textclass(parent_context.textclass);
2328 Context newcontext(true, textclass,
2329 &(textclass.defaultLayout()));
2330 newcontext.check_layout(os);
2331 begin_inset(os, "Separator plain\n");
2333 newcontext.check_end_layout(os);
2335 switch (context.layout->latextype) {
2336 case LATEX_LIST_ENVIRONMENT:
2337 context.in_list_preamble =
2338 !context.layout->listpreamble().empty()
2339 && p.hasListPreamble(context.layout->itemcommand());
2340 context.add_par_extra_stuff("\\labelwidthstring "
2341 + p.verbatim_item() + '\n');
2344 case LATEX_BIB_ENVIRONMENT:
2345 p.verbatim_item(); // swallow next arg
2351 context.check_deeper(os);
2352 if (newlayout->keepempty) {
2353 // We need to start a new paragraph
2354 // even if it is empty.
2355 context.new_paragraph(os);
2356 context.check_layout(os);
2358 // handle known optional and required arguments
2359 if (context.layout->latextype == LATEX_ENVIRONMENT)
2360 output_arguments(os, p, outer, false, string(), context,
2361 context.layout->latexargs());
2362 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2363 context.in_list_preamble =
2364 !context.layout->listpreamble().empty()
2365 && p.hasListPreamble(context.layout->itemcommand());
2367 output_arguments(oss, p, outer, false, string(), context,
2368 context.layout->latexargs());
2369 context.list_extra_stuff = oss.str();
2371 if (context.in_list_preamble) {
2372 // Collect the stuff between \begin and first \item
2373 context.list_preamble =
2374 parse_text_snippet(p, FLAG_END, outer, context);
2375 context.in_list_preamble = false;
2377 parse_text(p, os, FLAG_END, outer, context);
2378 if (context.layout->latextype == LATEX_ENVIRONMENT)
2379 output_arguments(os, p, outer, false, "post", context,
2380 context.layout->postcommandargs());
2381 context.check_end_layout(os);
2382 if (parent_context.deeper_paragraph) {
2383 // We must suppress the "end deeper" because we
2384 // suppressed the "begin deeper" above.
2385 context.need_end_deeper = false;
2387 context.check_end_deeper(os);
2388 parent_context.new_paragraph(os);
2390 if (!preamble.titleLayoutFound())
2391 preamble.titleLayoutFound(newlayout->intitle);
2392 set<string> const & req = newlayout->required();
2393 set<string>::const_iterator it = req.begin();
2394 set<string>::const_iterator en = req.end();
2395 for (; it != en; ++it)
2396 preamble.registerAutomaticallyLoadedPackage(*it);
2400 // The single '=' is meant here.
2401 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2402 eat_whitespace(p, os, parent_context, false);
2403 parent_context.check_layout(os);
2404 begin_inset(os, "Flex ");
2405 docstring flex_name = newinsetlayout->name();
2406 // FIXME: what do we do if the prefix is not Flex: ?
2407 if (prefixIs(flex_name, from_ascii("Flex:")))
2408 flex_name.erase(0, 5);
2409 os << to_utf8(flex_name) << '\n'
2410 << "status collapsed\n";
2411 if (newinsetlayout->isPassThru()) {
2412 string const arg = p.verbatimEnvironment(name);
2413 Context context(true, parent_context.textclass,
2414 &parent_context.textclass.plainLayout(),
2415 parent_context.layout);
2416 output_ert(os, arg, parent_context);
2418 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2423 if (name == "appendix") {
2424 // This is no good latex style, but it works and is used in some documents...
2425 eat_whitespace(p, os, parent_context, false);
2426 parent_context.check_end_layout(os);
2427 Context context(true, parent_context.textclass, parent_context.layout,
2428 parent_context.layout, parent_context.font);
2429 context.check_layout(os);
2430 os << "\\start_of_appendix\n";
2431 parse_text(p, os, FLAG_END, outer, context);
2432 context.check_end_layout(os);
2437 if (known_environments.find(name) != known_environments.end()) {
2438 vector<ArgumentType> arguments = known_environments[name];
2439 // The last "argument" denotes whether we may translate the
2440 // environment contents to LyX
2441 // The default required if no argument is given makes us
2442 // compatible with the reLyXre environment.
2443 ArgumentType contents = arguments.empty() ?
2446 if (!arguments.empty())
2447 arguments.pop_back();
2448 // See comment in parse_unknown_environment()
2449 bool const specialfont =
2450 (parent_context.font != parent_context.normalfont);
2451 bool const new_layout_allowed =
2452 parent_context.new_layout_allowed;
2454 parent_context.new_layout_allowed = false;
2455 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2456 outer, parent_context);
2457 if (contents == verbatim)
2458 output_ert_inset(os, p.ertEnvironment(name),
2461 parse_text_snippet(p, os, FLAG_END, outer,
2463 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2465 parent_context.new_layout_allowed = new_layout_allowed;
2469 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2474 active_environments.pop_back();
2478 /// parses a comment and outputs it to \p os.
2479 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2480 bool skipNewlines = false)
2482 LASSERT(t.cat() == catComment, return);
2483 if (!t.cs().empty()) {
2484 context.check_layout(os);
2485 output_comment(p, os, t.cs(), context);
2486 if (p.next_token().cat() == catNewline) {
2487 // A newline after a comment line starts a new
2489 if (context.new_layout_allowed) {
2490 if(!context.atParagraphStart())
2491 // Only start a new paragraph if not already
2492 // done (we might get called recursively)
2493 context.new_paragraph(os);
2495 output_ert_inset(os, "\n", context);
2496 eat_whitespace(p, os, context, true);
2498 } else if (!skipNewlines) {
2499 // "%\n" combination
2506 * Reads spaces and comments until the first non-space, non-comment token.
2507 * New paragraphs (double newlines or \\par) are handled like simple spaces
2508 * if \p eatParagraph is true.
2509 * If \p eatNewline is false, newlines won't be treated as whitespace.
2510 * Spaces are skipped, but comments are written to \p os.
2512 void eat_whitespace(Parser & p, ostream & os, Context & context,
2513 bool eatParagraph, bool eatNewline)
2516 Token const & t = p.get_token();
2517 if (t.cat() == catComment)
2518 parse_comment(p, os, t, context, !eatNewline);
2519 else if ((!eatParagraph && p.isParagraph()) ||
2520 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2529 * Set a font attribute, parse text and reset the font attribute.
2530 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2531 * \param currentvalue Current value of the attribute. Is set to the new
2532 * value during parsing.
2533 * \param newvalue New value of the attribute
2535 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2536 Context & context, string const & attribute,
2537 string & currentvalue, string const & newvalue)
2539 context.check_layout(os);
2540 string const oldvalue = currentvalue;
2541 currentvalue = newvalue;
2542 os << '\n' << attribute << ' ' << newvalue << "\n";
2543 parse_text_snippet(p, os, flags, outer, context);
2544 context.check_layout(os);
2545 os << '\n' << attribute << ' ' << oldvalue << "\n";
2546 currentvalue = oldvalue;
2550 /// get the arguments of a natbib or jurabib citation command
2551 void get_cite_arguments(Parser & p, bool natbibOrder,
2552 string & before, string & after, bool const qualified = false)
2554 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2556 // text before the citation
2558 // text after the citation
2559 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2561 if (!after.empty()) {
2562 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2563 if (natbibOrder && !before.empty())
2564 swap(before, after);
2569 void copy_file(FileName const & src, string const & dstname)
2573 string const absParent = getParentFilePath(false);
2575 if (FileName::isAbsolute(dstname))
2576 dst = FileName(dstname);
2578 dst = makeAbsPath(dstname, absParent);
2579 FileName const srcpath = src.onlyPath();
2580 FileName const dstpath = dst.onlyPath();
2581 if (equivalent(srcpath, dstpath))
2583 if (!dstpath.isDirectory()) {
2584 if (!dstpath.createPath()) {
2585 cerr << "Warning: Could not create directory for file `"
2586 << dst.absFileName() << "´." << endl;
2590 if (dst.isReadableFile()) {
2591 if (overwriteFiles())
2592 cerr << "Warning: Overwriting existing file `"
2593 << dst.absFileName() << "´." << endl;
2595 cerr << "Warning: Not overwriting existing file `"
2596 << dst.absFileName() << "´." << endl;
2600 if (!src.copyTo(dst))
2601 cerr << "Warning: Could not copy file `" << src.absFileName()
2602 << "´ to `" << dst.absFileName() << "´." << endl;
2606 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2607 bool parse_chunk(Parser & p, ostream & os, Context & context)
2609 // check whether a chunk is possible here.
2610 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2616 // read the parameters
2617 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2618 if (!params.first) {
2623 Parser::Arg const code = p.verbatimStuff("\n@");
2628 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2629 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2633 // The last newline read is important for paragraph handling
2637 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2638 // We must have a valid layout before outputting the Chunk inset.
2639 context.check_layout(os);
2640 Context chunkcontext(true, context.textclass);
2641 chunkcontext.layout = &context.textclass.plainLayout();
2642 begin_inset(os, "Flex Chunk");
2643 os << "\nstatus open\n";
2644 if (!params.second.empty()) {
2645 chunkcontext.check_layout(os);
2646 Context paramscontext(true, context.textclass);
2647 paramscontext.layout = &context.textclass.plainLayout();
2648 begin_inset(os, "Argument 1");
2649 os << "\nstatus open\n";
2650 output_ert(os, params.second, paramscontext);
2653 output_ert(os, code.second, chunkcontext);
2661 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2662 bool is_macro(Parser & p)
2664 Token first = p.curr_token();
2665 if (first.cat() != catEscape || !p.good())
2667 if (first.cs() == "def")
2669 if (first.cs() != "global" && first.cs() != "long")
2671 Token second = p.get_token();
2673 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2674 second.cat() == catNewline || second.cat() == catComment)) {
2675 second = p.get_token();
2678 bool secondvalid = second.cat() == catEscape;
2680 bool thirdvalid = false;
2681 if (p.good() && first.cs() == "global" && secondvalid &&
2682 second.cs() == "long") {
2683 third = p.get_token();
2685 while (p.good() && !p.isParagraph() &&
2686 (third.cat() == catSpace ||
2687 third.cat() == catNewline ||
2688 third.cat() == catComment)) {
2689 third = p.get_token();
2692 thirdvalid = third.cat() == catEscape;
2694 for (int i = 0; i < pos; ++i)
2699 return (first.cs() == "global" || first.cs() == "long") &&
2700 second.cs() == "def";
2701 return first.cs() == "global" && second.cs() == "long" &&
2702 third.cs() == "def";
2706 /// Parse a macro definition (assumes that is_macro() returned true)
2707 void parse_macro(Parser & p, ostream & os, Context & context)
2709 context.check_layout(os);
2710 Token first = p.curr_token();
2713 string command = first.asInput();
2714 if (first.cs() != "def") {
2716 eat_whitespace(p, os, context, false);
2717 second = p.curr_token();
2718 command += second.asInput();
2719 if (second.cs() != "def") {
2721 eat_whitespace(p, os, context, false);
2722 third = p.curr_token();
2723 command += third.asInput();
2726 eat_whitespace(p, os, context, false);
2727 string const name = p.get_token().cs();
2728 eat_whitespace(p, os, context, false);
2734 while (p.next_token().cat() != catBegin) {
2735 if (p.next_token().cat() == catParameter) {
2740 // followed by number?
2741 if (p.next_token().cat() == catOther) {
2742 string s = p.get_token().asInput();
2744 // number = current arity + 1?
2745 if (s.size() == 1 && s[0] == arity + '0' + 1)
2750 paramtext += p.get_token().cs();
2752 paramtext += p.get_token().cs();
2757 // only output simple (i.e. compatible) macro as FormulaMacros
2758 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2760 context.check_layout(os);
2761 begin_inset(os, "FormulaMacro");
2762 os << "\n\\def" << ert;
2765 output_ert_inset(os, command + ert, context);
2769 void registerExternalTemplatePackages(string const & name)
2771 external::TemplateManager const & etm = external::TemplateManager::get();
2772 external::Template const * const et = etm.getTemplateByName(name);
2775 external::Template::Formats::const_iterator cit = et->formats.end();
2777 cit = et->formats.find("PDFLaTeX");
2778 if (cit == et->formats.end())
2779 // If the template has not specified a PDFLaTeX output,
2780 // we try the LaTeX format.
2781 cit = et->formats.find("LaTeX");
2782 if (cit == et->formats.end())
2784 vector<string>::const_iterator qit = cit->second.requirements.begin();
2785 vector<string>::const_iterator qend = cit->second.requirements.end();
2786 for (; qit != qend; ++qit)
2787 preamble.registerAutomaticallyLoadedPackage(*qit);
2790 } // anonymous namespace
2794 * Find a file with basename \p name in path \p path and an extension
2797 string find_file(string const & name, string const & path,
2798 char const * const * extensions)
2800 for (char const * const * what = extensions; *what; ++what) {
2801 string const trial = addExtension(name, *what);
2802 if (makeAbsPath(trial, path).exists())
2809 /// Convert filenames with TeX macros and/or quotes to something LyX
2811 string const normalize_filename(string const & name)
2816 Token const & t = p.get_token();
2817 if (t.cat() != catEscape)
2819 else if (t.cs() == "lyxdot") {
2820 // This is used by LyX for simple dots in relative
2824 } else if (t.cs() == "space") {
2827 } else if (t.cs() == "string") {
2828 // Convert \string" to " and \string~ to ~
2829 Token const & n = p.next_token();
2830 if (n.asInput() != "\"" && n.asInput() != "~")
2835 // Strip quotes. This is a bit complicated (see latex_path()).
2836 string full = os.str();
2837 if (!full.empty() && full[0] == '"') {
2838 string base = removeExtension(full);
2839 string ext = getExtension(full);
2840 if (!base.empty() && base[base.length()-1] == '"')
2843 return addExtension(trim(base, "\""), ext);
2844 if (full[full.length()-1] == '"')
2847 return trim(full, "\"");
2853 /// Convert \p name from TeX convention (relative to master file) to LyX
2854 /// convention (relative to .lyx file) if it is relative
2855 void fix_child_filename(string & name)
2857 string const absMasterTeX = getMasterFilePath(true);
2858 bool const isabs = FileName::isAbsolute(name);
2859 // convert from "relative to .tex master" to absolute original path
2861 name = makeAbsPath(name, absMasterTeX).absFileName();
2862 bool copyfile = copyFiles();
2863 string const absParentLyX = getParentFilePath(false);
2866 // convert from absolute original path to "relative to master file"
2867 string const rel = to_utf8(makeRelPath(from_utf8(name),
2868 from_utf8(absMasterTeX)));
2869 // re-interpret "relative to .tex file" as "relative to .lyx file"
2870 // (is different if the master .lyx file resides in a
2871 // different path than the master .tex file)
2872 string const absMasterLyX = getMasterFilePath(false);
2873 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2874 // Do not copy if the new path is impossible to create. Example:
2875 // absMasterTeX = "/foo/bar/"
2876 // absMasterLyX = "/bar/"
2877 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2878 if (contains(name, "/../"))
2885 // convert from absolute original path to
2886 // "relative to .lyx file"
2887 name = to_utf8(makeRelPath(from_utf8(abs),
2888 from_utf8(absParentLyX)));
2892 // convert from absolute original path to "relative to .lyx file"
2893 name = to_utf8(makeRelPath(from_utf8(name),
2894 from_utf8(absParentLyX)));
2899 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2900 Context & context, string const & rdelim)
2902 Layout const * newlayout = 0;
2903 InsetLayout const * newinsetlayout = 0;
2904 char const * const * where = 0;
2905 // Store the latest bibliographystyle, addcontentslineContent and
2906 // nocite{*} option (needed for bibtex inset)
2908 string contentslineContent;
2909 // Some classes provide a \bibliographystyle, so do not output
2910 // any if none is explicitly set.
2911 string bibliographystyle;
2912 bool const use_natbib = isProvided("natbib");
2913 bool const use_jurabib = isProvided("jurabib");
2914 bool const use_biblatex = isProvided("biblatex")
2915 && preamble.citeEngine() != "biblatex-natbib";
2916 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2917 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2918 need_commentbib = use_biblatex || use_biblatex_natbib;
2921 // it is impossible to determine the correct encoding for non-CJK Japanese.
2922 // Therefore write a note at the beginning of the document
2923 if (is_nonCJKJapanese) {
2924 context.check_layout(os);
2925 begin_inset(os, "Note Note\n");
2926 os << "status open\n\\begin_layout Plain Layout\n"
2927 << "\\series bold\n"
2928 << "Important information:\n"
2929 << "\\end_layout\n\n"
2930 << "\\begin_layout Plain Layout\n"
2931 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2932 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2933 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2934 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2935 << " and specify the encoding using the -e command-line switch.\n"
2936 << " In addition, you might want to double check that the desired output encoding\n"
2937 << " is correctly selected in Document > Settings > Language.\n"
2938 << "\\end_layout\n";
2940 is_nonCJKJapanese = false;
2943 bool have_cycled = false;
2945 // Leave here only after at least one cycle
2946 if (have_cycled && flags & FLAG_LEAVE) {
2947 flags &= ~FLAG_LEAVE;
2951 Token const & t = p.get_token();
2953 debugToken(cerr, t, flags);
2956 if (context.in_list_preamble
2957 && p.next_token().cs() == context.layout->itemcommand()) {
2958 // We are parsing a list preamble. End before first \item.
2959 flags |= FLAG_LEAVE;
2960 context.in_list_preamble = false;
2963 if (flags & FLAG_ITEM) {
2964 if (t.cat() == catSpace)
2967 flags &= ~FLAG_ITEM;
2968 if (t.cat() == catBegin) {
2969 // skip the brace and collect everything to the next matching
2971 flags |= FLAG_BRACE_LAST;
2975 // handle only this single token, leave the loop if done
2976 flags |= FLAG_LEAVE;
2979 if (t.cat() != catEscape && t.character() == ']' &&
2980 (flags & FLAG_BRACK_LAST))
2982 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2984 string tok = t.asInput();
2985 // we only support delimiters with max 2 chars for now.
2986 if (rdelim.size() > 1)
2987 tok += p.next_token().asInput();
2988 if (t.cat() != catEscape && !rdelim.empty()
2989 && tok == rdelim && (flags & FLAG_RDELIM)) {
2990 if (rdelim.size() > 1)
2991 p.get_token(); // eat rdelim
2995 // If there is anything between \end{env} and \begin{env} we
2996 // don't need to output a separator.
2997 if (t.cat() != catSpace && t.cat() != catNewline &&
2998 t.asInput() != "\\begin")
3005 bool const starred = p.next_token().asInput() == "*";
3006 string const starredname(starred ? (t.cs() + '*') : t.cs());
3007 if (t.cat() == catMath) {
3008 // we are inside some text mode thingy, so opening new math is allowed
3009 context.check_layout(os);
3010 begin_inset(os, "Formula ");
3011 Token const & n = p.get_token();
3012 bool const display(n.cat() == catMath && outer);
3014 // TeX's $$...$$ syntax for displayed math
3016 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3018 p.get_token(); // skip the second '$' token
3020 // simple $...$ stuff
3023 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3028 // Prevent the conversion of a line break to a
3029 // space (bug 7668). This does not change the
3030 // output, but looks ugly in LyX.
3031 eat_whitespace(p, os, context, false);
3036 if (t.cat() == catSuper || t.cat() == catSub) {
3037 cerr << "catcode " << t << " illegal in text mode\n";
3041 // Basic support for quotes. We try to disambiguate
3042 // quotes from the context (e.g., a left english quote is
3043 // the same as a right german quote...).
3044 // Try to make a smart guess about the side
3045 Token const prev = p.prev_token();
3046 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3047 && prev.character() != '\n' && prev.character() != '~');
3048 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3049 context.check_layout(os);
3050 begin_inset(os, "Quotes ");
3051 os << guessQuoteStyle("eld", opening);
3057 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3058 context.check_layout(os);
3059 begin_inset(os, "Quotes ");
3060 os << guessQuoteStyle("erd", opening);
3067 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3068 context.check_layout(os);
3069 begin_inset(os, "Quotes ");
3070 os << guessQuoteStyle("ald", opening);
3077 if (t.asInput() == "<"
3078 && p.next_token().asInput() == "<") {
3079 bool has_chunk = false;
3083 has_chunk = parse_chunk(p, os, context);
3089 context.check_layout(os);
3090 begin_inset(os, "Quotes ");
3091 os << guessQuoteStyle("ard", opening);
3099 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3100 check_space(p, os, context);
3104 // babel shorthands (also used by polyglossia)
3105 // Since these can have different meanings for different languages
3106 // we import them as ERT (but they must be put in ERT to get output
3108 if (t.asInput() == "\"") {
3110 // These are known pairs. We put them together in
3111 // one ERT inset. In other cases (such as "a), only
3112 // the quotation mark is ERTed.
3113 if (p.next_token().asInput() == "\""
3114 || p.next_token().asInput() == "|"
3115 || p.next_token().asInput() == "-"
3116 || p.next_token().asInput() == "~"
3117 || p.next_token().asInput() == "="
3118 || p.next_token().asInput() == "/"
3119 || p.next_token().asInput() == "~"
3120 || p.next_token().asInput() == "'"
3121 || p.next_token().asInput() == "`"
3122 || p.next_token().asInput() == "<"
3123 || p.next_token().asInput() == ">") {
3124 s += p.next_token().asInput();
3127 output_ert_inset(os, s, context);
3131 if (t.character() == '[' && noweb_mode &&
3132 p.next_token().character() == '[') {
3133 // These can contain underscores
3135 string const s = p.getFullOpt() + ']';
3136 if (p.next_token().character() == ']')
3139 cerr << "Warning: Inserting missing ']' in '"
3140 << s << "'." << endl;
3141 output_ert_inset(os, s, context);
3145 if (t.cat() == catLetter) {
3146 context.check_layout(os);
3151 if (t.cat() == catOther ||
3152 t.cat() == catAlign ||
3153 t.cat() == catParameter) {
3154 context.check_layout(os);
3155 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3156 context.merging_hyphens_allowed &&
3157 context.font.family != "ttfamily" &&
3158 !context.layout->pass_thru) {
3159 if (p.next_next_token().asInput() == "-") {
3161 os << to_utf8(docstring(1, 0x2014));
3165 os << to_utf8(docstring(1, 0x2013));
3168 // This translates "&" to "\\&" which may be wrong...
3173 if (p.isParagraph()) {
3174 // In minted floating listings we will collect
3175 // everything into the caption, where multiple
3176 // paragraphs are forbidden.
3177 if (minted_float.empty()) {
3178 if (context.new_layout_allowed)
3179 context.new_paragraph(os);
3181 output_ert_inset(os, "\\par ", context);
3184 eat_whitespace(p, os, context, true);
3188 if (t.cat() == catActive) {
3189 context.check_layout(os);
3190 if (t.character() == '~') {
3191 if (context.layout->free_spacing)
3194 begin_inset(os, "space ~\n");
3202 if (t.cat() == catBegin) {
3203 Token const next = p.next_token();
3204 Token const end = p.next_next_token();
3205 if (next.cat() == catEnd) {
3207 Token const prev = p.prev_token();
3209 if (p.next_token().character() == '`')
3210 ; // ignore it in {}``
3212 output_ert_inset(os, "{}", context);
3213 } else if (next.cat() == catEscape &&
3214 is_known(next.cs(), known_quotes) &&
3215 end.cat() == catEnd) {
3216 // Something like {\textquoteright} (e.g.
3217 // from writer2latex). We may skip the
3218 // braces here for better readability.
3219 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3221 } else if (p.next_token().asInput() == "\\ascii") {
3222 // handle the \ascii characters
3223 // (the case without braces is handled later)
3224 // the code is "{\ascii\xxx}"
3225 p.get_token(); // eat \ascii
3226 string name2 = p.get_token().asInput();
3227 p.get_token(); // eat the final '}'
3228 string const name = "{\\ascii" + name2 + "}";
3232 // get the character from unicodesymbols
3233 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3234 Encodings::TEXT_CMD, termination, rem, &req);
3236 context.check_layout(os);
3239 output_ert_inset(os,
3240 to_utf8(rem), context);
3241 for (set<string>::const_iterator it = req.begin();
3242 it != req.end(); ++it)
3243 preamble.registerAutomaticallyLoadedPackage(*it);
3245 // we did not find a non-ert version
3246 output_ert_inset(os, name, context);
3248 context.check_layout(os);
3249 // special handling of font attribute changes
3250 Token const prev = p.prev_token();
3251 TeXFont const oldFont = context.font;
3252 if (next.character() == '[' ||
3253 next.character() == ']' ||
3254 next.character() == '*') {
3256 if (p.next_token().cat() == catEnd) {
3261 output_ert_inset(os, "{", context);
3262 parse_text_snippet(p, os,
3265 output_ert_inset(os, "}", context);
3267 } else if (! context.new_layout_allowed) {
3268 output_ert_inset(os, "{", context);
3269 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3271 output_ert_inset(os, "}", context);
3272 } else if (is_known(next.cs(), known_sizes)) {
3273 // next will change the size, so we must
3275 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3277 if (!context.atParagraphStart())
3279 << context.font.size << "\n";
3280 } else if (is_known(next.cs(), known_font_families)) {
3281 // next will change the font family, so we
3282 // must reset it here
3283 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3285 if (!context.atParagraphStart())
3287 << context.font.family << "\n";
3288 } else if (is_known(next.cs(), known_font_series)) {
3289 // next will change the font series, so we
3290 // must reset it here
3291 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3293 if (!context.atParagraphStart())
3295 << context.font.series << "\n";
3296 } else if (is_known(next.cs(), known_font_shapes)) {
3297 // next will change the font shape, so we
3298 // must reset it here
3299 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3301 if (!context.atParagraphStart())
3303 << context.font.shape << "\n";
3304 } else if (is_known(next.cs(), known_old_font_families) ||
3305 is_known(next.cs(), known_old_font_series) ||
3306 is_known(next.cs(), known_old_font_shapes)) {
3307 // next will change the font family, series
3308 // and shape, so we must reset it here
3309 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3311 if (!context.atParagraphStart())
3313 << context.font.family
3315 << context.font.series
3317 << context.font.shape << "\n";
3319 output_ert_inset(os, "{", context);
3320 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3322 output_ert_inset(os, "}", context);
3328 if (t.cat() == catEnd) {
3329 if (flags & FLAG_BRACE_LAST) {
3332 cerr << "stray '}' in text\n";
3333 output_ert_inset(os, "}", context);
3337 if (t.cat() == catComment) {
3338 parse_comment(p, os, t, context);
3343 // control sequences
3346 if (t.cs() == "(" || t.cs() == "[") {
3347 bool const simple = t.cs() == "(";
3348 context.check_layout(os);
3349 begin_inset(os, "Formula");
3350 os << " \\" << t.cs();
3351 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3352 os << '\\' << (simple ? ')' : ']');
3355 // Prevent the conversion of a line break to a
3356 // space (bug 7668). This does not change the
3357 // output, but looks ugly in LyX.
3358 eat_whitespace(p, os, context, false);
3363 if (t.cs() == "begin") {
3364 parse_environment(p, os, outer, last_env,
3369 if (t.cs() == "end") {
3370 if (flags & FLAG_END) {
3371 // eat environment name
3372 string const name = p.getArg('{', '}');
3373 if (name != active_environment())
3374 cerr << "\\end{" + name + "} does not match \\begin{"
3375 + active_environment() + "}\n";
3378 p.error("found 'end' unexpectedly");
3382 // "item" by default, but could be something else
3383 if (t.cs() == context.layout->itemcommand()) {
3385 if (context.layout->labeltype == LABEL_MANUAL) {
3386 // FIXME: This swallows comments, but we cannot use
3387 // eat_whitespace() since we must not output
3388 // anything before the item.
3389 p.skip_spaces(true);
3390 s = p.verbatimOption();
3392 p.skip_spaces(false);
3394 context.check_layout(os);
3395 if (context.has_item) {
3396 // An item in an unknown list-like environment
3397 // FIXME: Do this in check_layout()!
3398 context.has_item = false;
3399 string item = "\\" + context.layout->itemcommand();
3402 output_ert_inset(os, item, context);
3404 if (context.layout->labeltype != LABEL_MANUAL)
3405 output_arguments(os, p, outer, false, "item", context,
3406 context.layout->itemargs());
3407 if (!context.list_preamble.empty()) {
3408 // We have a list preamble. Output it here.
3409 begin_inset(os, "Argument listpreamble:1");
3410 os << "\nstatus collapsed\n\n"
3411 << "\\begin_layout Plain Layout\n\n"
3412 << rtrim(context.list_preamble)
3413 << "\n\\end_layout";
3415 context.list_preamble.clear();
3417 if (!context.list_extra_stuff.empty()) {
3418 os << context.list_extra_stuff;
3419 context.list_extra_stuff.clear();
3421 else if (!s.empty()) {
3422 // LyX adds braces around the argument,
3423 // so we need to remove them here.
3424 if (s.size() > 2 && s[0] == '{' &&
3425 s[s.size()-1] == '}')
3426 s = s.substr(1, s.size()-2);
3427 // If the argument contains a space we
3428 // must put it into ERT: Otherwise LyX
3429 // would misinterpret the space as
3430 // item delimiter (bug 7663)
3431 if (contains(s, ' ')) {
3432 output_ert_inset(os, s, context);
3435 os << parse_text_snippet(p2,
3436 FLAG_BRACK_LAST, outer, context);
3438 // The space is needed to separate the
3439 // item from the rest of the sentence.
3441 eat_whitespace(p, os, context, false);
3446 if (t.cs() == "bibitem") {
3448 context.check_layout(os);
3449 eat_whitespace(p, os, context, false);
3450 string label = p.verbatimOption();
3451 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3452 bool const literal = !lbl.first;
3453 label = literal ? subst(label, "\n", " ") : lbl.second;
3454 string lit = literal ? "\"true\"" : "\"false\"";
3455 string key = convert_literate_command_inset_arg(p.verbatim_item());
3456 begin_command_inset(os, "bibitem", "bibitem");
3457 os << "label \"" << label << "\"\n"
3458 << "key \"" << key << "\"\n"
3459 << "literal " << lit << "\n";
3465 // catch the case of \def\inputGnumericTable
3467 if (t.cs() == "def") {
3468 Token second = p.next_token();
3469 if (second.cs() == "inputGnumericTable") {
3473 Token third = p.get_token();
3475 if (third.cs() == "input") {
3479 string name = normalize_filename(p.verbatim_item());
3480 string const path = getMasterFilePath(true);
3481 // We want to preserve relative / absolute filenames,
3482 // therefore path is only used for testing
3483 // The file extension is in every case ".tex".
3484 // So we need to remove this extension and check for
3485 // the original one.
3486 name = removeExtension(name);
3487 if (!makeAbsPath(name, path).exists()) {
3488 char const * const Gnumeric_formats[] = {"gnumeric",
3490 string const Gnumeric_name =
3491 find_file(name, path, Gnumeric_formats);
3492 if (!Gnumeric_name.empty())
3493 name = Gnumeric_name;
3495 FileName const absname = makeAbsPath(name, path);
3496 if (absname.exists()) {
3497 fix_child_filename(name);
3498 copy_file(absname, name);
3500 cerr << "Warning: Could not find file '"
3501 << name << "'." << endl;
3502 context.check_layout(os);
3503 begin_inset(os, "External\n\ttemplate ");
3504 os << "GnumericSpreadsheet\n\tfilename "
3507 context.check_layout(os);
3509 // register the packages that are automatically loaded
3510 // by the Gnumeric template
3511 registerExternalTemplatePackages("GnumericSpreadsheet");
3516 parse_macro(p, os, context);
3520 if (t.cs() == "noindent") {
3522 context.add_par_extra_stuff("\\noindent\n");
3526 if (t.cs() == "appendix") {
3527 context.add_par_extra_stuff("\\start_of_appendix\n");
3528 // We need to start a new paragraph. Otherwise the
3529 // appendix in 'bla\appendix\chapter{' would start
3531 context.new_paragraph(os);
3532 // We need to make sure that the paragraph is
3533 // generated even if it is empty. Otherwise the
3534 // appendix in '\par\appendix\par\chapter{' would
3536 context.check_layout(os);
3537 // FIXME: This is a hack to prevent paragraph
3538 // deletion if it is empty. Handle this better!
3539 output_comment(p, os,
3540 "dummy comment inserted by tex2lyx to "
3541 "ensure that this paragraph is not empty",
3543 // Both measures above may generate an additional
3544 // empty paragraph, but that does not hurt, because
3545 // whitespace does not matter here.
3546 eat_whitespace(p, os, context, true);
3550 // Must catch empty dates before findLayout is called below
3551 if (t.cs() == "date") {
3552 eat_whitespace(p, os, context, false);
3554 string const date = p.verbatim_item();
3557 preamble.suppressDate(true);
3560 preamble.suppressDate(false);
3561 if (context.new_layout_allowed &&
3562 (newlayout = findLayout(context.textclass,
3565 output_command_layout(os, p, outer,
3566 context, newlayout);
3567 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3568 if (!preamble.titleLayoutFound())
3569 preamble.titleLayoutFound(newlayout->intitle);
3570 set<string> const & req = newlayout->required();
3571 set<string>::const_iterator it = req.begin();
3572 set<string>::const_iterator en = req.end();
3573 for (; it != en; ++it)
3574 preamble.registerAutomaticallyLoadedPackage(*it);
3576 output_ert_inset(os,
3577 "\\date{" + p.verbatim_item() + '}',
3583 // Before we look for the layout name with star and alone below, we check the layouts including
3584 // the LateXParam, which might be one or several options or a star.
3585 // The single '=' is meant here.
3586 if (context.new_layout_allowed &&
3587 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3588 // store the latexparam here. This is eaten in output_command_layout
3589 context.latexparam = newlayout->latexparam();
3591 output_command_layout(os, p, outer, context, newlayout);
3592 context.latexparam.clear();
3594 if (!preamble.titleLayoutFound())
3595 preamble.titleLayoutFound(newlayout->intitle);
3596 set<string> const & req = newlayout->required();
3597 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3598 preamble.registerAutomaticallyLoadedPackage(*it);
3602 // Starred section headings
3603 // Must attempt to parse "Section*" before "Section".
3604 if ((p.next_token().asInput() == "*") &&
3605 context.new_layout_allowed &&
3606 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3609 output_command_layout(os, p, outer, context, newlayout);
3611 if (!preamble.titleLayoutFound())
3612 preamble.titleLayoutFound(newlayout->intitle);
3613 set<string> const & req = newlayout->required();
3614 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3615 preamble.registerAutomaticallyLoadedPackage(*it);
3619 // Section headings and the like
3620 if (context.new_layout_allowed &&
3621 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3623 output_command_layout(os, p, outer, context, newlayout);
3625 if (!preamble.titleLayoutFound())
3626 preamble.titleLayoutFound(newlayout->intitle);
3627 set<string> const & req = newlayout->required();
3628 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3629 preamble.registerAutomaticallyLoadedPackage(*it);
3633 if (t.cs() == "subfloat") {
3634 // the syntax is \subfloat[list entry][sub caption]{content}
3635 // if it is a table of figure depends on the surrounding float
3637 // do nothing if there is no outer float
3638 if (!float_type.empty()) {
3639 context.check_layout(os);
3641 begin_inset(os, "Float " + float_type + "\n");
3643 << "\nsideways false"
3644 << "\nstatus collapsed\n\n";
3647 bool has_caption = false;
3648 if (p.next_token().cat() != catEscape &&
3649 p.next_token().character() == '[') {
3650 p.get_token(); // eat '['
3651 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3654 // In case we have two optional args, the second is the caption.
3655 if (p.next_token().cat() != catEscape &&
3656 p.next_token().character() == '[') {
3657 p.get_token(); // eat '['
3658 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3661 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3662 // the caption comes always as the last
3664 // we must make sure that the caption gets a \begin_layout
3665 os << "\n\\begin_layout Plain Layout";
3667 begin_inset(os, "Caption Standard\n");
3668 Context newcontext(true, context.textclass,
3669 0, 0, context.font);
3670 newcontext.check_layout(os);
3671 os << caption << "\n";
3672 newcontext.check_end_layout(os);
3675 // close the layout we opened
3676 os << "\n\\end_layout";
3681 // if the float type is not supported or there is no surrounding float
3686 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3688 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3690 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3691 + "{" + p.verbatim_item() + '}', context);
3696 if (t.cs() == "xymatrix") {
3697 // we must open a new math because LyX's xy support is in math
3698 context.check_layout(os);
3699 begin_inset(os, "Formula ");
3701 os << "\\" << t.cs() << '{';
3702 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3705 preamble.registerAutomaticallyLoadedPackage("xy");
3709 if (t.cs() == "includegraphics") {
3710 bool const clip = p.next_token().asInput() == "*";
3713 string const arg = p.getArg('[', ']');
3714 map<string, string> opts;
3715 vector<string> keys;
3716 split_map(arg, opts, keys);
3718 opts["clip"] = string();
3719 string name = normalize_filename(p.verbatim_item());
3721 string const path = getMasterFilePath(true);
3722 // We want to preserve relative / absolute filenames,
3723 // therefore path is only used for testing
3724 if (!makeAbsPath(name, path).exists()) {
3725 // The file extension is probably missing.
3726 // Now try to find it out.
3727 string const dvips_name =
3728 find_file(name, path,
3729 known_dvips_graphics_formats);
3730 string const pdftex_name =
3731 find_file(name, path,
3732 known_pdftex_graphics_formats);
3733 if (!dvips_name.empty()) {
3734 if (!pdftex_name.empty()) {
3735 cerr << "This file contains the "
3737 "\"\\includegraphics{"
3739 "However, files\n\""
3740 << dvips_name << "\" and\n\""
3741 << pdftex_name << "\"\n"
3742 "both exist, so I had to make a "
3743 "choice and took the first one.\n"
3744 "Please move the unwanted one "
3745 "someplace else and try again\n"
3746 "if my choice was wrong."
3750 } else if (!pdftex_name.empty()) {
3756 FileName const absname = makeAbsPath(name, path);
3757 if (absname.exists()) {
3758 fix_child_filename(name);
3759 copy_file(absname, name);
3761 cerr << "Warning: Could not find graphics file '"
3762 << name << "'." << endl;
3764 context.check_layout(os);
3765 begin_inset(os, "Graphics ");
3766 os << "\n\tfilename " << name << '\n';
3767 if (opts.find("width") != opts.end())
3769 << translate_len(opts["width"]) << '\n';
3770 if (opts.find("totalheight") != opts.end())
3772 << translate_len(opts["totalheight"]) << '\n';
3773 if (opts.find("scale") != opts.end()) {
3774 istringstream iss(opts["scale"]);
3778 os << "\tscale " << val << '\n';
3780 if (opts.find("angle") != opts.end()) {
3781 os << "\trotateAngle "
3782 << opts["angle"] << '\n';
3783 vector<string>::const_iterator a =
3784 find(keys.begin(), keys.end(), "angle");
3785 vector<string>::const_iterator s =
3786 find(keys.begin(), keys.end(), "width");
3787 if (s == keys.end())
3788 s = find(keys.begin(), keys.end(), "totalheight");
3789 if (s == keys.end())
3790 s = find(keys.begin(), keys.end(), "scale");
3791 if (s != keys.end() && distance(s, a) > 0)
3792 os << "\tscaleBeforeRotation\n";
3794 if (opts.find("origin") != opts.end()) {
3796 string const opt = opts["origin"];
3797 if (opt.find('l') != string::npos) ss << "left";
3798 if (opt.find('r') != string::npos) ss << "right";
3799 if (opt.find('c') != string::npos) ss << "center";
3800 if (opt.find('t') != string::npos) ss << "Top";
3801 if (opt.find('b') != string::npos) ss << "Bottom";
3802 if (opt.find('B') != string::npos) ss << "Baseline";
3803 if (!ss.str().empty())
3804 os << "\trotateOrigin " << ss.str() << '\n';
3806 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3808 if (opts.find("keepaspectratio") != opts.end())
3809 os << "\tkeepAspectRatio\n";
3810 if (opts.find("clip") != opts.end())
3812 if (opts.find("draft") != opts.end())
3814 if (opts.find("bb") != opts.end())
3815 os << "\tBoundingBox "
3816 << opts["bb"] << '\n';
3817 int numberOfbbOptions = 0;
3818 if (opts.find("bbllx") != opts.end())
3819 numberOfbbOptions++;
3820 if (opts.find("bblly") != opts.end())
3821 numberOfbbOptions++;
3822 if (opts.find("bburx") != opts.end())
3823 numberOfbbOptions++;
3824 if (opts.find("bbury") != opts.end())
3825 numberOfbbOptions++;
3826 if (numberOfbbOptions == 4)
3827 os << "\tBoundingBox "
3828 << opts["bbllx"] << " " << opts["bblly"] << " "
3829 << opts["bburx"] << " " << opts["bbury"] << '\n';
3830 else if (numberOfbbOptions > 0)
3831 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3832 numberOfbbOptions = 0;
3833 if (opts.find("natwidth") != opts.end())
3834 numberOfbbOptions++;
3835 if (opts.find("natheight") != opts.end())
3836 numberOfbbOptions++;
3837 if (numberOfbbOptions == 2)
3838 os << "\tBoundingBox 0bp 0bp "
3839 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3840 else if (numberOfbbOptions > 0)
3841 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3842 ostringstream special;
3843 if (opts.find("hiresbb") != opts.end())
3844 special << "hiresbb,";
3845 if (opts.find("trim") != opts.end())
3847 if (opts.find("viewport") != opts.end())
3848 special << "viewport=" << opts["viewport"] << ',';
3849 if (opts.find("height") != opts.end())
3850 special << "height=" << opts["height"] << ',';
3851 if (opts.find("type") != opts.end())
3852 special << "type=" << opts["type"] << ',';
3853 if (opts.find("ext") != opts.end())
3854 special << "ext=" << opts["ext"] << ',';
3855 if (opts.find("read") != opts.end())
3856 special << "read=" << opts["read"] << ',';
3857 if (opts.find("command") != opts.end())
3858 special << "command=" << opts["command"] << ',';
3859 string s_special = special.str();
3860 if (!s_special.empty()) {
3861 // We had special arguments. Remove the trailing ','.
3862 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3864 // TODO: Handle the unknown settings better.
3865 // Warn about invalid options.
3866 // Check whether some option was given twice.
3868 preamble.registerAutomaticallyLoadedPackage("graphicx");
3872 if (t.cs() == "footnote" ||
3873 (t.cs() == "thanks" && context.layout->intitle)) {
3875 context.check_layout(os);
3876 begin_inset(os, "Foot\n");
3877 os << "status collapsed\n\n";
3878 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3883 if (t.cs() == "marginpar") {
3885 context.check_layout(os);
3886 begin_inset(os, "Marginal\n");
3887 os << "status collapsed\n\n";
3888 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3893 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3894 bool const use_minted = t.cs() == "mintinline";
3896 parse_listings(p, os, context, true, use_minted);
3900 if (t.cs() == "ensuremath") {
3902 context.check_layout(os);
3903 string const s = p.verbatim_item();
3904 //FIXME: this never triggers in UTF8
3905 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3908 output_ert_inset(os, "\\ensuremath{" + s + "}",
3913 else if (t.cs() == "makeindex"
3914 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3915 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3916 if (preamble.titleLayoutFound()) {
3918 skip_spaces_braces(p);
3920 output_ert_inset(os, t.asInput(), context);
3924 if (t.cs() == "tableofcontents"
3925 || t.cs() == "lstlistoflistings"
3926 || t.cs() == "listoflistings") {
3927 string name = t.cs();
3928 if (preamble.minted() && name == "listoflistings")
3929 name.insert(0, "lst");
3930 context.check_layout(os);
3931 begin_command_inset(os, "toc", name);
3933 skip_spaces_braces(p);
3934 if (name == "lstlistoflistings") {
3935 if (preamble.minted())
3936 preamble.registerAutomaticallyLoadedPackage("minted");
3938 preamble.registerAutomaticallyLoadedPackage("listings");
3943 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3944 context.check_layout(os);
3945 if (t.cs() == "listoffigures")
3946 begin_inset(os, "FloatList figure\n");
3948 begin_inset(os, "FloatList table\n");
3950 skip_spaces_braces(p);
3954 if (t.cs() == "listof") {
3955 p.skip_spaces(true);
3956 string const name = p.verbatim_item();
3957 if (context.textclass.floats().typeExist(name)) {
3958 context.check_layout(os);
3959 begin_inset(os, "FloatList ");
3962 p.verbatim_item(); // swallow second arg
3964 output_ert_inset(os, "\\listof{" + name + "}", context);
3968 if (t.cs() == "theendnotes"
3969 || (t.cs() == "printendnotes"
3970 && p.next_token().asInput() != "*"
3972 context.check_layout(os);
3973 begin_inset(os, "FloatList endnote\n");
3975 skip_spaces_braces(p);
3979 if ((where = is_known(t.cs(), known_text_font_families))) {
3980 parse_text_attributes(p, os, FLAG_ITEM, outer,
3981 context, "\\family", context.font.family,
3982 known_coded_font_families[where - known_text_font_families]);
3986 // beamer has a \textbf<overlay>{} inset
3987 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3988 parse_text_attributes(p, os, FLAG_ITEM, outer,
3989 context, "\\series", context.font.series,
3990 known_coded_font_series[where - known_text_font_series]);
3994 // beamer has a \textit<overlay>{} inset
3995 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
3996 parse_text_attributes(p, os, FLAG_ITEM, outer,
3997 context, "\\shape", context.font.shape,
3998 known_coded_font_shapes[where - known_text_font_shapes]);
4002 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4003 context.check_layout(os);
4004 TeXFont oldFont = context.font;
4005 context.font.init();
4006 context.font.size = oldFont.size;
4007 os << "\n\\family " << context.font.family << "\n";
4008 os << "\n\\series " << context.font.series << "\n";
4009 os << "\n\\shape " << context.font.shape << "\n";
4010 if (t.cs() == "textnormal") {
4011 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4012 output_font_change(os, context.font, oldFont);
4013 context.font = oldFont;
4015 eat_whitespace(p, os, context, false);
4019 if (t.cs() == "textcolor") {
4020 // scheme is \textcolor{color name}{text}
4021 string const color = p.verbatim_item();
4022 // we support the predefined colors of the color and the xcolor package
4023 if (color == "black" || color == "blue" || color == "cyan"
4024 || color == "green" || color == "magenta" || color == "red"
4025 || color == "white" || color == "yellow") {
4026 context.check_layout(os);
4027 os << "\n\\color " << color << "\n";
4028 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4029 context.check_layout(os);
4030 os << "\n\\color inherit\n";
4031 preamble.registerAutomaticallyLoadedPackage("color");
4032 } else if (color == "brown" || color == "darkgray" || color == "gray"
4033 || color == "lightgray" || color == "lime" || color == "olive"
4034 || color == "orange" || color == "pink" || color == "purple"
4035 || color == "teal" || color == "violet") {
4036 context.check_layout(os);
4037 os << "\n\\color " << color << "\n";
4038 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4039 context.check_layout(os);
4040 os << "\n\\color inherit\n";
4041 preamble.registerAutomaticallyLoadedPackage("xcolor");
4043 // for custom defined colors
4044 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4048 if (t.cs() == "underbar" || t.cs() == "uline") {
4049 // \underbar is not 100% correct (LyX outputs \uline
4050 // of ulem.sty). The difference is that \ulem allows
4051 // line breaks, and \underbar does not.
4052 // Do NOT handle \underline.
4053 // \underbar cuts through y, g, q, p etc.,
4054 // \underline does not.
4055 context.check_layout(os);
4056 os << "\n\\bar under\n";
4057 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4058 context.check_layout(os);
4059 os << "\n\\bar default\n";
4060 preamble.registerAutomaticallyLoadedPackage("ulem");
4064 if (t.cs() == "sout") {
4065 context.check_layout(os);
4066 os << "\n\\strikeout on\n";
4067 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4068 context.check_layout(os);
4069 os << "\n\\strikeout default\n";
4070 preamble.registerAutomaticallyLoadedPackage("ulem");
4074 // beamer has an \emph<overlay>{} inset
4075 if ((t.cs() == "uuline" || t.cs() == "uwave"
4076 || t.cs() == "emph" || t.cs() == "noun"
4077 || t.cs() == "xout") && !p.hasOpt("<")) {
4078 context.check_layout(os);
4079 os << "\n\\" << t.cs() << " on\n";
4080 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4081 context.check_layout(os);
4082 os << "\n\\" << t.cs() << " default\n";
4083 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4084 preamble.registerAutomaticallyLoadedPackage("ulem");
4088 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4089 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4090 context.check_layout(os);
4093 initials = p.getArg('[', ']');
4095 string name = p.getArg('{', '}');
4096 string localtime = p.getArg('{', '}');
4097 preamble.registerAuthor(name, initials);
4098 Author const & author = preamble.getAuthor(name);
4099 // from_asctime_utc() will fail if LyX decides to output the
4100 // time in the text language.
4101 time_t ptime = from_asctime_utc(localtime);
4102 if (ptime == static_cast<time_t>(-1)) {
4103 cerr << "Warning: Could not parse time `" << localtime
4104 << "´ for change tracking, using current time instead.\n";
4105 ptime = current_time();
4107 if (t.cs() == "lyxadded")
4108 os << "\n\\change_inserted ";
4110 os << "\n\\change_deleted ";
4111 os << author.bufferId() << ' ' << ptime << '\n';
4112 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4113 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4114 LaTeXPackages::isAvailable("xcolor");
4115 // No need to test for luatex, since luatex comes in
4116 // two flavours (dvi and pdf), like latex, and those
4117 // are detected by pdflatex.
4118 if (pdflatex || xetex) {
4120 preamble.registerAutomaticallyLoadedPackage("ulem");
4121 preamble.registerAutomaticallyLoadedPackage("xcolor");
4122 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4126 preamble.registerAutomaticallyLoadedPackage("ulem");
4127 preamble.registerAutomaticallyLoadedPackage("xcolor");
4133 if (t.cs() == "textipa") {
4134 context.check_layout(os);
4135 begin_inset(os, "IPA\n");
4136 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4137 context.merging_hyphens_allowed = false;
4138 set<string> pass_thru_cmds = context.pass_thru_cmds;
4139 // These commands have special meanings in IPA
4140 context.pass_thru_cmds.insert("!");
4141 context.pass_thru_cmds.insert(";");
4142 context.pass_thru_cmds.insert(":");
4143 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4144 context.pass_thru_cmds = pass_thru_cmds;
4145 context.merging_hyphens_allowed = merging_hyphens_allowed;
4147 preamble.registerAutomaticallyLoadedPackage("tipa");
4148 preamble.registerAutomaticallyLoadedPackage("tipx");
4152 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4153 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4154 context.check_layout(os);
4158 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4159 begin_inset(os, "IPADeco " + type + "\n");
4160 os << "status open\n";
4161 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4167 if (t.cs() == "textvertline") {
4168 // FIXME: This is not correct, \textvertline is higher than |
4174 if (t.cs() == "tone" ) {
4175 context.check_layout(os);
4176 // register the tone package
4177 preamble.registerAutomaticallyLoadedPackage("tone");
4178 string content = trimSpaceAndEol(p.verbatim_item());
4179 string command = t.asInput() + "{" + content + "}";
4180 // some tones can be detected by unicodesymbols, some need special code
4181 if (is_known(content, known_tones)) {
4182 os << "\\IPAChar " << command << "\n";
4185 // try to see whether the string is in unicodesymbols
4189 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4190 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4191 termination, rem, &req);
4195 output_ert_inset(os, to_utf8(rem), context);
4196 for (set<string>::const_iterator it = req.begin();
4197 it != req.end(); ++it)
4198 preamble.registerAutomaticallyLoadedPackage(*it);
4200 // we did not find a non-ert version
4201 output_ert_inset(os, command, context);
4205 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4206 t.cs() == "vphantom") {
4207 context.check_layout(os);
4208 if (t.cs() == "phantom")
4209 begin_inset(os, "Phantom Phantom\n");
4210 if (t.cs() == "hphantom")
4211 begin_inset(os, "Phantom HPhantom\n");
4212 if (t.cs() == "vphantom")
4213 begin_inset(os, "Phantom VPhantom\n");
4214 os << "status open\n";
4215 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4221 if (t.cs() == "href") {
4222 context.check_layout(os);
4223 string target = convert_literate_command_inset_arg(p.verbatim_item());
4224 string name = p.verbatim_item();
4225 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4226 bool const literal = !nm.first;
4227 name = literal ? subst(name, "\n", " ") : nm.second;
4228 string lit = literal ? "\"true\"" : "\"false\"";
4230 size_t i = target.find(':');
4231 if (i != string::npos) {
4232 type = target.substr(0, i + 1);
4233 if (type == "mailto:" || type == "file:")
4234 target = target.substr(i + 1);
4235 // handle the case that name is equal to target, except of "http(s)://"
4236 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4239 begin_command_inset(os, "href", "href");
4241 os << "name \"" << name << "\"\n";
4242 os << "target \"" << target << "\"\n";
4243 if (type == "mailto:" || type == "file:")
4244 os << "type \"" << type << "\"\n";
4245 os << "literal " << lit << "\n";
4247 skip_spaces_braces(p);
4251 if (t.cs() == "lyxline") {
4252 // swallow size argument (it is not used anyway)
4254 if (!context.atParagraphStart()) {
4255 // so our line is in the middle of a paragraph
4256 // we need to add a new line, lest this line
4257 // follow the other content on that line and
4258 // run off the side of the page
4259 // FIXME: This may create an empty paragraph,
4260 // but without that it would not be
4261 // possible to set noindent below.
4262 // Fortunately LaTeX does not care
4263 // about the empty paragraph.
4264 context.new_paragraph(os);
4266 if (preamble.indentParagraphs()) {
4267 // we need to unindent, lest the line be too long
4268 context.add_par_extra_stuff("\\noindent\n");
4270 context.check_layout(os);
4271 begin_command_inset(os, "line", "rule");
4272 os << "offset \"0.5ex\"\n"
4273 "width \"100line%\"\n"
4279 if (t.cs() == "rule") {
4280 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4281 string const width = p.getArg('{', '}');
4282 string const thickness = p.getArg('{', '}');
4283 context.check_layout(os);
4284 begin_command_inset(os, "line", "rule");
4285 if (!offset.empty())
4286 os << "offset \"" << translate_len(offset) << "\"\n";
4287 os << "width \"" << translate_len(width) << "\"\n"
4288 "height \"" << translate_len(thickness) << "\"\n";
4293 // Handle refstyle first in order to to catch \eqref, because this
4294 // can also occur without refstyle. Only recognize these commands if
4295 // refstyle.sty was found in the preamble (otherwise \eqref
4296 // and user defined ref commands could be misdetected).
4297 // We uncapitalize the input in order to catch capitalized commands
4299 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4300 && preamble.refstyle()) {
4301 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4302 string plural = "false";
4303 // Catch the plural option [s]
4305 string const opt = p.getOpt();
4309 // LyX does not yet support other optional arguments of ref commands
4310 output_ert_inset(os, t.asInput() + opt + "{" +
4311 p.verbatim_item() + '}', context);
4315 context.check_layout(os);
4316 begin_command_inset(os, "ref", "formatted");
4317 os << "reference \"";
4318 os << known_refstyle_prefixes[where - known_refstyle_commands]
4320 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4322 os << "plural \"" << plural << "\"\n";
4323 os << "caps \"" << cap << "\"\n";
4324 os << "noprefix \"false\"\n";
4326 preamble.registerAutomaticallyLoadedPackage("refstyle");
4330 // if refstyle is used, we must not convert \prettyref to a
4331 // formatted reference, since that would result in a refstyle command.
4332 if ((where = is_known(t.cs(), known_ref_commands)) &&
4333 (t.cs() != "prettyref" || !preamble.refstyle())) {
4334 string const opt = p.getOpt();
4336 context.check_layout(os);
4337 begin_command_inset(os, "ref",
4338 known_coded_ref_commands[where - known_ref_commands]);
4339 os << "reference \""
4340 << convert_literate_command_inset_arg(p.verbatim_item())
4342 os << "plural \"false\"\n";
4343 os << "caps \"false\"\n";
4344 os << "noprefix \"false\"\n";
4346 if (t.cs() == "vref" || t.cs() == "vpageref")
4347 preamble.registerAutomaticallyLoadedPackage("varioref");
4348 else if (t.cs() == "prettyref")
4349 preamble.registerAutomaticallyLoadedPackage("prettyref");
4351 // LyX does not yet support optional arguments of ref commands
4352 output_ert_inset(os, t.asInput() + opt + "{" +
4353 p.verbatim_item() + '}', context);
4359 is_known(t.cs(), known_natbib_commands) &&
4360 ((t.cs() != "citefullauthor" &&
4361 t.cs() != "citeyear" &&
4362 t.cs() != "citeyearpar") ||
4363 p.next_token().asInput() != "*")) {
4364 context.check_layout(os);
4365 string command = t.cs();
4366 if (p.next_token().asInput() == "*") {
4370 if (command == "citefullauthor")
4371 // alternative name for "\\citeauthor*"
4372 command = "citeauthor*";
4374 // text before the citation
4376 // text after the citation
4378 get_cite_arguments(p, true, before, after);
4380 if (command == "cite") {
4381 // \cite without optional argument means
4382 // \citet, \cite with at least one optional
4383 // argument means \citep.
4384 if (before.empty() && after.empty())
4389 if (before.empty() && after == "[]")
4390 // avoid \citet[]{a}
4392 else if (before == "[]" && after == "[]") {
4393 // avoid \citet[][]{a}
4397 bool literal = false;
4398 pair<bool, string> aft;
4399 pair<bool, string> bef;
4400 // remove the brackets around after and before
4401 if (!after.empty()) {
4403 after.erase(after.length() - 1, 1);
4404 aft = convert_latexed_command_inset_arg(after);
4405 literal = !aft.first;
4406 after = literal ? subst(after, "\n", " ") : aft.second;
4408 if (!before.empty()) {
4410 before.erase(before.length() - 1, 1);
4411 bef = convert_latexed_command_inset_arg(before);
4412 literal |= !bef.first;
4413 before = literal ? subst(before, "\n", " ") : bef.second;
4414 if (literal && !after.empty())
4415 after = subst(after, "\n", " ");
4417 string lit = literal ? "\"true\"" : "\"false\"";
4418 begin_command_inset(os, "citation", command);
4419 os << "after " << '"' << after << '"' << "\n";
4420 os << "before " << '"' << before << '"' << "\n";
4422 << convert_literate_command_inset_arg(p.verbatim_item())
4424 << "literal " << lit << "\n";
4426 // Need to set the cite engine if natbib is loaded by
4427 // the document class directly
4428 if (preamble.citeEngine() == "basic")
4429 preamble.citeEngine("natbib");
4434 && is_known(t.cs(), known_biblatex_commands)
4435 && ((t.cs() == "cite"
4436 || t.cs() == "citeauthor"
4437 || t.cs() == "Citeauthor"
4438 || t.cs() == "parencite"
4439 || t.cs() == "citetitle")
4440 || p.next_token().asInput() != "*"))
4441 || (use_biblatex_natbib
4442 && (is_known(t.cs(), known_biblatex_commands)
4443 || is_known(t.cs(), known_natbib_commands))
4444 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4445 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4446 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4447 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4448 || t.cs() == "parencite" || t.cs() == "citetitle")
4449 || p.next_token().asInput() != "*"))){
4450 context.check_layout(os);
4451 string command = t.cs();
4452 if (p.next_token().asInput() == "*") {
4457 bool const qualified = suffixIs(command, "s");
4459 command = rtrim(command, "s");
4461 // text before the citation
4463 // text after the citation
4465 get_cite_arguments(p, true, before, after, qualified);
4467 // These use natbib cmd names in LyX
4468 // for inter-citeengine compativility
4469 if (command == "citeyear")
4470 command = "citebyear";
4471 else if (command == "cite*")
4472 command = "citeyear";
4473 else if (command == "textcite")
4475 else if (command == "Textcite")
4477 else if (command == "parencite")
4479 else if (command == "Parencite")
4481 else if (command == "parencite*")
4482 command = "citeyearpar";
4483 else if (command == "smartcite")
4484 command = "footcite";
4485 else if (command == "Smartcite")
4486 command = "Footcite";
4488 string const emptyarg = qualified ? "()" : "[]";
4489 if (before.empty() && after == emptyarg)
4492 else if (before == emptyarg && after == emptyarg) {
4493 // avoid \cite[][]{a}
4497 bool literal = false;
4498 pair<bool, string> aft;
4499 pair<bool, string> bef;
4500 // remove the brackets around after and before
4501 if (!after.empty()) {
4503 after.erase(after.length() - 1, 1);
4504 aft = convert_latexed_command_inset_arg(after);
4505 literal = !aft.first;
4506 after = literal ? subst(after, "\n", " ") : aft.second;
4508 if (!before.empty()) {
4510 before.erase(before.length() - 1, 1);
4511 bef = convert_latexed_command_inset_arg(before);
4512 literal |= !bef.first;
4513 before = literal ? subst(before, "\n", " ") : bef.second;
4515 string keys, pretextlist, posttextlist;
4517 vector<pair<string, string>> pres, posts, preslit, postslit;
4518 vector<string> lkeys;
4519 // text before the citation
4520 string lbefore, lbeforelit;
4521 // text after the citation
4522 string lafter, lafterlit;
4524 pair<bool, string> laft, lbef;
4526 get_cite_arguments(p, true, lbefore, lafter);
4527 // remove the brackets around after and before
4528 if (!lafter.empty()) {
4530 lafter.erase(lafter.length() - 1, 1);
4531 laft = convert_latexed_command_inset_arg(lafter);
4532 literal |= !laft.first;
4533 lafter = laft.second;
4534 lafterlit = subst(lafter, "\n", " ");
4536 if (!lbefore.empty()) {
4537 lbefore.erase(0, 1);
4538 lbefore.erase(lbefore.length() - 1, 1);
4539 lbef = convert_latexed_command_inset_arg(lbefore);
4540 literal |= !lbef.first;
4541 lbefore = lbef.second;
4542 lbeforelit = subst(lbefore, "\n", " ");
4544 if (lbefore.empty() && lafter == "[]") {
4549 else if (lbefore == "[]" && lafter == "[]") {
4550 // avoid \cite[][]{a}
4556 lkey = p.getArg('{', '}');
4559 pres.push_back(make_pair(lkey, lbefore));
4560 preslit.push_back(make_pair(lkey, lbeforelit));
4561 posts.push_back(make_pair(lkey, lafter));
4562 postslit.push_back(make_pair(lkey, lafterlit));
4563 lkeys.push_back(lkey);
4565 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4570 for (auto const & ptl : pres) {
4571 if (!pretextlist.empty())
4572 pretextlist += '\t';
4573 pretextlist += ptl.first;
4574 if (!ptl.second.empty())
4575 pretextlist += " " + ptl.second;
4577 for (auto const & potl : posts) {
4578 if (!posttextlist.empty())
4579 posttextlist += '\t';
4580 posttextlist += potl.first;
4581 if (!potl.second.empty())
4582 posttextlist += " " + potl.second;
4585 keys = convert_literate_command_inset_arg(p.verbatim_item());
4588 after = subst(after, "\n", " ");
4589 if (!before.empty())
4590 before = subst(after, "\n", " ");
4592 string lit = literal ? "\"true\"" : "\"false\"";
4593 begin_command_inset(os, "citation", command);
4594 os << "after " << '"' << after << '"' << "\n";
4595 os << "before " << '"' << before << '"' << "\n";
4599 if (!pretextlist.empty())
4600 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4601 if (!posttextlist.empty())
4602 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4603 os << "literal " << lit << "\n";
4605 // Need to set the cite engine if biblatex is loaded by
4606 // the document class directly
4607 if (preamble.citeEngine() == "basic")
4608 use_biblatex_natbib ?
4609 preamble.citeEngine("biblatex-natbib")
4610 : preamble.citeEngine("biblatex");
4615 is_known(t.cs(), known_jurabib_commands) &&
4616 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4617 context.check_layout(os);
4618 string command = t.cs();
4619 if (p.next_token().asInput() == "*") {
4623 char argumentOrder = '\0';
4624 vector<string> const options =
4625 preamble.getPackageOptions("jurabib");
4626 if (find(options.begin(), options.end(),
4627 "natbiborder") != options.end())
4628 argumentOrder = 'n';
4629 else if (find(options.begin(), options.end(),
4630 "jurabiborder") != options.end())
4631 argumentOrder = 'j';
4633 // text before the citation
4635 // text after the citation
4637 get_cite_arguments(p, argumentOrder != 'j', before, after);
4639 string const citation = p.verbatim_item();
4640 if (!before.empty() && argumentOrder == '\0') {
4641 cerr << "Warning: Assuming argument order "
4642 "of jurabib version 0.6 for\n'"
4643 << command << before << after << '{'
4644 << citation << "}'.\n"
4645 "Add 'jurabiborder' to the jurabib "
4646 "package options if you used an\n"
4647 "earlier jurabib version." << endl;
4649 bool literal = false;
4650 pair<bool, string> aft;
4651 pair<bool, string> bef;
4652 // remove the brackets around after and before
4653 if (!after.empty()) {
4655 after.erase(after.length() - 1, 1);
4656 aft = convert_latexed_command_inset_arg(after);
4657 literal = !aft.first;
4658 after = literal ? subst(after, "\n", " ") : aft.second;
4660 if (!before.empty()) {
4662 before.erase(before.length() - 1, 1);
4663 bef = convert_latexed_command_inset_arg(before);
4664 literal |= !bef.first;
4665 before = literal ? subst(before, "\n", " ") : bef.second;
4666 if (literal && !after.empty())
4667 after = subst(after, "\n", " ");
4669 string lit = literal ? "\"true\"" : "\"false\"";
4670 begin_command_inset(os, "citation", command);
4671 os << "after " << '"' << after << "\"\n"
4672 << "before " << '"' << before << "\"\n"
4673 << "key " << '"' << citation << "\"\n"
4674 << "literal " << lit << "\n";
4676 // Need to set the cite engine if jurabib is loaded by
4677 // the document class directly
4678 if (preamble.citeEngine() == "basic")
4679 preamble.citeEngine("jurabib");
4683 if (t.cs() == "cite"
4684 || t.cs() == "nocite") {
4685 context.check_layout(os);
4686 string after = p.getArg('[', ']');
4687 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4688 bool const literal = !aft.first;
4689 after = literal ? subst(after, "\n", " ") : aft.second;
4690 string lit = literal ? "\"true\"" : "\"false\"";
4691 string key = convert_literate_command_inset_arg(p.verbatim_item());
4692 // store the case that it is "\nocite{*}" to use it later for
4695 begin_command_inset(os, "citation", t.cs());
4696 os << "after " << '"' << after << "\"\n"
4697 << "key " << '"' << key << "\"\n"
4698 << "literal " << lit << "\n";
4700 } else if (t.cs() == "nocite")
4705 if (t.cs() == "index" ||
4706 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4707 context.check_layout(os);
4708 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4709 p.getArg('[', ']') : "";
4710 string const kind = arg.empty() ? "idx" : arg;
4711 begin_inset(os, "Index ");
4712 os << kind << "\nstatus collapsed\n";
4713 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4716 preamble.registerAutomaticallyLoadedPackage("splitidx");
4720 if (t.cs() == "nomenclature") {
4721 context.check_layout(os);
4722 begin_command_inset(os, "nomenclature", "nomenclature");
4723 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4724 if (!prefix.empty())
4725 os << "prefix " << '"' << prefix << '"' << "\n";
4726 string symbol = p.verbatim_item();
4727 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4728 bool literal = !sym.first;
4729 string description = p.verbatim_item();
4730 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4731 literal |= !desc.first;
4733 symbol = subst(symbol, "\n", " ");
4734 description = subst(description, "\n", " ");
4736 symbol = sym.second;
4737 description = desc.second;
4739 string lit = literal ? "\"true\"" : "\"false\"";
4740 os << "symbol " << '"' << symbol;
4741 os << "\"\ndescription \""
4742 << description << "\"\n"
4743 << "literal " << lit << "\n";
4745 preamble.registerAutomaticallyLoadedPackage("nomencl");
4749 if (t.cs() == "label") {
4750 context.check_layout(os);
4751 begin_command_inset(os, "label", "label");
4753 << convert_literate_command_inset_arg(p.verbatim_item())
4759 if (t.cs() == "lyxmintcaption") {
4760 string const pos = p.getArg('[', ']');
4762 string const caption =
4763 parse_text_snippet(p, FLAG_ITEM, false,
4765 minted_nonfloat_caption = "[t]" + caption;
4767 // We already got the caption at the bottom,
4768 // so simply skip it.
4769 parse_text_snippet(p, FLAG_ITEM, false, context);
4771 eat_whitespace(p, os, context, true);
4775 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4776 context.check_layout(os);
4777 string commandname = t.cs();
4779 if (p.next_token().asInput() == "*") {
4784 begin_command_inset(os, "index_print", commandname);
4785 string const indexname = p.getArg('[', ']');
4787 if (indexname.empty())
4788 os << "type \"idx\"\n";
4790 os << "type \"" << indexname << "\"\n";
4791 os << "literal \"true\"\n";
4794 skip_spaces_braces(p);
4795 preamble.registerAutomaticallyLoadedPackage("makeidx");
4796 if (preamble.use_indices() == "true")
4797 preamble.registerAutomaticallyLoadedPackage("splitidx");
4801 if (t.cs() == "printnomenclature") {
4803 string width_type = "";
4804 context.check_layout(os);
4805 begin_command_inset(os, "nomencl_print", "printnomenclature");
4806 // case of a custom width
4808 width = p.getArg('[', ']');
4809 width = translate_len(width);
4810 width_type = "custom";
4812 // case of no custom width
4813 // the case of no custom width but the width set
4814 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4815 // because the user could have set anything, not only the width
4816 // of the longest label (which would be width_type = "auto")
4817 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4818 if (label.empty() && width_type.empty())
4819 width_type = "none";
4820 os << "set_width \"" << width_type << "\"\n";
4821 if (width_type == "custom")
4822 os << "width \"" << width << '\"';
4824 skip_spaces_braces(p);
4825 preamble.registerAutomaticallyLoadedPackage("nomencl");
4829 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4830 context.check_layout(os);
4831 begin_inset(os, "script ");
4832 os << t.cs().substr(4) << '\n';
4833 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4834 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4836 if (t.cs() == "textsubscript")
4837 preamble.registerAutomaticallyLoadedPackage("subscript");
4841 if ((where = is_known(t.cs(), known_quotes))) {
4842 context.check_layout(os);
4843 begin_inset(os, "Quotes ");
4844 string quotetype = known_coded_quotes[where - known_quotes];
4845 // try to make a smart guess about the side
4846 Token const prev = p.prev_token();
4847 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4848 && prev.character() != '\n' && prev.character() != '~');
4849 quotetype = guessQuoteStyle(quotetype, opening);
4852 // LyX adds {} after the quote, so we have to eat
4853 // spaces here if there are any before a possible
4855 eat_whitespace(p, os, context, false);
4860 if ((where = is_known(t.cs(), known_sizes)) &&
4861 context.new_layout_allowed) {
4862 context.check_layout(os);
4863 TeXFont const oldFont = context.font;
4864 context.font.size = known_coded_sizes[where - known_sizes];
4865 output_font_change(os, oldFont, context.font);
4866 eat_whitespace(p, os, context, false);
4870 if ((where = is_known(t.cs(), known_font_families)) &&
4871 context.new_layout_allowed) {
4872 context.check_layout(os);
4873 TeXFont const oldFont = context.font;
4874 context.font.family =
4875 known_coded_font_families[where - known_font_families];
4876 output_font_change(os, oldFont, context.font);
4877 eat_whitespace(p, os, context, false);
4881 if ((where = is_known(t.cs(), known_font_series)) &&
4882 context.new_layout_allowed) {
4883 context.check_layout(os);
4884 TeXFont const oldFont = context.font;
4885 context.font.series =
4886 known_coded_font_series[where - known_font_series];
4887 output_font_change(os, oldFont, context.font);
4888 eat_whitespace(p, os, context, false);
4892 if ((where = is_known(t.cs(), known_font_shapes)) &&
4893 context.new_layout_allowed) {
4894 context.check_layout(os);
4895 TeXFont const oldFont = context.font;
4896 context.font.shape =
4897 known_coded_font_shapes[where - known_font_shapes];
4898 output_font_change(os, oldFont, context.font);
4899 eat_whitespace(p, os, context, false);
4902 if ((where = is_known(t.cs(), known_old_font_families)) &&
4903 context.new_layout_allowed) {
4904 context.check_layout(os);
4905 TeXFont const oldFont = context.font;
4906 context.font.init();
4907 context.font.size = oldFont.size;
4908 context.font.family =
4909 known_coded_font_families[where - known_old_font_families];
4910 output_font_change(os, oldFont, context.font);
4911 eat_whitespace(p, os, context, false);
4915 if ((where = is_known(t.cs(), known_old_font_series)) &&
4916 context.new_layout_allowed) {
4917 context.check_layout(os);
4918 TeXFont const oldFont = context.font;
4919 context.font.init();
4920 context.font.size = oldFont.size;
4921 context.font.series =
4922 known_coded_font_series[where - known_old_font_series];
4923 output_font_change(os, oldFont, context.font);
4924 eat_whitespace(p, os, context, false);
4928 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4929 context.new_layout_allowed) {
4930 context.check_layout(os);
4931 TeXFont const oldFont = context.font;
4932 context.font.init();
4933 context.font.size = oldFont.size;
4934 context.font.shape =
4935 known_coded_font_shapes[where - known_old_font_shapes];
4936 output_font_change(os, oldFont, context.font);
4937 eat_whitespace(p, os, context, false);
4941 if (t.cs() == "selectlanguage") {
4942 context.check_layout(os);
4943 // save the language for the case that a
4944 // \foreignlanguage is used
4945 context.font.language = babel2lyx(p.verbatim_item());
4946 os << "\n\\lang " << context.font.language << "\n";
4950 if (t.cs() == "foreignlanguage") {
4951 string const lang = babel2lyx(p.verbatim_item());
4952 parse_text_attributes(p, os, FLAG_ITEM, outer,
4954 context.font.language, lang);
4958 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4959 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4960 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4962 // We have to output the whole command if it has an option
4963 // because LyX doesn't support this yet, see bug #8214,
4964 // only if there is a single option specifying a variant, we can handle it.
4966 string langopts = p.getOpt();
4967 // check if the option contains a variant, if yes, extract it
4968 string::size_type pos_var = langopts.find("variant");
4969 string::size_type i = langopts.find(',');
4970 string::size_type k = langopts.find('=', pos_var);
4971 if (pos_var != string::npos && i == string::npos) {
4973 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4974 lang = preamble.polyglossia2lyx(variant);
4975 parse_text_attributes(p, os, FLAG_ITEM, outer,
4977 context.font.language, lang);
4979 output_ert_inset(os, t.asInput() + langopts, context);
4981 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4982 parse_text_attributes(p, os, FLAG_ITEM, outer,
4984 context.font.language, lang);
4989 if (t.cs() == "inputencoding") {
4990 // nothing to write here
4991 string const enc = subst(p.verbatim_item(), "\n", " ");
4992 p.setEncoding(enc, Encoding::inputenc);
4996 if (is_known(t.cs(), known_special_chars) ||
4997 (t.cs() == "protect" &&
4998 p.next_token().cat() == catEscape &&
4999 is_known(p.next_token().cs(), known_special_protect_chars))) {
5000 // LyX sometimes puts a \protect in front, so we have to ignore it
5002 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5003 known_special_chars);
5004 context.check_layout(os);
5005 os << known_coded_special_chars[where - known_special_chars];
5006 skip_spaces_braces(p);
5010 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5011 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5012 p.next_next_token().asInput() == "-") ||
5013 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5014 // LyX sometimes puts a \protect in front, so we have to ignore it
5015 if (t.cs() == "protect")
5017 context.check_layout(os);
5018 if (t.cs() == "nobreakdash")
5019 os << "\\SpecialChar nobreakdash\n";
5021 os << "\\SpecialChar endofsentence\n";
5026 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5027 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5028 || t.cs() == "%" || t.cs() == "-") {
5029 context.check_layout(os);
5031 os << "\\SpecialChar softhyphen\n";
5037 if (t.cs() == "char") {
5038 context.check_layout(os);
5039 if (p.next_token().character() == '`') {
5041 if (p.next_token().cs() == "\"") {
5046 output_ert_inset(os, "\\char`", context);
5049 output_ert_inset(os, "\\char", context);
5054 if (t.cs() == "verb") {
5055 context.check_layout(os);
5056 // set catcodes to verbatim early, just in case.
5057 p.setCatcodes(VERBATIM_CATCODES);
5058 string delim = p.get_token().asInput();
5059 Parser::Arg arg = p.verbatimStuff(delim);
5061 output_ert_inset(os, "\\verb" + delim
5062 + arg.second + delim, context);
5064 cerr << "invalid \\verb command. Skipping" << endl;
5068 // Problem: \= creates a tabstop inside the tabbing environment
5069 // and else an accent. In the latter case we really would want
5070 // \={o} instead of \= o.
5071 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5072 output_ert_inset(os, t.asInput(), context);
5076 if (t.cs() == "\\") {
5077 context.check_layout(os);
5079 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5080 else if (p.next_token().asInput() == "*") {
5082 // getOpt() eats the following space if there
5083 // is no optional argument, but that is OK
5084 // here since it has no effect in the output.
5085 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5088 begin_inset(os, "Newline newline");
5094 if (t.cs() == "newline" ||
5095 (t.cs() == "linebreak" && !p.hasOpt())) {
5096 context.check_layout(os);
5097 begin_inset(os, "Newline ");
5100 skip_spaces_braces(p);
5104 if (t.cs() == "input" || t.cs() == "include"
5105 || t.cs() == "verbatiminput"
5106 || t.cs() == "lstinputlisting"
5107 || t.cs() == "inputminted") {
5108 string name = t.cs();
5109 if (name == "verbatiminput"
5110 && p.next_token().asInput() == "*")
5111 name += p.get_token().asInput();
5112 context.check_layout(os);
5114 bool literal = false;
5115 if (name == "lstinputlisting" && p.hasOpt()) {
5116 lstparams = p.getArg('[', ']');
5117 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5118 literal = !oa.first;
5120 lstparams = subst(lstparams, "\n", " ");
5122 lstparams = oa.second;
5123 } else if (name == "inputminted") {
5124 name = "lstinputlisting";
5125 string const lang = p.getArg('{', '}');
5126 if (lang != "tex") {
5127 string cmd = "\\inputminted{" + lang + "}{";
5128 cmd += p.getArg('{', '}') + "}";
5129 output_ert_inset(os, cmd, context);
5132 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5133 minted_nonfloat_caption.erase(0,3);
5134 // extract label and caption from the already produced LyX code
5135 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5136 string const caption = nfc.front();
5138 vector<string>::iterator it =
5139 find(nfc.begin(), nfc.end(), "LatexCommand label");
5140 if (it != nfc.end()) {
5142 if (it != nfc.end())
5144 label = support::split(label, '"');
5147 minted_nonfloat_caption.clear();
5148 lstparams = "caption=" + caption;
5150 lstparams += ",label=" + label;
5151 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5152 literal = !oa.first;
5154 lstparams = subst(lstparams, "\n", " ");
5156 lstparams = oa.second;
5159 string lit = literal ? "\"true\"" : "\"false\"";
5160 string filename(normalize_filename(p.getArg('{', '}')));
5161 string const path = getMasterFilePath(true);
5162 // We want to preserve relative / absolute filenames,
5163 // therefore path is only used for testing
5164 if ((t.cs() == "include" || t.cs() == "input") &&
5165 !makeAbsPath(filename, path).exists()) {
5166 // The file extension is probably missing.
5167 // Now try to find it out.
5168 string const tex_name =
5169 find_file(filename, path,
5170 known_tex_extensions);
5171 if (!tex_name.empty())
5172 filename = tex_name;
5174 bool external = false;
5176 if (makeAbsPath(filename, path).exists()) {
5177 string const abstexname =
5178 makeAbsPath(filename, path).absFileName();
5179 string const absfigname =
5180 changeExtension(abstexname, ".fig");
5181 fix_child_filename(filename);
5182 string const lyxname = changeExtension(filename,
5183 roundtripMode() ? ".lyx.lyx" : ".lyx");
5184 string const abslyxname = makeAbsPath(
5185 lyxname, getParentFilePath(false)).absFileName();
5187 if (!skipChildren())
5188 external = FileName(absfigname).exists();
5189 if (t.cs() == "input" && !skipChildren()) {
5190 string const ext = getExtension(abstexname);
5192 // Combined PS/LaTeX:
5193 // x.eps, x.pstex_t (old xfig)
5194 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5195 FileName const absepsname(
5196 changeExtension(abstexname, ".eps"));
5197 FileName const abspstexname(
5198 changeExtension(abstexname, ".pstex"));
5199 bool const xfigeps =
5200 (absepsname.exists() ||
5201 abspstexname.exists()) &&
5204 // Combined PDF/LaTeX:
5205 // x.pdf, x.pdftex_t (old xfig)
5206 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5207 FileName const abspdfname(
5208 changeExtension(abstexname, ".pdf"));
5209 bool const xfigpdf =
5210 abspdfname.exists() &&
5211 (ext == "pdftex_t" || ext == "pdf_t");
5215 // Combined PS/PDF/LaTeX:
5216 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5217 string const absbase2(
5218 removeExtension(abstexname) + "_pspdftex");
5219 FileName const abseps2name(
5220 addExtension(absbase2, ".eps"));
5221 FileName const abspdf2name(
5222 addExtension(absbase2, ".pdf"));
5223 bool const xfigboth =
5224 abspdf2name.exists() &&
5225 abseps2name.exists() && ext == "pspdftex";
5227 xfig = xfigpdf || xfigeps || xfigboth;
5228 external = external && xfig;
5231 outname = changeExtension(filename, ".fig");
5232 FileName abssrc(changeExtension(abstexname, ".fig"));
5233 copy_file(abssrc, outname);
5235 // Don't try to convert, the result
5236 // would be full of ERT.
5238 FileName abssrc(abstexname);
5239 copy_file(abssrc, outname);
5240 } else if (t.cs() != "verbatiminput" &&
5242 tex2lyx(abstexname, FileName(abslyxname),
5245 // no need to call copy_file
5246 // tex2lyx creates the file
5249 FileName abssrc(abstexname);
5250 copy_file(abssrc, outname);
5253 cerr << "Warning: Could not find included file '"
5254 << filename << "'." << endl;
5258 begin_inset(os, "External\n");
5259 os << "\ttemplate XFig\n"
5260 << "\tfilename " << outname << '\n';
5261 registerExternalTemplatePackages("XFig");
5263 begin_command_inset(os, "include", name);
5264 outname = subst(outname, "\"", "\\\"");
5265 os << "preview false\n"
5266 "filename \"" << outname << "\"\n";
5267 if (!lstparams.empty())
5268 os << "lstparams \"" << lstparams << "\"\n";
5269 os << "literal " << lit << "\n";
5270 if (t.cs() == "verbatiminput")
5271 preamble.registerAutomaticallyLoadedPackage("verbatim");
5277 if (t.cs() == "bibliographystyle") {
5278 // store new bibliographystyle
5279 bibliographystyle = p.verbatim_item();
5280 // If any other command than \bibliography, \addcontentsline
5281 // and \nocite{*} follows, we need to output the style
5282 // (because it might be used by that command).
5283 // Otherwise, it will automatically be output by LyX.
5286 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5287 if (t2.cat() == catBegin)
5289 if (t2.cat() != catEscape)
5291 if (t2.cs() == "nocite") {
5292 if (p.getArg('{', '}') == "*")
5294 } else if (t2.cs() == "bibliography")
5296 else if (t2.cs() == "phantomsection") {
5300 else if (t2.cs() == "addcontentsline") {
5301 // get the 3 arguments of \addcontentsline
5304 contentslineContent = p.getArg('{', '}');
5305 // if the last argument is not \refname we must output
5306 if (contentslineContent == "\\refname")
5313 output_ert_inset(os,
5314 "\\bibliographystyle{" + bibliographystyle + '}',
5320 if (t.cs() == "phantomsection") {
5321 // we only support this if it occurs between
5322 // \bibliographystyle and \bibliography
5323 if (bibliographystyle.empty())
5324 output_ert_inset(os, "\\phantomsection", context);
5328 if (t.cs() == "addcontentsline") {
5329 context.check_layout(os);
5330 // get the 3 arguments of \addcontentsline
5331 string const one = p.getArg('{', '}');
5332 string const two = p.getArg('{', '}');
5333 string const three = p.getArg('{', '}');
5334 // only if it is a \refname, we support if for the bibtex inset
5335 if (contentslineContent != "\\refname") {
5336 output_ert_inset(os,
5337 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5343 else if (t.cs() == "bibliography") {
5344 context.check_layout(os);
5346 begin_command_inset(os, "bibtex", "bibtex");
5347 if (!btprint.empty()) {
5348 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5349 // clear the string because the next BibTeX inset can be without the
5350 // \nocite{*} option
5353 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5354 // Do we have addcontentsline?
5355 if (contentslineContent == "\\refname") {
5356 BibOpts = "bibtotoc";
5357 // clear string because next BibTeX inset can be without addcontentsline
5358 contentslineContent.clear();
5360 // Do we have a bibliographystyle set?
5361 if (!bibliographystyle.empty()) {
5362 if (BibOpts.empty())
5363 BibOpts = normalize_filename(bibliographystyle);
5365 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5366 // clear it because each bibtex entry has its style
5367 // and we need an empty string to handle \phantomsection
5368 bibliographystyle.clear();
5370 os << "options " << '"' << BibOpts << '"' << "\n";
5371 if (p.getEncoding() != preamble.docencoding) {
5372 Encoding const * const enc = encodings.fromIconvName(
5373 p.getEncoding(), Encoding::inputenc, true);
5375 cerr << "Unknown bib encoding " << p.getEncoding()
5376 << ". Ignoring." << std::endl;
5378 os << "encoding " << '"' << enc->name() << '"' << "\n";
5384 if (t.cs() == "printbibliography") {
5385 context.check_layout(os);
5387 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5388 vector<string> opts = getVectorFromString(bbloptions);
5389 vector<string>::iterator it =
5390 find(opts.begin(), opts.end(), "heading=bibintoc");
5391 if (it != opts.end()) {
5393 BibOpts = "bibtotoc";
5395 bbloptions = getStringFromVector(opts);
5396 begin_command_inset(os, "bibtex", "bibtex");
5397 if (!btprint.empty()) {
5398 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5399 // clear the string because the next BibTeX inset can be without the
5400 // \nocite{*} option
5404 for (auto const & bf : preamble.biblatex_bibliographies) {
5405 if (!bibfiles.empty())
5407 bibfiles += normalize_filename(bf);
5409 if (!bibfiles.empty())
5410 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5411 // Do we have addcontentsline?
5412 if (contentslineContent == "\\refname") {
5413 BibOpts = "bibtotoc";
5414 // clear string because next BibTeX inset can be without addcontentsline
5415 contentslineContent.clear();
5417 os << "options " << '"' << BibOpts << '"' << "\n";
5418 if (!bbloptions.empty())
5419 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5420 if (!preamble.bibencoding.empty()) {
5421 Encoding const * const enc = encodings.fromLaTeXName(
5422 preamble.bibencoding, Encoding::inputenc, true);
5424 cerr << "Unknown bib encoding " << preamble.bibencoding
5425 << ". Ignoring." << std::endl;
5427 os << "encoding " << '"' << enc->name() << '"' << "\n";
5430 for (auto const & bf : preamble.biblatex_encodings) {
5431 if (!bibfileencs.empty())
5432 bibfileencs += "\t";
5435 if (!bibfileencs.empty())
5436 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5438 need_commentbib = false;
5442 if (t.cs() == "bibbysection") {
5443 context.check_layout(os);
5445 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5446 vector<string> opts = getVectorFromString(bbloptions);
5447 vector<string>::iterator it =
5448 find(opts.begin(), opts.end(), "heading=bibintoc");
5449 if (it != opts.end()) {
5451 BibOpts = "bibtotoc";
5453 bbloptions = getStringFromVector(opts);
5454 begin_command_inset(os, "bibtex", "bibtex");
5455 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5457 for (auto const & bf : preamble.biblatex_bibliographies) {
5458 if (!bibfiles.empty())
5460 bibfiles += normalize_filename(bf);
5462 if (!bibfiles.empty())
5463 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5464 os << "options " << '"' << BibOpts << '"' << "\n";
5465 if (!bbloptions.empty())
5466 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5468 need_commentbib = false;
5472 if (t.cs() == "parbox") {
5473 // Test whether this is an outer box of a shaded box
5475 // swallow arguments
5476 while (p.hasOpt()) {
5478 p.skip_spaces(true);
5481 p.skip_spaces(true);
5483 if (p.next_token().cat() == catBegin)
5485 p.skip_spaces(true);
5486 Token to = p.get_token();
5487 bool shaded = false;
5488 if (to.asInput() == "\\begin") {
5489 p.skip_spaces(true);
5490 if (p.getArg('{', '}') == "shaded")
5495 parse_outer_box(p, os, FLAG_ITEM, outer,
5496 context, "parbox", "shaded");
5498 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5499 "", "", t.cs(), "", "");
5503 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5504 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5505 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5506 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5510 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5511 string backgroundcolor;
5512 preamble.registerAutomaticallyLoadedPackage("xcolor");
5513 if (t.cs() == "fcolorbox") {
5514 string const framecolor = p.getArg('{', '}');
5515 backgroundcolor = p.getArg('{', '}');
5516 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5518 backgroundcolor = p.getArg('{', '}');
5519 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5524 // FIXME: due to the compiler limit of "if" nestings
5525 // the code for the alignment was put here
5526 // put them in their own if if this is fixed
5527 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5528 || t.cs() == "shadowsize"
5529 || t.cs() == "raggedleft" || t.cs() == "centering"
5530 || t.cs() == "raggedright") {
5531 if (t.cs() == "fboxrule")
5533 if (t.cs() == "fboxsep")
5535 if (t.cs() == "shadowsize")
5537 if (t.cs() != "raggedleft" && t.cs() != "centering"
5538 && t.cs() != "raggedright") {
5539 p.skip_spaces(true);
5540 while (p.good() && p.next_token().cat() != catSpace
5541 && p.next_token().cat() != catNewline
5542 && p.next_token().cat() != catEscape) {
5543 if (t.cs() == "fboxrule")
5544 fboxrule = fboxrule + p.get_token().asInput();
5545 if (t.cs() == "fboxsep")
5546 fboxsep = fboxsep + p.get_token().asInput();
5547 if (t.cs() == "shadowsize")
5548 shadow_size = shadow_size + p.get_token().asInput();
5551 output_ert_inset(os, t.asInput(), context);
5556 //\framebox() is part of the picture environment and different from \framebox{}
5557 //\framebox{} will be parsed by parse_outer_box
5558 if (t.cs() == "framebox") {
5559 if (p.next_token().character() == '(') {
5560 //the syntax is: \framebox(x,y)[position]{content}
5561 string arg = t.asInput();
5562 arg += p.getFullParentheseArg();
5563 arg += p.getFullOpt();
5564 eat_whitespace(p, os, context, false);
5565 output_ert_inset(os, arg + '{', context);
5566 parse_text(p, os, FLAG_ITEM, outer, context);
5567 output_ert_inset(os, "}", context);
5569 //the syntax is: \framebox[width][position]{content}
5570 string special = p.getFullOpt();
5571 special += p.getOpt();
5572 parse_outer_box(p, os, FLAG_ITEM, outer,
5573 context, t.cs(), special);
5578 //\makebox() is part of the picture environment and different from \makebox{}
5579 //\makebox{} will be parsed by parse_box
5580 if (t.cs() == "makebox") {
5581 if (p.next_token().character() == '(') {
5582 //the syntax is: \makebox(x,y)[position]{content}
5583 string arg = t.asInput();
5584 arg += p.getFullParentheseArg();
5585 arg += p.getFullOpt();
5586 eat_whitespace(p, os, context, false);
5587 output_ert_inset(os, arg + '{', context);
5588 parse_text(p, os, FLAG_ITEM, outer, context);
5589 output_ert_inset(os, "}", context);
5591 //the syntax is: \makebox[width][position]{content}
5592 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5593 "", "", t.cs(), "", "");
5597 if (t.cs() == "smallskip" ||
5598 t.cs() == "medskip" ||
5599 t.cs() == "bigskip" ||
5600 t.cs() == "vfill") {
5601 context.check_layout(os);
5602 begin_inset(os, "VSpace ");
5605 skip_spaces_braces(p);
5609 if ((where = is_known(t.cs(), known_spaces))
5610 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5611 context.check_layout(os);
5612 begin_inset(os, "space ");
5613 os << '\\' << known_coded_spaces[where - known_spaces]
5616 // LaTeX swallows whitespace after all spaces except
5617 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5618 // We have to do that here, too, because LyX
5619 // adds "{}" which would make the spaces significant.
5620 if (!contains(",>!;:", t.cs()))
5621 eat_whitespace(p, os, context, false);
5622 // LyX adds "{}" after all spaces except "\\ " and
5623 // "\\,", so we have to remove "{}".
5624 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5625 // remove the braces after "\\,", too.
5631 if (t.cs() == "newpage" ||
5632 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5633 t.cs() == "clearpage" ||
5634 t.cs() == "cleardoublepage" ||
5635 t.cs() == "nopagebreak") {
5636 context.check_layout(os);
5637 begin_inset(os, "Newpage ");
5640 skip_spaces_braces(p);
5644 if (t.cs() == "DeclareRobustCommand" ||
5645 t.cs() == "DeclareRobustCommandx" ||
5646 t.cs() == "newcommand" ||
5647 t.cs() == "newcommandx" ||
5648 t.cs() == "providecommand" ||
5649 t.cs() == "providecommandx" ||
5650 t.cs() == "renewcommand" ||
5651 t.cs() == "renewcommandx") {
5652 // DeclareRobustCommand, DeclareRobustCommandx,
5653 // providecommand and providecommandx could be handled
5654 // by parse_command(), but we need to call
5655 // add_known_command() here.
5656 string name = t.asInput();
5657 if (p.next_token().asInput() == "*") {
5658 // Starred form. Eat '*'
5662 string const command = p.verbatim_item();
5663 string const opt1 = p.getFullOpt();
5664 string const opt2 = p.getFullOpt();
5665 add_known_command(command, opt1, !opt2.empty());
5666 string const ert = name + '{' + command + '}' +
5668 '{' + p.verbatim_item() + '}';
5670 if (t.cs() == "DeclareRobustCommand" ||
5671 t.cs() == "DeclareRobustCommandx" ||
5672 t.cs() == "providecommand" ||
5673 t.cs() == "providecommandx" ||
5674 name[name.length()-1] == '*')
5675 output_ert_inset(os, ert, context);
5677 context.check_layout(os);
5678 begin_inset(os, "FormulaMacro");
5685 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5686 // let could be handled by parse_command(),
5687 // but we need to call add_known_command() here.
5688 string ert = t.asInput();
5691 if (p.next_token().cat() == catBegin) {
5692 name = p.verbatim_item();
5693 ert += '{' + name + '}';
5695 name = p.verbatim_item();
5700 if (p.next_token().cat() == catBegin) {
5701 command = p.verbatim_item();
5702 ert += '{' + command + '}';
5704 command = p.verbatim_item();
5707 // If command is known, make name known too, to parse
5708 // its arguments correctly. For this reason we also
5709 // have commands in syntax.default that are hardcoded.
5710 CommandMap::iterator it = known_commands.find(command);
5711 if (it != known_commands.end())
5712 known_commands[t.asInput()] = it->second;
5713 output_ert_inset(os, ert, context);
5717 if (t.cs() == "hspace" || t.cs() == "vspace") {
5720 string name = t.asInput();
5721 string const length = p.verbatim_item();
5724 bool valid = splitLatexLength(length, valstring, unit);
5725 bool known_hspace = false;
5726 bool known_vspace = false;
5727 bool known_unit = false;
5730 istringstream iss(valstring);
5733 if (t.cs()[0] == 'h') {
5734 if (unit == "\\fill") {
5739 known_hspace = true;
5742 if (unit == "\\smallskipamount") {
5744 known_vspace = true;
5745 } else if (unit == "\\medskipamount") {
5747 known_vspace = true;
5748 } else if (unit == "\\bigskipamount") {
5750 known_vspace = true;
5751 } else if (length == "\\baselineskip") {
5753 known_vspace = true;
5754 } else if (unit == "\\fill") {
5756 known_vspace = true;
5760 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5762 known_vspace = true;
5764 if (!known_hspace && !known_vspace) {
5765 switch (unitFromString(unit)) {
5781 //unitFromString(unit) fails for relative units like Length::PCW
5782 // therefore handle them separately
5783 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5784 || unit == "\\textwidth" || unit == "\\linewidth"
5785 || unit == "\\textheight" || unit == "\\paperheight"
5786 || unit == "\\baselineskip")
5794 // check for glue lengths
5795 bool is_gluelength = false;
5796 string gluelength = length;
5797 string::size_type i = length.find(" minus");
5798 if (i == string::npos) {
5799 i = length.find(" plus");
5800 if (i != string::npos)
5801 is_gluelength = true;
5803 is_gluelength = true;
5804 // if yes transform "9xx minus 8yy plus 7zz"
5806 if (is_gluelength) {
5807 i = gluelength.find(" minus");
5808 if (i != string::npos)
5809 gluelength.replace(i, 7, "-");
5810 i = gluelength.find(" plus");
5811 if (i != string::npos)
5812 gluelength.replace(i, 6, "+");
5815 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5816 // Literal horizontal length or known variable
5817 context.check_layout(os);
5818 begin_inset(os, "space ");
5826 if (known_unit && !known_hspace)
5827 os << "\n\\length " << translate_len(length);
5829 os << "\n\\length " << gluelength;
5831 } else if (known_unit || known_vspace || is_gluelength) {
5832 // Literal vertical length or known variable
5833 context.check_layout(os);
5834 begin_inset(os, "VSpace ");
5837 if (known_unit && !known_vspace)
5838 os << translate_len(length);
5845 // LyX can't handle other length variables in Inset VSpace/space
5850 output_ert_inset(os, name + '{' + unit + '}', context);
5851 else if (value == -1.0)
5852 output_ert_inset(os, name + "{-" + unit + '}', context);
5854 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5856 output_ert_inset(os, name + '{' + length + '}', context);
5861 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5862 // might be one or several options or a star.
5863 // The single '=' is meant here.
5864 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5868 context.check_layout(os);
5869 // store the latexparam here. This is eaten in parse_text_in_inset
5870 context.latexparam = newinsetlayout->latexparam();
5871 docstring name = newinsetlayout->name();
5872 bool const caption = name.find(from_ascii("Caption:")) == 0;
5874 // Already done for floating minted listings.
5875 if (minted_float.empty()) {
5876 begin_inset(os, "Caption ");
5877 os << to_utf8(name.substr(8)) << '\n';
5880 // FIXME: what do we do if the prefix is not Flex: ?
5881 if (prefixIs(name, from_ascii("Flex:")))
5883 begin_inset(os, "Flex ");
5884 os << to_utf8(name) << '\n'
5885 << "status collapsed\n";
5887 if (!minted_float.empty()) {
5888 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5889 } else if (newinsetlayout->isPassThru()) {
5890 // set catcodes to verbatim early, just in case.
5891 p.setCatcodes(VERBATIM_CATCODES);
5892 string delim = p.get_token().asInput();
5894 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5895 //FIXME: handle error condition
5896 string const arg = p.verbatimStuff("}").second;
5897 Context newcontext(true, context.textclass);
5898 if (newinsetlayout->forcePlainLayout())
5899 newcontext.layout = &context.textclass.plainLayout();
5900 output_ert(os, arg, newcontext);
5902 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5903 context.latexparam.clear();
5906 // Minted caption insets are not closed here because
5907 // we collect everything into the caption.
5908 if (minted_float.empty())
5913 // The single '=' is meant here.
5914 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5918 context.check_layout(os);
5919 docstring name = newinsetlayout->name();
5920 bool const caption = name.find(from_ascii("Caption:")) == 0;
5922 // Already done for floating minted listings.
5923 if (minted_float.empty()) {
5924 begin_inset(os, "Caption ");
5925 os << to_utf8(name.substr(8)) << '\n';
5928 // FIXME: what do we do if the prefix is not Flex: ?
5929 if (prefixIs(name, from_ascii("Flex:")))
5931 begin_inset(os, "Flex ");
5932 os << to_utf8(name) << '\n'
5933 << "status collapsed\n";
5935 if (!minted_float.empty()) {
5936 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5937 } else if (newinsetlayout->isPassThru()) {
5938 // set catcodes to verbatim early, just in case.
5939 p.setCatcodes(VERBATIM_CATCODES);
5940 string delim = p.get_token().asInput();
5942 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5943 //FIXME: handle error condition
5944 string const arg = p.verbatimStuff("}").second;
5945 Context newcontext(true, context.textclass);
5946 if (newinsetlayout->forcePlainLayout())
5947 newcontext.layout = &context.textclass.plainLayout();
5948 output_ert(os, arg, newcontext);
5950 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5953 // Minted caption insets are not closed here because
5954 // we collect everything into the caption.
5955 if (minted_float.empty())
5960 if (t.cs() == "includepdf") {
5962 string const arg = p.getArg('[', ']');
5963 map<string, string> opts;
5964 vector<string> keys;
5965 split_map(arg, opts, keys);
5966 string name = normalize_filename(p.verbatim_item());
5967 string const path = getMasterFilePath(true);
5968 // We want to preserve relative / absolute filenames,
5969 // therefore path is only used for testing
5970 if (!makeAbsPath(name, path).exists()) {
5971 // The file extension is probably missing.
5972 // Now try to find it out.
5973 char const * const pdfpages_format[] = {"pdf", 0};
5974 string const pdftex_name =
5975 find_file(name, path, pdfpages_format);
5976 if (!pdftex_name.empty()) {
5981 FileName const absname = makeAbsPath(name, path);
5982 if (absname.exists())
5984 fix_child_filename(name);
5985 copy_file(absname, name);
5987 cerr << "Warning: Could not find file '"
5988 << name << "'." << endl;
5990 context.check_layout(os);
5991 begin_inset(os, "External\n\ttemplate ");
5992 os << "PDFPages\n\tfilename "
5994 // parse the options
5995 if (opts.find("pages") != opts.end())
5996 os << "\textra LaTeX \"pages="
5997 << opts["pages"] << "\"\n";
5998 if (opts.find("angle") != opts.end())
5999 os << "\trotateAngle "
6000 << opts["angle"] << '\n';
6001 if (opts.find("origin") != opts.end()) {
6003 string const opt = opts["origin"];
6004 if (opt == "tl") ss << "topleft";
6005 if (opt == "bl") ss << "bottomleft";
6006 if (opt == "Bl") ss << "baselineleft";
6007 if (opt == "c") ss << "center";
6008 if (opt == "tc") ss << "topcenter";
6009 if (opt == "bc") ss << "bottomcenter";
6010 if (opt == "Bc") ss << "baselinecenter";
6011 if (opt == "tr") ss << "topright";
6012 if (opt == "br") ss << "bottomright";
6013 if (opt == "Br") ss << "baselineright";
6014 if (!ss.str().empty())
6015 os << "\trotateOrigin " << ss.str() << '\n';
6017 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
6019 if (opts.find("width") != opts.end())
6021 << translate_len(opts["width"]) << '\n';
6022 if (opts.find("height") != opts.end())
6024 << translate_len(opts["height"]) << '\n';
6025 if (opts.find("keepaspectratio") != opts.end())
6026 os << "\tkeepAspectRatio\n";
6028 context.check_layout(os);
6029 registerExternalTemplatePackages("PDFPages");
6033 if (t.cs() == "loadgame") {
6035 string name = normalize_filename(p.verbatim_item());
6036 string const path = getMasterFilePath(true);
6037 // We want to preserve relative / absolute filenames,
6038 // therefore path is only used for testing
6039 if (!makeAbsPath(name, path).exists()) {
6040 // The file extension is probably missing.
6041 // Now try to find it out.
6042 char const * const lyxskak_format[] = {"fen", 0};
6043 string const lyxskak_name =
6044 find_file(name, path, lyxskak_format);
6045 if (!lyxskak_name.empty())
6046 name = lyxskak_name;
6048 FileName const absname = makeAbsPath(name, path);
6049 if (absname.exists())
6051 fix_child_filename(name);
6052 copy_file(absname, name);
6054 cerr << "Warning: Could not find file '"
6055 << name << "'." << endl;
6056 context.check_layout(os);
6057 begin_inset(os, "External\n\ttemplate ");
6058 os << "ChessDiagram\n\tfilename "
6061 context.check_layout(os);
6062 // after a \loadgame follows a \showboard
6063 if (p.get_token().asInput() == "showboard")
6065 registerExternalTemplatePackages("ChessDiagram");
6069 // try to see whether the string is in unicodesymbols
6070 // Only use text mode commands, since we are in text mode here,
6071 // and math commands may be invalid (bug 6797)
6072 string name = t.asInput();
6073 // handle the dingbats, cyrillic and greek
6074 if (name == "\\textcyr")
6075 name = "\\textcyrillic";
6076 if (name == "\\ding" || name == "\\textcyrillic" ||
6077 (name == "\\textgreek" && !preamble.usePolyglossia()))
6078 name = name + '{' + p.getArg('{', '}') + '}';
6079 // handle the ifsym characters
6080 else if (name == "\\textifsymbol") {
6081 string const optif = p.getFullOpt();
6082 string const argif = p.getArg('{', '}');
6083 name = name + optif + '{' + argif + '}';
6085 // handle the \ascii characters
6086 // the case of \ascii within braces, as LyX outputs it, is already
6087 // handled for t.cat() == catBegin
6088 else if (name == "\\ascii") {
6089 // the code is "\asci\xxx"
6090 name = "{" + name + p.get_token().asInput() + "}";
6093 // handle some TIPA special characters
6094 else if (preamble.isPackageUsed("tipa")) {
6095 if (name == "\\s") {
6096 // fromLaTeXCommand() does not yet
6097 // recognize tipa short cuts
6098 name = "\\textsyllabic";
6099 } else if (name == "\\=" &&
6100 p.next_token().asInput() == "*") {
6101 // fromLaTeXCommand() does not yet
6102 // recognize tipa short cuts
6104 name = "\\textsubbar";
6105 } else if (name == "\\textdoublevertline") {
6106 // FIXME: This is not correct,
6107 // \textvertline is higher than \textbardbl
6108 name = "\\textbardbl";
6110 } else if (name == "\\!" ) {
6111 if (p.next_token().asInput() == "b") {
6112 p.get_token(); // eat 'b'
6115 } else if (p.next_token().asInput() == "d") {
6119 } else if (p.next_token().asInput() == "g") {
6123 } else if (p.next_token().asInput() == "G") {
6125 name = "\\texthtscg";
6127 } else if (p.next_token().asInput() == "j") {
6129 name = "\\texthtbardotlessj";
6131 } else if (p.next_token().asInput() == "o") {
6133 name = "\\textbullseye";
6136 } else if (name == "\\*" ) {
6137 if (p.next_token().asInput() == "k") {
6139 name = "\\textturnk";
6141 } else if (p.next_token().asInput() == "r") {
6142 p.get_token(); // eat 'b'
6143 name = "\\textturnr";
6145 } else if (p.next_token().asInput() == "t") {
6147 name = "\\textturnt";
6149 } else if (p.next_token().asInput() == "w") {
6151 name = "\\textturnw";
6156 if ((name.size() == 2 &&
6157 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6158 p.next_token().asInput() != "*") ||
6159 is_known(name.substr(1), known_tipa_marks)) {
6160 // name is a command that corresponds to a
6161 // combining character in unicodesymbols.
6162 // Append the argument, fromLaTeXCommand()
6163 // will either convert it to a single
6164 // character or a combining sequence.
6165 name += '{' + p.verbatim_item() + '}';
6167 // now get the character from unicodesymbols
6171 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6172 Encodings::TEXT_CMD, termination, rem, &req));
6174 context.check_layout(os);
6177 output_ert_inset(os, to_utf8(rem), context);
6179 skip_spaces_braces(p);
6180 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6181 preamble.registerAutomaticallyLoadedPackage(*it);
6183 //cerr << "#: " << t << " mode: " << mode << endl;
6184 // heuristic: read up to next non-nested space
6186 string s = t.asInput();
6187 string z = p.verbatim_item();
6188 while (p.good() && z != " " && !z.empty()) {
6189 //cerr << "read: " << z << endl;
6191 z = p.verbatim_item();
6193 cerr << "found ERT: " << s << endl;
6194 output_ert_inset(os, s + ' ', context);
6197 if (t.asInput() == name &&
6198 p.next_token().asInput() == "*") {
6199 // Starred commands like \vspace*{}
6200 p.get_token(); // Eat '*'
6203 if (!parse_command(name, p, os, outer, context)) {
6204 output_ert_inset(os, name, context);
6205 // Try to handle options of unknown commands:
6206 // Look if we have optional arguments,
6207 // and if so, put the brackets in ERT.
6208 while (p.hasOpt()) {
6209 p.get_token(); // eat '['
6210 output_ert_inset(os, "[", context);
6211 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6212 output_ert_inset(os, "]", context);
6220 string guessLanguage(Parser & p, string const & lang)
6222 typedef std::map<std::string, size_t> LangMap;
6223 // map from language names to number of characters
6226 for (char const * const * i = supported_CJK_languages; *i; i++)
6227 used[string(*i)] = 0;
6230 Token const t = p.get_token();
6231 // comments are not counted for any language
6232 if (t.cat() == catComment)
6234 // commands are not counted as well, but we need to detect
6235 // \begin{CJK} and switch encoding if needed
6236 if (t.cat() == catEscape) {
6237 if (t.cs() == "inputencoding") {
6238 string const enc = subst(p.verbatim_item(), "\n", " ");
6239 p.setEncoding(enc, Encoding::inputenc);
6242 if (t.cs() != "begin")
6245 // Non-CJK content is counted for lang.
6246 // We do not care about the real language here:
6247 // If we have more non-CJK contents than CJK contents,
6248 // we simply use the language that was specified as
6249 // babel main language.
6250 used[lang] += t.asInput().length();
6253 // Now we are starting an environment
6255 string const name = p.getArg('{', '}');
6256 if (name != "CJK") {
6260 // It is a CJK environment
6262 /* name = */ p.getArg('{', '}');
6263 string const encoding = p.getArg('{', '}');
6264 /* mapping = */ p.getArg('{', '}');
6265 string const encoding_old = p.getEncoding();
6266 char const * const * const where =
6267 is_known(encoding, supported_CJK_encodings);
6269 p.setEncoding(encoding, Encoding::CJK);
6271 p.setEncoding("UTF-8");
6272 string const text = p.ertEnvironment("CJK");
6273 p.setEncoding(encoding_old);
6276 // ignore contents in unknown CJK encoding
6279 // the language of the text
6281 supported_CJK_languages[where - supported_CJK_encodings];
6282 used[cjk] += text.length();
6284 LangMap::const_iterator use = used.begin();
6285 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6286 if (it->second > use->second)
6293 void check_comment_bib(ostream & os, Context & context)
6295 if (!need_commentbib)
6297 // We have a bibliography database, but no bibliography with biblatex
6298 // which is completely valid. Insert a bibtex inset in a note.
6299 context.check_layout(os);
6300 begin_inset(os, "Note Note\n");
6301 os << "status open\n";
6302 os << "\\begin_layout Plain Layout\n";
6303 begin_command_inset(os, "bibtex", "bibtex");
6305 for (auto const & bf : preamble.biblatex_bibliographies) {
6306 if (!bibfiles.empty())
6308 bibfiles += normalize_filename(bf);
6310 if (!bibfiles.empty())
6311 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6313 for (auto const & bf : preamble.biblatex_encodings) {
6314 if (!bibfileencs.empty())
6315 bibfileencs += "\t";
6318 if (!bibfileencs.empty())
6319 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6320 end_inset(os);// Bibtex
6321 os << "\\end_layout\n";
6322 end_inset(os);// Note