2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subsecref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "subsec", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
189 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
191 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
192 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
193 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
194 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
195 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
197 // Whether we need to insert a bibtex inset in a comment
198 bool need_commentbib = false;
200 /// LaTeX names for quotes
201 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
202 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
203 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
204 "guilsinglleft", "frq", "guilsinglright", 0};
206 /// the same as known_quotes with .lyx names
207 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
208 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
209 "gld", "grd", "gls", "ers", "fls",
210 "fls", "frs", "frs", 0};
212 /// LaTeX names for font sizes
213 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
214 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
216 /// the same as known_sizes with .lyx names
217 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
218 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
220 /// LaTeX 2.09 names for font families
221 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
223 /// LaTeX names for font families
224 char const * const known_font_families[] = { "rmfamily", "sffamily",
227 /// LaTeX names for font family changing commands
228 char const * const known_text_font_families[] = { "textrm", "textsf",
231 /// The same as known_old_font_families, known_font_families and
232 /// known_text_font_families with .lyx names
233 char const * const known_coded_font_families[] = { "roman", "sans",
236 /// LaTeX 2.09 names for font series
237 char const * const known_old_font_series[] = { "bf", 0};
239 /// LaTeX names for font series
240 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
242 /// LaTeX names for font series changing commands
243 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
245 /// The same as known_old_font_series, known_font_series and
246 /// known_text_font_series with .lyx names
247 char const * const known_coded_font_series[] = { "bold", "medium", 0};
249 /// LaTeX 2.09 names for font shapes
250 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
252 /// LaTeX names for font shapes
253 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
256 /// LaTeX names for font shape changing commands
257 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
260 /// The same as known_old_font_shapes, known_font_shapes and
261 /// known_text_font_shapes with .lyx names
262 char const * const known_coded_font_shapes[] = { "italic", "slanted",
263 "smallcaps", "up", 0};
265 /// Known special characters which need skip_spaces_braces() afterwards
266 char const * const known_special_chars[] = {"ldots",
267 "lyxarrow", "textcompwordmark",
268 "slash", "textasciitilde", "textasciicircum", "textbackslash",
269 "LyX", "TeX", "LaTeXe",
272 /// special characters from known_special_chars which may have a \\protect before
273 char const * const known_special_protect_chars[] = {"LyX", "TeX",
274 "LaTeXe", "LaTeX", 0};
276 /// the same as known_special_chars with .lyx names
277 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
278 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
279 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
280 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
281 "\\SpecialChar LaTeX\n", 0};
284 * Graphics file extensions known by the dvips driver of the graphics package.
285 * These extensions are used to complete the filename of an included
286 * graphics file if it does not contain an extension.
287 * The order must be the same that latex uses to find a file, because we
288 * will use the first extension that matches.
289 * This is only an approximation for the common cases. If we would want to
290 * do it right in all cases, we would need to know which graphics driver is
291 * used and know the extensions of every driver of the graphics package.
293 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
294 "ps.gz", "eps.Z", "ps.Z", 0};
297 * Graphics file extensions known by the pdftex driver of the graphics package.
298 * \sa known_dvips_graphics_formats
300 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
304 * Known file extensions for TeX files as used by \\include.
306 char const * const known_tex_extensions[] = {"tex", 0};
308 /// spaces known by InsetSpace
309 char const * const known_spaces[] = { " ", "space", ",",
310 "thinspace", "quad", "qquad", "enspace", "enskip",
311 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
312 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
313 "upbracefill", "downbracefill", 0};
315 /// the same as known_spaces with .lyx names
316 char const * const known_coded_spaces[] = { "space{}", "space{}",
317 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
318 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
319 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
320 "upbracefill{}", "downbracefill{}", 0};
322 /// known TIPA combining diacritical marks
323 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
324 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
325 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
326 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
327 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
328 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
329 "textsubring", "textsubbar", 0};
331 /// TIPA tones that need special handling
332 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
334 // string to store the float type to be able to determine the type of subfloats
335 string float_type = "";
337 // string to store the float status of minted listings
338 string minted_float = "";
340 // whether a caption has been parsed for a floating minted listing
341 bool minted_float_has_caption = false;
343 // The caption for non-floating minted listings
344 string minted_nonfloat_caption = "";
347 /// splits "x=z, y=b" into a map and an ordered keyword vector
348 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
353 keys.resize(v.size());
354 for (size_t i = 0; i < v.size(); ++i) {
355 size_t const pos = v[i].find('=');
356 string const index = trimSpaceAndEol(v[i].substr(0, pos));
357 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
365 * Split a LaTeX length into value and unit.
366 * The latter can be a real unit like "pt", or a latex length variable
367 * like "\textwidth". The unit may contain additional stuff like glue
368 * lengths, but we don't care, because such lengths are ERT anyway.
369 * \returns true if \p value and \p unit are valid.
371 bool splitLatexLength(string const & len, string & value, string & unit)
375 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
376 //'4,5' is a valid LaTeX length number. Change it to '4.5'
377 string const length = subst(len, ',', '.');
378 if (i == string::npos)
381 if (len[0] == '\\') {
382 // We had something like \textwidth without a factor
388 value = trimSpaceAndEol(string(length, 0, i));
392 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
393 if (contains(len, '\\'))
394 unit = trimSpaceAndEol(string(len, i));
396 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
401 /// A simple function to translate a latex length to something LyX can
402 /// understand. Not perfect, but rather best-effort.
403 bool translate_len(string const & length, string & valstring, string & unit)
405 if (!splitLatexLength(length, valstring, unit))
407 // LyX uses percent values
409 istringstream iss(valstring);
414 string const percentval = oss.str();
416 if (unit.empty() || unit[0] != '\\')
418 string::size_type const i = unit.find(' ');
419 string const endlen = (i == string::npos) ? string() : string(unit, i);
420 if (unit == "\\textwidth") {
421 valstring = percentval;
422 unit = "text%" + endlen;
423 } else if (unit == "\\columnwidth") {
424 valstring = percentval;
425 unit = "col%" + endlen;
426 } else if (unit == "\\paperwidth") {
427 valstring = percentval;
428 unit = "page%" + endlen;
429 } else if (unit == "\\linewidth") {
430 valstring = percentval;
431 unit = "line%" + endlen;
432 } else if (unit == "\\paperheight") {
433 valstring = percentval;
434 unit = "pheight%" + endlen;
435 } else if (unit == "\\textheight") {
436 valstring = percentval;
437 unit = "theight%" + endlen;
438 } else if (unit == "\\baselineskip") {
439 valstring = percentval;
440 unit = "baselineskip%" + endlen;
448 string translate_len(string const & length)
452 if (translate_len(length, value, unit))
454 // If the input is invalid, return what we have.
462 * Translates a LaTeX length into \p value, \p unit and
463 * \p special parts suitable for a box inset.
464 * The difference from translate_len() is that a box inset knows about
465 * some special "units" that are stored in \p special.
467 void translate_box_len(string const & length, string & value, string & unit, string & special)
469 if (translate_len(length, value, unit)) {
470 if (unit == "\\height" || unit == "\\depth" ||
471 unit == "\\totalheight" || unit == "\\width") {
472 special = unit.substr(1);
473 // The unit is not used, but LyX requires a dummy setting
485 void begin_inset(ostream & os, string const & name)
487 os << "\n\\begin_inset " << name;
491 void begin_command_inset(ostream & os, string const & name,
492 string const & latexname)
494 begin_inset(os, "CommandInset ");
495 os << name << "\nLatexCommand " << latexname << '\n';
499 void end_inset(ostream & os)
501 os << "\n\\end_inset\n\n";
505 bool skip_braces(Parser & p)
507 if (p.next_token().cat() != catBegin)
510 if (p.next_token().cat() == catEnd) {
519 /// replace LaTeX commands in \p s from the unicodesymbols file with their
521 pair<bool, docstring> convert_unicodesymbols(docstring s)
524 int const nchars_escape = 8;
525 static char_type const chars_escape[nchars_escape] = {
526 '&', '_', '$', '%', '#', '^', '{', '}'};
528 for (size_t i = 0; i < s.size();) {
537 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
538 Encodings::TEXT_CMD, termination, rem, &req));
539 set<string>::const_iterator it = req.begin();
540 set<string>::const_iterator en = req.end();
541 for (; it != en; ++it)
542 preamble.registerAutomaticallyLoadedPackage(*it);
545 if (s.empty() || s[0] != '\\')
549 for (int k = 0; k < nchars_escape; k++)
550 if (prefixIs(s, from_ascii("\\") + chars_escape[k]))
555 return make_pair(res, os.str());
559 /// try to convert \p s to a valid InsetCommand argument
560 /// return whether this succeeded. If not, these command insets
561 /// get the "literate" flag.
562 pair<bool, string> convert_latexed_command_inset_arg(string s)
564 bool success = false;
566 // since we don't know the input encoding we can't use from_utf8
567 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
569 s = to_utf8(res.second);
571 // LyX cannot handle newlines in a latex command
572 return make_pair(success, subst(s, "\n", " "));
575 /// try to convert \p s to a valid InsetCommand argument
576 /// without trying to recode macros.
577 string convert_literate_command_inset_arg(string s)
579 // LyX cannot handle newlines in a latex command
580 return subst(s, "\n", " ");
583 void output_ert(ostream & os, string const & s, Context & context)
585 context.check_layout(os);
586 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
588 os << "\n\\backslash\n";
589 else if (*it == '\n') {
590 context.new_paragraph(os);
591 context.check_layout(os);
595 context.check_end_layout(os);
599 void output_ert_inset(ostream & os, string const & s, Context & context)
601 // We must have a valid layout before outputting the ERT inset.
602 context.check_layout(os);
603 Context newcontext(true, context.textclass);
604 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
605 if (layout.forcePlainLayout())
606 newcontext.layout = &context.textclass.plainLayout();
607 begin_inset(os, "ERT");
608 os << "\nstatus collapsed\n";
609 output_ert(os, s, newcontext);
614 void output_comment(Parser & p, ostream & os, string const & s,
617 if (p.next_token().cat() == catNewline)
618 output_ert_inset(os, '%' + s, context);
620 output_ert_inset(os, '%' + s + '\n', context);
624 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
626 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
629 if (checkModule(name, command))
630 return findLayoutWithoutModule(textclass, name, command);
635 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
637 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
640 if (checkModule(name, command))
641 return findInsetLayoutWithoutModule(textclass, name, command);
646 void eat_whitespace(Parser &, ostream &, Context &, bool);
650 * Skips whitespace and braces.
651 * This should be called after a command has been parsed that is not put into
652 * ERT, and where LyX adds "{}" if needed.
654 void skip_spaces_braces(Parser & p, bool keepws = false)
656 /* The following four examples produce the same typeset output and
657 should be handled by this function:
665 // Unfortunately we need to skip comments, too.
666 // We can't use eat_whitespace since writing them after the {}
667 // results in different output in some cases.
668 bool const skipped_spaces = p.skip_spaces(true);
669 bool const skipped_braces = skip_braces(p);
670 if (keepws && skipped_spaces && !skipped_braces)
671 // put back the space (it is better handled by check_space)
672 p.unskip_spaces(true);
676 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
677 Context & context, Layout::LaTeXArgMap const & latexargs)
680 context.check_layout(os);
685 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
686 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
687 for (; lait != laend; ++lait) {
689 eat_whitespace(p, os, context, false);
690 if (lait->second.mandatory) {
691 if (p.next_token().cat() != catBegin)
693 p.get_token(); // eat '{'
695 context.check_layout(os);
698 begin_inset(os, "Argument ");
701 os << i << "\nstatus collapsed\n\n";
702 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
705 if (p.next_token().cat() == catEscape ||
706 p.next_token().character() != '[')
708 p.get_token(); // eat '['
710 context.check_layout(os);
713 begin_inset(os, "Argument ");
716 os << i << "\nstatus collapsed\n\n";
717 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
720 eat_whitespace(p, os, context, false);
725 void output_command_layout(ostream & os, Parser & p, bool outer,
726 Context & parent_context,
727 Layout const * newlayout)
729 TeXFont const oldFont = parent_context.font;
730 // save the current font size
731 string const size = oldFont.size;
732 // reset the font size to default, because the font size switches
733 // don't affect section headings and the like
734 parent_context.font.size = Context::normalfont.size;
735 // we only need to write the font change if we have an open layout
736 if (!parent_context.atParagraphStart())
737 output_font_change(os, oldFont, parent_context.font);
738 parent_context.check_end_layout(os);
739 Context context(true, parent_context.textclass, newlayout,
740 parent_context.layout, parent_context.font);
741 if (parent_context.deeper_paragraph) {
742 // We are beginning a nested environment after a
743 // deeper paragraph inside the outer list environment.
744 // Therefore we don't need to output a "begin deeper".
745 context.need_end_deeper = true;
747 context.check_deeper(os);
748 output_arguments(os, p, outer, true, false, context,
749 context.layout->latexargs());
750 parse_text(p, os, FLAG_ITEM, outer, context);
751 output_arguments(os, p, outer, false, true, context,
752 context.layout->postcommandargs());
753 context.check_end_layout(os);
754 if (parent_context.deeper_paragraph) {
755 // We must suppress the "end deeper" because we
756 // suppressed the "begin deeper" above.
757 context.need_end_deeper = false;
759 context.check_end_deeper(os);
760 // We don't need really a new paragraph, but
761 // we must make sure that the next item gets a \begin_layout.
762 parent_context.new_paragraph(os);
763 // Set the font size to the original value. No need to output it here
764 // (Context::begin_layout() will do that if needed)
765 parent_context.font.size = size;
770 * Output a space if necessary.
771 * This function gets called for every whitespace token.
773 * We have three cases here:
774 * 1. A space must be suppressed. Example: The lyxcode case below
775 * 2. A space may be suppressed. Example: Spaces before "\par"
776 * 3. A space must not be suppressed. Example: A space between two words
778 * We currently handle only 1. and 3 and from 2. only the case of
779 * spaces before newlines as a side effect.
781 * 2. could be used to suppress as many spaces as possible. This has two effects:
782 * - Reimporting LyX generated LaTeX files changes almost no whitespace
783 * - Superflous whitespace from non LyX generated LaTeX files is removed.
784 * The drawback is that the logic inside the function becomes
785 * complicated, and that is the reason why it is not implemented.
787 void check_space(Parser & p, ostream & os, Context & context)
789 Token const next = p.next_token();
790 Token const curr = p.curr_token();
791 // A space before a single newline and vice versa must be ignored
792 // LyX emits a newline before \end{lyxcode}.
793 // This newline must be ignored,
794 // otherwise LyX will add an additional protected space.
795 if (next.cat() == catSpace ||
796 next.cat() == catNewline ||
797 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
800 context.check_layout(os);
806 * Parse all arguments of \p command
808 void parse_arguments(string const & command,
809 vector<ArgumentType> const & template_arguments,
810 Parser & p, ostream & os, bool outer, Context & context)
812 string ert = command;
813 size_t no_arguments = template_arguments.size();
814 for (size_t i = 0; i < no_arguments; ++i) {
815 switch (template_arguments[i]) {
818 // This argument contains regular LaTeX
819 output_ert_inset(os, ert + '{', context);
820 eat_whitespace(p, os, context, false);
821 if (template_arguments[i] == required)
822 parse_text(p, os, FLAG_ITEM, outer, context);
824 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
828 // This argument consists only of a single item.
829 // The presence of '{' or not must be preserved.
831 if (p.next_token().cat() == catBegin)
832 ert += '{' + p.verbatim_item() + '}';
834 ert += p.verbatim_item();
838 // This argument may contain special characters
839 ert += '{' + p.verbatim_item() + '}';
843 // true because we must not eat whitespace
844 // if an optional arg follows we must not strip the
845 // brackets from this one
846 if (i < no_arguments - 1 &&
847 template_arguments[i+1] == optional)
848 ert += p.getFullOpt(true);
850 ert += p.getOpt(true);
854 output_ert_inset(os, ert, context);
859 * Check whether \p command is a known command. If yes,
860 * handle the command with all arguments.
861 * \return true if the command was parsed, false otherwise.
863 bool parse_command(string const & command, Parser & p, ostream & os,
864 bool outer, Context & context)
866 if (known_commands.find(command) != known_commands.end()) {
867 parse_arguments(command, known_commands[command], p, os,
875 /// Parses a minipage or parbox
876 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
877 unsigned inner_flags, bool outer, Context & parent_context,
878 string const & outer_type, string const & special,
879 string inner_type, string const & frame_color,
880 string const & background_color)
884 string hor_pos = "l";
885 // We need to set the height to the LaTeX default of 1\\totalheight
886 // for the case when no height argument is given
887 string height_value = "1";
888 string height_unit = "in";
889 string height_special = "totalheight";
894 string width_special = "none";
895 string thickness = "0.4pt";
896 if (!fboxrule.empty())
897 thickness = fboxrule;
901 if (!fboxsep.empty())
902 separation = fboxsep;
906 if (!shadow_size.empty())
907 shadowsize = shadow_size;
910 string framecolor = "black";
911 string backgroundcolor = "none";
912 if (!frame_color.empty())
913 framecolor = frame_color;
914 if (!background_color.empty())
915 backgroundcolor = background_color;
916 // if there is a color box around the \begin statements have not yet been parsed
918 if (!frame_color.empty() || !background_color.empty()) {
919 eat_whitespace(p, os, parent_context, false);
920 p.get_token().asInput(); // the '{'
922 if (p.next_token().asInput() == "\\begin") {
923 p.get_token().asInput();
925 inner_type = "minipage";
926 inner_flags = FLAG_END;
927 active_environments.push_back("minipage");
930 else if (p.next_token().asInput() == "\\parbox") {
931 p.get_token().asInput();
932 inner_type = "parbox";
933 inner_flags = FLAG_ITEM;
936 else if (p.next_token().asInput() == "\\makebox") {
937 p.get_token().asInput();
938 inner_type = "makebox";
939 inner_flags = FLAG_ITEM;
941 // in case there is just \colorbox{color}{text}
944 inner_type = "makebox";
945 inner_flags = FLAG_BRACE_LAST;
950 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
952 if (!inner_type.empty() && p.hasOpt()) {
953 if (inner_type != "makebox")
954 position = p.getArg('[', ']');
956 latex_width = p.getArg('[', ']');
957 translate_box_len(latex_width, width_value, width_unit, width_special);
960 if (position != "t" && position != "c" && position != "b") {
961 cerr << "invalid position " << position << " for "
962 << inner_type << endl;
966 if (inner_type != "makebox") {
967 latex_height = p.getArg('[', ']');
968 translate_box_len(latex_height, height_value, height_unit, height_special);
970 string const opt = p.getArg('[', ']');
973 if (hor_pos != "l" && hor_pos != "c" &&
974 hor_pos != "r" && hor_pos != "s") {
975 cerr << "invalid hor_pos " << hor_pos
976 << " for " << inner_type << endl;
983 inner_pos = p.getArg('[', ']');
984 if (inner_pos != "c" && inner_pos != "t" &&
985 inner_pos != "b" && inner_pos != "s") {
986 cerr << "invalid inner_pos "
987 << inner_pos << " for "
988 << inner_type << endl;
989 inner_pos = position;
993 if (inner_type == "makebox")
997 if (inner_type.empty()) {
998 if (special.empty() && outer_type != "framebox")
999 latex_width = "1\\columnwidth";
1002 latex_width = p2.getArg('[', ']');
1003 string const opt = p2.getArg('[', ']');
1006 if (hor_pos != "l" && hor_pos != "c" &&
1007 hor_pos != "r" && hor_pos != "s") {
1008 cerr << "invalid hor_pos " << hor_pos
1009 << " for " << outer_type << endl;
1013 if (outer_type == "framebox")
1017 } else if (inner_type != "makebox")
1018 latex_width = p.verbatim_item();
1019 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1020 // as this is LyX's standard for such cases (except for makebox)
1021 // \framebox is more special and handled below
1022 if (latex_width.empty() && inner_type != "makebox"
1023 && outer_type != "framebox")
1024 latex_width = "1\\columnwidth";
1026 translate_len(latex_width, width_value, width_unit);
1028 bool shadedparbox = false;
1029 if (inner_type == "shaded") {
1030 eat_whitespace(p, os, parent_context, false);
1031 if (outer_type == "parbox") {
1033 if (p.next_token().cat() == catBegin)
1035 eat_whitespace(p, os, parent_context, false);
1036 shadedparbox = true;
1041 // If we already read the inner box we have to push the inner env
1042 if (!outer_type.empty() && !inner_type.empty() &&
1043 (inner_flags & FLAG_END))
1044 active_environments.push_back(inner_type);
1045 bool use_ert = false;
1046 if (!outer_type.empty() && !inner_type.empty()) {
1047 // Look whether there is some content after the end of the
1048 // inner box, but before the end of the outer box.
1049 // If yes, we need to output ERT.
1051 if (inner_flags & FLAG_END)
1052 p.ertEnvironment(inner_type);
1055 p.skip_spaces(true);
1056 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1057 if ((outer_env && p.next_token().asInput() != "\\end") ||
1058 (!outer_env && p.next_token().cat() != catEnd)) {
1059 // something is between the end of the inner box and
1060 // the end of the outer box, so we need to use ERT.
1068 if (!outer_type.empty()) {
1069 if (outer_flags & FLAG_END)
1070 ss << "\\begin{" << outer_type << '}';
1072 ss << '\\' << outer_type << '{';
1073 if (!special.empty())
1077 if (!inner_type.empty()) {
1078 if (inner_type != "shaded") {
1079 if (inner_flags & FLAG_END)
1080 ss << "\\begin{" << inner_type << '}';
1082 ss << '\\' << inner_type;
1084 if (!position.empty())
1085 ss << '[' << position << ']';
1086 if (!latex_height.empty())
1087 ss << '[' << latex_height << ']';
1088 if (!inner_pos.empty())
1089 ss << '[' << inner_pos << ']';
1090 ss << '{' << latex_width << '}';
1091 if (!(inner_flags & FLAG_END))
1094 if (inner_type == "shaded")
1095 ss << "\\begin{shaded}";
1096 output_ert_inset(os, ss.str(), parent_context);
1097 if (!inner_type.empty()) {
1098 parse_text(p, os, inner_flags, outer, parent_context);
1099 if (inner_flags & FLAG_END)
1100 output_ert_inset(os, "\\end{" + inner_type + '}',
1103 output_ert_inset(os, "}", parent_context);
1105 if (!outer_type.empty()) {
1106 // If we already read the inner box we have to pop
1108 if (!inner_type.empty() && (inner_flags & FLAG_END))
1109 active_environments.pop_back();
1111 // Ensure that the end of the outer box is parsed correctly:
1112 // The opening brace has been eaten by parse_outer_box()
1113 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1114 outer_flags &= ~FLAG_ITEM;
1115 outer_flags |= FLAG_BRACE_LAST;
1117 parse_text(p, os, outer_flags, outer, parent_context);
1118 if (outer_flags & FLAG_END)
1119 output_ert_inset(os, "\\end{" + outer_type + '}',
1122 output_ert_inset(os, "}", parent_context);
1125 // LyX does not like empty positions, so we have
1126 // to set them to the LaTeX default values here.
1127 if (position.empty())
1129 if (inner_pos.empty())
1130 inner_pos = position;
1131 parent_context.check_layout(os);
1132 begin_inset(os, "Box ");
1133 if (outer_type == "framed")
1135 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1137 else if (outer_type == "shadowbox")
1138 os << "Shadowbox\n";
1139 else if ((outer_type == "shaded" && inner_type.empty()) ||
1140 (outer_type == "minipage" && inner_type == "shaded") ||
1141 (outer_type == "parbox" && inner_type == "shaded")) {
1143 preamble.registerAutomaticallyLoadedPackage("color");
1144 } else if (outer_type == "doublebox")
1145 os << "Doublebox\n";
1146 else if (outer_type.empty() || outer_type == "mbox")
1147 os << "Frameless\n";
1149 os << outer_type << '\n';
1150 os << "position \"" << position << "\"\n";
1151 os << "hor_pos \"" << hor_pos << "\"\n";
1152 if (outer_type == "mbox")
1153 os << "has_inner_box 1\n";
1154 else if (!frame_color.empty() && inner_type == "makebox")
1155 os << "has_inner_box 0\n";
1157 os << "has_inner_box " << !inner_type.empty() << "\n";
1158 os << "inner_pos \"" << inner_pos << "\"\n";
1159 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1161 if (outer_type == "mbox")
1162 os << "use_makebox 1\n";
1163 else if (!frame_color.empty())
1164 os << "use_makebox 0\n";
1166 os << "use_makebox " << (inner_type == "makebox") << '\n';
1167 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1168 os << "width \"\"\n";
1169 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1170 else if (contains(width_unit, '\\'))
1171 os << "width \"" << width_value << "in" << "\"\n";
1173 os << "width \"" << width_value << width_unit << "\"\n";
1174 if (contains(width_unit, '\\')) {
1175 width_unit.erase (0,1); // remove the leading '\'
1176 os << "special \"" << width_unit << "\"\n";
1178 os << "special \"" << width_special << "\"\n";
1179 if (contains(height_unit, '\\'))
1180 os << "height \"" << height_value << "in" << "\"\n";
1182 os << "height \"" << height_value << height_unit << "\"\n";
1183 os << "height_special \"" << height_special << "\"\n";
1184 os << "thickness \"" << thickness << "\"\n";
1185 os << "separation \"" << separation << "\"\n";
1186 os << "shadowsize \"" << shadowsize << "\"\n";
1187 os << "framecolor \"" << framecolor << "\"\n";
1188 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1189 os << "status open\n\n";
1191 // Unfortunately we can't use parse_text_in_inset:
1192 // InsetBox::forcePlainLayout() is hard coded and does not
1193 // use the inset layout. Apart from that do we call parse_text
1194 // up to two times, but need only one check_end_layout.
1195 bool const forcePlainLayout =
1196 (!inner_type.empty() || inner_type == "makebox") &&
1197 outer_type != "shaded" && outer_type != "framed";
1198 Context context(true, parent_context.textclass);
1199 if (forcePlainLayout)
1200 context.layout = &context.textclass.plainLayout();
1202 context.font = parent_context.font;
1204 // If we have no inner box the contents will be read with the outer box
1205 if (!inner_type.empty())
1206 parse_text(p, os, inner_flags, outer, context);
1208 // Ensure that the end of the outer box is parsed correctly:
1209 // The opening brace has been eaten by parse_outer_box()
1210 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1211 outer_flags &= ~FLAG_ITEM;
1212 outer_flags |= FLAG_BRACE_LAST;
1215 // Find end of outer box, output contents if inner_type is
1216 // empty and output possible comments
1217 if (!outer_type.empty()) {
1218 // If we already read the inner box we have to pop
1220 if (!inner_type.empty() && (inner_flags & FLAG_END))
1221 active_environments.pop_back();
1222 // This does not output anything but comments if
1223 // inner_type is not empty (see use_ert)
1224 parse_text(p, os, outer_flags, outer, context);
1227 context.check_end_layout(os);
1229 #ifdef PRESERVE_LAYOUT
1230 // LyX puts a % after the end of the minipage
1231 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1233 //output_comment(p, os, "dummy", parent_context);
1236 parent_context.new_paragraph(os);
1238 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1239 //output_comment(p, os, "dummy", parent_context);
1242 // We add a protected space if something real follows
1243 if (p.good() && p.next_token().cat() != catComment) {
1244 begin_inset(os, "space ~\n");
1250 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1251 active_environments.pop_back();
1252 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1253 // in this case we have to eat the the closing brace of the color box
1254 p.get_token().asInput(); // the '}'
1256 if (p.next_token().asInput() == "}") {
1257 // in this case we assume that the closing brace is from the box settings
1258 // therefore reset these values for the next box
1264 // all boxes except of Frameless and Shaded require calc
1265 if (!(outer_type.empty() || outer_type == "mbox") &&
1266 !((outer_type == "shaded" && inner_type.empty()) ||
1267 (outer_type == "minipage" && inner_type == "shaded") ||
1268 (outer_type == "parbox" && inner_type == "shaded")))
1269 preamble.registerAutomaticallyLoadedPackage("calc");
1273 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1274 Context & parent_context, string const & outer_type,
1275 string const & special)
1277 eat_whitespace(p, os, parent_context, false);
1278 if (flags & FLAG_ITEM) {
1280 if (p.next_token().cat() == catBegin)
1283 cerr << "Warning: Ignoring missing '{' after \\"
1284 << outer_type << '.' << endl;
1285 eat_whitespace(p, os, parent_context, false);
1288 unsigned int inner_flags = 0;
1290 if (outer_type == "minipage" || outer_type == "parbox") {
1291 p.skip_spaces(true);
1292 while (p.hasOpt()) {
1294 p.skip_spaces(true);
1297 p.skip_spaces(true);
1298 if (outer_type == "parbox") {
1300 if (p.next_token().cat() == catBegin)
1302 p.skip_spaces(true);
1305 if (outer_type == "shaded" || outer_type == "mbox") {
1306 // These boxes never have an inner box
1308 } else if (p.next_token().asInput() == "\\parbox") {
1309 inner = p.get_token().cs();
1310 inner_flags = FLAG_ITEM;
1311 } else if (p.next_token().asInput() == "\\begin") {
1312 // Is this a minipage or shaded box?
1315 inner = p.getArg('{', '}');
1317 if (inner == "minipage" || inner == "shaded")
1318 inner_flags = FLAG_END;
1323 if (inner_flags == FLAG_END) {
1324 if (inner != "shaded")
1328 eat_whitespace(p, os, parent_context, false);
1330 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1331 outer_type, special, inner, "", "");
1333 if (inner_flags == FLAG_ITEM) {
1335 eat_whitespace(p, os, parent_context, false);
1337 parse_box(p, os, flags, inner_flags, outer, parent_context,
1338 outer_type, special, inner, "", "");
1343 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1344 bool in_line, bool use_minted)
1346 parent_context.check_layout(os);
1347 begin_inset(os, "listings\n");
1348 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1350 while ((i = arg.find(", ")) != string::npos
1351 || (i = arg.find(",\t")) != string::npos)
1352 arg.erase(i + 1, 1);
1355 string const language = p.getArg('{', '}');
1356 p.skip_spaces(true);
1357 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1358 if (!minted_float.empty()) {
1359 arg += string(arg.empty() ? "" : ",") + minted_float;
1360 minted_nonfloat_caption.clear();
1364 os << "lstparams " << '"' << arg << '"' << '\n';
1365 if (arg.find("\\color") != string::npos)
1366 preamble.registerAutomaticallyLoadedPackage("color");
1369 os << "inline true\n";
1371 os << "inline false\n";
1372 os << "status collapsed\n";
1373 Context context(true, parent_context.textclass);
1374 context.layout = &parent_context.textclass.plainLayout();
1375 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1376 minted_nonfloat_caption.erase(0,3);
1377 os << "\n\\begin_layout Plain Layout\n";
1378 begin_inset(os, "Caption Standard\n");
1379 Context newcontext(true, context.textclass,
1380 context.layout, 0, context.font);
1381 newcontext.check_layout(os);
1382 os << minted_nonfloat_caption << "\n";
1383 newcontext.check_end_layout(os);
1385 os << "\n\\end_layout\n";
1386 minted_nonfloat_caption.clear();
1390 // set catcodes to verbatim early, just in case.
1391 p.setCatcodes(VERBATIM_CATCODES);
1392 string delim = p.get_token().asInput();
1393 //FIXME: handler error condition
1394 s = p.verbatimStuff(delim).second;
1395 // context.new_paragraph(os);
1396 } else if (use_minted) {
1397 s = p.verbatimEnvironment("minted");
1399 s = p.verbatimEnvironment("lstlisting");
1401 output_ert(os, s, context);
1402 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1403 minted_nonfloat_caption.erase(0,3);
1404 os << "\n\\begin_layout Plain Layout\n";
1405 begin_inset(os, "Caption Standard\n");
1406 Context newcontext(true, context.textclass,
1407 context.layout, 0, context.font);
1408 newcontext.check_layout(os);
1409 os << minted_nonfloat_caption << "\n";
1410 newcontext.check_end_layout(os);
1412 os << "\n\\end_layout\n";
1413 minted_nonfloat_caption.clear();
1415 // Don't close the inset here for floating minted listings.
1416 // It will be closed at the end of the listing environment.
1417 if (!use_minted || minted_float.empty())
1420 eat_whitespace(p, os, parent_context, true);
1421 Token t = p.get_token();
1422 if (t.asInput() != "\\end") {
1423 // If anything follows, collect it into a caption.
1424 minted_float_has_caption = true;
1425 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1426 begin_inset(os, "Caption Standard\n");
1427 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1434 /// parse an unknown environment
1435 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1436 unsigned flags, bool outer,
1437 Context & parent_context)
1439 if (name == "tabbing")
1440 // We need to remember that we have to handle '\=' specially
1441 flags |= FLAG_TABBING;
1443 // We need to translate font changes and paragraphs inside the
1444 // environment to ERT if we have a non standard font.
1445 // Otherwise things like
1446 // \large\begin{foo}\huge bar\end{foo}
1448 bool const specialfont =
1449 (parent_context.font != parent_context.normalfont);
1450 bool const new_layout_allowed = parent_context.new_layout_allowed;
1452 parent_context.new_layout_allowed = false;
1453 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1454 parse_text_snippet(p, os, flags, outer, parent_context);
1455 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1457 parent_context.new_layout_allowed = new_layout_allowed;
1461 void parse_environment(Parser & p, ostream & os, bool outer,
1462 string & last_env, Context & parent_context)
1464 Layout const * newlayout;
1465 InsetLayout const * newinsetlayout = 0;
1466 string const name = p.getArg('{', '}');
1467 const bool is_starred = suffixIs(name, '*');
1468 string const unstarred_name = rtrim(name, "*");
1469 active_environments.push_back(name);
1471 if (is_math_env(name)) {
1472 parent_context.check_layout(os);
1473 begin_inset(os, "Formula ");
1474 os << "\\begin{" << name << "}";
1475 parse_math(p, os, FLAG_END, MATH_MODE);
1476 os << "\\end{" << name << "}";
1478 if (is_display_math_env(name)) {
1479 // Prevent the conversion of a line break to a space
1480 // (bug 7668). This does not change the output, but
1481 // looks ugly in LyX.
1482 eat_whitespace(p, os, parent_context, false);
1486 else if (is_known(name, preamble.polyglossia_languages)) {
1487 // We must begin a new paragraph if not already done
1488 if (! parent_context.atParagraphStart()) {
1489 parent_context.check_end_layout(os);
1490 parent_context.new_paragraph(os);
1492 // save the language in the context so that it is
1493 // handled by parse_text
1494 parent_context.font.language = preamble.polyglossia2lyx(name);
1495 parse_text(p, os, FLAG_END, outer, parent_context);
1496 // Just in case the environment is empty
1497 parent_context.extra_stuff.erase();
1498 // We must begin a new paragraph to reset the language
1499 parent_context.new_paragraph(os);
1503 else if (unstarred_name == "tabular" || name == "longtable") {
1504 eat_whitespace(p, os, parent_context, false);
1505 string width = "0pt";
1506 if (name == "tabular*") {
1507 width = lyx::translate_len(p.getArg('{', '}'));
1508 eat_whitespace(p, os, parent_context, false);
1510 parent_context.check_layout(os);
1511 begin_inset(os, "Tabular ");
1512 handle_tabular(p, os, name, width, parent_context);
1517 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1518 eat_whitespace(p, os, parent_context, false);
1519 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1520 eat_whitespace(p, os, parent_context, false);
1521 parent_context.check_layout(os);
1522 begin_inset(os, "Float " + unstarred_name + "\n");
1523 // store the float type for subfloats
1524 // subfloats only work with figures and tables
1525 if (unstarred_name == "figure")
1526 float_type = unstarred_name;
1527 else if (unstarred_name == "table")
1528 float_type = unstarred_name;
1532 os << "placement " << opt << '\n';
1533 if (contains(opt, "H"))
1534 preamble.registerAutomaticallyLoadedPackage("float");
1536 Floating const & fl = parent_context.textclass.floats()
1537 .getType(unstarred_name);
1538 if (!fl.floattype().empty() && fl.usesFloatPkg())
1539 preamble.registerAutomaticallyLoadedPackage("float");
1542 os << "wide " << convert<string>(is_starred)
1543 << "\nsideways false"
1544 << "\nstatus open\n\n";
1545 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1547 // We don't need really a new paragraph, but
1548 // we must make sure that the next item gets a \begin_layout.
1549 parent_context.new_paragraph(os);
1551 // the float is parsed thus delete the type
1555 else if (unstarred_name == "sidewaysfigure"
1556 || unstarred_name == "sidewaystable"
1557 || unstarred_name == "sidewaysalgorithm") {
1558 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1559 eat_whitespace(p, os, parent_context, false);
1560 parent_context.check_layout(os);
1561 if (unstarred_name == "sidewaysfigure")
1562 begin_inset(os, "Float figure\n");
1563 else if (unstarred_name == "sidewaystable")
1564 begin_inset(os, "Float table\n");
1565 else if (unstarred_name == "sidewaysalgorithm")
1566 begin_inset(os, "Float algorithm\n");
1568 os << "placement " << opt << '\n';
1569 if (contains(opt, "H"))
1570 preamble.registerAutomaticallyLoadedPackage("float");
1571 os << "wide " << convert<string>(is_starred)
1572 << "\nsideways true"
1573 << "\nstatus open\n\n";
1574 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1576 // We don't need really a new paragraph, but
1577 // we must make sure that the next item gets a \begin_layout.
1578 parent_context.new_paragraph(os);
1580 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1583 else if (name == "wrapfigure" || name == "wraptable") {
1584 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1585 eat_whitespace(p, os, parent_context, false);
1586 parent_context.check_layout(os);
1589 string overhang = "0col%";
1592 lines = p.getArg('[', ']');
1593 string const placement = p.getArg('{', '}');
1595 overhang = p.getArg('[', ']');
1596 string const width = p.getArg('{', '}');
1598 if (name == "wrapfigure")
1599 begin_inset(os, "Wrap figure\n");
1601 begin_inset(os, "Wrap table\n");
1602 os << "lines " << lines
1603 << "\nplacement " << placement
1604 << "\noverhang " << lyx::translate_len(overhang)
1605 << "\nwidth " << lyx::translate_len(width)
1606 << "\nstatus open\n\n";
1607 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1609 // We don't need really a new paragraph, but
1610 // we must make sure that the next item gets a \begin_layout.
1611 parent_context.new_paragraph(os);
1613 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1616 else if (name == "minipage") {
1617 eat_whitespace(p, os, parent_context, false);
1618 // Test whether this is an outer box of a shaded box
1620 // swallow arguments
1621 while (p.hasOpt()) {
1623 p.skip_spaces(true);
1626 p.skip_spaces(true);
1627 Token t = p.get_token();
1628 bool shaded = false;
1629 if (t.asInput() == "\\begin") {
1630 p.skip_spaces(true);
1631 if (p.getArg('{', '}') == "shaded")
1636 parse_outer_box(p, os, FLAG_END, outer,
1637 parent_context, name, "shaded");
1639 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1640 "", "", name, "", "");
1644 else if (name == "comment") {
1645 eat_whitespace(p, os, parent_context, false);
1646 parent_context.check_layout(os);
1647 begin_inset(os, "Note Comment\n");
1648 os << "status open\n";
1649 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1652 skip_braces(p); // eat {} that might by set by LyX behind comments
1653 preamble.registerAutomaticallyLoadedPackage("verbatim");
1656 else if (unstarred_name == "verbatim") {
1657 // FIXME: this should go in the generic code that
1658 // handles environments defined in layout file that
1659 // have "PassThru 1". However, the code over there is
1660 // already too complicated for my taste.
1661 string const ascii_name =
1662 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1663 parent_context.new_paragraph(os);
1664 Context context(true, parent_context.textclass,
1665 &parent_context.textclass[from_ascii(ascii_name)]);
1666 string s = p.verbatimEnvironment(name);
1667 output_ert(os, s, context);
1671 else if (name == "IPA") {
1672 eat_whitespace(p, os, parent_context, false);
1673 parent_context.check_layout(os);
1674 begin_inset(os, "IPA\n");
1675 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1678 preamble.registerAutomaticallyLoadedPackage("tipa");
1679 preamble.registerAutomaticallyLoadedPackage("tipx");
1682 else if (name == "CJK") {
1683 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1684 // It is impossible to decide if a CJK environment was in its own paragraph or within
1685 // a line. We therefore always assume a paragraph since the latter is a rare case.
1686 eat_whitespace(p, os, parent_context, false);
1687 parent_context.check_end_layout(os);
1688 // store the encoding to be able to reset it
1689 string const encoding_old = p.getEncoding();
1690 string const encoding = p.getArg('{', '}');
1691 // FIXME: For some reason JIS does not work. Although the text
1692 // in tests/CJK.tex is identical with the SJIS version if you
1693 // convert both snippets using the recode command line utility,
1694 // the resulting .lyx file contains some extra characters if
1695 // you set buggy_encoding to false for JIS.
1696 bool const buggy_encoding = encoding == "JIS";
1697 if (!buggy_encoding)
1698 p.setEncoding(encoding, Encoding::CJK);
1700 // FIXME: This will read garbage, since the data is not encoded in utf8.
1701 p.setEncoding("UTF-8");
1703 // LyX only supports the same mapping for all CJK
1704 // environments, so we might need to output everything as ERT
1705 string const mapping = trim(p.getArg('{', '}'));
1706 char const * const * const where =
1707 is_known(encoding, supported_CJK_encodings);
1708 if (!buggy_encoding && !preamble.fontCJKSet())
1709 preamble.fontCJK(mapping);
1710 bool knownMapping = mapping == preamble.fontCJK();
1711 if (buggy_encoding || !knownMapping || !where) {
1712 parent_context.check_layout(os);
1713 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1715 // we must parse the content as verbatim because e.g. JIS can contain
1716 // normally invalid characters
1717 // FIXME: This works only for the most simple cases.
1718 // Since TeX control characters are not parsed,
1719 // things like comments are completely wrong.
1720 string const s = p.plainEnvironment("CJK");
1721 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1723 output_ert_inset(os, "\\", parent_context);
1724 else if (*it == '$')
1725 output_ert_inset(os, "$", parent_context);
1726 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1731 output_ert_inset(os, "\\end{" + name + "}",
1735 supported_CJK_languages[where - supported_CJK_encodings];
1736 // store the language because we must reset it at the end
1737 string const lang_old = parent_context.font.language;
1738 parent_context.font.language = lang;
1739 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1740 parent_context.font.language = lang_old;
1741 parent_context.new_paragraph(os);
1743 p.setEncoding(encoding_old);
1747 else if (name == "lyxgreyedout") {
1748 eat_whitespace(p, os, parent_context, false);
1749 parent_context.check_layout(os);
1750 begin_inset(os, "Note Greyedout\n");
1751 os << "status open\n";
1752 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1755 if (!preamble.notefontcolor().empty())
1756 preamble.registerAutomaticallyLoadedPackage("color");
1759 else if (name == "btSect") {
1760 eat_whitespace(p, os, parent_context, false);
1761 parent_context.check_layout(os);
1762 begin_command_inset(os, "bibtex", "bibtex");
1763 string bibstyle = "plain";
1765 bibstyle = p.getArg('[', ']');
1766 p.skip_spaces(true);
1768 string const bibfile = p.getArg('{', '}');
1769 eat_whitespace(p, os, parent_context, false);
1770 Token t = p.get_token();
1771 if (t.asInput() == "\\btPrintCited") {
1772 p.skip_spaces(true);
1773 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1775 if (t.asInput() == "\\btPrintNotCited") {
1776 p.skip_spaces(true);
1777 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1779 if (t.asInput() == "\\btPrintAll") {
1780 p.skip_spaces(true);
1781 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1783 os << "bibfiles " << '"' << bibfile << "\"\n"
1784 << "options " << '"' << bibstyle << "\"\n";
1785 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1790 else if (name == "framed" || name == "shaded") {
1791 eat_whitespace(p, os, parent_context, false);
1792 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1794 preamble.registerAutomaticallyLoadedPackage("framed");
1797 else if (name == "listing") {
1798 minted_float = "float";
1799 eat_whitespace(p, os, parent_context, false);
1800 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1802 minted_float += "=" + opt;
1803 // If something precedes \begin{minted}, we output it at the end
1804 // as a caption, in order to keep it inside the listings inset.
1805 eat_whitespace(p, os, parent_context, true);
1807 Token const & t = p.get_token();
1808 p.skip_spaces(true);
1809 string const envname = p.next_token().cat() == catBegin
1810 ? p.getArg('{', '}') : string();
1811 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1813 minted_float_has_caption = false;
1814 string content = parse_text_snippet(p, FLAG_END, outer,
1816 size_t i = content.find("\\begin_inset listings");
1817 bool minted_env = i != string::npos;
1820 caption = content.substr(0, i);
1821 content.erase(0, i);
1823 parent_context.check_layout(os);
1824 if (minted_env && minted_float_has_caption) {
1825 eat_whitespace(p, os, parent_context, true);
1826 os << content << "\n";
1827 if (!caption.empty())
1828 os << caption << "\n";
1829 os << "\n\\end_layout\n"; // close inner layout
1830 end_inset(os); // close caption inset
1831 os << "\n\\end_layout\n"; // close outer layout
1832 } else if (!caption.empty()) {
1834 begin_inset(os, "listings\n");
1835 os << "lstparams " << '"' << minted_float << '"' << '\n';
1836 os << "inline false\n";
1837 os << "status collapsed\n";
1839 os << "\n\\begin_layout Plain Layout\n";
1840 begin_inset(os, "Caption Standard\n");
1841 Context newcontext(true, parent_context.textclass,
1842 0, 0, parent_context.font);
1843 newcontext.check_layout(os);
1844 os << caption << "\n";
1845 newcontext.check_end_layout(os);
1847 os << "\n\\end_layout\n";
1848 } else if (content.empty()) {
1849 begin_inset(os, "listings\n");
1850 os << "lstparams " << '"' << minted_float << '"' << '\n';
1851 os << "inline false\n";
1852 os << "status collapsed\n";
1854 os << content << "\n";
1856 end_inset(os); // close listings inset
1857 parent_context.check_end_layout(os);
1858 parent_context.new_paragraph(os);
1860 minted_float.clear();
1861 minted_float_has_caption = false;
1864 else if (name == "lstlisting" || name == "minted") {
1865 bool use_minted = name == "minted";
1866 eat_whitespace(p, os, parent_context, false);
1867 if (use_minted && minted_float.empty()) {
1868 // look ahead for a bottom caption
1870 bool found_end_minted = false;
1871 while (!found_end_minted && p.good()) {
1872 Token const & t = p.get_token();
1874 string const envname =
1875 p.next_token().cat() == catBegin
1876 ? p.getArg('{', '}') : string();
1877 found_end_minted = t.asInput() == "\\end"
1878 && envname == "minted";
1880 eat_whitespace(p, os, parent_context, true);
1881 Token const & t = p.get_token();
1882 p.skip_spaces(true);
1883 if (t.asInput() == "\\lyxmintcaption") {
1884 string const pos = p.getArg('[', ']');
1886 string const caption =
1887 parse_text_snippet(p, FLAG_ITEM,
1888 false, parent_context);
1889 minted_nonfloat_caption = "[b]" + caption;
1894 parse_listings(p, os, parent_context, false, use_minted);
1898 else if (!parent_context.new_layout_allowed)
1899 parse_unknown_environment(p, name, os, FLAG_END, outer,
1902 // Alignment and spacing settings
1903 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1904 // therefore are totally broken!
1905 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1906 // they are commands not environments. They are furthermore switches that
1907 // can be ended by another switches, but also by commands like \footnote or
1908 // \parbox. So the only safe way is to leave them untouched.
1909 // However, we support the pseudo-environments
1910 // \begin{centering} ... \end{centering}
1911 // \begin{raggedright} ... \end{raggedright}
1912 // \begin{raggedleft} ... \end{raggedleft}
1913 // since they are used by LyX in floats (for spacing reasons)
1914 else if (name == "center" || name == "centering" ||
1915 name == "flushleft" || name == "raggedright" ||
1916 name == "flushright" || name == "raggedleft" ||
1917 name == "singlespace" || name == "onehalfspace" ||
1918 name == "doublespace" || name == "spacing") {
1919 eat_whitespace(p, os, parent_context, false);
1920 // We must begin a new paragraph if not already done
1921 if (! parent_context.atParagraphStart()) {
1922 parent_context.check_end_layout(os);
1923 parent_context.new_paragraph(os);
1925 if (name == "flushleft" || name == "raggedright")
1926 parent_context.add_extra_stuff("\\align left\n");
1927 else if (name == "flushright" || name == "raggedleft")
1928 parent_context.add_extra_stuff("\\align right\n");
1929 else if (name == "center" || name == "centering")
1930 parent_context.add_extra_stuff("\\align center\n");
1931 else if (name == "singlespace")
1932 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1933 else if (name == "onehalfspace") {
1934 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1935 preamble.registerAutomaticallyLoadedPackage("setspace");
1936 } else if (name == "doublespace") {
1937 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1938 preamble.registerAutomaticallyLoadedPackage("setspace");
1939 } else if (name == "spacing") {
1940 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1941 preamble.registerAutomaticallyLoadedPackage("setspace");
1943 parse_text(p, os, FLAG_END, outer, parent_context);
1944 // Just in case the environment is empty
1945 parent_context.extra_stuff.erase();
1946 // We must begin a new paragraph to reset the alignment
1947 parent_context.new_paragraph(os);
1951 // The single '=' is meant here.
1952 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1953 eat_whitespace(p, os, parent_context, false);
1954 Context context(true, parent_context.textclass, newlayout,
1955 parent_context.layout, parent_context.font);
1956 if (parent_context.deeper_paragraph) {
1957 // We are beginning a nested environment after a
1958 // deeper paragraph inside the outer list environment.
1959 // Therefore we don't need to output a "begin deeper".
1960 context.need_end_deeper = true;
1962 parent_context.check_end_layout(os);
1963 if (last_env == name) {
1964 // we need to output a separator since LyX would export
1965 // the two environments as one otherwise (bug 5716)
1966 TeX2LyXDocClass const & textclass(parent_context.textclass);
1967 Context newcontext(true, textclass,
1968 &(textclass.defaultLayout()));
1969 newcontext.check_layout(os);
1970 begin_inset(os, "Separator plain\n");
1972 newcontext.check_end_layout(os);
1974 switch (context.layout->latextype) {
1975 case LATEX_LIST_ENVIRONMENT:
1976 context.add_par_extra_stuff("\\labelwidthstring "
1977 + p.verbatim_item() + '\n');
1980 case LATEX_BIB_ENVIRONMENT:
1981 p.verbatim_item(); // swallow next arg
1987 context.check_deeper(os);
1988 // handle known optional and required arguments
1989 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1990 // It is impossible to place anything after the environment name,
1991 // but before the first \\item.
1992 if (context.layout->latextype == LATEX_ENVIRONMENT)
1993 output_arguments(os, p, outer, false, false, context,
1994 context.layout->latexargs());
1995 parse_text(p, os, FLAG_END, outer, context);
1996 if (context.layout->latextype == LATEX_ENVIRONMENT)
1997 output_arguments(os, p, outer, false, true, context,
1998 context.layout->postcommandargs());
1999 context.check_end_layout(os);
2000 if (parent_context.deeper_paragraph) {
2001 // We must suppress the "end deeper" because we
2002 // suppressed the "begin deeper" above.
2003 context.need_end_deeper = false;
2005 context.check_end_deeper(os);
2006 parent_context.new_paragraph(os);
2008 if (!preamble.titleLayoutFound())
2009 preamble.titleLayoutFound(newlayout->intitle);
2010 set<string> const & req = newlayout->requires();
2011 set<string>::const_iterator it = req.begin();
2012 set<string>::const_iterator en = req.end();
2013 for (; it != en; ++it)
2014 preamble.registerAutomaticallyLoadedPackage(*it);
2017 // The single '=' is meant here.
2018 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2019 eat_whitespace(p, os, parent_context, false);
2020 parent_context.check_layout(os);
2021 begin_inset(os, "Flex ");
2022 docstring flex_name = newinsetlayout->name();
2023 // FIXME: what do we do if the prefix is not Flex: ?
2024 if (prefixIs(flex_name, from_ascii("Flex:")))
2025 flex_name.erase(0, 5);
2026 os << to_utf8(flex_name) << '\n'
2027 << "status collapsed\n";
2028 if (newinsetlayout->isPassThru()) {
2029 string const arg = p.verbatimEnvironment(name);
2030 Context context(true, parent_context.textclass,
2031 &parent_context.textclass.plainLayout(),
2032 parent_context.layout);
2033 output_ert(os, arg, parent_context);
2035 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2039 else if (name == "appendix") {
2040 // This is no good latex style, but it works and is used in some documents...
2041 eat_whitespace(p, os, parent_context, false);
2042 parent_context.check_end_layout(os);
2043 Context context(true, parent_context.textclass, parent_context.layout,
2044 parent_context.layout, parent_context.font);
2045 context.check_layout(os);
2046 os << "\\start_of_appendix\n";
2047 parse_text(p, os, FLAG_END, outer, context);
2048 context.check_end_layout(os);
2052 else if (known_environments.find(name) != known_environments.end()) {
2053 vector<ArgumentType> arguments = known_environments[name];
2054 // The last "argument" denotes wether we may translate the
2055 // environment contents to LyX
2056 // The default required if no argument is given makes us
2057 // compatible with the reLyXre environment.
2058 ArgumentType contents = arguments.empty() ?
2061 if (!arguments.empty())
2062 arguments.pop_back();
2063 // See comment in parse_unknown_environment()
2064 bool const specialfont =
2065 (parent_context.font != parent_context.normalfont);
2066 bool const new_layout_allowed =
2067 parent_context.new_layout_allowed;
2069 parent_context.new_layout_allowed = false;
2070 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2071 outer, parent_context);
2072 if (contents == verbatim)
2073 output_ert_inset(os, p.ertEnvironment(name),
2076 parse_text_snippet(p, os, FLAG_END, outer,
2078 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2080 parent_context.new_layout_allowed = new_layout_allowed;
2084 parse_unknown_environment(p, name, os, FLAG_END, outer,
2088 active_environments.pop_back();
2092 /// parses a comment and outputs it to \p os.
2093 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2095 LASSERT(t.cat() == catComment, return);
2096 if (!t.cs().empty()) {
2097 context.check_layout(os);
2098 output_comment(p, os, t.cs(), context);
2099 if (p.next_token().cat() == catNewline) {
2100 // A newline after a comment line starts a new
2102 if (context.new_layout_allowed) {
2103 if(!context.atParagraphStart())
2104 // Only start a new paragraph if not already
2105 // done (we might get called recursively)
2106 context.new_paragraph(os);
2108 output_ert_inset(os, "\n", context);
2109 eat_whitespace(p, os, context, true);
2112 // "%\n" combination
2119 * Reads spaces and comments until the first non-space, non-comment token.
2120 * New paragraphs (double newlines or \\par) are handled like simple spaces
2121 * if \p eatParagraph is true.
2122 * Spaces are skipped, but comments are written to \p os.
2124 void eat_whitespace(Parser & p, ostream & os, Context & context,
2128 Token const & t = p.get_token();
2129 if (t.cat() == catComment)
2130 parse_comment(p, os, t, context);
2131 else if ((! eatParagraph && p.isParagraph()) ||
2132 (t.cat() != catSpace && t.cat() != catNewline)) {
2141 * Set a font attribute, parse text and reset the font attribute.
2142 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2143 * \param currentvalue Current value of the attribute. Is set to the new
2144 * value during parsing.
2145 * \param newvalue New value of the attribute
2147 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2148 Context & context, string const & attribute,
2149 string & currentvalue, string const & newvalue)
2151 context.check_layout(os);
2152 string const oldvalue = currentvalue;
2153 currentvalue = newvalue;
2154 os << '\n' << attribute << ' ' << newvalue << "\n";
2155 parse_text_snippet(p, os, flags, outer, context);
2156 context.check_layout(os);
2157 os << '\n' << attribute << ' ' << oldvalue << "\n";
2158 currentvalue = oldvalue;
2162 /// get the arguments of a natbib or jurabib citation command
2163 void get_cite_arguments(Parser & p, bool natbibOrder,
2164 string & before, string & after, bool const qualified = false)
2166 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2168 // text before the citation
2170 // text after the citation
2171 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2173 if (!after.empty()) {
2174 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2175 if (natbibOrder && !before.empty())
2176 swap(before, after);
2181 void copy_file(FileName const & src, string dstname)
2185 string const absParent = getParentFilePath(false);
2187 if (FileName::isAbsolute(dstname))
2188 dst = FileName(dstname);
2190 dst = makeAbsPath(dstname, absParent);
2191 FileName const srcpath = src.onlyPath();
2192 FileName const dstpath = dst.onlyPath();
2193 if (equivalent(srcpath, dstpath))
2195 if (!dstpath.isDirectory()) {
2196 if (!dstpath.createPath()) {
2197 cerr << "Warning: Could not create directory for file `"
2198 << dst.absFileName() << "´." << endl;
2202 if (dst.isReadableFile()) {
2203 if (overwriteFiles())
2204 cerr << "Warning: Overwriting existing file `"
2205 << dst.absFileName() << "´." << endl;
2207 cerr << "Warning: Not overwriting existing file `"
2208 << dst.absFileName() << "´." << endl;
2212 if (!src.copyTo(dst))
2213 cerr << "Warning: Could not copy file `" << src.absFileName()
2214 << "´ to `" << dst.absFileName() << "´." << endl;
2218 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2219 bool parse_chunk(Parser & p, ostream & os, Context & context)
2221 // check whether a chunk is possible here.
2222 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2228 // read the parameters
2229 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2230 if (!params.first) {
2235 Parser::Arg const code = p.verbatimStuff("\n@");
2240 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2241 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2245 // The last newline read is important for paragraph handling
2249 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2250 // We must have a valid layout before outputting the Chunk inset.
2251 context.check_layout(os);
2252 Context chunkcontext(true, context.textclass);
2253 chunkcontext.layout = &context.textclass.plainLayout();
2254 begin_inset(os, "Flex Chunk");
2255 os << "\nstatus open\n";
2256 if (!params.second.empty()) {
2257 chunkcontext.check_layout(os);
2258 Context paramscontext(true, context.textclass);
2259 paramscontext.layout = &context.textclass.plainLayout();
2260 begin_inset(os, "Argument 1");
2261 os << "\nstatus open\n";
2262 output_ert(os, params.second, paramscontext);
2265 output_ert(os, code.second, chunkcontext);
2273 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2274 bool is_macro(Parser & p)
2276 Token first = p.curr_token();
2277 if (first.cat() != catEscape || !p.good())
2279 if (first.cs() == "def")
2281 if (first.cs() != "global" && first.cs() != "long")
2283 Token second = p.get_token();
2285 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2286 second.cat() == catNewline || second.cat() == catComment)) {
2287 second = p.get_token();
2290 bool secondvalid = second.cat() == catEscape;
2292 bool thirdvalid = false;
2293 if (p.good() && first.cs() == "global" && secondvalid &&
2294 second.cs() == "long") {
2295 third = p.get_token();
2297 while (p.good() && !p.isParagraph() &&
2298 (third.cat() == catSpace ||
2299 third.cat() == catNewline ||
2300 third.cat() == catComment)) {
2301 third = p.get_token();
2304 thirdvalid = third.cat() == catEscape;
2306 for (int i = 0; i < pos; ++i)
2311 return (first.cs() == "global" || first.cs() == "long") &&
2312 second.cs() == "def";
2313 return first.cs() == "global" && second.cs() == "long" &&
2314 third.cs() == "def";
2318 /// Parse a macro definition (assumes that is_macro() returned true)
2319 void parse_macro(Parser & p, ostream & os, Context & context)
2321 context.check_layout(os);
2322 Token first = p.curr_token();
2325 string command = first.asInput();
2326 if (first.cs() != "def") {
2328 eat_whitespace(p, os, context, false);
2329 second = p.curr_token();
2330 command += second.asInput();
2331 if (second.cs() != "def") {
2333 eat_whitespace(p, os, context, false);
2334 third = p.curr_token();
2335 command += third.asInput();
2338 eat_whitespace(p, os, context, false);
2339 string const name = p.get_token().cs();
2340 eat_whitespace(p, os, context, false);
2346 while (p.next_token().cat() != catBegin) {
2347 if (p.next_token().cat() == catParameter) {
2352 // followed by number?
2353 if (p.next_token().cat() == catOther) {
2354 string s = p.get_token().asInput();
2356 // number = current arity + 1?
2357 if (s.size() == 1 && s[0] == arity + '0' + 1)
2362 paramtext += p.get_token().cs();
2364 paramtext += p.get_token().cs();
2369 // only output simple (i.e. compatible) macro as FormulaMacros
2370 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2372 context.check_layout(os);
2373 begin_inset(os, "FormulaMacro");
2374 os << "\n\\def" << ert;
2377 output_ert_inset(os, command + ert, context);
2381 void registerExternalTemplatePackages(string const & name)
2383 external::TemplateManager const & etm = external::TemplateManager::get();
2384 external::Template const * const et = etm.getTemplateByName(name);
2387 external::Template::Formats::const_iterator cit = et->formats.end();
2389 cit = et->formats.find("PDFLaTeX");
2390 if (cit == et->formats.end())
2391 // If the template has not specified a PDFLaTeX output,
2392 // we try the LaTeX format.
2393 cit = et->formats.find("LaTeX");
2394 if (cit == et->formats.end())
2396 vector<string>::const_iterator qit = cit->second.requirements.begin();
2397 vector<string>::const_iterator qend = cit->second.requirements.end();
2398 for (; qit != qend; ++qit)
2399 preamble.registerAutomaticallyLoadedPackage(*qit);
2402 } // anonymous namespace
2406 * Find a file with basename \p name in path \p path and an extension
2409 string find_file(string const & name, string const & path,
2410 char const * const * extensions)
2412 for (char const * const * what = extensions; *what; ++what) {
2413 string const trial = addExtension(name, *what);
2414 if (makeAbsPath(trial, path).exists())
2421 /// Convert filenames with TeX macros and/or quotes to something LyX
2423 string const normalize_filename(string const & name)
2428 Token const & t = p.get_token();
2429 if (t.cat() != catEscape)
2431 else if (t.cs() == "lyxdot") {
2432 // This is used by LyX for simple dots in relative
2436 } else if (t.cs() == "space") {
2439 } else if (t.cs() == "string") {
2440 // Convert \string" to " and \string~ to ~
2441 Token const & n = p.next_token();
2442 if (n.asInput() != "\"" && n.asInput() != "~")
2447 // Strip quotes. This is a bit complicated (see latex_path()).
2448 string full = os.str();
2449 if (!full.empty() && full[0] == '"') {
2450 string base = removeExtension(full);
2451 string ext = getExtension(full);
2452 if (!base.empty() && base[base.length()-1] == '"')
2455 return addExtension(trim(base, "\""), ext);
2456 if (full[full.length()-1] == '"')
2459 return trim(full, "\"");
2465 /// Convert \p name from TeX convention (relative to master file) to LyX
2466 /// convention (relative to .lyx file) if it is relative
2467 void fix_child_filename(string & name)
2469 string const absMasterTeX = getMasterFilePath(true);
2470 bool const isabs = FileName::isAbsolute(name);
2471 // convert from "relative to .tex master" to absolute original path
2473 name = makeAbsPath(name, absMasterTeX).absFileName();
2474 bool copyfile = copyFiles();
2475 string const absParentLyX = getParentFilePath(false);
2478 // convert from absolute original path to "relative to master file"
2479 string const rel = to_utf8(makeRelPath(from_utf8(name),
2480 from_utf8(absMasterTeX)));
2481 // re-interpret "relative to .tex file" as "relative to .lyx file"
2482 // (is different if the master .lyx file resides in a
2483 // different path than the master .tex file)
2484 string const absMasterLyX = getMasterFilePath(false);
2485 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2486 // Do not copy if the new path is impossible to create. Example:
2487 // absMasterTeX = "/foo/bar/"
2488 // absMasterLyX = "/bar/"
2489 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2490 if (contains(name, "/../"))
2497 // convert from absolute original path to
2498 // "relative to .lyx file"
2499 name = to_utf8(makeRelPath(from_utf8(abs),
2500 from_utf8(absParentLyX)));
2504 // convert from absolute original path to "relative to .lyx file"
2505 name = to_utf8(makeRelPath(from_utf8(name),
2506 from_utf8(absParentLyX)));
2511 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2514 Layout const * newlayout = 0;
2515 InsetLayout const * newinsetlayout = 0;
2516 char const * const * where = 0;
2517 // Store the latest bibliographystyle, addcontentslineContent and
2518 // nocite{*} option (needed for bibtex inset)
2520 string contentslineContent;
2521 // Some classes provide a \bibliographystyle, so do not output
2522 // any if none is explicitly set.
2523 string bibliographystyle;
2524 bool const use_natbib = isProvided("natbib");
2525 bool const use_jurabib = isProvided("jurabib");
2526 bool const use_biblatex = isProvided("biblatex")
2527 && preamble.citeEngine() != "biblatex-natbib";
2528 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2529 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2530 need_commentbib = use_biblatex || use_biblatex_natbib;
2533 // it is impossible to determine the correct encoding for non-CJK Japanese.
2534 // Therefore write a note at the beginning of the document
2535 if (is_nonCJKJapanese) {
2536 context.check_layout(os);
2537 begin_inset(os, "Note Note\n");
2538 os << "status open\n\\begin_layout Plain Layout\n"
2539 << "\\series bold\n"
2540 << "Important information:\n"
2541 << "\\end_layout\n\n"
2542 << "\\begin_layout Plain Layout\n"
2543 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2544 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2545 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2546 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2547 << " and specify the encoding using the -e command-line switch.\n"
2548 << " In addition, you might want to double check that the desired output encoding\n"
2549 << " is correctly selected in Document > Settings > Language.\n"
2550 << "\\end_layout\n";
2552 is_nonCJKJapanese = false;
2555 bool have_cycled = false;
2557 // Leave here only after at least one cycle
2558 if (have_cycled && flags & FLAG_LEAVE) {
2559 flags &= ~FLAG_LEAVE;
2563 Token const & t = p.get_token();
2565 debugToken(cerr, t, flags);
2568 if (flags & FLAG_ITEM) {
2569 if (t.cat() == catSpace)
2572 flags &= ~FLAG_ITEM;
2573 if (t.cat() == catBegin) {
2574 // skip the brace and collect everything to the next matching
2576 flags |= FLAG_BRACE_LAST;
2580 // handle only this single token, leave the loop if done
2581 flags |= FLAG_LEAVE;
2584 if (t.cat() != catEscape && t.character() == ']' &&
2585 (flags & FLAG_BRACK_LAST))
2587 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2590 // If there is anything between \end{env} and \begin{env} we
2591 // don't need to output a separator.
2592 if (t.cat() != catSpace && t.cat() != catNewline &&
2593 t.asInput() != "\\begin")
2600 bool const starred = p.next_token().asInput() == "*";
2601 string const starredname(starred ? (t.cs() + '*') : t.cs());
2602 if (t.cat() == catMath) {
2603 // we are inside some text mode thingy, so opening new math is allowed
2604 context.check_layout(os);
2605 begin_inset(os, "Formula ");
2606 Token const & n = p.get_token();
2607 bool const display(n.cat() == catMath && outer);
2609 // TeX's $$...$$ syntax for displayed math
2611 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2613 p.get_token(); // skip the second '$' token
2615 // simple $...$ stuff
2618 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2623 // Prevent the conversion of a line break to a
2624 // space (bug 7668). This does not change the
2625 // output, but looks ugly in LyX.
2626 eat_whitespace(p, os, context, false);
2631 if (t.cat() == catSuper || t.cat() == catSub) {
2632 cerr << "catcode " << t << " illegal in text mode\n";
2636 // Basic support for english quotes. This should be
2637 // extended to other quotes, but is not so easy (a
2638 // left english quote is the same as a right german
2640 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2641 context.check_layout(os);
2642 begin_inset(os, "Quotes ");
2649 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2650 context.check_layout(os);
2651 begin_inset(os, "Quotes ");
2659 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2660 context.check_layout(os);
2661 begin_inset(os, "Quotes ");
2669 if (t.asInput() == "<"
2670 && p.next_token().asInput() == "<") {
2671 bool has_chunk = false;
2675 has_chunk = parse_chunk(p, os, context);
2681 context.check_layout(os);
2682 begin_inset(os, "Quotes ");
2683 //FIXME: this is a right danish quote;
2684 // why not a left french quote?
2693 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2694 check_space(p, os, context);
2698 // babel shorthands (also used by polyglossia)
2699 // Since these can have different meanings for different languages
2700 // we import them as ERT (but they must be put in ERT to get output
2702 if (t.asInput() == "\"") {
2704 // These are known pairs. We put them together in
2705 // one ERT inset. In other cases (such as "a), only
2706 // the quotation mark is ERTed.
2707 if (p.next_token().asInput() == "\""
2708 || p.next_token().asInput() == "|"
2709 || p.next_token().asInput() == "-"
2710 || p.next_token().asInput() == "~"
2711 || p.next_token().asInput() == "="
2712 || p.next_token().asInput() == "/"
2713 || p.next_token().asInput() == "~"
2714 || p.next_token().asInput() == "'"
2715 || p.next_token().asInput() == "`"
2716 || p.next_token().asInput() == "<"
2717 || p.next_token().asInput() == ">") {
2718 s += p.next_token().asInput();
2721 output_ert_inset(os, s, context);
2725 if (t.character() == '[' && noweb_mode &&
2726 p.next_token().character() == '[') {
2727 // These can contain underscores
2729 string const s = p.getFullOpt() + ']';
2730 if (p.next_token().character() == ']')
2733 cerr << "Warning: Inserting missing ']' in '"
2734 << s << "'." << endl;
2735 output_ert_inset(os, s, context);
2739 if (t.cat() == catLetter) {
2740 context.check_layout(os);
2745 if (t.cat() == catOther ||
2746 t.cat() == catAlign ||
2747 t.cat() == catParameter) {
2748 context.check_layout(os);
2749 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2750 context.merging_hyphens_allowed &&
2751 context.font.family != "ttfamily" &&
2752 !context.layout->pass_thru) {
2753 if (p.next_next_token().asInput() == "-") {
2755 os << to_utf8(docstring(1, 0x2014));
2759 os << to_utf8(docstring(1, 0x2013));
2762 // This translates "&" to "\\&" which may be wrong...
2767 if (p.isParagraph()) {
2768 // In minted floating listings we will collect
2769 // everything into the caption, where multiple
2770 // paragraphs are forbidden.
2771 if (minted_float.empty()) {
2772 if (context.new_layout_allowed)
2773 context.new_paragraph(os);
2775 output_ert_inset(os, "\\par ", context);
2778 eat_whitespace(p, os, context, true);
2782 if (t.cat() == catActive) {
2783 context.check_layout(os);
2784 if (t.character() == '~') {
2785 if (context.layout->free_spacing)
2788 begin_inset(os, "space ~\n");
2796 if (t.cat() == catBegin) {
2797 Token const next = p.next_token();
2798 Token const end = p.next_next_token();
2799 if (next.cat() == catEnd) {
2801 Token const prev = p.prev_token();
2803 if (p.next_token().character() == '`')
2804 ; // ignore it in {}``
2806 output_ert_inset(os, "{}", context);
2807 } else if (next.cat() == catEscape &&
2808 is_known(next.cs(), known_quotes) &&
2809 end.cat() == catEnd) {
2810 // Something like {\textquoteright} (e.g.
2811 // from writer2latex). LyX writes
2812 // \textquoteright{}, so we may skip the
2813 // braces here for better readability.
2814 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2816 } else if (p.next_token().asInput() == "\\ascii") {
2817 // handle the \ascii characters
2818 // (the case without braces is handled later)
2819 // the code is "{\ascii\xxx}"
2820 p.get_token(); // eat \ascii
2821 string name2 = p.get_token().asInput();
2822 p.get_token(); // eat the final '}'
2823 string const name = "{\\ascii" + name2 + "}";
2827 // get the character from unicodesymbols
2828 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2829 Encodings::TEXT_CMD, termination, rem, &req);
2831 context.check_layout(os);
2834 output_ert_inset(os,
2835 to_utf8(rem), context);
2836 for (set<string>::const_iterator it = req.begin();
2837 it != req.end(); ++it)
2838 preamble.registerAutomaticallyLoadedPackage(*it);
2840 // we did not find a non-ert version
2841 output_ert_inset(os, name, context);
2843 context.check_layout(os);
2844 // special handling of font attribute changes
2845 Token const prev = p.prev_token();
2846 TeXFont const oldFont = context.font;
2847 if (next.character() == '[' ||
2848 next.character() == ']' ||
2849 next.character() == '*') {
2851 if (p.next_token().cat() == catEnd) {
2856 output_ert_inset(os, "{", context);
2857 parse_text_snippet(p, os,
2860 output_ert_inset(os, "}", context);
2862 } else if (! context.new_layout_allowed) {
2863 output_ert_inset(os, "{", context);
2864 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2866 output_ert_inset(os, "}", context);
2867 } else if (is_known(next.cs(), known_sizes)) {
2868 // next will change the size, so we must
2870 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2872 if (!context.atParagraphStart())
2874 << context.font.size << "\n";
2875 } else if (is_known(next.cs(), known_font_families)) {
2876 // next will change the font family, so we
2877 // must reset it here
2878 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2880 if (!context.atParagraphStart())
2882 << context.font.family << "\n";
2883 } else if (is_known(next.cs(), known_font_series)) {
2884 // next will change the font series, so we
2885 // must reset it here
2886 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2888 if (!context.atParagraphStart())
2890 << context.font.series << "\n";
2891 } else if (is_known(next.cs(), known_font_shapes)) {
2892 // next will change the font shape, so we
2893 // must reset it here
2894 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2896 if (!context.atParagraphStart())
2898 << context.font.shape << "\n";
2899 } else if (is_known(next.cs(), known_old_font_families) ||
2900 is_known(next.cs(), known_old_font_series) ||
2901 is_known(next.cs(), known_old_font_shapes)) {
2902 // next will change the font family, series
2903 // and shape, so we must reset it here
2904 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2906 if (!context.atParagraphStart())
2908 << context.font.family
2910 << context.font.series
2912 << context.font.shape << "\n";
2914 output_ert_inset(os, "{", context);
2915 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2917 output_ert_inset(os, "}", context);
2923 if (t.cat() == catEnd) {
2924 if (flags & FLAG_BRACE_LAST) {
2927 cerr << "stray '}' in text\n";
2928 output_ert_inset(os, "}", context);
2932 if (t.cat() == catComment) {
2933 parse_comment(p, os, t, context);
2938 // control sequences
2941 if (t.cs() == "(" || t.cs() == "[") {
2942 bool const simple = t.cs() == "(";
2943 context.check_layout(os);
2944 begin_inset(os, "Formula");
2945 os << " \\" << t.cs();
2946 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2947 os << '\\' << (simple ? ')' : ']');
2950 // Prevent the conversion of a line break to a
2951 // space (bug 7668). This does not change the
2952 // output, but looks ugly in LyX.
2953 eat_whitespace(p, os, context, false);
2958 if (t.cs() == "begin") {
2959 parse_environment(p, os, outer, last_env,
2964 if (t.cs() == "end") {
2965 if (flags & FLAG_END) {
2966 // eat environment name
2967 string const name = p.getArg('{', '}');
2968 if (name != active_environment())
2969 cerr << "\\end{" + name + "} does not match \\begin{"
2970 + active_environment() + "}\n";
2973 p.error("found 'end' unexpectedly");
2977 if (t.cs() == "item") {
2979 bool const optarg = p.hasOpt();
2981 // FIXME: This swallows comments, but we cannot use
2982 // eat_whitespace() since we must not output
2983 // anything before the item.
2984 p.skip_spaces(true);
2985 s = p.verbatimOption();
2987 p.skip_spaces(false);
2989 context.check_layout(os);
2990 if (context.has_item) {
2991 // An item in an unknown list-like environment
2992 // FIXME: Do this in check_layout()!
2993 context.has_item = false;
2995 output_ert_inset(os, "\\item", context);
2997 output_ert_inset(os, "\\item ", context);
3000 if (context.layout->labeltype != LABEL_MANUAL) {
3001 // handle option of itemize item
3002 begin_inset(os, "Argument item:1\n");
3003 os << "status open\n";
3004 os << "\n\\begin_layout Plain Layout\n";
3006 os << parse_text_snippet(p2,
3007 FLAG_BRACK_LAST, outer, context);
3008 // we must not use context.check_end_layout(os)
3009 // because that would close the outer itemize layout
3010 os << "\n\\end_layout\n";
3012 eat_whitespace(p, os, context, false);
3013 } else if (!s.empty()) {
3014 // LyX adds braces around the argument,
3015 // so we need to remove them here.
3016 if (s.size() > 2 && s[0] == '{' &&
3017 s[s.size()-1] == '}')
3018 s = s.substr(1, s.size()-2);
3019 // If the argument contains a space we
3020 // must put it into ERT: Otherwise LyX
3021 // would misinterpret the space as
3022 // item delimiter (bug 7663)
3023 if (contains(s, ' ')) {
3024 output_ert_inset(os, s, context);
3027 os << parse_text_snippet(p2,
3028 FLAG_BRACK_LAST, outer, context);
3030 // The space is needed to separate the
3031 // item from the rest of the sentence.
3033 eat_whitespace(p, os, context, false);
3039 if (t.cs() == "bibitem") {
3041 context.check_layout(os);
3042 eat_whitespace(p, os, context, false);
3043 string label = p.verbatimOption();
3044 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3045 bool const literal = !lbl.first;
3046 label = literal ? subst(label, "\n", " ") : lbl.second;
3047 string lit = literal ? "\"true\"" : "\"false\"";
3048 string key = convert_literate_command_inset_arg(p.verbatim_item());
3049 begin_command_inset(os, "bibitem", "bibitem");
3050 os << "label \"" << label << "\"\n"
3051 << "key \"" << key << "\"\n"
3052 << "literal " << lit << "\n";
3058 // catch the case of \def\inputGnumericTable
3060 if (t.cs() == "def") {
3061 Token second = p.next_token();
3062 if (second.cs() == "inputGnumericTable") {
3066 Token third = p.get_token();
3068 if (third.cs() == "input") {
3072 string name = normalize_filename(p.verbatim_item());
3073 string const path = getMasterFilePath(true);
3074 // We want to preserve relative / absolute filenames,
3075 // therefore path is only used for testing
3076 // The file extension is in every case ".tex".
3077 // So we need to remove this extension and check for
3078 // the original one.
3079 name = removeExtension(name);
3080 if (!makeAbsPath(name, path).exists()) {
3081 char const * const Gnumeric_formats[] = {"gnumeric",
3083 string const Gnumeric_name =
3084 find_file(name, path, Gnumeric_formats);
3085 if (!Gnumeric_name.empty())
3086 name = Gnumeric_name;
3088 FileName const absname = makeAbsPath(name, path);
3089 if (absname.exists()) {
3090 fix_child_filename(name);
3091 copy_file(absname, name);
3093 cerr << "Warning: Could not find file '"
3094 << name << "'." << endl;
3095 context.check_layout(os);
3096 begin_inset(os, "External\n\ttemplate ");
3097 os << "GnumericSpreadsheet\n\tfilename "
3100 context.check_layout(os);
3102 // register the packages that are automatically loaded
3103 // by the Gnumeric template
3104 registerExternalTemplatePackages("GnumericSpreadsheet");
3109 parse_macro(p, os, context);
3113 if (t.cs() == "noindent") {
3115 context.add_par_extra_stuff("\\noindent\n");
3119 if (t.cs() == "appendix") {
3120 context.add_par_extra_stuff("\\start_of_appendix\n");
3121 // We need to start a new paragraph. Otherwise the
3122 // appendix in 'bla\appendix\chapter{' would start
3124 context.new_paragraph(os);
3125 // We need to make sure that the paragraph is
3126 // generated even if it is empty. Otherwise the
3127 // appendix in '\par\appendix\par\chapter{' would
3129 context.check_layout(os);
3130 // FIXME: This is a hack to prevent paragraph
3131 // deletion if it is empty. Handle this better!
3132 output_comment(p, os,
3133 "dummy comment inserted by tex2lyx to "
3134 "ensure that this paragraph is not empty",
3136 // Both measures above may generate an additional
3137 // empty paragraph, but that does not hurt, because
3138 // whitespace does not matter here.
3139 eat_whitespace(p, os, context, true);
3143 // Must catch empty dates before findLayout is called below
3144 if (t.cs() == "date") {
3145 eat_whitespace(p, os, context, false);
3147 string const date = p.verbatim_item();
3150 preamble.suppressDate(true);
3153 preamble.suppressDate(false);
3154 if (context.new_layout_allowed &&
3155 (newlayout = findLayout(context.textclass,
3158 output_command_layout(os, p, outer,
3159 context, newlayout);
3160 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3161 if (!preamble.titleLayoutFound())
3162 preamble.titleLayoutFound(newlayout->intitle);
3163 set<string> const & req = newlayout->requires();
3164 set<string>::const_iterator it = req.begin();
3165 set<string>::const_iterator en = req.end();
3166 for (; it != en; ++it)
3167 preamble.registerAutomaticallyLoadedPackage(*it);
3169 output_ert_inset(os,
3170 "\\date{" + p.verbatim_item() + '}',
3176 // Starred section headings
3177 // Must attempt to parse "Section*" before "Section".
3178 if ((p.next_token().asInput() == "*") &&
3179 context.new_layout_allowed &&
3180 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3183 output_command_layout(os, p, outer, context, newlayout);
3185 if (!preamble.titleLayoutFound())
3186 preamble.titleLayoutFound(newlayout->intitle);
3187 set<string> const & req = newlayout->requires();
3188 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3189 preamble.registerAutomaticallyLoadedPackage(*it);
3193 // Section headings and the like
3194 if (context.new_layout_allowed &&
3195 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3197 output_command_layout(os, p, outer, context, newlayout);
3199 if (!preamble.titleLayoutFound())
3200 preamble.titleLayoutFound(newlayout->intitle);
3201 set<string> const & req = newlayout->requires();
3202 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3203 preamble.registerAutomaticallyLoadedPackage(*it);
3207 if (t.cs() == "subfloat") {
3208 // the syntax is \subfloat[list entry][sub caption]{content}
3209 // if it is a table of figure depends on the surrounding float
3211 // do nothing if there is no outer float
3212 if (!float_type.empty()) {
3213 context.check_layout(os);
3215 begin_inset(os, "Float " + float_type + "\n");
3217 << "\nsideways false"
3218 << "\nstatus collapsed\n\n";
3221 bool has_caption = false;
3222 if (p.next_token().cat() != catEscape &&
3223 p.next_token().character() == '[') {
3224 p.get_token(); // eat '['
3225 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3228 // In case we have two optional args, the second is the caption.
3229 if (p.next_token().cat() != catEscape &&
3230 p.next_token().character() == '[') {
3231 p.get_token(); // eat '['
3232 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3235 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3236 // the caption comes always as the last
3238 // we must make sure that the caption gets a \begin_layout
3239 os << "\n\\begin_layout Plain Layout";
3241 begin_inset(os, "Caption Standard\n");
3242 Context newcontext(true, context.textclass,
3243 0, 0, context.font);
3244 newcontext.check_layout(os);
3245 os << caption << "\n";
3246 newcontext.check_end_layout(os);
3249 // close the layout we opened
3250 os << "\n\\end_layout";
3255 // if the float type is not supported or there is no surrounding float
3260 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3262 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3264 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3265 + "{" + p.verbatim_item() + '}', context);
3270 if (t.cs() == "xymatrix") {
3271 // we must open a new math because LyX's xy support is in math
3272 context.check_layout(os);
3273 begin_inset(os, "Formula ");
3275 os << "\\" << t.cs() << '{';
3276 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3279 preamble.registerAutomaticallyLoadedPackage("xy");
3283 if (t.cs() == "includegraphics") {
3284 bool const clip = p.next_token().asInput() == "*";
3287 string const arg = p.getArg('[', ']');
3288 map<string, string> opts;
3289 vector<string> keys;
3290 split_map(arg, opts, keys);
3292 opts["clip"] = string();
3293 string name = normalize_filename(p.verbatim_item());
3295 string const path = getMasterFilePath(true);
3296 // We want to preserve relative / absolute filenames,
3297 // therefore path is only used for testing
3298 if (!makeAbsPath(name, path).exists()) {
3299 // The file extension is probably missing.
3300 // Now try to find it out.
3301 string const dvips_name =
3302 find_file(name, path,
3303 known_dvips_graphics_formats);
3304 string const pdftex_name =
3305 find_file(name, path,
3306 known_pdftex_graphics_formats);
3307 if (!dvips_name.empty()) {
3308 if (!pdftex_name.empty()) {
3309 cerr << "This file contains the "
3311 "\"\\includegraphics{"
3313 "However, files\n\""
3314 << dvips_name << "\" and\n\""
3315 << pdftex_name << "\"\n"
3316 "both exist, so I had to make a "
3317 "choice and took the first one.\n"
3318 "Please move the unwanted one "
3319 "someplace else and try again\n"
3320 "if my choice was wrong."
3324 } else if (!pdftex_name.empty()) {
3330 FileName const absname = makeAbsPath(name, path);
3331 if (absname.exists()) {
3332 fix_child_filename(name);
3333 copy_file(absname, name);
3335 cerr << "Warning: Could not find graphics file '"
3336 << name << "'." << endl;
3338 context.check_layout(os);
3339 begin_inset(os, "Graphics ");
3340 os << "\n\tfilename " << name << '\n';
3341 if (opts.find("width") != opts.end())
3343 << translate_len(opts["width"]) << '\n';
3344 if (opts.find("height") != opts.end())
3346 << translate_len(opts["height"]) << '\n';
3347 if (opts.find("scale") != opts.end()) {
3348 istringstream iss(opts["scale"]);
3352 os << "\tscale " << val << '\n';
3354 if (opts.find("angle") != opts.end()) {
3355 os << "\trotateAngle "
3356 << opts["angle"] << '\n';
3357 vector<string>::const_iterator a =
3358 find(keys.begin(), keys.end(), "angle");
3359 vector<string>::const_iterator s =
3360 find(keys.begin(), keys.end(), "width");
3361 if (s == keys.end())
3362 s = find(keys.begin(), keys.end(), "height");
3363 if (s == keys.end())
3364 s = find(keys.begin(), keys.end(), "scale");
3365 if (s != keys.end() && distance(s, a) > 0)
3366 os << "\tscaleBeforeRotation\n";
3368 if (opts.find("origin") != opts.end()) {
3370 string const opt = opts["origin"];
3371 if (opt.find('l') != string::npos) ss << "left";
3372 if (opt.find('r') != string::npos) ss << "right";
3373 if (opt.find('c') != string::npos) ss << "center";
3374 if (opt.find('t') != string::npos) ss << "Top";
3375 if (opt.find('b') != string::npos) ss << "Bottom";
3376 if (opt.find('B') != string::npos) ss << "Baseline";
3377 if (!ss.str().empty())
3378 os << "\trotateOrigin " << ss.str() << '\n';
3380 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3382 if (opts.find("keepaspectratio") != opts.end())
3383 os << "\tkeepAspectRatio\n";
3384 if (opts.find("clip") != opts.end())
3386 if (opts.find("draft") != opts.end())
3388 if (opts.find("bb") != opts.end())
3389 os << "\tBoundingBox "
3390 << opts["bb"] << '\n';
3391 int numberOfbbOptions = 0;
3392 if (opts.find("bbllx") != opts.end())
3393 numberOfbbOptions++;
3394 if (opts.find("bblly") != opts.end())
3395 numberOfbbOptions++;
3396 if (opts.find("bburx") != opts.end())
3397 numberOfbbOptions++;
3398 if (opts.find("bbury") != opts.end())
3399 numberOfbbOptions++;
3400 if (numberOfbbOptions == 4)
3401 os << "\tBoundingBox "
3402 << opts["bbllx"] << " " << opts["bblly"] << " "
3403 << opts["bburx"] << " " << opts["bbury"] << '\n';
3404 else if (numberOfbbOptions > 0)
3405 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3406 numberOfbbOptions = 0;
3407 if (opts.find("natwidth") != opts.end())
3408 numberOfbbOptions++;
3409 if (opts.find("natheight") != opts.end())
3410 numberOfbbOptions++;
3411 if (numberOfbbOptions == 2)
3412 os << "\tBoundingBox 0bp 0bp "
3413 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3414 else if (numberOfbbOptions > 0)
3415 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3416 ostringstream special;
3417 if (opts.find("hiresbb") != opts.end())
3418 special << "hiresbb,";
3419 if (opts.find("trim") != opts.end())
3421 if (opts.find("viewport") != opts.end())
3422 special << "viewport=" << opts["viewport"] << ',';
3423 if (opts.find("totalheight") != opts.end())
3424 special << "totalheight=" << opts["totalheight"] << ',';
3425 if (opts.find("type") != opts.end())
3426 special << "type=" << opts["type"] << ',';
3427 if (opts.find("ext") != opts.end())
3428 special << "ext=" << opts["ext"] << ',';
3429 if (opts.find("read") != opts.end())
3430 special << "read=" << opts["read"] << ',';
3431 if (opts.find("command") != opts.end())
3432 special << "command=" << opts["command"] << ',';
3433 string s_special = special.str();
3434 if (!s_special.empty()) {
3435 // We had special arguments. Remove the trailing ','.
3436 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3438 // TODO: Handle the unknown settings better.
3439 // Warn about invalid options.
3440 // Check whether some option was given twice.
3442 preamble.registerAutomaticallyLoadedPackage("graphicx");
3446 if (t.cs() == "footnote" ||
3447 (t.cs() == "thanks" && context.layout->intitle)) {
3449 context.check_layout(os);
3450 begin_inset(os, "Foot\n");
3451 os << "status collapsed\n\n";
3452 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3457 if (t.cs() == "marginpar") {
3459 context.check_layout(os);
3460 begin_inset(os, "Marginal\n");
3461 os << "status collapsed\n\n";
3462 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3467 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3468 bool const use_minted = t.cs() == "mintinline";
3470 parse_listings(p, os, context, true, use_minted);
3474 if (t.cs() == "ensuremath") {
3476 context.check_layout(os);
3477 string const s = p.verbatim_item();
3478 //FIXME: this never triggers in UTF8
3479 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3482 output_ert_inset(os, "\\ensuremath{" + s + "}",
3487 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3488 if (preamble.titleLayoutFound()) {
3490 skip_spaces_braces(p);
3492 output_ert_inset(os, t.asInput(), context);
3496 if (t.cs() == "tableofcontents"
3497 || t.cs() == "lstlistoflistings"
3498 || t.cs() == "listoflistings") {
3499 string name = t.cs();
3500 if (preamble.minted() && name == "listoflistings")
3501 name.insert(0, "lst");
3502 context.check_layout(os);
3503 begin_command_inset(os, "toc", name);
3505 skip_spaces_braces(p);
3506 if (name == "lstlistoflistings") {
3507 if (preamble.minted())
3508 preamble.registerAutomaticallyLoadedPackage("minted");
3510 preamble.registerAutomaticallyLoadedPackage("listings");
3515 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3516 context.check_layout(os);
3517 if (t.cs() == "listoffigures")
3518 begin_inset(os, "FloatList figure\n");
3520 begin_inset(os, "FloatList table\n");
3522 skip_spaces_braces(p);
3526 if (t.cs() == "listof") {
3527 p.skip_spaces(true);
3528 string const name = p.get_token().cs();
3529 if (context.textclass.floats().typeExist(name)) {
3530 context.check_layout(os);
3531 begin_inset(os, "FloatList ");
3534 p.get_token(); // swallow second arg
3536 output_ert_inset(os, "\\listof{" + name + "}", context);
3540 if ((where = is_known(t.cs(), known_text_font_families))) {
3541 parse_text_attributes(p, os, FLAG_ITEM, outer,
3542 context, "\\family", context.font.family,
3543 known_coded_font_families[where - known_text_font_families]);
3547 if ((where = is_known(t.cs(), known_text_font_series))) {
3548 parse_text_attributes(p, os, FLAG_ITEM, outer,
3549 context, "\\series", context.font.series,
3550 known_coded_font_series[where - known_text_font_series]);
3554 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3555 parse_text_attributes(p, os, FLAG_ITEM, outer,
3556 context, "\\shape", context.font.shape,
3557 known_coded_font_shapes[where - known_text_font_shapes]);
3561 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3562 context.check_layout(os);
3563 TeXFont oldFont = context.font;
3564 context.font.init();
3565 context.font.size = oldFont.size;
3566 os << "\n\\family " << context.font.family << "\n";
3567 os << "\n\\series " << context.font.series << "\n";
3568 os << "\n\\shape " << context.font.shape << "\n";
3569 if (t.cs() == "textnormal") {
3570 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3571 output_font_change(os, context.font, oldFont);
3572 context.font = oldFont;
3574 eat_whitespace(p, os, context, false);
3578 if (t.cs() == "textcolor") {
3579 // scheme is \textcolor{color name}{text}
3580 string const color = p.verbatim_item();
3581 // we support the predefined colors of the color and the xcolor package
3582 if (color == "black" || color == "blue" || color == "cyan"
3583 || color == "green" || color == "magenta" || color == "red"
3584 || color == "white" || color == "yellow") {
3585 context.check_layout(os);
3586 os << "\n\\color " << color << "\n";
3587 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3588 context.check_layout(os);
3589 os << "\n\\color inherit\n";
3590 preamble.registerAutomaticallyLoadedPackage("color");
3591 } else if (color == "brown" || color == "darkgray" || color == "gray"
3592 || color == "lightgray" || color == "lime" || color == "olive"
3593 || color == "orange" || color == "pink" || color == "purple"
3594 || color == "teal" || color == "violet") {
3595 context.check_layout(os);
3596 os << "\n\\color " << color << "\n";
3597 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3598 context.check_layout(os);
3599 os << "\n\\color inherit\n";
3600 preamble.registerAutomaticallyLoadedPackage("xcolor");
3602 // for custom defined colors
3603 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3607 if (t.cs() == "underbar" || t.cs() == "uline") {
3608 // \underbar is not 100% correct (LyX outputs \uline
3609 // of ulem.sty). The difference is that \ulem allows
3610 // line breaks, and \underbar does not.
3611 // Do NOT handle \underline.
3612 // \underbar cuts through y, g, q, p etc.,
3613 // \underline does not.
3614 context.check_layout(os);
3615 os << "\n\\bar under\n";
3616 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3617 context.check_layout(os);
3618 os << "\n\\bar default\n";
3619 preamble.registerAutomaticallyLoadedPackage("ulem");
3623 if (t.cs() == "sout") {
3624 context.check_layout(os);
3625 os << "\n\\strikeout on\n";
3626 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3627 context.check_layout(os);
3628 os << "\n\\strikeout default\n";
3629 preamble.registerAutomaticallyLoadedPackage("ulem");
3633 if (t.cs() == "uuline" || t.cs() == "uwave"
3634 || t.cs() == "emph" || t.cs() == "noun"
3635 || t.cs() == "xout") {
3636 context.check_layout(os);
3637 os << "\n\\" << t.cs() << " on\n";
3638 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3639 context.check_layout(os);
3640 os << "\n\\" << t.cs() << " default\n";
3641 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3642 preamble.registerAutomaticallyLoadedPackage("ulem");
3646 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3647 context.check_layout(os);
3648 string name = p.getArg('{', '}');
3649 string localtime = p.getArg('{', '}');
3650 preamble.registerAuthor(name);
3651 Author const & author = preamble.getAuthor(name);
3652 // from_asctime_utc() will fail if LyX decides to output the
3653 // time in the text language.
3654 time_t ptime = from_asctime_utc(localtime);
3655 if (ptime == static_cast<time_t>(-1)) {
3656 cerr << "Warning: Could not parse time `" << localtime
3657 << "´ for change tracking, using current time instead.\n";
3658 ptime = current_time();
3660 if (t.cs() == "lyxadded")
3661 os << "\n\\change_inserted ";
3663 os << "\n\\change_deleted ";
3664 os << author.bufferId() << ' ' << ptime << '\n';
3665 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3666 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3667 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3668 LaTeXPackages::isAvailable("xcolor");
3669 // No need to test for luatex, since luatex comes in
3670 // two flavours (dvi and pdf), like latex, and those
3671 // are detected by pdflatex.
3672 if (pdflatex || xetex) {
3674 preamble.registerAutomaticallyLoadedPackage("ulem");
3675 preamble.registerAutomaticallyLoadedPackage("xcolor");
3676 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3680 preamble.registerAutomaticallyLoadedPackage("dvipost");
3681 } else if (xcolorulem) {
3682 preamble.registerAutomaticallyLoadedPackage("ulem");
3683 preamble.registerAutomaticallyLoadedPackage("xcolor");
3689 if (t.cs() == "textipa") {
3690 context.check_layout(os);
3691 begin_inset(os, "IPA\n");
3692 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3693 context.merging_hyphens_allowed = false;
3694 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3695 context.merging_hyphens_allowed = merging_hyphens_allowed;
3697 preamble.registerAutomaticallyLoadedPackage("tipa");
3698 preamble.registerAutomaticallyLoadedPackage("tipx");
3702 if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3703 context.check_layout(os);
3704 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3705 os << "status open\n";
3706 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3712 if (t.cs() == "textvertline") {
3713 // FIXME: This is not correct, \textvertline is higher than |
3719 if (t.cs() == "tone" ) {
3720 context.check_layout(os);
3721 // register the tone package
3722 preamble.registerAutomaticallyLoadedPackage("tone");
3723 string content = trimSpaceAndEol(p.verbatim_item());
3724 string command = t.asInput() + "{" + content + "}";
3725 // some tones can be detected by unicodesymbols, some need special code
3726 if (is_known(content, known_tones)) {
3727 os << "\\IPAChar " << command << "\n";
3730 // try to see whether the string is in unicodesymbols
3734 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3735 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3736 termination, rem, &req);
3740 output_ert_inset(os, to_utf8(rem), context);
3741 for (set<string>::const_iterator it = req.begin();
3742 it != req.end(); ++it)
3743 preamble.registerAutomaticallyLoadedPackage(*it);
3745 // we did not find a non-ert version
3746 output_ert_inset(os, command, context);
3750 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3751 t.cs() == "vphantom") {
3752 context.check_layout(os);
3753 if (t.cs() == "phantom")
3754 begin_inset(os, "Phantom Phantom\n");
3755 if (t.cs() == "hphantom")
3756 begin_inset(os, "Phantom HPhantom\n");
3757 if (t.cs() == "vphantom")
3758 begin_inset(os, "Phantom VPhantom\n");
3759 os << "status open\n";
3760 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3766 if (t.cs() == "href") {
3767 context.check_layout(os);
3768 string target = convert_literate_command_inset_arg(p.verbatim_item());
3769 string name = p.verbatim_item();
3770 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3771 bool const literal = !nm.first;
3772 name = literal ? subst(name, "\n", " ") : nm.second;
3773 string lit = literal ? "\"true\"" : "\"false\"";
3775 size_t i = target.find(':');
3776 if (i != string::npos) {
3777 type = target.substr(0, i + 1);
3778 if (type == "mailto:" || type == "file:")
3779 target = target.substr(i + 1);
3780 // handle the case that name is equal to target, except of "http(s)://"
3781 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3784 begin_command_inset(os, "href", "href");
3786 os << "name \"" << name << "\"\n";
3787 os << "target \"" << target << "\"\n";
3788 if (type == "mailto:" || type == "file:")
3789 os << "type \"" << type << "\"\n";
3790 os << "literal " << lit << "\n";
3792 skip_spaces_braces(p);
3796 if (t.cs() == "lyxline") {
3797 // swallow size argument (it is not used anyway)
3799 if (!context.atParagraphStart()) {
3800 // so our line is in the middle of a paragraph
3801 // we need to add a new line, lest this line
3802 // follow the other content on that line and
3803 // run off the side of the page
3804 // FIXME: This may create an empty paragraph,
3805 // but without that it would not be
3806 // possible to set noindent below.
3807 // Fortunately LaTeX does not care
3808 // about the empty paragraph.
3809 context.new_paragraph(os);
3811 if (preamble.indentParagraphs()) {
3812 // we need to unindent, lest the line be too long
3813 context.add_par_extra_stuff("\\noindent\n");
3815 context.check_layout(os);
3816 begin_command_inset(os, "line", "rule");
3817 os << "offset \"0.5ex\"\n"
3818 "width \"100line%\"\n"
3824 if (t.cs() == "rule") {
3825 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3826 string const width = p.getArg('{', '}');
3827 string const thickness = p.getArg('{', '}');
3828 context.check_layout(os);
3829 begin_command_inset(os, "line", "rule");
3830 if (!offset.empty())
3831 os << "offset \"" << translate_len(offset) << "\"\n";
3832 os << "width \"" << translate_len(width) << "\"\n"
3833 "height \"" << translate_len(thickness) << "\"\n";
3838 // handle refstyle first to catch \eqref which can also occur
3839 // without refstyle. Only recognize these commands if
3840 // refstyle.sty was found in the preamble (otherwise \eqref
3841 // and user defined ref commands could be misdetected).
3842 if ((where = is_known(t.cs(), known_refstyle_commands))
3843 && preamble.refstyle()) {
3844 context.check_layout(os);
3845 begin_command_inset(os, "ref", "formatted");
3846 os << "reference \"";
3847 os << known_refstyle_prefixes[where - known_refstyle_commands]
3849 os << convert_literate_command_inset_arg(p.verbatim_item())
3851 os << "plural \"false\"\n";
3852 os << "caps \"false\"\n";
3853 os << "noprefix \"false\"\n";
3855 preamble.registerAutomaticallyLoadedPackage("refstyle");
3859 // if refstyle is used, we must not convert \prettyref to a
3860 // formatted reference, since that would result in a refstyle command.
3861 if ((where = is_known(t.cs(), known_ref_commands)) &&
3862 (t.cs() != "prettyref" || !preamble.refstyle())) {
3863 string const opt = p.getOpt();
3865 context.check_layout(os);
3866 begin_command_inset(os, "ref",
3867 known_coded_ref_commands[where - known_ref_commands]);
3868 os << "reference \""
3869 << convert_literate_command_inset_arg(p.verbatim_item())
3871 os << "plural \"false\"\n";
3872 os << "caps \"false\"\n";
3873 os << "noprefix \"false\"\n";
3875 if (t.cs() == "vref" || t.cs() == "vpageref")
3876 preamble.registerAutomaticallyLoadedPackage("varioref");
3877 else if (t.cs() == "prettyref")
3878 preamble.registerAutomaticallyLoadedPackage("prettyref");
3880 // LyX does not yet support optional arguments of ref commands
3881 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3882 p.verbatim_item() + '}', context);
3888 is_known(t.cs(), known_natbib_commands) &&
3889 ((t.cs() != "citefullauthor" &&
3890 t.cs() != "citeyear" &&
3891 t.cs() != "citeyearpar") ||
3892 p.next_token().asInput() != "*")) {
3893 context.check_layout(os);
3894 string command = t.cs();
3895 if (p.next_token().asInput() == "*") {
3899 if (command == "citefullauthor")
3900 // alternative name for "\\citeauthor*"
3901 command = "citeauthor*";
3903 // text before the citation
3905 // text after the citation
3907 get_cite_arguments(p, true, before, after);
3909 if (command == "cite") {
3910 // \cite without optional argument means
3911 // \citet, \cite with at least one optional
3912 // argument means \citep.
3913 if (before.empty() && after.empty())
3918 if (before.empty() && after == "[]")
3919 // avoid \citet[]{a}
3921 else if (before == "[]" && after == "[]") {
3922 // avoid \citet[][]{a}
3926 bool literal = false;
3927 pair<bool, string> aft;
3928 pair<bool, string> bef;
3929 // remove the brackets around after and before
3930 if (!after.empty()) {
3932 after.erase(after.length() - 1, 1);
3933 aft = convert_latexed_command_inset_arg(after);
3934 literal = !aft.first;
3935 after = literal ? subst(after, "\n", " ") : aft.second;
3937 if (!before.empty()) {
3939 before.erase(before.length() - 1, 1);
3940 bef = convert_latexed_command_inset_arg(before);
3941 literal |= !bef.first;
3942 before = literal ? subst(before, "\n", " ") : bef.second;
3943 if (literal && !after.empty())
3944 after = subst(after, "\n", " ");
3946 string lit = literal ? "\"true\"" : "\"false\"";
3947 begin_command_inset(os, "citation", command);
3948 os << "after " << '"' << after << '"' << "\n";
3949 os << "before " << '"' << before << '"' << "\n";
3951 << convert_literate_command_inset_arg(p.verbatim_item())
3953 << "literal " << lit << "\n";
3955 // Need to set the cite engine if natbib is loaded by
3956 // the document class directly
3957 if (preamble.citeEngine() == "basic")
3958 preamble.citeEngine("natbib");
3963 && is_known(t.cs(), known_biblatex_commands)
3964 && ((t.cs() == "cite"
3965 || t.cs() == "citeauthor"
3966 || t.cs() == "Citeauthor"
3967 || t.cs() == "parencite"
3968 || t.cs() == "citetitle")
3969 || p.next_token().asInput() != "*"))
3970 || (use_biblatex_natbib
3971 && (is_known(t.cs(), known_biblatex_commands)
3972 || is_known(t.cs(), known_natbib_commands))
3973 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3974 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3975 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3976 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3977 || t.cs() == "parencite" || t.cs() == "citetitle")
3978 || p.next_token().asInput() != "*"))){
3979 context.check_layout(os);
3980 string command = t.cs();
3981 if (p.next_token().asInput() == "*") {
3986 bool const qualified = suffixIs(command, "s");
3988 command = rtrim(command, "s");
3990 // text before the citation
3992 // text after the citation
3994 get_cite_arguments(p, true, before, after, qualified);
3996 // These use natbib cmd names in LyX
3997 // for inter-citeengine compativility
3998 if (command == "citeyear")
3999 command = "citebyear";
4000 else if (command == "cite*")
4001 command = "citeyear";
4002 else if (command == "textcite")
4004 else if (command == "Textcite")
4006 else if (command == "parencite")
4008 else if (command == "Parencite")
4010 else if (command == "parencite*")
4011 command = "citeyearpar";
4012 else if (command == "smartcite")
4013 command = "footcite";
4014 else if (command == "Smartcite")
4015 command = "Footcite";
4017 string const emptyarg = qualified ? "()" : "[]";
4018 if (before.empty() && after == emptyarg)
4021 else if (before == emptyarg && after == emptyarg) {
4022 // avoid \cite[][]{a}
4026 bool literal = false;
4027 pair<bool, string> aft;
4028 pair<bool, string> bef;
4029 // remove the brackets around after and before
4030 if (!after.empty()) {
4032 after.erase(after.length() - 1, 1);
4033 aft = convert_latexed_command_inset_arg(after);
4034 literal = !aft.first;
4035 after = literal ? subst(after, "\n", " ") : aft.second;
4037 if (!before.empty()) {
4039 before.erase(before.length() - 1, 1);
4040 bef = convert_latexed_command_inset_arg(before);
4041 literal |= !bef.first;
4042 before = literal ? subst(before, "\n", " ") : bef.second;
4044 string keys, pretextlist, posttextlist;
4046 map<string, string> pres, posts, preslit, postslit;
4047 vector<string> lkeys;
4048 // text before the citation
4049 string lbefore, lbeforelit;
4050 // text after the citation
4051 string lafter, lafterlit;
4053 pair<bool, string> laft, lbef;
4055 get_cite_arguments(p, true, lbefore, lafter);
4056 // remove the brackets around after and before
4057 if (!lafter.empty()) {
4059 lafter.erase(lafter.length() - 1, 1);
4060 laft = convert_latexed_command_inset_arg(lafter);
4061 literal |= !laft.first;
4062 lafter = laft.second;
4063 lafterlit = subst(lbefore, "\n", " ");
4065 if (!lbefore.empty()) {
4066 lbefore.erase(0, 1);
4067 lbefore.erase(lbefore.length() - 1, 1);
4068 lbef = convert_latexed_command_inset_arg(lbefore);
4069 literal |= !lbef.first;
4070 lbefore = lbef.second;
4071 lbeforelit = subst(lbefore, "\n", " ");
4073 if (lbefore.empty() && lafter == "[]") {
4078 else if (lbefore == "[]" && lafter == "[]") {
4079 // avoid \cite[][]{a}
4085 lkey = p.getArg('{', '}');
4088 if (!lbefore.empty()) {
4089 pres.insert(make_pair(lkey, lbefore));
4090 preslit.insert(make_pair(lkey, lbeforelit));
4092 if (!lafter.empty()) {
4093 posts.insert(make_pair(lkey, lafter));
4094 postslit.insert(make_pair(lkey, lafterlit));
4096 lkeys.push_back(lkey);
4098 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4103 for (auto const & ptl : pres) {
4104 if (!pretextlist.empty())
4105 pretextlist += '\t';
4106 pretextlist += ptl.first + " " + ptl.second;
4108 for (auto const & potl : posts) {
4109 if (!posttextlist.empty())
4110 posttextlist += '\t';
4111 posttextlist += potl.first + " " + potl.second;
4114 keys = convert_literate_command_inset_arg(p.verbatim_item());
4117 after = subst(after, "\n", " ");
4118 if (!before.empty())
4119 before = subst(after, "\n", " ");
4121 string lit = literal ? "\"true\"" : "\"false\"";
4122 begin_command_inset(os, "citation", command);
4123 os << "after " << '"' << after << '"' << "\n";
4124 os << "before " << '"' << before << '"' << "\n";
4128 if (!pretextlist.empty())
4129 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4130 if (!posttextlist.empty())
4131 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4132 os << "literal " << lit << "\n";
4134 // Need to set the cite engine if biblatex is loaded by
4135 // the document class directly
4136 if (preamble.citeEngine() == "basic")
4137 use_biblatex_natbib ?
4138 preamble.citeEngine("biblatex-natbib")
4139 : preamble.citeEngine("biblatex");
4144 is_known(t.cs(), known_jurabib_commands) &&
4145 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4146 context.check_layout(os);
4147 string command = t.cs();
4148 if (p.next_token().asInput() == "*") {
4152 char argumentOrder = '\0';
4153 vector<string> const options =
4154 preamble.getPackageOptions("jurabib");
4155 if (find(options.begin(), options.end(),
4156 "natbiborder") != options.end())
4157 argumentOrder = 'n';
4158 else if (find(options.begin(), options.end(),
4159 "jurabiborder") != options.end())
4160 argumentOrder = 'j';
4162 // text before the citation
4164 // text after the citation
4166 get_cite_arguments(p, argumentOrder != 'j', before, after);
4168 string const citation = p.verbatim_item();
4169 if (!before.empty() && argumentOrder == '\0') {
4170 cerr << "Warning: Assuming argument order "
4171 "of jurabib version 0.6 for\n'"
4172 << command << before << after << '{'
4173 << citation << "}'.\n"
4174 "Add 'jurabiborder' to the jurabib "
4175 "package options if you used an\n"
4176 "earlier jurabib version." << endl;
4178 bool literal = false;
4179 pair<bool, string> aft;
4180 pair<bool, string> bef;
4181 // remove the brackets around after and before
4182 if (!after.empty()) {
4184 after.erase(after.length() - 1, 1);
4185 aft = convert_latexed_command_inset_arg(after);
4186 literal = !aft.first;
4187 after = literal ? subst(after, "\n", " ") : aft.second;
4189 if (!before.empty()) {
4191 before.erase(before.length() - 1, 1);
4192 bef = convert_latexed_command_inset_arg(before);
4193 literal |= !bef.first;
4194 before = literal ? subst(before, "\n", " ") : bef.second;
4195 if (literal && !after.empty())
4196 after = subst(after, "\n", " ");
4198 string lit = literal ? "\"true\"" : "\"false\"";
4199 begin_command_inset(os, "citation", command);
4200 os << "after " << '"' << after << "\"\n"
4201 << "before " << '"' << before << "\"\n"
4202 << "key " << '"' << citation << "\"\n"
4203 << "literal " << lit << "\n";
4205 // Need to set the cite engine if jurabib is loaded by
4206 // the document class directly
4207 if (preamble.citeEngine() == "basic")
4208 preamble.citeEngine("jurabib");
4212 if (t.cs() == "cite"
4213 || t.cs() == "nocite") {
4214 context.check_layout(os);
4215 string after = p.getArg('[', ']');
4216 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4217 bool const literal = !aft.first;
4218 after = literal ? subst(after, "\n", " ") : aft.second;
4219 string lit = literal ? "\"true\"" : "\"false\"";
4220 string key = convert_literate_command_inset_arg(p.verbatim_item());
4221 // store the case that it is "\nocite{*}" to use it later for
4224 begin_command_inset(os, "citation", t.cs());
4225 os << "after " << '"' << after << "\"\n"
4226 << "key " << '"' << key << "\"\n"
4227 << "literal " << lit << "\n";
4229 } else if (t.cs() == "nocite")
4234 if (t.cs() == "index" ||
4235 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4236 context.check_layout(os);
4237 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4238 p.getArg('[', ']') : "";
4239 string const kind = arg.empty() ? "idx" : arg;
4240 begin_inset(os, "Index ");
4241 os << kind << "\nstatus collapsed\n";
4242 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4245 preamble.registerAutomaticallyLoadedPackage("splitidx");
4249 if (t.cs() == "nomenclature") {
4250 context.check_layout(os);
4251 begin_command_inset(os, "nomenclature", "nomenclature");
4252 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4253 if (!prefix.empty())
4254 os << "prefix " << '"' << prefix << '"' << "\n";
4255 string symbol = p.verbatim_item();
4256 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4257 bool literal = !sym.first;
4258 string description = p.verbatim_item();
4259 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4260 literal |= !desc.first;
4262 symbol = subst(symbol, "\n", " ");
4263 description = subst(description, "\n", " ");
4265 symbol = sym.second;
4266 description = desc.second;
4268 string lit = literal ? "\"true\"" : "\"false\"";
4269 os << "symbol " << '"' << symbol;
4270 os << "\"\ndescription \""
4271 << description << "\"\n"
4272 << "literal " << lit << "\n";
4274 preamble.registerAutomaticallyLoadedPackage("nomencl");
4278 if (t.cs() == "label") {
4279 context.check_layout(os);
4280 begin_command_inset(os, "label", "label");
4282 << convert_literate_command_inset_arg(p.verbatim_item())
4288 if (t.cs() == "lyxmintcaption") {
4289 string const pos = p.getArg('[', ']');
4291 string const caption =
4292 parse_text_snippet(p, FLAG_ITEM, false,
4294 minted_nonfloat_caption = "[t]" + caption;
4296 // We already got the caption at the bottom,
4297 // so simply skip it.
4298 parse_text_snippet(p, FLAG_ITEM, false, context);
4303 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4304 context.check_layout(os);
4305 string commandname = t.cs();
4307 if (p.next_token().asInput() == "*") {
4312 begin_command_inset(os, "index_print", commandname);
4313 string const indexname = p.getArg('[', ']');
4315 if (indexname.empty())
4316 os << "type \"idx\"\n";
4318 os << "type \"" << indexname << "\"\n";
4319 os << "literal \"true\"\n";
4322 skip_spaces_braces(p);
4323 preamble.registerAutomaticallyLoadedPackage("makeidx");
4324 if (preamble.use_indices() == "true")
4325 preamble.registerAutomaticallyLoadedPackage("splitidx");
4329 if (t.cs() == "printnomenclature") {
4331 string width_type = "";
4332 context.check_layout(os);
4333 begin_command_inset(os, "nomencl_print", "printnomenclature");
4334 // case of a custom width
4336 width = p.getArg('[', ']');
4337 width = translate_len(width);
4338 width_type = "custom";
4340 // case of no custom width
4341 // the case of no custom width but the width set
4342 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4343 // because the user could have set anything, not only the width
4344 // of the longest label (which would be width_type = "auto")
4345 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4346 if (label.empty() && width_type.empty())
4347 width_type = "none";
4348 os << "set_width \"" << width_type << "\"\n";
4349 if (width_type == "custom")
4350 os << "width \"" << width << '\"';
4352 skip_spaces_braces(p);
4353 preamble.registerAutomaticallyLoadedPackage("nomencl");
4357 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4358 context.check_layout(os);
4359 begin_inset(os, "script ");
4360 os << t.cs().substr(4) << '\n';
4361 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4362 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4364 if (t.cs() == "textsubscript")
4365 preamble.registerAutomaticallyLoadedPackage("subscript");
4369 if ((where = is_known(t.cs(), known_quotes))) {
4370 context.check_layout(os);
4371 begin_inset(os, "Quotes ");
4372 os << known_coded_quotes[where - known_quotes];
4374 // LyX adds {} after the quote, so we have to eat
4375 // spaces here if there are any before a possible
4377 eat_whitespace(p, os, context, false);
4382 if ((where = is_known(t.cs(), known_sizes)) &&
4383 context.new_layout_allowed) {
4384 context.check_layout(os);
4385 TeXFont const oldFont = context.font;
4386 context.font.size = known_coded_sizes[where - known_sizes];
4387 output_font_change(os, oldFont, context.font);
4388 eat_whitespace(p, os, context, false);
4392 if ((where = is_known(t.cs(), known_font_families)) &&
4393 context.new_layout_allowed) {
4394 context.check_layout(os);
4395 TeXFont const oldFont = context.font;
4396 context.font.family =
4397 known_coded_font_families[where - known_font_families];
4398 output_font_change(os, oldFont, context.font);
4399 eat_whitespace(p, os, context, false);
4403 if ((where = is_known(t.cs(), known_font_series)) &&
4404 context.new_layout_allowed) {
4405 context.check_layout(os);
4406 TeXFont const oldFont = context.font;
4407 context.font.series =
4408 known_coded_font_series[where - known_font_series];
4409 output_font_change(os, oldFont, context.font);
4410 eat_whitespace(p, os, context, false);
4414 if ((where = is_known(t.cs(), known_font_shapes)) &&
4415 context.new_layout_allowed) {
4416 context.check_layout(os);
4417 TeXFont const oldFont = context.font;
4418 context.font.shape =
4419 known_coded_font_shapes[where - known_font_shapes];
4420 output_font_change(os, oldFont, context.font);
4421 eat_whitespace(p, os, context, false);
4424 if ((where = is_known(t.cs(), known_old_font_families)) &&
4425 context.new_layout_allowed) {
4426 context.check_layout(os);
4427 TeXFont const oldFont = context.font;
4428 context.font.init();
4429 context.font.size = oldFont.size;
4430 context.font.family =
4431 known_coded_font_families[where - known_old_font_families];
4432 output_font_change(os, oldFont, context.font);
4433 eat_whitespace(p, os, context, false);
4437 if ((where = is_known(t.cs(), known_old_font_series)) &&
4438 context.new_layout_allowed) {
4439 context.check_layout(os);
4440 TeXFont const oldFont = context.font;
4441 context.font.init();
4442 context.font.size = oldFont.size;
4443 context.font.series =
4444 known_coded_font_series[where - known_old_font_series];
4445 output_font_change(os, oldFont, context.font);
4446 eat_whitespace(p, os, context, false);
4450 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4451 context.new_layout_allowed) {
4452 context.check_layout(os);
4453 TeXFont const oldFont = context.font;
4454 context.font.init();
4455 context.font.size = oldFont.size;
4456 context.font.shape =
4457 known_coded_font_shapes[where - known_old_font_shapes];
4458 output_font_change(os, oldFont, context.font);
4459 eat_whitespace(p, os, context, false);
4463 if (t.cs() == "selectlanguage") {
4464 context.check_layout(os);
4465 // save the language for the case that a
4466 // \foreignlanguage is used
4467 context.font.language = babel2lyx(p.verbatim_item());
4468 os << "\n\\lang " << context.font.language << "\n";
4472 if (t.cs() == "foreignlanguage") {
4473 string const lang = babel2lyx(p.verbatim_item());
4474 parse_text_attributes(p, os, FLAG_ITEM, outer,
4476 context.font.language, lang);
4480 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4481 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4482 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4484 // We have to output the whole command if it has an option
4485 // because LyX doesn't support this yet, see bug #8214,
4486 // only if there is a single option specifying a variant, we can handle it.
4488 string langopts = p.getOpt();
4489 // check if the option contains a variant, if yes, extract it
4490 string::size_type pos_var = langopts.find("variant");
4491 string::size_type i = langopts.find(',');
4492 string::size_type k = langopts.find('=', pos_var);
4493 if (pos_var != string::npos && i == string::npos) {
4495 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4496 lang = preamble.polyglossia2lyx(variant);
4497 parse_text_attributes(p, os, FLAG_ITEM, outer,
4499 context.font.language, lang);
4501 output_ert_inset(os, t.asInput() + langopts, context);
4503 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4504 parse_text_attributes(p, os, FLAG_ITEM, outer,
4506 context.font.language, lang);
4511 if (t.cs() == "inputencoding") {
4512 // nothing to write here
4513 string const enc = subst(p.verbatim_item(), "\n", " ");
4514 p.setEncoding(enc, Encoding::inputenc);
4518 if (is_known(t.cs(), known_special_chars) ||
4519 (t.cs() == "protect" &&
4520 p.next_token().cat() == catEscape &&
4521 is_known(p.next_token().cs(), known_special_protect_chars))) {
4522 // LyX sometimes puts a \protect in front, so we have to ignore it
4524 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4525 known_special_chars);
4526 context.check_layout(os);
4527 os << known_coded_special_chars[where - known_special_chars];
4528 skip_spaces_braces(p);
4532 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4533 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4534 p.next_next_token().asInput() == "-") ||
4535 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4536 // LyX sometimes puts a \protect in front, so we have to ignore it
4537 if (t.cs() == "protect")
4539 context.check_layout(os);
4540 if (t.cs() == "nobreakdash")
4541 os << "\\SpecialChar nobreakdash\n";
4543 os << "\\SpecialChar endofsentence\n";
4548 if (t.cs() == "textquotedbl") {
4549 context.check_layout(os);
4555 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4556 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4557 || t.cs() == "%" || t.cs() == "-") {
4558 context.check_layout(os);
4560 os << "\\SpecialChar softhyphen\n";
4566 if (t.cs() == "char") {
4567 context.check_layout(os);
4568 if (p.next_token().character() == '`') {
4570 if (p.next_token().cs() == "\"") {
4575 output_ert_inset(os, "\\char`", context);
4578 output_ert_inset(os, "\\char", context);
4583 if (t.cs() == "verb") {
4584 context.check_layout(os);
4585 // set catcodes to verbatim early, just in case.
4586 p.setCatcodes(VERBATIM_CATCODES);
4587 string delim = p.get_token().asInput();
4588 Parser::Arg arg = p.verbatimStuff(delim);
4590 output_ert_inset(os, "\\verb" + delim
4591 + arg.second + delim, context);
4593 cerr << "invalid \\verb command. Skipping" << endl;
4597 // Problem: \= creates a tabstop inside the tabbing environment
4598 // and else an accent. In the latter case we really would want
4599 // \={o} instead of \= o.
4600 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4601 output_ert_inset(os, t.asInput(), context);
4605 if (t.cs() == "\\") {
4606 context.check_layout(os);
4608 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4609 else if (p.next_token().asInput() == "*") {
4611 // getOpt() eats the following space if there
4612 // is no optional argument, but that is OK
4613 // here since it has no effect in the output.
4614 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4617 begin_inset(os, "Newline newline");
4623 if (t.cs() == "newline" ||
4624 (t.cs() == "linebreak" && !p.hasOpt())) {
4625 context.check_layout(os);
4626 begin_inset(os, "Newline ");
4629 skip_spaces_braces(p);
4633 if (t.cs() == "input" || t.cs() == "include"
4634 || t.cs() == "verbatiminput") {
4635 string name = t.cs();
4636 if (t.cs() == "verbatiminput"
4637 && p.next_token().asInput() == "*")
4638 name += p.get_token().asInput();
4639 context.check_layout(os);
4640 string filename(normalize_filename(p.getArg('{', '}')));
4641 string const path = getMasterFilePath(true);
4642 // We want to preserve relative / absolute filenames,
4643 // therefore path is only used for testing
4644 if ((t.cs() == "include" || t.cs() == "input") &&
4645 !makeAbsPath(filename, path).exists()) {
4646 // The file extension is probably missing.
4647 // Now try to find it out.
4648 string const tex_name =
4649 find_file(filename, path,
4650 known_tex_extensions);
4651 if (!tex_name.empty())
4652 filename = tex_name;
4654 bool external = false;
4656 if (makeAbsPath(filename, path).exists()) {
4657 string const abstexname =
4658 makeAbsPath(filename, path).absFileName();
4659 string const absfigname =
4660 changeExtension(abstexname, ".fig");
4661 fix_child_filename(filename);
4662 string const lyxname = changeExtension(filename,
4663 roundtripMode() ? ".lyx.lyx" : ".lyx");
4664 string const abslyxname = makeAbsPath(
4665 lyxname, getParentFilePath(false)).absFileName();
4667 if (!skipChildren())
4668 external = FileName(absfigname).exists();
4669 if (t.cs() == "input" && !skipChildren()) {
4670 string const ext = getExtension(abstexname);
4672 // Combined PS/LaTeX:
4673 // x.eps, x.pstex_t (old xfig)
4674 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4675 FileName const absepsname(
4676 changeExtension(abstexname, ".eps"));
4677 FileName const abspstexname(
4678 changeExtension(abstexname, ".pstex"));
4679 bool const xfigeps =
4680 (absepsname.exists() ||
4681 abspstexname.exists()) &&
4684 // Combined PDF/LaTeX:
4685 // x.pdf, x.pdftex_t (old xfig)
4686 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4687 FileName const abspdfname(
4688 changeExtension(abstexname, ".pdf"));
4689 bool const xfigpdf =
4690 abspdfname.exists() &&
4691 (ext == "pdftex_t" || ext == "pdf_t");
4695 // Combined PS/PDF/LaTeX:
4696 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4697 string const absbase2(
4698 removeExtension(abstexname) + "_pspdftex");
4699 FileName const abseps2name(
4700 addExtension(absbase2, ".eps"));
4701 FileName const abspdf2name(
4702 addExtension(absbase2, ".pdf"));
4703 bool const xfigboth =
4704 abspdf2name.exists() &&
4705 abseps2name.exists() && ext == "pspdftex";
4707 xfig = xfigpdf || xfigeps || xfigboth;
4708 external = external && xfig;
4711 outname = changeExtension(filename, ".fig");
4712 FileName abssrc(changeExtension(abstexname, ".fig"));
4713 copy_file(abssrc, outname);
4715 // Don't try to convert, the result
4716 // would be full of ERT.
4718 FileName abssrc(abstexname);
4719 copy_file(abssrc, outname);
4720 } else if (t.cs() != "verbatiminput" &&
4722 tex2lyx(abstexname, FileName(abslyxname),
4725 // no need to call copy_file
4726 // tex2lyx creates the file
4729 FileName abssrc(abstexname);
4730 copy_file(abssrc, outname);
4733 cerr << "Warning: Could not find included file '"
4734 << filename << "'." << endl;
4738 begin_inset(os, "External\n");
4739 os << "\ttemplate XFig\n"
4740 << "\tfilename " << outname << '\n';
4741 registerExternalTemplatePackages("XFig");
4743 begin_command_inset(os, "include", name);
4744 outname = subst(outname, "\"", "\\\"");
4745 os << "preview false\n"
4746 "filename \"" << outname << "\"\n";
4747 if (t.cs() == "verbatiminput")
4748 preamble.registerAutomaticallyLoadedPackage("verbatim");
4754 if (t.cs() == "bibliographystyle") {
4755 // store new bibliographystyle
4756 bibliographystyle = p.verbatim_item();
4757 // If any other command than \bibliography, \addcontentsline
4758 // and \nocite{*} follows, we need to output the style
4759 // (because it might be used by that command).
4760 // Otherwise, it will automatically be output by LyX.
4763 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4764 if (t2.cat() == catBegin)
4766 if (t2.cat() != catEscape)
4768 if (t2.cs() == "nocite") {
4769 if (p.getArg('{', '}') == "*")
4771 } else if (t2.cs() == "bibliography")
4773 else if (t2.cs() == "phantomsection") {
4777 else if (t2.cs() == "addcontentsline") {
4778 // get the 3 arguments of \addcontentsline
4781 contentslineContent = p.getArg('{', '}');
4782 // if the last argument is not \refname we must output
4783 if (contentslineContent == "\\refname")
4790 output_ert_inset(os,
4791 "\\bibliographystyle{" + bibliographystyle + '}',
4797 if (t.cs() == "phantomsection") {
4798 // we only support this if it occurs between
4799 // \bibliographystyle and \bibliography
4800 if (bibliographystyle.empty())
4801 output_ert_inset(os, "\\phantomsection", context);
4805 if (t.cs() == "addcontentsline") {
4806 context.check_layout(os);
4807 // get the 3 arguments of \addcontentsline
4808 string const one = p.getArg('{', '}');
4809 string const two = p.getArg('{', '}');
4810 string const three = p.getArg('{', '}');
4811 // only if it is a \refname, we support if for the bibtex inset
4812 if (contentslineContent != "\\refname") {
4813 output_ert_inset(os,
4814 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4820 else if (t.cs() == "bibliography") {
4821 context.check_layout(os);
4823 begin_command_inset(os, "bibtex", "bibtex");
4824 if (!btprint.empty()) {
4825 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4826 // clear the string because the next BibTeX inset can be without the
4827 // \nocite{*} option
4830 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4831 // Do we have addcontentsline?
4832 if (contentslineContent == "\\refname") {
4833 BibOpts = "bibtotoc";
4834 // clear string because next BibTeX inset can be without addcontentsline
4835 contentslineContent.clear();
4837 // Do we have a bibliographystyle set?
4838 if (!bibliographystyle.empty()) {
4839 if (BibOpts.empty())
4840 BibOpts = normalize_filename(bibliographystyle);
4842 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4843 // clear it because each bibtex entry has its style
4844 // and we need an empty string to handle \phantomsection
4845 bibliographystyle.clear();
4847 os << "options " << '"' << BibOpts << '"' << "\n";
4852 if (t.cs() == "printbibliography") {
4853 context.check_layout(os);
4855 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4856 vector<string> opts = getVectorFromString(bbloptions);
4857 vector<string>::iterator it =
4858 find(opts.begin(), opts.end(), "heading=bibintoc");
4859 if (it != opts.end()) {
4861 BibOpts = "bibtotoc";
4863 bbloptions = getStringFromVector(opts);
4864 begin_command_inset(os, "bibtex", "bibtex");
4865 if (!btprint.empty()) {
4866 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4867 // clear the string because the next BibTeX inset can be without the
4868 // \nocite{*} option
4872 for (auto const & bf : preamble.biblatex_bibliographies) {
4873 if (!bibfiles.empty())
4875 bibfiles += normalize_filename(bf);
4877 if (!bibfiles.empty())
4878 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4879 // Do we have addcontentsline?
4880 if (contentslineContent == "\\refname") {
4881 BibOpts = "bibtotoc";
4882 // clear string because next BibTeX inset can be without addcontentsline
4883 contentslineContent.clear();
4885 os << "options " << '"' << BibOpts << '"' << "\n";
4886 if (!bbloptions.empty())
4887 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4889 need_commentbib = false;
4893 if (t.cs() == "bibbysection") {
4894 context.check_layout(os);
4896 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4897 vector<string> opts = getVectorFromString(bbloptions);
4898 vector<string>::iterator it =
4899 find(opts.begin(), opts.end(), "heading=bibintoc");
4900 if (it != opts.end()) {
4902 BibOpts = "bibtotoc";
4904 bbloptions = getStringFromVector(opts);
4905 begin_command_inset(os, "bibtex", "bibtex");
4906 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4908 for (auto const & bf : preamble.biblatex_bibliographies) {
4909 if (!bibfiles.empty())
4911 bibfiles += normalize_filename(bf);
4913 if (!bibfiles.empty())
4914 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4915 os << "options " << '"' << BibOpts << '"' << "\n";
4916 if (!bbloptions.empty())
4917 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4919 need_commentbib = false;
4923 if (t.cs() == "parbox") {
4924 // Test whether this is an outer box of a shaded box
4926 // swallow arguments
4927 while (p.hasOpt()) {
4929 p.skip_spaces(true);
4932 p.skip_spaces(true);
4934 if (p.next_token().cat() == catBegin)
4936 p.skip_spaces(true);
4937 Token to = p.get_token();
4938 bool shaded = false;
4939 if (to.asInput() == "\\begin") {
4940 p.skip_spaces(true);
4941 if (p.getArg('{', '}') == "shaded")
4946 parse_outer_box(p, os, FLAG_ITEM, outer,
4947 context, "parbox", "shaded");
4949 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4950 "", "", t.cs(), "", "");
4954 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4955 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4956 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4957 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4961 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4962 string backgroundcolor;
4963 preamble.registerAutomaticallyLoadedPackage("xcolor");
4964 if (t.cs() == "fcolorbox") {
4965 string const framecolor = p.getArg('{', '}');
4966 backgroundcolor = p.getArg('{', '}');
4967 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4969 backgroundcolor = p.getArg('{', '}');
4970 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4975 // FIXME: due to the compiler limit of "if" nestings
4976 // the code for the alignment was put here
4977 // put them in their own if if this is fixed
4978 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4979 || t.cs() == "shadowsize"
4980 || t.cs() == "raggedleft" || t.cs() == "centering"
4981 || t.cs() == "raggedright") {
4982 if (t.cs() == "fboxrule")
4984 if (t.cs() == "fboxsep")
4986 if (t.cs() == "shadowsize")
4988 if (t.cs() != "raggedleft" && t.cs() != "centering"
4989 && t.cs() != "raggedright") {
4990 p.skip_spaces(true);
4991 while (p.good() && p.next_token().cat() != catSpace
4992 && p.next_token().cat() != catNewline
4993 && p.next_token().cat() != catEscape) {
4994 if (t.cs() == "fboxrule")
4995 fboxrule = fboxrule + p.get_token().asInput();
4996 if (t.cs() == "fboxsep")
4997 fboxsep = fboxsep + p.get_token().asInput();
4998 if (t.cs() == "shadowsize")
4999 shadow_size = shadow_size + p.get_token().asInput();
5002 output_ert_inset(os, t.asInput(), context);
5007 //\framebox() is part of the picture environment and different from \framebox{}
5008 //\framebox{} will be parsed by parse_outer_box
5009 if (t.cs() == "framebox") {
5010 if (p.next_token().character() == '(') {
5011 //the syntax is: \framebox(x,y)[position]{content}
5012 string arg = t.asInput();
5013 arg += p.getFullParentheseArg();
5014 arg += p.getFullOpt();
5015 eat_whitespace(p, os, context, false);
5016 output_ert_inset(os, arg + '{', context);
5017 parse_text(p, os, FLAG_ITEM, outer, context);
5018 output_ert_inset(os, "}", context);
5020 //the syntax is: \framebox[width][position]{content}
5021 string special = p.getFullOpt();
5022 special += p.getOpt();
5023 parse_outer_box(p, os, FLAG_ITEM, outer,
5024 context, t.cs(), special);
5029 //\makebox() is part of the picture environment and different from \makebox{}
5030 //\makebox{} will be parsed by parse_box
5031 if (t.cs() == "makebox") {
5032 if (p.next_token().character() == '(') {
5033 //the syntax is: \makebox(x,y)[position]{content}
5034 string arg = t.asInput();
5035 arg += p.getFullParentheseArg();
5036 arg += p.getFullOpt();
5037 eat_whitespace(p, os, context, false);
5038 output_ert_inset(os, arg + '{', context);
5039 parse_text(p, os, FLAG_ITEM, outer, context);
5040 output_ert_inset(os, "}", context);
5042 //the syntax is: \makebox[width][position]{content}
5043 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5044 "", "", t.cs(), "", "");
5048 if (t.cs() == "smallskip" ||
5049 t.cs() == "medskip" ||
5050 t.cs() == "bigskip" ||
5051 t.cs() == "vfill") {
5052 context.check_layout(os);
5053 begin_inset(os, "VSpace ");
5056 skip_spaces_braces(p);
5060 if ((where = is_known(t.cs(), known_spaces))) {
5061 context.check_layout(os);
5062 begin_inset(os, "space ");
5063 os << '\\' << known_coded_spaces[where - known_spaces]
5066 // LaTeX swallows whitespace after all spaces except
5067 // "\\,". We have to do that here, too, because LyX
5068 // adds "{}" which would make the spaces significant.
5070 eat_whitespace(p, os, context, false);
5071 // LyX adds "{}" after all spaces except "\\ " and
5072 // "\\,", so we have to remove "{}".
5073 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5074 // remove the braces after "\\,", too.
5080 if (t.cs() == "newpage" ||
5081 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5082 t.cs() == "clearpage" ||
5083 t.cs() == "cleardoublepage") {
5084 context.check_layout(os);
5085 begin_inset(os, "Newpage ");
5088 skip_spaces_braces(p);
5092 if (t.cs() == "DeclareRobustCommand" ||
5093 t.cs() == "DeclareRobustCommandx" ||
5094 t.cs() == "newcommand" ||
5095 t.cs() == "newcommandx" ||
5096 t.cs() == "providecommand" ||
5097 t.cs() == "providecommandx" ||
5098 t.cs() == "renewcommand" ||
5099 t.cs() == "renewcommandx") {
5100 // DeclareRobustCommand, DeclareRobustCommandx,
5101 // providecommand and providecommandx could be handled
5102 // by parse_command(), but we need to call
5103 // add_known_command() here.
5104 string name = t.asInput();
5105 if (p.next_token().asInput() == "*") {
5106 // Starred form. Eat '*'
5110 string const command = p.verbatim_item();
5111 string const opt1 = p.getFullOpt();
5112 string const opt2 = p.getFullOpt();
5113 add_known_command(command, opt1, !opt2.empty());
5114 string const ert = name + '{' + command + '}' +
5116 '{' + p.verbatim_item() + '}';
5118 if (t.cs() == "DeclareRobustCommand" ||
5119 t.cs() == "DeclareRobustCommandx" ||
5120 t.cs() == "providecommand" ||
5121 t.cs() == "providecommandx" ||
5122 name[name.length()-1] == '*')
5123 output_ert_inset(os, ert, context);
5125 context.check_layout(os);
5126 begin_inset(os, "FormulaMacro");
5133 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5134 // let could be handled by parse_command(),
5135 // but we need to call add_known_command() here.
5136 string ert = t.asInput();
5139 if (p.next_token().cat() == catBegin) {
5140 name = p.verbatim_item();
5141 ert += '{' + name + '}';
5143 name = p.verbatim_item();
5148 if (p.next_token().cat() == catBegin) {
5149 command = p.verbatim_item();
5150 ert += '{' + command + '}';
5152 command = p.verbatim_item();
5155 // If command is known, make name known too, to parse
5156 // its arguments correctly. For this reason we also
5157 // have commands in syntax.default that are hardcoded.
5158 CommandMap::iterator it = known_commands.find(command);
5159 if (it != known_commands.end())
5160 known_commands[t.asInput()] = it->second;
5161 output_ert_inset(os, ert, context);
5165 if (t.cs() == "hspace" || t.cs() == "vspace") {
5168 string name = t.asInput();
5169 string const length = p.verbatim_item();
5172 bool valid = splitLatexLength(length, valstring, unit);
5173 bool known_hspace = false;
5174 bool known_vspace = false;
5175 bool known_unit = false;
5178 istringstream iss(valstring);
5181 if (t.cs()[0] == 'h') {
5182 if (unit == "\\fill") {
5187 known_hspace = true;
5190 if (unit == "\\smallskipamount") {
5192 known_vspace = true;
5193 } else if (unit == "\\medskipamount") {
5195 known_vspace = true;
5196 } else if (unit == "\\bigskipamount") {
5198 known_vspace = true;
5199 } else if (unit == "\\fill") {
5201 known_vspace = true;
5205 if (!known_hspace && !known_vspace) {
5206 switch (unitFromString(unit)) {
5222 //unitFromString(unit) fails for relative units like Length::PCW
5223 // therefore handle them separately
5224 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5225 || unit == "\\textwidth" || unit == "\\linewidth"
5226 || unit == "\\textheight" || unit == "\\paperheight"
5227 || unit == "\\baselineskip")
5235 // check for glue lengths
5236 bool is_gluelength = false;
5237 string gluelength = length;
5238 string::size_type i = length.find(" minus");
5239 if (i == string::npos) {
5240 i = length.find(" plus");
5241 if (i != string::npos)
5242 is_gluelength = true;
5244 is_gluelength = true;
5245 // if yes transform "9xx minus 8yy plus 7zz"
5247 if (is_gluelength) {
5248 i = gluelength.find(" minus");
5249 if (i != string::npos)
5250 gluelength.replace(i, 7, "-");
5251 i = gluelength.find(" plus");
5252 if (i != string::npos)
5253 gluelength.replace(i, 6, "+");
5256 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5257 // Literal horizontal length or known variable
5258 context.check_layout(os);
5259 begin_inset(os, "space ");
5267 if (known_unit && !known_hspace)
5268 os << "\n\\length " << translate_len(length);
5270 os << "\n\\length " << gluelength;
5272 } else if (known_unit || known_vspace || is_gluelength) {
5273 // Literal vertical length or known variable
5274 context.check_layout(os);
5275 begin_inset(os, "VSpace ");
5278 if (known_unit && !known_vspace)
5279 os << translate_len(length);
5286 // LyX can't handle other length variables in Inset VSpace/space
5291 output_ert_inset(os, name + '{' + unit + '}', context);
5292 else if (value == -1.0)
5293 output_ert_inset(os, name + "{-" + unit + '}', context);
5295 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5297 output_ert_inset(os, name + '{' + length + '}', context);
5302 // The single '=' is meant here.
5303 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5307 context.check_layout(os);
5308 docstring name = newinsetlayout->name();
5309 bool const caption = name.find(from_ascii("Caption:")) == 0;
5311 // Already done for floating minted listings.
5312 if (minted_float.empty()) {
5313 begin_inset(os, "Caption ");
5314 os << to_utf8(name.substr(8)) << '\n';
5317 // FIXME: what do we do if the prefix is not Flex: ?
5318 if (prefixIs(name, from_ascii("Flex:")))
5320 begin_inset(os, "Flex ");
5321 os << to_utf8(name) << '\n'
5322 << "status collapsed\n";
5324 if (!minted_float.empty()) {
5325 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5326 } else if (newinsetlayout->isPassThru()) {
5327 // set catcodes to verbatim early, just in case.
5328 p.setCatcodes(VERBATIM_CATCODES);
5329 string delim = p.get_token().asInput();
5331 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5332 //FIXME: handle error condition
5333 string const arg = p.verbatimStuff("}").second;
5334 Context newcontext(true, context.textclass);
5335 if (newinsetlayout->forcePlainLayout())
5336 newcontext.layout = &context.textclass.plainLayout();
5337 output_ert(os, arg, newcontext);
5339 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5342 // Minted caption insets are not closed here because
5343 // we collect everything into the caption.
5344 if (minted_float.empty())
5349 if (t.cs() == "includepdf") {
5351 string const arg = p.getArg('[', ']');
5352 map<string, string> opts;
5353 vector<string> keys;
5354 split_map(arg, opts, keys);
5355 string name = normalize_filename(p.verbatim_item());
5356 string const path = getMasterFilePath(true);
5357 // We want to preserve relative / absolute filenames,
5358 // therefore path is only used for testing
5359 if (!makeAbsPath(name, path).exists()) {
5360 // The file extension is probably missing.
5361 // Now try to find it out.
5362 char const * const pdfpages_format[] = {"pdf", 0};
5363 string const pdftex_name =
5364 find_file(name, path, pdfpages_format);
5365 if (!pdftex_name.empty()) {
5370 FileName const absname = makeAbsPath(name, path);
5371 if (absname.exists())
5373 fix_child_filename(name);
5374 copy_file(absname, name);
5376 cerr << "Warning: Could not find file '"
5377 << name << "'." << endl;
5379 context.check_layout(os);
5380 begin_inset(os, "External\n\ttemplate ");
5381 os << "PDFPages\n\tfilename "
5383 // parse the options
5384 if (opts.find("pages") != opts.end())
5385 os << "\textra LaTeX \"pages="
5386 << opts["pages"] << "\"\n";
5387 if (opts.find("angle") != opts.end())
5388 os << "\trotateAngle "
5389 << opts["angle"] << '\n';
5390 if (opts.find("origin") != opts.end()) {
5392 string const opt = opts["origin"];
5393 if (opt == "tl") ss << "topleft";
5394 if (opt == "bl") ss << "bottomleft";
5395 if (opt == "Bl") ss << "baselineleft";
5396 if (opt == "c") ss << "center";
5397 if (opt == "tc") ss << "topcenter";
5398 if (opt == "bc") ss << "bottomcenter";
5399 if (opt == "Bc") ss << "baselinecenter";
5400 if (opt == "tr") ss << "topright";
5401 if (opt == "br") ss << "bottomright";
5402 if (opt == "Br") ss << "baselineright";
5403 if (!ss.str().empty())
5404 os << "\trotateOrigin " << ss.str() << '\n';
5406 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5408 if (opts.find("width") != opts.end())
5410 << translate_len(opts["width"]) << '\n';
5411 if (opts.find("height") != opts.end())
5413 << translate_len(opts["height"]) << '\n';
5414 if (opts.find("keepaspectratio") != opts.end())
5415 os << "\tkeepAspectRatio\n";
5417 context.check_layout(os);
5418 registerExternalTemplatePackages("PDFPages");
5422 if (t.cs() == "loadgame") {
5424 string name = normalize_filename(p.verbatim_item());
5425 string const path = getMasterFilePath(true);
5426 // We want to preserve relative / absolute filenames,
5427 // therefore path is only used for testing
5428 if (!makeAbsPath(name, path).exists()) {
5429 // The file extension is probably missing.
5430 // Now try to find it out.
5431 char const * const lyxskak_format[] = {"fen", 0};
5432 string const lyxskak_name =
5433 find_file(name, path, lyxskak_format);
5434 if (!lyxskak_name.empty())
5435 name = lyxskak_name;
5437 FileName const absname = makeAbsPath(name, path);
5438 if (absname.exists())
5440 fix_child_filename(name);
5441 copy_file(absname, name);
5443 cerr << "Warning: Could not find file '"
5444 << name << "'." << endl;
5445 context.check_layout(os);
5446 begin_inset(os, "External\n\ttemplate ");
5447 os << "ChessDiagram\n\tfilename "
5450 context.check_layout(os);
5451 // after a \loadgame follows a \showboard
5452 if (p.get_token().asInput() == "showboard")
5454 registerExternalTemplatePackages("ChessDiagram");
5458 // try to see whether the string is in unicodesymbols
5459 // Only use text mode commands, since we are in text mode here,
5460 // and math commands may be invalid (bug 6797)
5461 string name = t.asInput();
5462 // handle the dingbats, cyrillic and greek
5463 if (name == "\\ding" || name == "\\textcyr" ||
5464 (name == "\\textgreek" && !preamble.usePolyglossia()))
5465 name = name + '{' + p.getArg('{', '}') + '}';
5466 // handle the ifsym characters
5467 else if (name == "\\textifsymbol") {
5468 string const optif = p.getFullOpt();
5469 string const argif = p.getArg('{', '}');
5470 name = name + optif + '{' + argif + '}';
5472 // handle the \ascii characters
5473 // the case of \ascii within braces, as LyX outputs it, is already
5474 // handled for t.cat() == catBegin
5475 else if (name == "\\ascii") {
5476 // the code is "\asci\xxx"
5477 name = "{" + name + p.get_token().asInput() + "}";
5480 // handle some TIPA special characters
5481 else if (preamble.isPackageUsed("tipa")) {
5482 if (name == "\\s") {
5483 // fromLaTeXCommand() does not yet
5484 // recognize tipa short cuts
5485 name = "\\textsyllabic";
5486 } else if (name == "\\=" &&
5487 p.next_token().asInput() == "*") {
5488 // fromLaTeXCommand() does not yet
5489 // recognize tipa short cuts
5491 name = "\\textsubbar";
5492 } else if (name == "\\textdoublevertline") {
5493 // FIXME: This is not correct,
5494 // \textvertline is higher than \textbardbl
5495 name = "\\textbardbl";
5497 } else if (name == "\\!" ) {
5498 if (p.next_token().asInput() == "b") {
5499 p.get_token(); // eat 'b'
5502 } else if (p.next_token().asInput() == "d") {
5506 } else if (p.next_token().asInput() == "g") {
5510 } else if (p.next_token().asInput() == "G") {
5512 name = "\\texthtscg";
5514 } else if (p.next_token().asInput() == "j") {
5516 name = "\\texthtbardotlessj";
5518 } else if (p.next_token().asInput() == "o") {
5520 name = "\\textbullseye";
5523 } else if (name == "\\*" ) {
5524 if (p.next_token().asInput() == "k") {
5526 name = "\\textturnk";
5528 } else if (p.next_token().asInput() == "r") {
5529 p.get_token(); // eat 'b'
5530 name = "\\textturnr";
5532 } else if (p.next_token().asInput() == "t") {
5534 name = "\\textturnt";
5536 } else if (p.next_token().asInput() == "w") {
5538 name = "\\textturnw";
5543 if ((name.size() == 2 &&
5544 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5545 p.next_token().asInput() != "*") ||
5546 is_known(name.substr(1), known_tipa_marks)) {
5547 // name is a command that corresponds to a
5548 // combining character in unicodesymbols.
5549 // Append the argument, fromLaTeXCommand()
5550 // will either convert it to a single
5551 // character or a combining sequence.
5552 name += '{' + p.verbatim_item() + '}';
5554 // now get the character from unicodesymbols
5558 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5559 Encodings::TEXT_CMD, termination, rem, &req));
5561 context.check_layout(os);
5564 output_ert_inset(os, to_utf8(rem), context);
5566 skip_spaces_braces(p);
5567 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5568 preamble.registerAutomaticallyLoadedPackage(*it);
5570 //cerr << "#: " << t << " mode: " << mode << endl;
5571 // heuristic: read up to next non-nested space
5573 string s = t.asInput();
5574 string z = p.verbatim_item();
5575 while (p.good() && z != " " && !z.empty()) {
5576 //cerr << "read: " << z << endl;
5578 z = p.verbatim_item();
5580 cerr << "found ERT: " << s << endl;
5581 output_ert_inset(os, s + ' ', context);
5584 if (t.asInput() == name &&
5585 p.next_token().asInput() == "*") {
5586 // Starred commands like \vspace*{}
5587 p.get_token(); // Eat '*'
5590 if (!parse_command(name, p, os, outer, context))
5591 output_ert_inset(os, name, context);
5597 string guessLanguage(Parser & p, string const & lang)
5599 typedef std::map<std::string, size_t> LangMap;
5600 // map from language names to number of characters
5603 for (char const * const * i = supported_CJK_languages; *i; i++)
5604 used[string(*i)] = 0;
5607 Token const t = p.get_token();
5608 // comments are not counted for any language
5609 if (t.cat() == catComment)
5611 // commands are not counted as well, but we need to detect
5612 // \begin{CJK} and switch encoding if needed
5613 if (t.cat() == catEscape) {
5614 if (t.cs() == "inputencoding") {
5615 string const enc = subst(p.verbatim_item(), "\n", " ");
5616 p.setEncoding(enc, Encoding::inputenc);
5619 if (t.cs() != "begin")
5622 // Non-CJK content is counted for lang.
5623 // We do not care about the real language here:
5624 // If we have more non-CJK contents than CJK contents,
5625 // we simply use the language that was specified as
5626 // babel main language.
5627 used[lang] += t.asInput().length();
5630 // Now we are starting an environment
5632 string const name = p.getArg('{', '}');
5633 if (name != "CJK") {
5637 // It is a CJK environment
5639 /* name = */ p.getArg('{', '}');
5640 string const encoding = p.getArg('{', '}');
5641 /* mapping = */ p.getArg('{', '}');
5642 string const encoding_old = p.getEncoding();
5643 char const * const * const where =
5644 is_known(encoding, supported_CJK_encodings);
5646 p.setEncoding(encoding, Encoding::CJK);
5648 p.setEncoding("UTF-8");
5649 string const text = p.ertEnvironment("CJK");
5650 p.setEncoding(encoding_old);
5653 // ignore contents in unknown CJK encoding
5656 // the language of the text
5658 supported_CJK_languages[where - supported_CJK_encodings];
5659 used[cjk] += text.length();
5661 LangMap::const_iterator use = used.begin();
5662 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5663 if (it->second > use->second)
5670 void check_comment_bib(ostream & os, Context & context)
5672 if (!need_commentbib)
5674 // We have a bibliography database, but no bibliography with biblatex
5675 // which is completely valid. Insert a bibtex inset in a note.
5676 context.check_layout(os);
5677 begin_inset(os, "Note Note\n");
5678 os << "status open\n";
5679 os << "\\begin_layout Plain Layout\n";
5680 begin_command_inset(os, "bibtex", "bibtex");
5682 for (auto const & bf : preamble.biblatex_bibliographies) {
5683 if (!bibfiles.empty())
5685 bibfiles += normalize_filename(bf);
5687 if (!bibfiles.empty())
5688 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5689 end_inset(os);// Bibtex
5690 os << "\\end_layout\n";
5691 end_inset(os);// Note