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",
196 // Whether we need to insert a bibtex inset in a comment
197 bool need_commentbib = false;
199 /// LaTeX names for quotes
200 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
201 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
202 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
203 "guilsinglleft", "frq", "guilsinglright", 0};
205 /// the same as known_quotes with .lyx names
206 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
207 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
208 "gld", "grd", "gls", "ers", "fls",
209 "fls", "frs", "frs", 0};
211 /// LaTeX names for font sizes
212 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
213 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
215 /// the same as known_sizes with .lyx names
216 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
217 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
219 /// LaTeX 2.09 names for font families
220 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
222 /// LaTeX names for font families
223 char const * const known_font_families[] = { "rmfamily", "sffamily",
226 /// LaTeX names for font family changing commands
227 char const * const known_text_font_families[] = { "textrm", "textsf",
230 /// The same as known_old_font_families, known_font_families and
231 /// known_text_font_families with .lyx names
232 char const * const known_coded_font_families[] = { "roman", "sans",
235 /// LaTeX 2.09 names for font series
236 char const * const known_old_font_series[] = { "bf", 0};
238 /// LaTeX names for font series
239 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
241 /// LaTeX names for font series changing commands
242 char const * const known_text_font_series[] = { "textbf", "textmd", 0};
244 /// The same as known_old_font_series, known_font_series and
245 /// known_text_font_series with .lyx names
246 char const * const known_coded_font_series[] = { "bold", "medium", 0};
248 /// LaTeX 2.09 names for font shapes
249 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
251 /// LaTeX names for font shapes
252 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
255 /// LaTeX names for font shape changing commands
256 char const * const known_text_font_shapes[] = { "textit", "textsl", "textsc",
259 /// The same as known_old_font_shapes, known_font_shapes and
260 /// known_text_font_shapes with .lyx names
261 char const * const known_coded_font_shapes[] = { "italic", "slanted",
262 "smallcaps", "up", 0};
264 /// Known special characters which need skip_spaces_braces() afterwards
265 char const * const known_special_chars[] = {"ldots",
266 "lyxarrow", "textcompwordmark",
267 "slash", "textasciitilde", "textasciicircum", "textbackslash",
268 "LyX", "TeX", "LaTeXe",
271 /// special characters from known_special_chars which may have a \\protect before
272 char const * const known_special_protect_chars[] = {"LyX", "TeX",
273 "LaTeXe", "LaTeX", 0};
275 /// the same as known_special_chars with .lyx names
276 char const * const known_coded_special_chars[] = {"\\SpecialChar ldots\n",
277 "\\SpecialChar menuseparator\n", "\\SpecialChar ligaturebreak\n",
278 "\\SpecialChar breakableslash\n", "~", "^", "\n\\backslash\n",
279 "\\SpecialChar LyX\n", "\\SpecialChar TeX\n", "\\SpecialChar LaTeX2e\n",
280 "\\SpecialChar LaTeX\n", 0};
283 * Graphics file extensions known by the dvips driver of the graphics package.
284 * These extensions are used to complete the filename of an included
285 * graphics file if it does not contain an extension.
286 * The order must be the same that latex uses to find a file, because we
287 * will use the first extension that matches.
288 * This is only an approximation for the common cases. If we would want to
289 * do it right in all cases, we would need to know which graphics driver is
290 * used and know the extensions of every driver of the graphics package.
292 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
293 "ps.gz", "eps.Z", "ps.Z", 0};
296 * Graphics file extensions known by the pdftex driver of the graphics package.
297 * \sa known_dvips_graphics_formats
299 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
303 * Known file extensions for TeX files as used by \\include.
305 char const * const known_tex_extensions[] = {"tex", 0};
307 /// spaces known by InsetSpace
308 char const * const known_spaces[] = { " ", "space", ",",
309 "thinspace", "quad", "qquad", "enspace", "enskip",
310 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
311 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
312 "upbracefill", "downbracefill", 0};
314 /// the same as known_spaces with .lyx names
315 char const * const known_coded_spaces[] = { "space{}", "space{}",
316 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
317 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
318 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
319 "upbracefill{}", "downbracefill{}", 0};
321 /// known TIPA combining diacritical marks
322 char const * const known_tipa_marks[] = {"textsubwedge", "textsubumlaut",
323 "textsubtilde", "textseagull", "textsubbridge", "textinvsubbridge",
324 "textsubsquare", "textsubrhalfring", "textsublhalfring", "textsubplus",
325 "textovercross", "textsubarch", "textsuperimposetilde", "textraising",
326 "textlowering", "textadvancing", "textretracting", "textdoublegrave",
327 "texthighrise", "textlowrise", "textrisefall", "textsyllabic",
328 "textsubring", "textsubbar", 0};
330 /// TIPA tones that need special handling
331 char const * const known_tones[] = {"15", "51", "45", "12", "454", 0};
333 // string to store the float type to be able to determine the type of subfloats
334 string float_type = "";
336 // string to store the float status of minted listings
337 string minted_float = "";
339 // whether a caption has been parsed for a floating minted listing
340 bool minted_float_has_caption = false;
342 // The caption for non-floating minted listings
343 string minted_nonfloat_caption = "";
346 /// splits "x=z, y=b" into a map and an ordered keyword vector
347 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
352 keys.resize(v.size());
353 for (size_t i = 0; i < v.size(); ++i) {
354 size_t const pos = v[i].find('=');
355 string const index = trimSpaceAndEol(v[i].substr(0, pos));
356 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
364 * Split a LaTeX length into value and unit.
365 * The latter can be a real unit like "pt", or a latex length variable
366 * like "\textwidth". The unit may contain additional stuff like glue
367 * lengths, but we don't care, because such lengths are ERT anyway.
368 * \returns true if \p value and \p unit are valid.
370 bool splitLatexLength(string const & len, string & value, string & unit)
374 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
375 //'4,5' is a valid LaTeX length number. Change it to '4.5'
376 string const length = subst(len, ',', '.');
377 if (i == string::npos)
380 if (len[0] == '\\') {
381 // We had something like \textwidth without a factor
387 value = trimSpaceAndEol(string(length, 0, i));
391 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
392 if (contains(len, '\\'))
393 unit = trimSpaceAndEol(string(len, i));
395 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
400 /// A simple function to translate a latex length to something LyX can
401 /// understand. Not perfect, but rather best-effort.
402 bool translate_len(string const & length, string & valstring, string & unit)
404 if (!splitLatexLength(length, valstring, unit))
406 // LyX uses percent values
408 istringstream iss(valstring);
413 string const percentval = oss.str();
415 if (unit.empty() || unit[0] != '\\')
417 string::size_type const i = unit.find(' ');
418 string const endlen = (i == string::npos) ? string() : string(unit, i);
419 if (unit == "\\textwidth") {
420 valstring = percentval;
421 unit = "text%" + endlen;
422 } else if (unit == "\\columnwidth") {
423 valstring = percentval;
424 unit = "col%" + endlen;
425 } else if (unit == "\\paperwidth") {
426 valstring = percentval;
427 unit = "page%" + endlen;
428 } else if (unit == "\\linewidth") {
429 valstring = percentval;
430 unit = "line%" + endlen;
431 } else if (unit == "\\paperheight") {
432 valstring = percentval;
433 unit = "pheight%" + endlen;
434 } else if (unit == "\\textheight") {
435 valstring = percentval;
436 unit = "theight%" + endlen;
437 } else if (unit == "\\baselineskip") {
438 valstring = percentval;
439 unit = "baselineskip%" + endlen;
447 string translate_len(string const & length)
451 if (translate_len(length, value, unit))
453 // If the input is invalid, return what we have.
461 * Translates a LaTeX length into \p value, \p unit and
462 * \p special parts suitable for a box inset.
463 * The difference from translate_len() is that a box inset knows about
464 * some special "units" that are stored in \p special.
466 void translate_box_len(string const & length, string & value, string & unit, string & special)
468 if (translate_len(length, value, unit)) {
469 if (unit == "\\height" || unit == "\\depth" ||
470 unit == "\\totalheight" || unit == "\\width") {
471 special = unit.substr(1);
472 // The unit is not used, but LyX requires a dummy setting
485 * Find a file with basename \p name in path \p path and an extension
488 string find_file(string const & name, string const & path,
489 char const * const * extensions)
491 for (char const * const * what = extensions; *what; ++what) {
492 string const trial = addExtension(name, *what);
493 if (makeAbsPath(trial, path).exists())
500 void begin_inset(ostream & os, string const & name)
502 os << "\n\\begin_inset " << name;
506 void begin_command_inset(ostream & os, string const & name,
507 string const & latexname)
509 begin_inset(os, "CommandInset ");
510 os << name << "\nLatexCommand " << latexname << '\n';
514 void end_inset(ostream & os)
516 os << "\n\\end_inset\n\n";
520 bool skip_braces(Parser & p)
522 if (p.next_token().cat() != catBegin)
525 if (p.next_token().cat() == catEnd) {
534 /// replace LaTeX commands in \p s from the unicodesymbols file with their
536 docstring convert_unicodesymbols(docstring s)
539 for (size_t i = 0; i < s.size();) {
548 docstring parsed = normalize_c(encodings.fromLaTeXCommand(s,
549 Encodings::TEXT_CMD, termination, rem, &req));
550 set<string>::const_iterator it = req.begin();
551 set<string>::const_iterator en = req.end();
552 for (; it != en; ++it)
553 preamble.registerAutomaticallyLoadedPackage(*it);
556 if (s.empty() || s[0] != '\\')
565 /// try to convert \p s to a valid InsetCommand argument
566 string convert_command_inset_arg(string s)
569 // since we don't know the input encoding we can't use from_utf8
570 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
571 // LyX cannot handle newlines in a latex command
572 return subst(s, "\n", " ");
576 void output_ert(ostream & os, string const & s, Context & context)
578 context.check_layout(os);
579 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
581 os << "\n\\backslash\n";
582 else if (*it == '\n') {
583 context.new_paragraph(os);
584 context.check_layout(os);
588 context.check_end_layout(os);
592 void output_ert_inset(ostream & os, string const & s, Context & context)
594 // We must have a valid layout before outputting the ERT inset.
595 context.check_layout(os);
596 Context newcontext(true, context.textclass);
597 InsetLayout const & layout = context.textclass.insetLayout(from_ascii("ERT"));
598 if (layout.forcePlainLayout())
599 newcontext.layout = &context.textclass.plainLayout();
600 begin_inset(os, "ERT");
601 os << "\nstatus collapsed\n";
602 output_ert(os, s, newcontext);
607 void output_comment(Parser & p, ostream & os, string const & s,
610 if (p.next_token().cat() == catNewline)
611 output_ert_inset(os, '%' + s, context);
613 output_ert_inset(os, '%' + s + '\n', context);
617 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
619 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
622 if (checkModule(name, command))
623 return findLayoutWithoutModule(textclass, name, command);
628 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
630 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
633 if (checkModule(name, command))
634 return findInsetLayoutWithoutModule(textclass, name, command);
639 void eat_whitespace(Parser &, ostream &, Context &, bool);
643 * Skips whitespace and braces.
644 * This should be called after a command has been parsed that is not put into
645 * ERT, and where LyX adds "{}" if needed.
647 void skip_spaces_braces(Parser & p, bool keepws = false)
649 /* The following four examples produce the same typeset output and
650 should be handled by this function:
658 // Unfortunately we need to skip comments, too.
659 // We can't use eat_whitespace since writing them after the {}
660 // results in different output in some cases.
661 bool const skipped_spaces = p.skip_spaces(true);
662 bool const skipped_braces = skip_braces(p);
663 if (keepws && skipped_spaces && !skipped_braces)
664 // put back the space (it is better handled by check_space)
665 p.unskip_spaces(true);
669 void output_arguments(ostream & os, Parser & p, bool outer, bool need_layout, bool post,
670 Context & context, Layout::LaTeXArgMap const & latexargs)
673 context.check_layout(os);
678 Layout::LaTeXArgMap::const_iterator lait = latexargs.begin();
679 Layout::LaTeXArgMap::const_iterator const laend = latexargs.end();
680 for (; lait != laend; ++lait) {
682 eat_whitespace(p, os, context, false);
683 if (lait->second.mandatory) {
684 if (p.next_token().cat() != catBegin)
686 p.get_token(); // eat '{'
688 context.check_layout(os);
691 begin_inset(os, "Argument ");
694 os << i << "\nstatus collapsed\n\n";
695 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
698 if (p.next_token().cat() == catEscape ||
699 p.next_token().character() != '[')
701 p.get_token(); // eat '['
703 context.check_layout(os);
706 begin_inset(os, "Argument ");
709 os << i << "\nstatus collapsed\n\n";
710 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
713 eat_whitespace(p, os, context, false);
718 void output_command_layout(ostream & os, Parser & p, bool outer,
719 Context & parent_context,
720 Layout const * newlayout)
722 TeXFont const oldFont = parent_context.font;
723 // save the current font size
724 string const size = oldFont.size;
725 // reset the font size to default, because the font size switches
726 // don't affect section headings and the like
727 parent_context.font.size = Context::normalfont.size;
728 // we only need to write the font change if we have an open layout
729 if (!parent_context.atParagraphStart())
730 output_font_change(os, oldFont, parent_context.font);
731 parent_context.check_end_layout(os);
732 Context context(true, parent_context.textclass, newlayout,
733 parent_context.layout, parent_context.font);
734 if (parent_context.deeper_paragraph) {
735 // We are beginning a nested environment after a
736 // deeper paragraph inside the outer list environment.
737 // Therefore we don't need to output a "begin deeper".
738 context.need_end_deeper = true;
740 context.check_deeper(os);
741 output_arguments(os, p, outer, true, false, context,
742 context.layout->latexargs());
743 parse_text(p, os, FLAG_ITEM, outer, context);
744 output_arguments(os, p, outer, false, true, context,
745 context.layout->postcommandargs());
746 context.check_end_layout(os);
747 if (parent_context.deeper_paragraph) {
748 // We must suppress the "end deeper" because we
749 // suppressed the "begin deeper" above.
750 context.need_end_deeper = false;
752 context.check_end_deeper(os);
753 // We don't need really a new paragraph, but
754 // we must make sure that the next item gets a \begin_layout.
755 parent_context.new_paragraph(os);
756 // Set the font size to the original value. No need to output it here
757 // (Context::begin_layout() will do that if needed)
758 parent_context.font.size = size;
763 * Output a space if necessary.
764 * This function gets called for every whitespace token.
766 * We have three cases here:
767 * 1. A space must be suppressed. Example: The lyxcode case below
768 * 2. A space may be suppressed. Example: Spaces before "\par"
769 * 3. A space must not be suppressed. Example: A space between two words
771 * We currently handle only 1. and 3 and from 2. only the case of
772 * spaces before newlines as a side effect.
774 * 2. could be used to suppress as many spaces as possible. This has two effects:
775 * - Reimporting LyX generated LaTeX files changes almost no whitespace
776 * - Superflous whitespace from non LyX generated LaTeX files is removed.
777 * The drawback is that the logic inside the function becomes
778 * complicated, and that is the reason why it is not implemented.
780 void check_space(Parser & p, ostream & os, Context & context)
782 Token const next = p.next_token();
783 Token const curr = p.curr_token();
784 // A space before a single newline and vice versa must be ignored
785 // LyX emits a newline before \end{lyxcode}.
786 // This newline must be ignored,
787 // otherwise LyX will add an additional protected space.
788 if (next.cat() == catSpace ||
789 next.cat() == catNewline ||
790 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
793 context.check_layout(os);
799 * Parse all arguments of \p command
801 void parse_arguments(string const & command,
802 vector<ArgumentType> const & template_arguments,
803 Parser & p, ostream & os, bool outer, Context & context)
805 string ert = command;
806 size_t no_arguments = template_arguments.size();
807 for (size_t i = 0; i < no_arguments; ++i) {
808 switch (template_arguments[i]) {
811 // This argument contains regular LaTeX
812 output_ert_inset(os, ert + '{', context);
813 eat_whitespace(p, os, context, false);
814 if (template_arguments[i] == required)
815 parse_text(p, os, FLAG_ITEM, outer, context);
817 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
821 // This argument consists only of a single item.
822 // The presence of '{' or not must be preserved.
824 if (p.next_token().cat() == catBegin)
825 ert += '{' + p.verbatim_item() + '}';
827 ert += p.verbatim_item();
831 // This argument may contain special characters
832 ert += '{' + p.verbatim_item() + '}';
836 // true because we must not eat whitespace
837 // if an optional arg follows we must not strip the
838 // brackets from this one
839 if (i < no_arguments - 1 &&
840 template_arguments[i+1] == optional)
841 ert += p.getFullOpt(true);
843 ert += p.getOpt(true);
847 output_ert_inset(os, ert, context);
852 * Check whether \p command is a known command. If yes,
853 * handle the command with all arguments.
854 * \return true if the command was parsed, false otherwise.
856 bool parse_command(string const & command, Parser & p, ostream & os,
857 bool outer, Context & context)
859 if (known_commands.find(command) != known_commands.end()) {
860 parse_arguments(command, known_commands[command], p, os,
868 /// Parses a minipage or parbox
869 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
870 unsigned inner_flags, bool outer, Context & parent_context,
871 string const & outer_type, string const & special,
872 string inner_type, string const & frame_color,
873 string const & background_color)
877 string hor_pos = "l";
878 // We need to set the height to the LaTeX default of 1\\totalheight
879 // for the case when no height argument is given
880 string height_value = "1";
881 string height_unit = "in";
882 string height_special = "totalheight";
887 string width_special = "none";
888 string thickness = "0.4pt";
889 if (!fboxrule.empty())
890 thickness = fboxrule;
894 if (!fboxsep.empty())
895 separation = fboxsep;
899 if (!shadow_size.empty())
900 shadowsize = shadow_size;
903 string framecolor = "black";
904 string backgroundcolor = "none";
905 if (!frame_color.empty())
906 framecolor = frame_color;
907 if (!background_color.empty())
908 backgroundcolor = background_color;
909 // if there is a color box around the \begin statements have not yet been parsed
911 if (!frame_color.empty() || !background_color.empty()) {
912 eat_whitespace(p, os, parent_context, false);
913 p.get_token().asInput(); // the '{'
915 if (p.next_token().asInput() == "\\begin") {
916 p.get_token().asInput();
918 inner_type = "minipage";
919 inner_flags = FLAG_END;
920 active_environments.push_back("minipage");
923 else if (p.next_token().asInput() == "\\parbox") {
924 p.get_token().asInput();
925 inner_type = "parbox";
926 inner_flags = FLAG_ITEM;
929 else if (p.next_token().asInput() == "\\makebox") {
930 p.get_token().asInput();
931 inner_type = "makebox";
932 inner_flags = FLAG_ITEM;
934 // in case there is just \colorbox{color}{text}
937 inner_type = "makebox";
938 inner_flags = FLAG_BRACE_LAST;
943 if (!p.hasOpt() && (inner_type == "makebox" || outer_type == "mbox"))
945 if (!inner_type.empty() && p.hasOpt()) {
946 if (inner_type != "makebox")
947 position = p.getArg('[', ']');
949 latex_width = p.getArg('[', ']');
950 translate_box_len(latex_width, width_value, width_unit, width_special);
953 if (position != "t" && position != "c" && position != "b") {
954 cerr << "invalid position " << position << " for "
955 << inner_type << endl;
959 if (inner_type != "makebox") {
960 latex_height = p.getArg('[', ']');
961 translate_box_len(latex_height, height_value, height_unit, height_special);
963 string const opt = p.getArg('[', ']');
966 if (hor_pos != "l" && hor_pos != "c" &&
967 hor_pos != "r" && hor_pos != "s") {
968 cerr << "invalid hor_pos " << hor_pos
969 << " for " << inner_type << endl;
976 inner_pos = p.getArg('[', ']');
977 if (inner_pos != "c" && inner_pos != "t" &&
978 inner_pos != "b" && inner_pos != "s") {
979 cerr << "invalid inner_pos "
980 << inner_pos << " for "
981 << inner_type << endl;
982 inner_pos = position;
986 if (inner_type == "makebox")
990 if (inner_type.empty()) {
991 if (special.empty() && outer_type != "framebox")
992 latex_width = "1\\columnwidth";
995 latex_width = p2.getArg('[', ']');
996 string const opt = p2.getArg('[', ']');
999 if (hor_pos != "l" && hor_pos != "c" &&
1000 hor_pos != "r" && hor_pos != "s") {
1001 cerr << "invalid hor_pos " << hor_pos
1002 << " for " << outer_type << endl;
1006 if (outer_type == "framebox")
1010 } else if (inner_type != "makebox")
1011 latex_width = p.verbatim_item();
1012 // if e.g. only \ovalbox{content} was used, set the width to 1\columnwidth
1013 // as this is LyX's standard for such cases (except for makebox)
1014 // \framebox is more special and handled below
1015 if (latex_width.empty() && inner_type != "makebox"
1016 && outer_type != "framebox")
1017 latex_width = "1\\columnwidth";
1019 translate_len(latex_width, width_value, width_unit);
1021 bool shadedparbox = false;
1022 if (inner_type == "shaded") {
1023 eat_whitespace(p, os, parent_context, false);
1024 if (outer_type == "parbox") {
1026 if (p.next_token().cat() == catBegin)
1028 eat_whitespace(p, os, parent_context, false);
1029 shadedparbox = true;
1034 // If we already read the inner box we have to push the inner env
1035 if (!outer_type.empty() && !inner_type.empty() &&
1036 (inner_flags & FLAG_END))
1037 active_environments.push_back(inner_type);
1038 bool use_ert = false;
1039 if (!outer_type.empty() && !inner_type.empty()) {
1040 // Look whether there is some content after the end of the
1041 // inner box, but before the end of the outer box.
1042 // If yes, we need to output ERT.
1044 if (inner_flags & FLAG_END)
1045 p.ertEnvironment(inner_type);
1048 p.skip_spaces(true);
1049 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
1050 if ((outer_env && p.next_token().asInput() != "\\end") ||
1051 (!outer_env && p.next_token().cat() != catEnd)) {
1052 // something is between the end of the inner box and
1053 // the end of the outer box, so we need to use ERT.
1061 if (!outer_type.empty()) {
1062 if (outer_flags & FLAG_END)
1063 ss << "\\begin{" << outer_type << '}';
1065 ss << '\\' << outer_type << '{';
1066 if (!special.empty())
1070 if (!inner_type.empty()) {
1071 if (inner_type != "shaded") {
1072 if (inner_flags & FLAG_END)
1073 ss << "\\begin{" << inner_type << '}';
1075 ss << '\\' << inner_type;
1077 if (!position.empty())
1078 ss << '[' << position << ']';
1079 if (!latex_height.empty())
1080 ss << '[' << latex_height << ']';
1081 if (!inner_pos.empty())
1082 ss << '[' << inner_pos << ']';
1083 ss << '{' << latex_width << '}';
1084 if (!(inner_flags & FLAG_END))
1087 if (inner_type == "shaded")
1088 ss << "\\begin{shaded}";
1089 output_ert_inset(os, ss.str(), parent_context);
1090 if (!inner_type.empty()) {
1091 parse_text(p, os, inner_flags, outer, parent_context);
1092 if (inner_flags & FLAG_END)
1093 output_ert_inset(os, "\\end{" + inner_type + '}',
1096 output_ert_inset(os, "}", parent_context);
1098 if (!outer_type.empty()) {
1099 // If we already read the inner box we have to pop
1101 if (!inner_type.empty() && (inner_flags & FLAG_END))
1102 active_environments.pop_back();
1104 // Ensure that the end of the outer box is parsed correctly:
1105 // The opening brace has been eaten by parse_outer_box()
1106 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1107 outer_flags &= ~FLAG_ITEM;
1108 outer_flags |= FLAG_BRACE_LAST;
1110 parse_text(p, os, outer_flags, outer, parent_context);
1111 if (outer_flags & FLAG_END)
1112 output_ert_inset(os, "\\end{" + outer_type + '}',
1115 output_ert_inset(os, "}", parent_context);
1118 // LyX does not like empty positions, so we have
1119 // to set them to the LaTeX default values here.
1120 if (position.empty())
1122 if (inner_pos.empty())
1123 inner_pos = position;
1124 parent_context.check_layout(os);
1125 begin_inset(os, "Box ");
1126 if (outer_type == "framed")
1128 else if (outer_type == "framebox" || outer_type == "fbox" || !frame_color.empty())
1130 else if (outer_type == "shadowbox")
1131 os << "Shadowbox\n";
1132 else if ((outer_type == "shaded" && inner_type.empty()) ||
1133 (outer_type == "minipage" && inner_type == "shaded") ||
1134 (outer_type == "parbox" && inner_type == "shaded")) {
1136 preamble.registerAutomaticallyLoadedPackage("color");
1137 } else if (outer_type == "doublebox")
1138 os << "Doublebox\n";
1139 else if (outer_type.empty() || outer_type == "mbox")
1140 os << "Frameless\n";
1142 os << outer_type << '\n';
1143 os << "position \"" << position << "\"\n";
1144 os << "hor_pos \"" << hor_pos << "\"\n";
1145 if (outer_type == "mbox")
1146 os << "has_inner_box 1\n";
1147 else if (!frame_color.empty() && inner_type == "makebox")
1148 os << "has_inner_box 0\n";
1150 os << "has_inner_box " << !inner_type.empty() << "\n";
1151 os << "inner_pos \"" << inner_pos << "\"\n";
1152 os << "use_parbox " << (inner_type == "parbox" || shadedparbox)
1154 if (outer_type == "mbox")
1155 os << "use_makebox 1\n";
1156 else if (!frame_color.empty())
1157 os << "use_makebox 0\n";
1159 os << "use_makebox " << (inner_type == "makebox") << '\n';
1160 if (outer_type == "mbox" || (outer_type == "fbox" && inner_type.empty()))
1161 os << "width \"\"\n";
1162 // for values like "1.5\width" LyX uses "1.5in" as width ad sets "width" as sepecial
1163 else if (contains(width_unit, '\\'))
1164 os << "width \"" << width_value << "in" << "\"\n";
1166 os << "width \"" << width_value << width_unit << "\"\n";
1167 if (contains(width_unit, '\\')) {
1168 width_unit.erase (0,1); // remove the leading '\'
1169 os << "special \"" << width_unit << "\"\n";
1171 os << "special \"" << width_special << "\"\n";
1172 if (contains(height_unit, '\\'))
1173 os << "height \"" << height_value << "in" << "\"\n";
1175 os << "height \"" << height_value << height_unit << "\"\n";
1176 os << "height_special \"" << height_special << "\"\n";
1177 os << "thickness \"" << thickness << "\"\n";
1178 os << "separation \"" << separation << "\"\n";
1179 os << "shadowsize \"" << shadowsize << "\"\n";
1180 os << "framecolor \"" << framecolor << "\"\n";
1181 os << "backgroundcolor \"" << backgroundcolor << "\"\n";
1182 os << "status open\n\n";
1184 // Unfortunately we can't use parse_text_in_inset:
1185 // InsetBox::forcePlainLayout() is hard coded and does not
1186 // use the inset layout. Apart from that do we call parse_text
1187 // up to two times, but need only one check_end_layout.
1188 bool const forcePlainLayout =
1189 (!inner_type.empty() || inner_type == "makebox") &&
1190 outer_type != "shaded" && outer_type != "framed";
1191 Context context(true, parent_context.textclass);
1192 if (forcePlainLayout)
1193 context.layout = &context.textclass.plainLayout();
1195 context.font = parent_context.font;
1197 // If we have no inner box the contents will be read with the outer box
1198 if (!inner_type.empty())
1199 parse_text(p, os, inner_flags, outer, context);
1201 // Ensure that the end of the outer box is parsed correctly:
1202 // The opening brace has been eaten by parse_outer_box()
1203 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
1204 outer_flags &= ~FLAG_ITEM;
1205 outer_flags |= FLAG_BRACE_LAST;
1208 // Find end of outer box, output contents if inner_type is
1209 // empty and output possible comments
1210 if (!outer_type.empty()) {
1211 // If we already read the inner box we have to pop
1213 if (!inner_type.empty() && (inner_flags & FLAG_END))
1214 active_environments.pop_back();
1215 // This does not output anything but comments if
1216 // inner_type is not empty (see use_ert)
1217 parse_text(p, os, outer_flags, outer, context);
1220 context.check_end_layout(os);
1222 #ifdef PRESERVE_LAYOUT
1223 // LyX puts a % after the end of the minipage
1224 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
1226 //output_comment(p, os, "dummy", parent_context);
1229 parent_context.new_paragraph(os);
1231 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
1232 //output_comment(p, os, "dummy", parent_context);
1235 // We add a protected space if something real follows
1236 if (p.good() && p.next_token().cat() != catComment) {
1237 begin_inset(os, "space ~\n");
1243 if (inner_type == "minipage" && (!frame_color.empty() || !background_color.empty()))
1244 active_environments.pop_back();
1245 if (inner_flags != FLAG_BRACE_LAST && (!frame_color.empty() || !background_color.empty())) {
1246 // in this case we have to eat the the closing brace of the color box
1247 p.get_token().asInput(); // the '}'
1249 if (p.next_token().asInput() == "}") {
1250 // in this case we assume that the closing brace is from the box settings
1251 // therefore reset these values for the next box
1257 // all boxes except of Frameless and Shaded require calc
1258 if (!(outer_type.empty() || outer_type == "mbox") &&
1259 !((outer_type == "shaded" && inner_type.empty()) ||
1260 (outer_type == "minipage" && inner_type == "shaded") ||
1261 (outer_type == "parbox" && inner_type == "shaded")))
1262 preamble.registerAutomaticallyLoadedPackage("calc");
1266 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
1267 Context & parent_context, string const & outer_type,
1268 string const & special)
1270 eat_whitespace(p, os, parent_context, false);
1271 if (flags & FLAG_ITEM) {
1273 if (p.next_token().cat() == catBegin)
1276 cerr << "Warning: Ignoring missing '{' after \\"
1277 << outer_type << '.' << endl;
1278 eat_whitespace(p, os, parent_context, false);
1281 unsigned int inner_flags = 0;
1283 if (outer_type == "minipage" || outer_type == "parbox") {
1284 p.skip_spaces(true);
1285 while (p.hasOpt()) {
1287 p.skip_spaces(true);
1290 p.skip_spaces(true);
1291 if (outer_type == "parbox") {
1293 if (p.next_token().cat() == catBegin)
1295 p.skip_spaces(true);
1298 if (outer_type == "shaded" || outer_type == "mbox") {
1299 // These boxes never have an inner box
1301 } else if (p.next_token().asInput() == "\\parbox") {
1302 inner = p.get_token().cs();
1303 inner_flags = FLAG_ITEM;
1304 } else if (p.next_token().asInput() == "\\begin") {
1305 // Is this a minipage or shaded box?
1308 inner = p.getArg('{', '}');
1310 if (inner == "minipage" || inner == "shaded")
1311 inner_flags = FLAG_END;
1316 if (inner_flags == FLAG_END) {
1317 if (inner != "shaded")
1321 eat_whitespace(p, os, parent_context, false);
1323 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1324 outer_type, special, inner, "", "");
1326 if (inner_flags == FLAG_ITEM) {
1328 eat_whitespace(p, os, parent_context, false);
1330 parse_box(p, os, flags, inner_flags, outer, parent_context,
1331 outer_type, special, inner, "", "");
1336 void parse_listings(Parser & p, ostream & os, Context & parent_context,
1337 bool in_line, bool use_minted)
1339 parent_context.check_layout(os);
1340 begin_inset(os, "listings\n");
1341 string arg = p.hasOpt() ? subst(p.verbatimOption(), "\n", "") : string();
1343 while ((i = arg.find(", ")) != string::npos
1344 || (i = arg.find(",\t")) != string::npos)
1345 arg.erase(i + 1, 1);
1348 string const language = p.getArg('{', '}');
1349 p.skip_spaces(true);
1350 arg += string(arg.empty() ? "" : ",") + "language=" + language;
1351 if (!minted_float.empty()) {
1352 arg += string(arg.empty() ? "" : ",") + minted_float;
1353 minted_nonfloat_caption.clear();
1357 os << "lstparams " << '"' << arg << '"' << '\n';
1358 if (arg.find("\\color") != string::npos)
1359 preamble.registerAutomaticallyLoadedPackage("color");
1362 os << "inline true\n";
1364 os << "inline false\n";
1365 os << "status collapsed\n";
1366 Context context(true, parent_context.textclass);
1367 context.layout = &parent_context.textclass.plainLayout();
1368 if (use_minted && prefixIs(minted_nonfloat_caption, "[t]")) {
1369 minted_nonfloat_caption.erase(0,3);
1370 os << "\n\\begin_layout Plain Layout\n";
1371 begin_inset(os, "Caption Standard\n");
1372 Context newcontext(true, context.textclass,
1373 context.layout, 0, context.font);
1374 newcontext.check_layout(os);
1375 os << minted_nonfloat_caption << "\n";
1376 newcontext.check_end_layout(os);
1378 os << "\n\\end_layout\n";
1379 minted_nonfloat_caption.clear();
1383 // set catcodes to verbatim early, just in case.
1384 p.setCatcodes(VERBATIM_CATCODES);
1385 string delim = p.get_token().asInput();
1386 //FIXME: handler error condition
1387 s = p.verbatimStuff(delim).second;
1388 // context.new_paragraph(os);
1389 } else if (use_minted) {
1390 s = p.verbatimEnvironment("minted");
1392 s = p.verbatimEnvironment("lstlisting");
1394 output_ert(os, s, context);
1395 if (use_minted && prefixIs(minted_nonfloat_caption, "[b]")) {
1396 minted_nonfloat_caption.erase(0,3);
1397 os << "\n\\begin_layout Plain Layout\n";
1398 begin_inset(os, "Caption Standard\n");
1399 Context newcontext(true, context.textclass,
1400 context.layout, 0, context.font);
1401 newcontext.check_layout(os);
1402 os << minted_nonfloat_caption << "\n";
1403 newcontext.check_end_layout(os);
1405 os << "\n\\end_layout\n";
1406 minted_nonfloat_caption.clear();
1408 // Don't close the inset here for floating minted listings.
1409 // It will be closed at the end of the listing environment.
1410 if (!use_minted || minted_float.empty())
1413 eat_whitespace(p, os, parent_context, true);
1414 Token t = p.get_token();
1415 if (t.asInput() != "\\end") {
1416 // If anything follows, collect it into a caption.
1417 minted_float_has_caption = true;
1418 os << "\n\\begin_layout Plain Layout\n"; // outer layout
1419 begin_inset(os, "Caption Standard\n");
1420 os << "\n\\begin_layout Plain Layout\n"; // inner layout
1427 /// parse an unknown environment
1428 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1429 unsigned flags, bool outer,
1430 Context & parent_context)
1432 if (name == "tabbing")
1433 // We need to remember that we have to handle '\=' specially
1434 flags |= FLAG_TABBING;
1436 // We need to translate font changes and paragraphs inside the
1437 // environment to ERT if we have a non standard font.
1438 // Otherwise things like
1439 // \large\begin{foo}\huge bar\end{foo}
1441 bool const specialfont =
1442 (parent_context.font != parent_context.normalfont);
1443 bool const new_layout_allowed = parent_context.new_layout_allowed;
1445 parent_context.new_layout_allowed = false;
1446 output_ert_inset(os, "\\begin{" + name + "}", parent_context);
1447 parse_text_snippet(p, os, flags, outer, parent_context);
1448 output_ert_inset(os, "\\end{" + name + "}", parent_context);
1450 parent_context.new_layout_allowed = new_layout_allowed;
1454 void parse_environment(Parser & p, ostream & os, bool outer,
1455 string & last_env, Context & parent_context)
1457 Layout const * newlayout;
1458 InsetLayout const * newinsetlayout = 0;
1459 string const name = p.getArg('{', '}');
1460 const bool is_starred = suffixIs(name, '*');
1461 string const unstarred_name = rtrim(name, "*");
1462 active_environments.push_back(name);
1464 if (is_math_env(name)) {
1465 parent_context.check_layout(os);
1466 begin_inset(os, "Formula ");
1467 os << "\\begin{" << name << "}";
1468 parse_math(p, os, FLAG_END, MATH_MODE);
1469 os << "\\end{" << name << "}";
1471 if (is_display_math_env(name)) {
1472 // Prevent the conversion of a line break to a space
1473 // (bug 7668). This does not change the output, but
1474 // looks ugly in LyX.
1475 eat_whitespace(p, os, parent_context, false);
1479 else if (is_known(name, preamble.polyglossia_languages)) {
1480 // We must begin a new paragraph if not already done
1481 if (! parent_context.atParagraphStart()) {
1482 parent_context.check_end_layout(os);
1483 parent_context.new_paragraph(os);
1485 // save the language in the context so that it is
1486 // handled by parse_text
1487 parent_context.font.language = preamble.polyglossia2lyx(name);
1488 parse_text(p, os, FLAG_END, outer, parent_context);
1489 // Just in case the environment is empty
1490 parent_context.extra_stuff.erase();
1491 // We must begin a new paragraph to reset the language
1492 parent_context.new_paragraph(os);
1496 else if (unstarred_name == "tabular" || name == "longtable") {
1497 eat_whitespace(p, os, parent_context, false);
1498 string width = "0pt";
1499 if (name == "tabular*") {
1500 width = lyx::translate_len(p.getArg('{', '}'));
1501 eat_whitespace(p, os, parent_context, false);
1503 parent_context.check_layout(os);
1504 begin_inset(os, "Tabular ");
1505 handle_tabular(p, os, name, width, parent_context);
1510 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1511 eat_whitespace(p, os, parent_context, false);
1512 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1513 eat_whitespace(p, os, parent_context, false);
1514 parent_context.check_layout(os);
1515 begin_inset(os, "Float " + unstarred_name + "\n");
1516 // store the float type for subfloats
1517 // subfloats only work with figures and tables
1518 if (unstarred_name == "figure")
1519 float_type = unstarred_name;
1520 else if (unstarred_name == "table")
1521 float_type = unstarred_name;
1525 os << "placement " << opt << '\n';
1526 if (contains(opt, "H"))
1527 preamble.registerAutomaticallyLoadedPackage("float");
1529 Floating const & fl = parent_context.textclass.floats()
1530 .getType(unstarred_name);
1531 if (!fl.floattype().empty() && fl.usesFloatPkg())
1532 preamble.registerAutomaticallyLoadedPackage("float");
1535 os << "wide " << convert<string>(is_starred)
1536 << "\nsideways false"
1537 << "\nstatus open\n\n";
1538 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1540 // We don't need really a new paragraph, but
1541 // we must make sure that the next item gets a \begin_layout.
1542 parent_context.new_paragraph(os);
1544 // the float is parsed thus delete the type
1548 else if (unstarred_name == "sidewaysfigure"
1549 || unstarred_name == "sidewaystable"
1550 || unstarred_name == "sidewaysalgorithm") {
1551 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1552 eat_whitespace(p, os, parent_context, false);
1553 parent_context.check_layout(os);
1554 if (unstarred_name == "sidewaysfigure")
1555 begin_inset(os, "Float figure\n");
1556 else if (unstarred_name == "sidewaystable")
1557 begin_inset(os, "Float table\n");
1558 else if (unstarred_name == "sidewaysalgorithm")
1559 begin_inset(os, "Float algorithm\n");
1561 os << "placement " << opt << '\n';
1562 if (contains(opt, "H"))
1563 preamble.registerAutomaticallyLoadedPackage("float");
1564 os << "wide " << convert<string>(is_starred)
1565 << "\nsideways true"
1566 << "\nstatus open\n\n";
1567 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1569 // We don't need really a new paragraph, but
1570 // we must make sure that the next item gets a \begin_layout.
1571 parent_context.new_paragraph(os);
1573 preamble.registerAutomaticallyLoadedPackage("rotfloat");
1576 else if (name == "wrapfigure" || name == "wraptable") {
1577 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1578 eat_whitespace(p, os, parent_context, false);
1579 parent_context.check_layout(os);
1582 string overhang = "0col%";
1585 lines = p.getArg('[', ']');
1586 string const placement = p.getArg('{', '}');
1588 overhang = p.getArg('[', ']');
1589 string const width = p.getArg('{', '}');
1591 if (name == "wrapfigure")
1592 begin_inset(os, "Wrap figure\n");
1594 begin_inset(os, "Wrap table\n");
1595 os << "lines " << lines
1596 << "\nplacement " << placement
1597 << "\noverhang " << lyx::translate_len(overhang)
1598 << "\nwidth " << lyx::translate_len(width)
1599 << "\nstatus open\n\n";
1600 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1602 // We don't need really a new paragraph, but
1603 // we must make sure that the next item gets a \begin_layout.
1604 parent_context.new_paragraph(os);
1606 preamble.registerAutomaticallyLoadedPackage("wrapfig");
1609 else if (name == "minipage") {
1610 eat_whitespace(p, os, parent_context, false);
1611 // Test whether this is an outer box of a shaded box
1613 // swallow arguments
1614 while (p.hasOpt()) {
1616 p.skip_spaces(true);
1619 p.skip_spaces(true);
1620 Token t = p.get_token();
1621 bool shaded = false;
1622 if (t.asInput() == "\\begin") {
1623 p.skip_spaces(true);
1624 if (p.getArg('{', '}') == "shaded")
1629 parse_outer_box(p, os, FLAG_END, outer,
1630 parent_context, name, "shaded");
1632 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1633 "", "", name, "", "");
1637 else if (name == "comment") {
1638 eat_whitespace(p, os, parent_context, false);
1639 parent_context.check_layout(os);
1640 begin_inset(os, "Note Comment\n");
1641 os << "status open\n";
1642 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1645 skip_braces(p); // eat {} that might by set by LyX behind comments
1646 preamble.registerAutomaticallyLoadedPackage("verbatim");
1649 else if (unstarred_name == "verbatim") {
1650 // FIXME: this should go in the generic code that
1651 // handles environments defined in layout file that
1652 // have "PassThru 1". However, the code over there is
1653 // already too complicated for my taste.
1654 string const ascii_name =
1655 (name == "verbatim*") ? "Verbatim*" : "Verbatim";
1656 parent_context.new_paragraph(os);
1657 Context context(true, parent_context.textclass,
1658 &parent_context.textclass[from_ascii(ascii_name)]);
1659 string s = p.verbatimEnvironment(name);
1660 output_ert(os, s, context);
1664 else if (name == "IPA") {
1665 eat_whitespace(p, os, parent_context, false);
1666 parent_context.check_layout(os);
1667 begin_inset(os, "IPA\n");
1668 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1671 preamble.registerAutomaticallyLoadedPackage("tipa");
1672 preamble.registerAutomaticallyLoadedPackage("tipx");
1675 else if (name == "CJK") {
1676 // the scheme is \begin{CJK}{encoding}{mapping}text\end{CJK}
1677 // It is impossible to decide if a CJK environment was in its own paragraph or within
1678 // a line. We therefore always assume a paragraph since the latter is a rare case.
1679 eat_whitespace(p, os, parent_context, false);
1680 parent_context.check_end_layout(os);
1681 // store the encoding to be able to reset it
1682 string const encoding_old = p.getEncoding();
1683 string const encoding = p.getArg('{', '}');
1684 // FIXME: For some reason JIS does not work. Although the text
1685 // in tests/CJK.tex is identical with the SJIS version if you
1686 // convert both snippets using the recode command line utility,
1687 // the resulting .lyx file contains some extra characters if
1688 // you set buggy_encoding to false for JIS.
1689 bool const buggy_encoding = encoding == "JIS";
1690 if (!buggy_encoding)
1691 p.setEncoding(encoding, Encoding::CJK);
1693 // FIXME: This will read garbage, since the data is not encoded in utf8.
1694 p.setEncoding("UTF-8");
1696 // LyX only supports the same mapping for all CJK
1697 // environments, so we might need to output everything as ERT
1698 string const mapping = trim(p.getArg('{', '}'));
1699 char const * const * const where =
1700 is_known(encoding, supported_CJK_encodings);
1701 if (!buggy_encoding && !preamble.fontCJKSet())
1702 preamble.fontCJK(mapping);
1703 bool knownMapping = mapping == preamble.fontCJK();
1704 if (buggy_encoding || !knownMapping || !where) {
1705 parent_context.check_layout(os);
1706 output_ert_inset(os, "\\begin{" + name + "}{" + encoding + "}{" + mapping + "}",
1708 // we must parse the content as verbatim because e.g. JIS can contain
1709 // normally invalid characters
1710 // FIXME: This works only for the most simple cases.
1711 // Since TeX control characters are not parsed,
1712 // things like comments are completely wrong.
1713 string const s = p.plainEnvironment("CJK");
1714 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1716 output_ert_inset(os, "\\", parent_context);
1717 else if (*it == '$')
1718 output_ert_inset(os, "$", parent_context);
1719 else if (*it == '\n' && it + 1 != et && s.begin() + 1 != it)
1724 output_ert_inset(os, "\\end{" + name + "}",
1728 supported_CJK_languages[where - supported_CJK_encodings];
1729 // store the language because we must reset it at the end
1730 string const lang_old = parent_context.font.language;
1731 parent_context.font.language = lang;
1732 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1733 parent_context.font.language = lang_old;
1734 parent_context.new_paragraph(os);
1736 p.setEncoding(encoding_old);
1740 else if (name == "lyxgreyedout") {
1741 eat_whitespace(p, os, parent_context, false);
1742 parent_context.check_layout(os);
1743 begin_inset(os, "Note Greyedout\n");
1744 os << "status open\n";
1745 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1748 if (!preamble.notefontcolor().empty())
1749 preamble.registerAutomaticallyLoadedPackage("color");
1752 else if (name == "btSect") {
1753 eat_whitespace(p, os, parent_context, false);
1754 parent_context.check_layout(os);
1755 begin_command_inset(os, "bibtex", "bibtex");
1756 string bibstyle = "plain";
1758 bibstyle = p.getArg('[', ']');
1759 p.skip_spaces(true);
1761 string const bibfile = p.getArg('{', '}');
1762 eat_whitespace(p, os, parent_context, false);
1763 Token t = p.get_token();
1764 if (t.asInput() == "\\btPrintCited") {
1765 p.skip_spaces(true);
1766 os << "btprint " << '"' << "btPrintCited" << '"' << "\n";
1768 if (t.asInput() == "\\btPrintNotCited") {
1769 p.skip_spaces(true);
1770 os << "btprint " << '"' << "btPrintNotCited" << '"' << "\n";
1772 if (t.asInput() == "\\btPrintAll") {
1773 p.skip_spaces(true);
1774 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
1776 os << "bibfiles " << '"' << bibfile << "\"\n"
1777 << "options " << '"' << bibstyle << "\"\n";
1778 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1783 else if (name == "framed" || name == "shaded") {
1784 eat_whitespace(p, os, parent_context, false);
1785 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1787 preamble.registerAutomaticallyLoadedPackage("framed");
1790 else if (name == "listing") {
1791 minted_float = "float";
1792 eat_whitespace(p, os, parent_context, false);
1793 string const opt = p.hasOpt() ? p.getArg('[', ']') : string();
1795 minted_float += "=" + opt;
1796 // If something precedes \begin{minted}, we output it at the end
1797 // as a caption, in order to keep it inside the listings inset.
1798 eat_whitespace(p, os, parent_context, true);
1800 Token const & t = p.get_token();
1801 p.skip_spaces(true);
1802 string const envname = p.next_token().cat() == catBegin
1803 ? p.getArg('{', '}') : string();
1804 bool prologue = t.asInput() != "\\begin" || envname != "minted";
1806 minted_float_has_caption = false;
1807 string content = parse_text_snippet(p, FLAG_END, outer,
1809 size_t i = content.find("\\begin_inset listings");
1810 bool minted_env = i != string::npos;
1813 caption = content.substr(0, i);
1814 content.erase(0, i);
1816 parent_context.check_layout(os);
1817 if (minted_env && minted_float_has_caption) {
1818 eat_whitespace(p, os, parent_context, true);
1819 os << content << "\n";
1820 if (!caption.empty())
1821 os << caption << "\n";
1822 os << "\n\\end_layout\n"; // close inner layout
1823 end_inset(os); // close caption inset
1824 os << "\n\\end_layout\n"; // close outer layout
1825 } else if (!caption.empty()) {
1827 begin_inset(os, "listings\n");
1828 os << "lstparams " << '"' << minted_float << '"' << '\n';
1829 os << "inline false\n";
1830 os << "status collapsed\n";
1832 os << "\n\\begin_layout Plain Layout\n";
1833 begin_inset(os, "Caption Standard\n");
1834 Context newcontext(true, parent_context.textclass,
1835 0, 0, parent_context.font);
1836 newcontext.check_layout(os);
1837 os << caption << "\n";
1838 newcontext.check_end_layout(os);
1840 os << "\n\\end_layout\n";
1841 } else if (content.empty()) {
1842 begin_inset(os, "listings\n");
1843 os << "lstparams " << '"' << minted_float << '"' << '\n';
1844 os << "inline false\n";
1845 os << "status collapsed\n";
1847 os << content << "\n";
1849 end_inset(os); // close listings inset
1850 parent_context.check_end_layout(os);
1851 parent_context.new_paragraph(os);
1853 minted_float.clear();
1854 minted_float_has_caption = false;
1857 else if (name == "lstlisting" || name == "minted") {
1858 bool use_minted = name == "minted";
1859 eat_whitespace(p, os, parent_context, false);
1860 if (use_minted && minted_float.empty()) {
1861 // look ahead for a bottom caption
1863 bool found_end_minted = false;
1864 while (!found_end_minted && p.good()) {
1865 Token const & t = p.get_token();
1867 string const envname =
1868 p.next_token().cat() == catBegin
1869 ? p.getArg('{', '}') : string();
1870 found_end_minted = t.asInput() == "\\end"
1871 && envname == "minted";
1873 eat_whitespace(p, os, parent_context, true);
1874 Token const & t = p.get_token();
1875 p.skip_spaces(true);
1876 if (t.asInput() == "\\lyxmintcaption") {
1877 string const pos = p.getArg('[', ']');
1879 string const caption =
1880 parse_text_snippet(p, FLAG_ITEM,
1881 false, parent_context);
1882 minted_nonfloat_caption = "[b]" + caption;
1887 parse_listings(p, os, parent_context, false, use_minted);
1891 else if (!parent_context.new_layout_allowed)
1892 parse_unknown_environment(p, name, os, FLAG_END, outer,
1895 // Alignment and spacing settings
1896 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1897 // therefore are totally broken!
1898 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1899 // they are commands not environments. They are furthermore switches that
1900 // can be ended by another switches, but also by commands like \footnote or
1901 // \parbox. So the only safe way is to leave them untouched.
1902 else if (name == "center" || name == "centering" ||
1903 name == "flushleft" || name == "flushright" ||
1904 name == "singlespace" || name == "onehalfspace" ||
1905 name == "doublespace" || name == "spacing") {
1906 eat_whitespace(p, os, parent_context, false);
1907 // We must begin a new paragraph if not already done
1908 if (! parent_context.atParagraphStart()) {
1909 parent_context.check_end_layout(os);
1910 parent_context.new_paragraph(os);
1912 if (name == "flushleft")
1913 parent_context.add_extra_stuff("\\align left\n");
1914 else if (name == "flushright")
1915 parent_context.add_extra_stuff("\\align right\n");
1916 else if (name == "center" || name == "centering")
1917 parent_context.add_extra_stuff("\\align center\n");
1918 else if (name == "singlespace")
1919 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1920 else if (name == "onehalfspace") {
1921 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1922 preamble.registerAutomaticallyLoadedPackage("setspace");
1923 } else if (name == "doublespace") {
1924 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1925 preamble.registerAutomaticallyLoadedPackage("setspace");
1926 } else if (name == "spacing") {
1927 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1928 preamble.registerAutomaticallyLoadedPackage("setspace");
1930 parse_text(p, os, FLAG_END, outer, parent_context);
1931 // Just in case the environment is empty
1932 parent_context.extra_stuff.erase();
1933 // We must begin a new paragraph to reset the alignment
1934 parent_context.new_paragraph(os);
1938 // The single '=' is meant here.
1939 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1940 eat_whitespace(p, os, parent_context, false);
1941 Context context(true, parent_context.textclass, newlayout,
1942 parent_context.layout, parent_context.font);
1943 if (parent_context.deeper_paragraph) {
1944 // We are beginning a nested environment after a
1945 // deeper paragraph inside the outer list environment.
1946 // Therefore we don't need to output a "begin deeper".
1947 context.need_end_deeper = true;
1949 parent_context.check_end_layout(os);
1950 if (last_env == name) {
1951 // we need to output a separator since LyX would export
1952 // the two environments as one otherwise (bug 5716)
1953 TeX2LyXDocClass const & textclass(parent_context.textclass);
1954 Context newcontext(true, textclass,
1955 &(textclass.defaultLayout()));
1956 newcontext.check_layout(os);
1957 begin_inset(os, "Separator plain\n");
1959 newcontext.check_end_layout(os);
1961 switch (context.layout->latextype) {
1962 case LATEX_LIST_ENVIRONMENT:
1963 context.add_par_extra_stuff("\\labelwidthstring "
1964 + p.verbatim_item() + '\n');
1967 case LATEX_BIB_ENVIRONMENT:
1968 p.verbatim_item(); // swallow next arg
1974 context.check_deeper(os);
1975 // handle known optional and required arguments
1976 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1977 // It is impossible to place anything after the environment name,
1978 // but before the first \\item.
1979 if (context.layout->latextype == LATEX_ENVIRONMENT)
1980 output_arguments(os, p, outer, false, false, context,
1981 context.layout->latexargs());
1982 parse_text(p, os, FLAG_END, outer, context);
1983 if (context.layout->latextype == LATEX_ENVIRONMENT)
1984 output_arguments(os, p, outer, false, true, context,
1985 context.layout->postcommandargs());
1986 context.check_end_layout(os);
1987 if (parent_context.deeper_paragraph) {
1988 // We must suppress the "end deeper" because we
1989 // suppressed the "begin deeper" above.
1990 context.need_end_deeper = false;
1992 context.check_end_deeper(os);
1993 parent_context.new_paragraph(os);
1995 if (!preamble.titleLayoutFound())
1996 preamble.titleLayoutFound(newlayout->intitle);
1997 set<string> const & req = newlayout->requires();
1998 set<string>::const_iterator it = req.begin();
1999 set<string>::const_iterator en = req.end();
2000 for (; it != en; ++it)
2001 preamble.registerAutomaticallyLoadedPackage(*it);
2004 // The single '=' is meant here.
2005 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
2006 eat_whitespace(p, os, parent_context, false);
2007 parent_context.check_layout(os);
2008 begin_inset(os, "Flex ");
2009 docstring flex_name = newinsetlayout->name();
2010 // FIXME: what do we do if the prefix is not Flex: ?
2011 if (prefixIs(flex_name, from_ascii("Flex:")))
2012 flex_name.erase(0, 5);
2013 os << to_utf8(flex_name) << '\n'
2014 << "status collapsed\n";
2015 if (newinsetlayout->isPassThru()) {
2016 string const arg = p.verbatimEnvironment(name);
2017 Context context(true, parent_context.textclass,
2018 &parent_context.textclass.plainLayout(),
2019 parent_context.layout);
2020 output_ert(os, arg, parent_context);
2022 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2026 else if (name == "appendix") {
2027 // This is no good latex style, but it works and is used in some documents...
2028 eat_whitespace(p, os, parent_context, false);
2029 parent_context.check_end_layout(os);
2030 Context context(true, parent_context.textclass, parent_context.layout,
2031 parent_context.layout, parent_context.font);
2032 context.check_layout(os);
2033 os << "\\start_of_appendix\n";
2034 parse_text(p, os, FLAG_END, outer, context);
2035 context.check_end_layout(os);
2039 else if (known_environments.find(name) != known_environments.end()) {
2040 vector<ArgumentType> arguments = known_environments[name];
2041 // The last "argument" denotes wether we may translate the
2042 // environment contents to LyX
2043 // The default required if no argument is given makes us
2044 // compatible with the reLyXre environment.
2045 ArgumentType contents = arguments.empty() ?
2048 if (!arguments.empty())
2049 arguments.pop_back();
2050 // See comment in parse_unknown_environment()
2051 bool const specialfont =
2052 (parent_context.font != parent_context.normalfont);
2053 bool const new_layout_allowed =
2054 parent_context.new_layout_allowed;
2056 parent_context.new_layout_allowed = false;
2057 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2058 outer, parent_context);
2059 if (contents == verbatim)
2060 output_ert_inset(os, p.ertEnvironment(name),
2063 parse_text_snippet(p, os, FLAG_END, outer,
2065 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2067 parent_context.new_layout_allowed = new_layout_allowed;
2071 parse_unknown_environment(p, name, os, FLAG_END, outer,
2075 active_environments.pop_back();
2079 /// parses a comment and outputs it to \p os.
2080 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2082 LASSERT(t.cat() == catComment, return);
2083 if (!t.cs().empty()) {
2084 context.check_layout(os);
2085 output_comment(p, os, t.cs(), context);
2086 if (p.next_token().cat() == catNewline) {
2087 // A newline after a comment line starts a new
2089 if (context.new_layout_allowed) {
2090 if(!context.atParagraphStart())
2091 // Only start a new paragraph if not already
2092 // done (we might get called recursively)
2093 context.new_paragraph(os);
2095 output_ert_inset(os, "\n", context);
2096 eat_whitespace(p, os, context, true);
2099 // "%\n" combination
2106 * Reads spaces and comments until the first non-space, non-comment token.
2107 * New paragraphs (double newlines or \\par) are handled like simple spaces
2108 * if \p eatParagraph is true.
2109 * Spaces are skipped, but comments are written to \p os.
2111 void eat_whitespace(Parser & p, ostream & os, Context & context,
2115 Token const & t = p.get_token();
2116 if (t.cat() == catComment)
2117 parse_comment(p, os, t, context);
2118 else if ((! eatParagraph && p.isParagraph()) ||
2119 (t.cat() != catSpace && t.cat() != catNewline)) {
2128 * Set a font attribute, parse text and reset the font attribute.
2129 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2130 * \param currentvalue Current value of the attribute. Is set to the new
2131 * value during parsing.
2132 * \param newvalue New value of the attribute
2134 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2135 Context & context, string const & attribute,
2136 string & currentvalue, string const & newvalue)
2138 context.check_layout(os);
2139 string const oldvalue = currentvalue;
2140 currentvalue = newvalue;
2141 os << '\n' << attribute << ' ' << newvalue << "\n";
2142 parse_text_snippet(p, os, flags, outer, context);
2143 context.check_layout(os);
2144 os << '\n' << attribute << ' ' << oldvalue << "\n";
2145 currentvalue = oldvalue;
2149 /// get the arguments of a natbib or jurabib citation command
2150 void get_cite_arguments(Parser & p, bool natbibOrder,
2151 string & before, string & after)
2153 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2155 // text before the citation
2157 // text after the citation
2158 after = p.getFullOpt();
2160 if (!after.empty()) {
2161 before = p.getFullOpt();
2162 if (natbibOrder && !before.empty())
2163 swap(before, after);
2168 /// Convert filenames with TeX macros and/or quotes to something LyX
2170 string const normalize_filename(string const & name)
2175 Token const & t = p.get_token();
2176 if (t.cat() != catEscape)
2178 else if (t.cs() == "lyxdot") {
2179 // This is used by LyX for simple dots in relative
2183 } else if (t.cs() == "space") {
2186 } else if (t.cs() == "string") {
2187 // Convert \string" to " and \string~ to ~
2188 Token const & n = p.next_token();
2189 if (n.asInput() != "\"" && n.asInput() != "~")
2194 // Strip quotes. This is a bit complicated (see latex_path()).
2195 string full = os.str();
2196 if (!full.empty() && full[0] == '"') {
2197 string base = removeExtension(full);
2198 string ext = getExtension(full);
2199 if (!base.empty() && base[base.length()-1] == '"')
2202 return addExtension(trim(base, "\""), ext);
2203 if (full[full.length()-1] == '"')
2206 return trim(full, "\"");
2212 /// Convert \p name from TeX convention (relative to master file) to LyX
2213 /// convention (relative to .lyx file) if it is relative
2214 void fix_child_filename(string & name)
2216 string const absMasterTeX = getMasterFilePath(true);
2217 bool const isabs = FileName::isAbsolute(name);
2218 // convert from "relative to .tex master" to absolute original path
2220 name = makeAbsPath(name, absMasterTeX).absFileName();
2221 bool copyfile = copyFiles();
2222 string const absParentLyX = getParentFilePath(false);
2225 // convert from absolute original path to "relative to master file"
2226 string const rel = to_utf8(makeRelPath(from_utf8(name),
2227 from_utf8(absMasterTeX)));
2228 // re-interpret "relative to .tex file" as "relative to .lyx file"
2229 // (is different if the master .lyx file resides in a
2230 // different path than the master .tex file)
2231 string const absMasterLyX = getMasterFilePath(false);
2232 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2233 // Do not copy if the new path is impossible to create. Example:
2234 // absMasterTeX = "/foo/bar/"
2235 // absMasterLyX = "/bar/"
2236 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2237 if (contains(name, "/../"))
2244 // convert from absolute original path to
2245 // "relative to .lyx file"
2246 name = to_utf8(makeRelPath(from_utf8(abs),
2247 from_utf8(absParentLyX)));
2251 // convert from absolute original path to "relative to .lyx file"
2252 name = to_utf8(makeRelPath(from_utf8(name),
2253 from_utf8(absParentLyX)));
2258 void copy_file(FileName const & src, string dstname)
2262 string const absParent = getParentFilePath(false);
2264 if (FileName::isAbsolute(dstname))
2265 dst = FileName(dstname);
2267 dst = makeAbsPath(dstname, absParent);
2268 FileName const srcpath = src.onlyPath();
2269 FileName const dstpath = dst.onlyPath();
2270 if (equivalent(srcpath, dstpath))
2272 if (!dstpath.isDirectory()) {
2273 if (!dstpath.createPath()) {
2274 cerr << "Warning: Could not create directory for file `"
2275 << dst.absFileName() << "´." << endl;
2279 if (dst.isReadableFile()) {
2280 if (overwriteFiles())
2281 cerr << "Warning: Overwriting existing file `"
2282 << dst.absFileName() << "´." << endl;
2284 cerr << "Warning: Not overwriting existing file `"
2285 << dst.absFileName() << "´." << endl;
2289 if (!src.copyTo(dst))
2290 cerr << "Warning: Could not copy file `" << src.absFileName()
2291 << "´ to `" << dst.absFileName() << "´." << endl;
2295 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2296 bool parse_chunk(Parser & p, ostream & os, Context & context)
2298 // check whether a chunk is possible here.
2299 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2305 // read the parameters
2306 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2307 if (!params.first) {
2312 Parser::Arg const code = p.verbatimStuff("\n@");
2317 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2318 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2322 // The last newline read is important for paragraph handling
2326 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2327 // We must have a valid layout before outputting the Chunk inset.
2328 context.check_layout(os);
2329 Context chunkcontext(true, context.textclass);
2330 chunkcontext.layout = &context.textclass.plainLayout();
2331 begin_inset(os, "Flex Chunk");
2332 os << "\nstatus open\n";
2333 if (!params.second.empty()) {
2334 chunkcontext.check_layout(os);
2335 Context paramscontext(true, context.textclass);
2336 paramscontext.layout = &context.textclass.plainLayout();
2337 begin_inset(os, "Argument 1");
2338 os << "\nstatus open\n";
2339 output_ert(os, params.second, paramscontext);
2342 output_ert(os, code.second, chunkcontext);
2350 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2351 bool is_macro(Parser & p)
2353 Token first = p.curr_token();
2354 if (first.cat() != catEscape || !p.good())
2356 if (first.cs() == "def")
2358 if (first.cs() != "global" && first.cs() != "long")
2360 Token second = p.get_token();
2362 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2363 second.cat() == catNewline || second.cat() == catComment)) {
2364 second = p.get_token();
2367 bool secondvalid = second.cat() == catEscape;
2369 bool thirdvalid = false;
2370 if (p.good() && first.cs() == "global" && secondvalid &&
2371 second.cs() == "long") {
2372 third = p.get_token();
2374 while (p.good() && !p.isParagraph() &&
2375 (third.cat() == catSpace ||
2376 third.cat() == catNewline ||
2377 third.cat() == catComment)) {
2378 third = p.get_token();
2381 thirdvalid = third.cat() == catEscape;
2383 for (int i = 0; i < pos; ++i)
2388 return (first.cs() == "global" || first.cs() == "long") &&
2389 second.cs() == "def";
2390 return first.cs() == "global" && second.cs() == "long" &&
2391 third.cs() == "def";
2395 /// Parse a macro definition (assumes that is_macro() returned true)
2396 void parse_macro(Parser & p, ostream & os, Context & context)
2398 context.check_layout(os);
2399 Token first = p.curr_token();
2402 string command = first.asInput();
2403 if (first.cs() != "def") {
2405 eat_whitespace(p, os, context, false);
2406 second = p.curr_token();
2407 command += second.asInput();
2408 if (second.cs() != "def") {
2410 eat_whitespace(p, os, context, false);
2411 third = p.curr_token();
2412 command += third.asInput();
2415 eat_whitespace(p, os, context, false);
2416 string const name = p.get_token().cs();
2417 eat_whitespace(p, os, context, false);
2423 while (p.next_token().cat() != catBegin) {
2424 if (p.next_token().cat() == catParameter) {
2429 // followed by number?
2430 if (p.next_token().cat() == catOther) {
2431 string s = p.get_token().asInput();
2433 // number = current arity + 1?
2434 if (s.size() == 1 && s[0] == arity + '0' + 1)
2439 paramtext += p.get_token().cs();
2441 paramtext += p.get_token().cs();
2446 // only output simple (i.e. compatible) macro as FormulaMacros
2447 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2449 context.check_layout(os);
2450 begin_inset(os, "FormulaMacro");
2451 os << "\n\\def" << ert;
2454 output_ert_inset(os, command + ert, context);
2458 void registerExternalTemplatePackages(string const & name)
2460 external::TemplateManager const & etm = external::TemplateManager::get();
2461 external::Template const * const et = etm.getTemplateByName(name);
2464 external::Template::Formats::const_iterator cit = et->formats.end();
2466 cit = et->formats.find("PDFLaTeX");
2467 if (cit == et->formats.end())
2468 // If the template has not specified a PDFLaTeX output,
2469 // we try the LaTeX format.
2470 cit = et->formats.find("LaTeX");
2471 if (cit == et->formats.end())
2473 vector<string>::const_iterator qit = cit->second.requirements.begin();
2474 vector<string>::const_iterator qend = cit->second.requirements.end();
2475 for (; qit != qend; ++qit)
2476 preamble.registerAutomaticallyLoadedPackage(*qit);
2479 } // anonymous namespace
2482 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2485 Layout const * newlayout = 0;
2486 InsetLayout const * newinsetlayout = 0;
2487 char const * const * where = 0;
2488 // Store the latest bibliographystyle, addcontentslineContent and
2489 // nocite{*} option (needed for bibtex inset)
2491 string contentslineContent;
2492 // Some classes provide a \bibliographystyle, so do not output
2493 // any if none is explicitly set.
2494 string bibliographystyle;
2495 bool const use_natbib = isProvided("natbib");
2496 bool const use_jurabib = isProvided("jurabib");
2497 bool const use_biblatex = isProvided("biblatex")
2498 && preamble.citeEngine() != "biblatex-natbib";
2499 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2500 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2501 need_commentbib = use_biblatex || use_biblatex_natbib;
2504 // it is impossible to determine the correct encoding for non-CJK Japanese.
2505 // Therefore write a note at the beginning of the document
2506 if (is_nonCJKJapanese) {
2507 context.check_layout(os);
2508 begin_inset(os, "Note Note\n");
2509 os << "status open\n\\begin_layout Plain Layout\n"
2510 << "\\series bold\n"
2511 << "Important information:\n"
2512 << "\\end_layout\n\n"
2513 << "\\begin_layout Plain Layout\n"
2514 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2515 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2516 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2517 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2518 << " and specify the encoding using the -e command-line switch.\n"
2519 << " In addition, you might want to double check that the desired output encoding\n"
2520 << " is correctly selected in Document > Settings > Language.\n"
2521 << "\\end_layout\n";
2523 is_nonCJKJapanese = false;
2527 Token const & t = p.get_token();
2529 debugToken(cerr, t, flags);
2532 if (flags & FLAG_ITEM) {
2533 if (t.cat() == catSpace)
2536 flags &= ~FLAG_ITEM;
2537 if (t.cat() == catBegin) {
2538 // skip the brace and collect everything to the next matching
2540 flags |= FLAG_BRACE_LAST;
2544 // handle only this single token, leave the loop if done
2545 flags |= FLAG_LEAVE;
2548 if (t.cat() != catEscape && t.character() == ']' &&
2549 (flags & FLAG_BRACK_LAST))
2551 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2554 // If there is anything between \end{env} and \begin{env} we
2555 // don't need to output a separator.
2556 if (t.cat() != catSpace && t.cat() != catNewline &&
2557 t.asInput() != "\\begin")
2563 bool const starred = p.next_token().asInput() == "*";
2564 string const starredname(starred ? (t.cs() + '*') : t.cs());
2565 if (t.cat() == catMath) {
2566 // we are inside some text mode thingy, so opening new math is allowed
2567 context.check_layout(os);
2568 begin_inset(os, "Formula ");
2569 Token const & n = p.get_token();
2570 bool const display(n.cat() == catMath && outer);
2572 // TeX's $$...$$ syntax for displayed math
2574 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2576 p.get_token(); // skip the second '$' token
2578 // simple $...$ stuff
2581 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2586 // Prevent the conversion of a line break to a
2587 // space (bug 7668). This does not change the
2588 // output, but looks ugly in LyX.
2589 eat_whitespace(p, os, context, false);
2593 else if (t.cat() == catSuper || t.cat() == catSub)
2594 cerr << "catcode " << t << " illegal in text mode\n";
2596 // Basic support for english quotes. This should be
2597 // extended to other quotes, but is not so easy (a
2598 // left english quote is the same as a right german
2600 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2601 context.check_layout(os);
2602 begin_inset(os, "Quotes ");
2608 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2609 context.check_layout(os);
2610 begin_inset(os, "Quotes ");
2617 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2618 context.check_layout(os);
2619 begin_inset(os, "Quotes ");
2626 else if (t.asInput() == "<"
2627 && p.next_token().asInput() == "<") {
2628 bool has_chunk = false;
2632 has_chunk = parse_chunk(p, os, context);
2638 context.check_layout(os);
2639 begin_inset(os, "Quotes ");
2640 //FIXME: this is a right danish quote;
2641 // why not a left french quote?
2649 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2650 check_space(p, os, context);
2652 // babel shorthands (also used by polyglossia)
2653 // Since these can have different meanings for different languages
2654 // we import them as ERT (but they must be put in ERT to get output
2656 else if (t.asInput() == "\"") {
2658 // These are known pairs. We put them together in
2659 // one ERT inset. In other cases (such as "a), only
2660 // the quotation mark is ERTed.
2661 if (p.next_token().asInput() == "\""
2662 || p.next_token().asInput() == "|"
2663 || p.next_token().asInput() == "-"
2664 || p.next_token().asInput() == "~"
2665 || p.next_token().asInput() == "="
2666 || p.next_token().asInput() == "/"
2667 || p.next_token().asInput() == "~"
2668 || p.next_token().asInput() == "'"
2669 || p.next_token().asInput() == "`"
2670 || p.next_token().asInput() == "<"
2671 || p.next_token().asInput() == ">") {
2672 s += p.next_token().asInput();
2675 output_ert_inset(os, s, context);
2678 else if (t.character() == '[' && noweb_mode &&
2679 p.next_token().character() == '[') {
2680 // These can contain underscores
2682 string const s = p.getFullOpt() + ']';
2683 if (p.next_token().character() == ']')
2686 cerr << "Warning: Inserting missing ']' in '"
2687 << s << "'." << endl;
2688 output_ert_inset(os, s, context);
2691 else if (t.cat() == catLetter) {
2692 context.check_layout(os);
2696 else if (t.cat() == catOther ||
2697 t.cat() == catAlign ||
2698 t.cat() == catParameter) {
2699 context.check_layout(os);
2700 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2701 context.merging_hyphens_allowed &&
2702 context.font.family != "ttfamily" &&
2703 !context.layout->pass_thru) {
2704 if (p.next_next_token().asInput() == "-") {
2706 os << to_utf8(docstring(1, 0x2014));
2710 os << to_utf8(docstring(1, 0x2013));
2713 // This translates "&" to "\\&" which may be wrong...
2717 else if (p.isParagraph()) {
2718 // In minted floating listings we will collect
2719 // everything into the caption, where multiple
2720 // paragraphs are forbidden.
2721 if (minted_float.empty()) {
2722 if (context.new_layout_allowed)
2723 context.new_paragraph(os);
2725 output_ert_inset(os, "\\par ", context);
2728 eat_whitespace(p, os, context, true);
2731 else if (t.cat() == catActive) {
2732 context.check_layout(os);
2733 if (t.character() == '~') {
2734 if (context.layout->free_spacing)
2737 begin_inset(os, "space ~\n");
2744 else if (t.cat() == catBegin) {
2745 Token const next = p.next_token();
2746 Token const end = p.next_next_token();
2747 if (next.cat() == catEnd) {
2749 Token const prev = p.prev_token();
2751 if (p.next_token().character() == '`')
2752 ; // ignore it in {}``
2754 output_ert_inset(os, "{}", context);
2755 } else if (next.cat() == catEscape &&
2756 is_known(next.cs(), known_quotes) &&
2757 end.cat() == catEnd) {
2758 // Something like {\textquoteright} (e.g.
2759 // from writer2latex). LyX writes
2760 // \textquoteright{}, so we may skip the
2761 // braces here for better readability.
2762 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2764 } else if (p.next_token().asInput() == "\\ascii") {
2765 // handle the \ascii characters
2766 // (the case without braces is handled later)
2767 // the code is "{\ascii\xxx}"
2768 p.get_token(); // eat \ascii
2769 string name2 = p.get_token().asInput();
2770 p.get_token(); // eat the final '}'
2771 string const name = "{\\ascii" + name2 + "}";
2775 // get the character from unicodesymbols
2776 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2777 Encodings::TEXT_CMD, termination, rem, &req);
2779 context.check_layout(os);
2782 output_ert_inset(os,
2783 to_utf8(rem), context);
2784 for (set<string>::const_iterator it = req.begin();
2785 it != req.end(); ++it)
2786 preamble.registerAutomaticallyLoadedPackage(*it);
2788 // we did not find a non-ert version
2789 output_ert_inset(os, name, context);
2791 context.check_layout(os);
2792 // special handling of font attribute changes
2793 Token const prev = p.prev_token();
2794 TeXFont const oldFont = context.font;
2795 if (next.character() == '[' ||
2796 next.character() == ']' ||
2797 next.character() == '*') {
2799 if (p.next_token().cat() == catEnd) {
2804 output_ert_inset(os, "{", context);
2805 parse_text_snippet(p, os,
2808 output_ert_inset(os, "}", context);
2810 } else if (! context.new_layout_allowed) {
2811 output_ert_inset(os, "{", context);
2812 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2814 output_ert_inset(os, "}", context);
2815 } else if (is_known(next.cs(), known_sizes)) {
2816 // next will change the size, so we must
2818 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2820 if (!context.atParagraphStart())
2822 << context.font.size << "\n";
2823 } else if (is_known(next.cs(), known_font_families)) {
2824 // next will change the font family, so we
2825 // must reset it here
2826 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2828 if (!context.atParagraphStart())
2830 << context.font.family << "\n";
2831 } else if (is_known(next.cs(), known_font_series)) {
2832 // next will change the font series, so we
2833 // must reset it here
2834 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2836 if (!context.atParagraphStart())
2838 << context.font.series << "\n";
2839 } else if (is_known(next.cs(), known_font_shapes)) {
2840 // next will change the font shape, so we
2841 // must reset it here
2842 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2844 if (!context.atParagraphStart())
2846 << context.font.shape << "\n";
2847 } else if (is_known(next.cs(), known_old_font_families) ||
2848 is_known(next.cs(), known_old_font_series) ||
2849 is_known(next.cs(), known_old_font_shapes)) {
2850 // next will change the font family, series
2851 // and shape, so we must reset it here
2852 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2854 if (!context.atParagraphStart())
2856 << context.font.family
2858 << context.font.series
2860 << context.font.shape << "\n";
2862 output_ert_inset(os, "{", context);
2863 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2865 output_ert_inset(os, "}", context);
2870 else if (t.cat() == catEnd) {
2871 if (flags & FLAG_BRACE_LAST) {
2874 cerr << "stray '}' in text\n";
2875 output_ert_inset(os, "}", context);
2878 else if (t.cat() == catComment)
2879 parse_comment(p, os, t, context);
2882 // control sequences
2885 else if (t.cs() == "(" || t.cs() == "[") {
2886 bool const simple = t.cs() == "(";
2887 context.check_layout(os);
2888 begin_inset(os, "Formula");
2889 os << " \\" << t.cs();
2890 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2891 os << '\\' << (simple ? ')' : ']');
2894 // Prevent the conversion of a line break to a
2895 // space (bug 7668). This does not change the
2896 // output, but looks ugly in LyX.
2897 eat_whitespace(p, os, context, false);
2901 else if (t.cs() == "begin")
2902 parse_environment(p, os, outer, last_env,
2905 else if (t.cs() == "end") {
2906 if (flags & FLAG_END) {
2907 // eat environment name
2908 string const name = p.getArg('{', '}');
2909 if (name != active_environment())
2910 cerr << "\\end{" + name + "} does not match \\begin{"
2911 + active_environment() + "}\n";
2914 p.error("found 'end' unexpectedly");
2917 else if (t.cs() == "item") {
2919 bool const optarg = p.hasOpt();
2921 // FIXME: This swallows comments, but we cannot use
2922 // eat_whitespace() since we must not output
2923 // anything before the item.
2924 p.skip_spaces(true);
2925 s = p.verbatimOption();
2927 p.skip_spaces(false);
2929 context.check_layout(os);
2930 if (context.has_item) {
2931 // An item in an unknown list-like environment
2932 // FIXME: Do this in check_layout()!
2933 context.has_item = false;
2935 output_ert_inset(os, "\\item", context);
2937 output_ert_inset(os, "\\item ", context);
2940 if (context.layout->labeltype != LABEL_MANUAL) {
2941 // handle option of itemize item
2942 begin_inset(os, "Argument item:1\n");
2943 os << "status open\n";
2944 os << "\n\\begin_layout Plain Layout\n";
2946 os << parse_text_snippet(p2,
2947 FLAG_BRACK_LAST, outer, context);
2948 // we must not use context.check_end_layout(os)
2949 // because that would close the outer itemize layout
2950 os << "\n\\end_layout\n";
2952 eat_whitespace(p, os, context, false);
2953 } else if (!s.empty()) {
2954 // LyX adds braces around the argument,
2955 // so we need to remove them here.
2956 if (s.size() > 2 && s[0] == '{' &&
2957 s[s.size()-1] == '}')
2958 s = s.substr(1, s.size()-2);
2959 // If the argument contains a space we
2960 // must put it into ERT: Otherwise LyX
2961 // would misinterpret the space as
2962 // item delimiter (bug 7663)
2963 if (contains(s, ' ')) {
2964 output_ert_inset(os, s, context);
2967 os << parse_text_snippet(p2,
2968 FLAG_BRACK_LAST, outer, context);
2970 // The space is needed to separate the
2971 // item from the rest of the sentence.
2973 eat_whitespace(p, os, context, false);
2978 else if (t.cs() == "bibitem") {
2980 context.check_layout(os);
2981 eat_whitespace(p, os, context, false);
2982 string label = convert_command_inset_arg(p.verbatimOption());
2983 string key = convert_command_inset_arg(p.verbatim_item());
2984 if (contains(label, '\\') || contains(key, '\\')) {
2985 // LyX can't handle LaTeX commands in labels or keys
2986 output_ert_inset(os, t.asInput() + '[' + label +
2987 "]{" + p.verbatim_item() + '}',
2990 begin_command_inset(os, "bibitem", "bibitem");
2991 os << "label \"" << label << "\"\n"
2992 << "key \"" << key << "\"\n"
2993 << "literal \"true\"\n";
2998 else if (is_macro(p)) {
2999 // catch the case of \def\inputGnumericTable
3001 if (t.cs() == "def") {
3002 Token second = p.next_token();
3003 if (second.cs() == "inputGnumericTable") {
3007 Token third = p.get_token();
3009 if (third.cs() == "input") {
3013 string name = normalize_filename(p.verbatim_item());
3014 string const path = getMasterFilePath(true);
3015 // We want to preserve relative / absolute filenames,
3016 // therefore path is only used for testing
3017 // The file extension is in every case ".tex".
3018 // So we need to remove this extension and check for
3019 // the original one.
3020 name = removeExtension(name);
3021 if (!makeAbsPath(name, path).exists()) {
3022 char const * const Gnumeric_formats[] = {"gnumeric",
3024 string const Gnumeric_name =
3025 find_file(name, path, Gnumeric_formats);
3026 if (!Gnumeric_name.empty())
3027 name = Gnumeric_name;
3029 FileName const absname = makeAbsPath(name, path);
3030 if (absname.exists()) {
3031 fix_child_filename(name);
3032 copy_file(absname, name);
3034 cerr << "Warning: Could not find file '"
3035 << name << "'." << endl;
3036 context.check_layout(os);
3037 begin_inset(os, "External\n\ttemplate ");
3038 os << "GnumericSpreadsheet\n\tfilename "
3041 context.check_layout(os);
3043 // register the packages that are automatically loaded
3044 // by the Gnumeric template
3045 registerExternalTemplatePackages("GnumericSpreadsheet");
3050 parse_macro(p, os, context);
3053 else if (t.cs() == "noindent") {
3055 context.add_par_extra_stuff("\\noindent\n");
3058 else if (t.cs() == "appendix") {
3059 context.add_par_extra_stuff("\\start_of_appendix\n");
3060 // We need to start a new paragraph. Otherwise the
3061 // appendix in 'bla\appendix\chapter{' would start
3063 context.new_paragraph(os);
3064 // We need to make sure that the paragraph is
3065 // generated even if it is empty. Otherwise the
3066 // appendix in '\par\appendix\par\chapter{' would
3068 context.check_layout(os);
3069 // FIXME: This is a hack to prevent paragraph
3070 // deletion if it is empty. Handle this better!
3071 output_comment(p, os,
3072 "dummy comment inserted by tex2lyx to "
3073 "ensure that this paragraph is not empty",
3075 // Both measures above may generate an additional
3076 // empty paragraph, but that does not hurt, because
3077 // whitespace does not matter here.
3078 eat_whitespace(p, os, context, true);
3081 // Must catch empty dates before findLayout is called below
3082 else if (t.cs() == "date") {
3083 eat_whitespace(p, os, context, false);
3085 string const date = p.verbatim_item();
3088 preamble.suppressDate(true);
3091 preamble.suppressDate(false);
3092 if (context.new_layout_allowed &&
3093 (newlayout = findLayout(context.textclass,
3096 output_command_layout(os, p, outer,
3097 context, newlayout);
3098 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3099 if (!preamble.titleLayoutFound())
3100 preamble.titleLayoutFound(newlayout->intitle);
3101 set<string> const & req = newlayout->requires();
3102 set<string>::const_iterator it = req.begin();
3103 set<string>::const_iterator en = req.end();
3104 for (; it != en; ++it)
3105 preamble.registerAutomaticallyLoadedPackage(*it);
3107 output_ert_inset(os,
3108 "\\date{" + p.verbatim_item() + '}',
3113 // Starred section headings
3114 // Must attempt to parse "Section*" before "Section".
3115 else if ((p.next_token().asInput() == "*") &&
3116 context.new_layout_allowed &&
3117 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3120 output_command_layout(os, p, outer, context, newlayout);
3122 if (!preamble.titleLayoutFound())
3123 preamble.titleLayoutFound(newlayout->intitle);
3124 set<string> const & req = newlayout->requires();
3125 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3126 preamble.registerAutomaticallyLoadedPackage(*it);
3129 // Section headings and the like
3130 else if (context.new_layout_allowed &&
3131 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3133 output_command_layout(os, p, outer, context, newlayout);
3135 if (!preamble.titleLayoutFound())
3136 preamble.titleLayoutFound(newlayout->intitle);
3137 set<string> const & req = newlayout->requires();
3138 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3139 preamble.registerAutomaticallyLoadedPackage(*it);
3142 else if (t.cs() == "subfloat") {
3143 // the syntax is \subfloat[list entry][sub caption]{content}
3144 // if it is a table of figure depends on the surrounding float
3145 // FIXME: second optional argument is not parsed
3147 // do nothing if there is no outer float
3148 if (!float_type.empty()) {
3149 context.check_layout(os);
3151 begin_inset(os, "Float " + float_type + "\n");
3153 << "\nsideways false"
3154 << "\nstatus collapsed\n\n";
3157 bool has_caption = false;
3158 if (p.next_token().cat() != catEscape &&
3159 p.next_token().character() == '[') {
3160 p.get_token(); // eat '['
3161 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3165 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3166 // the caption comes always as the last
3168 // we must make sure that the caption gets a \begin_layout
3169 os << "\n\\begin_layout Plain Layout";
3171 begin_inset(os, "Caption Standard\n");
3172 Context newcontext(true, context.textclass,
3173 0, 0, context.font);
3174 newcontext.check_layout(os);
3175 os << caption << "\n";
3176 newcontext.check_end_layout(os);
3177 // We don't need really a new paragraph, but
3178 // we must make sure that the next item gets a \begin_layout.
3179 //newcontext.new_paragraph(os);
3183 // We don't need really a new paragraph, but
3184 // we must make sure that the next item gets a \begin_layout.
3186 context.new_paragraph(os);
3189 context.check_end_layout(os);
3190 // close the layout we opened
3192 os << "\n\\end_layout\n";
3194 // if the float type is not supported or there is no surrounding float
3197 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
3198 output_ert_inset(os, t.asInput() + '[' + opt_arg +
3199 "]{" + p.verbatim_item() + '}', context);
3201 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3205 else if (t.cs() == "includegraphics") {
3206 bool const clip = p.next_token().asInput() == "*";
3209 string const arg = p.getArg('[', ']');
3210 map<string, string> opts;
3211 vector<string> keys;
3212 split_map(arg, opts, keys);
3214 opts["clip"] = string();
3215 string name = normalize_filename(p.verbatim_item());
3217 string const path = getMasterFilePath(true);
3218 // We want to preserve relative / absolute filenames,
3219 // therefore path is only used for testing
3220 if (!makeAbsPath(name, path).exists()) {
3221 // The file extension is probably missing.
3222 // Now try to find it out.
3223 string const dvips_name =
3224 find_file(name, path,
3225 known_dvips_graphics_formats);
3226 string const pdftex_name =
3227 find_file(name, path,
3228 known_pdftex_graphics_formats);
3229 if (!dvips_name.empty()) {
3230 if (!pdftex_name.empty()) {
3231 cerr << "This file contains the "
3233 "\"\\includegraphics{"
3235 "However, files\n\""
3236 << dvips_name << "\" and\n\""
3237 << pdftex_name << "\"\n"
3238 "both exist, so I had to make a "
3239 "choice and took the first one.\n"
3240 "Please move the unwanted one "
3241 "someplace else and try again\n"
3242 "if my choice was wrong."
3246 } else if (!pdftex_name.empty()) {
3252 FileName const absname = makeAbsPath(name, path);
3253 if (absname.exists()) {
3254 fix_child_filename(name);
3255 copy_file(absname, name);
3257 cerr << "Warning: Could not find graphics file '"
3258 << name << "'." << endl;
3260 context.check_layout(os);
3261 begin_inset(os, "Graphics ");
3262 os << "\n\tfilename " << name << '\n';
3263 if (opts.find("width") != opts.end())
3265 << translate_len(opts["width"]) << '\n';
3266 if (opts.find("height") != opts.end())
3268 << translate_len(opts["height"]) << '\n';
3269 if (opts.find("scale") != opts.end()) {
3270 istringstream iss(opts["scale"]);
3274 os << "\tscale " << val << '\n';
3276 if (opts.find("angle") != opts.end()) {
3277 os << "\trotateAngle "
3278 << opts["angle"] << '\n';
3279 vector<string>::const_iterator a =
3280 find(keys.begin(), keys.end(), "angle");
3281 vector<string>::const_iterator s =
3282 find(keys.begin(), keys.end(), "width");
3283 if (s == keys.end())
3284 s = find(keys.begin(), keys.end(), "height");
3285 if (s == keys.end())
3286 s = find(keys.begin(), keys.end(), "scale");
3287 if (s != keys.end() && distance(s, a) > 0)
3288 os << "\tscaleBeforeRotation\n";
3290 if (opts.find("origin") != opts.end()) {
3292 string const opt = opts["origin"];
3293 if (opt.find('l') != string::npos) ss << "left";
3294 if (opt.find('r') != string::npos) ss << "right";
3295 if (opt.find('c') != string::npos) ss << "center";
3296 if (opt.find('t') != string::npos) ss << "Top";
3297 if (opt.find('b') != string::npos) ss << "Bottom";
3298 if (opt.find('B') != string::npos) ss << "Baseline";
3299 if (!ss.str().empty())
3300 os << "\trotateOrigin " << ss.str() << '\n';
3302 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3304 if (opts.find("keepaspectratio") != opts.end())
3305 os << "\tkeepAspectRatio\n";
3306 if (opts.find("clip") != opts.end())
3308 if (opts.find("draft") != opts.end())
3310 if (opts.find("bb") != opts.end())
3311 os << "\tBoundingBox "
3312 << opts["bb"] << '\n';
3313 int numberOfbbOptions = 0;
3314 if (opts.find("bbllx") != opts.end())
3315 numberOfbbOptions++;
3316 if (opts.find("bblly") != opts.end())
3317 numberOfbbOptions++;
3318 if (opts.find("bburx") != opts.end())
3319 numberOfbbOptions++;
3320 if (opts.find("bbury") != opts.end())
3321 numberOfbbOptions++;
3322 if (numberOfbbOptions == 4)
3323 os << "\tBoundingBox "
3324 << opts["bbllx"] << " " << opts["bblly"] << " "
3325 << opts["bburx"] << " " << opts["bbury"] << '\n';
3326 else if (numberOfbbOptions > 0)
3327 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3328 numberOfbbOptions = 0;
3329 if (opts.find("natwidth") != opts.end())
3330 numberOfbbOptions++;
3331 if (opts.find("natheight") != opts.end())
3332 numberOfbbOptions++;
3333 if (numberOfbbOptions == 2)
3334 os << "\tBoundingBox 0bp 0bp "
3335 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3336 else if (numberOfbbOptions > 0)
3337 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3338 ostringstream special;
3339 if (opts.find("hiresbb") != opts.end())
3340 special << "hiresbb,";
3341 if (opts.find("trim") != opts.end())
3343 if (opts.find("viewport") != opts.end())
3344 special << "viewport=" << opts["viewport"] << ',';
3345 if (opts.find("totalheight") != opts.end())
3346 special << "totalheight=" << opts["totalheight"] << ',';
3347 if (opts.find("type") != opts.end())
3348 special << "type=" << opts["type"] << ',';
3349 if (opts.find("ext") != opts.end())
3350 special << "ext=" << opts["ext"] << ',';
3351 if (opts.find("read") != opts.end())
3352 special << "read=" << opts["read"] << ',';
3353 if (opts.find("command") != opts.end())
3354 special << "command=" << opts["command"] << ',';
3355 string s_special = special.str();
3356 if (!s_special.empty()) {
3357 // We had special arguments. Remove the trailing ','.
3358 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3360 // TODO: Handle the unknown settings better.
3361 // Warn about invalid options.
3362 // Check whether some option was given twice.
3364 preamble.registerAutomaticallyLoadedPackage("graphicx");
3367 else if (t.cs() == "footnote" ||
3368 (t.cs() == "thanks" && context.layout->intitle)) {
3370 context.check_layout(os);
3371 begin_inset(os, "Foot\n");
3372 os << "status collapsed\n\n";
3373 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3377 else if (t.cs() == "marginpar") {
3379 context.check_layout(os);
3380 begin_inset(os, "Marginal\n");
3381 os << "status collapsed\n\n";
3382 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3386 else if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3387 bool const use_minted = t.cs() == "mintinline";
3389 parse_listings(p, os, context, true, use_minted);
3392 else if (t.cs() == "ensuremath") {
3394 context.check_layout(os);
3395 string const s = p.verbatim_item();
3396 //FIXME: this never triggers in UTF8
3397 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3400 output_ert_inset(os, "\\ensuremath{" + s + "}",
3404 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3405 if (preamble.titleLayoutFound()) {
3407 skip_spaces_braces(p);
3409 output_ert_inset(os, t.asInput(), context);
3412 else if (t.cs() == "tableofcontents"
3413 || t.cs() == "lstlistoflistings"
3414 || t.cs() == "listoflistings") {
3415 string name = t.cs();
3416 if (preamble.minted() && name == "listoflistings")
3417 name.insert(0, "lst");
3418 context.check_layout(os);
3419 begin_command_inset(os, "toc", name);
3421 skip_spaces_braces(p);
3422 if (name == "lstlistoflistings") {
3423 if (preamble.minted())
3424 preamble.registerAutomaticallyLoadedPackage("minted");
3426 preamble.registerAutomaticallyLoadedPackage("listings");
3430 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3431 context.check_layout(os);
3432 if (t.cs() == "listoffigures")
3433 begin_inset(os, "FloatList figure\n");
3435 begin_inset(os, "FloatList table\n");
3437 skip_spaces_braces(p);
3440 else if (t.cs() == "listof") {
3441 p.skip_spaces(true);
3442 string const name = p.get_token().cs();
3443 if (context.textclass.floats().typeExist(name)) {
3444 context.check_layout(os);
3445 begin_inset(os, "FloatList ");
3448 p.get_token(); // swallow second arg
3450 output_ert_inset(os, "\\listof{" + name + "}", context);
3453 else if ((where = is_known(t.cs(), known_text_font_families)))
3454 parse_text_attributes(p, os, FLAG_ITEM, outer,
3455 context, "\\family", context.font.family,
3456 known_coded_font_families[where - known_text_font_families]);
3458 else if ((where = is_known(t.cs(), known_text_font_series)))
3459 parse_text_attributes(p, os, FLAG_ITEM, outer,
3460 context, "\\series", context.font.series,
3461 known_coded_font_series[where - known_text_font_series]);
3463 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3464 parse_text_attributes(p, os, FLAG_ITEM, outer,
3465 context, "\\shape", context.font.shape,
3466 known_coded_font_shapes[where - known_text_font_shapes]);
3468 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3469 context.check_layout(os);
3470 TeXFont oldFont = context.font;
3471 context.font.init();
3472 context.font.size = oldFont.size;
3473 os << "\n\\family " << context.font.family << "\n";
3474 os << "\n\\series " << context.font.series << "\n";
3475 os << "\n\\shape " << context.font.shape << "\n";
3476 if (t.cs() == "textnormal") {
3477 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3478 output_font_change(os, context.font, oldFont);
3479 context.font = oldFont;
3481 eat_whitespace(p, os, context, false);
3484 else if (t.cs() == "textcolor") {
3485 // scheme is \textcolor{color name}{text}
3486 string const color = p.verbatim_item();
3487 // we support the predefined colors of the color and the xcolor package
3488 if (color == "black" || color == "blue" || color == "cyan"
3489 || color == "green" || color == "magenta" || color == "red"
3490 || color == "white" || color == "yellow") {
3491 context.check_layout(os);
3492 os << "\n\\color " << color << "\n";
3493 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3494 context.check_layout(os);
3495 os << "\n\\color inherit\n";
3496 preamble.registerAutomaticallyLoadedPackage("color");
3497 } else if (color == "brown" || color == "darkgray" || color == "gray"
3498 || color == "lightgray" || color == "lime" || color == "olive"
3499 || color == "orange" || color == "pink" || color == "purple"
3500 || color == "teal" || color == "violet") {
3501 context.check_layout(os);
3502 os << "\n\\color " << color << "\n";
3503 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3504 context.check_layout(os);
3505 os << "\n\\color inherit\n";
3506 preamble.registerAutomaticallyLoadedPackage("xcolor");
3508 // for custom defined colors
3509 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3512 else if (t.cs() == "underbar" || t.cs() == "uline") {
3513 // \underbar is not 100% correct (LyX outputs \uline
3514 // of ulem.sty). The difference is that \ulem allows
3515 // line breaks, and \underbar does not.
3516 // Do NOT handle \underline.
3517 // \underbar cuts through y, g, q, p etc.,
3518 // \underline does not.
3519 context.check_layout(os);
3520 os << "\n\\bar under\n";
3521 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3522 context.check_layout(os);
3523 os << "\n\\bar default\n";
3524 preamble.registerAutomaticallyLoadedPackage("ulem");
3527 else if (t.cs() == "sout") {
3528 context.check_layout(os);
3529 os << "\n\\strikeout on\n";
3530 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3531 context.check_layout(os);
3532 os << "\n\\strikeout default\n";
3533 preamble.registerAutomaticallyLoadedPackage("ulem");
3536 else if (t.cs() == "uuline" || t.cs() == "uwave"
3537 || t.cs() == "emph" || t.cs() == "noun"
3538 || t.cs() == "xout") {
3539 context.check_layout(os);
3540 os << "\n\\" << t.cs() << " on\n";
3541 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3542 context.check_layout(os);
3543 os << "\n\\" << t.cs() << " default\n";
3544 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3545 preamble.registerAutomaticallyLoadedPackage("ulem");
3548 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3549 context.check_layout(os);
3550 string name = p.getArg('{', '}');
3551 string localtime = p.getArg('{', '}');
3552 preamble.registerAuthor(name);
3553 Author const & author = preamble.getAuthor(name);
3554 // from_asctime_utc() will fail if LyX decides to output the
3555 // time in the text language.
3556 time_t ptime = from_asctime_utc(localtime);
3557 if (ptime == static_cast<time_t>(-1)) {
3558 cerr << "Warning: Could not parse time `" << localtime
3559 << "´ for change tracking, using current time instead.\n";
3560 ptime = current_time();
3562 if (t.cs() == "lyxadded")
3563 os << "\n\\change_inserted ";
3565 os << "\n\\change_deleted ";
3566 os << author.bufferId() << ' ' << ptime << '\n';
3567 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3568 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3569 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3570 LaTeXPackages::isAvailable("xcolor");
3571 // No need to test for luatex, since luatex comes in
3572 // two flavours (dvi and pdf), like latex, and those
3573 // are detected by pdflatex.
3574 if (pdflatex || xetex) {
3576 preamble.registerAutomaticallyLoadedPackage("ulem");
3577 preamble.registerAutomaticallyLoadedPackage("xcolor");
3578 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3582 preamble.registerAutomaticallyLoadedPackage("dvipost");
3583 } else if (xcolorulem) {
3584 preamble.registerAutomaticallyLoadedPackage("ulem");
3585 preamble.registerAutomaticallyLoadedPackage("xcolor");
3590 else if (t.cs() == "textipa") {
3591 context.check_layout(os);
3592 begin_inset(os, "IPA\n");
3593 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3594 context.merging_hyphens_allowed = false;
3595 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3596 context.merging_hyphens_allowed = merging_hyphens_allowed;
3598 preamble.registerAutomaticallyLoadedPackage("tipa");
3599 preamble.registerAutomaticallyLoadedPackage("tipx");
3602 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3603 context.check_layout(os);
3604 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3605 os << "status open\n";
3606 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3611 else if (t.cs() == "textvertline") {
3612 // FIXME: This is not correct, \textvertline is higher than |
3618 else if (t.cs() == "tone" ) {
3619 context.check_layout(os);
3620 // register the tone package
3621 preamble.registerAutomaticallyLoadedPackage("tone");
3622 string content = trimSpaceAndEol(p.verbatim_item());
3623 string command = t.asInput() + "{" + content + "}";
3624 // some tones can be detected by unicodesymbols, some need special code
3625 if (is_known(content, known_tones)) {
3626 os << "\\IPAChar " << command << "\n";
3629 // try to see whether the string is in unicodesymbols
3633 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3634 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3635 termination, rem, &req);
3639 output_ert_inset(os, to_utf8(rem), context);
3640 for (set<string>::const_iterator it = req.begin();
3641 it != req.end(); ++it)
3642 preamble.registerAutomaticallyLoadedPackage(*it);
3644 // we did not find a non-ert version
3645 output_ert_inset(os, command, context);
3648 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3649 t.cs() == "vphantom") {
3650 context.check_layout(os);
3651 if (t.cs() == "phantom")
3652 begin_inset(os, "Phantom Phantom\n");
3653 if (t.cs() == "hphantom")
3654 begin_inset(os, "Phantom HPhantom\n");
3655 if (t.cs() == "vphantom")
3656 begin_inset(os, "Phantom VPhantom\n");
3657 os << "status open\n";
3658 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3663 else if (t.cs() == "href") {
3664 context.check_layout(os);
3665 string target = convert_command_inset_arg(p.verbatim_item());
3666 string name = convert_command_inset_arg(p.verbatim_item());
3668 size_t i = target.find(':');
3669 if (i != string::npos) {
3670 type = target.substr(0, i + 1);
3671 if (type == "mailto:" || type == "file:")
3672 target = target.substr(i + 1);
3673 // handle the case that name is equal to target, except of "http(s)://"
3674 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3677 begin_command_inset(os, "href", "href");
3679 os << "name \"" << name << "\"\n";
3680 os << "target \"" << target << "\"\n";
3681 if (type == "mailto:" || type == "file:")
3682 os << "type \"" << type << "\"\n";
3683 os << "literal \"true\"\n";
3685 skip_spaces_braces(p);
3688 else if (t.cs() == "lyxline") {
3689 // swallow size argument (it is not used anyway)
3691 if (!context.atParagraphStart()) {
3692 // so our line is in the middle of a paragraph
3693 // we need to add a new line, lest this line
3694 // follow the other content on that line and
3695 // run off the side of the page
3696 // FIXME: This may create an empty paragraph,
3697 // but without that it would not be
3698 // possible to set noindent below.
3699 // Fortunately LaTeX does not care
3700 // about the empty paragraph.
3701 context.new_paragraph(os);
3703 if (preamble.indentParagraphs()) {
3704 // we need to unindent, lest the line be too long
3705 context.add_par_extra_stuff("\\noindent\n");
3707 context.check_layout(os);
3708 begin_command_inset(os, "line", "rule");
3709 os << "offset \"0.5ex\"\n"
3710 "width \"100line%\"\n"
3715 else if (t.cs() == "rule") {
3716 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3717 string const width = p.getArg('{', '}');
3718 string const thickness = p.getArg('{', '}');
3719 context.check_layout(os);
3720 begin_command_inset(os, "line", "rule");
3721 if (!offset.empty())
3722 os << "offset \"" << translate_len(offset) << "\"\n";
3723 os << "width \"" << translate_len(width) << "\"\n"
3724 "height \"" << translate_len(thickness) << "\"\n";
3728 // handle refstyle first to catch \eqref which can also occur
3729 // without refstyle. Only recognize these commands if
3730 // refstyle.sty was found in the preamble (otherwise \eqref
3731 // and user defined ref commands could be misdetected).
3732 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3733 preamble.refstyle()) {
3734 context.check_layout(os);
3735 begin_command_inset(os, "ref", "formatted");
3736 os << "reference \"";
3737 os << known_refstyle_prefixes[where - known_refstyle_commands]
3739 os << convert_command_inset_arg(p.verbatim_item())
3741 os << "plural \"false\"\n";
3742 os << "caps \"false\"\n";
3743 os << "noprefix \"false\"\n";
3745 preamble.registerAutomaticallyLoadedPackage("refstyle");
3748 // if refstyle is used, we must not convert \prettyref to a
3749 // formatted reference, since that would result in a refstyle command.
3750 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3751 (t.cs() != "prettyref" || !preamble.refstyle())) {
3752 string const opt = p.getOpt();
3754 context.check_layout(os);
3755 begin_command_inset(os, "ref",
3756 known_coded_ref_commands[where - known_ref_commands]);
3757 os << "reference \""
3758 << convert_command_inset_arg(p.verbatim_item())
3760 os << "plural \"false\"\n";
3761 os << "caps \"false\"\n";
3762 os << "noprefix \"false\"\n";
3764 if (t.cs() == "vref" || t.cs() == "vpageref")
3765 preamble.registerAutomaticallyLoadedPackage("varioref");
3766 else if (t.cs() == "prettyref")
3767 preamble.registerAutomaticallyLoadedPackage("prettyref");
3769 // LyX does not yet support optional arguments of ref commands
3770 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3771 p.verbatim_item() + '}', context);
3775 else if (use_natbib &&
3776 is_known(t.cs(), known_natbib_commands) &&
3777 ((t.cs() != "citefullauthor" &&
3778 t.cs() != "citeyear" &&
3779 t.cs() != "citeyearpar") ||
3780 p.next_token().asInput() != "*")) {
3781 context.check_layout(os);
3782 string command = t.cs();
3783 if (p.next_token().asInput() == "*") {
3787 if (command == "citefullauthor")
3788 // alternative name for "\\citeauthor*"
3789 command = "citeauthor*";
3791 // text before the citation
3793 // text after the citation
3795 get_cite_arguments(p, true, before, after);
3797 if (command == "cite") {
3798 // \cite without optional argument means
3799 // \citet, \cite with at least one optional
3800 // argument means \citep.
3801 if (before.empty() && after.empty())
3806 if (before.empty() && after == "[]")
3807 // avoid \citet[]{a}
3809 else if (before == "[]" && after == "[]") {
3810 // avoid \citet[][]{a}
3814 // remove the brackets around after and before
3815 if (!after.empty()) {
3817 after.erase(after.length() - 1, 1);
3818 after = convert_command_inset_arg(after);
3820 if (!before.empty()) {
3822 before.erase(before.length() - 1, 1);
3823 before = convert_command_inset_arg(before);
3825 begin_command_inset(os, "citation", command);
3826 os << "after " << '"' << after << '"' << "\n";
3827 os << "before " << '"' << before << '"' << "\n";
3829 << convert_command_inset_arg(p.verbatim_item())
3831 << "literal \"true\"\n";
3833 // Need to set the cite engine if natbib is loaded by
3834 // the document class directly
3835 if (preamble.citeEngine() == "basic")
3836 preamble.citeEngine("natbib");
3839 else if (use_biblatex
3840 && is_known(t.cs(), known_biblatex_commands)
3841 && ((t.cs() == "cite"
3842 || t.cs() == "citeauthor"
3843 || t.cs() == "Citeauthor"
3844 || t.cs() == "parencite"
3845 || t.cs() == "citetitle")
3846 || p.next_token().asInput() != "*")) {
3847 context.check_layout(os);
3848 string command = t.cs();
3849 if (p.next_token().asInput() == "*") {
3854 // text before the citation
3856 // text after the citation
3858 get_cite_arguments(p, true, before, after);
3860 // These use natbib cmd names in LyX
3861 // for inter-citeengine compativility
3862 if (command == "citeyear")
3863 command = "citebyear";
3864 else if (command == "cite*")
3865 command = "citeyear";
3866 else if (command == "textcite")
3868 else if (command == "Textcite")
3870 else if (command == "parencite")
3872 else if (command == "Parencite")
3874 else if (command == "parencite*")
3875 command = "citeyearpar";
3876 else if (command == "smartcite")
3877 command = "footcite";
3878 else if (command == "Smartcite")
3879 command = "Footcite";
3881 if (before.empty() && after == "[]")
3884 else if (before == "[]" && after == "[]") {
3885 // avoid \cite[][]{a}
3889 // remove the brackets around after and before
3890 if (!after.empty()) {
3892 after.erase(after.length() - 1, 1);
3893 after = convert_command_inset_arg(after);
3895 if (!before.empty()) {
3897 before.erase(before.length() - 1, 1);
3898 before = convert_command_inset_arg(before);
3900 begin_command_inset(os, "citation", command);
3901 os << "after " << '"' << after << '"' << "\n";
3902 os << "before " << '"' << before << '"' << "\n";
3904 << convert_command_inset_arg(p.verbatim_item())
3906 << "literal \"true\"\n";
3908 // Need to set the cite engine if biblatex is loaded by
3909 // the document class directly
3910 if (preamble.citeEngine() == "basic")
3911 preamble.citeEngine("biblatex");
3914 else if (use_biblatex_natbib
3915 && (is_known(t.cs(), known_biblatex_commands)
3916 || is_known(t.cs(), known_natbib_commands))
3917 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3918 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3919 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3920 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3921 || t.cs() == "parencite" || t.cs() == "citetitle")
3922 || p.next_token().asInput() != "*")) {
3923 context.check_layout(os);
3924 string command = t.cs();
3925 if (p.next_token().asInput() == "*") {
3930 // text before the citation
3932 // text after the citation
3934 get_cite_arguments(p, true, before, after);
3936 // These use natbib cmd names in LyX
3937 // for inter-citeengine compativility
3938 if (command == "citeyear")
3939 command = "citebyear";
3940 else if (command == "cite*")
3941 command = "citeyear";
3942 else if (command == "textcite")
3944 else if (command == "Textcite")
3946 else if (command == "parencite")
3948 else if (command == "Parencite")
3950 else if (command == "parencite*")
3951 command = "citeyearpar";
3952 else if (command == "smartcite")
3953 command = "footcite";
3954 else if (command == "Smartcite")
3955 command = "Footcite";
3957 if (before.empty() && after == "[]")
3960 else if (before == "[]" && after == "[]") {
3961 // avoid \cite[][]{a}
3965 // remove the brackets around after and before
3966 if (!after.empty()) {
3968 after.erase(after.length() - 1, 1);
3969 after = convert_command_inset_arg(after);
3971 if (!before.empty()) {
3973 before.erase(before.length() - 1, 1);
3974 before = convert_command_inset_arg(before);
3976 begin_command_inset(os, "citation", command);
3977 os << "after " << '"' << after << '"' << "\n";
3978 os << "before " << '"' << before << '"' << "\n";
3980 << convert_command_inset_arg(p.verbatim_item())
3982 << "literal \"true\"\n";
3984 // Need to set the cite engine if biblatex is loaded by
3985 // the document class directly
3986 if (preamble.citeEngine() == "basic")
3987 preamble.citeEngine("biblatex-natbib");
3990 else if (use_jurabib &&
3991 is_known(t.cs(), known_jurabib_commands) &&
3992 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3993 context.check_layout(os);
3994 string command = t.cs();
3995 if (p.next_token().asInput() == "*") {
3999 char argumentOrder = '\0';
4000 vector<string> const options =
4001 preamble.getPackageOptions("jurabib");
4002 if (find(options.begin(), options.end(),
4003 "natbiborder") != options.end())
4004 argumentOrder = 'n';
4005 else if (find(options.begin(), options.end(),
4006 "jurabiborder") != options.end())
4007 argumentOrder = 'j';
4009 // text before the citation
4011 // text after the citation
4013 get_cite_arguments(p, argumentOrder != 'j', before, after);
4015 string const citation = p.verbatim_item();
4016 if (!before.empty() && argumentOrder == '\0') {
4017 cerr << "Warning: Assuming argument order "
4018 "of jurabib version 0.6 for\n'"
4019 << command << before << after << '{'
4020 << citation << "}'.\n"
4021 "Add 'jurabiborder' to the jurabib "
4022 "package options if you used an\n"
4023 "earlier jurabib version." << endl;
4025 if (!after.empty()) {
4027 after.erase(after.length() - 1, 1);
4029 if (!before.empty()) {
4031 before.erase(before.length() - 1, 1);
4033 begin_command_inset(os, "citation", command);
4034 os << "after " << '"' << after << "\"\n"
4035 << "before " << '"' << before << "\"\n"
4036 << "key " << '"' << citation << "\"\n"
4037 << "literal \"true\"\n";
4039 // Need to set the cite engine if jurabib is loaded by
4040 // the document class directly
4041 if (preamble.citeEngine() == "basic")
4042 preamble.citeEngine("jurabib");
4045 else if (t.cs() == "cite"
4046 || t.cs() == "nocite") {
4047 context.check_layout(os);
4048 string after = convert_command_inset_arg(p.getArg('[', ']'));
4049 string key = convert_command_inset_arg(p.verbatim_item());
4050 // store the case that it is "\nocite{*}" to use it later for
4053 begin_command_inset(os, "citation", t.cs());
4054 os << "after " << '"' << after << "\"\n"
4055 << "key " << '"' << key << "\"\n"
4056 << "literal \"true\"\n";
4058 } else if (t.cs() == "nocite")
4062 else if (t.cs() == "index" ||
4063 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4064 context.check_layout(os);
4065 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4066 p.getArg('[', ']') : "";
4067 string const kind = arg.empty() ? "idx" : arg;
4068 begin_inset(os, "Index ");
4069 os << kind << "\nstatus collapsed\n";
4070 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4073 preamble.registerAutomaticallyLoadedPackage("splitidx");
4076 else if (t.cs() == "nomenclature") {
4077 context.check_layout(os);
4078 begin_command_inset(os, "nomenclature", "nomenclature");
4079 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
4080 if (!prefix.empty())
4081 os << "prefix " << '"' << prefix << '"' << "\n";
4082 os << "symbol " << '"'
4083 << convert_command_inset_arg(p.verbatim_item());
4084 os << "\"\ndescription \""
4085 << convert_command_inset_arg(p.verbatim_item())
4087 << "literal \"true\"\n";
4089 preamble.registerAutomaticallyLoadedPackage("nomencl");
4092 else if (t.cs() == "label") {
4093 context.check_layout(os);
4094 begin_command_inset(os, "label", "label");
4096 << convert_command_inset_arg(p.verbatim_item())
4101 else if (t.cs() == "lyxmintcaption") {
4102 string const pos = p.getArg('[', ']');
4104 string const caption =
4105 parse_text_snippet(p, FLAG_ITEM, false,
4107 minted_nonfloat_caption = "[t]" + caption;
4109 // We already got the caption at the bottom,
4110 // so simply skip it.
4111 parse_text_snippet(p, FLAG_ITEM, false, context);
4115 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4116 context.check_layout(os);
4117 string commandname = t.cs();
4119 if (p.next_token().asInput() == "*") {
4124 begin_command_inset(os, "index_print", commandname);
4125 string const indexname = p.getArg('[', ']');
4127 if (indexname.empty())
4128 os << "type \"idx\"\n";
4130 os << "type \"" << indexname << "\"\n";
4131 os << "literal \"true\"\n";
4134 skip_spaces_braces(p);
4135 preamble.registerAutomaticallyLoadedPackage("makeidx");
4136 if (preamble.use_indices() == "true")
4137 preamble.registerAutomaticallyLoadedPackage("splitidx");
4140 else if (t.cs() == "printnomenclature") {
4142 string width_type = "";
4143 context.check_layout(os);
4144 begin_command_inset(os, "nomencl_print", "printnomenclature");
4145 // case of a custom width
4147 width = p.getArg('[', ']');
4148 width = translate_len(width);
4149 width_type = "custom";
4151 // case of no custom width
4152 // the case of no custom width but the width set
4153 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4154 // because the user could have set anything, not only the width
4155 // of the longest label (which would be width_type = "auto")
4156 string label = convert_command_inset_arg(p.getArg('{', '}'));
4157 if (label.empty() && width_type.empty())
4158 width_type = "none";
4159 os << "set_width \"" << width_type << "\"\n";
4160 if (width_type == "custom")
4161 os << "width \"" << width << '\"';
4163 skip_spaces_braces(p);
4164 preamble.registerAutomaticallyLoadedPackage("nomencl");
4167 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4168 context.check_layout(os);
4169 begin_inset(os, "script ");
4170 os << t.cs().substr(4) << '\n';
4171 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4172 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4174 if (t.cs() == "textsubscript")
4175 preamble.registerAutomaticallyLoadedPackage("subscript");
4178 else if ((where = is_known(t.cs(), known_quotes))) {
4179 context.check_layout(os);
4180 begin_inset(os, "Quotes ");
4181 os << known_coded_quotes[where - known_quotes];
4183 // LyX adds {} after the quote, so we have to eat
4184 // spaces here if there are any before a possible
4186 eat_whitespace(p, os, context, false);
4190 else if ((where = is_known(t.cs(), known_sizes)) &&
4191 context.new_layout_allowed) {
4192 context.check_layout(os);
4193 TeXFont const oldFont = context.font;
4194 context.font.size = known_coded_sizes[where - known_sizes];
4195 output_font_change(os, oldFont, context.font);
4196 eat_whitespace(p, os, context, false);
4199 else if ((where = is_known(t.cs(), known_font_families)) &&
4200 context.new_layout_allowed) {
4201 context.check_layout(os);
4202 TeXFont const oldFont = context.font;
4203 context.font.family =
4204 known_coded_font_families[where - known_font_families];
4205 output_font_change(os, oldFont, context.font);
4206 eat_whitespace(p, os, context, false);
4209 else if ((where = is_known(t.cs(), known_font_series)) &&
4210 context.new_layout_allowed) {
4211 context.check_layout(os);
4212 TeXFont const oldFont = context.font;
4213 context.font.series =
4214 known_coded_font_series[where - known_font_series];
4215 output_font_change(os, oldFont, context.font);
4216 eat_whitespace(p, os, context, false);
4219 else if ((where = is_known(t.cs(), known_font_shapes)) &&
4220 context.new_layout_allowed) {
4221 context.check_layout(os);
4222 TeXFont const oldFont = context.font;
4223 context.font.shape =
4224 known_coded_font_shapes[where - known_font_shapes];
4225 output_font_change(os, oldFont, context.font);
4226 eat_whitespace(p, os, context, false);
4228 else if ((where = is_known(t.cs(), known_old_font_families)) &&
4229 context.new_layout_allowed) {
4230 context.check_layout(os);
4231 TeXFont const oldFont = context.font;
4232 context.font.init();
4233 context.font.size = oldFont.size;
4234 context.font.family =
4235 known_coded_font_families[where - known_old_font_families];
4236 output_font_change(os, oldFont, context.font);
4237 eat_whitespace(p, os, context, false);
4240 else if ((where = is_known(t.cs(), known_old_font_series)) &&
4241 context.new_layout_allowed) {
4242 context.check_layout(os);
4243 TeXFont const oldFont = context.font;
4244 context.font.init();
4245 context.font.size = oldFont.size;
4246 context.font.series =
4247 known_coded_font_series[where - known_old_font_series];
4248 output_font_change(os, oldFont, context.font);
4249 eat_whitespace(p, os, context, false);
4252 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4253 context.new_layout_allowed) {
4254 context.check_layout(os);
4255 TeXFont const oldFont = context.font;
4256 context.font.init();
4257 context.font.size = oldFont.size;
4258 context.font.shape =
4259 known_coded_font_shapes[where - known_old_font_shapes];
4260 output_font_change(os, oldFont, context.font);
4261 eat_whitespace(p, os, context, false);
4264 else if (t.cs() == "selectlanguage") {
4265 context.check_layout(os);
4266 // save the language for the case that a
4267 // \foreignlanguage is used
4268 context.font.language = babel2lyx(p.verbatim_item());
4269 os << "\n\\lang " << context.font.language << "\n";
4272 else if (t.cs() == "foreignlanguage") {
4273 string const lang = babel2lyx(p.verbatim_item());
4274 parse_text_attributes(p, os, FLAG_ITEM, outer,
4276 context.font.language, lang);
4279 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4280 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4281 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4283 // We have to output the whole command if it has an option
4284 // because LyX doesn't support this yet, see bug #8214,
4285 // only if there is a single option specifying a variant, we can handle it.
4287 string langopts = p.getOpt();
4288 // check if the option contains a variant, if yes, extract it
4289 string::size_type pos_var = langopts.find("variant");
4290 string::size_type i = langopts.find(',');
4291 string::size_type k = langopts.find('=', pos_var);
4292 if (pos_var != string::npos && i == string::npos) {
4294 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4295 lang = preamble.polyglossia2lyx(variant);
4296 parse_text_attributes(p, os, FLAG_ITEM, outer,
4298 context.font.language, lang);
4300 output_ert_inset(os, t.asInput() + langopts, context);
4302 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4303 parse_text_attributes(p, os, FLAG_ITEM, outer,
4305 context.font.language, lang);
4309 else if (t.cs() == "inputencoding") {
4310 // nothing to write here
4311 string const enc = subst(p.verbatim_item(), "\n", " ");
4312 p.setEncoding(enc, Encoding::inputenc);
4315 else if (is_known(t.cs(), known_special_chars) ||
4316 (t.cs() == "protect" &&
4317 p.next_token().cat() == catEscape &&
4318 is_known(p.next_token().cs(), known_special_protect_chars))) {
4319 // LyX sometimes puts a \protect in front, so we have to ignore it
4321 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4322 known_special_chars);
4323 context.check_layout(os);
4324 os << known_coded_special_chars[where - known_special_chars];
4325 skip_spaces_braces(p);
4328 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4329 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4330 p.next_next_token().asInput() == "-") ||
4331 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4332 // LyX sometimes puts a \protect in front, so we have to ignore it
4333 if (t.cs() == "protect")
4335 context.check_layout(os);
4336 if (t.cs() == "nobreakdash")
4337 os << "\\SpecialChar nobreakdash\n";
4339 os << "\\SpecialChar endofsentence\n";
4343 else if (t.cs() == "textquotedbl") {
4344 context.check_layout(os);
4349 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4350 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4351 || t.cs() == "%" || t.cs() == "-") {
4352 context.check_layout(os);
4354 os << "\\SpecialChar softhyphen\n";
4359 else if (t.cs() == "char") {
4360 context.check_layout(os);
4361 if (p.next_token().character() == '`') {
4363 if (p.next_token().cs() == "\"") {
4368 output_ert_inset(os, "\\char`", context);
4371 output_ert_inset(os, "\\char", context);
4375 else if (t.cs() == "verb") {
4376 context.check_layout(os);
4377 // set catcodes to verbatim early, just in case.
4378 p.setCatcodes(VERBATIM_CATCODES);
4379 string delim = p.get_token().asInput();
4380 Parser::Arg arg = p.verbatimStuff(delim);
4382 output_ert_inset(os, "\\verb" + delim
4383 + arg.second + delim, context);
4385 cerr << "invalid \\verb command. Skipping" << endl;
4388 // Problem: \= creates a tabstop inside the tabbing environment
4389 // and else an accent. In the latter case we really would want
4390 // \={o} instead of \= o.
4391 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4392 output_ert_inset(os, t.asInput(), context);
4394 else if (t.cs() == "\\") {
4395 context.check_layout(os);
4397 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4398 else if (p.next_token().asInput() == "*") {
4400 // getOpt() eats the following space if there
4401 // is no optional argument, but that is OK
4402 // here since it has no effect in the output.
4403 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4406 begin_inset(os, "Newline newline");
4411 else if (t.cs() == "newline" ||
4412 (t.cs() == "linebreak" && !p.hasOpt())) {
4413 context.check_layout(os);
4414 begin_inset(os, "Newline ");
4417 skip_spaces_braces(p);
4420 else if (t.cs() == "input" || t.cs() == "include"
4421 || t.cs() == "verbatiminput") {
4422 string name = t.cs();
4423 if (t.cs() == "verbatiminput"
4424 && p.next_token().asInput() == "*")
4425 name += p.get_token().asInput();
4426 context.check_layout(os);
4427 string filename(normalize_filename(p.getArg('{', '}')));
4428 string const path = getMasterFilePath(true);
4429 // We want to preserve relative / absolute filenames,
4430 // therefore path is only used for testing
4431 if ((t.cs() == "include" || t.cs() == "input") &&
4432 !makeAbsPath(filename, path).exists()) {
4433 // The file extension is probably missing.
4434 // Now try to find it out.
4435 string const tex_name =
4436 find_file(filename, path,
4437 known_tex_extensions);
4438 if (!tex_name.empty())
4439 filename = tex_name;
4441 bool external = false;
4443 if (makeAbsPath(filename, path).exists()) {
4444 string const abstexname =
4445 makeAbsPath(filename, path).absFileName();
4446 string const absfigname =
4447 changeExtension(abstexname, ".fig");
4448 fix_child_filename(filename);
4449 string const lyxname = changeExtension(filename,
4450 roundtripMode() ? ".lyx.lyx" : ".lyx");
4451 string const abslyxname = makeAbsPath(
4452 lyxname, getParentFilePath(false)).absFileName();
4454 if (!skipChildren())
4455 external = FileName(absfigname).exists();
4456 if (t.cs() == "input" && !skipChildren()) {
4457 string const ext = getExtension(abstexname);
4459 // Combined PS/LaTeX:
4460 // x.eps, x.pstex_t (old xfig)
4461 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4462 FileName const absepsname(
4463 changeExtension(abstexname, ".eps"));
4464 FileName const abspstexname(
4465 changeExtension(abstexname, ".pstex"));
4466 bool const xfigeps =
4467 (absepsname.exists() ||
4468 abspstexname.exists()) &&
4471 // Combined PDF/LaTeX:
4472 // x.pdf, x.pdftex_t (old xfig)
4473 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4474 FileName const abspdfname(
4475 changeExtension(abstexname, ".pdf"));
4476 bool const xfigpdf =
4477 abspdfname.exists() &&
4478 (ext == "pdftex_t" || ext == "pdf_t");
4482 // Combined PS/PDF/LaTeX:
4483 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4484 string const absbase2(
4485 removeExtension(abstexname) + "_pspdftex");
4486 FileName const abseps2name(
4487 addExtension(absbase2, ".eps"));
4488 FileName const abspdf2name(
4489 addExtension(absbase2, ".pdf"));
4490 bool const xfigboth =
4491 abspdf2name.exists() &&
4492 abseps2name.exists() && ext == "pspdftex";
4494 xfig = xfigpdf || xfigeps || xfigboth;
4495 external = external && xfig;
4498 outname = changeExtension(filename, ".fig");
4499 FileName abssrc(changeExtension(abstexname, ".fig"));
4500 copy_file(abssrc, outname);
4502 // Don't try to convert, the result
4503 // would be full of ERT.
4505 FileName abssrc(abstexname);
4506 copy_file(abssrc, outname);
4507 } else if (t.cs() != "verbatiminput" &&
4509 tex2lyx(abstexname, FileName(abslyxname),
4512 // no need to call copy_file
4513 // tex2lyx creates the file
4516 FileName abssrc(abstexname);
4517 copy_file(abssrc, outname);
4520 cerr << "Warning: Could not find included file '"
4521 << filename << "'." << endl;
4525 begin_inset(os, "External\n");
4526 os << "\ttemplate XFig\n"
4527 << "\tfilename " << outname << '\n';
4528 registerExternalTemplatePackages("XFig");
4530 begin_command_inset(os, "include", name);
4531 outname = subst(outname, "\"", "\\\"");
4532 os << "preview false\n"
4533 "filename \"" << outname << "\"\n";
4534 if (t.cs() == "verbatiminput")
4535 preamble.registerAutomaticallyLoadedPackage("verbatim");
4540 else if (t.cs() == "bibliographystyle") {
4541 // store new bibliographystyle
4542 bibliographystyle = p.verbatim_item();
4543 // If any other command than \bibliography, \addcontentsline
4544 // and \nocite{*} follows, we need to output the style
4545 // (because it might be used by that command).
4546 // Otherwise, it will automatically be output by LyX.
4549 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4550 if (t2.cat() == catBegin)
4552 if (t2.cat() != catEscape)
4554 if (t2.cs() == "nocite") {
4555 if (p.getArg('{', '}') == "*")
4557 } else if (t2.cs() == "bibliography")
4559 else if (t2.cs() == "phantomsection") {
4563 else if (t2.cs() == "addcontentsline") {
4564 // get the 3 arguments of \addcontentsline
4567 contentslineContent = p.getArg('{', '}');
4568 // if the last argument is not \refname we must output
4569 if (contentslineContent == "\\refname")
4576 output_ert_inset(os,
4577 "\\bibliographystyle{" + bibliographystyle + '}',
4582 else if (t.cs() == "phantomsection") {
4583 // we only support this if it occurs between
4584 // \bibliographystyle and \bibliography
4585 if (bibliographystyle.empty())
4586 output_ert_inset(os, "\\phantomsection", context);
4589 else if (t.cs() == "addcontentsline") {
4590 context.check_layout(os);
4591 // get the 3 arguments of \addcontentsline
4592 string const one = p.getArg('{', '}');
4593 string const two = p.getArg('{', '}');
4594 string const three = p.getArg('{', '}');
4595 // only if it is a \refname, we support if for the bibtex inset
4596 if (contentslineContent != "\\refname") {
4597 output_ert_inset(os,
4598 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4603 else if (t.cs() == "bibliography") {
4604 context.check_layout(os);
4606 begin_command_inset(os, "bibtex", "bibtex");
4607 if (!btprint.empty()) {
4608 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4609 // clear the string because the next BibTeX inset can be without the
4610 // \nocite{*} option
4613 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4614 // Do we have addcontentsline?
4615 if (contentslineContent == "\\refname") {
4616 BibOpts = "bibtotoc";
4617 // clear string because next BibTeX inset can be without addcontentsline
4618 contentslineContent.clear();
4620 // Do we have a bibliographystyle set?
4621 if (!bibliographystyle.empty()) {
4622 if (BibOpts.empty())
4623 BibOpts = normalize_filename(bibliographystyle);
4625 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4626 // clear it because each bibtex entry has its style
4627 // and we need an empty string to handle \phantomsection
4628 bibliographystyle.clear();
4630 os << "options " << '"' << BibOpts << '"' << "\n";
4634 else if (t.cs() == "printbibliography") {
4635 context.check_layout(os);
4637 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4638 vector<string> opts = getVectorFromString(bbloptions);
4639 vector<string>::iterator it =
4640 find(opts.begin(), opts.end(), "heading=bibintoc");
4641 if (it != opts.end()) {
4643 BibOpts = "bibtotoc";
4645 bbloptions = getStringFromVector(opts);
4646 begin_command_inset(os, "bibtex", "bibtex");
4647 if (!btprint.empty()) {
4648 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4649 // clear the string because the next BibTeX inset can be without the
4650 // \nocite{*} option
4654 for (auto const & bf : preamble.biblatex_bibliographies) {
4655 if (!bibfiles.empty())
4657 bibfiles += normalize_filename(bf);
4659 if (!bibfiles.empty())
4660 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4661 // Do we have addcontentsline?
4662 if (contentslineContent == "\\refname") {
4663 BibOpts = "bibtotoc";
4664 // clear string because next BibTeX inset can be without addcontentsline
4665 contentslineContent.clear();
4667 os << "options " << '"' << BibOpts << '"' << "\n";
4668 if (!bbloptions.empty())
4669 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4671 need_commentbib = false;
4674 else if (t.cs() == "parbox") {
4675 // Test whether this is an outer box of a shaded box
4677 // swallow arguments
4678 while (p.hasOpt()) {
4680 p.skip_spaces(true);
4683 p.skip_spaces(true);
4685 if (p.next_token().cat() == catBegin)
4687 p.skip_spaces(true);
4688 Token to = p.get_token();
4689 bool shaded = false;
4690 if (to.asInput() == "\\begin") {
4691 p.skip_spaces(true);
4692 if (p.getArg('{', '}') == "shaded")
4697 parse_outer_box(p, os, FLAG_ITEM, outer,
4698 context, "parbox", "shaded");
4700 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4701 "", "", t.cs(), "", "");
4704 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4705 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4706 t.cs() == "shadowbox" || t.cs() == "doublebox")
4707 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4709 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4710 string backgroundcolor;
4711 preamble.registerAutomaticallyLoadedPackage("xcolor");
4712 if (t.cs() == "fcolorbox") {
4713 string const framecolor = p.getArg('{', '}');
4714 backgroundcolor = p.getArg('{', '}');
4715 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4717 backgroundcolor = p.getArg('{', '}');
4718 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4722 // FIXME: due to the compiler limit of "if" nestings
4723 // the code for the alignment was put here
4724 // put them in their own if if this is fixed
4725 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4726 || t.cs() == "shadowsize"
4727 || t.cs() == "raggedleft" || t.cs() == "centering"
4728 || t.cs() == "raggedright") {
4729 if (t.cs() == "fboxrule")
4731 if (t.cs() == "fboxsep")
4733 if (t.cs() == "shadowsize")
4735 if (t.cs() != "raggedleft" && t.cs() != "centering"
4736 && t.cs() != "raggedright") {
4737 p.skip_spaces(true);
4738 while (p.good() && p.next_token().cat() != catSpace
4739 && p.next_token().cat() != catNewline
4740 && p.next_token().cat() != catEscape) {
4741 if (t.cs() == "fboxrule")
4742 fboxrule = fboxrule + p.get_token().asInput();
4743 if (t.cs() == "fboxsep")
4744 fboxsep = fboxsep + p.get_token().asInput();
4745 if (t.cs() == "shadowsize")
4746 shadow_size = shadow_size + p.get_token().asInput();
4749 output_ert_inset(os, t.asInput(), context);
4753 //\framebox() is part of the picture environment and different from \framebox{}
4754 //\framebox{} will be parsed by parse_outer_box
4755 else if (t.cs() == "framebox") {
4756 if (p.next_token().character() == '(') {
4757 //the syntax is: \framebox(x,y)[position]{content}
4758 string arg = t.asInput();
4759 arg += p.getFullParentheseArg();
4760 arg += p.getFullOpt();
4761 eat_whitespace(p, os, context, false);
4762 output_ert_inset(os, arg + '{', context);
4763 parse_text(p, os, FLAG_ITEM, outer, context);
4764 output_ert_inset(os, "}", context);
4766 //the syntax is: \framebox[width][position]{content}
4767 string special = p.getFullOpt();
4768 special += p.getOpt();
4769 parse_outer_box(p, os, FLAG_ITEM, outer,
4770 context, t.cs(), special);
4774 //\makebox() is part of the picture environment and different from \makebox{}
4775 //\makebox{} will be parsed by parse_box
4776 else if (t.cs() == "makebox") {
4777 if (p.next_token().character() == '(') {
4778 //the syntax is: \makebox(x,y)[position]{content}
4779 string arg = t.asInput();
4780 arg += p.getFullParentheseArg();
4781 arg += p.getFullOpt();
4782 eat_whitespace(p, os, context, false);
4783 output_ert_inset(os, arg + '{', context);
4784 parse_text(p, os, FLAG_ITEM, outer, context);
4785 output_ert_inset(os, "}", context);
4787 //the syntax is: \makebox[width][position]{content}
4788 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4789 "", "", t.cs(), "", "");
4792 else if (t.cs() == "smallskip" ||
4793 t.cs() == "medskip" ||
4794 t.cs() == "bigskip" ||
4795 t.cs() == "vfill") {
4796 context.check_layout(os);
4797 begin_inset(os, "VSpace ");
4800 skip_spaces_braces(p);
4803 else if ((where = is_known(t.cs(), known_spaces))) {
4804 context.check_layout(os);
4805 begin_inset(os, "space ");
4806 os << '\\' << known_coded_spaces[where - known_spaces]
4809 // LaTeX swallows whitespace after all spaces except
4810 // "\\,". We have to do that here, too, because LyX
4811 // adds "{}" which would make the spaces significant.
4813 eat_whitespace(p, os, context, false);
4814 // LyX adds "{}" after all spaces except "\\ " and
4815 // "\\,", so we have to remove "{}".
4816 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4817 // remove the braces after "\\,", too.
4822 else if (t.cs() == "newpage" ||
4823 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4824 t.cs() == "clearpage" ||
4825 t.cs() == "cleardoublepage") {
4826 context.check_layout(os);
4827 begin_inset(os, "Newpage ");
4830 skip_spaces_braces(p);
4833 else if (t.cs() == "DeclareRobustCommand" ||
4834 t.cs() == "DeclareRobustCommandx" ||
4835 t.cs() == "newcommand" ||
4836 t.cs() == "newcommandx" ||
4837 t.cs() == "providecommand" ||
4838 t.cs() == "providecommandx" ||
4839 t.cs() == "renewcommand" ||
4840 t.cs() == "renewcommandx") {
4841 // DeclareRobustCommand, DeclareRobustCommandx,
4842 // providecommand and providecommandx could be handled
4843 // by parse_command(), but we need to call
4844 // add_known_command() here.
4845 string name = t.asInput();
4846 if (p.next_token().asInput() == "*") {
4847 // Starred form. Eat '*'
4851 string const command = p.verbatim_item();
4852 string const opt1 = p.getFullOpt();
4853 string const opt2 = p.getFullOpt();
4854 add_known_command(command, opt1, !opt2.empty());
4855 string const ert = name + '{' + command + '}' +
4857 '{' + p.verbatim_item() + '}';
4859 if (t.cs() == "DeclareRobustCommand" ||
4860 t.cs() == "DeclareRobustCommandx" ||
4861 t.cs() == "providecommand" ||
4862 t.cs() == "providecommandx" ||
4863 name[name.length()-1] == '*')
4864 output_ert_inset(os, ert, context);
4866 context.check_layout(os);
4867 begin_inset(os, "FormulaMacro");
4873 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4874 // let could be handled by parse_command(),
4875 // but we need to call add_known_command() here.
4876 string ert = t.asInput();
4879 if (p.next_token().cat() == catBegin) {
4880 name = p.verbatim_item();
4881 ert += '{' + name + '}';
4883 name = p.verbatim_item();
4888 if (p.next_token().cat() == catBegin) {
4889 command = p.verbatim_item();
4890 ert += '{' + command + '}';
4892 command = p.verbatim_item();
4895 // If command is known, make name known too, to parse
4896 // its arguments correctly. For this reason we also
4897 // have commands in syntax.default that are hardcoded.
4898 CommandMap::iterator it = known_commands.find(command);
4899 if (it != known_commands.end())
4900 known_commands[t.asInput()] = it->second;
4901 output_ert_inset(os, ert, context);
4904 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4907 string name = t.asInput();
4908 string const length = p.verbatim_item();
4911 bool valid = splitLatexLength(length, valstring, unit);
4912 bool known_hspace = false;
4913 bool known_vspace = false;
4914 bool known_unit = false;
4917 istringstream iss(valstring);
4920 if (t.cs()[0] == 'h') {
4921 if (unit == "\\fill") {
4926 known_hspace = true;
4929 if (unit == "\\smallskipamount") {
4931 known_vspace = true;
4932 } else if (unit == "\\medskipamount") {
4934 known_vspace = true;
4935 } else if (unit == "\\bigskipamount") {
4937 known_vspace = true;
4938 } else if (unit == "\\fill") {
4940 known_vspace = true;
4944 if (!known_hspace && !known_vspace) {
4945 switch (unitFromString(unit)) {
4961 //unitFromString(unit) fails for relative units like Length::PCW
4962 // therefore handle them separately
4963 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4964 || unit == "\\textwidth" || unit == "\\linewidth"
4965 || unit == "\\textheight" || unit == "\\paperheight"
4966 || unit == "\\baselineskip")
4974 // check for glue lengths
4975 bool is_gluelength = false;
4976 string gluelength = length;
4977 string::size_type i = length.find(" minus");
4978 if (i == string::npos) {
4979 i = length.find(" plus");
4980 if (i != string::npos)
4981 is_gluelength = true;
4983 is_gluelength = true;
4984 // if yes transform "9xx minus 8yy plus 7zz"
4986 if (is_gluelength) {
4987 i = gluelength.find(" minus");
4988 if (i != string::npos)
4989 gluelength.replace(i, 7, "-");
4990 i = gluelength.find(" plus");
4991 if (i != string::npos)
4992 gluelength.replace(i, 6, "+");
4995 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
4996 // Literal horizontal length or known variable
4997 context.check_layout(os);
4998 begin_inset(os, "space ");
5006 if (known_unit && !known_hspace)
5007 os << "\n\\length " << translate_len(length);
5009 os << "\n\\length " << gluelength;
5011 } else if (known_unit || known_vspace || is_gluelength) {
5012 // Literal vertical length or known variable
5013 context.check_layout(os);
5014 begin_inset(os, "VSpace ");
5017 if (known_unit && !known_vspace)
5018 os << translate_len(length);
5025 // LyX can't handle other length variables in Inset VSpace/space
5030 output_ert_inset(os, name + '{' + unit + '}', context);
5031 else if (value == -1.0)
5032 output_ert_inset(os, name + "{-" + unit + '}', context);
5034 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5036 output_ert_inset(os, name + '{' + length + '}', context);
5040 // The single '=' is meant here.
5041 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5045 context.check_layout(os);
5046 docstring name = newinsetlayout->name();
5047 bool const caption = name.find(from_ascii("Caption:")) == 0;
5049 // Already done for floating minted listings.
5050 if (minted_float.empty()) {
5051 begin_inset(os, "Caption ");
5052 os << to_utf8(name.substr(8)) << '\n';
5055 // FIXME: what do we do if the prefix is not Flex: ?
5056 if (prefixIs(name, from_ascii("Flex:")))
5058 begin_inset(os, "Flex ");
5059 os << to_utf8(name) << '\n'
5060 << "status collapsed\n";
5062 if (!minted_float.empty()) {
5063 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5064 } else if (newinsetlayout->isPassThru()) {
5065 // set catcodes to verbatim early, just in case.
5066 p.setCatcodes(VERBATIM_CATCODES);
5067 string delim = p.get_token().asInput();
5069 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5070 //FIXME: handle error condition
5071 string const arg = p.verbatimStuff("}").second;
5072 Context newcontext(true, context.textclass);
5073 if (newinsetlayout->forcePlainLayout())
5074 newcontext.layout = &context.textclass.plainLayout();
5075 output_ert(os, arg, newcontext);
5077 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5080 // Minted caption insets are not closed here because
5081 // we collect everything into the caption.
5082 if (minted_float.empty())
5086 else if (t.cs() == "includepdf") {
5088 string const arg = p.getArg('[', ']');
5089 map<string, string> opts;
5090 vector<string> keys;
5091 split_map(arg, opts, keys);
5092 string name = normalize_filename(p.verbatim_item());
5093 string const path = getMasterFilePath(true);
5094 // We want to preserve relative / absolute filenames,
5095 // therefore path is only used for testing
5096 if (!makeAbsPath(name, path).exists()) {
5097 // The file extension is probably missing.
5098 // Now try to find it out.
5099 char const * const pdfpages_format[] = {"pdf", 0};
5100 string const pdftex_name =
5101 find_file(name, path, pdfpages_format);
5102 if (!pdftex_name.empty()) {
5107 FileName const absname = makeAbsPath(name, path);
5108 if (absname.exists())
5110 fix_child_filename(name);
5111 copy_file(absname, name);
5113 cerr << "Warning: Could not find file '"
5114 << name << "'." << endl;
5116 context.check_layout(os);
5117 begin_inset(os, "External\n\ttemplate ");
5118 os << "PDFPages\n\tfilename "
5120 // parse the options
5121 if (opts.find("pages") != opts.end())
5122 os << "\textra LaTeX \"pages="
5123 << opts["pages"] << "\"\n";
5124 if (opts.find("angle") != opts.end())
5125 os << "\trotateAngle "
5126 << opts["angle"] << '\n';
5127 if (opts.find("origin") != opts.end()) {
5129 string const opt = opts["origin"];
5130 if (opt == "tl") ss << "topleft";
5131 if (opt == "bl") ss << "bottomleft";
5132 if (opt == "Bl") ss << "baselineleft";
5133 if (opt == "c") ss << "center";
5134 if (opt == "tc") ss << "topcenter";
5135 if (opt == "bc") ss << "bottomcenter";
5136 if (opt == "Bc") ss << "baselinecenter";
5137 if (opt == "tr") ss << "topright";
5138 if (opt == "br") ss << "bottomright";
5139 if (opt == "Br") ss << "baselineright";
5140 if (!ss.str().empty())
5141 os << "\trotateOrigin " << ss.str() << '\n';
5143 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5145 if (opts.find("width") != opts.end())
5147 << translate_len(opts["width"]) << '\n';
5148 if (opts.find("height") != opts.end())
5150 << translate_len(opts["height"]) << '\n';
5151 if (opts.find("keepaspectratio") != opts.end())
5152 os << "\tkeepAspectRatio\n";
5154 context.check_layout(os);
5155 registerExternalTemplatePackages("PDFPages");
5158 else if (t.cs() == "loadgame") {
5160 string name = normalize_filename(p.verbatim_item());
5161 string const path = getMasterFilePath(true);
5162 // We want to preserve relative / absolute filenames,
5163 // therefore path is only used for testing
5164 if (!makeAbsPath(name, path).exists()) {
5165 // The file extension is probably missing.
5166 // Now try to find it out.
5167 char const * const lyxskak_format[] = {"fen", 0};
5168 string const lyxskak_name =
5169 find_file(name, path, lyxskak_format);
5170 if (!lyxskak_name.empty())
5171 name = lyxskak_name;
5173 FileName const absname = makeAbsPath(name, path);
5174 if (absname.exists())
5176 fix_child_filename(name);
5177 copy_file(absname, name);
5179 cerr << "Warning: Could not find file '"
5180 << name << "'." << endl;
5181 context.check_layout(os);
5182 begin_inset(os, "External\n\ttemplate ");
5183 os << "ChessDiagram\n\tfilename "
5186 context.check_layout(os);
5187 // after a \loadgame follows a \showboard
5188 if (p.get_token().asInput() == "showboard")
5190 registerExternalTemplatePackages("ChessDiagram");
5194 // try to see whether the string is in unicodesymbols
5195 // Only use text mode commands, since we are in text mode here,
5196 // and math commands may be invalid (bug 6797)
5197 string name = t.asInput();
5198 // handle the dingbats, cyrillic and greek
5199 if (name == "\\ding" || name == "\\textcyr" ||
5200 (name == "\\textgreek" && !preamble.usePolyglossia()))
5201 name = name + '{' + p.getArg('{', '}') + '}';
5202 // handle the ifsym characters
5203 else if (name == "\\textifsymbol") {
5204 string const optif = p.getFullOpt();
5205 string const argif = p.getArg('{', '}');
5206 name = name + optif + '{' + argif + '}';
5208 // handle the \ascii characters
5209 // the case of \ascii within braces, as LyX outputs it, is already
5210 // handled for t.cat() == catBegin
5211 else if (name == "\\ascii") {
5212 // the code is "\asci\xxx"
5213 name = "{" + name + p.get_token().asInput() + "}";
5216 // handle some TIPA special characters
5217 else if (preamble.isPackageUsed("tipa")) {
5218 if (name == "\\s") {
5219 // fromLaTeXCommand() does not yet
5220 // recognize tipa short cuts
5221 name = "\\textsyllabic";
5222 } else if (name == "\\=" &&
5223 p.next_token().asInput() == "*") {
5224 // fromLaTeXCommand() does not yet
5225 // recognize tipa short cuts
5227 name = "\\textsubbar";
5228 } else if (name == "\\textdoublevertline") {
5229 // FIXME: This is not correct,
5230 // \textvertline is higher than \textbardbl
5231 name = "\\textbardbl";
5233 } else if (name == "\\!" ) {
5234 if (p.next_token().asInput() == "b") {
5235 p.get_token(); // eat 'b'
5238 } else if (p.next_token().asInput() == "d") {
5242 } else if (p.next_token().asInput() == "g") {
5246 } else if (p.next_token().asInput() == "G") {
5248 name = "\\texthtscg";
5250 } else if (p.next_token().asInput() == "j") {
5252 name = "\\texthtbardotlessj";
5254 } else if (p.next_token().asInput() == "o") {
5256 name = "\\textbullseye";
5259 } else if (name == "\\*" ) {
5260 if (p.next_token().asInput() == "k") {
5262 name = "\\textturnk";
5264 } else if (p.next_token().asInput() == "r") {
5265 p.get_token(); // eat 'b'
5266 name = "\\textturnr";
5268 } else if (p.next_token().asInput() == "t") {
5270 name = "\\textturnt";
5272 } else if (p.next_token().asInput() == "w") {
5274 name = "\\textturnw";
5279 if ((name.size() == 2 &&
5280 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5281 p.next_token().asInput() != "*") ||
5282 is_known(name.substr(1), known_tipa_marks)) {
5283 // name is a command that corresponds to a
5284 // combining character in unicodesymbols.
5285 // Append the argument, fromLaTeXCommand()
5286 // will either convert it to a single
5287 // character or a combining sequence.
5288 name += '{' + p.verbatim_item() + '}';
5290 // now get the character from unicodesymbols
5294 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5295 Encodings::TEXT_CMD, termination, rem, &req));
5297 context.check_layout(os);
5300 output_ert_inset(os, to_utf8(rem), context);
5302 skip_spaces_braces(p);
5303 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5304 preamble.registerAutomaticallyLoadedPackage(*it);
5306 //cerr << "#: " << t << " mode: " << mode << endl;
5307 // heuristic: read up to next non-nested space
5309 string s = t.asInput();
5310 string z = p.verbatim_item();
5311 while (p.good() && z != " " && !z.empty()) {
5312 //cerr << "read: " << z << endl;
5314 z = p.verbatim_item();
5316 cerr << "found ERT: " << s << endl;
5317 output_ert_inset(os, s + ' ', context);
5320 if (t.asInput() == name &&
5321 p.next_token().asInput() == "*") {
5322 // Starred commands like \vspace*{}
5323 p.get_token(); // Eat '*'
5326 if (!parse_command(name, p, os, outer, context))
5327 output_ert_inset(os, name, context);
5331 if (flags & FLAG_LEAVE) {
5332 flags &= ~FLAG_LEAVE;
5339 string guessLanguage(Parser & p, string const & lang)
5341 typedef std::map<std::string, size_t> LangMap;
5342 // map from language names to number of characters
5345 for (char const * const * i = supported_CJK_languages; *i; i++)
5346 used[string(*i)] = 0;
5349 Token const t = p.get_token();
5350 // comments are not counted for any language
5351 if (t.cat() == catComment)
5353 // commands are not counted as well, but we need to detect
5354 // \begin{CJK} and switch encoding if needed
5355 if (t.cat() == catEscape) {
5356 if (t.cs() == "inputencoding") {
5357 string const enc = subst(p.verbatim_item(), "\n", " ");
5358 p.setEncoding(enc, Encoding::inputenc);
5361 if (t.cs() != "begin")
5364 // Non-CJK content is counted for lang.
5365 // We do not care about the real language here:
5366 // If we have more non-CJK contents than CJK contents,
5367 // we simply use the language that was specified as
5368 // babel main language.
5369 used[lang] += t.asInput().length();
5372 // Now we are starting an environment
5374 string const name = p.getArg('{', '}');
5375 if (name != "CJK") {
5379 // It is a CJK environment
5381 /* name = */ p.getArg('{', '}');
5382 string const encoding = p.getArg('{', '}');
5383 /* mapping = */ p.getArg('{', '}');
5384 string const encoding_old = p.getEncoding();
5385 char const * const * const where =
5386 is_known(encoding, supported_CJK_encodings);
5388 p.setEncoding(encoding, Encoding::CJK);
5390 p.setEncoding("UTF-8");
5391 string const text = p.ertEnvironment("CJK");
5392 p.setEncoding(encoding_old);
5395 // ignore contents in unknown CJK encoding
5398 // the language of the text
5400 supported_CJK_languages[where - supported_CJK_encodings];
5401 used[cjk] += text.length();
5403 LangMap::const_iterator use = used.begin();
5404 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5405 if (it->second > use->second)
5412 void check_comment_bib(ostream & os, Context & context)
5414 if (!need_commentbib)
5416 // We have a bibliography database, but no bibliography with biblatex
5417 // which is completely valid. Insert a bibtex inset in a note.
5418 context.check_layout(os);
5419 begin_inset(os, "Note Note\n");
5420 os << "status open\n";
5421 os << "\\begin_layout Plain Layout\n";
5422 begin_command_inset(os, "bibtex", "bibtex");
5424 for (auto const & bf : preamble.biblatex_bibliographies) {
5425 if (!bibfiles.empty())
5427 bibfiles += normalize_filename(bf);
5429 if (!bibfiles.empty())
5430 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5431 end_inset(os);// Bibtex
5432 os << "\\end_layout\n";
5433 end_inset(os);// Note