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", "textquotedblright", "textquotesingle",
207 /// the same as known_quotes with .lyx names
208 char const * const known_coded_quotes[] = { "qrd", "ard", "ard", "ard",
209 "ald", "ald", "ald", "gls", "gld", "els", "els", "eld",
210 "gld", "eld", "gls", "ers", "ars",
211 "ars", "als", "als", "erd", "qrs", "qrd", 0};
213 /// LaTeX names for font sizes
214 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
215 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
217 /// the same as known_sizes with .lyx names
218 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
219 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
221 /// LaTeX 2.09 names for font families
222 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
224 /// LaTeX names for font families
225 char const * const known_font_families[] = { "rmfamily", "sffamily",
228 /// LaTeX names for font family changing commands
229 char const * const known_text_font_families[] = { "textrm", "textsf",
232 /// The same as known_old_font_families, known_font_families and
233 /// known_text_font_families with .lyx names
234 char const * const known_coded_font_families[] = { "roman", "sans",
237 /// LaTeX 2.09 names for font series
238 char const * const known_old_font_series[] = { "bf", 0};
240 /// LaTeX names for font series
241 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
243 /// LaTeX names for font series changing commands
244 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
246 /// The same as known_old_font_series, known_font_series and
247 /// known_text_font_series with .lyx names
248 char const * const known_coded_font_series[] = { "bold", "medium", 0};
250 /// LaTeX 2.09 names for font shapes
251 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
253 /// LaTeX names for font shapes
254 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
257 /// LaTeX names for font shape changing commands
258 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
261 /// The same as known_old_font_shapes, known_font_shapes and
262 /// known_text_font_shapes with .lyx names
263 char const * const known_coded_font_shapes[] = { "italic", "slanted",
264 "smallcaps", "up", 0};
266 /// Known special characters which need skip_spaces_braces() afterwards
267 char const * const known_special_chars[] = {"ldots",
268 "lyxarrow", "textcompwordmark",
269 "slash", "textasciitilde", "textasciicircum", "textbackslash",
270 "LyX", "TeX", "LaTeXe",
273 /// special characters from known_special_chars which may have a \\protect before
274 char const * const known_special_protect_chars[] = {"LyX", "TeX",
275 "LaTeXe", "LaTeX", 0};
277 /// the same as known_special_chars with .lyx names
278 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
279 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
280 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
281 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
282 "\\SpecialChar LaTeX\n", 0};
285 * Graphics file extensions known by the dvips driver of the graphics package.
286 * These extensions are used to complete the filename of an included
287 * graphics file if it does not contain an extension.
288 * The order must be the same that latex uses to find a file, because we
289 * will use the first extension that matches.
290 * This is only an approximation for the common cases. If we would want to
291 * do it right in all cases, we would need to know which graphics driver is
292 * used and know the extensions of every driver of the graphics package.
294 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
295 "ps.gz", "eps.Z", "ps.Z", 0};
298 * Graphics file extensions known by the pdftex driver of the graphics package.
299 * \sa known_dvips_graphics_formats
301 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
305 * Known file extensions for TeX files as used by \\include.
307 char const * const known_tex_extensions[] = {"tex", 0};
309 /// spaces known by InsetSpace
310 char const * const known_spaces[] = { " ", "space", ",",
311 "thinspace", "quad", "qquad", "enspace", "enskip",
312 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
313 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
314 "upbracefill", "downbracefill", 0};
316 /// the same as known_spaces with .lyx names
317 char const * const known_coded_spaces[] = { "space{}", "space{}",
318 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
319 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
320 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
321 "upbracefill{}", "downbracefill{}", 0};
323 /// known TIPA combining diacritical marks
324 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
325 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
326 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
327 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
328 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
329 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
330 "textsubring", "textsubbar", 0};
332 /// TIPA tones that need special handling
333 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
335 // string to store the float type to be able to determine the type of subfloats
336 string float_type = "";
338 // string to store the float status of minted listings
339 string minted_float = "";
341 // whether a caption has been parsed for a floating minted listing
342 bool minted_float_has_caption = false;
344 // The caption for non-floating minted listings
345 string minted_nonfloat_caption = "";
347 // Characters that have to be escaped by \\ in LaTeX
348 char const * const known_escaped_chars[] = {
349 "&", "_", "$", "%", "#", "^", "{", "}"};
352 /// splits "x=z, y=b" into a map and an ordered keyword vector
353 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
358 keys.resize(v.size());
359 for (size_t i = 0; i < v.size(); ++i) {
360 size_t const pos = v[i].find('=');
361 string const index = trimSpaceAndEol(v[i].substr(0, pos));
362 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
370 * Split a LaTeX length into value and unit.
371 * The latter can be a real unit like "pt", or a latex length variable
372 * like "\textwidth". The unit may contain additional stuff like glue
373 * lengths, but we don't care, because such lengths are ERT anyway.
374 * \returns true if \p value and \p unit are valid.
376 bool splitLatexLength(string const & len, string & value, string & unit)
380 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
381 //'4,5' is a valid LaTeX length number. Change it to '4.5'
382 string const length = subst(len, ',', '.');
383 if (i == string::npos)
386 if (len[0] == '\\') {
387 // We had something like \textwidth without a factor
393 value = trimSpaceAndEol(string(length, 0, i));
397 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
398 if (contains(len, '\\'))
399 unit = trimSpaceAndEol(string(len, i));
401 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
406 /// A simple function to translate a latex length to something LyX can
407 /// understand. Not perfect, but rather best-effort.
408 bool translate_len(string const & length, string & valstring, string & unit)
410 if (!splitLatexLength(length, valstring, unit))
412 // LyX uses percent values
414 istringstream iss(valstring);
419 string const percentval = oss.str();
421 if (unit.empty() || unit[0] != '\\')
423 string::size_type const i = unit.find(' ');
424 string const endlen = (i == string::npos) ? string() : string(unit, i);
425 if (unit == "\\textwidth") {
426 valstring = percentval;
427 unit = "text%" + endlen;
428 } else if (unit == "\\columnwidth") {
429 valstring = percentval;
430 unit = "col%" + endlen;
431 } else if (unit == "\\paperwidth") {
432 valstring = percentval;
433 unit = "page%" + endlen;
434 } else if (unit == "\\linewidth") {
435 valstring = percentval;
436 unit = "line%" + endlen;
437 } else if (unit == "\\paperheight") {
438 valstring = percentval;
439 unit = "pheight%" + endlen;
440 } else if (unit == "\\textheight") {
441 valstring = percentval;
442 unit = "theight%" + endlen;
443 } else if (unit == "\\baselineskip") {
444 valstring = percentval;
445 unit = "baselineskip%" + endlen;
451 /// If we have ambiguous quotation marks, make a smart guess
452 /// based on main quote style
453 string guessQuoteStyle(string in, bool const opening)
456 if (prefixIs(in, "qr")) {// straight quote
458 res = subst(res, "r", "l");
459 } else if (in == "eld") {// ``
460 if (preamble.quotesStyle() == "german")
462 else if (preamble.quotesStyle() == "british")
464 else if (preamble.quotesStyle() == "french")
466 else if (preamble.quotesStyle() == "russian")
468 } else if (in == "erd") {// ''
469 if (preamble.quotesStyle() == "polish")
471 else if (preamble.quotesStyle() == "british")
473 else if (preamble.quotesStyle() == "french")
475 else if (preamble.quotesStyle() == "swedish")
476 res = opening ? "sld" : "srd";
477 } else if (in == "els") {// `
478 if (preamble.quotesStyle() == "german")
480 else if (preamble.quotesStyle() == "british")
482 } else if (in == "ers") {// '
483 if (preamble.quotesStyle() == "polish")
485 else if (preamble.quotesStyle() == "british")
487 else if (preamble.quotesStyle() == "swedish")
488 res = opening ? "sls" : "srs";
489 } else if (in == "ard") {// >>
490 if (preamble.quotesStyle() == "swiss")
492 else if (preamble.quotesStyle() == "french")
494 else if (preamble.quotesStyle() == "russian")
496 } else if (in == "ald") {// <<
497 if (preamble.quotesStyle() == "swiss")
499 else if (preamble.quotesStyle() == "french")
501 else if (preamble.quotesStyle() == "russian")
503 } else if (in == "ars") {// >
504 if (preamble.quotesStyle() == "swiss")
506 } else if (in == "als") {// <
507 if (preamble.quotesStyle() == "swiss")
509 } else if (in == "gld") {// ,,
510 if (preamble.quotesStyle() == "polish")
512 else if (preamble.quotesStyle() == "russian")
514 } else if (in == "gls") {// ,
515 if (preamble.quotesStyle() == "polish")
525 string translate_len(string const & length)
529 if (translate_len(length, value, unit))
531 // If the input is invalid, return what we have.
539 * Translates a LaTeX length into \p value, \p unit and
540 * \p special parts suitable for a box inset.
541 * The difference from translate_len() is that a box inset knows about
542 * some special "units" that are stored in \p special.
544 void translate_box_len(string const & length, string & value, string & unit, string & special)
546 if (translate_len(length, value, unit)) {
547 if (unit == "\\height" || unit == "\\depth" ||
548 unit == "\\totalheight" || unit == "\\width") {
549 special = unit.substr(1);
550 // The unit is not used, but LyX requires a dummy setting
562 void begin_inset(ostream & os, string const & name)
564 os << "\n\\begin_inset " << name;
568 void begin_command_inset(ostream & os, string const & name,
569 string const & latexname)
571 begin_inset(os, "CommandInset ");
572 os << name << "\nLatexCommand " << latexname << '\n';
576 void end_inset(ostream & os)
578 os << "\n\\end_inset\n\n";
582 bool skip_braces(Parser & p)
584 if (p.next_token().cat() != catBegin)
587 if (p.next_token().cat() == catEnd) {
596 /// replace LaTeX commands in \p s from the unicodesymbols file with their
598 pair<bool, docstring> convert_unicodesymbols(docstring s)
602 for (size_t i = 0; i < s.size();) {
611 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
612 Encodings::TEXT_CMD, termination, rem, &req));
613 set<string>::const_iterator it = req.begin();
614 set<string>::const_iterator en = req.end();
615 for (; it != en; ++it)
616 preamble.registerAutomaticallyLoadedPackage(*it);
619 if (s.empty() || s[0] != '\\')
623 for (auto const & c : known_escaped_chars)
624 if (prefixIs(s, from_ascii("\\") + c))
629 return make_pair(res, os.str());
633 /// try to convert \p s to a valid InsetCommand argument
634 /// return whether this succeeded. If not, these command insets
635 /// get the "literate" flag.
636 pair<bool, string> convert_latexed_command_inset_arg(string s)
638 bool success = false;
640 // since we don't know the input encoding we can't use from_utf8
641 pair<bool, docstring> res = convert_unicodesymbols(from_ascii(s));
643 s = to_utf8(res.second);
645 // LyX cannot handle newlines in a latex command
646 return make_pair(success, subst(s, "\n", " "));
649 /// try to convert \p s to a valid InsetCommand argument
650 /// without trying to recode macros.
651 string convert_literate_command_inset_arg(string s)
653 // LyX cannot handle newlines in a latex command
654 return subst(s, "\n", " ");
657 void output_ert(ostream & os, string const & s, Context & context)
659 context.check_layout(os);
660 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
662 os << "\n\\backslash\n";
663 else if (*it == '\n') {
664 context.new_paragraph(os);
665 context.check_layout(os);
669 context.check_end_layout(os);
673 void output_ert_inset(ostream & os, string const & s, Context & context)
675 // We must have a valid layout before outputting the ERT inset.
676 context.check_layout(os);
677 Context newcontext(true, context.textclass);
678 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
679 if (layout.forcePlainLayout())
680 newcontext.layout = &context.textclass.plainLayout();
681 begin_inset(os, "ERT");
682 os << "\nstatus collapsed\n";
683 output_ert(os, s, newcontext);
688 void output_comment(Parser & p, ostream & os, string const & s,
691 if (p.next_token().cat() == catNewline)
692 output_ert_inset(os, '%' + s, context);
694 output_ert_inset(os, '%' + s + '\n', context);
698 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
700 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
703 if (checkModule(name, command))
704 return findLayoutWithoutModule(textclass, name, command);
709 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
711 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
714 if (checkModule(name, command))
715 return findInsetLayoutWithoutModule(textclass, name, command);
720 void eat_whitespace(Parser &, ostream &, Context &, bool);
724 * Skips whitespace and braces.
725 * This should be called after a command has been parsed that is not put into
726 * ERT, and where LyX adds "{}" if needed.
728 void skip_spaces_braces(Parser & p, bool keepws = false)
730 /* The following four examples produce the same typeset output and
731 should be handled by this function:
739 // Unfortunately we need to skip comments, too.
740 // We can't use eat_whitespace since writing them after the {}
741 // results in different output in some cases.
742 bool const skipped_spaces = p.skip_spaces(true);
743 bool const skipped_braces = skip_braces(p);
744 if (keepws && skipped_spaces && !skipped_braces)
745 // put back the space (it is better handled by check_space)
746 p.unskip_spaces(true);
750 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
751 Context & context, Layout::LaTeXArgMap const & latexargs)
754 context.check_layout(os);
759 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
760 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
761 for (; lait != laend; ++lait) {
763 eat_whitespace(p, os, context, false);
764 if (lait->second.mandatory) {
765 if (p.next_token().cat() != catBegin)
767 p.get_token(); // eat '{'
769 context.check_layout(os);
772 begin_inset(os, "Argument ");
775 os << i << "\nstatus collapsed\n\n";
776 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
779 if (p.next_token().cat() == catEscape ||
780 p.next_token().character() != '[')
782 p.get_token(); // eat '['
784 context.check_layout(os);
787 begin_inset(os, "Argument ");
790 os << i << "\nstatus collapsed\n\n";
791 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
794 eat_whitespace(p, os, context, false);
799 void output_command_layout(ostream & os, Parser & p, bool outer,
800 Context & parent_context,
801 Layout const * newlayout)
803 TeXFont const oldFont = parent_context.font;
804 // save the current font size
805 string const size = oldFont.size;
806 // reset the font size to default, because the font size switches
807 // don't affect section headings and the like
808 parent_context.font.size = Context::normalfont.size;
809 // we only need to write the font change if we have an open layout
810 if (!parent_context.atParagraphStart())
811 output_font_change(os, oldFont, parent_context.font);
812 parent_context.check_end_layout(os);
813 Context context(true, parent_context.textclass, newlayout,
814 parent_context.layout, parent_context.font);
815 if (parent_context.deeper_paragraph) {
816 // We are beginning a nested environment after a
817 // deeper paragraph inside the outer list environment.
818 // Therefore we don't need to output a "begin deeper".
819 context.need_end_deeper = true;
821 context.check_deeper(os);
822 output_arguments(os, p, outer, true, false, context,
823 context.layout->latexargs());
824 parse_text(p, os, FLAG_ITEM, outer, context);
825 output_arguments(os, p, outer, false, true, context,
826 context.layout->postcommandargs());
827 context.check_end_layout(os);
828 if (parent_context.deeper_paragraph) {
829 // We must suppress the "end deeper" because we
830 // suppressed the "begin deeper" above.
831 context.need_end_deeper = false;
833 context.check_end_deeper(os);
834 // We don't need really a new paragraph, but
835 // we must make sure that the next item gets a \begin_layout.
836 parent_context.new_paragraph(os);
837 // Set the font size to the original value. No need to output it here
838 // (Context::begin_layout() will do that if needed)
839 parent_context.font.size = size;
844 * Output a space if necessary.
845 * This function gets called for every whitespace token.
847 * We have three cases here:
848 * 1. A space must be suppressed. Example: The lyxcode case below
849 * 2. A space may be suppressed. Example: Spaces before "\par"
850 * 3. A space must not be suppressed. Example: A space between two words
852 * We currently handle only 1. and 3 and from 2. only the case of
853 * spaces before newlines as a side effect.
855 * 2. could be used to suppress as many spaces as possible. This has two effects:
856 * - Reimporting LyX generated LaTeX files changes almost no whitespace
857 * - Superflous whitespace from non LyX generated LaTeX files is removed.
858 * The drawback is that the logic inside the function becomes
859 * complicated, and that is the reason why it is not implemented.
861 void check_space(Parser & p, ostream & os, Context & context)
863 Token const next = p.next_token();
864 Token const curr = p.curr_token();
865 // A space before a single newline and vice versa must be ignored
866 // LyX emits a newline before \end{lyxcode}.
867 // This newline must be ignored,
868 // otherwise LyX will add an additional protected space.
869 if (next.cat() == catSpace ||
870 next.cat() == catNewline ||
871 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
874 context.check_layout(os);
880 * Parse all arguments of \p command
882 void parse_arguments(string const & command,
883 vector<ArgumentType> const & template_arguments,
884 Parser & p, ostream & os, bool outer, Context & context)
886 string ert = command;
887 size_t no_arguments = template_arguments.size();
888 for (size_t i = 0; i < no_arguments; ++i) {
889 switch (template_arguments[i]) {
892 // This argument contains regular LaTeX
893 output_ert_inset(os, ert + '{', context);
894 eat_whitespace(p, os, context, false);
895 if (template_arguments[i] == required)
896 parse_text(p, os, FLAG_ITEM, outer, context);
898 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
902 // This argument consists only of a single item.
903 // The presence of '{' or not must be preserved.
905 if (p.next_token().cat() == catBegin)
906 ert += '{' + p.verbatim_item() + '}';
908 ert += p.verbatim_item();
912 // This argument may contain special characters
913 ert += '{' + p.verbatim_item() + '}';
917 // true because we must not eat whitespace
918 // if an optional arg follows we must not strip the
919 // brackets from this one
920 if (i < no_arguments - 1 &&
921 template_arguments[i+1] == optional)
922 ert += p.getFullOpt(true);
924 ert += p.getOpt(true);
928 output_ert_inset(os, ert, context);
933 * Check whether \p command is a known command. If yes,
934 * handle the command with all arguments.
935 * \return true if the command was parsed, false otherwise.
937 bool parse_command(string const & command, Parser & p, ostream & os,
938 bool outer, Context & context)
940 if (known_commands.find(command) != known_commands.end()) {
941 parse_arguments(command, known_commands[command], p, os,
949 /// Parses a minipage or parbox
950 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
951 unsigned inner_flags, bool outer, Context & parent_context,
952 string const & outer_type, string const & special,
953 string inner_type, string const & frame_color,
954 string const & background_color)
958 string hor_pos = "l";
959 // We need to set the height to the LaTeX default of 1\\totalheight
960 // for the case when no height argument is given
961 string height_value = "1";
962 string height_unit = "in";
963 string height_special = "totalheight";
968 string width_special = "none";
969 string thickness = "0.4pt";
970 if (!fboxrule.empty())
971 thickness = fboxrule;
975 if (!fboxsep.empty())
976 separation = fboxsep;
980 if (!shadow_size.empty())
981 shadowsize = shadow_size;
984 string framecolor = "black";
985 string backgroundcolor = "none";
986 if (!frame_color.empty())
987 framecolor = frame_color;
988 if (!background_color.empty())
989 backgroundcolor = background_color;
990 // if there is a color box around the \begin statements have not yet been parsed
992 if (!frame_color.empty() || !background_color.empty()) {
993 eat_whitespace(p, os, parent_context, false);
994 p.get_token().asInput(); // the '{'
996 if (p.next_token().asInput() == "\\begin") {
997 p.get_token().asInput();
999 inner_type = "minipage";
1000 inner_flags = FLAG_END;
1001 active_environments.push_back("minipage");
1004 else if (p.next_token().asInput() == "\\parbox") {
1005 p.get_token().asInput();
1006 inner_type = "parbox";
1007 inner_flags = FLAG_ITEM;
1010 else if (p.next_token().asInput() == "\\makebox") {
1011 p.get_token().asInput();
1012 inner_type = "makebox";
1013 inner_flags = FLAG_ITEM;
1015 // in case there is just \colorbox{color}{text}
1018 inner_type = "makebox";
1019 inner_flags = FLAG_BRACE_LAST;
1024 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
1026 if (!inner_type.empty() && p.hasOpt()) {
1027 if (inner_type != "makebox")
1028 position = p.getArg('[', ']');
1030 latex_width = p.getArg('[', ']');
1031 translate_box_len(latex_width, width_value, width_unit, width_special);
1034 if (position != "t" && position != "c" && position != "b") {
1035 cerr << "invalid position " << position << " for "
1036 << inner_type << endl;
1040 if (inner_type != "makebox") {
1041 latex_height = p.getArg('[', ']');
1042 translate_box_len(latex_height, height_value, height_unit, height_special);
1044 string const opt = p.getArg('[', ']');
1047 if (hor_pos != "l" && hor_pos != "c" &&
1048 hor_pos != "r" && hor_pos != "s") {
1049 cerr << "invalid hor_pos " << hor_pos
1050 << " for " << inner_type << endl;
1057 inner_pos = p.getArg('[', ']');
1058 if (inner_pos != "c" && inner_pos != "t" &&
1059 inner_pos != "b" && inner_pos != "s") {
1060 cerr << "invalid inner_pos "
1061 << inner_pos << " for "
1062 << inner_type << endl;
1063 inner_pos = position;
1067 if (inner_type == "makebox")
1071 if (inner_type.empty()) {
1072 if (special.empty() && outer_type != "framebox")
1073 latex_width = "1\\columnwidth";
1076 latex_width = p2.getArg('[', ']');
1077 string const opt = p2.getArg('[', ']');
1080 if (hor_pos != "l" && hor_pos != "c" &&
1081 hor_pos != "r" && hor_pos != "s") {
1082 cerr << "invalid hor_pos " << hor_pos
1083 << " for " << outer_type << endl;
1087 if (outer_type == "framebox")
1091 } else if (inner_type != "makebox")
1092 latex_width = p.verbatim_item();
1093 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1094 // as this is LyX's standard for such cases (except for makebox)
1095 // \framebox is more special and handled below
1096 if (latex_width.empty() && inner_type != "makebox"
1097 && outer_type != "framebox")
1098 latex_width = "1\\columnwidth";
1100 translate_len(latex_width, width_value, width_unit);
1102 bool shadedparbox = false;
1103 if (inner_type == "shaded") {
1104 eat_whitespace(p, os, parent_context, false);
1105 if (outer_type == "parbox") {
1107 if (p.next_token().cat() == catBegin)
1109 eat_whitespace(p, os, parent_context, false);
1110 shadedparbox = true;
1115 // If we already read the inner box we have to push the inner env
1116 if (!outer_type.empty() && !inner_type.empty() &&
1117 (inner_flags & FLAG_END))
1118 active_environments.push_back(inner_type);
1119 bool use_ert = false;
1120 if (!outer_type.empty() && !inner_type.empty()) {
1121 // Look whether there is some content after the end of the
1122 // inner box, but before the end of the outer box.
1123 // If yes, we need to output ERT.
1125 if (inner_flags & FLAG_END)
1126 p.ertEnvironment(inner_type);
1129 p.skip_spaces(true);
1130 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1131 if ((outer_env && p.next_token().asInput() != "\\end") ||
1132 (!outer_env && p.next_token().cat() != catEnd)) {
1133 // something is between the end of the inner box and
1134 // the end of the outer box, so we need to use ERT.
1142 if (!outer_type.empty()) {
1143 if (outer_flags & FLAG_END)
1144 ss << "\\begin{" << outer_type << '}';
1146 ss << '\\' << outer_type << '{';
1147 if (!special.empty())
1151 if (!inner_type.empty()) {
1152 if (inner_type != "shaded") {
1153 if (inner_flags & FLAG_END)
1154 ss << "\\begin{" << inner_type << '}';
1156 ss << '\\' << inner_type;
1158 if (!position.empty())
1159 ss << '[' << position << ']';
1160 if (!latex_height.empty())
1161 ss << '[' << latex_height << ']';
1162 if (!inner_pos.empty())
1163 ss << '[' << inner_pos << ']';
1164 ss << '{' << latex_width << '}';
1165 if (!(inner_flags & FLAG_END))
1168 if (inner_type == "shaded")
1169 ss << "\\begin{shaded}";
1170 output_ert_inset(os, ss.str(), parent_context);
1171 if (!inner_type.empty()) {
1172 parse_text(p, os, inner_flags, outer, parent_context);
1173 if (inner_flags & FLAG_END)
1174 output_ert_inset(os, "\\end{" + inner_type + '}',
1177 output_ert_inset(os, "}", parent_context);
1179 if (!outer_type.empty()) {
1180 // If we already read the inner box we have to pop
1182 if (!inner_type.empty() && (inner_flags & FLAG_END))
1183 active_environments.pop_back();
1185 // Ensure that the end of the outer box is parsed correctly:
1186 // The opening brace has been eaten by parse_outer_box()
1187 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1188 outer_flags &= ~FLAG_ITEM;
1189 outer_flags |= FLAG_BRACE_LAST;
1191 parse_text(p, os, outer_flags, outer, parent_context);
1192 if (outer_flags & FLAG_END)
1193 output_ert_inset(os, "\\end{" + outer_type + '}',
1196 output_ert_inset(os, "}", parent_context);
1199 // LyX does not like empty positions, so we have
1200 // to set them to the LaTeX default values here.
1201 if (position.empty())
1203 if (inner_pos.empty())
1204 inner_pos = position;
1205 parent_context.check_layout(os);
1206 begin_inset(os, "Box ");
1207 if (outer_type == "framed")
1209 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1211 else if (outer_type == "shadowbox")
1212 os << "Shadowbox\n";
1213 else if ((outer_type == "shaded" && inner_type.empty()) ||
1214 (outer_type == "minipage" && inner_type == "shaded") ||
1215 (outer_type == "parbox" && inner_type == "shaded")) {
1217 preamble.registerAutomaticallyLoadedPackage("color");
1218 } else if (outer_type == "doublebox")
1219 os << "Doublebox\n";
1220 else if (outer_type.empty() || outer_type == "mbox")
1221 os << "Frameless\n";
1223 os << outer_type << '\n';
1224 os << "position \"" << position << "\"\n";
1225 os << "hor_pos \"" << hor_pos << "\"\n";
1226 if (outer_type == "mbox")
1227 os << "has_inner_box 1\n";
1228 else if (!frame_color.empty() && inner_type == "makebox")
1229 os << "has_inner_box 0\n";
1231 os << "has_inner_box " << !inner_type.empty() << "\n";
1232 os << "inner_pos \"" << inner_pos << "\"\n";
1233 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1235 if (outer_type == "mbox")
1236 os << "use_makebox 1\n";
1237 else if (!frame_color.empty())
1238 os << "use_makebox 0\n";
1240 os << "use_makebox " << (inner_type == "makebox") << '\n';
1241 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1242 os << "width \"\"\n";
1243 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1244 else if (contains(width_unit, '\\'))
1245 os << "width \"" << width_value << "in" << "\"\n";
1247 os << "width \"" << width_value << width_unit << "\"\n";
1248 if (contains(width_unit, '\\')) {
1249 width_unit.erase (0,1); // remove the leading '\'
1250 os << "special \"" << width_unit << "\"\n";
1252 os << "special \"" << width_special << "\"\n";
1253 if (contains(height_unit, '\\'))
1254 os << "height \"" << height_value << "in" << "\"\n";
1256 os << "height \"" << height_value << height_unit << "\"\n";
1257 os << "height_special \"" << height_special << "\"\n";
1258 os << "thickness \"" << thickness << "\"\n";
1259 os << "separation \"" << separation << "\"\n";
1260 os << "shadowsize \"" << shadowsize << "\"\n";
1261 os << "framecolor \"" << framecolor << "\"\n";
1262 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1263 os << "status open\n\n";
1265 // Unfortunately we can't use parse_text_in_inset:
1266 // InsetBox::forcePlainLayout() is hard coded and does not
1267 // use the inset layout. Apart from that do we call parse_text
1268 // up to two times, but need only one check_end_layout.
1269 bool const forcePlainLayout =
1270 (!inner_type.empty() || inner_type == "makebox") &&
1271 outer_type != "shaded" && outer_type != "framed";
1272 Context context(true, parent_context.textclass);
1273 if (forcePlainLayout)
1274 context.layout = &context.textclass.plainLayout();
1276 context.font = parent_context.font;
1278 // If we have no inner box the contents will be read with the outer box
1279 if (!inner_type.empty())
1280 parse_text(p, os, inner_flags, outer, context);
1282 // Ensure that the end of the outer box is parsed correctly:
1283 // The opening brace has been eaten by parse_outer_box()
1284 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1285 outer_flags &= ~FLAG_ITEM;
1286 outer_flags |= FLAG_BRACE_LAST;
1289 // Find end of outer box, output contents if inner_type is
1290 // empty and output possible comments
1291 if (!outer_type.empty()) {
1292 // If we already read the inner box we have to pop
1294 if (!inner_type.empty() && (inner_flags & FLAG_END))
1295 active_environments.pop_back();
1296 // This does not output anything but comments if
1297 // inner_type is not empty (see use_ert)
1298 parse_text(p, os, outer_flags, outer, context);
1301 context.check_end_layout(os);
1303 #ifdef PRESERVE_LAYOUT
1304 // LyX puts a % after the end of the minipage
1305 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1307 //output_comment(p, os, "dummy", parent_context);
1310 parent_context.new_paragraph(os);
1312 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1313 //output_comment(p, os, "dummy", parent_context);
1316 // We add a protected space if something real follows
1317 if (p.good() && p.next_token().cat() != catComment) {
1318 begin_inset(os, "space ~\n");
1324 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1325 active_environments.pop_back();
1326 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1327 // in this case we have to eat the the closing brace of the color box
1328 p.get_token().asInput(); // the '}'
1330 if (p.next_token().asInput() == "}") {
1331 // in this case we assume that the closing brace is from the box settings
1332 // therefore reset these values for the next box
1338 // all boxes except of Frameless and Shaded require calc
1339 if (!(outer_type.empty() || outer_type == "mbox") &&
1340 !((outer_type == "shaded" && inner_type.empty()) ||
1341 (outer_type == "minipage" && inner_type == "shaded") ||
1342 (outer_type == "parbox" && inner_type == "shaded")))
1343 preamble.registerAutomaticallyLoadedPackage("calc");
1347 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1348 Context & parent_context, string const & outer_type,
1349 string const & special)
1351 eat_whitespace(p, os, parent_context, false);
1352 if (flags & FLAG_ITEM) {
1354 if (p.next_token().cat() == catBegin)
1357 cerr << "Warning: Ignoring missing '{' after \\"
1358 << outer_type << '.' << endl;
1359 eat_whitespace(p, os, parent_context, false);
1362 unsigned int inner_flags = 0;
1364 if (outer_type == "minipage" || outer_type == "parbox") {
1365 p.skip_spaces(true);
1366 while (p.hasOpt()) {
1368 p.skip_spaces(true);
1371 p.skip_spaces(true);
1372 if (outer_type == "parbox") {
1374 if (p.next_token().cat() == catBegin)
1376 p.skip_spaces(true);
1379 if (outer_type == "shaded" || outer_type == "mbox") {
1380 // These boxes never have an inner box
1382 } else if (p.next_token().asInput() == "\\parbox") {
1383 inner = p.get_token().cs();
1384 inner_flags = FLAG_ITEM;
1385 } else if (p.next_token().asInput() == "\\begin") {
1386 // Is this a minipage or shaded box?
1389 inner = p.getArg('{', '}');
1391 if (inner == "minipage" || inner == "shaded")
1392 inner_flags = FLAG_END;
1397 if (inner_flags == FLAG_END) {
1398 if (inner != "shaded")
1402 eat_whitespace(p, os, parent_context, false);
1404 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1405 outer_type, special, inner, "", "");
1407 if (inner_flags == FLAG_ITEM) {
1409 eat_whitespace(p, os, parent_context, false);
1411 parse_box(p, os, flags, inner_flags, outer, parent_context,
1412 outer_type, special, inner, "", "");
1417 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1418 bool in_line, bool use_minted)
1420 parent_context.check_layout(os);
1421 begin_inset(os, "listings\n");
1422 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1424 while ((i = arg.find(", ")) != string::npos
1425 || (i = arg.find(",\t")) != string::npos)
1426 arg.erase(i + 1, 1);
1429 string const language = p.getArg('{', '}');
1430 p.skip_spaces(true);
1431 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1432 if (!minted_float.empty()) {
1433 arg += string(arg.empty() ? "" : ",") + minted_float;
1434 minted_nonfloat_caption.clear();
1438 os << "lstparams " << '"' << arg << '"' << '\n';
1439 if (arg.find("\\color") != string::npos)
1440 preamble.registerAutomaticallyLoadedPackage("color");
1443 os << "inline true\n";
1445 os << "inline false\n";
1446 os << "status collapsed\n";
1447 Context context(true, parent_context.textclass);
1448 context.layout = &parent_context.textclass.plainLayout();
1449 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1450 minted_nonfloat_caption.erase(0,3);
1451 os << "\n\\begin_layout Plain Layout\n";
1452 begin_inset(os, "Caption Standard\n");
1453 Context newcontext(true, context.textclass,
1454 context.layout, 0, context.font);
1455 newcontext.check_layout(os);
1456 os << minted_nonfloat_caption << "\n";
1457 newcontext.check_end_layout(os);
1459 os << "\n\\end_layout\n";
1460 minted_nonfloat_caption.clear();
1464 // set catcodes to verbatim early, just in case.
1465 p.setCatcodes(VERBATIM_CATCODES);
1466 string delim = p.get_token().asInput();
1467 //FIXME: handler error condition
1468 s = p.verbatimStuff(delim).second;
1469 // context.new_paragraph(os);
1470 } else if (use_minted) {
1471 s = p.verbatimEnvironment("minted");
1473 s = p.verbatimEnvironment("lstlisting");
1475 output_ert(os, s, context);
1476 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1477 minted_nonfloat_caption.erase(0,3);
1478 os << "\n\\begin_layout Plain Layout\n";
1479 begin_inset(os, "Caption Standard\n");
1480 Context newcontext(true, context.textclass,
1481 context.layout, 0, context.font);
1482 newcontext.check_layout(os);
1483 os << minted_nonfloat_caption << "\n";
1484 newcontext.check_end_layout(os);
1486 os << "\n\\end_layout\n";
1487 minted_nonfloat_caption.clear();
1489 // Don't close the inset here for floating minted listings.
1490 // It will be closed at the end of the listing environment.
1491 if (!use_minted || minted_float.empty())
1494 eat_whitespace(p, os, parent_context, true);
1495 Token t = p.get_token();
1496 if (t.asInput() != "\\end") {
1497 // If anything follows, collect it into a caption.
1498 minted_float_has_caption = true;
1499 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1500 begin_inset(os, "Caption Standard\n");
1501 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1508 /// parse an unknown environment
1509 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1510 unsigned flags, bool outer,
1511 Context & parent_context)
1513 if (name == "tabbing")
1514 // We need to remember that we have to handle '\=' specially
1515 flags |= FLAG_TABBING;
1517 // We need to translate font changes and paragraphs inside the
1518 // environment to ERT if we have a non standard font.
1519 // Otherwise things like
1520 // \large\begin{foo}\huge bar\end{foo}
1522 bool const specialfont =
1523 (parent_context.font != parent_context.normalfont);
1524 bool const new_layout_allowed = parent_context.new_layout_allowed;
1526 parent_context.new_layout_allowed = false;
1527 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1528 parse_text_snippet(p, os, flags, outer, parent_context);
1529 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1531 parent_context.new_layout_allowed = new_layout_allowed;
1535 void parse_environment(Parser & p, ostream & os, bool outer,
1536 string & last_env, Context & parent_context)
1538 Layout const * newlayout;
1539 InsetLayout const * newinsetlayout = 0;
1540 string const name = p.getArg('{', '}');
1541 const bool is_starred = suffixIs(name, '*');
1542 string const unstarred_name = rtrim(name, "*");
1543 active_environments.push_back(name);
1545 if (is_math_env(name)) {
1546 parent_context.check_layout(os);
1547 begin_inset(os, "Formula ");
1548 os << "\\begin{" << name << "}";
1549 parse_math(p, os, FLAG_END, MATH_MODE);
1550 os << "\\end{" << name << "}";
1552 if (is_display_math_env(name)) {
1553 // Prevent the conversion of a line break to a space
1554 // (bug 7668). This does not change the output, but
1555 // looks ugly in LyX.
1556 eat_whitespace(p, os, parent_context, false);
1560 else if (is_known(name, preamble.polyglossia_languages)) {
1561 // We must begin a new paragraph if not already done
1562 if (! parent_context.atParagraphStart()) {
1563 parent_context.check_end_layout(os);
1564 parent_context.new_paragraph(os);
1566 // save the language in the context so that it is
1567 // handled by parse_text
1568 parent_context.font.language = preamble.polyglossia2lyx(name);
1569 parse_text(p, os, FLAG_END, outer, parent_context);
1570 // Just in case the environment is empty
1571 parent_context.extra_stuff.erase();
1572 // We must begin a new paragraph to reset the language
1573 parent_context.new_paragraph(os);
1577 else if (unstarred_name == "tabular" || name == "longtable") {
1578 eat_whitespace(p, os, parent_context, false);
1579 string width = "0pt";
1580 if (name == "tabular*") {
1581 width = lyx::translate_len(p.getArg('{', '}'));
1582 eat_whitespace(p, os, parent_context, false);
1584 parent_context.check_layout(os);
1585 begin_inset(os, "Tabular ");
1586 handle_tabular(p, os, name, width, parent_context);
1591 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1592 eat_whitespace(p, os, parent_context, false);
1593 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1594 eat_whitespace(p, os, parent_context, false);
1595 parent_context.check_layout(os);
1596 begin_inset(os, "Float " + unstarred_name + "\n");
1597 // store the float type for subfloats
1598 // subfloats only work with figures and tables
1599 if (unstarred_name == "figure")
1600 float_type = unstarred_name;
1601 else if (unstarred_name == "table")
1602 float_type = unstarred_name;
1606 os << "placement " << opt << '\n';
1607 if (contains(opt, "H"))
1608 preamble.registerAutomaticallyLoadedPackage("float");
1610 Floating const & fl = parent_context.textclass.floats()
1611 .getType(unstarred_name);
1612 if (!fl.floattype().empty() && fl.usesFloatPkg())
1613 preamble.registerAutomaticallyLoadedPackage("float");
1616 os << "wide " << convert<string>(is_starred)
1617 << "\nsideways false"
1618 << "\nstatus open\n\n";
1619 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1621 // We don't need really a new paragraph, but
1622 // we must make sure that the next item gets a \begin_layout.
1623 parent_context.new_paragraph(os);
1625 // the float is parsed thus delete the type
1629 else if (unstarred_name == "sidewaysfigure"
1630 || unstarred_name == "sidewaystable"
1631 || unstarred_name == "sidewaysalgorithm") {
1632 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1633 eat_whitespace(p, os, parent_context, false);
1634 parent_context.check_layout(os);
1635 if (unstarred_name == "sidewaysfigure")
1636 begin_inset(os, "Float figure\n");
1637 else if (unstarred_name == "sidewaystable")
1638 begin_inset(os, "Float table\n");
1639 else if (unstarred_name == "sidewaysalgorithm")
1640 begin_inset(os, "Float algorithm\n");
1642 os << "placement " << opt << '\n';
1643 if (contains(opt, "H"))
1644 preamble.registerAutomaticallyLoadedPackage("float");
1645 os << "wide " << convert<string>(is_starred)
1646 << "\nsideways true"
1647 << "\nstatus open\n\n";
1648 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1650 // We don't need really a new paragraph, but
1651 // we must make sure that the next item gets a \begin_layout.
1652 parent_context.new_paragraph(os);
1654 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1657 else if (name == "wrapfigure" || name == "wraptable") {
1658 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1659 eat_whitespace(p, os, parent_context, false);
1660 parent_context.check_layout(os);
1663 string overhang = "0col%";
1666 lines = p.getArg('[', ']');
1667 string const placement = p.getArg('{', '}');
1669 overhang = p.getArg('[', ']');
1670 string const width = p.getArg('{', '}');
1672 if (name == "wrapfigure")
1673 begin_inset(os, "Wrap figure\n");
1675 begin_inset(os, "Wrap table\n");
1676 os << "lines " << lines
1677 << "\nplacement " << placement
1678 << "\noverhang " << lyx::translate_len(overhang)
1679 << "\nwidth " << lyx::translate_len(width)
1680 << "\nstatus open\n\n";
1681 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1683 // We don't need really a new paragraph, but
1684 // we must make sure that the next item gets a \begin_layout.
1685 parent_context.new_paragraph(os);
1687 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1690 else if (name == "minipage") {
1691 eat_whitespace(p, os, parent_context, false);
1692 // Test whether this is an outer box of a shaded box
1694 // swallow arguments
1695 while (p.hasOpt()) {
1697 p.skip_spaces(true);
1700 p.skip_spaces(true);
1701 Token t = p.get_token();
1702 bool shaded = false;
1703 if (t.asInput() == "\\begin") {
1704 p.skip_spaces(true);
1705 if (p.getArg('{', '}') == "shaded")
1710 parse_outer_box(p, os, FLAG_END, outer,
1711 parent_context, name, "shaded");
1713 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1714 "", "", name, "", "");
1718 else if (name == "comment") {
1719 eat_whitespace(p, os, parent_context, false);
1720 parent_context.check_layout(os);
1721 begin_inset(os, "Note Comment\n");
1722 os << "status open\n";
1723 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1726 skip_braces(p); // eat {} that might by set by LyX behind comments
1727 preamble.registerAutomaticallyLoadedPackage("verbatim");
1730 else if (unstarred_name == "verbatim") {
1731 // FIXME: this should go in the generic code that
1732 // handles environments defined in layout file that
1733 // have "PassThru 1". However, the code over there is
1734 // already too complicated for my taste.
1735 string const ascii_name =
1736 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1737 parent_context.new_paragraph(os);
1738 Context context(true, parent_context.textclass,
1739 &parent_context.textclass[from_ascii(ascii_name)]);
1740 string s = p.verbatimEnvironment(name);
1741 output_ert(os, s, context);
1745 else if (name == "IPA") {
1746 eat_whitespace(p, os, parent_context, false);
1747 parent_context.check_layout(os);
1748 begin_inset(os, "IPA\n");
1749 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1752 preamble.registerAutomaticallyLoadedPackage("tipa");
1753 preamble.registerAutomaticallyLoadedPackage("tipx");
1756 else if (name == "CJK") {
1757 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1758 // It is impossible to decide if a CJK environment was in its own paragraph or within
1759 // a line. We therefore always assume a paragraph since the latter is a rare case.
1760 eat_whitespace(p, os, parent_context, false);
1761 parent_context.check_end_layout(os);
1762 // store the encoding to be able to reset it
1763 string const encoding_old = p.getEncoding();
1764 string const encoding = p.getArg('{', '}');
1765 // FIXME: For some reason JIS does not work. Although the text
1766 // in tests/CJK.tex is identical with the SJIS version if you
1767 // convert both snippets using the recode command line utility,
1768 // the resulting .lyx file contains some extra characters if
1769 // you set buggy_encoding to false for JIS.
1770 bool const buggy_encoding = encoding == "JIS";
1771 if (!buggy_encoding)
1772 p.setEncoding(encoding, Encoding::CJK);
1774 // FIXME: This will read garbage, since the data is not encoded in utf8.
1775 p.setEncoding("UTF-8");
1777 // LyX only supports the same mapping for all CJK
1778 // environments, so we might need to output everything as ERT
1779 string const mapping = trim(p.getArg('{', '}'));
1780 char const * const * const where =
1781 is_known(encoding, supported_CJK_encodings);
1782 if (!buggy_encoding && !preamble.fontCJKSet())
1783 preamble.fontCJK(mapping);
1784 bool knownMapping = mapping == preamble.fontCJK();
1785 if (buggy_encoding || !knownMapping || !where) {
1786 parent_context.check_layout(os);
1787 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1789 // we must parse the content as verbatim because e.g. JIS can contain
1790 // normally invalid characters
1791 // FIXME: This works only for the most simple cases.
1792 // Since TeX control characters are not parsed,
1793 // things like comments are completely wrong.
1794 string const s = p.plainEnvironment("CJK");
1795 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1798 if (snip == "\\" || is_known(snip, known_escaped_chars))
1799 output_ert_inset(os, snip, parent_context);
1800 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1805 output_ert_inset(os, "\\end{" + name + "}",
1809 supported_CJK_languages[where - supported_CJK_encodings];
1810 // store the language because we must reset it at the end
1811 string const lang_old = parent_context.font.language;
1812 parent_context.font.language = lang;
1813 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1814 parent_context.font.language = lang_old;
1815 parent_context.new_paragraph(os);
1817 p.setEncoding(encoding_old);
1821 else if (name == "lyxgreyedout") {
1822 eat_whitespace(p, os, parent_context, false);
1823 parent_context.check_layout(os);
1824 begin_inset(os, "Note Greyedout\n");
1825 os << "status open\n";
1826 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1829 if (!preamble.notefontcolor().empty())
1830 preamble.registerAutomaticallyLoadedPackage("color");
1833 else if (name == "btSect") {
1834 eat_whitespace(p, os, parent_context, false);
1835 parent_context.check_layout(os);
1836 begin_command_inset(os, "bibtex", "bibtex");
1837 string bibstyle = "plain";
1839 bibstyle = p.getArg('[', ']');
1840 p.skip_spaces(true);
1842 string const bibfile = p.getArg('{', '}');
1843 eat_whitespace(p, os, parent_context, false);
1844 Token t = p.get_token();
1845 if (t.asInput() == "\\btPrintCited") {
1846 p.skip_spaces(true);
1847 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1849 if (t.asInput() == "\\btPrintNotCited") {
1850 p.skip_spaces(true);
1851 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1853 if (t.asInput() == "\\btPrintAll") {
1854 p.skip_spaces(true);
1855 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1857 os << "bibfiles " << '"' << bibfile << "\"\n"
1858 << "options " << '"' << bibstyle << "\"\n";
1859 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1864 else if (name == "framed" || name == "shaded") {
1865 eat_whitespace(p, os, parent_context, false);
1866 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1868 preamble.registerAutomaticallyLoadedPackage("framed");
1871 else if (name == "listing") {
1872 minted_float = "float";
1873 eat_whitespace(p, os, parent_context, false);
1874 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1876 minted_float += "=" + opt;
1877 // If something precedes \begin{minted}, we output it at the end
1878 // as a caption, in order to keep it inside the listings inset.
1879 eat_whitespace(p, os, parent_context, true);
1881 Token const & t = p.get_token();
1882 p.skip_spaces(true);
1883 string const envname = p.next_token().cat() == catBegin
1884 ? p.getArg('{', '}') : string();
1885 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1887 minted_float_has_caption = false;
1888 string content = parse_text_snippet(p, FLAG_END, outer,
1890 size_t i = content.find("\\begin_inset listings");
1891 bool minted_env = i != string::npos;
1894 caption = content.substr(0, i);
1895 content.erase(0, i);
1897 parent_context.check_layout(os);
1898 if (minted_env && minted_float_has_caption) {
1899 eat_whitespace(p, os, parent_context, true);
1900 os << content << "\n";
1901 if (!caption.empty())
1902 os << caption << "\n";
1903 os << "\n\\end_layout\n"; // close inner layout
1904 end_inset(os); // close caption inset
1905 os << "\n\\end_layout\n"; // close outer layout
1906 } else if (!caption.empty()) {
1908 begin_inset(os, "listings\n");
1909 os << "lstparams " << '"' << minted_float << '"' << '\n';
1910 os << "inline false\n";
1911 os << "status collapsed\n";
1913 os << "\n\\begin_layout Plain Layout\n";
1914 begin_inset(os, "Caption Standard\n");
1915 Context newcontext(true, parent_context.textclass,
1916 0, 0, parent_context.font);
1917 newcontext.check_layout(os);
1918 os << caption << "\n";
1919 newcontext.check_end_layout(os);
1921 os << "\n\\end_layout\n";
1922 } else if (content.empty()) {
1923 begin_inset(os, "listings\n");
1924 os << "lstparams " << '"' << minted_float << '"' << '\n';
1925 os << "inline false\n";
1926 os << "status collapsed\n";
1928 os << content << "\n";
1930 end_inset(os); // close listings inset
1931 parent_context.check_end_layout(os);
1932 parent_context.new_paragraph(os);
1934 minted_float.clear();
1935 minted_float_has_caption = false;
1938 else if (name == "lstlisting" || name == "minted") {
1939 bool use_minted = name == "minted";
1940 eat_whitespace(p, os, parent_context, false);
1941 if (use_minted && minted_float.empty()) {
1942 // look ahead for a bottom caption
1944 bool found_end_minted = false;
1945 while (!found_end_minted && p.good()) {
1946 Token const & t = p.get_token();
1948 string const envname =
1949 p.next_token().cat() == catBegin
1950 ? p.getArg('{', '}') : string();
1951 found_end_minted = t.asInput() == "\\end"
1952 && envname == "minted";
1954 eat_whitespace(p, os, parent_context, true);
1955 Token const & t = p.get_token();
1956 p.skip_spaces(true);
1957 if (t.asInput() == "\\lyxmintcaption") {
1958 string const pos = p.getArg('[', ']');
1960 string const caption =
1961 parse_text_snippet(p, FLAG_ITEM,
1962 false, parent_context);
1963 minted_nonfloat_caption = "[b]" + caption;
1968 parse_listings(p, os, parent_context, false, use_minted);
1972 else if (!parent_context.new_layout_allowed)
1973 parse_unknown_environment(p, name, os, FLAG_END, outer,
1976 // Alignment and spacing settings
1977 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1978 // therefore are totally broken!
1979 // Note that \centering, \raggedright, and \raggedleft cannot be handled, as
1980 // they are commands not environments. They are furthermore switches that
1981 // can be ended by another switches, but also by commands like \footnote or
1982 // \parbox. So the only safe way is to leave them untouched.
1983 // However, we support the pseudo-environments
1984 // \begin{centering} ... \end{centering}
1985 // \begin{raggedright} ... \end{raggedright}
1986 // \begin{raggedleft} ... \end{raggedleft}
1987 // since they are used by LyX in floats (for spacing reasons)
1988 else if (name == "center" || name == "centering" ||
1989 name == "flushleft" || name == "raggedright" ||
1990 name == "flushright" || name == "raggedleft" ||
1991 name == "singlespace" || name == "onehalfspace" ||
1992 name == "doublespace" || name == "spacing") {
1993 eat_whitespace(p, os, parent_context, false);
1994 // We must begin a new paragraph if not already done
1995 if (! parent_context.atParagraphStart()) {
1996 parent_context.check_end_layout(os);
1997 parent_context.new_paragraph(os);
1999 if (name == "flushleft" || name == "raggedright")
2000 parent_context.add_extra_stuff("\\align left\n");
2001 else if (name == "flushright" || name == "raggedleft")
2002 parent_context.add_extra_stuff("\\align right\n");
2003 else if (name == "center" || name == "centering")
2004 parent_context.add_extra_stuff("\\align center\n");
2005 else if (name == "singlespace")
2006 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
2007 else if (name == "onehalfspace") {
2008 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
2009 preamble.registerAutomaticallyLoadedPackage("setspace");
2010 } else if (name == "doublespace") {
2011 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
2012 preamble.registerAutomaticallyLoadedPackage("setspace");
2013 } else if (name == "spacing") {
2014 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
2015 preamble.registerAutomaticallyLoadedPackage("setspace");
2017 parse_text(p, os, FLAG_END, outer, parent_context);
2018 // Just in case the environment is empty
2019 parent_context.extra_stuff.erase();
2020 // We must begin a new paragraph to reset the alignment
2021 parent_context.new_paragraph(os);
2025 // The single '=' is meant here.
2026 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
2027 eat_whitespace(p, os, parent_context, false);
2028 Context context(true, parent_context.textclass, newlayout,
2029 parent_context.layout, parent_context.font);
2030 if (parent_context.deeper_paragraph) {
2031 // We are beginning a nested environment after a
2032 // deeper paragraph inside the outer list environment.
2033 // Therefore we don't need to output a "begin deeper".
2034 context.need_end_deeper = true;
2036 parent_context.check_end_layout(os);
2037 if (last_env == name) {
2038 // we need to output a separator since LyX would export
2039 // the two environments as one otherwise (bug 5716)
2040 TeX2LyXDocClass const & textclass(parent_context.textclass);
2041 Context newcontext(true, textclass,
2042 &(textclass.defaultLayout()));
2043 newcontext.check_layout(os);
2044 begin_inset(os, "Separator plain\n");
2046 newcontext.check_end_layout(os);
2048 switch (context.layout->latextype) {
2049 case LATEX_LIST_ENVIRONMENT:
2050 context.add_par_extra_stuff("\\labelwidthstring "
2051 + p.verbatim_item() + '\n');
2054 case LATEX_BIB_ENVIRONMENT:
2055 p.verbatim_item(); // swallow next arg
2061 context.check_deeper(os);
2062 // handle known optional and required arguments
2063 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
2064 // It is impossible to place anything after the environment name,
2065 // but before the first \\item.
2066 if (context.layout->latextype == LATEX_ENVIRONMENT)
2067 output_arguments(os, p, outer, false, false, context,
2068 context.layout->latexargs());
2069 parse_text(p, os, FLAG_END, outer, context);
2070 if (context.layout->latextype == LATEX_ENVIRONMENT)
2071 output_arguments(os, p, outer, false, true, context,
2072 context.layout->postcommandargs());
2073 context.check_end_layout(os);
2074 if (parent_context.deeper_paragraph) {
2075 // We must suppress the "end deeper" because we
2076 // suppressed the "begin deeper" above.
2077 context.need_end_deeper = false;
2079 context.check_end_deeper(os);
2080 parent_context.new_paragraph(os);
2082 if (!preamble.titleLayoutFound())
2083 preamble.titleLayoutFound(newlayout->intitle);
2084 set<string> const & req = newlayout->requires();
2085 set<string>::const_iterator it = req.begin();
2086 set<string>::const_iterator en = req.end();
2087 for (; it != en; ++it)
2088 preamble.registerAutomaticallyLoadedPackage(*it);
2091 // The single '=' is meant here.
2092 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2093 eat_whitespace(p, os, parent_context, false);
2094 parent_context.check_layout(os);
2095 begin_inset(os, "Flex ");
2096 docstring flex_name = newinsetlayout->name();
2097 // FIXME: what do we do if the prefix is not Flex: ?
2098 if (prefixIs(flex_name, from_ascii("Flex:")))
2099 flex_name.erase(0, 5);
2100 os << to_utf8(flex_name) << '\n'
2101 << "status collapsed\n";
2102 if (newinsetlayout->isPassThru()) {
2103 string const arg = p.verbatimEnvironment(name);
2104 Context context(true, parent_context.textclass,
2105 &parent_context.textclass.plainLayout(),
2106 parent_context.layout);
2107 output_ert(os, arg, parent_context);
2109 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2113 else if (name == "appendix") {
2114 // This is no good latex style, but it works and is used in some documents...
2115 eat_whitespace(p, os, parent_context, false);
2116 parent_context.check_end_layout(os);
2117 Context context(true, parent_context.textclass, parent_context.layout,
2118 parent_context.layout, parent_context.font);
2119 context.check_layout(os);
2120 os << "\\start_of_appendix\n";
2121 parse_text(p, os, FLAG_END, outer, context);
2122 context.check_end_layout(os);
2126 else if (known_environments.find(name) != known_environments.end()) {
2127 vector<ArgumentType> arguments = known_environments[name];
2128 // The last "argument" denotes wether we may translate the
2129 // environment contents to LyX
2130 // The default required if no argument is given makes us
2131 // compatible with the reLyXre environment.
2132 ArgumentType contents = arguments.empty() ?
2135 if (!arguments.empty())
2136 arguments.pop_back();
2137 // See comment in parse_unknown_environment()
2138 bool const specialfont =
2139 (parent_context.font != parent_context.normalfont);
2140 bool const new_layout_allowed =
2141 parent_context.new_layout_allowed;
2143 parent_context.new_layout_allowed = false;
2144 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2145 outer, parent_context);
2146 if (contents == verbatim)
2147 output_ert_inset(os, p.ertEnvironment(name),
2150 parse_text_snippet(p, os, FLAG_END, outer,
2152 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2154 parent_context.new_layout_allowed = new_layout_allowed;
2158 parse_unknown_environment(p, name, os, FLAG_END, outer,
2162 active_environments.pop_back();
2166 /// parses a comment and outputs it to \p os.
2167 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2169 LASSERT(t.cat() == catComment, return);
2170 if (!t.cs().empty()) {
2171 context.check_layout(os);
2172 output_comment(p, os, t.cs(), context);
2173 if (p.next_token().cat() == catNewline) {
2174 // A newline after a comment line starts a new
2176 if (context.new_layout_allowed) {
2177 if(!context.atParagraphStart())
2178 // Only start a new paragraph if not already
2179 // done (we might get called recursively)
2180 context.new_paragraph(os);
2182 output_ert_inset(os, "\n", context);
2183 eat_whitespace(p, os, context, true);
2186 // "%\n" combination
2193 * Reads spaces and comments until the first non-space, non-comment token.
2194 * New paragraphs (double newlines or \\par) are handled like simple spaces
2195 * if \p eatParagraph is true.
2196 * Spaces are skipped, but comments are written to \p os.
2198 void eat_whitespace(Parser & p, ostream & os, Context & context,
2202 Token const & t = p.get_token();
2203 if (t.cat() == catComment)
2204 parse_comment(p, os, t, context);
2205 else if ((! eatParagraph && p.isParagraph()) ||
2206 (t.cat() != catSpace && t.cat() != catNewline)) {
2215 * Set a font attribute, parse text and reset the font attribute.
2216 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2217 * \param currentvalue Current value of the attribute. Is set to the new
2218 * value during parsing.
2219 * \param newvalue New value of the attribute
2221 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2222 Context & context, string const & attribute,
2223 string & currentvalue, string const & newvalue)
2225 context.check_layout(os);
2226 string const oldvalue = currentvalue;
2227 currentvalue = newvalue;
2228 os << '\n' << attribute << ' ' << newvalue << "\n";
2229 parse_text_snippet(p, os, flags, outer, context);
2230 context.check_layout(os);
2231 os << '\n' << attribute << ' ' << oldvalue << "\n";
2232 currentvalue = oldvalue;
2236 /// get the arguments of a natbib or jurabib citation command
2237 void get_cite_arguments(Parser & p, bool natbibOrder,
2238 string & before, string & after, bool const qualified = false)
2240 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2242 // text before the citation
2244 // text after the citation
2245 after = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2247 if (!after.empty()) {
2248 before = qualified ? p.getFullOpt(false, '(', ')') : p.getFullOpt();
2249 if (natbibOrder && !before.empty())
2250 swap(before, after);
2255 void copy_file(FileName const & src, string dstname)
2259 string const absParent = getParentFilePath(false);
2261 if (FileName::isAbsolute(dstname))
2262 dst = FileName(dstname);
2264 dst = makeAbsPath(dstname, absParent);
2265 FileName const srcpath = src.onlyPath();
2266 FileName const dstpath = dst.onlyPath();
2267 if (equivalent(srcpath, dstpath))
2269 if (!dstpath.isDirectory()) {
2270 if (!dstpath.createPath()) {
2271 cerr << "Warning: Could not create directory for file `"
2272 << dst.absFileName() << "´." << endl;
2276 if (dst.isReadableFile()) {
2277 if (overwriteFiles())
2278 cerr << "Warning: Overwriting existing file `"
2279 << dst.absFileName() << "´." << endl;
2281 cerr << "Warning: Not overwriting existing file `"
2282 << dst.absFileName() << "´." << endl;
2286 if (!src.copyTo(dst))
2287 cerr << "Warning: Could not copy file `" << src.absFileName()
2288 << "´ to `" << dst.absFileName() << "´." << endl;
2292 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2293 bool parse_chunk(Parser & p, ostream & os, Context & context)
2295 // check whether a chunk is possible here.
2296 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2302 // read the parameters
2303 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2304 if (!params.first) {
2309 Parser::Arg const code = p.verbatimStuff("\n@");
2314 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2315 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2319 // The last newline read is important for paragraph handling
2323 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2324 // We must have a valid layout before outputting the Chunk inset.
2325 context.check_layout(os);
2326 Context chunkcontext(true, context.textclass);
2327 chunkcontext.layout = &context.textclass.plainLayout();
2328 begin_inset(os, "Flex Chunk");
2329 os << "\nstatus open\n";
2330 if (!params.second.empty()) {
2331 chunkcontext.check_layout(os);
2332 Context paramscontext(true, context.textclass);
2333 paramscontext.layout = &context.textclass.plainLayout();
2334 begin_inset(os, "Argument 1");
2335 os << "\nstatus open\n";
2336 output_ert(os, params.second, paramscontext);
2339 output_ert(os, code.second, chunkcontext);
2347 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2348 bool is_macro(Parser & p)
2350 Token first = p.curr_token();
2351 if (first.cat() != catEscape || !p.good())
2353 if (first.cs() == "def")
2355 if (first.cs() != "global" && first.cs() != "long")
2357 Token second = p.get_token();
2359 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2360 second.cat() == catNewline || second.cat() == catComment)) {
2361 second = p.get_token();
2364 bool secondvalid = second.cat() == catEscape;
2366 bool thirdvalid = false;
2367 if (p.good() && first.cs() == "global" && secondvalid &&
2368 second.cs() == "long") {
2369 third = p.get_token();
2371 while (p.good() && !p.isParagraph() &&
2372 (third.cat() == catSpace ||
2373 third.cat() == catNewline ||
2374 third.cat() == catComment)) {
2375 third = p.get_token();
2378 thirdvalid = third.cat() == catEscape;
2380 for (int i = 0; i < pos; ++i)
2385 return (first.cs() == "global" || first.cs() == "long") &&
2386 second.cs() == "def";
2387 return first.cs() == "global" && second.cs() == "long" &&
2388 third.cs() == "def";
2392 /// Parse a macro definition (assumes that is_macro() returned true)
2393 void parse_macro(Parser & p, ostream & os, Context & context)
2395 context.check_layout(os);
2396 Token first = p.curr_token();
2399 string command = first.asInput();
2400 if (first.cs() != "def") {
2402 eat_whitespace(p, os, context, false);
2403 second = p.curr_token();
2404 command += second.asInput();
2405 if (second.cs() != "def") {
2407 eat_whitespace(p, os, context, false);
2408 third = p.curr_token();
2409 command += third.asInput();
2412 eat_whitespace(p, os, context, false);
2413 string const name = p.get_token().cs();
2414 eat_whitespace(p, os, context, false);
2420 while (p.next_token().cat() != catBegin) {
2421 if (p.next_token().cat() == catParameter) {
2426 // followed by number?
2427 if (p.next_token().cat() == catOther) {
2428 string s = p.get_token().asInput();
2430 // number = current arity + 1?
2431 if (s.size() == 1 && s[0] == arity + '0' + 1)
2436 paramtext += p.get_token().cs();
2438 paramtext += p.get_token().cs();
2443 // only output simple (i.e. compatible) macro as FormulaMacros
2444 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2446 context.check_layout(os);
2447 begin_inset(os, "FormulaMacro");
2448 os << "\n\\def" << ert;
2451 output_ert_inset(os, command + ert, context);
2455 void registerExternalTemplatePackages(string const & name)
2457 external::TemplateManager const & etm = external::TemplateManager::get();
2458 external::Template const * const et = etm.getTemplateByName(name);
2461 external::Template::Formats::const_iterator cit = et->formats.end();
2463 cit = et->formats.find("PDFLaTeX");
2464 if (cit == et->formats.end())
2465 // If the template has not specified a PDFLaTeX output,
2466 // we try the LaTeX format.
2467 cit = et->formats.find("LaTeX");
2468 if (cit == et->formats.end())
2470 vector<string>::const_iterator qit = cit->second.requirements.begin();
2471 vector<string>::const_iterator qend = cit->second.requirements.end();
2472 for (; qit != qend; ++qit)
2473 preamble.registerAutomaticallyLoadedPackage(*qit);
2476 } // anonymous namespace
2480 * Find a file with basename \p name in path \p path and an extension
2483 string find_file(string const & name, string const & path,
2484 char const * const * extensions)
2486 for (char const * const * what = extensions; *what; ++what) {
2487 string const trial = addExtension(name, *what);
2488 if (makeAbsPath(trial, path).exists())
2495 /// Convert filenames with TeX macros and/or quotes to something LyX
2497 string const normalize_filename(string const & name)
2502 Token const & t = p.get_token();
2503 if (t.cat() != catEscape)
2505 else if (t.cs() == "lyxdot") {
2506 // This is used by LyX for simple dots in relative
2510 } else if (t.cs() == "space") {
2513 } else if (t.cs() == "string") {
2514 // Convert \string" to " and \string~ to ~
2515 Token const & n = p.next_token();
2516 if (n.asInput() != "\"" && n.asInput() != "~")
2521 // Strip quotes. This is a bit complicated (see latex_path()).
2522 string full = os.str();
2523 if (!full.empty() && full[0] == '"') {
2524 string base = removeExtension(full);
2525 string ext = getExtension(full);
2526 if (!base.empty() && base[base.length()-1] == '"')
2529 return addExtension(trim(base, "\""), ext);
2530 if (full[full.length()-1] == '"')
2533 return trim(full, "\"");
2539 /// Convert \p name from TeX convention (relative to master file) to LyX
2540 /// convention (relative to .lyx file) if it is relative
2541 void fix_child_filename(string & name)
2543 string const absMasterTeX = getMasterFilePath(true);
2544 bool const isabs = FileName::isAbsolute(name);
2545 // convert from "relative to .tex master" to absolute original path
2547 name = makeAbsPath(name, absMasterTeX).absFileName();
2548 bool copyfile = copyFiles();
2549 string const absParentLyX = getParentFilePath(false);
2552 // convert from absolute original path to "relative to master file"
2553 string const rel = to_utf8(makeRelPath(from_utf8(name),
2554 from_utf8(absMasterTeX)));
2555 // re-interpret "relative to .tex file" as "relative to .lyx file"
2556 // (is different if the master .lyx file resides in a
2557 // different path than the master .tex file)
2558 string const absMasterLyX = getMasterFilePath(false);
2559 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2560 // Do not copy if the new path is impossible to create. Example:
2561 // absMasterTeX = "/foo/bar/"
2562 // absMasterLyX = "/bar/"
2563 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2564 if (contains(name, "/../"))
2571 // convert from absolute original path to
2572 // "relative to .lyx file"
2573 name = to_utf8(makeRelPath(from_utf8(abs),
2574 from_utf8(absParentLyX)));
2578 // convert from absolute original path to "relative to .lyx file"
2579 name = to_utf8(makeRelPath(from_utf8(name),
2580 from_utf8(absParentLyX)));
2585 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2588 Layout const * newlayout = 0;
2589 InsetLayout const * newinsetlayout = 0;
2590 char const * const * where = 0;
2591 // Store the latest bibliographystyle, addcontentslineContent and
2592 // nocite{*} option (needed for bibtex inset)
2594 string contentslineContent;
2595 // Some classes provide a \bibliographystyle, so do not output
2596 // any if none is explicitly set.
2597 string bibliographystyle;
2598 bool const use_natbib = isProvided("natbib");
2599 bool const use_jurabib = isProvided("jurabib");
2600 bool const use_biblatex = isProvided("biblatex")
2601 && preamble.citeEngine() != "biblatex-natbib";
2602 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2603 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2604 need_commentbib = use_biblatex || use_biblatex_natbib;
2607 // it is impossible to determine the correct encoding for non-CJK Japanese.
2608 // Therefore write a note at the beginning of the document
2609 if (is_nonCJKJapanese) {
2610 context.check_layout(os);
2611 begin_inset(os, "Note Note\n");
2612 os << "status open\n\\begin_layout Plain Layout\n"
2613 << "\\series bold\n"
2614 << "Important information:\n"
2615 << "\\end_layout\n\n"
2616 << "\\begin_layout Plain Layout\n"
2617 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2618 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2619 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2620 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2621 << " and specify the encoding using the -e command-line switch.\n"
2622 << " In addition, you might want to double check that the desired output encoding\n"
2623 << " is correctly selected in Document > Settings > Language.\n"
2624 << "\\end_layout\n";
2626 is_nonCJKJapanese = false;
2629 bool have_cycled = false;
2631 // Leave here only after at least one cycle
2632 if (have_cycled && flags & FLAG_LEAVE) {
2633 flags &= ~FLAG_LEAVE;
2637 Token const & t = p.get_token();
2639 debugToken(cerr, t, flags);
2642 if (flags & FLAG_ITEM) {
2643 if (t.cat() == catSpace)
2646 flags &= ~FLAG_ITEM;
2647 if (t.cat() == catBegin) {
2648 // skip the brace and collect everything to the next matching
2650 flags |= FLAG_BRACE_LAST;
2654 // handle only this single token, leave the loop if done
2655 flags |= FLAG_LEAVE;
2658 if (t.cat() != catEscape && t.character() == ']' &&
2659 (flags & FLAG_BRACK_LAST))
2661 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2664 // If there is anything between \end{env} and \begin{env} we
2665 // don't need to output a separator.
2666 if (t.cat() != catSpace && t.cat() != catNewline &&
2667 t.asInput() != "\\begin")
2674 bool const starred = p.next_token().asInput() == "*";
2675 string const starredname(starred ? (t.cs() + '*') : t.cs());
2676 if (t.cat() == catMath) {
2677 // we are inside some text mode thingy, so opening new math is allowed
2678 context.check_layout(os);
2679 begin_inset(os, "Formula ");
2680 Token const & n = p.get_token();
2681 bool const display(n.cat() == catMath && outer);
2683 // TeX's $$...$$ syntax for displayed math
2685 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2687 p.get_token(); // skip the second '$' token
2689 // simple $...$ stuff
2692 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2697 // Prevent the conversion of a line break to a
2698 // space (bug 7668). This does not change the
2699 // output, but looks ugly in LyX.
2700 eat_whitespace(p, os, context, false);
2705 if (t.cat() == catSuper || t.cat() == catSub) {
2706 cerr << "catcode " << t << " illegal in text mode\n";
2710 // Basic support for quotes. We try to disambiguate
2711 // quotes from the context (e.g., a left english quote is
2712 // the same as a right german quote...).
2713 // Try to make a smart guess about the side
2714 Token const prev = p.prev_token();
2715 bool const opening = (prev.cat() != catSpace && prev.character() != 0
2716 && prev.character() != '\n' && prev.character() != '~');
2717 if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2718 context.check_layout(os);
2719 begin_inset(os, "Quotes ");
2720 os << guessQuoteStyle("eld", opening);
2726 if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2727 context.check_layout(os);
2728 begin_inset(os, "Quotes ");
2729 os << guessQuoteStyle("erd", opening);
2736 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2737 context.check_layout(os);
2738 begin_inset(os, "Quotes ");
2739 os << guessQuoteStyle("ald", opening);
2746 if (t.asInput() == "<"
2747 && p.next_token().asInput() == "<") {
2748 bool has_chunk = false;
2752 has_chunk = parse_chunk(p, os, context);
2758 context.check_layout(os);
2759 begin_inset(os, "Quotes ");
2760 os << guessQuoteStyle("ard", opening);
2768 if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph())) {
2769 check_space(p, os, context);
2773 // babel shorthands (also used by polyglossia)
2774 // Since these can have different meanings for different languages
2775 // we import them as ERT (but they must be put in ERT to get output
2777 if (t.asInput() == "\"") {
2779 // These are known pairs. We put them together in
2780 // one ERT inset. In other cases (such as "a), only
2781 // the quotation mark is ERTed.
2782 if (p.next_token().asInput() == "\""
2783 || p.next_token().asInput() == "|"
2784 || p.next_token().asInput() == "-"
2785 || p.next_token().asInput() == "~"
2786 || p.next_token().asInput() == "="
2787 || p.next_token().asInput() == "/"
2788 || p.next_token().asInput() == "~"
2789 || p.next_token().asInput() == "'"
2790 || p.next_token().asInput() == "`"
2791 || p.next_token().asInput() == "<"
2792 || p.next_token().asInput() == ">") {
2793 s += p.next_token().asInput();
2796 output_ert_inset(os, s, context);
2800 if (t.character() == '[' && noweb_mode &&
2801 p.next_token().character() == '[') {
2802 // These can contain underscores
2804 string const s = p.getFullOpt() + ']';
2805 if (p.next_token().character() == ']')
2808 cerr << "Warning: Inserting missing ']' in '"
2809 << s << "'." << endl;
2810 output_ert_inset(os, s, context);
2814 if (t.cat() == catLetter) {
2815 context.check_layout(os);
2820 if (t.cat() == catOther ||
2821 t.cat() == catAlign ||
2822 t.cat() == catParameter) {
2823 context.check_layout(os);
2824 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2825 context.merging_hyphens_allowed &&
2826 context.font.family != "ttfamily" &&
2827 !context.layout->pass_thru) {
2828 if (p.next_next_token().asInput() == "-") {
2830 os << to_utf8(docstring(1, 0x2014));
2834 os << to_utf8(docstring(1, 0x2013));
2837 // This translates "&" to "\\&" which may be wrong...
2842 if (p.isParagraph()) {
2843 // In minted floating listings we will collect
2844 // everything into the caption, where multiple
2845 // paragraphs are forbidden.
2846 if (minted_float.empty()) {
2847 if (context.new_layout_allowed)
2848 context.new_paragraph(os);
2850 output_ert_inset(os, "\\par ", context);
2853 eat_whitespace(p, os, context, true);
2857 if (t.cat() == catActive) {
2858 context.check_layout(os);
2859 if (t.character() == '~') {
2860 if (context.layout->free_spacing)
2863 begin_inset(os, "space ~\n");
2871 if (t.cat() == catBegin) {
2872 Token const next = p.next_token();
2873 Token const end = p.next_next_token();
2874 if (next.cat() == catEnd) {
2876 Token const prev = p.prev_token();
2878 if (p.next_token().character() == '`')
2879 ; // ignore it in {}``
2881 output_ert_inset(os, "{}", context);
2882 } else if (next.cat() == catEscape &&
2883 is_known(next.cs(), known_quotes) &&
2884 end.cat() == catEnd) {
2885 // Something like {\textquoteright} (e.g.
2886 // from writer2latex). We may skip the
2887 // braces here for better readability.
2888 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2890 } else if (p.next_token().asInput() == "\\ascii") {
2891 // handle the \ascii characters
2892 // (the case without braces is handled later)
2893 // the code is "{\ascii\xxx}"
2894 p.get_token(); // eat \ascii
2895 string name2 = p.get_token().asInput();
2896 p.get_token(); // eat the final '}'
2897 string const name = "{\\ascii" + name2 + "}";
2901 // get the character from unicodesymbols
2902 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2903 Encodings::TEXT_CMD, termination, rem, &req);
2905 context.check_layout(os);
2908 output_ert_inset(os,
2909 to_utf8(rem), context);
2910 for (set<string>::const_iterator it = req.begin();
2911 it != req.end(); ++it)
2912 preamble.registerAutomaticallyLoadedPackage(*it);
2914 // we did not find a non-ert version
2915 output_ert_inset(os, name, context);
2917 context.check_layout(os);
2918 // special handling of font attribute changes
2919 Token const prev = p.prev_token();
2920 TeXFont const oldFont = context.font;
2921 if (next.character() == '[' ||
2922 next.character() == ']' ||
2923 next.character() == '*') {
2925 if (p.next_token().cat() == catEnd) {
2930 output_ert_inset(os, "{", context);
2931 parse_text_snippet(p, os,
2934 output_ert_inset(os, "}", context);
2936 } else if (! context.new_layout_allowed) {
2937 output_ert_inset(os, "{", context);
2938 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2940 output_ert_inset(os, "}", context);
2941 } else if (is_known(next.cs(), known_sizes)) {
2942 // next will change the size, so we must
2944 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2946 if (!context.atParagraphStart())
2948 << context.font.size << "\n";
2949 } else if (is_known(next.cs(), known_font_families)) {
2950 // next will change the font family, so we
2951 // must reset it here
2952 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2954 if (!context.atParagraphStart())
2956 << context.font.family << "\n";
2957 } else if (is_known(next.cs(), known_font_series)) {
2958 // next will change the font series, so we
2959 // must reset it here
2960 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2962 if (!context.atParagraphStart())
2964 << context.font.series << "\n";
2965 } else if (is_known(next.cs(), known_font_shapes)) {
2966 // next will change the font shape, so we
2967 // must reset it here
2968 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2970 if (!context.atParagraphStart())
2972 << context.font.shape << "\n";
2973 } else if (is_known(next.cs(), known_old_font_families) ||
2974 is_known(next.cs(), known_old_font_series) ||
2975 is_known(next.cs(), known_old_font_shapes)) {
2976 // next will change the font family, series
2977 // and shape, so we must reset it here
2978 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2980 if (!context.atParagraphStart())
2982 << context.font.family
2984 << context.font.series
2986 << context.font.shape << "\n";
2988 output_ert_inset(os, "{", context);
2989 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2991 output_ert_inset(os, "}", context);
2997 if (t.cat() == catEnd) {
2998 if (flags & FLAG_BRACE_LAST) {
3001 cerr << "stray '}' in text\n";
3002 output_ert_inset(os, "}", context);
3006 if (t.cat() == catComment) {
3007 parse_comment(p, os, t, context);
3012 // control sequences
3015 if (t.cs() == "(" || t.cs() == "[") {
3016 bool const simple = t.cs() == "(";
3017 context.check_layout(os);
3018 begin_inset(os, "Formula");
3019 os << " \\" << t.cs();
3020 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
3021 os << '\\' << (simple ? ')' : ']');
3024 // Prevent the conversion of a line break to a
3025 // space (bug 7668). This does not change the
3026 // output, but looks ugly in LyX.
3027 eat_whitespace(p, os, context, false);
3032 if (t.cs() == "begin") {
3033 parse_environment(p, os, outer, last_env,
3038 if (t.cs() == "end") {
3039 if (flags & FLAG_END) {
3040 // eat environment name
3041 string const name = p.getArg('{', '}');
3042 if (name != active_environment())
3043 cerr << "\\end{" + name + "} does not match \\begin{"
3044 + active_environment() + "}\n";
3047 p.error("found 'end' unexpectedly");
3051 if (t.cs() == "item") {
3053 bool const optarg = p.hasOpt();
3055 // FIXME: This swallows comments, but we cannot use
3056 // eat_whitespace() since we must not output
3057 // anything before the item.
3058 p.skip_spaces(true);
3059 s = p.verbatimOption();
3061 p.skip_spaces(false);
3063 context.check_layout(os);
3064 if (context.has_item) {
3065 // An item in an unknown list-like environment
3066 // FIXME: Do this in check_layout()!
3067 context.has_item = false;
3069 output_ert_inset(os, "\\item", context);
3071 output_ert_inset(os, "\\item ", context);
3074 if (context.layout->labeltype != LABEL_MANUAL) {
3075 // handle option of itemize item
3076 begin_inset(os, "Argument item:1\n");
3077 os << "status open\n";
3078 os << "\n\\begin_layout Plain Layout\n";
3080 os << parse_text_snippet(p2,
3081 FLAG_BRACK_LAST, outer, context);
3082 // we must not use context.check_end_layout(os)
3083 // because that would close the outer itemize layout
3084 os << "\n\\end_layout\n";
3086 eat_whitespace(p, os, context, false);
3087 } else if (!s.empty()) {
3088 // LyX adds braces around the argument,
3089 // so we need to remove them here.
3090 if (s.size() > 2 && s[0] == '{' &&
3091 s[s.size()-1] == '}')
3092 s = s.substr(1, s.size()-2);
3093 // If the argument contains a space we
3094 // must put it into ERT: Otherwise LyX
3095 // would misinterpret the space as
3096 // item delimiter (bug 7663)
3097 if (contains(s, ' ')) {
3098 output_ert_inset(os, s, context);
3101 os << parse_text_snippet(p2,
3102 FLAG_BRACK_LAST, outer, context);
3104 // The space is needed to separate the
3105 // item from the rest of the sentence.
3107 eat_whitespace(p, os, context, false);
3113 if (t.cs() == "bibitem") {
3115 context.check_layout(os);
3116 eat_whitespace(p, os, context, false);
3117 string label = p.verbatimOption();
3118 pair<bool, string> lbl = convert_latexed_command_inset_arg(label);
3119 bool const literal = !lbl.first;
3120 label = literal ? subst(label, "\n", " ") : lbl.second;
3121 string lit = literal ? "\"true\"" : "\"false\"";
3122 string key = convert_literate_command_inset_arg(p.verbatim_item());
3123 begin_command_inset(os, "bibitem", "bibitem");
3124 os << "label \"" << label << "\"\n"
3125 << "key \"" << key << "\"\n"
3126 << "literal " << lit << "\n";
3132 // catch the case of \def\inputGnumericTable
3134 if (t.cs() == "def") {
3135 Token second = p.next_token();
3136 if (second.cs() == "inputGnumericTable") {
3140 Token third = p.get_token();
3142 if (third.cs() == "input") {
3146 string name = normalize_filename(p.verbatim_item());
3147 string const path = getMasterFilePath(true);
3148 // We want to preserve relative / absolute filenames,
3149 // therefore path is only used for testing
3150 // The file extension is in every case ".tex".
3151 // So we need to remove this extension and check for
3152 // the original one.
3153 name = removeExtension(name);
3154 if (!makeAbsPath(name, path).exists()) {
3155 char const * const Gnumeric_formats[] = {"gnumeric",
3157 string const Gnumeric_name =
3158 find_file(name, path, Gnumeric_formats);
3159 if (!Gnumeric_name.empty())
3160 name = Gnumeric_name;
3162 FileName const absname = makeAbsPath(name, path);
3163 if (absname.exists()) {
3164 fix_child_filename(name);
3165 copy_file(absname, name);
3167 cerr << "Warning: Could not find file '"
3168 << name << "'." << endl;
3169 context.check_layout(os);
3170 begin_inset(os, "External\n\ttemplate ");
3171 os << "GnumericSpreadsheet\n\tfilename "
3174 context.check_layout(os);
3176 // register the packages that are automatically loaded
3177 // by the Gnumeric template
3178 registerExternalTemplatePackages("GnumericSpreadsheet");
3183 parse_macro(p, os, context);
3187 if (t.cs() == "noindent") {
3189 context.add_par_extra_stuff("\\noindent\n");
3193 if (t.cs() == "appendix") {
3194 context.add_par_extra_stuff("\\start_of_appendix\n");
3195 // We need to start a new paragraph. Otherwise the
3196 // appendix in 'bla\appendix\chapter{' would start
3198 context.new_paragraph(os);
3199 // We need to make sure that the paragraph is
3200 // generated even if it is empty. Otherwise the
3201 // appendix in '\par\appendix\par\chapter{' would
3203 context.check_layout(os);
3204 // FIXME: This is a hack to prevent paragraph
3205 // deletion if it is empty. Handle this better!
3206 output_comment(p, os,
3207 "dummy comment inserted by tex2lyx to "
3208 "ensure that this paragraph is not empty",
3210 // Both measures above may generate an additional
3211 // empty paragraph, but that does not hurt, because
3212 // whitespace does not matter here.
3213 eat_whitespace(p, os, context, true);
3217 // Must catch empty dates before findLayout is called below
3218 if (t.cs() == "date") {
3219 eat_whitespace(p, os, context, false);
3221 string const date = p.verbatim_item();
3224 preamble.suppressDate(true);
3227 preamble.suppressDate(false);
3228 if (context.new_layout_allowed &&
3229 (newlayout = findLayout(context.textclass,
3232 output_command_layout(os, p, outer,
3233 context, newlayout);
3234 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3235 if (!preamble.titleLayoutFound())
3236 preamble.titleLayoutFound(newlayout->intitle);
3237 set<string> const & req = newlayout->requires();
3238 set<string>::const_iterator it = req.begin();
3239 set<string>::const_iterator en = req.end();
3240 for (; it != en; ++it)
3241 preamble.registerAutomaticallyLoadedPackage(*it);
3243 output_ert_inset(os,
3244 "\\date{" + p.verbatim_item() + '}',
3250 // Starred section headings
3251 // Must attempt to parse "Section*" before "Section".
3252 if ((p.next_token().asInput() == "*") &&
3253 context.new_layout_allowed &&
3254 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3257 output_command_layout(os, p, outer, context, newlayout);
3259 if (!preamble.titleLayoutFound())
3260 preamble.titleLayoutFound(newlayout->intitle);
3261 set<string> const & req = newlayout->requires();
3262 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3263 preamble.registerAutomaticallyLoadedPackage(*it);
3267 // Section headings and the like
3268 if (context.new_layout_allowed &&
3269 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3271 output_command_layout(os, p, outer, context, newlayout);
3273 if (!preamble.titleLayoutFound())
3274 preamble.titleLayoutFound(newlayout->intitle);
3275 set<string> const & req = newlayout->requires();
3276 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3277 preamble.registerAutomaticallyLoadedPackage(*it);
3281 if (t.cs() == "subfloat") {
3282 // the syntax is \subfloat[list entry][sub caption]{content}
3283 // if it is a table of figure depends on the surrounding float
3285 // do nothing if there is no outer float
3286 if (!float_type.empty()) {
3287 context.check_layout(os);
3289 begin_inset(os, "Float " + float_type + "\n");
3291 << "\nsideways false"
3292 << "\nstatus collapsed\n\n";
3295 bool has_caption = false;
3296 if (p.next_token().cat() != catEscape &&
3297 p.next_token().character() == '[') {
3298 p.get_token(); // eat '['
3299 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3302 // In case we have two optional args, the second is the caption.
3303 if (p.next_token().cat() != catEscape &&
3304 p.next_token().character() == '[') {
3305 p.get_token(); // eat '['
3306 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3309 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3310 // the caption comes always as the last
3312 // we must make sure that the caption gets a \begin_layout
3313 os << "\n\\begin_layout Plain Layout";
3315 begin_inset(os, "Caption Standard\n");
3316 Context newcontext(true, context.textclass,
3317 0, 0, context.font);
3318 newcontext.check_layout(os);
3319 os << caption << "\n";
3320 newcontext.check_end_layout(os);
3323 // close the layout we opened
3324 os << "\n\\end_layout";
3329 // if the float type is not supported or there is no surrounding float
3334 opt_arg1 = convert_literate_command_inset_arg(p.getFullOpt());
3336 opt_arg2 = convert_literate_command_inset_arg(p.getFullOpt());
3338 output_ert_inset(os, t.asInput() + opt_arg1 + opt_arg2
3339 + "{" + p.verbatim_item() + '}', context);
3344 if (t.cs() == "xymatrix") {
3345 // we must open a new math because LyX's xy support is in math
3346 context.check_layout(os);
3347 begin_inset(os, "Formula ");
3349 os << "\\" << t.cs() << '{';
3350 parse_math(p, os, FLAG_ITEM, MATH_MODE);
3353 preamble.registerAutomaticallyLoadedPackage("xy");
3357 if (t.cs() == "includegraphics") {
3358 bool const clip = p.next_token().asInput() == "*";
3361 string const arg = p.getArg('[', ']');
3362 map<string, string> opts;
3363 vector<string> keys;
3364 split_map(arg, opts, keys);
3366 opts["clip"] = string();
3367 string name = normalize_filename(p.verbatim_item());
3369 string const path = getMasterFilePath(true);
3370 // We want to preserve relative / absolute filenames,
3371 // therefore path is only used for testing
3372 if (!makeAbsPath(name, path).exists()) {
3373 // The file extension is probably missing.
3374 // Now try to find it out.
3375 string const dvips_name =
3376 find_file(name, path,
3377 known_dvips_graphics_formats);
3378 string const pdftex_name =
3379 find_file(name, path,
3380 known_pdftex_graphics_formats);
3381 if (!dvips_name.empty()) {
3382 if (!pdftex_name.empty()) {
3383 cerr << "This file contains the "
3385 "\"\\includegraphics{"
3387 "However, files\n\""
3388 << dvips_name << "\" and\n\""
3389 << pdftex_name << "\"\n"
3390 "both exist, so I had to make a "
3391 "choice and took the first one.\n"
3392 "Please move the unwanted one "
3393 "someplace else and try again\n"
3394 "if my choice was wrong."
3398 } else if (!pdftex_name.empty()) {
3404 FileName const absname = makeAbsPath(name, path);
3405 if (absname.exists()) {
3406 fix_child_filename(name);
3407 copy_file(absname, name);
3409 cerr << "Warning: Could not find graphics file '"
3410 << name << "'." << endl;
3412 context.check_layout(os);
3413 begin_inset(os, "Graphics ");
3414 os << "\n\tfilename " << name << '\n';
3415 if (opts.find("width") != opts.end())
3417 << translate_len(opts["width"]) << '\n';
3418 if (opts.find("height") != opts.end())
3420 << translate_len(opts["height"]) << '\n';
3421 if (opts.find("scale") != opts.end()) {
3422 istringstream iss(opts["scale"]);
3426 os << "\tscale " << val << '\n';
3428 if (opts.find("angle") != opts.end()) {
3429 os << "\trotateAngle "
3430 << opts["angle"] << '\n';
3431 vector<string>::const_iterator a =
3432 find(keys.begin(), keys.end(), "angle");
3433 vector<string>::const_iterator s =
3434 find(keys.begin(), keys.end(), "width");
3435 if (s == keys.end())
3436 s = find(keys.begin(), keys.end(), "height");
3437 if (s == keys.end())
3438 s = find(keys.begin(), keys.end(), "scale");
3439 if (s != keys.end() && distance(s, a) > 0)
3440 os << "\tscaleBeforeRotation\n";
3442 if (opts.find("origin") != opts.end()) {
3444 string const opt = opts["origin"];
3445 if (opt.find('l') != string::npos) ss << "left";
3446 if (opt.find('r') != string::npos) ss << "right";
3447 if (opt.find('c') != string::npos) ss << "center";
3448 if (opt.find('t') != string::npos) ss << "Top";
3449 if (opt.find('b') != string::npos) ss << "Bottom";
3450 if (opt.find('B') != string::npos) ss << "Baseline";
3451 if (!ss.str().empty())
3452 os << "\trotateOrigin " << ss.str() << '\n';
3454 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3456 if (opts.find("keepaspectratio") != opts.end())
3457 os << "\tkeepAspectRatio\n";
3458 if (opts.find("clip") != opts.end())
3460 if (opts.find("draft") != opts.end())
3462 if (opts.find("bb") != opts.end())
3463 os << "\tBoundingBox "
3464 << opts["bb"] << '\n';
3465 int numberOfbbOptions = 0;
3466 if (opts.find("bbllx") != opts.end())
3467 numberOfbbOptions++;
3468 if (opts.find("bblly") != opts.end())
3469 numberOfbbOptions++;
3470 if (opts.find("bburx") != opts.end())
3471 numberOfbbOptions++;
3472 if (opts.find("bbury") != opts.end())
3473 numberOfbbOptions++;
3474 if (numberOfbbOptions == 4)
3475 os << "\tBoundingBox "
3476 << opts["bbllx"] << " " << opts["bblly"] << " "
3477 << opts["bburx"] << " " << opts["bbury"] << '\n';
3478 else if (numberOfbbOptions > 0)
3479 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3480 numberOfbbOptions = 0;
3481 if (opts.find("natwidth") != opts.end())
3482 numberOfbbOptions++;
3483 if (opts.find("natheight") != opts.end())
3484 numberOfbbOptions++;
3485 if (numberOfbbOptions == 2)
3486 os << "\tBoundingBox 0bp 0bp "
3487 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3488 else if (numberOfbbOptions > 0)
3489 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3490 ostringstream special;
3491 if (opts.find("hiresbb") != opts.end())
3492 special << "hiresbb,";
3493 if (opts.find("trim") != opts.end())
3495 if (opts.find("viewport") != opts.end())
3496 special << "viewport=" << opts["viewport"] << ',';
3497 if (opts.find("totalheight") != opts.end())
3498 special << "totalheight=" << opts["totalheight"] << ',';
3499 if (opts.find("type") != opts.end())
3500 special << "type=" << opts["type"] << ',';
3501 if (opts.find("ext") != opts.end())
3502 special << "ext=" << opts["ext"] << ',';
3503 if (opts.find("read") != opts.end())
3504 special << "read=" << opts["read"] << ',';
3505 if (opts.find("command") != opts.end())
3506 special << "command=" << opts["command"] << ',';
3507 string s_special = special.str();
3508 if (!s_special.empty()) {
3509 // We had special arguments. Remove the trailing ','.
3510 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3512 // TODO: Handle the unknown settings better.
3513 // Warn about invalid options.
3514 // Check whether some option was given twice.
3516 preamble.registerAutomaticallyLoadedPackage("graphicx");
3520 if (t.cs() == "footnote" ||
3521 (t.cs() == "thanks" && context.layout->intitle)) {
3523 context.check_layout(os);
3524 begin_inset(os, "Foot\n");
3525 os << "status collapsed\n\n";
3526 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3531 if (t.cs() == "marginpar") {
3533 context.check_layout(os);
3534 begin_inset(os, "Marginal\n");
3535 os << "status collapsed\n\n";
3536 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3541 if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3542 bool const use_minted = t.cs() == "mintinline";
3544 parse_listings(p, os, context, true, use_minted);
3548 if (t.cs() == "ensuremath") {
3550 context.check_layout(os);
3551 string const s = p.verbatim_item();
3552 //FIXME: this never triggers in UTF8
3553 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3556 output_ert_inset(os, "\\ensuremath{" + s + "}",
3561 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3562 if (preamble.titleLayoutFound()) {
3564 skip_spaces_braces(p);
3566 output_ert_inset(os, t.asInput(), context);
3570 if (t.cs() == "tableofcontents"
3571 || t.cs() == "lstlistoflistings"
3572 || t.cs() == "listoflistings") {
3573 string name = t.cs();
3574 if (preamble.minted() && name == "listoflistings")
3575 name.insert(0, "lst");
3576 context.check_layout(os);
3577 begin_command_inset(os, "toc", name);
3579 skip_spaces_braces(p);
3580 if (name == "lstlistoflistings") {
3581 if (preamble.minted())
3582 preamble.registerAutomaticallyLoadedPackage("minted");
3584 preamble.registerAutomaticallyLoadedPackage("listings");
3589 if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3590 context.check_layout(os);
3591 if (t.cs() == "listoffigures")
3592 begin_inset(os, "FloatList figure\n");
3594 begin_inset(os, "FloatList table\n");
3596 skip_spaces_braces(p);
3600 if (t.cs() == "listof") {
3601 p.skip_spaces(true);
3602 string const name = p.get_token().cs();
3603 if (context.textclass.floats().typeExist(name)) {
3604 context.check_layout(os);
3605 begin_inset(os, "FloatList ");
3608 p.get_token(); // swallow second arg
3610 output_ert_inset(os, "\\listof{" + name + "}", context);
3614 if ((where = is_known(t.cs(), known_text_font_families))) {
3615 parse_text_attributes(p, os, FLAG_ITEM, outer,
3616 context, "\\family", context.font.family,
3617 known_coded_font_families[where - known_text_font_families]);
3621 if ((where = is_known(t.cs(), known_text_font_series))) {
3622 parse_text_attributes(p, os, FLAG_ITEM, outer,
3623 context, "\\series", context.font.series,
3624 known_coded_font_series[where - known_text_font_series]);
3628 if ((where = is_known(t.cs(), known_text_font_shapes))) {
3629 parse_text_attributes(p, os, FLAG_ITEM, outer,
3630 context, "\\shape", context.font.shape,
3631 known_coded_font_shapes[where - known_text_font_shapes]);
3635 if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3636 context.check_layout(os);
3637 TeXFont oldFont = context.font;
3638 context.font.init();
3639 context.font.size = oldFont.size;
3640 os << "\n\\family " << context.font.family << "\n";
3641 os << "\n\\series " << context.font.series << "\n";
3642 os << "\n\\shape " << context.font.shape << "\n";
3643 if (t.cs() == "textnormal") {
3644 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3645 output_font_change(os, context.font, oldFont);
3646 context.font = oldFont;
3648 eat_whitespace(p, os, context, false);
3652 if (t.cs() == "textcolor") {
3653 // scheme is \textcolor{color name}{text}
3654 string const color = p.verbatim_item();
3655 // we support the predefined colors of the color and the xcolor package
3656 if (color == "black" || color == "blue" || color == "cyan"
3657 || color == "green" || color == "magenta" || color == "red"
3658 || color == "white" || color == "yellow") {
3659 context.check_layout(os);
3660 os << "\n\\color " << color << "\n";
3661 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3662 context.check_layout(os);
3663 os << "\n\\color inherit\n";
3664 preamble.registerAutomaticallyLoadedPackage("color");
3665 } else if (color == "brown" || color == "darkgray" || color == "gray"
3666 || color == "lightgray" || color == "lime" || color == "olive"
3667 || color == "orange" || color == "pink" || color == "purple"
3668 || color == "teal" || color == "violet") {
3669 context.check_layout(os);
3670 os << "\n\\color " << color << "\n";
3671 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3672 context.check_layout(os);
3673 os << "\n\\color inherit\n";
3674 preamble.registerAutomaticallyLoadedPackage("xcolor");
3676 // for custom defined colors
3677 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3681 if (t.cs() == "underbar" || t.cs() == "uline") {
3682 // \underbar is not 100% correct (LyX outputs \uline
3683 // of ulem.sty). The difference is that \ulem allows
3684 // line breaks, and \underbar does not.
3685 // Do NOT handle \underline.
3686 // \underbar cuts through y, g, q, p etc.,
3687 // \underline does not.
3688 context.check_layout(os);
3689 os << "\n\\bar under\n";
3690 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3691 context.check_layout(os);
3692 os << "\n\\bar default\n";
3693 preamble.registerAutomaticallyLoadedPackage("ulem");
3697 if (t.cs() == "sout") {
3698 context.check_layout(os);
3699 os << "\n\\strikeout on\n";
3700 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3701 context.check_layout(os);
3702 os << "\n\\strikeout default\n";
3703 preamble.registerAutomaticallyLoadedPackage("ulem");
3707 if (t.cs() == "uuline" || t.cs() == "uwave"
3708 || t.cs() == "emph" || t.cs() == "noun"
3709 || t.cs() == "xout") {
3710 context.check_layout(os);
3711 os << "\n\\" << t.cs() << " on\n";
3712 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3713 context.check_layout(os);
3714 os << "\n\\" << t.cs() << " default\n";
3715 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3716 preamble.registerAutomaticallyLoadedPackage("ulem");
3720 if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3721 context.check_layout(os);
3722 string name = p.getArg('{', '}');
3723 string localtime = p.getArg('{', '}');
3724 preamble.registerAuthor(name);
3725 Author const & author = preamble.getAuthor(name);
3726 // from_asctime_utc() will fail if LyX decides to output the
3727 // time in the text language.
3728 time_t ptime = from_asctime_utc(localtime);
3729 if (ptime == static_cast<time_t>(-1)) {
3730 cerr << "Warning: Could not parse time `" << localtime
3731 << "´ for change tracking, using current time instead.\n";
3732 ptime = current_time();
3734 if (t.cs() == "lyxadded")
3735 os << "\n\\change_inserted ";
3737 os << "\n\\change_deleted ";
3738 os << author.bufferId() << ' ' << ptime << '\n';
3739 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3740 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3741 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3742 LaTeXPackages::isAvailable("xcolor");
3743 // No need to test for luatex, since luatex comes in
3744 // two flavours (dvi and pdf), like latex, and those
3745 // are detected by pdflatex.
3746 if (pdflatex || xetex) {
3748 preamble.registerAutomaticallyLoadedPackage("ulem");
3749 preamble.registerAutomaticallyLoadedPackage("xcolor");
3750 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3754 preamble.registerAutomaticallyLoadedPackage("dvipost");
3755 } else if (xcolorulem) {
3756 preamble.registerAutomaticallyLoadedPackage("ulem");
3757 preamble.registerAutomaticallyLoadedPackage("xcolor");
3763 if (t.cs() == "textipa") {
3764 context.check_layout(os);
3765 begin_inset(os, "IPA\n");
3766 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3767 context.merging_hyphens_allowed = false;
3768 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3769 context.merging_hyphens_allowed = merging_hyphens_allowed;
3771 preamble.registerAutomaticallyLoadedPackage("tipa");
3772 preamble.registerAutomaticallyLoadedPackage("tipx");
3776 if ((preamble.isPackageUsed("tipa") && t.cs() == "t" && p.next_token().asInput() == "*")
3777 || t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3778 context.check_layout(os);
3782 string const type = (t.cs() == "t") ? "bottomtiebar" : t.cs().substr(4);
3783 begin_inset(os, "IPADeco " + type + "\n");
3784 os << "status open\n";
3785 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3791 if (t.cs() == "textvertline") {
3792 // FIXME: This is not correct, \textvertline is higher than |
3798 if (t.cs() == "tone" ) {
3799 context.check_layout(os);
3800 // register the tone package
3801 preamble.registerAutomaticallyLoadedPackage("tone");
3802 string content = trimSpaceAndEol(p.verbatim_item());
3803 string command = t.asInput() + "{" + content + "}";
3804 // some tones can be detected by unicodesymbols, some need special code
3805 if (is_known(content, known_tones)) {
3806 os << "\\IPAChar " << command << "\n";
3809 // try to see whether the string is in unicodesymbols
3813 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3814 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3815 termination, rem, &req);
3819 output_ert_inset(os, to_utf8(rem), context);
3820 for (set<string>::const_iterator it = req.begin();
3821 it != req.end(); ++it)
3822 preamble.registerAutomaticallyLoadedPackage(*it);
3824 // we did not find a non-ert version
3825 output_ert_inset(os, command, context);
3829 if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3830 t.cs() == "vphantom") {
3831 context.check_layout(os);
3832 if (t.cs() == "phantom")
3833 begin_inset(os, "Phantom Phantom\n");
3834 if (t.cs() == "hphantom")
3835 begin_inset(os, "Phantom HPhantom\n");
3836 if (t.cs() == "vphantom")
3837 begin_inset(os, "Phantom VPhantom\n");
3838 os << "status open\n";
3839 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3845 if (t.cs() == "href") {
3846 context.check_layout(os);
3847 string target = convert_literate_command_inset_arg(p.verbatim_item());
3848 string name = p.verbatim_item();
3849 pair<bool, string> nm = convert_latexed_command_inset_arg(name);
3850 bool const literal = !nm.first;
3851 name = literal ? subst(name, "\n", " ") : nm.second;
3852 string lit = literal ? "\"true\"" : "\"false\"";
3854 size_t i = target.find(':');
3855 if (i != string::npos) {
3856 type = target.substr(0, i + 1);
3857 if (type == "mailto:" || type == "file:")
3858 target = target.substr(i + 1);
3859 // handle the case that name is equal to target, except of "http(s)://"
3860 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3863 begin_command_inset(os, "href", "href");
3865 os << "name \"" << name << "\"\n";
3866 os << "target \"" << target << "\"\n";
3867 if (type == "mailto:" || type == "file:")
3868 os << "type \"" << type << "\"\n";
3869 os << "literal " << lit << "\n";
3871 skip_spaces_braces(p);
3875 if (t.cs() == "lyxline") {
3876 // swallow size argument (it is not used anyway)
3878 if (!context.atParagraphStart()) {
3879 // so our line is in the middle of a paragraph
3880 // we need to add a new line, lest this line
3881 // follow the other content on that line and
3882 // run off the side of the page
3883 // FIXME: This may create an empty paragraph,
3884 // but without that it would not be
3885 // possible to set noindent below.
3886 // Fortunately LaTeX does not care
3887 // about the empty paragraph.
3888 context.new_paragraph(os);
3890 if (preamble.indentParagraphs()) {
3891 // we need to unindent, lest the line be too long
3892 context.add_par_extra_stuff("\\noindent\n");
3894 context.check_layout(os);
3895 begin_command_inset(os, "line", "rule");
3896 os << "offset \"0.5ex\"\n"
3897 "width \"100line%\"\n"
3903 if (t.cs() == "rule") {
3904 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3905 string const width = p.getArg('{', '}');
3906 string const thickness = p.getArg('{', '}');
3907 context.check_layout(os);
3908 begin_command_inset(os, "line", "rule");
3909 if (!offset.empty())
3910 os << "offset \"" << translate_len(offset) << "\"\n";
3911 os << "width \"" << translate_len(width) << "\"\n"
3912 "height \"" << translate_len(thickness) << "\"\n";
3917 // handle refstyle first to catch \eqref which can also occur
3918 // without refstyle. Only recognize these commands if
3919 // refstyle.sty was found in the preamble (otherwise \eqref
3920 // and user defined ref commands could be misdetected).
3921 if ((where = is_known(t.cs(), known_refstyle_commands))
3922 && preamble.refstyle()) {
3923 context.check_layout(os);
3924 begin_command_inset(os, "ref", "formatted");
3925 os << "reference \"";
3926 os << known_refstyle_prefixes[where - known_refstyle_commands]
3928 os << convert_literate_command_inset_arg(p.verbatim_item())
3930 os << "plural \"false\"\n";
3931 os << "caps \"false\"\n";
3932 os << "noprefix \"false\"\n";
3934 preamble.registerAutomaticallyLoadedPackage("refstyle");
3938 // if refstyle is used, we must not convert \prettyref to a
3939 // formatted reference, since that would result in a refstyle command.
3940 if ((where = is_known(t.cs(), known_ref_commands)) &&
3941 (t.cs() != "prettyref" || !preamble.refstyle())) {
3942 string const opt = p.getOpt();
3944 context.check_layout(os);
3945 begin_command_inset(os, "ref",
3946 known_coded_ref_commands[where - known_ref_commands]);
3947 os << "reference \""
3948 << convert_literate_command_inset_arg(p.verbatim_item())
3950 os << "plural \"false\"\n";
3951 os << "caps \"false\"\n";
3952 os << "noprefix \"false\"\n";
3954 if (t.cs() == "vref" || t.cs() == "vpageref")
3955 preamble.registerAutomaticallyLoadedPackage("varioref");
3956 else if (t.cs() == "prettyref")
3957 preamble.registerAutomaticallyLoadedPackage("prettyref");
3959 // LyX does not yet support optional arguments of ref commands
3960 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3961 p.verbatim_item() + '}', context);
3967 is_known(t.cs(), known_natbib_commands) &&
3968 ((t.cs() != "citefullauthor" &&
3969 t.cs() != "citeyear" &&
3970 t.cs() != "citeyearpar") ||
3971 p.next_token().asInput() != "*")) {
3972 context.check_layout(os);
3973 string command = t.cs();
3974 if (p.next_token().asInput() == "*") {
3978 if (command == "citefullauthor")
3979 // alternative name for "\\citeauthor*"
3980 command = "citeauthor*";
3982 // text before the citation
3984 // text after the citation
3986 get_cite_arguments(p, true, before, after);
3988 if (command == "cite") {
3989 // \cite without optional argument means
3990 // \citet, \cite with at least one optional
3991 // argument means \citep.
3992 if (before.empty() && after.empty())
3997 if (before.empty() && after == "[]")
3998 // avoid \citet[]{a}
4000 else if (before == "[]" && after == "[]") {
4001 // avoid \citet[][]{a}
4005 bool literal = false;
4006 pair<bool, string> aft;
4007 pair<bool, string> bef;
4008 // remove the brackets around after and before
4009 if (!after.empty()) {
4011 after.erase(after.length() - 1, 1);
4012 aft = convert_latexed_command_inset_arg(after);
4013 literal = !aft.first;
4014 after = literal ? subst(after, "\n", " ") : aft.second;
4016 if (!before.empty()) {
4018 before.erase(before.length() - 1, 1);
4019 bef = convert_latexed_command_inset_arg(before);
4020 literal |= !bef.first;
4021 before = literal ? subst(before, "\n", " ") : bef.second;
4022 if (literal && !after.empty())
4023 after = subst(after, "\n", " ");
4025 string lit = literal ? "\"true\"" : "\"false\"";
4026 begin_command_inset(os, "citation", command);
4027 os << "after " << '"' << after << '"' << "\n";
4028 os << "before " << '"' << before << '"' << "\n";
4030 << convert_literate_command_inset_arg(p.verbatim_item())
4032 << "literal " << lit << "\n";
4034 // Need to set the cite engine if natbib is loaded by
4035 // the document class directly
4036 if (preamble.citeEngine() == "basic")
4037 preamble.citeEngine("natbib");
4042 && is_known(t.cs(), known_biblatex_commands)
4043 && ((t.cs() == "cite"
4044 || t.cs() == "citeauthor"
4045 || t.cs() == "Citeauthor"
4046 || t.cs() == "parencite"
4047 || t.cs() == "citetitle")
4048 || p.next_token().asInput() != "*"))
4049 || (use_biblatex_natbib
4050 && (is_known(t.cs(), known_biblatex_commands)
4051 || is_known(t.cs(), known_natbib_commands))
4052 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
4053 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
4054 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
4055 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
4056 || t.cs() == "parencite" || t.cs() == "citetitle")
4057 || p.next_token().asInput() != "*"))){
4058 context.check_layout(os);
4059 string command = t.cs();
4060 if (p.next_token().asInput() == "*") {
4065 bool const qualified = suffixIs(command, "s");
4067 command = rtrim(command, "s");
4069 // text before the citation
4071 // text after the citation
4073 get_cite_arguments(p, true, before, after, qualified);
4075 // These use natbib cmd names in LyX
4076 // for inter-citeengine compativility
4077 if (command == "citeyear")
4078 command = "citebyear";
4079 else if (command == "cite*")
4080 command = "citeyear";
4081 else if (command == "textcite")
4083 else if (command == "Textcite")
4085 else if (command == "parencite")
4087 else if (command == "Parencite")
4089 else if (command == "parencite*")
4090 command = "citeyearpar";
4091 else if (command == "smartcite")
4092 command = "footcite";
4093 else if (command == "Smartcite")
4094 command = "Footcite";
4096 string const emptyarg = qualified ? "()" : "[]";
4097 if (before.empty() && after == emptyarg)
4100 else if (before == emptyarg && after == emptyarg) {
4101 // avoid \cite[][]{a}
4105 bool literal = false;
4106 pair<bool, string> aft;
4107 pair<bool, string> bef;
4108 // remove the brackets around after and before
4109 if (!after.empty()) {
4111 after.erase(after.length() - 1, 1);
4112 aft = convert_latexed_command_inset_arg(after);
4113 literal = !aft.first;
4114 after = literal ? subst(after, "\n", " ") : aft.second;
4116 if (!before.empty()) {
4118 before.erase(before.length() - 1, 1);
4119 bef = convert_latexed_command_inset_arg(before);
4120 literal |= !bef.first;
4121 before = literal ? subst(before, "\n", " ") : bef.second;
4123 string keys, pretextlist, posttextlist;
4125 map<string, string> pres, posts, preslit, postslit;
4126 vector<string> lkeys;
4127 // text before the citation
4128 string lbefore, lbeforelit;
4129 // text after the citation
4130 string lafter, lafterlit;
4132 pair<bool, string> laft, lbef;
4134 get_cite_arguments(p, true, lbefore, lafter);
4135 // remove the brackets around after and before
4136 if (!lafter.empty()) {
4138 lafter.erase(lafter.length() - 1, 1);
4139 laft = convert_latexed_command_inset_arg(lafter);
4140 literal |= !laft.first;
4141 lafter = laft.second;
4142 lafterlit = subst(lbefore, "\n", " ");
4144 if (!lbefore.empty()) {
4145 lbefore.erase(0, 1);
4146 lbefore.erase(lbefore.length() - 1, 1);
4147 lbef = convert_latexed_command_inset_arg(lbefore);
4148 literal |= !lbef.first;
4149 lbefore = lbef.second;
4150 lbeforelit = subst(lbefore, "\n", " ");
4152 if (lbefore.empty() && lafter == "[]") {
4157 else if (lbefore == "[]" && lafter == "[]") {
4158 // avoid \cite[][]{a}
4164 lkey = p.getArg('{', '}');
4167 if (!lbefore.empty()) {
4168 pres.insert(make_pair(lkey, lbefore));
4169 preslit.insert(make_pair(lkey, lbeforelit));
4171 if (!lafter.empty()) {
4172 posts.insert(make_pair(lkey, lafter));
4173 postslit.insert(make_pair(lkey, lafterlit));
4175 lkeys.push_back(lkey);
4177 keys = convert_literate_command_inset_arg(getStringFromVector(lkeys));
4182 for (auto const & ptl : pres) {
4183 if (!pretextlist.empty())
4184 pretextlist += '\t';
4185 pretextlist += ptl.first + " " + ptl.second;
4187 for (auto const & potl : posts) {
4188 if (!posttextlist.empty())
4189 posttextlist += '\t';
4190 posttextlist += potl.first + " " + potl.second;
4193 keys = convert_literate_command_inset_arg(p.verbatim_item());
4196 after = subst(after, "\n", " ");
4197 if (!before.empty())
4198 before = subst(after, "\n", " ");
4200 string lit = literal ? "\"true\"" : "\"false\"";
4201 begin_command_inset(os, "citation", command);
4202 os << "after " << '"' << after << '"' << "\n";
4203 os << "before " << '"' << before << '"' << "\n";
4207 if (!pretextlist.empty())
4208 os << "pretextlist " << '"' << pretextlist << '"' << "\n";
4209 if (!posttextlist.empty())
4210 os << "posttextlist " << '"' << posttextlist << '"' << "\n";
4211 os << "literal " << lit << "\n";
4213 // Need to set the cite engine if biblatex is loaded by
4214 // the document class directly
4215 if (preamble.citeEngine() == "basic")
4216 use_biblatex_natbib ?
4217 preamble.citeEngine("biblatex-natbib")
4218 : preamble.citeEngine("biblatex");
4223 is_known(t.cs(), known_jurabib_commands) &&
4224 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
4225 context.check_layout(os);
4226 string command = t.cs();
4227 if (p.next_token().asInput() == "*") {
4231 char argumentOrder = '\0';
4232 vector<string> const options =
4233 preamble.getPackageOptions("jurabib");
4234 if (find(options.begin(), options.end(),
4235 "natbiborder") != options.end())
4236 argumentOrder = 'n';
4237 else if (find(options.begin(), options.end(),
4238 "jurabiborder") != options.end())
4239 argumentOrder = 'j';
4241 // text before the citation
4243 // text after the citation
4245 get_cite_arguments(p, argumentOrder != 'j', before, after);
4247 string const citation = p.verbatim_item();
4248 if (!before.empty() && argumentOrder == '\0') {
4249 cerr << "Warning: Assuming argument order "
4250 "of jurabib version 0.6 for\n'"
4251 << command << before << after << '{'
4252 << citation << "}'.\n"
4253 "Add 'jurabiborder' to the jurabib "
4254 "package options if you used an\n"
4255 "earlier jurabib version." << endl;
4257 bool literal = false;
4258 pair<bool, string> aft;
4259 pair<bool, string> bef;
4260 // remove the brackets around after and before
4261 if (!after.empty()) {
4263 after.erase(after.length() - 1, 1);
4264 aft = convert_latexed_command_inset_arg(after);
4265 literal = !aft.first;
4266 after = literal ? subst(after, "\n", " ") : aft.second;
4268 if (!before.empty()) {
4270 before.erase(before.length() - 1, 1);
4271 bef = convert_latexed_command_inset_arg(before);
4272 literal |= !bef.first;
4273 before = literal ? subst(before, "\n", " ") : bef.second;
4274 if (literal && !after.empty())
4275 after = subst(after, "\n", " ");
4277 string lit = literal ? "\"true\"" : "\"false\"";
4278 begin_command_inset(os, "citation", command);
4279 os << "after " << '"' << after << "\"\n"
4280 << "before " << '"' << before << "\"\n"
4281 << "key " << '"' << citation << "\"\n"
4282 << "literal " << lit << "\n";
4284 // Need to set the cite engine if jurabib is loaded by
4285 // the document class directly
4286 if (preamble.citeEngine() == "basic")
4287 preamble.citeEngine("jurabib");
4291 if (t.cs() == "cite"
4292 || t.cs() == "nocite") {
4293 context.check_layout(os);
4294 string after = p.getArg('[', ']');
4295 pair<bool, string> aft = convert_latexed_command_inset_arg(after);
4296 bool const literal = !aft.first;
4297 after = literal ? subst(after, "\n", " ") : aft.second;
4298 string lit = literal ? "\"true\"" : "\"false\"";
4299 string key = convert_literate_command_inset_arg(p.verbatim_item());
4300 // store the case that it is "\nocite{*}" to use it later for
4303 begin_command_inset(os, "citation", t.cs());
4304 os << "after " << '"' << after << "\"\n"
4305 << "key " << '"' << key << "\"\n"
4306 << "literal " << lit << "\n";
4308 } else if (t.cs() == "nocite")
4313 if (t.cs() == "index" ||
4314 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4315 context.check_layout(os);
4316 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4317 p.getArg('[', ']') : "";
4318 string const kind = arg.empty() ? "idx" : arg;
4319 begin_inset(os, "Index ");
4320 os << kind << "\nstatus collapsed\n";
4321 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4324 preamble.registerAutomaticallyLoadedPackage("splitidx");
4328 if (t.cs() == "nomenclature") {
4329 context.check_layout(os);
4330 begin_command_inset(os, "nomenclature", "nomenclature");
4331 string prefix = convert_literate_command_inset_arg(p.getArg('[', ']'));
4332 if (!prefix.empty())
4333 os << "prefix " << '"' << prefix << '"' << "\n";
4334 string symbol = p.verbatim_item();
4335 pair<bool, string> sym = convert_latexed_command_inset_arg(symbol);
4336 bool literal = !sym.first;
4337 string description = p.verbatim_item();
4338 pair<bool, string> desc = convert_latexed_command_inset_arg(description);
4339 literal |= !desc.first;
4341 symbol = subst(symbol, "\n", " ");
4342 description = subst(description, "\n", " ");
4344 symbol = sym.second;
4345 description = desc.second;
4347 string lit = literal ? "\"true\"" : "\"false\"";
4348 os << "symbol " << '"' << symbol;
4349 os << "\"\ndescription \""
4350 << description << "\"\n"
4351 << "literal " << lit << "\n";
4353 preamble.registerAutomaticallyLoadedPackage("nomencl");
4357 if (t.cs() == "label") {
4358 context.check_layout(os);
4359 begin_command_inset(os, "label", "label");
4361 << convert_literate_command_inset_arg(p.verbatim_item())
4367 if (t.cs() == "lyxmintcaption") {
4368 string const pos = p.getArg('[', ']');
4370 string const caption =
4371 parse_text_snippet(p, FLAG_ITEM, false,
4373 minted_nonfloat_caption = "[t]" + caption;
4375 // We already got the caption at the bottom,
4376 // so simply skip it.
4377 parse_text_snippet(p, FLAG_ITEM, false, context);
4382 if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4383 context.check_layout(os);
4384 string commandname = t.cs();
4386 if (p.next_token().asInput() == "*") {
4391 begin_command_inset(os, "index_print", commandname);
4392 string const indexname = p.getArg('[', ']');
4394 if (indexname.empty())
4395 os << "type \"idx\"\n";
4397 os << "type \"" << indexname << "\"\n";
4398 os << "literal \"true\"\n";
4401 skip_spaces_braces(p);
4402 preamble.registerAutomaticallyLoadedPackage("makeidx");
4403 if (preamble.use_indices() == "true")
4404 preamble.registerAutomaticallyLoadedPackage("splitidx");
4408 if (t.cs() == "printnomenclature") {
4410 string width_type = "";
4411 context.check_layout(os);
4412 begin_command_inset(os, "nomencl_print", "printnomenclature");
4413 // case of a custom width
4415 width = p.getArg('[', ']');
4416 width = translate_len(width);
4417 width_type = "custom";
4419 // case of no custom width
4420 // the case of no custom width but the width set
4421 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4422 // because the user could have set anything, not only the width
4423 // of the longest label (which would be width_type = "auto")
4424 string label = convert_literate_command_inset_arg(p.getArg('{', '}'));
4425 if (label.empty() && width_type.empty())
4426 width_type = "none";
4427 os << "set_width \"" << width_type << "\"\n";
4428 if (width_type == "custom")
4429 os << "width \"" << width << '\"';
4431 skip_spaces_braces(p);
4432 preamble.registerAutomaticallyLoadedPackage("nomencl");
4436 if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4437 context.check_layout(os);
4438 begin_inset(os, "script ");
4439 os << t.cs().substr(4) << '\n';
4440 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4441 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4443 if (t.cs() == "textsubscript")
4444 preamble.registerAutomaticallyLoadedPackage("subscript");
4448 if ((where = is_known(t.cs(), known_quotes))) {
4449 context.check_layout(os);
4450 begin_inset(os, "Quotes ");
4451 string quotetype = known_coded_quotes[where - known_quotes];
4452 // try to make a smart guess about the side
4453 Token const prev = p.prev_token();
4454 bool const opening = (prev.cat() != catSpace && prev.character() != 0
4455 && prev.character() != '\n' && prev.character() != '~');
4456 quotetype = guessQuoteStyle(quotetype, opening);
4459 // LyX adds {} after the quote, so we have to eat
4460 // spaces here if there are any before a possible
4462 eat_whitespace(p, os, context, false);
4467 if ((where = is_known(t.cs(), known_sizes)) &&
4468 context.new_layout_allowed) {
4469 context.check_layout(os);
4470 TeXFont const oldFont = context.font;
4471 context.font.size = known_coded_sizes[where - known_sizes];
4472 output_font_change(os, oldFont, context.font);
4473 eat_whitespace(p, os, context, false);
4477 if ((where = is_known(t.cs(), known_font_families)) &&
4478 context.new_layout_allowed) {
4479 context.check_layout(os);
4480 TeXFont const oldFont = context.font;
4481 context.font.family =
4482 known_coded_font_families[where - known_font_families];
4483 output_font_change(os, oldFont, context.font);
4484 eat_whitespace(p, os, context, false);
4488 if ((where = is_known(t.cs(), known_font_series)) &&
4489 context.new_layout_allowed) {
4490 context.check_layout(os);
4491 TeXFont const oldFont = context.font;
4492 context.font.series =
4493 known_coded_font_series[where - known_font_series];
4494 output_font_change(os, oldFont, context.font);
4495 eat_whitespace(p, os, context, false);
4499 if ((where = is_known(t.cs(), known_font_shapes)) &&
4500 context.new_layout_allowed) {
4501 context.check_layout(os);
4502 TeXFont const oldFont = context.font;
4503 context.font.shape =
4504 known_coded_font_shapes[where - known_font_shapes];
4505 output_font_change(os, oldFont, context.font);
4506 eat_whitespace(p, os, context, false);
4509 if ((where = is_known(t.cs(), known_old_font_families)) &&
4510 context.new_layout_allowed) {
4511 context.check_layout(os);
4512 TeXFont const oldFont = context.font;
4513 context.font.init();
4514 context.font.size = oldFont.size;
4515 context.font.family =
4516 known_coded_font_families[where - known_old_font_families];
4517 output_font_change(os, oldFont, context.font);
4518 eat_whitespace(p, os, context, false);
4522 if ((where = is_known(t.cs(), known_old_font_series)) &&
4523 context.new_layout_allowed) {
4524 context.check_layout(os);
4525 TeXFont const oldFont = context.font;
4526 context.font.init();
4527 context.font.size = oldFont.size;
4528 context.font.series =
4529 known_coded_font_series[where - known_old_font_series];
4530 output_font_change(os, oldFont, context.font);
4531 eat_whitespace(p, os, context, false);
4535 if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4536 context.new_layout_allowed) {
4537 context.check_layout(os);
4538 TeXFont const oldFont = context.font;
4539 context.font.init();
4540 context.font.size = oldFont.size;
4541 context.font.shape =
4542 known_coded_font_shapes[where - known_old_font_shapes];
4543 output_font_change(os, oldFont, context.font);
4544 eat_whitespace(p, os, context, false);
4548 if (t.cs() == "selectlanguage") {
4549 context.check_layout(os);
4550 // save the language for the case that a
4551 // \foreignlanguage is used
4552 context.font.language = babel2lyx(p.verbatim_item());
4553 os << "\n\\lang " << context.font.language << "\n";
4557 if (t.cs() == "foreignlanguage") {
4558 string const lang = babel2lyx(p.verbatim_item());
4559 parse_text_attributes(p, os, FLAG_ITEM, outer,
4561 context.font.language, lang);
4565 if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4566 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4567 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4569 // We have to output the whole command if it has an option
4570 // because LyX doesn't support this yet, see bug #8214,
4571 // only if there is a single option specifying a variant, we can handle it.
4573 string langopts = p.getOpt();
4574 // check if the option contains a variant, if yes, extract it
4575 string::size_type pos_var = langopts.find("variant");
4576 string::size_type i = langopts.find(',');
4577 string::size_type k = langopts.find('=', pos_var);
4578 if (pos_var != string::npos && i == string::npos) {
4580 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4581 lang = preamble.polyglossia2lyx(variant);
4582 parse_text_attributes(p, os, FLAG_ITEM, outer,
4584 context.font.language, lang);
4586 output_ert_inset(os, t.asInput() + langopts, context);
4588 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4589 parse_text_attributes(p, os, FLAG_ITEM, outer,
4591 context.font.language, lang);
4596 if (t.cs() == "inputencoding") {
4597 // nothing to write here
4598 string const enc = subst(p.verbatim_item(), "\n", " ");
4599 p.setEncoding(enc, Encoding::inputenc);
4603 if (is_known(t.cs(), known_special_chars) ||
4604 (t.cs() == "protect" &&
4605 p.next_token().cat() == catEscape &&
4606 is_known(p.next_token().cs(), known_special_protect_chars))) {
4607 // LyX sometimes puts a \protect in front, so we have to ignore it
4609 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4610 known_special_chars);
4611 context.check_layout(os);
4612 os << known_coded_special_chars[where - known_special_chars];
4613 skip_spaces_braces(p);
4617 if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4618 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4619 p.next_next_token().asInput() == "-") ||
4620 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4621 // LyX sometimes puts a \protect in front, so we have to ignore it
4622 if (t.cs() == "protect")
4624 context.check_layout(os);
4625 if (t.cs() == "nobreakdash")
4626 os << "\\SpecialChar nobreakdash\n";
4628 os << "\\SpecialChar endofsentence\n";
4633 if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4634 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4635 || t.cs() == "%" || t.cs() == "-") {
4636 context.check_layout(os);
4638 os << "\\SpecialChar softhyphen\n";
4644 if (t.cs() == "char") {
4645 context.check_layout(os);
4646 if (p.next_token().character() == '`') {
4648 if (p.next_token().cs() == "\"") {
4653 output_ert_inset(os, "\\char`", context);
4656 output_ert_inset(os, "\\char", context);
4661 if (t.cs() == "verb") {
4662 context.check_layout(os);
4663 // set catcodes to verbatim early, just in case.
4664 p.setCatcodes(VERBATIM_CATCODES);
4665 string delim = p.get_token().asInput();
4666 Parser::Arg arg = p.verbatimStuff(delim);
4668 output_ert_inset(os, "\\verb" + delim
4669 + arg.second + delim, context);
4671 cerr << "invalid \\verb command. Skipping" << endl;
4675 // Problem: \= creates a tabstop inside the tabbing environment
4676 // and else an accent. In the latter case we really would want
4677 // \={o} instead of \= o.
4678 if (t.cs() == "=" && (flags & FLAG_TABBING)) {
4679 output_ert_inset(os, t.asInput(), context);
4683 if (t.cs() == "\\") {
4684 context.check_layout(os);
4686 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4687 else if (p.next_token().asInput() == "*") {
4689 // getOpt() eats the following space if there
4690 // is no optional argument, but that is OK
4691 // here since it has no effect in the output.
4692 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4695 begin_inset(os, "Newline newline");
4701 if (t.cs() == "newline" ||
4702 (t.cs() == "linebreak" && !p.hasOpt())) {
4703 context.check_layout(os);
4704 begin_inset(os, "Newline ");
4707 skip_spaces_braces(p);
4711 if (t.cs() == "input" || t.cs() == "include"
4712 || t.cs() == "verbatiminput"
4713 || t.cs() == "lstinputlisting") {
4714 string name = t.cs();
4715 if (name == "verbatiminput"
4716 && p.next_token().asInput() == "*")
4717 name += p.get_token().asInput();
4718 context.check_layout(os);
4720 bool literal = false;
4721 if (name == "lstinputlisting" && p.hasOpt()) {
4722 lstparams = p.getArg('[', ']');
4723 pair<bool, string> oa = convert_latexed_command_inset_arg(lstparams);
4724 literal = !oa.first;
4726 lstparams = subst(lstparams, "\n", " ");
4728 string lit = literal ? "\"true\"" : "\"false\"";
4729 string filename(normalize_filename(p.getArg('{', '}')));
4730 string const path = getMasterFilePath(true);
4731 // We want to preserve relative / absolute filenames,
4732 // therefore path is only used for testing
4733 if ((t.cs() == "include" || t.cs() == "input") &&
4734 !makeAbsPath(filename, path).exists()) {
4735 // The file extension is probably missing.
4736 // Now try to find it out.
4737 string const tex_name =
4738 find_file(filename, path,
4739 known_tex_extensions);
4740 if (!tex_name.empty())
4741 filename = tex_name;
4743 bool external = false;
4745 if (makeAbsPath(filename, path).exists()) {
4746 string const abstexname =
4747 makeAbsPath(filename, path).absFileName();
4748 string const absfigname =
4749 changeExtension(abstexname, ".fig");
4750 fix_child_filename(filename);
4751 string const lyxname = changeExtension(filename,
4752 roundtripMode() ? ".lyx.lyx" : ".lyx");
4753 string const abslyxname = makeAbsPath(
4754 lyxname, getParentFilePath(false)).absFileName();
4756 if (!skipChildren())
4757 external = FileName(absfigname).exists();
4758 if (t.cs() == "input" && !skipChildren()) {
4759 string const ext = getExtension(abstexname);
4761 // Combined PS/LaTeX:
4762 // x.eps, x.pstex_t (old xfig)
4763 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4764 FileName const absepsname(
4765 changeExtension(abstexname, ".eps"));
4766 FileName const abspstexname(
4767 changeExtension(abstexname, ".pstex"));
4768 bool const xfigeps =
4769 (absepsname.exists() ||
4770 abspstexname.exists()) &&
4773 // Combined PDF/LaTeX:
4774 // x.pdf, x.pdftex_t (old xfig)
4775 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4776 FileName const abspdfname(
4777 changeExtension(abstexname, ".pdf"));
4778 bool const xfigpdf =
4779 abspdfname.exists() &&
4780 (ext == "pdftex_t" || ext == "pdf_t");
4784 // Combined PS/PDF/LaTeX:
4785 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4786 string const absbase2(
4787 removeExtension(abstexname) + "_pspdftex");
4788 FileName const abseps2name(
4789 addExtension(absbase2, ".eps"));
4790 FileName const abspdf2name(
4791 addExtension(absbase2, ".pdf"));
4792 bool const xfigboth =
4793 abspdf2name.exists() &&
4794 abseps2name.exists() && ext == "pspdftex";
4796 xfig = xfigpdf || xfigeps || xfigboth;
4797 external = external && xfig;
4800 outname = changeExtension(filename, ".fig");
4801 FileName abssrc(changeExtension(abstexname, ".fig"));
4802 copy_file(abssrc, outname);
4804 // Don't try to convert, the result
4805 // would be full of ERT.
4807 FileName abssrc(abstexname);
4808 copy_file(abssrc, outname);
4809 } else if (t.cs() != "verbatiminput" &&
4811 tex2lyx(abstexname, FileName(abslyxname),
4814 // no need to call copy_file
4815 // tex2lyx creates the file
4818 FileName abssrc(abstexname);
4819 copy_file(abssrc, outname);
4822 cerr << "Warning: Could not find included file '"
4823 << filename << "'." << endl;
4827 begin_inset(os, "External\n");
4828 os << "\ttemplate XFig\n"
4829 << "\tfilename " << outname << '\n';
4830 registerExternalTemplatePackages("XFig");
4832 begin_command_inset(os, "include", name);
4833 outname = subst(outname, "\"", "\\\"");
4834 os << "preview false\n"
4835 "filename \"" << outname << "\"\n";
4836 if (!lstparams.empty())
4837 os << "lstparams \"" << lstparams << "\"\n";
4838 os << "literal " << lit << "\n";
4839 if (t.cs() == "verbatiminput")
4840 preamble.registerAutomaticallyLoadedPackage("verbatim");
4846 if (t.cs() == "bibliographystyle") {
4847 // store new bibliographystyle
4848 bibliographystyle = p.verbatim_item();
4849 // If any other command than \bibliography, \addcontentsline
4850 // and \nocite{*} follows, we need to output the style
4851 // (because it might be used by that command).
4852 // Otherwise, it will automatically be output by LyX.
4855 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4856 if (t2.cat() == catBegin)
4858 if (t2.cat() != catEscape)
4860 if (t2.cs() == "nocite") {
4861 if (p.getArg('{', '}') == "*")
4863 } else if (t2.cs() == "bibliography")
4865 else if (t2.cs() == "phantomsection") {
4869 else if (t2.cs() == "addcontentsline") {
4870 // get the 3 arguments of \addcontentsline
4873 contentslineContent = p.getArg('{', '}');
4874 // if the last argument is not \refname we must output
4875 if (contentslineContent == "\\refname")
4882 output_ert_inset(os,
4883 "\\bibliographystyle{" + bibliographystyle + '}',
4889 if (t.cs() == "phantomsection") {
4890 // we only support this if it occurs between
4891 // \bibliographystyle and \bibliography
4892 if (bibliographystyle.empty())
4893 output_ert_inset(os, "\\phantomsection", context);
4897 if (t.cs() == "addcontentsline") {
4898 context.check_layout(os);
4899 // get the 3 arguments of \addcontentsline
4900 string const one = p.getArg('{', '}');
4901 string const two = p.getArg('{', '}');
4902 string const three = p.getArg('{', '}');
4903 // only if it is a \refname, we support if for the bibtex inset
4904 if (contentslineContent != "\\refname") {
4905 output_ert_inset(os,
4906 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4912 else if (t.cs() == "bibliography") {
4913 context.check_layout(os);
4915 begin_command_inset(os, "bibtex", "bibtex");
4916 if (!btprint.empty()) {
4917 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4918 // clear the string because the next BibTeX inset can be without the
4919 // \nocite{*} option
4922 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4923 // Do we have addcontentsline?
4924 if (contentslineContent == "\\refname") {
4925 BibOpts = "bibtotoc";
4926 // clear string because next BibTeX inset can be without addcontentsline
4927 contentslineContent.clear();
4929 // Do we have a bibliographystyle set?
4930 if (!bibliographystyle.empty()) {
4931 if (BibOpts.empty())
4932 BibOpts = normalize_filename(bibliographystyle);
4934 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4935 // clear it because each bibtex entry has its style
4936 // and we need an empty string to handle \phantomsection
4937 bibliographystyle.clear();
4939 os << "options " << '"' << BibOpts << '"' << "\n";
4944 if (t.cs() == "printbibliography") {
4945 context.check_layout(os);
4947 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4948 vector<string> opts = getVectorFromString(bbloptions);
4949 vector<string>::iterator it =
4950 find(opts.begin(), opts.end(), "heading=bibintoc");
4951 if (it != opts.end()) {
4953 BibOpts = "bibtotoc";
4955 bbloptions = getStringFromVector(opts);
4956 begin_command_inset(os, "bibtex", "bibtex");
4957 if (!btprint.empty()) {
4958 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4959 // clear the string because the next BibTeX inset can be without the
4960 // \nocite{*} option
4964 for (auto const & bf : preamble.biblatex_bibliographies) {
4965 if (!bibfiles.empty())
4967 bibfiles += normalize_filename(bf);
4969 if (!bibfiles.empty())
4970 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4971 // Do we have addcontentsline?
4972 if (contentslineContent == "\\refname") {
4973 BibOpts = "bibtotoc";
4974 // clear string because next BibTeX inset can be without addcontentsline
4975 contentslineContent.clear();
4977 os << "options " << '"' << BibOpts << '"' << "\n";
4978 if (!bbloptions.empty())
4979 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4981 need_commentbib = false;
4985 if (t.cs() == "bibbysection") {
4986 context.check_layout(os);
4988 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4989 vector<string> opts = getVectorFromString(bbloptions);
4990 vector<string>::iterator it =
4991 find(opts.begin(), opts.end(), "heading=bibintoc");
4992 if (it != opts.end()) {
4994 BibOpts = "bibtotoc";
4996 bbloptions = getStringFromVector(opts);
4997 begin_command_inset(os, "bibtex", "bibtex");
4998 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
5000 for (auto const & bf : preamble.biblatex_bibliographies) {
5001 if (!bibfiles.empty())
5003 bibfiles += normalize_filename(bf);
5005 if (!bibfiles.empty())
5006 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5007 os << "options " << '"' << BibOpts << '"' << "\n";
5008 if (!bbloptions.empty())
5009 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
5011 need_commentbib = false;
5015 if (t.cs() == "parbox") {
5016 // Test whether this is an outer box of a shaded box
5018 // swallow arguments
5019 while (p.hasOpt()) {
5021 p.skip_spaces(true);
5024 p.skip_spaces(true);
5026 if (p.next_token().cat() == catBegin)
5028 p.skip_spaces(true);
5029 Token to = p.get_token();
5030 bool shaded = false;
5031 if (to.asInput() == "\\begin") {
5032 p.skip_spaces(true);
5033 if (p.getArg('{', '}') == "shaded")
5038 parse_outer_box(p, os, FLAG_ITEM, outer,
5039 context, "parbox", "shaded");
5041 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5042 "", "", t.cs(), "", "");
5046 if (t.cs() == "fbox" || t.cs() == "mbox" ||
5047 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
5048 t.cs() == "shadowbox" || t.cs() == "doublebox") {
5049 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
5053 if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
5054 string backgroundcolor;
5055 preamble.registerAutomaticallyLoadedPackage("xcolor");
5056 if (t.cs() == "fcolorbox") {
5057 string const framecolor = p.getArg('{', '}');
5058 backgroundcolor = p.getArg('{', '}');
5059 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
5061 backgroundcolor = p.getArg('{', '}');
5062 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
5067 // FIXME: due to the compiler limit of "if" nestings
5068 // the code for the alignment was put here
5069 // put them in their own if if this is fixed
5070 if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
5071 || t.cs() == "shadowsize"
5072 || t.cs() == "raggedleft" || t.cs() == "centering"
5073 || t.cs() == "raggedright") {
5074 if (t.cs() == "fboxrule")
5076 if (t.cs() == "fboxsep")
5078 if (t.cs() == "shadowsize")
5080 if (t.cs() != "raggedleft" && t.cs() != "centering"
5081 && t.cs() != "raggedright") {
5082 p.skip_spaces(true);
5083 while (p.good() && p.next_token().cat() != catSpace
5084 && p.next_token().cat() != catNewline
5085 && p.next_token().cat() != catEscape) {
5086 if (t.cs() == "fboxrule")
5087 fboxrule = fboxrule + p.get_token().asInput();
5088 if (t.cs() == "fboxsep")
5089 fboxsep = fboxsep + p.get_token().asInput();
5090 if (t.cs() == "shadowsize")
5091 shadow_size = shadow_size + p.get_token().asInput();
5094 output_ert_inset(os, t.asInput(), context);
5099 //\framebox() is part of the picture environment and different from \framebox{}
5100 //\framebox{} will be parsed by parse_outer_box
5101 if (t.cs() == "framebox") {
5102 if (p.next_token().character() == '(') {
5103 //the syntax is: \framebox(x,y)[position]{content}
5104 string arg = t.asInput();
5105 arg += p.getFullParentheseArg();
5106 arg += p.getFullOpt();
5107 eat_whitespace(p, os, context, false);
5108 output_ert_inset(os, arg + '{', context);
5109 parse_text(p, os, FLAG_ITEM, outer, context);
5110 output_ert_inset(os, "}", context);
5112 //the syntax is: \framebox[width][position]{content}
5113 string special = p.getFullOpt();
5114 special += p.getOpt();
5115 parse_outer_box(p, os, FLAG_ITEM, outer,
5116 context, t.cs(), special);
5121 //\makebox() is part of the picture environment and different from \makebox{}
5122 //\makebox{} will be parsed by parse_box
5123 if (t.cs() == "makebox") {
5124 if (p.next_token().character() == '(') {
5125 //the syntax is: \makebox(x,y)[position]{content}
5126 string arg = t.asInput();
5127 arg += p.getFullParentheseArg();
5128 arg += p.getFullOpt();
5129 eat_whitespace(p, os, context, false);
5130 output_ert_inset(os, arg + '{', context);
5131 parse_text(p, os, FLAG_ITEM, outer, context);
5132 output_ert_inset(os, "}", context);
5134 //the syntax is: \makebox[width][position]{content}
5135 parse_box(p, os, 0, FLAG_ITEM, outer, context,
5136 "", "", t.cs(), "", "");
5140 if (t.cs() == "smallskip" ||
5141 t.cs() == "medskip" ||
5142 t.cs() == "bigskip" ||
5143 t.cs() == "vfill") {
5144 context.check_layout(os);
5145 begin_inset(os, "VSpace ");
5148 skip_spaces_braces(p);
5152 if ((where = is_known(t.cs(), known_spaces))) {
5153 context.check_layout(os);
5154 begin_inset(os, "space ");
5155 os << '\\' << known_coded_spaces[where - known_spaces]
5158 // LaTeX swallows whitespace after all spaces except
5159 // "\\,". We have to do that here, too, because LyX
5160 // adds "{}" which would make the spaces significant.
5162 eat_whitespace(p, os, context, false);
5163 // LyX adds "{}" after all spaces except "\\ " and
5164 // "\\,", so we have to remove "{}".
5165 // "\\,{}" is equivalent to "\\," in LaTeX, so we
5166 // remove the braces after "\\,", too.
5172 if (t.cs() == "newpage" ||
5173 (t.cs() == "pagebreak" && !p.hasOpt()) ||
5174 t.cs() == "clearpage" ||
5175 t.cs() == "cleardoublepage") {
5176 context.check_layout(os);
5177 begin_inset(os, "Newpage ");
5180 skip_spaces_braces(p);
5184 if (t.cs() == "DeclareRobustCommand" ||
5185 t.cs() == "DeclareRobustCommandx" ||
5186 t.cs() == "newcommand" ||
5187 t.cs() == "newcommandx" ||
5188 t.cs() == "providecommand" ||
5189 t.cs() == "providecommandx" ||
5190 t.cs() == "renewcommand" ||
5191 t.cs() == "renewcommandx") {
5192 // DeclareRobustCommand, DeclareRobustCommandx,
5193 // providecommand and providecommandx could be handled
5194 // by parse_command(), but we need to call
5195 // add_known_command() here.
5196 string name = t.asInput();
5197 if (p.next_token().asInput() == "*") {
5198 // Starred form. Eat '*'
5202 string const command = p.verbatim_item();
5203 string const opt1 = p.getFullOpt();
5204 string const opt2 = p.getFullOpt();
5205 add_known_command(command, opt1, !opt2.empty());
5206 string const ert = name + '{' + command + '}' +
5208 '{' + p.verbatim_item() + '}';
5210 if (t.cs() == "DeclareRobustCommand" ||
5211 t.cs() == "DeclareRobustCommandx" ||
5212 t.cs() == "providecommand" ||
5213 t.cs() == "providecommandx" ||
5214 name[name.length()-1] == '*')
5215 output_ert_inset(os, ert, context);
5217 context.check_layout(os);
5218 begin_inset(os, "FormulaMacro");
5225 if (t.cs() == "let" && p.next_token().asInput() != "*") {
5226 // let could be handled by parse_command(),
5227 // but we need to call add_known_command() here.
5228 string ert = t.asInput();
5231 if (p.next_token().cat() == catBegin) {
5232 name = p.verbatim_item();
5233 ert += '{' + name + '}';
5235 name = p.verbatim_item();
5240 if (p.next_token().cat() == catBegin) {
5241 command = p.verbatim_item();
5242 ert += '{' + command + '}';
5244 command = p.verbatim_item();
5247 // If command is known, make name known too, to parse
5248 // its arguments correctly. For this reason we also
5249 // have commands in syntax.default that are hardcoded.
5250 CommandMap::iterator it = known_commands.find(command);
5251 if (it != known_commands.end())
5252 known_commands[t.asInput()] = it->second;
5253 output_ert_inset(os, ert, context);
5257 if (t.cs() == "hspace" || t.cs() == "vspace") {
5260 string name = t.asInput();
5261 string const length = p.verbatim_item();
5264 bool valid = splitLatexLength(length, valstring, unit);
5265 bool known_hspace = false;
5266 bool known_vspace = false;
5267 bool known_unit = false;
5270 istringstream iss(valstring);
5273 if (t.cs()[0] == 'h') {
5274 if (unit == "\\fill") {
5279 known_hspace = true;
5282 if (unit == "\\smallskipamount") {
5284 known_vspace = true;
5285 } else if (unit == "\\medskipamount") {
5287 known_vspace = true;
5288 } else if (unit == "\\bigskipamount") {
5290 known_vspace = true;
5291 } else if (unit == "\\fill") {
5293 known_vspace = true;
5297 if (!known_hspace && !known_vspace) {
5298 switch (unitFromString(unit)) {
5314 //unitFromString(unit) fails for relative units like Length::PCW
5315 // therefore handle them separately
5316 if (unit == "\\paperwidth" || unit == "\\columnwidth"
5317 || unit == "\\textwidth" || unit == "\\linewidth"
5318 || unit == "\\textheight" || unit == "\\paperheight"
5319 || unit == "\\baselineskip")
5327 // check for glue lengths
5328 bool is_gluelength = false;
5329 string gluelength = length;
5330 string::size_type i = length.find(" minus");
5331 if (i == string::npos) {
5332 i = length.find(" plus");
5333 if (i != string::npos)
5334 is_gluelength = true;
5336 is_gluelength = true;
5337 // if yes transform "9xx minus 8yy plus 7zz"
5339 if (is_gluelength) {
5340 i = gluelength.find(" minus");
5341 if (i != string::npos)
5342 gluelength.replace(i, 7, "-");
5343 i = gluelength.find(" plus");
5344 if (i != string::npos)
5345 gluelength.replace(i, 6, "+");
5348 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5349 // Literal horizontal length or known variable
5350 context.check_layout(os);
5351 begin_inset(os, "space ");
5359 if (known_unit && !known_hspace)
5360 os << "\n\\length " << translate_len(length);
5362 os << "\n\\length " << gluelength;
5364 } else if (known_unit || known_vspace || is_gluelength) {
5365 // Literal vertical length or known variable
5366 context.check_layout(os);
5367 begin_inset(os, "VSpace ");
5370 if (known_unit && !known_vspace)
5371 os << translate_len(length);
5378 // LyX can't handle other length variables in Inset VSpace/space
5383 output_ert_inset(os, name + '{' + unit + '}', context);
5384 else if (value == -1.0)
5385 output_ert_inset(os, name + "{-" + unit + '}', context);
5387 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5389 output_ert_inset(os, name + '{' + length + '}', context);
5394 // The single '=' is meant here.
5395 if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5399 context.check_layout(os);
5400 docstring name = newinsetlayout->name();
5401 bool const caption = name.find(from_ascii("Caption:")) == 0;
5403 // Already done for floating minted listings.
5404 if (minted_float.empty()) {
5405 begin_inset(os, "Caption ");
5406 os << to_utf8(name.substr(8)) << '\n';
5409 // FIXME: what do we do if the prefix is not Flex: ?
5410 if (prefixIs(name, from_ascii("Flex:")))
5412 begin_inset(os, "Flex ");
5413 os << to_utf8(name) << '\n'
5414 << "status collapsed\n";
5416 if (!minted_float.empty()) {
5417 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5418 } else if (newinsetlayout->isPassThru()) {
5419 // set catcodes to verbatim early, just in case.
5420 p.setCatcodes(VERBATIM_CATCODES);
5421 string delim = p.get_token().asInput();
5423 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5424 //FIXME: handle error condition
5425 string const arg = p.verbatimStuff("}").second;
5426 Context newcontext(true, context.textclass);
5427 if (newinsetlayout->forcePlainLayout())
5428 newcontext.layout = &context.textclass.plainLayout();
5429 output_ert(os, arg, newcontext);
5431 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5434 // Minted caption insets are not closed here because
5435 // we collect everything into the caption.
5436 if (minted_float.empty())
5441 if (t.cs() == "includepdf") {
5443 string const arg = p.getArg('[', ']');
5444 map<string, string> opts;
5445 vector<string> keys;
5446 split_map(arg, opts, keys);
5447 string name = normalize_filename(p.verbatim_item());
5448 string const path = getMasterFilePath(true);
5449 // We want to preserve relative / absolute filenames,
5450 // therefore path is only used for testing
5451 if (!makeAbsPath(name, path).exists()) {
5452 // The file extension is probably missing.
5453 // Now try to find it out.
5454 char const * const pdfpages_format[] = {"pdf", 0};
5455 string const pdftex_name =
5456 find_file(name, path, pdfpages_format);
5457 if (!pdftex_name.empty()) {
5462 FileName const absname = makeAbsPath(name, path);
5463 if (absname.exists())
5465 fix_child_filename(name);
5466 copy_file(absname, name);
5468 cerr << "Warning: Could not find file '"
5469 << name << "'." << endl;
5471 context.check_layout(os);
5472 begin_inset(os, "External\n\ttemplate ");
5473 os << "PDFPages\n\tfilename "
5475 // parse the options
5476 if (opts.find("pages") != opts.end())
5477 os << "\textra LaTeX \"pages="
5478 << opts["pages"] << "\"\n";
5479 if (opts.find("angle") != opts.end())
5480 os << "\trotateAngle "
5481 << opts["angle"] << '\n';
5482 if (opts.find("origin") != opts.end()) {
5484 string const opt = opts["origin"];
5485 if (opt == "tl") ss << "topleft";
5486 if (opt == "bl") ss << "bottomleft";
5487 if (opt == "Bl") ss << "baselineleft";
5488 if (opt == "c") ss << "center";
5489 if (opt == "tc") ss << "topcenter";
5490 if (opt == "bc") ss << "bottomcenter";
5491 if (opt == "Bc") ss << "baselinecenter";
5492 if (opt == "tr") ss << "topright";
5493 if (opt == "br") ss << "bottomright";
5494 if (opt == "Br") ss << "baselineright";
5495 if (!ss.str().empty())
5496 os << "\trotateOrigin " << ss.str() << '\n';
5498 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5500 if (opts.find("width") != opts.end())
5502 << translate_len(opts["width"]) << '\n';
5503 if (opts.find("height") != opts.end())
5505 << translate_len(opts["height"]) << '\n';
5506 if (opts.find("keepaspectratio") != opts.end())
5507 os << "\tkeepAspectRatio\n";
5509 context.check_layout(os);
5510 registerExternalTemplatePackages("PDFPages");
5514 if (t.cs() == "loadgame") {
5516 string name = normalize_filename(p.verbatim_item());
5517 string const path = getMasterFilePath(true);
5518 // We want to preserve relative / absolute filenames,
5519 // therefore path is only used for testing
5520 if (!makeAbsPath(name, path).exists()) {
5521 // The file extension is probably missing.
5522 // Now try to find it out.
5523 char const * const lyxskak_format[] = {"fen", 0};
5524 string const lyxskak_name =
5525 find_file(name, path, lyxskak_format);
5526 if (!lyxskak_name.empty())
5527 name = lyxskak_name;
5529 FileName const absname = makeAbsPath(name, path);
5530 if (absname.exists())
5532 fix_child_filename(name);
5533 copy_file(absname, name);
5535 cerr << "Warning: Could not find file '"
5536 << name << "'." << endl;
5537 context.check_layout(os);
5538 begin_inset(os, "External\n\ttemplate ");
5539 os << "ChessDiagram\n\tfilename "
5542 context.check_layout(os);
5543 // after a \loadgame follows a \showboard
5544 if (p.get_token().asInput() == "showboard")
5546 registerExternalTemplatePackages("ChessDiagram");
5550 // try to see whether the string is in unicodesymbols
5551 // Only use text mode commands, since we are in text mode here,
5552 // and math commands may be invalid (bug 6797)
5553 string name = t.asInput();
5554 // handle the dingbats, cyrillic and greek
5555 if (name == "\\ding" || name == "\\textcyr" ||
5556 (name == "\\textgreek" && !preamble.usePolyglossia()))
5557 name = name + '{' + p.getArg('{', '}') + '}';
5558 // handle the ifsym characters
5559 else if (name == "\\textifsymbol") {
5560 string const optif = p.getFullOpt();
5561 string const argif = p.getArg('{', '}');
5562 name = name + optif + '{' + argif + '}';
5564 // handle the \ascii characters
5565 // the case of \ascii within braces, as LyX outputs it, is already
5566 // handled for t.cat() == catBegin
5567 else if (name == "\\ascii") {
5568 // the code is "\asci\xxx"
5569 name = "{" + name + p.get_token().asInput() + "}";
5572 // handle some TIPA special characters
5573 else if (preamble.isPackageUsed("tipa")) {
5574 if (name == "\\s") {
5575 // fromLaTeXCommand() does not yet
5576 // recognize tipa short cuts
5577 name = "\\textsyllabic";
5578 } else if (name == "\\=" &&
5579 p.next_token().asInput() == "*") {
5580 // fromLaTeXCommand() does not yet
5581 // recognize tipa short cuts
5583 name = "\\textsubbar";
5584 } else if (name == "\\textdoublevertline") {
5585 // FIXME: This is not correct,
5586 // \textvertline is higher than \textbardbl
5587 name = "\\textbardbl";
5589 } else if (name == "\\!" ) {
5590 if (p.next_token().asInput() == "b") {
5591 p.get_token(); // eat 'b'
5594 } else if (p.next_token().asInput() == "d") {
5598 } else if (p.next_token().asInput() == "g") {
5602 } else if (p.next_token().asInput() == "G") {
5604 name = "\\texthtscg";
5606 } else if (p.next_token().asInput() == "j") {
5608 name = "\\texthtbardotlessj";
5610 } else if (p.next_token().asInput() == "o") {
5612 name = "\\textbullseye";
5615 } else if (name == "\\*" ) {
5616 if (p.next_token().asInput() == "k") {
5618 name = "\\textturnk";
5620 } else if (p.next_token().asInput() == "r") {
5621 p.get_token(); // eat 'b'
5622 name = "\\textturnr";
5624 } else if (p.next_token().asInput() == "t") {
5626 name = "\\textturnt";
5628 } else if (p.next_token().asInput() == "w") {
5630 name = "\\textturnw";
5635 if ((name.size() == 2 &&
5636 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5637 p.next_token().asInput() != "*") ||
5638 is_known(name.substr(1), known_tipa_marks)) {
5639 // name is a command that corresponds to a
5640 // combining character in unicodesymbols.
5641 // Append the argument, fromLaTeXCommand()
5642 // will either convert it to a single
5643 // character or a combining sequence.
5644 name += '{' + p.verbatim_item() + '}';
5646 // now get the character from unicodesymbols
5650 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5651 Encodings::TEXT_CMD, termination, rem, &req));
5653 context.check_layout(os);
5656 output_ert_inset(os, to_utf8(rem), context);
5658 skip_spaces_braces(p);
5659 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5660 preamble.registerAutomaticallyLoadedPackage(*it);
5662 //cerr << "#: " << t << " mode: " << mode << endl;
5663 // heuristic: read up to next non-nested space
5665 string s = t.asInput();
5666 string z = p.verbatim_item();
5667 while (p.good() && z != " " && !z.empty()) {
5668 //cerr << "read: " << z << endl;
5670 z = p.verbatim_item();
5672 cerr << "found ERT: " << s << endl;
5673 output_ert_inset(os, s + ' ', context);
5676 if (t.asInput() == name &&
5677 p.next_token().asInput() == "*") {
5678 // Starred commands like \vspace*{}
5679 p.get_token(); // Eat '*'
5682 if (!parse_command(name, p, os, outer, context))
5683 output_ert_inset(os, name, context);
5689 string guessLanguage(Parser & p, string const & lang)
5691 typedef std::map<std::string, size_t> LangMap;
5692 // map from language names to number of characters
5695 for (char const * const * i = supported_CJK_languages; *i; i++)
5696 used[string(*i)] = 0;
5699 Token const t = p.get_token();
5700 // comments are not counted for any language
5701 if (t.cat() == catComment)
5703 // commands are not counted as well, but we need to detect
5704 // \begin{CJK} and switch encoding if needed
5705 if (t.cat() == catEscape) {
5706 if (t.cs() == "inputencoding") {
5707 string const enc = subst(p.verbatim_item(), "\n", " ");
5708 p.setEncoding(enc, Encoding::inputenc);
5711 if (t.cs() != "begin")
5714 // Non-CJK content is counted for lang.
5715 // We do not care about the real language here:
5716 // If we have more non-CJK contents than CJK contents,
5717 // we simply use the language that was specified as
5718 // babel main language.
5719 used[lang] += t.asInput().length();
5722 // Now we are starting an environment
5724 string const name = p.getArg('{', '}');
5725 if (name != "CJK") {
5729 // It is a CJK environment
5731 /* name = */ p.getArg('{', '}');
5732 string const encoding = p.getArg('{', '}');
5733 /* mapping = */ p.getArg('{', '}');
5734 string const encoding_old = p.getEncoding();
5735 char const * const * const where =
5736 is_known(encoding, supported_CJK_encodings);
5738 p.setEncoding(encoding, Encoding::CJK);
5740 p.setEncoding("UTF-8");
5741 string const text = p.ertEnvironment("CJK");
5742 p.setEncoding(encoding_old);
5745 // ignore contents in unknown CJK encoding
5748 // the language of the text
5750 supported_CJK_languages[where - supported_CJK_encodings];
5751 used[cjk] += text.length();
5753 LangMap::const_iterator use = used.begin();
5754 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5755 if (it->second > use->second)
5762 void check_comment_bib(ostream & os, Context & context)
5764 if (!need_commentbib)
5766 // We have a bibliography database, but no bibliography with biblatex
5767 // which is completely valid. Insert a bibtex inset in a note.
5768 context.check_layout(os);
5769 begin_inset(os, "Note Note\n");
5770 os << "status open\n";
5771 os << "\\begin_layout Plain Layout\n";
5772 begin_command_inset(os, "bibtex", "bibtex");
5774 for (auto const & bf : preamble.biblatex_bibliographies) {
5775 if (!bibfiles.empty())
5777 bibfiles += normalize_filename(bf);
5779 if (!bibfiles.empty())
5780 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5781 end_inset(os);// Bibtex
5782 os << "\\end_layout\n";
5783 end_inset(os);// Note