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 & 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 newcontext.in_table_cell = context.in_table_cell;
72 output_arguments(os, p, outer, false, string(), newcontext,
74 // If we have a latex param, we eat it here.
75 if (!context.latexparam.empty()) {
77 Context dummy(true, context.textclass);
78 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
79 string(1, context.latexparam.back()));
81 parse_text(p, os, flags, outer, newcontext, rdelim);
83 output_arguments(os, p, outer, false, "post", newcontext,
84 layout->postcommandargs());
85 newcontext.check_end_layout(os);
86 context.cell_align = newcontext.cell_align;
92 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
93 Context const & context, string const & name,
94 string const & rdelim = string())
96 InsetLayout const * layout = 0;
97 DocumentClass::InsetLayouts::const_iterator it =
98 context.textclass.insetLayouts().find(from_ascii(name));
99 if (it != context.textclass.insetLayouts().end())
100 layout = &(it->second);
101 Context newcontext = context;
102 parse_text_in_inset(p, os, flags, outer, newcontext, layout, rdelim);
105 /// parses a paragraph snippet, useful for example for \\emph{...}
106 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
109 Context newcontext(context);
110 // Don't inherit the paragraph-level extra stuff
111 newcontext.par_extra_stuff.clear();
112 parse_text(p, os, flags, outer, newcontext);
113 // Make sure that we don't create invalid .lyx files
114 context.need_layout = newcontext.need_layout;
115 context.need_end_layout = newcontext.need_end_layout;
120 * Thin wrapper around parse_text_snippet() using a string.
122 * We completely ignore \c context.need_layout and \c context.need_end_layout,
123 * because our return value is not used directly (otherwise the stream version
124 * of parse_text_snippet() could be used). That means that the caller needs
125 * to do layout management manually.
126 * This is intended to parse text that does not create any layout changes.
128 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
131 Context newcontext(context);
132 newcontext.need_layout = false;
133 newcontext.need_end_layout = false;
134 newcontext.new_layout_allowed = false;
135 // Avoid warning by Context::~Context()
136 newcontext.par_extra_stuff.clear();
138 parse_text_snippet(p, os, flags, outer, newcontext);
142 string fboxrule = "";
144 string shadow_size = "";
146 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
147 "vpageref", "prettyref", "nameref", "eqref", 0 };
149 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
150 "vpageref", "formatted", "nameref", "eqref", 0 };
152 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
153 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
154 "secref", "subsecref", "tabref", "thmref", 0 };
156 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
157 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
158 "sec", "subsec", "tab", "thm", 0 };
162 * supported CJK encodings
163 * JIS does not work with LyX's encoding conversion
165 const char * const supported_CJK_encodings[] = {
166 "EUC-JP", "KS", "GB", "UTF8",
167 "Bg5", /*"JIS",*/ "SJIS", 0};
170 * the same as supported_CJK_encodings with their corresponding LyX language name
171 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
173 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
174 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
175 * please keep this in sync with supported_CJK_encodings line by line!
177 const char * const supported_CJK_languages[] = {
178 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
179 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
183 * The starred forms are also known except for "citefullauthor",
184 * "citeyear" and "citeyearpar".
186 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
187 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
188 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
192 * No starred form other than "cite*" known.
194 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
195 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
196 // jurabib commands not (yet) supported by LyX:
198 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
199 // "footciteauthor", "footciteyear", "footciteyearpar",
200 "citefield", "citetitle", 0 };
204 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
206 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
207 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
208 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
209 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
210 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
212 // Whether we need to insert a bibtex inset in a comment
213 bool need_commentbib = false;
215 /// LaTeX names for quotes
216 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
217 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
218 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
219 "guilsinglleft", "frq", "guilsinglright", "textquotedblright", "textquotesingle",
222 /// the same as known_quotes with .lyx names
223 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
224 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
225 "gld", "eld", "gls", "ers", "ars",
226 "ars", "als", "als", "erd", "qrs", "qrd", 0};
228 /// LaTeX names for font sizes
229 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
230 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
232 /// the same as known_sizes with .lyx names
233 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
234 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
236 /// LaTeX 2.09 names for font families
237 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
239 /// LaTeX names for font families
240 char const * const known_font_families[] = { "rmfamily", "sffamily",
243 /// LaTeX names for font family changing commands
244 char const * const known_text_font_families[] = { "textrm", "textsf",
247 /// The same as known_old_font_families, known_font_families and
248 /// known_text_font_families with .lyx names
249 char const * const known_coded_font_families[] = { "roman", "sans",
252 /// LaTeX 2.09 names for font series
253 char const * const known_old_font_series[] = { "bf", 0};
255 /// LaTeX names for font series
256 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
258 /// LaTeX names for font series changing commands
259 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
261 /// The same as known_old_font_series, known_font_series and
262 /// known_text_font_series with .lyx names
263 char const * const known_coded_font_series[] = { "bold", "medium", 0};
265 /// LaTeX 2.09 names for font shapes
266 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
268 /// LaTeX names for font shapes
269 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
272 /// LaTeX names for font shape changing commands
273 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
276 /// The same as known_old_font_shapes, known_font_shapes and
277 /// known_text_font_shapes with .lyx names
278 char const * const known_coded_font_shapes[] = { "italic", "slanted",
279 "smallcaps", "up", 0};
281 /// Known special characters which need skip_spaces_braces() afterwards
282 char const * const known_special_chars[] = {"ldots",
283 "lyxarrow", "textcompwordmark",
284 "slash", "textasciitilde", "textasciicircum", "textbackslash",
285 "LyX", "TeX", "LaTeXe",
288 /// special characters from known_special_chars which may have a \\protect before
289 char const * const known_special_protect_chars[] = {"LyX", "TeX",
290 "LaTeXe", "LaTeX", 0};
292 /// the same as known_special_chars with .lyx names
293 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
294 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
295 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
296 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
297 "\\SpecialChar LaTeX\n", 0};
300 * Graphics file extensions known by the dvips driver of the graphics package.
301 * These extensions are used to complete the filename of an included
302 * graphics file if it does not contain an extension.
303 * The order must be the same that latex uses to find a file, because we
304 * will use the first extension that matches.
305 * This is only an approximation for the common cases. If we would want to
306 * do it right in all cases, we would need to know which graphics driver is
307 * used and know the extensions of every driver of the graphics package.
309 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
310 "ps.gz", "eps.Z", "ps.Z", 0};
313 * Graphics file extensions known by the pdftex driver of the graphics package.
314 * \sa known_dvips_graphics_formats
316 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
320 * Known file extensions for TeX files as used by \\include.
322 char const * const known_tex_extensions[] = {"tex", 0};
324 /// spaces known by InsetSpace
325 char const * const known_spaces[] = { " ", "space",
326 ",", "thinspace",// \\, = \\thinspace
327 "quad", "qquad", "enspace", "enskip",
328 ";", ">", "medspace",// \\; = \\> = \\medspace
329 ":", "thickspace",// \\: = \\thickspace
330 "!", "negthinspace",// \\! = \\negthinspace
331 "negmedspace", "negthickspace",
332 "textvisiblespace", "hfill", "dotfill", "hrulefill", "leftarrowfill",
333 "rightarrowfill", "upbracefill", "downbracefill", 0};
335 /// the same as known_spaces with .lyx names
336 char const * const known_coded_spaces[] = { "space{}", "space{}",
337 "thinspace{}", "thinspace{}",
338 "quad{}", "qquad{}", "enspace{}", "enskip{}",
339 "medspace{}", "medspace{}", "medspace{}",
340 "thickspace{}", "thickspace{}",
341 "negthinspace{}", "negthinspace{}",
342 "negmedspace{}", "negthickspace{}",
343 "textvisiblespace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
344 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
346 /// known TIPA combining diacritical marks
347 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
348 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
349 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
350 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
351 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
352 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
353 "textsubring", "textsubbar", 0};
355 /// TIPA tones that need special handling
356 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
358 // string to store the float type to be able to determine the type of subfloats
359 string float_type = "";
361 // string to store the float status of minted listings
362 string minted_float = "";
364 // whether a caption has been parsed for a floating minted listing
365 bool minted_float_has_caption = false;
367 // The caption for non-floating minted listings
368 string minted_nonfloat_caption = "";
370 // Characters that have to be escaped by \\ in LaTeX
371 char const * const known_escaped_chars[] = {
372 "&", "_", "$", "%", "#", "^", "{", "}", 0};
375 /// splits "x=z, y=b" into a map and an ordered keyword vector
376 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
381 keys.resize(v.size());
382 for (size_t i = 0; i < v.size(); ++i) {
383 size_t const pos = v[i].find('=');
384 string const index = trimSpaceAndEol(v[i].substr(0, pos));
385 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
393 * Split a LaTeX length into value and unit.
394 * The latter can be a real unit like "pt", or a latex length variable
395 * like "\textwidth". The unit may contain additional stuff like glue
396 * lengths, but we don't care, because such lengths are ERT anyway.
397 * \returns true if \p value and \p unit are valid.
399 bool splitLatexLength(string const & len, string & value, string & unit)
403 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
404 //'4,5' is a valid LaTeX length number. Change it to '4.5'
405 string const length = subst(len, ',', '.');
406 if (i == string::npos)
409 if (len[0] == '\\') {
410 // We had something like \textwidth without a factor
416 value = trimSpaceAndEol(string(length, 0, i));
420 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
421 if (contains(len, '\\'))
422 unit = trimSpaceAndEol(string(len, i));
424 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
429 /// A simple function to translate a latex length to something LyX can
430 /// understand. Not perfect, but rather best-effort.
431 bool translate_len(string const & length, string & valstring, string & unit)
433 if (!splitLatexLength(length, valstring, unit))
435 // LyX uses percent values
437 istringstream iss(valstring);
442 string const percentval = oss.str();
444 if (unit.empty() || unit[0] != '\\')
446 string::size_type const i = unit.find(' ');
447 string const endlen = (i == string::npos) ? string() : string(unit, i);
448 if (unit == "\\textwidth") {
449 valstring = percentval;
450 unit = "text%" + endlen;
451 } else if (unit == "\\columnwidth") {
452 valstring = percentval;
453 unit = "col%" + endlen;
454 } else if (unit == "\\paperwidth") {
455 valstring = percentval;
456 unit = "page%" + endlen;
457 } else if (unit == "\\linewidth") {
458 valstring = percentval;
459 unit = "line%" + endlen;
460 } else if (unit == "\\paperheight") {
461 valstring = percentval;
462 unit = "pheight%" + endlen;
463 } else if (unit == "\\textheight") {
464 valstring = percentval;
465 unit = "theight%" + endlen;
466 } else if (unit == "\\baselineskip") {
467 valstring = percentval;
468 unit = "baselineskip%" + endlen;
474 /// If we have ambiguous quotation marks, make a smart guess
475 /// based on main quote style
476 string guessQuoteStyle(string const & in, bool const opening)
479 if (prefixIs(in, "qr")) {// straight quote
481 res = subst(res, "r", "l");
482 } else if (in == "eld") {// ``
483 if (preamble.quotesStyle() == "german")
485 else if (preamble.quotesStyle() == "british")
487 else if (preamble.quotesStyle() == "french")
489 else if (preamble.quotesStyle() == "russian")
491 } else if (in == "erd") {// ''
492 if (preamble.quotesStyle() == "polish")
494 else if (preamble.quotesStyle() == "british")
496 else if (preamble.quotesStyle() == "french")
498 else if (preamble.quotesStyle() == "hungarian")
500 else if (preamble.quotesStyle() == "swedish")
501 res = opening ? "sld" : "srd";
502 } else if (in == "els") {// `
503 if (preamble.quotesStyle() == "german")
505 else if (preamble.quotesStyle() == "british")
507 } else if (in == "ers") {// '
508 if (preamble.quotesStyle() == "polish")
510 else if (preamble.quotesStyle() == "british")
512 else if (preamble.quotesStyle() == "swedish")
513 res = opening ? "sls" : "srs";
514 } else if (in == "ard") {// >>
515 if (preamble.quotesStyle() == "swiss")
517 else if (preamble.quotesStyle() == "french")
519 else if (preamble.quotesStyle() == "russian")
521 else if (preamble.quotesStyle() == "hungarian")
523 } else if (in == "ald") {// <<
524 if (preamble.quotesStyle() == "swiss")
526 else if (preamble.quotesStyle() == "french")
528 else if (preamble.quotesStyle() == "russian")
530 else if (preamble.quotesStyle() == "hungarian")
532 } else if (in == "ars") {// >
533 if (preamble.quotesStyle() == "swiss")
535 } else if (in == "als") {// <
536 if (preamble.quotesStyle() == "swiss")
538 } else if (in == "gld") {// ,,
539 if (preamble.quotesStyle() == "polish")
541 else if (preamble.quotesStyle() == "hungarian")
543 else if (preamble.quotesStyle() == "russian")
545 } else if (in == "gls") {// ,
546 if (preamble.quotesStyle() == "polish")
553 string const fromPolyglossiaEnvironment(string const & s)
555 // Since \arabic is taken by the LaTeX kernel,
556 // the Arabic polyglossia environment is upcased
564 string uncapitalize(string const & s)
566 docstring in = from_ascii(s);
567 char_type t = lowercase(s[0]);
573 bool isCapitalized(string const & s)
575 docstring in = from_ascii(s);
576 char_type t = uppercase(s[0]);
578 return to_ascii(in) == s;
585 string translate_len(string const & length)
589 if (translate_len(length, value, unit))
591 // If the input is invalid, return what we have.
599 * Translates a LaTeX length into \p value, \p unit and
600 * \p special parts suitable for a box inset.
601 * The difference from translate_len() is that a box inset knows about
602 * some special "units" that are stored in \p special.
604 void translate_box_len(string const & length, string & value, string & unit, string & special)
606 if (translate_len(length, value, unit)) {
607 if (unit == "\\height" || unit == "\\depth" ||
608 unit == "\\totalheight" || unit == "\\width") {
609 special = unit.substr(1);
610 // The unit is not used, but LyX requires a dummy setting
622 void begin_inset(ostream & os, string const & name)
624 os << "\n\\begin_inset " << name;
628 void begin_command_inset(ostream & os, string const & name,
629 string const & latexname)
631 begin_inset(os, "CommandInset ");
632 os << name << "\nLatexCommand " << latexname << '\n';
636 void end_inset(ostream & os)
638 os << "\n\\end_inset\n\n";
642 bool skip_braces(Parser & p)
644 if (p.next_token().cat() != catBegin)
647 if (p.next_token().cat() == catEnd) {
656 /// replace LaTeX commands in \p s from the unicodesymbols file with their
658 pair<bool, docstring> convert_unicodesymbols(docstring s)
662 for (size_t i = 0; i < s.size();) {
671 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
672 Encodings::TEXT_CMD, termination, rem, &req));
673 set<string>::const_iterator it = req.begin();
674 set<string>::const_iterator en = req.end();
675 for (; it != en; ++it)
676 preamble.registerAutomaticallyLoadedPackage(*it);
679 if (s.empty() || s[0] != '\\')
683 for (auto const & c : known_escaped_chars)
684 if (c != 0 && prefixIs(s, from_ascii("\\") + c))
689 return make_pair(res, os.str());
693 /// try to convert \p s to a valid InsetCommand argument
694 /// return whether this succeeded. If not, these command insets
695 /// get the "literate" flag.
696 pair<bool, string> convert_latexed_command_inset_arg(string s)
698 bool success = false;
700 // since we don't know the input encoding we can't use from_utf8
701 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
703 s = to_utf8(res.second);
705 // LyX cannot handle newlines in a latex command
706 return make_pair(success, subst(s, "\n", " "));
709 /// try to convert \p s to a valid InsetCommand argument
710 /// without trying to recode macros.
711 string convert_literate_command_inset_arg(string const & s)
713 // LyX cannot handle newlines in a latex command
714 return subst(s, "\n", " ");
717 void output_ert(ostream & os, string const & s, Context & context)
719 context.check_layout(os);
720 for (char const c : s) {
722 os << "\n\\backslash\n";
723 else if (c == '\n') {
724 context.new_paragraph(os);
725 context.check_layout(os);
729 context.check_end_layout(os);
733 void output_ert_inset(ostream & os, string const & s, Context & context)
735 // We must have a valid layout before outputting the ERT inset.
736 context.check_layout(os);
737 Context newcontext(true, context.textclass);
738 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
739 if (layout.forcePlainLayout())
740 newcontext.layout = &context.textclass.plainLayout();
741 begin_inset(os, "ERT");
742 os << "\nstatus collapsed\n";
743 output_ert(os, s, newcontext);
748 void output_comment(Parser & p, ostream & os, string const & s,
751 if (p.next_token().cat() == catNewline)
752 output_ert_inset(os, '%' + s, context);
754 output_ert_inset(os, '%' + s + '\n', context);
758 Layout const * findLayout(TextClass const & textclass, string const & name, bool command,
759 string const & latexparam = string())
761 Layout const * layout = findLayoutWithoutModule(textclass, name, command, latexparam);
764 if (checkModule(name, command))
765 return findLayoutWithoutModule(textclass, name, command, latexparam);
770 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command,
771 string const & latexparam = string())
773 InsetLayout const * insetlayout =
774 findInsetLayoutWithoutModule(textclass, name, command, latexparam);
777 if (checkModule(name, command))
778 return findInsetLayoutWithoutModule(textclass, name, command, latexparam);
783 void eat_whitespace(Parser &, ostream &, Context &, bool eatParagraph,
784 bool eatNewline = true);
788 * Skips whitespace and braces.
789 * This should be called after a command has been parsed that is not put into
790 * ERT, and where LyX adds "{}" if needed.
792 void skip_spaces_braces(Parser & p, bool keepws = false)
794 /* The following four examples produce the same typeset output and
795 should be handled by this function:
803 // Unfortunately we need to skip comments, too.
804 // We can't use eat_whitespace since writing them after the {}
805 // results in different output in some cases.
806 bool const skipped_spaces = p.skip_spaces(true);
807 bool const skipped_braces = skip_braces(p);
808 if (keepws && skipped_spaces && !skipped_braces)
809 // put back the space (it is better handled by check_space)
810 p.unskip_spaces(true);
814 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, string const & prefix,
815 Context & context, Layout::LaTeXArgMap const & latexargs)
817 if (context.layout->latextype != LATEX_ITEM_ENVIRONMENT || !prefix.empty()) {
819 context.check_layout(os);
825 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
826 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
827 for (; lait != laend; ++lait) {
829 eat_whitespace(p, os, context, false);
830 if (lait->second.mandatory) {
831 if (p.next_token().cat() != catBegin)
833 string ldelim = to_utf8(lait->second.ldelim);
834 string rdelim = to_utf8(lait->second.rdelim);
839 p.get_token(); // eat ldelim
840 if (ldelim.size() > 1)
841 p.get_token(); // eat ldelim
843 context.check_layout(os);
846 begin_inset(os, "Argument ");
849 os << i << "\nstatus collapsed\n\n";
850 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
853 string ldelim = to_utf8(lait->second.ldelim);
854 string rdelim = to_utf8(lait->second.rdelim);
859 string tok = p.next_token().asInput();
860 // we only support delimiters with max 2 chars for now.
861 if (ldelim.size() > 1)
862 tok += p.next_next_token().asInput();
863 if (p.next_token().cat() == catEscape || tok != ldelim)
865 p.get_token(); // eat ldelim
866 if (ldelim.size() > 1)
867 p.get_token(); // eat ldelim
869 context.check_layout(os);
872 begin_inset(os, "Argument ");
875 os << i << "\nstatus collapsed\n\n";
876 parse_text_in_inset(p, os, FLAG_RDELIM, outer, context, 0, rdelim);
879 eat_whitespace(p, os, context, false);
884 void output_command_layout(ostream & os, Parser & p, bool outer,
885 Context & parent_context,
886 Layout const * newlayout)
888 TeXFont const oldFont = parent_context.font;
889 // save the current font size
890 string const size = oldFont.size;
891 // reset the font size to default, because the font size switches
892 // don't affect section headings and the like
893 parent_context.font.size = Context::normalfont.size;
894 // we only need to write the font change if we have an open layout
895 if (!parent_context.atParagraphStart())
896 output_font_change(os, oldFont, parent_context.font);
897 parent_context.check_end_layout(os);
898 Context context(true, parent_context.textclass, newlayout,
899 parent_context.layout, parent_context.font);
900 if (parent_context.deeper_paragraph) {
901 // We are beginning a nested environment after a
902 // deeper paragraph inside the outer list environment.
903 // Therefore we don't need to output a "begin deeper".
904 context.need_end_deeper = true;
906 context.check_deeper(os);
907 output_arguments(os, p, outer, true, string(), context,
908 context.layout->latexargs());
909 // If we have a latex param, we eat it here.
910 if (!parent_context.latexparam.empty()) {
912 Context dummy(true, parent_context.textclass);
913 parse_text(p, oss, FLAG_RDELIM, outer, dummy,
914 string(1, parent_context.latexparam.back()));
916 parse_text(p, os, FLAG_ITEM, outer, context);
917 output_arguments(os, p, outer, false, "post", context,
918 context.layout->postcommandargs());
919 context.check_end_layout(os);
920 if (parent_context.deeper_paragraph) {
921 // We must suppress the "end deeper" because we
922 // suppressed the "begin deeper" above.
923 context.need_end_deeper = false;
925 context.check_end_deeper(os);
926 // We don't need really a new paragraph, but
927 // we must make sure that the next item gets a \begin_layout.
928 parent_context.new_paragraph(os);
929 // Set the font size to the original value. No need to output it here
930 // (Context::begin_layout() will do that if needed)
931 parent_context.font.size = size;
936 * Output a space if necessary.
937 * This function gets called for every whitespace token.
939 * We have three cases here:
940 * 1. A space must be suppressed. Example: The lyxcode case below
941 * 2. A space may be suppressed. Example: Spaces before "\par"
942 * 3. A space must not be suppressed. Example: A space between two words
944 * We currently handle only 1. and 3 and from 2. only the case of
945 * spaces before newlines as a side effect.
947 * 2. could be used to suppress as many spaces as possible. This has two effects:
948 * - Reimporting LyX generated LaTeX files changes almost no whitespace
949 * - Superfluous whitespace from non LyX generated LaTeX files is removed.
950 * The drawback is that the logic inside the function becomes
951 * complicated, and that is the reason why it is not implemented.
953 void check_space(Parser & p, ostream & os, Context & context)
955 Token const next = p.next_token();
956 Token const curr = p.curr_token();
957 // A space before a single newline and vice versa must be ignored
958 // LyX emits a newline before \end{lyxcode}.
959 // This newline must be ignored,
960 // otherwise LyX will add an additional protected space.
961 if (next.cat() == catSpace ||
962 next.cat() == catNewline ||
963 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
966 context.check_layout(os);
972 * Parse all arguments of \p command
974 void parse_arguments(string const & command,
975 vector<ArgumentType> const & template_arguments,
976 Parser & p, ostream & os, bool outer, Context & context)
978 string ert = command;
979 size_t no_arguments = template_arguments.size();
980 for (size_t i = 0; i < no_arguments; ++i) {
981 switch (template_arguments[i]) {
984 // This argument contains regular LaTeX
985 output_ert_inset(os, ert + '{', context);
986 eat_whitespace(p, os, context, false);
987 if (template_arguments[i] == required)
988 parse_text(p, os, FLAG_ITEM, outer, context);
990 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
994 // This argument consists only of a single item.
995 // The presence of '{' or not must be preserved.
997 if (p.next_token().cat() == catBegin)
998 ert += '{' + p.verbatim_item() + '}';
1000 ert += p.verbatim_item();
1004 // This argument may contain special characters
1005 ert += '{' + p.verbatim_item() + '}';
1009 // true because we must not eat whitespace
1010 // if an optional arg follows we must not strip the
1011 // brackets from this one
1012 if (i < no_arguments - 1 &&
1013 template_arguments[i+1] == optional)
1014 ert += p.getFullOpt(true);
1016 ert += p.getOpt(true);
1020 output_ert_inset(os, ert, context);
1025 * Check whether \p command is a known command. If yes,
1026 * handle the command with all arguments.
1027 * \return true if the command was parsed, false otherwise.
1029 bool parse_command(string const & command, Parser & p, ostream & os,
1030 bool outer, Context & context)
1032 if (known_commands.find(command) != known_commands.end()) {
1033 parse_arguments(command, known_commands[command], p, os,
1041 /// Parses a minipage or parbox
1042 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
1043 unsigned inner_flags, bool outer, Context & parent_context,
1044 string const & outer_type, string const & special,
1045 string inner_type, string const & frame_color,
1046 string const & background_color)
1050 string hor_pos = "l";
1051 // We need to set the height to the LaTeX default of 1\\totalheight
1052 // for the case when no height argument is given
1053 string height_value = "1";
1054 string height_unit = "in";
1055 string height_special = "totalheight";
1056 string latex_height;
1060 string width_special = "none";
1061 string thickness = "0.4pt";
1062 if (!fboxrule.empty())
1063 thickness = fboxrule;
1065 thickness = "0.4pt";
1067 if (!fboxsep.empty())
1068 separation = fboxsep;
1072 if (!shadow_size.empty())
1073 shadowsize = shadow_size;
1076 string framecolor = "black";
1077 string backgroundcolor = "none";
1078 if (!frame_color.empty())
1079 framecolor = frame_color;
1080 if (!background_color.empty())
1081 backgroundcolor = background_color;
1082 // if there is a color box around the \begin statements have not yet been parsed
1084 if (!frame_color.empty() || !background_color.empty()) {
1085 eat_whitespace(p, os, parent_context, false);
1086 p.get_token().asInput(); // the '{'
1088 if (p.next_token().asInput() == "\\begin") {
1089 p.get_token().asInput();
1091 inner_type = "minipage";
1092 inner_flags = FLAG_END;
1093 active_environments.push_back("minipage");
1096 else if (p.next_token().asInput() == "\\parbox") {
1097 p.get_token().asInput();
1098 inner_type = "parbox";
1099 inner_flags = FLAG_ITEM;
1102 else if (p.next_token().asInput() == "\\makebox") {
1103 p.get_token().asInput();
1104 inner_type = "makebox";
1105 inner_flags = FLAG_ITEM;
1107 // in case there is just \colorbox{color}{text}
1110 inner_type = "makebox";
1111 inner_flags = FLAG_BRACE_LAST;
1116 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1118 if (!inner_type.empty() && p.hasOpt()) {
1119 if (inner_type != "makebox")
1120 position = p.getArg('[', ']');
1122 latex_width = p.getArg('[', ']');
1123 translate_box_len(latex_width, width_value, width_unit, width_special);
1126 if (position != "t" && position != "c" && position != "b") {
1127 cerr << "invalid position " << position << " for "
1128 << inner_type << endl;
1132 if (inner_type != "makebox") {
1133 latex_height = p.getArg('[', ']');
1134 translate_box_len(latex_height, height_value, height_unit, height_special);
1136 string const opt = p.getArg('[', ']');
1139 if (hor_pos != "l" && hor_pos != "c" &&
1140 hor_pos != "r" && hor_pos != "s") {
1141 cerr << "invalid hor_pos " << hor_pos
1142 << " for " << inner_type << endl;
1149 inner_pos = p.getArg('[', ']');
1150 if (inner_pos != "c" && inner_pos != "t" &&
1151 inner_pos != "b" && inner_pos != "s") {
1152 cerr << "invalid inner_pos "
1153 << inner_pos << " for "
1154 << inner_type << endl;
1155 inner_pos = position;
1159 if (inner_type == "makebox")
1163 if (inner_type.empty()) {
1164 if (special.empty() && outer_type != "framebox")
1165 latex_width = "1\\columnwidth";
1168 latex_width = p2.getArg('[', ']');
1169 string const opt = p2.getArg('[', ']');
1172 if (hor_pos != "l" && hor_pos != "c" &&
1173 hor_pos != "r" && hor_pos != "s") {
1174 cerr << "invalid hor_pos " << hor_pos
1175 << " for " << outer_type << endl;
1179 if (outer_type == "framebox")
1183 } else if (inner_type != "makebox")
1184 latex_width = p.verbatim_item();
1185 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1186 // as this is LyX's standard for such cases (except for makebox)
1187 // \framebox is more special and handled below
1188 if (latex_width.empty() && inner_type != "makebox"
1189 && outer_type != "framebox")
1190 latex_width = "1\\columnwidth";
1192 translate_len(latex_width, width_value, width_unit);
1194 bool shadedparbox = false;
1195 if (inner_type == "shaded") {
1196 eat_whitespace(p, os, parent_context, false);
1197 if (outer_type == "parbox") {
1199 if (p.next_token().cat() == catBegin)
1201 eat_whitespace(p, os, parent_context, false);
1202 shadedparbox = true;
1207 // If we already read the inner box we have to push the inner env
1208 if (!outer_type.empty() && !inner_type.empty() &&
1209 (inner_flags & FLAG_END))
1210 active_environments.push_back(inner_type);
1211 bool use_ert = false;
1212 if (!outer_type.empty() && !inner_type.empty()) {
1213 // Look whether there is some content after the end of the
1214 // inner box, but before the end of the outer box.
1215 // If yes, we need to output ERT.
1217 if (inner_flags & FLAG_END)
1218 p.ertEnvironment(inner_type);
1221 p.skip_spaces(true);
1222 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1223 if ((outer_env && p.next_token().asInput() != "\\end") ||
1224 (!outer_env && p.next_token().cat() != catEnd)) {
1225 // something is between the end of the inner box and
1226 // the end of the outer box, so we need to use ERT.
1234 if (!outer_type.empty()) {
1235 if (outer_flags & FLAG_END)
1236 ss << "\\begin{" << outer_type << '}';
1238 ss << '\\' << outer_type << '{';
1239 if (!special.empty())
1243 if (!inner_type.empty()) {
1244 if (inner_type != "shaded") {
1245 if (inner_flags & FLAG_END)
1246 ss << "\\begin{" << inner_type << '}';
1248 ss << '\\' << inner_type;
1250 if (!position.empty())
1251 ss << '[' << position << ']';
1252 if (!latex_height.empty())
1253 ss << '[' << latex_height << ']';
1254 if (!inner_pos.empty())
1255 ss << '[' << inner_pos << ']';
1256 ss << '{' << latex_width << '}';
1257 if (!(inner_flags & FLAG_END))
1260 if (inner_type == "shaded")
1261 ss << "\\begin{shaded}";
1262 output_ert_inset(os, ss.str(), parent_context);
1263 if (!inner_type.empty()) {
1264 parse_text(p, os, inner_flags, outer, parent_context);
1265 if (inner_flags & FLAG_END)
1266 output_ert_inset(os, "\\end{" + inner_type + '}',
1269 output_ert_inset(os, "}", parent_context);
1271 if (!outer_type.empty()) {
1272 // If we already read the inner box we have to pop
1274 if (!inner_type.empty() && (inner_flags & FLAG_END))
1275 active_environments.pop_back();
1277 // Ensure that the end of the outer box is parsed correctly:
1278 // The opening brace has been eaten by parse_outer_box()
1279 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1280 outer_flags &= ~FLAG_ITEM;
1281 outer_flags |= FLAG_BRACE_LAST;
1283 parse_text(p, os, outer_flags, outer, parent_context);
1284 if (outer_flags & FLAG_END)
1285 output_ert_inset(os, "\\end{" + outer_type + '}',
1288 output_ert_inset(os, "}", parent_context);
1291 // LyX does not like empty positions, so we have
1292 // to set them to the LaTeX default values here.
1293 if (position.empty())
1295 if (inner_pos.empty())
1296 inner_pos = position;
1297 parent_context.check_layout(os);
1298 begin_inset(os, "Box ");
1299 if (outer_type == "framed")
1301 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1303 else if (outer_type == "shadowbox")
1304 os << "Shadowbox\n";
1305 else if ((outer_type == "shaded" && inner_type.empty()) ||
1306 (outer_type == "minipage" && inner_type == "shaded") ||
1307 (outer_type == "parbox" && inner_type == "shaded")) {
1309 preamble.registerAutomaticallyLoadedPackage("color");
1310 } else if (outer_type == "doublebox")
1311 os << "Doublebox\n";
1312 else if (outer_type.empty() || outer_type == "mbox")
1313 os << "Frameless\n";
1315 os << outer_type << '\n';
1316 os << "position \"" << position << "\"\n";
1317 os << "hor_pos \"" << hor_pos << "\"\n";
1318 if (outer_type == "mbox")
1319 os << "has_inner_box 1\n";
1320 else if (!frame_color.empty() && inner_type == "makebox")
1321 os << "has_inner_box 0\n";
1323 os << "has_inner_box " << !inner_type.empty() << "\n";
1324 os << "inner_pos \"" << inner_pos << "\"\n";
1325 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1327 if (outer_type == "mbox")
1328 os << "use_makebox 1\n";
1329 else if (!frame_color.empty())
1330 os << "use_makebox 0\n";
1332 os << "use_makebox " << (inner_type == "makebox") << '\n';
1333 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1334 os << "width \"\"\n";
1335 // for values like "1.5\width" LyX uses "1.5in" as width and sets "width" as special
1336 else if (contains(width_unit, '\\'))
1337 os << "width \"" << width_value << "in" << "\"\n";
1339 os << "width \"" << width_value << width_unit << "\"\n";
1340 if (contains(width_unit, '\\')) {
1341 width_unit.erase (0,1); // remove the leading '\'
1342 os << "special \"" << width_unit << "\"\n";
1344 os << "special \"" << width_special << "\"\n";
1345 if (contains(height_unit, '\\'))
1346 os << "height \"" << height_value << "in" << "\"\n";
1348 os << "height \"" << height_value << height_unit << "\"\n";
1349 os << "height_special \"" << height_special << "\"\n";
1350 os << "thickness \"" << thickness << "\"\n";
1351 os << "separation \"" << separation << "\"\n";
1352 os << "shadowsize \"" << shadowsize << "\"\n";
1353 os << "framecolor \"" << framecolor << "\"\n";
1354 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1355 os << "status open\n\n";
1357 // Unfortunately we can't use parse_text_in_inset:
1358 // InsetBox::forcePlainLayout() is hard coded and does not
1359 // use the inset layout. Apart from that do we call parse_text
1360 // up to two times, but need only one check_end_layout.
1361 bool const forcePlainLayout =
1362 (!inner_type.empty() || inner_type == "makebox") &&
1363 outer_type != "shaded" && outer_type != "framed";
1364 Context context(true, parent_context.textclass);
1365 if (forcePlainLayout)
1366 context.layout = &context.textclass.plainLayout();
1368 context.font = parent_context.font;
1370 // If we have no inner box the contents will be read with the outer box
1371 if (!inner_type.empty())
1372 parse_text(p, os, inner_flags, outer, context);
1374 // Ensure that the end of the outer box is parsed correctly:
1375 // The opening brace has been eaten by parse_outer_box()
1376 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1377 outer_flags &= ~FLAG_ITEM;
1378 outer_flags |= FLAG_BRACE_LAST;
1381 // Find end of outer box, output contents if inner_type is
1382 // empty and output possible comments
1383 if (!outer_type.empty()) {
1384 // If we already read the inner box we have to pop
1386 if (!inner_type.empty() && (inner_flags & FLAG_END))
1387 active_environments.pop_back();
1388 // This does not output anything but comments if
1389 // inner_type is not empty (see use_ert)
1390 parse_text(p, os, outer_flags, outer, context);
1393 context.check_end_layout(os);
1395 #ifdef PRESERVE_LAYOUT
1396 // LyX puts a % after the end of the minipage
1397 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1399 //output_comment(p, os, "dummy", parent_context);
1402 parent_context.new_paragraph(os);
1404 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1405 //output_comment(p, os, "dummy", parent_context);
1408 // We add a protected space if something real follows
1409 if (p.good() && p.next_token().cat() != catComment) {
1410 begin_inset(os, "space ~\n");
1416 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1417 active_environments.pop_back();
1418 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1419 // in this case we have to eat the the closing brace of the color box
1420 p.get_token().asInput(); // the '}'
1422 if (p.next_token().asInput() == "}") {
1423 // in this case we assume that the closing brace is from the box settings
1424 // therefore reset these values for the next box
1430 // all boxes except of Frameless and Shaded require calc
1431 if (!(outer_type.empty() || outer_type == "mbox") &&
1432 !((outer_type == "shaded" && inner_type.empty()) ||
1433 (outer_type == "minipage" && inner_type == "shaded") ||
1434 (outer_type == "parbox" && inner_type == "shaded")))
1435 preamble.registerAutomaticallyLoadedPackage("calc");
1439 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1440 Context & parent_context, string const & outer_type,
1441 string const & special)
1443 eat_whitespace(p, os, parent_context, false);
1444 if (flags & FLAG_ITEM) {
1446 if (p.next_token().cat() == catBegin)
1449 cerr << "Warning: Ignoring missing '{' after \\"
1450 << outer_type << '.' << endl;
1451 eat_whitespace(p, os, parent_context, false);
1454 unsigned int inner_flags = 0;
1456 if (outer_type == "minipage" || outer_type == "parbox") {
1457 p.skip_spaces(true);
1458 while (p.hasOpt()) {
1460 p.skip_spaces(true);
1463 p.skip_spaces(true);
1464 if (outer_type == "parbox") {
1466 if (p.next_token().cat() == catBegin)
1468 p.skip_spaces(true);
1471 if (outer_type == "shaded" || outer_type == "mbox") {
1472 // These boxes never have an inner box
1474 } else if (p.next_token().asInput() == "\\parbox") {
1475 inner = p.get_token().cs();
1476 inner_flags = FLAG_ITEM;
1477 } else if (p.next_token().asInput() == "\\begin") {
1478 // Is this a minipage or shaded box?
1481 inner = p.getArg('{', '}');
1483 if (inner == "minipage" || inner == "shaded")
1484 inner_flags = FLAG_END;
1489 if (inner_flags == FLAG_END) {
1490 if (inner != "shaded")
1494 eat_whitespace(p, os, parent_context, false);
1496 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1497 outer_type, special, inner, "", "");
1499 if (inner_flags == FLAG_ITEM) {
1501 eat_whitespace(p, os, parent_context, false);
1503 parse_box(p, os, flags, inner_flags, outer, parent_context,
1504 outer_type, special, inner, "", "");
1509 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1510 bool in_line, bool use_minted)
1512 parent_context.check_layout(os);
1513 begin_inset(os, "listings\n");
1514 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1516 while ((i = arg.find(", ")) != string::npos
1517 || (i = arg.find(",\t")) != string::npos)
1518 arg.erase(i + 1, 1);
1521 string const language = p.getArg('{', '}');
1522 p.skip_spaces(true);
1523 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1524 if (!minted_float.empty()) {
1525 arg += string(arg.empty() ? "" : ",") + minted_float;
1526 minted_nonfloat_caption.clear();
1530 os << "lstparams " << '"' << arg << '"' << '\n';
1531 if (arg.find("\\color") != string::npos)
1532 preamble.registerAutomaticallyLoadedPackage("color");
1535 os << "inline true\n";
1537 os << "inline false\n";
1538 os << "status open\n";
1539 Context context(true, parent_context.textclass);
1540 context.layout = &parent_context.textclass.plainLayout();
1541 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1542 minted_nonfloat_caption.erase(0,3);
1543 os << "\n\\begin_layout Plain Layout\n";
1544 begin_inset(os, "Caption Standard\n");
1545 Context newcontext(true, context.textclass,
1546 context.layout, 0, context.font);
1547 newcontext.check_layout(os);
1548 os << minted_nonfloat_caption << "\n";
1549 newcontext.check_end_layout(os);
1551 os << "\n\\end_layout\n";
1552 minted_nonfloat_caption.clear();
1556 // set catcodes to verbatim early, just in case.
1557 p.setCatcodes(VERBATIM_CATCODES);
1558 string delim = p.get_token().asInput();
1559 //FIXME: handler error condition
1560 s = p.verbatimStuff(delim).second;
1561 // context.new_paragraph(os);
1562 } else if (use_minted) {
1563 s = p.verbatimEnvironment("minted");
1565 s = p.verbatimEnvironment("lstlisting");
1567 output_ert(os, s, context);
1568 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1569 minted_nonfloat_caption.erase(0,3);
1570 os << "\n\\begin_layout Plain Layout\n";
1571 begin_inset(os, "Caption Standard\n");
1572 Context newcontext(true, context.textclass,
1573 context.layout, 0, context.font);
1574 newcontext.check_layout(os);
1575 os << minted_nonfloat_caption << "\n";
1576 newcontext.check_end_layout(os);
1578 os << "\n\\end_layout\n";
1579 minted_nonfloat_caption.clear();
1581 // Don't close the inset here for floating minted listings.
1582 // It will be closed at the end of the listing environment.
1583 if (!use_minted || minted_float.empty())
1586 eat_whitespace(p, os, parent_context, true);
1587 Token t = p.get_token();
1588 if (t.asInput() != "\\end") {
1589 // If anything follows, collect it into a caption.
1590 minted_float_has_caption = true;
1591 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1592 begin_inset(os, "Caption Standard\n");
1593 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1600 /// parse an unknown environment
1601 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1602 unsigned flags, bool outer,
1603 Context & parent_context)
1605 if (name == "tabbing")
1606 // We need to remember that we have to handle '\=' specially
1607 flags |= FLAG_TABBING;
1609 // We need to translate font changes and paragraphs inside the
1610 // environment to ERT if we have a non standard font.
1611 // Otherwise things like
1612 // \large\begin{foo}\huge bar\end{foo}
1614 bool const specialfont =
1615 (parent_context.font != parent_context.normalfont);
1616 bool const new_layout_allowed = parent_context.new_layout_allowed;
1618 parent_context.new_layout_allowed = false;
1619 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1620 // Try to handle options: Look if we have optional arguments,
1621 // and if so, put the brackets in ERT.
1622 while (p.hasOpt()) {
1623 p.get_token(); // eat '['
1624 output_ert_inset(os, "[", parent_context);
1625 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, parent_context);
1626 output_ert_inset(os, "]", parent_context);
1628 parse_text_snippet(p, os, flags, outer, parent_context);
1629 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1631 parent_context.new_layout_allowed = new_layout_allowed;
1635 void parse_environment(Parser & p, ostream & os, bool outer,
1636 string & last_env, Context & parent_context)
1638 Layout const * newlayout;
1639 InsetLayout const * newinsetlayout = 0;
1640 string const name = p.getArg('{', '}');
1641 const bool is_starred = suffixIs(name, '*');
1642 string const unstarred_name = rtrim(name, "*");
1643 active_environments.push_back(name);
1645 // We use this loop and break out after a condition is met
1646 // rather than a huge else-if-chain.
1648 if (is_math_env(name)) {
1649 parent_context.check_layout(os);
1650 begin_inset(os, "Formula ");
1651 os << "\\begin{" << name << "}";
1652 parse_math(p, os, FLAG_END, MATH_MODE);
1653 os << "\\end{" << name << "}";
1655 if (is_display_math_env(name)) {
1656 // Prevent the conversion of a line break to a space
1657 // (bug 7668). This does not change the output, but
1658 // looks ugly in LyX.
1659 eat_whitespace(p, os, parent_context, false);
1664 // We need to use fromPolyglossiaEnvironment due to Arabic > arabic
1665 if (is_known(fromPolyglossiaEnvironment(name), preamble.polyglossia_languages)) {
1666 // We must begin a new paragraph if not already done
1667 if (!parent_context.atParagraphStart()) {
1668 parent_context.check_end_layout(os);
1669 parent_context.new_paragraph(os);
1671 // store previous language because we must reset it at the end
1672 string const lang_old = parent_context.font.language;
1673 // save new language in context so that it is
1674 // handled by parse_text
1675 parent_context.font.language =
1676 preamble.polyglossia2lyx(fromPolyglossiaEnvironment(name));
1677 parse_text(p, os, FLAG_END, outer, parent_context);
1678 // reset previous language
1679 parent_context.font.language = lang_old;
1680 // Just in case the environment is empty
1681 parent_context.extra_stuff.erase();
1682 // We must begin a new paragraph to reset the language
1683 parent_context.new_paragraph(os);
1688 if (unstarred_name == "tabular" || name == "longtable"
1689 || name == "tabularx" || name == "xltabular") {
1690 eat_whitespace(p, os, parent_context, false);
1691 string width = "0pt";
1693 if ((name == "longtable" || name == "xltabular") && p.hasOpt()) {
1694 string const opt = p.getArg('[', ']');
1697 else if (opt == "l")
1699 else if (opt == "r")
1702 if (name == "tabular*" || name == "tabularx" || name == "xltabular") {
1703 width = lyx::translate_len(p.getArg('{', '}'));
1704 eat_whitespace(p, os, parent_context, false);
1706 parent_context.check_layout(os);
1707 begin_inset(os, "Tabular ");
1708 handle_tabular(p, os, name, width, halign, parent_context);
1714 if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1715 eat_whitespace(p, os, parent_context, false);
1716 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1717 eat_whitespace(p, os, parent_context, false);
1718 parent_context.check_layout(os);
1719 begin_inset(os, "Float " + unstarred_name + "\n");
1720 // store the float type for subfloats
1721 // subfloats only work with figures and tables
1722 if (unstarred_name == "figure")
1723 float_type = unstarred_name;
1724 else if (unstarred_name == "table")
1725 float_type = unstarred_name;
1729 os << "placement " << opt << '\n';
1730 if (contains(opt, "H"))
1731 preamble.registerAutomaticallyLoadedPackage("float");
1733 Floating const & fl = parent_context.textclass.floats()
1734 .getType(unstarred_name);
1735 if (!fl.floattype().empty() && fl.usesFloatPkg())
1736 preamble.registerAutomaticallyLoadedPackage("float");
1739 os << "wide " << convert<string>(is_starred)
1740 << "\nsideways false"
1741 << "\nstatus open\n\n";
1742 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1743 if (unstarred_name == "algorithm")
1744 // in algorithm, \; has special meaning
1745 parent_context.pass_thru_cmds.insert(";");
1746 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1747 if (unstarred_name == "algorithm")
1748 parent_context.pass_thru_cmds = pass_thru_cmds;
1750 // We don't need really a new paragraph, but
1751 // we must make sure that the next item gets a \begin_layout.
1752 parent_context.new_paragraph(os);
1754 // the float is parsed thus delete the type
1759 if (unstarred_name == "sidewaysfigure"
1760 || unstarred_name == "sidewaystable"
1761 || unstarred_name == "sidewaysalgorithm") {
1762 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1763 eat_whitespace(p, os, parent_context, false);
1764 parent_context.check_layout(os);
1765 if (unstarred_name == "sidewaysfigure")
1766 begin_inset(os, "Float figure\n");
1767 else if (unstarred_name == "sidewaystable")
1768 begin_inset(os, "Float table\n");
1769 else if (unstarred_name == "sidewaysalgorithm")
1770 begin_inset(os, "Float algorithm\n");
1772 os << "placement " << opt << '\n';
1773 if (contains(opt, "H"))
1774 preamble.registerAutomaticallyLoadedPackage("float");
1775 os << "wide " << convert<string>(is_starred)
1776 << "\nsideways true"
1777 << "\nstatus open\n\n";
1778 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1780 // We don't need really a new paragraph, but
1781 // we must make sure that the next item gets a \begin_layout.
1782 parent_context.new_paragraph(os);
1784 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1788 if (name == "wrapfigure" || name == "wraptable") {
1789 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1790 eat_whitespace(p, os, parent_context, false);
1791 parent_context.check_layout(os);
1794 string overhang = "0col%";
1797 lines = p.getArg('[', ']');
1798 string const placement = p.getArg('{', '}');
1800 overhang = p.getArg('[', ']');
1801 string const width = p.getArg('{', '}');
1803 if (name == "wrapfigure")
1804 begin_inset(os, "Wrap figure\n");
1806 begin_inset(os, "Wrap table\n");
1807 os << "lines " << lines
1808 << "\nplacement " << placement
1809 << "\noverhang " << lyx::translate_len(overhang)
1810 << "\nwidth " << lyx::translate_len(width)
1811 << "\nstatus open\n\n";
1812 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1814 // We don't need really a new paragraph, but
1815 // we must make sure that the next item gets a \begin_layout.
1816 parent_context.new_paragraph(os);
1818 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1822 if (name == "minipage") {
1823 eat_whitespace(p, os, parent_context, false);
1824 // Test whether this is an outer box of a shaded box
1826 // swallow arguments
1827 while (p.hasOpt()) {
1829 p.skip_spaces(true);
1832 p.skip_spaces(true);
1833 Token t = p.get_token();
1834 bool shaded = false;
1835 if (t.asInput() == "\\begin") {
1836 p.skip_spaces(true);
1837 if (p.getArg('{', '}') == "shaded")
1842 parse_outer_box(p, os, FLAG_END, outer,
1843 parent_context, name, "shaded");
1845 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1846 "", "", name, "", "");
1851 if (name == "comment") {
1852 eat_whitespace(p, os, parent_context, false);
1853 parent_context.check_layout(os);
1854 begin_inset(os, "Note Comment\n");
1855 os << "status open\n";
1856 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1859 skip_braces(p); // eat {} that might by set by LyX behind comments
1860 preamble.registerAutomaticallyLoadedPackage("verbatim");
1864 if (unstarred_name == "verbatim") {
1865 // FIXME: this should go in the generic code that
1866 // handles environments defined in layout file that
1867 // have "PassThru 1". However, the code over there is
1868 // already too complicated for my taste.
1869 string const ascii_name =
1870 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1871 parent_context.new_paragraph(os);
1872 Context context(true, parent_context.textclass,
1873 &parent_context.textclass[from_ascii(ascii_name)]);
1874 string s = p.verbatimEnvironment(name);
1875 output_ert(os, s, context);
1880 if (name == "IPA") {
1881 eat_whitespace(p, os, parent_context, false);
1882 parent_context.check_layout(os);
1883 begin_inset(os, "IPA\n");
1884 set<string> pass_thru_cmds = parent_context.pass_thru_cmds;
1885 // These commands have special meanings in IPA
1886 parent_context.pass_thru_cmds.insert("!");
1887 parent_context.pass_thru_cmds.insert(";");
1888 parent_context.pass_thru_cmds.insert(":");
1889 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1890 parent_context.pass_thru_cmds = pass_thru_cmds;
1893 preamble.registerAutomaticallyLoadedPackage("tipa");
1894 preamble.registerAutomaticallyLoadedPackage("tipx");
1898 if (name == parent_context.textclass.titlename()
1899 && parent_context.textclass.titletype() == TITLE_ENVIRONMENT) {
1900 parse_text(p, os, FLAG_END, outer, parent_context);
1901 // Just in case the environment is empty
1902 parent_context.extra_stuff.erase();
1903 // We must begin a new paragraph
1904 parent_context.new_paragraph(os);
1909 if (name == "CJK") {
1910 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1911 // It is impossible to decide if a CJK environment was in its own paragraph or within
1912 // a line. We therefore always assume a paragraph since the latter is a rare case.
1913 eat_whitespace(p, os, parent_context, false);
1914 parent_context.check_end_layout(os);
1915 // store the encoding to be able to reset it
1916 string const encoding_old = p.getEncoding();
1917 string const encoding = p.getArg('{', '}');
1918 // FIXME: For some reason JIS does not work. Although the text
1919 // in tests/CJK.tex is identical with the SJIS version if you
1920 // convert both snippets using the recode command line utility,
1921 // the resulting .lyx file contains some extra characters if
1922 // you set buggy_encoding to false for JIS.
1923 bool const buggy_encoding = encoding == "JIS";
1924 if (!buggy_encoding)
1925 p.setEncoding(encoding, Encoding::CJK);
1927 // FIXME: This will read garbage, since the data is not encoded in utf8.
1928 p.setEncoding("UTF-8");
1930 // LyX only supports the same mapping for all CJK
1931 // environments, so we might need to output everything as ERT
1932 string const mapping = trim(p.getArg('{', '}'));
1933 char const * const * const where =
1934 is_known(encoding, supported_CJK_encodings);
1935 if (!buggy_encoding && !preamble.fontCJKSet())
1936 preamble.fontCJK(mapping);
1937 bool knownMapping = mapping == preamble.fontCJK();
1938 if (buggy_encoding || !knownMapping || !where) {
1939 parent_context.check_layout(os);
1940 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1942 // we must parse the content as verbatim because e.g. JIS can contain
1943 // normally invalid characters
1944 // FIXME: This works only for the most simple cases.
1945 // Since TeX control characters are not parsed,
1946 // things like comments are completely wrong.
1947 string const s = p.plainEnvironment("CJK");
1948 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1951 if (snip == "\\" || is_known(snip, known_escaped_chars))
1952 output_ert_inset(os, snip, parent_context);
1953 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1958 output_ert_inset(os, "\\end{" + name + "}",
1962 supported_CJK_languages[where - supported_CJK_encodings];
1963 // store the language because we must reset it at the end
1964 string const lang_old = parent_context.font.language;
1965 parent_context.font.language = lang;
1966 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1967 parent_context.font.language = lang_old;
1968 parent_context.new_paragraph(os);
1970 p.setEncoding(encoding_old);
1975 if (name == "lyxgreyedout") {
1976 eat_whitespace(p, os, parent_context, false);
1977 parent_context.check_layout(os);
1978 begin_inset(os, "Note Greyedout\n");
1979 os << "status open\n";
1980 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1983 if (!preamble.notefontcolor().empty())
1984 preamble.registerAutomaticallyLoadedPackage("color");
1988 if (name == "btSect") {
1989 eat_whitespace(p, os, parent_context, false);
1990 parent_context.check_layout(os);
1991 begin_command_inset(os, "bibtex", "bibtex");
1992 string bibstyle = "plain";
1994 bibstyle = p.getArg('[', ']');
1995 p.skip_spaces(true);
1997 string const bibfile = p.getArg('{', '}');
1998 eat_whitespace(p, os, parent_context, false);
1999 Token t = p.get_token();
2000 if (t.asInput() == "\\btPrintCited") {
2001 p.skip_spaces(true);
2002 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
2004 if (t.asInput() == "\\btPrintNotCited") {
2005 p.skip_spaces(true);
2006 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
2008 if (t.asInput() == "\\btPrintAll") {
2009 p.skip_spaces(true);
2010 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2012 os << "bibfiles " << '"' << bibfile << "\"\n"
2013 << "options " << '"' << bibstyle << "\"\n";
2014 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
2020 if (name == "btUnit") {
2021 string const nt = p.next_next_token().cs();
2022 // Do not attempt to overwrite a former diverging multibib.
2023 // Those are output as ERT instead.
2024 if ((nt == "part" || nt == "chapter"
2025 || nt == "section" || nt == "subsection")
2026 && (preamble.multibib().empty() || preamble.multibib() == nt)) {
2027 parse_text(p, os, FLAG_END, outer, parent_context);
2028 preamble.multibib(nt);
2030 parse_unknown_environment(p, name, os, FLAG_END, outer,
2035 // This is only attempted at turn environments that consist only
2036 // of a tabular (this is how tables in LyX, modulo longtables, are rotated).
2037 // Thus we will fall through in other cases.
2038 if (name == "turn") {
2039 // We check if the next thing is a tabular[*|x]
2041 p.getArg('{', '}');// eat turn argument
2042 bool found_end = false;
2043 bool only_table = false;
2044 bool end_table = false;
2047 string envname = p.getArg('{', '}');
2048 if (rtrim(envname, "*") == "tabular" || envname == "tabularx") {
2049 // Now we check if the table is the only content
2050 // of the turn environment
2051 string const tenv = envname;
2052 while (!found_end && !end_table && p.good()) {
2053 envname = p.next_token().cat() == catBegin
2054 ? p.getArg('{', '}') : string();
2055 Token const & t = p.get_token();
2057 end_table = t.asInput() != "\\end"
2059 found_end = t.asInput() == "\\end"
2060 && envname == "turn";
2064 envname = p.getArg('{', '}');
2065 only_table = p.next_next_token().asInput() == "\\end"
2066 && envname == "turn";
2070 string const angle = p.getArg('{', '}');
2072 int const save_tablerotation = parent_context.tablerotation;
2073 parent_context.tablerotation = convert<int>(angle);
2074 parse_text(p, os, FLAG_END, outer, parent_context);
2075 parent_context.tablerotation = save_tablerotation;
2085 // This is only attempted at landscape environments that consist only
2086 // of a longtable (this is how longtables in LyX are rotated by 90 degs).
2087 // Other landscape environment is handled via the landscape module, thus
2088 // we will fall through in that case.
2089 if (name == "landscape") {
2090 // We check if the next thing is a longtable
2092 bool found_end = false;
2093 bool only_longtable = false;
2094 bool end_longtable = false;
2097 string envname = p.getArg('{', '}');
2098 if (envname == "longtable" || envname == "xltabular") {
2099 // Now we check if the longtable is the only content
2100 // of the landscape environment
2101 string const ltenv = envname;
2102 while (!found_end && !end_longtable && p.good()) {
2103 envname = p.next_token().cat() == catBegin
2104 ? p.getArg('{', '}') : string();
2105 Token const & t = p.get_token();
2107 end_longtable = t.asInput() != "\\end"
2108 && envname == ltenv;
2109 found_end = t.asInput() == "\\end"
2110 && envname == "landscape";
2112 if (end_longtable) {
2114 envname = p.getArg('{', '}');
2115 only_longtable = p.next_next_token().asInput() == "\\end"
2116 && envname == "landscape";
2118 if (only_longtable) {
2121 int const save_tablerotation = parent_context.tablerotation;
2122 parent_context.tablerotation = 90;
2123 parse_text(p, os, FLAG_END, outer, parent_context);
2124 parent_context.tablerotation = save_tablerotation;
2134 if (name == "framed" || name == "shaded") {
2135 eat_whitespace(p, os, parent_context, false);
2136 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
2138 preamble.registerAutomaticallyLoadedPackage("framed");
2142 if (name == "listing") {
2143 minted_float = "float";
2144 eat_whitespace(p, os, parent_context, false);
2145 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
2147 minted_float += "=" + opt;
2148 // If something precedes \begin{minted}, we output it at the end
2149 // as a caption, in order to keep it inside the listings inset.
2150 eat_whitespace(p, os, parent_context, true);
2152 Token const & t = p.get_token();
2153 p.skip_spaces(true);
2154 string const envname = p.next_token().cat() == catBegin
2155 ? p.getArg('{', '}') : string();
2156 bool prologue = t.asInput() != "\\begin" || envname != "minted";
2158 minted_float_has_caption = false;
2159 string content = parse_text_snippet(p, FLAG_END, outer,
2161 size_t i = content.find("\\begin_inset listings");
2162 bool minted_env = i != string::npos;
2165 caption = content.substr(0, i);
2166 content.erase(0, i);
2168 parent_context.check_layout(os);
2169 if (minted_env && minted_float_has_caption) {
2170 eat_whitespace(p, os, parent_context, true);
2171 os << content << "\n";
2172 if (!caption.empty())
2173 os << caption << "\n";
2174 os << "\n\\end_layout\n"; // close inner layout
2175 end_inset(os); // close caption inset
2176 os << "\n\\end_layout\n"; // close outer layout
2177 } else if (!caption.empty()) {
2179 begin_inset(os, "listings\n");
2180 os << "lstparams " << '"' << minted_float << '"' << '\n';
2181 os << "inline false\n";
2182 os << "status collapsed\n";
2184 os << "\n\\begin_layout Plain Layout\n";
2185 begin_inset(os, "Caption Standard\n");
2186 Context newcontext(true, parent_context.textclass,
2187 0, 0, parent_context.font);
2188 newcontext.check_layout(os);
2189 os << caption << "\n";
2190 newcontext.check_end_layout(os);
2192 os << "\n\\end_layout\n";
2193 } else if (content.empty()) {
2194 begin_inset(os, "listings\n");
2195 os << "lstparams " << '"' << minted_float << '"' << '\n';
2196 os << "inline false\n";
2197 os << "status collapsed\n";
2199 os << content << "\n";
2201 end_inset(os); // close listings inset
2202 parent_context.check_end_layout(os);
2203 parent_context.new_paragraph(os);
2205 minted_float.clear();
2206 minted_float_has_caption = false;
2210 if (name == "lstlisting" || name == "minted") {
2211 bool use_minted = name == "minted";
2212 // with listings, we do not eat newlines here since
2213 // \begin{lstlistings}
2216 // // \begin{lstlistings}%
2219 // reads [foo] as content, whereas
2220 // // \begin{lstlistings}%
2223 // \begin{lstlistings}[foo,
2225 // reads [foo...] as argument.
2226 eat_whitespace(p, os, parent_context, false, use_minted);
2227 if (use_minted && minted_float.empty()) {
2228 // look ahead for a bottom caption
2230 bool found_end_minted = false;
2231 while (!found_end_minted && p.good()) {
2232 Token const & t = p.get_token();
2234 string const envname =
2235 p.next_token().cat() == catBegin
2236 ? p.getArg('{', '}') : string();
2237 found_end_minted = t.asInput() == "\\end"
2238 && envname == "minted";
2240 eat_whitespace(p, os, parent_context, true);
2241 Token const & t = p.get_token();
2242 p.skip_spaces(true);
2243 if (t.asInput() == "\\lyxmintcaption") {
2244 string const pos = p.getArg('[', ']');
2246 string const caption =
2247 parse_text_snippet(p, FLAG_ITEM,
2248 false, parent_context);
2249 minted_nonfloat_caption = "[b]" + caption;
2250 eat_whitespace(p, os, parent_context, true);
2255 parse_listings(p, os, parent_context, false, use_minted);
2260 if (!parent_context.new_layout_allowed) {
2261 parse_unknown_environment(p, name, os, FLAG_END, outer,
2266 // Alignment and spacing settings
2267 // FIXME (bug xxxx): These settings can span multiple paragraphs and
2268 // therefore are totally broken!
2269 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
2270 // they are commands not environments. They are furthermore switches that
2271 // can be ended by another switches, but also by commands like \footnote or
2272 // \parbox. So the only safe way is to leave them untouched.
2273 // However, we support the pseudo-environments
2274 // \begin{centering} ... \end{centering}
2275 // \begin{raggedright} ... \end{raggedright}
2276 // \begin{raggedleft} ... \end{raggedleft}
2277 // since they are used by LyX in floats (for spacing reasons)
2278 if (name == "center" || name == "centering"
2279 || name == "flushleft" || name == "raggedright"
2280 || name == "flushright" || name == "raggedleft"
2281 || name == "singlespace" || name == "onehalfspace"
2282 || name == "doublespace" || name == "spacing") {
2283 eat_whitespace(p, os, parent_context, false);
2284 // We must begin a new paragraph if not already done
2285 if (! parent_context.atParagraphStart()) {
2286 parent_context.check_end_layout(os);
2287 parent_context.new_paragraph(os);
2289 if (name == "flushleft" || name == "raggedright")
2290 parent_context.add_extra_stuff("\\align left\n");
2291 else if (name == "flushright" || name == "raggedleft")
2292 parent_context.add_extra_stuff("\\align right\n");
2293 else if (name == "center" || name == "centering")
2294 parent_context.add_extra_stuff("\\align center\n");
2295 else if (name == "singlespace")
2296 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2297 else if (name == "onehalfspace") {
2298 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2299 preamble.registerAutomaticallyLoadedPackage("setspace");
2300 } else if (name == "doublespace") {
2301 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2302 preamble.registerAutomaticallyLoadedPackage("setspace");
2303 } else if (name == "spacing") {
2304 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2305 preamble.registerAutomaticallyLoadedPackage("setspace");
2307 parse_text(p, os, FLAG_END, outer, parent_context);
2308 // Just in case the environment is empty
2309 parent_context.extra_stuff.erase();
2310 // We must begin a new paragraph to reset the alignment
2311 parent_context.new_paragraph(os);
2316 // The single '=' is meant here.
2317 if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2318 eat_whitespace(p, os, parent_context, false);
2319 Context context(true, parent_context.textclass, newlayout,
2320 parent_context.layout, parent_context.font);
2321 if (parent_context.deeper_paragraph) {
2322 // We are beginning a nested environment after a
2323 // deeper paragraph inside the outer list environment.
2324 // Therefore we don't need to output a "begin deeper".
2325 context.need_end_deeper = true;
2327 parent_context.check_end_layout(os);
2328 if (last_env == name) {
2329 // we need to output a separator since LyX would export
2330 // the two environments as one otherwise (bug 5716)
2331 TeX2LyXDocClass const & textclass(parent_context.textclass);
2332 Context newcontext(true, textclass,
2333 &(textclass.defaultLayout()));
2334 newcontext.check_layout(os);
2335 begin_inset(os, "Separator plain\n");
2337 newcontext.check_end_layout(os);
2339 switch (context.layout->latextype) {
2340 case LATEX_LIST_ENVIRONMENT:
2341 context.in_list_preamble =
2342 !context.layout->listpreamble().empty()
2343 && p.hasListPreamble(context.layout->itemcommand());
2344 context.add_par_extra_stuff("\\labelwidthstring "
2345 + p.verbatim_item() + '\n');
2348 case LATEX_BIB_ENVIRONMENT:
2349 p.verbatim_item(); // swallow next arg
2355 context.check_deeper(os);
2356 if (newlayout->keepempty) {
2357 // We need to start a new paragraph
2358 // even if it is empty.
2359 context.new_paragraph(os);
2360 context.check_layout(os);
2362 // handle known optional and required arguments
2363 if (context.layout->latextype == LATEX_ENVIRONMENT)
2364 output_arguments(os, p, outer, false, string(), context,
2365 context.layout->latexargs());
2366 else if (context.layout->latextype == LATEX_ITEM_ENVIRONMENT) {
2367 context.in_list_preamble =
2368 !context.layout->listpreamble().empty()
2369 && p.hasListPreamble(context.layout->itemcommand());
2371 output_arguments(oss, p, outer, false, string(), context,
2372 context.layout->latexargs());
2373 context.list_extra_stuff = oss.str();
2375 if (context.in_list_preamble) {
2376 // Collect the stuff between \begin and first \item
2377 context.list_preamble =
2378 parse_text_snippet(p, FLAG_END, outer, context);
2379 context.in_list_preamble = false;
2381 parse_text(p, os, FLAG_END, outer, context);
2382 if (context.layout->latextype == LATEX_ENVIRONMENT)
2383 output_arguments(os, p, outer, false, "post", context,
2384 context.layout->postcommandargs());
2385 context.check_end_layout(os);
2386 if (parent_context.deeper_paragraph) {
2387 // We must suppress the "end deeper" because we
2388 // suppressed the "begin deeper" above.
2389 context.need_end_deeper = false;
2391 context.check_end_deeper(os);
2392 parent_context.new_paragraph(os);
2394 if (!preamble.titleLayoutFound())
2395 preamble.titleLayoutFound(newlayout->intitle);
2396 set<string> const & req = newlayout->required();
2397 set<string>::const_iterator it = req.begin();
2398 set<string>::const_iterator en = req.end();
2399 for (; it != en; ++it)
2400 preamble.registerAutomaticallyLoadedPackage(*it);
2404 // The single '=' is meant here.
2405 if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2406 eat_whitespace(p, os, parent_context, false);
2407 parent_context.check_layout(os);
2408 begin_inset(os, "Flex ");
2409 docstring flex_name = newinsetlayout->name();
2410 // FIXME: what do we do if the prefix is not Flex: ?
2411 if (prefixIs(flex_name, from_ascii("Flex:")))
2412 flex_name.erase(0, 5);
2413 os << to_utf8(flex_name) << '\n'
2414 << "status collapsed\n";
2415 if (newinsetlayout->isPassThru()) {
2416 string const arg = p.verbatimEnvironment(name);
2417 Context context(true, parent_context.textclass,
2418 &parent_context.textclass.plainLayout(),
2419 parent_context.layout);
2420 output_ert(os, arg, parent_context);
2422 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2427 if (name == "appendix") {
2428 // This is no good latex style, but it works and is used in some documents...
2429 eat_whitespace(p, os, parent_context, false);
2430 parent_context.check_end_layout(os);
2431 Context context(true, parent_context.textclass, parent_context.layout,
2432 parent_context.layout, parent_context.font);
2433 context.check_layout(os);
2434 os << "\\start_of_appendix\n";
2435 parse_text(p, os, FLAG_END, outer, context);
2436 context.check_end_layout(os);
2441 if (known_environments.find(name) != known_environments.end()) {
2442 vector<ArgumentType> arguments = known_environments[name];
2443 // The last "argument" denotes whether we may translate the
2444 // environment contents to LyX
2445 // The default required if no argument is given makes us
2446 // compatible with the reLyXre environment.
2447 ArgumentType contents = arguments.empty() ?
2450 if (!arguments.empty())
2451 arguments.pop_back();
2452 // See comment in parse_unknown_environment()
2453 bool const specialfont =
2454 (parent_context.font != parent_context.normalfont);
2455 bool const new_layout_allowed =
2456 parent_context.new_layout_allowed;
2458 parent_context.new_layout_allowed = false;
2459 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2460 outer, parent_context);
2461 if (contents == verbatim)
2462 output_ert_inset(os, p.ertEnvironment(name),
2465 parse_text_snippet(p, os, FLAG_END, outer,
2467 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2469 parent_context.new_layout_allowed = new_layout_allowed;
2473 parse_unknown_environment(p, name, os, FLAG_END, outer, parent_context);
2478 active_environments.pop_back();
2482 /// parses a comment and outputs it to \p os.
2483 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context,
2484 bool skipNewlines = false)
2486 LASSERT(t.cat() == catComment, return);
2487 if (!t.cs().empty()) {
2488 context.check_layout(os);
2489 output_comment(p, os, t.cs(), context);
2490 if (p.next_token().cat() == catNewline) {
2491 // A newline after a comment line starts a new
2493 if (context.new_layout_allowed) {
2494 if(!context.atParagraphStart())
2495 // Only start a new paragraph if not already
2496 // done (we might get called recursively)
2497 context.new_paragraph(os);
2499 output_ert_inset(os, "\n", context);
2500 eat_whitespace(p, os, context, true);
2502 } else if (!skipNewlines) {
2503 // "%\n" combination
2510 * Reads spaces and comments until the first non-space, non-comment token.
2511 * New paragraphs (double newlines or \\par) are handled like simple spaces
2512 * if \p eatParagraph is true.
2513 * If \p eatNewline is false, newlines won't be treated as whitespace.
2514 * Spaces are skipped, but comments are written to \p os.
2516 void eat_whitespace(Parser & p, ostream & os, Context & context,
2517 bool eatParagraph, bool eatNewline)
2520 Token const & t = p.get_token();
2521 if (t.cat() == catComment)
2522 parse_comment(p, os, t, context, !eatNewline);
2523 else if ((!eatParagraph && p.isParagraph()) ||
2524 (t.cat() != catSpace && (t.cat() != catNewline || !eatNewline))) {
2533 * Set a font attribute, parse text and reset the font attribute.
2534 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2535 * \param currentvalue Current value of the attribute. Is set to the new
2536 * value during parsing.
2537 * \param newvalue New value of the attribute
2539 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2540 Context & context, string const & attribute,
2541 string & currentvalue, string const & newvalue)
2543 context.check_layout(os);
2544 string const oldvalue = currentvalue;
2545 currentvalue = newvalue;
2546 os << '\n' << attribute << ' ' << newvalue << "\n";
2547 parse_text_snippet(p, os, flags, outer, context);
2548 context.check_layout(os);
2549 os << '\n' << attribute << ' ' << oldvalue << "\n";
2550 currentvalue = oldvalue;
2554 /// get the arguments of a natbib or jurabib citation command
2555 void get_cite_arguments(Parser & p, bool natbibOrder,
2556 string & before, string & after, bool const qualified = false)
2558 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2560 // text before the citation
2562 // text after the citation
2563 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2565 if (!after.empty()) {
2566 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2567 if (natbibOrder && !before.empty())
2568 swap(before, after);
2573 void copy_file(FileName const & src, string const & dstname)
2577 string const absParent = getParentFilePath(false);
2579 if (FileName::isAbsolute(dstname))
2580 dst = FileName(dstname);
2582 dst = makeAbsPath(dstname, absParent);
2583 FileName const srcpath = src.onlyPath();
2584 FileName const dstpath = dst.onlyPath();
2585 if (equivalent(srcpath, dstpath))
2587 if (!dstpath.isDirectory()) {
2588 if (!dstpath.createPath()) {
2589 cerr << "Warning: Could not create directory for file `"
2590 << dst.absFileName() << "´." << endl;
2594 if (dst.isReadableFile()) {
2595 if (overwriteFiles())
2596 cerr << "Warning: Overwriting existing file `"
2597 << dst.absFileName() << "´." << endl;
2599 cerr << "Warning: Not overwriting existing file `"
2600 << dst.absFileName() << "´." << endl;
2604 if (!src.copyTo(dst))
2605 cerr << "Warning: Could not copy file `" << src.absFileName()
2606 << "´ to `" << dst.absFileName() << "´." << endl;
2610 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2611 bool parse_chunk(Parser & p, ostream & os, Context & context)
2613 // check whether a chunk is possible here.
2614 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2620 // read the parameters
2621 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2622 if (!params.first) {
2627 Parser::Arg const code = p.verbatimStuff("\n@");
2632 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2633 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2637 // The last newline read is important for paragraph handling
2641 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2642 // We must have a valid layout before outputting the Chunk inset.
2643 context.check_layout(os);
2644 Context chunkcontext(true, context.textclass);
2645 chunkcontext.layout = &context.textclass.plainLayout();
2646 begin_inset(os, "Flex Chunk");
2647 os << "\nstatus open\n";
2648 if (!params.second.empty()) {
2649 chunkcontext.check_layout(os);
2650 Context paramscontext(true, context.textclass);
2651 paramscontext.layout = &context.textclass.plainLayout();
2652 begin_inset(os, "Argument 1");
2653 os << "\nstatus open\n";
2654 output_ert(os, params.second, paramscontext);
2657 output_ert(os, code.second, chunkcontext);
2665 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2666 bool is_macro(Parser & p)
2668 Token first = p.curr_token();
2669 if (first.cat() != catEscape || !p.good())
2671 if (first.cs() == "def")
2673 if (first.cs() != "global" && first.cs() != "long")
2675 Token second = p.get_token();
2677 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2678 second.cat() == catNewline || second.cat() == catComment)) {
2679 second = p.get_token();
2682 bool secondvalid = second.cat() == catEscape;
2684 bool thirdvalid = false;
2685 if (p.good() && first.cs() == "global" && secondvalid &&
2686 second.cs() == "long") {
2687 third = p.get_token();
2689 while (p.good() && !p.isParagraph() &&
2690 (third.cat() == catSpace ||
2691 third.cat() == catNewline ||
2692 third.cat() == catComment)) {
2693 third = p.get_token();
2696 thirdvalid = third.cat() == catEscape;
2698 for (int i = 0; i < pos; ++i)
2703 return (first.cs() == "global" || first.cs() == "long") &&
2704 second.cs() == "def";
2705 return first.cs() == "global" && second.cs() == "long" &&
2706 third.cs() == "def";
2710 /// Parse a macro definition (assumes that is_macro() returned true)
2711 void parse_macro(Parser & p, ostream & os, Context & context)
2713 context.check_layout(os);
2714 Token first = p.curr_token();
2717 string command = first.asInput();
2718 if (first.cs() != "def") {
2720 eat_whitespace(p, os, context, false);
2721 second = p.curr_token();
2722 command += second.asInput();
2723 if (second.cs() != "def") {
2725 eat_whitespace(p, os, context, false);
2726 third = p.curr_token();
2727 command += third.asInput();
2730 eat_whitespace(p, os, context, false);
2731 string const name = p.get_token().cs();
2732 eat_whitespace(p, os, context, false);
2738 while (p.next_token().cat() != catBegin) {
2739 if (p.next_token().cat() == catParameter) {
2744 // followed by number?
2745 if (p.next_token().cat() == catOther) {
2746 string s = p.get_token().asInput();
2748 // number = current arity + 1?
2749 if (s.size() == 1 && s[0] == arity + '0' + 1)
2754 paramtext += p.get_token().cs();
2756 paramtext += p.get_token().cs();
2761 // only output simple (i.e. compatible) macro as FormulaMacros
2762 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2764 context.check_layout(os);
2765 begin_inset(os, "FormulaMacro");
2766 os << "\n\\def" << ert;
2769 output_ert_inset(os, command + ert, context);
2773 void registerExternalTemplatePackages(string const & name)
2775 external::TemplateManager const & etm = external::TemplateManager::get();
2776 external::Template const * const et = etm.getTemplateByName(name);
2779 external::Template::Formats::const_iterator cit = et->formats.end();
2781 cit = et->formats.find("PDFLaTeX");
2782 if (cit == et->formats.end())
2783 // If the template has not specified a PDFLaTeX output,
2784 // we try the LaTeX format.
2785 cit = et->formats.find("LaTeX");
2786 if (cit == et->formats.end())
2788 vector<string>::const_iterator qit = cit->second.requirements.begin();
2789 vector<string>::const_iterator qend = cit->second.requirements.end();
2790 for (; qit != qend; ++qit)
2791 preamble.registerAutomaticallyLoadedPackage(*qit);
2794 } // anonymous namespace
2798 * Find a file with basename \p name in path \p path and an extension
2801 string find_file(string const & name, string const & path,
2802 char const * const * extensions)
2804 for (char const * const * what = extensions; *what; ++what) {
2805 string const trial = addExtension(name, *what);
2806 if (makeAbsPath(trial, path).exists())
2813 /// Convert filenames with TeX macros and/or quotes to something LyX
2815 string const normalize_filename(string const & name)
2820 Token const & t = p.get_token();
2821 if (t.cat() != catEscape)
2823 else if (t.cs() == "lyxdot") {
2824 // This is used by LyX for simple dots in relative
2828 } else if (t.cs() == "space") {
2831 } else if (t.cs() == "string") {
2832 // Convert \string" to " and \string~ to ~
2833 Token const & n = p.next_token();
2834 if (n.asInput() != "\"" && n.asInput() != "~")
2839 // Strip quotes. This is a bit complicated (see latex_path()).
2840 string full = os.str();
2841 if (!full.empty() && full[0] == '"') {
2842 string base = removeExtension(full);
2843 string ext = getExtension(full);
2844 if (!base.empty() && base[base.length()-1] == '"')
2847 return addExtension(trim(base, "\""), ext);
2848 if (full[full.length()-1] == '"')
2851 return trim(full, "\"");
2857 /// Convert \p name from TeX convention (relative to master file) to LyX
2858 /// convention (relative to .lyx file) if it is relative
2859 void fix_child_filename(string & name)
2861 string const absMasterTeX = getMasterFilePath(true);
2862 bool const isabs = FileName::isAbsolute(name);
2863 // convert from "relative to .tex master" to absolute original path
2865 name = makeAbsPath(name, absMasterTeX).absFileName();
2866 bool copyfile = copyFiles();
2867 string const absParentLyX = getParentFilePath(false);
2870 // convert from absolute original path to "relative to master file"
2871 string const rel = to_utf8(makeRelPath(from_utf8(name),
2872 from_utf8(absMasterTeX)));
2873 // re-interpret "relative to .tex file" as "relative to .lyx file"
2874 // (is different if the master .lyx file resides in a
2875 // different path than the master .tex file)
2876 string const absMasterLyX = getMasterFilePath(false);
2877 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2878 // Do not copy if the new path is impossible to create. Example:
2879 // absMasterTeX = "/foo/bar/"
2880 // absMasterLyX = "/bar/"
2881 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2882 if (contains(name, "/../"))
2889 // convert from absolute original path to
2890 // "relative to .lyx file"
2891 name = to_utf8(makeRelPath(from_utf8(abs),
2892 from_utf8(absParentLyX)));
2896 // convert from absolute original path to "relative to .lyx file"
2897 name = to_utf8(makeRelPath(from_utf8(name),
2898 from_utf8(absParentLyX)));
2903 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2904 Context & context, string const & rdelim)
2906 Layout const * newlayout = 0;
2907 InsetLayout const * newinsetlayout = 0;
2908 char const * const * where = 0;
2909 // Store the latest bibliographystyle, addcontentslineContent and
2910 // nocite{*} option (needed for bibtex inset)
2912 string contentslineContent;
2913 // Some classes provide a \bibliographystyle, so do not output
2914 // any if none is explicitly set.
2915 string bibliographystyle;
2916 bool const use_natbib = isProvided("natbib");
2917 bool const use_jurabib = isProvided("jurabib");
2918 bool const use_biblatex = isProvided("biblatex")
2919 && preamble.citeEngine() != "biblatex-natbib";
2920 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2921 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2922 need_commentbib = use_biblatex || use_biblatex_natbib;
2925 // it is impossible to determine the correct encoding for non-CJK Japanese.
2926 // Therefore write a note at the beginning of the document
2927 if (is_nonCJKJapanese) {
2928 context.check_layout(os);
2929 begin_inset(os, "Note Note\n");
2930 os << "status open\n\\begin_layout Plain Layout\n"
2931 << "\\series bold\n"
2932 << "Important information:\n"
2933 << "\\end_layout\n\n"
2934 << "\\begin_layout Plain Layout\n"
2935 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2936 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2937 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2938 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2939 << " and specify the encoding using the -e command-line switch.\n"
2940 << " In addition, you might want to double check that the desired output encoding\n"
2941 << " is correctly selected in Document > Settings > Language.\n"
2942 << "\\end_layout\n";
2944 is_nonCJKJapanese = false;
2947 bool have_cycled = false;
2949 // Leave here only after at least one cycle
2950 if (have_cycled && flags & FLAG_LEAVE) {
2951 flags &= ~FLAG_LEAVE;
2955 Token const & t = p.get_token();
2957 debugToken(cerr, t, flags);
2960 if (context.in_list_preamble
2961 && p.next_token().cs() == context.layout->itemcommand()) {
2962 // We are parsing a list preamble. End before first \item.
2963 flags |= FLAG_LEAVE;
2964 context.in_list_preamble = false;
2967 if (flags & FLAG_ITEM) {
2968 if (t.cat() == catSpace)
2971 flags &= ~FLAG_ITEM;
2972 if (t.cat() == catBegin) {
2973 // skip the brace and collect everything to the next matching
2975 flags |= FLAG_BRACE_LAST;
2979 // handle only this single token, leave the loop if done
2980 flags |= FLAG_LEAVE;
2983 if (t.cat() != catEscape && t.character() == ']' &&
2984 (flags & FLAG_BRACK_LAST))
2986 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2988 string tok = t.asInput();
2989 // we only support delimiters with max 2 chars for now.
2990 if (rdelim.size() > 1)
2991 tok += p.next_token().asInput();
2992 if (t.cat() != catEscape && !rdelim.empty()
2993 && tok == rdelim && (flags & FLAG_RDELIM)) {
2994 if (rdelim.size() > 1)
2995 p.get_token(); // eat rdelim
2999 // If there is anything between \end{env} and \begin{env} we
3000 // don't need to output a separator.
3001 if (t.cat() != catSpace && t.cat() != catNewline &&
3002 t.asInput() != "\\begin")
3009 bool const starred = p.next_token().asInput() == "*";
3010 string const starredname(starred ? (t.cs() + '*') : t.cs());
3011 if (t.cat() == catMath) {
3012 // we are inside some text mode thingy, so opening new math is allowed
3013 context.check_layout(os);
3014 begin_inset(os, "Formula ");
3015 Token const & n = p.get_token();
3016 bool const display(n.cat() == catMath && outer);
3018 // TeX's $$...$$ syntax for displayed math
3020 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3022 p.get_token(); // skip the second '$' token
3024 // simple $...$ stuff
3027 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
3032 // Prevent the conversion of a line break to a
3033 // space (bug 7668). This does not change the
3034 // output, but looks ugly in LyX.
3035 eat_whitespace(p, os, context, false);
3040 if (t.cat() == catSuper || t.cat() == catSub) {
3041 cerr << "catcode " << t << " illegal in text mode\n";
3045 // Basic support for quotes. We try to disambiguate
3046 // quotes from the context (e.g., a left english quote is
3047 // the same as a right german quote...).
3048 // Try to make a smart guess about the side
3049 Token const prev = p.prev_token();
3050 bool const opening = (prev.cat() != catSpace && prev.character() != 0
3051 && prev.character() != '\n' && prev.character() != '~');
3052 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
3053 context.check_layout(os);
3054 begin_inset(os, "Quotes ");
3055 os << guessQuoteStyle("eld", opening);
3061 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
3062 context.check_layout(os);
3063 begin_inset(os, "Quotes ");
3064 os << guessQuoteStyle("erd", opening);
3071 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
3072 context.check_layout(os);
3073 begin_inset(os, "Quotes ");
3074 os << guessQuoteStyle("ald", opening);
3081 if (t.asInput() == "<"
3082 && p.next_token().asInput() == "<") {
3083 bool has_chunk = false;
3087 has_chunk = parse_chunk(p, os, context);
3093 context.check_layout(os);
3094 begin_inset(os, "Quotes ");
3095 os << guessQuoteStyle("ard", opening);
3103 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
3104 check_space(p, os, context);
3108 // babel shorthands (also used by polyglossia)
3109 // Since these can have different meanings for different languages
3110 // we import them as ERT (but they must be put in ERT to get output
3112 if (t.asInput() == "\"") {
3114 // These are known pairs. We put them together in
3115 // one ERT inset. In other cases (such as "a), only
3116 // the quotation mark is ERTed.
3117 if (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 || p.next_token().asInput() == "'"
3125 || p.next_token().asInput() == "`"
3126 || p.next_token().asInput() == "<"
3127 || p.next_token().asInput() == ">") {
3128 s += p.next_token().asInput();
3131 output_ert_inset(os, s, context);
3135 if (t.character() == '[' && noweb_mode &&
3136 p.next_token().character() == '[') {
3137 // These can contain underscores
3139 string const s = p.getFullOpt() + ']';
3140 if (p.next_token().character() == ']')
3143 cerr << "Warning: Inserting missing ']' in '"
3144 << s << "'." << endl;
3145 output_ert_inset(os, s, context);
3149 if (t.cat() == catLetter) {
3150 context.check_layout(os);
3155 if (t.cat() == catOther ||
3156 t.cat() == catAlign ||
3157 t.cat() == catParameter) {
3158 context.check_layout(os);
3159 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
3160 context.merging_hyphens_allowed &&
3161 context.font.family != "ttfamily" &&
3162 !context.layout->pass_thru) {
3163 if (p.next_next_token().asInput() == "-") {
3165 os << to_utf8(docstring(1, 0x2014));
3169 os << to_utf8(docstring(1, 0x2013));
3172 // This translates "&" to "\\&" which may be wrong...
3177 if (p.isParagraph()) {
3178 // In minted floating listings we will collect
3179 // everything into the caption, where multiple
3180 // paragraphs are forbidden.
3181 if (minted_float.empty()) {
3182 if (context.new_layout_allowed)
3183 context.new_paragraph(os);
3185 output_ert_inset(os, "\\par ", context);
3188 eat_whitespace(p, os, context, true);
3192 if (t.cat() == catActive) {
3193 context.check_layout(os);
3194 if (t.character() == '~') {
3195 if (context.layout->free_spacing)
3198 begin_inset(os, "space ~\n");
3206 if (t.cat() == catBegin) {
3207 Token const next = p.next_token();
3208 Token const end = p.next_next_token();
3209 if (next.cat() == catEnd) {
3211 Token const prev = p.prev_token();
3213 if (p.next_token().character() == '`')
3214 ; // ignore it in {}``
3216 output_ert_inset(os, "{}", context);
3217 } else if (next.cat() == catEscape &&
3218 is_known(next.cs(), known_quotes) &&
3219 end.cat() == catEnd) {
3220 // Something like {\textquoteright} (e.g.
3221 // from writer2latex). We may skip the
3222 // braces here for better readability.
3223 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3225 } else if (p.next_token().asInput() == "\\ascii") {
3226 // handle the \ascii characters
3227 // (the case without braces is handled later)
3228 // the code is "{\ascii\xxx}"
3229 p.get_token(); // eat \ascii
3230 string name2 = p.get_token().asInput();
3231 p.get_token(); // eat the final '}'
3232 string const name = "{\\ascii" + name2 + "}";
3236 // get the character from unicodesymbols
3237 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
3238 Encodings::TEXT_CMD, termination, rem, &req);
3240 context.check_layout(os);
3243 output_ert_inset(os,
3244 to_utf8(rem), context);
3245 for (set<string>::const_iterator it = req.begin();
3246 it != req.end(); ++it)
3247 preamble.registerAutomaticallyLoadedPackage(*it);
3249 // we did not find a non-ert version
3250 output_ert_inset(os, name, context);
3252 context.check_layout(os);
3253 // special handling of font attribute changes
3254 Token const prev = p.prev_token();
3255 TeXFont const oldFont = context.font;
3256 if (next.character() == '[' ||
3257 next.character() == ']' ||
3258 next.character() == '*') {
3260 if (p.next_token().cat() == catEnd) {
3265 output_ert_inset(os, "{", context);
3266 parse_text_snippet(p, os,
3269 output_ert_inset(os, "}", context);
3271 } else if (! context.new_layout_allowed) {
3272 output_ert_inset(os, "{", context);
3273 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3275 output_ert_inset(os, "}", context);
3276 } else if (is_known(next.cs(), known_sizes)) {
3277 // next will change the size, so we must
3279 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3281 if (!context.atParagraphStart())
3283 << context.font.size << "\n";
3284 } else if (is_known(next.cs(), known_font_families)) {
3285 // next will change the font family, so we
3286 // must reset it here
3287 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3289 if (!context.atParagraphStart())
3291 << context.font.family << "\n";
3292 } else if (is_known(next.cs(), known_font_series)) {
3293 // next will change the font series, so we
3294 // must reset it here
3295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3297 if (!context.atParagraphStart())
3299 << context.font.series << "\n";
3300 } else if (is_known(next.cs(), known_font_shapes)) {
3301 // next will change the font shape, so we
3302 // must reset it here
3303 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3305 if (!context.atParagraphStart())
3307 << context.font.shape << "\n";
3308 } else if (is_known(next.cs(), known_old_font_families) ||
3309 is_known(next.cs(), known_old_font_series) ||
3310 is_known(next.cs(), known_old_font_shapes)) {
3311 // next will change the font family, series
3312 // and shape, so we must reset it here
3313 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3315 if (!context.atParagraphStart())
3317 << context.font.family
3319 << context.font.series
3321 << context.font.shape << "\n";
3323 output_ert_inset(os, "{", context);
3324 parse_text_snippet(p, os, FLAG_BRACE_LAST,
3326 output_ert_inset(os, "}", context);
3332 if (t.cat() == catEnd) {
3333 if (flags & FLAG_BRACE_LAST) {
3336 cerr << "stray '}' in text\n";
3337 output_ert_inset(os, "}", context);
3341 if (t.cat() == catComment) {
3342 parse_comment(p, os, t, context);
3347 // control sequences
3350 if (t.cs() == "(" || t.cs() == "[") {
3351 bool const simple = t.cs() == "(";
3352 context.check_layout(os);
3353 begin_inset(os, "Formula");
3354 os << " \\" << t.cs();
3355 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3356 os << '\\' << (simple ? ')' : ']');
3359 // Prevent the conversion of a line break to a
3360 // space (bug 7668). This does not change the
3361 // output, but looks ugly in LyX.
3362 eat_whitespace(p, os, context, false);
3367 if (t.cs() == "begin") {
3368 parse_environment(p, os, outer, last_env,
3373 if (t.cs() == "end") {
3374 if (flags & FLAG_END) {
3375 // eat environment name
3376 string const name = p.getArg('{', '}');
3377 if (name != active_environment())
3378 cerr << "\\end{" + name + "} does not match \\begin{"
3379 + active_environment() + "}\n";
3382 p.error("found 'end' unexpectedly");
3386 // "item" by default, but could be something else
3387 if (t.cs() == context.layout->itemcommand()) {
3389 if (context.layout->labeltype == LABEL_MANUAL) {
3390 // FIXME: This swallows comments, but we cannot use
3391 // eat_whitespace() since we must not output
3392 // anything before the item.
3393 p.skip_spaces(true);
3394 s = p.verbatimOption();
3396 p.skip_spaces(false);
3398 context.check_layout(os);
3399 if (context.has_item) {
3400 // An item in an unknown list-like environment
3401 // FIXME: Do this in check_layout()!
3402 context.has_item = false;
3403 string item = "\\" + context.layout->itemcommand();
3406 output_ert_inset(os, item, context);
3408 if (context.layout->labeltype != LABEL_MANUAL)
3409 output_arguments(os, p, outer, false, "item", context,
3410 context.layout->itemargs());
3411 if (!context.list_preamble.empty()) {
3412 // We have a list preamble. Output it here.
3413 begin_inset(os, "Argument listpreamble:1");
3414 os << "\nstatus collapsed\n\n"
3415 << "\\begin_layout Plain Layout\n\n"
3416 << rtrim(context.list_preamble)
3417 << "\n\\end_layout";
3419 context.list_preamble.clear();
3421 if (!context.list_extra_stuff.empty()) {
3422 os << context.list_extra_stuff;
3423 context.list_extra_stuff.clear();
3425 else if (!s.empty()) {
3426 // LyX adds braces around the argument,
3427 // so we need to remove them here.
3428 if (s.size() > 2 && s[0] == '{' &&
3429 s[s.size()-1] == '}')
3430 s = s.substr(1, s.size()-2);
3431 // If the argument contains a space we
3432 // must put it into ERT: Otherwise LyX
3433 // would misinterpret the space as
3434 // item delimiter (bug 7663)
3435 if (contains(s, ' ')) {
3436 output_ert_inset(os, s, context);
3439 os << parse_text_snippet(p2,
3440 FLAG_BRACK_LAST, outer, context);
3442 // The space is needed to separate the
3443 // item from the rest of the sentence.
3445 eat_whitespace(p, os, context, false);
3450 if (t.cs() == "bibitem") {
3452 context.check_layout(os);
3453 eat_whitespace(p, os, context, false);
3454 string label = p.verbatimOption();
3455 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3456 bool const literal = !lbl.first;
3457 label = literal ? subst(label, "\n", " ") : lbl.second;
3458 string lit = literal ? "\"true\"" : "\"false\"";
3459 string key = convert_literate_command_inset_arg(p.verbatim_item());
3460 begin_command_inset(os, "bibitem", "bibitem");
3461 os << "label \"" << label << "\"\n"
3462 << "key \"" << key << "\"\n"
3463 << "literal " << lit << "\n";
3469 // catch the case of \def\inputGnumericTable
3471 if (t.cs() == "def") {
3472 Token second = p.next_token();
3473 if (second.cs() == "inputGnumericTable") {
3477 Token third = p.get_token();
3479 if (third.cs() == "input") {
3483 string name = normalize_filename(p.verbatim_item());
3484 string const path = getMasterFilePath(true);
3485 // We want to preserve relative / absolute filenames,
3486 // therefore path is only used for testing
3487 // The file extension is in every case ".tex".
3488 // So we need to remove this extension and check for
3489 // the original one.
3490 name = removeExtension(name);
3491 if (!makeAbsPath(name, path).exists()) {
3492 char const * const Gnumeric_formats[] = {"gnumeric",
3494 string const Gnumeric_name =
3495 find_file(name, path, Gnumeric_formats);
3496 if (!Gnumeric_name.empty())
3497 name = Gnumeric_name;
3499 FileName const absname = makeAbsPath(name, path);
3500 if (absname.exists()) {
3501 fix_child_filename(name);
3502 copy_file(absname, name);
3504 cerr << "Warning: Could not find file '"
3505 << name << "'." << endl;
3506 context.check_layout(os);
3507 begin_inset(os, "External\n\ttemplate ");
3508 os << "GnumericSpreadsheet\n\tfilename "
3511 context.check_layout(os);
3513 // register the packages that are automatically loaded
3514 // by the Gnumeric template
3515 registerExternalTemplatePackages("GnumericSpreadsheet");
3520 parse_macro(p, os, context);
3524 if (t.cs() == "noindent") {
3526 context.add_par_extra_stuff("\\noindent\n");
3530 if (t.cs() == "appendix") {
3531 context.add_par_extra_stuff("\\start_of_appendix\n");
3532 // We need to start a new paragraph. Otherwise the
3533 // appendix in 'bla\appendix\chapter{' would start
3535 context.new_paragraph(os);
3536 // We need to make sure that the paragraph is
3537 // generated even if it is empty. Otherwise the
3538 // appendix in '\par\appendix\par\chapter{' would
3540 context.check_layout(os);
3541 // FIXME: This is a hack to prevent paragraph
3542 // deletion if it is empty. Handle this better!
3543 output_comment(p, os,
3544 "dummy comment inserted by tex2lyx to "
3545 "ensure that this paragraph is not empty",
3547 // Both measures above may generate an additional
3548 // empty paragraph, but that does not hurt, because
3549 // whitespace does not matter here.
3550 eat_whitespace(p, os, context, true);
3554 // Must catch empty dates before findLayout is called below
3555 if (t.cs() == "date") {
3556 eat_whitespace(p, os, context, false);
3558 string const date = p.verbatim_item();
3561 preamble.suppressDate(true);
3564 preamble.suppressDate(false);
3565 if (context.new_layout_allowed &&
3566 (newlayout = findLayout(context.textclass,
3569 output_command_layout(os, p, outer,
3570 context, newlayout);
3571 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3572 if (!preamble.titleLayoutFound())
3573 preamble.titleLayoutFound(newlayout->intitle);
3574 set<string> const & req = newlayout->required();
3575 set<string>::const_iterator it = req.begin();
3576 set<string>::const_iterator en = req.end();
3577 for (; it != en; ++it)
3578 preamble.registerAutomaticallyLoadedPackage(*it);
3580 output_ert_inset(os,
3581 "\\date{" + p.verbatim_item() + '}',
3587 // Before we look for the layout name with star and alone below, we check the layouts including
3588 // the LateXParam, which might be one or several options or a star.
3589 // The single '=' is meant here.
3590 if (context.new_layout_allowed &&
3591 (newlayout = findLayout(context.textclass, t.cs(), true, p.getCommandLatexParam()))) {
3592 // store the latexparam here. This is eaten in output_command_layout
3593 context.latexparam = newlayout->latexparam();
3595 output_command_layout(os, p, outer, context, newlayout);
3596 context.latexparam.clear();
3598 if (!preamble.titleLayoutFound())
3599 preamble.titleLayoutFound(newlayout->intitle);
3600 set<string> const & req = newlayout->required();
3601 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3602 preamble.registerAutomaticallyLoadedPackage(*it);
3606 // Starred section headings
3607 // Must attempt to parse "Section*" before "Section".
3608 if ((p.next_token().asInput() == "*") &&
3609 context.new_layout_allowed &&
3610 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3613 output_command_layout(os, p, outer, context, newlayout);
3615 if (!preamble.titleLayoutFound())
3616 preamble.titleLayoutFound(newlayout->intitle);
3617 set<string> const & req = newlayout->required();
3618 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3619 preamble.registerAutomaticallyLoadedPackage(*it);
3623 // Section headings and the like
3624 if (context.new_layout_allowed &&
3625 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3627 output_command_layout(os, p, outer, context, newlayout);
3629 if (!preamble.titleLayoutFound())
3630 preamble.titleLayoutFound(newlayout->intitle);
3631 set<string> const & req = newlayout->required();
3632 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3633 preamble.registerAutomaticallyLoadedPackage(*it);
3637 if (t.cs() == "subfloat") {
3638 // the syntax is \subfloat[list entry][sub caption]{content}
3639 // if it is a table of figure depends on the surrounding float
3641 // do nothing if there is no outer float
3642 if (!float_type.empty()) {
3643 context.check_layout(os);
3645 begin_inset(os, "Float " + float_type + "\n");
3647 << "\nsideways false"
3648 << "\nstatus collapsed\n\n";
3651 bool has_caption = false;
3652 if (p.next_token().cat() != catEscape &&
3653 p.next_token().character() == '[') {
3654 p.get_token(); // eat '['
3655 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3658 // In case we have two optional args, the second is the caption.
3659 if (p.next_token().cat() != catEscape &&
3660 p.next_token().character() == '[') {
3661 p.get_token(); // eat '['
3662 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3665 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3666 // the caption comes always as the last
3668 // we must make sure that the caption gets a \begin_layout
3669 os << "\n\\begin_layout Plain Layout";
3671 begin_inset(os, "Caption Standard\n");
3672 Context newcontext(true, context.textclass,
3673 0, 0, context.font);
3674 newcontext.check_layout(os);
3675 os << caption << "\n";
3676 newcontext.check_end_layout(os);
3679 // close the layout we opened
3680 os << "\n\\end_layout";
3685 // if the float type is not supported or there is no surrounding float
3690 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3692 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3694 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3695 + "{" + p.verbatim_item() + '}', context);
3700 if (t.cs() == "xymatrix") {
3701 // we must open a new math because LyX's xy support is in math
3702 context.check_layout(os);
3703 begin_inset(os, "Formula ");
3705 os << "\\" << t.cs() << '{';
3706 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3709 preamble.registerAutomaticallyLoadedPackage("xy");
3713 if (t.cs() == "includegraphics") {
3714 bool const clip = p.next_token().asInput() == "*";
3717 string const arg = p.getArg('[', ']');
3718 map<string, string> opts;
3719 vector<string> keys;
3720 split_map(arg, opts, keys);
3722 opts["clip"] = string();
3723 string name = normalize_filename(p.verbatim_item());
3725 string const path = getMasterFilePath(true);
3726 // We want to preserve relative / absolute filenames,
3727 // therefore path is only used for testing
3728 if (!makeAbsPath(name, path).exists()) {
3729 // The file extension is probably missing.
3730 // Now try to find it out.
3731 string const dvips_name =
3732 find_file(name, path,
3733 known_dvips_graphics_formats);
3734 string const pdftex_name =
3735 find_file(name, path,
3736 known_pdftex_graphics_formats);
3737 if (!dvips_name.empty()) {
3738 if (!pdftex_name.empty()) {
3739 cerr << "This file contains the "
3741 "\"\\includegraphics{"
3743 "However, files\n\""
3744 << dvips_name << "\" and\n\""
3745 << pdftex_name << "\"\n"
3746 "both exist, so I had to make a "
3747 "choice and took the first one.\n"
3748 "Please move the unwanted one "
3749 "someplace else and try again\n"
3750 "if my choice was wrong."
3754 } else if (!pdftex_name.empty()) {
3760 FileName const absname = makeAbsPath(name, path);
3761 if (absname.exists()) {
3762 fix_child_filename(name);
3763 copy_file(absname, name);
3765 cerr << "Warning: Could not find graphics file '"
3766 << name << "'." << endl;
3768 context.check_layout(os);
3769 begin_inset(os, "Graphics ");
3770 os << "\n\tfilename " << name << '\n';
3771 if (opts.find("width") != opts.end())
3773 << translate_len(opts["width"]) << '\n';
3774 if (opts.find("totalheight") != opts.end())
3776 << translate_len(opts["totalheight"]) << '\n';
3777 if (opts.find("scale") != opts.end()) {
3778 istringstream iss(opts["scale"]);
3782 os << "\tscale " << val << '\n';
3784 if (opts.find("angle") != opts.end()) {
3785 os << "\trotateAngle "
3786 << opts["angle"] << '\n';
3787 vector<string>::const_iterator a =
3788 find(keys.begin(), keys.end(), "angle");
3789 vector<string>::const_iterator s =
3790 find(keys.begin(), keys.end(), "width");
3791 if (s == keys.end())
3792 s = find(keys.begin(), keys.end(), "totalheight");
3793 if (s == keys.end())
3794 s = find(keys.begin(), keys.end(), "scale");
3795 if (s != keys.end() && distance(s, a) > 0)
3796 os << "\tscaleBeforeRotation\n";
3798 if (opts.find("origin") != opts.end()) {
3800 string const opt = opts["origin"];
3801 if (opt.find('l') != string::npos) ss << "left";
3802 if (opt.find('r') != string::npos) ss << "right";
3803 if (opt.find('c') != string::npos) ss << "center";
3804 if (opt.find('t') != string::npos) ss << "Top";
3805 if (opt.find('b') != string::npos) ss << "Bottom";
3806 if (opt.find('B') != string::npos) ss << "Baseline";
3807 if (!ss.str().empty())
3808 os << "\trotateOrigin " << ss.str() << '\n';
3810 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3812 if (opts.find("keepaspectratio") != opts.end())
3813 os << "\tkeepAspectRatio\n";
3814 if (opts.find("clip") != opts.end())
3816 if (opts.find("draft") != opts.end())
3818 if (opts.find("bb") != opts.end())
3819 os << "\tBoundingBox "
3820 << opts["bb"] << '\n';
3821 int numberOfbbOptions = 0;
3822 if (opts.find("bbllx") != opts.end())
3823 numberOfbbOptions++;
3824 if (opts.find("bblly") != opts.end())
3825 numberOfbbOptions++;
3826 if (opts.find("bburx") != opts.end())
3827 numberOfbbOptions++;
3828 if (opts.find("bbury") != opts.end())
3829 numberOfbbOptions++;
3830 if (numberOfbbOptions == 4)
3831 os << "\tBoundingBox "
3832 << opts["bbllx"] << " " << opts["bblly"] << " "
3833 << opts["bburx"] << " " << opts["bbury"] << '\n';
3834 else if (numberOfbbOptions > 0)
3835 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3836 numberOfbbOptions = 0;
3837 if (opts.find("natwidth") != opts.end())
3838 numberOfbbOptions++;
3839 if (opts.find("natheight") != opts.end())
3840 numberOfbbOptions++;
3841 if (numberOfbbOptions == 2)
3842 os << "\tBoundingBox 0bp 0bp "
3843 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3844 else if (numberOfbbOptions > 0)
3845 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3846 ostringstream special;
3847 if (opts.find("hiresbb") != opts.end())
3848 special << "hiresbb,";
3849 if (opts.find("trim") != opts.end())
3851 if (opts.find("viewport") != opts.end())
3852 special << "viewport=" << opts["viewport"] << ',';
3853 if (opts.find("height") != opts.end())
3854 special << "height=" << opts["height"] << ',';
3855 if (opts.find("type") != opts.end())
3856 special << "type=" << opts["type"] << ',';
3857 if (opts.find("ext") != opts.end())
3858 special << "ext=" << opts["ext"] << ',';
3859 if (opts.find("read") != opts.end())
3860 special << "read=" << opts["read"] << ',';
3861 if (opts.find("command") != opts.end())
3862 special << "command=" << opts["command"] << ',';
3863 string s_special = special.str();
3864 if (!s_special.empty()) {
3865 // We had special arguments. Remove the trailing ','.
3866 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3868 // TODO: Handle the unknown settings better.
3869 // Warn about invalid options.
3870 // Check whether some option was given twice.
3872 preamble.registerAutomaticallyLoadedPackage("graphicx");
3876 if (t.cs() == "footnote" ||
3877 (t.cs() == "thanks" && context.layout->intitle)) {
3879 context.check_layout(os);
3880 begin_inset(os, "Foot\n");
3881 os << "status collapsed\n\n";
3882 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3887 if (t.cs() == "marginpar") {
3889 context.check_layout(os);
3890 begin_inset(os, "Marginal\n");
3891 os << "status collapsed\n\n";
3892 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3897 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3898 bool const use_minted = t.cs() == "mintinline";
3900 parse_listings(p, os, context, true, use_minted);
3904 if (t.cs() == "ensuremath") {
3906 context.check_layout(os);
3907 string const s = p.verbatim_item();
3908 //FIXME: this never triggers in UTF8
3909 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3912 output_ert_inset(os, "\\ensuremath{" + s + "}",
3917 else if (t.cs() == "makeindex"
3918 || ((t.cs() == "maketitle" || t.cs() == context.textclass.titlename())
3919 && context.textclass.titletype() == TITLE_COMMAND_AFTER)) {
3920 if (preamble.titleLayoutFound()) {
3922 skip_spaces_braces(p);
3924 output_ert_inset(os, t.asInput(), context);
3928 if (t.cs() == "tableofcontents"
3929 || t.cs() == "lstlistoflistings"
3930 || t.cs() == "listoflistings") {
3931 string name = t.cs();
3932 if (preamble.minted() && name == "listoflistings")
3933 name.insert(0, "lst");
3934 context.check_layout(os);
3935 begin_command_inset(os, "toc", name);
3937 skip_spaces_braces(p);
3938 if (name == "lstlistoflistings") {
3939 if (preamble.minted())
3940 preamble.registerAutomaticallyLoadedPackage("minted");
3942 preamble.registerAutomaticallyLoadedPackage("listings");
3947 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3948 context.check_layout(os);
3949 if (t.cs() == "listoffigures")
3950 begin_inset(os, "FloatList figure\n");
3952 begin_inset(os, "FloatList table\n");
3954 skip_spaces_braces(p);
3958 if (t.cs() == "listof") {
3959 p.skip_spaces(true);
3960 string const name = p.verbatim_item();
3961 if (context.textclass.floats().typeExist(name)) {
3962 context.check_layout(os);
3963 begin_inset(os, "FloatList ");
3966 p.verbatim_item(); // swallow second arg
3968 output_ert_inset(os, "\\listof{" + name + "}", context);
3972 if (t.cs() == "theendnotes"
3973 || (t.cs() == "printendnotes"
3974 && p.next_token().asInput() != "*"
3976 context.check_layout(os);
3977 begin_inset(os, "FloatList endnote\n");
3979 skip_spaces_braces(p);
3983 if ((where = is_known(t.cs(), known_text_font_families))) {
3984 parse_text_attributes(p, os, FLAG_ITEM, outer,
3985 context, "\\family", context.font.family,
3986 known_coded_font_families[where - known_text_font_families]);
3990 // beamer has a \textbf<overlay>{} inset
3991 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_series))) {
3992 parse_text_attributes(p, os, FLAG_ITEM, outer,
3993 context, "\\series", context.font.series,
3994 known_coded_font_series[where - known_text_font_series]);
3998 // beamer has a \textit<overlay>{} inset
3999 if (!p.hasOpt("<") && (where = is_known(t.cs(), known_text_font_shapes))) {
4000 parse_text_attributes(p, os, FLAG_ITEM, outer,
4001 context, "\\shape", context.font.shape,
4002 known_coded_font_shapes[where - known_text_font_shapes]);
4006 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
4007 context.check_layout(os);
4008 TeXFont oldFont = context.font;
4009 context.font.init();
4010 context.font.size = oldFont.size;
4011 os << "\n\\family " << context.font.family << "\n";
4012 os << "\n\\series " << context.font.series << "\n";
4013 os << "\n\\shape " << context.font.shape << "\n";
4014 if (t.cs() == "textnormal") {
4015 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4016 output_font_change(os, context.font, oldFont);
4017 context.font = oldFont;
4019 eat_whitespace(p, os, context, false);
4023 if (t.cs() == "textcolor") {
4024 // scheme is \textcolor{color name}{text}
4025 string const color = p.verbatim_item();
4026 // we support the predefined colors of the color and the xcolor package
4027 if (color == "black" || color == "blue" || color == "cyan"
4028 || color == "green" || color == "magenta" || color == "red"
4029 || color == "white" || color == "yellow") {
4030 context.check_layout(os);
4031 os << "\n\\color " << color << "\n";
4032 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4033 context.check_layout(os);
4034 os << "\n\\color inherit\n";
4035 preamble.registerAutomaticallyLoadedPackage("color");
4036 } else if (color == "brown" || color == "darkgray" || color == "gray"
4037 || color == "lightgray" || color == "lime" || color == "olive"
4038 || color == "orange" || color == "pink" || color == "purple"
4039 || color == "teal" || color == "violet") {
4040 context.check_layout(os);
4041 os << "\n\\color " << color << "\n";
4042 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4043 context.check_layout(os);
4044 os << "\n\\color inherit\n";
4045 preamble.registerAutomaticallyLoadedPackage("xcolor");
4047 // for custom defined colors
4048 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
4052 if (t.cs() == "underbar" || t.cs() == "uline") {
4053 // \underbar is not 100% correct (LyX outputs \uline
4054 // of ulem.sty). The difference is that \ulem allows
4055 // line breaks, and \underbar does not.
4056 // Do NOT handle \underline.
4057 // \underbar cuts through y, g, q, p etc.,
4058 // \underline does not.
4059 context.check_layout(os);
4060 os << "\n\\bar under\n";
4061 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4062 context.check_layout(os);
4063 os << "\n\\bar default\n";
4064 preamble.registerAutomaticallyLoadedPackage("ulem");
4068 if (t.cs() == "sout") {
4069 context.check_layout(os);
4070 os << "\n\\strikeout on\n";
4071 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4072 context.check_layout(os);
4073 os << "\n\\strikeout default\n";
4074 preamble.registerAutomaticallyLoadedPackage("ulem");
4078 // beamer has an \emph<overlay>{} inset
4079 if ((t.cs() == "uuline" || t.cs() == "uwave"
4080 || t.cs() == "emph" || t.cs() == "noun"
4081 || t.cs() == "xout") && !p.hasOpt("<")) {
4082 context.check_layout(os);
4083 os << "\n\\" << t.cs() << " on\n";
4084 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4085 context.check_layout(os);
4086 os << "\n\\" << t.cs() << " default\n";
4087 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
4088 preamble.registerAutomaticallyLoadedPackage("ulem");
4092 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted" || t.cs() == "lyxobjdeleted"
4093 || t.cs() == "lyxdisplayobjdeleted" || t.cs() == "lyxudisplayobjdeleted") {
4094 context.check_layout(os);
4097 initials = p.getArg('[', ']');
4099 string name = p.getArg('{', '}');
4100 string localtime = p.getArg('{', '}');
4101 preamble.registerAuthor(name, initials);
4102 Author const & author = preamble.getAuthor(name);
4103 // from_asctime_utc() will fail if LyX decides to output the
4104 // time in the text language.
4105 time_t ptime = from_asctime_utc(localtime);
4106 if (ptime == static_cast<time_t>(-1)) {
4107 cerr << "Warning: Could not parse time `" << localtime
4108 << "´ for change tracking, using current time instead.\n";
4109 ptime = current_time();
4111 if (t.cs() == "lyxadded")
4112 os << "\n\\change_inserted ";
4114 os << "\n\\change_deleted ";
4115 os << author.bufferId() << ' ' << ptime << '\n';
4116 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
4117 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
4118 LaTeXPackages::isAvailable("xcolor");
4119 // No need to test for luatex, since luatex comes in
4120 // two flavours (dvi and pdf), like latex, and those
4121 // are detected by pdflatex.
4122 if (pdflatex || xetex) {
4124 preamble.registerAutomaticallyLoadedPackage("ulem");
4125 preamble.registerAutomaticallyLoadedPackage("xcolor");
4126 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
4130 preamble.registerAutomaticallyLoadedPackage("ulem");
4131 preamble.registerAutomaticallyLoadedPackage("xcolor");
4137 if (t.cs() == "textipa") {
4138 context.check_layout(os);
4139 begin_inset(os, "IPA\n");
4140 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
4141 context.merging_hyphens_allowed = false;
4142 set<string> pass_thru_cmds = context.pass_thru_cmds;
4143 // These commands have special meanings in IPA
4144 context.pass_thru_cmds.insert("!");
4145 context.pass_thru_cmds.insert(";");
4146 context.pass_thru_cmds.insert(":");
4147 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4148 context.pass_thru_cmds = pass_thru_cmds;
4149 context.merging_hyphens_allowed = merging_hyphens_allowed;
4151 preamble.registerAutomaticallyLoadedPackage("tipa");
4152 preamble.registerAutomaticallyLoadedPackage("tipx");
4156 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
4157 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
4158 context.check_layout(os);
4162 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
4163 begin_inset(os, "IPADeco " + type + "\n");
4164 os << "status open\n";
4165 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
4171 if (t.cs() == "textvertline") {
4172 // FIXME: This is not correct, \textvertline is higher than |
4178 if (t.cs() == "tone" ) {
4179 context.check_layout(os);
4180 // register the tone package
4181 preamble.registerAutomaticallyLoadedPackage("tone");
4182 string content = trimSpaceAndEol(p.verbatim_item());
4183 string command = t.asInput() + "{" + content + "}";
4184 // some tones can be detected by unicodesymbols, some need special code
4185 if (is_known(content, known_tones)) {
4186 os << "\\IPAChar " << command << "\n";
4189 // try to see whether the string is in unicodesymbols
4193 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
4194 Encodings::TEXT_CMD | Encodings::MATH_CMD,
4195 termination, rem, &req);
4199 output_ert_inset(os, to_utf8(rem), context);
4200 for (set<string>::const_iterator it = req.begin();
4201 it != req.end(); ++it)
4202 preamble.registerAutomaticallyLoadedPackage(*it);
4204 // we did not find a non-ert version
4205 output_ert_inset(os, command, context);
4209 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
4210 t.cs() == "vphantom") {
4211 context.check_layout(os);
4212 if (t.cs() == "phantom")
4213 begin_inset(os, "Phantom Phantom\n");
4214 if (t.cs() == "hphantom")
4215 begin_inset(os, "Phantom HPhantom\n");
4216 if (t.cs() == "vphantom")
4217 begin_inset(os, "Phantom VPhantom\n");
4218 os << "status open\n";
4219 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
4225 if (t.cs() == "href") {
4226 context.check_layout(os);
4227 string target = convert_literate_command_inset_arg(p.verbatim_item());
4228 string name = p.verbatim_item();
4229 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
4230 bool const literal = !nm.first;
4231 name = literal ? subst(name, "\n", " ") : nm.second;
4232 string lit = literal ? "\"true\"" : "\"false\"";
4234 size_t i = target.find(':');
4235 if (i != string::npos) {
4236 type = target.substr(0, i + 1);
4237 if (type == "mailto:" || type == "file:")
4238 target = target.substr(i + 1);
4239 // handle the case that name is equal to target, except of "http(s)://"
4240 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
4243 begin_command_inset(os, "href", "href");
4245 os << "name \"" << name << "\"\n";
4246 os << "target \"" << target << "\"\n";
4247 if (type == "mailto:" || type == "file:")
4248 os << "type \"" << type << "\"\n";
4249 os << "literal " << lit << "\n";
4251 skip_spaces_braces(p);
4255 if (t.cs() == "lyxline") {
4256 // swallow size argument (it is not used anyway)
4258 if (!context.atParagraphStart()) {
4259 // so our line is in the middle of a paragraph
4260 // we need to add a new line, lest this line
4261 // follow the other content on that line and
4262 // run off the side of the page
4263 // FIXME: This may create an empty paragraph,
4264 // but without that it would not be
4265 // possible to set noindent below.
4266 // Fortunately LaTeX does not care
4267 // about the empty paragraph.
4268 context.new_paragraph(os);
4270 if (preamble.indentParagraphs()) {
4271 // we need to unindent, lest the line be too long
4272 context.add_par_extra_stuff("\\noindent\n");
4274 context.check_layout(os);
4275 begin_command_inset(os, "line", "rule");
4276 os << "offset \"0.5ex\"\n"
4277 "width \"100line%\"\n"
4283 if (t.cs() == "rule") {
4284 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
4285 string const width = p.getArg('{', '}');
4286 string const thickness = p.getArg('{', '}');
4287 context.check_layout(os);
4288 begin_command_inset(os, "line", "rule");
4289 if (!offset.empty())
4290 os << "offset \"" << translate_len(offset) << "\"\n";
4291 os << "width \"" << translate_len(width) << "\"\n"
4292 "height \"" << translate_len(thickness) << "\"\n";
4297 // Handle refstyle first in order to to catch \eqref, because this
4298 // can also occur without refstyle. Only recognize these commands if
4299 // refstyle.sty was found in the preamble (otherwise \eqref
4300 // and user defined ref commands could be misdetected).
4301 // We uncapitalize the input in order to catch capitalized commands
4303 if ((where = is_known(uncapitalize(t.cs()), known_refstyle_commands))
4304 && preamble.refstyle()) {
4305 string const cap = isCapitalized(t.cs()) ? "true" : "false";
4306 string plural = "false";
4307 // Catch the plural option [s]
4309 string const opt = p.getOpt();
4313 // LyX does not yet support other optional arguments of ref commands
4314 output_ert_inset(os, t.asInput() + opt + "{" +
4315 p.verbatim_item() + '}', context);
4319 context.check_layout(os);
4320 begin_command_inset(os, "ref", "formatted");
4321 os << "reference \"";
4322 os << known_refstyle_prefixes[where - known_refstyle_commands]
4324 os << convert_literate_command_inset_arg(p.getArg('{', '}'))
4326 os << "plural \"" << plural << "\"\n";
4327 os << "caps \"" << cap << "\"\n";
4328 os << "noprefix \"false\"\n";
4330 preamble.registerAutomaticallyLoadedPackage("refstyle");
4334 // if refstyle is used, we must not convert \prettyref to a
4335 // formatted reference, since that would result in a refstyle command.
4336 if ((where = is_known(t.cs(), known_ref_commands)) &&
4337 (t.cs() != "prettyref" || !preamble.refstyle())) {
4338 string const opt = p.getOpt();
4340 context.check_layout(os);
4341 begin_command_inset(os, "ref",
4342 known_coded_ref_commands[where - known_ref_commands]);
4343 os << "reference \""
4344 << convert_literate_command_inset_arg(p.verbatim_item())
4346 os << "plural \"false\"\n";
4347 os << "caps \"false\"\n";
4348 os << "noprefix \"false\"\n";
4350 if (t.cs() == "vref" || t.cs() == "vpageref")
4351 preamble.registerAutomaticallyLoadedPackage("varioref");
4352 else if (t.cs() == "prettyref")
4353 preamble.registerAutomaticallyLoadedPackage("prettyref");
4355 // LyX does not yet support optional arguments of ref commands
4356 output_ert_inset(os, t.asInput() + opt + "{" +
4357 p.verbatim_item() + '}', context);
4363 is_known(t.cs(), known_natbib_commands) &&
4364 ((t.cs() != "citefullauthor" &&
4365 t.cs() != "citeyear" &&
4366 t.cs() != "citeyearpar") ||
4367 p.next_token().asInput() != "*")) {
4368 context.check_layout(os);
4369 string command = t.cs();
4370 if (p.next_token().asInput() == "*") {
4374 if (command == "citefullauthor")
4375 // alternative name for "\\citeauthor*"
4376 command = "citeauthor*";
4378 // text before the citation
4380 // text after the citation
4382 get_cite_arguments(p, true, before, after);
4384 if (command == "cite") {
4385 // \cite without optional argument means
4386 // \citet, \cite with at least one optional
4387 // argument means \citep.
4388 if (before.empty() && after.empty())
4393 if (before.empty() && after == "[]")
4394 // avoid \citet[]{a}
4396 else if (before == "[]" && after == "[]") {
4397 // avoid \citet[][]{a}
4401 bool literal = false;
4402 pair<bool, string> aft;
4403 pair<bool, string> bef;
4404 // remove the brackets around after and before
4405 if (!after.empty()) {
4407 after.erase(after.length() - 1, 1);
4408 aft = convert_latexed_command_inset_arg(after);
4409 literal = !aft.first;
4410 after = literal ? subst(after, "\n", " ") : aft.second;
4412 if (!before.empty()) {
4414 before.erase(before.length() - 1, 1);
4415 bef = convert_latexed_command_inset_arg(before);
4416 literal |= !bef.first;
4417 before = literal ? subst(before, "\n", " ") : bef.second;
4418 if (literal && !after.empty())
4419 after = subst(after, "\n", " ");
4421 string lit = literal ? "\"true\"" : "\"false\"";
4422 begin_command_inset(os, "citation", command);
4423 os << "after " << '"' << after << '"' << "\n";
4424 os << "before " << '"' << before << '"' << "\n";
4426 << convert_literate_command_inset_arg(p.verbatim_item())
4428 << "literal " << lit << "\n";
4430 // Need to set the cite engine if natbib is loaded by
4431 // the document class directly
4432 if (preamble.citeEngine() == "basic")
4433 preamble.citeEngine("natbib");
4438 && is_known(t.cs(), known_biblatex_commands)
4439 && ((t.cs() == "cite"
4440 || t.cs() == "citeauthor"
4441 || t.cs() == "Citeauthor"
4442 || t.cs() == "parencite"
4443 || t.cs() == "citetitle")
4444 || p.next_token().asInput() != "*"))
4445 || (use_biblatex_natbib
4446 && (is_known(t.cs(), known_biblatex_commands)
4447 || is_known(t.cs(), known_natbib_commands))
4448 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4449 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4450 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4451 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4452 || t.cs() == "parencite" || t.cs() == "citetitle")
4453 || p.next_token().asInput() != "*"))){
4454 context.check_layout(os);
4455 string command = t.cs();
4456 if (p.next_token().asInput() == "*") {
4461 bool const qualified = suffixIs(command, "s");
4463 command = rtrim(command, "s");
4465 // text before the citation
4467 // text after the citation
4469 get_cite_arguments(p, true, before, after, qualified);
4471 // These use natbib cmd names in LyX
4472 // for inter-citeengine compativility
4473 if (command == "citeyear")
4474 command = "citebyear";
4475 else if (command == "cite*")
4476 command = "citeyear";
4477 else if (command == "textcite")
4479 else if (command == "Textcite")
4481 else if (command == "parencite")
4483 else if (command == "Parencite")
4485 else if (command == "parencite*")
4486 command = "citeyearpar";
4487 else if (command == "smartcite")
4488 command = "footcite";
4489 else if (command == "Smartcite")
4490 command = "Footcite";
4492 string const emptyarg = qualified ? "()" : "[]";
4493 if (before.empty() && after == emptyarg)
4496 else if (before == emptyarg && after == emptyarg) {
4497 // avoid \cite[][]{a}
4501 bool literal = false;
4502 pair<bool, string> aft;
4503 pair<bool, string> bef;
4504 // remove the brackets around after and before
4505 if (!after.empty()) {
4507 after.erase(after.length() - 1, 1);
4508 aft = convert_latexed_command_inset_arg(after);
4509 literal = !aft.first;
4510 after = literal ? subst(after, "\n", " ") : aft.second;
4512 if (!before.empty()) {
4514 before.erase(before.length() - 1, 1);
4515 bef = convert_latexed_command_inset_arg(before);
4516 literal |= !bef.first;
4517 before = literal ? subst(before, "\n", " ") : bef.second;
4519 string keys, pretextlist, posttextlist;
4521 vector<pair<string, string>> pres, posts, preslit, postslit;
4522 vector<string> lkeys;
4523 // text before the citation
4524 string lbefore, lbeforelit;
4525 // text after the citation
4526 string lafter, lafterlit;
4528 pair<bool, string> laft, lbef;
4530 get_cite_arguments(p, true, lbefore, lafter);
4531 // remove the brackets around after and before
4532 if (!lafter.empty()) {
4534 lafter.erase(lafter.length() - 1, 1);
4535 laft = convert_latexed_command_inset_arg(lafter);
4536 literal |= !laft.first;
4537 lafter = laft.second;
4538 lafterlit = subst(lafter, "\n", " ");
4540 if (!lbefore.empty()) {
4541 lbefore.erase(0, 1);
4542 lbefore.erase(lbefore.length() - 1, 1);
4543 lbef = convert_latexed_command_inset_arg(lbefore);
4544 literal |= !lbef.first;
4545 lbefore = lbef.second;
4546 lbeforelit = subst(lbefore, "\n", " ");
4548 if (lbefore.empty() && lafter == "[]") {
4553 else if (lbefore == "[]" && lafter == "[]") {
4554 // avoid \cite[][]{a}
4560 lkey = p.getArg('{', '}');
4563 pres.push_back(make_pair(lkey, lbefore));
4564 preslit.push_back(make_pair(lkey, lbeforelit));
4565 posts.push_back(make_pair(lkey, lafter));
4566 postslit.push_back(make_pair(lkey, lafterlit));
4567 lkeys.push_back(lkey);
4569 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4574 for (auto const & ptl : pres) {
4575 if (!pretextlist.empty())
4576 pretextlist += '\t';
4577 pretextlist += ptl.first;
4578 if (!ptl.second.empty())
4579 pretextlist += " " + ptl.second;
4581 for (auto const & potl : posts) {
4582 if (!posttextlist.empty())
4583 posttextlist += '\t';
4584 posttextlist += potl.first;
4585 if (!potl.second.empty())
4586 posttextlist += " " + potl.second;
4589 keys = convert_literate_command_inset_arg(p.verbatim_item());
4592 after = subst(after, "\n", " ");
4593 if (!before.empty())
4594 before = subst(after, "\n", " ");
4596 string lit = literal ? "\"true\"" : "\"false\"";
4597 begin_command_inset(os, "citation", command);
4598 os << "after " << '"' << after << '"' << "\n";
4599 os << "before " << '"' << before << '"' << "\n";
4603 if (!pretextlist.empty())
4604 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4605 if (!posttextlist.empty())
4606 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4607 os << "literal " << lit << "\n";
4609 // Need to set the cite engine if biblatex is loaded by
4610 // the document class directly
4611 if (preamble.citeEngine() == "basic")
4612 use_biblatex_natbib ?
4613 preamble.citeEngine("biblatex-natbib")
4614 : preamble.citeEngine("biblatex");
4619 is_known(t.cs(), known_jurabib_commands) &&
4620 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4621 context.check_layout(os);
4622 string command = t.cs();
4623 if (p.next_token().asInput() == "*") {
4627 char argumentOrder = '\0';
4628 vector<string> const options =
4629 preamble.getPackageOptions("jurabib");
4630 if (find(options.begin(), options.end(),
4631 "natbiborder") != options.end())
4632 argumentOrder = 'n';
4633 else if (find(options.begin(), options.end(),
4634 "jurabiborder") != options.end())
4635 argumentOrder = 'j';
4637 // text before the citation
4639 // text after the citation
4641 get_cite_arguments(p, argumentOrder != 'j', before, after);
4643 string const citation = p.verbatim_item();
4644 if (!before.empty() && argumentOrder == '\0') {
4645 cerr << "Warning: Assuming argument order "
4646 "of jurabib version 0.6 for\n'"
4647 << command << before << after << '{'
4648 << citation << "}'.\n"
4649 "Add 'jurabiborder' to the jurabib "
4650 "package options if you used an\n"
4651 "earlier jurabib version." << endl;
4653 bool literal = false;
4654 pair<bool, string> aft;
4655 pair<bool, string> bef;
4656 // remove the brackets around after and before
4657 if (!after.empty()) {
4659 after.erase(after.length() - 1, 1);
4660 aft = convert_latexed_command_inset_arg(after);
4661 literal = !aft.first;
4662 after = literal ? subst(after, "\n", " ") : aft.second;
4664 if (!before.empty()) {
4666 before.erase(before.length() - 1, 1);
4667 bef = convert_latexed_command_inset_arg(before);
4668 literal |= !bef.first;
4669 before = literal ? subst(before, "\n", " ") : bef.second;
4670 if (literal && !after.empty())
4671 after = subst(after, "\n", " ");
4673 string lit = literal ? "\"true\"" : "\"false\"";
4674 begin_command_inset(os, "citation", command);
4675 os << "after " << '"' << after << "\"\n"
4676 << "before " << '"' << before << "\"\n"
4677 << "key " << '"' << citation << "\"\n"
4678 << "literal " << lit << "\n";
4680 // Need to set the cite engine if jurabib is loaded by
4681 // the document class directly
4682 if (preamble.citeEngine() == "basic")
4683 preamble.citeEngine("jurabib");
4687 if (t.cs() == "cite"
4688 || t.cs() == "nocite") {
4689 context.check_layout(os);
4690 string after = p.getArg('[', ']');
4691 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4692 bool const literal = !aft.first;
4693 after = literal ? subst(after, "\n", " ") : aft.second;
4694 string lit = literal ? "\"true\"" : "\"false\"";
4695 string key = convert_literate_command_inset_arg(p.verbatim_item());
4696 // store the case that it is "\nocite{*}" to use it later for
4699 begin_command_inset(os, "citation", t.cs());
4700 os << "after " << '"' << after << "\"\n"
4701 << "key " << '"' << key << "\"\n"
4702 << "literal " << lit << "\n";
4704 } else if (t.cs() == "nocite")
4709 if (t.cs() == "index" ||
4710 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4711 context.check_layout(os);
4712 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4713 p.getArg('[', ']') : "";
4714 string const kind = arg.empty() ? "idx" : arg;
4715 begin_inset(os, "Index ");
4716 os << kind << "\nstatus collapsed\n";
4717 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4720 preamble.registerAutomaticallyLoadedPackage("splitidx");
4724 if (t.cs() == "nomenclature") {
4725 context.check_layout(os);
4726 begin_command_inset(os, "nomenclature", "nomenclature");
4727 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4728 if (!prefix.empty())
4729 os << "prefix " << '"' << prefix << '"' << "\n";
4730 string symbol = p.verbatim_item();
4731 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4732 bool literal = !sym.first;
4733 string description = p.verbatim_item();
4734 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4735 literal |= !desc.first;
4737 symbol = subst(symbol, "\n", " ");
4738 description = subst(description, "\n", " ");
4740 symbol = sym.second;
4741 description = desc.second;
4743 string lit = literal ? "\"true\"" : "\"false\"";
4744 os << "symbol " << '"' << symbol;
4745 os << "\"\ndescription \""
4746 << description << "\"\n"
4747 << "literal " << lit << "\n";
4749 preamble.registerAutomaticallyLoadedPackage("nomencl");
4753 if (t.cs() == "label") {
4754 context.check_layout(os);
4755 begin_command_inset(os, "label", "label");
4757 << convert_literate_command_inset_arg(p.verbatim_item())
4763 if (t.cs() == "lyxmintcaption") {
4764 string const pos = p.getArg('[', ']');
4766 string const caption =
4767 parse_text_snippet(p, FLAG_ITEM, false,
4769 minted_nonfloat_caption = "[t]" + caption;
4771 // We already got the caption at the bottom,
4772 // so simply skip it.
4773 parse_text_snippet(p, FLAG_ITEM, false, context);
4775 eat_whitespace(p, os, context, true);
4779 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4780 context.check_layout(os);
4781 string commandname = t.cs();
4783 if (p.next_token().asInput() == "*") {
4788 begin_command_inset(os, "index_print", commandname);
4789 string const indexname = p.getArg('[', ']');
4791 if (indexname.empty())
4792 os << "type \"idx\"\n";
4794 os << "type \"" << indexname << "\"\n";
4795 os << "literal \"true\"\n";
4798 skip_spaces_braces(p);
4799 preamble.registerAutomaticallyLoadedPackage("makeidx");
4800 if (preamble.use_indices() == "true")
4801 preamble.registerAutomaticallyLoadedPackage("splitidx");
4805 if (t.cs() == "printnomenclature") {
4807 string width_type = "";
4808 context.check_layout(os);
4809 begin_command_inset(os, "nomencl_print", "printnomenclature");
4810 // case of a custom width
4812 width = p.getArg('[', ']');
4813 width = translate_len(width);
4814 width_type = "custom";
4816 // case of no custom width
4817 // the case of no custom width but the width set
4818 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4819 // because the user could have set anything, not only the width
4820 // of the longest label (which would be width_type = "auto")
4821 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4822 if (label.empty() && width_type.empty())
4823 width_type = "none";
4824 os << "set_width \"" << width_type << "\"\n";
4825 if (width_type == "custom")
4826 os << "width \"" << width << '\"';
4828 skip_spaces_braces(p);
4829 preamble.registerAutomaticallyLoadedPackage("nomencl");
4833 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4834 context.check_layout(os);
4835 begin_inset(os, "script ");
4836 os << t.cs().substr(4) << '\n';
4837 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4838 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4840 if (t.cs() == "textsubscript")
4841 preamble.registerAutomaticallyLoadedPackage("subscript");
4845 if ((where = is_known(t.cs(), known_quotes))) {
4846 context.check_layout(os);
4847 begin_inset(os, "Quotes ");
4848 string quotetype = known_coded_quotes[where - known_quotes];
4849 // try to make a smart guess about the side
4850 Token const prev = p.prev_token();
4851 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4852 && prev.character() != '\n' && prev.character() != '~');
4853 quotetype = guessQuoteStyle(quotetype, opening);
4856 // LyX adds {} after the quote, so we have to eat
4857 // spaces here if there are any before a possible
4859 eat_whitespace(p, os, context, false);
4864 if ((where = is_known(t.cs(), known_sizes)) &&
4865 context.new_layout_allowed) {
4866 context.check_layout(os);
4867 TeXFont const oldFont = context.font;
4868 context.font.size = known_coded_sizes[where - known_sizes];
4869 output_font_change(os, oldFont, context.font);
4870 eat_whitespace(p, os, context, false);
4874 if ((where = is_known(t.cs(), known_font_families)) &&
4875 context.new_layout_allowed) {
4876 context.check_layout(os);
4877 TeXFont const oldFont = context.font;
4878 context.font.family =
4879 known_coded_font_families[where - known_font_families];
4880 output_font_change(os, oldFont, context.font);
4881 eat_whitespace(p, os, context, false);
4885 if ((where = is_known(t.cs(), known_font_series)) &&
4886 context.new_layout_allowed) {
4887 context.check_layout(os);
4888 TeXFont const oldFont = context.font;
4889 context.font.series =
4890 known_coded_font_series[where - known_font_series];
4891 output_font_change(os, oldFont, context.font);
4892 eat_whitespace(p, os, context, false);
4896 if ((where = is_known(t.cs(), known_font_shapes)) &&
4897 context.new_layout_allowed) {
4898 context.check_layout(os);
4899 TeXFont const oldFont = context.font;
4900 context.font.shape =
4901 known_coded_font_shapes[where - known_font_shapes];
4902 output_font_change(os, oldFont, context.font);
4903 eat_whitespace(p, os, context, false);
4906 if ((where = is_known(t.cs(), known_old_font_families)) &&
4907 context.new_layout_allowed) {
4908 context.check_layout(os);
4909 TeXFont const oldFont = context.font;
4910 context.font.init();
4911 context.font.size = oldFont.size;
4912 context.font.family =
4913 known_coded_font_families[where - known_old_font_families];
4914 output_font_change(os, oldFont, context.font);
4915 eat_whitespace(p, os, context, false);
4919 if ((where = is_known(t.cs(), known_old_font_series)) &&
4920 context.new_layout_allowed) {
4921 context.check_layout(os);
4922 TeXFont const oldFont = context.font;
4923 context.font.init();
4924 context.font.size = oldFont.size;
4925 context.font.series =
4926 known_coded_font_series[where - known_old_font_series];
4927 output_font_change(os, oldFont, context.font);
4928 eat_whitespace(p, os, context, false);
4932 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4933 context.new_layout_allowed) {
4934 context.check_layout(os);
4935 TeXFont const oldFont = context.font;
4936 context.font.init();
4937 context.font.size = oldFont.size;
4938 context.font.shape =
4939 known_coded_font_shapes[where - known_old_font_shapes];
4940 output_font_change(os, oldFont, context.font);
4941 eat_whitespace(p, os, context, false);
4945 if (t.cs() == "selectlanguage") {
4946 context.check_layout(os);
4947 // save the language for the case that a
4948 // \foreignlanguage is used
4949 context.font.language = babel2lyx(p.verbatim_item());
4950 os << "\n\\lang " << context.font.language << "\n";
4954 if (t.cs() == "foreignlanguage") {
4955 string const lang = babel2lyx(p.verbatim_item());
4956 parse_text_attributes(p, os, FLAG_ITEM, outer,
4958 context.font.language, lang);
4962 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4963 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4964 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4966 // We have to output the whole command if it has an option
4967 // because LyX doesn't support this yet, see bug #8214,
4968 // only if there is a single option specifying a variant, we can handle it.
4970 string langopts = p.getOpt();
4971 // check if the option contains a variant, if yes, extract it
4972 string::size_type pos_var = langopts.find("variant");
4973 string::size_type i = langopts.find(',');
4974 string::size_type k = langopts.find('=', pos_var);
4975 if (pos_var != string::npos && i == string::npos) {
4977 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4978 lang = preamble.polyglossia2lyx(variant);
4979 parse_text_attributes(p, os, FLAG_ITEM, outer,
4981 context.font.language, lang);
4983 output_ert_inset(os, t.asInput() + langopts, context);
4985 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4986 parse_text_attributes(p, os, FLAG_ITEM, outer,
4988 context.font.language, lang);
4993 if (t.cs() == "inputencoding") {
4994 // nothing to write here
4995 string const enc = subst(p.verbatim_item(), "\n", " ");
4996 p.setEncoding(enc, Encoding::inputenc);
5000 if (is_known(t.cs(), known_special_chars) ||
5001 (t.cs() == "protect" &&
5002 p.next_token().cat() == catEscape &&
5003 is_known(p.next_token().cs(), known_special_protect_chars))) {
5004 // LyX sometimes puts a \protect in front, so we have to ignore it
5006 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
5007 known_special_chars);
5008 context.check_layout(os);
5009 os << known_coded_special_chars[where - known_special_chars];
5010 skip_spaces_braces(p);
5014 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
5015 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
5016 p.next_next_token().asInput() == "-") ||
5017 (t.cs() == "@" && p.next_token().asInput() == ".")) {
5018 // LyX sometimes puts a \protect in front, so we have to ignore it
5019 if (t.cs() == "protect")
5021 context.check_layout(os);
5022 if (t.cs() == "nobreakdash")
5023 os << "\\SpecialChar nobreakdash\n";
5025 os << "\\SpecialChar endofsentence\n";
5030 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
5031 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
5032 || t.cs() == "%" || t.cs() == "-") {
5033 context.check_layout(os);
5035 os << "\\SpecialChar softhyphen\n";
5041 if (t.cs() == "char") {
5042 context.check_layout(os);
5043 if (p.next_token().character() == '`') {
5045 if (p.next_token().cs() == "\"") {
5050 output_ert_inset(os, "\\char`", context);
5053 output_ert_inset(os, "\\char", context);
5058 if (t.cs() == "verb") {
5059 context.check_layout(os);
5060 // set catcodes to verbatim early, just in case.
5061 p.setCatcodes(VERBATIM_CATCODES);
5062 string delim = p.get_token().asInput();
5063 Parser::Arg arg = p.verbatimStuff(delim);
5065 output_ert_inset(os, "\\verb" + delim
5066 + arg.second + delim, context);
5068 cerr << "invalid \\verb command. Skipping" << endl;
5072 // Problem: \= creates a tabstop inside the tabbing environment
5073 // and else an accent. In the latter case we really would want
5074 // \={o} instead of \= o.
5075 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
5076 output_ert_inset(os, t.asInput(), context);
5080 if (t.cs() == "\\") {
5081 context.check_layout(os);
5083 output_ert_inset(os, "\\\\" + p.getOpt(), context);
5084 else if (p.next_token().asInput() == "*") {
5086 // getOpt() eats the following space if there
5087 // is no optional argument, but that is OK
5088 // here since it has no effect in the output.
5089 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
5092 begin_inset(os, "Newline newline");
5098 if (t.cs() == "newline" ||
5099 (t.cs() == "linebreak" && !p.hasOpt())) {
5100 context.check_layout(os);
5101 begin_inset(os, "Newline ");
5104 skip_spaces_braces(p);
5108 if (t.cs() == "endgraf" && context.in_table_cell) {
5109 context.new_paragraph(os);
5110 context.check_layout(os);
5111 skip_spaces_braces(p);
5115 if (t.cs() == "input" || t.cs() == "include"
5116 || t.cs() == "verbatiminput"
5117 || t.cs() == "lstinputlisting"
5118 || t.cs() == "inputminted") {
5119 string name = t.cs();
5120 if (name == "verbatiminput"
5121 && p.next_token().asInput() == "*")
5122 name += p.get_token().asInput();
5123 context.check_layout(os);
5125 bool literal = false;
5126 if (name == "lstinputlisting" && p.hasOpt()) {
5127 lstparams = p.getArg('[', ']');
5128 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5129 literal = !oa.first;
5131 lstparams = subst(lstparams, "\n", " ");
5133 lstparams = oa.second;
5134 } else if (name == "inputminted") {
5135 name = "lstinputlisting";
5136 string const lang = p.getArg('{', '}');
5137 if (lang != "tex") {
5138 string cmd = "\\inputminted{" + lang + "}{";
5139 cmd += p.getArg('{', '}') + "}";
5140 output_ert_inset(os, cmd, context);
5143 if (prefixIs(minted_nonfloat_caption, "[t]")) {
5144 minted_nonfloat_caption.erase(0,3);
5145 // extract label and caption from the already produced LyX code
5146 vector<string> nfc = getVectorFromString(minted_nonfloat_caption, "\n");
5147 string const caption = nfc.front();
5149 vector<string>::iterator it =
5150 find(nfc.begin(), nfc.end(), "LatexCommand label");
5151 if (it != nfc.end()) {
5153 if (it != nfc.end())
5155 label = support::split(label, '"');
5158 minted_nonfloat_caption.clear();
5159 lstparams = "caption=" + caption;
5161 lstparams += ",label=" + label;
5162 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
5163 literal = !oa.first;
5165 lstparams = subst(lstparams, "\n", " ");
5167 lstparams = oa.second;
5170 string lit = literal ? "\"true\"" : "\"false\"";
5171 string filename(normalize_filename(p.getArg('{', '}')));
5172 string const path = getMasterFilePath(true);
5173 // We want to preserve relative / absolute filenames,
5174 // therefore path is only used for testing
5175 if ((t.cs() == "include" || t.cs() == "input") &&
5176 !makeAbsPath(filename, path).exists()) {
5177 // The file extension is probably missing.
5178 // Now try to find it out.
5179 string const tex_name =
5180 find_file(filename, path,
5181 known_tex_extensions);
5182 if (!tex_name.empty())
5183 filename = tex_name;
5185 bool external = false;
5187 if (makeAbsPath(filename, path).exists()) {
5188 string const abstexname =
5189 makeAbsPath(filename, path).absFileName();
5190 string const absfigname =
5191 changeExtension(abstexname, ".fig");
5192 fix_child_filename(filename);
5193 string const lyxname = changeExtension(filename,
5194 roundtripMode() ? ".lyx.lyx" : ".lyx");
5195 string const abslyxname = makeAbsPath(
5196 lyxname, getParentFilePath(false)).absFileName();
5198 if (!skipChildren())
5199 external = FileName(absfigname).exists();
5200 if (t.cs() == "input" && !skipChildren()) {
5201 string const ext = getExtension(abstexname);
5203 // Combined PS/LaTeX:
5204 // x.eps, x.pstex_t (old xfig)
5205 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
5206 FileName const absepsname(
5207 changeExtension(abstexname, ".eps"));
5208 FileName const abspstexname(
5209 changeExtension(abstexname, ".pstex"));
5210 bool const xfigeps =
5211 (absepsname.exists() ||
5212 abspstexname.exists()) &&
5215 // Combined PDF/LaTeX:
5216 // x.pdf, x.pdftex_t (old xfig)
5217 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
5218 FileName const abspdfname(
5219 changeExtension(abstexname, ".pdf"));
5220 bool const xfigpdf =
5221 abspdfname.exists() &&
5222 (ext == "pdftex_t" || ext == "pdf_t");
5226 // Combined PS/PDF/LaTeX:
5227 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
5228 string const absbase2(
5229 removeExtension(abstexname) + "_pspdftex");
5230 FileName const abseps2name(
5231 addExtension(absbase2, ".eps"));
5232 FileName const abspdf2name(
5233 addExtension(absbase2, ".pdf"));
5234 bool const xfigboth =
5235 abspdf2name.exists() &&
5236 abseps2name.exists() && ext == "pspdftex";
5238 xfig = xfigpdf || xfigeps || xfigboth;
5239 external = external && xfig;
5242 outname = changeExtension(filename, ".fig");
5243 FileName abssrc(changeExtension(abstexname, ".fig"));
5244 copy_file(abssrc, outname);
5246 // Don't try to convert, the result
5247 // would be full of ERT.
5249 FileName abssrc(abstexname);
5250 copy_file(abssrc, outname);
5251 } else if (t.cs() != "verbatiminput" &&
5253 tex2lyx(abstexname, FileName(abslyxname),
5256 // no need to call copy_file
5257 // tex2lyx creates the file
5260 FileName abssrc(abstexname);
5261 copy_file(abssrc, outname);
5264 cerr << "Warning: Could not find included file '"
5265 << filename << "'." << endl;
5269 begin_inset(os, "External\n");
5270 os << "\ttemplate XFig\n"
5271 << "\tfilename " << outname << '\n';
5272 registerExternalTemplatePackages("XFig");
5274 begin_command_inset(os, "include", name);
5275 outname = subst(outname, "\"", "\\\"");
5276 os << "preview false\n"
5277 "filename \"" << outname << "\"\n";
5278 if (!lstparams.empty())
5279 os << "lstparams \"" << lstparams << "\"\n";
5280 os << "literal " << lit << "\n";
5281 if (t.cs() == "verbatiminput")
5282 preamble.registerAutomaticallyLoadedPackage("verbatim");
5288 if (t.cs() == "bibliographystyle") {
5289 // store new bibliographystyle
5290 bibliographystyle = p.verbatim_item();
5291 // If any other command than \bibliography, \addcontentsline
5292 // and \nocite{*} follows, we need to output the style
5293 // (because it might be used by that command).
5294 // Otherwise, it will automatically be output by LyX.
5297 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
5298 if (t2.cat() == catBegin)
5300 if (t2.cat() != catEscape)
5302 if (t2.cs() == "nocite") {
5303 if (p.getArg('{', '}') == "*")
5305 } else if (t2.cs() == "bibliography")
5307 else if (t2.cs() == "phantomsection") {
5311 else if (t2.cs() == "addcontentsline") {
5312 // get the 3 arguments of \addcontentsline
5315 contentslineContent = p.getArg('{', '}');
5316 // if the last argument is not \refname we must output
5317 if (contentslineContent == "\\refname")
5324 output_ert_inset(os,
5325 "\\bibliographystyle{" + bibliographystyle + '}',
5331 if (t.cs() == "phantomsection") {
5332 // we only support this if it occurs between
5333 // \bibliographystyle and \bibliography
5334 if (bibliographystyle.empty())
5335 output_ert_inset(os, "\\phantomsection", context);
5339 if (t.cs() == "addcontentsline") {
5340 context.check_layout(os);
5341 // get the 3 arguments of \addcontentsline
5342 string const one = p.getArg('{', '}');
5343 string const two = p.getArg('{', '}');
5344 string const three = p.getArg('{', '}');
5345 // only if it is a \refname, we support if for the bibtex inset
5346 if (contentslineContent != "\\refname") {
5347 output_ert_inset(os,
5348 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
5354 else if (t.cs() == "bibliography") {
5355 context.check_layout(os);
5357 begin_command_inset(os, "bibtex", "bibtex");
5358 if (!btprint.empty()) {
5359 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5360 // clear the string because the next BibTeX inset can be without the
5361 // \nocite{*} option
5364 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
5365 // Do we have addcontentsline?
5366 if (contentslineContent == "\\refname") {
5367 BibOpts = "bibtotoc";
5368 // clear string because next BibTeX inset can be without addcontentsline
5369 contentslineContent.clear();
5371 // Do we have a bibliographystyle set?
5372 if (!bibliographystyle.empty()) {
5373 if (BibOpts.empty())
5374 BibOpts = normalize_filename(bibliographystyle);
5376 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
5377 // clear it because each bibtex entry has its style
5378 // and we need an empty string to handle \phantomsection
5379 bibliographystyle.clear();
5381 os << "options " << '"' << BibOpts << '"' << "\n";
5382 if (p.getEncoding() != preamble.docencoding) {
5383 Encoding const * const enc = encodings.fromIconvName(
5384 p.getEncoding(), Encoding::inputenc, true);
5386 cerr << "Unknown bib encoding " << p.getEncoding()
5387 << ". Ignoring." << std::endl;
5389 os << "encoding " << '"' << enc->name() << '"' << "\n";
5395 if (t.cs() == "printbibliography") {
5396 context.check_layout(os);
5398 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5399 vector<string> opts = getVectorFromString(bbloptions);
5400 vector<string>::iterator it =
5401 find(opts.begin(), opts.end(), "heading=bibintoc");
5402 if (it != opts.end()) {
5404 BibOpts = "bibtotoc";
5406 bbloptions = getStringFromVector(opts);
5407 begin_command_inset(os, "bibtex", "bibtex");
5408 if (!btprint.empty()) {
5409 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
5410 // clear the string because the next BibTeX inset can be without the
5411 // \nocite{*} option
5415 for (auto const & bf : preamble.biblatex_bibliographies) {
5416 if (!bibfiles.empty())
5418 bibfiles += normalize_filename(bf);
5420 if (!bibfiles.empty())
5421 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5422 // Do we have addcontentsline?
5423 if (contentslineContent == "\\refname") {
5424 BibOpts = "bibtotoc";
5425 // clear string because next BibTeX inset can be without addcontentsline
5426 contentslineContent.clear();
5428 os << "options " << '"' << BibOpts << '"' << "\n";
5429 if (!bbloptions.empty())
5430 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5431 if (!preamble.bibencoding.empty()) {
5432 Encoding const * const enc = encodings.fromLaTeXName(
5433 preamble.bibencoding, Encoding::inputenc, true);
5435 cerr << "Unknown bib encoding " << preamble.bibencoding
5436 << ". Ignoring." << std::endl;
5438 os << "encoding " << '"' << enc->name() << '"' << "\n";
5441 for (auto const & bf : preamble.biblatex_encodings) {
5442 if (!bibfileencs.empty())
5443 bibfileencs += "\t";
5446 if (!bibfileencs.empty())
5447 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
5449 need_commentbib = false;
5453 if (t.cs() == "bibbysection") {
5454 context.check_layout(os);
5456 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
5457 vector<string> opts = getVectorFromString(bbloptions);
5458 vector<string>::iterator it =
5459 find(opts.begin(), opts.end(), "heading=bibintoc");
5460 if (it != opts.end()) {
5462 BibOpts = "bibtotoc";
5464 bbloptions = getStringFromVector(opts);
5465 begin_command_inset(os, "bibtex", "bibtex");
5466 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5468 for (auto const & bf : preamble.biblatex_bibliographies) {
5469 if (!bibfiles.empty())
5471 bibfiles += normalize_filename(bf);
5473 if (!bibfiles.empty())
5474 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5475 os << "options " << '"' << BibOpts << '"' << "\n";
5476 if (!bbloptions.empty())
5477 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5479 need_commentbib = false;
5483 if (t.cs() == "parbox") {
5484 // Test whether this is an outer box of a shaded box
5486 // swallow arguments
5487 while (p.hasOpt()) {
5489 p.skip_spaces(true);
5492 p.skip_spaces(true);
5494 if (p.next_token().cat() == catBegin)
5496 p.skip_spaces(true);
5497 Token to = p.get_token();
5498 bool shaded = false;
5499 if (to.asInput() == "\\begin") {
5500 p.skip_spaces(true);
5501 if (p.getArg('{', '}') == "shaded")
5506 parse_outer_box(p, os, FLAG_ITEM, outer,
5507 context, "parbox", "shaded");
5509 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5510 "", "", t.cs(), "", "");
5514 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5515 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5516 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5517 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5521 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5522 string backgroundcolor;
5523 preamble.registerAutomaticallyLoadedPackage("xcolor");
5524 if (t.cs() == "fcolorbox") {
5525 string const framecolor = p.getArg('{', '}');
5526 backgroundcolor = p.getArg('{', '}');
5527 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5529 backgroundcolor = p.getArg('{', '}');
5530 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5535 // FIXME: due to the compiler limit of "if" nestings
5536 // the code for the alignment was put here
5537 // put them in their own if if this is fixed
5538 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5539 || t.cs() == "shadowsize") {
5540 if (t.cs() == "fboxrule")
5542 if (t.cs() == "fboxsep")
5544 if (t.cs() == "shadowsize")
5546 p.skip_spaces(true);
5547 while (p.good() && p.next_token().cat() != catSpace
5548 && p.next_token().cat() != catNewline
5549 && p.next_token().cat() != catEscape) {
5550 if (t.cs() == "fboxrule")
5551 fboxrule = fboxrule + p.get_token().asInput();
5552 if (t.cs() == "fboxsep")
5553 fboxsep = fboxsep + p.get_token().asInput();
5554 if (t.cs() == "shadowsize")
5555 shadow_size = shadow_size + p.get_token().asInput();
5560 if (t.cs() == "raggedleft" || t.cs() == "centering" || t.cs() == "raggedright") {
5561 if (context.in_table_cell) {
5562 if (t.cs() == "raggedleft")
5563 context.cell_align = 'r';
5564 else if (t.cs() == "centering")
5565 context.cell_align = 'c';
5566 else if (t.cs() == "raggedright")
5567 context.cell_align = 'l';
5568 p.skip_spaces(true);
5570 output_ert_inset(os, t.asInput(), context);
5575 //\framebox() is part of the picture environment and different from \framebox{}
5576 //\framebox{} will be parsed by parse_outer_box
5577 if (t.cs() == "framebox") {
5578 if (p.next_token().character() == '(') {
5579 //the syntax is: \framebox(x,y)[position]{content}
5580 string arg = t.asInput();
5581 arg += p.getFullParentheseArg();
5582 arg += p.getFullOpt();
5583 eat_whitespace(p, os, context, false);
5584 output_ert_inset(os, arg + '{', context);
5585 parse_text(p, os, FLAG_ITEM, outer, context);
5586 output_ert_inset(os, "}", context);
5588 //the syntax is: \framebox[width][position]{content}
5589 string special = p.getFullOpt();
5590 special += p.getOpt();
5591 parse_outer_box(p, os, FLAG_ITEM, outer,
5592 context, t.cs(), special);
5597 //\makebox() is part of the picture environment and different from \makebox{}
5598 //\makebox{} will be parsed by parse_box
5599 if (t.cs() == "makebox") {
5600 if (p.next_token().character() == '(') {
5601 //the syntax is: \makebox(x,y)[position]{content}
5602 string arg = t.asInput();
5603 arg += p.getFullParentheseArg();
5604 arg += p.getFullOpt();
5605 eat_whitespace(p, os, context, false);
5606 output_ert_inset(os, arg + '{', context);
5607 parse_text(p, os, FLAG_ITEM, outer, context);
5608 output_ert_inset(os, "}", context);
5610 //the syntax is: \makebox[width][position]{content}
5611 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5612 "", "", t.cs(), "", "");
5616 if (t.cs() == "smallskip" ||
5617 t.cs() == "medskip" ||
5618 t.cs() == "bigskip" ||
5619 t.cs() == "vfill") {
5620 context.check_layout(os);
5621 begin_inset(os, "VSpace ");
5624 skip_spaces_braces(p);
5628 if ((where = is_known(t.cs(), known_spaces))
5629 && (context.pass_thru_cmds.find(t.cs()) == context.pass_thru_cmds.end())) {
5630 context.check_layout(os);
5631 begin_inset(os, "space ");
5632 os << '\\' << known_coded_spaces[where - known_spaces]
5635 // LaTeX swallows whitespace after all spaces except
5636 // "\\,", "\\>", "\\!", "\\;", and "\\:".
5637 // We have to do that here, too, because LyX
5638 // adds "{}" which would make the spaces significant.
5639 if (!contains(",>!;:", t.cs()))
5640 eat_whitespace(p, os, context, false);
5641 // LyX adds "{}" after all spaces except "\\ " and
5642 // "\\,", so we have to remove "{}".
5643 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5644 // remove the braces after "\\,", too.
5650 if (t.cs() == "newpage" ||
5651 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5652 t.cs() == "clearpage" ||
5653 t.cs() == "cleardoublepage" ||
5654 t.cs() == "nopagebreak") {
5655 context.check_layout(os);
5656 begin_inset(os, "Newpage ");
5659 skip_spaces_braces(p);
5663 if (t.cs() == "DeclareRobustCommand" ||
5664 t.cs() == "DeclareRobustCommandx" ||
5665 t.cs() == "newcommand" ||
5666 t.cs() == "newcommandx" ||
5667 t.cs() == "providecommand" ||
5668 t.cs() == "providecommandx" ||
5669 t.cs() == "renewcommand" ||
5670 t.cs() == "renewcommandx") {
5671 // DeclareRobustCommand, DeclareRobustCommandx,
5672 // providecommand and providecommandx could be handled
5673 // by parse_command(), but we need to call
5674 // add_known_command() here.
5675 string name = t.asInput();
5676 if (p.next_token().asInput() == "*") {
5677 // Starred form. Eat '*'
5681 string const command = p.verbatim_item();
5682 string const opt1 = p.getFullOpt();
5683 string const opt2 = p.getFullOpt();
5684 add_known_command(command, opt1, !opt2.empty());
5685 string const ert = name + '{' + command + '}' +
5687 '{' + p.verbatim_item() + '}';
5689 if (t.cs() == "DeclareRobustCommand" ||
5690 t.cs() == "DeclareRobustCommandx" ||
5691 t.cs() == "providecommand" ||
5692 t.cs() == "providecommandx" ||
5693 name[name.length()-1] == '*')
5694 output_ert_inset(os, ert, context);
5696 context.check_layout(os);
5697 begin_inset(os, "FormulaMacro");
5704 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5705 // let could be handled by parse_command(),
5706 // but we need to call add_known_command() here.
5707 string ert = t.asInput();
5710 if (p.next_token().cat() == catBegin) {
5711 name = p.verbatim_item();
5712 ert += '{' + name + '}';
5714 name = p.verbatim_item();
5719 if (p.next_token().cat() == catBegin) {
5720 command = p.verbatim_item();
5721 ert += '{' + command + '}';
5723 command = p.verbatim_item();
5726 // If command is known, make name known too, to parse
5727 // its arguments correctly. For this reason we also
5728 // have commands in syntax.default that are hardcoded.
5729 CommandMap::iterator it = known_commands.find(command);
5730 if (it != known_commands.end())
5731 known_commands[t.asInput()] = it->second;
5732 output_ert_inset(os, ert, context);
5736 if (t.cs() == "hspace" || t.cs() == "vspace") {
5739 string name = t.asInput();
5740 string const length = p.verbatim_item();
5743 bool valid = splitLatexLength(length, valstring, unit);
5744 bool known_hspace = false;
5745 bool known_vspace = false;
5746 bool known_unit = false;
5749 istringstream iss(valstring);
5752 if (t.cs()[0] == 'h') {
5753 if (unit == "\\fill") {
5758 known_hspace = true;
5761 if (unit == "\\smallskipamount") {
5763 known_vspace = true;
5764 } else if (unit == "\\medskipamount") {
5766 known_vspace = true;
5767 } else if (unit == "\\bigskipamount") {
5769 known_vspace = true;
5770 } else if (length == "\\baselineskip") {
5772 known_vspace = true;
5773 } else if (unit == "\\fill") {
5775 known_vspace = true;
5779 if (value == 0.5 && t.cs()[0] != 'h' && unit == "\\baselineskip") {
5781 known_vspace = true;
5783 if (!known_hspace && !known_vspace) {
5784 switch (unitFromString(unit)) {
5800 //unitFromString(unit) fails for relative units like Length::PCW
5801 // therefore handle them separately
5802 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5803 || unit == "\\textwidth" || unit == "\\linewidth"
5804 || unit == "\\textheight" || unit == "\\paperheight"
5805 || unit == "\\baselineskip")
5813 // check for glue lengths
5814 bool is_gluelength = false;
5815 string gluelength = length;
5816 string::size_type i = length.find(" minus");
5817 if (i == string::npos) {
5818 i = length.find(" plus");
5819 if (i != string::npos)
5820 is_gluelength = true;
5822 is_gluelength = true;
5823 // if yes transform "9xx minus 8yy plus 7zz"
5825 if (is_gluelength) {
5826 i = gluelength.find(" minus");
5827 if (i != string::npos)
5828 gluelength.replace(i, 7, "-");
5829 i = gluelength.find(" plus");
5830 if (i != string::npos)
5831 gluelength.replace(i, 6, "+");
5834 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5835 // Literal horizontal length or known variable
5836 context.check_layout(os);
5837 begin_inset(os, "space ");
5845 if (known_unit && !known_hspace)
5846 os << "\n\\length " << translate_len(length);
5848 os << "\n\\length " << gluelength;
5850 } else if (known_unit || known_vspace || is_gluelength) {
5851 // Literal vertical length or known variable
5852 context.check_layout(os);
5853 begin_inset(os, "VSpace ");
5856 if (known_unit && !known_vspace)
5857 os << translate_len(length);
5864 // LyX can't handle other length variables in Inset VSpace/space
5869 output_ert_inset(os, name + '{' + unit + '}', context);
5870 else if (value == -1.0)
5871 output_ert_inset(os, name + "{-" + unit + '}', context);
5873 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5875 output_ert_inset(os, name + '{' + length + '}', context);
5880 // Before we look for the layout name alone below, we check the layouts including the LateXParam, which
5881 // might be one or several options or a star.
5882 // The single '=' is meant here.
5883 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true, p.getCommandLatexParam()))) {
5887 context.check_layout(os);
5888 // store the latexparam here. This is eaten in parse_text_in_inset
5889 context.latexparam = newinsetlayout->latexparam();
5890 docstring name = newinsetlayout->name();
5891 bool const caption = name.find(from_ascii("Caption:")) == 0;
5893 // Already done for floating minted listings.
5894 if (minted_float.empty()) {
5895 begin_inset(os, "Caption ");
5896 os << to_utf8(name.substr(8)) << '\n';
5899 // FIXME: what do we do if the prefix is not Flex: ?
5900 if (prefixIs(name, from_ascii("Flex:")))
5902 begin_inset(os, "Flex ");
5903 os << to_utf8(name) << '\n'
5904 << "status collapsed\n";
5906 if (!minted_float.empty()) {
5907 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5908 } else if (newinsetlayout->isPassThru()) {
5909 // set catcodes to verbatim early, just in case.
5910 p.setCatcodes(VERBATIM_CATCODES);
5911 string delim = p.get_token().asInput();
5913 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5914 //FIXME: handle error condition
5915 string const arg = p.verbatimStuff("}").second;
5916 Context newcontext(true, context.textclass);
5917 if (newinsetlayout->forcePlainLayout())
5918 newcontext.layout = &context.textclass.plainLayout();
5919 output_ert(os, arg, newcontext);
5921 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5922 context.latexparam.clear();
5925 // Minted caption insets are not closed here because
5926 // we collect everything into the caption.
5927 if (minted_float.empty())
5932 // The single '=' is meant here.
5933 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5937 context.check_layout(os);
5938 docstring name = newinsetlayout->name();
5939 bool const caption = name.find(from_ascii("Caption:")) == 0;
5941 // Already done for floating minted listings.
5942 if (minted_float.empty()) {
5943 begin_inset(os, "Caption ");
5944 os << to_utf8(name.substr(8)) << '\n';
5947 // FIXME: what do we do if the prefix is not Flex: ?
5948 if (prefixIs(name, from_ascii("Flex:")))
5950 begin_inset(os, "Flex ");
5951 os << to_utf8(name) << '\n'
5952 << "status collapsed\n";
5954 if (!minted_float.empty()) {
5955 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5956 } else if (newinsetlayout->isPassThru()) {
5957 // set catcodes to verbatim early, just in case.
5958 p.setCatcodes(VERBATIM_CATCODES);
5959 string delim = p.get_token().asInput();
5961 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5962 //FIXME: handle error condition
5963 string const arg = p.verbatimStuff("}").second;
5964 Context newcontext(true, context.textclass);
5965 if (newinsetlayout->forcePlainLayout())
5966 newcontext.layout = &context.textclass.plainLayout();
5967 output_ert(os, arg, newcontext);
5969 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5972 // Minted caption insets are not closed here because
5973 // we collect everything into the caption.
5974 if (minted_float.empty())
5979 if (t.cs() == "includepdf") {
5981 string const arg = p.getArg('[', ']');
5982 map<string, string> opts;
5983 vector<string> keys;
5984 split_map(arg, opts, keys);
5985 string name = normalize_filename(p.verbatim_item());
5986 string const path = getMasterFilePath(true);
5987 // We want to preserve relative / absolute filenames,
5988 // therefore path is only used for testing
5989 if (!makeAbsPath(name, path).exists()) {
5990 // The file extension is probably missing.
5991 // Now try to find it out.
5992 char const * const pdfpages_format[] = {"pdf", 0};
5993 string const pdftex_name =
5994 find_file(name, path, pdfpages_format);
5995 if (!pdftex_name.empty()) {
6000 FileName const absname = makeAbsPath(name, path);
6001 if (absname.exists())
6003 fix_child_filename(name);
6004 copy_file(absname, name);
6006 cerr << "Warning: Could not find file '"
6007 << name << "'." << endl;
6009 context.check_layout(os);
6010 begin_inset(os, "External\n\ttemplate ");
6011 os << "PDFPages\n\tfilename "
6013 // parse the options
6014 if (opts.find("pages") != opts.end())
6015 os << "\textra LaTeX \"pages="
6016 << opts["pages"] << "\"\n";
6017 if (opts.find("angle") != opts.end())
6018 os << "\trotateAngle "
6019 << opts["angle"] << '\n';
6020 if (opts.find("origin") != opts.end()) {
6022 string const opt = opts["origin"];
6023 if (opt == "tl") ss << "topleft";
6024 if (opt == "bl") ss << "bottomleft";
6025 if (opt == "Bl") ss << "baselineleft";
6026 if (opt == "c") ss << "center";
6027 if (opt == "tc") ss << "topcenter";
6028 if (opt == "bc") ss << "bottomcenter";
6029 if (opt == "Bc") ss << "baselinecenter";
6030 if (opt == "tr") ss << "topright";
6031 if (opt == "br") ss << "bottomright";
6032 if (opt == "Br") ss << "baselineright";
6033 if (!ss.str().empty())
6034 os << "\trotateOrigin " << ss.str() << '\n';
6036 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
6038 if (opts.find("width") != opts.end())
6040 << translate_len(opts["width"]) << '\n';
6041 if (opts.find("height") != opts.end())
6043 << translate_len(opts["height"]) << '\n';
6044 if (opts.find("keepaspectratio") != opts.end())
6045 os << "\tkeepAspectRatio\n";
6047 context.check_layout(os);
6048 registerExternalTemplatePackages("PDFPages");
6052 if (t.cs() == "loadgame") {
6054 string name = normalize_filename(p.verbatim_item());
6055 string const path = getMasterFilePath(true);
6056 // We want to preserve relative / absolute filenames,
6057 // therefore path is only used for testing
6058 if (!makeAbsPath(name, path).exists()) {
6059 // The file extension is probably missing.
6060 // Now try to find it out.
6061 char const * const lyxskak_format[] = {"fen", 0};
6062 string const lyxskak_name =
6063 find_file(name, path, lyxskak_format);
6064 if (!lyxskak_name.empty())
6065 name = lyxskak_name;
6067 FileName const absname = makeAbsPath(name, path);
6068 if (absname.exists())
6070 fix_child_filename(name);
6071 copy_file(absname, name);
6073 cerr << "Warning: Could not find file '"
6074 << name << "'." << endl;
6075 context.check_layout(os);
6076 begin_inset(os, "External\n\ttemplate ");
6077 os << "ChessDiagram\n\tfilename "
6080 context.check_layout(os);
6081 // after a \loadgame follows a \showboard
6082 if (p.get_token().asInput() == "showboard")
6084 registerExternalTemplatePackages("ChessDiagram");
6088 // try to see whether the string is in unicodesymbols
6089 // Only use text mode commands, since we are in text mode here,
6090 // and math commands may be invalid (bug 6797)
6091 string name = t.asInput();
6092 // handle the dingbats, cyrillic and greek
6093 if (name == "\\textcyr")
6094 name = "\\textcyrillic";
6095 if (name == "\\ding" || name == "\\textcyrillic" ||
6096 (name == "\\textgreek" && !preamble.usePolyglossia()))
6097 name = name + '{' + p.getArg('{', '}') + '}';
6098 // handle the ifsym characters
6099 else if (name == "\\textifsymbol") {
6100 string const optif = p.getFullOpt();
6101 string const argif = p.getArg('{', '}');
6102 name = name + optif + '{' + argif + '}';
6104 // handle the \ascii characters
6105 // the case of \ascii within braces, as LyX outputs it, is already
6106 // handled for t.cat() == catBegin
6107 else if (name == "\\ascii") {
6108 // the code is "\asci\xxx"
6109 name = "{" + name + p.get_token().asInput() + "}";
6112 // handle some TIPA special characters
6113 else if (preamble.isPackageUsed("tipa")) {
6114 if (name == "\\s") {
6115 // fromLaTeXCommand() does not yet
6116 // recognize tipa short cuts
6117 name = "\\textsyllabic";
6118 } else if (name == "\\=" &&
6119 p.next_token().asInput() == "*") {
6120 // fromLaTeXCommand() does not yet
6121 // recognize tipa short cuts
6123 name = "\\textsubbar";
6124 } else if (name == "\\textdoublevertline") {
6125 // FIXME: This is not correct,
6126 // \textvertline is higher than \textbardbl
6127 name = "\\textbardbl";
6129 } else if (name == "\\!" ) {
6130 if (p.next_token().asInput() == "b") {
6131 p.get_token(); // eat 'b'
6134 } else if (p.next_token().asInput() == "d") {
6138 } else if (p.next_token().asInput() == "g") {
6142 } else if (p.next_token().asInput() == "G") {
6144 name = "\\texthtscg";
6146 } else if (p.next_token().asInput() == "j") {
6148 name = "\\texthtbardotlessj";
6150 } else if (p.next_token().asInput() == "o") {
6152 name = "\\textbullseye";
6155 } else if (name == "\\*" ) {
6156 if (p.next_token().asInput() == "k") {
6158 name = "\\textturnk";
6160 } else if (p.next_token().asInput() == "r") {
6161 p.get_token(); // eat 'b'
6162 name = "\\textturnr";
6164 } else if (p.next_token().asInput() == "t") {
6166 name = "\\textturnt";
6168 } else if (p.next_token().asInput() == "w") {
6170 name = "\\textturnw";
6175 if ((name.size() == 2 &&
6176 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
6177 p.next_token().asInput() != "*") ||
6178 is_known(name.substr(1), known_tipa_marks)) {
6179 // name is a command that corresponds to a
6180 // combining character in unicodesymbols.
6181 // Append the argument, fromLaTeXCommand()
6182 // will either convert it to a single
6183 // character or a combining sequence.
6184 name += '{' + p.verbatim_item() + '}';
6186 // now get the character from unicodesymbols
6190 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
6191 Encodings::TEXT_CMD, termination, rem, &req));
6193 context.check_layout(os);
6196 output_ert_inset(os, to_utf8(rem), context);
6198 skip_spaces_braces(p);
6199 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
6200 preamble.registerAutomaticallyLoadedPackage(*it);
6202 //cerr << "#: " << t << " mode: " << mode << endl;
6203 // heuristic: read up to next non-nested space
6205 string s = t.asInput();
6206 string z = p.verbatim_item();
6207 while (p.good() && z != " " && !z.empty()) {
6208 //cerr << "read: " << z << endl;
6210 z = p.verbatim_item();
6212 cerr << "found ERT: " << s << endl;
6213 output_ert_inset(os, s + ' ', context);
6216 if (t.asInput() == name &&
6217 p.next_token().asInput() == "*") {
6218 // Starred commands like \vspace*{}
6219 p.get_token(); // Eat '*'
6222 if (!parse_command(name, p, os, outer, context)) {
6223 output_ert_inset(os, name, context);
6224 // Try to handle options of unknown commands:
6225 // Look if we have optional arguments,
6226 // and if so, put the brackets in ERT.
6227 while (p.hasOpt()) {
6228 p.get_token(); // eat '['
6229 output_ert_inset(os, "[", context);
6230 os << parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
6231 output_ert_inset(os, "]", context);
6239 string guessLanguage(Parser & p, string const & lang)
6241 typedef std::map<std::string, size_t> LangMap;
6242 // map from language names to number of characters
6245 for (char const * const * i = supported_CJK_languages; *i; i++)
6246 used[string(*i)] = 0;
6249 Token const t = p.get_token();
6250 // comments are not counted for any language
6251 if (t.cat() == catComment)
6253 // commands are not counted as well, but we need to detect
6254 // \begin{CJK} and switch encoding if needed
6255 if (t.cat() == catEscape) {
6256 if (t.cs() == "inputencoding") {
6257 string const enc = subst(p.verbatim_item(), "\n", " ");
6258 p.setEncoding(enc, Encoding::inputenc);
6261 if (t.cs() != "begin")
6264 // Non-CJK content is counted for lang.
6265 // We do not care about the real language here:
6266 // If we have more non-CJK contents than CJK contents,
6267 // we simply use the language that was specified as
6268 // babel main language.
6269 used[lang] += t.asInput().length();
6272 // Now we are starting an environment
6274 string const name = p.getArg('{', '}');
6275 if (name != "CJK") {
6279 // It is a CJK environment
6281 /* name = */ p.getArg('{', '}');
6282 string const encoding = p.getArg('{', '}');
6283 /* mapping = */ p.getArg('{', '}');
6284 string const encoding_old = p.getEncoding();
6285 char const * const * const where =
6286 is_known(encoding, supported_CJK_encodings);
6288 p.setEncoding(encoding, Encoding::CJK);
6290 p.setEncoding("UTF-8");
6291 string const text = p.ertEnvironment("CJK");
6292 p.setEncoding(encoding_old);
6295 // ignore contents in unknown CJK encoding
6298 // the language of the text
6300 supported_CJK_languages[where - supported_CJK_encodings];
6301 used[cjk] += text.length();
6303 LangMap::const_iterator use = used.begin();
6304 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
6305 if (it->second > use->second)
6312 void check_comment_bib(ostream & os, Context & context)
6314 if (!need_commentbib)
6316 // We have a bibliography database, but no bibliography with biblatex
6317 // which is completely valid. Insert a bibtex inset in a note.
6318 context.check_layout(os);
6319 begin_inset(os, "Note Note\n");
6320 os << "status open\n";
6321 os << "\\begin_layout Plain Layout\n";
6322 begin_command_inset(os, "bibtex", "bibtex");
6324 for (auto const & bf : preamble.biblatex_bibliographies) {
6325 if (!bibfiles.empty())
6327 bibfiles += normalize_filename(bf);
6329 if (!bibfiles.empty())
6330 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
6332 for (auto const & bf : preamble.biblatex_encodings) {
6333 if (!bibfileencs.empty())
6334 bibfileencs += "\t";
6337 if (!bibfileencs.empty())
6338 os << "file_encodings " << '"' << bibfileencs << '"' << "\n";
6339 end_inset(os);// Bibtex
6340 os << "\\end_layout\n";
6341 end_inset(os);// Note