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 = "";
346 // Characters that have to be escaped by \\ in LaTeX
347 char const * const known_escaped_chars[] = {
348 "&", "_", "$", "%", "#", "^", "{", "}"};
351 /// splits "x=z, y=b" into a map and an ordered keyword vector
352 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
357 keys.resize(v.size());
358 for (size_t i = 0; i < v.size(); ++i) {
359 size_t const pos = v[i].find('=');
360 string const index = trimSpaceAndEol(v[i].substr(0, pos));
361 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
369 * Split a LaTeX length into value and unit.
370 * The latter can be a real unit like "pt", or a latex length variable
371 * like "\textwidth". The unit may contain additional stuff like glue
372 * lengths, but we don't care, because such lengths are ERT anyway.
373 * \returns true if \p value and \p unit are valid.
375 bool splitLatexLength(string const & len, string & value, string & unit)
379 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
380 //'4,5' is a valid LaTeX length number. Change it to '4.5'
381 string const length = subst(len, ',', '.');
382 if (i == string::npos)
385 if (len[0] == '\\') {
386 // We had something like \textwidth without a factor
392 value = trimSpaceAndEol(string(length, 0, i));
396 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
397 if (contains(len, '\\'))
398 unit = trimSpaceAndEol(string(len, i));
400 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
405 /// A simple function to translate a latex length to something LyX can
406 /// understand. Not perfect, but rather best-effort.
407 bool translate_len(string const & length, string & valstring, string & unit)
409 if (!splitLatexLength(length, valstring, unit))
411 // LyX uses percent values
413 istringstream iss(valstring);
418 string const percentval = oss.str();
420 if (unit.empty() || unit[0] != '\\')
422 string::size_type const i = unit.find(' ');
423 string const endlen = (i == string::npos) ? string() : string(unit, i);
424 if (unit == "\\textwidth") {
425 valstring = percentval;
426 unit = "text%" + endlen;
427 } else if (unit == "\\columnwidth") {
428 valstring = percentval;
429 unit = "col%" + endlen;
430 } else if (unit == "\\paperwidth") {
431 valstring = percentval;
432 unit = "page%" + endlen;
433 } else if (unit == "\\linewidth") {
434 valstring = percentval;
435 unit = "line%" + endlen;
436 } else if (unit == "\\paperheight") {
437 valstring = percentval;
438 unit = "pheight%" + endlen;
439 } else if (unit == "\\textheight") {
440 valstring = percentval;
441 unit = "theight%" + endlen;
442 } else if (unit == "\\baselineskip") {
443 valstring = percentval;
444 unit = "baselineskip%" + endlen;
452 string translate_len(string const & length)
456 if (translate_len(length, value, unit))
458 // If the input is invalid, return what we have.
466 * Translates a LaTeX length into \p value, \p unit and
467 * \p special parts suitable for a box inset.
468 * The difference from translate_len() is that a box inset knows about
469 * some special "units" that are stored in \p special.
471 void translate_box_len(string const & length, string & value, string & unit, string & special)
473 if (translate_len(length, value, unit)) {
474 if (unit == "\\height" || unit == "\\depth" ||
475 unit == "\\totalheight" || unit == "\\width") {
476 special = unit.substr(1);
477 // The unit is not used, but LyX requires a dummy setting
489 void begin_inset(ostream & os, string const & name)
491 os << "\n\\begin_inset " << name;
495 void begin_command_inset(ostream & os, string const & name,
496 string const & latexname)
498 begin_inset(os, "CommandInset ");
499 os << name << "\nLatexCommand " << latexname << '\n';
503 void end_inset(ostream & os)
505 os << "\n\\end_inset\n\n";
509 bool skip_braces(Parser & p)
511 if (p.next_token().cat() != catBegin)
514 if (p.next_token().cat() == catEnd) {
523 /// replace LaTeX commands in \p s from the unicodesymbols file with their
525 pair<bool, docstring> convert_unicodesymbols(docstring s)
529 for (size_t i = 0; i < s.size();) {
538 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
539 Encodings::TEXT_CMD, termination, rem, &req));
540 set<string>::const_iterator it = req.begin();
541 set<string>::const_iterator en = req.end();
542 for (; it != en; ++it)
543 preamble.registerAutomaticallyLoadedPackage(*it);
546 if (s.empty() || s[0] != '\\')
550 for (auto const & c : known_escaped_chars)
551 if (prefixIs(s, from_ascii("\\") + c))
556 return make_pair(res, os.str());
560 /// try to convert \p s to a valid InsetCommand argument
561 /// return whether this succeeded. If not, these command insets
562 /// get the "literate" flag.
563 pair<bool, string> convert_latexed_command_inset_arg(string s)
565 bool success = false;
567 // since we don't know the input encoding we can't use from_utf8
568 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
570 s = to_utf8(res.second);
572 // LyX cannot handle newlines in a latex command
573 return make_pair(success, subst(s, "\n", " "));
576 /// try to convert \p s to a valid InsetCommand argument
577 /// without trying to recode macros.
578 string convert_literate_command_inset_arg(string s)
580 // LyX cannot handle newlines in a latex command
581 return subst(s, "\n", " ");
584 void output_ert(ostream & os, string const & s, Context & context)
586 context.check_layout(os);
587 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
589 os << "\n\\backslash\n";
590 else if (*it == '\n') {
591 context.new_paragraph(os);
592 context.check_layout(os);
596 context.check_end_layout(os);
600 void output_ert_inset(ostream & os, string const & s, Context & context)
602 // We must have a valid layout before outputting the ERT inset.
603 context.check_layout(os);
604 Context newcontext(true, context.textclass);
605 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
606 if (layout.forcePlainLayout())
607 newcontext.layout = &context.textclass.plainLayout();
608 begin_inset(os, "ERT");
609 os << "\nstatus collapsed\n";
610 output_ert(os, s, newcontext);
615 void output_comment(Parser & p, ostream & os, string const & s,
618 if (p.next_token().cat() == catNewline)
619 output_ert_inset(os, '%' + s, context);
621 output_ert_inset(os, '%' + s + '\n', context);
625 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
627 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
630 if (checkModule(name, command))
631 return findLayoutWithoutModule(textclass, name, command);
636 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
638 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
641 if (checkModule(name, command))
642 return findInsetLayoutWithoutModule(textclass, name, command);
647 void eat_whitespace(Parser &, ostream &, Context &, bool);
651 * Skips whitespace and braces.
652 * This should be called after a command has been parsed that is not put into
653 * ERT, and where LyX adds "{}" if needed.
655 void skip_spaces_braces(Parser & p, bool keepws = false)
657 /* The following four examples produce the same typeset output and
658 should be handled by this function:
666 // Unfortunately we need to skip comments, too.
667 // We can't use eat_whitespace since writing them after the {}
668 // results in different output in some cases.
669 bool const skipped_spaces = p.skip_spaces(true);
670 bool const skipped_braces = skip_braces(p);
671 if (keepws && skipped_spaces && !skipped_braces)
672 // put back the space (it is better handled by check_space)
673 p.unskip_spaces(true);
677 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
678 Context & context, Layout::LaTeXArgMap const & latexargs)
681 context.check_layout(os);
686 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
687 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
688 for (; lait != laend; ++lait) {
690 eat_whitespace(p, os, context, false);
691 if (lait->second.mandatory) {
692 if (p.next_token().cat() != catBegin)
694 p.get_token(); // eat '{'
696 context.check_layout(os);
699 begin_inset(os, "Argument ");
702 os << i << "\nstatus collapsed\n\n";
703 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
706 if (p.next_token().cat() == catEscape ||
707 p.next_token().character() != '[')
709 p.get_token(); // eat '['
711 context.check_layout(os);
714 begin_inset(os, "Argument ");
717 os << i << "\nstatus collapsed\n\n";
718 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
721 eat_whitespace(p, os, context, false);
726 void output_command_layout(ostream & os, Parser & p, bool outer,
727 Context & parent_context,
728 Layout const * newlayout)
730 TeXFont const oldFont = parent_context.font;
731 // save the current font size
732 string const size = oldFont.size;
733 // reset the font size to default, because the font size switches
734 // don't affect section headings and the like
735 parent_context.font.size = Context::normalfont.size;
736 // we only need to write the font change if we have an open layout
737 if (!parent_context.atParagraphStart())
738 output_font_change(os, oldFont, parent_context.font);
739 parent_context.check_end_layout(os);
740 Context context(true, parent_context.textclass, newlayout,
741 parent_context.layout, parent_context.font);
742 if (parent_context.deeper_paragraph) {
743 // We are beginning a nested environment after a
744 // deeper paragraph inside the outer list environment.
745 // Therefore we don't need to output a "begin deeper".
746 context.need_end_deeper = true;
748 context.check_deeper(os);
749 output_arguments(os, p, outer, true, false, context,
750 context.layout->latexargs());
751 parse_text(p, os, FLAG_ITEM, outer, context);
752 output_arguments(os, p, outer, false, true, context,
753 context.layout->postcommandargs());
754 context.check_end_layout(os);
755 if (parent_context.deeper_paragraph) {
756 // We must suppress the "end deeper" because we
757 // suppressed the "begin deeper" above.
758 context.need_end_deeper = false;
760 context.check_end_deeper(os);
761 // We don't need really a new paragraph, but
762 // we must make sure that the next item gets a \begin_layout.
763 parent_context.new_paragraph(os);
764 // Set the font size to the original value. No need to output it here
765 // (Context::begin_layout() will do that if needed)
766 parent_context.font.size = size;
771 * Output a space if necessary.
772 * This function gets called for every whitespace token.
774 * We have three cases here:
775 * 1. A space must be suppressed. Example: The lyxcode case below
776 * 2. A space may be suppressed. Example: Spaces before "\par"
777 * 3. A space must not be suppressed. Example: A space between two words
779 * We currently handle only 1. and 3 and from 2. only the case of
780 * spaces before newlines as a side effect.
782 * 2. could be used to suppress as many spaces as possible. This has two effects:
783 * - Reimporting LyX generated LaTeX files changes almost no whitespace
784 * - Superflous whitespace from non LyX generated LaTeX files is removed.
785 * The drawback is that the logic inside the function becomes
786 * complicated, and that is the reason why it is not implemented.
788 void check_space(Parser & p, ostream & os, Context & context)
790 Token const next = p.next_token();
791 Token const curr = p.curr_token();
792 // A space before a single newline and vice versa must be ignored
793 // LyX emits a newline before \end{lyxcode}.
794 // This newline must be ignored,
795 // otherwise LyX will add an additional protected space.
796 if (next.cat() == catSpace ||
797 next.cat() == catNewline ||
798 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
801 context.check_layout(os);
807 * Parse all arguments of \p command
809 void parse_arguments(string const & command,
810 vector<ArgumentType> const & template_arguments,
811 Parser & p, ostream & os, bool outer, Context & context)
813 string ert = command;
814 size_t no_arguments = template_arguments.size();
815 for (size_t i = 0; i < no_arguments; ++i) {
816 switch (template_arguments[i]) {
819 // This argument contains regular LaTeX
820 output_ert_inset(os, ert + '{', context);
821 eat_whitespace(p, os, context, false);
822 if (template_arguments[i] == required)
823 parse_text(p, os, FLAG_ITEM, outer, context);
825 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
829 // This argument consists only of a single item.
830 // The presence of '{' or not must be preserved.
832 if (p.next_token().cat() == catBegin)
833 ert += '{' + p.verbatim_item() + '}';
835 ert += p.verbatim_item();
839 // This argument may contain special characters
840 ert += '{' + p.verbatim_item() + '}';
844 // true because we must not eat whitespace
845 // if an optional arg follows we must not strip the
846 // brackets from this one
847 if (i < no_arguments - 1 &&
848 template_arguments[i+1] == optional)
849 ert += p.getFullOpt(true);
851 ert += p.getOpt(true);
855 output_ert_inset(os, ert, context);
860 * Check whether \p command is a known command. If yes,
861 * handle the command with all arguments.
862 * \return true if the command was parsed, false otherwise.
864 bool parse_command(string const & command, Parser & p, ostream & os,
865 bool outer, Context & context)
867 if (known_commands.find(command) != known_commands.end()) {
868 parse_arguments(command, known_commands[command], p, os,
876 /// Parses a minipage or parbox
877 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
878 unsigned inner_flags, bool outer, Context & parent_context,
879 string const & outer_type, string const & special,
880 string inner_type, string const & frame_color,
881 string const & background_color)
885 string hor_pos = "l";
886 // We need to set the height to the LaTeX default of 1\\totalheight
887 // for the case when no height argument is given
888 string height_value = "1";
889 string height_unit = "in";
890 string height_special = "totalheight";
895 string width_special = "none";
896 string thickness = "0.4pt";
897 if (!fboxrule.empty())
898 thickness = fboxrule;
902 if (!fboxsep.empty())
903 separation = fboxsep;
907 if (!shadow_size.empty())
908 shadowsize = shadow_size;
911 string framecolor = "black";
912 string backgroundcolor = "none";
913 if (!frame_color.empty())
914 framecolor = frame_color;
915 if (!background_color.empty())
916 backgroundcolor = background_color;
917 // if there is a color box around the \begin statements have not yet been parsed
919 if (!frame_color.empty() || !background_color.empty()) {
920 eat_whitespace(p, os, parent_context, false);
921 p.get_token().asInput(); // the '{'
923 if (p.next_token().asInput() == "\\begin") {
924 p.get_token().asInput();
926 inner_type = "minipage";
927 inner_flags = FLAG_END;
928 active_environments.push_back("minipage");
931 else if (p.next_token().asInput() == "\\parbox") {
932 p.get_token().asInput();
933 inner_type = "parbox";
934 inner_flags = FLAG_ITEM;
937 else if (p.next_token().asInput() == "\\makebox") {
938 p.get_token().asInput();
939 inner_type = "makebox";
940 inner_flags = FLAG_ITEM;
942 // in case there is just \colorbox{color}{text}
945 inner_type = "makebox";
946 inner_flags = FLAG_BRACE_LAST;
951 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
953 if (!inner_type.empty() && p.hasOpt()) {
954 if (inner_type != "makebox")
955 position = p.getArg('[', ']');
957 latex_width = p.getArg('[', ']');
958 translate_box_len(latex_width, width_value, width_unit, width_special);
961 if (position != "t" && position != "c" && position != "b") {
962 cerr << "invalid position " << position << " for "
963 << inner_type << endl;
967 if (inner_type != "makebox") {
968 latex_height = p.getArg('[', ']');
969 translate_box_len(latex_height, height_value, height_unit, height_special);
971 string const opt = p.getArg('[', ']');
974 if (hor_pos != "l" && hor_pos != "c" &&
975 hor_pos != "r" && hor_pos != "s") {
976 cerr << "invalid hor_pos " << hor_pos
977 << " for " << inner_type << endl;
984 inner_pos = p.getArg('[', ']');
985 if (inner_pos != "c" && inner_pos != "t" &&
986 inner_pos != "b" && inner_pos != "s") {
987 cerr << "invalid inner_pos "
988 << inner_pos << " for "
989 << inner_type << endl;
990 inner_pos = position;
994 if (inner_type == "makebox")
998 if (inner_type.empty()) {
999 if (special.empty() && outer_type != "framebox")
1000 latex_width = "1\\columnwidth";
1003 latex_width = p2.getArg('[', ']');
1004 string const opt = p2.getArg('[', ']');
1007 if (hor_pos != "l" && hor_pos != "c" &&
1008 hor_pos != "r" && hor_pos != "s") {
1009 cerr << "invalid hor_pos " << hor_pos
1010 << " for " << outer_type << endl;
1014 if (outer_type == "framebox")
1018 } else if (inner_type != "makebox")
1019 latex_width = p.verbatim_item();
1020 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1021 // as this is LyX's standard for such cases (except for makebox)
1022 // \framebox is more special and handled below
1023 if (latex_width.empty() && inner_type != "makebox"
1024 && outer_type != "framebox")
1025 latex_width = "1\\columnwidth";
1027 translate_len(latex_width, width_value, width_unit);
1029 bool shadedparbox = false;
1030 if (inner_type == "shaded") {
1031 eat_whitespace(p, os, parent_context, false);
1032 if (outer_type == "parbox") {
1034 if (p.next_token().cat() == catBegin)
1036 eat_whitespace(p, os, parent_context, false);
1037 shadedparbox = true;
1042 // If we already read the inner box we have to push the inner env
1043 if (!outer_type.empty() && !inner_type.empty() &&
1044 (inner_flags & FLAG_END))
1045 active_environments.push_back(inner_type);
1046 bool use_ert = false;
1047 if (!outer_type.empty() && !inner_type.empty()) {
1048 // Look whether there is some content after the end of the
1049 // inner box, but before the end of the outer box.
1050 // If yes, we need to output ERT.
1052 if (inner_flags & FLAG_END)
1053 p.ertEnvironment(inner_type);
1056 p.skip_spaces(true);
1057 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1058 if ((outer_env && p.next_token().asInput() != "\\end") ||
1059 (!outer_env && p.next_token().cat() != catEnd)) {
1060 // something is between the end of the inner box and
1061 // the end of the outer box, so we need to use ERT.
1069 if (!outer_type.empty()) {
1070 if (outer_flags & FLAG_END)
1071 ss << "\\begin{" << outer_type << '}';
1073 ss << '\\' << outer_type << '{';
1074 if (!special.empty())
1078 if (!inner_type.empty()) {
1079 if (inner_type != "shaded") {
1080 if (inner_flags & FLAG_END)
1081 ss << "\\begin{" << inner_type << '}';
1083 ss << '\\' << inner_type;
1085 if (!position.empty())
1086 ss << '[' << position << ']';
1087 if (!latex_height.empty())
1088 ss << '[' << latex_height << ']';
1089 if (!inner_pos.empty())
1090 ss << '[' << inner_pos << ']';
1091 ss << '{' << latex_width << '}';
1092 if (!(inner_flags & FLAG_END))
1095 if (inner_type == "shaded")
1096 ss << "\\begin{shaded}";
1097 output_ert_inset(os, ss.str(), parent_context);
1098 if (!inner_type.empty()) {
1099 parse_text(p, os, inner_flags, outer, parent_context);
1100 if (inner_flags & FLAG_END)
1101 output_ert_inset(os, "\\end{" + inner_type + '}',
1104 output_ert_inset(os, "}", parent_context);
1106 if (!outer_type.empty()) {
1107 // If we already read the inner box we have to pop
1109 if (!inner_type.empty() && (inner_flags & FLAG_END))
1110 active_environments.pop_back();
1112 // Ensure that the end of the outer box is parsed correctly:
1113 // The opening brace has been eaten by parse_outer_box()
1114 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1115 outer_flags &= ~FLAG_ITEM;
1116 outer_flags |= FLAG_BRACE_LAST;
1118 parse_text(p, os, outer_flags, outer, parent_context);
1119 if (outer_flags & FLAG_END)
1120 output_ert_inset(os, "\\end{" + outer_type + '}',
1123 output_ert_inset(os, "}", parent_context);
1126 // LyX does not like empty positions, so we have
1127 // to set them to the LaTeX default values here.
1128 if (position.empty())
1130 if (inner_pos.empty())
1131 inner_pos = position;
1132 parent_context.check_layout(os);
1133 begin_inset(os, "Box ");
1134 if (outer_type == "framed")
1136 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1138 else if (outer_type == "shadowbox")
1139 os << "Shadowbox\n";
1140 else if ((outer_type == "shaded" && inner_type.empty()) ||
1141 (outer_type == "minipage" && inner_type == "shaded") ||
1142 (outer_type == "parbox" && inner_type == "shaded")) {
1144 preamble.registerAutomaticallyLoadedPackage("color");
1145 } else if (outer_type == "doublebox")
1146 os << "Doublebox\n";
1147 else if (outer_type.empty() || outer_type == "mbox")
1148 os << "Frameless\n";
1150 os << outer_type << '\n';
1151 os << "position \"" << position << "\"\n";
1152 os << "hor_pos \"" << hor_pos << "\"\n";
1153 if (outer_type == "mbox")
1154 os << "has_inner_box 1\n";
1155 else if (!frame_color.empty() && inner_type == "makebox")
1156 os << "has_inner_box 0\n";
1158 os << "has_inner_box " << !inner_type.empty() << "\n";
1159 os << "inner_pos \"" << inner_pos << "\"\n";
1160 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1162 if (outer_type == "mbox")
1163 os << "use_makebox 1\n";
1164 else if (!frame_color.empty())
1165 os << "use_makebox 0\n";
1167 os << "use_makebox " << (inner_type == "makebox") << '\n';
1168 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1169 os << "width \"\"\n";
1170 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1171 else if (contains(width_unit, '\\'))
1172 os << "width \"" << width_value << "in" << "\"\n";
1174 os << "width \"" << width_value << width_unit << "\"\n";
1175 if (contains(width_unit, '\\')) {
1176 width_unit.erase (0,1); // remove the leading '\'
1177 os << "special \"" << width_unit << "\"\n";
1179 os << "special \"" << width_special << "\"\n";
1180 if (contains(height_unit, '\\'))
1181 os << "height \"" << height_value << "in" << "\"\n";
1183 os << "height \"" << height_value << height_unit << "\"\n";
1184 os << "height_special \"" << height_special << "\"\n";
1185 os << "thickness \"" << thickness << "\"\n";
1186 os << "separation \"" << separation << "\"\n";
1187 os << "shadowsize \"" << shadowsize << "\"\n";
1188 os << "framecolor \"" << framecolor << "\"\n";
1189 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1190 os << "status open\n\n";
1192 // Unfortunately we can't use parse_text_in_inset:
1193 // InsetBox::forcePlainLayout() is hard coded and does not
1194 // use the inset layout. Apart from that do we call parse_text
1195 // up to two times, but need only one check_end_layout.
1196 bool const forcePlainLayout =
1197 (!inner_type.empty() || inner_type == "makebox") &&
1198 outer_type != "shaded" && outer_type != "framed";
1199 Context context(true, parent_context.textclass);
1200 if (forcePlainLayout)
1201 context.layout = &context.textclass.plainLayout();
1203 context.font = parent_context.font;
1205 // If we have no inner box the contents will be read with the outer box
1206 if (!inner_type.empty())
1207 parse_text(p, os, inner_flags, outer, context);
1209 // Ensure that the end of the outer box is parsed correctly:
1210 // The opening brace has been eaten by parse_outer_box()
1211 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1212 outer_flags &= ~FLAG_ITEM;
1213 outer_flags |= FLAG_BRACE_LAST;
1216 // Find end of outer box, output contents if inner_type is
1217 // empty and output possible comments
1218 if (!outer_type.empty()) {
1219 // If we already read the inner box we have to pop
1221 if (!inner_type.empty() && (inner_flags & FLAG_END))
1222 active_environments.pop_back();
1223 // This does not output anything but comments if
1224 // inner_type is not empty (see use_ert)
1225 parse_text(p, os, outer_flags, outer, context);
1228 context.check_end_layout(os);
1230 #ifdef PRESERVE_LAYOUT
1231 // LyX puts a % after the end of the minipage
1232 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1234 //output_comment(p, os, "dummy", parent_context);
1237 parent_context.new_paragraph(os);
1239 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1240 //output_comment(p, os, "dummy", parent_context);
1243 // We add a protected space if something real follows
1244 if (p.good() && p.next_token().cat() != catComment) {
1245 begin_inset(os, "space ~\n");
1251 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1252 active_environments.pop_back();
1253 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1254 // in this case we have to eat the the closing brace of the color box
1255 p.get_token().asInput(); // the '}'
1257 if (p.next_token().asInput() == "}") {
1258 // in this case we assume that the closing brace is from the box settings
1259 // therefore reset these values for the next box
1265 // all boxes except of Frameless and Shaded require calc
1266 if (!(outer_type.empty() || outer_type == "mbox") &&
1267 !((outer_type == "shaded" && inner_type.empty()) ||
1268 (outer_type == "minipage" && inner_type == "shaded") ||
1269 (outer_type == "parbox" && inner_type == "shaded")))
1270 preamble.registerAutomaticallyLoadedPackage("calc");
1274 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1275 Context & parent_context, string const & outer_type,
1276 string const & special)
1278 eat_whitespace(p, os, parent_context, false);
1279 if (flags & FLAG_ITEM) {
1281 if (p.next_token().cat() == catBegin)
1284 cerr << "Warning: Ignoring missing '{' after \\"
1285 << outer_type << '.' << endl;
1286 eat_whitespace(p, os, parent_context, false);
1289 unsigned int inner_flags = 0;
1291 if (outer_type == "minipage" || outer_type == "parbox") {
1292 p.skip_spaces(true);
1293 while (p.hasOpt()) {
1295 p.skip_spaces(true);
1298 p.skip_spaces(true);
1299 if (outer_type == "parbox") {
1301 if (p.next_token().cat() == catBegin)
1303 p.skip_spaces(true);
1306 if (outer_type == "shaded" || outer_type == "mbox") {
1307 // These boxes never have an inner box
1309 } else if (p.next_token().asInput() == "\\parbox") {
1310 inner = p.get_token().cs();
1311 inner_flags = FLAG_ITEM;
1312 } else if (p.next_token().asInput() == "\\begin") {
1313 // Is this a minipage or shaded box?
1316 inner = p.getArg('{', '}');
1318 if (inner == "minipage" || inner == "shaded")
1319 inner_flags = FLAG_END;
1324 if (inner_flags == FLAG_END) {
1325 if (inner != "shaded")
1329 eat_whitespace(p, os, parent_context, false);
1331 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1332 outer_type, special, inner, "", "");
1334 if (inner_flags == FLAG_ITEM) {
1336 eat_whitespace(p, os, parent_context, false);
1338 parse_box(p, os, flags, inner_flags, outer, parent_context,
1339 outer_type, special, inner, "", "");
1344 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1345 bool in_line, bool use_minted)
1347 parent_context.check_layout(os);
1348 begin_inset(os, "listings\n");
1349 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1351 while ((i = arg.find(", ")) != string::npos
1352 || (i = arg.find(",\t")) != string::npos)
1353 arg.erase(i + 1, 1);
1356 string const language = p.getArg('{', '}');
1357 p.skip_spaces(true);
1358 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1359 if (!minted_float.empty()) {
1360 arg += string(arg.empty() ? "" : ",") + minted_float;
1361 minted_nonfloat_caption.clear();
1365 os << "lstparams " << '"' << arg << '"' << '\n';
1366 if (arg.find("\\color") != string::npos)
1367 preamble.registerAutomaticallyLoadedPackage("color");
1370 os << "inline true\n";
1372 os << "inline false\n";
1373 os << "status collapsed\n";
1374 Context context(true, parent_context.textclass);
1375 context.layout = &parent_context.textclass.plainLayout();
1376 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1377 minted_nonfloat_caption.erase(0,3);
1378 os << "\n\\begin_layout Plain Layout\n";
1379 begin_inset(os, "Caption Standard\n");
1380 Context newcontext(true, context.textclass,
1381 context.layout, 0, context.font);
1382 newcontext.check_layout(os);
1383 os << minted_nonfloat_caption << "\n";
1384 newcontext.check_end_layout(os);
1386 os << "\n\\end_layout\n";
1387 minted_nonfloat_caption.clear();
1391 // set catcodes to verbatim early, just in case.
1392 p.setCatcodes(VERBATIM_CATCODES);
1393 string delim = p.get_token().asInput();
1394 //FIXME: handler error condition
1395 s = p.verbatimStuff(delim).second;
1396 // context.new_paragraph(os);
1397 } else if (use_minted) {
1398 s = p.verbatimEnvironment("minted");
1400 s = p.verbatimEnvironment("lstlisting");
1402 output_ert(os, s, context);
1403 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1404 minted_nonfloat_caption.erase(0,3);
1405 os << "\n\\begin_layout Plain Layout\n";
1406 begin_inset(os, "Caption Standard\n");
1407 Context newcontext(true, context.textclass,
1408 context.layout, 0, context.font);
1409 newcontext.check_layout(os);
1410 os << minted_nonfloat_caption << "\n";
1411 newcontext.check_end_layout(os);
1413 os << "\n\\end_layout\n";
1414 minted_nonfloat_caption.clear();
1416 // Don't close the inset here for floating minted listings.
1417 // It will be closed at the end of the listing environment.
1418 if (!use_minted || minted_float.empty())
1421 eat_whitespace(p, os, parent_context, true);
1422 Token t = p.get_token();
1423 if (t.asInput() != "\\end") {
1424 // If anything follows, collect it into a caption.
1425 minted_float_has_caption = true;
1426 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1427 begin_inset(os, "Caption Standard\n");
1428 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1435 /// parse an unknown environment
1436 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1437 unsigned flags, bool outer,
1438 Context & parent_context)
1440 if (name == "tabbing")
1441 // We need to remember that we have to handle '\=' specially
1442 flags |= FLAG_TABBING;
1444 // We need to translate font changes and paragraphs inside the
1445 // environment to ERT if we have a non standard font.
1446 // Otherwise things like
1447 // \large\begin{foo}\huge bar\end{foo}
1449 bool const specialfont =
1450 (parent_context.font != parent_context.normalfont);
1451 bool const new_layout_allowed = parent_context.new_layout_allowed;
1453 parent_context.new_layout_allowed = false;
1454 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1455 parse_text_snippet(p, os, flags, outer, parent_context);
1456 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1458 parent_context.new_layout_allowed = new_layout_allowed;
1462 void parse_environment(Parser & p, ostream & os, bool outer,
1463 string & last_env, Context & parent_context)
1465 Layout const * newlayout;
1466 InsetLayout const * newinsetlayout = 0;
1467 string const name = p.getArg('{', '}');
1468 const bool is_starred = suffixIs(name, '*');
1469 string const unstarred_name = rtrim(name, "*");
1470 active_environments.push_back(name);
1472 if (is_math_env(name)) {
1473 parent_context.check_layout(os);
1474 begin_inset(os, "Formula ");
1475 os << "\\begin{" << name << "}";
1476 parse_math(p, os, FLAG_END, MATH_MODE);
1477 os << "\\end{" << name << "}";
1479 if (is_display_math_env(name)) {
1480 // Prevent the conversion of a line break to a space
1481 // (bug 7668). This does not change the output, but
1482 // looks ugly in LyX.
1483 eat_whitespace(p, os, parent_context, false);
1487 else if (is_known(name, preamble.polyglossia_languages)) {
1488 // We must begin a new paragraph if not already done
1489 if (! parent_context.atParagraphStart()) {
1490 parent_context.check_end_layout(os);
1491 parent_context.new_paragraph(os);
1493 // save the language in the context so that it is
1494 // handled by parse_text
1495 parent_context.font.language = preamble.polyglossia2lyx(name);
1496 parse_text(p, os, FLAG_END, outer, parent_context);
1497 // Just in case the environment is empty
1498 parent_context.extra_stuff.erase();
1499 // We must begin a new paragraph to reset the language
1500 parent_context.new_paragraph(os);
1504 else if (unstarred_name == "tabular" || name == "longtable") {
1505 eat_whitespace(p, os, parent_context, false);
1506 string width = "0pt";
1507 if (name == "tabular*") {
1508 width = lyx::translate_len(p.getArg('{', '}'));
1509 eat_whitespace(p, os, parent_context, false);
1511 parent_context.check_layout(os);
1512 begin_inset(os, "Tabular ");
1513 handle_tabular(p, os, name, width, parent_context);
1518 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1519 eat_whitespace(p, os, parent_context, false);
1520 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1521 eat_whitespace(p, os, parent_context, false);
1522 parent_context.check_layout(os);
1523 begin_inset(os, "Float " + unstarred_name + "\n");
1524 // store the float type for subfloats
1525 // subfloats only work with figures and tables
1526 if (unstarred_name == "figure")
1527 float_type = unstarred_name;
1528 else if (unstarred_name == "table")
1529 float_type = unstarred_name;
1533 os << "placement " << opt << '\n';
1534 if (contains(opt, "H"))
1535 preamble.registerAutomaticallyLoadedPackage("float");
1537 Floating const & fl = parent_context.textclass.floats()
1538 .getType(unstarred_name);
1539 if (!fl.floattype().empty() && fl.usesFloatPkg())
1540 preamble.registerAutomaticallyLoadedPackage("float");
1543 os << "wide " << convert<string>(is_starred)
1544 << "\nsideways false"
1545 << "\nstatus open\n\n";
1546 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1548 // We don't need really a new paragraph, but
1549 // we must make sure that the next item gets a \begin_layout.
1550 parent_context.new_paragraph(os);
1552 // the float is parsed thus delete the type
1556 else if (unstarred_name == "sidewaysfigure"
1557 || unstarred_name == "sidewaystable"
1558 || unstarred_name == "sidewaysalgorithm") {
1559 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1560 eat_whitespace(p, os, parent_context, false);
1561 parent_context.check_layout(os);
1562 if (unstarred_name == "sidewaysfigure")
1563 begin_inset(os, "Float figure\n");
1564 else if (unstarred_name == "sidewaystable")
1565 begin_inset(os, "Float table\n");
1566 else if (unstarred_name == "sidewaysalgorithm")
1567 begin_inset(os, "Float algorithm\n");
1569 os << "placement " << opt << '\n';
1570 if (contains(opt, "H"))
1571 preamble.registerAutomaticallyLoadedPackage("float");
1572 os << "wide " << convert<string>(is_starred)
1573 << "\nsideways true"
1574 << "\nstatus open\n\n";
1575 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1577 // We don't need really a new paragraph, but
1578 // we must make sure that the next item gets a \begin_layout.
1579 parent_context.new_paragraph(os);
1581 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1584 else if (name == "wrapfigure" || name == "wraptable") {
1585 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1586 eat_whitespace(p, os, parent_context, false);
1587 parent_context.check_layout(os);
1590 string overhang = "0col%";
1593 lines = p.getArg('[', ']');
1594 string const placement = p.getArg('{', '}');
1596 overhang = p.getArg('[', ']');
1597 string const width = p.getArg('{', '}');
1599 if (name == "wrapfigure")
1600 begin_inset(os, "Wrap figure\n");
1602 begin_inset(os, "Wrap table\n");
1603 os << "lines " << lines
1604 << "\nplacement " << placement
1605 << "\noverhang " << lyx::translate_len(overhang)
1606 << "\nwidth " << lyx::translate_len(width)
1607 << "\nstatus open\n\n";
1608 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1610 // We don't need really a new paragraph, but
1611 // we must make sure that the next item gets a \begin_layout.
1612 parent_context.new_paragraph(os);
1614 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1617 else if (name == "minipage") {
1618 eat_whitespace(p, os, parent_context, false);
1619 // Test whether this is an outer box of a shaded box
1621 // swallow arguments
1622 while (p.hasOpt()) {
1624 p.skip_spaces(true);
1627 p.skip_spaces(true);
1628 Token t = p.get_token();
1629 bool shaded = false;
1630 if (t.asInput() == "\\begin") {
1631 p.skip_spaces(true);
1632 if (p.getArg('{', '}') == "shaded")
1637 parse_outer_box(p, os, FLAG_END, outer,
1638 parent_context, name, "shaded");
1640 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1641 "", "", name, "", "");
1645 else if (name == "comment") {
1646 eat_whitespace(p, os, parent_context, false);
1647 parent_context.check_layout(os);
1648 begin_inset(os, "Note Comment\n");
1649 os << "status open\n";
1650 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1653 skip_braces(p); // eat {} that might by set by LyX behind comments
1654 preamble.registerAutomaticallyLoadedPackage("verbatim");
1657 else if (unstarred_name == "verbatim") {
1658 // FIXME: this should go in the generic code that
1659 // handles environments defined in layout file that
1660 // have "PassThru 1". However, the code over there is
1661 // already too complicated for my taste.
1662 string const ascii_name =
1663 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1664 parent_context.new_paragraph(os);
1665 Context context(true, parent_context.textclass,
1666 &parent_context.textclass[from_ascii(ascii_name)]);
1667 string s = p.verbatimEnvironment(name);
1668 output_ert(os, s, context);
1672 else if (name == "IPA") {
1673 eat_whitespace(p, os, parent_context, false);
1674 parent_context.check_layout(os);
1675 begin_inset(os, "IPA\n");
1676 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1679 preamble.registerAutomaticallyLoadedPackage("tipa");
1680 preamble.registerAutomaticallyLoadedPackage("tipx");
1683 else if (name == "CJK") {
1684 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1685 // It is impossible to decide if a CJK environment was in its own paragraph or within
1686 // a line. We therefore always assume a paragraph since the latter is a rare case.
1687 eat_whitespace(p, os, parent_context, false);
1688 parent_context.check_end_layout(os);
1689 // store the encoding to be able to reset it
1690 string const encoding_old = p.getEncoding();
1691 string const encoding = p.getArg('{', '}');
1692 // FIXME: For some reason JIS does not work. Although the text
1693 // in tests/CJK.tex is identical with the SJIS version if you
1694 // convert both snippets using the recode command line utility,
1695 // the resulting .lyx file contains some extra characters if
1696 // you set buggy_encoding to false for JIS.
1697 bool const buggy_encoding = encoding == "JIS";
1698 if (!buggy_encoding)
1699 p.setEncoding(encoding, Encoding::CJK);
1701 // FIXME: This will read garbage, since the data is not encoded in utf8.
1702 p.setEncoding("UTF-8");
1704 // LyX only supports the same mapping for all CJK
1705 // environments, so we might need to output everything as ERT
1706 string const mapping = trim(p.getArg('{', '}'));
1707 char const * const * const where =
1708 is_known(encoding, supported_CJK_encodings);
1709 if (!buggy_encoding && !preamble.fontCJKSet())
1710 preamble.fontCJK(mapping);
1711 bool knownMapping = mapping == preamble.fontCJK();
1712 if (buggy_encoding || !knownMapping || !where) {
1713 parent_context.check_layout(os);
1714 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1716 // we must parse the content as verbatim because e.g. JIS can contain
1717 // normally invalid characters
1718 // FIXME: This works only for the most simple cases.
1719 // Since TeX control characters are not parsed,
1720 // things like comments are completely wrong.
1721 string const s = p.plainEnvironment("CJK");
1722 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1725 if (snip == "\\" || is_known(snip, known_escaped_chars))
1726 output_ert_inset(os, snip, parent_context);
1727 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1732 output_ert_inset(os, "\\end{" + name + "}",
1736 supported_CJK_languages[where - supported_CJK_encodings];
1737 // store the language because we must reset it at the end
1738 string const lang_old = parent_context.font.language;
1739 parent_context.font.language = lang;
1740 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1741 parent_context.font.language = lang_old;
1742 parent_context.new_paragraph(os);
1744 p.setEncoding(encoding_old);
1748 else if (name == "lyxgreyedout") {
1749 eat_whitespace(p, os, parent_context, false);
1750 parent_context.check_layout(os);
1751 begin_inset(os, "Note Greyedout\n");
1752 os << "status open\n";
1753 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1756 if (!preamble.notefontcolor().empty())
1757 preamble.registerAutomaticallyLoadedPackage("color");
1760 else if (name == "btSect") {
1761 eat_whitespace(p, os, parent_context, false);
1762 parent_context.check_layout(os);
1763 begin_command_inset(os, "bibtex", "bibtex");
1764 string bibstyle = "plain";
1766 bibstyle = p.getArg('[', ']');
1767 p.skip_spaces(true);
1769 string const bibfile = p.getArg('{', '}');
1770 eat_whitespace(p, os, parent_context, false);
1771 Token t = p.get_token();
1772 if (t.asInput() == "\\btPrintCited") {
1773 p.skip_spaces(true);
1774 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1776 if (t.asInput() == "\\btPrintNotCited") {
1777 p.skip_spaces(true);
1778 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1780 if (t.asInput() == "\\btPrintAll") {
1781 p.skip_spaces(true);
1782 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1784 os << "bibfiles " << '"' << bibfile << "\"\n"
1785 << "options " << '"' << bibstyle << "\"\n";
1786 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1791 else if (name == "framed" || name == "shaded") {
1792 eat_whitespace(p, os, parent_context, false);
1793 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1795 preamble.registerAutomaticallyLoadedPackage("framed");
1798 else if (name == "listing") {
1799 minted_float = "float";
1800 eat_whitespace(p, os, parent_context, false);
1801 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1803 minted_float += "=" + opt;
1804 // If something precedes \begin{minted}, we output it at the end
1805 // as a caption, in order to keep it inside the listings inset.
1806 eat_whitespace(p, os, parent_context, true);
1808 Token const & t = p.get_token();
1809 p.skip_spaces(true);
1810 string const envname = p.next_token().cat() == catBegin
1811 ? p.getArg('{', '}') : string();
1812 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1814 minted_float_has_caption = false;
1815 string content = parse_text_snippet(p, FLAG_END, outer,
1817 size_t i = content.find("\\begin_inset listings");
1818 bool minted_env = i != string::npos;
1821 caption = content.substr(0, i);
1822 content.erase(0, i);
1824 parent_context.check_layout(os);
1825 if (minted_env && minted_float_has_caption) {
1826 eat_whitespace(p, os, parent_context, true);
1827 os << content << "\n";
1828 if (!caption.empty())
1829 os << caption << "\n";
1830 os << "\n\\end_layout\n"; // close inner layout
1831 end_inset(os); // close caption inset
1832 os << "\n\\end_layout\n"; // close outer layout
1833 } else if (!caption.empty()) {
1835 begin_inset(os, "listings\n");
1836 os << "lstparams " << '"' << minted_float << '"' << '\n';
1837 os << "inline false\n";
1838 os << "status collapsed\n";
1840 os << "\n\\begin_layout Plain Layout\n";
1841 begin_inset(os, "Caption Standard\n");
1842 Context newcontext(true, parent_context.textclass,
1843 0, 0, parent_context.font);
1844 newcontext.check_layout(os);
1845 os << caption << "\n";
1846 newcontext.check_end_layout(os);
1848 os << "\n\\end_layout\n";
1849 } else if (content.empty()) {
1850 begin_inset(os, "listings\n");
1851 os << "lstparams " << '"' << minted_float << '"' << '\n';
1852 os << "inline false\n";
1853 os << "status collapsed\n";
1855 os << content << "\n";
1857 end_inset(os); // close listings inset
1858 parent_context.check_end_layout(os);
1859 parent_context.new_paragraph(os);
1861 minted_float.clear();
1862 minted_float_has_caption = false;
1865 else if (name == "lstlisting" || name == "minted") {
1866 bool use_minted = name == "minted";
1867 eat_whitespace(p, os, parent_context, false);
1868 if (use_minted && minted_float.empty()) {
1869 // look ahead for a bottom caption
1871 bool found_end_minted = false;
1872 while (!found_end_minted && p.good()) {
1873 Token const & t = p.get_token();
1875 string const envname =
1876 p.next_token().cat() == catBegin
1877 ? p.getArg('{', '}') : string();
1878 found_end_minted = t.asInput() == "\\end"
1879 && envname == "minted";
1881 eat_whitespace(p, os, parent_context, true);
1882 Token const & t = p.get_token();
1883 p.skip_spaces(true);
1884 if (t.asInput() == "\\lyxmintcaption") {
1885 string const pos = p.getArg('[', ']');
1887 string const caption =
1888 parse_text_snippet(p, FLAG_ITEM,
1889 false, parent_context);
1890 minted_nonfloat_caption = "[b]" + caption;
1895 parse_listings(p, os, parent_context, false, use_minted);
1899 else if (!parent_context.new_layout_allowed)
1900 parse_unknown_environment(p, name, os, FLAG_END, outer,
1903 // Alignment and spacing settings
1904 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1905 // therefore are totally broken!
1906 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1907 // they are commands not environments. They are furthermore switches that
1908 // can be ended by another switches, but also by commands like \footnote or
1909 // \parbox. So the only safe way is to leave them untouched.
1910 // However, we support the pseudo-environments
1911 // \begin{centering} ... \end{centering}
1912 // \begin{raggedright} ... \end{raggedright}
1913 // \begin{raggedleft} ... \end{raggedleft}
1914 // since they are used by LyX in floats (for spacing reasons)
1915 else if (name == "center" || name == "centering" ||
1916 name == "flushleft" || name == "raggedright" ||
1917 name == "flushright" || name == "raggedleft" ||
1918 name == "singlespace" || name == "onehalfspace" ||
1919 name == "doublespace" || name == "spacing") {
1920 eat_whitespace(p, os, parent_context, false);
1921 // We must begin a new paragraph if not already done
1922 if (! parent_context.atParagraphStart()) {
1923 parent_context.check_end_layout(os);
1924 parent_context.new_paragraph(os);
1926 if (name == "flushleft" || name == "raggedright")
1927 parent_context.add_extra_stuff("\\align left\n");
1928 else if (name == "flushright" || name == "raggedleft")
1929 parent_context.add_extra_stuff("\\align right\n");
1930 else if (name == "center" || name == "centering")
1931 parent_context.add_extra_stuff("\\align center\n");
1932 else if (name == "singlespace")
1933 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1934 else if (name == "onehalfspace") {
1935 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1936 preamble.registerAutomaticallyLoadedPackage("setspace");
1937 } else if (name == "doublespace") {
1938 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1939 preamble.registerAutomaticallyLoadedPackage("setspace");
1940 } else if (name == "spacing") {
1941 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1942 preamble.registerAutomaticallyLoadedPackage("setspace");
1944 parse_text(p, os, FLAG_END, outer, parent_context);
1945 // Just in case the environment is empty
1946 parent_context.extra_stuff.erase();
1947 // We must begin a new paragraph to reset the alignment
1948 parent_context.new_paragraph(os);
1952 // The single '=' is meant here.
1953 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1954 eat_whitespace(p, os, parent_context, false);
1955 Context context(true, parent_context.textclass, newlayout,
1956 parent_context.layout, parent_context.font);
1957 if (parent_context.deeper_paragraph) {
1958 // We are beginning a nested environment after a
1959 // deeper paragraph inside the outer list environment.
1960 // Therefore we don't need to output a "begin deeper".
1961 context.need_end_deeper = true;
1963 parent_context.check_end_layout(os);
1964 if (last_env == name) {
1965 // we need to output a separator since LyX would export
1966 // the two environments as one otherwise (bug 5716)
1967 TeX2LyXDocClass const & textclass(parent_context.textclass);
1968 Context newcontext(true, textclass,
1969 &(textclass.defaultLayout()));
1970 newcontext.check_layout(os);
1971 begin_inset(os, "Separator plain\n");
1973 newcontext.check_end_layout(os);
1975 switch (context.layout->latextype) {
1976 case LATEX_LIST_ENVIRONMENT:
1977 context.add_par_extra_stuff("\\labelwidthstring "
1978 + p.verbatim_item() + '\n');
1981 case LATEX_BIB_ENVIRONMENT:
1982 p.verbatim_item(); // swallow next arg
1988 context.check_deeper(os);
1989 // handle known optional and required arguments
1990 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1991 // It is impossible to place anything after the environment name,
1992 // but before the first \\item.
1993 if (context.layout->latextype == LATEX_ENVIRONMENT)
1994 output_arguments(os, p, outer, false, false, context,
1995 context.layout->latexargs());
1996 parse_text(p, os, FLAG_END, outer, context);
1997 if (context.layout->latextype == LATEX_ENVIRONMENT)
1998 output_arguments(os, p, outer, false, true, context,
1999 context.layout->postcommandargs());
2000 context.check_end_layout(os);
2001 if (parent_context.deeper_paragraph) {
2002 // We must suppress the "end deeper" because we
2003 // suppressed the "begin deeper" above.
2004 context.need_end_deeper = false;
2006 context.check_end_deeper(os);
2007 parent_context.new_paragraph(os);
2009 if (!preamble.titleLayoutFound())
2010 preamble.titleLayoutFound(newlayout->intitle);
2011 set<string> const & req = newlayout->requires();
2012 set<string>::const_iterator it = req.begin();
2013 set<string>::const_iterator en = req.end();
2014 for (; it != en; ++it)
2015 preamble.registerAutomaticallyLoadedPackage(*it);
2018 // The single '=' is meant here.
2019 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2020 eat_whitespace(p, os, parent_context, false);
2021 parent_context.check_layout(os);
2022 begin_inset(os, "Flex ");
2023 docstring flex_name = newinsetlayout->name();
2024 // FIXME: what do we do if the prefix is not Flex: ?
2025 if (prefixIs(flex_name, from_ascii("Flex:")))
2026 flex_name.erase(0, 5);
2027 os << to_utf8(flex_name) << '\n'
2028 << "status collapsed\n";
2029 if (newinsetlayout->isPassThru()) {
2030 string const arg = p.verbatimEnvironment(name);
2031 Context context(true, parent_context.textclass,
2032 &parent_context.textclass.plainLayout(),
2033 parent_context.layout);
2034 output_ert(os, arg, parent_context);
2036 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2040 else if (name == "appendix") {
2041 // This is no good latex style, but it works and is used in some documents...
2042 eat_whitespace(p, os, parent_context, false);
2043 parent_context.check_end_layout(os);
2044 Context context(true, parent_context.textclass, parent_context.layout,
2045 parent_context.layout, parent_context.font);
2046 context.check_layout(os);
2047 os << "\\start_of_appendix\n";
2048 parse_text(p, os, FLAG_END, outer, context);
2049 context.check_end_layout(os);
2053 else if (known_environments.find(name) != known_environments.end()) {
2054 vector<ArgumentType> arguments = known_environments[name];
2055 // The last "argument" denotes wether we may translate the
2056 // environment contents to LyX
2057 // The default required if no argument is given makes us
2058 // compatible with the reLyXre environment.
2059 ArgumentType contents = arguments.empty() ?
2062 if (!arguments.empty())
2063 arguments.pop_back();
2064 // See comment in parse_unknown_environment()
2065 bool const specialfont =
2066 (parent_context.font != parent_context.normalfont);
2067 bool const new_layout_allowed =
2068 parent_context.new_layout_allowed;
2070 parent_context.new_layout_allowed = false;
2071 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2072 outer, parent_context);
2073 if (contents == verbatim)
2074 output_ert_inset(os, p.ertEnvironment(name),
2077 parse_text_snippet(p, os, FLAG_END, outer,
2079 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2081 parent_context.new_layout_allowed = new_layout_allowed;
2085 parse_unknown_environment(p, name, os, FLAG_END, outer,
2089 active_environments.pop_back();
2093 /// parses a comment and outputs it to \p os.
2094 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2096 LASSERT(t.cat() == catComment, return);
2097 if (!t.cs().empty()) {
2098 context.check_layout(os);
2099 output_comment(p, os, t.cs(), context);
2100 if (p.next_token().cat() == catNewline) {
2101 // A newline after a comment line starts a new
2103 if (context.new_layout_allowed) {
2104 if(!context.atParagraphStart())
2105 // Only start a new paragraph if not already
2106 // done (we might get called recursively)
2107 context.new_paragraph(os);
2109 output_ert_inset(os, "\n", context);
2110 eat_whitespace(p, os, context, true);
2113 // "%\n" combination
2120 * Reads spaces and comments until the first non-space, non-comment token.
2121 * New paragraphs (double newlines or \\par) are handled like simple spaces
2122 * if \p eatParagraph is true.
2123 * Spaces are skipped, but comments are written to \p os.
2125 void eat_whitespace(Parser & p, ostream & os, Context & context,
2129 Token const & t = p.get_token();
2130 if (t.cat() == catComment)
2131 parse_comment(p, os, t, context);
2132 else if ((! eatParagraph && p.isParagraph()) ||
2133 (t.cat() != catSpace && t.cat() != catNewline)) {
2142 * Set a font attribute, parse text and reset the font attribute.
2143 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2144 * \param currentvalue Current value of the attribute. Is set to the new
2145 * value during parsing.
2146 * \param newvalue New value of the attribute
2148 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2149 Context & context, string const & attribute,
2150 string & currentvalue, string const & newvalue)
2152 context.check_layout(os);
2153 string const oldvalue = currentvalue;
2154 currentvalue = newvalue;
2155 os << '\n' << attribute << ' ' << newvalue << "\n";
2156 parse_text_snippet(p, os, flags, outer, context);
2157 context.check_layout(os);
2158 os << '\n' << attribute << ' ' << oldvalue << "\n";
2159 currentvalue = oldvalue;
2163 /// get the arguments of a natbib or jurabib citation command
2164 void get_cite_arguments(Parser & p, bool natbibOrder,
2165 string & before, string & after, bool const qualified = false)
2167 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2169 // text before the citation
2171 // text after the citation
2172 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2174 if (!after.empty()) {
2175 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2176 if (natbibOrder && !before.empty())
2177 swap(before, after);
2182 void copy_file(FileName const & src, string dstname)
2186 string const absParent = getParentFilePath(false);
2188 if (FileName::isAbsolute(dstname))
2189 dst = FileName(dstname);
2191 dst = makeAbsPath(dstname, absParent);
2192 FileName const srcpath = src.onlyPath();
2193 FileName const dstpath = dst.onlyPath();
2194 if (equivalent(srcpath, dstpath))
2196 if (!dstpath.isDirectory()) {
2197 if (!dstpath.createPath()) {
2198 cerr << "Warning: Could not create directory for file `"
2199 << dst.absFileName() << "´." << endl;
2203 if (dst.isReadableFile()) {
2204 if (overwriteFiles())
2205 cerr << "Warning: Overwriting existing file `"
2206 << dst.absFileName() << "´." << endl;
2208 cerr << "Warning: Not overwriting existing file `"
2209 << dst.absFileName() << "´." << endl;
2213 if (!src.copyTo(dst))
2214 cerr << "Warning: Could not copy file `" << src.absFileName()
2215 << "´ to `" << dst.absFileName() << "´." << endl;
2219 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2220 bool parse_chunk(Parser & p, ostream & os, Context & context)
2222 // check whether a chunk is possible here.
2223 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2229 // read the parameters
2230 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2231 if (!params.first) {
2236 Parser::Arg const code = p.verbatimStuff("\n@");
2241 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2242 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2246 // The last newline read is important for paragraph handling
2250 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2251 // We must have a valid layout before outputting the Chunk inset.
2252 context.check_layout(os);
2253 Context chunkcontext(true, context.textclass);
2254 chunkcontext.layout = &context.textclass.plainLayout();
2255 begin_inset(os, "Flex Chunk");
2256 os << "\nstatus open\n";
2257 if (!params.second.empty()) {
2258 chunkcontext.check_layout(os);
2259 Context paramscontext(true, context.textclass);
2260 paramscontext.layout = &context.textclass.plainLayout();
2261 begin_inset(os, "Argument 1");
2262 os << "\nstatus open\n";
2263 output_ert(os, params.second, paramscontext);
2266 output_ert(os, code.second, chunkcontext);
2274 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2275 bool is_macro(Parser & p)
2277 Token first = p.curr_token();
2278 if (first.cat() != catEscape || !p.good())
2280 if (first.cs() == "def")
2282 if (first.cs() != "global" && first.cs() != "long")
2284 Token second = p.get_token();
2286 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2287 second.cat() == catNewline || second.cat() == catComment)) {
2288 second = p.get_token();
2291 bool secondvalid = second.cat() == catEscape;
2293 bool thirdvalid = false;
2294 if (p.good() && first.cs() == "global" && secondvalid &&
2295 second.cs() == "long") {
2296 third = p.get_token();
2298 while (p.good() && !p.isParagraph() &&
2299 (third.cat() == catSpace ||
2300 third.cat() == catNewline ||
2301 third.cat() == catComment)) {
2302 third = p.get_token();
2305 thirdvalid = third.cat() == catEscape;
2307 for (int i = 0; i < pos; ++i)
2312 return (first.cs() == "global" || first.cs() == "long") &&
2313 second.cs() == "def";
2314 return first.cs() == "global" && second.cs() == "long" &&
2315 third.cs() == "def";
2319 /// Parse a macro definition (assumes that is_macro() returned true)
2320 void parse_macro(Parser & p, ostream & os, Context & context)
2322 context.check_layout(os);
2323 Token first = p.curr_token();
2326 string command = first.asInput();
2327 if (first.cs() != "def") {
2329 eat_whitespace(p, os, context, false);
2330 second = p.curr_token();
2331 command += second.asInput();
2332 if (second.cs() != "def") {
2334 eat_whitespace(p, os, context, false);
2335 third = p.curr_token();
2336 command += third.asInput();
2339 eat_whitespace(p, os, context, false);
2340 string const name = p.get_token().cs();
2341 eat_whitespace(p, os, context, false);
2347 while (p.next_token().cat() != catBegin) {
2348 if (p.next_token().cat() == catParameter) {
2353 // followed by number?
2354 if (p.next_token().cat() == catOther) {
2355 string s = p.get_token().asInput();
2357 // number = current arity + 1?
2358 if (s.size() == 1 && s[0] == arity + '0' + 1)
2363 paramtext += p.get_token().cs();
2365 paramtext += p.get_token().cs();
2370 // only output simple (i.e. compatible) macro as FormulaMacros
2371 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2373 context.check_layout(os);
2374 begin_inset(os, "FormulaMacro");
2375 os << "\n\\def" << ert;
2378 output_ert_inset(os, command + ert, context);
2382 void registerExternalTemplatePackages(string const & name)
2384 external::TemplateManager const & etm = external::TemplateManager::get();
2385 external::Template const * const et = etm.getTemplateByName(name);
2388 external::Template::Formats::const_iterator cit = et->formats.end();
2390 cit = et->formats.find("PDFLaTeX");
2391 if (cit == et->formats.end())
2392 // If the template has not specified a PDFLaTeX output,
2393 // we try the LaTeX format.
2394 cit = et->formats.find("LaTeX");
2395 if (cit == et->formats.end())
2397 vector<string>::const_iterator qit = cit->second.requirements.begin();
2398 vector<string>::const_iterator qend = cit->second.requirements.end();
2399 for (; qit != qend; ++qit)
2400 preamble.registerAutomaticallyLoadedPackage(*qit);
2403 } // anonymous namespace
2407 * Find a file with basename \p name in path \p path and an extension
2410 string find_file(string const & name, string const & path,
2411 char const * const * extensions)
2413 for (char const * const * what = extensions; *what; ++what) {
2414 string const trial = addExtension(name, *what);
2415 if (makeAbsPath(trial, path).exists())
2422 /// Convert filenames with TeX macros and/or quotes to something LyX
2424 string const normalize_filename(string const & name)
2429 Token const & t = p.get_token();
2430 if (t.cat() != catEscape)
2432 else if (t.cs() == "lyxdot") {
2433 // This is used by LyX for simple dots in relative
2437 } else if (t.cs() == "space") {
2440 } else if (t.cs() == "string") {
2441 // Convert \string" to " and \string~ to ~
2442 Token const & n = p.next_token();
2443 if (n.asInput() != "\"" && n.asInput() != "~")
2448 // Strip quotes. This is a bit complicated (see latex_path()).
2449 string full = os.str();
2450 if (!full.empty() && full[0] == '"') {
2451 string base = removeExtension(full);
2452 string ext = getExtension(full);
2453 if (!base.empty() && base[base.length()-1] == '"')
2456 return addExtension(trim(base, "\""), ext);
2457 if (full[full.length()-1] == '"')
2460 return trim(full, "\"");
2466 /// Convert \p name from TeX convention (relative to master file) to LyX
2467 /// convention (relative to .lyx file) if it is relative
2468 void fix_child_filename(string & name)
2470 string const absMasterTeX = getMasterFilePath(true);
2471 bool const isabs = FileName::isAbsolute(name);
2472 // convert from "relative to .tex master" to absolute original path
2474 name = makeAbsPath(name, absMasterTeX).absFileName();
2475 bool copyfile = copyFiles();
2476 string const absParentLyX = getParentFilePath(false);
2479 // convert from absolute original path to "relative to master file"
2480 string const rel = to_utf8(makeRelPath(from_utf8(name),
2481 from_utf8(absMasterTeX)));
2482 // re-interpret "relative to .tex file" as "relative to .lyx file"
2483 // (is different if the master .lyx file resides in a
2484 // different path than the master .tex file)
2485 string const absMasterLyX = getMasterFilePath(false);
2486 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2487 // Do not copy if the new path is impossible to create. Example:
2488 // absMasterTeX = "/foo/bar/"
2489 // absMasterLyX = "/bar/"
2490 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2491 if (contains(name, "/../"))
2498 // convert from absolute original path to
2499 // "relative to .lyx file"
2500 name = to_utf8(makeRelPath(from_utf8(abs),
2501 from_utf8(absParentLyX)));
2505 // convert from absolute original path to "relative to .lyx file"
2506 name = to_utf8(makeRelPath(from_utf8(name),
2507 from_utf8(absParentLyX)));
2512 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2515 Layout const * newlayout = 0;
2516 InsetLayout const * newinsetlayout = 0;
2517 char const * const * where = 0;
2518 // Store the latest bibliographystyle, addcontentslineContent and
2519 // nocite{*} option (needed for bibtex inset)
2521 string contentslineContent;
2522 // Some classes provide a \bibliographystyle, so do not output
2523 // any if none is explicitly set.
2524 string bibliographystyle;
2525 bool const use_natbib = isProvided("natbib");
2526 bool const use_jurabib = isProvided("jurabib");
2527 bool const use_biblatex = isProvided("biblatex")
2528 && preamble.citeEngine() != "biblatex-natbib";
2529 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2530 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2531 need_commentbib = use_biblatex || use_biblatex_natbib;
2534 // it is impossible to determine the correct encoding for non-CJK Japanese.
2535 // Therefore write a note at the beginning of the document
2536 if (is_nonCJKJapanese) {
2537 context.check_layout(os);
2538 begin_inset(os, "Note Note\n");
2539 os << "status open\n\\begin_layout Plain Layout\n"
2540 << "\\series bold\n"
2541 << "Important information:\n"
2542 << "\\end_layout\n\n"
2543 << "\\begin_layout Plain Layout\n"
2544 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2545 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2546 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2547 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2548 << " and specify the encoding using the -e command-line switch.\n"
2549 << " In addition, you might want to double check that the desired output encoding\n"
2550 << " is correctly selected in Document > Settings > Language.\n"
2551 << "\\end_layout\n";
2553 is_nonCJKJapanese = false;
2556 bool have_cycled = false;
2558 // Leave here only after at least one cycle
2559 if (have_cycled && flags & FLAG_LEAVE) {
2560 flags &= ~FLAG_LEAVE;
2564 Token const & t = p.get_token();
2566 debugToken(cerr, t, flags);
2569 if (flags & FLAG_ITEM) {
2570 if (t.cat() == catSpace)
2573 flags &= ~FLAG_ITEM;
2574 if (t.cat() == catBegin) {
2575 // skip the brace and collect everything to the next matching
2577 flags |= FLAG_BRACE_LAST;
2581 // handle only this single token, leave the loop if done
2582 flags |= FLAG_LEAVE;
2585 if (t.cat() != catEscape && t.character() == ']' &&
2586 (flags & FLAG_BRACK_LAST))
2588 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2591 // If there is anything between \end{env} and \begin{env} we
2592 // don't need to output a separator.
2593 if (t.cat() != catSpace && t.cat() != catNewline &&
2594 t.asInput() != "\\begin")
2601 bool const starred = p.next_token().asInput() == "*";
2602 string const starredname(starred ? (t.cs() + '*') : t.cs());
2603 if (t.cat() == catMath) {
2604 // we are inside some text mode thingy, so opening new math is allowed
2605 context.check_layout(os);
2606 begin_inset(os, "Formula ");
2607 Token const & n = p.get_token();
2608 bool const display(n.cat() == catMath && outer);
2610 // TeX's $$...$$ syntax for displayed math
2612 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2614 p.get_token(); // skip the second '$' token
2616 // simple $...$ stuff
2619 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2624 // Prevent the conversion of a line break to a
2625 // space (bug 7668). This does not change the
2626 // output, but looks ugly in LyX.
2627 eat_whitespace(p, os, context, false);
2632 if (t.cat() == catSuper || t.cat() == catSub) {
2633 cerr << "catcode " << t << " illegal in text mode\n";
2637 // Basic support for english quotes. This should be
2638 // extended to other quotes, but is not so easy (a
2639 // left english quote is the same as a right german
2641 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2642 context.check_layout(os);
2643 begin_inset(os, "Quotes ");
2650 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2651 context.check_layout(os);
2652 begin_inset(os, "Quotes ");
2660 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2661 context.check_layout(os);
2662 begin_inset(os, "Quotes ");
2670 if (t.asInput() == "<"
2671 && p.next_token().asInput() == "<") {
2672 bool has_chunk = false;
2676 has_chunk = parse_chunk(p, os, context);
2682 context.check_layout(os);
2683 begin_inset(os, "Quotes ");
2684 //FIXME: this is a right danish quote;
2685 // why not a left french quote?
2694 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2695 check_space(p, os, context);
2699 // babel shorthands (also used by polyglossia)
2700 // Since these can have different meanings for different languages
2701 // we import them as ERT (but they must be put in ERT to get output
2703 if (t.asInput() == "\"") {
2705 // These are known pairs. We put them together in
2706 // one ERT inset. In other cases (such as "a), only
2707 // the quotation mark is ERTed.
2708 if (p.next_token().asInput() == "\""
2709 || p.next_token().asInput() == "|"
2710 || p.next_token().asInput() == "-"
2711 || p.next_token().asInput() == "~"
2712 || p.next_token().asInput() == "="
2713 || p.next_token().asInput() == "/"
2714 || p.next_token().asInput() == "~"
2715 || p.next_token().asInput() == "'"
2716 || p.next_token().asInput() == "`"
2717 || p.next_token().asInput() == "<"
2718 || p.next_token().asInput() == ">") {
2719 s += p.next_token().asInput();
2722 output_ert_inset(os, s, context);
2726 if (t.character() == '[' && noweb_mode &&
2727 p.next_token().character() == '[') {
2728 // These can contain underscores
2730 string const s = p.getFullOpt() + ']';
2731 if (p.next_token().character() == ']')
2734 cerr << "Warning: Inserting missing ']' in '"
2735 << s << "'." << endl;
2736 output_ert_inset(os, s, context);
2740 if (t.cat() == catLetter) {
2741 context.check_layout(os);
2746 if (t.cat() == catOther ||
2747 t.cat() == catAlign ||
2748 t.cat() == catParameter) {
2749 context.check_layout(os);
2750 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2751 context.merging_hyphens_allowed &&
2752 context.font.family != "ttfamily" &&
2753 !context.layout->pass_thru) {
2754 if (p.next_next_token().asInput() == "-") {
2756 os << to_utf8(docstring(1, 0x2014));
2760 os << to_utf8(docstring(1, 0x2013));
2763 // This translates "&" to "\\&" which may be wrong...
2768 if (p.isParagraph()) {
2769 // In minted floating listings we will collect
2770 // everything into the caption, where multiple
2771 // paragraphs are forbidden.
2772 if (minted_float.empty()) {
2773 if (context.new_layout_allowed)
2774 context.new_paragraph(os);
2776 output_ert_inset(os, "\\par ", context);
2779 eat_whitespace(p, os, context, true);
2783 if (t.cat() == catActive) {
2784 context.check_layout(os);
2785 if (t.character() == '~') {
2786 if (context.layout->free_spacing)
2789 begin_inset(os, "space ~\n");
2797 if (t.cat() == catBegin) {
2798 Token const next = p.next_token();
2799 Token const end = p.next_next_token();
2800 if (next.cat() == catEnd) {
2802 Token const prev = p.prev_token();
2804 if (p.next_token().character() == '`')
2805 ; // ignore it in {}``
2807 output_ert_inset(os, "{}", context);
2808 } else if (next.cat() == catEscape &&
2809 is_known(next.cs(), known_quotes) &&
2810 end.cat() == catEnd) {
2811 // Something like {\textquoteright} (e.g.
2812 // from writer2latex). LyX writes
2813 // \textquoteright{}, so we may skip the
2814 // braces here for better readability.
2815 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2817 } else if (p.next_token().asInput() == "\\ascii") {
2818 // handle the \ascii characters
2819 // (the case without braces is handled later)
2820 // the code is "{\ascii\xxx}"
2821 p.get_token(); // eat \ascii
2822 string name2 = p.get_token().asInput();
2823 p.get_token(); // eat the final '}'
2824 string const name = "{\\ascii" + name2 + "}";
2828 // get the character from unicodesymbols
2829 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2830 Encodings::TEXT_CMD, termination, rem, &req);
2832 context.check_layout(os);
2835 output_ert_inset(os,
2836 to_utf8(rem), context);
2837 for (set<string>::const_iterator it = req.begin();
2838 it != req.end(); ++it)
2839 preamble.registerAutomaticallyLoadedPackage(*it);
2841 // we did not find a non-ert version
2842 output_ert_inset(os, name, context);
2844 context.check_layout(os);
2845 // special handling of font attribute changes
2846 Token const prev = p.prev_token();
2847 TeXFont const oldFont = context.font;
2848 if (next.character() == '[' ||
2849 next.character() == ']' ||
2850 next.character() == '*') {
2852 if (p.next_token().cat() == catEnd) {
2857 output_ert_inset(os, "{", context);
2858 parse_text_snippet(p, os,
2861 output_ert_inset(os, "}", context);
2863 } else if (! context.new_layout_allowed) {
2864 output_ert_inset(os, "{", context);
2865 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2867 output_ert_inset(os, "}", context);
2868 } else if (is_known(next.cs(), known_sizes)) {
2869 // next will change the size, so we must
2871 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2873 if (!context.atParagraphStart())
2875 << context.font.size << "\n";
2876 } else if (is_known(next.cs(), known_font_families)) {
2877 // next will change the font family, so we
2878 // must reset it here
2879 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2881 if (!context.atParagraphStart())
2883 << context.font.family << "\n";
2884 } else if (is_known(next.cs(), known_font_series)) {
2885 // next will change the font series, so we
2886 // must reset it here
2887 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2889 if (!context.atParagraphStart())
2891 << context.font.series << "\n";
2892 } else if (is_known(next.cs(), known_font_shapes)) {
2893 // next will change the font shape, so we
2894 // must reset it here
2895 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2897 if (!context.atParagraphStart())
2899 << context.font.shape << "\n";
2900 } else if (is_known(next.cs(), known_old_font_families) ||
2901 is_known(next.cs(), known_old_font_series) ||
2902 is_known(next.cs(), known_old_font_shapes)) {
2903 // next will change the font family, series
2904 // and shape, so we must reset it here
2905 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2907 if (!context.atParagraphStart())
2909 << context.font.family
2911 << context.font.series
2913 << context.font.shape << "\n";
2915 output_ert_inset(os, "{", context);
2916 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2918 output_ert_inset(os, "}", context);
2924 if (t.cat() == catEnd) {
2925 if (flags & FLAG_BRACE_LAST) {
2928 cerr << "stray '}' in text\n";
2929 output_ert_inset(os, "}", context);
2933 if (t.cat() == catComment) {
2934 parse_comment(p, os, t, context);
2939 // control sequences
2942 if (t.cs() == "(" || t.cs() == "[") {
2943 bool const simple = t.cs() == "(";
2944 context.check_layout(os);
2945 begin_inset(os, "Formula");
2946 os << " \\" << t.cs();
2947 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2948 os << '\\' << (simple ? ')' : ']');
2951 // Prevent the conversion of a line break to a
2952 // space (bug 7668). This does not change the
2953 // output, but looks ugly in LyX.
2954 eat_whitespace(p, os, context, false);
2959 if (t.cs() == "begin") {
2960 parse_environment(p, os, outer, last_env,
2965 if (t.cs() == "end") {
2966 if (flags & FLAG_END) {
2967 // eat environment name
2968 string const name = p.getArg('{', '}');
2969 if (name != active_environment())
2970 cerr << "\\end{" + name + "} does not match \\begin{"
2971 + active_environment() + "}\n";
2974 p.error("found 'end' unexpectedly");
2978 if (t.cs() == "item") {
2980 bool const optarg = p.hasOpt();
2982 // FIXME: This swallows comments, but we cannot use
2983 // eat_whitespace() since we must not output
2984 // anything before the item.
2985 p.skip_spaces(true);
2986 s = p.verbatimOption();
2988 p.skip_spaces(false);
2990 context.check_layout(os);
2991 if (context.has_item) {
2992 // An item in an unknown list-like environment
2993 // FIXME: Do this in check_layout()!
2994 context.has_item = false;
2996 output_ert_inset(os, "\\item", context);
2998 output_ert_inset(os, "\\item ", context);
3001 if (context.layout->labeltype != LABEL_MANUAL) {
3002 // handle option of itemize item
3003 begin_inset(os, "Argument item:1\n");
3004 os << "status open\n";
3005 os << "\n\\begin_layout Plain Layout\n";
3007 os << parse_text_snippet(p2,
3008 FLAG_BRACK_LAST, outer, context);
3009 // we must not use context.check_end_layout(os)
3010 // because that would close the outer itemize layout
3011 os << "\n\\end_layout\n";
3013 eat_whitespace(p, os, context, false);
3014 } else if (!s.empty()) {
3015 // LyX adds braces around the argument,
3016 // so we need to remove them here.
3017 if (s.size() > 2 && s[0] == '{' &&
3018 s[s.size()-1] == '}')
3019 s = s.substr(1, s.size()-2);
3020 // If the argument contains a space we
3021 // must put it into ERT: Otherwise LyX
3022 // would misinterpret the space as
3023 // item delimiter (bug 7663)
3024 if (contains(s, ' ')) {
3025 output_ert_inset(os, s, context);
3028 os << parse_text_snippet(p2,
3029 FLAG_BRACK_LAST, outer, context);
3031 // The space is needed to separate the
3032 // item from the rest of the sentence.
3034 eat_whitespace(p, os, context, false);
3040 if (t.cs() == "bibitem") {
3042 context.check_layout(os);
3043 eat_whitespace(p, os, context, false);
3044 string label = p.verbatimOption();
3045 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3046 bool const literal = !lbl.first;
3047 label = literal ? subst(label, "\n", " ") : lbl.second;
3048 string lit = literal ? "\"true\"" : "\"false\"";
3049 string key = convert_literate_command_inset_arg(p.verbatim_item());
3050 begin_command_inset(os, "bibitem", "bibitem");
3051 os << "label \"" << label << "\"\n"
3052 << "key \"" << key << "\"\n"
3053 << "literal " << lit << "\n";
3059 // catch the case of \def\inputGnumericTable
3061 if (t.cs() == "def") {
3062 Token second = p.next_token();
3063 if (second.cs() == "inputGnumericTable") {
3067 Token third = p.get_token();
3069 if (third.cs() == "input") {
3073 string name = normalize_filename(p.verbatim_item());
3074 string const path = getMasterFilePath(true);
3075 // We want to preserve relative / absolute filenames,
3076 // therefore path is only used for testing
3077 // The file extension is in every case ".tex".
3078 // So we need to remove this extension and check for
3079 // the original one.
3080 name = removeExtension(name);
3081 if (!makeAbsPath(name, path).exists()) {
3082 char const * const Gnumeric_formats[] = {"gnumeric",
3084 string const Gnumeric_name =
3085 find_file(name, path, Gnumeric_formats);
3086 if (!Gnumeric_name.empty())
3087 name = Gnumeric_name;
3089 FileName const absname = makeAbsPath(name, path);
3090 if (absname.exists()) {
3091 fix_child_filename(name);
3092 copy_file(absname, name);
3094 cerr << "Warning: Could not find file '"
3095 << name << "'." << endl;
3096 context.check_layout(os);
3097 begin_inset(os, "External\n\ttemplate ");
3098 os << "GnumericSpreadsheet\n\tfilename "
3101 context.check_layout(os);
3103 // register the packages that are automatically loaded
3104 // by the Gnumeric template
3105 registerExternalTemplatePackages("GnumericSpreadsheet");
3110 parse_macro(p, os, context);
3114 if (t.cs() == "noindent") {
3116 context.add_par_extra_stuff("\\noindent\n");
3120 if (t.cs() == "appendix") {
3121 context.add_par_extra_stuff("\\start_of_appendix\n");
3122 // We need to start a new paragraph. Otherwise the
3123 // appendix in 'bla\appendix\chapter{' would start
3125 context.new_paragraph(os);
3126 // We need to make sure that the paragraph is
3127 // generated even if it is empty. Otherwise the
3128 // appendix in '\par\appendix\par\chapter{' would
3130 context.check_layout(os);
3131 // FIXME: This is a hack to prevent paragraph
3132 // deletion if it is empty. Handle this better!
3133 output_comment(p, os,
3134 "dummy comment inserted by tex2lyx to "
3135 "ensure that this paragraph is not empty",
3137 // Both measures above may generate an additional
3138 // empty paragraph, but that does not hurt, because
3139 // whitespace does not matter here.
3140 eat_whitespace(p, os, context, true);
3144 // Must catch empty dates before findLayout is called below
3145 if (t.cs() == "date") {
3146 eat_whitespace(p, os, context, false);
3148 string const date = p.verbatim_item();
3151 preamble.suppressDate(true);
3154 preamble.suppressDate(false);
3155 if (context.new_layout_allowed &&
3156 (newlayout = findLayout(context.textclass,
3159 output_command_layout(os, p, outer,
3160 context, newlayout);
3161 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3162 if (!preamble.titleLayoutFound())
3163 preamble.titleLayoutFound(newlayout->intitle);
3164 set<string> const & req = newlayout->requires();
3165 set<string>::const_iterator it = req.begin();
3166 set<string>::const_iterator en = req.end();
3167 for (; it != en; ++it)
3168 preamble.registerAutomaticallyLoadedPackage(*it);
3170 output_ert_inset(os,
3171 "\\date{" + p.verbatim_item() + '}',
3177 // Starred section headings
3178 // Must attempt to parse "Section*" before "Section".
3179 if ((p.next_token().asInput() == "*") &&
3180 context.new_layout_allowed &&
3181 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3184 output_command_layout(os, p, outer, context, newlayout);
3186 if (!preamble.titleLayoutFound())
3187 preamble.titleLayoutFound(newlayout->intitle);
3188 set<string> const & req = newlayout->requires();
3189 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3190 preamble.registerAutomaticallyLoadedPackage(*it);
3194 // Section headings and the like
3195 if (context.new_layout_allowed &&
3196 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3198 output_command_layout(os, p, outer, context, newlayout);
3200 if (!preamble.titleLayoutFound())
3201 preamble.titleLayoutFound(newlayout->intitle);
3202 set<string> const & req = newlayout->requires();
3203 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3204 preamble.registerAutomaticallyLoadedPackage(*it);
3208 if (t.cs() == "subfloat") {
3209 // the syntax is \subfloat[list entry][sub caption]{content}
3210 // if it is a table of figure depends on the surrounding float
3212 // do nothing if there is no outer float
3213 if (!float_type.empty()) {
3214 context.check_layout(os);
3216 begin_inset(os, "Float " + float_type + "\n");
3218 << "\nsideways false"
3219 << "\nstatus collapsed\n\n";
3222 bool has_caption = false;
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 // In case we have two optional args, the second is the caption.
3230 if (p.next_token().cat() != catEscape &&
3231 p.next_token().character() == '[') {
3232 p.get_token(); // eat '['
3233 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3236 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3237 // the caption comes always as the last
3239 // we must make sure that the caption gets a \begin_layout
3240 os << "\n\\begin_layout Plain Layout";
3242 begin_inset(os, "Caption Standard\n");
3243 Context newcontext(true, context.textclass,
3244 0, 0, context.font);
3245 newcontext.check_layout(os);
3246 os << caption << "\n";
3247 newcontext.check_end_layout(os);
3250 // close the layout we opened
3251 os << "\n\\end_layout";
3256 // if the float type is not supported or there is no surrounding float
3261 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3263 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3265 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3266 + "{" + p.verbatim_item() + '}', context);
3271 if (t.cs() == "xymatrix") {
3272 // we must open a new math because LyX's xy support is in math
3273 context.check_layout(os);
3274 begin_inset(os, "Formula ");
3276 os << "\\" << t.cs() << '{';
3277 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3280 preamble.registerAutomaticallyLoadedPackage("xy");
3284 if (t.cs() == "includegraphics") {
3285 bool const clip = p.next_token().asInput() == "*";
3288 string const arg = p.getArg('[', ']');
3289 map<string, string> opts;
3290 vector<string> keys;
3291 split_map(arg, opts, keys);
3293 opts["clip"] = string();
3294 string name = normalize_filename(p.verbatim_item());
3296 string const path = getMasterFilePath(true);
3297 // We want to preserve relative / absolute filenames,
3298 // therefore path is only used for testing
3299 if (!makeAbsPath(name, path).exists()) {
3300 // The file extension is probably missing.
3301 // Now try to find it out.
3302 string const dvips_name =
3303 find_file(name, path,
3304 known_dvips_graphics_formats);
3305 string const pdftex_name =
3306 find_file(name, path,
3307 known_pdftex_graphics_formats);
3308 if (!dvips_name.empty()) {
3309 if (!pdftex_name.empty()) {
3310 cerr << "This file contains the "
3312 "\"\\includegraphics{"
3314 "However, files\n\""
3315 << dvips_name << "\" and\n\""
3316 << pdftex_name << "\"\n"
3317 "both exist, so I had to make a "
3318 "choice and took the first one.\n"
3319 "Please move the unwanted one "
3320 "someplace else and try again\n"
3321 "if my choice was wrong."
3325 } else if (!pdftex_name.empty()) {
3331 FileName const absname = makeAbsPath(name, path);
3332 if (absname.exists()) {
3333 fix_child_filename(name);
3334 copy_file(absname, name);
3336 cerr << "Warning: Could not find graphics file '"
3337 << name << "'." << endl;
3339 context.check_layout(os);
3340 begin_inset(os, "Graphics ");
3341 os << "\n\tfilename " << name << '\n';
3342 if (opts.find("width") != opts.end())
3344 << translate_len(opts["width"]) << '\n';
3345 if (opts.find("height") != opts.end())
3347 << translate_len(opts["height"]) << '\n';
3348 if (opts.find("scale") != opts.end()) {
3349 istringstream iss(opts["scale"]);
3353 os << "\tscale " << val << '\n';
3355 if (opts.find("angle") != opts.end()) {
3356 os << "\trotateAngle "
3357 << opts["angle"] << '\n';
3358 vector<string>::const_iterator a =
3359 find(keys.begin(), keys.end(), "angle");
3360 vector<string>::const_iterator s =
3361 find(keys.begin(), keys.end(), "width");
3362 if (s == keys.end())
3363 s = find(keys.begin(), keys.end(), "height");
3364 if (s == keys.end())
3365 s = find(keys.begin(), keys.end(), "scale");
3366 if (s != keys.end() && distance(s, a) > 0)
3367 os << "\tscaleBeforeRotation\n";
3369 if (opts.find("origin") != opts.end()) {
3371 string const opt = opts["origin"];
3372 if (opt.find('l') != string::npos) ss << "left";
3373 if (opt.find('r') != string::npos) ss << "right";
3374 if (opt.find('c') != string::npos) ss << "center";
3375 if (opt.find('t') != string::npos) ss << "Top";
3376 if (opt.find('b') != string::npos) ss << "Bottom";
3377 if (opt.find('B') != string::npos) ss << "Baseline";
3378 if (!ss.str().empty())
3379 os << "\trotateOrigin " << ss.str() << '\n';
3381 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3383 if (opts.find("keepaspectratio") != opts.end())
3384 os << "\tkeepAspectRatio\n";
3385 if (opts.find("clip") != opts.end())
3387 if (opts.find("draft") != opts.end())
3389 if (opts.find("bb") != opts.end())
3390 os << "\tBoundingBox "
3391 << opts["bb"] << '\n';
3392 int numberOfbbOptions = 0;
3393 if (opts.find("bbllx") != opts.end())
3394 numberOfbbOptions++;
3395 if (opts.find("bblly") != opts.end())
3396 numberOfbbOptions++;
3397 if (opts.find("bburx") != opts.end())
3398 numberOfbbOptions++;
3399 if (opts.find("bbury") != opts.end())
3400 numberOfbbOptions++;
3401 if (numberOfbbOptions == 4)
3402 os << "\tBoundingBox "
3403 << opts["bbllx"] << " " << opts["bblly"] << " "
3404 << opts["bburx"] << " " << opts["bbury"] << '\n';
3405 else if (numberOfbbOptions > 0)
3406 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3407 numberOfbbOptions = 0;
3408 if (opts.find("natwidth") != opts.end())
3409 numberOfbbOptions++;
3410 if (opts.find("natheight") != opts.end())
3411 numberOfbbOptions++;
3412 if (numberOfbbOptions == 2)
3413 os << "\tBoundingBox 0bp 0bp "
3414 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3415 else if (numberOfbbOptions > 0)
3416 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3417 ostringstream special;
3418 if (opts.find("hiresbb") != opts.end())
3419 special << "hiresbb,";
3420 if (opts.find("trim") != opts.end())
3422 if (opts.find("viewport") != opts.end())
3423 special << "viewport=" << opts["viewport"] << ',';
3424 if (opts.find("totalheight") != opts.end())
3425 special << "totalheight=" << opts["totalheight"] << ',';
3426 if (opts.find("type") != opts.end())
3427 special << "type=" << opts["type"] << ',';
3428 if (opts.find("ext") != opts.end())
3429 special << "ext=" << opts["ext"] << ',';
3430 if (opts.find("read") != opts.end())
3431 special << "read=" << opts["read"] << ',';
3432 if (opts.find("command") != opts.end())
3433 special << "command=" << opts["command"] << ',';
3434 string s_special = special.str();
3435 if (!s_special.empty()) {
3436 // We had special arguments. Remove the trailing ','.
3437 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3439 // TODO: Handle the unknown settings better.
3440 // Warn about invalid options.
3441 // Check whether some option was given twice.
3443 preamble.registerAutomaticallyLoadedPackage("graphicx");
3447 if (t.cs() == "footnote" ||
3448 (t.cs() == "thanks" && context.layout->intitle)) {
3450 context.check_layout(os);
3451 begin_inset(os, "Foot\n");
3452 os << "status collapsed\n\n";
3453 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3458 if (t.cs() == "marginpar") {
3460 context.check_layout(os);
3461 begin_inset(os, "Marginal\n");
3462 os << "status collapsed\n\n";
3463 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3468 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3469 bool const use_minted = t.cs() == "mintinline";
3471 parse_listings(p, os, context, true, use_minted);
3475 if (t.cs() == "ensuremath") {
3477 context.check_layout(os);
3478 string const s = p.verbatim_item();
3479 //FIXME: this never triggers in UTF8
3480 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3483 output_ert_inset(os, "\\ensuremath{" + s + "}",
3488 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3489 if (preamble.titleLayoutFound()) {
3491 skip_spaces_braces(p);
3493 output_ert_inset(os, t.asInput(), context);
3497 if (t.cs() == "tableofcontents"
3498 || t.cs() == "lstlistoflistings"
3499 || t.cs() == "listoflistings") {
3500 string name = t.cs();
3501 if (preamble.minted() && name == "listoflistings")
3502 name.insert(0, "lst");
3503 context.check_layout(os);
3504 begin_command_inset(os, "toc", name);
3506 skip_spaces_braces(p);
3507 if (name == "lstlistoflistings") {
3508 if (preamble.minted())
3509 preamble.registerAutomaticallyLoadedPackage("minted");
3511 preamble.registerAutomaticallyLoadedPackage("listings");
3516 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3517 context.check_layout(os);
3518 if (t.cs() == "listoffigures")
3519 begin_inset(os, "FloatList figure\n");
3521 begin_inset(os, "FloatList table\n");
3523 skip_spaces_braces(p);
3527 if (t.cs() == "listof") {
3528 p.skip_spaces(true);
3529 string const name = p.get_token().cs();
3530 if (context.textclass.floats().typeExist(name)) {
3531 context.check_layout(os);
3532 begin_inset(os, "FloatList ");
3535 p.get_token(); // swallow second arg
3537 output_ert_inset(os, "\\listof{" + name + "}", context);
3541 if ((where = is_known(t.cs(), known_text_font_families))) {
3542 parse_text_attributes(p, os, FLAG_ITEM, outer,
3543 context, "\\family", context.font.family,
3544 known_coded_font_families[where - known_text_font_families]);
3548 if ((where = is_known(t.cs(), known_text_font_series))) {
3549 parse_text_attributes(p, os, FLAG_ITEM, outer,
3550 context, "\\series", context.font.series,
3551 known_coded_font_series[where - known_text_font_series]);
3555 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3556 parse_text_attributes(p, os, FLAG_ITEM, outer,
3557 context, "\\shape", context.font.shape,
3558 known_coded_font_shapes[where - known_text_font_shapes]);
3562 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3563 context.check_layout(os);
3564 TeXFont oldFont = context.font;
3565 context.font.init();
3566 context.font.size = oldFont.size;
3567 os << "\n\\family " << context.font.family << "\n";
3568 os << "\n\\series " << context.font.series << "\n";
3569 os << "\n\\shape " << context.font.shape << "\n";
3570 if (t.cs() == "textnormal") {
3571 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3572 output_font_change(os, context.font, oldFont);
3573 context.font = oldFont;
3575 eat_whitespace(p, os, context, false);
3579 if (t.cs() == "textcolor") {
3580 // scheme is \textcolor{color name}{text}
3581 string const color = p.verbatim_item();
3582 // we support the predefined colors of the color and the xcolor package
3583 if (color == "black" || color == "blue" || color == "cyan"
3584 || color == "green" || color == "magenta" || color == "red"
3585 || color == "white" || color == "yellow") {
3586 context.check_layout(os);
3587 os << "\n\\color " << color << "\n";
3588 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3589 context.check_layout(os);
3590 os << "\n\\color inherit\n";
3591 preamble.registerAutomaticallyLoadedPackage("color");
3592 } else if (color == "brown" || color == "darkgray" || color == "gray"
3593 || color == "lightgray" || color == "lime" || color == "olive"
3594 || color == "orange" || color == "pink" || color == "purple"
3595 || color == "teal" || color == "violet") {
3596 context.check_layout(os);
3597 os << "\n\\color " << color << "\n";
3598 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3599 context.check_layout(os);
3600 os << "\n\\color inherit\n";
3601 preamble.registerAutomaticallyLoadedPackage("xcolor");
3603 // for custom defined colors
3604 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3608 if (t.cs() == "underbar" || t.cs() == "uline") {
3609 // \underbar is not 100% correct (LyX outputs \uline
3610 // of ulem.sty). The difference is that \ulem allows
3611 // line breaks, and \underbar does not.
3612 // Do NOT handle \underline.
3613 // \underbar cuts through y, g, q, p etc.,
3614 // \underline does not.
3615 context.check_layout(os);
3616 os << "\n\\bar under\n";
3617 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3618 context.check_layout(os);
3619 os << "\n\\bar default\n";
3620 preamble.registerAutomaticallyLoadedPackage("ulem");
3624 if (t.cs() == "sout") {
3625 context.check_layout(os);
3626 os << "\n\\strikeout on\n";
3627 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3628 context.check_layout(os);
3629 os << "\n\\strikeout default\n";
3630 preamble.registerAutomaticallyLoadedPackage("ulem");
3634 if (t.cs() == "uuline" || t.cs() == "uwave"
3635 || t.cs() == "emph" || t.cs() == "noun"
3636 || t.cs() == "xout") {
3637 context.check_layout(os);
3638 os << "\n\\" << t.cs() << " on\n";
3639 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3640 context.check_layout(os);
3641 os << "\n\\" << t.cs() << " default\n";
3642 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3643 preamble.registerAutomaticallyLoadedPackage("ulem");
3647 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3648 context.check_layout(os);
3649 string name = p.getArg('{', '}');
3650 string localtime = p.getArg('{', '}');
3651 preamble.registerAuthor(name);
3652 Author const & author = preamble.getAuthor(name);
3653 // from_asctime_utc() will fail if LyX decides to output the
3654 // time in the text language.
3655 time_t ptime = from_asctime_utc(localtime);
3656 if (ptime == static_cast<time_t>(-1)) {
3657 cerr << "Warning: Could not parse time `" << localtime
3658 << "´ for change tracking, using current time instead.\n";
3659 ptime = current_time();
3661 if (t.cs() == "lyxadded")
3662 os << "\n\\change_inserted ";
3664 os << "\n\\change_deleted ";
3665 os << author.bufferId() << ' ' << ptime << '\n';
3666 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3667 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3668 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3669 LaTeXPackages::isAvailable("xcolor");
3670 // No need to test for luatex, since luatex comes in
3671 // two flavours (dvi and pdf), like latex, and those
3672 // are detected by pdflatex.
3673 if (pdflatex || xetex) {
3675 preamble.registerAutomaticallyLoadedPackage("ulem");
3676 preamble.registerAutomaticallyLoadedPackage("xcolor");
3677 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3681 preamble.registerAutomaticallyLoadedPackage("dvipost");
3682 } else if (xcolorulem) {
3683 preamble.registerAutomaticallyLoadedPackage("ulem");
3684 preamble.registerAutomaticallyLoadedPackage("xcolor");
3690 if (t.cs() == "textipa") {
3691 context.check_layout(os);
3692 begin_inset(os, "IPA\n");
3693 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3694 context.merging_hyphens_allowed = false;
3695 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3696 context.merging_hyphens_allowed = merging_hyphens_allowed;
3698 preamble.registerAutomaticallyLoadedPackage("tipa");
3699 preamble.registerAutomaticallyLoadedPackage("tipx");
3703 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3704 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3705 context.check_layout(os);
3709 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3710 begin_inset(os, "IPADeco " + type + "\n");
3711 os << "status open\n";
3712 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3718 if (t.cs() == "textvertline") {
3719 // FIXME: This is not correct, \textvertline is higher than |
3725 if (t.cs() == "tone" ) {
3726 context.check_layout(os);
3727 // register the tone package
3728 preamble.registerAutomaticallyLoadedPackage("tone");
3729 string content = trimSpaceAndEol(p.verbatim_item());
3730 string command = t.asInput() + "{" + content + "}";
3731 // some tones can be detected by unicodesymbols, some need special code
3732 if (is_known(content, known_tones)) {
3733 os << "\\IPAChar " << command << "\n";
3736 // try to see whether the string is in unicodesymbols
3740 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3741 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3742 termination, rem, &req);
3746 output_ert_inset(os, to_utf8(rem), context);
3747 for (set<string>::const_iterator it = req.begin();
3748 it != req.end(); ++it)
3749 preamble.registerAutomaticallyLoadedPackage(*it);
3751 // we did not find a non-ert version
3752 output_ert_inset(os, command, context);
3756 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3757 t.cs() == "vphantom") {
3758 context.check_layout(os);
3759 if (t.cs() == "phantom")
3760 begin_inset(os, "Phantom Phantom\n");
3761 if (t.cs() == "hphantom")
3762 begin_inset(os, "Phantom HPhantom\n");
3763 if (t.cs() == "vphantom")
3764 begin_inset(os, "Phantom VPhantom\n");
3765 os << "status open\n";
3766 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3772 if (t.cs() == "href") {
3773 context.check_layout(os);
3774 string target = convert_literate_command_inset_arg(p.verbatim_item());
3775 string name = p.verbatim_item();
3776 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3777 bool const literal = !nm.first;
3778 name = literal ? subst(name, "\n", " ") : nm.second;
3779 string lit = literal ? "\"true\"" : "\"false\"";
3781 size_t i = target.find(':');
3782 if (i != string::npos) {
3783 type = target.substr(0, i + 1);
3784 if (type == "mailto:" || type == "file:")
3785 target = target.substr(i + 1);
3786 // handle the case that name is equal to target, except of "http(s)://"
3787 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3790 begin_command_inset(os, "href", "href");
3792 os << "name \"" << name << "\"\n";
3793 os << "target \"" << target << "\"\n";
3794 if (type == "mailto:" || type == "file:")
3795 os << "type \"" << type << "\"\n";
3796 os << "literal " << lit << "\n";
3798 skip_spaces_braces(p);
3802 if (t.cs() == "lyxline") {
3803 // swallow size argument (it is not used anyway)
3805 if (!context.atParagraphStart()) {
3806 // so our line is in the middle of a paragraph
3807 // we need to add a new line, lest this line
3808 // follow the other content on that line and
3809 // run off the side of the page
3810 // FIXME: This may create an empty paragraph,
3811 // but without that it would not be
3812 // possible to set noindent below.
3813 // Fortunately LaTeX does not care
3814 // about the empty paragraph.
3815 context.new_paragraph(os);
3817 if (preamble.indentParagraphs()) {
3818 // we need to unindent, lest the line be too long
3819 context.add_par_extra_stuff("\\noindent\n");
3821 context.check_layout(os);
3822 begin_command_inset(os, "line", "rule");
3823 os << "offset \"0.5ex\"\n"
3824 "width \"100line%\"\n"
3830 if (t.cs() == "rule") {
3831 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3832 string const width = p.getArg('{', '}');
3833 string const thickness = p.getArg('{', '}');
3834 context.check_layout(os);
3835 begin_command_inset(os, "line", "rule");
3836 if (!offset.empty())
3837 os << "offset \"" << translate_len(offset) << "\"\n";
3838 os << "width \"" << translate_len(width) << "\"\n"
3839 "height \"" << translate_len(thickness) << "\"\n";
3844 // handle refstyle first to catch \eqref which can also occur
3845 // without refstyle. Only recognize these commands if
3846 // refstyle.sty was found in the preamble (otherwise \eqref
3847 // and user defined ref commands could be misdetected).
3848 if ((where = is_known(t.cs(), known_refstyle_commands))
3849 && preamble.refstyle()) {
3850 context.check_layout(os);
3851 begin_command_inset(os, "ref", "formatted");
3852 os << "reference \"";
3853 os << known_refstyle_prefixes[where - known_refstyle_commands]
3855 os << convert_literate_command_inset_arg(p.verbatim_item())
3857 os << "plural \"false\"\n";
3858 os << "caps \"false\"\n";
3859 os << "noprefix \"false\"\n";
3861 preamble.registerAutomaticallyLoadedPackage("refstyle");
3865 // if refstyle is used, we must not convert \prettyref to a
3866 // formatted reference, since that would result in a refstyle command.
3867 if ((where = is_known(t.cs(), known_ref_commands)) &&
3868 (t.cs() != "prettyref" || !preamble.refstyle())) {
3869 string const opt = p.getOpt();
3871 context.check_layout(os);
3872 begin_command_inset(os, "ref",
3873 known_coded_ref_commands[where - known_ref_commands]);
3874 os << "reference \""
3875 << convert_literate_command_inset_arg(p.verbatim_item())
3877 os << "plural \"false\"\n";
3878 os << "caps \"false\"\n";
3879 os << "noprefix \"false\"\n";
3881 if (t.cs() == "vref" || t.cs() == "vpageref")
3882 preamble.registerAutomaticallyLoadedPackage("varioref");
3883 else if (t.cs() == "prettyref")
3884 preamble.registerAutomaticallyLoadedPackage("prettyref");
3886 // LyX does not yet support optional arguments of ref commands
3887 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3888 p.verbatim_item() + '}', context);
3894 is_known(t.cs(), known_natbib_commands) &&
3895 ((t.cs() != "citefullauthor" &&
3896 t.cs() != "citeyear" &&
3897 t.cs() != "citeyearpar") ||
3898 p.next_token().asInput() != "*")) {
3899 context.check_layout(os);
3900 string command = t.cs();
3901 if (p.next_token().asInput() == "*") {
3905 if (command == "citefullauthor")
3906 // alternative name for "\\citeauthor*"
3907 command = "citeauthor*";
3909 // text before the citation
3911 // text after the citation
3913 get_cite_arguments(p, true, before, after);
3915 if (command == "cite") {
3916 // \cite without optional argument means
3917 // \citet, \cite with at least one optional
3918 // argument means \citep.
3919 if (before.empty() && after.empty())
3924 if (before.empty() && after == "[]")
3925 // avoid \citet[]{a}
3927 else if (before == "[]" && after == "[]") {
3928 // avoid \citet[][]{a}
3932 bool literal = false;
3933 pair<bool, string> aft;
3934 pair<bool, string> bef;
3935 // remove the brackets around after and before
3936 if (!after.empty()) {
3938 after.erase(after.length() - 1, 1);
3939 aft = convert_latexed_command_inset_arg(after);
3940 literal = !aft.first;
3941 after = literal ? subst(after, "\n", " ") : aft.second;
3943 if (!before.empty()) {
3945 before.erase(before.length() - 1, 1);
3946 bef = convert_latexed_command_inset_arg(before);
3947 literal |= !bef.first;
3948 before = literal ? subst(before, "\n", " ") : bef.second;
3949 if (literal && !after.empty())
3950 after = subst(after, "\n", " ");
3952 string lit = literal ? "\"true\"" : "\"false\"";
3953 begin_command_inset(os, "citation", command);
3954 os << "after " << '"' << after << '"' << "\n";
3955 os << "before " << '"' << before << '"' << "\n";
3957 << convert_literate_command_inset_arg(p.verbatim_item())
3959 << "literal " << lit << "\n";
3961 // Need to set the cite engine if natbib is loaded by
3962 // the document class directly
3963 if (preamble.citeEngine() == "basic")
3964 preamble.citeEngine("natbib");
3969 && is_known(t.cs(), known_biblatex_commands)
3970 && ((t.cs() == "cite"
3971 || t.cs() == "citeauthor"
3972 || t.cs() == "Citeauthor"
3973 || t.cs() == "parencite"
3974 || t.cs() == "citetitle")
3975 || p.next_token().asInput() != "*"))
3976 || (use_biblatex_natbib
3977 && (is_known(t.cs(), known_biblatex_commands)
3978 || is_known(t.cs(), known_natbib_commands))
3979 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3980 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3981 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3982 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3983 || t.cs() == "parencite" || t.cs() == "citetitle")
3984 || p.next_token().asInput() != "*"))){
3985 context.check_layout(os);
3986 string command = t.cs();
3987 if (p.next_token().asInput() == "*") {
3992 bool const qualified = suffixIs(command, "s");
3994 command = rtrim(command, "s");
3996 // text before the citation
3998 // text after the citation
4000 get_cite_arguments(p, true, before, after, qualified);
4002 // These use natbib cmd names in LyX
4003 // for inter-citeengine compativility
4004 if (command == "citeyear")
4005 command = "citebyear";
4006 else if (command == "cite*")
4007 command = "citeyear";
4008 else if (command == "textcite")
4010 else if (command == "Textcite")
4012 else if (command == "parencite")
4014 else if (command == "Parencite")
4016 else if (command == "parencite*")
4017 command = "citeyearpar";
4018 else if (command == "smartcite")
4019 command = "footcite";
4020 else if (command == "Smartcite")
4021 command = "Footcite";
4023 string const emptyarg = qualified ? "()" : "[]";
4024 if (before.empty() && after == emptyarg)
4027 else if (before == emptyarg && after == emptyarg) {
4028 // avoid \cite[][]{a}
4032 bool literal = false;
4033 pair<bool, string> aft;
4034 pair<bool, string> bef;
4035 // remove the brackets around after and before
4036 if (!after.empty()) {
4038 after.erase(after.length() - 1, 1);
4039 aft = convert_latexed_command_inset_arg(after);
4040 literal = !aft.first;
4041 after = literal ? subst(after, "\n", " ") : aft.second;
4043 if (!before.empty()) {
4045 before.erase(before.length() - 1, 1);
4046 bef = convert_latexed_command_inset_arg(before);
4047 literal |= !bef.first;
4048 before = literal ? subst(before, "\n", " ") : bef.second;
4050 string keys, pretextlist, posttextlist;
4052 map<string, string> pres, posts, preslit, postslit;
4053 vector<string> lkeys;
4054 // text before the citation
4055 string lbefore, lbeforelit;
4056 // text after the citation
4057 string lafter, lafterlit;
4059 pair<bool, string> laft, lbef;
4061 get_cite_arguments(p, true, lbefore, lafter);
4062 // remove the brackets around after and before
4063 if (!lafter.empty()) {
4065 lafter.erase(lafter.length() - 1, 1);
4066 laft = convert_latexed_command_inset_arg(lafter);
4067 literal |= !laft.first;
4068 lafter = laft.second;
4069 lafterlit = subst(lbefore, "\n", " ");
4071 if (!lbefore.empty()) {
4072 lbefore.erase(0, 1);
4073 lbefore.erase(lbefore.length() - 1, 1);
4074 lbef = convert_latexed_command_inset_arg(lbefore);
4075 literal |= !lbef.first;
4076 lbefore = lbef.second;
4077 lbeforelit = subst(lbefore, "\n", " ");
4079 if (lbefore.empty() && lafter == "[]") {
4084 else if (lbefore == "[]" && lafter == "[]") {
4085 // avoid \cite[][]{a}
4091 lkey = p.getArg('{', '}');
4094 if (!lbefore.empty()) {
4095 pres.insert(make_pair(lkey, lbefore));
4096 preslit.insert(make_pair(lkey, lbeforelit));
4098 if (!lafter.empty()) {
4099 posts.insert(make_pair(lkey, lafter));
4100 postslit.insert(make_pair(lkey, lafterlit));
4102 lkeys.push_back(lkey);
4104 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4109 for (auto const & ptl : pres) {
4110 if (!pretextlist.empty())
4111 pretextlist += '\t';
4112 pretextlist += ptl.first + " " + ptl.second;
4114 for (auto const & potl : posts) {
4115 if (!posttextlist.empty())
4116 posttextlist += '\t';
4117 posttextlist += potl.first + " " + potl.second;
4120 keys = convert_literate_command_inset_arg(p.verbatim_item());
4123 after = subst(after, "\n", " ");
4124 if (!before.empty())
4125 before = subst(after, "\n", " ");
4127 string lit = literal ? "\"true\"" : "\"false\"";
4128 begin_command_inset(os, "citation", command);
4129 os << "after " << '"' << after << '"' << "\n";
4130 os << "before " << '"' << before << '"' << "\n";
4134 if (!pretextlist.empty())
4135 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4136 if (!posttextlist.empty())
4137 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4138 os << "literal " << lit << "\n";
4140 // Need to set the cite engine if biblatex is loaded by
4141 // the document class directly
4142 if (preamble.citeEngine() == "basic")
4143 use_biblatex_natbib ?
4144 preamble.citeEngine("biblatex-natbib")
4145 : preamble.citeEngine("biblatex");
4150 is_known(t.cs(), known_jurabib_commands) &&
4151 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4152 context.check_layout(os);
4153 string command = t.cs();
4154 if (p.next_token().asInput() == "*") {
4158 char argumentOrder = '\0';
4159 vector<string> const options =
4160 preamble.getPackageOptions("jurabib");
4161 if (find(options.begin(), options.end(),
4162 "natbiborder") != options.end())
4163 argumentOrder = 'n';
4164 else if (find(options.begin(), options.end(),
4165 "jurabiborder") != options.end())
4166 argumentOrder = 'j';
4168 // text before the citation
4170 // text after the citation
4172 get_cite_arguments(p, argumentOrder != 'j', before, after);
4174 string const citation = p.verbatim_item();
4175 if (!before.empty() && argumentOrder == '\0') {
4176 cerr << "Warning: Assuming argument order "
4177 "of jurabib version 0.6 for\n'"
4178 << command << before << after << '{'
4179 << citation << "}'.\n"
4180 "Add 'jurabiborder' to the jurabib "
4181 "package options if you used an\n"
4182 "earlier jurabib version." << endl;
4184 bool literal = false;
4185 pair<bool, string> aft;
4186 pair<bool, string> bef;
4187 // remove the brackets around after and before
4188 if (!after.empty()) {
4190 after.erase(after.length() - 1, 1);
4191 aft = convert_latexed_command_inset_arg(after);
4192 literal = !aft.first;
4193 after = literal ? subst(after, "\n", " ") : aft.second;
4195 if (!before.empty()) {
4197 before.erase(before.length() - 1, 1);
4198 bef = convert_latexed_command_inset_arg(before);
4199 literal |= !bef.first;
4200 before = literal ? subst(before, "\n", " ") : bef.second;
4201 if (literal && !after.empty())
4202 after = subst(after, "\n", " ");
4204 string lit = literal ? "\"true\"" : "\"false\"";
4205 begin_command_inset(os, "citation", command);
4206 os << "after " << '"' << after << "\"\n"
4207 << "before " << '"' << before << "\"\n"
4208 << "key " << '"' << citation << "\"\n"
4209 << "literal " << lit << "\n";
4211 // Need to set the cite engine if jurabib is loaded by
4212 // the document class directly
4213 if (preamble.citeEngine() == "basic")
4214 preamble.citeEngine("jurabib");
4218 if (t.cs() == "cite"
4219 || t.cs() == "nocite") {
4220 context.check_layout(os);
4221 string after = p.getArg('[', ']');
4222 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4223 bool const literal = !aft.first;
4224 after = literal ? subst(after, "\n", " ") : aft.second;
4225 string lit = literal ? "\"true\"" : "\"false\"";
4226 string key = convert_literate_command_inset_arg(p.verbatim_item());
4227 // store the case that it is "\nocite{*}" to use it later for
4230 begin_command_inset(os, "citation", t.cs());
4231 os << "after " << '"' << after << "\"\n"
4232 << "key " << '"' << key << "\"\n"
4233 << "literal " << lit << "\n";
4235 } else if (t.cs() == "nocite")
4240 if (t.cs() == "index" ||
4241 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4242 context.check_layout(os);
4243 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4244 p.getArg('[', ']') : "";
4245 string const kind = arg.empty() ? "idx" : arg;
4246 begin_inset(os, "Index ");
4247 os << kind << "\nstatus collapsed\n";
4248 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4251 preamble.registerAutomaticallyLoadedPackage("splitidx");
4255 if (t.cs() == "nomenclature") {
4256 context.check_layout(os);
4257 begin_command_inset(os, "nomenclature", "nomenclature");
4258 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4259 if (!prefix.empty())
4260 os << "prefix " << '"' << prefix << '"' << "\n";
4261 string symbol = p.verbatim_item();
4262 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4263 bool literal = !sym.first;
4264 string description = p.verbatim_item();
4265 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4266 literal |= !desc.first;
4268 symbol = subst(symbol, "\n", " ");
4269 description = subst(description, "\n", " ");
4271 symbol = sym.second;
4272 description = desc.second;
4274 string lit = literal ? "\"true\"" : "\"false\"";
4275 os << "symbol " << '"' << symbol;
4276 os << "\"\ndescription \""
4277 << description << "\"\n"
4278 << "literal " << lit << "\n";
4280 preamble.registerAutomaticallyLoadedPackage("nomencl");
4284 if (t.cs() == "label") {
4285 context.check_layout(os);
4286 begin_command_inset(os, "label", "label");
4288 << convert_literate_command_inset_arg(p.verbatim_item())
4294 if (t.cs() == "lyxmintcaption") {
4295 string const pos = p.getArg('[', ']');
4297 string const caption =
4298 parse_text_snippet(p, FLAG_ITEM, false,
4300 minted_nonfloat_caption = "[t]" + caption;
4302 // We already got the caption at the bottom,
4303 // so simply skip it.
4304 parse_text_snippet(p, FLAG_ITEM, false, context);
4309 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4310 context.check_layout(os);
4311 string commandname = t.cs();
4313 if (p.next_token().asInput() == "*") {
4318 begin_command_inset(os, "index_print", commandname);
4319 string const indexname = p.getArg('[', ']');
4321 if (indexname.empty())
4322 os << "type \"idx\"\n";
4324 os << "type \"" << indexname << "\"\n";
4325 os << "literal \"true\"\n";
4328 skip_spaces_braces(p);
4329 preamble.registerAutomaticallyLoadedPackage("makeidx");
4330 if (preamble.use_indices() == "true")
4331 preamble.registerAutomaticallyLoadedPackage("splitidx");
4335 if (t.cs() == "printnomenclature") {
4337 string width_type = "";
4338 context.check_layout(os);
4339 begin_command_inset(os, "nomencl_print", "printnomenclature");
4340 // case of a custom width
4342 width = p.getArg('[', ']');
4343 width = translate_len(width);
4344 width_type = "custom";
4346 // case of no custom width
4347 // the case of no custom width but the width set
4348 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4349 // because the user could have set anything, not only the width
4350 // of the longest label (which would be width_type = "auto")
4351 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4352 if (label.empty() && width_type.empty())
4353 width_type = "none";
4354 os << "set_width \"" << width_type << "\"\n";
4355 if (width_type == "custom")
4356 os << "width \"" << width << '\"';
4358 skip_spaces_braces(p);
4359 preamble.registerAutomaticallyLoadedPackage("nomencl");
4363 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4364 context.check_layout(os);
4365 begin_inset(os, "script ");
4366 os << t.cs().substr(4) << '\n';
4367 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4368 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4370 if (t.cs() == "textsubscript")
4371 preamble.registerAutomaticallyLoadedPackage("subscript");
4375 if ((where = is_known(t.cs(), known_quotes))) {
4376 context.check_layout(os);
4377 begin_inset(os, "Quotes ");
4378 os << known_coded_quotes[where - known_quotes];
4380 // LyX adds {} after the quote, so we have to eat
4381 // spaces here if there are any before a possible
4383 eat_whitespace(p, os, context, false);
4388 if ((where = is_known(t.cs(), known_sizes)) &&
4389 context.new_layout_allowed) {
4390 context.check_layout(os);
4391 TeXFont const oldFont = context.font;
4392 context.font.size = known_coded_sizes[where - known_sizes];
4393 output_font_change(os, oldFont, context.font);
4394 eat_whitespace(p, os, context, false);
4398 if ((where = is_known(t.cs(), known_font_families)) &&
4399 context.new_layout_allowed) {
4400 context.check_layout(os);
4401 TeXFont const oldFont = context.font;
4402 context.font.family =
4403 known_coded_font_families[where - known_font_families];
4404 output_font_change(os, oldFont, context.font);
4405 eat_whitespace(p, os, context, false);
4409 if ((where = is_known(t.cs(), known_font_series)) &&
4410 context.new_layout_allowed) {
4411 context.check_layout(os);
4412 TeXFont const oldFont = context.font;
4413 context.font.series =
4414 known_coded_font_series[where - known_font_series];
4415 output_font_change(os, oldFont, context.font);
4416 eat_whitespace(p, os, context, false);
4420 if ((where = is_known(t.cs(), known_font_shapes)) &&
4421 context.new_layout_allowed) {
4422 context.check_layout(os);
4423 TeXFont const oldFont = context.font;
4424 context.font.shape =
4425 known_coded_font_shapes[where - known_font_shapes];
4426 output_font_change(os, oldFont, context.font);
4427 eat_whitespace(p, os, context, false);
4430 if ((where = is_known(t.cs(), known_old_font_families)) &&
4431 context.new_layout_allowed) {
4432 context.check_layout(os);
4433 TeXFont const oldFont = context.font;
4434 context.font.init();
4435 context.font.size = oldFont.size;
4436 context.font.family =
4437 known_coded_font_families[where - known_old_font_families];
4438 output_font_change(os, oldFont, context.font);
4439 eat_whitespace(p, os, context, false);
4443 if ((where = is_known(t.cs(), known_old_font_series)) &&
4444 context.new_layout_allowed) {
4445 context.check_layout(os);
4446 TeXFont const oldFont = context.font;
4447 context.font.init();
4448 context.font.size = oldFont.size;
4449 context.font.series =
4450 known_coded_font_series[where - known_old_font_series];
4451 output_font_change(os, oldFont, context.font);
4452 eat_whitespace(p, os, context, false);
4456 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4457 context.new_layout_allowed) {
4458 context.check_layout(os);
4459 TeXFont const oldFont = context.font;
4460 context.font.init();
4461 context.font.size = oldFont.size;
4462 context.font.shape =
4463 known_coded_font_shapes[where - known_old_font_shapes];
4464 output_font_change(os, oldFont, context.font);
4465 eat_whitespace(p, os, context, false);
4469 if (t.cs() == "selectlanguage") {
4470 context.check_layout(os);
4471 // save the language for the case that a
4472 // \foreignlanguage is used
4473 context.font.language = babel2lyx(p.verbatim_item());
4474 os << "\n\\lang " << context.font.language << "\n";
4478 if (t.cs() == "foreignlanguage") {
4479 string const lang = babel2lyx(p.verbatim_item());
4480 parse_text_attributes(p, os, FLAG_ITEM, outer,
4482 context.font.language, lang);
4486 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4487 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4488 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4490 // We have to output the whole command if it has an option
4491 // because LyX doesn't support this yet, see bug #8214,
4492 // only if there is a single option specifying a variant, we can handle it.
4494 string langopts = p.getOpt();
4495 // check if the option contains a variant, if yes, extract it
4496 string::size_type pos_var = langopts.find("variant");
4497 string::size_type i = langopts.find(',');
4498 string::size_type k = langopts.find('=', pos_var);
4499 if (pos_var != string::npos && i == string::npos) {
4501 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4502 lang = preamble.polyglossia2lyx(variant);
4503 parse_text_attributes(p, os, FLAG_ITEM, outer,
4505 context.font.language, lang);
4507 output_ert_inset(os, t.asInput() + langopts, context);
4509 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4510 parse_text_attributes(p, os, FLAG_ITEM, outer,
4512 context.font.language, lang);
4517 if (t.cs() == "inputencoding") {
4518 // nothing to write here
4519 string const enc = subst(p.verbatim_item(), "\n", " ");
4520 p.setEncoding(enc, Encoding::inputenc);
4524 if (is_known(t.cs(), known_special_chars) ||
4525 (t.cs() == "protect" &&
4526 p.next_token().cat() == catEscape &&
4527 is_known(p.next_token().cs(), known_special_protect_chars))) {
4528 // LyX sometimes puts a \protect in front, so we have to ignore it
4530 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4531 known_special_chars);
4532 context.check_layout(os);
4533 os << known_coded_special_chars[where - known_special_chars];
4534 skip_spaces_braces(p);
4538 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4539 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4540 p.next_next_token().asInput() == "-") ||
4541 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4542 // LyX sometimes puts a \protect in front, so we have to ignore it
4543 if (t.cs() == "protect")
4545 context.check_layout(os);
4546 if (t.cs() == "nobreakdash")
4547 os << "\\SpecialChar nobreakdash\n";
4549 os << "\\SpecialChar endofsentence\n";
4554 if (t.cs() == "textquotedbl") {
4555 context.check_layout(os);
4561 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4562 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4563 || t.cs() == "%" || t.cs() == "-") {
4564 context.check_layout(os);
4566 os << "\\SpecialChar softhyphen\n";
4572 if (t.cs() == "char") {
4573 context.check_layout(os);
4574 if (p.next_token().character() == '`') {
4576 if (p.next_token().cs() == "\"") {
4581 output_ert_inset(os, "\\char`", context);
4584 output_ert_inset(os, "\\char", context);
4589 if (t.cs() == "verb") {
4590 context.check_layout(os);
4591 // set catcodes to verbatim early, just in case.
4592 p.setCatcodes(VERBATIM_CATCODES);
4593 string delim = p.get_token().asInput();
4594 Parser::Arg arg = p.verbatimStuff(delim);
4596 output_ert_inset(os, "\\verb" + delim
4597 + arg.second + delim, context);
4599 cerr << "invalid \\verb command. Skipping" << endl;
4603 // Problem: \= creates a tabstop inside the tabbing environment
4604 // and else an accent. In the latter case we really would want
4605 // \={o} instead of \= o.
4606 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4607 output_ert_inset(os, t.asInput(), context);
4611 if (t.cs() == "\\") {
4612 context.check_layout(os);
4614 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4615 else if (p.next_token().asInput() == "*") {
4617 // getOpt() eats the following space if there
4618 // is no optional argument, but that is OK
4619 // here since it has no effect in the output.
4620 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4623 begin_inset(os, "Newline newline");
4629 if (t.cs() == "newline" ||
4630 (t.cs() == "linebreak" && !p.hasOpt())) {
4631 context.check_layout(os);
4632 begin_inset(os, "Newline ");
4635 skip_spaces_braces(p);
4639 if (t.cs() == "input" || t.cs() == "include"
4640 || t.cs() == "verbatiminput"
4641 || t.cs() == "lstinputlisting") {
4642 string name = t.cs();
4643 if (name == "verbatiminput"
4644 && p.next_token().asInput() == "*")
4645 name += p.get_token().asInput();
4646 context.check_layout(os);
4648 bool literal = false;
4649 if (name == "lstinputlisting" && p.hasOpt()) {
4650 lstparams = p.getArg('[', ']');
4651 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4652 literal = !oa.first;
4654 lstparams = subst(lstparams, "\n", " ");
4656 string lit = literal ? "\"true\"" : "\"false\"";
4657 string filename(normalize_filename(p.getArg('{', '}')));
4658 string const path = getMasterFilePath(true);
4659 // We want to preserve relative / absolute filenames,
4660 // therefore path is only used for testing
4661 if ((t.cs() == "include" || t.cs() == "input") &&
4662 !makeAbsPath(filename, path).exists()) {
4663 // The file extension is probably missing.
4664 // Now try to find it out.
4665 string const tex_name =
4666 find_file(filename, path,
4667 known_tex_extensions);
4668 if (!tex_name.empty())
4669 filename = tex_name;
4671 bool external = false;
4673 if (makeAbsPath(filename, path).exists()) {
4674 string const abstexname =
4675 makeAbsPath(filename, path).absFileName();
4676 string const absfigname =
4677 changeExtension(abstexname, ".fig");
4678 fix_child_filename(filename);
4679 string const lyxname = changeExtension(filename,
4680 roundtripMode() ? ".lyx.lyx" : ".lyx");
4681 string const abslyxname = makeAbsPath(
4682 lyxname, getParentFilePath(false)).absFileName();
4684 if (!skipChildren())
4685 external = FileName(absfigname).exists();
4686 if (t.cs() == "input" && !skipChildren()) {
4687 string const ext = getExtension(abstexname);
4689 // Combined PS/LaTeX:
4690 // x.eps, x.pstex_t (old xfig)
4691 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4692 FileName const absepsname(
4693 changeExtension(abstexname, ".eps"));
4694 FileName const abspstexname(
4695 changeExtension(abstexname, ".pstex"));
4696 bool const xfigeps =
4697 (absepsname.exists() ||
4698 abspstexname.exists()) &&
4701 // Combined PDF/LaTeX:
4702 // x.pdf, x.pdftex_t (old xfig)
4703 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4704 FileName const abspdfname(
4705 changeExtension(abstexname, ".pdf"));
4706 bool const xfigpdf =
4707 abspdfname.exists() &&
4708 (ext == "pdftex_t" || ext == "pdf_t");
4712 // Combined PS/PDF/LaTeX:
4713 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4714 string const absbase2(
4715 removeExtension(abstexname) + "_pspdftex");
4716 FileName const abseps2name(
4717 addExtension(absbase2, ".eps"));
4718 FileName const abspdf2name(
4719 addExtension(absbase2, ".pdf"));
4720 bool const xfigboth =
4721 abspdf2name.exists() &&
4722 abseps2name.exists() && ext == "pspdftex";
4724 xfig = xfigpdf || xfigeps || xfigboth;
4725 external = external && xfig;
4728 outname = changeExtension(filename, ".fig");
4729 FileName abssrc(changeExtension(abstexname, ".fig"));
4730 copy_file(abssrc, outname);
4732 // Don't try to convert, the result
4733 // would be full of ERT.
4735 FileName abssrc(abstexname);
4736 copy_file(abssrc, outname);
4737 } else if (t.cs() != "verbatiminput" &&
4739 tex2lyx(abstexname, FileName(abslyxname),
4742 // no need to call copy_file
4743 // tex2lyx creates the file
4746 FileName abssrc(abstexname);
4747 copy_file(abssrc, outname);
4750 cerr << "Warning: Could not find included file '"
4751 << filename << "'." << endl;
4755 begin_inset(os, "External\n");
4756 os << "\ttemplate XFig\n"
4757 << "\tfilename " << outname << '\n';
4758 registerExternalTemplatePackages("XFig");
4760 begin_command_inset(os, "include", name);
4761 outname = subst(outname, "\"", "\\\"");
4762 os << "preview false\n"
4763 "filename \"" << outname << "\"\n";
4764 if (!lstparams.empty())
4765 os << "lstparams \"" << lstparams << "\"\n";
4766 os << "literal " << lit << "\n";
4767 if (t.cs() == "verbatiminput")
4768 preamble.registerAutomaticallyLoadedPackage("verbatim");
4774 if (t.cs() == "bibliographystyle") {
4775 // store new bibliographystyle
4776 bibliographystyle = p.verbatim_item();
4777 // If any other command than \bibliography, \addcontentsline
4778 // and \nocite{*} follows, we need to output the style
4779 // (because it might be used by that command).
4780 // Otherwise, it will automatically be output by LyX.
4783 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4784 if (t2.cat() == catBegin)
4786 if (t2.cat() != catEscape)
4788 if (t2.cs() == "nocite") {
4789 if (p.getArg('{', '}') == "*")
4791 } else if (t2.cs() == "bibliography")
4793 else if (t2.cs() == "phantomsection") {
4797 else if (t2.cs() == "addcontentsline") {
4798 // get the 3 arguments of \addcontentsline
4801 contentslineContent = p.getArg('{', '}');
4802 // if the last argument is not \refname we must output
4803 if (contentslineContent == "\\refname")
4810 output_ert_inset(os,
4811 "\\bibliographystyle{" + bibliographystyle + '}',
4817 if (t.cs() == "phantomsection") {
4818 // we only support this if it occurs between
4819 // \bibliographystyle and \bibliography
4820 if (bibliographystyle.empty())
4821 output_ert_inset(os, "\\phantomsection", context);
4825 if (t.cs() == "addcontentsline") {
4826 context.check_layout(os);
4827 // get the 3 arguments of \addcontentsline
4828 string const one = p.getArg('{', '}');
4829 string const two = p.getArg('{', '}');
4830 string const three = p.getArg('{', '}');
4831 // only if it is a \refname, we support if for the bibtex inset
4832 if (contentslineContent != "\\refname") {
4833 output_ert_inset(os,
4834 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4840 else if (t.cs() == "bibliography") {
4841 context.check_layout(os);
4843 begin_command_inset(os, "bibtex", "bibtex");
4844 if (!btprint.empty()) {
4845 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4846 // clear the string because the next BibTeX inset can be without the
4847 // \nocite{*} option
4850 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4851 // Do we have addcontentsline?
4852 if (contentslineContent == "\\refname") {
4853 BibOpts = "bibtotoc";
4854 // clear string because next BibTeX inset can be without addcontentsline
4855 contentslineContent.clear();
4857 // Do we have a bibliographystyle set?
4858 if (!bibliographystyle.empty()) {
4859 if (BibOpts.empty())
4860 BibOpts = normalize_filename(bibliographystyle);
4862 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4863 // clear it because each bibtex entry has its style
4864 // and we need an empty string to handle \phantomsection
4865 bibliographystyle.clear();
4867 os << "options " << '"' << BibOpts << '"' << "\n";
4872 if (t.cs() == "printbibliography") {
4873 context.check_layout(os);
4875 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4876 vector<string> opts = getVectorFromString(bbloptions);
4877 vector<string>::iterator it =
4878 find(opts.begin(), opts.end(), "heading=bibintoc");
4879 if (it != opts.end()) {
4881 BibOpts = "bibtotoc";
4883 bbloptions = getStringFromVector(opts);
4884 begin_command_inset(os, "bibtex", "bibtex");
4885 if (!btprint.empty()) {
4886 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4887 // clear the string because the next BibTeX inset can be without the
4888 // \nocite{*} option
4892 for (auto const & bf : preamble.biblatex_bibliographies) {
4893 if (!bibfiles.empty())
4895 bibfiles += normalize_filename(bf);
4897 if (!bibfiles.empty())
4898 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4899 // Do we have addcontentsline?
4900 if (contentslineContent == "\\refname") {
4901 BibOpts = "bibtotoc";
4902 // clear string because next BibTeX inset can be without addcontentsline
4903 contentslineContent.clear();
4905 os << "options " << '"' << BibOpts << '"' << "\n";
4906 if (!bbloptions.empty())
4907 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4909 need_commentbib = false;
4913 if (t.cs() == "bibbysection") {
4914 context.check_layout(os);
4916 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4917 vector<string> opts = getVectorFromString(bbloptions);
4918 vector<string>::iterator it =
4919 find(opts.begin(), opts.end(), "heading=bibintoc");
4920 if (it != opts.end()) {
4922 BibOpts = "bibtotoc";
4924 bbloptions = getStringFromVector(opts);
4925 begin_command_inset(os, "bibtex", "bibtex");
4926 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4928 for (auto const & bf : preamble.biblatex_bibliographies) {
4929 if (!bibfiles.empty())
4931 bibfiles += normalize_filename(bf);
4933 if (!bibfiles.empty())
4934 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4935 os << "options " << '"' << BibOpts << '"' << "\n";
4936 if (!bbloptions.empty())
4937 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4939 need_commentbib = false;
4943 if (t.cs() == "parbox") {
4944 // Test whether this is an outer box of a shaded box
4946 // swallow arguments
4947 while (p.hasOpt()) {
4949 p.skip_spaces(true);
4952 p.skip_spaces(true);
4954 if (p.next_token().cat() == catBegin)
4956 p.skip_spaces(true);
4957 Token to = p.get_token();
4958 bool shaded = false;
4959 if (to.asInput() == "\\begin") {
4960 p.skip_spaces(true);
4961 if (p.getArg('{', '}') == "shaded")
4966 parse_outer_box(p, os, FLAG_ITEM, outer,
4967 context, "parbox", "shaded");
4969 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4970 "", "", t.cs(), "", "");
4974 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4975 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4976 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4977 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4981 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4982 string backgroundcolor;
4983 preamble.registerAutomaticallyLoadedPackage("xcolor");
4984 if (t.cs() == "fcolorbox") {
4985 string const framecolor = p.getArg('{', '}');
4986 backgroundcolor = p.getArg('{', '}');
4987 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4989 backgroundcolor = p.getArg('{', '}');
4990 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4995 // FIXME: due to the compiler limit of "if" nestings
4996 // the code for the alignment was put here
4997 // put them in their own if if this is fixed
4998 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4999 || t.cs() == "shadowsize"
5000 || t.cs() == "raggedleft" || t.cs() == "centering"
5001 || t.cs() == "raggedright") {
5002 if (t.cs() == "fboxrule")
5004 if (t.cs() == "fboxsep")
5006 if (t.cs() == "shadowsize")
5008 if (t.cs() != "raggedleft" && t.cs() != "centering"
5009 && t.cs() != "raggedright") {
5010 p.skip_spaces(true);
5011 while (p.good() && p.next_token().cat() != catSpace
5012 && p.next_token().cat() != catNewline
5013 && p.next_token().cat() != catEscape) {
5014 if (t.cs() == "fboxrule")
5015 fboxrule = fboxrule + p.get_token().asInput();
5016 if (t.cs() == "fboxsep")
5017 fboxsep = fboxsep + p.get_token().asInput();
5018 if (t.cs() == "shadowsize")
5019 shadow_size = shadow_size + p.get_token().asInput();
5022 output_ert_inset(os, t.asInput(), context);
5027 //\framebox() is part of the picture environment and different from \framebox{}
5028 //\framebox{} will be parsed by parse_outer_box
5029 if (t.cs() == "framebox") {
5030 if (p.next_token().character() == '(') {
5031 //the syntax is: \framebox(x,y)[position]{content}
5032 string arg = t.asInput();
5033 arg += p.getFullParentheseArg();
5034 arg += p.getFullOpt();
5035 eat_whitespace(p, os, context, false);
5036 output_ert_inset(os, arg + '{', context);
5037 parse_text(p, os, FLAG_ITEM, outer, context);
5038 output_ert_inset(os, "}", context);
5040 //the syntax is: \framebox[width][position]{content}
5041 string special = p.getFullOpt();
5042 special += p.getOpt();
5043 parse_outer_box(p, os, FLAG_ITEM, outer,
5044 context, t.cs(), special);
5049 //\makebox() is part of the picture environment and different from \makebox{}
5050 //\makebox{} will be parsed by parse_box
5051 if (t.cs() == "makebox") {
5052 if (p.next_token().character() == '(') {
5053 //the syntax is: \makebox(x,y)[position]{content}
5054 string arg = t.asInput();
5055 arg += p.getFullParentheseArg();
5056 arg += p.getFullOpt();
5057 eat_whitespace(p, os, context, false);
5058 output_ert_inset(os, arg + '{', context);
5059 parse_text(p, os, FLAG_ITEM, outer, context);
5060 output_ert_inset(os, "}", context);
5062 //the syntax is: \makebox[width][position]{content}
5063 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5064 "", "", t.cs(), "", "");
5068 if (t.cs() == "smallskip" ||
5069 t.cs() == "medskip" ||
5070 t.cs() == "bigskip" ||
5071 t.cs() == "vfill") {
5072 context.check_layout(os);
5073 begin_inset(os, "VSpace ");
5076 skip_spaces_braces(p);
5080 if ((where = is_known(t.cs(), known_spaces))) {
5081 context.check_layout(os);
5082 begin_inset(os, "space ");
5083 os << '\\' << known_coded_spaces[where - known_spaces]
5086 // LaTeX swallows whitespace after all spaces except
5087 // "\\,". We have to do that here, too, because LyX
5088 // adds "{}" which would make the spaces significant.
5090 eat_whitespace(p, os, context, false);
5091 // LyX adds "{}" after all spaces except "\\ " and
5092 // "\\,", so we have to remove "{}".
5093 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5094 // remove the braces after "\\,", too.
5100 if (t.cs() == "newpage" ||
5101 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5102 t.cs() == "clearpage" ||
5103 t.cs() == "cleardoublepage") {
5104 context.check_layout(os);
5105 begin_inset(os, "Newpage ");
5108 skip_spaces_braces(p);
5112 if (t.cs() == "DeclareRobustCommand" ||
5113 t.cs() == "DeclareRobustCommandx" ||
5114 t.cs() == "newcommand" ||
5115 t.cs() == "newcommandx" ||
5116 t.cs() == "providecommand" ||
5117 t.cs() == "providecommandx" ||
5118 t.cs() == "renewcommand" ||
5119 t.cs() == "renewcommandx") {
5120 // DeclareRobustCommand, DeclareRobustCommandx,
5121 // providecommand and providecommandx could be handled
5122 // by parse_command(), but we need to call
5123 // add_known_command() here.
5124 string name = t.asInput();
5125 if (p.next_token().asInput() == "*") {
5126 // Starred form. Eat '*'
5130 string const command = p.verbatim_item();
5131 string const opt1 = p.getFullOpt();
5132 string const opt2 = p.getFullOpt();
5133 add_known_command(command, opt1, !opt2.empty());
5134 string const ert = name + '{' + command + '}' +
5136 '{' + p.verbatim_item() + '}';
5138 if (t.cs() == "DeclareRobustCommand" ||
5139 t.cs() == "DeclareRobustCommandx" ||
5140 t.cs() == "providecommand" ||
5141 t.cs() == "providecommandx" ||
5142 name[name.length()-1] == '*')
5143 output_ert_inset(os, ert, context);
5145 context.check_layout(os);
5146 begin_inset(os, "FormulaMacro");
5153 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5154 // let could be handled by parse_command(),
5155 // but we need to call add_known_command() here.
5156 string ert = t.asInput();
5159 if (p.next_token().cat() == catBegin) {
5160 name = p.verbatim_item();
5161 ert += '{' + name + '}';
5163 name = p.verbatim_item();
5168 if (p.next_token().cat() == catBegin) {
5169 command = p.verbatim_item();
5170 ert += '{' + command + '}';
5172 command = p.verbatim_item();
5175 // If command is known, make name known too, to parse
5176 // its arguments correctly. For this reason we also
5177 // have commands in syntax.default that are hardcoded.
5178 CommandMap::iterator it = known_commands.find(command);
5179 if (it != known_commands.end())
5180 known_commands[t.asInput()] = it->second;
5181 output_ert_inset(os, ert, context);
5185 if (t.cs() == "hspace" || t.cs() == "vspace") {
5188 string name = t.asInput();
5189 string const length = p.verbatim_item();
5192 bool valid = splitLatexLength(length, valstring, unit);
5193 bool known_hspace = false;
5194 bool known_vspace = false;
5195 bool known_unit = false;
5198 istringstream iss(valstring);
5201 if (t.cs()[0] == 'h') {
5202 if (unit == "\\fill") {
5207 known_hspace = true;
5210 if (unit == "\\smallskipamount") {
5212 known_vspace = true;
5213 } else if (unit == "\\medskipamount") {
5215 known_vspace = true;
5216 } else if (unit == "\\bigskipamount") {
5218 known_vspace = true;
5219 } else if (unit == "\\fill") {
5221 known_vspace = true;
5225 if (!known_hspace && !known_vspace) {
5226 switch (unitFromString(unit)) {
5242 //unitFromString(unit) fails for relative units like Length::PCW
5243 // therefore handle them separately
5244 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5245 || unit == "\\textwidth" || unit == "\\linewidth"
5246 || unit == "\\textheight" || unit == "\\paperheight"
5247 || unit == "\\baselineskip")
5255 // check for glue lengths
5256 bool is_gluelength = false;
5257 string gluelength = length;
5258 string::size_type i = length.find(" minus");
5259 if (i == string::npos) {
5260 i = length.find(" plus");
5261 if (i != string::npos)
5262 is_gluelength = true;
5264 is_gluelength = true;
5265 // if yes transform "9xx minus 8yy plus 7zz"
5267 if (is_gluelength) {
5268 i = gluelength.find(" minus");
5269 if (i != string::npos)
5270 gluelength.replace(i, 7, "-");
5271 i = gluelength.find(" plus");
5272 if (i != string::npos)
5273 gluelength.replace(i, 6, "+");
5276 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5277 // Literal horizontal length or known variable
5278 context.check_layout(os);
5279 begin_inset(os, "space ");
5287 if (known_unit && !known_hspace)
5288 os << "\n\\length " << translate_len(length);
5290 os << "\n\\length " << gluelength;
5292 } else if (known_unit || known_vspace || is_gluelength) {
5293 // Literal vertical length or known variable
5294 context.check_layout(os);
5295 begin_inset(os, "VSpace ");
5298 if (known_unit && !known_vspace)
5299 os << translate_len(length);
5306 // LyX can't handle other length variables in Inset VSpace/space
5311 output_ert_inset(os, name + '{' + unit + '}', context);
5312 else if (value == -1.0)
5313 output_ert_inset(os, name + "{-" + unit + '}', context);
5315 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5317 output_ert_inset(os, name + '{' + length + '}', context);
5322 // The single '=' is meant here.
5323 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5327 context.check_layout(os);
5328 docstring name = newinsetlayout->name();
5329 bool const caption = name.find(from_ascii("Caption:")) == 0;
5331 // Already done for floating minted listings.
5332 if (minted_float.empty()) {
5333 begin_inset(os, "Caption ");
5334 os << to_utf8(name.substr(8)) << '\n';
5337 // FIXME: what do we do if the prefix is not Flex: ?
5338 if (prefixIs(name, from_ascii("Flex:")))
5340 begin_inset(os, "Flex ");
5341 os << to_utf8(name) << '\n'
5342 << "status collapsed\n";
5344 if (!minted_float.empty()) {
5345 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5346 } else if (newinsetlayout->isPassThru()) {
5347 // set catcodes to verbatim early, just in case.
5348 p.setCatcodes(VERBATIM_CATCODES);
5349 string delim = p.get_token().asInput();
5351 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5352 //FIXME: handle error condition
5353 string const arg = p.verbatimStuff("}").second;
5354 Context newcontext(true, context.textclass);
5355 if (newinsetlayout->forcePlainLayout())
5356 newcontext.layout = &context.textclass.plainLayout();
5357 output_ert(os, arg, newcontext);
5359 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5362 // Minted caption insets are not closed here because
5363 // we collect everything into the caption.
5364 if (minted_float.empty())
5369 if (t.cs() == "includepdf") {
5371 string const arg = p.getArg('[', ']');
5372 map<string, string> opts;
5373 vector<string> keys;
5374 split_map(arg, opts, keys);
5375 string name = normalize_filename(p.verbatim_item());
5376 string const path = getMasterFilePath(true);
5377 // We want to preserve relative / absolute filenames,
5378 // therefore path is only used for testing
5379 if (!makeAbsPath(name, path).exists()) {
5380 // The file extension is probably missing.
5381 // Now try to find it out.
5382 char const * const pdfpages_format[] = {"pdf", 0};
5383 string const pdftex_name =
5384 find_file(name, path, pdfpages_format);
5385 if (!pdftex_name.empty()) {
5390 FileName const absname = makeAbsPath(name, path);
5391 if (absname.exists())
5393 fix_child_filename(name);
5394 copy_file(absname, name);
5396 cerr << "Warning: Could not find file '"
5397 << name << "'." << endl;
5399 context.check_layout(os);
5400 begin_inset(os, "External\n\ttemplate ");
5401 os << "PDFPages\n\tfilename "
5403 // parse the options
5404 if (opts.find("pages") != opts.end())
5405 os << "\textra LaTeX \"pages="
5406 << opts["pages"] << "\"\n";
5407 if (opts.find("angle") != opts.end())
5408 os << "\trotateAngle "
5409 << opts["angle"] << '\n';
5410 if (opts.find("origin") != opts.end()) {
5412 string const opt = opts["origin"];
5413 if (opt == "tl") ss << "topleft";
5414 if (opt == "bl") ss << "bottomleft";
5415 if (opt == "Bl") ss << "baselineleft";
5416 if (opt == "c") ss << "center";
5417 if (opt == "tc") ss << "topcenter";
5418 if (opt == "bc") ss << "bottomcenter";
5419 if (opt == "Bc") ss << "baselinecenter";
5420 if (opt == "tr") ss << "topright";
5421 if (opt == "br") ss << "bottomright";
5422 if (opt == "Br") ss << "baselineright";
5423 if (!ss.str().empty())
5424 os << "\trotateOrigin " << ss.str() << '\n';
5426 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5428 if (opts.find("width") != opts.end())
5430 << translate_len(opts["width"]) << '\n';
5431 if (opts.find("height") != opts.end())
5433 << translate_len(opts["height"]) << '\n';
5434 if (opts.find("keepaspectratio") != opts.end())
5435 os << "\tkeepAspectRatio\n";
5437 context.check_layout(os);
5438 registerExternalTemplatePackages("PDFPages");
5442 if (t.cs() == "loadgame") {
5444 string name = normalize_filename(p.verbatim_item());
5445 string const path = getMasterFilePath(true);
5446 // We want to preserve relative / absolute filenames,
5447 // therefore path is only used for testing
5448 if (!makeAbsPath(name, path).exists()) {
5449 // The file extension is probably missing.
5450 // Now try to find it out.
5451 char const * const lyxskak_format[] = {"fen", 0};
5452 string const lyxskak_name =
5453 find_file(name, path, lyxskak_format);
5454 if (!lyxskak_name.empty())
5455 name = lyxskak_name;
5457 FileName const absname = makeAbsPath(name, path);
5458 if (absname.exists())
5460 fix_child_filename(name);
5461 copy_file(absname, name);
5463 cerr << "Warning: Could not find file '"
5464 << name << "'." << endl;
5465 context.check_layout(os);
5466 begin_inset(os, "External\n\ttemplate ");
5467 os << "ChessDiagram\n\tfilename "
5470 context.check_layout(os);
5471 // after a \loadgame follows a \showboard
5472 if (p.get_token().asInput() == "showboard")
5474 registerExternalTemplatePackages("ChessDiagram");
5478 // try to see whether the string is in unicodesymbols
5479 // Only use text mode commands, since we are in text mode here,
5480 // and math commands may be invalid (bug 6797)
5481 string name = t.asInput();
5482 // handle the dingbats, cyrillic and greek
5483 if (name == "\\ding" || name == "\\textcyr" ||
5484 (name == "\\textgreek" && !preamble.usePolyglossia()))
5485 name = name + '{' + p.getArg('{', '}') + '}';
5486 // handle the ifsym characters
5487 else if (name == "\\textifsymbol") {
5488 string const optif = p.getFullOpt();
5489 string const argif = p.getArg('{', '}');
5490 name = name + optif + '{' + argif + '}';
5492 // handle the \ascii characters
5493 // the case of \ascii within braces, as LyX outputs it, is already
5494 // handled for t.cat() == catBegin
5495 else if (name == "\\ascii") {
5496 // the code is "\asci\xxx"
5497 name = "{" + name + p.get_token().asInput() + "}";
5500 // handle some TIPA special characters
5501 else if (preamble.isPackageUsed("tipa")) {
5502 if (name == "\\s") {
5503 // fromLaTeXCommand() does not yet
5504 // recognize tipa short cuts
5505 name = "\\textsyllabic";
5506 } else if (name == "\\=" &&
5507 p.next_token().asInput() == "*") {
5508 // fromLaTeXCommand() does not yet
5509 // recognize tipa short cuts
5511 name = "\\textsubbar";
5512 } else if (name == "\\textdoublevertline") {
5513 // FIXME: This is not correct,
5514 // \textvertline is higher than \textbardbl
5515 name = "\\textbardbl";
5517 } else if (name == "\\!" ) {
5518 if (p.next_token().asInput() == "b") {
5519 p.get_token(); // eat 'b'
5522 } else if (p.next_token().asInput() == "d") {
5526 } else if (p.next_token().asInput() == "g") {
5530 } else if (p.next_token().asInput() == "G") {
5532 name = "\\texthtscg";
5534 } else if (p.next_token().asInput() == "j") {
5536 name = "\\texthtbardotlessj";
5538 } else if (p.next_token().asInput() == "o") {
5540 name = "\\textbullseye";
5543 } else if (name == "\\*" ) {
5544 if (p.next_token().asInput() == "k") {
5546 name = "\\textturnk";
5548 } else if (p.next_token().asInput() == "r") {
5549 p.get_token(); // eat 'b'
5550 name = "\\textturnr";
5552 } else if (p.next_token().asInput() == "t") {
5554 name = "\\textturnt";
5556 } else if (p.next_token().asInput() == "w") {
5558 name = "\\textturnw";
5563 if ((name.size() == 2 &&
5564 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5565 p.next_token().asInput() != "*") ||
5566 is_known(name.substr(1), known_tipa_marks)) {
5567 // name is a command that corresponds to a
5568 // combining character in unicodesymbols.
5569 // Append the argument, fromLaTeXCommand()
5570 // will either convert it to a single
5571 // character or a combining sequence.
5572 name += '{' + p.verbatim_item() + '}';
5574 // now get the character from unicodesymbols
5578 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5579 Encodings::TEXT_CMD, termination, rem, &req));
5581 context.check_layout(os);
5584 output_ert_inset(os, to_utf8(rem), context);
5586 skip_spaces_braces(p);
5587 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5588 preamble.registerAutomaticallyLoadedPackage(*it);
5590 //cerr << "#: " << t << " mode: " << mode << endl;
5591 // heuristic: read up to next non-nested space
5593 string s = t.asInput();
5594 string z = p.verbatim_item();
5595 while (p.good() && z != " " && !z.empty()) {
5596 //cerr << "read: " << z << endl;
5598 z = p.verbatim_item();
5600 cerr << "found ERT: " << s << endl;
5601 output_ert_inset(os, s + ' ', context);
5604 if (t.asInput() == name &&
5605 p.next_token().asInput() == "*") {
5606 // Starred commands like \vspace*{}
5607 p.get_token(); // Eat '*'
5610 if (!parse_command(name, p, os, outer, context))
5611 output_ert_inset(os, name, context);
5617 string guessLanguage(Parser & p, string const & lang)
5619 typedef std::map<std::string, size_t> LangMap;
5620 // map from language names to number of characters
5623 for (char const * const * i = supported_CJK_languages; *i; i++)
5624 used[string(*i)] = 0;
5627 Token const t = p.get_token();
5628 // comments are not counted for any language
5629 if (t.cat() == catComment)
5631 // commands are not counted as well, but we need to detect
5632 // \begin{CJK} and switch encoding if needed
5633 if (t.cat() == catEscape) {
5634 if (t.cs() == "inputencoding") {
5635 string const enc = subst(p.verbatim_item(), "\n", " ");
5636 p.setEncoding(enc, Encoding::inputenc);
5639 if (t.cs() != "begin")
5642 // Non-CJK content is counted for lang.
5643 // We do not care about the real language here:
5644 // If we have more non-CJK contents than CJK contents,
5645 // we simply use the language that was specified as
5646 // babel main language.
5647 used[lang] += t.asInput().length();
5650 // Now we are starting an environment
5652 string const name = p.getArg('{', '}');
5653 if (name != "CJK") {
5657 // It is a CJK environment
5659 /* name = */ p.getArg('{', '}');
5660 string const encoding = p.getArg('{', '}');
5661 /* mapping = */ p.getArg('{', '}');
5662 string const encoding_old = p.getEncoding();
5663 char const * const * const where =
5664 is_known(encoding, supported_CJK_encodings);
5666 p.setEncoding(encoding, Encoding::CJK);
5668 p.setEncoding("UTF-8");
5669 string const text = p.ertEnvironment("CJK");
5670 p.setEncoding(encoding_old);
5673 // ignore contents in unknown CJK encoding
5676 // the language of the text
5678 supported_CJK_languages[where - supported_CJK_encodings];
5679 used[cjk] += text.length();
5681 LangMap::const_iterator use = used.begin();
5682 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5683 if (it->second > use->second)
5690 void check_comment_bib(ostream & os, Context & context)
5692 if (!need_commentbib)
5694 // We have a bibliography database, but no bibliography with biblatex
5695 // which is completely valid. Insert a bibtex inset in a note.
5696 context.check_layout(os);
5697 begin_inset(os, "Note Note\n");
5698 os << "status open\n";
5699 os << "\\begin_layout Plain Layout\n";
5700 begin_command_inset(os, "bibtex", "bibtex");
5702 for (auto const & bf : preamble.biblatex_bibliographies) {
5703 if (!bibfiles.empty())
5705 bibfiles += normalize_filename(bf);
5707 if (!bibfiles.empty())
5708 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5709 end_inset(os);// Bibtex
5710 os << "\\end_layout\n";
5711 end_inset(os);// Note