2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
22 #include "LaTeXPackages.h"
27 #include "insets/ExternalTemplate.h"
29 #include "support/lassert.h"
30 #include "support/convert.h"
31 #include "support/FileName.h"
32 #include "support/filetools.h"
33 #include "support/lstrings.h"
34 #include "support/lyxtime.h"
43 using namespace lyx::support;
50 void output_arguments(ostream &, Parser &, bool, bool, bool, Context &,
51 Layout::LaTeXArgMap const &);
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context, InsetLayout const * layout)
59 bool const forcePlainLayout =
60 layout ? layout->forcePlainLayout() : false;
61 Context newcontext(true, context.textclass);
63 newcontext.layout = &context.textclass.plainLayout();
65 newcontext.font = context.font;
67 output_arguments(os, p, outer, false, false, newcontext,
69 parse_text(p, os, flags, outer, newcontext);
71 output_arguments(os, p, outer, false, true, newcontext,
72 layout->postcommandargs());
73 newcontext.check_end_layout(os);
79 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
80 Context const & context, string const & name)
82 InsetLayout const * layout = 0;
83 DocumentClass::InsetLayouts::const_iterator it =
84 context.textclass.insetLayouts().find(from_ascii(name));
85 if (it != context.textclass.insetLayouts().end())
86 layout = &(it->second);
87 parse_text_in_inset(p, os, flags, outer, context, layout);
90 /// parses a paragraph snippet, useful for example for \\emph{...}
91 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
94 Context newcontext(context);
95 // Don't inherit the paragraph-level extra stuff
96 newcontext.par_extra_stuff.clear();
97 parse_text(p, os, flags, outer, newcontext);
98 // Make sure that we don't create invalid .lyx files
99 context.need_layout = newcontext.need_layout;
100 context.need_end_layout = newcontext.need_end_layout;
105 * Thin wrapper around parse_text_snippet() using a string.
107 * We completely ignore \c context.need_layout and \c context.need_end_layout,
108 * because our return value is not used directly (otherwise the stream version
109 * of parse_text_snippet() could be used). That means that the caller needs
110 * to do layout management manually.
111 * This is intended to parse text that does not create any layout changes.
113 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
116 Context newcontext(context);
117 newcontext.need_layout = false;
118 newcontext.need_end_layout = false;
119 newcontext.new_layout_allowed = false;
120 // Avoid warning by Context::~Context()
121 newcontext.par_extra_stuff.clear();
123 parse_text_snippet(p, os, flags, outer, newcontext);
127 string fboxrule = "";
129 string shadow_size = "";
131 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
132 "vpageref", "prettyref", "nameref", "eqref", 0 };
134 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
135 "vpageref", "formatted", "nameref", "eqref", 0 };
137 char const * const known_refstyle_commands[] = { "algref", "chapref", "corref",
138 "eqref", "enuref", "figref", "fnref", "lemref", "parref", "partref", "propref",
139 "secref", "subsecref", "tabref", "thmref", 0 };
141 char const * const known_refstyle_prefixes[] = { "alg", "chap", "cor",
142 "eq", "enu", "fig", "fn", "lem", "par", "part", "prop",
143 "sec", "subsec", "tab", "thm", 0 };
147 * supported CJK encodings
148 * JIS does not work with LyX's encoding conversion
150 const char * const supported_CJK_encodings[] = {
151 "EUC-JP", "KS", "GB", "UTF8",
152 "Bg5", /*"JIS",*/ "SJIS", 0};
155 * the same as supported_CJK_encodings with their corresponding LyX language name
156 * FIXME: The mapping "UTF8" => "chinese-traditional" is only correct for files
158 * NOTE: "Bg5", "JIS" and "SJIS" are not supported by LyX, on re-export the
159 * encodings "UTF8", "EUC-JP" and "EUC-JP" will be used.
160 * please keep this in sync with supported_CJK_encodings line by line!
162 const char * const supported_CJK_languages[] = {
163 "japanese-cjk", "korean", "chinese-simplified", "chinese-traditional",
164 "chinese-traditional", /*"japanese-cjk",*/ "japanese-cjk", 0};
168 * The starred forms are also known except for "citefullauthor",
169 * "citeyear" and "citeyearpar".
171 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
172 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
173 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
177 * No starred form other than "cite*" known.
179 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
180 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
181 // jurabib commands not (yet) supported by LyX:
183 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
184 // "footciteauthor", "footciteyear", "footciteyearpar",
185 "citefield", "citetitle", 0 };
189 * Known starred forms: \cite*, \citeauthor*, \Citeauthor*, \parencite*, \citetitle*.
191 char const * const known_biblatex_commands[] = { "cite", "Cite", "textcite", "Textcite",
192 "parencite", "Parencite", "citeauthor", "Citeauthor", "citeyear", "smartcite", "Smartcite",
193 "footcite", "Footcite", "autocite", "Autocite", "citetitle", "fullcite", "footfullcite",
194 "supercite", "cites", "Cites", "textcites", "Textcites", "parencites", "Parencites",
195 "smartcites", "Smartcites", "autocites", "Autocites", 0 };
197 // Whether we need to insert a bibtex inset in a comment
198 bool need_commentbib = false;
200 /// LaTeX names for quotes
201 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
202 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
203 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
204 "guilsinglleft", "frq", "guilsinglright", 0};
206 /// the same as known_quotes with .lyx names
207 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
208 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
209 "gld", "grd", "gls", "ers", "fls",
210 "fls", "frs", "frs", 0};
212 /// LaTeX names for font sizes
213 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
214 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
216 /// the same as known_sizes with .lyx names
217 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
218 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
220 /// LaTeX 2.09 names for font families
221 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
223 /// LaTeX names for font families
224 char const * const known_font_families[] = { "rmfamily", "sffamily",
227 /// LaTeX names for font family changing commands
228 char const * const known_text_font_families[] = { "textrm", "textsf",
231 /// The same as known_old_font_families, known_font_families and
232 /// known_text_font_families with .lyx names
233 char const * const known_coded_font_families[] = { "roman", "sans",
236 /// LaTeX 2.09 names for font series
237 char const * const known_old_font_series[] = { "bf", 0};
239 /// LaTeX names for font series
240 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
242 /// LaTeX names for font series changing commands
243 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
245 /// The same as known_old_font_series, known_font_series and
246 /// known_text_font_series with .lyx names
247 char const * const known_coded_font_series[] = { "bold", "medium", 0};
249 /// LaTeX 2.09 names for font shapes
250 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
252 /// LaTeX names for font shapes
253 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
256 /// LaTeX names for font shape changing commands
257 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
260 /// The same as known_old_font_shapes, known_font_shapes and
261 /// known_text_font_shapes with .lyx names
262 char const * const known_coded_font_shapes[] = { "italic", "slanted",
263 "smallcaps", "up", 0};
265 /// Known special characters which need skip_spaces_braces() afterwards
266 char const * const known_special_chars[] = {"ldots",
267 "lyxarrow", "textcompwordmark",
268 "slash", "textasciitilde", "textasciicircum", "textbackslash",
269 "LyX", "TeX", "LaTeXe",
272 /// special characters from known_special_chars which may have a \\protect before
273 char const * const known_special_protect_chars[] = {"LyX", "TeX",
274 "LaTeXe", "LaTeX", 0};
276 /// the same as known_special_chars with .lyx names
277 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
278 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
279 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
280 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
281 "\\SpecialChar LaTeX\n", 0};
284 * Graphics file extensions known by the dvips driver of the graphics package.
285 * These extensions are used to complete the filename of an included
286 * graphics file if it does not contain an extension.
287 * The order must be the same that latex uses to find a file, because we
288 * will use the first extension that matches.
289 * This is only an approximation for the common cases. If we would want to
290 * do it right in all cases, we would need to know which graphics driver is
291 * used and know the extensions of every driver of the graphics package.
293 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
294 "ps.gz", "eps.Z", "ps.Z", 0};
297 * Graphics file extensions known by the pdftex driver of the graphics package.
298 * \sa known_dvips_graphics_formats
300 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
304 * Known file extensions for TeX files as used by \\include.
306 char const * const known_tex_extensions[] = {"tex", 0};
308 /// spaces known by InsetSpace
309 char const * const known_spaces[] = { " ", "space", ",",
310 "thinspace", "quad", "qquad", "enspace", "enskip",
311 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
312 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
313 "upbracefill", "downbracefill", 0};
315 /// the same as known_spaces with .lyx names
316 char const * const known_coded_spaces[] = { "space{}", "space{}",
317 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
318 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
319 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
320 "upbracefill{}", "downbracefill{}", 0};
322 /// known TIPA combining diacritical marks
323 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
324 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
325 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
326 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
327 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
328 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
329 "textsubring", "textsubbar", 0};
331 /// TIPA tones that need special handling
332 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
334 // string to store the float type to be able to determine the type of subfloats
335 string float_type = "";
337 // string to store the float status of minted listings
338 string minted_float = "";
340 // whether a caption has been parsed for a floating minted listing
341 bool minted_float_has_caption = false;
343 // The caption for non-floating minted listings
344 string minted_nonfloat_caption = "";
347 /// splits "x=z, y=b" into a map and an ordered keyword vector
348 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
353 keys.resize(v.size());
354 for (size_t i = 0; i < v.size(); ++i) {
355 size_t const pos = v[i].find('=');
356 string const index = trimSpaceAndEol(v[i].substr(0, pos));
357 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
365 * Split a LaTeX length into value and unit.
366 * The latter can be a real unit like "pt", or a latex length variable
367 * like "\textwidth". The unit may contain additional stuff like glue
368 * lengths, but we don't care, because such lengths are ERT anyway.
369 * \returns true if \p value and \p unit are valid.
371 bool splitLatexLength(string const & len, string & value, string & unit)
375 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
376 //'4,5' is a valid LaTeX length number. Change it to '4.5'
377 string const length = subst(len, ',', '.');
378 if (i == string::npos)
381 if (len[0] == '\\') {
382 // We had something like \textwidth without a factor
388 value = trimSpaceAndEol(string(length, 0, i));
392 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
393 if (contains(len, '\\'))
394 unit = trimSpaceAndEol(string(len, i));
396 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
401 /// A simple function to translate a latex length to something LyX can
402 /// understand. Not perfect, but rather best-effort.
403 bool translate_len(string const & length, string & valstring, string & unit)
405 if (!splitLatexLength(length, valstring, unit))
407 // LyX uses percent values
409 istringstream iss(valstring);
414 string const percentval = oss.str();
416 if (unit.empty() || unit[0] != '\\')
418 string::size_type const i = unit.find(' ');
419 string const endlen = (i == string::npos) ? string() : string(unit, i);
420 if (unit == "\\textwidth") {
421 valstring = percentval;
422 unit = "text%" + endlen;
423 } else if (unit == "\\columnwidth") {
424 valstring = percentval;
425 unit = "col%" + endlen;
426 } else if (unit == "\\paperwidth") {
427 valstring = percentval;
428 unit = "page%" + endlen;
429 } else if (unit == "\\linewidth") {
430 valstring = percentval;
431 unit = "line%" + endlen;
432 } else if (unit == "\\paperheight") {
433 valstring = percentval;
434 unit = "pheight%" + endlen;
435 } else if (unit == "\\textheight") {
436 valstring = percentval;
437 unit = "theight%" + endlen;
438 } else if (unit == "\\baselineskip") {
439 valstring = percentval;
440 unit = "baselineskip%" + endlen;
448 string translate_len(string const & length)
452 if (translate_len(length, value, unit))
454 // If the input is invalid, return what we have.
462 * Translates a LaTeX length into \p value, \p unit and
463 * \p special parts suitable for a box inset.
464 * The difference from translate_len() is that a box inset knows about
465 * some special "units" that are stored in \p special.
467 void translate_box_len(string const & length, string & value, string & unit, string & special)
469 if (translate_len(length, value, unit)) {
470 if (unit == "\\height" || unit == "\\depth" ||
471 unit == "\\totalheight" || unit == "\\width") {
472 special = unit.substr(1);
473 // The unit is not used, but LyX requires a dummy setting
485 void begin_inset(ostream & os, string const & name)
487 os << "\n\\begin_inset " << name;
491 void begin_command_inset(ostream & os, string const & name,
492 string const & latexname)
494 begin_inset(os, "CommandInset ");
495 os << name << "\nLatexCommand " << latexname << '\n';
499 void end_inset(ostream & os)
501 os << "\n\\end_inset\n\n";
505 bool skip_braces(Parser & p)
507 if (p.next_token().cat() != catBegin)
510 if (p.next_token().cat() == catEnd) {
519 /// replace LaTeX commands in \p s from the unicodesymbols file with their
521 pair<bool, docstring> convert_unicodesymbols(docstring s)
524 int const nchars_escape = 8;
525 static char_type const chars_escape[nchars_escape] = {
526 '&', '_', '$', '%', '#', '^', '{', '}'};
528 for (size_t i = 0; i < s.size();) {
537 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
538 Encodings::TEXT_CMD, termination, rem, &req));
539 set<string>::const_iterator it = req.begin();
540 set<string>::const_iterator en = req.end();
541 for (; it != en; ++it)
542 preamble.registerAutomaticallyLoadedPackage(*it);
545 if (s.empty() || s[0] != '\\')
549 for (int k = 0; k < nchars_escape; k++)
550 if (prefixIs(s, from_ascii("\\") + chars_escape[k]))
555 return make_pair(res, os.str());
559 /// try to convert \p s to a valid InsetCommand argument
560 /// return whether this succeeded. If not, these command insets
561 /// get the "literate" flag.
562 pair<bool, string> convert_latexed_command_inset_arg(string s)
564 bool success = false;
566 // since we don't know the input encoding we can't use from_utf8
567 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
569 s = to_utf8(res.second);
571 // LyX cannot handle newlines in a latex command
572 return make_pair(success, subst(s, "\n", " "));
575 /// try to convert \p s to a valid InsetCommand argument
576 /// without trying to recode macros.
577 string convert_literate_command_inset_arg(string s)
579 // LyX cannot handle newlines in a latex command
580 return subst(s, "\n", " ");
583 void output_ert(ostream & os, string const & s, Context & context)
585 context.check_layout(os);
586 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
588 os << "\n\\backslash\n";
589 else if (*it == '\n') {
590 context.new_paragraph(os);
591 context.check_layout(os);
595 context.check_end_layout(os);
599 void output_ert_inset(ostream & os, string const & s, Context & context)
601 // We must have a valid layout before outputting the ERT inset.
602 context.check_layout(os);
603 Context newcontext(true, context.textclass);
604 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
605 if (layout.forcePlainLayout())
606 newcontext.layout = &context.textclass.plainLayout();
607 begin_inset(os, "ERT");
608 os << "\nstatus collapsed\n";
609 output_ert(os, s, newcontext);
614 void output_comment(Parser & p, ostream & os, string const & s,
617 if (p.next_token().cat() == catNewline)
618 output_ert_inset(os, '%' + s, context);
620 output_ert_inset(os, '%' + s + '\n', context);
624 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
626 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
629 if (checkModule(name, command))
630 return findLayoutWithoutModule(textclass, name, command);
635 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
637 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
640 if (checkModule(name, command))
641 return findInsetLayoutWithoutModule(textclass, name, command);
646 void eat_whitespace(Parser &, ostream &, Context &, bool);
650 * Skips whitespace and braces.
651 * This should be called after a command has been parsed that is not put into
652 * ERT, and where LyX adds "{}" if needed.
654 void skip_spaces_braces(Parser & p, bool keepws = false)
656 /* The following four examples produce the same typeset output and
657 should be handled by this function:
665 // Unfortunately we need to skip comments, too.
666 // We can't use eat_whitespace since writing them after the {}
667 // results in different output in some cases.
668 bool const skipped_spaces = p.skip_spaces(true);
669 bool const skipped_braces = skip_braces(p);
670 if (keepws && skipped_spaces && !skipped_braces)
671 // put back the space (it is better handled by check_space)
672 p.unskip_spaces(true);
676 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
677 Context & context, Layout::LaTeXArgMap const & latexargs)
680 context.check_layout(os);
685 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
686 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
687 for (; lait != laend; ++lait) {
689 eat_whitespace(p, os, context, false);
690 if (lait->second.mandatory) {
691 if (p.next_token().cat() != catBegin)
693 p.get_token(); // eat '{'
695 context.check_layout(os);
698 begin_inset(os, "Argument ");
701 os << i << "\nstatus collapsed\n\n";
702 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
705 if (p.next_token().cat() == catEscape ||
706 p.next_token().character() != '[')
708 p.get_token(); // eat '['
710 context.check_layout(os);
713 begin_inset(os, "Argument ");
716 os << i << "\nstatus collapsed\n\n";
717 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
720 eat_whitespace(p, os, context, false);
725 void output_command_layout(ostream & os, Parser & p, bool outer,
726 Context & parent_context,
727 Layout const * newlayout)
729 TeXFont const oldFont = parent_context.font;
730 // save the current font size
731 string const size = oldFont.size;
732 // reset the font size to default, because the font size switches
733 // don't affect section headings and the like
734 parent_context.font.size = Context::normalfont.size;
735 // we only need to write the font change if we have an open layout
736 if (!parent_context.atParagraphStart())
737 output_font_change(os, oldFont, parent_context.font);
738 parent_context.check_end_layout(os);
739 Context context(true, parent_context.textclass, newlayout,
740 parent_context.layout, parent_context.font);
741 if (parent_context.deeper_paragraph) {
742 // We are beginning a nested environment after a
743 // deeper paragraph inside the outer list environment.
744 // Therefore we don't need to output a "begin deeper".
745 context.need_end_deeper = true;
747 context.check_deeper(os);
748 output_arguments(os, p, outer, true, false, context,
749 context.layout->latexargs());
750 parse_text(p, os, FLAG_ITEM, outer, context);
751 output_arguments(os, p, outer, false, true, context,
752 context.layout->postcommandargs());
753 context.check_end_layout(os);
754 if (parent_context.deeper_paragraph) {
755 // We must suppress the "end deeper" because we
756 // suppressed the "begin deeper" above.
757 context.need_end_deeper = false;
759 context.check_end_deeper(os);
760 // We don't need really a new paragraph, but
761 // we must make sure that the next item gets a \begin_layout.
762 parent_context.new_paragraph(os);
763 // Set the font size to the original value. No need to output it here
764 // (Context::begin_layout() will do that if needed)
765 parent_context.font.size = size;
770 * Output a space if necessary.
771 * This function gets called for every whitespace token.
773 * We have three cases here:
774 * 1. A space must be suppressed. Example: The lyxcode case below
775 * 2. A space may be suppressed. Example: Spaces before "\par"
776 * 3. A space must not be suppressed. Example: A space between two words
778 * We currently handle only 1. and 3 and from 2. only the case of
779 * spaces before newlines as a side effect.
781 * 2. could be used to suppress as many spaces as possible. This has two effects:
782 * - Reimporting LyX generated LaTeX files changes almost no whitespace
783 * - Superflous whitespace from non LyX generated LaTeX files is removed.
784 * The drawback is that the logic inside the function becomes
785 * complicated, and that is the reason why it is not implemented.
787 void check_space(Parser & p, ostream & os, Context & context)
789 Token const next = p.next_token();
790 Token const curr = p.curr_token();
791 // A space before a single newline and vice versa must be ignored
792 // LyX emits a newline before \end{lyxcode}.
793 // This newline must be ignored,
794 // otherwise LyX will add an additional protected space.
795 if (next.cat() == catSpace ||
796 next.cat() == catNewline ||
797 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
800 context.check_layout(os);
806 * Parse all arguments of \p command
808 void parse_arguments(string const & command,
809 vector<ArgumentType> const & template_arguments,
810 Parser & p, ostream & os, bool outer, Context & context)
812 string ert = command;
813 size_t no_arguments = template_arguments.size();
814 for (size_t i = 0; i < no_arguments; ++i) {
815 switch (template_arguments[i]) {
818 // This argument contains regular LaTeX
819 output_ert_inset(os, ert + '{', context);
820 eat_whitespace(p, os, context, false);
821 if (template_arguments[i] == required)
822 parse_text(p, os, FLAG_ITEM, outer, context);
824 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
828 // This argument consists only of a single item.
829 // The presence of '{' or not must be preserved.
831 if (p.next_token().cat() == catBegin)
832 ert += '{' + p.verbatim_item() + '}';
834 ert += p.verbatim_item();
838 // This argument may contain special characters
839 ert += '{' + p.verbatim_item() + '}';
843 // true because we must not eat whitespace
844 // if an optional arg follows we must not strip the
845 // brackets from this one
846 if (i < no_arguments - 1 &&
847 template_arguments[i+1] == optional)
848 ert += p.getFullOpt(true);
850 ert += p.getOpt(true);
854 output_ert_inset(os, ert, context);
859 * Check whether \p command is a known command. If yes,
860 * handle the command with all arguments.
861 * \return true if the command was parsed, false otherwise.
863 bool parse_command(string const & command, Parser & p, ostream & os,
864 bool outer, Context & context)
866 if (known_commands.find(command) != known_commands.end()) {
867 parse_arguments(command, known_commands[command], p, os,
875 /// Parses a minipage or parbox
876 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
877 unsigned inner_flags, bool outer, Context & parent_context,
878 string const & outer_type, string const & special,
879 string inner_type, string const & frame_color,
880 string const & background_color)
884 string hor_pos = "l";
885 // We need to set the height to the LaTeX default of 1\\totalheight
886 // for the case when no height argument is given
887 string height_value = "1";
888 string height_unit = "in";
889 string height_special = "totalheight";
894 string width_special = "none";
895 string thickness = "0.4pt";
896 if (!fboxrule.empty())
897 thickness = fboxrule;
901 if (!fboxsep.empty())
902 separation = fboxsep;
906 if (!shadow_size.empty())
907 shadowsize = shadow_size;
910 string framecolor = "black";
911 string backgroundcolor = "none";
912 if (!frame_color.empty())
913 framecolor = frame_color;
914 if (!background_color.empty())
915 backgroundcolor = background_color;
916 // if there is a color box around the \begin statements have not yet been parsed
918 if (!frame_color.empty() || !background_color.empty()) {
919 eat_whitespace(p, os, parent_context, false);
920 p.get_token().asInput(); // the '{'
922 if (p.next_token().asInput() == "\\begin") {
923 p.get_token().asInput();
925 inner_type = "minipage";
926 inner_flags = FLAG_END;
927 active_environments.push_back("minipage");
930 else if (p.next_token().asInput() == "\\parbox") {
931 p.get_token().asInput();
932 inner_type = "parbox";
933 inner_flags = FLAG_ITEM;
936 else if (p.next_token().asInput() == "\\makebox") {
937 p.get_token().asInput();
938 inner_type = "makebox";
939 inner_flags = FLAG_ITEM;
941 // in case there is just \colorbox{color}{text}
944 inner_type = "makebox";
945 inner_flags = FLAG_BRACE_LAST;
950 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
952 if (!inner_type.empty() && p.hasOpt()) {
953 if (inner_type != "makebox")
954 position = p.getArg('[', ']');
956 latex_width = p.getArg('[', ']');
957 translate_box_len(latex_width, width_value, width_unit, width_special);
960 if (position != "t" && position != "c" && position != "b") {
961 cerr << "invalid position " << position << " for "
962 << inner_type << endl;
966 if (inner_type != "makebox") {
967 latex_height = p.getArg('[', ']');
968 translate_box_len(latex_height, height_value, height_unit, height_special);
970 string const opt = p.getArg('[', ']');
973 if (hor_pos != "l" && hor_pos != "c" &&
974 hor_pos != "r" && hor_pos != "s") {
975 cerr << "invalid hor_pos " << hor_pos
976 << " for " << inner_type << endl;
983 inner_pos = p.getArg('[', ']');
984 if (inner_pos != "c" && inner_pos != "t" &&
985 inner_pos != "b" && inner_pos != "s") {
986 cerr << "invalid inner_pos "
987 << inner_pos << " for "
988 << inner_type << endl;
989 inner_pos = position;
993 if (inner_type == "makebox")
997 if (inner_type.empty()) {
998 if (special.empty() && outer_type != "framebox")
999 latex_width = "1\\columnwidth";
1002 latex_width = p2.getArg('[', ']');
1003 string const opt = p2.getArg('[', ']');
1006 if (hor_pos != "l" && hor_pos != "c" &&
1007 hor_pos != "r" && hor_pos != "s") {
1008 cerr << "invalid hor_pos " << hor_pos
1009 << " for " << outer_type << endl;
1013 if (outer_type == "framebox")
1017 } else if (inner_type != "makebox")
1018 latex_width = p.verbatim_item();
1019 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1020 // as this is LyX's standard for such cases (except for makebox)
1021 // \framebox is more special and handled below
1022 if (latex_width.empty() && inner_type != "makebox"
1023 && outer_type != "framebox")
1024 latex_width = "1\\columnwidth";
1026 translate_len(latex_width, width_value, width_unit);
1028 bool shadedparbox = false;
1029 if (inner_type == "shaded") {
1030 eat_whitespace(p, os, parent_context, false);
1031 if (outer_type == "parbox") {
1033 if (p.next_token().cat() == catBegin)
1035 eat_whitespace(p, os, parent_context, false);
1036 shadedparbox = true;
1041 // If we already read the inner box we have to push the inner env
1042 if (!outer_type.empty() && !inner_type.empty() &&
1043 (inner_flags & FLAG_END))
1044 active_environments.push_back(inner_type);
1045 bool use_ert = false;
1046 if (!outer_type.empty() && !inner_type.empty()) {
1047 // Look whether there is some content after the end of the
1048 // inner box, but before the end of the outer box.
1049 // If yes, we need to output ERT.
1051 if (inner_flags & FLAG_END)
1052 p.ertEnvironment(inner_type);
1055 p.skip_spaces(true);
1056 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1057 if ((outer_env && p.next_token().asInput() != "\\end") ||
1058 (!outer_env && p.next_token().cat() != catEnd)) {
1059 // something is between the end of the inner box and
1060 // the end of the outer box, so we need to use ERT.
1068 if (!outer_type.empty()) {
1069 if (outer_flags & FLAG_END)
1070 ss << "\\begin{" << outer_type << '}';
1072 ss << '\\' << outer_type << '{';
1073 if (!special.empty())
1077 if (!inner_type.empty()) {
1078 if (inner_type != "shaded") {
1079 if (inner_flags & FLAG_END)
1080 ss << "\\begin{" << inner_type << '}';
1082 ss << '\\' << inner_type;
1084 if (!position.empty())
1085 ss << '[' << position << ']';
1086 if (!latex_height.empty())
1087 ss << '[' << latex_height << ']';
1088 if (!inner_pos.empty())
1089 ss << '[' << inner_pos << ']';
1090 ss << '{' << latex_width << '}';
1091 if (!(inner_flags & FLAG_END))
1094 if (inner_type == "shaded")
1095 ss << "\\begin{shaded}";
1096 output_ert_inset(os, ss.str(), parent_context);
1097 if (!inner_type.empty()) {
1098 parse_text(p, os, inner_flags, outer, parent_context);
1099 if (inner_flags & FLAG_END)
1100 output_ert_inset(os, "\\end{" + inner_type + '}',
1103 output_ert_inset(os, "}", parent_context);
1105 if (!outer_type.empty()) {
1106 // If we already read the inner box we have to pop
1108 if (!inner_type.empty() && (inner_flags & FLAG_END))
1109 active_environments.pop_back();
1111 // Ensure that the end of the outer box is parsed correctly:
1112 // The opening brace has been eaten by parse_outer_box()
1113 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1114 outer_flags &= ~FLAG_ITEM;
1115 outer_flags |= FLAG_BRACE_LAST;
1117 parse_text(p, os, outer_flags, outer, parent_context);
1118 if (outer_flags & FLAG_END)
1119 output_ert_inset(os, "\\end{" + outer_type + '}',
1122 output_ert_inset(os, "}", parent_context);
1125 // LyX does not like empty positions, so we have
1126 // to set them to the LaTeX default values here.
1127 if (position.empty())
1129 if (inner_pos.empty())
1130 inner_pos = position;
1131 parent_context.check_layout(os);
1132 begin_inset(os, "Box ");
1133 if (outer_type == "framed")
1135 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1137 else if (outer_type == "shadowbox")
1138 os << "Shadowbox\n";
1139 else if ((outer_type == "shaded" && inner_type.empty()) ||
1140 (outer_type == "minipage" && inner_type == "shaded") ||
1141 (outer_type == "parbox" && inner_type == "shaded")) {
1143 preamble.registerAutomaticallyLoadedPackage("color");
1144 } else if (outer_type == "doublebox")
1145 os << "Doublebox\n";
1146 else if (outer_type.empty() || outer_type == "mbox")
1147 os << "Frameless\n";
1149 os << outer_type << '\n';
1150 os << "position \"" << position << "\"\n";
1151 os << "hor_pos \"" << hor_pos << "\"\n";
1152 if (outer_type == "mbox")
1153 os << "has_inner_box 1\n";
1154 else if (!frame_color.empty() && inner_type == "makebox")
1155 os << "has_inner_box 0\n";
1157 os << "has_inner_box " << !inner_type.empty() << "\n";
1158 os << "inner_pos \"" << inner_pos << "\"\n";
1159 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1161 if (outer_type == "mbox")
1162 os << "use_makebox 1\n";
1163 else if (!frame_color.empty())
1164 os << "use_makebox 0\n";
1166 os << "use_makebox " << (inner_type == "makebox") << '\n';
1167 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1168 os << "width \"\"\n";
1169 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1170 else if (contains(width_unit, '\\'))
1171 os << "width \"" << width_value << "in" << "\"\n";
1173 os << "width \"" << width_value << width_unit << "\"\n";
1174 if (contains(width_unit, '\\')) {
1175 width_unit.erase (0,1); // remove the leading '\'
1176 os << "special \"" << width_unit << "\"\n";
1178 os << "special \"" << width_special << "\"\n";
1179 if (contains(height_unit, '\\'))
1180 os << "height \"" << height_value << "in" << "\"\n";
1182 os << "height \"" << height_value << height_unit << "\"\n";
1183 os << "height_special \"" << height_special << "\"\n";
1184 os << "thickness \"" << thickness << "\"\n";
1185 os << "separation \"" << separation << "\"\n";
1186 os << "shadowsize \"" << shadowsize << "\"\n";
1187 os << "framecolor \"" << framecolor << "\"\n";
1188 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1189 os << "status open\n\n";
1191 // Unfortunately we can't use parse_text_in_inset:
1192 // InsetBox::forcePlainLayout() is hard coded and does not
1193 // use the inset layout. Apart from that do we call parse_text
1194 // up to two times, but need only one check_end_layout.
1195 bool const forcePlainLayout =
1196 (!inner_type.empty() || inner_type == "makebox") &&
1197 outer_type != "shaded" && outer_type != "framed";
1198 Context context(true, parent_context.textclass);
1199 if (forcePlainLayout)
1200 context.layout = &context.textclass.plainLayout();
1202 context.font = parent_context.font;
1204 // If we have no inner box the contents will be read with the outer box
1205 if (!inner_type.empty())
1206 parse_text(p, os, inner_flags, outer, context);
1208 // Ensure that the end of the outer box is parsed correctly:
1209 // The opening brace has been eaten by parse_outer_box()
1210 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1211 outer_flags &= ~FLAG_ITEM;
1212 outer_flags |= FLAG_BRACE_LAST;
1215 // Find end of outer box, output contents if inner_type is
1216 // empty and output possible comments
1217 if (!outer_type.empty()) {
1218 // If we already read the inner box we have to pop
1220 if (!inner_type.empty() && (inner_flags & FLAG_END))
1221 active_environments.pop_back();
1222 // This does not output anything but comments if
1223 // inner_type is not empty (see use_ert)
1224 parse_text(p, os, outer_flags, outer, context);
1227 context.check_end_layout(os);
1229 #ifdef PRESERVE_LAYOUT
1230 // LyX puts a % after the end of the minipage
1231 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1233 //output_comment(p, os, "dummy", parent_context);
1236 parent_context.new_paragraph(os);
1238 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1239 //output_comment(p, os, "dummy", parent_context);
1242 // We add a protected space if something real follows
1243 if (p.good() && p.next_token().cat() != catComment) {
1244 begin_inset(os, "space ~\n");
1250 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1251 active_environments.pop_back();
1252 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1253 // in this case we have to eat the the closing brace of the color box
1254 p.get_token().asInput(); // the '}'
1256 if (p.next_token().asInput() == "}") {
1257 // in this case we assume that the closing brace is from the box settings
1258 // therefore reset these values for the next box
1264 // all boxes except of Frameless and Shaded require calc
1265 if (!(outer_type.empty() || outer_type == "mbox") &&
1266 !((outer_type == "shaded" && inner_type.empty()) ||
1267 (outer_type == "minipage" && inner_type == "shaded") ||
1268 (outer_type == "parbox" && inner_type == "shaded")))
1269 preamble.registerAutomaticallyLoadedPackage("calc");
1273 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1274 Context & parent_context, string const & outer_type,
1275 string const & special)
1277 eat_whitespace(p, os, parent_context, false);
1278 if (flags & FLAG_ITEM) {
1280 if (p.next_token().cat() == catBegin)
1283 cerr << "Warning: Ignoring missing '{' after \\"
1284 << outer_type << '.' << endl;
1285 eat_whitespace(p, os, parent_context, false);
1288 unsigned int inner_flags = 0;
1290 if (outer_type == "minipage" || outer_type == "parbox") {
1291 p.skip_spaces(true);
1292 while (p.hasOpt()) {
1294 p.skip_spaces(true);
1297 p.skip_spaces(true);
1298 if (outer_type == "parbox") {
1300 if (p.next_token().cat() == catBegin)
1302 p.skip_spaces(true);
1305 if (outer_type == "shaded" || outer_type == "mbox") {
1306 // These boxes never have an inner box
1308 } else if (p.next_token().asInput() == "\\parbox") {
1309 inner = p.get_token().cs();
1310 inner_flags = FLAG_ITEM;
1311 } else if (p.next_token().asInput() == "\\begin") {
1312 // Is this a minipage or shaded box?
1315 inner = p.getArg('{', '}');
1317 if (inner == "minipage" || inner == "shaded")
1318 inner_flags = FLAG_END;
1323 if (inner_flags == FLAG_END) {
1324 if (inner != "shaded")
1328 eat_whitespace(p, os, parent_context, false);
1330 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1331 outer_type, special, inner, "", "");
1333 if (inner_flags == FLAG_ITEM) {
1335 eat_whitespace(p, os, parent_context, false);
1337 parse_box(p, os, flags, inner_flags, outer, parent_context,
1338 outer_type, special, inner, "", "");
1343 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1344 bool in_line, bool use_minted)
1346 parent_context.check_layout(os);
1347 begin_inset(os, "listings\n");
1348 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1350 while ((i = arg.find(", ")) != string::npos
1351 || (i = arg.find(",\t")) != string::npos)
1352 arg.erase(i + 1, 1);
1355 string const language = p.getArg('{', '}');
1356 p.skip_spaces(true);
1357 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1358 if (!minted_float.empty()) {
1359 arg += string(arg.empty() ? "" : ",") + minted_float;
1360 minted_nonfloat_caption.clear();
1364 os << "lstparams " << '"' << arg << '"' << '\n';
1365 if (arg.find("\\color") != string::npos)
1366 preamble.registerAutomaticallyLoadedPackage("color");
1369 os << "inline true\n";
1371 os << "inline false\n";
1372 os << "status collapsed\n";
1373 Context context(true, parent_context.textclass);
1374 context.layout = &parent_context.textclass.plainLayout();
1375 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1376 minted_nonfloat_caption.erase(0,3);
1377 os << "\n\\begin_layout Plain Layout\n";
1378 begin_inset(os, "Caption Standard\n");
1379 Context newcontext(true, context.textclass,
1380 context.layout, 0, context.font);
1381 newcontext.check_layout(os);
1382 os << minted_nonfloat_caption << "\n";
1383 newcontext.check_end_layout(os);
1385 os << "\n\\end_layout\n";
1386 minted_nonfloat_caption.clear();
1390 // set catcodes to verbatim early, just in case.
1391 p.setCatcodes(VERBATIM_CATCODES);
1392 string delim = p.get_token().asInput();
1393 //FIXME: handler error condition
1394 s = p.verbatimStuff(delim).second;
1395 // context.new_paragraph(os);
1396 } else if (use_minted) {
1397 s = p.verbatimEnvironment("minted");
1399 s = p.verbatimEnvironment("lstlisting");
1401 output_ert(os, s, context);
1402 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1403 minted_nonfloat_caption.erase(0,3);
1404 os << "\n\\begin_layout Plain Layout\n";
1405 begin_inset(os, "Caption Standard\n");
1406 Context newcontext(true, context.textclass,
1407 context.layout, 0, context.font);
1408 newcontext.check_layout(os);
1409 os << minted_nonfloat_caption << "\n";
1410 newcontext.check_end_layout(os);
1412 os << "\n\\end_layout\n";
1413 minted_nonfloat_caption.clear();
1415 // Don't close the inset here for floating minted listings.
1416 // It will be closed at the end of the listing environment.
1417 if (!use_minted || minted_float.empty())
1420 eat_whitespace(p, os, parent_context, true);
1421 Token t = p.get_token();
1422 if (t.asInput() != "\\end") {
1423 // If anything follows, collect it into a caption.
1424 minted_float_has_caption = true;
1425 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1426 begin_inset(os, "Caption Standard\n");
1427 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1434 /// parse an unknown environment
1435 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1436 unsigned flags, bool outer,
1437 Context & parent_context)
1439 if (name == "tabbing")
1440 // We need to remember that we have to handle '\=' specially
1441 flags |= FLAG_TABBING;
1443 // We need to translate font changes and paragraphs inside the
1444 // environment to ERT if we have a non standard font.
1445 // Otherwise things like
1446 // \large\begin{foo}\huge bar\end{foo}
1448 bool const specialfont =
1449 (parent_context.font != parent_context.normalfont);
1450 bool const new_layout_allowed = parent_context.new_layout_allowed;
1452 parent_context.new_layout_allowed = false;
1453 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1454 parse_text_snippet(p, os, flags, outer, parent_context);
1455 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1457 parent_context.new_layout_allowed = new_layout_allowed;
1461 void parse_environment(Parser & p, ostream & os, bool outer,
1462 string & last_env, Context & parent_context)
1464 Layout const * newlayout;
1465 InsetLayout const * newinsetlayout = 0;
1466 string const name = p.getArg('{', '}');
1467 const bool is_starred = suffixIs(name, '*');
1468 string const unstarred_name = rtrim(name, "*");
1469 active_environments.push_back(name);
1471 if (is_math_env(name)) {
1472 parent_context.check_layout(os);
1473 begin_inset(os, "Formula ");
1474 os << "\\begin{" << name << "}";
1475 parse_math(p, os, FLAG_END, MATH_MODE);
1476 os << "\\end{" << name << "}";
1478 if (is_display_math_env(name)) {
1479 // Prevent the conversion of a line break to a space
1480 // (bug 7668). This does not change the output, but
1481 // looks ugly in LyX.
1482 eat_whitespace(p, os, parent_context, false);
1486 else if (is_known(name, preamble.polyglossia_languages)) {
1487 // We must begin a new paragraph if not already done
1488 if (! parent_context.atParagraphStart()) {
1489 parent_context.check_end_layout(os);
1490 parent_context.new_paragraph(os);
1492 // save the language in the context so that it is
1493 // handled by parse_text
1494 parent_context.font.language = preamble.polyglossia2lyx(name);
1495 parse_text(p, os, FLAG_END, outer, parent_context);
1496 // Just in case the environment is empty
1497 parent_context.extra_stuff.erase();
1498 // We must begin a new paragraph to reset the language
1499 parent_context.new_paragraph(os);
1503 else if (unstarred_name == "tabular" || name == "longtable") {
1504 eat_whitespace(p, os, parent_context, false);
1505 string width = "0pt";
1506 if (name == "tabular*") {
1507 width = lyx::translate_len(p.getArg('{', '}'));
1508 eat_whitespace(p, os, parent_context, false);
1510 parent_context.check_layout(os);
1511 begin_inset(os, "Tabular ");
1512 handle_tabular(p, os, name, width, parent_context);
1517 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1518 eat_whitespace(p, os, parent_context, false);
1519 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1520 eat_whitespace(p, os, parent_context, false);
1521 parent_context.check_layout(os);
1522 begin_inset(os, "Float " + unstarred_name + "\n");
1523 // store the float type for subfloats
1524 // subfloats only work with figures and tables
1525 if (unstarred_name == "figure")
1526 float_type = unstarred_name;
1527 else if (unstarred_name == "table")
1528 float_type = unstarred_name;
1532 os << "placement " << opt << '\n';
1533 if (contains(opt, "H"))
1534 preamble.registerAutomaticallyLoadedPackage("float");
1536 Floating const & fl = parent_context.textclass.floats()
1537 .getType(unstarred_name);
1538 if (!fl.floattype().empty() && fl.usesFloatPkg())
1539 preamble.registerAutomaticallyLoadedPackage("float");
1542 os << "wide " << convert<string>(is_starred)
1543 << "\nsideways false"
1544 << "\nstatus open\n\n";
1545 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1547 // We don't need really a new paragraph, but
1548 // we must make sure that the next item gets a \begin_layout.
1549 parent_context.new_paragraph(os);
1551 // the float is parsed thus delete the type
1555 else if (unstarred_name == "sidewaysfigure"
1556 || unstarred_name == "sidewaystable"
1557 || unstarred_name == "sidewaysalgorithm") {
1558 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1559 eat_whitespace(p, os, parent_context, false);
1560 parent_context.check_layout(os);
1561 if (unstarred_name == "sidewaysfigure")
1562 begin_inset(os, "Float figure\n");
1563 else if (unstarred_name == "sidewaystable")
1564 begin_inset(os, "Float table\n");
1565 else if (unstarred_name == "sidewaysalgorithm")
1566 begin_inset(os, "Float algorithm\n");
1568 os << "placement " << opt << '\n';
1569 if (contains(opt, "H"))
1570 preamble.registerAutomaticallyLoadedPackage("float");
1571 os << "wide " << convert<string>(is_starred)
1572 << "\nsideways true"
1573 << "\nstatus open\n\n";
1574 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1576 // We don't need really a new paragraph, but
1577 // we must make sure that the next item gets a \begin_layout.
1578 parent_context.new_paragraph(os);
1580 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1583 else if (name == "wrapfigure" || name == "wraptable") {
1584 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1585 eat_whitespace(p, os, parent_context, false);
1586 parent_context.check_layout(os);
1589 string overhang = "0col%";
1592 lines = p.getArg('[', ']');
1593 string const placement = p.getArg('{', '}');
1595 overhang = p.getArg('[', ']');
1596 string const width = p.getArg('{', '}');
1598 if (name == "wrapfigure")
1599 begin_inset(os, "Wrap figure\n");
1601 begin_inset(os, "Wrap table\n");
1602 os << "lines " << lines
1603 << "\nplacement " << placement
1604 << "\noverhang " << lyx::translate_len(overhang)
1605 << "\nwidth " << lyx::translate_len(width)
1606 << "\nstatus open\n\n";
1607 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1609 // We don't need really a new paragraph, but
1610 // we must make sure that the next item gets a \begin_layout.
1611 parent_context.new_paragraph(os);
1613 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1616 else if (name == "minipage") {
1617 eat_whitespace(p, os, parent_context, false);
1618 // Test whether this is an outer box of a shaded box
1620 // swallow arguments
1621 while (p.hasOpt()) {
1623 p.skip_spaces(true);
1626 p.skip_spaces(true);
1627 Token t = p.get_token();
1628 bool shaded = false;
1629 if (t.asInput() == "\\begin") {
1630 p.skip_spaces(true);
1631 if (p.getArg('{', '}') == "shaded")
1636 parse_outer_box(p, os, FLAG_END, outer,
1637 parent_context, name, "shaded");
1639 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1640 "", "", name, "", "");
1644 else if (name == "comment") {
1645 eat_whitespace(p, os, parent_context, false);
1646 parent_context.check_layout(os);
1647 begin_inset(os, "Note Comment\n");
1648 os << "status open\n";
1649 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1652 skip_braces(p); // eat {} that might by set by LyX behind comments
1653 preamble.registerAutomaticallyLoadedPackage("verbatim");
1656 else if (unstarred_name == "verbatim") {
1657 // FIXME: this should go in the generic code that
1658 // handles environments defined in layout file that
1659 // have "PassThru 1". However, the code over there is
1660 // already too complicated for my taste.
1661 string const ascii_name =
1662 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1663 parent_context.new_paragraph(os);
1664 Context context(true, parent_context.textclass,
1665 &parent_context.textclass[from_ascii(ascii_name)]);
1666 string s = p.verbatimEnvironment(name);
1667 output_ert(os, s, context);
1671 else if (name == "IPA") {
1672 eat_whitespace(p, os, parent_context, false);
1673 parent_context.check_layout(os);
1674 begin_inset(os, "IPA\n");
1675 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1678 preamble.registerAutomaticallyLoadedPackage("tipa");
1679 preamble.registerAutomaticallyLoadedPackage("tipx");
1682 else if (name == "CJK") {
1683 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1684 // It is impossible to decide if a CJK environment was in its own paragraph or within
1685 // a line. We therefore always assume a paragraph since the latter is a rare case.
1686 eat_whitespace(p, os, parent_context, false);
1687 parent_context.check_end_layout(os);
1688 // store the encoding to be able to reset it
1689 string const encoding_old = p.getEncoding();
1690 string const encoding = p.getArg('{', '}');
1691 // FIXME: For some reason JIS does not work. Although the text
1692 // in tests/CJK.tex is identical with the SJIS version if you
1693 // convert both snippets using the recode command line utility,
1694 // the resulting .lyx file contains some extra characters if
1695 // you set buggy_encoding to false for JIS.
1696 bool const buggy_encoding = encoding == "JIS";
1697 if (!buggy_encoding)
1698 p.setEncoding(encoding, Encoding::CJK);
1700 // FIXME: This will read garbage, since the data is not encoded in utf8.
1701 p.setEncoding("UTF-8");
1703 // LyX only supports the same mapping for all CJK
1704 // environments, so we might need to output everything as ERT
1705 string const mapping = trim(p.getArg('{', '}'));
1706 char const * const * const where =
1707 is_known(encoding, supported_CJK_encodings);
1708 if (!buggy_encoding && !preamble.fontCJKSet())
1709 preamble.fontCJK(mapping);
1710 bool knownMapping = mapping == preamble.fontCJK();
1711 if (buggy_encoding || !knownMapping || !where) {
1712 parent_context.check_layout(os);
1713 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1715 // we must parse the content as verbatim because e.g. JIS can contain
1716 // normally invalid characters
1717 // FIXME: This works only for the most simple cases.
1718 // Since TeX control characters are not parsed,
1719 // things like comments are completely wrong.
1720 string const s = p.plainEnvironment("CJK");
1721 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1723 output_ert_inset(os, "\\", parent_context);
1724 else if (*it == '$')
1725 output_ert_inset(os, "$", parent_context);
1726 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1731 output_ert_inset(os, "\\end{" + name + "}",
1735 supported_CJK_languages[where - supported_CJK_encodings];
1736 // store the language because we must reset it at the end
1737 string const lang_old = parent_context.font.language;
1738 parent_context.font.language = lang;
1739 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1740 parent_context.font.language = lang_old;
1741 parent_context.new_paragraph(os);
1743 p.setEncoding(encoding_old);
1747 else if (name == "lyxgreyedout") {
1748 eat_whitespace(p, os, parent_context, false);
1749 parent_context.check_layout(os);
1750 begin_inset(os, "Note Greyedout\n");
1751 os << "status open\n";
1752 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1755 if (!preamble.notefontcolor().empty())
1756 preamble.registerAutomaticallyLoadedPackage("color");
1759 else if (name == "btSect") {
1760 eat_whitespace(p, os, parent_context, false);
1761 parent_context.check_layout(os);
1762 begin_command_inset(os, "bibtex", "bibtex");
1763 string bibstyle = "plain";
1765 bibstyle = p.getArg('[', ']');
1766 p.skip_spaces(true);
1768 string const bibfile = p.getArg('{', '}');
1769 eat_whitespace(p, os, parent_context, false);
1770 Token t = p.get_token();
1771 if (t.asInput() == "\\btPrintCited") {
1772 p.skip_spaces(true);
1773 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1775 if (t.asInput() == "\\btPrintNotCited") {
1776 p.skip_spaces(true);
1777 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1779 if (t.asInput() == "\\btPrintAll") {
1780 p.skip_spaces(true);
1781 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1783 os << "bibfiles " << '"' << bibfile << "\"\n"
1784 << "options " << '"' << bibstyle << "\"\n";
1785 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1790 else if (name == "framed" || name == "shaded") {
1791 eat_whitespace(p, os, parent_context, false);
1792 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1794 preamble.registerAutomaticallyLoadedPackage("framed");
1797 else if (name == "listing") {
1798 minted_float = "float";
1799 eat_whitespace(p, os, parent_context, false);
1800 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1802 minted_float += "=" + opt;
1803 // If something precedes \begin{minted}, we output it at the end
1804 // as a caption, in order to keep it inside the listings inset.
1805 eat_whitespace(p, os, parent_context, true);
1807 Token const & t = p.get_token();
1808 p.skip_spaces(true);
1809 string const envname = p.next_token().cat() == catBegin
1810 ? p.getArg('{', '}') : string();
1811 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1813 minted_float_has_caption = false;
1814 string content = parse_text_snippet(p, FLAG_END, outer,
1816 size_t i = content.find("\\begin_inset listings");
1817 bool minted_env = i != string::npos;
1820 caption = content.substr(0, i);
1821 content.erase(0, i);
1823 parent_context.check_layout(os);
1824 if (minted_env && minted_float_has_caption) {
1825 eat_whitespace(p, os, parent_context, true);
1826 os << content << "\n";
1827 if (!caption.empty())
1828 os << caption << "\n";
1829 os << "\n\\end_layout\n"; // close inner layout
1830 end_inset(os); // close caption inset
1831 os << "\n\\end_layout\n"; // close outer layout
1832 } else if (!caption.empty()) {
1834 begin_inset(os, "listings\n");
1835 os << "lstparams " << '"' << minted_float << '"' << '\n';
1836 os << "inline false\n";
1837 os << "status collapsed\n";
1839 os << "\n\\begin_layout Plain Layout\n";
1840 begin_inset(os, "Caption Standard\n");
1841 Context newcontext(true, parent_context.textclass,
1842 0, 0, parent_context.font);
1843 newcontext.check_layout(os);
1844 os << caption << "\n";
1845 newcontext.check_end_layout(os);
1847 os << "\n\\end_layout\n";
1848 } else if (content.empty()) {
1849 begin_inset(os, "listings\n");
1850 os << "lstparams " << '"' << minted_float << '"' << '\n';
1851 os << "inline false\n";
1852 os << "status collapsed\n";
1854 os << content << "\n";
1856 end_inset(os); // close listings inset
1857 parent_context.check_end_layout(os);
1858 parent_context.new_paragraph(os);
1860 minted_float.clear();
1861 minted_float_has_caption = false;
1864 else if (name == "lstlisting" || name == "minted") {
1865 bool use_minted = name == "minted";
1866 eat_whitespace(p, os, parent_context, false);
1867 if (use_minted && minted_float.empty()) {
1868 // look ahead for a bottom caption
1870 bool found_end_minted = false;
1871 while (!found_end_minted && p.good()) {
1872 Token const & t = p.get_token();
1874 string const envname =
1875 p.next_token().cat() == catBegin
1876 ? p.getArg('{', '}') : string();
1877 found_end_minted = t.asInput() == "\\end"
1878 && envname == "minted";
1880 eat_whitespace(p, os, parent_context, true);
1881 Token const & t = p.get_token();
1882 p.skip_spaces(true);
1883 if (t.asInput() == "\\lyxmintcaption") {
1884 string const pos = p.getArg('[', ']');
1886 string const caption =
1887 parse_text_snippet(p, FLAG_ITEM,
1888 false, parent_context);
1889 minted_nonfloat_caption = "[b]" + caption;
1894 parse_listings(p, os, parent_context, false, use_minted);
1898 else if (!parent_context.new_layout_allowed)
1899 parse_unknown_environment(p, name, os, FLAG_END, outer,
1902 // Alignment and spacing settings
1903 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1904 // therefore are totally broken!
1905 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1906 // they are commands not environments. They are furthermore switches that
1907 // can be ended by another switches, but also by commands like \footnote or
1908 // \parbox. So the only safe way is to leave them untouched.
1909 // However, we support the pseudo-environments
1910 // \begin{centering} ... \end{centering}
1911 // \begin{raggedright} ... \end{raggedright}
1912 // \begin{raggedleft} ... \end{raggedleft}
1913 // since they are used by LyX in floats (for spacing reasons)
1914 else if (name == "center" || name == "centering" ||
1915 name == "flushleft" || name == "raggedright" ||
1916 name == "flushright" || name == "raggedleft" ||
1917 name == "singlespace" || name == "onehalfspace" ||
1918 name == "doublespace" || name == "spacing") {
1919 eat_whitespace(p, os, parent_context, false);
1920 // We must begin a new paragraph if not already done
1921 if (! parent_context.atParagraphStart()) {
1922 parent_context.check_end_layout(os);
1923 parent_context.new_paragraph(os);
1925 if (name == "flushleft" || name == "raggedright")
1926 parent_context.add_extra_stuff("\\align left\n");
1927 else if (name == "flushright" || name == "raggedleft")
1928 parent_context.add_extra_stuff("\\align right\n");
1929 else if (name == "center" || name == "centering")
1930 parent_context.add_extra_stuff("\\align center\n");
1931 else if (name == "singlespace")
1932 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1933 else if (name == "onehalfspace") {
1934 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1935 preamble.registerAutomaticallyLoadedPackage("setspace");
1936 } else if (name == "doublespace") {
1937 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1938 preamble.registerAutomaticallyLoadedPackage("setspace");
1939 } else if (name == "spacing") {
1940 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1941 preamble.registerAutomaticallyLoadedPackage("setspace");
1943 parse_text(p, os, FLAG_END, outer, parent_context);
1944 // Just in case the environment is empty
1945 parent_context.extra_stuff.erase();
1946 // We must begin a new paragraph to reset the alignment
1947 parent_context.new_paragraph(os);
1951 // The single '=' is meant here.
1952 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1953 eat_whitespace(p, os, parent_context, false);
1954 Context context(true, parent_context.textclass, newlayout,
1955 parent_context.layout, parent_context.font);
1956 if (parent_context.deeper_paragraph) {
1957 // We are beginning a nested environment after a
1958 // deeper paragraph inside the outer list environment.
1959 // Therefore we don't need to output a "begin deeper".
1960 context.need_end_deeper = true;
1962 parent_context.check_end_layout(os);
1963 if (last_env == name) {
1964 // we need to output a separator since LyX would export
1965 // the two environments as one otherwise (bug 5716)
1966 TeX2LyXDocClass const & textclass(parent_context.textclass);
1967 Context newcontext(true, textclass,
1968 &(textclass.defaultLayout()));
1969 newcontext.check_layout(os);
1970 begin_inset(os, "Separator plain\n");
1972 newcontext.check_end_layout(os);
1974 switch (context.layout->latextype) {
1975 case LATEX_LIST_ENVIRONMENT:
1976 context.add_par_extra_stuff("\\labelwidthstring "
1977 + p.verbatim_item() + '\n');
1980 case LATEX_BIB_ENVIRONMENT:
1981 p.verbatim_item(); // swallow next arg
1987 context.check_deeper(os);
1988 // handle known optional and required arguments
1989 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1990 // It is impossible to place anything after the environment name,
1991 // but before the first \\item.
1992 if (context.layout->latextype == LATEX_ENVIRONMENT)
1993 output_arguments(os, p, outer, false, false, context,
1994 context.layout->latexargs());
1995 parse_text(p, os, FLAG_END, outer, context);
1996 if (context.layout->latextype == LATEX_ENVIRONMENT)
1997 output_arguments(os, p, outer, false, true, context,
1998 context.layout->postcommandargs());
1999 context.check_end_layout(os);
2000 if (parent_context.deeper_paragraph) {
2001 // We must suppress the "end deeper" because we
2002 // suppressed the "begin deeper" above.
2003 context.need_end_deeper = false;
2005 context.check_end_deeper(os);
2006 parent_context.new_paragraph(os);
2008 if (!preamble.titleLayoutFound())
2009 preamble.titleLayoutFound(newlayout->intitle);
2010 set<string> const & req = newlayout->requires();
2011 set<string>::const_iterator it = req.begin();
2012 set<string>::const_iterator en = req.end();
2013 for (; it != en; ++it)
2014 preamble.registerAutomaticallyLoadedPackage(*it);
2017 // The single '=' is meant here.
2018 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2019 eat_whitespace(p, os, parent_context, false);
2020 parent_context.check_layout(os);
2021 begin_inset(os, "Flex ");
2022 os << to_utf8(newinsetlayout->name()) << '\n'
2023 << "status collapsed\n";
2024 if (newinsetlayout->isPassThru()) {
2025 string const arg = p.verbatimEnvironment(name);
2026 Context context(true, parent_context.textclass,
2027 &parent_context.textclass.plainLayout(),
2028 parent_context.layout);
2029 output_ert(os, arg, parent_context);
2031 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2035 else if (name == "appendix") {
2036 // This is no good latex style, but it works and is used in some documents...
2037 eat_whitespace(p, os, parent_context, false);
2038 parent_context.check_end_layout(os);
2039 Context context(true, parent_context.textclass, parent_context.layout,
2040 parent_context.layout, parent_context.font);
2041 context.check_layout(os);
2042 os << "\\start_of_appendix\n";
2043 parse_text(p, os, FLAG_END, outer, context);
2044 context.check_end_layout(os);
2048 else if (known_environments.find(name) != known_environments.end()) {
2049 vector<ArgumentType> arguments = known_environments[name];
2050 // The last "argument" denotes wether we may translate the
2051 // environment contents to LyX
2052 // The default required if no argument is given makes us
2053 // compatible with the reLyXre environment.
2054 ArgumentType contents = arguments.empty() ?
2057 if (!arguments.empty())
2058 arguments.pop_back();
2059 // See comment in parse_unknown_environment()
2060 bool const specialfont =
2061 (parent_context.font != parent_context.normalfont);
2062 bool const new_layout_allowed =
2063 parent_context.new_layout_allowed;
2065 parent_context.new_layout_allowed = false;
2066 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2067 outer, parent_context);
2068 if (contents == verbatim)
2069 output_ert_inset(os, p.ertEnvironment(name),
2072 parse_text_snippet(p, os, FLAG_END, outer,
2074 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2076 parent_context.new_layout_allowed = new_layout_allowed;
2080 parse_unknown_environment(p, name, os, FLAG_END, outer,
2084 active_environments.pop_back();
2088 /// parses a comment and outputs it to \p os.
2089 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2091 LASSERT(t.cat() == catComment, return);
2092 if (!t.cs().empty()) {
2093 context.check_layout(os);
2094 output_comment(p, os, t.cs(), context);
2095 if (p.next_token().cat() == catNewline) {
2096 // A newline after a comment line starts a new
2098 if (context.new_layout_allowed) {
2099 if(!context.atParagraphStart())
2100 // Only start a new paragraph if not already
2101 // done (we might get called recursively)
2102 context.new_paragraph(os);
2104 output_ert_inset(os, "\n", context);
2105 eat_whitespace(p, os, context, true);
2108 // "%\n" combination
2115 * Reads spaces and comments until the first non-space, non-comment token.
2116 * New paragraphs (double newlines or \\par) are handled like simple spaces
2117 * if \p eatParagraph is true.
2118 * Spaces are skipped, but comments are written to \p os.
2120 void eat_whitespace(Parser & p, ostream & os, Context & context,
2124 Token const & t = p.get_token();
2125 if (t.cat() == catComment)
2126 parse_comment(p, os, t, context);
2127 else if ((! eatParagraph && p.isParagraph()) ||
2128 (t.cat() != catSpace && t.cat() != catNewline)) {
2137 * Set a font attribute, parse text and reset the font attribute.
2138 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2139 * \param currentvalue Current value of the attribute. Is set to the new
2140 * value during parsing.
2141 * \param newvalue New value of the attribute
2143 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2144 Context & context, string const & attribute,
2145 string & currentvalue, string const & newvalue)
2147 context.check_layout(os);
2148 string const oldvalue = currentvalue;
2149 currentvalue = newvalue;
2150 os << '\n' << attribute << ' ' << newvalue << "\n";
2151 parse_text_snippet(p, os, flags, outer, context);
2152 context.check_layout(os);
2153 os << '\n' << attribute << ' ' << oldvalue << "\n";
2154 currentvalue = oldvalue;
2158 /// get the arguments of a natbib or jurabib citation command
2159 void get_cite_arguments(Parser & p, bool natbibOrder,
2160 string & before, string & after, bool const qualified = false)
2162 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2164 // text before the citation
2166 // text after the citation
2167 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2169 if (!after.empty()) {
2170 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2171 if (natbibOrder && !before.empty())
2172 swap(before, after);
2177 void copy_file(FileName const & src, string dstname)
2181 string const absParent = getParentFilePath(false);
2183 if (FileName::isAbsolute(dstname))
2184 dst = FileName(dstname);
2186 dst = makeAbsPath(dstname, absParent);
2187 FileName const srcpath = src.onlyPath();
2188 FileName const dstpath = dst.onlyPath();
2189 if (equivalent(srcpath, dstpath))
2191 if (!dstpath.isDirectory()) {
2192 if (!dstpath.createPath()) {
2193 cerr << "Warning: Could not create directory for file `"
2194 << dst.absFileName() << "´." << endl;
2198 if (dst.isReadableFile()) {
2199 if (overwriteFiles())
2200 cerr << "Warning: Overwriting existing file `"
2201 << dst.absFileName() << "´." << endl;
2203 cerr << "Warning: Not overwriting existing file `"
2204 << dst.absFileName() << "´." << endl;
2208 if (!src.copyTo(dst))
2209 cerr << "Warning: Could not copy file `" << src.absFileName()
2210 << "´ to `" << dst.absFileName() << "´." << endl;
2214 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2215 bool parse_chunk(Parser & p, ostream & os, Context & context)
2217 // check whether a chunk is possible here.
2218 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2224 // read the parameters
2225 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2226 if (!params.first) {
2231 Parser::Arg const code = p.verbatimStuff("\n@");
2236 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2237 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2241 // The last newline read is important for paragraph handling
2245 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2246 // We must have a valid layout before outputting the Chunk inset.
2247 context.check_layout(os);
2248 Context chunkcontext(true, context.textclass);
2249 chunkcontext.layout = &context.textclass.plainLayout();
2250 begin_inset(os, "Flex Chunk");
2251 os << "\nstatus open\n";
2252 if (!params.second.empty()) {
2253 chunkcontext.check_layout(os);
2254 Context paramscontext(true, context.textclass);
2255 paramscontext.layout = &context.textclass.plainLayout();
2256 begin_inset(os, "Argument 1");
2257 os << "\nstatus open\n";
2258 output_ert(os, params.second, paramscontext);
2261 output_ert(os, code.second, chunkcontext);
2269 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2270 bool is_macro(Parser & p)
2272 Token first = p.curr_token();
2273 if (first.cat() != catEscape || !p.good())
2275 if (first.cs() == "def")
2277 if (first.cs() != "global" && first.cs() != "long")
2279 Token second = p.get_token();
2281 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2282 second.cat() == catNewline || second.cat() == catComment)) {
2283 second = p.get_token();
2286 bool secondvalid = second.cat() == catEscape;
2288 bool thirdvalid = false;
2289 if (p.good() && first.cs() == "global" && secondvalid &&
2290 second.cs() == "long") {
2291 third = p.get_token();
2293 while (p.good() && !p.isParagraph() &&
2294 (third.cat() == catSpace ||
2295 third.cat() == catNewline ||
2296 third.cat() == catComment)) {
2297 third = p.get_token();
2300 thirdvalid = third.cat() == catEscape;
2302 for (int i = 0; i < pos; ++i)
2307 return (first.cs() == "global" || first.cs() == "long") &&
2308 second.cs() == "def";
2309 return first.cs() == "global" && second.cs() == "long" &&
2310 third.cs() == "def";
2314 /// Parse a macro definition (assumes that is_macro() returned true)
2315 void parse_macro(Parser & p, ostream & os, Context & context)
2317 context.check_layout(os);
2318 Token first = p.curr_token();
2321 string command = first.asInput();
2322 if (first.cs() != "def") {
2324 eat_whitespace(p, os, context, false);
2325 second = p.curr_token();
2326 command += second.asInput();
2327 if (second.cs() != "def") {
2329 eat_whitespace(p, os, context, false);
2330 third = p.curr_token();
2331 command += third.asInput();
2334 eat_whitespace(p, os, context, false);
2335 string const name = p.get_token().cs();
2336 eat_whitespace(p, os, context, false);
2342 while (p.next_token().cat() != catBegin) {
2343 if (p.next_token().cat() == catParameter) {
2348 // followed by number?
2349 if (p.next_token().cat() == catOther) {
2350 string s = p.get_token().asInput();
2352 // number = current arity + 1?
2353 if (s.size() == 1 && s[0] == arity + '0' + 1)
2358 paramtext += p.get_token().cs();
2360 paramtext += p.get_token().cs();
2365 // only output simple (i.e. compatible) macro as FormulaMacros
2366 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2368 context.check_layout(os);
2369 begin_inset(os, "FormulaMacro");
2370 os << "\n\\def" << ert;
2373 output_ert_inset(os, command + ert, context);
2377 void registerExternalTemplatePackages(string const & name)
2379 external::TemplateManager const & etm = external::TemplateManager::get();
2380 external::Template const * const et = etm.getTemplateByName(name);
2383 external::Template::Formats::const_iterator cit = et->formats.end();
2385 cit = et->formats.find("PDFLaTeX");
2386 if (cit == et->formats.end())
2387 // If the template has not specified a PDFLaTeX output,
2388 // we try the LaTeX format.
2389 cit = et->formats.find("LaTeX");
2390 if (cit == et->formats.end())
2392 vector<string>::const_iterator qit = cit->second.requirements.begin();
2393 vector<string>::const_iterator qend = cit->second.requirements.end();
2394 for (; qit != qend; ++qit)
2395 preamble.registerAutomaticallyLoadedPackage(*qit);
2398 } // anonymous namespace
2402 * Find a file with basename \p name in path \p path and an extension
2405 string find_file(string const & name, string const & path,
2406 char const * const * extensions)
2408 for (char const * const * what = extensions; *what; ++what) {
2409 string const trial = addExtension(name, *what);
2410 if (makeAbsPath(trial, path).exists())
2417 /// Convert filenames with TeX macros and/or quotes to something LyX
2419 string const normalize_filename(string const & name)
2424 Token const & t = p.get_token();
2425 if (t.cat() != catEscape)
2427 else if (t.cs() == "lyxdot") {
2428 // This is used by LyX for simple dots in relative
2432 } else if (t.cs() == "space") {
2435 } else if (t.cs() == "string") {
2436 // Convert \string" to " and \string~ to ~
2437 Token const & n = p.next_token();
2438 if (n.asInput() != "\"" && n.asInput() != "~")
2443 // Strip quotes. This is a bit complicated (see latex_path()).
2444 string full = os.str();
2445 if (!full.empty() && full[0] == '"') {
2446 string base = removeExtension(full);
2447 string ext = getExtension(full);
2448 if (!base.empty() && base[base.length()-1] == '"')
2451 return addExtension(trim(base, "\""), ext);
2452 if (full[full.length()-1] == '"')
2455 return trim(full, "\"");
2461 /// Convert \p name from TeX convention (relative to master file) to LyX
2462 /// convention (relative to .lyx file) if it is relative
2463 void fix_child_filename(string & name)
2465 string const absMasterTeX = getMasterFilePath(true);
2466 bool const isabs = FileName::isAbsolute(name);
2467 // convert from "relative to .tex master" to absolute original path
2469 name = makeAbsPath(name, absMasterTeX).absFileName();
2470 bool copyfile = copyFiles();
2471 string const absParentLyX = getParentFilePath(false);
2474 // convert from absolute original path to "relative to master file"
2475 string const rel = to_utf8(makeRelPath(from_utf8(name),
2476 from_utf8(absMasterTeX)));
2477 // re-interpret "relative to .tex file" as "relative to .lyx file"
2478 // (is different if the master .lyx file resides in a
2479 // different path than the master .tex file)
2480 string const absMasterLyX = getMasterFilePath(false);
2481 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2482 // Do not copy if the new path is impossible to create. Example:
2483 // absMasterTeX = "/foo/bar/"
2484 // absMasterLyX = "/bar/"
2485 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2486 if (contains(name, "/../"))
2493 // convert from absolute original path to
2494 // "relative to .lyx file"
2495 name = to_utf8(makeRelPath(from_utf8(abs),
2496 from_utf8(absParentLyX)));
2500 // convert from absolute original path to "relative to .lyx file"
2501 name = to_utf8(makeRelPath(from_utf8(name),
2502 from_utf8(absParentLyX)));
2507 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2510 Layout const * newlayout = 0;
2511 InsetLayout const * newinsetlayout = 0;
2512 char const * const * where = 0;
2513 // Store the latest bibliographystyle, addcontentslineContent and
2514 // nocite{*} option (needed for bibtex inset)
2516 string contentslineContent;
2517 string bibliographystyle = "default";
2518 bool const use_natbib = isProvided("natbib");
2519 bool const use_jurabib = isProvided("jurabib");
2520 bool const use_biblatex = isProvided("biblatex")
2521 && preamble.citeEngine() != "biblatex-natbib";
2522 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2523 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2524 need_commentbib = use_biblatex || use_biblatex_natbib;
2527 // it is impossible to determine the correct encoding for non-CJK Japanese.
2528 // Therefore write a note at the beginning of the document
2529 if (is_nonCJKJapanese) {
2530 context.check_layout(os);
2531 begin_inset(os, "Note Note\n");
2532 os << "status open\n\\begin_layout Plain Layout\n"
2533 << "\\series bold\n"
2534 << "Important information:\n"
2535 << "\\end_layout\n\n"
2536 << "\\begin_layout Plain Layout\n"
2537 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2538 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2539 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2540 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2541 << " and specify the encoding using the -e command-line switch.\n"
2542 << " In addition, you might want to double check that the desired output encoding\n"
2543 << " is correctly selected in Document > Settings > Language.\n"
2544 << "\\end_layout\n";
2546 is_nonCJKJapanese = false;
2549 bool have_cycled = false;
2551 // Leave here only after at least one cycle
2552 if (have_cycled && flags & FLAG_LEAVE) {
2553 flags &= ~FLAG_LEAVE;
2557 Token const & t = p.get_token();
2559 debugToken(cerr, t, flags);
2562 if (flags & FLAG_ITEM) {
2563 if (t.cat() == catSpace)
2566 flags &= ~FLAG_ITEM;
2567 if (t.cat() == catBegin) {
2568 // skip the brace and collect everything to the next matching
2570 flags |= FLAG_BRACE_LAST;
2574 // handle only this single token, leave the loop if done
2575 flags |= FLAG_LEAVE;
2578 if (t.cat() != catEscape && t.character() == ']' &&
2579 (flags & FLAG_BRACK_LAST))
2581 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2584 // If there is anything between \end{env} and \begin{env} we
2585 // don't need to output a separator.
2586 if (t.cat() != catSpace && t.cat() != catNewline &&
2587 t.asInput() != "\\begin")
2594 bool const starred = p.next_token().asInput() == "*";
2595 string const starredname(starred ? (t.cs() + '*') : t.cs());
2596 if (t.cat() == catMath) {
2597 // we are inside some text mode thingy, so opening new math is allowed
2598 context.check_layout(os);
2599 begin_inset(os, "Formula ");
2600 Token const & n = p.get_token();
2601 bool const display(n.cat() == catMath && outer);
2603 // TeX's $$...$$ syntax for displayed math
2605 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2607 p.get_token(); // skip the second '$' token
2609 // simple $...$ stuff
2612 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2617 // Prevent the conversion of a line break to a
2618 // space (bug 7668). This does not change the
2619 // output, but looks ugly in LyX.
2620 eat_whitespace(p, os, context, false);
2625 if (t.cat() == catSuper || t.cat() == catSub) {
2626 cerr << "catcode " << t << " illegal in text mode\n";
2630 // Basic support for english quotes. This should be
2631 // extended to other quotes, but is not so easy (a
2632 // left english quote is the same as a right german
2634 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2635 context.check_layout(os);
2636 begin_inset(os, "Quotes ");
2643 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2644 context.check_layout(os);
2645 begin_inset(os, "Quotes ");
2653 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2654 context.check_layout(os);
2655 begin_inset(os, "Quotes ");
2663 if (t.asInput() == "<"
2664 && p.next_token().asInput() == "<") {
2665 bool has_chunk = false;
2669 has_chunk = parse_chunk(p, os, context);
2675 context.check_layout(os);
2676 begin_inset(os, "Quotes ");
2677 //FIXME: this is a right danish quote;
2678 // why not a left french quote?
2687 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2688 check_space(p, os, context);
2692 // babel shorthands (also used by polyglossia)
2693 // Since these can have different meanings for different languages
2694 // we import them as ERT (but they must be put in ERT to get output
2696 if (t.asInput() == "\"") {
2698 // These are known pairs. We put them together in
2699 // one ERT inset. In other cases (such as "a), only
2700 // the quotation mark is ERTed.
2701 if (p.next_token().asInput() == "\""
2702 || p.next_token().asInput() == "|"
2703 || p.next_token().asInput() == "-"
2704 || p.next_token().asInput() == "~"
2705 || p.next_token().asInput() == "="
2706 || p.next_token().asInput() == "/"
2707 || 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 s += p.next_token().asInput();
2715 output_ert_inset(os, s, context);
2719 if (t.character() == '[' && noweb_mode &&
2720 p.next_token().character() == '[') {
2721 // These can contain underscores
2723 string const s = p.getFullOpt() + ']';
2724 if (p.next_token().character() == ']')
2727 cerr << "Warning: Inserting missing ']' in '"
2728 << s << "'." << endl;
2729 output_ert_inset(os, s, context);
2733 if (t.cat() == catLetter) {
2734 context.check_layout(os);
2739 if (t.cat() == catOther ||
2740 t.cat() == catAlign ||
2741 t.cat() == catParameter) {
2742 context.check_layout(os);
2743 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2744 context.merging_hyphens_allowed &&
2745 context.font.family != "ttfamily" &&
2746 !context.layout->pass_thru) {
2747 if (p.next_next_token().asInput() == "-") {
2749 os << to_utf8(docstring(1, 0x2014));
2753 os << to_utf8(docstring(1, 0x2013));
2756 // This translates "&" to "\\&" which may be wrong...
2761 if (p.isParagraph()) {
2762 // In minted floating listings we will collect
2763 // everything into the caption, where multiple
2764 // paragraphs are forbidden.
2765 if (minted_float.empty()) {
2766 if (context.new_layout_allowed)
2767 context.new_paragraph(os);
2769 output_ert_inset(os, "\\par ", context);
2772 eat_whitespace(p, os, context, true);
2776 if (t.cat() == catActive) {
2777 context.check_layout(os);
2778 if (t.character() == '~') {
2779 if (context.layout->free_spacing)
2782 begin_inset(os, "space ~\n");
2790 if (t.cat() == catBegin) {
2791 Token const next = p.next_token();
2792 Token const end = p.next_next_token();
2793 if (next.cat() == catEnd) {
2795 Token const prev = p.prev_token();
2797 if (p.next_token().character() == '`')
2798 ; // ignore it in {}``
2800 output_ert_inset(os, "{}", context);
2801 } else if (next.cat() == catEscape &&
2802 is_known(next.cs(), known_quotes) &&
2803 end.cat() == catEnd) {
2804 // Something like {\textquoteright} (e.g.
2805 // from writer2latex). LyX writes
2806 // \textquoteright{}, so we may skip the
2807 // braces here for better readability.
2808 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2810 } else if (p.next_token().asInput() == "\\ascii") {
2811 // handle the \ascii characters
2812 // (the case without braces is handled later)
2813 // the code is "{\ascii\xxx}"
2814 p.get_token(); // eat \ascii
2815 string name2 = p.get_token().asInput();
2816 p.get_token(); // eat the final '}'
2817 string const name = "{\\ascii" + name2 + "}";
2821 // get the character from unicodesymbols
2822 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2823 Encodings::TEXT_CMD, termination, rem, &req);
2825 context.check_layout(os);
2828 output_ert_inset(os,
2829 to_utf8(rem), context);
2830 for (set<string>::const_iterator it = req.begin();
2831 it != req.end(); ++it)
2832 preamble.registerAutomaticallyLoadedPackage(*it);
2834 // we did not find a non-ert version
2835 output_ert_inset(os, name, context);
2837 context.check_layout(os);
2838 // special handling of font attribute changes
2839 Token const prev = p.prev_token();
2840 TeXFont const oldFont = context.font;
2841 if (next.character() == '[' ||
2842 next.character() == ']' ||
2843 next.character() == '*') {
2845 if (p.next_token().cat() == catEnd) {
2850 output_ert_inset(os, "{", context);
2851 parse_text_snippet(p, os,
2854 output_ert_inset(os, "}", context);
2856 } else if (! context.new_layout_allowed) {
2857 output_ert_inset(os, "{", context);
2858 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2860 output_ert_inset(os, "}", context);
2861 } else if (is_known(next.cs(), known_sizes)) {
2862 // next will change the size, so we must
2864 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2866 if (!context.atParagraphStart())
2868 << context.font.size << "\n";
2869 } else if (is_known(next.cs(), known_font_families)) {
2870 // next will change the font family, so we
2871 // must reset it here
2872 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2874 if (!context.atParagraphStart())
2876 << context.font.family << "\n";
2877 } else if (is_known(next.cs(), known_font_series)) {
2878 // next will change the font series, so we
2879 // must reset it here
2880 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2882 if (!context.atParagraphStart())
2884 << context.font.series << "\n";
2885 } else if (is_known(next.cs(), known_font_shapes)) {
2886 // next will change the font shape, so we
2887 // must reset it here
2888 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2890 if (!context.atParagraphStart())
2892 << context.font.shape << "\n";
2893 } else if (is_known(next.cs(), known_old_font_families) ||
2894 is_known(next.cs(), known_old_font_series) ||
2895 is_known(next.cs(), known_old_font_shapes)) {
2896 // next will change the font family, series
2897 // and shape, so we must reset it here
2898 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2900 if (!context.atParagraphStart())
2902 << context.font.family
2904 << context.font.series
2906 << context.font.shape << "\n";
2908 output_ert_inset(os, "{", context);
2909 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2911 output_ert_inset(os, "}", context);
2917 if (t.cat() == catEnd) {
2918 if (flags & FLAG_BRACE_LAST) {
2921 cerr << "stray '}' in text\n";
2922 output_ert_inset(os, "}", context);
2926 if (t.cat() == catComment) {
2927 parse_comment(p, os, t, context);
2932 // control sequences
2935 if (t.cs() == "(" || t.cs() == "[") {
2936 bool const simple = t.cs() == "(";
2937 context.check_layout(os);
2938 begin_inset(os, "Formula");
2939 os << " \\" << t.cs();
2940 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2941 os << '\\' << (simple ? ')' : ']');
2944 // Prevent the conversion of a line break to a
2945 // space (bug 7668). This does not change the
2946 // output, but looks ugly in LyX.
2947 eat_whitespace(p, os, context, false);
2952 if (t.cs() == "begin") {
2953 parse_environment(p, os, outer, last_env,
2958 if (t.cs() == "end") {
2959 if (flags & FLAG_END) {
2960 // eat environment name
2961 string const name = p.getArg('{', '}');
2962 if (name != active_environment())
2963 cerr << "\\end{" + name + "} does not match \\begin{"
2964 + active_environment() + "}\n";
2967 p.error("found 'end' unexpectedly");
2971 if (t.cs() == "item") {
2973 bool const optarg = p.hasOpt();
2975 // FIXME: This swallows comments, but we cannot use
2976 // eat_whitespace() since we must not output
2977 // anything before the item.
2978 p.skip_spaces(true);
2979 s = p.verbatimOption();
2981 p.skip_spaces(false);
2983 context.check_layout(os);
2984 if (context.has_item) {
2985 // An item in an unknown list-like environment
2986 // FIXME: Do this in check_layout()!
2987 context.has_item = false;
2989 output_ert_inset(os, "\\item", context);
2991 output_ert_inset(os, "\\item ", context);
2994 if (context.layout->labeltype != LABEL_MANUAL) {
2995 // handle option of itemize item
2996 begin_inset(os, "Argument item:1\n");
2997 os << "status open\n";
2998 os << "\n\\begin_layout Plain Layout\n";
3000 os << parse_text_snippet(p2,
3001 FLAG_BRACK_LAST, outer, context);
3002 // we must not use context.check_end_layout(os)
3003 // because that would close the outer itemize layout
3004 os << "\n\\end_layout\n";
3006 eat_whitespace(p, os, context, false);
3007 } else if (!s.empty()) {
3008 // LyX adds braces around the argument,
3009 // so we need to remove them here.
3010 if (s.size() > 2 && s[0] == '{' &&
3011 s[s.size()-1] == '}')
3012 s = s.substr(1, s.size()-2);
3013 // If the argument contains a space we
3014 // must put it into ERT: Otherwise LyX
3015 // would misinterpret the space as
3016 // item delimiter (bug 7663)
3017 if (contains(s, ' ')) {
3018 output_ert_inset(os, s, context);
3021 os << parse_text_snippet(p2,
3022 FLAG_BRACK_LAST, outer, context);
3024 // The space is needed to separate the
3025 // item from the rest of the sentence.
3027 eat_whitespace(p, os, context, false);
3033 if (t.cs() == "bibitem") {
3035 context.check_layout(os);
3036 eat_whitespace(p, os, context, false);
3037 string label = p.verbatimOption();
3038 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3039 bool const literal = !lbl.first;
3040 label = literal ? subst(label, "\n", " ") : lbl.second;
3041 string lit = literal ? "\"true\"" : "\"false\"";
3042 string key = convert_literate_command_inset_arg(p.verbatim_item());
3043 begin_command_inset(os, "bibitem", "bibitem");
3044 os << "label \"" << label << "\"\n"
3045 << "key \"" << key << "\"\n"
3046 << "literal " << lit << "\n";
3052 // catch the case of \def\inputGnumericTable
3054 if (t.cs() == "def") {
3055 Token second = p.next_token();
3056 if (second.cs() == "inputGnumericTable") {
3060 Token third = p.get_token();
3062 if (third.cs() == "input") {
3066 string name = normalize_filename(p.verbatim_item());
3067 string const path = getMasterFilePath(true);
3068 // We want to preserve relative / absolute filenames,
3069 // therefore path is only used for testing
3070 // The file extension is in every case ".tex".
3071 // So we need to remove this extension and check for
3072 // the original one.
3073 name = removeExtension(name);
3074 if (!makeAbsPath(name, path).exists()) {
3075 char const * const Gnumeric_formats[] = {"gnumeric",
3077 string const Gnumeric_name =
3078 find_file(name, path, Gnumeric_formats);
3079 if (!Gnumeric_name.empty())
3080 name = Gnumeric_name;
3082 FileName const absname = makeAbsPath(name, path);
3083 if (absname.exists()) {
3084 fix_child_filename(name);
3085 copy_file(absname, name);
3087 cerr << "Warning: Could not find file '"
3088 << name << "'." << endl;
3089 context.check_layout(os);
3090 begin_inset(os, "External\n\ttemplate ");
3091 os << "GnumericSpreadsheet\n\tfilename "
3094 context.check_layout(os);
3096 // register the packages that are automatically loaded
3097 // by the Gnumeric template
3098 registerExternalTemplatePackages("GnumericSpreadsheet");
3103 parse_macro(p, os, context);
3107 if (t.cs() == "noindent") {
3109 context.add_par_extra_stuff("\\noindent\n");
3113 if (t.cs() == "appendix") {
3114 context.add_par_extra_stuff("\\start_of_appendix\n");
3115 // We need to start a new paragraph. Otherwise the
3116 // appendix in 'bla\appendix\chapter{' would start
3118 context.new_paragraph(os);
3119 // We need to make sure that the paragraph is
3120 // generated even if it is empty. Otherwise the
3121 // appendix in '\par\appendix\par\chapter{' would
3123 context.check_layout(os);
3124 // FIXME: This is a hack to prevent paragraph
3125 // deletion if it is empty. Handle this better!
3126 output_comment(p, os,
3127 "dummy comment inserted by tex2lyx to "
3128 "ensure that this paragraph is not empty",
3130 // Both measures above may generate an additional
3131 // empty paragraph, but that does not hurt, because
3132 // whitespace does not matter here.
3133 eat_whitespace(p, os, context, true);
3137 // Must catch empty dates before findLayout is called below
3138 if (t.cs() == "date") {
3139 eat_whitespace(p, os, context, false);
3141 string const date = p.verbatim_item();
3144 preamble.suppressDate(true);
3147 preamble.suppressDate(false);
3148 if (context.new_layout_allowed &&
3149 (newlayout = findLayout(context.textclass,
3152 output_command_layout(os, p, outer,
3153 context, newlayout);
3154 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3155 if (!preamble.titleLayoutFound())
3156 preamble.titleLayoutFound(newlayout->intitle);
3157 set<string> const & req = newlayout->requires();
3158 set<string>::const_iterator it = req.begin();
3159 set<string>::const_iterator en = req.end();
3160 for (; it != en; ++it)
3161 preamble.registerAutomaticallyLoadedPackage(*it);
3163 output_ert_inset(os,
3164 "\\date{" + p.verbatim_item() + '}',
3170 // Starred section headings
3171 // Must attempt to parse "Section*" before "Section".
3172 if ((p.next_token().asInput() == "*") &&
3173 context.new_layout_allowed &&
3174 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3177 output_command_layout(os, p, outer, context, newlayout);
3179 if (!preamble.titleLayoutFound())
3180 preamble.titleLayoutFound(newlayout->intitle);
3181 set<string> const & req = newlayout->requires();
3182 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3183 preamble.registerAutomaticallyLoadedPackage(*it);
3187 // Section headings and the like
3188 if (context.new_layout_allowed &&
3189 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3191 output_command_layout(os, p, outer, context, newlayout);
3193 if (!preamble.titleLayoutFound())
3194 preamble.titleLayoutFound(newlayout->intitle);
3195 set<string> const & req = newlayout->requires();
3196 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3197 preamble.registerAutomaticallyLoadedPackage(*it);
3201 if (t.cs() == "subfloat") {
3202 // the syntax is \subfloat[list entry][sub caption]{content}
3203 // if it is a table of figure depends on the surrounding float
3205 // do nothing if there is no outer float
3206 if (!float_type.empty()) {
3207 context.check_layout(os);
3209 begin_inset(os, "Float " + float_type + "\n");
3211 << "\nsideways false"
3212 << "\nstatus collapsed\n\n";
3215 bool has_caption = false;
3216 if (p.next_token().cat() != catEscape &&
3217 p.next_token().character() == '[') {
3218 p.get_token(); // eat '['
3219 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3222 // In case we have two optional args, the second is the caption.
3223 if (p.next_token().cat() != catEscape &&
3224 p.next_token().character() == '[') {
3225 p.get_token(); // eat '['
3226 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3229 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3230 // the caption comes always as the last
3232 // we must make sure that the caption gets a \begin_layout
3233 os << "\n\\begin_layout Plain Layout";
3235 begin_inset(os, "Caption Standard\n");
3236 Context newcontext(true, context.textclass,
3237 0, 0, context.font);
3238 newcontext.check_layout(os);
3239 os << caption << "\n";
3240 newcontext.check_end_layout(os);
3243 // close the layout we opened
3244 os << "\n\\end_layout";
3249 // if the float type is not supported or there is no surrounding float
3254 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3256 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3258 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3259 + "{" + p.verbatim_item() + '}', context);
3264 if (t.cs() == "includegraphics") {
3265 bool const clip = p.next_token().asInput() == "*";
3268 string const arg = p.getArg('[', ']');
3269 map<string, string> opts;
3270 vector<string> keys;
3271 split_map(arg, opts, keys);
3273 opts["clip"] = string();
3274 string name = normalize_filename(p.verbatim_item());
3276 string const path = getMasterFilePath(true);
3277 // We want to preserve relative / absolute filenames,
3278 // therefore path is only used for testing
3279 if (!makeAbsPath(name, path).exists()) {
3280 // The file extension is probably missing.
3281 // Now try to find it out.
3282 string const dvips_name =
3283 find_file(name, path,
3284 known_dvips_graphics_formats);
3285 string const pdftex_name =
3286 find_file(name, path,
3287 known_pdftex_graphics_formats);
3288 if (!dvips_name.empty()) {
3289 if (!pdftex_name.empty()) {
3290 cerr << "This file contains the "
3292 "\"\\includegraphics{"
3294 "However, files\n\""
3295 << dvips_name << "\" and\n\""
3296 << pdftex_name << "\"\n"
3297 "both exist, so I had to make a "
3298 "choice and took the first one.\n"
3299 "Please move the unwanted one "
3300 "someplace else and try again\n"
3301 "if my choice was wrong."
3305 } else if (!pdftex_name.empty()) {
3311 FileName const absname = makeAbsPath(name, path);
3312 if (absname.exists()) {
3313 fix_child_filename(name);
3314 copy_file(absname, name);
3316 cerr << "Warning: Could not find graphics file '"
3317 << name << "'." << endl;
3319 context.check_layout(os);
3320 begin_inset(os, "Graphics ");
3321 os << "\n\tfilename " << name << '\n';
3322 if (opts.find("width") != opts.end())
3324 << translate_len(opts["width"]) << '\n';
3325 if (opts.find("height") != opts.end())
3327 << translate_len(opts["height"]) << '\n';
3328 if (opts.find("scale") != opts.end()) {
3329 istringstream iss(opts["scale"]);
3333 os << "\tscale " << val << '\n';
3335 if (opts.find("angle") != opts.end()) {
3336 os << "\trotateAngle "
3337 << opts["angle"] << '\n';
3338 vector<string>::const_iterator a =
3339 find(keys.begin(), keys.end(), "angle");
3340 vector<string>::const_iterator s =
3341 find(keys.begin(), keys.end(), "width");
3342 if (s == keys.end())
3343 s = find(keys.begin(), keys.end(), "height");
3344 if (s == keys.end())
3345 s = find(keys.begin(), keys.end(), "scale");
3346 if (s != keys.end() && distance(s, a) > 0)
3347 os << "\tscaleBeforeRotation\n";
3349 if (opts.find("origin") != opts.end()) {
3351 string const opt = opts["origin"];
3352 if (opt.find('l') != string::npos) ss << "left";
3353 if (opt.find('r') != string::npos) ss << "right";
3354 if (opt.find('c') != string::npos) ss << "center";
3355 if (opt.find('t') != string::npos) ss << "Top";
3356 if (opt.find('b') != string::npos) ss << "Bottom";
3357 if (opt.find('B') != string::npos) ss << "Baseline";
3358 if (!ss.str().empty())
3359 os << "\trotateOrigin " << ss.str() << '\n';
3361 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3363 if (opts.find("keepaspectratio") != opts.end())
3364 os << "\tkeepAspectRatio\n";
3365 if (opts.find("clip") != opts.end())
3367 if (opts.find("draft") != opts.end())
3369 if (opts.find("bb") != opts.end())
3370 os << "\tBoundingBox "
3371 << opts["bb"] << '\n';
3372 int numberOfbbOptions = 0;
3373 if (opts.find("bbllx") != opts.end())
3374 numberOfbbOptions++;
3375 if (opts.find("bblly") != opts.end())
3376 numberOfbbOptions++;
3377 if (opts.find("bburx") != opts.end())
3378 numberOfbbOptions++;
3379 if (opts.find("bbury") != opts.end())
3380 numberOfbbOptions++;
3381 if (numberOfbbOptions == 4)
3382 os << "\tBoundingBox "
3383 << opts["bbllx"] << " " << opts["bblly"] << " "
3384 << opts["bburx"] << " " << opts["bbury"] << '\n';
3385 else if (numberOfbbOptions > 0)
3386 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3387 numberOfbbOptions = 0;
3388 if (opts.find("natwidth") != opts.end())
3389 numberOfbbOptions++;
3390 if (opts.find("natheight") != opts.end())
3391 numberOfbbOptions++;
3392 if (numberOfbbOptions == 2)
3393 os << "\tBoundingBox 0bp 0bp "
3394 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3395 else if (numberOfbbOptions > 0)
3396 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3397 ostringstream special;
3398 if (opts.find("hiresbb") != opts.end())
3399 special << "hiresbb,";
3400 if (opts.find("trim") != opts.end())
3402 if (opts.find("viewport") != opts.end())
3403 special << "viewport=" << opts["viewport"] << ',';
3404 if (opts.find("totalheight") != opts.end())
3405 special << "totalheight=" << opts["totalheight"] << ',';
3406 if (opts.find("type") != opts.end())
3407 special << "type=" << opts["type"] << ',';
3408 if (opts.find("ext") != opts.end())
3409 special << "ext=" << opts["ext"] << ',';
3410 if (opts.find("read") != opts.end())
3411 special << "read=" << opts["read"] << ',';
3412 if (opts.find("command") != opts.end())
3413 special << "command=" << opts["command"] << ',';
3414 string s_special = special.str();
3415 if (!s_special.empty()) {
3416 // We had special arguments. Remove the trailing ','.
3417 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3419 // TODO: Handle the unknown settings better.
3420 // Warn about invalid options.
3421 // Check whether some option was given twice.
3423 preamble.registerAutomaticallyLoadedPackage("graphicx");
3427 if (t.cs() == "footnote" ||
3428 (t.cs() == "thanks" && context.layout->intitle)) {
3430 context.check_layout(os);
3431 begin_inset(os, "Foot\n");
3432 os << "status collapsed\n\n";
3433 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3438 if (t.cs() == "marginpar") {
3440 context.check_layout(os);
3441 begin_inset(os, "Marginal\n");
3442 os << "status collapsed\n\n";
3443 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3448 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3449 bool const use_minted = t.cs() == "mintinline";
3451 parse_listings(p, os, context, true, use_minted);
3455 if (t.cs() == "ensuremath") {
3457 context.check_layout(os);
3458 string const s = p.verbatim_item();
3459 //FIXME: this never triggers in UTF8
3460 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3463 output_ert_inset(os, "\\ensuremath{" + s + "}",
3468 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3469 if (preamble.titleLayoutFound()) {
3471 skip_spaces_braces(p);
3473 output_ert_inset(os, t.asInput(), context);
3477 if (t.cs() == "tableofcontents"
3478 || t.cs() == "lstlistoflistings"
3479 || t.cs() == "listoflistings") {
3480 string name = t.cs();
3481 if (preamble.minted() && name == "listoflistings")
3482 name.insert(0, "lst");
3483 context.check_layout(os);
3484 begin_command_inset(os, "toc", name);
3486 skip_spaces_braces(p);
3487 if (name == "lstlistoflistings") {
3488 if (preamble.minted())
3489 preamble.registerAutomaticallyLoadedPackage("minted");
3491 preamble.registerAutomaticallyLoadedPackage("listings");
3496 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3497 context.check_layout(os);
3498 if (t.cs() == "listoffigures")
3499 begin_inset(os, "FloatList figure\n");
3501 begin_inset(os, "FloatList table\n");
3503 skip_spaces_braces(p);
3507 if (t.cs() == "listof") {
3508 p.skip_spaces(true);
3509 string const name = p.get_token().cs();
3510 if (context.textclass.floats().typeExist(name)) {
3511 context.check_layout(os);
3512 begin_inset(os, "FloatList ");
3515 p.get_token(); // swallow second arg
3517 output_ert_inset(os, "\\listof{" + name + "}", context);
3521 if ((where = is_known(t.cs(), known_text_font_families))) {
3522 parse_text_attributes(p, os, FLAG_ITEM, outer,
3523 context, "\\family", context.font.family,
3524 known_coded_font_families[where - known_text_font_families]);
3528 if ((where = is_known(t.cs(), known_text_font_series))) {
3529 parse_text_attributes(p, os, FLAG_ITEM, outer,
3530 context, "\\series", context.font.series,
3531 known_coded_font_series[where - known_text_font_series]);
3535 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3536 parse_text_attributes(p, os, FLAG_ITEM, outer,
3537 context, "\\shape", context.font.shape,
3538 known_coded_font_shapes[where - known_text_font_shapes]);
3542 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3543 context.check_layout(os);
3544 TeXFont oldFont = context.font;
3545 context.font.init();
3546 context.font.size = oldFont.size;
3547 os << "\n\\family " << context.font.family << "\n";
3548 os << "\n\\series " << context.font.series << "\n";
3549 os << "\n\\shape " << context.font.shape << "\n";
3550 if (t.cs() == "textnormal") {
3551 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3552 output_font_change(os, context.font, oldFont);
3553 context.font = oldFont;
3555 eat_whitespace(p, os, context, false);
3559 if (t.cs() == "textcolor") {
3560 // scheme is \textcolor{color name}{text}
3561 string const color = p.verbatim_item();
3562 // we support the predefined colors of the color and the xcolor package
3563 if (color == "black" || color == "blue" || color == "cyan"
3564 || color == "green" || color == "magenta" || color == "red"
3565 || color == "white" || color == "yellow") {
3566 context.check_layout(os);
3567 os << "\n\\color " << color << "\n";
3568 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3569 context.check_layout(os);
3570 os << "\n\\color inherit\n";
3571 preamble.registerAutomaticallyLoadedPackage("color");
3572 } else if (color == "brown" || color == "darkgray" || color == "gray"
3573 || color == "lightgray" || color == "lime" || color == "olive"
3574 || color == "orange" || color == "pink" || color == "purple"
3575 || color == "teal" || color == "violet") {
3576 context.check_layout(os);
3577 os << "\n\\color " << color << "\n";
3578 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3579 context.check_layout(os);
3580 os << "\n\\color inherit\n";
3581 preamble.registerAutomaticallyLoadedPackage("xcolor");
3583 // for custom defined colors
3584 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3588 if (t.cs() == "underbar" || t.cs() == "uline") {
3589 // \underbar is not 100% correct (LyX outputs \uline
3590 // of ulem.sty). The difference is that \ulem allows
3591 // line breaks, and \underbar does not.
3592 // Do NOT handle \underline.
3593 // \underbar cuts through y, g, q, p etc.,
3594 // \underline does not.
3595 context.check_layout(os);
3596 os << "\n\\bar under\n";
3597 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3598 context.check_layout(os);
3599 os << "\n\\bar default\n";
3600 preamble.registerAutomaticallyLoadedPackage("ulem");
3604 if (t.cs() == "sout") {
3605 context.check_layout(os);
3606 os << "\n\\strikeout on\n";
3607 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3608 context.check_layout(os);
3609 os << "\n\\strikeout default\n";
3610 preamble.registerAutomaticallyLoadedPackage("ulem");
3614 if (t.cs() == "uuline" || t.cs() == "uwave"
3615 || t.cs() == "emph" || t.cs() == "noun"
3616 || t.cs() == "xout") {
3617 context.check_layout(os);
3618 os << "\n\\" << t.cs() << " on\n";
3619 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3620 context.check_layout(os);
3621 os << "\n\\" << t.cs() << " default\n";
3622 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3623 preamble.registerAutomaticallyLoadedPackage("ulem");
3627 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3628 context.check_layout(os);
3629 string name = p.getArg('{', '}');
3630 string localtime = p.getArg('{', '}');
3631 preamble.registerAuthor(name);
3632 Author const & author = preamble.getAuthor(name);
3633 // from_asctime_utc() will fail if LyX decides to output the
3634 // time in the text language.
3635 time_t ptime = from_asctime_utc(localtime);
3636 if (ptime == static_cast<time_t>(-1)) {
3637 cerr << "Warning: Could not parse time `" << localtime
3638 << "´ for change tracking, using current time instead.\n";
3639 ptime = current_time();
3641 if (t.cs() == "lyxadded")
3642 os << "\n\\change_inserted ";
3644 os << "\n\\change_deleted ";
3645 os << author.bufferId() << ' ' << ptime << '\n';
3646 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3647 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3648 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3649 LaTeXPackages::isAvailable("xcolor");
3650 // No need to test for luatex, since luatex comes in
3651 // two flavours (dvi and pdf), like latex, and those
3652 // are detected by pdflatex.
3653 if (pdflatex || xetex) {
3655 preamble.registerAutomaticallyLoadedPackage("ulem");
3656 preamble.registerAutomaticallyLoadedPackage("xcolor");
3657 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3661 preamble.registerAutomaticallyLoadedPackage("dvipost");
3662 } else if (xcolorulem) {
3663 preamble.registerAutomaticallyLoadedPackage("ulem");
3664 preamble.registerAutomaticallyLoadedPackage("xcolor");
3670 if (t.cs() == "textipa") {
3671 context.check_layout(os);
3672 begin_inset(os, "IPA\n");
3673 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3674 context.merging_hyphens_allowed = false;
3675 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3676 context.merging_hyphens_allowed = merging_hyphens_allowed;
3678 preamble.registerAutomaticallyLoadedPackage("tipa");
3679 preamble.registerAutomaticallyLoadedPackage("tipx");
3683 if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3684 context.check_layout(os);
3685 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3686 os << "status open\n";
3687 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3693 if (t.cs() == "textvertline") {
3694 // FIXME: This is not correct, \textvertline is higher than |
3700 if (t.cs() == "tone" ) {
3701 context.check_layout(os);
3702 // register the tone package
3703 preamble.registerAutomaticallyLoadedPackage("tone");
3704 string content = trimSpaceAndEol(p.verbatim_item());
3705 string command = t.asInput() + "{" + content + "}";
3706 // some tones can be detected by unicodesymbols, some need special code
3707 if (is_known(content, known_tones)) {
3708 os << "\\IPAChar " << command << "\n";
3711 // try to see whether the string is in unicodesymbols
3715 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3716 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3717 termination, rem, &req);
3721 output_ert_inset(os, to_utf8(rem), context);
3722 for (set<string>::const_iterator it = req.begin();
3723 it != req.end(); ++it)
3724 preamble.registerAutomaticallyLoadedPackage(*it);
3726 // we did not find a non-ert version
3727 output_ert_inset(os, command, context);
3731 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3732 t.cs() == "vphantom") {
3733 context.check_layout(os);
3734 if (t.cs() == "phantom")
3735 begin_inset(os, "Phantom Phantom\n");
3736 if (t.cs() == "hphantom")
3737 begin_inset(os, "Phantom HPhantom\n");
3738 if (t.cs() == "vphantom")
3739 begin_inset(os, "Phantom VPhantom\n");
3740 os << "status open\n";
3741 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3747 if (t.cs() == "href") {
3748 context.check_layout(os);
3749 string target = convert_literate_command_inset_arg(p.verbatim_item());
3750 string name = p.verbatim_item();
3751 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3752 bool const literal = !nm.first;
3753 name = literal ? subst(name, "\n", " ") : nm.second;
3754 string lit = literal ? "\"true\"" : "\"false\"";
3756 size_t i = target.find(':');
3757 if (i != string::npos) {
3758 type = target.substr(0, i + 1);
3759 if (type == "mailto:" || type == "file:")
3760 target = target.substr(i + 1);
3761 // handle the case that name is equal to target, except of "http(s)://"
3762 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3765 begin_command_inset(os, "href", "href");
3767 os << "name \"" << name << "\"\n";
3768 os << "target \"" << target << "\"\n";
3769 if (type == "mailto:" || type == "file:")
3770 os << "type \"" << type << "\"\n";
3771 os << "literal " << lit << "\n";
3773 skip_spaces_braces(p);
3777 if (t.cs() == "lyxline") {
3778 // swallow size argument (it is not used anyway)
3780 if (!context.atParagraphStart()) {
3781 // so our line is in the middle of a paragraph
3782 // we need to add a new line, lest this line
3783 // follow the other content on that line and
3784 // run off the side of the page
3785 // FIXME: This may create an empty paragraph,
3786 // but without that it would not be
3787 // possible to set noindent below.
3788 // Fortunately LaTeX does not care
3789 // about the empty paragraph.
3790 context.new_paragraph(os);
3792 if (preamble.indentParagraphs()) {
3793 // we need to unindent, lest the line be too long
3794 context.add_par_extra_stuff("\\noindent\n");
3796 context.check_layout(os);
3797 begin_command_inset(os, "line", "rule");
3798 os << "offset \"0.5ex\"\n"
3799 "width \"100line%\"\n"
3805 if (t.cs() == "rule") {
3806 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3807 string const width = p.getArg('{', '}');
3808 string const thickness = p.getArg('{', '}');
3809 context.check_layout(os);
3810 begin_command_inset(os, "line", "rule");
3811 if (!offset.empty())
3812 os << "offset \"" << translate_len(offset) << "\"\n";
3813 os << "width \"" << translate_len(width) << "\"\n"
3814 "height \"" << translate_len(thickness) << "\"\n";
3819 // handle refstyle first to catch \eqref which can also occur
3820 // without refstyle. Only recognize these commands if
3821 // refstyle.sty was found in the preamble (otherwise \eqref
3822 // and user defined ref commands could be misdetected).
3823 if ((where = is_known(t.cs(), known_refstyle_commands))
3824 && preamble.refstyle()) {
3825 context.check_layout(os);
3826 begin_command_inset(os, "ref", "formatted");
3827 os << "reference \"";
3828 os << known_refstyle_prefixes[where - known_refstyle_commands]
3830 os << convert_literate_command_inset_arg(p.verbatim_item())
3832 os << "plural \"false\"\n";
3833 os << "caps \"false\"\n";
3834 os << "noprefix \"false\"\n";
3836 preamble.registerAutomaticallyLoadedPackage("refstyle");
3840 // if refstyle is used, we must not convert \prettyref to a
3841 // formatted reference, since that would result in a refstyle command.
3842 if ((where = is_known(t.cs(), known_ref_commands)) &&
3843 (t.cs() != "prettyref" || !preamble.refstyle())) {
3844 string const opt = p.getOpt();
3846 context.check_layout(os);
3847 begin_command_inset(os, "ref",
3848 known_coded_ref_commands[where - known_ref_commands]);
3849 os << "reference \""
3850 << convert_literate_command_inset_arg(p.verbatim_item())
3852 os << "plural \"false\"\n";
3853 os << "caps \"false\"\n";
3854 os << "noprefix \"false\"\n";
3856 if (t.cs() == "vref" || t.cs() == "vpageref")
3857 preamble.registerAutomaticallyLoadedPackage("varioref");
3858 else if (t.cs() == "prettyref")
3859 preamble.registerAutomaticallyLoadedPackage("prettyref");
3861 // LyX does not yet support optional arguments of ref commands
3862 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3863 p.verbatim_item() + '}', context);
3869 is_known(t.cs(), known_natbib_commands) &&
3870 ((t.cs() != "citefullauthor" &&
3871 t.cs() != "citeyear" &&
3872 t.cs() != "citeyearpar") ||
3873 p.next_token().asInput() != "*")) {
3874 context.check_layout(os);
3875 string command = t.cs();
3876 if (p.next_token().asInput() == "*") {
3880 if (command == "citefullauthor")
3881 // alternative name for "\\citeauthor*"
3882 command = "citeauthor*";
3884 // text before the citation
3886 // text after the citation
3888 get_cite_arguments(p, true, before, after);
3890 if (command == "cite") {
3891 // \cite without optional argument means
3892 // \citet, \cite with at least one optional
3893 // argument means \citep.
3894 if (before.empty() && after.empty())
3899 if (before.empty() && after == "[]")
3900 // avoid \citet[]{a}
3902 else if (before == "[]" && after == "[]") {
3903 // avoid \citet[][]{a}
3907 bool literal = false;
3908 pair<bool, string> aft;
3909 pair<bool, string> bef;
3910 // remove the brackets around after and before
3911 if (!after.empty()) {
3913 after.erase(after.length() - 1, 1);
3914 aft = convert_latexed_command_inset_arg(after);
3915 literal = !aft.first;
3916 after = literal ? subst(after, "\n", " ") : aft.second;
3918 if (!before.empty()) {
3920 before.erase(before.length() - 1, 1);
3921 bef = convert_latexed_command_inset_arg(before);
3922 literal |= !bef.first;
3923 before = literal ? subst(before, "\n", " ") : bef.second;
3924 if (literal && !after.empty())
3925 after = subst(after, "\n", " ");
3927 string lit = literal ? "\"true\"" : "\"false\"";
3928 begin_command_inset(os, "citation", command);
3929 os << "after " << '"' << after << '"' << "\n";
3930 os << "before " << '"' << before << '"' << "\n";
3932 << convert_literate_command_inset_arg(p.verbatim_item())
3934 << "literal " << lit << "\n";
3936 // Need to set the cite engine if natbib is loaded by
3937 // the document class directly
3938 if (preamble.citeEngine() == "basic")
3939 preamble.citeEngine("natbib");
3944 && is_known(t.cs(), known_biblatex_commands)
3945 && ((t.cs() == "cite"
3946 || t.cs() == "citeauthor"
3947 || t.cs() == "Citeauthor"
3948 || t.cs() == "parencite"
3949 || t.cs() == "citetitle")
3950 || p.next_token().asInput() != "*"))
3951 || (use_biblatex_natbib
3952 && (is_known(t.cs(), known_biblatex_commands)
3953 || is_known(t.cs(), known_natbib_commands))
3954 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3955 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3956 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3957 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3958 || t.cs() == "parencite" || t.cs() == "citetitle")
3959 || p.next_token().asInput() != "*"))){
3960 context.check_layout(os);
3961 string command = t.cs();
3962 if (p.next_token().asInput() == "*") {
3967 bool const qualified = suffixIs(command, "s");
3969 command = rtrim(command, "s");
3971 // text before the citation
3973 // text after the citation
3975 get_cite_arguments(p, true, before, after, qualified);
3977 // These use natbib cmd names in LyX
3978 // for inter-citeengine compativility
3979 if (command == "citeyear")
3980 command = "citebyear";
3981 else if (command == "cite*")
3982 command = "citeyear";
3983 else if (command == "textcite")
3985 else if (command == "Textcite")
3987 else if (command == "parencite")
3989 else if (command == "Parencite")
3991 else if (command == "parencite*")
3992 command = "citeyearpar";
3993 else if (command == "smartcite")
3994 command = "footcite";
3995 else if (command == "Smartcite")
3996 command = "Footcite";
3998 string const emptyarg = qualified ? "()" : "[]";
3999 if (before.empty() && after == emptyarg)
4002 else if (before == emptyarg && after == emptyarg) {
4003 // avoid \cite[][]{a}
4007 bool literal = false;
4008 pair<bool, string> aft;
4009 pair<bool, string> bef;
4010 // remove the brackets around after and before
4011 if (!after.empty()) {
4013 after.erase(after.length() - 1, 1);
4014 aft = convert_latexed_command_inset_arg(after);
4015 literal = !aft.first;
4016 after = literal ? subst(after, "\n", " ") : aft.second;
4018 if (!before.empty()) {
4020 before.erase(before.length() - 1, 1);
4021 bef = convert_latexed_command_inset_arg(before);
4022 literal |= !bef.first;
4023 before = literal ? subst(before, "\n", " ") : bef.second;
4025 string keys, pretextlist, posttextlist;
4027 map<string, string> pres, posts, preslit, postslit;
4028 vector<string> lkeys;
4029 // text before the citation
4030 string lbefore, lbeforelit;
4031 // text after the citation
4032 string lafter, lafterlit;
4034 pair<bool, string> laft, lbef;
4036 get_cite_arguments(p, true, lbefore, lafter);
4037 // remove the brackets around after and before
4038 if (!lafter.empty()) {
4040 lafter.erase(lafter.length() - 1, 1);
4041 laft = convert_latexed_command_inset_arg(lafter);
4042 literal |= !laft.first;
4043 lafter = laft.second;
4044 lafterlit = subst(lbefore, "\n", " ");
4046 if (!lbefore.empty()) {
4047 lbefore.erase(0, 1);
4048 lbefore.erase(lbefore.length() - 1, 1);
4049 lbef = convert_latexed_command_inset_arg(lbefore);
4050 literal |= !lbef.first;
4051 lbefore = lbef.second;
4052 lbeforelit = subst(lbefore, "\n", " ");
4054 if (lbefore.empty() && lafter == "[]") {
4059 else if (lbefore == "[]" && lafter == "[]") {
4060 // avoid \cite[][]{a}
4066 lkey = p.getArg('{', '}');
4069 if (!lbefore.empty()) {
4070 pres.insert(make_pair(lkey, lbefore));
4071 preslit.insert(make_pair(lkey, lbeforelit));
4073 if (!lafter.empty()) {
4074 posts.insert(make_pair(lkey, lafter));
4075 postslit.insert(make_pair(lkey, lafterlit));
4077 lkeys.push_back(lkey);
4079 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4084 for (auto const & ptl : pres) {
4085 if (!pretextlist.empty())
4086 pretextlist += '\t';
4087 pretextlist += ptl.first + " " + ptl.second;
4089 for (auto const & potl : posts) {
4090 if (!posttextlist.empty())
4091 posttextlist += '\t';
4092 posttextlist += potl.first + " " + potl.second;
4095 keys = convert_literate_command_inset_arg(p.verbatim_item());
4098 after = subst(after, "\n", " ");
4099 if (!before.empty())
4100 before = subst(after, "\n", " ");
4102 string lit = literal ? "\"true\"" : "\"false\"";
4103 begin_command_inset(os, "citation", command);
4104 os << "after " << '"' << after << '"' << "\n";
4105 os << "before " << '"' << before << '"' << "\n";
4109 if (!pretextlist.empty())
4110 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4111 if (!posttextlist.empty())
4112 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4113 os << "literal " << lit << "\n";
4115 // Need to set the cite engine if biblatex is loaded by
4116 // the document class directly
4117 if (preamble.citeEngine() == "basic")
4118 use_biblatex_natbib ?
4119 preamble.citeEngine("biblatex-natbib")
4120 : preamble.citeEngine("biblatex");
4125 is_known(t.cs(), known_jurabib_commands) &&
4126 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4127 context.check_layout(os);
4128 string command = t.cs();
4129 if (p.next_token().asInput() == "*") {
4133 char argumentOrder = '\0';
4134 vector<string> const options =
4135 preamble.getPackageOptions("jurabib");
4136 if (find(options.begin(), options.end(),
4137 "natbiborder") != options.end())
4138 argumentOrder = 'n';
4139 else if (find(options.begin(), options.end(),
4140 "jurabiborder") != options.end())
4141 argumentOrder = 'j';
4143 // text before the citation
4145 // text after the citation
4147 get_cite_arguments(p, argumentOrder != 'j', before, after);
4149 string const citation = p.verbatim_item();
4150 if (!before.empty() && argumentOrder == '\0') {
4151 cerr << "Warning: Assuming argument order "
4152 "of jurabib version 0.6 for\n'"
4153 << command << before << after << '{'
4154 << citation << "}'.\n"
4155 "Add 'jurabiborder' to the jurabib "
4156 "package options if you used an\n"
4157 "earlier jurabib version." << endl;
4159 bool literal = false;
4160 pair<bool, string> aft;
4161 pair<bool, string> bef;
4162 // remove the brackets around after and before
4163 if (!after.empty()) {
4165 after.erase(after.length() - 1, 1);
4166 aft = convert_latexed_command_inset_arg(after);
4167 literal = !aft.first;
4168 after = literal ? subst(after, "\n", " ") : aft.second;
4170 if (!before.empty()) {
4172 before.erase(before.length() - 1, 1);
4173 bef = convert_latexed_command_inset_arg(before);
4174 literal |= !bef.first;
4175 before = literal ? subst(before, "\n", " ") : bef.second;
4176 if (literal && !after.empty())
4177 after = subst(after, "\n", " ");
4179 string lit = literal ? "\"true\"" : "\"false\"";
4180 begin_command_inset(os, "citation", command);
4181 os << "after " << '"' << after << "\"\n"
4182 << "before " << '"' << before << "\"\n"
4183 << "key " << '"' << citation << "\"\n"
4184 << "literal " << lit << "\n";
4186 // Need to set the cite engine if jurabib is loaded by
4187 // the document class directly
4188 if (preamble.citeEngine() == "basic")
4189 preamble.citeEngine("jurabib");
4193 if (t.cs() == "cite"
4194 || t.cs() == "nocite") {
4195 context.check_layout(os);
4196 string after = p.getArg('[', ']');
4197 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4198 bool const literal = !aft.first;
4199 after = literal ? subst(after, "\n", " ") : aft.second;
4200 string lit = literal ? "\"true\"" : "\"false\"";
4201 string key = convert_literate_command_inset_arg(p.verbatim_item());
4202 // store the case that it is "\nocite{*}" to use it later for
4205 begin_command_inset(os, "citation", t.cs());
4206 os << "after " << '"' << after << "\"\n"
4207 << "key " << '"' << key << "\"\n"
4208 << "literal " << lit << "\n";
4210 } else if (t.cs() == "nocite")
4215 if (t.cs() == "index" ||
4216 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4217 context.check_layout(os);
4218 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4219 p.getArg('[', ']') : "";
4220 string const kind = arg.empty() ? "idx" : arg;
4221 begin_inset(os, "Index ");
4222 os << kind << "\nstatus collapsed\n";
4223 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4226 preamble.registerAutomaticallyLoadedPackage("splitidx");
4230 if (t.cs() == "nomenclature") {
4231 context.check_layout(os);
4232 begin_command_inset(os, "nomenclature", "nomenclature");
4233 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4234 if (!prefix.empty())
4235 os << "prefix " << '"' << prefix << '"' << "\n";
4236 string symbol = p.verbatim_item();
4237 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4238 bool literal = !sym.first;
4239 string description = p.verbatim_item();
4240 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4241 literal |= !desc.first;
4243 symbol = subst(symbol, "\n", " ");
4244 description = subst(description, "\n", " ");
4246 symbol = sym.second;
4247 description = desc.second;
4249 string lit = literal ? "\"true\"" : "\"false\"";
4250 os << "symbol " << '"' << symbol;
4251 os << "\"\ndescription \""
4252 << description << "\"\n"
4253 << "literal " << lit << "\n";
4255 preamble.registerAutomaticallyLoadedPackage("nomencl");
4259 if (t.cs() == "label") {
4260 context.check_layout(os);
4261 begin_command_inset(os, "label", "label");
4263 << convert_literate_command_inset_arg(p.verbatim_item())
4269 if (t.cs() == "lyxmintcaption") {
4270 string const pos = p.getArg('[', ']');
4272 string const caption =
4273 parse_text_snippet(p, FLAG_ITEM, false,
4275 minted_nonfloat_caption = "[t]" + caption;
4277 // We already got the caption at the bottom,
4278 // so simply skip it.
4279 parse_text_snippet(p, FLAG_ITEM, false, context);
4284 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4285 context.check_layout(os);
4286 string commandname = t.cs();
4288 if (p.next_token().asInput() == "*") {
4293 begin_command_inset(os, "index_print", commandname);
4294 string const indexname = p.getArg('[', ']');
4296 if (indexname.empty())
4297 os << "type \"idx\"\n";
4299 os << "type \"" << indexname << "\"\n";
4300 os << "literal \"true\"\n";
4303 skip_spaces_braces(p);
4304 preamble.registerAutomaticallyLoadedPackage("makeidx");
4305 if (preamble.use_indices() == "true")
4306 preamble.registerAutomaticallyLoadedPackage("splitidx");
4310 if (t.cs() == "printnomenclature") {
4312 string width_type = "";
4313 context.check_layout(os);
4314 begin_command_inset(os, "nomencl_print", "printnomenclature");
4315 // case of a custom width
4317 width = p.getArg('[', ']');
4318 width = translate_len(width);
4319 width_type = "custom";
4321 // case of no custom width
4322 // the case of no custom width but the width set
4323 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4324 // because the user could have set anything, not only the width
4325 // of the longest label (which would be width_type = "auto")
4326 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4327 if (label.empty() && width_type.empty())
4328 width_type = "none";
4329 os << "set_width \"" << width_type << "\"\n";
4330 if (width_type == "custom")
4331 os << "width \"" << width << '\"';
4333 skip_spaces_braces(p);
4334 preamble.registerAutomaticallyLoadedPackage("nomencl");
4338 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4339 context.check_layout(os);
4340 begin_inset(os, "script ");
4341 os << t.cs().substr(4) << '\n';
4342 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4343 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4345 if (t.cs() == "textsubscript")
4346 preamble.registerAutomaticallyLoadedPackage("subscript");
4350 if ((where = is_known(t.cs(), known_quotes))) {
4351 context.check_layout(os);
4352 begin_inset(os, "Quotes ");
4353 os << known_coded_quotes[where - known_quotes];
4355 // LyX adds {} after the quote, so we have to eat
4356 // spaces here if there are any before a possible
4358 eat_whitespace(p, os, context, false);
4363 if ((where = is_known(t.cs(), known_sizes)) &&
4364 context.new_layout_allowed) {
4365 context.check_layout(os);
4366 TeXFont const oldFont = context.font;
4367 context.font.size = known_coded_sizes[where - known_sizes];
4368 output_font_change(os, oldFont, context.font);
4369 eat_whitespace(p, os, context, false);
4373 if ((where = is_known(t.cs(), known_font_families)) &&
4374 context.new_layout_allowed) {
4375 context.check_layout(os);
4376 TeXFont const oldFont = context.font;
4377 context.font.family =
4378 known_coded_font_families[where - known_font_families];
4379 output_font_change(os, oldFont, context.font);
4380 eat_whitespace(p, os, context, false);
4384 if ((where = is_known(t.cs(), known_font_series)) &&
4385 context.new_layout_allowed) {
4386 context.check_layout(os);
4387 TeXFont const oldFont = context.font;
4388 context.font.series =
4389 known_coded_font_series[where - known_font_series];
4390 output_font_change(os, oldFont, context.font);
4391 eat_whitespace(p, os, context, false);
4395 if ((where = is_known(t.cs(), known_font_shapes)) &&
4396 context.new_layout_allowed) {
4397 context.check_layout(os);
4398 TeXFont const oldFont = context.font;
4399 context.font.shape =
4400 known_coded_font_shapes[where - known_font_shapes];
4401 output_font_change(os, oldFont, context.font);
4402 eat_whitespace(p, os, context, false);
4405 if ((where = is_known(t.cs(), known_old_font_families)) &&
4406 context.new_layout_allowed) {
4407 context.check_layout(os);
4408 TeXFont const oldFont = context.font;
4409 context.font.init();
4410 context.font.size = oldFont.size;
4411 context.font.family =
4412 known_coded_font_families[where - known_old_font_families];
4413 output_font_change(os, oldFont, context.font);
4414 eat_whitespace(p, os, context, false);
4418 if ((where = is_known(t.cs(), known_old_font_series)) &&
4419 context.new_layout_allowed) {
4420 context.check_layout(os);
4421 TeXFont const oldFont = context.font;
4422 context.font.init();
4423 context.font.size = oldFont.size;
4424 context.font.series =
4425 known_coded_font_series[where - known_old_font_series];
4426 output_font_change(os, oldFont, context.font);
4427 eat_whitespace(p, os, context, false);
4431 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4432 context.new_layout_allowed) {
4433 context.check_layout(os);
4434 TeXFont const oldFont = context.font;
4435 context.font.init();
4436 context.font.size = oldFont.size;
4437 context.font.shape =
4438 known_coded_font_shapes[where - known_old_font_shapes];
4439 output_font_change(os, oldFont, context.font);
4440 eat_whitespace(p, os, context, false);
4444 if (t.cs() == "selectlanguage") {
4445 context.check_layout(os);
4446 // save the language for the case that a
4447 // \foreignlanguage is used
4448 context.font.language = babel2lyx(p.verbatim_item());
4449 os << "\n\\lang " << context.font.language << "\n";
4453 if (t.cs() == "foreignlanguage") {
4454 string const lang = babel2lyx(p.verbatim_item());
4455 parse_text_attributes(p, os, FLAG_ITEM, outer,
4457 context.font.language, lang);
4461 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4462 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4463 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4465 // We have to output the whole command if it has an option
4466 // because LyX doesn't support this yet, see bug #8214,
4467 // only if there is a single option specifying a variant, we can handle it.
4469 string langopts = p.getOpt();
4470 // check if the option contains a variant, if yes, extract it
4471 string::size_type pos_var = langopts.find("variant");
4472 string::size_type i = langopts.find(',');
4473 string::size_type k = langopts.find('=', pos_var);
4474 if (pos_var != string::npos && i == string::npos) {
4476 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4477 lang = preamble.polyglossia2lyx(variant);
4478 parse_text_attributes(p, os, FLAG_ITEM, outer,
4480 context.font.language, lang);
4482 output_ert_inset(os, t.asInput() + langopts, context);
4484 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4485 parse_text_attributes(p, os, FLAG_ITEM, outer,
4487 context.font.language, lang);
4492 if (t.cs() == "inputencoding") {
4493 // nothing to write here
4494 string const enc = subst(p.verbatim_item(), "\n", " ");
4495 p.setEncoding(enc, Encoding::inputenc);
4499 if (is_known(t.cs(), known_special_chars) ||
4500 (t.cs() == "protect" &&
4501 p.next_token().cat() == catEscape &&
4502 is_known(p.next_token().cs(), known_special_protect_chars))) {
4503 // LyX sometimes puts a \protect in front, so we have to ignore it
4505 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4506 known_special_chars);
4507 context.check_layout(os);
4508 os << known_coded_special_chars[where - known_special_chars];
4509 skip_spaces_braces(p);
4513 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4514 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4515 p.next_next_token().asInput() == "-") ||
4516 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4517 // LyX sometimes puts a \protect in front, so we have to ignore it
4518 if (t.cs() == "protect")
4520 context.check_layout(os);
4521 if (t.cs() == "nobreakdash")
4522 os << "\\SpecialChar nobreakdash\n";
4524 os << "\\SpecialChar endofsentence\n";
4529 if (t.cs() == "textquotedbl") {
4530 context.check_layout(os);
4536 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4537 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4538 || t.cs() == "%" || t.cs() == "-") {
4539 context.check_layout(os);
4541 os << "\\SpecialChar softhyphen\n";
4547 if (t.cs() == "char") {
4548 context.check_layout(os);
4549 if (p.next_token().character() == '`') {
4551 if (p.next_token().cs() == "\"") {
4556 output_ert_inset(os, "\\char`", context);
4559 output_ert_inset(os, "\\char", context);
4564 if (t.cs() == "verb") {
4565 context.check_layout(os);
4566 // set catcodes to verbatim early, just in case.
4567 p.setCatcodes(VERBATIM_CATCODES);
4568 string delim = p.get_token().asInput();
4569 Parser::Arg arg = p.verbatimStuff(delim);
4571 output_ert_inset(os, "\\verb" + delim
4572 + arg.second + delim, context);
4574 cerr << "invalid \\verb command. Skipping" << endl;
4578 // Problem: \= creates a tabstop inside the tabbing environment
4579 // and else an accent. In the latter case we really would want
4580 // \={o} instead of \= o.
4581 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4582 output_ert_inset(os, t.asInput(), context);
4586 if (t.cs() == "\\") {
4587 context.check_layout(os);
4589 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4590 else if (p.next_token().asInput() == "*") {
4592 // getOpt() eats the following space if there
4593 // is no optional argument, but that is OK
4594 // here since it has no effect in the output.
4595 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4598 begin_inset(os, "Newline newline");
4604 if (t.cs() == "newline" ||
4605 (t.cs() == "linebreak" && !p.hasOpt())) {
4606 context.check_layout(os);
4607 begin_inset(os, "Newline ");
4610 skip_spaces_braces(p);
4614 if (t.cs() == "input" || t.cs() == "include"
4615 || t.cs() == "verbatiminput") {
4616 string name = t.cs();
4617 if (t.cs() == "verbatiminput"
4618 && p.next_token().asInput() == "*")
4619 name += p.get_token().asInput();
4620 context.check_layout(os);
4621 string filename(normalize_filename(p.getArg('{', '}')));
4622 string const path = getMasterFilePath(true);
4623 // We want to preserve relative / absolute filenames,
4624 // therefore path is only used for testing
4625 if ((t.cs() == "include" || t.cs() == "input") &&
4626 !makeAbsPath(filename, path).exists()) {
4627 // The file extension is probably missing.
4628 // Now try to find it out.
4629 string const tex_name =
4630 find_file(filename, path,
4631 known_tex_extensions);
4632 if (!tex_name.empty())
4633 filename = tex_name;
4635 bool external = false;
4637 if (makeAbsPath(filename, path).exists()) {
4638 string const abstexname =
4639 makeAbsPath(filename, path).absFileName();
4640 string const absfigname =
4641 changeExtension(abstexname, ".fig");
4642 fix_child_filename(filename);
4643 string const lyxname = changeExtension(filename,
4644 roundtripMode() ? ".lyx.lyx" : ".lyx");
4645 string const abslyxname = makeAbsPath(
4646 lyxname, getParentFilePath(false)).absFileName();
4648 if (!skipChildren())
4649 external = FileName(absfigname).exists();
4650 if (t.cs() == "input" && !skipChildren()) {
4651 string const ext = getExtension(abstexname);
4653 // Combined PS/LaTeX:
4654 // x.eps, x.pstex_t (old xfig)
4655 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4656 FileName const absepsname(
4657 changeExtension(abstexname, ".eps"));
4658 FileName const abspstexname(
4659 changeExtension(abstexname, ".pstex"));
4660 bool const xfigeps =
4661 (absepsname.exists() ||
4662 abspstexname.exists()) &&
4665 // Combined PDF/LaTeX:
4666 // x.pdf, x.pdftex_t (old xfig)
4667 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4668 FileName const abspdfname(
4669 changeExtension(abstexname, ".pdf"));
4670 bool const xfigpdf =
4671 abspdfname.exists() &&
4672 (ext == "pdftex_t" || ext == "pdf_t");
4676 // Combined PS/PDF/LaTeX:
4677 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4678 string const absbase2(
4679 removeExtension(abstexname) + "_pspdftex");
4680 FileName const abseps2name(
4681 addExtension(absbase2, ".eps"));
4682 FileName const abspdf2name(
4683 addExtension(absbase2, ".pdf"));
4684 bool const xfigboth =
4685 abspdf2name.exists() &&
4686 abseps2name.exists() && ext == "pspdftex";
4688 xfig = xfigpdf || xfigeps || xfigboth;
4689 external = external && xfig;
4692 outname = changeExtension(filename, ".fig");
4693 FileName abssrc(changeExtension(abstexname, ".fig"));
4694 copy_file(abssrc, outname);
4696 // Don't try to convert, the result
4697 // would be full of ERT.
4699 FileName abssrc(abstexname);
4700 copy_file(abssrc, outname);
4701 } else if (t.cs() != "verbatiminput" &&
4703 tex2lyx(abstexname, FileName(abslyxname),
4706 // no need to call copy_file
4707 // tex2lyx creates the file
4710 FileName abssrc(abstexname);
4711 copy_file(abssrc, outname);
4714 cerr << "Warning: Could not find included file '"
4715 << filename << "'." << endl;
4719 begin_inset(os, "External\n");
4720 os << "\ttemplate XFig\n"
4721 << "\tfilename " << outname << '\n';
4722 registerExternalTemplatePackages("XFig");
4724 begin_command_inset(os, "include", name);
4725 outname = subst(outname, "\"", "\\\"");
4726 os << "preview false\n"
4727 "filename \"" << outname << "\"\n";
4728 if (t.cs() == "verbatiminput")
4729 preamble.registerAutomaticallyLoadedPackage("verbatim");
4735 if (t.cs() == "bibliographystyle") {
4736 // store new bibliographystyle
4737 bibliographystyle = p.verbatim_item();
4738 // If any other command than \bibliography, \addcontentsline
4739 // and \nocite{*} follows, we need to output the style
4740 // (because it might be used by that command).
4741 // Otherwise, it will automatically be output by LyX.
4744 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4745 if (t2.cat() == catBegin)
4747 if (t2.cat() != catEscape)
4749 if (t2.cs() == "nocite") {
4750 if (p.getArg('{', '}') == "*")
4752 } else if (t2.cs() == "bibliography")
4754 else if (t2.cs() == "phantomsection") {
4758 else if (t2.cs() == "addcontentsline") {
4759 // get the 3 arguments of \addcontentsline
4762 contentslineContent = p.getArg('{', '}');
4763 // if the last argument is not \refname we must output
4764 if (contentslineContent == "\\refname")
4771 output_ert_inset(os,
4772 "\\bibliographystyle{" + bibliographystyle + '}',
4778 if (t.cs() == "phantomsection") {
4779 // we only support this if it occurs between
4780 // \bibliographystyle and \bibliography
4781 if (bibliographystyle.empty())
4782 output_ert_inset(os, "\\phantomsection", context);
4786 if (t.cs() == "addcontentsline") {
4787 context.check_layout(os);
4788 // get the 3 arguments of \addcontentsline
4789 string const one = p.getArg('{', '}');
4790 string const two = p.getArg('{', '}');
4791 string const three = p.getArg('{', '}');
4792 // only if it is a \refname, we support if for the bibtex inset
4793 if (contentslineContent != "\\refname") {
4794 output_ert_inset(os,
4795 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4801 else if (t.cs() == "bibliography") {
4802 context.check_layout(os);
4804 begin_command_inset(os, "bibtex", "bibtex");
4805 if (!btprint.empty()) {
4806 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4807 // clear the string because the next BibTeX inset can be without the
4808 // \nocite{*} option
4811 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4812 // Do we have addcontentsline?
4813 if (contentslineContent == "\\refname") {
4814 BibOpts = "bibtotoc";
4815 // clear string because next BibTeX inset can be without addcontentsline
4816 contentslineContent.clear();
4818 // Do we have a bibliographystyle set?
4819 if (!bibliographystyle.empty()) {
4820 if (BibOpts.empty())
4821 BibOpts = normalize_filename(bibliographystyle);
4823 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4824 // clear it because each bibtex entry has its style
4825 // and we need an empty string to handle \phantomsection
4826 bibliographystyle.clear();
4828 os << "options " << '"' << BibOpts << '"' << "\n";
4833 if (t.cs() == "printbibliography") {
4834 context.check_layout(os);
4836 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4837 vector<string> opts = getVectorFromString(bbloptions);
4838 vector<string>::iterator it =
4839 find(opts.begin(), opts.end(), "heading=bibintoc");
4840 if (it != opts.end()) {
4842 BibOpts = "bibtotoc";
4844 bbloptions = getStringFromVector(opts);
4845 begin_command_inset(os, "bibtex", "bibtex");
4846 if (!btprint.empty()) {
4847 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4848 // clear the string because the next BibTeX inset can be without the
4849 // \nocite{*} option
4853 for (auto const & bf : preamble.biblatex_bibliographies) {
4854 if (!bibfiles.empty())
4856 bibfiles += normalize_filename(bf);
4858 if (!bibfiles.empty())
4859 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4860 // Do we have addcontentsline?
4861 if (contentslineContent == "\\refname") {
4862 BibOpts = "bibtotoc";
4863 // clear string because next BibTeX inset can be without addcontentsline
4864 contentslineContent.clear();
4866 os << "options " << '"' << BibOpts << '"' << "\n";
4867 if (!bbloptions.empty())
4868 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4870 need_commentbib = false;
4874 if (t.cs() == "bibbysection") {
4875 context.check_layout(os);
4877 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4878 vector<string> opts = getVectorFromString(bbloptions);
4879 vector<string>::iterator it =
4880 find(opts.begin(), opts.end(), "heading=bibintoc");
4881 if (it != opts.end()) {
4883 BibOpts = "bibtotoc";
4885 bbloptions = getStringFromVector(opts);
4886 begin_command_inset(os, "bibtex", "bibtex");
4887 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4889 for (auto const & bf : preamble.biblatex_bibliographies) {
4890 if (!bibfiles.empty())
4892 bibfiles += normalize_filename(bf);
4894 if (!bibfiles.empty())
4895 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4896 os << "options " << '"' << BibOpts << '"' << "\n";
4897 if (!bbloptions.empty())
4898 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4900 need_commentbib = false;
4904 if (t.cs() == "parbox") {
4905 // Test whether this is an outer box of a shaded box
4907 // swallow arguments
4908 while (p.hasOpt()) {
4910 p.skip_spaces(true);
4913 p.skip_spaces(true);
4915 if (p.next_token().cat() == catBegin)
4917 p.skip_spaces(true);
4918 Token to = p.get_token();
4919 bool shaded = false;
4920 if (to.asInput() == "\\begin") {
4921 p.skip_spaces(true);
4922 if (p.getArg('{', '}') == "shaded")
4927 parse_outer_box(p, os, FLAG_ITEM, outer,
4928 context, "parbox", "shaded");
4930 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4931 "", "", t.cs(), "", "");
4935 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4936 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4937 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4938 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4942 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4943 string backgroundcolor;
4944 preamble.registerAutomaticallyLoadedPackage("xcolor");
4945 if (t.cs() == "fcolorbox") {
4946 string const framecolor = p.getArg('{', '}');
4947 backgroundcolor = p.getArg('{', '}');
4948 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4950 backgroundcolor = p.getArg('{', '}');
4951 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4956 // FIXME: due to the compiler limit of "if" nestings
4957 // the code for the alignment was put here
4958 // put them in their own if if this is fixed
4959 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4960 || t.cs() == "shadowsize"
4961 || t.cs() == "raggedleft" || t.cs() == "centering"
4962 || t.cs() == "raggedright") {
4963 if (t.cs() == "fboxrule")
4965 if (t.cs() == "fboxsep")
4967 if (t.cs() == "shadowsize")
4969 if (t.cs() != "raggedleft" && t.cs() != "centering"
4970 && t.cs() != "raggedright") {
4971 p.skip_spaces(true);
4972 while (p.good() && p.next_token().cat() != catSpace
4973 && p.next_token().cat() != catNewline
4974 && p.next_token().cat() != catEscape) {
4975 if (t.cs() == "fboxrule")
4976 fboxrule = fboxrule + p.get_token().asInput();
4977 if (t.cs() == "fboxsep")
4978 fboxsep = fboxsep + p.get_token().asInput();
4979 if (t.cs() == "shadowsize")
4980 shadow_size = shadow_size + p.get_token().asInput();
4983 output_ert_inset(os, t.asInput(), context);
4988 //\framebox() is part of the picture environment and different from \framebox{}
4989 //\framebox{} will be parsed by parse_outer_box
4990 if (t.cs() == "framebox") {
4991 if (p.next_token().character() == '(') {
4992 //the syntax is: \framebox(x,y)[position]{content}
4993 string arg = t.asInput();
4994 arg += p.getFullParentheseArg();
4995 arg += p.getFullOpt();
4996 eat_whitespace(p, os, context, false);
4997 output_ert_inset(os, arg + '{', context);
4998 parse_text(p, os, FLAG_ITEM, outer, context);
4999 output_ert_inset(os, "}", context);
5001 //the syntax is: \framebox[width][position]{content}
5002 string special = p.getFullOpt();
5003 special += p.getOpt();
5004 parse_outer_box(p, os, FLAG_ITEM, outer,
5005 context, t.cs(), special);
5010 //\makebox() is part of the picture environment and different from \makebox{}
5011 //\makebox{} will be parsed by parse_box
5012 if (t.cs() == "makebox") {
5013 if (p.next_token().character() == '(') {
5014 //the syntax is: \makebox(x,y)[position]{content}
5015 string arg = t.asInput();
5016 arg += p.getFullParentheseArg();
5017 arg += p.getFullOpt();
5018 eat_whitespace(p, os, context, false);
5019 output_ert_inset(os, arg + '{', context);
5020 parse_text(p, os, FLAG_ITEM, outer, context);
5021 output_ert_inset(os, "}", context);
5023 //the syntax is: \makebox[width][position]{content}
5024 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5025 "", "", t.cs(), "", "");
5029 if (t.cs() == "smallskip" ||
5030 t.cs() == "medskip" ||
5031 t.cs() == "bigskip" ||
5032 t.cs() == "vfill") {
5033 context.check_layout(os);
5034 begin_inset(os, "VSpace ");
5037 skip_spaces_braces(p);
5041 if ((where = is_known(t.cs(), known_spaces))) {
5042 context.check_layout(os);
5043 begin_inset(os, "space ");
5044 os << '\\' << known_coded_spaces[where - known_spaces]
5047 // LaTeX swallows whitespace after all spaces except
5048 // "\\,". We have to do that here, too, because LyX
5049 // adds "{}" which would make the spaces significant.
5051 eat_whitespace(p, os, context, false);
5052 // LyX adds "{}" after all spaces except "\\ " and
5053 // "\\,", so we have to remove "{}".
5054 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5055 // remove the braces after "\\,", too.
5061 if (t.cs() == "newpage" ||
5062 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5063 t.cs() == "clearpage" ||
5064 t.cs() == "cleardoublepage") {
5065 context.check_layout(os);
5066 begin_inset(os, "Newpage ");
5069 skip_spaces_braces(p);
5073 if (t.cs() == "DeclareRobustCommand" ||
5074 t.cs() == "DeclareRobustCommandx" ||
5075 t.cs() == "newcommand" ||
5076 t.cs() == "newcommandx" ||
5077 t.cs() == "providecommand" ||
5078 t.cs() == "providecommandx" ||
5079 t.cs() == "renewcommand" ||
5080 t.cs() == "renewcommandx") {
5081 // DeclareRobustCommand, DeclareRobustCommandx,
5082 // providecommand and providecommandx could be handled
5083 // by parse_command(), but we need to call
5084 // add_known_command() here.
5085 string name = t.asInput();
5086 if (p.next_token().asInput() == "*") {
5087 // Starred form. Eat '*'
5091 string const command = p.verbatim_item();
5092 string const opt1 = p.getFullOpt();
5093 string const opt2 = p.getFullOpt();
5094 add_known_command(command, opt1, !opt2.empty());
5095 string const ert = name + '{' + command + '}' +
5097 '{' + p.verbatim_item() + '}';
5099 if (t.cs() == "DeclareRobustCommand" ||
5100 t.cs() == "DeclareRobustCommandx" ||
5101 t.cs() == "providecommand" ||
5102 t.cs() == "providecommandx" ||
5103 name[name.length()-1] == '*')
5104 output_ert_inset(os, ert, context);
5106 context.check_layout(os);
5107 begin_inset(os, "FormulaMacro");
5114 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5115 // let could be handled by parse_command(),
5116 // but we need to call add_known_command() here.
5117 string ert = t.asInput();
5120 if (p.next_token().cat() == catBegin) {
5121 name = p.verbatim_item();
5122 ert += '{' + name + '}';
5124 name = p.verbatim_item();
5129 if (p.next_token().cat() == catBegin) {
5130 command = p.verbatim_item();
5131 ert += '{' + command + '}';
5133 command = p.verbatim_item();
5136 // If command is known, make name known too, to parse
5137 // its arguments correctly. For this reason we also
5138 // have commands in syntax.default that are hardcoded.
5139 CommandMap::iterator it = known_commands.find(command);
5140 if (it != known_commands.end())
5141 known_commands[t.asInput()] = it->second;
5142 output_ert_inset(os, ert, context);
5146 if (t.cs() == "hspace" || t.cs() == "vspace") {
5149 string name = t.asInput();
5150 string const length = p.verbatim_item();
5153 bool valid = splitLatexLength(length, valstring, unit);
5154 bool known_hspace = false;
5155 bool known_vspace = false;
5156 bool known_unit = false;
5159 istringstream iss(valstring);
5162 if (t.cs()[0] == 'h') {
5163 if (unit == "\\fill") {
5168 known_hspace = true;
5171 if (unit == "\\smallskipamount") {
5173 known_vspace = true;
5174 } else if (unit == "\\medskipamount") {
5176 known_vspace = true;
5177 } else if (unit == "\\bigskipamount") {
5179 known_vspace = true;
5180 } else if (unit == "\\fill") {
5182 known_vspace = true;
5186 if (!known_hspace && !known_vspace) {
5187 switch (unitFromString(unit)) {
5203 //unitFromString(unit) fails for relative units like Length::PCW
5204 // therefore handle them separately
5205 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5206 || unit == "\\textwidth" || unit == "\\linewidth"
5207 || unit == "\\textheight" || unit == "\\paperheight"
5208 || unit == "\\baselineskip")
5216 // check for glue lengths
5217 bool is_gluelength = false;
5218 string gluelength = length;
5219 string::size_type i = length.find(" minus");
5220 if (i == string::npos) {
5221 i = length.find(" plus");
5222 if (i != string::npos)
5223 is_gluelength = true;
5225 is_gluelength = true;
5226 // if yes transform "9xx minus 8yy plus 7zz"
5228 if (is_gluelength) {
5229 i = gluelength.find(" minus");
5230 if (i != string::npos)
5231 gluelength.replace(i, 7, "-");
5232 i = gluelength.find(" plus");
5233 if (i != string::npos)
5234 gluelength.replace(i, 6, "+");
5237 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5238 // Literal horizontal length or known variable
5239 context.check_layout(os);
5240 begin_inset(os, "space ");
5248 if (known_unit && !known_hspace)
5249 os << "\n\\length " << translate_len(length);
5251 os << "\n\\length " << gluelength;
5253 } else if (known_unit || known_vspace || is_gluelength) {
5254 // Literal vertical length or known variable
5255 context.check_layout(os);
5256 begin_inset(os, "VSpace ");
5259 if (known_unit && !known_vspace)
5260 os << translate_len(length);
5267 // LyX can't handle other length variables in Inset VSpace/space
5272 output_ert_inset(os, name + '{' + unit + '}', context);
5273 else if (value == -1.0)
5274 output_ert_inset(os, name + "{-" + unit + '}', context);
5276 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5278 output_ert_inset(os, name + '{' + length + '}', context);
5283 // The single '=' is meant here.
5284 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5288 context.check_layout(os);
5289 docstring const name = newinsetlayout->name();
5290 bool const caption = name.find(from_ascii("Caption:")) == 0;
5292 // Already done for floating minted listings.
5293 if (minted_float.empty()) {
5294 begin_inset(os, "Caption ");
5295 os << to_utf8(name.substr(8)) << '\n';
5298 begin_inset(os, "Flex ");
5299 os << to_utf8(name) << '\n'
5300 << "status collapsed\n";
5302 if (!minted_float.empty()) {
5303 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5304 } else if (newinsetlayout->isPassThru()) {
5305 // set catcodes to verbatim early, just in case.
5306 p.setCatcodes(VERBATIM_CATCODES);
5307 string delim = p.get_token().asInput();
5309 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5310 //FIXME: handle error condition
5311 string const arg = p.verbatimStuff("}").second;
5312 Context newcontext(true, context.textclass);
5313 if (newinsetlayout->forcePlainLayout())
5314 newcontext.layout = &context.textclass.plainLayout();
5315 output_ert(os, arg, newcontext);
5317 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5320 // Minted caption insets are not closed here because
5321 // we collect everything into the caption.
5322 if (minted_float.empty())
5327 if (t.cs() == "includepdf") {
5329 string const arg = p.getArg('[', ']');
5330 map<string, string> opts;
5331 vector<string> keys;
5332 split_map(arg, opts, keys);
5333 string name = normalize_filename(p.verbatim_item());
5334 string const path = getMasterFilePath(true);
5335 // We want to preserve relative / absolute filenames,
5336 // therefore path is only used for testing
5337 if (!makeAbsPath(name, path).exists()) {
5338 // The file extension is probably missing.
5339 // Now try to find it out.
5340 char const * const pdfpages_format[] = {"pdf", 0};
5341 string const pdftex_name =
5342 find_file(name, path, pdfpages_format);
5343 if (!pdftex_name.empty()) {
5348 FileName const absname = makeAbsPath(name, path);
5349 if (absname.exists())
5351 fix_child_filename(name);
5352 copy_file(absname, name);
5354 cerr << "Warning: Could not find file '"
5355 << name << "'." << endl;
5357 context.check_layout(os);
5358 begin_inset(os, "External\n\ttemplate ");
5359 os << "PDFPages\n\tfilename "
5361 // parse the options
5362 if (opts.find("pages") != opts.end())
5363 os << "\textra LaTeX \"pages="
5364 << opts["pages"] << "\"\n";
5365 if (opts.find("angle") != opts.end())
5366 os << "\trotateAngle "
5367 << opts["angle"] << '\n';
5368 if (opts.find("origin") != opts.end()) {
5370 string const opt = opts["origin"];
5371 if (opt == "tl") ss << "topleft";
5372 if (opt == "bl") ss << "bottomleft";
5373 if (opt == "Bl") ss << "baselineleft";
5374 if (opt == "c") ss << "center";
5375 if (opt == "tc") ss << "topcenter";
5376 if (opt == "bc") ss << "bottomcenter";
5377 if (opt == "Bc") ss << "baselinecenter";
5378 if (opt == "tr") ss << "topright";
5379 if (opt == "br") ss << "bottomright";
5380 if (opt == "Br") ss << "baselineright";
5381 if (!ss.str().empty())
5382 os << "\trotateOrigin " << ss.str() << '\n';
5384 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5386 if (opts.find("width") != opts.end())
5388 << translate_len(opts["width"]) << '\n';
5389 if (opts.find("height") != opts.end())
5391 << translate_len(opts["height"]) << '\n';
5392 if (opts.find("keepaspectratio") != opts.end())
5393 os << "\tkeepAspectRatio\n";
5395 context.check_layout(os);
5396 registerExternalTemplatePackages("PDFPages");
5400 if (t.cs() == "loadgame") {
5402 string name = normalize_filename(p.verbatim_item());
5403 string const path = getMasterFilePath(true);
5404 // We want to preserve relative / absolute filenames,
5405 // therefore path is only used for testing
5406 if (!makeAbsPath(name, path).exists()) {
5407 // The file extension is probably missing.
5408 // Now try to find it out.
5409 char const * const lyxskak_format[] = {"fen", 0};
5410 string const lyxskak_name =
5411 find_file(name, path, lyxskak_format);
5412 if (!lyxskak_name.empty())
5413 name = lyxskak_name;
5415 FileName const absname = makeAbsPath(name, path);
5416 if (absname.exists())
5418 fix_child_filename(name);
5419 copy_file(absname, name);
5421 cerr << "Warning: Could not find file '"
5422 << name << "'." << endl;
5423 context.check_layout(os);
5424 begin_inset(os, "External\n\ttemplate ");
5425 os << "ChessDiagram\n\tfilename "
5428 context.check_layout(os);
5429 // after a \loadgame follows a \showboard
5430 if (p.get_token().asInput() == "showboard")
5432 registerExternalTemplatePackages("ChessDiagram");
5436 // try to see whether the string is in unicodesymbols
5437 // Only use text mode commands, since we are in text mode here,
5438 // and math commands may be invalid (bug 6797)
5439 string name = t.asInput();
5440 // handle the dingbats, cyrillic and greek
5441 if (name == "\\ding" || name == "\\textcyr" ||
5442 (name == "\\textgreek" && !preamble.usePolyglossia()))
5443 name = name + '{' + p.getArg('{', '}') + '}';
5444 // handle the ifsym characters
5445 else if (name == "\\textifsymbol") {
5446 string const optif = p.getFullOpt();
5447 string const argif = p.getArg('{', '}');
5448 name = name + optif + '{' + argif + '}';
5450 // handle the \ascii characters
5451 // the case of \ascii within braces, as LyX outputs it, is already
5452 // handled for t.cat() == catBegin
5453 else if (name == "\\ascii") {
5454 // the code is "\asci\xxx"
5455 name = "{" + name + p.get_token().asInput() + "}";
5458 // handle some TIPA special characters
5459 else if (preamble.isPackageUsed("tipa")) {
5460 if (name == "\\s") {
5461 // fromLaTeXCommand() does not yet
5462 // recognize tipa short cuts
5463 name = "\\textsyllabic";
5464 } else if (name == "\\=" &&
5465 p.next_token().asInput() == "*") {
5466 // fromLaTeXCommand() does not yet
5467 // recognize tipa short cuts
5469 name = "\\textsubbar";
5470 } else if (name == "\\textdoublevertline") {
5471 // FIXME: This is not correct,
5472 // \textvertline is higher than \textbardbl
5473 name = "\\textbardbl";
5475 } else if (name == "\\!" ) {
5476 if (p.next_token().asInput() == "b") {
5477 p.get_token(); // eat 'b'
5480 } else if (p.next_token().asInput() == "d") {
5484 } else if (p.next_token().asInput() == "g") {
5488 } else if (p.next_token().asInput() == "G") {
5490 name = "\\texthtscg";
5492 } else if (p.next_token().asInput() == "j") {
5494 name = "\\texthtbardotlessj";
5496 } else if (p.next_token().asInput() == "o") {
5498 name = "\\textbullseye";
5501 } else if (name == "\\*" ) {
5502 if (p.next_token().asInput() == "k") {
5504 name = "\\textturnk";
5506 } else if (p.next_token().asInput() == "r") {
5507 p.get_token(); // eat 'b'
5508 name = "\\textturnr";
5510 } else if (p.next_token().asInput() == "t") {
5512 name = "\\textturnt";
5514 } else if (p.next_token().asInput() == "w") {
5516 name = "\\textturnw";
5521 if ((name.size() == 2 &&
5522 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5523 p.next_token().asInput() != "*") ||
5524 is_known(name.substr(1), known_tipa_marks)) {
5525 // name is a command that corresponds to a
5526 // combining character in unicodesymbols.
5527 // Append the argument, fromLaTeXCommand()
5528 // will either convert it to a single
5529 // character or a combining sequence.
5530 name += '{' + p.verbatim_item() + '}';
5532 // now get the character from unicodesymbols
5536 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5537 Encodings::TEXT_CMD, termination, rem, &req));
5539 context.check_layout(os);
5542 output_ert_inset(os, to_utf8(rem), context);
5544 skip_spaces_braces(p);
5545 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5546 preamble.registerAutomaticallyLoadedPackage(*it);
5548 //cerr << "#: " << t << " mode: " << mode << endl;
5549 // heuristic: read up to next non-nested space
5551 string s = t.asInput();
5552 string z = p.verbatim_item();
5553 while (p.good() && z != " " && !z.empty()) {
5554 //cerr << "read: " << z << endl;
5556 z = p.verbatim_item();
5558 cerr << "found ERT: " << s << endl;
5559 output_ert_inset(os, s + ' ', context);
5562 if (t.asInput() == name &&
5563 p.next_token().asInput() == "*") {
5564 // Starred commands like \vspace*{}
5565 p.get_token(); // Eat '*'
5568 if (!parse_command(name, p, os, outer, context))
5569 output_ert_inset(os, name, context);
5575 string guessLanguage(Parser & p, string const & lang)
5577 typedef std::map<std::string, size_t> LangMap;
5578 // map from language names to number of characters
5581 for (char const * const * i = supported_CJK_languages; *i; i++)
5582 used[string(*i)] = 0;
5585 Token const t = p.get_token();
5586 // comments are not counted for any language
5587 if (t.cat() == catComment)
5589 // commands are not counted as well, but we need to detect
5590 // \begin{CJK} and switch encoding if needed
5591 if (t.cat() == catEscape) {
5592 if (t.cs() == "inputencoding") {
5593 string const enc = subst(p.verbatim_item(), "\n", " ");
5594 p.setEncoding(enc, Encoding::inputenc);
5597 if (t.cs() != "begin")
5600 // Non-CJK content is counted for lang.
5601 // We do not care about the real language here:
5602 // If we have more non-CJK contents than CJK contents,
5603 // we simply use the language that was specified as
5604 // babel main language.
5605 used[lang] += t.asInput().length();
5608 // Now we are starting an environment
5610 string const name = p.getArg('{', '}');
5611 if (name != "CJK") {
5615 // It is a CJK environment
5617 /* name = */ p.getArg('{', '}');
5618 string const encoding = p.getArg('{', '}');
5619 /* mapping = */ p.getArg('{', '}');
5620 string const encoding_old = p.getEncoding();
5621 char const * const * const where =
5622 is_known(encoding, supported_CJK_encodings);
5624 p.setEncoding(encoding, Encoding::CJK);
5626 p.setEncoding("UTF-8");
5627 string const text = p.ertEnvironment("CJK");
5628 p.setEncoding(encoding_old);
5631 // ignore contents in unknown CJK encoding
5634 // the language of the text
5636 supported_CJK_languages[where - supported_CJK_encodings];
5637 used[cjk] += text.length();
5639 LangMap::const_iterator use = used.begin();
5640 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5641 if (it->second > use->second)
5648 void check_comment_bib(ostream & os, Context & context)
5650 if (!need_commentbib)
5652 // We have a bibliography database, but no bibliography with biblatex
5653 // which is completely valid. Insert a bibtex inset in a note.
5654 context.check_layout(os);
5655 begin_inset(os, "Note Note\n");
5656 os << "status open\n";
5657 os << "\\begin_layout Plain Layout\n";
5658 begin_command_inset(os, "bibtex", "bibtex");
5660 for (auto const & bf : preamble.biblatex_bibliographies) {
5661 if (!bibfiles.empty())
5663 bibfiles += normalize_filename(bf);
5665 if (!bibfiles.empty())
5666 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5667 end_inset(os);// Bibtex
5668 os << "\\end_layout\n";
5669 end_inset(os);// Note