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
486 * Find a file with basename \p name in path \p path and an extension
489 string find_file(string const & name, string const & path,
490 char const * const * extensions)
492 for (char const * const * what = extensions; *what; ++what) {
493 string const trial = addExtension(name, *what);
494 if (makeAbsPath(trial, path).exists())
501 void begin_inset(ostream & os, string const & name)
503 os << "\n\\begin_inset " << name;
507 void begin_command_inset(ostream & os, string const & name,
508 string const & latexname)
510 begin_inset(os, "CommandInset ");
511 os << name << "\nLatexCommand " << latexname << '\n';
515 void end_inset(ostream & os)
517 os << "\n\\end_inset\n\n";
521 bool skip_braces(Parser & p)
523 if (p.next_token().cat() != catBegin)
526 if (p.next_token().cat() == catEnd) {
535 /// replace LaTeX commands in \p s from the unicodesymbols file with their
537 pair<bool, docstring> convert_unicodesymbols(docstring s)
540 int const nchars_escape = 8;
541 static char_type const chars_escape[nchars_escape] = {
542 '&', '_', '$', '%', '#', '^', '{', '}'};
544 for (size_t i = 0; i < s.size();) {
553 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
554 Encodings::TEXT_CMD, termination, rem, &req));
555 set<string>::const_iterator it = req.begin();
556 set<string>::const_iterator en = req.end();
557 for (; it != en; ++it)
558 preamble.registerAutomaticallyLoadedPackage(*it);
561 if (s.empty() || s[0] != '\\')
565 for (int k = 0; k < nchars_escape; k++)
566 if (prefixIs(s, from_ascii("\\") + chars_escape[k]))
571 return make_pair(res, os.str());
575 /// try to convert \p s to a valid InsetCommand argument
576 /// return whether this succeeded. If not, these command insets
577 /// get the "literate" flag.
578 pair<bool, string> convert_latexed_command_inset_arg(string s)
580 bool success = false;
582 // since we don't know the input encoding we can't use from_utf8
583 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
585 s = to_utf8(res.second);
587 // LyX cannot handle newlines in a latex command
588 return make_pair(success, subst(s, "\n", " "));
591 /// try to convert \p s to a valid InsetCommand argument
592 /// without trying to recode macros.
593 string convert_literate_command_inset_arg(string s)
595 // LyX cannot handle newlines in a latex command
596 return subst(s, "\n", " ");
599 void output_ert(ostream & os, string const & s, Context & context)
601 context.check_layout(os);
602 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
604 os << "\n\\backslash\n";
605 else if (*it == '\n') {
606 context.new_paragraph(os);
607 context.check_layout(os);
611 context.check_end_layout(os);
615 void output_ert_inset(ostream & os, string const & s, Context & context)
617 // We must have a valid layout before outputting the ERT inset.
618 context.check_layout(os);
619 Context newcontext(true, context.textclass);
620 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
621 if (layout.forcePlainLayout())
622 newcontext.layout = &context.textclass.plainLayout();
623 begin_inset(os, "ERT");
624 os << "\nstatus collapsed\n";
625 output_ert(os, s, newcontext);
630 void output_comment(Parser & p, ostream & os, string const & s,
633 if (p.next_token().cat() == catNewline)
634 output_ert_inset(os, '%' + s, context);
636 output_ert_inset(os, '%' + s + '\n', context);
640 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
642 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
645 if (checkModule(name, command))
646 return findLayoutWithoutModule(textclass, name, command);
651 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
653 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
656 if (checkModule(name, command))
657 return findInsetLayoutWithoutModule(textclass, name, command);
662 void eat_whitespace(Parser &, ostream &, Context &, bool);
666 * Skips whitespace and braces.
667 * This should be called after a command has been parsed that is not put into
668 * ERT, and where LyX adds "{}" if needed.
670 void skip_spaces_braces(Parser & p, bool keepws = false)
672 /* The following four examples produce the same typeset output and
673 should be handled by this function:
681 // Unfortunately we need to skip comments, too.
682 // We can't use eat_whitespace since writing them after the {}
683 // results in different output in some cases.
684 bool const skipped_spaces = p.skip_spaces(true);
685 bool const skipped_braces = skip_braces(p);
686 if (keepws && skipped_spaces && !skipped_braces)
687 // put back the space (it is better handled by check_space)
688 p.unskip_spaces(true);
692 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
693 Context & context, Layout::LaTeXArgMap const & latexargs)
696 context.check_layout(os);
701 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
702 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
703 for (; lait != laend; ++lait) {
705 eat_whitespace(p, os, context, false);
706 if (lait->second.mandatory) {
707 if (p.next_token().cat() != catBegin)
709 p.get_token(); // eat '{'
711 context.check_layout(os);
714 begin_inset(os, "Argument ");
717 os << i << "\nstatus collapsed\n\n";
718 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
721 if (p.next_token().cat() == catEscape ||
722 p.next_token().character() != '[')
724 p.get_token(); // eat '['
726 context.check_layout(os);
729 begin_inset(os, "Argument ");
732 os << i << "\nstatus collapsed\n\n";
733 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
736 eat_whitespace(p, os, context, false);
741 void output_command_layout(ostream & os, Parser & p, bool outer,
742 Context & parent_context,
743 Layout const * newlayout)
745 TeXFont const oldFont = parent_context.font;
746 // save the current font size
747 string const size = oldFont.size;
748 // reset the font size to default, because the font size switches
749 // don't affect section headings and the like
750 parent_context.font.size = Context::normalfont.size;
751 // we only need to write the font change if we have an open layout
752 if (!parent_context.atParagraphStart())
753 output_font_change(os, oldFont, parent_context.font);
754 parent_context.check_end_layout(os);
755 Context context(true, parent_context.textclass, newlayout,
756 parent_context.layout, parent_context.font);
757 if (parent_context.deeper_paragraph) {
758 // We are beginning a nested environment after a
759 // deeper paragraph inside the outer list environment.
760 // Therefore we don't need to output a "begin deeper".
761 context.need_end_deeper = true;
763 context.check_deeper(os);
764 output_arguments(os, p, outer, true, false, context,
765 context.layout->latexargs());
766 parse_text(p, os, FLAG_ITEM, outer, context);
767 output_arguments(os, p, outer, false, true, context,
768 context.layout->postcommandargs());
769 context.check_end_layout(os);
770 if (parent_context.deeper_paragraph) {
771 // We must suppress the "end deeper" because we
772 // suppressed the "begin deeper" above.
773 context.need_end_deeper = false;
775 context.check_end_deeper(os);
776 // We don't need really a new paragraph, but
777 // we must make sure that the next item gets a \begin_layout.
778 parent_context.new_paragraph(os);
779 // Set the font size to the original value. No need to output it here
780 // (Context::begin_layout() will do that if needed)
781 parent_context.font.size = size;
786 * Output a space if necessary.
787 * This function gets called for every whitespace token.
789 * We have three cases here:
790 * 1. A space must be suppressed. Example: The lyxcode case below
791 * 2. A space may be suppressed. Example: Spaces before "\par"
792 * 3. A space must not be suppressed. Example: A space between two words
794 * We currently handle only 1. and 3 and from 2. only the case of
795 * spaces before newlines as a side effect.
797 * 2. could be used to suppress as many spaces as possible. This has two effects:
798 * - Reimporting LyX generated LaTeX files changes almost no whitespace
799 * - Superflous whitespace from non LyX generated LaTeX files is removed.
800 * The drawback is that the logic inside the function becomes
801 * complicated, and that is the reason why it is not implemented.
803 void check_space(Parser & p, ostream & os, Context & context)
805 Token const next = p.next_token();
806 Token const curr = p.curr_token();
807 // A space before a single newline and vice versa must be ignored
808 // LyX emits a newline before \end{lyxcode}.
809 // This newline must be ignored,
810 // otherwise LyX will add an additional protected space.
811 if (next.cat() == catSpace ||
812 next.cat() == catNewline ||
813 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
816 context.check_layout(os);
822 * Parse all arguments of \p command
824 void parse_arguments(string const & command,
825 vector<ArgumentType> const & template_arguments,
826 Parser & p, ostream & os, bool outer, Context & context)
828 string ert = command;
829 size_t no_arguments = template_arguments.size();
830 for (size_t i = 0; i < no_arguments; ++i) {
831 switch (template_arguments[i]) {
834 // This argument contains regular LaTeX
835 output_ert_inset(os, ert + '{', context);
836 eat_whitespace(p, os, context, false);
837 if (template_arguments[i] == required)
838 parse_text(p, os, FLAG_ITEM, outer, context);
840 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
844 // This argument consists only of a single item.
845 // The presence of '{' or not must be preserved.
847 if (p.next_token().cat() == catBegin)
848 ert += '{' + p.verbatim_item() + '}';
850 ert += p.verbatim_item();
854 // This argument may contain special characters
855 ert += '{' + p.verbatim_item() + '}';
859 // true because we must not eat whitespace
860 // if an optional arg follows we must not strip the
861 // brackets from this one
862 if (i < no_arguments - 1 &&
863 template_arguments[i+1] == optional)
864 ert += p.getFullOpt(true);
866 ert += p.getOpt(true);
870 output_ert_inset(os, ert, context);
875 * Check whether \p command is a known command. If yes,
876 * handle the command with all arguments.
877 * \return true if the command was parsed, false otherwise.
879 bool parse_command(string const & command, Parser & p, ostream & os,
880 bool outer, Context & context)
882 if (known_commands.find(command) != known_commands.end()) {
883 parse_arguments(command, known_commands[command], p, os,
891 /// Parses a minipage or parbox
892 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
893 unsigned inner_flags, bool outer, Context & parent_context,
894 string const & outer_type, string const & special,
895 string inner_type, string const & frame_color,
896 string const & background_color)
900 string hor_pos = "l";
901 // We need to set the height to the LaTeX default of 1\\totalheight
902 // for the case when no height argument is given
903 string height_value = "1";
904 string height_unit = "in";
905 string height_special = "totalheight";
910 string width_special = "none";
911 string thickness = "0.4pt";
912 if (!fboxrule.empty())
913 thickness = fboxrule;
917 if (!fboxsep.empty())
918 separation = fboxsep;
922 if (!shadow_size.empty())
923 shadowsize = shadow_size;
926 string framecolor = "black";
927 string backgroundcolor = "none";
928 if (!frame_color.empty())
929 framecolor = frame_color;
930 if (!background_color.empty())
931 backgroundcolor = background_color;
932 // if there is a color box around the \begin statements have not yet been parsed
934 if (!frame_color.empty() || !background_color.empty()) {
935 eat_whitespace(p, os, parent_context, false);
936 p.get_token().asInput(); // the '{'
938 if (p.next_token().asInput() == "\\begin") {
939 p.get_token().asInput();
941 inner_type = "minipage";
942 inner_flags = FLAG_END;
943 active_environments.push_back("minipage");
946 else if (p.next_token().asInput() == "\\parbox") {
947 p.get_token().asInput();
948 inner_type = "parbox";
949 inner_flags = FLAG_ITEM;
952 else if (p.next_token().asInput() == "\\makebox") {
953 p.get_token().asInput();
954 inner_type = "makebox";
955 inner_flags = FLAG_ITEM;
957 // in case there is just \colorbox{color}{text}
960 inner_type = "makebox";
961 inner_flags = FLAG_BRACE_LAST;
966 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
968 if (!inner_type.empty() && p.hasOpt()) {
969 if (inner_type != "makebox")
970 position = p.getArg('[', ']');
972 latex_width = p.getArg('[', ']');
973 translate_box_len(latex_width, width_value, width_unit, width_special);
976 if (position != "t" && position != "c" && position != "b") {
977 cerr << "invalid position " << position << " for "
978 << inner_type << endl;
982 if (inner_type != "makebox") {
983 latex_height = p.getArg('[', ']');
984 translate_box_len(latex_height, height_value, height_unit, height_special);
986 string const opt = p.getArg('[', ']');
989 if (hor_pos != "l" && hor_pos != "c" &&
990 hor_pos != "r" && hor_pos != "s") {
991 cerr << "invalid hor_pos " << hor_pos
992 << " for " << inner_type << endl;
999 inner_pos = p.getArg('[', ']');
1000 if (inner_pos != "c" && inner_pos != "t" &&
1001 inner_pos != "b" && inner_pos != "s") {
1002 cerr << "invalid inner_pos "
1003 << inner_pos << " for "
1004 << inner_type << endl;
1005 inner_pos = position;
1009 if (inner_type == "makebox")
1013 if (inner_type.empty()) {
1014 if (special.empty() && outer_type != "framebox")
1015 latex_width = "1\\columnwidth";
1018 latex_width = p2.getArg('[', ']');
1019 string const opt = p2.getArg('[', ']');
1022 if (hor_pos != "l" && hor_pos != "c" &&
1023 hor_pos != "r" && hor_pos != "s") {
1024 cerr << "invalid hor_pos " << hor_pos
1025 << " for " << outer_type << endl;
1029 if (outer_type == "framebox")
1033 } else if (inner_type != "makebox")
1034 latex_width = p.verbatim_item();
1035 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1036 // as this is LyX's standard for such cases (except for makebox)
1037 // \framebox is more special and handled below
1038 if (latex_width.empty() && inner_type != "makebox"
1039 && outer_type != "framebox")
1040 latex_width = "1\\columnwidth";
1042 translate_len(latex_width, width_value, width_unit);
1044 bool shadedparbox = false;
1045 if (inner_type == "shaded") {
1046 eat_whitespace(p, os, parent_context, false);
1047 if (outer_type == "parbox") {
1049 if (p.next_token().cat() == catBegin)
1051 eat_whitespace(p, os, parent_context, false);
1052 shadedparbox = true;
1057 // If we already read the inner box we have to push the inner env
1058 if (!outer_type.empty() && !inner_type.empty() &&
1059 (inner_flags & FLAG_END))
1060 active_environments.push_back(inner_type);
1061 bool use_ert = false;
1062 if (!outer_type.empty() && !inner_type.empty()) {
1063 // Look whether there is some content after the end of the
1064 // inner box, but before the end of the outer box.
1065 // If yes, we need to output ERT.
1067 if (inner_flags & FLAG_END)
1068 p.ertEnvironment(inner_type);
1071 p.skip_spaces(true);
1072 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1073 if ((outer_env && p.next_token().asInput() != "\\end") ||
1074 (!outer_env && p.next_token().cat() != catEnd)) {
1075 // something is between the end of the inner box and
1076 // the end of the outer box, so we need to use ERT.
1084 if (!outer_type.empty()) {
1085 if (outer_flags & FLAG_END)
1086 ss << "\\begin{" << outer_type << '}';
1088 ss << '\\' << outer_type << '{';
1089 if (!special.empty())
1093 if (!inner_type.empty()) {
1094 if (inner_type != "shaded") {
1095 if (inner_flags & FLAG_END)
1096 ss << "\\begin{" << inner_type << '}';
1098 ss << '\\' << inner_type;
1100 if (!position.empty())
1101 ss << '[' << position << ']';
1102 if (!latex_height.empty())
1103 ss << '[' << latex_height << ']';
1104 if (!inner_pos.empty())
1105 ss << '[' << inner_pos << ']';
1106 ss << '{' << latex_width << '}';
1107 if (!(inner_flags & FLAG_END))
1110 if (inner_type == "shaded")
1111 ss << "\\begin{shaded}";
1112 output_ert_inset(os, ss.str(), parent_context);
1113 if (!inner_type.empty()) {
1114 parse_text(p, os, inner_flags, outer, parent_context);
1115 if (inner_flags & FLAG_END)
1116 output_ert_inset(os, "\\end{" + inner_type + '}',
1119 output_ert_inset(os, "}", parent_context);
1121 if (!outer_type.empty()) {
1122 // If we already read the inner box we have to pop
1124 if (!inner_type.empty() && (inner_flags & FLAG_END))
1125 active_environments.pop_back();
1127 // Ensure that the end of the outer box is parsed correctly:
1128 // The opening brace has been eaten by parse_outer_box()
1129 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1130 outer_flags &= ~FLAG_ITEM;
1131 outer_flags |= FLAG_BRACE_LAST;
1133 parse_text(p, os, outer_flags, outer, parent_context);
1134 if (outer_flags & FLAG_END)
1135 output_ert_inset(os, "\\end{" + outer_type + '}',
1138 output_ert_inset(os, "}", parent_context);
1141 // LyX does not like empty positions, so we have
1142 // to set them to the LaTeX default values here.
1143 if (position.empty())
1145 if (inner_pos.empty())
1146 inner_pos = position;
1147 parent_context.check_layout(os);
1148 begin_inset(os, "Box ");
1149 if (outer_type == "framed")
1151 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1153 else if (outer_type == "shadowbox")
1154 os << "Shadowbox\n";
1155 else if ((outer_type == "shaded" && inner_type.empty()) ||
1156 (outer_type == "minipage" && inner_type == "shaded") ||
1157 (outer_type == "parbox" && inner_type == "shaded")) {
1159 preamble.registerAutomaticallyLoadedPackage("color");
1160 } else if (outer_type == "doublebox")
1161 os << "Doublebox\n";
1162 else if (outer_type.empty() || outer_type == "mbox")
1163 os << "Frameless\n";
1165 os << outer_type << '\n';
1166 os << "position \"" << position << "\"\n";
1167 os << "hor_pos \"" << hor_pos << "\"\n";
1168 if (outer_type == "mbox")
1169 os << "has_inner_box 1\n";
1170 else if (!frame_color.empty() && inner_type == "makebox")
1171 os << "has_inner_box 0\n";
1173 os << "has_inner_box " << !inner_type.empty() << "\n";
1174 os << "inner_pos \"" << inner_pos << "\"\n";
1175 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1177 if (outer_type == "mbox")
1178 os << "use_makebox 1\n";
1179 else if (!frame_color.empty())
1180 os << "use_makebox 0\n";
1182 os << "use_makebox " << (inner_type == "makebox") << '\n';
1183 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1184 os << "width \"\"\n";
1185 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1186 else if (contains(width_unit, '\\'))
1187 os << "width \"" << width_value << "in" << "\"\n";
1189 os << "width \"" << width_value << width_unit << "\"\n";
1190 if (contains(width_unit, '\\')) {
1191 width_unit.erase (0,1); // remove the leading '\'
1192 os << "special \"" << width_unit << "\"\n";
1194 os << "special \"" << width_special << "\"\n";
1195 if (contains(height_unit, '\\'))
1196 os << "height \"" << height_value << "in" << "\"\n";
1198 os << "height \"" << height_value << height_unit << "\"\n";
1199 os << "height_special \"" << height_special << "\"\n";
1200 os << "thickness \"" << thickness << "\"\n";
1201 os << "separation \"" << separation << "\"\n";
1202 os << "shadowsize \"" << shadowsize << "\"\n";
1203 os << "framecolor \"" << framecolor << "\"\n";
1204 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1205 os << "status open\n\n";
1207 // Unfortunately we can't use parse_text_in_inset:
1208 // InsetBox::forcePlainLayout() is hard coded and does not
1209 // use the inset layout. Apart from that do we call parse_text
1210 // up to two times, but need only one check_end_layout.
1211 bool const forcePlainLayout =
1212 (!inner_type.empty() || inner_type == "makebox") &&
1213 outer_type != "shaded" && outer_type != "framed";
1214 Context context(true, parent_context.textclass);
1215 if (forcePlainLayout)
1216 context.layout = &context.textclass.plainLayout();
1218 context.font = parent_context.font;
1220 // If we have no inner box the contents will be read with the outer box
1221 if (!inner_type.empty())
1222 parse_text(p, os, inner_flags, outer, context);
1224 // Ensure that the end of the outer box is parsed correctly:
1225 // The opening brace has been eaten by parse_outer_box()
1226 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1227 outer_flags &= ~FLAG_ITEM;
1228 outer_flags |= FLAG_BRACE_LAST;
1231 // Find end of outer box, output contents if inner_type is
1232 // empty and output possible comments
1233 if (!outer_type.empty()) {
1234 // If we already read the inner box we have to pop
1236 if (!inner_type.empty() && (inner_flags & FLAG_END))
1237 active_environments.pop_back();
1238 // This does not output anything but comments if
1239 // inner_type is not empty (see use_ert)
1240 parse_text(p, os, outer_flags, outer, context);
1243 context.check_end_layout(os);
1245 #ifdef PRESERVE_LAYOUT
1246 // LyX puts a % after the end of the minipage
1247 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1249 //output_comment(p, os, "dummy", parent_context);
1252 parent_context.new_paragraph(os);
1254 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1255 //output_comment(p, os, "dummy", parent_context);
1258 // We add a protected space if something real follows
1259 if (p.good() && p.next_token().cat() != catComment) {
1260 begin_inset(os, "space ~\n");
1266 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1267 active_environments.pop_back();
1268 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1269 // in this case we have to eat the the closing brace of the color box
1270 p.get_token().asInput(); // the '}'
1272 if (p.next_token().asInput() == "}") {
1273 // in this case we assume that the closing brace is from the box settings
1274 // therefore reset these values for the next box
1280 // all boxes except of Frameless and Shaded require calc
1281 if (!(outer_type.empty() || outer_type == "mbox") &&
1282 !((outer_type == "shaded" && inner_type.empty()) ||
1283 (outer_type == "minipage" && inner_type == "shaded") ||
1284 (outer_type == "parbox" && inner_type == "shaded")))
1285 preamble.registerAutomaticallyLoadedPackage("calc");
1289 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1290 Context & parent_context, string const & outer_type,
1291 string const & special)
1293 eat_whitespace(p, os, parent_context, false);
1294 if (flags & FLAG_ITEM) {
1296 if (p.next_token().cat() == catBegin)
1299 cerr << "Warning: Ignoring missing '{' after \\"
1300 << outer_type << '.' << endl;
1301 eat_whitespace(p, os, parent_context, false);
1304 unsigned int inner_flags = 0;
1306 if (outer_type == "minipage" || outer_type == "parbox") {
1307 p.skip_spaces(true);
1308 while (p.hasOpt()) {
1310 p.skip_spaces(true);
1313 p.skip_spaces(true);
1314 if (outer_type == "parbox") {
1316 if (p.next_token().cat() == catBegin)
1318 p.skip_spaces(true);
1321 if (outer_type == "shaded" || outer_type == "mbox") {
1322 // These boxes never have an inner box
1324 } else if (p.next_token().asInput() == "\\parbox") {
1325 inner = p.get_token().cs();
1326 inner_flags = FLAG_ITEM;
1327 } else if (p.next_token().asInput() == "\\begin") {
1328 // Is this a minipage or shaded box?
1331 inner = p.getArg('{', '}');
1333 if (inner == "minipage" || inner == "shaded")
1334 inner_flags = FLAG_END;
1339 if (inner_flags == FLAG_END) {
1340 if (inner != "shaded")
1344 eat_whitespace(p, os, parent_context, false);
1346 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1347 outer_type, special, inner, "", "");
1349 if (inner_flags == FLAG_ITEM) {
1351 eat_whitespace(p, os, parent_context, false);
1353 parse_box(p, os, flags, inner_flags, outer, parent_context,
1354 outer_type, special, inner, "", "");
1359 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1360 bool in_line, bool use_minted)
1362 parent_context.check_layout(os);
1363 begin_inset(os, "listings\n");
1364 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1366 while ((i = arg.find(", ")) != string::npos
1367 || (i = arg.find(",\t")) != string::npos)
1368 arg.erase(i + 1, 1);
1371 string const language = p.getArg('{', '}');
1372 p.skip_spaces(true);
1373 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1374 if (!minted_float.empty()) {
1375 arg += string(arg.empty() ? "" : ",") + minted_float;
1376 minted_nonfloat_caption.clear();
1380 os << "lstparams " << '"' << arg << '"' << '\n';
1381 if (arg.find("\\color") != string::npos)
1382 preamble.registerAutomaticallyLoadedPackage("color");
1385 os << "inline true\n";
1387 os << "inline false\n";
1388 os << "status collapsed\n";
1389 Context context(true, parent_context.textclass);
1390 context.layout = &parent_context.textclass.plainLayout();
1391 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1392 minted_nonfloat_caption.erase(0,3);
1393 os << "\n\\begin_layout Plain Layout\n";
1394 begin_inset(os, "Caption Standard\n");
1395 Context newcontext(true, context.textclass,
1396 context.layout, 0, context.font);
1397 newcontext.check_layout(os);
1398 os << minted_nonfloat_caption << "\n";
1399 newcontext.check_end_layout(os);
1401 os << "\n\\end_layout\n";
1402 minted_nonfloat_caption.clear();
1406 // set catcodes to verbatim early, just in case.
1407 p.setCatcodes(VERBATIM_CATCODES);
1408 string delim = p.get_token().asInput();
1409 //FIXME: handler error condition
1410 s = p.verbatimStuff(delim).second;
1411 // context.new_paragraph(os);
1412 } else if (use_minted) {
1413 s = p.verbatimEnvironment("minted");
1415 s = p.verbatimEnvironment("lstlisting");
1417 output_ert(os, s, context);
1418 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1419 minted_nonfloat_caption.erase(0,3);
1420 os << "\n\\begin_layout Plain Layout\n";
1421 begin_inset(os, "Caption Standard\n");
1422 Context newcontext(true, context.textclass,
1423 context.layout, 0, context.font);
1424 newcontext.check_layout(os);
1425 os << minted_nonfloat_caption << "\n";
1426 newcontext.check_end_layout(os);
1428 os << "\n\\end_layout\n";
1429 minted_nonfloat_caption.clear();
1431 // Don't close the inset here for floating minted listings.
1432 // It will be closed at the end of the listing environment.
1433 if (!use_minted || minted_float.empty())
1436 eat_whitespace(p, os, parent_context, true);
1437 Token t = p.get_token();
1438 if (t.asInput() != "\\end") {
1439 // If anything follows, collect it into a caption.
1440 minted_float_has_caption = true;
1441 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1442 begin_inset(os, "Caption Standard\n");
1443 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1450 /// parse an unknown environment
1451 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1452 unsigned flags, bool outer,
1453 Context & parent_context)
1455 if (name == "tabbing")
1456 // We need to remember that we have to handle '\=' specially
1457 flags |= FLAG_TABBING;
1459 // We need to translate font changes and paragraphs inside the
1460 // environment to ERT if we have a non standard font.
1461 // Otherwise things like
1462 // \large\begin{foo}\huge bar\end{foo}
1464 bool const specialfont =
1465 (parent_context.font != parent_context.normalfont);
1466 bool const new_layout_allowed = parent_context.new_layout_allowed;
1468 parent_context.new_layout_allowed = false;
1469 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1470 parse_text_snippet(p, os, flags, outer, parent_context);
1471 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1473 parent_context.new_layout_allowed = new_layout_allowed;
1477 void parse_environment(Parser & p, ostream & os, bool outer,
1478 string & last_env, Context & parent_context)
1480 Layout const * newlayout;
1481 InsetLayout const * newinsetlayout = 0;
1482 string const name = p.getArg('{', '}');
1483 const bool is_starred = suffixIs(name, '*');
1484 string const unstarred_name = rtrim(name, "*");
1485 active_environments.push_back(name);
1487 if (is_math_env(name)) {
1488 parent_context.check_layout(os);
1489 begin_inset(os, "Formula ");
1490 os << "\\begin{" << name << "}";
1491 parse_math(p, os, FLAG_END, MATH_MODE);
1492 os << "\\end{" << name << "}";
1494 if (is_display_math_env(name)) {
1495 // Prevent the conversion of a line break to a space
1496 // (bug 7668). This does not change the output, but
1497 // looks ugly in LyX.
1498 eat_whitespace(p, os, parent_context, false);
1502 else if (is_known(name, preamble.polyglossia_languages)) {
1503 // We must begin a new paragraph if not already done
1504 if (! parent_context.atParagraphStart()) {
1505 parent_context.check_end_layout(os);
1506 parent_context.new_paragraph(os);
1508 // save the language in the context so that it is
1509 // handled by parse_text
1510 parent_context.font.language = preamble.polyglossia2lyx(name);
1511 parse_text(p, os, FLAG_END, outer, parent_context);
1512 // Just in case the environment is empty
1513 parent_context.extra_stuff.erase();
1514 // We must begin a new paragraph to reset the language
1515 parent_context.new_paragraph(os);
1519 else if (unstarred_name == "tabular" || name == "longtable") {
1520 eat_whitespace(p, os, parent_context, false);
1521 string width = "0pt";
1522 if (name == "tabular*") {
1523 width = lyx::translate_len(p.getArg('{', '}'));
1524 eat_whitespace(p, os, parent_context, false);
1526 parent_context.check_layout(os);
1527 begin_inset(os, "Tabular ");
1528 handle_tabular(p, os, name, width, parent_context);
1533 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1534 eat_whitespace(p, os, parent_context, false);
1535 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1536 eat_whitespace(p, os, parent_context, false);
1537 parent_context.check_layout(os);
1538 begin_inset(os, "Float " + unstarred_name + "\n");
1539 // store the float type for subfloats
1540 // subfloats only work with figures and tables
1541 if (unstarred_name == "figure")
1542 float_type = unstarred_name;
1543 else if (unstarred_name == "table")
1544 float_type = unstarred_name;
1548 os << "placement " << opt << '\n';
1549 if (contains(opt, "H"))
1550 preamble.registerAutomaticallyLoadedPackage("float");
1552 Floating const & fl = parent_context.textclass.floats()
1553 .getType(unstarred_name);
1554 if (!fl.floattype().empty() && fl.usesFloatPkg())
1555 preamble.registerAutomaticallyLoadedPackage("float");
1558 os << "wide " << convert<string>(is_starred)
1559 << "\nsideways false"
1560 << "\nstatus open\n\n";
1561 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1563 // We don't need really a new paragraph, but
1564 // we must make sure that the next item gets a \begin_layout.
1565 parent_context.new_paragraph(os);
1567 // the float is parsed thus delete the type
1571 else if (unstarred_name == "sidewaysfigure"
1572 || unstarred_name == "sidewaystable"
1573 || unstarred_name == "sidewaysalgorithm") {
1574 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1575 eat_whitespace(p, os, parent_context, false);
1576 parent_context.check_layout(os);
1577 if (unstarred_name == "sidewaysfigure")
1578 begin_inset(os, "Float figure\n");
1579 else if (unstarred_name == "sidewaystable")
1580 begin_inset(os, "Float table\n");
1581 else if (unstarred_name == "sidewaysalgorithm")
1582 begin_inset(os, "Float algorithm\n");
1584 os << "placement " << opt << '\n';
1585 if (contains(opt, "H"))
1586 preamble.registerAutomaticallyLoadedPackage("float");
1587 os << "wide " << convert<string>(is_starred)
1588 << "\nsideways true"
1589 << "\nstatus open\n\n";
1590 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1592 // We don't need really a new paragraph, but
1593 // we must make sure that the next item gets a \begin_layout.
1594 parent_context.new_paragraph(os);
1596 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1599 else if (name == "wrapfigure" || name == "wraptable") {
1600 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1601 eat_whitespace(p, os, parent_context, false);
1602 parent_context.check_layout(os);
1605 string overhang = "0col%";
1608 lines = p.getArg('[', ']');
1609 string const placement = p.getArg('{', '}');
1611 overhang = p.getArg('[', ']');
1612 string const width = p.getArg('{', '}');
1614 if (name == "wrapfigure")
1615 begin_inset(os, "Wrap figure\n");
1617 begin_inset(os, "Wrap table\n");
1618 os << "lines " << lines
1619 << "\nplacement " << placement
1620 << "\noverhang " << lyx::translate_len(overhang)
1621 << "\nwidth " << lyx::translate_len(width)
1622 << "\nstatus open\n\n";
1623 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1625 // We don't need really a new paragraph, but
1626 // we must make sure that the next item gets a \begin_layout.
1627 parent_context.new_paragraph(os);
1629 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1632 else if (name == "minipage") {
1633 eat_whitespace(p, os, parent_context, false);
1634 // Test whether this is an outer box of a shaded box
1636 // swallow arguments
1637 while (p.hasOpt()) {
1639 p.skip_spaces(true);
1642 p.skip_spaces(true);
1643 Token t = p.get_token();
1644 bool shaded = false;
1645 if (t.asInput() == "\\begin") {
1646 p.skip_spaces(true);
1647 if (p.getArg('{', '}') == "shaded")
1652 parse_outer_box(p, os, FLAG_END, outer,
1653 parent_context, name, "shaded");
1655 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1656 "", "", name, "", "");
1660 else if (name == "comment") {
1661 eat_whitespace(p, os, parent_context, false);
1662 parent_context.check_layout(os);
1663 begin_inset(os, "Note Comment\n");
1664 os << "status open\n";
1665 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1668 skip_braces(p); // eat {} that might by set by LyX behind comments
1669 preamble.registerAutomaticallyLoadedPackage("verbatim");
1672 else if (unstarred_name == "verbatim") {
1673 // FIXME: this should go in the generic code that
1674 // handles environments defined in layout file that
1675 // have "PassThru 1". However, the code over there is
1676 // already too complicated for my taste.
1677 string const ascii_name =
1678 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1679 parent_context.new_paragraph(os);
1680 Context context(true, parent_context.textclass,
1681 &parent_context.textclass[from_ascii(ascii_name)]);
1682 string s = p.verbatimEnvironment(name);
1683 output_ert(os, s, context);
1687 else if (name == "IPA") {
1688 eat_whitespace(p, os, parent_context, false);
1689 parent_context.check_layout(os);
1690 begin_inset(os, "IPA\n");
1691 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1694 preamble.registerAutomaticallyLoadedPackage("tipa");
1695 preamble.registerAutomaticallyLoadedPackage("tipx");
1698 else if (name == "CJK") {
1699 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1700 // It is impossible to decide if a CJK environment was in its own paragraph or within
1701 // a line. We therefore always assume a paragraph since the latter is a rare case.
1702 eat_whitespace(p, os, parent_context, false);
1703 parent_context.check_end_layout(os);
1704 // store the encoding to be able to reset it
1705 string const encoding_old = p.getEncoding();
1706 string const encoding = p.getArg('{', '}');
1707 // FIXME: For some reason JIS does not work. Although the text
1708 // in tests/CJK.tex is identical with the SJIS version if you
1709 // convert both snippets using the recode command line utility,
1710 // the resulting .lyx file contains some extra characters if
1711 // you set buggy_encoding to false for JIS.
1712 bool const buggy_encoding = encoding == "JIS";
1713 if (!buggy_encoding)
1714 p.setEncoding(encoding, Encoding::CJK);
1716 // FIXME: This will read garbage, since the data is not encoded in utf8.
1717 p.setEncoding("UTF-8");
1719 // LyX only supports the same mapping for all CJK
1720 // environments, so we might need to output everything as ERT
1721 string const mapping = trim(p.getArg('{', '}'));
1722 char const * const * const where =
1723 is_known(encoding, supported_CJK_encodings);
1724 if (!buggy_encoding && !preamble.fontCJKSet())
1725 preamble.fontCJK(mapping);
1726 bool knownMapping = mapping == preamble.fontCJK();
1727 if (buggy_encoding || !knownMapping || !where) {
1728 parent_context.check_layout(os);
1729 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1731 // we must parse the content as verbatim because e.g. JIS can contain
1732 // normally invalid characters
1733 // FIXME: This works only for the most simple cases.
1734 // Since TeX control characters are not parsed,
1735 // things like comments are completely wrong.
1736 string const s = p.plainEnvironment("CJK");
1737 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1739 output_ert_inset(os, "\\", parent_context);
1740 else if (*it == '$')
1741 output_ert_inset(os, "$", parent_context);
1742 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1747 output_ert_inset(os, "\\end{" + name + "}",
1751 supported_CJK_languages[where - supported_CJK_encodings];
1752 // store the language because we must reset it at the end
1753 string const lang_old = parent_context.font.language;
1754 parent_context.font.language = lang;
1755 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1756 parent_context.font.language = lang_old;
1757 parent_context.new_paragraph(os);
1759 p.setEncoding(encoding_old);
1763 else if (name == "lyxgreyedout") {
1764 eat_whitespace(p, os, parent_context, false);
1765 parent_context.check_layout(os);
1766 begin_inset(os, "Note Greyedout\n");
1767 os << "status open\n";
1768 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1771 if (!preamble.notefontcolor().empty())
1772 preamble.registerAutomaticallyLoadedPackage("color");
1775 else if (name == "btSect") {
1776 eat_whitespace(p, os, parent_context, false);
1777 parent_context.check_layout(os);
1778 begin_command_inset(os, "bibtex", "bibtex");
1779 string bibstyle = "plain";
1781 bibstyle = p.getArg('[', ']');
1782 p.skip_spaces(true);
1784 string const bibfile = p.getArg('{', '}');
1785 eat_whitespace(p, os, parent_context, false);
1786 Token t = p.get_token();
1787 if (t.asInput() == "\\btPrintCited") {
1788 p.skip_spaces(true);
1789 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1791 if (t.asInput() == "\\btPrintNotCited") {
1792 p.skip_spaces(true);
1793 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1795 if (t.asInput() == "\\btPrintAll") {
1796 p.skip_spaces(true);
1797 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1799 os << "bibfiles " << '"' << bibfile << "\"\n"
1800 << "options " << '"' << bibstyle << "\"\n";
1801 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1806 else if (name == "framed" || name == "shaded") {
1807 eat_whitespace(p, os, parent_context, false);
1808 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1810 preamble.registerAutomaticallyLoadedPackage("framed");
1813 else if (name == "listing") {
1814 minted_float = "float";
1815 eat_whitespace(p, os, parent_context, false);
1816 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1818 minted_float += "=" + opt;
1819 // If something precedes \begin{minted}, we output it at the end
1820 // as a caption, in order to keep it inside the listings inset.
1821 eat_whitespace(p, os, parent_context, true);
1823 Token const & t = p.get_token();
1824 p.skip_spaces(true);
1825 string const envname = p.next_token().cat() == catBegin
1826 ? p.getArg('{', '}') : string();
1827 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1829 minted_float_has_caption = false;
1830 string content = parse_text_snippet(p, FLAG_END, outer,
1832 size_t i = content.find("\\begin_inset listings");
1833 bool minted_env = i != string::npos;
1836 caption = content.substr(0, i);
1837 content.erase(0, i);
1839 parent_context.check_layout(os);
1840 if (minted_env && minted_float_has_caption) {
1841 eat_whitespace(p, os, parent_context, true);
1842 os << content << "\n";
1843 if (!caption.empty())
1844 os << caption << "\n";
1845 os << "\n\\end_layout\n"; // close inner layout
1846 end_inset(os); // close caption inset
1847 os << "\n\\end_layout\n"; // close outer layout
1848 } else if (!caption.empty()) {
1850 begin_inset(os, "listings\n");
1851 os << "lstparams " << '"' << minted_float << '"' << '\n';
1852 os << "inline false\n";
1853 os << "status collapsed\n";
1855 os << "\n\\begin_layout Plain Layout\n";
1856 begin_inset(os, "Caption Standard\n");
1857 Context newcontext(true, parent_context.textclass,
1858 0, 0, parent_context.font);
1859 newcontext.check_layout(os);
1860 os << caption << "\n";
1861 newcontext.check_end_layout(os);
1863 os << "\n\\end_layout\n";
1864 } else if (content.empty()) {
1865 begin_inset(os, "listings\n");
1866 os << "lstparams " << '"' << minted_float << '"' << '\n';
1867 os << "inline false\n";
1868 os << "status collapsed\n";
1870 os << content << "\n";
1872 end_inset(os); // close listings inset
1873 parent_context.check_end_layout(os);
1874 parent_context.new_paragraph(os);
1876 minted_float.clear();
1877 minted_float_has_caption = false;
1880 else if (name == "lstlisting" || name == "minted") {
1881 bool use_minted = name == "minted";
1882 eat_whitespace(p, os, parent_context, false);
1883 if (use_minted && minted_float.empty()) {
1884 // look ahead for a bottom caption
1886 bool found_end_minted = false;
1887 while (!found_end_minted && p.good()) {
1888 Token const & t = p.get_token();
1890 string const envname =
1891 p.next_token().cat() == catBegin
1892 ? p.getArg('{', '}') : string();
1893 found_end_minted = t.asInput() == "\\end"
1894 && envname == "minted";
1896 eat_whitespace(p, os, parent_context, true);
1897 Token const & t = p.get_token();
1898 p.skip_spaces(true);
1899 if (t.asInput() == "\\lyxmintcaption") {
1900 string const pos = p.getArg('[', ']');
1902 string const caption =
1903 parse_text_snippet(p, FLAG_ITEM,
1904 false, parent_context);
1905 minted_nonfloat_caption = "[b]" + caption;
1910 parse_listings(p, os, parent_context, false, use_minted);
1914 else if (!parent_context.new_layout_allowed)
1915 parse_unknown_environment(p, name, os, FLAG_END, outer,
1918 // Alignment and spacing settings
1919 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1920 // therefore are totally broken!
1921 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1922 // they are commands not environments. They are furthermore switches that
1923 // can be ended by another switches, but also by commands like \footnote or
1924 // \parbox. So the only safe way is to leave them untouched.
1925 // However, we support the pseudo-environments
1926 // \begin{centering} ... \end{centering}
1927 // \begin{raggedright} ... \end{raggedright}
1928 // \begin{raggedleft} ... \end{raggedleft}
1929 // since they are used by LyX in floats (for spacing reasons)
1930 else if (name == "center" || name == "centering" ||
1931 name == "flushleft" || name == "raggedright" ||
1932 name == "flushright" || name == "raggedleft" ||
1933 name == "singlespace" || name == "onehalfspace" ||
1934 name == "doublespace" || name == "spacing") {
1935 eat_whitespace(p, os, parent_context, false);
1936 // We must begin a new paragraph if not already done
1937 if (! parent_context.atParagraphStart()) {
1938 parent_context.check_end_layout(os);
1939 parent_context.new_paragraph(os);
1941 if (name == "flushleft" || name == "raggedright")
1942 parent_context.add_extra_stuff("\\align left\n");
1943 else if (name == "flushright" || name == "raggedleft")
1944 parent_context.add_extra_stuff("\\align right\n");
1945 else if (name == "center" || name == "centering")
1946 parent_context.add_extra_stuff("\\align center\n");
1947 else if (name == "singlespace")
1948 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1949 else if (name == "onehalfspace") {
1950 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1951 preamble.registerAutomaticallyLoadedPackage("setspace");
1952 } else if (name == "doublespace") {
1953 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1954 preamble.registerAutomaticallyLoadedPackage("setspace");
1955 } else if (name == "spacing") {
1956 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1957 preamble.registerAutomaticallyLoadedPackage("setspace");
1959 parse_text(p, os, FLAG_END, outer, parent_context);
1960 // Just in case the environment is empty
1961 parent_context.extra_stuff.erase();
1962 // We must begin a new paragraph to reset the alignment
1963 parent_context.new_paragraph(os);
1967 // The single '=' is meant here.
1968 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1969 eat_whitespace(p, os, parent_context, false);
1970 Context context(true, parent_context.textclass, newlayout,
1971 parent_context.layout, parent_context.font);
1972 if (parent_context.deeper_paragraph) {
1973 // We are beginning a nested environment after a
1974 // deeper paragraph inside the outer list environment.
1975 // Therefore we don't need to output a "begin deeper".
1976 context.need_end_deeper = true;
1978 parent_context.check_end_layout(os);
1979 if (last_env == name) {
1980 // we need to output a separator since LyX would export
1981 // the two environments as one otherwise (bug 5716)
1982 TeX2LyXDocClass const & textclass(parent_context.textclass);
1983 Context newcontext(true, textclass,
1984 &(textclass.defaultLayout()));
1985 newcontext.check_layout(os);
1986 begin_inset(os, "Separator plain\n");
1988 newcontext.check_end_layout(os);
1990 switch (context.layout->latextype) {
1991 case LATEX_LIST_ENVIRONMENT:
1992 context.add_par_extra_stuff("\\labelwidthstring "
1993 + p.verbatim_item() + '\n');
1996 case LATEX_BIB_ENVIRONMENT:
1997 p.verbatim_item(); // swallow next arg
2003 context.check_deeper(os);
2004 // handle known optional and required arguments
2005 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
2006 // It is impossible to place anything after the environment name,
2007 // but before the first \\item.
2008 if (context.layout->latextype == LATEX_ENVIRONMENT)
2009 output_arguments(os, p, outer, false, false, context,
2010 context.layout->latexargs());
2011 parse_text(p, os, FLAG_END, outer, context);
2012 if (context.layout->latextype == LATEX_ENVIRONMENT)
2013 output_arguments(os, p, outer, false, true, context,
2014 context.layout->postcommandargs());
2015 context.check_end_layout(os);
2016 if (parent_context.deeper_paragraph) {
2017 // We must suppress the "end deeper" because we
2018 // suppressed the "begin deeper" above.
2019 context.need_end_deeper = false;
2021 context.check_end_deeper(os);
2022 parent_context.new_paragraph(os);
2024 if (!preamble.titleLayoutFound())
2025 preamble.titleLayoutFound(newlayout->intitle);
2026 set<string> const & req = newlayout->requires();
2027 set<string>::const_iterator it = req.begin();
2028 set<string>::const_iterator en = req.end();
2029 for (; it != en; ++it)
2030 preamble.registerAutomaticallyLoadedPackage(*it);
2033 // The single '=' is meant here.
2034 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2035 eat_whitespace(p, os, parent_context, false);
2036 parent_context.check_layout(os);
2037 begin_inset(os, "Flex ");
2038 docstring flex_name = newinsetlayout->name();
2039 // FIXME: what do we do if the prefix is not Flex: ?
2040 if (prefixIs(flex_name, from_ascii("Flex:")))
2041 flex_name.erase(0, 5);
2042 os << to_utf8(flex_name) << '\n'
2043 << "status collapsed\n";
2044 if (newinsetlayout->isPassThru()) {
2045 string const arg = p.verbatimEnvironment(name);
2046 Context context(true, parent_context.textclass,
2047 &parent_context.textclass.plainLayout(),
2048 parent_context.layout);
2049 output_ert(os, arg, parent_context);
2051 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2055 else if (name == "appendix") {
2056 // This is no good latex style, but it works and is used in some documents...
2057 eat_whitespace(p, os, parent_context, false);
2058 parent_context.check_end_layout(os);
2059 Context context(true, parent_context.textclass, parent_context.layout,
2060 parent_context.layout, parent_context.font);
2061 context.check_layout(os);
2062 os << "\\start_of_appendix\n";
2063 parse_text(p, os, FLAG_END, outer, context);
2064 context.check_end_layout(os);
2068 else if (known_environments.find(name) != known_environments.end()) {
2069 vector<ArgumentType> arguments = known_environments[name];
2070 // The last "argument" denotes wether we may translate the
2071 // environment contents to LyX
2072 // The default required if no argument is given makes us
2073 // compatible with the reLyXre environment.
2074 ArgumentType contents = arguments.empty() ?
2077 if (!arguments.empty())
2078 arguments.pop_back();
2079 // See comment in parse_unknown_environment()
2080 bool const specialfont =
2081 (parent_context.font != parent_context.normalfont);
2082 bool const new_layout_allowed =
2083 parent_context.new_layout_allowed;
2085 parent_context.new_layout_allowed = false;
2086 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2087 outer, parent_context);
2088 if (contents == verbatim)
2089 output_ert_inset(os, p.ertEnvironment(name),
2092 parse_text_snippet(p, os, FLAG_END, outer,
2094 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2096 parent_context.new_layout_allowed = new_layout_allowed;
2100 parse_unknown_environment(p, name, os, FLAG_END, outer,
2104 active_environments.pop_back();
2108 /// parses a comment and outputs it to \p os.
2109 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2111 LASSERT(t.cat() == catComment, return);
2112 if (!t.cs().empty()) {
2113 context.check_layout(os);
2114 output_comment(p, os, t.cs(), context);
2115 if (p.next_token().cat() == catNewline) {
2116 // A newline after a comment line starts a new
2118 if (context.new_layout_allowed) {
2119 if(!context.atParagraphStart())
2120 // Only start a new paragraph if not already
2121 // done (we might get called recursively)
2122 context.new_paragraph(os);
2124 output_ert_inset(os, "\n", context);
2125 eat_whitespace(p, os, context, true);
2128 // "%\n" combination
2135 * Reads spaces and comments until the first non-space, non-comment token.
2136 * New paragraphs (double newlines or \\par) are handled like simple spaces
2137 * if \p eatParagraph is true.
2138 * Spaces are skipped, but comments are written to \p os.
2140 void eat_whitespace(Parser & p, ostream & os, Context & context,
2144 Token const & t = p.get_token();
2145 if (t.cat() == catComment)
2146 parse_comment(p, os, t, context);
2147 else if ((! eatParagraph && p.isParagraph()) ||
2148 (t.cat() != catSpace && t.cat() != catNewline)) {
2157 * Set a font attribute, parse text and reset the font attribute.
2158 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2159 * \param currentvalue Current value of the attribute. Is set to the new
2160 * value during parsing.
2161 * \param newvalue New value of the attribute
2163 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2164 Context & context, string const & attribute,
2165 string & currentvalue, string const & newvalue)
2167 context.check_layout(os);
2168 string const oldvalue = currentvalue;
2169 currentvalue = newvalue;
2170 os << '\n' << attribute << ' ' << newvalue << "\n";
2171 parse_text_snippet(p, os, flags, outer, context);
2172 context.check_layout(os);
2173 os << '\n' << attribute << ' ' << oldvalue << "\n";
2174 currentvalue = oldvalue;
2178 /// get the arguments of a natbib or jurabib citation command
2179 void get_cite_arguments(Parser & p, bool natbibOrder,
2180 string & before, string & after, bool const qualified = false)
2182 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2184 // text before the citation
2186 // text after the citation
2187 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2189 if (!after.empty()) {
2190 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2191 if (natbibOrder && !before.empty())
2192 swap(before, after);
2197 /// Convert filenames with TeX macros and/or quotes to something LyX
2199 string const normalize_filename(string const & name)
2204 Token const & t = p.get_token();
2205 if (t.cat() != catEscape)
2207 else if (t.cs() == "lyxdot") {
2208 // This is used by LyX for simple dots in relative
2212 } else if (t.cs() == "space") {
2215 } else if (t.cs() == "string") {
2216 // Convert \string" to " and \string~ to ~
2217 Token const & n = p.next_token();
2218 if (n.asInput() != "\"" && n.asInput() != "~")
2223 // Strip quotes. This is a bit complicated (see latex_path()).
2224 string full = os.str();
2225 if (!full.empty() && full[0] == '"') {
2226 string base = removeExtension(full);
2227 string ext = getExtension(full);
2228 if (!base.empty() && base[base.length()-1] == '"')
2231 return addExtension(trim(base, "\""), ext);
2232 if (full[full.length()-1] == '"')
2235 return trim(full, "\"");
2241 /// Convert \p name from TeX convention (relative to master file) to LyX
2242 /// convention (relative to .lyx file) if it is relative
2243 void fix_child_filename(string & name)
2245 string const absMasterTeX = getMasterFilePath(true);
2246 bool const isabs = FileName::isAbsolute(name);
2247 // convert from "relative to .tex master" to absolute original path
2249 name = makeAbsPath(name, absMasterTeX).absFileName();
2250 bool copyfile = copyFiles();
2251 string const absParentLyX = getParentFilePath(false);
2254 // convert from absolute original path to "relative to master file"
2255 string const rel = to_utf8(makeRelPath(from_utf8(name),
2256 from_utf8(absMasterTeX)));
2257 // re-interpret "relative to .tex file" as "relative to .lyx file"
2258 // (is different if the master .lyx file resides in a
2259 // different path than the master .tex file)
2260 string const absMasterLyX = getMasterFilePath(false);
2261 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2262 // Do not copy if the new path is impossible to create. Example:
2263 // absMasterTeX = "/foo/bar/"
2264 // absMasterLyX = "/bar/"
2265 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2266 if (contains(name, "/../"))
2273 // convert from absolute original path to
2274 // "relative to .lyx file"
2275 name = to_utf8(makeRelPath(from_utf8(abs),
2276 from_utf8(absParentLyX)));
2280 // convert from absolute original path to "relative to .lyx file"
2281 name = to_utf8(makeRelPath(from_utf8(name),
2282 from_utf8(absParentLyX)));
2287 void copy_file(FileName const & src, string dstname)
2291 string const absParent = getParentFilePath(false);
2293 if (FileName::isAbsolute(dstname))
2294 dst = FileName(dstname);
2296 dst = makeAbsPath(dstname, absParent);
2297 FileName const srcpath = src.onlyPath();
2298 FileName const dstpath = dst.onlyPath();
2299 if (equivalent(srcpath, dstpath))
2301 if (!dstpath.isDirectory()) {
2302 if (!dstpath.createPath()) {
2303 cerr << "Warning: Could not create directory for file `"
2304 << dst.absFileName() << "´." << endl;
2308 if (dst.isReadableFile()) {
2309 if (overwriteFiles())
2310 cerr << "Warning: Overwriting existing file `"
2311 << dst.absFileName() << "´." << endl;
2313 cerr << "Warning: Not overwriting existing file `"
2314 << dst.absFileName() << "´." << endl;
2318 if (!src.copyTo(dst))
2319 cerr << "Warning: Could not copy file `" << src.absFileName()
2320 << "´ to `" << dst.absFileName() << "´." << endl;
2324 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2325 bool parse_chunk(Parser & p, ostream & os, Context & context)
2327 // check whether a chunk is possible here.
2328 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2334 // read the parameters
2335 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2336 if (!params.first) {
2341 Parser::Arg const code = p.verbatimStuff("\n@");
2346 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2347 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2351 // The last newline read is important for paragraph handling
2355 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2356 // We must have a valid layout before outputting the Chunk inset.
2357 context.check_layout(os);
2358 Context chunkcontext(true, context.textclass);
2359 chunkcontext.layout = &context.textclass.plainLayout();
2360 begin_inset(os, "Flex Chunk");
2361 os << "\nstatus open\n";
2362 if (!params.second.empty()) {
2363 chunkcontext.check_layout(os);
2364 Context paramscontext(true, context.textclass);
2365 paramscontext.layout = &context.textclass.plainLayout();
2366 begin_inset(os, "Argument 1");
2367 os << "\nstatus open\n";
2368 output_ert(os, params.second, paramscontext);
2371 output_ert(os, code.second, chunkcontext);
2379 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2380 bool is_macro(Parser & p)
2382 Token first = p.curr_token();
2383 if (first.cat() != catEscape || !p.good())
2385 if (first.cs() == "def")
2387 if (first.cs() != "global" && first.cs() != "long")
2389 Token second = p.get_token();
2391 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2392 second.cat() == catNewline || second.cat() == catComment)) {
2393 second = p.get_token();
2396 bool secondvalid = second.cat() == catEscape;
2398 bool thirdvalid = false;
2399 if (p.good() && first.cs() == "global" && secondvalid &&
2400 second.cs() == "long") {
2401 third = p.get_token();
2403 while (p.good() && !p.isParagraph() &&
2404 (third.cat() == catSpace ||
2405 third.cat() == catNewline ||
2406 third.cat() == catComment)) {
2407 third = p.get_token();
2410 thirdvalid = third.cat() == catEscape;
2412 for (int i = 0; i < pos; ++i)
2417 return (first.cs() == "global" || first.cs() == "long") &&
2418 second.cs() == "def";
2419 return first.cs() == "global" && second.cs() == "long" &&
2420 third.cs() == "def";
2424 /// Parse a macro definition (assumes that is_macro() returned true)
2425 void parse_macro(Parser & p, ostream & os, Context & context)
2427 context.check_layout(os);
2428 Token first = p.curr_token();
2431 string command = first.asInput();
2432 if (first.cs() != "def") {
2434 eat_whitespace(p, os, context, false);
2435 second = p.curr_token();
2436 command += second.asInput();
2437 if (second.cs() != "def") {
2439 eat_whitespace(p, os, context, false);
2440 third = p.curr_token();
2441 command += third.asInput();
2444 eat_whitespace(p, os, context, false);
2445 string const name = p.get_token().cs();
2446 eat_whitespace(p, os, context, false);
2452 while (p.next_token().cat() != catBegin) {
2453 if (p.next_token().cat() == catParameter) {
2458 // followed by number?
2459 if (p.next_token().cat() == catOther) {
2460 string s = p.get_token().asInput();
2462 // number = current arity + 1?
2463 if (s.size() == 1 && s[0] == arity + '0' + 1)
2468 paramtext += p.get_token().cs();
2470 paramtext += p.get_token().cs();
2475 // only output simple (i.e. compatible) macro as FormulaMacros
2476 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2478 context.check_layout(os);
2479 begin_inset(os, "FormulaMacro");
2480 os << "\n\\def" << ert;
2483 output_ert_inset(os, command + ert, context);
2487 void registerExternalTemplatePackages(string const & name)
2489 external::TemplateManager const & etm = external::TemplateManager::get();
2490 external::Template const * const et = etm.getTemplateByName(name);
2493 external::Template::Formats::const_iterator cit = et->formats.end();
2495 cit = et->formats.find("PDFLaTeX");
2496 if (cit == et->formats.end())
2497 // If the template has not specified a PDFLaTeX output,
2498 // we try the LaTeX format.
2499 cit = et->formats.find("LaTeX");
2500 if (cit == et->formats.end())
2502 vector<string>::const_iterator qit = cit->second.requirements.begin();
2503 vector<string>::const_iterator qend = cit->second.requirements.end();
2504 for (; qit != qend; ++qit)
2505 preamble.registerAutomaticallyLoadedPackage(*qit);
2508 } // anonymous namespace
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() == "includegraphics") {
3271 bool const clip = p.next_token().asInput() == "*";
3274 string const arg = p.getArg('[', ']');
3275 map<string, string> opts;
3276 vector<string> keys;
3277 split_map(arg, opts, keys);
3279 opts["clip"] = string();
3280 string name = normalize_filename(p.verbatim_item());
3282 string const path = getMasterFilePath(true);
3283 // We want to preserve relative / absolute filenames,
3284 // therefore path is only used for testing
3285 if (!makeAbsPath(name, path).exists()) {
3286 // The file extension is probably missing.
3287 // Now try to find it out.
3288 string const dvips_name =
3289 find_file(name, path,
3290 known_dvips_graphics_formats);
3291 string const pdftex_name =
3292 find_file(name, path,
3293 known_pdftex_graphics_formats);
3294 if (!dvips_name.empty()) {
3295 if (!pdftex_name.empty()) {
3296 cerr << "This file contains the "
3298 "\"\\includegraphics{"
3300 "However, files\n\""
3301 << dvips_name << "\" and\n\""
3302 << pdftex_name << "\"\n"
3303 "both exist, so I had to make a "
3304 "choice and took the first one.\n"
3305 "Please move the unwanted one "
3306 "someplace else and try again\n"
3307 "if my choice was wrong."
3311 } else if (!pdftex_name.empty()) {
3317 FileName const absname = makeAbsPath(name, path);
3318 if (absname.exists()) {
3319 fix_child_filename(name);
3320 copy_file(absname, name);
3322 cerr << "Warning: Could not find graphics file '"
3323 << name << "'." << endl;
3325 context.check_layout(os);
3326 begin_inset(os, "Graphics ");
3327 os << "\n\tfilename " << name << '\n';
3328 if (opts.find("width") != opts.end())
3330 << translate_len(opts["width"]) << '\n';
3331 if (opts.find("height") != opts.end())
3333 << translate_len(opts["height"]) << '\n';
3334 if (opts.find("scale") != opts.end()) {
3335 istringstream iss(opts["scale"]);
3339 os << "\tscale " << val << '\n';
3341 if (opts.find("angle") != opts.end()) {
3342 os << "\trotateAngle "
3343 << opts["angle"] << '\n';
3344 vector<string>::const_iterator a =
3345 find(keys.begin(), keys.end(), "angle");
3346 vector<string>::const_iterator s =
3347 find(keys.begin(), keys.end(), "width");
3348 if (s == keys.end())
3349 s = find(keys.begin(), keys.end(), "height");
3350 if (s == keys.end())
3351 s = find(keys.begin(), keys.end(), "scale");
3352 if (s != keys.end() && distance(s, a) > 0)
3353 os << "\tscaleBeforeRotation\n";
3355 if (opts.find("origin") != opts.end()) {
3357 string const opt = opts["origin"];
3358 if (opt.find('l') != string::npos) ss << "left";
3359 if (opt.find('r') != string::npos) ss << "right";
3360 if (opt.find('c') != string::npos) ss << "center";
3361 if (opt.find('t') != string::npos) ss << "Top";
3362 if (opt.find('b') != string::npos) ss << "Bottom";
3363 if (opt.find('B') != string::npos) ss << "Baseline";
3364 if (!ss.str().empty())
3365 os << "\trotateOrigin " << ss.str() << '\n';
3367 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3369 if (opts.find("keepaspectratio") != opts.end())
3370 os << "\tkeepAspectRatio\n";
3371 if (opts.find("clip") != opts.end())
3373 if (opts.find("draft") != opts.end())
3375 if (opts.find("bb") != opts.end())
3376 os << "\tBoundingBox "
3377 << opts["bb"] << '\n';
3378 int numberOfbbOptions = 0;
3379 if (opts.find("bbllx") != opts.end())
3380 numberOfbbOptions++;
3381 if (opts.find("bblly") != opts.end())
3382 numberOfbbOptions++;
3383 if (opts.find("bburx") != opts.end())
3384 numberOfbbOptions++;
3385 if (opts.find("bbury") != opts.end())
3386 numberOfbbOptions++;
3387 if (numberOfbbOptions == 4)
3388 os << "\tBoundingBox "
3389 << opts["bbllx"] << " " << opts["bblly"] << " "
3390 << opts["bburx"] << " " << opts["bbury"] << '\n';
3391 else if (numberOfbbOptions > 0)
3392 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3393 numberOfbbOptions = 0;
3394 if (opts.find("natwidth") != opts.end())
3395 numberOfbbOptions++;
3396 if (opts.find("natheight") != opts.end())
3397 numberOfbbOptions++;
3398 if (numberOfbbOptions == 2)
3399 os << "\tBoundingBox 0bp 0bp "
3400 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3401 else if (numberOfbbOptions > 0)
3402 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3403 ostringstream special;
3404 if (opts.find("hiresbb") != opts.end())
3405 special << "hiresbb,";
3406 if (opts.find("trim") != opts.end())
3408 if (opts.find("viewport") != opts.end())
3409 special << "viewport=" << opts["viewport"] << ',';
3410 if (opts.find("totalheight") != opts.end())
3411 special << "totalheight=" << opts["totalheight"] << ',';
3412 if (opts.find("type") != opts.end())
3413 special << "type=" << opts["type"] << ',';
3414 if (opts.find("ext") != opts.end())
3415 special << "ext=" << opts["ext"] << ',';
3416 if (opts.find("read") != opts.end())
3417 special << "read=" << opts["read"] << ',';
3418 if (opts.find("command") != opts.end())
3419 special << "command=" << opts["command"] << ',';
3420 string s_special = special.str();
3421 if (!s_special.empty()) {
3422 // We had special arguments. Remove the trailing ','.
3423 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3425 // TODO: Handle the unknown settings better.
3426 // Warn about invalid options.
3427 // Check whether some option was given twice.
3429 preamble.registerAutomaticallyLoadedPackage("graphicx");
3433 if (t.cs() == "footnote" ||
3434 (t.cs() == "thanks" && context.layout->intitle)) {
3436 context.check_layout(os);
3437 begin_inset(os, "Foot\n");
3438 os << "status collapsed\n\n";
3439 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3444 if (t.cs() == "marginpar") {
3446 context.check_layout(os);
3447 begin_inset(os, "Marginal\n");
3448 os << "status collapsed\n\n";
3449 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3454 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3455 bool const use_minted = t.cs() == "mintinline";
3457 parse_listings(p, os, context, true, use_minted);
3461 if (t.cs() == "ensuremath") {
3463 context.check_layout(os);
3464 string const s = p.verbatim_item();
3465 //FIXME: this never triggers in UTF8
3466 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3469 output_ert_inset(os, "\\ensuremath{" + s + "}",
3474 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3475 if (preamble.titleLayoutFound()) {
3477 skip_spaces_braces(p);
3479 output_ert_inset(os, t.asInput(), context);
3483 if (t.cs() == "tableofcontents"
3484 || t.cs() == "lstlistoflistings"
3485 || t.cs() == "listoflistings") {
3486 string name = t.cs();
3487 if (preamble.minted() && name == "listoflistings")
3488 name.insert(0, "lst");
3489 context.check_layout(os);
3490 begin_command_inset(os, "toc", name);
3492 skip_spaces_braces(p);
3493 if (name == "lstlistoflistings") {
3494 if (preamble.minted())
3495 preamble.registerAutomaticallyLoadedPackage("minted");
3497 preamble.registerAutomaticallyLoadedPackage("listings");
3502 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3503 context.check_layout(os);
3504 if (t.cs() == "listoffigures")
3505 begin_inset(os, "FloatList figure\n");
3507 begin_inset(os, "FloatList table\n");
3509 skip_spaces_braces(p);
3513 if (t.cs() == "listof") {
3514 p.skip_spaces(true);
3515 string const name = p.get_token().cs();
3516 if (context.textclass.floats().typeExist(name)) {
3517 context.check_layout(os);
3518 begin_inset(os, "FloatList ");
3521 p.get_token(); // swallow second arg
3523 output_ert_inset(os, "\\listof{" + name + "}", context);
3527 if ((where = is_known(t.cs(), known_text_font_families))) {
3528 parse_text_attributes(p, os, FLAG_ITEM, outer,
3529 context, "\\family", context.font.family,
3530 known_coded_font_families[where - known_text_font_families]);
3534 if ((where = is_known(t.cs(), known_text_font_series))) {
3535 parse_text_attributes(p, os, FLAG_ITEM, outer,
3536 context, "\\series", context.font.series,
3537 known_coded_font_series[where - known_text_font_series]);
3541 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3542 parse_text_attributes(p, os, FLAG_ITEM, outer,
3543 context, "\\shape", context.font.shape,
3544 known_coded_font_shapes[where - known_text_font_shapes]);
3548 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3549 context.check_layout(os);
3550 TeXFont oldFont = context.font;
3551 context.font.init();
3552 context.font.size = oldFont.size;
3553 os << "\n\\family " << context.font.family << "\n";
3554 os << "\n\\series " << context.font.series << "\n";
3555 os << "\n\\shape " << context.font.shape << "\n";
3556 if (t.cs() == "textnormal") {
3557 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3558 output_font_change(os, context.font, oldFont);
3559 context.font = oldFont;
3561 eat_whitespace(p, os, context, false);
3565 if (t.cs() == "textcolor") {
3566 // scheme is \textcolor{color name}{text}
3567 string const color = p.verbatim_item();
3568 // we support the predefined colors of the color and the xcolor package
3569 if (color == "black" || color == "blue" || color == "cyan"
3570 || color == "green" || color == "magenta" || color == "red"
3571 || color == "white" || color == "yellow") {
3572 context.check_layout(os);
3573 os << "\n\\color " << color << "\n";
3574 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3575 context.check_layout(os);
3576 os << "\n\\color inherit\n";
3577 preamble.registerAutomaticallyLoadedPackage("color");
3578 } else if (color == "brown" || color == "darkgray" || color == "gray"
3579 || color == "lightgray" || color == "lime" || color == "olive"
3580 || color == "orange" || color == "pink" || color == "purple"
3581 || color == "teal" || color == "violet") {
3582 context.check_layout(os);
3583 os << "\n\\color " << color << "\n";
3584 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3585 context.check_layout(os);
3586 os << "\n\\color inherit\n";
3587 preamble.registerAutomaticallyLoadedPackage("xcolor");
3589 // for custom defined colors
3590 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3594 if (t.cs() == "underbar" || t.cs() == "uline") {
3595 // \underbar is not 100% correct (LyX outputs \uline
3596 // of ulem.sty). The difference is that \ulem allows
3597 // line breaks, and \underbar does not.
3598 // Do NOT handle \underline.
3599 // \underbar cuts through y, g, q, p etc.,
3600 // \underline does not.
3601 context.check_layout(os);
3602 os << "\n\\bar under\n";
3603 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3604 context.check_layout(os);
3605 os << "\n\\bar default\n";
3606 preamble.registerAutomaticallyLoadedPackage("ulem");
3610 if (t.cs() == "sout") {
3611 context.check_layout(os);
3612 os << "\n\\strikeout on\n";
3613 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3614 context.check_layout(os);
3615 os << "\n\\strikeout default\n";
3616 preamble.registerAutomaticallyLoadedPackage("ulem");
3620 if (t.cs() == "uuline" || t.cs() == "uwave"
3621 || t.cs() == "emph" || t.cs() == "noun"
3622 || t.cs() == "xout") {
3623 context.check_layout(os);
3624 os << "\n\\" << t.cs() << " on\n";
3625 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3626 context.check_layout(os);
3627 os << "\n\\" << t.cs() << " default\n";
3628 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3629 preamble.registerAutomaticallyLoadedPackage("ulem");
3633 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3634 context.check_layout(os);
3635 string name = p.getArg('{', '}');
3636 string localtime = p.getArg('{', '}');
3637 preamble.registerAuthor(name);
3638 Author const & author = preamble.getAuthor(name);
3639 // from_asctime_utc() will fail if LyX decides to output the
3640 // time in the text language.
3641 time_t ptime = from_asctime_utc(localtime);
3642 if (ptime == static_cast<time_t>(-1)) {
3643 cerr << "Warning: Could not parse time `" << localtime
3644 << "´ for change tracking, using current time instead.\n";
3645 ptime = current_time();
3647 if (t.cs() == "lyxadded")
3648 os << "\n\\change_inserted ";
3650 os << "\n\\change_deleted ";
3651 os << author.bufferId() << ' ' << ptime << '\n';
3652 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3653 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3654 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3655 LaTeXPackages::isAvailable("xcolor");
3656 // No need to test for luatex, since luatex comes in
3657 // two flavours (dvi and pdf), like latex, and those
3658 // are detected by pdflatex.
3659 if (pdflatex || xetex) {
3661 preamble.registerAutomaticallyLoadedPackage("ulem");
3662 preamble.registerAutomaticallyLoadedPackage("xcolor");
3663 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3667 preamble.registerAutomaticallyLoadedPackage("dvipost");
3668 } else if (xcolorulem) {
3669 preamble.registerAutomaticallyLoadedPackage("ulem");
3670 preamble.registerAutomaticallyLoadedPackage("xcolor");
3676 if (t.cs() == "textipa") {
3677 context.check_layout(os);
3678 begin_inset(os, "IPA\n");
3679 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3680 context.merging_hyphens_allowed = false;
3681 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3682 context.merging_hyphens_allowed = merging_hyphens_allowed;
3684 preamble.registerAutomaticallyLoadedPackage("tipa");
3685 preamble.registerAutomaticallyLoadedPackage("tipx");
3689 if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3690 context.check_layout(os);
3691 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3692 os << "status open\n";
3693 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3699 if (t.cs() == "textvertline") {
3700 // FIXME: This is not correct, \textvertline is higher than |
3706 if (t.cs() == "tone" ) {
3707 context.check_layout(os);
3708 // register the tone package
3709 preamble.registerAutomaticallyLoadedPackage("tone");
3710 string content = trimSpaceAndEol(p.verbatim_item());
3711 string command = t.asInput() + "{" + content + "}";
3712 // some tones can be detected by unicodesymbols, some need special code
3713 if (is_known(content, known_tones)) {
3714 os << "\\IPAChar " << command << "\n";
3717 // try to see whether the string is in unicodesymbols
3721 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3722 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3723 termination, rem, &req);
3727 output_ert_inset(os, to_utf8(rem), context);
3728 for (set<string>::const_iterator it = req.begin();
3729 it != req.end(); ++it)
3730 preamble.registerAutomaticallyLoadedPackage(*it);
3732 // we did not find a non-ert version
3733 output_ert_inset(os, command, context);
3737 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3738 t.cs() == "vphantom") {
3739 context.check_layout(os);
3740 if (t.cs() == "phantom")
3741 begin_inset(os, "Phantom Phantom\n");
3742 if (t.cs() == "hphantom")
3743 begin_inset(os, "Phantom HPhantom\n");
3744 if (t.cs() == "vphantom")
3745 begin_inset(os, "Phantom VPhantom\n");
3746 os << "status open\n";
3747 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3753 if (t.cs() == "href") {
3754 context.check_layout(os);
3755 string target = convert_literate_command_inset_arg(p.verbatim_item());
3756 string name = p.verbatim_item();
3757 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3758 bool const literal = !nm.first;
3759 name = literal ? subst(name, "\n", " ") : nm.second;
3760 string lit = literal ? "\"true\"" : "\"false\"";
3762 size_t i = target.find(':');
3763 if (i != string::npos) {
3764 type = target.substr(0, i + 1);
3765 if (type == "mailto:" || type == "file:")
3766 target = target.substr(i + 1);
3767 // handle the case that name is equal to target, except of "http(s)://"
3768 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3771 begin_command_inset(os, "href", "href");
3773 os << "name \"" << name << "\"\n";
3774 os << "target \"" << target << "\"\n";
3775 if (type == "mailto:" || type == "file:")
3776 os << "type \"" << type << "\"\n";
3777 os << "literal " << lit << "\n";
3779 skip_spaces_braces(p);
3783 if (t.cs() == "lyxline") {
3784 // swallow size argument (it is not used anyway)
3786 if (!context.atParagraphStart()) {
3787 // so our line is in the middle of a paragraph
3788 // we need to add a new line, lest this line
3789 // follow the other content on that line and
3790 // run off the side of the page
3791 // FIXME: This may create an empty paragraph,
3792 // but without that it would not be
3793 // possible to set noindent below.
3794 // Fortunately LaTeX does not care
3795 // about the empty paragraph.
3796 context.new_paragraph(os);
3798 if (preamble.indentParagraphs()) {
3799 // we need to unindent, lest the line be too long
3800 context.add_par_extra_stuff("\\noindent\n");
3802 context.check_layout(os);
3803 begin_command_inset(os, "line", "rule");
3804 os << "offset \"0.5ex\"\n"
3805 "width \"100line%\"\n"
3811 if (t.cs() == "rule") {
3812 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3813 string const width = p.getArg('{', '}');
3814 string const thickness = p.getArg('{', '}');
3815 context.check_layout(os);
3816 begin_command_inset(os, "line", "rule");
3817 if (!offset.empty())
3818 os << "offset \"" << translate_len(offset) << "\"\n";
3819 os << "width \"" << translate_len(width) << "\"\n"
3820 "height \"" << translate_len(thickness) << "\"\n";
3825 // handle refstyle first to catch \eqref which can also occur
3826 // without refstyle. Only recognize these commands if
3827 // refstyle.sty was found in the preamble (otherwise \eqref
3828 // and user defined ref commands could be misdetected).
3829 if ((where = is_known(t.cs(), known_refstyle_commands))
3830 && preamble.refstyle()) {
3831 context.check_layout(os);
3832 begin_command_inset(os, "ref", "formatted");
3833 os << "reference \"";
3834 os << known_refstyle_prefixes[where - known_refstyle_commands]
3836 os << convert_literate_command_inset_arg(p.verbatim_item())
3838 os << "plural \"false\"\n";
3839 os << "caps \"false\"\n";
3840 os << "noprefix \"false\"\n";
3842 preamble.registerAutomaticallyLoadedPackage("refstyle");
3846 // if refstyle is used, we must not convert \prettyref to a
3847 // formatted reference, since that would result in a refstyle command.
3848 if ((where = is_known(t.cs(), known_ref_commands)) &&
3849 (t.cs() != "prettyref" || !preamble.refstyle())) {
3850 string const opt = p.getOpt();
3852 context.check_layout(os);
3853 begin_command_inset(os, "ref",
3854 known_coded_ref_commands[where - known_ref_commands]);
3855 os << "reference \""
3856 << convert_literate_command_inset_arg(p.verbatim_item())
3858 os << "plural \"false\"\n";
3859 os << "caps \"false\"\n";
3860 os << "noprefix \"false\"\n";
3862 if (t.cs() == "vref" || t.cs() == "vpageref")
3863 preamble.registerAutomaticallyLoadedPackage("varioref");
3864 else if (t.cs() == "prettyref")
3865 preamble.registerAutomaticallyLoadedPackage("prettyref");
3867 // LyX does not yet support optional arguments of ref commands
3868 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3869 p.verbatim_item() + '}', context);
3875 is_known(t.cs(), known_natbib_commands) &&
3876 ((t.cs() != "citefullauthor" &&
3877 t.cs() != "citeyear" &&
3878 t.cs() != "citeyearpar") ||
3879 p.next_token().asInput() != "*")) {
3880 context.check_layout(os);
3881 string command = t.cs();
3882 if (p.next_token().asInput() == "*") {
3886 if (command == "citefullauthor")
3887 // alternative name for "\\citeauthor*"
3888 command = "citeauthor*";
3890 // text before the citation
3892 // text after the citation
3894 get_cite_arguments(p, true, before, after);
3896 if (command == "cite") {
3897 // \cite without optional argument means
3898 // \citet, \cite with at least one optional
3899 // argument means \citep.
3900 if (before.empty() && after.empty())
3905 if (before.empty() && after == "[]")
3906 // avoid \citet[]{a}
3908 else if (before == "[]" && after == "[]") {
3909 // avoid \citet[][]{a}
3913 bool literal = false;
3914 pair<bool, string> aft;
3915 pair<bool, string> bef;
3916 // remove the brackets around after and before
3917 if (!after.empty()) {
3919 after.erase(after.length() - 1, 1);
3920 aft = convert_latexed_command_inset_arg(after);
3921 literal = !aft.first;
3922 after = literal ? subst(after, "\n", " ") : aft.second;
3924 if (!before.empty()) {
3926 before.erase(before.length() - 1, 1);
3927 bef = convert_latexed_command_inset_arg(after);
3928 literal |= !bef.first;
3929 before = literal ? subst(before, "\n", " ") : bef.second;
3930 if (literal && !after.empty())
3931 after = subst(after, "\n", " ");
3933 string lit = literal ? "\"true\"" : "\"false\"";
3934 begin_command_inset(os, "citation", command);
3935 os << "after " << '"' << after << '"' << "\n";
3936 os << "before " << '"' << before << '"' << "\n";
3938 << convert_literate_command_inset_arg(p.verbatim_item())
3940 << "literal " << lit << "\n";
3942 // Need to set the cite engine if natbib is loaded by
3943 // the document class directly
3944 if (preamble.citeEngine() == "basic")
3945 preamble.citeEngine("natbib");
3950 && is_known(t.cs(), known_biblatex_commands)
3951 && ((t.cs() == "cite"
3952 || t.cs() == "citeauthor"
3953 || t.cs() == "Citeauthor"
3954 || t.cs() == "parencite"
3955 || t.cs() == "citetitle")
3956 || p.next_token().asInput() != "*"))
3957 || (use_biblatex_natbib
3958 && (is_known(t.cs(), known_biblatex_commands)
3959 || is_known(t.cs(), known_natbib_commands))
3960 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3961 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3962 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3963 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3964 || t.cs() == "parencite" || t.cs() == "citetitle")
3965 || p.next_token().asInput() != "*"))){
3966 context.check_layout(os);
3967 string command = t.cs();
3968 if (p.next_token().asInput() == "*") {
3973 bool const qualified = suffixIs(command, "s");
3975 command = rtrim(command, "s");
3977 // text before the citation
3979 // text after the citation
3981 get_cite_arguments(p, true, before, after, qualified);
3983 // These use natbib cmd names in LyX
3984 // for inter-citeengine compativility
3985 if (command == "citeyear")
3986 command = "citebyear";
3987 else if (command == "cite*")
3988 command = "citeyear";
3989 else if (command == "textcite")
3991 else if (command == "Textcite")
3993 else if (command == "parencite")
3995 else if (command == "Parencite")
3997 else if (command == "parencite*")
3998 command = "citeyearpar";
3999 else if (command == "smartcite")
4000 command = "footcite";
4001 else if (command == "Smartcite")
4002 command = "Footcite";
4004 string const emptyarg = qualified ? "()" : "[]";
4005 if (before.empty() && after == emptyarg)
4008 else if (before == emptyarg && after == emptyarg) {
4009 // avoid \cite[][]{a}
4013 bool literal = false;
4014 pair<bool, string> aft;
4015 pair<bool, string> bef;
4016 // remove the brackets around after and before
4017 if (!after.empty()) {
4019 after.erase(after.length() - 1, 1);
4020 aft = convert_latexed_command_inset_arg(after);
4021 literal = !aft.first;
4022 after = literal ? subst(after, "\n", " ") : aft.second;
4024 if (!before.empty()) {
4026 before.erase(before.length() - 1, 1);
4027 bef = convert_latexed_command_inset_arg(after);
4028 literal |= !bef.first;
4029 before = literal ? subst(before, "\n", " ") : bef.second;
4031 string keys, pretextlist, posttextlist;
4033 map<string, string> pres, posts, preslit, postslit;
4034 vector<string> lkeys;
4035 // text before the citation
4036 string lbefore, lbeforelit;
4037 // text after the citation
4038 string lafter, lafterlit;
4040 pair<bool, string> laft, lbef;
4042 get_cite_arguments(p, true, lbefore, lafter);
4043 // remove the brackets around after and before
4044 if (!lafter.empty()) {
4046 lafter.erase(lafter.length() - 1, 1);
4047 laft = convert_latexed_command_inset_arg(lafter);
4048 literal |= !laft.first;
4049 lafter = laft.second;
4050 lafterlit = subst(lbefore, "\n", " ");
4052 if (!lbefore.empty()) {
4053 lbefore.erase(0, 1);
4054 lbefore.erase(lbefore.length() - 1, 1);
4055 lbef = convert_latexed_command_inset_arg(lbefore);
4056 literal |= !lbef.first;
4057 lbefore = lbef.second;
4058 lbeforelit = subst(lbefore, "\n", " ");
4060 if (lbefore.empty() && lafter == "[]") {
4065 else if (lbefore == "[]" && lafter == "[]") {
4066 // avoid \cite[][]{a}
4072 lkey = p.getArg('{', '}');
4075 if (!lbefore.empty()) {
4076 pres.insert(make_pair(lkey, lbefore));
4077 preslit.insert(make_pair(lkey, lbeforelit));
4079 if (!lafter.empty()) {
4080 posts.insert(make_pair(lkey, lafter));
4081 postslit.insert(make_pair(lkey, lafterlit));
4083 lkeys.push_back(lkey);
4085 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4090 for (auto const & ptl : pres) {
4091 if (!pretextlist.empty())
4092 pretextlist += '\t';
4093 pretextlist += ptl.first + " " + ptl.second;
4095 for (auto const & potl : posts) {
4096 if (!posttextlist.empty())
4097 posttextlist += '\t';
4098 posttextlist += potl.first + " " + potl.second;
4101 keys = convert_literate_command_inset_arg(p.verbatim_item());
4104 after = subst(after, "\n", " ");
4105 if (!before.empty())
4106 before = subst(after, "\n", " ");
4108 string lit = literal ? "\"true\"" : "\"false\"";
4109 begin_command_inset(os, "citation", command);
4110 os << "after " << '"' << after << '"' << "\n";
4111 os << "before " << '"' << before << '"' << "\n";
4115 if (!pretextlist.empty())
4116 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4117 if (!posttextlist.empty())
4118 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4119 os << "literal " << lit << "\n";
4121 // Need to set the cite engine if biblatex is loaded by
4122 // the document class directly
4123 if (preamble.citeEngine() == "basic")
4124 use_biblatex_natbib ?
4125 preamble.citeEngine("biblatex-natbib")
4126 : preamble.citeEngine("biblatex");
4131 is_known(t.cs(), known_jurabib_commands) &&
4132 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4133 context.check_layout(os);
4134 string command = t.cs();
4135 if (p.next_token().asInput() == "*") {
4139 char argumentOrder = '\0';
4140 vector<string> const options =
4141 preamble.getPackageOptions("jurabib");
4142 if (find(options.begin(), options.end(),
4143 "natbiborder") != options.end())
4144 argumentOrder = 'n';
4145 else if (find(options.begin(), options.end(),
4146 "jurabiborder") != options.end())
4147 argumentOrder = 'j';
4149 // text before the citation
4151 // text after the citation
4153 get_cite_arguments(p, argumentOrder != 'j', before, after);
4155 string const citation = p.verbatim_item();
4156 if (!before.empty() && argumentOrder == '\0') {
4157 cerr << "Warning: Assuming argument order "
4158 "of jurabib version 0.6 for\n'"
4159 << command << before << after << '{'
4160 << citation << "}'.\n"
4161 "Add 'jurabiborder' to the jurabib "
4162 "package options if you used an\n"
4163 "earlier jurabib version." << endl;
4165 bool literal = false;
4166 pair<bool, string> aft;
4167 pair<bool, string> bef;
4168 // remove the brackets around after and before
4169 if (!after.empty()) {
4171 after.erase(after.length() - 1, 1);
4172 aft = convert_latexed_command_inset_arg(after);
4173 literal = !aft.first;
4174 after = literal ? subst(after, "\n", " ") : aft.second;
4176 if (!before.empty()) {
4178 before.erase(before.length() - 1, 1);
4179 bef = convert_latexed_command_inset_arg(after);
4180 literal |= !bef.first;
4181 before = literal ? subst(before, "\n", " ") : bef.second;
4182 if (literal && !after.empty())
4183 after = subst(after, "\n", " ");
4185 string lit = literal ? "\"true\"" : "\"false\"";
4186 begin_command_inset(os, "citation", command);
4187 os << "after " << '"' << after << "\"\n"
4188 << "before " << '"' << before << "\"\n"
4189 << "key " << '"' << citation << "\"\n"
4190 << "literal " << lit << "\n";
4192 // Need to set the cite engine if jurabib is loaded by
4193 // the document class directly
4194 if (preamble.citeEngine() == "basic")
4195 preamble.citeEngine("jurabib");
4199 if (t.cs() == "cite"
4200 || t.cs() == "nocite") {
4201 context.check_layout(os);
4202 string after = p.getArg('[', ']');
4203 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4204 bool const literal = !aft.first;
4205 after = literal ? subst(after, "\n", " ") : aft.second;
4206 string lit = literal ? "\"true\"" : "\"false\"";
4207 string key = convert_literate_command_inset_arg(p.verbatim_item());
4208 // store the case that it is "\nocite{*}" to use it later for
4211 begin_command_inset(os, "citation", t.cs());
4212 os << "after " << '"' << after << "\"\n"
4213 << "key " << '"' << key << "\"\n"
4214 << "literal " << lit << "\n";
4216 } else if (t.cs() == "nocite")
4221 if (t.cs() == "index" ||
4222 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4223 context.check_layout(os);
4224 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4225 p.getArg('[', ']') : "";
4226 string const kind = arg.empty() ? "idx" : arg;
4227 begin_inset(os, "Index ");
4228 os << kind << "\nstatus collapsed\n";
4229 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4232 preamble.registerAutomaticallyLoadedPackage("splitidx");
4236 if (t.cs() == "nomenclature") {
4237 context.check_layout(os);
4238 begin_command_inset(os, "nomenclature", "nomenclature");
4239 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4240 if (!prefix.empty())
4241 os << "prefix " << '"' << prefix << '"' << "\n";
4242 string symbol = p.verbatim_item();
4243 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4244 bool literal = !sym.first;
4245 string description = p.verbatim_item();
4246 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4247 literal |= !desc.first;
4249 symbol = subst(symbol, "\n", " ");
4250 description = subst(description, "\n", " ");
4252 symbol = sym.second;
4253 description = desc.second;
4255 string lit = literal ? "\"true\"" : "\"false\"";
4256 os << "symbol " << '"' << symbol;
4257 os << "\"\ndescription \""
4258 << description << "\"\n"
4259 << "literal " << lit << "\n";
4261 preamble.registerAutomaticallyLoadedPackage("nomencl");
4265 if (t.cs() == "label") {
4266 context.check_layout(os);
4267 begin_command_inset(os, "label", "label");
4269 << convert_literate_command_inset_arg(p.verbatim_item())
4275 if (t.cs() == "lyxmintcaption") {
4276 string const pos = p.getArg('[', ']');
4278 string const caption =
4279 parse_text_snippet(p, FLAG_ITEM, false,
4281 minted_nonfloat_caption = "[t]" + caption;
4283 // We already got the caption at the bottom,
4284 // so simply skip it.
4285 parse_text_snippet(p, FLAG_ITEM, false, context);
4290 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4291 context.check_layout(os);
4292 string commandname = t.cs();
4294 if (p.next_token().asInput() == "*") {
4299 begin_command_inset(os, "index_print", commandname);
4300 string const indexname = p.getArg('[', ']');
4302 if (indexname.empty())
4303 os << "type \"idx\"\n";
4305 os << "type \"" << indexname << "\"\n";
4306 os << "literal \"true\"\n";
4309 skip_spaces_braces(p);
4310 preamble.registerAutomaticallyLoadedPackage("makeidx");
4311 if (preamble.use_indices() == "true")
4312 preamble.registerAutomaticallyLoadedPackage("splitidx");
4316 if (t.cs() == "printnomenclature") {
4318 string width_type = "";
4319 context.check_layout(os);
4320 begin_command_inset(os, "nomencl_print", "printnomenclature");
4321 // case of a custom width
4323 width = p.getArg('[', ']');
4324 width = translate_len(width);
4325 width_type = "custom";
4327 // case of no custom width
4328 // the case of no custom width but the width set
4329 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4330 // because the user could have set anything, not only the width
4331 // of the longest label (which would be width_type = "auto")
4332 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4333 if (label.empty() && width_type.empty())
4334 width_type = "none";
4335 os << "set_width \"" << width_type << "\"\n";
4336 if (width_type == "custom")
4337 os << "width \"" << width << '\"';
4339 skip_spaces_braces(p);
4340 preamble.registerAutomaticallyLoadedPackage("nomencl");
4344 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4345 context.check_layout(os);
4346 begin_inset(os, "script ");
4347 os << t.cs().substr(4) << '\n';
4348 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4349 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4351 if (t.cs() == "textsubscript")
4352 preamble.registerAutomaticallyLoadedPackage("subscript");
4356 if ((where = is_known(t.cs(), known_quotes))) {
4357 context.check_layout(os);
4358 begin_inset(os, "Quotes ");
4359 os << known_coded_quotes[where - known_quotes];
4361 // LyX adds {} after the quote, so we have to eat
4362 // spaces here if there are any before a possible
4364 eat_whitespace(p, os, context, false);
4369 if ((where = is_known(t.cs(), known_sizes)) &&
4370 context.new_layout_allowed) {
4371 context.check_layout(os);
4372 TeXFont const oldFont = context.font;
4373 context.font.size = known_coded_sizes[where - known_sizes];
4374 output_font_change(os, oldFont, context.font);
4375 eat_whitespace(p, os, context, false);
4379 if ((where = is_known(t.cs(), known_font_families)) &&
4380 context.new_layout_allowed) {
4381 context.check_layout(os);
4382 TeXFont const oldFont = context.font;
4383 context.font.family =
4384 known_coded_font_families[where - known_font_families];
4385 output_font_change(os, oldFont, context.font);
4386 eat_whitespace(p, os, context, false);
4390 if ((where = is_known(t.cs(), known_font_series)) &&
4391 context.new_layout_allowed) {
4392 context.check_layout(os);
4393 TeXFont const oldFont = context.font;
4394 context.font.series =
4395 known_coded_font_series[where - known_font_series];
4396 output_font_change(os, oldFont, context.font);
4397 eat_whitespace(p, os, context, false);
4401 if ((where = is_known(t.cs(), known_font_shapes)) &&
4402 context.new_layout_allowed) {
4403 context.check_layout(os);
4404 TeXFont const oldFont = context.font;
4405 context.font.shape =
4406 known_coded_font_shapes[where - known_font_shapes];
4407 output_font_change(os, oldFont, context.font);
4408 eat_whitespace(p, os, context, false);
4411 if ((where = is_known(t.cs(), known_old_font_families)) &&
4412 context.new_layout_allowed) {
4413 context.check_layout(os);
4414 TeXFont const oldFont = context.font;
4415 context.font.init();
4416 context.font.size = oldFont.size;
4417 context.font.family =
4418 known_coded_font_families[where - known_old_font_families];
4419 output_font_change(os, oldFont, context.font);
4420 eat_whitespace(p, os, context, false);
4424 if ((where = is_known(t.cs(), known_old_font_series)) &&
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.series =
4431 known_coded_font_series[where - known_old_font_series];
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_shapes)) &&
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.shape =
4444 known_coded_font_shapes[where - known_old_font_shapes];
4445 output_font_change(os, oldFont, context.font);
4446 eat_whitespace(p, os, context, false);
4450 if (t.cs() == "selectlanguage") {
4451 context.check_layout(os);
4452 // save the language for the case that a
4453 // \foreignlanguage is used
4454 context.font.language = babel2lyx(p.verbatim_item());
4455 os << "\n\\lang " << context.font.language << "\n";
4459 if (t.cs() == "foreignlanguage") {
4460 string const lang = babel2lyx(p.verbatim_item());
4461 parse_text_attributes(p, os, FLAG_ITEM, outer,
4463 context.font.language, lang);
4467 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4468 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4469 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4471 // We have to output the whole command if it has an option
4472 // because LyX doesn't support this yet, see bug #8214,
4473 // only if there is a single option specifying a variant, we can handle it.
4475 string langopts = p.getOpt();
4476 // check if the option contains a variant, if yes, extract it
4477 string::size_type pos_var = langopts.find("variant");
4478 string::size_type i = langopts.find(',');
4479 string::size_type k = langopts.find('=', pos_var);
4480 if (pos_var != string::npos && i == string::npos) {
4482 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4483 lang = preamble.polyglossia2lyx(variant);
4484 parse_text_attributes(p, os, FLAG_ITEM, outer,
4486 context.font.language, lang);
4488 output_ert_inset(os, t.asInput() + langopts, context);
4490 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4491 parse_text_attributes(p, os, FLAG_ITEM, outer,
4493 context.font.language, lang);
4498 if (t.cs() == "inputencoding") {
4499 // nothing to write here
4500 string const enc = subst(p.verbatim_item(), "\n", " ");
4501 p.setEncoding(enc, Encoding::inputenc);
4505 if (is_known(t.cs(), known_special_chars) ||
4506 (t.cs() == "protect" &&
4507 p.next_token().cat() == catEscape &&
4508 is_known(p.next_token().cs(), known_special_protect_chars))) {
4509 // LyX sometimes puts a \protect in front, so we have to ignore it
4511 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4512 known_special_chars);
4513 context.check_layout(os);
4514 os << known_coded_special_chars[where - known_special_chars];
4515 skip_spaces_braces(p);
4519 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4520 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4521 p.next_next_token().asInput() == "-") ||
4522 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4523 // LyX sometimes puts a \protect in front, so we have to ignore it
4524 if (t.cs() == "protect")
4526 context.check_layout(os);
4527 if (t.cs() == "nobreakdash")
4528 os << "\\SpecialChar nobreakdash\n";
4530 os << "\\SpecialChar endofsentence\n";
4535 if (t.cs() == "textquotedbl") {
4536 context.check_layout(os);
4542 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4543 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4544 || t.cs() == "%" || t.cs() == "-") {
4545 context.check_layout(os);
4547 os << "\\SpecialChar softhyphen\n";
4553 if (t.cs() == "char") {
4554 context.check_layout(os);
4555 if (p.next_token().character() == '`') {
4557 if (p.next_token().cs() == "\"") {
4562 output_ert_inset(os, "\\char`", context);
4565 output_ert_inset(os, "\\char", context);
4570 if (t.cs() == "verb") {
4571 context.check_layout(os);
4572 // set catcodes to verbatim early, just in case.
4573 p.setCatcodes(VERBATIM_CATCODES);
4574 string delim = p.get_token().asInput();
4575 Parser::Arg arg = p.verbatimStuff(delim);
4577 output_ert_inset(os, "\\verb" + delim
4578 + arg.second + delim, context);
4580 cerr << "invalid \\verb command. Skipping" << endl;
4584 // Problem: \= creates a tabstop inside the tabbing environment
4585 // and else an accent. In the latter case we really would want
4586 // \={o} instead of \= o.
4587 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4588 output_ert_inset(os, t.asInput(), context);
4592 if (t.cs() == "\\") {
4593 context.check_layout(os);
4595 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4596 else if (p.next_token().asInput() == "*") {
4598 // getOpt() eats the following space if there
4599 // is no optional argument, but that is OK
4600 // here since it has no effect in the output.
4601 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4604 begin_inset(os, "Newline newline");
4610 if (t.cs() == "newline" ||
4611 (t.cs() == "linebreak" && !p.hasOpt())) {
4612 context.check_layout(os);
4613 begin_inset(os, "Newline ");
4616 skip_spaces_braces(p);
4620 if (t.cs() == "input" || t.cs() == "include"
4621 || t.cs() == "verbatiminput") {
4622 string name = t.cs();
4623 if (t.cs() == "verbatiminput"
4624 && p.next_token().asInput() == "*")
4625 name += p.get_token().asInput();
4626 context.check_layout(os);
4627 string filename(normalize_filename(p.getArg('{', '}')));
4628 string const path = getMasterFilePath(true);
4629 // We want to preserve relative / absolute filenames,
4630 // therefore path is only used for testing
4631 if ((t.cs() == "include" || t.cs() == "input") &&
4632 !makeAbsPath(filename, path).exists()) {
4633 // The file extension is probably missing.
4634 // Now try to find it out.
4635 string const tex_name =
4636 find_file(filename, path,
4637 known_tex_extensions);
4638 if (!tex_name.empty())
4639 filename = tex_name;
4641 bool external = false;
4643 if (makeAbsPath(filename, path).exists()) {
4644 string const abstexname =
4645 makeAbsPath(filename, path).absFileName();
4646 string const absfigname =
4647 changeExtension(abstexname, ".fig");
4648 fix_child_filename(filename);
4649 string const lyxname = changeExtension(filename,
4650 roundtripMode() ? ".lyx.lyx" : ".lyx");
4651 string const abslyxname = makeAbsPath(
4652 lyxname, getParentFilePath(false)).absFileName();
4654 if (!skipChildren())
4655 external = FileName(absfigname).exists();
4656 if (t.cs() == "input" && !skipChildren()) {
4657 string const ext = getExtension(abstexname);
4659 // Combined PS/LaTeX:
4660 // x.eps, x.pstex_t (old xfig)
4661 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4662 FileName const absepsname(
4663 changeExtension(abstexname, ".eps"));
4664 FileName const abspstexname(
4665 changeExtension(abstexname, ".pstex"));
4666 bool const xfigeps =
4667 (absepsname.exists() ||
4668 abspstexname.exists()) &&
4671 // Combined PDF/LaTeX:
4672 // x.pdf, x.pdftex_t (old xfig)
4673 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4674 FileName const abspdfname(
4675 changeExtension(abstexname, ".pdf"));
4676 bool const xfigpdf =
4677 abspdfname.exists() &&
4678 (ext == "pdftex_t" || ext == "pdf_t");
4682 // Combined PS/PDF/LaTeX:
4683 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4684 string const absbase2(
4685 removeExtension(abstexname) + "_pspdftex");
4686 FileName const abseps2name(
4687 addExtension(absbase2, ".eps"));
4688 FileName const abspdf2name(
4689 addExtension(absbase2, ".pdf"));
4690 bool const xfigboth =
4691 abspdf2name.exists() &&
4692 abseps2name.exists() && ext == "pspdftex";
4694 xfig = xfigpdf || xfigeps || xfigboth;
4695 external = external && xfig;
4698 outname = changeExtension(filename, ".fig");
4699 FileName abssrc(changeExtension(abstexname, ".fig"));
4700 copy_file(abssrc, outname);
4702 // Don't try to convert, the result
4703 // would be full of ERT.
4705 FileName abssrc(abstexname);
4706 copy_file(abssrc, outname);
4707 } else if (t.cs() != "verbatiminput" &&
4709 tex2lyx(abstexname, FileName(abslyxname),
4712 // no need to call copy_file
4713 // tex2lyx creates the file
4716 FileName abssrc(abstexname);
4717 copy_file(abssrc, outname);
4720 cerr << "Warning: Could not find included file '"
4721 << filename << "'." << endl;
4725 begin_inset(os, "External\n");
4726 os << "\ttemplate XFig\n"
4727 << "\tfilename " << outname << '\n';
4728 registerExternalTemplatePackages("XFig");
4730 begin_command_inset(os, "include", name);
4731 outname = subst(outname, "\"", "\\\"");
4732 os << "preview false\n"
4733 "filename \"" << outname << "\"\n";
4734 if (t.cs() == "verbatiminput")
4735 preamble.registerAutomaticallyLoadedPackage("verbatim");
4741 if (t.cs() == "bibliographystyle") {
4742 // store new bibliographystyle
4743 bibliographystyle = p.verbatim_item();
4744 // If any other command than \bibliography, \addcontentsline
4745 // and \nocite{*} follows, we need to output the style
4746 // (because it might be used by that command).
4747 // Otherwise, it will automatically be output by LyX.
4750 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4751 if (t2.cat() == catBegin)
4753 if (t2.cat() != catEscape)
4755 if (t2.cs() == "nocite") {
4756 if (p.getArg('{', '}') == "*")
4758 } else if (t2.cs() == "bibliography")
4760 else if (t2.cs() == "phantomsection") {
4764 else if (t2.cs() == "addcontentsline") {
4765 // get the 3 arguments of \addcontentsline
4768 contentslineContent = p.getArg('{', '}');
4769 // if the last argument is not \refname we must output
4770 if (contentslineContent == "\\refname")
4777 output_ert_inset(os,
4778 "\\bibliographystyle{" + bibliographystyle + '}',
4784 if (t.cs() == "phantomsection") {
4785 // we only support this if it occurs between
4786 // \bibliographystyle and \bibliography
4787 if (bibliographystyle.empty())
4788 output_ert_inset(os, "\\phantomsection", context);
4792 if (t.cs() == "addcontentsline") {
4793 context.check_layout(os);
4794 // get the 3 arguments of \addcontentsline
4795 string const one = p.getArg('{', '}');
4796 string const two = p.getArg('{', '}');
4797 string const three = p.getArg('{', '}');
4798 // only if it is a \refname, we support if for the bibtex inset
4799 if (contentslineContent != "\\refname") {
4800 output_ert_inset(os,
4801 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4807 else if (t.cs() == "bibliography") {
4808 context.check_layout(os);
4810 begin_command_inset(os, "bibtex", "bibtex");
4811 if (!btprint.empty()) {
4812 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4813 // clear the string because the next BibTeX inset can be without the
4814 // \nocite{*} option
4817 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4818 // Do we have addcontentsline?
4819 if (contentslineContent == "\\refname") {
4820 BibOpts = "bibtotoc";
4821 // clear string because next BibTeX inset can be without addcontentsline
4822 contentslineContent.clear();
4824 // Do we have a bibliographystyle set?
4825 if (!bibliographystyle.empty()) {
4826 if (BibOpts.empty())
4827 BibOpts = normalize_filename(bibliographystyle);
4829 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4830 // clear it because each bibtex entry has its style
4831 // and we need an empty string to handle \phantomsection
4832 bibliographystyle.clear();
4834 os << "options " << '"' << BibOpts << '"' << "\n";
4839 if (t.cs() == "printbibliography") {
4840 context.check_layout(os);
4842 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4843 vector<string> opts = getVectorFromString(bbloptions);
4844 vector<string>::iterator it =
4845 find(opts.begin(), opts.end(), "heading=bibintoc");
4846 if (it != opts.end()) {
4848 BibOpts = "bibtotoc";
4850 bbloptions = getStringFromVector(opts);
4851 begin_command_inset(os, "bibtex", "bibtex");
4852 if (!btprint.empty()) {
4853 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4854 // clear the string because the next BibTeX inset can be without the
4855 // \nocite{*} option
4859 for (auto const & bf : preamble.biblatex_bibliographies) {
4860 if (!bibfiles.empty())
4862 bibfiles += normalize_filename(bf);
4864 if (!bibfiles.empty())
4865 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4866 // Do we have addcontentsline?
4867 if (contentslineContent == "\\refname") {
4868 BibOpts = "bibtotoc";
4869 // clear string because next BibTeX inset can be without addcontentsline
4870 contentslineContent.clear();
4872 os << "options " << '"' << BibOpts << '"' << "\n";
4873 if (!bbloptions.empty())
4874 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4876 need_commentbib = false;
4880 if (t.cs() == "bibbysection") {
4881 context.check_layout(os);
4883 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4884 vector<string> opts = getVectorFromString(bbloptions);
4885 vector<string>::iterator it =
4886 find(opts.begin(), opts.end(), "heading=bibintoc");
4887 if (it != opts.end()) {
4889 BibOpts = "bibtotoc";
4891 bbloptions = getStringFromVector(opts);
4892 begin_command_inset(os, "bibtex", "bibtex");
4893 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4895 for (auto const & bf : preamble.biblatex_bibliographies) {
4896 if (!bibfiles.empty())
4898 bibfiles += normalize_filename(bf);
4900 if (!bibfiles.empty())
4901 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4902 os << "options " << '"' << BibOpts << '"' << "\n";
4903 if (!bbloptions.empty())
4904 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4906 need_commentbib = false;
4910 if (t.cs() == "parbox") {
4911 // Test whether this is an outer box of a shaded box
4913 // swallow arguments
4914 while (p.hasOpt()) {
4916 p.skip_spaces(true);
4919 p.skip_spaces(true);
4921 if (p.next_token().cat() == catBegin)
4923 p.skip_spaces(true);
4924 Token to = p.get_token();
4925 bool shaded = false;
4926 if (to.asInput() == "\\begin") {
4927 p.skip_spaces(true);
4928 if (p.getArg('{', '}') == "shaded")
4933 parse_outer_box(p, os, FLAG_ITEM, outer,
4934 context, "parbox", "shaded");
4936 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4937 "", "", t.cs(), "", "");
4941 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4942 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4943 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4944 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4948 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4949 string backgroundcolor;
4950 preamble.registerAutomaticallyLoadedPackage("xcolor");
4951 if (t.cs() == "fcolorbox") {
4952 string const framecolor = p.getArg('{', '}');
4953 backgroundcolor = p.getArg('{', '}');
4954 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4956 backgroundcolor = p.getArg('{', '}');
4957 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4962 // FIXME: due to the compiler limit of "if" nestings
4963 // the code for the alignment was put here
4964 // put them in their own if if this is fixed
4965 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4966 || t.cs() == "shadowsize"
4967 || t.cs() == "raggedleft" || t.cs() == "centering"
4968 || t.cs() == "raggedright") {
4969 if (t.cs() == "fboxrule")
4971 if (t.cs() == "fboxsep")
4973 if (t.cs() == "shadowsize")
4975 if (t.cs() != "raggedleft" && t.cs() != "centering"
4976 && t.cs() != "raggedright") {
4977 p.skip_spaces(true);
4978 while (p.good() && p.next_token().cat() != catSpace
4979 && p.next_token().cat() != catNewline
4980 && p.next_token().cat() != catEscape) {
4981 if (t.cs() == "fboxrule")
4982 fboxrule = fboxrule + p.get_token().asInput();
4983 if (t.cs() == "fboxsep")
4984 fboxsep = fboxsep + p.get_token().asInput();
4985 if (t.cs() == "shadowsize")
4986 shadow_size = shadow_size + p.get_token().asInput();
4989 output_ert_inset(os, t.asInput(), context);
4994 //\framebox() is part of the picture environment and different from \framebox{}
4995 //\framebox{} will be parsed by parse_outer_box
4996 if (t.cs() == "framebox") {
4997 if (p.next_token().character() == '(') {
4998 //the syntax is: \framebox(x,y)[position]{content}
4999 string arg = t.asInput();
5000 arg += p.getFullParentheseArg();
5001 arg += p.getFullOpt();
5002 eat_whitespace(p, os, context, false);
5003 output_ert_inset(os, arg + '{', context);
5004 parse_text(p, os, FLAG_ITEM, outer, context);
5005 output_ert_inset(os, "}", context);
5007 //the syntax is: \framebox[width][position]{content}
5008 string special = p.getFullOpt();
5009 special += p.getOpt();
5010 parse_outer_box(p, os, FLAG_ITEM, outer,
5011 context, t.cs(), special);
5016 //\makebox() is part of the picture environment and different from \makebox{}
5017 //\makebox{} will be parsed by parse_box
5018 if (t.cs() == "makebox") {
5019 if (p.next_token().character() == '(') {
5020 //the syntax is: \makebox(x,y)[position]{content}
5021 string arg = t.asInput();
5022 arg += p.getFullParentheseArg();
5023 arg += p.getFullOpt();
5024 eat_whitespace(p, os, context, false);
5025 output_ert_inset(os, arg + '{', context);
5026 parse_text(p, os, FLAG_ITEM, outer, context);
5027 output_ert_inset(os, "}", context);
5029 //the syntax is: \makebox[width][position]{content}
5030 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5031 "", "", t.cs(), "", "");
5035 if (t.cs() == "smallskip" ||
5036 t.cs() == "medskip" ||
5037 t.cs() == "bigskip" ||
5038 t.cs() == "vfill") {
5039 context.check_layout(os);
5040 begin_inset(os, "VSpace ");
5043 skip_spaces_braces(p);
5047 if ((where = is_known(t.cs(), known_spaces))) {
5048 context.check_layout(os);
5049 begin_inset(os, "space ");
5050 os << '\\' << known_coded_spaces[where - known_spaces]
5053 // LaTeX swallows whitespace after all spaces except
5054 // "\\,". We have to do that here, too, because LyX
5055 // adds "{}" which would make the spaces significant.
5057 eat_whitespace(p, os, context, false);
5058 // LyX adds "{}" after all spaces except "\\ " and
5059 // "\\,", so we have to remove "{}".
5060 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5061 // remove the braces after "\\,", too.
5067 if (t.cs() == "newpage" ||
5068 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5069 t.cs() == "clearpage" ||
5070 t.cs() == "cleardoublepage") {
5071 context.check_layout(os);
5072 begin_inset(os, "Newpage ");
5075 skip_spaces_braces(p);
5079 if (t.cs() == "DeclareRobustCommand" ||
5080 t.cs() == "DeclareRobustCommandx" ||
5081 t.cs() == "newcommand" ||
5082 t.cs() == "newcommandx" ||
5083 t.cs() == "providecommand" ||
5084 t.cs() == "providecommandx" ||
5085 t.cs() == "renewcommand" ||
5086 t.cs() == "renewcommandx") {
5087 // DeclareRobustCommand, DeclareRobustCommandx,
5088 // providecommand and providecommandx could be handled
5089 // by parse_command(), but we need to call
5090 // add_known_command() here.
5091 string name = t.asInput();
5092 if (p.next_token().asInput() == "*") {
5093 // Starred form. Eat '*'
5097 string const command = p.verbatim_item();
5098 string const opt1 = p.getFullOpt();
5099 string const opt2 = p.getFullOpt();
5100 add_known_command(command, opt1, !opt2.empty());
5101 string const ert = name + '{' + command + '}' +
5103 '{' + p.verbatim_item() + '}';
5105 if (t.cs() == "DeclareRobustCommand" ||
5106 t.cs() == "DeclareRobustCommandx" ||
5107 t.cs() == "providecommand" ||
5108 t.cs() == "providecommandx" ||
5109 name[name.length()-1] == '*')
5110 output_ert_inset(os, ert, context);
5112 context.check_layout(os);
5113 begin_inset(os, "FormulaMacro");
5120 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5121 // let could be handled by parse_command(),
5122 // but we need to call add_known_command() here.
5123 string ert = t.asInput();
5126 if (p.next_token().cat() == catBegin) {
5127 name = p.verbatim_item();
5128 ert += '{' + name + '}';
5130 name = p.verbatim_item();
5135 if (p.next_token().cat() == catBegin) {
5136 command = p.verbatim_item();
5137 ert += '{' + command + '}';
5139 command = p.verbatim_item();
5142 // If command is known, make name known too, to parse
5143 // its arguments correctly. For this reason we also
5144 // have commands in syntax.default that are hardcoded.
5145 CommandMap::iterator it = known_commands.find(command);
5146 if (it != known_commands.end())
5147 known_commands[t.asInput()] = it->second;
5148 output_ert_inset(os, ert, context);
5152 if (t.cs() == "hspace" || t.cs() == "vspace") {
5155 string name = t.asInput();
5156 string const length = p.verbatim_item();
5159 bool valid = splitLatexLength(length, valstring, unit);
5160 bool known_hspace = false;
5161 bool known_vspace = false;
5162 bool known_unit = false;
5165 istringstream iss(valstring);
5168 if (t.cs()[0] == 'h') {
5169 if (unit == "\\fill") {
5174 known_hspace = true;
5177 if (unit == "\\smallskipamount") {
5179 known_vspace = true;
5180 } else if (unit == "\\medskipamount") {
5182 known_vspace = true;
5183 } else if (unit == "\\bigskipamount") {
5185 known_vspace = true;
5186 } else if (unit == "\\fill") {
5188 known_vspace = true;
5192 if (!known_hspace && !known_vspace) {
5193 switch (unitFromString(unit)) {
5209 //unitFromString(unit) fails for relative units like Length::PCW
5210 // therefore handle them separately
5211 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5212 || unit == "\\textwidth" || unit == "\\linewidth"
5213 || unit == "\\textheight" || unit == "\\paperheight"
5214 || unit == "\\baselineskip")
5222 // check for glue lengths
5223 bool is_gluelength = false;
5224 string gluelength = length;
5225 string::size_type i = length.find(" minus");
5226 if (i == string::npos) {
5227 i = length.find(" plus");
5228 if (i != string::npos)
5229 is_gluelength = true;
5231 is_gluelength = true;
5232 // if yes transform "9xx minus 8yy plus 7zz"
5234 if (is_gluelength) {
5235 i = gluelength.find(" minus");
5236 if (i != string::npos)
5237 gluelength.replace(i, 7, "-");
5238 i = gluelength.find(" plus");
5239 if (i != string::npos)
5240 gluelength.replace(i, 6, "+");
5243 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5244 // Literal horizontal length or known variable
5245 context.check_layout(os);
5246 begin_inset(os, "space ");
5254 if (known_unit && !known_hspace)
5255 os << "\n\\length " << translate_len(length);
5257 os << "\n\\length " << gluelength;
5259 } else if (known_unit || known_vspace || is_gluelength) {
5260 // Literal vertical length or known variable
5261 context.check_layout(os);
5262 begin_inset(os, "VSpace ");
5265 if (known_unit && !known_vspace)
5266 os << translate_len(length);
5273 // LyX can't handle other length variables in Inset VSpace/space
5278 output_ert_inset(os, name + '{' + unit + '}', context);
5279 else if (value == -1.0)
5280 output_ert_inset(os, name + "{-" + unit + '}', context);
5282 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5284 output_ert_inset(os, name + '{' + length + '}', context);
5289 // The single '=' is meant here.
5290 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5294 context.check_layout(os);
5295 docstring name = newinsetlayout->name();
5296 bool const caption = name.find(from_ascii("Caption:")) == 0;
5298 // Already done for floating minted listings.
5299 if (minted_float.empty()) {
5300 begin_inset(os, "Caption ");
5301 os << to_utf8(name.substr(8)) << '\n';
5304 // FIXME: what do we do if the prefix is not Flex: ?
5305 if (prefixIs(name, from_ascii("Flex:")))
5307 begin_inset(os, "Flex ");
5308 os << to_utf8(name) << '\n'
5309 << "status collapsed\n";
5311 if (!minted_float.empty()) {
5312 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5313 } else if (newinsetlayout->isPassThru()) {
5314 // set catcodes to verbatim early, just in case.
5315 p.setCatcodes(VERBATIM_CATCODES);
5316 string delim = p.get_token().asInput();
5318 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5319 //FIXME: handle error condition
5320 string const arg = p.verbatimStuff("}").second;
5321 Context newcontext(true, context.textclass);
5322 if (newinsetlayout->forcePlainLayout())
5323 newcontext.layout = &context.textclass.plainLayout();
5324 output_ert(os, arg, newcontext);
5326 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5329 // Minted caption insets are not closed here because
5330 // we collect everything into the caption.
5331 if (minted_float.empty())
5336 if (t.cs() == "includepdf") {
5338 string const arg = p.getArg('[', ']');
5339 map<string, string> opts;
5340 vector<string> keys;
5341 split_map(arg, opts, keys);
5342 string name = normalize_filename(p.verbatim_item());
5343 string const path = getMasterFilePath(true);
5344 // We want to preserve relative / absolute filenames,
5345 // therefore path is only used for testing
5346 if (!makeAbsPath(name, path).exists()) {
5347 // The file extension is probably missing.
5348 // Now try to find it out.
5349 char const * const pdfpages_format[] = {"pdf", 0};
5350 string const pdftex_name =
5351 find_file(name, path, pdfpages_format);
5352 if (!pdftex_name.empty()) {
5357 FileName const absname = makeAbsPath(name, path);
5358 if (absname.exists())
5360 fix_child_filename(name);
5361 copy_file(absname, name);
5363 cerr << "Warning: Could not find file '"
5364 << name << "'." << endl;
5366 context.check_layout(os);
5367 begin_inset(os, "External\n\ttemplate ");
5368 os << "PDFPages\n\tfilename "
5370 // parse the options
5371 if (opts.find("pages") != opts.end())
5372 os << "\textra LaTeX \"pages="
5373 << opts["pages"] << "\"\n";
5374 if (opts.find("angle") != opts.end())
5375 os << "\trotateAngle "
5376 << opts["angle"] << '\n';
5377 if (opts.find("origin") != opts.end()) {
5379 string const opt = opts["origin"];
5380 if (opt == "tl") ss << "topleft";
5381 if (opt == "bl") ss << "bottomleft";
5382 if (opt == "Bl") ss << "baselineleft";
5383 if (opt == "c") ss << "center";
5384 if (opt == "tc") ss << "topcenter";
5385 if (opt == "bc") ss << "bottomcenter";
5386 if (opt == "Bc") ss << "baselinecenter";
5387 if (opt == "tr") ss << "topright";
5388 if (opt == "br") ss << "bottomright";
5389 if (opt == "Br") ss << "baselineright";
5390 if (!ss.str().empty())
5391 os << "\trotateOrigin " << ss.str() << '\n';
5393 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5395 if (opts.find("width") != opts.end())
5397 << translate_len(opts["width"]) << '\n';
5398 if (opts.find("height") != opts.end())
5400 << translate_len(opts["height"]) << '\n';
5401 if (opts.find("keepaspectratio") != opts.end())
5402 os << "\tkeepAspectRatio\n";
5404 context.check_layout(os);
5405 registerExternalTemplatePackages("PDFPages");
5409 if (t.cs() == "loadgame") {
5411 string name = normalize_filename(p.verbatim_item());
5412 string const path = getMasterFilePath(true);
5413 // We want to preserve relative / absolute filenames,
5414 // therefore path is only used for testing
5415 if (!makeAbsPath(name, path).exists()) {
5416 // The file extension is probably missing.
5417 // Now try to find it out.
5418 char const * const lyxskak_format[] = {"fen", 0};
5419 string const lyxskak_name =
5420 find_file(name, path, lyxskak_format);
5421 if (!lyxskak_name.empty())
5422 name = lyxskak_name;
5424 FileName const absname = makeAbsPath(name, path);
5425 if (absname.exists())
5427 fix_child_filename(name);
5428 copy_file(absname, name);
5430 cerr << "Warning: Could not find file '"
5431 << name << "'." << endl;
5432 context.check_layout(os);
5433 begin_inset(os, "External\n\ttemplate ");
5434 os << "ChessDiagram\n\tfilename "
5437 context.check_layout(os);
5438 // after a \loadgame follows a \showboard
5439 if (p.get_token().asInput() == "showboard")
5441 registerExternalTemplatePackages("ChessDiagram");
5445 // try to see whether the string is in unicodesymbols
5446 // Only use text mode commands, since we are in text mode here,
5447 // and math commands may be invalid (bug 6797)
5448 string name = t.asInput();
5449 // handle the dingbats, cyrillic and greek
5450 if (name == "\\ding" || name == "\\textcyr" ||
5451 (name == "\\textgreek" && !preamble.usePolyglossia()))
5452 name = name + '{' + p.getArg('{', '}') + '}';
5453 // handle the ifsym characters
5454 else if (name == "\\textifsymbol") {
5455 string const optif = p.getFullOpt();
5456 string const argif = p.getArg('{', '}');
5457 name = name + optif + '{' + argif + '}';
5459 // handle the \ascii characters
5460 // the case of \ascii within braces, as LyX outputs it, is already
5461 // handled for t.cat() == catBegin
5462 else if (name == "\\ascii") {
5463 // the code is "\asci\xxx"
5464 name = "{" + name + p.get_token().asInput() + "}";
5467 // handle some TIPA special characters
5468 else if (preamble.isPackageUsed("tipa")) {
5469 if (name == "\\s") {
5470 // fromLaTeXCommand() does not yet
5471 // recognize tipa short cuts
5472 name = "\\textsyllabic";
5473 } else if (name == "\\=" &&
5474 p.next_token().asInput() == "*") {
5475 // fromLaTeXCommand() does not yet
5476 // recognize tipa short cuts
5478 name = "\\textsubbar";
5479 } else if (name == "\\textdoublevertline") {
5480 // FIXME: This is not correct,
5481 // \textvertline is higher than \textbardbl
5482 name = "\\textbardbl";
5484 } else if (name == "\\!" ) {
5485 if (p.next_token().asInput() == "b") {
5486 p.get_token(); // eat 'b'
5489 } else if (p.next_token().asInput() == "d") {
5493 } else if (p.next_token().asInput() == "g") {
5497 } else if (p.next_token().asInput() == "G") {
5499 name = "\\texthtscg";
5501 } else if (p.next_token().asInput() == "j") {
5503 name = "\\texthtbardotlessj";
5505 } else if (p.next_token().asInput() == "o") {
5507 name = "\\textbullseye";
5510 } else if (name == "\\*" ) {
5511 if (p.next_token().asInput() == "k") {
5513 name = "\\textturnk";
5515 } else if (p.next_token().asInput() == "r") {
5516 p.get_token(); // eat 'b'
5517 name = "\\textturnr";
5519 } else if (p.next_token().asInput() == "t") {
5521 name = "\\textturnt";
5523 } else if (p.next_token().asInput() == "w") {
5525 name = "\\textturnw";
5530 if ((name.size() == 2 &&
5531 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5532 p.next_token().asInput() != "*") ||
5533 is_known(name.substr(1), known_tipa_marks)) {
5534 // name is a command that corresponds to a
5535 // combining character in unicodesymbols.
5536 // Append the argument, fromLaTeXCommand()
5537 // will either convert it to a single
5538 // character or a combining sequence.
5539 name += '{' + p.verbatim_item() + '}';
5541 // now get the character from unicodesymbols
5545 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5546 Encodings::TEXT_CMD, termination, rem, &req));
5548 context.check_layout(os);
5551 output_ert_inset(os, to_utf8(rem), context);
5553 skip_spaces_braces(p);
5554 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5555 preamble.registerAutomaticallyLoadedPackage(*it);
5557 //cerr << "#: " << t << " mode: " << mode << endl;
5558 // heuristic: read up to next non-nested space
5560 string s = t.asInput();
5561 string z = p.verbatim_item();
5562 while (p.good() && z != " " && !z.empty()) {
5563 //cerr << "read: " << z << endl;
5565 z = p.verbatim_item();
5567 cerr << "found ERT: " << s << endl;
5568 output_ert_inset(os, s + ' ', context);
5571 if (t.asInput() == name &&
5572 p.next_token().asInput() == "*") {
5573 // Starred commands like \vspace*{}
5574 p.get_token(); // Eat '*'
5577 if (!parse_command(name, p, os, outer, context))
5578 output_ert_inset(os, name, context);
5584 string guessLanguage(Parser & p, string const & lang)
5586 typedef std::map<std::string, size_t> LangMap;
5587 // map from language names to number of characters
5590 for (char const * const * i = supported_CJK_languages; *i; i++)
5591 used[string(*i)] = 0;
5594 Token const t = p.get_token();
5595 // comments are not counted for any language
5596 if (t.cat() == catComment)
5598 // commands are not counted as well, but we need to detect
5599 // \begin{CJK} and switch encoding if needed
5600 if (t.cat() == catEscape) {
5601 if (t.cs() == "inputencoding") {
5602 string const enc = subst(p.verbatim_item(), "\n", " ");
5603 p.setEncoding(enc, Encoding::inputenc);
5606 if (t.cs() != "begin")
5609 // Non-CJK content is counted for lang.
5610 // We do not care about the real language here:
5611 // If we have more non-CJK contents than CJK contents,
5612 // we simply use the language that was specified as
5613 // babel main language.
5614 used[lang] += t.asInput().length();
5617 // Now we are starting an environment
5619 string const name = p.getArg('{', '}');
5620 if (name != "CJK") {
5624 // It is a CJK environment
5626 /* name = */ p.getArg('{', '}');
5627 string const encoding = p.getArg('{', '}');
5628 /* mapping = */ p.getArg('{', '}');
5629 string const encoding_old = p.getEncoding();
5630 char const * const * const where =
5631 is_known(encoding, supported_CJK_encodings);
5633 p.setEncoding(encoding, Encoding::CJK);
5635 p.setEncoding("UTF-8");
5636 string const text = p.ertEnvironment("CJK");
5637 p.setEncoding(encoding_old);
5640 // ignore contents in unknown CJK encoding
5643 // the language of the text
5645 supported_CJK_languages[where - supported_CJK_encodings];
5646 used[cjk] += text.length();
5648 LangMap::const_iterator use = used.begin();
5649 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5650 if (it->second > use->second)
5657 void check_comment_bib(ostream & os, Context & context)
5659 if (!need_commentbib)
5661 // We have a bibliography database, but no bibliography with biblatex
5662 // which is completely valid. Insert a bibtex inset in a note.
5663 context.check_layout(os);
5664 begin_inset(os, "Note Note\n");
5665 os << "status open\n";
5666 os << "\\begin_layout Plain Layout\n";
5667 begin_command_inset(os, "bibtex", "bibtex");
5669 for (auto const & bf : preamble.biblatex_bibliographies) {
5670 if (!bibfiles.empty())
5672 bibfiles += normalize_filename(bf);
5674 if (!bibfiles.empty())
5675 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5676 end_inset(os);// Bibtex
5677 os << "\\end_layout\n";
5678 end_inset(os);// Note