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 os << to_utf8(newinsetlayout->name()) << '\n'
2024 << "status collapsed\n";
2025 if (newinsetlayout->isPassThru()) {
2026 string const arg = p.verbatimEnvironment(name);
2027 Context context(true, parent_context.textclass,
2028 &parent_context.textclass.plainLayout(),
2029 parent_context.layout);
2030 output_ert(os, arg, parent_context);
2032 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2036 else if (name == "appendix") {
2037 // This is no good latex style, but it works and is used in some documents...
2038 eat_whitespace(p, os, parent_context, false);
2039 parent_context.check_end_layout(os);
2040 Context context(true, parent_context.textclass, parent_context.layout,
2041 parent_context.layout, parent_context.font);
2042 context.check_layout(os);
2043 os << "\\start_of_appendix\n";
2044 parse_text(p, os, FLAG_END, outer, context);
2045 context.check_end_layout(os);
2049 else if (known_environments.find(name) != known_environments.end()) {
2050 vector<ArgumentType> arguments = known_environments[name];
2051 // The last "argument" denotes wether we may translate the
2052 // environment contents to LyX
2053 // The default required if no argument is given makes us
2054 // compatible with the reLyXre environment.
2055 ArgumentType contents = arguments.empty() ?
2058 if (!arguments.empty())
2059 arguments.pop_back();
2060 // See comment in parse_unknown_environment()
2061 bool const specialfont =
2062 (parent_context.font != parent_context.normalfont);
2063 bool const new_layout_allowed =
2064 parent_context.new_layout_allowed;
2066 parent_context.new_layout_allowed = false;
2067 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2068 outer, parent_context);
2069 if (contents == verbatim)
2070 output_ert_inset(os, p.ertEnvironment(name),
2073 parse_text_snippet(p, os, FLAG_END, outer,
2075 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2077 parent_context.new_layout_allowed = new_layout_allowed;
2081 parse_unknown_environment(p, name, os, FLAG_END, outer,
2085 active_environments.pop_back();
2089 /// parses a comment and outputs it to \p os.
2090 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2092 LASSERT(t.cat() == catComment, return);
2093 if (!t.cs().empty()) {
2094 context.check_layout(os);
2095 output_comment(p, os, t.cs(), context);
2096 if (p.next_token().cat() == catNewline) {
2097 // A newline after a comment line starts a new
2099 if (context.new_layout_allowed) {
2100 if(!context.atParagraphStart())
2101 // Only start a new paragraph if not already
2102 // done (we might get called recursively)
2103 context.new_paragraph(os);
2105 output_ert_inset(os, "\n", context);
2106 eat_whitespace(p, os, context, true);
2109 // "%\n" combination
2116 * Reads spaces and comments until the first non-space, non-comment token.
2117 * New paragraphs (double newlines or \\par) are handled like simple spaces
2118 * if \p eatParagraph is true.
2119 * Spaces are skipped, but comments are written to \p os.
2121 void eat_whitespace(Parser & p, ostream & os, Context & context,
2125 Token const & t = p.get_token();
2126 if (t.cat() == catComment)
2127 parse_comment(p, os, t, context);
2128 else if ((! eatParagraph && p.isParagraph()) ||
2129 (t.cat() != catSpace && t.cat() != catNewline)) {
2138 * Set a font attribute, parse text and reset the font attribute.
2139 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2140 * \param currentvalue Current value of the attribute. Is set to the new
2141 * value during parsing.
2142 * \param newvalue New value of the attribute
2144 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2145 Context & context, string const & attribute,
2146 string & currentvalue, string const & newvalue)
2148 context.check_layout(os);
2149 string const oldvalue = currentvalue;
2150 currentvalue = newvalue;
2151 os << '\n' << attribute << ' ' << newvalue << "\n";
2152 parse_text_snippet(p, os, flags, outer, context);
2153 context.check_layout(os);
2154 os << '\n' << attribute << ' ' << oldvalue << "\n";
2155 currentvalue = oldvalue;
2159 /// get the arguments of a natbib or jurabib citation command
2160 void get_cite_arguments(Parser & p, bool natbibOrder,
2161 string & before, string & after, bool const qualified = false)
2163 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2165 // text before the citation
2167 // text after the citation
2168 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2170 if (!after.empty()) {
2171 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2172 if (natbibOrder && !before.empty())
2173 swap(before, after);
2178 void copy_file(FileName const & src, string dstname)
2182 string const absParent = getParentFilePath(false);
2184 if (FileName::isAbsolute(dstname))
2185 dst = FileName(dstname);
2187 dst = makeAbsPath(dstname, absParent);
2188 FileName const srcpath = src.onlyPath();
2189 FileName const dstpath = dst.onlyPath();
2190 if (equivalent(srcpath, dstpath))
2192 if (!dstpath.isDirectory()) {
2193 if (!dstpath.createPath()) {
2194 cerr << "Warning: Could not create directory for file `"
2195 << dst.absFileName() << "´." << endl;
2199 if (dst.isReadableFile()) {
2200 if (overwriteFiles())
2201 cerr << "Warning: Overwriting existing file `"
2202 << dst.absFileName() << "´." << endl;
2204 cerr << "Warning: Not overwriting existing file `"
2205 << dst.absFileName() << "´." << endl;
2209 if (!src.copyTo(dst))
2210 cerr << "Warning: Could not copy file `" << src.absFileName()
2211 << "´ to `" << dst.absFileName() << "´." << endl;
2215 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2216 bool parse_chunk(Parser & p, ostream & os, Context & context)
2218 // check whether a chunk is possible here.
2219 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2225 // read the parameters
2226 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2227 if (!params.first) {
2232 Parser::Arg const code = p.verbatimStuff("\n@");
2237 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2238 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2242 // The last newline read is important for paragraph handling
2246 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2247 // We must have a valid layout before outputting the Chunk inset.
2248 context.check_layout(os);
2249 Context chunkcontext(true, context.textclass);
2250 chunkcontext.layout = &context.textclass.plainLayout();
2251 begin_inset(os, "Flex Chunk");
2252 os << "\nstatus open\n";
2253 if (!params.second.empty()) {
2254 chunkcontext.check_layout(os);
2255 Context paramscontext(true, context.textclass);
2256 paramscontext.layout = &context.textclass.plainLayout();
2257 begin_inset(os, "Argument 1");
2258 os << "\nstatus open\n";
2259 output_ert(os, params.second, paramscontext);
2262 output_ert(os, code.second, chunkcontext);
2270 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2271 bool is_macro(Parser & p)
2273 Token first = p.curr_token();
2274 if (first.cat() != catEscape || !p.good())
2276 if (first.cs() == "def")
2278 if (first.cs() != "global" && first.cs() != "long")
2280 Token second = p.get_token();
2282 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2283 second.cat() == catNewline || second.cat() == catComment)) {
2284 second = p.get_token();
2287 bool secondvalid = second.cat() == catEscape;
2289 bool thirdvalid = false;
2290 if (p.good() && first.cs() == "global" && secondvalid &&
2291 second.cs() == "long") {
2292 third = p.get_token();
2294 while (p.good() && !p.isParagraph() &&
2295 (third.cat() == catSpace ||
2296 third.cat() == catNewline ||
2297 third.cat() == catComment)) {
2298 third = p.get_token();
2301 thirdvalid = third.cat() == catEscape;
2303 for (int i = 0; i < pos; ++i)
2308 return (first.cs() == "global" || first.cs() == "long") &&
2309 second.cs() == "def";
2310 return first.cs() == "global" && second.cs() == "long" &&
2311 third.cs() == "def";
2315 /// Parse a macro definition (assumes that is_macro() returned true)
2316 void parse_macro(Parser & p, ostream & os, Context & context)
2318 context.check_layout(os);
2319 Token first = p.curr_token();
2322 string command = first.asInput();
2323 if (first.cs() != "def") {
2325 eat_whitespace(p, os, context, false);
2326 second = p.curr_token();
2327 command += second.asInput();
2328 if (second.cs() != "def") {
2330 eat_whitespace(p, os, context, false);
2331 third = p.curr_token();
2332 command += third.asInput();
2335 eat_whitespace(p, os, context, false);
2336 string const name = p.get_token().cs();
2337 eat_whitespace(p, os, context, false);
2343 while (p.next_token().cat() != catBegin) {
2344 if (p.next_token().cat() == catParameter) {
2349 // followed by number?
2350 if (p.next_token().cat() == catOther) {
2351 string s = p.get_token().asInput();
2353 // number = current arity + 1?
2354 if (s.size() == 1 && s[0] == arity + '0' + 1)
2359 paramtext += p.get_token().cs();
2361 paramtext += p.get_token().cs();
2366 // only output simple (i.e. compatible) macro as FormulaMacros
2367 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2369 context.check_layout(os);
2370 begin_inset(os, "FormulaMacro");
2371 os << "\n\\def" << ert;
2374 output_ert_inset(os, command + ert, context);
2378 void registerExternalTemplatePackages(string const & name)
2380 external::TemplateManager const & etm = external::TemplateManager::get();
2381 external::Template const * const et = etm.getTemplateByName(name);
2384 external::Template::Formats::const_iterator cit = et->formats.end();
2386 cit = et->formats.find("PDFLaTeX");
2387 if (cit == et->formats.end())
2388 // If the template has not specified a PDFLaTeX output,
2389 // we try the LaTeX format.
2390 cit = et->formats.find("LaTeX");
2391 if (cit == et->formats.end())
2393 vector<string>::const_iterator qit = cit->second.requirements.begin();
2394 vector<string>::const_iterator qend = cit->second.requirements.end();
2395 for (; qit != qend; ++qit)
2396 preamble.registerAutomaticallyLoadedPackage(*qit);
2399 } // anonymous namespace
2403 * Find a file with basename \p name in path \p path and an extension
2406 string find_file(string const & name, string const & path,
2407 char const * const * extensions)
2409 for (char const * const * what = extensions; *what; ++what) {
2410 string const trial = addExtension(name, *what);
2411 if (makeAbsPath(trial, path).exists())
2418 /// Convert filenames with TeX macros and/or quotes to something LyX
2420 string const normalize_filename(string const & name)
2425 Token const & t = p.get_token();
2426 if (t.cat() != catEscape)
2428 else if (t.cs() == "lyxdot") {
2429 // This is used by LyX for simple dots in relative
2433 } else if (t.cs() == "space") {
2436 } else if (t.cs() == "string") {
2437 // Convert \string" to " and \string~ to ~
2438 Token const & n = p.next_token();
2439 if (n.asInput() != "\"" && n.asInput() != "~")
2444 // Strip quotes. This is a bit complicated (see latex_path()).
2445 string full = os.str();
2446 if (!full.empty() && full[0] == '"') {
2447 string base = removeExtension(full);
2448 string ext = getExtension(full);
2449 if (!base.empty() && base[base.length()-1] == '"')
2452 return addExtension(trim(base, "\""), ext);
2453 if (full[full.length()-1] == '"')
2456 return trim(full, "\"");
2462 /// Convert \p name from TeX convention (relative to master file) to LyX
2463 /// convention (relative to .lyx file) if it is relative
2464 void fix_child_filename(string & name)
2466 string const absMasterTeX = getMasterFilePath(true);
2467 bool const isabs = FileName::isAbsolute(name);
2468 // convert from "relative to .tex master" to absolute original path
2470 name = makeAbsPath(name, absMasterTeX).absFileName();
2471 bool copyfile = copyFiles();
2472 string const absParentLyX = getParentFilePath(false);
2475 // convert from absolute original path to "relative to master file"
2476 string const rel = to_utf8(makeRelPath(from_utf8(name),
2477 from_utf8(absMasterTeX)));
2478 // re-interpret "relative to .tex file" as "relative to .lyx file"
2479 // (is different if the master .lyx file resides in a
2480 // different path than the master .tex file)
2481 string const absMasterLyX = getMasterFilePath(false);
2482 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2483 // Do not copy if the new path is impossible to create. Example:
2484 // absMasterTeX = "/foo/bar/"
2485 // absMasterLyX = "/bar/"
2486 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2487 if (contains(name, "/../"))
2494 // convert from absolute original path to
2495 // "relative to .lyx file"
2496 name = to_utf8(makeRelPath(from_utf8(abs),
2497 from_utf8(absParentLyX)));
2501 // convert from absolute original path to "relative to .lyx file"
2502 name = to_utf8(makeRelPath(from_utf8(name),
2503 from_utf8(absParentLyX)));
2508 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2511 Layout const * newlayout = 0;
2512 InsetLayout const * newinsetlayout = 0;
2513 char const * const * where = 0;
2514 // Store the latest bibliographystyle, addcontentslineContent and
2515 // nocite{*} option (needed for bibtex inset)
2517 string contentslineContent;
2518 string bibliographystyle = "default";
2519 bool const use_natbib = isProvided("natbib");
2520 bool const use_jurabib = isProvided("jurabib");
2521 bool const use_biblatex = isProvided("biblatex")
2522 && preamble.citeEngine() != "biblatex-natbib";
2523 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2524 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2525 need_commentbib = use_biblatex || use_biblatex_natbib;
2528 // it is impossible to determine the correct encoding for non-CJK Japanese.
2529 // Therefore write a note at the beginning of the document
2530 if (is_nonCJKJapanese) {
2531 context.check_layout(os);
2532 begin_inset(os, "Note Note\n");
2533 os << "status open\n\\begin_layout Plain Layout\n"
2534 << "\\series bold\n"
2535 << "Important information:\n"
2536 << "\\end_layout\n\n"
2537 << "\\begin_layout Plain Layout\n"
2538 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2539 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2540 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2541 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2542 << " and specify the encoding using the -e command-line switch.\n"
2543 << " In addition, you might want to double check that the desired output encoding\n"
2544 << " is correctly selected in Document > Settings > Language.\n"
2545 << "\\end_layout\n";
2547 is_nonCJKJapanese = false;
2550 bool have_cycled = false;
2552 // Leave here only after at least one cycle
2553 if (have_cycled && flags & FLAG_LEAVE) {
2554 flags &= ~FLAG_LEAVE;
2558 Token const & t = p.get_token();
2560 debugToken(cerr, t, flags);
2563 if (flags & FLAG_ITEM) {
2564 if (t.cat() == catSpace)
2567 flags &= ~FLAG_ITEM;
2568 if (t.cat() == catBegin) {
2569 // skip the brace and collect everything to the next matching
2571 flags |= FLAG_BRACE_LAST;
2575 // handle only this single token, leave the loop if done
2576 flags |= FLAG_LEAVE;
2579 if (t.cat() != catEscape && t.character() == ']' &&
2580 (flags & FLAG_BRACK_LAST))
2582 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2585 // If there is anything between \end{env} and \begin{env} we
2586 // don't need to output a separator.
2587 if (t.cat() != catSpace && t.cat() != catNewline &&
2588 t.asInput() != "\\begin")
2595 bool const starred = p.next_token().asInput() == "*";
2596 string const starredname(starred ? (t.cs() + '*') : t.cs());
2597 if (t.cat() == catMath) {
2598 // we are inside some text mode thingy, so opening new math is allowed
2599 context.check_layout(os);
2600 begin_inset(os, "Formula ");
2601 Token const & n = p.get_token();
2602 bool const display(n.cat() == catMath && outer);
2604 // TeX's $$...$$ syntax for displayed math
2606 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2608 p.get_token(); // skip the second '$' token
2610 // simple $...$ stuff
2613 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2618 // Prevent the conversion of a line break to a
2619 // space (bug 7668). This does not change the
2620 // output, but looks ugly in LyX.
2621 eat_whitespace(p, os, context, false);
2626 if (t.cat() == catSuper || t.cat() == catSub) {
2627 cerr << "catcode " << t << " illegal in text mode\n";
2631 // Basic support for english quotes. This should be
2632 // extended to other quotes, but is not so easy (a
2633 // left english quote is the same as a right german
2635 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2636 context.check_layout(os);
2637 begin_inset(os, "Quotes ");
2644 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2645 context.check_layout(os);
2646 begin_inset(os, "Quotes ");
2654 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2655 context.check_layout(os);
2656 begin_inset(os, "Quotes ");
2664 if (t.asInput() == "<"
2665 && p.next_token().asInput() == "<") {
2666 bool has_chunk = false;
2670 has_chunk = parse_chunk(p, os, context);
2676 context.check_layout(os);
2677 begin_inset(os, "Quotes ");
2678 //FIXME: this is a right danish quote;
2679 // why not a left french quote?
2688 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2689 check_space(p, os, context);
2693 // babel shorthands (also used by polyglossia)
2694 // Since these can have different meanings for different languages
2695 // we import them as ERT (but they must be put in ERT to get output
2697 if (t.asInput() == "\"") {
2699 // These are known pairs. We put them together in
2700 // one ERT inset. In other cases (such as "a), only
2701 // the quotation mark is ERTed.
2702 if (p.next_token().asInput() == "\""
2703 || p.next_token().asInput() == "|"
2704 || p.next_token().asInput() == "-"
2705 || p.next_token().asInput() == "~"
2706 || p.next_token().asInput() == "="
2707 || p.next_token().asInput() == "/"
2708 || p.next_token().asInput() == "~"
2709 || p.next_token().asInput() == "'"
2710 || p.next_token().asInput() == "`"
2711 || p.next_token().asInput() == "<"
2712 || p.next_token().asInput() == ">") {
2713 s += p.next_token().asInput();
2716 output_ert_inset(os, s, context);
2720 if (t.character() == '[' && noweb_mode &&
2721 p.next_token().character() == '[') {
2722 // These can contain underscores
2724 string const s = p.getFullOpt() + ']';
2725 if (p.next_token().character() == ']')
2728 cerr << "Warning: Inserting missing ']' in '"
2729 << s << "'." << endl;
2730 output_ert_inset(os, s, context);
2734 if (t.cat() == catLetter) {
2735 context.check_layout(os);
2740 if (t.cat() == catOther ||
2741 t.cat() == catAlign ||
2742 t.cat() == catParameter) {
2743 context.check_layout(os);
2744 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2745 context.merging_hyphens_allowed &&
2746 context.font.family != "ttfamily" &&
2747 !context.layout->pass_thru) {
2748 if (p.next_next_token().asInput() == "-") {
2750 os << to_utf8(docstring(1, 0x2014));
2754 os << to_utf8(docstring(1, 0x2013));
2757 // This translates "&" to "\\&" which may be wrong...
2762 if (p.isParagraph()) {
2763 // In minted floating listings we will collect
2764 // everything into the caption, where multiple
2765 // paragraphs are forbidden.
2766 if (minted_float.empty()) {
2767 if (context.new_layout_allowed)
2768 context.new_paragraph(os);
2770 output_ert_inset(os, "\\par ", context);
2773 eat_whitespace(p, os, context, true);
2777 if (t.cat() == catActive) {
2778 context.check_layout(os);
2779 if (t.character() == '~') {
2780 if (context.layout->free_spacing)
2783 begin_inset(os, "space ~\n");
2791 if (t.cat() == catBegin) {
2792 Token const next = p.next_token();
2793 Token const end = p.next_next_token();
2794 if (next.cat() == catEnd) {
2796 Token const prev = p.prev_token();
2798 if (p.next_token().character() == '`')
2799 ; // ignore it in {}``
2801 output_ert_inset(os, "{}", context);
2802 } else if (next.cat() == catEscape &&
2803 is_known(next.cs(), known_quotes) &&
2804 end.cat() == catEnd) {
2805 // Something like {\textquoteright} (e.g.
2806 // from writer2latex). LyX writes
2807 // \textquoteright{}, so we may skip the
2808 // braces here for better readability.
2809 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2811 } else if (p.next_token().asInput() == "\\ascii") {
2812 // handle the \ascii characters
2813 // (the case without braces is handled later)
2814 // the code is "{\ascii\xxx}"
2815 p.get_token(); // eat \ascii
2816 string name2 = p.get_token().asInput();
2817 p.get_token(); // eat the final '}'
2818 string const name = "{\\ascii" + name2 + "}";
2822 // get the character from unicodesymbols
2823 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2824 Encodings::TEXT_CMD, termination, rem, &req);
2826 context.check_layout(os);
2829 output_ert_inset(os,
2830 to_utf8(rem), context);
2831 for (set<string>::const_iterator it = req.begin();
2832 it != req.end(); ++it)
2833 preamble.registerAutomaticallyLoadedPackage(*it);
2835 // we did not find a non-ert version
2836 output_ert_inset(os, name, context);
2838 context.check_layout(os);
2839 // special handling of font attribute changes
2840 Token const prev = p.prev_token();
2841 TeXFont const oldFont = context.font;
2842 if (next.character() == '[' ||
2843 next.character() == ']' ||
2844 next.character() == '*') {
2846 if (p.next_token().cat() == catEnd) {
2851 output_ert_inset(os, "{", context);
2852 parse_text_snippet(p, os,
2855 output_ert_inset(os, "}", context);
2857 } else if (! context.new_layout_allowed) {
2858 output_ert_inset(os, "{", context);
2859 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2861 output_ert_inset(os, "}", context);
2862 } else if (is_known(next.cs(), known_sizes)) {
2863 // next will change the size, so we must
2865 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2867 if (!context.atParagraphStart())
2869 << context.font.size << "\n";
2870 } else if (is_known(next.cs(), known_font_families)) {
2871 // next will change the font family, so we
2872 // must reset it here
2873 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2875 if (!context.atParagraphStart())
2877 << context.font.family << "\n";
2878 } else if (is_known(next.cs(), known_font_series)) {
2879 // next will change the font series, so we
2880 // must reset it here
2881 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2883 if (!context.atParagraphStart())
2885 << context.font.series << "\n";
2886 } else if (is_known(next.cs(), known_font_shapes)) {
2887 // next will change the font shape, so we
2888 // must reset it here
2889 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2891 if (!context.atParagraphStart())
2893 << context.font.shape << "\n";
2894 } else if (is_known(next.cs(), known_old_font_families) ||
2895 is_known(next.cs(), known_old_font_series) ||
2896 is_known(next.cs(), known_old_font_shapes)) {
2897 // next will change the font family, series
2898 // and shape, so we must reset it here
2899 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2901 if (!context.atParagraphStart())
2903 << context.font.family
2905 << context.font.series
2907 << context.font.shape << "\n";
2909 output_ert_inset(os, "{", context);
2910 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2912 output_ert_inset(os, "}", context);
2918 if (t.cat() == catEnd) {
2919 if (flags & FLAG_BRACE_LAST) {
2922 cerr << "stray '}' in text\n";
2923 output_ert_inset(os, "}", context);
2927 if (t.cat() == catComment) {
2928 parse_comment(p, os, t, context);
2933 // control sequences
2936 if (t.cs() == "(" || t.cs() == "[") {
2937 bool const simple = t.cs() == "(";
2938 context.check_layout(os);
2939 begin_inset(os, "Formula");
2940 os << " \\" << t.cs();
2941 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2942 os << '\\' << (simple ? ')' : ']');
2945 // Prevent the conversion of a line break to a
2946 // space (bug 7668). This does not change the
2947 // output, but looks ugly in LyX.
2948 eat_whitespace(p, os, context, false);
2953 if (t.cs() == "begin") {
2954 parse_environment(p, os, outer, last_env,
2959 if (t.cs() == "end") {
2960 if (flags & FLAG_END) {
2961 // eat environment name
2962 string const name = p.getArg('{', '}');
2963 if (name != active_environment())
2964 cerr << "\\end{" + name + "} does not match \\begin{"
2965 + active_environment() + "}\n";
2968 p.error("found 'end' unexpectedly");
2972 if (t.cs() == "item") {
2974 bool const optarg = p.hasOpt();
2976 // FIXME: This swallows comments, but we cannot use
2977 // eat_whitespace() since we must not output
2978 // anything before the item.
2979 p.skip_spaces(true);
2980 s = p.verbatimOption();
2982 p.skip_spaces(false);
2984 context.check_layout(os);
2985 if (context.has_item) {
2986 // An item in an unknown list-like environment
2987 // FIXME: Do this in check_layout()!
2988 context.has_item = false;
2990 output_ert_inset(os, "\\item", context);
2992 output_ert_inset(os, "\\item ", context);
2995 if (context.layout->labeltype != LABEL_MANUAL) {
2996 // handle option of itemize item
2997 begin_inset(os, "Argument item:1\n");
2998 os << "status open\n";
2999 os << "\n\\begin_layout Plain Layout\n";
3001 os << parse_text_snippet(p2,
3002 FLAG_BRACK_LAST, outer, context);
3003 // we must not use context.check_end_layout(os)
3004 // because that would close the outer itemize layout
3005 os << "\n\\end_layout\n";
3007 eat_whitespace(p, os, context, false);
3008 } else if (!s.empty()) {
3009 // LyX adds braces around the argument,
3010 // so we need to remove them here.
3011 if (s.size() > 2 && s[0] == '{' &&
3012 s[s.size()-1] == '}')
3013 s = s.substr(1, s.size()-2);
3014 // If the argument contains a space we
3015 // must put it into ERT: Otherwise LyX
3016 // would misinterpret the space as
3017 // item delimiter (bug 7663)
3018 if (contains(s, ' ')) {
3019 output_ert_inset(os, s, context);
3022 os << parse_text_snippet(p2,
3023 FLAG_BRACK_LAST, outer, context);
3025 // The space is needed to separate the
3026 // item from the rest of the sentence.
3028 eat_whitespace(p, os, context, false);
3034 if (t.cs() == "bibitem") {
3036 context.check_layout(os);
3037 eat_whitespace(p, os, context, false);
3038 string label = p.verbatimOption();
3039 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3040 bool const literal = !lbl.first;
3041 label = literal ? subst(label, "\n", " ") : lbl.second;
3042 string lit = literal ? "\"true\"" : "\"false\"";
3043 string key = convert_literate_command_inset_arg(p.verbatim_item());
3044 begin_command_inset(os, "bibitem", "bibitem");
3045 os << "label \"" << label << "\"\n"
3046 << "key \"" << key << "\"\n"
3047 << "literal " << lit << "\n";
3053 // catch the case of \def\inputGnumericTable
3055 if (t.cs() == "def") {
3056 Token second = p.next_token();
3057 if (second.cs() == "inputGnumericTable") {
3061 Token third = p.get_token();
3063 if (third.cs() == "input") {
3067 string name = normalize_filename(p.verbatim_item());
3068 string const path = getMasterFilePath(true);
3069 // We want to preserve relative / absolute filenames,
3070 // therefore path is only used for testing
3071 // The file extension is in every case ".tex".
3072 // So we need to remove this extension and check for
3073 // the original one.
3074 name = removeExtension(name);
3075 if (!makeAbsPath(name, path).exists()) {
3076 char const * const Gnumeric_formats[] = {"gnumeric",
3078 string const Gnumeric_name =
3079 find_file(name, path, Gnumeric_formats);
3080 if (!Gnumeric_name.empty())
3081 name = Gnumeric_name;
3083 FileName const absname = makeAbsPath(name, path);
3084 if (absname.exists()) {
3085 fix_child_filename(name);
3086 copy_file(absname, name);
3088 cerr << "Warning: Could not find file '"
3089 << name << "'." << endl;
3090 context.check_layout(os);
3091 begin_inset(os, "External\n\ttemplate ");
3092 os << "GnumericSpreadsheet\n\tfilename "
3095 context.check_layout(os);
3097 // register the packages that are automatically loaded
3098 // by the Gnumeric template
3099 registerExternalTemplatePackages("GnumericSpreadsheet");
3104 parse_macro(p, os, context);
3108 if (t.cs() == "noindent") {
3110 context.add_par_extra_stuff("\\noindent\n");
3114 if (t.cs() == "appendix") {
3115 context.add_par_extra_stuff("\\start_of_appendix\n");
3116 // We need to start a new paragraph. Otherwise the
3117 // appendix in 'bla\appendix\chapter{' would start
3119 context.new_paragraph(os);
3120 // We need to make sure that the paragraph is
3121 // generated even if it is empty. Otherwise the
3122 // appendix in '\par\appendix\par\chapter{' would
3124 context.check_layout(os);
3125 // FIXME: This is a hack to prevent paragraph
3126 // deletion if it is empty. Handle this better!
3127 output_comment(p, os,
3128 "dummy comment inserted by tex2lyx to "
3129 "ensure that this paragraph is not empty",
3131 // Both measures above may generate an additional
3132 // empty paragraph, but that does not hurt, because
3133 // whitespace does not matter here.
3134 eat_whitespace(p, os, context, true);
3138 // Must catch empty dates before findLayout is called below
3139 if (t.cs() == "date") {
3140 eat_whitespace(p, os, context, false);
3142 string const date = p.verbatim_item();
3145 preamble.suppressDate(true);
3148 preamble.suppressDate(false);
3149 if (context.new_layout_allowed &&
3150 (newlayout = findLayout(context.textclass,
3153 output_command_layout(os, p, outer,
3154 context, newlayout);
3155 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3156 if (!preamble.titleLayoutFound())
3157 preamble.titleLayoutFound(newlayout->intitle);
3158 set<string> const & req = newlayout->requires();
3159 set<string>::const_iterator it = req.begin();
3160 set<string>::const_iterator en = req.end();
3161 for (; it != en; ++it)
3162 preamble.registerAutomaticallyLoadedPackage(*it);
3164 output_ert_inset(os,
3165 "\\date{" + p.verbatim_item() + '}',
3171 // Starred section headings
3172 // Must attempt to parse "Section*" before "Section".
3173 if ((p.next_token().asInput() == "*") &&
3174 context.new_layout_allowed &&
3175 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3178 output_command_layout(os, p, outer, context, newlayout);
3180 if (!preamble.titleLayoutFound())
3181 preamble.titleLayoutFound(newlayout->intitle);
3182 set<string> const & req = newlayout->requires();
3183 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3184 preamble.registerAutomaticallyLoadedPackage(*it);
3188 // Section headings and the like
3189 if (context.new_layout_allowed &&
3190 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3192 output_command_layout(os, p, outer, context, newlayout);
3194 if (!preamble.titleLayoutFound())
3195 preamble.titleLayoutFound(newlayout->intitle);
3196 set<string> const & req = newlayout->requires();
3197 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3198 preamble.registerAutomaticallyLoadedPackage(*it);
3202 if (t.cs() == "subfloat") {
3203 // the syntax is \subfloat[list entry][sub caption]{content}
3204 // if it is a table of figure depends on the surrounding float
3206 // do nothing if there is no outer float
3207 if (!float_type.empty()) {
3208 context.check_layout(os);
3210 begin_inset(os, "Float " + float_type + "\n");
3212 << "\nsideways false"
3213 << "\nstatus collapsed\n\n";
3216 bool has_caption = false;
3217 if (p.next_token().cat() != catEscape &&
3218 p.next_token().character() == '[') {
3219 p.get_token(); // eat '['
3220 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3223 // In case we have two optional args, the second is the caption.
3224 if (p.next_token().cat() != catEscape &&
3225 p.next_token().character() == '[') {
3226 p.get_token(); // eat '['
3227 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3230 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3231 // the caption comes always as the last
3233 // we must make sure that the caption gets a \begin_layout
3234 os << "\n\\begin_layout Plain Layout";
3236 begin_inset(os, "Caption Standard\n");
3237 Context newcontext(true, context.textclass,
3238 0, 0, context.font);
3239 newcontext.check_layout(os);
3240 os << caption << "\n";
3241 newcontext.check_end_layout(os);
3244 // close the layout we opened
3245 os << "\n\\end_layout";
3250 // if the float type is not supported or there is no surrounding float
3255 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3257 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3259 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3260 + "{" + p.verbatim_item() + '}', context);
3265 if (t.cs() == "includegraphics") {
3266 bool const clip = p.next_token().asInput() == "*";
3269 string const arg = p.getArg('[', ']');
3270 map<string, string> opts;
3271 vector<string> keys;
3272 split_map(arg, opts, keys);
3274 opts["clip"] = string();
3275 string name = normalize_filename(p.verbatim_item());
3277 string const path = getMasterFilePath(true);
3278 // We want to preserve relative / absolute filenames,
3279 // therefore path is only used for testing
3280 if (!makeAbsPath(name, path).exists()) {
3281 // The file extension is probably missing.
3282 // Now try to find it out.
3283 string const dvips_name =
3284 find_file(name, path,
3285 known_dvips_graphics_formats);
3286 string const pdftex_name =
3287 find_file(name, path,
3288 known_pdftex_graphics_formats);
3289 if (!dvips_name.empty()) {
3290 if (!pdftex_name.empty()) {
3291 cerr << "This file contains the "
3293 "\"\\includegraphics{"
3295 "However, files\n\""
3296 << dvips_name << "\" and\n\""
3297 << pdftex_name << "\"\n"
3298 "both exist, so I had to make a "
3299 "choice and took the first one.\n"
3300 "Please move the unwanted one "
3301 "someplace else and try again\n"
3302 "if my choice was wrong."
3306 } else if (!pdftex_name.empty()) {
3312 FileName const absname = makeAbsPath(name, path);
3313 if (absname.exists()) {
3314 fix_child_filename(name);
3315 copy_file(absname, name);
3317 cerr << "Warning: Could not find graphics file '"
3318 << name << "'." << endl;
3320 context.check_layout(os);
3321 begin_inset(os, "Graphics ");
3322 os << "\n\tfilename " << name << '\n';
3323 if (opts.find("width") != opts.end())
3325 << translate_len(opts["width"]) << '\n';
3326 if (opts.find("height") != opts.end())
3328 << translate_len(opts["height"]) << '\n';
3329 if (opts.find("scale") != opts.end()) {
3330 istringstream iss(opts["scale"]);
3334 os << "\tscale " << val << '\n';
3336 if (opts.find("angle") != opts.end()) {
3337 os << "\trotateAngle "
3338 << opts["angle"] << '\n';
3339 vector<string>::const_iterator a =
3340 find(keys.begin(), keys.end(), "angle");
3341 vector<string>::const_iterator s =
3342 find(keys.begin(), keys.end(), "width");
3343 if (s == keys.end())
3344 s = find(keys.begin(), keys.end(), "height");
3345 if (s == keys.end())
3346 s = find(keys.begin(), keys.end(), "scale");
3347 if (s != keys.end() && distance(s, a) > 0)
3348 os << "\tscaleBeforeRotation\n";
3350 if (opts.find("origin") != opts.end()) {
3352 string const opt = opts["origin"];
3353 if (opt.find('l') != string::npos) ss << "left";
3354 if (opt.find('r') != string::npos) ss << "right";
3355 if (opt.find('c') != string::npos) ss << "center";
3356 if (opt.find('t') != string::npos) ss << "Top";
3357 if (opt.find('b') != string::npos) ss << "Bottom";
3358 if (opt.find('B') != string::npos) ss << "Baseline";
3359 if (!ss.str().empty())
3360 os << "\trotateOrigin " << ss.str() << '\n';
3362 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3364 if (opts.find("keepaspectratio") != opts.end())
3365 os << "\tkeepAspectRatio\n";
3366 if (opts.find("clip") != opts.end())
3368 if (opts.find("draft") != opts.end())
3370 if (opts.find("bb") != opts.end())
3371 os << "\tBoundingBox "
3372 << opts["bb"] << '\n';
3373 int numberOfbbOptions = 0;
3374 if (opts.find("bbllx") != opts.end())
3375 numberOfbbOptions++;
3376 if (opts.find("bblly") != opts.end())
3377 numberOfbbOptions++;
3378 if (opts.find("bburx") != opts.end())
3379 numberOfbbOptions++;
3380 if (opts.find("bbury") != opts.end())
3381 numberOfbbOptions++;
3382 if (numberOfbbOptions == 4)
3383 os << "\tBoundingBox "
3384 << opts["bbllx"] << " " << opts["bblly"] << " "
3385 << opts["bburx"] << " " << opts["bbury"] << '\n';
3386 else if (numberOfbbOptions > 0)
3387 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3388 numberOfbbOptions = 0;
3389 if (opts.find("natwidth") != opts.end())
3390 numberOfbbOptions++;
3391 if (opts.find("natheight") != opts.end())
3392 numberOfbbOptions++;
3393 if (numberOfbbOptions == 2)
3394 os << "\tBoundingBox 0bp 0bp "
3395 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3396 else if (numberOfbbOptions > 0)
3397 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3398 ostringstream special;
3399 if (opts.find("hiresbb") != opts.end())
3400 special << "hiresbb,";
3401 if (opts.find("trim") != opts.end())
3403 if (opts.find("viewport") != opts.end())
3404 special << "viewport=" << opts["viewport"] << ',';
3405 if (opts.find("totalheight") != opts.end())
3406 special << "totalheight=" << opts["totalheight"] << ',';
3407 if (opts.find("type") != opts.end())
3408 special << "type=" << opts["type"] << ',';
3409 if (opts.find("ext") != opts.end())
3410 special << "ext=" << opts["ext"] << ',';
3411 if (opts.find("read") != opts.end())
3412 special << "read=" << opts["read"] << ',';
3413 if (opts.find("command") != opts.end())
3414 special << "command=" << opts["command"] << ',';
3415 string s_special = special.str();
3416 if (!s_special.empty()) {
3417 // We had special arguments. Remove the trailing ','.
3418 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3420 // TODO: Handle the unknown settings better.
3421 // Warn about invalid options.
3422 // Check whether some option was given twice.
3424 preamble.registerAutomaticallyLoadedPackage("graphicx");
3428 if (t.cs() == "footnote" ||
3429 (t.cs() == "thanks" && context.layout->intitle)) {
3431 context.check_layout(os);
3432 begin_inset(os, "Foot\n");
3433 os << "status collapsed\n\n";
3434 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3439 if (t.cs() == "marginpar") {
3441 context.check_layout(os);
3442 begin_inset(os, "Marginal\n");
3443 os << "status collapsed\n\n";
3444 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3449 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3450 bool const use_minted = t.cs() == "mintinline";
3452 parse_listings(p, os, context, true, use_minted);
3456 if (t.cs() == "ensuremath") {
3458 context.check_layout(os);
3459 string const s = p.verbatim_item();
3460 //FIXME: this never triggers in UTF8
3461 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3464 output_ert_inset(os, "\\ensuremath{" + s + "}",
3469 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3470 if (preamble.titleLayoutFound()) {
3472 skip_spaces_braces(p);
3474 output_ert_inset(os, t.asInput(), context);
3478 if (t.cs() == "tableofcontents"
3479 || t.cs() == "lstlistoflistings"
3480 || t.cs() == "listoflistings") {
3481 string name = t.cs();
3482 if (preamble.minted() && name == "listoflistings")
3483 name.insert(0, "lst");
3484 context.check_layout(os);
3485 begin_command_inset(os, "toc", name);
3487 skip_spaces_braces(p);
3488 if (name == "lstlistoflistings") {
3489 if (preamble.minted())
3490 preamble.registerAutomaticallyLoadedPackage("minted");
3492 preamble.registerAutomaticallyLoadedPackage("listings");
3497 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3498 context.check_layout(os);
3499 if (t.cs() == "listoffigures")
3500 begin_inset(os, "FloatList figure\n");
3502 begin_inset(os, "FloatList table\n");
3504 skip_spaces_braces(p);
3508 if (t.cs() == "listof") {
3509 p.skip_spaces(true);
3510 string const name = p.get_token().cs();
3511 if (context.textclass.floats().typeExist(name)) {
3512 context.check_layout(os);
3513 begin_inset(os, "FloatList ");
3516 p.get_token(); // swallow second arg
3518 output_ert_inset(os, "\\listof{" + name + "}", context);
3522 if ((where = is_known(t.cs(), known_text_font_families))) {
3523 parse_text_attributes(p, os, FLAG_ITEM, outer,
3524 context, "\\family", context.font.family,
3525 known_coded_font_families[where - known_text_font_families]);
3529 if ((where = is_known(t.cs(), known_text_font_series))) {
3530 parse_text_attributes(p, os, FLAG_ITEM, outer,
3531 context, "\\series", context.font.series,
3532 known_coded_font_series[where - known_text_font_series]);
3536 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3537 parse_text_attributes(p, os, FLAG_ITEM, outer,
3538 context, "\\shape", context.font.shape,
3539 known_coded_font_shapes[where - known_text_font_shapes]);
3543 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3544 context.check_layout(os);
3545 TeXFont oldFont = context.font;
3546 context.font.init();
3547 context.font.size = oldFont.size;
3548 os << "\n\\family " << context.font.family << "\n";
3549 os << "\n\\series " << context.font.series << "\n";
3550 os << "\n\\shape " << context.font.shape << "\n";
3551 if (t.cs() == "textnormal") {
3552 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3553 output_font_change(os, context.font, oldFont);
3554 context.font = oldFont;
3556 eat_whitespace(p, os, context, false);
3560 if (t.cs() == "textcolor") {
3561 // scheme is \textcolor{color name}{text}
3562 string const color = p.verbatim_item();
3563 // we support the predefined colors of the color and the xcolor package
3564 if (color == "black" || color == "blue" || color == "cyan"
3565 || color == "green" || color == "magenta" || color == "red"
3566 || color == "white" || color == "yellow") {
3567 context.check_layout(os);
3568 os << "\n\\color " << color << "\n";
3569 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3570 context.check_layout(os);
3571 os << "\n\\color inherit\n";
3572 preamble.registerAutomaticallyLoadedPackage("color");
3573 } else if (color == "brown" || color == "darkgray" || color == "gray"
3574 || color == "lightgray" || color == "lime" || color == "olive"
3575 || color == "orange" || color == "pink" || color == "purple"
3576 || color == "teal" || color == "violet") {
3577 context.check_layout(os);
3578 os << "\n\\color " << color << "\n";
3579 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3580 context.check_layout(os);
3581 os << "\n\\color inherit\n";
3582 preamble.registerAutomaticallyLoadedPackage("xcolor");
3584 // for custom defined colors
3585 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3589 if (t.cs() == "underbar" || t.cs() == "uline") {
3590 // \underbar is not 100% correct (LyX outputs \uline
3591 // of ulem.sty). The difference is that \ulem allows
3592 // line breaks, and \underbar does not.
3593 // Do NOT handle \underline.
3594 // \underbar cuts through y, g, q, p etc.,
3595 // \underline does not.
3596 context.check_layout(os);
3597 os << "\n\\bar under\n";
3598 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3599 context.check_layout(os);
3600 os << "\n\\bar default\n";
3601 preamble.registerAutomaticallyLoadedPackage("ulem");
3605 if (t.cs() == "sout") {
3606 context.check_layout(os);
3607 os << "\n\\strikeout on\n";
3608 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3609 context.check_layout(os);
3610 os << "\n\\strikeout default\n";
3611 preamble.registerAutomaticallyLoadedPackage("ulem");
3615 if (t.cs() == "uuline" || t.cs() == "uwave"
3616 || t.cs() == "emph" || t.cs() == "noun"
3617 || t.cs() == "xout") {
3618 context.check_layout(os);
3619 os << "\n\\" << t.cs() << " on\n";
3620 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3621 context.check_layout(os);
3622 os << "\n\\" << t.cs() << " default\n";
3623 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3624 preamble.registerAutomaticallyLoadedPackage("ulem");
3628 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3629 context.check_layout(os);
3630 string name = p.getArg('{', '}');
3631 string localtime = p.getArg('{', '}');
3632 preamble.registerAuthor(name);
3633 Author const & author = preamble.getAuthor(name);
3634 // from_asctime_utc() will fail if LyX decides to output the
3635 // time in the text language.
3636 time_t ptime = from_asctime_utc(localtime);
3637 if (ptime == static_cast<time_t>(-1)) {
3638 cerr << "Warning: Could not parse time `" << localtime
3639 << "´ for change tracking, using current time instead.\n";
3640 ptime = current_time();
3642 if (t.cs() == "lyxadded")
3643 os << "\n\\change_inserted ";
3645 os << "\n\\change_deleted ";
3646 os << author.bufferId() << ' ' << ptime << '\n';
3647 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3648 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3649 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3650 LaTeXPackages::isAvailable("xcolor");
3651 // No need to test for luatex, since luatex comes in
3652 // two flavours (dvi and pdf), like latex, and those
3653 // are detected by pdflatex.
3654 if (pdflatex || xetex) {
3656 preamble.registerAutomaticallyLoadedPackage("ulem");
3657 preamble.registerAutomaticallyLoadedPackage("xcolor");
3658 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3662 preamble.registerAutomaticallyLoadedPackage("dvipost");
3663 } else if (xcolorulem) {
3664 preamble.registerAutomaticallyLoadedPackage("ulem");
3665 preamble.registerAutomaticallyLoadedPackage("xcolor");
3671 if (t.cs() == "textipa") {
3672 context.check_layout(os);
3673 begin_inset(os, "IPA\n");
3674 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3675 context.merging_hyphens_allowed = false;
3676 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3677 context.merging_hyphens_allowed = merging_hyphens_allowed;
3679 preamble.registerAutomaticallyLoadedPackage("tipa");
3680 preamble.registerAutomaticallyLoadedPackage("tipx");
3684 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3685 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3686 context.check_layout(os);
3690 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3691 begin_inset(os, "IPADeco " + type + "\n");
3692 os << "status open\n";
3693 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3699 if (t.cs() == "textvertline") {
3700 // FIXME: This is not correct, \textvertline is higher than |
3706 if (t.cs() == "tone" ) {
3707 context.check_layout(os);
3708 // register the tone package
3709 preamble.registerAutomaticallyLoadedPackage("tone");
3710 string content = trimSpaceAndEol(p.verbatim_item());
3711 string command = t.asInput() + "{" + content + "}";
3712 // some tones can be detected by unicodesymbols, some need special code
3713 if (is_known(content, known_tones)) {
3714 os << "\\IPAChar " << command << "\n";
3717 // try to see whether the string is in unicodesymbols
3721 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3722 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3723 termination, rem, &req);
3727 output_ert_inset(os, to_utf8(rem), context);
3728 for (set<string>::const_iterator it = req.begin();
3729 it != req.end(); ++it)
3730 preamble.registerAutomaticallyLoadedPackage(*it);
3732 // we did not find a non-ert version
3733 output_ert_inset(os, command, context);
3737 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3738 t.cs() == "vphantom") {
3739 context.check_layout(os);
3740 if (t.cs() == "phantom")
3741 begin_inset(os, "Phantom Phantom\n");
3742 if (t.cs() == "hphantom")
3743 begin_inset(os, "Phantom HPhantom\n");
3744 if (t.cs() == "vphantom")
3745 begin_inset(os, "Phantom VPhantom\n");
3746 os << "status open\n";
3747 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3753 if (t.cs() == "href") {
3754 context.check_layout(os);
3755 string target = convert_literate_command_inset_arg(p.verbatim_item());
3756 string name = p.verbatim_item();
3757 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3758 bool const literal = !nm.first;
3759 name = literal ? subst(name, "\n", " ") : nm.second;
3760 string lit = literal ? "\"true\"" : "\"false\"";
3762 size_t i = target.find(':');
3763 if (i != string::npos) {
3764 type = target.substr(0, i + 1);
3765 if (type == "mailto:" || type == "file:")
3766 target = target.substr(i + 1);
3767 // handle the case that name is equal to target, except of "http(s)://"
3768 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3771 begin_command_inset(os, "href", "href");
3773 os << "name \"" << name << "\"\n";
3774 os << "target \"" << target << "\"\n";
3775 if (type == "mailto:" || type == "file:")
3776 os << "type \"" << type << "\"\n";
3777 os << "literal " << lit << "\n";
3779 skip_spaces_braces(p);
3783 if (t.cs() == "lyxline") {
3784 // swallow size argument (it is not used anyway)
3786 if (!context.atParagraphStart()) {
3787 // so our line is in the middle of a paragraph
3788 // we need to add a new line, lest this line
3789 // follow the other content on that line and
3790 // run off the side of the page
3791 // FIXME: This may create an empty paragraph,
3792 // but without that it would not be
3793 // possible to set noindent below.
3794 // Fortunately LaTeX does not care
3795 // about the empty paragraph.
3796 context.new_paragraph(os);
3798 if (preamble.indentParagraphs()) {
3799 // we need to unindent, lest the line be too long
3800 context.add_par_extra_stuff("\\noindent\n");
3802 context.check_layout(os);
3803 begin_command_inset(os, "line", "rule");
3804 os << "offset \"0.5ex\"\n"
3805 "width \"100line%\"\n"
3811 if (t.cs() == "rule") {
3812 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3813 string const width = p.getArg('{', '}');
3814 string const thickness = p.getArg('{', '}');
3815 context.check_layout(os);
3816 begin_command_inset(os, "line", "rule");
3817 if (!offset.empty())
3818 os << "offset \"" << translate_len(offset) << "\"\n";
3819 os << "width \"" << translate_len(width) << "\"\n"
3820 "height \"" << translate_len(thickness) << "\"\n";
3825 // handle refstyle first to catch \eqref which can also occur
3826 // without refstyle. Only recognize these commands if
3827 // refstyle.sty was found in the preamble (otherwise \eqref
3828 // and user defined ref commands could be misdetected).
3829 if ((where = is_known(t.cs(), known_refstyle_commands))
3830 && preamble.refstyle()) {
3831 context.check_layout(os);
3832 begin_command_inset(os, "ref", "formatted");
3833 os << "reference \"";
3834 os << known_refstyle_prefixes[where - known_refstyle_commands]
3836 os << convert_literate_command_inset_arg(p.verbatim_item())
3838 os << "plural \"false\"\n";
3839 os << "caps \"false\"\n";
3840 os << "noprefix \"false\"\n";
3842 preamble.registerAutomaticallyLoadedPackage("refstyle");
3846 // if refstyle is used, we must not convert \prettyref to a
3847 // formatted reference, since that would result in a refstyle command.
3848 if ((where = is_known(t.cs(), known_ref_commands)) &&
3849 (t.cs() != "prettyref" || !preamble.refstyle())) {
3850 string const opt = p.getOpt();
3852 context.check_layout(os);
3853 begin_command_inset(os, "ref",
3854 known_coded_ref_commands[where - known_ref_commands]);
3855 os << "reference \""
3856 << convert_literate_command_inset_arg(p.verbatim_item())
3858 os << "plural \"false\"\n";
3859 os << "caps \"false\"\n";
3860 os << "noprefix \"false\"\n";
3862 if (t.cs() == "vref" || t.cs() == "vpageref")
3863 preamble.registerAutomaticallyLoadedPackage("varioref");
3864 else if (t.cs() == "prettyref")
3865 preamble.registerAutomaticallyLoadedPackage("prettyref");
3867 // LyX does not yet support optional arguments of ref commands
3868 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3869 p.verbatim_item() + '}', context);
3875 is_known(t.cs(), known_natbib_commands) &&
3876 ((t.cs() != "citefullauthor" &&
3877 t.cs() != "citeyear" &&
3878 t.cs() != "citeyearpar") ||
3879 p.next_token().asInput() != "*")) {
3880 context.check_layout(os);
3881 string command = t.cs();
3882 if (p.next_token().asInput() == "*") {
3886 if (command == "citefullauthor")
3887 // alternative name for "\\citeauthor*"
3888 command = "citeauthor*";
3890 // text before the citation
3892 // text after the citation
3894 get_cite_arguments(p, true, before, after);
3896 if (command == "cite") {
3897 // \cite without optional argument means
3898 // \citet, \cite with at least one optional
3899 // argument means \citep.
3900 if (before.empty() && after.empty())
3905 if (before.empty() && after == "[]")
3906 // avoid \citet[]{a}
3908 else if (before == "[]" && after == "[]") {
3909 // avoid \citet[][]{a}
3913 bool literal = false;
3914 pair<bool, string> aft;
3915 pair<bool, string> bef;
3916 // remove the brackets around after and before
3917 if (!after.empty()) {
3919 after.erase(after.length() - 1, 1);
3920 aft = convert_latexed_command_inset_arg(after);
3921 literal = !aft.first;
3922 after = literal ? subst(after, "\n", " ") : aft.second;
3924 if (!before.empty()) {
3926 before.erase(before.length() - 1, 1);
3927 bef = convert_latexed_command_inset_arg(before);
3928 literal |= !bef.first;
3929 before = literal ? subst(before, "\n", " ") : bef.second;
3930 if (literal && !after.empty())
3931 after = subst(after, "\n", " ");
3933 string lit = literal ? "\"true\"" : "\"false\"";
3934 begin_command_inset(os, "citation", command);
3935 os << "after " << '"' << after << '"' << "\n";
3936 os << "before " << '"' << before << '"' << "\n";
3938 << convert_literate_command_inset_arg(p.verbatim_item())
3940 << "literal " << lit << "\n";
3942 // Need to set the cite engine if natbib is loaded by
3943 // the document class directly
3944 if (preamble.citeEngine() == "basic")
3945 preamble.citeEngine("natbib");
3950 && is_known(t.cs(), known_biblatex_commands)
3951 && ((t.cs() == "cite"
3952 || t.cs() == "citeauthor"
3953 || t.cs() == "Citeauthor"
3954 || t.cs() == "parencite"
3955 || t.cs() == "citetitle")
3956 || p.next_token().asInput() != "*"))
3957 || (use_biblatex_natbib
3958 && (is_known(t.cs(), known_biblatex_commands)
3959 || is_known(t.cs(), known_natbib_commands))
3960 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3961 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3962 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3963 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3964 || t.cs() == "parencite" || t.cs() == "citetitle")
3965 || p.next_token().asInput() != "*"))){
3966 context.check_layout(os);
3967 string command = t.cs();
3968 if (p.next_token().asInput() == "*") {
3973 bool const qualified = suffixIs(command, "s");
3975 command = rtrim(command, "s");
3977 // text before the citation
3979 // text after the citation
3981 get_cite_arguments(p, true, before, after, qualified);
3983 // These use natbib cmd names in LyX
3984 // for inter-citeengine compativility
3985 if (command == "citeyear")
3986 command = "citebyear";
3987 else if (command == "cite*")
3988 command = "citeyear";
3989 else if (command == "textcite")
3991 else if (command == "Textcite")
3993 else if (command == "parencite")
3995 else if (command == "Parencite")
3997 else if (command == "parencite*")
3998 command = "citeyearpar";
3999 else if (command == "smartcite")
4000 command = "footcite";
4001 else if (command == "Smartcite")
4002 command = "Footcite";
4004 string const emptyarg = qualified ? "()" : "[]";
4005 if (before.empty() && after == emptyarg)
4008 else if (before == emptyarg && after == emptyarg) {
4009 // avoid \cite[][]{a}
4013 bool literal = false;
4014 pair<bool, string> aft;
4015 pair<bool, string> bef;
4016 // remove the brackets around after and before
4017 if (!after.empty()) {
4019 after.erase(after.length() - 1, 1);
4020 aft = convert_latexed_command_inset_arg(after);
4021 literal = !aft.first;
4022 after = literal ? subst(after, "\n", " ") : aft.second;
4024 if (!before.empty()) {
4026 before.erase(before.length() - 1, 1);
4027 bef = convert_latexed_command_inset_arg(before);
4028 literal |= !bef.first;
4029 before = literal ? subst(before, "\n", " ") : bef.second;
4031 string keys, pretextlist, posttextlist;
4033 map<string, string> pres, posts, preslit, postslit;
4034 vector<string> lkeys;
4035 // text before the citation
4036 string lbefore, lbeforelit;
4037 // text after the citation
4038 string lafter, lafterlit;
4040 pair<bool, string> laft, lbef;
4042 get_cite_arguments(p, true, lbefore, lafter);
4043 // remove the brackets around after and before
4044 if (!lafter.empty()) {
4046 lafter.erase(lafter.length() - 1, 1);
4047 laft = convert_latexed_command_inset_arg(lafter);
4048 literal |= !laft.first;
4049 lafter = laft.second;
4050 lafterlit = subst(lbefore, "\n", " ");
4052 if (!lbefore.empty()) {
4053 lbefore.erase(0, 1);
4054 lbefore.erase(lbefore.length() - 1, 1);
4055 lbef = convert_latexed_command_inset_arg(lbefore);
4056 literal |= !lbef.first;
4057 lbefore = lbef.second;
4058 lbeforelit = subst(lbefore, "\n", " ");
4060 if (lbefore.empty() && lafter == "[]") {
4065 else if (lbefore == "[]" && lafter == "[]") {
4066 // avoid \cite[][]{a}
4072 lkey = p.getArg('{', '}');
4075 if (!lbefore.empty()) {
4076 pres.insert(make_pair(lkey, lbefore));
4077 preslit.insert(make_pair(lkey, lbeforelit));
4079 if (!lafter.empty()) {
4080 posts.insert(make_pair(lkey, lafter));
4081 postslit.insert(make_pair(lkey, lafterlit));
4083 lkeys.push_back(lkey);
4085 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4090 for (auto const & ptl : pres) {
4091 if (!pretextlist.empty())
4092 pretextlist += '\t';
4093 pretextlist += ptl.first + " " + ptl.second;
4095 for (auto const & potl : posts) {
4096 if (!posttextlist.empty())
4097 posttextlist += '\t';
4098 posttextlist += potl.first + " " + potl.second;
4101 keys = convert_literate_command_inset_arg(p.verbatim_item());
4104 after = subst(after, "\n", " ");
4105 if (!before.empty())
4106 before = subst(after, "\n", " ");
4108 string lit = literal ? "\"true\"" : "\"false\"";
4109 begin_command_inset(os, "citation", command);
4110 os << "after " << '"' << after << '"' << "\n";
4111 os << "before " << '"' << before << '"' << "\n";
4115 if (!pretextlist.empty())
4116 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4117 if (!posttextlist.empty())
4118 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4119 os << "literal " << lit << "\n";
4121 // Need to set the cite engine if biblatex is loaded by
4122 // the document class directly
4123 if (preamble.citeEngine() == "basic")
4124 use_biblatex_natbib ?
4125 preamble.citeEngine("biblatex-natbib")
4126 : preamble.citeEngine("biblatex");
4131 is_known(t.cs(), known_jurabib_commands) &&
4132 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4133 context.check_layout(os);
4134 string command = t.cs();
4135 if (p.next_token().asInput() == "*") {
4139 char argumentOrder = '\0';
4140 vector<string> const options =
4141 preamble.getPackageOptions("jurabib");
4142 if (find(options.begin(), options.end(),
4143 "natbiborder") != options.end())
4144 argumentOrder = 'n';
4145 else if (find(options.begin(), options.end(),
4146 "jurabiborder") != options.end())
4147 argumentOrder = 'j';
4149 // text before the citation
4151 // text after the citation
4153 get_cite_arguments(p, argumentOrder != 'j', before, after);
4155 string const citation = p.verbatim_item();
4156 if (!before.empty() && argumentOrder == '\0') {
4157 cerr << "Warning: Assuming argument order "
4158 "of jurabib version 0.6 for\n'"
4159 << command << before << after << '{'
4160 << citation << "}'.\n"
4161 "Add 'jurabiborder' to the jurabib "
4162 "package options if you used an\n"
4163 "earlier jurabib version." << endl;
4165 bool literal = false;
4166 pair<bool, string> aft;
4167 pair<bool, string> bef;
4168 // remove the brackets around after and before
4169 if (!after.empty()) {
4171 after.erase(after.length() - 1, 1);
4172 aft = convert_latexed_command_inset_arg(after);
4173 literal = !aft.first;
4174 after = literal ? subst(after, "\n", " ") : aft.second;
4176 if (!before.empty()) {
4178 before.erase(before.length() - 1, 1);
4179 bef = convert_latexed_command_inset_arg(before);
4180 literal |= !bef.first;
4181 before = literal ? subst(before, "\n", " ") : bef.second;
4182 if (literal && !after.empty())
4183 after = subst(after, "\n", " ");
4185 string lit = literal ? "\"true\"" : "\"false\"";
4186 begin_command_inset(os, "citation", command);
4187 os << "after " << '"' << after << "\"\n"
4188 << "before " << '"' << before << "\"\n"
4189 << "key " << '"' << citation << "\"\n"
4190 << "literal " << lit << "\n";
4192 // Need to set the cite engine if jurabib is loaded by
4193 // the document class directly
4194 if (preamble.citeEngine() == "basic")
4195 preamble.citeEngine("jurabib");
4199 if (t.cs() == "cite"
4200 || t.cs() == "nocite") {
4201 context.check_layout(os);
4202 string after = p.getArg('[', ']');
4203 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4204 bool const literal = !aft.first;
4205 after = literal ? subst(after, "\n", " ") : aft.second;
4206 string lit = literal ? "\"true\"" : "\"false\"";
4207 string key = convert_literate_command_inset_arg(p.verbatim_item());
4208 // store the case that it is "\nocite{*}" to use it later for
4211 begin_command_inset(os, "citation", t.cs());
4212 os << "after " << '"' << after << "\"\n"
4213 << "key " << '"' << key << "\"\n"
4214 << "literal " << lit << "\n";
4216 } else if (t.cs() == "nocite")
4221 if (t.cs() == "index" ||
4222 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4223 context.check_layout(os);
4224 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4225 p.getArg('[', ']') : "";
4226 string const kind = arg.empty() ? "idx" : arg;
4227 begin_inset(os, "Index ");
4228 os << kind << "\nstatus collapsed\n";
4229 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4232 preamble.registerAutomaticallyLoadedPackage("splitidx");
4236 if (t.cs() == "nomenclature") {
4237 context.check_layout(os);
4238 begin_command_inset(os, "nomenclature", "nomenclature");
4239 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4240 if (!prefix.empty())
4241 os << "prefix " << '"' << prefix << '"' << "\n";
4242 string symbol = p.verbatim_item();
4243 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4244 bool literal = !sym.first;
4245 string description = p.verbatim_item();
4246 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4247 literal |= !desc.first;
4249 symbol = subst(symbol, "\n", " ");
4250 description = subst(description, "\n", " ");
4252 symbol = sym.second;
4253 description = desc.second;
4255 string lit = literal ? "\"true\"" : "\"false\"";
4256 os << "symbol " << '"' << symbol;
4257 os << "\"\ndescription \""
4258 << description << "\"\n"
4259 << "literal " << lit << "\n";
4261 preamble.registerAutomaticallyLoadedPackage("nomencl");
4265 if (t.cs() == "label") {
4266 context.check_layout(os);
4267 begin_command_inset(os, "label", "label");
4269 << convert_literate_command_inset_arg(p.verbatim_item())
4275 if (t.cs() == "lyxmintcaption") {
4276 string const pos = p.getArg('[', ']');
4278 string const caption =
4279 parse_text_snippet(p, FLAG_ITEM, false,
4281 minted_nonfloat_caption = "[t]" + caption;
4283 // We already got the caption at the bottom,
4284 // so simply skip it.
4285 parse_text_snippet(p, FLAG_ITEM, false, context);
4290 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4291 context.check_layout(os);
4292 string commandname = t.cs();
4294 if (p.next_token().asInput() == "*") {
4299 begin_command_inset(os, "index_print", commandname);
4300 string const indexname = p.getArg('[', ']');
4302 if (indexname.empty())
4303 os << "type \"idx\"\n";
4305 os << "type \"" << indexname << "\"\n";
4306 os << "literal \"true\"\n";
4309 skip_spaces_braces(p);
4310 preamble.registerAutomaticallyLoadedPackage("makeidx");
4311 if (preamble.use_indices() == "true")
4312 preamble.registerAutomaticallyLoadedPackage("splitidx");
4316 if (t.cs() == "printnomenclature") {
4318 string width_type = "";
4319 context.check_layout(os);
4320 begin_command_inset(os, "nomencl_print", "printnomenclature");
4321 // case of a custom width
4323 width = p.getArg('[', ']');
4324 width = translate_len(width);
4325 width_type = "custom";
4327 // case of no custom width
4328 // the case of no custom width but the width set
4329 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4330 // because the user could have set anything, not only the width
4331 // of the longest label (which would be width_type = "auto")
4332 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4333 if (label.empty() && width_type.empty())
4334 width_type = "none";
4335 os << "set_width \"" << width_type << "\"\n";
4336 if (width_type == "custom")
4337 os << "width \"" << width << '\"';
4339 skip_spaces_braces(p);
4340 preamble.registerAutomaticallyLoadedPackage("nomencl");
4344 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4345 context.check_layout(os);
4346 begin_inset(os, "script ");
4347 os << t.cs().substr(4) << '\n';
4348 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4349 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4351 if (t.cs() == "textsubscript")
4352 preamble.registerAutomaticallyLoadedPackage("subscript");
4356 if ((where = is_known(t.cs(), known_quotes))) {
4357 context.check_layout(os);
4358 begin_inset(os, "Quotes ");
4359 os << known_coded_quotes[where - known_quotes];
4361 // LyX adds {} after the quote, so we have to eat
4362 // spaces here if there are any before a possible
4364 eat_whitespace(p, os, context, false);
4369 if ((where = is_known(t.cs(), known_sizes)) &&
4370 context.new_layout_allowed) {
4371 context.check_layout(os);
4372 TeXFont const oldFont = context.font;
4373 context.font.size = known_coded_sizes[where - known_sizes];
4374 output_font_change(os, oldFont, context.font);
4375 eat_whitespace(p, os, context, false);
4379 if ((where = is_known(t.cs(), known_font_families)) &&
4380 context.new_layout_allowed) {
4381 context.check_layout(os);
4382 TeXFont const oldFont = context.font;
4383 context.font.family =
4384 known_coded_font_families[where - known_font_families];
4385 output_font_change(os, oldFont, context.font);
4386 eat_whitespace(p, os, context, false);
4390 if ((where = is_known(t.cs(), known_font_series)) &&
4391 context.new_layout_allowed) {
4392 context.check_layout(os);
4393 TeXFont const oldFont = context.font;
4394 context.font.series =
4395 known_coded_font_series[where - known_font_series];
4396 output_font_change(os, oldFont, context.font);
4397 eat_whitespace(p, os, context, false);
4401 if ((where = is_known(t.cs(), known_font_shapes)) &&
4402 context.new_layout_allowed) {
4403 context.check_layout(os);
4404 TeXFont const oldFont = context.font;
4405 context.font.shape =
4406 known_coded_font_shapes[where - known_font_shapes];
4407 output_font_change(os, oldFont, context.font);
4408 eat_whitespace(p, os, context, false);
4411 if ((where = is_known(t.cs(), known_old_font_families)) &&
4412 context.new_layout_allowed) {
4413 context.check_layout(os);
4414 TeXFont const oldFont = context.font;
4415 context.font.init();
4416 context.font.size = oldFont.size;
4417 context.font.family =
4418 known_coded_font_families[where - known_old_font_families];
4419 output_font_change(os, oldFont, context.font);
4420 eat_whitespace(p, os, context, false);
4424 if ((where = is_known(t.cs(), known_old_font_series)) &&
4425 context.new_layout_allowed) {
4426 context.check_layout(os);
4427 TeXFont const oldFont = context.font;
4428 context.font.init();
4429 context.font.size = oldFont.size;
4430 context.font.series =
4431 known_coded_font_series[where - known_old_font_series];
4432 output_font_change(os, oldFont, context.font);
4433 eat_whitespace(p, os, context, false);
4437 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4438 context.new_layout_allowed) {
4439 context.check_layout(os);
4440 TeXFont const oldFont = context.font;
4441 context.font.init();
4442 context.font.size = oldFont.size;
4443 context.font.shape =
4444 known_coded_font_shapes[where - known_old_font_shapes];
4445 output_font_change(os, oldFont, context.font);
4446 eat_whitespace(p, os, context, false);
4450 if (t.cs() == "selectlanguage") {
4451 context.check_layout(os);
4452 // save the language for the case that a
4453 // \foreignlanguage is used
4454 context.font.language = babel2lyx(p.verbatim_item());
4455 os << "\n\\lang " << context.font.language << "\n";
4459 if (t.cs() == "foreignlanguage") {
4460 string const lang = babel2lyx(p.verbatim_item());
4461 parse_text_attributes(p, os, FLAG_ITEM, outer,
4463 context.font.language, lang);
4467 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4468 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4469 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4471 // We have to output the whole command if it has an option
4472 // because LyX doesn't support this yet, see bug #8214,
4473 // only if there is a single option specifying a variant, we can handle it.
4475 string langopts = p.getOpt();
4476 // check if the option contains a variant, if yes, extract it
4477 string::size_type pos_var = langopts.find("variant");
4478 string::size_type i = langopts.find(',');
4479 string::size_type k = langopts.find('=', pos_var);
4480 if (pos_var != string::npos && i == string::npos) {
4482 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4483 lang = preamble.polyglossia2lyx(variant);
4484 parse_text_attributes(p, os, FLAG_ITEM, outer,
4486 context.font.language, lang);
4488 output_ert_inset(os, t.asInput() + langopts, context);
4490 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4491 parse_text_attributes(p, os, FLAG_ITEM, outer,
4493 context.font.language, lang);
4498 if (t.cs() == "inputencoding") {
4499 // nothing to write here
4500 string const enc = subst(p.verbatim_item(), "\n", " ");
4501 p.setEncoding(enc, Encoding::inputenc);
4505 if (is_known(t.cs(), known_special_chars) ||
4506 (t.cs() == "protect" &&
4507 p.next_token().cat() == catEscape &&
4508 is_known(p.next_token().cs(), known_special_protect_chars))) {
4509 // LyX sometimes puts a \protect in front, so we have to ignore it
4511 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4512 known_special_chars);
4513 context.check_layout(os);
4514 os << known_coded_special_chars[where - known_special_chars];
4515 skip_spaces_braces(p);
4519 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4520 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4521 p.next_next_token().asInput() == "-") ||
4522 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4523 // LyX sometimes puts a \protect in front, so we have to ignore it
4524 if (t.cs() == "protect")
4526 context.check_layout(os);
4527 if (t.cs() == "nobreakdash")
4528 os << "\\SpecialChar nobreakdash\n";
4530 os << "\\SpecialChar endofsentence\n";
4535 if (t.cs() == "textquotedbl") {
4536 context.check_layout(os);
4542 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4543 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4544 || t.cs() == "%" || t.cs() == "-") {
4545 context.check_layout(os);
4547 os << "\\SpecialChar softhyphen\n";
4553 if (t.cs() == "char") {
4554 context.check_layout(os);
4555 if (p.next_token().character() == '`') {
4557 if (p.next_token().cs() == "\"") {
4562 output_ert_inset(os, "\\char`", context);
4565 output_ert_inset(os, "\\char", context);
4570 if (t.cs() == "verb") {
4571 context.check_layout(os);
4572 // set catcodes to verbatim early, just in case.
4573 p.setCatcodes(VERBATIM_CATCODES);
4574 string delim = p.get_token().asInput();
4575 Parser::Arg arg = p.verbatimStuff(delim);
4577 output_ert_inset(os, "\\verb" + delim
4578 + arg.second + delim, context);
4580 cerr << "invalid \\verb command. Skipping" << endl;
4584 // Problem: \= creates a tabstop inside the tabbing environment
4585 // and else an accent. In the latter case we really would want
4586 // \={o} instead of \= o.
4587 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4588 output_ert_inset(os, t.asInput(), context);
4592 if (t.cs() == "\\") {
4593 context.check_layout(os);
4595 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4596 else if (p.next_token().asInput() == "*") {
4598 // getOpt() eats the following space if there
4599 // is no optional argument, but that is OK
4600 // here since it has no effect in the output.
4601 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4604 begin_inset(os, "Newline newline");
4610 if (t.cs() == "newline" ||
4611 (t.cs() == "linebreak" && !p.hasOpt())) {
4612 context.check_layout(os);
4613 begin_inset(os, "Newline ");
4616 skip_spaces_braces(p);
4620 if (t.cs() == "input" || t.cs() == "include"
4621 || t.cs() == "verbatiminput") {
4622 string name = t.cs();
4623 if (t.cs() == "verbatiminput"
4624 && p.next_token().asInput() == "*")
4625 name += p.get_token().asInput();
4626 context.check_layout(os);
4627 string filename(normalize_filename(p.getArg('{', '}')));
4628 string const path = getMasterFilePath(true);
4629 // We want to preserve relative / absolute filenames,
4630 // therefore path is only used for testing
4631 if ((t.cs() == "include" || t.cs() == "input") &&
4632 !makeAbsPath(filename, path).exists()) {
4633 // The file extension is probably missing.
4634 // Now try to find it out.
4635 string const tex_name =
4636 find_file(filename, path,
4637 known_tex_extensions);
4638 if (!tex_name.empty())
4639 filename = tex_name;
4641 bool external = false;
4643 if (makeAbsPath(filename, path).exists()) {
4644 string const abstexname =
4645 makeAbsPath(filename, path).absFileName();
4646 string const absfigname =
4647 changeExtension(abstexname, ".fig");
4648 fix_child_filename(filename);
4649 string const lyxname = changeExtension(filename,
4650 roundtripMode() ? ".lyx.lyx" : ".lyx");
4651 string const abslyxname = makeAbsPath(
4652 lyxname, getParentFilePath(false)).absFileName();
4654 if (!skipChildren())
4655 external = FileName(absfigname).exists();
4656 if (t.cs() == "input" && !skipChildren()) {
4657 string const ext = getExtension(abstexname);
4659 // Combined PS/LaTeX:
4660 // x.eps, x.pstex_t (old xfig)
4661 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4662 FileName const absepsname(
4663 changeExtension(abstexname, ".eps"));
4664 FileName const abspstexname(
4665 changeExtension(abstexname, ".pstex"));
4666 bool const xfigeps =
4667 (absepsname.exists() ||
4668 abspstexname.exists()) &&
4671 // Combined PDF/LaTeX:
4672 // x.pdf, x.pdftex_t (old xfig)
4673 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4674 FileName const abspdfname(
4675 changeExtension(abstexname, ".pdf"));
4676 bool const xfigpdf =
4677 abspdfname.exists() &&
4678 (ext == "pdftex_t" || ext == "pdf_t");
4682 // Combined PS/PDF/LaTeX:
4683 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4684 string const absbase2(
4685 removeExtension(abstexname) + "_pspdftex");
4686 FileName const abseps2name(
4687 addExtension(absbase2, ".eps"));
4688 FileName const abspdf2name(
4689 addExtension(absbase2, ".pdf"));
4690 bool const xfigboth =
4691 abspdf2name.exists() &&
4692 abseps2name.exists() && ext == "pspdftex";
4694 xfig = xfigpdf || xfigeps || xfigboth;
4695 external = external && xfig;
4698 outname = changeExtension(filename, ".fig");
4699 FileName abssrc(changeExtension(abstexname, ".fig"));
4700 copy_file(abssrc, outname);
4702 // Don't try to convert, the result
4703 // would be full of ERT.
4705 FileName abssrc(abstexname);
4706 copy_file(abssrc, outname);
4707 } else if (t.cs() != "verbatiminput" &&
4709 tex2lyx(abstexname, FileName(abslyxname),
4712 // no need to call copy_file
4713 // tex2lyx creates the file
4716 FileName abssrc(abstexname);
4717 copy_file(abssrc, outname);
4720 cerr << "Warning: Could not find included file '"
4721 << filename << "'." << endl;
4725 begin_inset(os, "External\n");
4726 os << "\ttemplate XFig\n"
4727 << "\tfilename " << outname << '\n';
4728 registerExternalTemplatePackages("XFig");
4730 begin_command_inset(os, "include", name);
4731 outname = subst(outname, "\"", "\\\"");
4732 os << "preview false\n"
4733 "filename \"" << outname << "\"\n";
4734 if (t.cs() == "verbatiminput")
4735 preamble.registerAutomaticallyLoadedPackage("verbatim");
4741 if (t.cs() == "bibliographystyle") {
4742 // store new bibliographystyle
4743 bibliographystyle = p.verbatim_item();
4744 // If any other command than \bibliography, \addcontentsline
4745 // and \nocite{*} follows, we need to output the style
4746 // (because it might be used by that command).
4747 // Otherwise, it will automatically be output by LyX.
4750 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4751 if (t2.cat() == catBegin)
4753 if (t2.cat() != catEscape)
4755 if (t2.cs() == "nocite") {
4756 if (p.getArg('{', '}') == "*")
4758 } else if (t2.cs() == "bibliography")
4760 else if (t2.cs() == "phantomsection") {
4764 else if (t2.cs() == "addcontentsline") {
4765 // get the 3 arguments of \addcontentsline
4768 contentslineContent = p.getArg('{', '}');
4769 // if the last argument is not \refname we must output
4770 if (contentslineContent == "\\refname")
4777 output_ert_inset(os,
4778 "\\bibliographystyle{" + bibliographystyle + '}',
4784 if (t.cs() == "phantomsection") {
4785 // we only support this if it occurs between
4786 // \bibliographystyle and \bibliography
4787 if (bibliographystyle.empty())
4788 output_ert_inset(os, "\\phantomsection", context);
4792 if (t.cs() == "addcontentsline") {
4793 context.check_layout(os);
4794 // get the 3 arguments of \addcontentsline
4795 string const one = p.getArg('{', '}');
4796 string const two = p.getArg('{', '}');
4797 string const three = p.getArg('{', '}');
4798 // only if it is a \refname, we support if for the bibtex inset
4799 if (contentslineContent != "\\refname") {
4800 output_ert_inset(os,
4801 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4807 else if (t.cs() == "bibliography") {
4808 context.check_layout(os);
4810 begin_command_inset(os, "bibtex", "bibtex");
4811 if (!btprint.empty()) {
4812 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4813 // clear the string because the next BibTeX inset can be without the
4814 // \nocite{*} option
4817 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4818 // Do we have addcontentsline?
4819 if (contentslineContent == "\\refname") {
4820 BibOpts = "bibtotoc";
4821 // clear string because next BibTeX inset can be without addcontentsline
4822 contentslineContent.clear();
4824 // Do we have a bibliographystyle set?
4825 if (!bibliographystyle.empty()) {
4826 if (BibOpts.empty())
4827 BibOpts = normalize_filename(bibliographystyle);
4829 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4830 // clear it because each bibtex entry has its style
4831 // and we need an empty string to handle \phantomsection
4832 bibliographystyle.clear();
4834 os << "options " << '"' << BibOpts << '"' << "\n";
4839 if (t.cs() == "printbibliography") {
4840 context.check_layout(os);
4842 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4843 vector<string> opts = getVectorFromString(bbloptions);
4844 vector<string>::iterator it =
4845 find(opts.begin(), opts.end(), "heading=bibintoc");
4846 if (it != opts.end()) {
4848 BibOpts = "bibtotoc";
4850 bbloptions = getStringFromVector(opts);
4851 begin_command_inset(os, "bibtex", "bibtex");
4852 if (!btprint.empty()) {
4853 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4854 // clear the string because the next BibTeX inset can be without the
4855 // \nocite{*} option
4859 for (auto const & bf : preamble.biblatex_bibliographies) {
4860 if (!bibfiles.empty())
4862 bibfiles += normalize_filename(bf);
4864 if (!bibfiles.empty())
4865 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4866 // Do we have addcontentsline?
4867 if (contentslineContent == "\\refname") {
4868 BibOpts = "bibtotoc";
4869 // clear string because next BibTeX inset can be without addcontentsline
4870 contentslineContent.clear();
4872 os << "options " << '"' << BibOpts << '"' << "\n";
4873 if (!bbloptions.empty())
4874 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4876 need_commentbib = false;
4880 if (t.cs() == "bibbysection") {
4881 context.check_layout(os);
4883 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4884 vector<string> opts = getVectorFromString(bbloptions);
4885 vector<string>::iterator it =
4886 find(opts.begin(), opts.end(), "heading=bibintoc");
4887 if (it != opts.end()) {
4889 BibOpts = "bibtotoc";
4891 bbloptions = getStringFromVector(opts);
4892 begin_command_inset(os, "bibtex", "bibtex");
4893 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4895 for (auto const & bf : preamble.biblatex_bibliographies) {
4896 if (!bibfiles.empty())
4898 bibfiles += normalize_filename(bf);
4900 if (!bibfiles.empty())
4901 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4902 os << "options " << '"' << BibOpts << '"' << "\n";
4903 if (!bbloptions.empty())
4904 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4906 need_commentbib = false;
4910 if (t.cs() == "parbox") {
4911 // Test whether this is an outer box of a shaded box
4913 // swallow arguments
4914 while (p.hasOpt()) {
4916 p.skip_spaces(true);
4919 p.skip_spaces(true);
4921 if (p.next_token().cat() == catBegin)
4923 p.skip_spaces(true);
4924 Token to = p.get_token();
4925 bool shaded = false;
4926 if (to.asInput() == "\\begin") {
4927 p.skip_spaces(true);
4928 if (p.getArg('{', '}') == "shaded")
4933 parse_outer_box(p, os, FLAG_ITEM, outer,
4934 context, "parbox", "shaded");
4936 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4937 "", "", t.cs(), "", "");
4941 if (t.cs() == "fbox" || t.cs() == "mbox" ||
4942 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4943 t.cs() == "shadowbox" || t.cs() == "doublebox") {
4944 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4948 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4949 string backgroundcolor;
4950 preamble.registerAutomaticallyLoadedPackage("xcolor");
4951 if (t.cs() == "fcolorbox") {
4952 string const framecolor = p.getArg('{', '}');
4953 backgroundcolor = p.getArg('{', '}');
4954 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4956 backgroundcolor = p.getArg('{', '}');
4957 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4962 // FIXME: due to the compiler limit of "if" nestings
4963 // the code for the alignment was put here
4964 // put them in their own if if this is fixed
4965 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4966 || t.cs() == "shadowsize"
4967 || t.cs() == "raggedleft" || t.cs() == "centering"
4968 || t.cs() == "raggedright") {
4969 if (t.cs() == "fboxrule")
4971 if (t.cs() == "fboxsep")
4973 if (t.cs() == "shadowsize")
4975 if (t.cs() != "raggedleft" && t.cs() != "centering"
4976 && t.cs() != "raggedright") {
4977 p.skip_spaces(true);
4978 while (p.good() && p.next_token().cat() != catSpace
4979 && p.next_token().cat() != catNewline
4980 && p.next_token().cat() != catEscape) {
4981 if (t.cs() == "fboxrule")
4982 fboxrule = fboxrule + p.get_token().asInput();
4983 if (t.cs() == "fboxsep")
4984 fboxsep = fboxsep + p.get_token().asInput();
4985 if (t.cs() == "shadowsize")
4986 shadow_size = shadow_size + p.get_token().asInput();
4989 output_ert_inset(os, t.asInput(), context);
4994 //\framebox() is part of the picture environment and different from \framebox{}
4995 //\framebox{} will be parsed by parse_outer_box
4996 if (t.cs() == "framebox") {
4997 if (p.next_token().character() == '(') {
4998 //the syntax is: \framebox(x,y)[position]{content}
4999 string arg = t.asInput();
5000 arg += p.getFullParentheseArg();
5001 arg += p.getFullOpt();
5002 eat_whitespace(p, os, context, false);
5003 output_ert_inset(os, arg + '{', context);
5004 parse_text(p, os, FLAG_ITEM, outer, context);
5005 output_ert_inset(os, "}", context);
5007 //the syntax is: \framebox[width][position]{content}
5008 string special = p.getFullOpt();
5009 special += p.getOpt();
5010 parse_outer_box(p, os, FLAG_ITEM, outer,
5011 context, t.cs(), special);
5016 //\makebox() is part of the picture environment and different from \makebox{}
5017 //\makebox{} will be parsed by parse_box
5018 if (t.cs() == "makebox") {
5019 if (p.next_token().character() == '(') {
5020 //the syntax is: \makebox(x,y)[position]{content}
5021 string arg = t.asInput();
5022 arg += p.getFullParentheseArg();
5023 arg += p.getFullOpt();
5024 eat_whitespace(p, os, context, false);
5025 output_ert_inset(os, arg + '{', context);
5026 parse_text(p, os, FLAG_ITEM, outer, context);
5027 output_ert_inset(os, "}", context);
5029 //the syntax is: \makebox[width][position]{content}
5030 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5031 "", "", t.cs(), "", "");
5035 if (t.cs() == "smallskip" ||
5036 t.cs() == "medskip" ||
5037 t.cs() == "bigskip" ||
5038 t.cs() == "vfill") {
5039 context.check_layout(os);
5040 begin_inset(os, "VSpace ");
5043 skip_spaces_braces(p);
5047 if ((where = is_known(t.cs(), known_spaces))) {
5048 context.check_layout(os);
5049 begin_inset(os, "space ");
5050 os << '\\' << known_coded_spaces[where - known_spaces]
5053 // LaTeX swallows whitespace after all spaces except
5054 // "\\,". We have to do that here, too, because LyX
5055 // adds "{}" which would make the spaces significant.
5057 eat_whitespace(p, os, context, false);
5058 // LyX adds "{}" after all spaces except "\\ " and
5059 // "\\,", so we have to remove "{}".
5060 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5061 // remove the braces after "\\,", too.
5067 if (t.cs() == "newpage" ||
5068 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5069 t.cs() == "clearpage" ||
5070 t.cs() == "cleardoublepage") {
5071 context.check_layout(os);
5072 begin_inset(os, "Newpage ");
5075 skip_spaces_braces(p);
5079 if (t.cs() == "DeclareRobustCommand" ||
5080 t.cs() == "DeclareRobustCommandx" ||
5081 t.cs() == "newcommand" ||
5082 t.cs() == "newcommandx" ||
5083 t.cs() == "providecommand" ||
5084 t.cs() == "providecommandx" ||
5085 t.cs() == "renewcommand" ||
5086 t.cs() == "renewcommandx") {
5087 // DeclareRobustCommand, DeclareRobustCommandx,
5088 // providecommand and providecommandx could be handled
5089 // by parse_command(), but we need to call
5090 // add_known_command() here.
5091 string name = t.asInput();
5092 if (p.next_token().asInput() == "*") {
5093 // Starred form. Eat '*'
5097 string const command = p.verbatim_item();
5098 string const opt1 = p.getFullOpt();
5099 string const opt2 = p.getFullOpt();
5100 add_known_command(command, opt1, !opt2.empty());
5101 string const ert = name + '{' + command + '}' +
5103 '{' + p.verbatim_item() + '}';
5105 if (t.cs() == "DeclareRobustCommand" ||
5106 t.cs() == "DeclareRobustCommandx" ||
5107 t.cs() == "providecommand" ||
5108 t.cs() == "providecommandx" ||
5109 name[name.length()-1] == '*')
5110 output_ert_inset(os, ert, context);
5112 context.check_layout(os);
5113 begin_inset(os, "FormulaMacro");
5120 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5121 // let could be handled by parse_command(),
5122 // but we need to call add_known_command() here.
5123 string ert = t.asInput();
5126 if (p.next_token().cat() == catBegin) {
5127 name = p.verbatim_item();
5128 ert += '{' + name + '}';
5130 name = p.verbatim_item();
5135 if (p.next_token().cat() == catBegin) {
5136 command = p.verbatim_item();
5137 ert += '{' + command + '}';
5139 command = p.verbatim_item();
5142 // If command is known, make name known too, to parse
5143 // its arguments correctly. For this reason we also
5144 // have commands in syntax.default that are hardcoded.
5145 CommandMap::iterator it = known_commands.find(command);
5146 if (it != known_commands.end())
5147 known_commands[t.asInput()] = it->second;
5148 output_ert_inset(os, ert, context);
5152 if (t.cs() == "hspace" || t.cs() == "vspace") {
5155 string name = t.asInput();
5156 string const length = p.verbatim_item();
5159 bool valid = splitLatexLength(length, valstring, unit);
5160 bool known_hspace = false;
5161 bool known_vspace = false;
5162 bool known_unit = false;
5165 istringstream iss(valstring);
5168 if (t.cs()[0] == 'h') {
5169 if (unit == "\\fill") {
5174 known_hspace = true;
5177 if (unit == "\\smallskipamount") {
5179 known_vspace = true;
5180 } else if (unit == "\\medskipamount") {
5182 known_vspace = true;
5183 } else if (unit == "\\bigskipamount") {
5185 known_vspace = true;
5186 } else if (unit == "\\fill") {
5188 known_vspace = true;
5192 if (!known_hspace && !known_vspace) {
5193 switch (unitFromString(unit)) {
5209 //unitFromString(unit) fails for relative units like Length::PCW
5210 // therefore handle them separately
5211 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5212 || unit == "\\textwidth" || unit == "\\linewidth"
5213 || unit == "\\textheight" || unit == "\\paperheight"
5214 || unit == "\\baselineskip")
5222 // check for glue lengths
5223 bool is_gluelength = false;
5224 string gluelength = length;
5225 string::size_type i = length.find(" minus");
5226 if (i == string::npos) {
5227 i = length.find(" plus");
5228 if (i != string::npos)
5229 is_gluelength = true;
5231 is_gluelength = true;
5232 // if yes transform "9xx minus 8yy plus 7zz"
5234 if (is_gluelength) {
5235 i = gluelength.find(" minus");
5236 if (i != string::npos)
5237 gluelength.replace(i, 7, "-");
5238 i = gluelength.find(" plus");
5239 if (i != string::npos)
5240 gluelength.replace(i, 6, "+");
5243 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5244 // Literal horizontal length or known variable
5245 context.check_layout(os);
5246 begin_inset(os, "space ");
5254 if (known_unit && !known_hspace)
5255 os << "\n\\length " << translate_len(length);
5257 os << "\n\\length " << gluelength;
5259 } else if (known_unit || known_vspace || is_gluelength) {
5260 // Literal vertical length or known variable
5261 context.check_layout(os);
5262 begin_inset(os, "VSpace ");
5265 if (known_unit && !known_vspace)
5266 os << translate_len(length);
5273 // LyX can't handle other length variables in Inset VSpace/space
5278 output_ert_inset(os, name + '{' + unit + '}', context);
5279 else if (value == -1.0)
5280 output_ert_inset(os, name + "{-" + unit + '}', context);
5282 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5284 output_ert_inset(os, name + '{' + length + '}', context);
5289 // The single '=' is meant here.
5290 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5294 context.check_layout(os);
5295 docstring const name = newinsetlayout->name();
5296 bool const caption = name.find(from_ascii("Caption:")) == 0;
5298 // Already done for floating minted listings.
5299 if (minted_float.empty()) {
5300 begin_inset(os, "Caption ");
5301 os << to_utf8(name.substr(8)) << '\n';
5304 begin_inset(os, "Flex ");
5305 os << to_utf8(name) << '\n'
5306 << "status collapsed\n";
5308 if (!minted_float.empty()) {
5309 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5310 } else if (newinsetlayout->isPassThru()) {
5311 // set catcodes to verbatim early, just in case.
5312 p.setCatcodes(VERBATIM_CATCODES);
5313 string delim = p.get_token().asInput();
5315 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5316 //FIXME: handle error condition
5317 string const arg = p.verbatimStuff("}").second;
5318 Context newcontext(true, context.textclass);
5319 if (newinsetlayout->forcePlainLayout())
5320 newcontext.layout = &context.textclass.plainLayout();
5321 output_ert(os, arg, newcontext);
5323 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5326 // Minted caption insets are not closed here because
5327 // we collect everything into the caption.
5328 if (minted_float.empty())
5333 if (t.cs() == "includepdf") {
5335 string const arg = p.getArg('[', ']');
5336 map<string, string> opts;
5337 vector<string> keys;
5338 split_map(arg, opts, keys);
5339 string name = normalize_filename(p.verbatim_item());
5340 string const path = getMasterFilePath(true);
5341 // We want to preserve relative / absolute filenames,
5342 // therefore path is only used for testing
5343 if (!makeAbsPath(name, path).exists()) {
5344 // The file extension is probably missing.
5345 // Now try to find it out.
5346 char const * const pdfpages_format[] = {"pdf", 0};
5347 string const pdftex_name =
5348 find_file(name, path, pdfpages_format);
5349 if (!pdftex_name.empty()) {
5354 FileName const absname = makeAbsPath(name, path);
5355 if (absname.exists())
5357 fix_child_filename(name);
5358 copy_file(absname, name);
5360 cerr << "Warning: Could not find file '"
5361 << name << "'." << endl;
5363 context.check_layout(os);
5364 begin_inset(os, "External\n\ttemplate ");
5365 os << "PDFPages\n\tfilename "
5367 // parse the options
5368 if (opts.find("pages") != opts.end())
5369 os << "\textra LaTeX \"pages="
5370 << opts["pages"] << "\"\n";
5371 if (opts.find("angle") != opts.end())
5372 os << "\trotateAngle "
5373 << opts["angle"] << '\n';
5374 if (opts.find("origin") != opts.end()) {
5376 string const opt = opts["origin"];
5377 if (opt == "tl") ss << "topleft";
5378 if (opt == "bl") ss << "bottomleft";
5379 if (opt == "Bl") ss << "baselineleft";
5380 if (opt == "c") ss << "center";
5381 if (opt == "tc") ss << "topcenter";
5382 if (opt == "bc") ss << "bottomcenter";
5383 if (opt == "Bc") ss << "baselinecenter";
5384 if (opt == "tr") ss << "topright";
5385 if (opt == "br") ss << "bottomright";
5386 if (opt == "Br") ss << "baselineright";
5387 if (!ss.str().empty())
5388 os << "\trotateOrigin " << ss.str() << '\n';
5390 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5392 if (opts.find("width") != opts.end())
5394 << translate_len(opts["width"]) << '\n';
5395 if (opts.find("height") != opts.end())
5397 << translate_len(opts["height"]) << '\n';
5398 if (opts.find("keepaspectratio") != opts.end())
5399 os << "\tkeepAspectRatio\n";
5401 context.check_layout(os);
5402 registerExternalTemplatePackages("PDFPages");
5406 if (t.cs() == "loadgame") {
5408 string name = normalize_filename(p.verbatim_item());
5409 string const path = getMasterFilePath(true);
5410 // We want to preserve relative / absolute filenames,
5411 // therefore path is only used for testing
5412 if (!makeAbsPath(name, path).exists()) {
5413 // The file extension is probably missing.
5414 // Now try to find it out.
5415 char const * const lyxskak_format[] = {"fen", 0};
5416 string const lyxskak_name =
5417 find_file(name, path, lyxskak_format);
5418 if (!lyxskak_name.empty())
5419 name = lyxskak_name;
5421 FileName const absname = makeAbsPath(name, path);
5422 if (absname.exists())
5424 fix_child_filename(name);
5425 copy_file(absname, name);
5427 cerr << "Warning: Could not find file '"
5428 << name << "'." << endl;
5429 context.check_layout(os);
5430 begin_inset(os, "External\n\ttemplate ");
5431 os << "ChessDiagram\n\tfilename "
5434 context.check_layout(os);
5435 // after a \loadgame follows a \showboard
5436 if (p.get_token().asInput() == "showboard")
5438 registerExternalTemplatePackages("ChessDiagram");
5442 // try to see whether the string is in unicodesymbols
5443 // Only use text mode commands, since we are in text mode here,
5444 // and math commands may be invalid (bug 6797)
5445 string name = t.asInput();
5446 // handle the dingbats, cyrillic and greek
5447 if (name == "\\ding" || name == "\\textcyr" ||
5448 (name == "\\textgreek" && !preamble.usePolyglossia()))
5449 name = name + '{' + p.getArg('{', '}') + '}';
5450 // handle the ifsym characters
5451 else if (name == "\\textifsymbol") {
5452 string const optif = p.getFullOpt();
5453 string const argif = p.getArg('{', '}');
5454 name = name + optif + '{' + argif + '}';
5456 // handle the \ascii characters
5457 // the case of \ascii within braces, as LyX outputs it, is already
5458 // handled for t.cat() == catBegin
5459 else if (name == "\\ascii") {
5460 // the code is "\asci\xxx"
5461 name = "{" + name + p.get_token().asInput() + "}";
5464 // handle some TIPA special characters
5465 else if (preamble.isPackageUsed("tipa")) {
5466 if (name == "\\s") {
5467 // fromLaTeXCommand() does not yet
5468 // recognize tipa short cuts
5469 name = "\\textsyllabic";
5470 } else if (name == "\\=" &&
5471 p.next_token().asInput() == "*") {
5472 // fromLaTeXCommand() does not yet
5473 // recognize tipa short cuts
5475 name = "\\textsubbar";
5476 } else if (name == "\\textdoublevertline") {
5477 // FIXME: This is not correct,
5478 // \textvertline is higher than \textbardbl
5479 name = "\\textbardbl";
5481 } else if (name == "\\!" ) {
5482 if (p.next_token().asInput() == "b") {
5483 p.get_token(); // eat 'b'
5486 } else if (p.next_token().asInput() == "d") {
5490 } else if (p.next_token().asInput() == "g") {
5494 } else if (p.next_token().asInput() == "G") {
5496 name = "\\texthtscg";
5498 } else if (p.next_token().asInput() == "j") {
5500 name = "\\texthtbardotlessj";
5502 } else if (p.next_token().asInput() == "o") {
5504 name = "\\textbullseye";
5507 } else if (name == "\\*" ) {
5508 if (p.next_token().asInput() == "k") {
5510 name = "\\textturnk";
5512 } else if (p.next_token().asInput() == "r") {
5513 p.get_token(); // eat 'b'
5514 name = "\\textturnr";
5516 } else if (p.next_token().asInput() == "t") {
5518 name = "\\textturnt";
5520 } else if (p.next_token().asInput() == "w") {
5522 name = "\\textturnw";
5527 if ((name.size() == 2 &&
5528 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5529 p.next_token().asInput() != "*") ||
5530 is_known(name.substr(1), known_tipa_marks)) {
5531 // name is a command that corresponds to a
5532 // combining character in unicodesymbols.
5533 // Append the argument, fromLaTeXCommand()
5534 // will either convert it to a single
5535 // character or a combining sequence.
5536 name += '{' + p.verbatim_item() + '}';
5538 // now get the character from unicodesymbols
5542 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5543 Encodings::TEXT_CMD, termination, rem, &req));
5545 context.check_layout(os);
5548 output_ert_inset(os, to_utf8(rem), context);
5550 skip_spaces_braces(p);
5551 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5552 preamble.registerAutomaticallyLoadedPackage(*it);
5554 //cerr << "#: " << t << " mode: " << mode << endl;
5555 // heuristic: read up to next non-nested space
5557 string s = t.asInput();
5558 string z = p.verbatim_item();
5559 while (p.good() && z != " " && !z.empty()) {
5560 //cerr << "read: " << z << endl;
5562 z = p.verbatim_item();
5564 cerr << "found ERT: " << s << endl;
5565 output_ert_inset(os, s + ' ', context);
5568 if (t.asInput() == name &&
5569 p.next_token().asInput() == "*") {
5570 // Starred commands like \vspace*{}
5571 p.get_token(); // Eat '*'
5574 if (!parse_command(name, p, os, outer, context))
5575 output_ert_inset(os, name, context);
5581 string guessLanguage(Parser & p, string const & lang)
5583 typedef std::map<std::string, size_t> LangMap;
5584 // map from language names to number of characters
5587 for (char const * const * i = supported_CJK_languages; *i; i++)
5588 used[string(*i)] = 0;
5591 Token const t = p.get_token();
5592 // comments are not counted for any language
5593 if (t.cat() == catComment)
5595 // commands are not counted as well, but we need to detect
5596 // \begin{CJK} and switch encoding if needed
5597 if (t.cat() == catEscape) {
5598 if (t.cs() == "inputencoding") {
5599 string const enc = subst(p.verbatim_item(), "\n", " ");
5600 p.setEncoding(enc, Encoding::inputenc);
5603 if (t.cs() != "begin")
5606 // Non-CJK content is counted for lang.
5607 // We do not care about the real language here:
5608 // If we have more non-CJK contents than CJK contents,
5609 // we simply use the language that was specified as
5610 // babel main language.
5611 used[lang] += t.asInput().length();
5614 // Now we are starting an environment
5616 string const name = p.getArg('{', '}');
5617 if (name != "CJK") {
5621 // It is a CJK environment
5623 /* name = */ p.getArg('{', '}');
5624 string const encoding = p.getArg('{', '}');
5625 /* mapping = */ p.getArg('{', '}');
5626 string const encoding_old = p.getEncoding();
5627 char const * const * const where =
5628 is_known(encoding, supported_CJK_encodings);
5630 p.setEncoding(encoding, Encoding::CJK);
5632 p.setEncoding("UTF-8");
5633 string const text = p.ertEnvironment("CJK");
5634 p.setEncoding(encoding_old);
5637 // ignore contents in unknown CJK encoding
5640 // the language of the text
5642 supported_CJK_languages[where - supported_CJK_encodings];
5643 used[cjk] += text.length();
5645 LangMap::const_iterator use = used.begin();
5646 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5647 if (it->second > use->second)
5654 void check_comment_bib(ostream & os, Context & context)
5656 if (!need_commentbib)
5658 // We have a bibliography database, but no bibliography with biblatex
5659 // which is completely valid. Insert a bibtex inset in a note.
5660 context.check_layout(os);
5661 begin_inset(os, "Note Note\n");
5662 os << "status open\n";
5663 os << "\\begin_layout Plain Layout\n";
5664 begin_command_inset(os, "bibtex", "bibtex");
5666 for (auto const & bf : preamble.biblatex_bibliographies) {
5667 if (!bibfiles.empty())
5669 bibfiles += normalize_filename(bf);
5671 if (!bibfiles.empty())
5672 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5673 end_inset(os);// Bibtex
5674 os << "\\end_layout\n";
5675 end_inset(os);// Note