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 os << to_utf8(newinsetlayout->name()) << '\n'
2010 << "status collapsed\n";
2011 if (newinsetlayout->isPassThru()) {
2012 string const arg = p.verbatimEnvironment(name);
2013 Context context(true, parent_context.textclass,
2014 &parent_context.textclass.plainLayout(),
2015 parent_context.layout);
2016 output_ert(os, arg, parent_context);
2018 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
2022 else if (name == "appendix") {
2023 // This is no good latex style, but it works and is used in some documents...
2024 eat_whitespace(p, os, parent_context, false);
2025 parent_context.check_end_layout(os);
2026 Context context(true, parent_context.textclass, parent_context.layout,
2027 parent_context.layout, parent_context.font);
2028 context.check_layout(os);
2029 os << "\\start_of_appendix\n";
2030 parse_text(p, os, FLAG_END, outer, context);
2031 context.check_end_layout(os);
2035 else if (known_environments.find(name) != known_environments.end()) {
2036 vector<ArgumentType> arguments = known_environments[name];
2037 // The last "argument" denotes wether we may translate the
2038 // environment contents to LyX
2039 // The default required if no argument is given makes us
2040 // compatible with the reLyXre environment.
2041 ArgumentType contents = arguments.empty() ?
2044 if (!arguments.empty())
2045 arguments.pop_back();
2046 // See comment in parse_unknown_environment()
2047 bool const specialfont =
2048 (parent_context.font != parent_context.normalfont);
2049 bool const new_layout_allowed =
2050 parent_context.new_layout_allowed;
2052 parent_context.new_layout_allowed = false;
2053 parse_arguments("\\begin{" + name + "}", arguments, p, os,
2054 outer, parent_context);
2055 if (contents == verbatim)
2056 output_ert_inset(os, p.ertEnvironment(name),
2059 parse_text_snippet(p, os, FLAG_END, outer,
2061 output_ert_inset(os, "\\end{" + name + "}", parent_context);
2063 parent_context.new_layout_allowed = new_layout_allowed;
2067 parse_unknown_environment(p, name, os, FLAG_END, outer,
2071 active_environments.pop_back();
2075 /// parses a comment and outputs it to \p os.
2076 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
2078 LASSERT(t.cat() == catComment, return);
2079 if (!t.cs().empty()) {
2080 context.check_layout(os);
2081 output_comment(p, os, t.cs(), context);
2082 if (p.next_token().cat() == catNewline) {
2083 // A newline after a comment line starts a new
2085 if (context.new_layout_allowed) {
2086 if(!context.atParagraphStart())
2087 // Only start a new paragraph if not already
2088 // done (we might get called recursively)
2089 context.new_paragraph(os);
2091 output_ert_inset(os, "\n", context);
2092 eat_whitespace(p, os, context, true);
2095 // "%\n" combination
2102 * Reads spaces and comments until the first non-space, non-comment token.
2103 * New paragraphs (double newlines or \\par) are handled like simple spaces
2104 * if \p eatParagraph is true.
2105 * Spaces are skipped, but comments are written to \p os.
2107 void eat_whitespace(Parser & p, ostream & os, Context & context,
2111 Token const & t = p.get_token();
2112 if (t.cat() == catComment)
2113 parse_comment(p, os, t, context);
2114 else if ((! eatParagraph && p.isParagraph()) ||
2115 (t.cat() != catSpace && t.cat() != catNewline)) {
2124 * Set a font attribute, parse text and reset the font attribute.
2125 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
2126 * \param currentvalue Current value of the attribute. Is set to the new
2127 * value during parsing.
2128 * \param newvalue New value of the attribute
2130 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
2131 Context & context, string const & attribute,
2132 string & currentvalue, string const & newvalue)
2134 context.check_layout(os);
2135 string const oldvalue = currentvalue;
2136 currentvalue = newvalue;
2137 os << '\n' << attribute << ' ' << newvalue << "\n";
2138 parse_text_snippet(p, os, flags, outer, context);
2139 context.check_layout(os);
2140 os << '\n' << attribute << ' ' << oldvalue << "\n";
2141 currentvalue = oldvalue;
2145 /// get the arguments of a natbib or jurabib citation command
2146 void get_cite_arguments(Parser & p, bool natbibOrder,
2147 string & before, string & after)
2149 // We need to distinguish "" and "[]", so we can't use p.getOpt().
2151 // text before the citation
2153 // text after the citation
2154 after = p.getFullOpt();
2156 if (!after.empty()) {
2157 before = p.getFullOpt();
2158 if (natbibOrder && !before.empty())
2159 swap(before, after);
2164 /// Convert filenames with TeX macros and/or quotes to something LyX
2166 string const normalize_filename(string const & name)
2171 Token const & t = p.get_token();
2172 if (t.cat() != catEscape)
2174 else if (t.cs() == "lyxdot") {
2175 // This is used by LyX for simple dots in relative
2179 } else if (t.cs() == "space") {
2182 } else if (t.cs() == "string") {
2183 // Convert \string" to " and \string~ to ~
2184 Token const & n = p.next_token();
2185 if (n.asInput() != "\"" && n.asInput() != "~")
2190 // Strip quotes. This is a bit complicated (see latex_path()).
2191 string full = os.str();
2192 if (!full.empty() && full[0] == '"') {
2193 string base = removeExtension(full);
2194 string ext = getExtension(full);
2195 if (!base.empty() && base[base.length()-1] == '"')
2198 return addExtension(trim(base, "\""), ext);
2199 if (full[full.length()-1] == '"')
2202 return trim(full, "\"");
2208 /// Convert \p name from TeX convention (relative to master file) to LyX
2209 /// convention (relative to .lyx file) if it is relative
2210 void fix_child_filename(string & name)
2212 string const absMasterTeX = getMasterFilePath(true);
2213 bool const isabs = FileName::isAbsolute(name);
2214 // convert from "relative to .tex master" to absolute original path
2216 name = makeAbsPath(name, absMasterTeX).absFileName();
2217 bool copyfile = copyFiles();
2218 string const absParentLyX = getParentFilePath(false);
2221 // convert from absolute original path to "relative to master file"
2222 string const rel = to_utf8(makeRelPath(from_utf8(name),
2223 from_utf8(absMasterTeX)));
2224 // re-interpret "relative to .tex file" as "relative to .lyx file"
2225 // (is different if the master .lyx file resides in a
2226 // different path than the master .tex file)
2227 string const absMasterLyX = getMasterFilePath(false);
2228 abs = makeAbsPath(rel, absMasterLyX).absFileName();
2229 // Do not copy if the new path is impossible to create. Example:
2230 // absMasterTeX = "/foo/bar/"
2231 // absMasterLyX = "/bar/"
2232 // name = "/baz.eps" => new absolute name would be "/../baz.eps"
2233 if (contains(name, "/../"))
2240 // convert from absolute original path to
2241 // "relative to .lyx file"
2242 name = to_utf8(makeRelPath(from_utf8(abs),
2243 from_utf8(absParentLyX)));
2247 // convert from absolute original path to "relative to .lyx file"
2248 name = to_utf8(makeRelPath(from_utf8(name),
2249 from_utf8(absParentLyX)));
2254 void copy_file(FileName const & src, string dstname)
2258 string const absParent = getParentFilePath(false);
2260 if (FileName::isAbsolute(dstname))
2261 dst = FileName(dstname);
2263 dst = makeAbsPath(dstname, absParent);
2264 FileName const srcpath = src.onlyPath();
2265 FileName const dstpath = dst.onlyPath();
2266 if (equivalent(srcpath, dstpath))
2268 if (!dstpath.isDirectory()) {
2269 if (!dstpath.createPath()) {
2270 cerr << "Warning: Could not create directory for file `"
2271 << dst.absFileName() << "´." << endl;
2275 if (dst.isReadableFile()) {
2276 if (overwriteFiles())
2277 cerr << "Warning: Overwriting existing file `"
2278 << dst.absFileName() << "´." << endl;
2280 cerr << "Warning: Not overwriting existing file `"
2281 << dst.absFileName() << "´." << endl;
2285 if (!src.copyTo(dst))
2286 cerr << "Warning: Could not copy file `" << src.absFileName()
2287 << "´ to `" << dst.absFileName() << "´." << endl;
2291 /// Parse a literate Chunk section. The initial "<<" is already parsed.
2292 bool parse_chunk(Parser & p, ostream & os, Context & context)
2294 // check whether a chunk is possible here.
2295 if (!context.textclass.hasInsetLayout(from_ascii("Flex:Chunk"))) {
2301 // read the parameters
2302 Parser::Arg const params = p.verbatimStuff(">>=\n", false);
2303 if (!params.first) {
2308 Parser::Arg const code = p.verbatimStuff("\n@");
2313 string const post_chunk = p.verbatimStuff("\n").second + '\n';
2314 if (post_chunk[0] != ' ' && post_chunk[0] != '\n') {
2318 // The last newline read is important for paragraph handling
2322 //cerr << "params=[" << params.second << "], code=[" << code.second << "]" <<endl;
2323 // We must have a valid layout before outputting the Chunk inset.
2324 context.check_layout(os);
2325 Context chunkcontext(true, context.textclass);
2326 chunkcontext.layout = &context.textclass.plainLayout();
2327 begin_inset(os, "Flex Chunk");
2328 os << "\nstatus open\n";
2329 if (!params.second.empty()) {
2330 chunkcontext.check_layout(os);
2331 Context paramscontext(true, context.textclass);
2332 paramscontext.layout = &context.textclass.plainLayout();
2333 begin_inset(os, "Argument 1");
2334 os << "\nstatus open\n";
2335 output_ert(os, params.second, paramscontext);
2338 output_ert(os, code.second, chunkcontext);
2346 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
2347 bool is_macro(Parser & p)
2349 Token first = p.curr_token();
2350 if (first.cat() != catEscape || !p.good())
2352 if (first.cs() == "def")
2354 if (first.cs() != "global" && first.cs() != "long")
2356 Token second = p.get_token();
2358 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
2359 second.cat() == catNewline || second.cat() == catComment)) {
2360 second = p.get_token();
2363 bool secondvalid = second.cat() == catEscape;
2365 bool thirdvalid = false;
2366 if (p.good() && first.cs() == "global" && secondvalid &&
2367 second.cs() == "long") {
2368 third = p.get_token();
2370 while (p.good() && !p.isParagraph() &&
2371 (third.cat() == catSpace ||
2372 third.cat() == catNewline ||
2373 third.cat() == catComment)) {
2374 third = p.get_token();
2377 thirdvalid = third.cat() == catEscape;
2379 for (int i = 0; i < pos; ++i)
2384 return (first.cs() == "global" || first.cs() == "long") &&
2385 second.cs() == "def";
2386 return first.cs() == "global" && second.cs() == "long" &&
2387 third.cs() == "def";
2391 /// Parse a macro definition (assumes that is_macro() returned true)
2392 void parse_macro(Parser & p, ostream & os, Context & context)
2394 context.check_layout(os);
2395 Token first = p.curr_token();
2398 string command = first.asInput();
2399 if (first.cs() != "def") {
2401 eat_whitespace(p, os, context, false);
2402 second = p.curr_token();
2403 command += second.asInput();
2404 if (second.cs() != "def") {
2406 eat_whitespace(p, os, context, false);
2407 third = p.curr_token();
2408 command += third.asInput();
2411 eat_whitespace(p, os, context, false);
2412 string const name = p.get_token().cs();
2413 eat_whitespace(p, os, context, false);
2419 while (p.next_token().cat() != catBegin) {
2420 if (p.next_token().cat() == catParameter) {
2425 // followed by number?
2426 if (p.next_token().cat() == catOther) {
2427 string s = p.get_token().asInput();
2429 // number = current arity + 1?
2430 if (s.size() == 1 && s[0] == arity + '0' + 1)
2435 paramtext += p.get_token().cs();
2437 paramtext += p.get_token().cs();
2442 // only output simple (i.e. compatible) macro as FormulaMacros
2443 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
2445 context.check_layout(os);
2446 begin_inset(os, "FormulaMacro");
2447 os << "\n\\def" << ert;
2450 output_ert_inset(os, command + ert, context);
2454 void registerExternalTemplatePackages(string const & name)
2456 external::TemplateManager const & etm = external::TemplateManager::get();
2457 external::Template const * const et = etm.getTemplateByName(name);
2460 external::Template::Formats::const_iterator cit = et->formats.end();
2462 cit = et->formats.find("PDFLaTeX");
2463 if (cit == et->formats.end())
2464 // If the template has not specified a PDFLaTeX output,
2465 // we try the LaTeX format.
2466 cit = et->formats.find("LaTeX");
2467 if (cit == et->formats.end())
2469 vector<string>::const_iterator qit = cit->second.requirements.begin();
2470 vector<string>::const_iterator qend = cit->second.requirements.end();
2471 for (; qit != qend; ++qit)
2472 preamble.registerAutomaticallyLoadedPackage(*qit);
2475 } // anonymous namespace
2478 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
2481 Layout const * newlayout = 0;
2482 InsetLayout const * newinsetlayout = 0;
2483 char const * const * where = 0;
2484 // Store the latest bibliographystyle, addcontentslineContent and
2485 // nocite{*} option (needed for bibtex inset)
2487 string contentslineContent;
2488 string bibliographystyle = "default";
2489 bool const use_natbib = isProvided("natbib");
2490 bool const use_jurabib = isProvided("jurabib");
2491 bool const use_biblatex = isProvided("biblatex")
2492 && preamble.citeEngine() != "biblatex-natbib";
2493 bool const use_biblatex_natbib = isProvided("biblatex-natbib")
2494 || (isProvided("biblatex") && preamble.citeEngine() == "biblatex-natbib");
2495 need_commentbib = use_biblatex || use_biblatex_natbib;
2498 // it is impossible to determine the correct encoding for non-CJK Japanese.
2499 // Therefore write a note at the beginning of the document
2500 if (is_nonCJKJapanese) {
2501 context.check_layout(os);
2502 begin_inset(os, "Note Note\n");
2503 os << "status open\n\\begin_layout Plain Layout\n"
2504 << "\\series bold\n"
2505 << "Important information:\n"
2506 << "\\end_layout\n\n"
2507 << "\\begin_layout Plain Layout\n"
2508 << "The original LaTeX source for this document is in Japanese (pLaTeX).\n"
2509 << " It was therefore impossible for tex2lyx to determine the correct encoding.\n"
2510 << " The iconv encoding " << p.getEncoding() << " was used.\n"
2511 << " If this is incorrect, you must run the tex2lyx program on the command line\n"
2512 << " and specify the encoding using the -e command-line switch.\n"
2513 << " In addition, you might want to double check that the desired output encoding\n"
2514 << " is correctly selected in Document > Settings > Language.\n"
2515 << "\\end_layout\n";
2517 is_nonCJKJapanese = false;
2521 Token const & t = p.get_token();
2523 debugToken(cerr, t, flags);
2526 if (flags & FLAG_ITEM) {
2527 if (t.cat() == catSpace)
2530 flags &= ~FLAG_ITEM;
2531 if (t.cat() == catBegin) {
2532 // skip the brace and collect everything to the next matching
2534 flags |= FLAG_BRACE_LAST;
2538 // handle only this single token, leave the loop if done
2539 flags |= FLAG_LEAVE;
2542 if (t.cat() != catEscape && t.character() == ']' &&
2543 (flags & FLAG_BRACK_LAST))
2545 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
2548 // If there is anything between \end{env} and \begin{env} we
2549 // don't need to output a separator.
2550 if (t.cat() != catSpace && t.cat() != catNewline &&
2551 t.asInput() != "\\begin")
2557 bool const starred = p.next_token().asInput() == "*";
2558 string const starredname(starred ? (t.cs() + '*') : t.cs());
2559 if (t.cat() == catMath) {
2560 // we are inside some text mode thingy, so opening new math is allowed
2561 context.check_layout(os);
2562 begin_inset(os, "Formula ");
2563 Token const & n = p.get_token();
2564 bool const display(n.cat() == catMath && outer);
2566 // TeX's $$...$$ syntax for displayed math
2568 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2570 p.get_token(); // skip the second '$' token
2572 // simple $...$ stuff
2575 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
2580 // Prevent the conversion of a line break to a
2581 // space (bug 7668). This does not change the
2582 // output, but looks ugly in LyX.
2583 eat_whitespace(p, os, context, false);
2587 else if (t.cat() == catSuper || t.cat() == catSub)
2588 cerr << "catcode " << t << " illegal in text mode\n";
2590 // Basic support for english quotes. This should be
2591 // extended to other quotes, but is not so easy (a
2592 // left english quote is the same as a right german
2594 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
2595 context.check_layout(os);
2596 begin_inset(os, "Quotes ");
2602 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
2603 context.check_layout(os);
2604 begin_inset(os, "Quotes ");
2611 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
2612 context.check_layout(os);
2613 begin_inset(os, "Quotes ");
2620 else if (t.asInput() == "<"
2621 && p.next_token().asInput() == "<") {
2622 bool has_chunk = false;
2626 has_chunk = parse_chunk(p, os, context);
2632 context.check_layout(os);
2633 begin_inset(os, "Quotes ");
2634 //FIXME: this is a right danish quote;
2635 // why not a left french quote?
2643 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
2644 check_space(p, os, context);
2646 // babel shorthands (also used by polyglossia)
2647 // Since these can have different meanings for different languages
2648 // we import them as ERT (but they must be put in ERT to get output
2650 else if (t.asInput() == "\"") {
2652 // These are known pairs. We put them together in
2653 // one ERT inset. In other cases (such as "a), only
2654 // the quotation mark is ERTed.
2655 if (p.next_token().asInput() == "\""
2656 || p.next_token().asInput() == "|"
2657 || p.next_token().asInput() == "-"
2658 || p.next_token().asInput() == "~"
2659 || p.next_token().asInput() == "="
2660 || p.next_token().asInput() == "/"
2661 || 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 s += p.next_token().asInput();
2669 output_ert_inset(os, s, context);
2672 else if (t.character() == '[' && noweb_mode &&
2673 p.next_token().character() == '[') {
2674 // These can contain underscores
2676 string const s = p.getFullOpt() + ']';
2677 if (p.next_token().character() == ']')
2680 cerr << "Warning: Inserting missing ']' in '"
2681 << s << "'." << endl;
2682 output_ert_inset(os, s, context);
2685 else if (t.cat() == catLetter) {
2686 context.check_layout(os);
2690 else if (t.cat() == catOther ||
2691 t.cat() == catAlign ||
2692 t.cat() == catParameter) {
2693 context.check_layout(os);
2694 if (t.asInput() == "-" && p.next_token().asInput() == "-" &&
2695 context.merging_hyphens_allowed &&
2696 context.font.family != "ttfamily" &&
2697 !context.layout->pass_thru) {
2698 if (p.next_next_token().asInput() == "-") {
2700 os << to_utf8(docstring(1, 0x2014));
2704 os << to_utf8(docstring(1, 0x2013));
2707 // This translates "&" to "\\&" which may be wrong...
2711 else if (p.isParagraph()) {
2712 // In minted floating listings we will collect
2713 // everything into the caption, where multiple
2714 // paragraphs are forbidden.
2715 if (minted_float.empty()) {
2716 if (context.new_layout_allowed)
2717 context.new_paragraph(os);
2719 output_ert_inset(os, "\\par ", context);
2722 eat_whitespace(p, os, context, true);
2725 else if (t.cat() == catActive) {
2726 context.check_layout(os);
2727 if (t.character() == '~') {
2728 if (context.layout->free_spacing)
2731 begin_inset(os, "space ~\n");
2738 else if (t.cat() == catBegin) {
2739 Token const next = p.next_token();
2740 Token const end = p.next_next_token();
2741 if (next.cat() == catEnd) {
2743 Token const prev = p.prev_token();
2745 if (p.next_token().character() == '`')
2746 ; // ignore it in {}``
2748 output_ert_inset(os, "{}", context);
2749 } else if (next.cat() == catEscape &&
2750 is_known(next.cs(), known_quotes) &&
2751 end.cat() == catEnd) {
2752 // Something like {\textquoteright} (e.g.
2753 // from writer2latex). LyX writes
2754 // \textquoteright{}, so we may skip the
2755 // braces here for better readability.
2756 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2758 } else if (p.next_token().asInput() == "\\ascii") {
2759 // handle the \ascii characters
2760 // (the case without braces is handled later)
2761 // the code is "{\ascii\xxx}"
2762 p.get_token(); // eat \ascii
2763 string name2 = p.get_token().asInput();
2764 p.get_token(); // eat the final '}'
2765 string const name = "{\\ascii" + name2 + "}";
2769 // get the character from unicodesymbols
2770 docstring s = encodings.fromLaTeXCommand(from_utf8(name),
2771 Encodings::TEXT_CMD, termination, rem, &req);
2773 context.check_layout(os);
2776 output_ert_inset(os,
2777 to_utf8(rem), context);
2778 for (set<string>::const_iterator it = req.begin();
2779 it != req.end(); ++it)
2780 preamble.registerAutomaticallyLoadedPackage(*it);
2782 // we did not find a non-ert version
2783 output_ert_inset(os, name, context);
2785 context.check_layout(os);
2786 // special handling of font attribute changes
2787 Token const prev = p.prev_token();
2788 TeXFont const oldFont = context.font;
2789 if (next.character() == '[' ||
2790 next.character() == ']' ||
2791 next.character() == '*') {
2793 if (p.next_token().cat() == catEnd) {
2798 output_ert_inset(os, "{", context);
2799 parse_text_snippet(p, os,
2802 output_ert_inset(os, "}", context);
2804 } else if (! context.new_layout_allowed) {
2805 output_ert_inset(os, "{", context);
2806 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2808 output_ert_inset(os, "}", context);
2809 } else if (is_known(next.cs(), known_sizes)) {
2810 // next will change the size, so we must
2812 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2814 if (!context.atParagraphStart())
2816 << context.font.size << "\n";
2817 } else if (is_known(next.cs(), known_font_families)) {
2818 // next will change the font family, so we
2819 // must reset it here
2820 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2822 if (!context.atParagraphStart())
2824 << context.font.family << "\n";
2825 } else if (is_known(next.cs(), known_font_series)) {
2826 // next will change the font series, so we
2827 // must reset it here
2828 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2830 if (!context.atParagraphStart())
2832 << context.font.series << "\n";
2833 } else if (is_known(next.cs(), known_font_shapes)) {
2834 // next will change the font shape, so we
2835 // must reset it here
2836 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2838 if (!context.atParagraphStart())
2840 << context.font.shape << "\n";
2841 } else if (is_known(next.cs(), known_old_font_families) ||
2842 is_known(next.cs(), known_old_font_series) ||
2843 is_known(next.cs(), known_old_font_shapes)) {
2844 // next will change the font family, series
2845 // and shape, so we must reset it here
2846 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2848 if (!context.atParagraphStart())
2850 << context.font.family
2852 << context.font.series
2854 << context.font.shape << "\n";
2856 output_ert_inset(os, "{", context);
2857 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2859 output_ert_inset(os, "}", context);
2864 else if (t.cat() == catEnd) {
2865 if (flags & FLAG_BRACE_LAST) {
2868 cerr << "stray '}' in text\n";
2869 output_ert_inset(os, "}", context);
2872 else if (t.cat() == catComment)
2873 parse_comment(p, os, t, context);
2876 // control sequences
2879 else if (t.cs() == "(" || t.cs() == "[") {
2880 bool const simple = t.cs() == "(";
2881 context.check_layout(os);
2882 begin_inset(os, "Formula");
2883 os << " \\" << t.cs();
2884 parse_math(p, os, simple ? FLAG_SIMPLE2 : FLAG_EQUATION, MATH_MODE);
2885 os << '\\' << (simple ? ')' : ']');
2888 // Prevent the conversion of a line break to a
2889 // space (bug 7668). This does not change the
2890 // output, but looks ugly in LyX.
2891 eat_whitespace(p, os, context, false);
2895 else if (t.cs() == "begin")
2896 parse_environment(p, os, outer, last_env,
2899 else if (t.cs() == "end") {
2900 if (flags & FLAG_END) {
2901 // eat environment name
2902 string const name = p.getArg('{', '}');
2903 if (name != active_environment())
2904 cerr << "\\end{" + name + "} does not match \\begin{"
2905 + active_environment() + "}\n";
2908 p.error("found 'end' unexpectedly");
2911 else if (t.cs() == "item") {
2913 bool const optarg = p.hasOpt();
2915 // FIXME: This swallows comments, but we cannot use
2916 // eat_whitespace() since we must not output
2917 // anything before the item.
2918 p.skip_spaces(true);
2919 s = p.verbatimOption();
2921 p.skip_spaces(false);
2923 context.check_layout(os);
2924 if (context.has_item) {
2925 // An item in an unknown list-like environment
2926 // FIXME: Do this in check_layout()!
2927 context.has_item = false;
2929 output_ert_inset(os, "\\item", context);
2931 output_ert_inset(os, "\\item ", context);
2934 if (context.layout->labeltype != LABEL_MANUAL) {
2935 // handle option of itemize item
2936 begin_inset(os, "Argument item:1\n");
2937 os << "status open\n";
2938 os << "\n\\begin_layout Plain Layout\n";
2940 os << parse_text_snippet(p2,
2941 FLAG_BRACK_LAST, outer, context);
2942 // we must not use context.check_end_layout(os)
2943 // because that would close the outer itemize layout
2944 os << "\n\\end_layout\n";
2946 eat_whitespace(p, os, context, false);
2947 } else if (!s.empty()) {
2948 // LyX adds braces around the argument,
2949 // so we need to remove them here.
2950 if (s.size() > 2 && s[0] == '{' &&
2951 s[s.size()-1] == '}')
2952 s = s.substr(1, s.size()-2);
2953 // If the argument contains a space we
2954 // must put it into ERT: Otherwise LyX
2955 // would misinterpret the space as
2956 // item delimiter (bug 7663)
2957 if (contains(s, ' ')) {
2958 output_ert_inset(os, s, context);
2961 os << parse_text_snippet(p2,
2962 FLAG_BRACK_LAST, outer, context);
2964 // The space is needed to separate the
2965 // item from the rest of the sentence.
2967 eat_whitespace(p, os, context, false);
2972 else if (t.cs() == "bibitem") {
2974 context.check_layout(os);
2975 eat_whitespace(p, os, context, false);
2976 string label = convert_command_inset_arg(p.verbatimOption());
2977 string key = convert_command_inset_arg(p.verbatim_item());
2978 if (contains(label, '\\') || contains(key, '\\')) {
2979 // LyX can't handle LaTeX commands in labels or keys
2980 output_ert_inset(os, t.asInput() + '[' + label +
2981 "]{" + p.verbatim_item() + '}',
2984 begin_command_inset(os, "bibitem", "bibitem");
2985 os << "label \"" << label << "\"\n"
2986 << "key \"" << key << "\"\n"
2987 << "literal \"true\"\n";
2992 else if (is_macro(p)) {
2993 // catch the case of \def\inputGnumericTable
2995 if (t.cs() == "def") {
2996 Token second = p.next_token();
2997 if (second.cs() == "inputGnumericTable") {
3001 Token third = p.get_token();
3003 if (third.cs() == "input") {
3007 string name = normalize_filename(p.verbatim_item());
3008 string const path = getMasterFilePath(true);
3009 // We want to preserve relative / absolute filenames,
3010 // therefore path is only used for testing
3011 // The file extension is in every case ".tex".
3012 // So we need to remove this extension and check for
3013 // the original one.
3014 name = removeExtension(name);
3015 if (!makeAbsPath(name, path).exists()) {
3016 char const * const Gnumeric_formats[] = {"gnumeric",
3018 string const Gnumeric_name =
3019 find_file(name, path, Gnumeric_formats);
3020 if (!Gnumeric_name.empty())
3021 name = Gnumeric_name;
3023 FileName const absname = makeAbsPath(name, path);
3024 if (absname.exists()) {
3025 fix_child_filename(name);
3026 copy_file(absname, name);
3028 cerr << "Warning: Could not find file '"
3029 << name << "'." << endl;
3030 context.check_layout(os);
3031 begin_inset(os, "External\n\ttemplate ");
3032 os << "GnumericSpreadsheet\n\tfilename "
3035 context.check_layout(os);
3037 // register the packages that are automatically loaded
3038 // by the Gnumeric template
3039 registerExternalTemplatePackages("GnumericSpreadsheet");
3044 parse_macro(p, os, context);
3047 else if (t.cs() == "noindent") {
3049 context.add_par_extra_stuff("\\noindent\n");
3052 else if (t.cs() == "appendix") {
3053 context.add_par_extra_stuff("\\start_of_appendix\n");
3054 // We need to start a new paragraph. Otherwise the
3055 // appendix in 'bla\appendix\chapter{' would start
3057 context.new_paragraph(os);
3058 // We need to make sure that the paragraph is
3059 // generated even if it is empty. Otherwise the
3060 // appendix in '\par\appendix\par\chapter{' would
3062 context.check_layout(os);
3063 // FIXME: This is a hack to prevent paragraph
3064 // deletion if it is empty. Handle this better!
3065 output_comment(p, os,
3066 "dummy comment inserted by tex2lyx to "
3067 "ensure that this paragraph is not empty",
3069 // Both measures above may generate an additional
3070 // empty paragraph, but that does not hurt, because
3071 // whitespace does not matter here.
3072 eat_whitespace(p, os, context, true);
3075 // Must catch empty dates before findLayout is called below
3076 else if (t.cs() == "date") {
3077 eat_whitespace(p, os, context, false);
3079 string const date = p.verbatim_item();
3082 preamble.suppressDate(true);
3085 preamble.suppressDate(false);
3086 if (context.new_layout_allowed &&
3087 (newlayout = findLayout(context.textclass,
3090 output_command_layout(os, p, outer,
3091 context, newlayout);
3092 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3093 if (!preamble.titleLayoutFound())
3094 preamble.titleLayoutFound(newlayout->intitle);
3095 set<string> const & req = newlayout->requires();
3096 set<string>::const_iterator it = req.begin();
3097 set<string>::const_iterator en = req.end();
3098 for (; it != en; ++it)
3099 preamble.registerAutomaticallyLoadedPackage(*it);
3101 output_ert_inset(os,
3102 "\\date{" + p.verbatim_item() + '}',
3107 // Starred section headings
3108 // Must attempt to parse "Section*" before "Section".
3109 else if ((p.next_token().asInput() == "*") &&
3110 context.new_layout_allowed &&
3111 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
3114 output_command_layout(os, p, outer, context, newlayout);
3116 if (!preamble.titleLayoutFound())
3117 preamble.titleLayoutFound(newlayout->intitle);
3118 set<string> const & req = newlayout->requires();
3119 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3120 preamble.registerAutomaticallyLoadedPackage(*it);
3123 // Section headings and the like
3124 else if (context.new_layout_allowed &&
3125 (newlayout = findLayout(context.textclass, t.cs(), true))) {
3127 output_command_layout(os, p, outer, context, newlayout);
3129 if (!preamble.titleLayoutFound())
3130 preamble.titleLayoutFound(newlayout->intitle);
3131 set<string> const & req = newlayout->requires();
3132 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
3133 preamble.registerAutomaticallyLoadedPackage(*it);
3136 else if (t.cs() == "subfloat") {
3137 // the syntax is \subfloat[list entry][sub caption]{content}
3138 // if it is a table of figure depends on the surrounding float
3139 // FIXME: second optional argument is not parsed
3141 // do nothing if there is no outer float
3142 if (!float_type.empty()) {
3143 context.check_layout(os);
3145 begin_inset(os, "Float " + float_type + "\n");
3147 << "\nsideways false"
3148 << "\nstatus collapsed\n\n";
3151 bool has_caption = false;
3152 if (p.next_token().cat() != catEscape &&
3153 p.next_token().character() == '[') {
3154 p.get_token(); // eat '['
3155 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
3159 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3160 // the caption comes always as the last
3162 // we must make sure that the caption gets a \begin_layout
3163 os << "\n\\begin_layout Plain Layout";
3165 begin_inset(os, "Caption Standard\n");
3166 Context newcontext(true, context.textclass,
3167 0, 0, context.font);
3168 newcontext.check_layout(os);
3169 os << caption << "\n";
3170 newcontext.check_end_layout(os);
3171 // We don't need really a new paragraph, but
3172 // we must make sure that the next item gets a \begin_layout.
3173 //newcontext.new_paragraph(os);
3177 // We don't need really a new paragraph, but
3178 // we must make sure that the next item gets a \begin_layout.
3180 context.new_paragraph(os);
3183 context.check_end_layout(os);
3184 // close the layout we opened
3186 os << "\n\\end_layout\n";
3188 // if the float type is not supported or there is no surrounding float
3191 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
3192 output_ert_inset(os, t.asInput() + '[' + opt_arg +
3193 "]{" + p.verbatim_item() + '}', context);
3195 output_ert_inset(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
3199 else if (t.cs() == "includegraphics") {
3200 bool const clip = p.next_token().asInput() == "*";
3203 string const arg = p.getArg('[', ']');
3204 map<string, string> opts;
3205 vector<string> keys;
3206 split_map(arg, opts, keys);
3208 opts["clip"] = string();
3209 string name = normalize_filename(p.verbatim_item());
3211 string const path = getMasterFilePath(true);
3212 // We want to preserve relative / absolute filenames,
3213 // therefore path is only used for testing
3214 if (!makeAbsPath(name, path).exists()) {
3215 // The file extension is probably missing.
3216 // Now try to find it out.
3217 string const dvips_name =
3218 find_file(name, path,
3219 known_dvips_graphics_formats);
3220 string const pdftex_name =
3221 find_file(name, path,
3222 known_pdftex_graphics_formats);
3223 if (!dvips_name.empty()) {
3224 if (!pdftex_name.empty()) {
3225 cerr << "This file contains the "
3227 "\"\\includegraphics{"
3229 "However, files\n\""
3230 << dvips_name << "\" and\n\""
3231 << pdftex_name << "\"\n"
3232 "both exist, so I had to make a "
3233 "choice and took the first one.\n"
3234 "Please move the unwanted one "
3235 "someplace else and try again\n"
3236 "if my choice was wrong."
3240 } else if (!pdftex_name.empty()) {
3246 FileName const absname = makeAbsPath(name, path);
3247 if (absname.exists()) {
3248 fix_child_filename(name);
3249 copy_file(absname, name);
3251 cerr << "Warning: Could not find graphics file '"
3252 << name << "'." << endl;
3254 context.check_layout(os);
3255 begin_inset(os, "Graphics ");
3256 os << "\n\tfilename " << name << '\n';
3257 if (opts.find("width") != opts.end())
3259 << translate_len(opts["width"]) << '\n';
3260 if (opts.find("height") != opts.end())
3262 << translate_len(opts["height"]) << '\n';
3263 if (opts.find("scale") != opts.end()) {
3264 istringstream iss(opts["scale"]);
3268 os << "\tscale " << val << '\n';
3270 if (opts.find("angle") != opts.end()) {
3271 os << "\trotateAngle "
3272 << opts["angle"] << '\n';
3273 vector<string>::const_iterator a =
3274 find(keys.begin(), keys.end(), "angle");
3275 vector<string>::const_iterator s =
3276 find(keys.begin(), keys.end(), "width");
3277 if (s == keys.end())
3278 s = find(keys.begin(), keys.end(), "height");
3279 if (s == keys.end())
3280 s = find(keys.begin(), keys.end(), "scale");
3281 if (s != keys.end() && distance(s, a) > 0)
3282 os << "\tscaleBeforeRotation\n";
3284 if (opts.find("origin") != opts.end()) {
3286 string const opt = opts["origin"];
3287 if (opt.find('l') != string::npos) ss << "left";
3288 if (opt.find('r') != string::npos) ss << "right";
3289 if (opt.find('c') != string::npos) ss << "center";
3290 if (opt.find('t') != string::npos) ss << "Top";
3291 if (opt.find('b') != string::npos) ss << "Bottom";
3292 if (opt.find('B') != string::npos) ss << "Baseline";
3293 if (!ss.str().empty())
3294 os << "\trotateOrigin " << ss.str() << '\n';
3296 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
3298 if (opts.find("keepaspectratio") != opts.end())
3299 os << "\tkeepAspectRatio\n";
3300 if (opts.find("clip") != opts.end())
3302 if (opts.find("draft") != opts.end())
3304 if (opts.find("bb") != opts.end())
3305 os << "\tBoundingBox "
3306 << opts["bb"] << '\n';
3307 int numberOfbbOptions = 0;
3308 if (opts.find("bbllx") != opts.end())
3309 numberOfbbOptions++;
3310 if (opts.find("bblly") != opts.end())
3311 numberOfbbOptions++;
3312 if (opts.find("bburx") != opts.end())
3313 numberOfbbOptions++;
3314 if (opts.find("bbury") != opts.end())
3315 numberOfbbOptions++;
3316 if (numberOfbbOptions == 4)
3317 os << "\tBoundingBox "
3318 << opts["bbllx"] << " " << opts["bblly"] << " "
3319 << opts["bburx"] << " " << opts["bbury"] << '\n';
3320 else if (numberOfbbOptions > 0)
3321 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3322 numberOfbbOptions = 0;
3323 if (opts.find("natwidth") != opts.end())
3324 numberOfbbOptions++;
3325 if (opts.find("natheight") != opts.end())
3326 numberOfbbOptions++;
3327 if (numberOfbbOptions == 2)
3328 os << "\tBoundingBox 0bp 0bp "
3329 << opts["natwidth"] << " " << opts["natheight"] << '\n';
3330 else if (numberOfbbOptions > 0)
3331 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
3332 ostringstream special;
3333 if (opts.find("hiresbb") != opts.end())
3334 special << "hiresbb,";
3335 if (opts.find("trim") != opts.end())
3337 if (opts.find("viewport") != opts.end())
3338 special << "viewport=" << opts["viewport"] << ',';
3339 if (opts.find("totalheight") != opts.end())
3340 special << "totalheight=" << opts["totalheight"] << ',';
3341 if (opts.find("type") != opts.end())
3342 special << "type=" << opts["type"] << ',';
3343 if (opts.find("ext") != opts.end())
3344 special << "ext=" << opts["ext"] << ',';
3345 if (opts.find("read") != opts.end())
3346 special << "read=" << opts["read"] << ',';
3347 if (opts.find("command") != opts.end())
3348 special << "command=" << opts["command"] << ',';
3349 string s_special = special.str();
3350 if (!s_special.empty()) {
3351 // We had special arguments. Remove the trailing ','.
3352 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
3354 // TODO: Handle the unknown settings better.
3355 // Warn about invalid options.
3356 // Check whether some option was given twice.
3358 preamble.registerAutomaticallyLoadedPackage("graphicx");
3361 else if (t.cs() == "footnote" ||
3362 (t.cs() == "thanks" && context.layout->intitle)) {
3364 context.check_layout(os);
3365 begin_inset(os, "Foot\n");
3366 os << "status collapsed\n\n";
3367 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3371 else if (t.cs() == "marginpar") {
3373 context.check_layout(os);
3374 begin_inset(os, "Marginal\n");
3375 os << "status collapsed\n\n";
3376 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3380 else if (t.cs() == "lstinline" || t.cs() == "mintinline") {
3381 bool const use_minted = t.cs() == "mintinline";
3383 parse_listings(p, os, context, true, use_minted);
3386 else if (t.cs() == "ensuremath") {
3388 context.check_layout(os);
3389 string const s = p.verbatim_item();
3390 //FIXME: this never triggers in UTF8
3391 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
3394 output_ert_inset(os, "\\ensuremath{" + s + "}",
3398 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
3399 if (preamble.titleLayoutFound()) {
3401 skip_spaces_braces(p);
3403 output_ert_inset(os, t.asInput(), context);
3406 else if (t.cs() == "tableofcontents"
3407 || t.cs() == "lstlistoflistings"
3408 || t.cs() == "listoflistings") {
3409 string name = t.cs();
3410 if (preamble.minted() && name == "listoflistings")
3411 name.insert(0, "lst");
3412 context.check_layout(os);
3413 begin_command_inset(os, "toc", name);
3415 skip_spaces_braces(p);
3416 if (name == "lstlistoflistings") {
3417 if (preamble.minted())
3418 preamble.registerAutomaticallyLoadedPackage("minted");
3420 preamble.registerAutomaticallyLoadedPackage("listings");
3424 else if (t.cs() == "listoffigures" || t.cs() == "listoftables") {
3425 context.check_layout(os);
3426 if (t.cs() == "listoffigures")
3427 begin_inset(os, "FloatList figure\n");
3429 begin_inset(os, "FloatList table\n");
3431 skip_spaces_braces(p);
3434 else if (t.cs() == "listof") {
3435 p.skip_spaces(true);
3436 string const name = p.get_token().cs();
3437 if (context.textclass.floats().typeExist(name)) {
3438 context.check_layout(os);
3439 begin_inset(os, "FloatList ");
3442 p.get_token(); // swallow second arg
3444 output_ert_inset(os, "\\listof{" + name + "}", context);
3447 else if ((where = is_known(t.cs(), known_text_font_families)))
3448 parse_text_attributes(p, os, FLAG_ITEM, outer,
3449 context, "\\family", context.font.family,
3450 known_coded_font_families[where - known_text_font_families]);
3452 else if ((where = is_known(t.cs(), known_text_font_series)))
3453 parse_text_attributes(p, os, FLAG_ITEM, outer,
3454 context, "\\series", context.font.series,
3455 known_coded_font_series[where - known_text_font_series]);
3457 else if ((where = is_known(t.cs(), known_text_font_shapes)))
3458 parse_text_attributes(p, os, FLAG_ITEM, outer,
3459 context, "\\shape", context.font.shape,
3460 known_coded_font_shapes[where - known_text_font_shapes]);
3462 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
3463 context.check_layout(os);
3464 TeXFont oldFont = context.font;
3465 context.font.init();
3466 context.font.size = oldFont.size;
3467 os << "\n\\family " << context.font.family << "\n";
3468 os << "\n\\series " << context.font.series << "\n";
3469 os << "\n\\shape " << context.font.shape << "\n";
3470 if (t.cs() == "textnormal") {
3471 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3472 output_font_change(os, context.font, oldFont);
3473 context.font = oldFont;
3475 eat_whitespace(p, os, context, false);
3478 else if (t.cs() == "textcolor") {
3479 // scheme is \textcolor{color name}{text}
3480 string const color = p.verbatim_item();
3481 // we support the predefined colors of the color and the xcolor package
3482 if (color == "black" || color == "blue" || color == "cyan"
3483 || color == "green" || color == "magenta" || color == "red"
3484 || color == "white" || color == "yellow") {
3485 context.check_layout(os);
3486 os << "\n\\color " << color << "\n";
3487 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3488 context.check_layout(os);
3489 os << "\n\\color inherit\n";
3490 preamble.registerAutomaticallyLoadedPackage("color");
3491 } else if (color == "brown" || color == "darkgray" || color == "gray"
3492 || color == "lightgray" || color == "lime" || color == "olive"
3493 || color == "orange" || color == "pink" || color == "purple"
3494 || color == "teal" || color == "violet") {
3495 context.check_layout(os);
3496 os << "\n\\color " << color << "\n";
3497 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3498 context.check_layout(os);
3499 os << "\n\\color inherit\n";
3500 preamble.registerAutomaticallyLoadedPackage("xcolor");
3502 // for custom defined colors
3503 output_ert_inset(os, t.asInput() + "{" + color + "}", context);
3506 else if (t.cs() == "underbar" || t.cs() == "uline") {
3507 // \underbar is not 100% correct (LyX outputs \uline
3508 // of ulem.sty). The difference is that \ulem allows
3509 // line breaks, and \underbar does not.
3510 // Do NOT handle \underline.
3511 // \underbar cuts through y, g, q, p etc.,
3512 // \underline does not.
3513 context.check_layout(os);
3514 os << "\n\\bar under\n";
3515 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3516 context.check_layout(os);
3517 os << "\n\\bar default\n";
3518 preamble.registerAutomaticallyLoadedPackage("ulem");
3521 else if (t.cs() == "sout") {
3522 context.check_layout(os);
3523 os << "\n\\strikeout on\n";
3524 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3525 context.check_layout(os);
3526 os << "\n\\strikeout default\n";
3527 preamble.registerAutomaticallyLoadedPackage("ulem");
3530 else if (t.cs() == "uuline" || t.cs() == "uwave"
3531 || t.cs() == "emph" || t.cs() == "noun"
3532 || t.cs() == "xout") {
3533 context.check_layout(os);
3534 os << "\n\\" << t.cs() << " on\n";
3535 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3536 context.check_layout(os);
3537 os << "\n\\" << t.cs() << " default\n";
3538 if (t.cs() == "uuline" || t.cs() == "uwave" || t.cs() == "xout")
3539 preamble.registerAutomaticallyLoadedPackage("ulem");
3542 else if (t.cs() == "lyxadded" || t.cs() == "lyxdeleted") {
3543 context.check_layout(os);
3544 string name = p.getArg('{', '}');
3545 string localtime = p.getArg('{', '}');
3546 preamble.registerAuthor(name);
3547 Author const & author = preamble.getAuthor(name);
3548 // from_asctime_utc() will fail if LyX decides to output the
3549 // time in the text language.
3550 time_t ptime = from_asctime_utc(localtime);
3551 if (ptime == static_cast<time_t>(-1)) {
3552 cerr << "Warning: Could not parse time `" << localtime
3553 << "´ for change tracking, using current time instead.\n";
3554 ptime = current_time();
3556 if (t.cs() == "lyxadded")
3557 os << "\n\\change_inserted ";
3559 os << "\n\\change_deleted ";
3560 os << author.bufferId() << ' ' << ptime << '\n';
3561 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
3562 bool dvipost = LaTeXPackages::isAvailable("dvipost");
3563 bool xcolorulem = LaTeXPackages::isAvailable("ulem") &&
3564 LaTeXPackages::isAvailable("xcolor");
3565 // No need to test for luatex, since luatex comes in
3566 // two flavours (dvi and pdf), like latex, and those
3567 // are detected by pdflatex.
3568 if (pdflatex || xetex) {
3570 preamble.registerAutomaticallyLoadedPackage("ulem");
3571 preamble.registerAutomaticallyLoadedPackage("xcolor");
3572 preamble.registerAutomaticallyLoadedPackage("pdfcolmk");
3576 preamble.registerAutomaticallyLoadedPackage("dvipost");
3577 } else if (xcolorulem) {
3578 preamble.registerAutomaticallyLoadedPackage("ulem");
3579 preamble.registerAutomaticallyLoadedPackage("xcolor");
3584 else if (t.cs() == "textipa") {
3585 context.check_layout(os);
3586 begin_inset(os, "IPA\n");
3587 bool merging_hyphens_allowed = context.merging_hyphens_allowed;
3588 context.merging_hyphens_allowed = false;
3589 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3590 context.merging_hyphens_allowed = merging_hyphens_allowed;
3592 preamble.registerAutomaticallyLoadedPackage("tipa");
3593 preamble.registerAutomaticallyLoadedPackage("tipx");
3596 else if (t.cs() == "texttoptiebar" || t.cs() == "textbottomtiebar") {
3597 context.check_layout(os);
3598 begin_inset(os, "IPADeco " + t.cs().substr(4) + "\n");
3599 os << "status open\n";
3600 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
3605 else if (t.cs() == "textvertline") {
3606 // FIXME: This is not correct, \textvertline is higher than |
3612 else if (t.cs() == "tone" ) {
3613 context.check_layout(os);
3614 // register the tone package
3615 preamble.registerAutomaticallyLoadedPackage("tone");
3616 string content = trimSpaceAndEol(p.verbatim_item());
3617 string command = t.asInput() + "{" + content + "}";
3618 // some tones can be detected by unicodesymbols, some need special code
3619 if (is_known(content, known_tones)) {
3620 os << "\\IPAChar " << command << "\n";
3623 // try to see whether the string is in unicodesymbols
3627 docstring s = encodings.fromLaTeXCommand(from_utf8(command),
3628 Encodings::TEXT_CMD | Encodings::MATH_CMD,
3629 termination, rem, &req);
3633 output_ert_inset(os, to_utf8(rem), context);
3634 for (set<string>::const_iterator it = req.begin();
3635 it != req.end(); ++it)
3636 preamble.registerAutomaticallyLoadedPackage(*it);
3638 // we did not find a non-ert version
3639 output_ert_inset(os, command, context);
3642 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
3643 t.cs() == "vphantom") {
3644 context.check_layout(os);
3645 if (t.cs() == "phantom")
3646 begin_inset(os, "Phantom Phantom\n");
3647 if (t.cs() == "hphantom")
3648 begin_inset(os, "Phantom HPhantom\n");
3649 if (t.cs() == "vphantom")
3650 begin_inset(os, "Phantom VPhantom\n");
3651 os << "status open\n";
3652 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
3657 else if (t.cs() == "href") {
3658 context.check_layout(os);
3659 string target = convert_command_inset_arg(p.verbatim_item());
3660 string name = convert_command_inset_arg(p.verbatim_item());
3662 size_t i = target.find(':');
3663 if (i != string::npos) {
3664 type = target.substr(0, i + 1);
3665 if (type == "mailto:" || type == "file:")
3666 target = target.substr(i + 1);
3667 // handle the case that name is equal to target, except of "http(s)://"
3668 else if (target.substr(i + 3) == name && (type == "http:" || type == "https:"))
3671 begin_command_inset(os, "href", "href");
3673 os << "name \"" << name << "\"\n";
3674 os << "target \"" << target << "\"\n";
3675 if (type == "mailto:" || type == "file:")
3676 os << "type \"" << type << "\"\n";
3677 os << "literal \"true\"\n";
3679 skip_spaces_braces(p);
3682 else if (t.cs() == "lyxline") {
3683 // swallow size argument (it is not used anyway)
3685 if (!context.atParagraphStart()) {
3686 // so our line is in the middle of a paragraph
3687 // we need to add a new line, lest this line
3688 // follow the other content on that line and
3689 // run off the side of the page
3690 // FIXME: This may create an empty paragraph,
3691 // but without that it would not be
3692 // possible to set noindent below.
3693 // Fortunately LaTeX does not care
3694 // about the empty paragraph.
3695 context.new_paragraph(os);
3697 if (preamble.indentParagraphs()) {
3698 // we need to unindent, lest the line be too long
3699 context.add_par_extra_stuff("\\noindent\n");
3701 context.check_layout(os);
3702 begin_command_inset(os, "line", "rule");
3703 os << "offset \"0.5ex\"\n"
3704 "width \"100line%\"\n"
3709 else if (t.cs() == "rule") {
3710 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
3711 string const width = p.getArg('{', '}');
3712 string const thickness = p.getArg('{', '}');
3713 context.check_layout(os);
3714 begin_command_inset(os, "line", "rule");
3715 if (!offset.empty())
3716 os << "offset \"" << translate_len(offset) << "\"\n";
3717 os << "width \"" << translate_len(width) << "\"\n"
3718 "height \"" << translate_len(thickness) << "\"\n";
3722 // handle refstyle first to catch \eqref which can also occur
3723 // without refstyle. Only recognize these commands if
3724 // refstyle.sty was found in the preamble (otherwise \eqref
3725 // and user defined ref commands could be misdetected).
3726 else if ((where = is_known(t.cs(), known_refstyle_commands)) &&
3727 preamble.refstyle()) {
3728 context.check_layout(os);
3729 begin_command_inset(os, "ref", "formatted");
3730 os << "reference \"";
3731 os << known_refstyle_prefixes[where - known_refstyle_commands]
3733 os << convert_command_inset_arg(p.verbatim_item())
3735 os << "plural \"false\"\n";
3736 os << "caps \"false\"\n";
3737 os << "noprefix \"false\"\n";
3739 preamble.registerAutomaticallyLoadedPackage("refstyle");
3742 // if refstyle is used, we must not convert \prettyref to a
3743 // formatted reference, since that would result in a refstyle command.
3744 else if ((where = is_known(t.cs(), known_ref_commands)) &&
3745 (t.cs() != "prettyref" || !preamble.refstyle())) {
3746 string const opt = p.getOpt();
3748 context.check_layout(os);
3749 begin_command_inset(os, "ref",
3750 known_coded_ref_commands[where - known_ref_commands]);
3751 os << "reference \""
3752 << convert_command_inset_arg(p.verbatim_item())
3754 os << "plural \"false\"\n";
3755 os << "caps \"false\"\n";
3756 os << "noprefix \"false\"\n";
3758 if (t.cs() == "vref" || t.cs() == "vpageref")
3759 preamble.registerAutomaticallyLoadedPackage("varioref");
3760 else if (t.cs() == "prettyref")
3761 preamble.registerAutomaticallyLoadedPackage("prettyref");
3763 // LyX does not yet support optional arguments of ref commands
3764 output_ert_inset(os, t.asInput() + '[' + opt + "]{" +
3765 p.verbatim_item() + '}', context);
3769 else if (use_natbib &&
3770 is_known(t.cs(), known_natbib_commands) &&
3771 ((t.cs() != "citefullauthor" &&
3772 t.cs() != "citeyear" &&
3773 t.cs() != "citeyearpar") ||
3774 p.next_token().asInput() != "*")) {
3775 context.check_layout(os);
3776 string command = t.cs();
3777 if (p.next_token().asInput() == "*") {
3781 if (command == "citefullauthor")
3782 // alternative name for "\\citeauthor*"
3783 command = "citeauthor*";
3785 // text before the citation
3787 // text after the citation
3789 get_cite_arguments(p, true, before, after);
3791 if (command == "cite") {
3792 // \cite without optional argument means
3793 // \citet, \cite with at least one optional
3794 // argument means \citep.
3795 if (before.empty() && after.empty())
3800 if (before.empty() && after == "[]")
3801 // avoid \citet[]{a}
3803 else if (before == "[]" && after == "[]") {
3804 // avoid \citet[][]{a}
3808 // remove the brackets around after and before
3809 if (!after.empty()) {
3811 after.erase(after.length() - 1, 1);
3812 after = convert_command_inset_arg(after);
3814 if (!before.empty()) {
3816 before.erase(before.length() - 1, 1);
3817 before = convert_command_inset_arg(before);
3819 begin_command_inset(os, "citation", command);
3820 os << "after " << '"' << after << '"' << "\n";
3821 os << "before " << '"' << before << '"' << "\n";
3823 << convert_command_inset_arg(p.verbatim_item())
3825 << "literal \"true\"\n";
3827 // Need to set the cite engine if natbib is loaded by
3828 // the document class directly
3829 if (preamble.citeEngine() == "basic")
3830 preamble.citeEngine("natbib");
3833 else if (use_biblatex
3834 && is_known(t.cs(), known_biblatex_commands)
3835 && ((t.cs() == "cite"
3836 || t.cs() == "citeauthor"
3837 || t.cs() == "Citeauthor"
3838 || t.cs() == "parencite"
3839 || t.cs() == "citetitle")
3840 || p.next_token().asInput() != "*")) {
3841 context.check_layout(os);
3842 string command = t.cs();
3843 if (p.next_token().asInput() == "*") {
3848 // text before the citation
3850 // text after the citation
3852 get_cite_arguments(p, true, before, after);
3854 // These use natbib cmd names in LyX
3855 // for inter-citeengine compativility
3856 if (command == "citeyear")
3857 command = "citebyear";
3858 else if (command == "cite*")
3859 command = "citeyear";
3860 else if (command == "textcite")
3862 else if (command == "Textcite")
3864 else if (command == "parencite")
3866 else if (command == "Parencite")
3868 else if (command == "parencite*")
3869 command = "citeyearpar";
3870 else if (command == "smartcite")
3871 command = "footcite";
3872 else if (command == "Smartcite")
3873 command = "Footcite";
3875 if (before.empty() && after == "[]")
3878 else if (before == "[]" && after == "[]") {
3879 // avoid \cite[][]{a}
3883 // remove the brackets around after and before
3884 if (!after.empty()) {
3886 after.erase(after.length() - 1, 1);
3887 after = convert_command_inset_arg(after);
3889 if (!before.empty()) {
3891 before.erase(before.length() - 1, 1);
3892 before = convert_command_inset_arg(before);
3894 begin_command_inset(os, "citation", command);
3895 os << "after " << '"' << after << '"' << "\n";
3896 os << "before " << '"' << before << '"' << "\n";
3898 << convert_command_inset_arg(p.verbatim_item())
3900 << "literal \"true\"\n";
3902 // Need to set the cite engine if biblatex is loaded by
3903 // the document class directly
3904 if (preamble.citeEngine() == "basic")
3905 preamble.citeEngine("biblatex");
3908 else if (use_biblatex_natbib
3909 && (is_known(t.cs(), known_biblatex_commands)
3910 || is_known(t.cs(), known_natbib_commands))
3911 && ((t.cs() == "cite" || t.cs() == "citet" || t.cs() == "Citet"
3912 || t.cs() == "citep" || t.cs() == "Citep" || t.cs() == "citealt"
3913 || t.cs() == "Citealt" || t.cs() == "citealp" || t.cs() == "Citealp"
3914 || t.cs() == "citeauthor" || t.cs() == "Citeauthor"
3915 || t.cs() == "parencite" || t.cs() == "citetitle")
3916 || p.next_token().asInput() != "*")) {
3917 context.check_layout(os);
3918 string command = t.cs();
3919 if (p.next_token().asInput() == "*") {
3924 // text before the citation
3926 // text after the citation
3928 get_cite_arguments(p, true, before, after);
3930 // These use natbib cmd names in LyX
3931 // for inter-citeengine compativility
3932 if (command == "citeyear")
3933 command = "citebyear";
3934 else if (command == "cite*")
3935 command = "citeyear";
3936 else if (command == "textcite")
3938 else if (command == "Textcite")
3940 else if (command == "parencite")
3942 else if (command == "Parencite")
3944 else if (command == "parencite*")
3945 command = "citeyearpar";
3946 else if (command == "smartcite")
3947 command = "footcite";
3948 else if (command == "Smartcite")
3949 command = "Footcite";
3951 if (before.empty() && after == "[]")
3954 else if (before == "[]" && after == "[]") {
3955 // avoid \cite[][]{a}
3959 // remove the brackets around after and before
3960 if (!after.empty()) {
3962 after.erase(after.length() - 1, 1);
3963 after = convert_command_inset_arg(after);
3965 if (!before.empty()) {
3967 before.erase(before.length() - 1, 1);
3968 before = convert_command_inset_arg(before);
3970 begin_command_inset(os, "citation", command);
3971 os << "after " << '"' << after << '"' << "\n";
3972 os << "before " << '"' << before << '"' << "\n";
3974 << convert_command_inset_arg(p.verbatim_item())
3976 << "literal \"true\"\n";
3978 // Need to set the cite engine if biblatex is loaded by
3979 // the document class directly
3980 if (preamble.citeEngine() == "basic")
3981 preamble.citeEngine("biblatex-natbib");
3984 else if (use_jurabib &&
3985 is_known(t.cs(), known_jurabib_commands) &&
3986 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
3987 context.check_layout(os);
3988 string command = t.cs();
3989 if (p.next_token().asInput() == "*") {
3993 char argumentOrder = '\0';
3994 vector<string> const options =
3995 preamble.getPackageOptions("jurabib");
3996 if (find(options.begin(), options.end(),
3997 "natbiborder") != options.end())
3998 argumentOrder = 'n';
3999 else if (find(options.begin(), options.end(),
4000 "jurabiborder") != options.end())
4001 argumentOrder = 'j';
4003 // text before the citation
4005 // text after the citation
4007 get_cite_arguments(p, argumentOrder != 'j', before, after);
4009 string const citation = p.verbatim_item();
4010 if (!before.empty() && argumentOrder == '\0') {
4011 cerr << "Warning: Assuming argument order "
4012 "of jurabib version 0.6 for\n'"
4013 << command << before << after << '{'
4014 << citation << "}'.\n"
4015 "Add 'jurabiborder' to the jurabib "
4016 "package options if you used an\n"
4017 "earlier jurabib version." << endl;
4019 if (!after.empty()) {
4021 after.erase(after.length() - 1, 1);
4023 if (!before.empty()) {
4025 before.erase(before.length() - 1, 1);
4027 begin_command_inset(os, "citation", command);
4028 os << "after " << '"' << after << "\"\n"
4029 << "before " << '"' << before << "\"\n"
4030 << "key " << '"' << citation << "\"\n"
4031 << "literal \"true\"\n";
4033 // Need to set the cite engine if jurabib is loaded by
4034 // the document class directly
4035 if (preamble.citeEngine() == "basic")
4036 preamble.citeEngine("jurabib");
4039 else if (t.cs() == "cite"
4040 || t.cs() == "nocite") {
4041 context.check_layout(os);
4042 string after = convert_command_inset_arg(p.getArg('[', ']'));
4043 string key = convert_command_inset_arg(p.verbatim_item());
4044 // store the case that it is "\nocite{*}" to use it later for
4047 begin_command_inset(os, "citation", t.cs());
4048 os << "after " << '"' << after << "\"\n"
4049 << "key " << '"' << key << "\"\n"
4050 << "literal \"true\"\n";
4052 } else if (t.cs() == "nocite")
4056 else if (t.cs() == "index" ||
4057 (t.cs() == "sindex" && preamble.use_indices() == "true")) {
4058 context.check_layout(os);
4059 string const arg = (t.cs() == "sindex" && p.hasOpt()) ?
4060 p.getArg('[', ']') : "";
4061 string const kind = arg.empty() ? "idx" : arg;
4062 begin_inset(os, "Index ");
4063 os << kind << "\nstatus collapsed\n";
4064 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
4067 preamble.registerAutomaticallyLoadedPackage("splitidx");
4070 else if (t.cs() == "nomenclature") {
4071 context.check_layout(os);
4072 begin_command_inset(os, "nomenclature", "nomenclature");
4073 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
4074 if (!prefix.empty())
4075 os << "prefix " << '"' << prefix << '"' << "\n";
4076 os << "symbol " << '"'
4077 << convert_command_inset_arg(p.verbatim_item());
4078 os << "\"\ndescription \""
4079 << convert_command_inset_arg(p.verbatim_item())
4081 << "literal \"true\"\n";
4083 preamble.registerAutomaticallyLoadedPackage("nomencl");
4086 else if (t.cs() == "label") {
4087 context.check_layout(os);
4088 begin_command_inset(os, "label", "label");
4090 << convert_command_inset_arg(p.verbatim_item())
4095 else if (t.cs() == "lyxmintcaption") {
4096 string const pos = p.getArg('[', ']');
4098 string const caption =
4099 parse_text_snippet(p, FLAG_ITEM, false,
4101 minted_nonfloat_caption = "[t]" + caption;
4103 // We already got the caption at the bottom,
4104 // so simply skip it.
4105 parse_text_snippet(p, FLAG_ITEM, false, context);
4109 else if (t.cs() == "printindex" || t.cs() == "printsubindex") {
4110 context.check_layout(os);
4111 string commandname = t.cs();
4113 if (p.next_token().asInput() == "*") {
4118 begin_command_inset(os, "index_print", commandname);
4119 string const indexname = p.getArg('[', ']');
4121 if (indexname.empty())
4122 os << "type \"idx\"\n";
4124 os << "type \"" << indexname << "\"\n";
4125 os << "literal \"true\"\n";
4128 skip_spaces_braces(p);
4129 preamble.registerAutomaticallyLoadedPackage("makeidx");
4130 if (preamble.use_indices() == "true")
4131 preamble.registerAutomaticallyLoadedPackage("splitidx");
4134 else if (t.cs() == "printnomenclature") {
4136 string width_type = "";
4137 context.check_layout(os);
4138 begin_command_inset(os, "nomencl_print", "printnomenclature");
4139 // case of a custom width
4141 width = p.getArg('[', ']');
4142 width = translate_len(width);
4143 width_type = "custom";
4145 // case of no custom width
4146 // the case of no custom width but the width set
4147 // via \settowidth{\nomlabelwidth}{***} cannot be supported
4148 // because the user could have set anything, not only the width
4149 // of the longest label (which would be width_type = "auto")
4150 string label = convert_command_inset_arg(p.getArg('{', '}'));
4151 if (label.empty() && width_type.empty())
4152 width_type = "none";
4153 os << "set_width \"" << width_type << "\"\n";
4154 if (width_type == "custom")
4155 os << "width \"" << width << '\"';
4157 skip_spaces_braces(p);
4158 preamble.registerAutomaticallyLoadedPackage("nomencl");
4161 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
4162 context.check_layout(os);
4163 begin_inset(os, "script ");
4164 os << t.cs().substr(4) << '\n';
4165 newinsetlayout = findInsetLayout(context.textclass, t.cs(), true);
4166 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
4168 if (t.cs() == "textsubscript")
4169 preamble.registerAutomaticallyLoadedPackage("subscript");
4172 else if ((where = is_known(t.cs(), known_quotes))) {
4173 context.check_layout(os);
4174 begin_inset(os, "Quotes ");
4175 os << known_coded_quotes[where - known_quotes];
4177 // LyX adds {} after the quote, so we have to eat
4178 // spaces here if there are any before a possible
4180 eat_whitespace(p, os, context, false);
4184 else if ((where = is_known(t.cs(), known_sizes)) &&
4185 context.new_layout_allowed) {
4186 context.check_layout(os);
4187 TeXFont const oldFont = context.font;
4188 context.font.size = known_coded_sizes[where - known_sizes];
4189 output_font_change(os, oldFont, context.font);
4190 eat_whitespace(p, os, context, false);
4193 else if ((where = is_known(t.cs(), known_font_families)) &&
4194 context.new_layout_allowed) {
4195 context.check_layout(os);
4196 TeXFont const oldFont = context.font;
4197 context.font.family =
4198 known_coded_font_families[where - known_font_families];
4199 output_font_change(os, oldFont, context.font);
4200 eat_whitespace(p, os, context, false);
4203 else if ((where = is_known(t.cs(), known_font_series)) &&
4204 context.new_layout_allowed) {
4205 context.check_layout(os);
4206 TeXFont const oldFont = context.font;
4207 context.font.series =
4208 known_coded_font_series[where - known_font_series];
4209 output_font_change(os, oldFont, context.font);
4210 eat_whitespace(p, os, context, false);
4213 else if ((where = is_known(t.cs(), known_font_shapes)) &&
4214 context.new_layout_allowed) {
4215 context.check_layout(os);
4216 TeXFont const oldFont = context.font;
4217 context.font.shape =
4218 known_coded_font_shapes[where - known_font_shapes];
4219 output_font_change(os, oldFont, context.font);
4220 eat_whitespace(p, os, context, false);
4222 else if ((where = is_known(t.cs(), known_old_font_families)) &&
4223 context.new_layout_allowed) {
4224 context.check_layout(os);
4225 TeXFont const oldFont = context.font;
4226 context.font.init();
4227 context.font.size = oldFont.size;
4228 context.font.family =
4229 known_coded_font_families[where - known_old_font_families];
4230 output_font_change(os, oldFont, context.font);
4231 eat_whitespace(p, os, context, false);
4234 else if ((where = is_known(t.cs(), known_old_font_series)) &&
4235 context.new_layout_allowed) {
4236 context.check_layout(os);
4237 TeXFont const oldFont = context.font;
4238 context.font.init();
4239 context.font.size = oldFont.size;
4240 context.font.series =
4241 known_coded_font_series[where - known_old_font_series];
4242 output_font_change(os, oldFont, context.font);
4243 eat_whitespace(p, os, context, false);
4246 else if ((where = is_known(t.cs(), known_old_font_shapes)) &&
4247 context.new_layout_allowed) {
4248 context.check_layout(os);
4249 TeXFont const oldFont = context.font;
4250 context.font.init();
4251 context.font.size = oldFont.size;
4252 context.font.shape =
4253 known_coded_font_shapes[where - known_old_font_shapes];
4254 output_font_change(os, oldFont, context.font);
4255 eat_whitespace(p, os, context, false);
4258 else if (t.cs() == "selectlanguage") {
4259 context.check_layout(os);
4260 // save the language for the case that a
4261 // \foreignlanguage is used
4262 context.font.language = babel2lyx(p.verbatim_item());
4263 os << "\n\\lang " << context.font.language << "\n";
4266 else if (t.cs() == "foreignlanguage") {
4267 string const lang = babel2lyx(p.verbatim_item());
4268 parse_text_attributes(p, os, FLAG_ITEM, outer,
4270 context.font.language, lang);
4273 else if (prefixIs(t.cs(), "text") && preamble.usePolyglossia()
4274 && is_known(t.cs().substr(4), preamble.polyglossia_languages)) {
4275 // scheme is \textLANGUAGE{text} where LANGUAGE is in polyglossia_languages[]
4277 // We have to output the whole command if it has an option
4278 // because LyX doesn't support this yet, see bug #8214,
4279 // only if there is a single option specifying a variant, we can handle it.
4281 string langopts = p.getOpt();
4282 // check if the option contains a variant, if yes, extract it
4283 string::size_type pos_var = langopts.find("variant");
4284 string::size_type i = langopts.find(',');
4285 string::size_type k = langopts.find('=', pos_var);
4286 if (pos_var != string::npos && i == string::npos) {
4288 variant = langopts.substr(k + 1, langopts.length() - k - 2);
4289 lang = preamble.polyglossia2lyx(variant);
4290 parse_text_attributes(p, os, FLAG_ITEM, outer,
4292 context.font.language, lang);
4294 output_ert_inset(os, t.asInput() + langopts, context);
4296 lang = preamble.polyglossia2lyx(t.cs().substr(4, string::npos));
4297 parse_text_attributes(p, os, FLAG_ITEM, outer,
4299 context.font.language, lang);
4303 else if (t.cs() == "inputencoding") {
4304 // nothing to write here
4305 string const enc = subst(p.verbatim_item(), "\n", " ");
4306 p.setEncoding(enc, Encoding::inputenc);
4309 else if (is_known(t.cs(), known_special_chars) ||
4310 (t.cs() == "protect" &&
4311 p.next_token().cat() == catEscape &&
4312 is_known(p.next_token().cs(), known_special_protect_chars))) {
4313 // LyX sometimes puts a \protect in front, so we have to ignore it
4315 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
4316 known_special_chars);
4317 context.check_layout(os);
4318 os << known_coded_special_chars[where - known_special_chars];
4319 skip_spaces_braces(p);
4322 else if ((t.cs() == "nobreakdash" && p.next_token().asInput() == "-") ||
4323 (t.cs() == "protect" && p.next_token().asInput() == "\\nobreakdash" &&
4324 p.next_next_token().asInput() == "-") ||
4325 (t.cs() == "@" && p.next_token().asInput() == ".")) {
4326 // LyX sometimes puts a \protect in front, so we have to ignore it
4327 if (t.cs() == "protect")
4329 context.check_layout(os);
4330 if (t.cs() == "nobreakdash")
4331 os << "\\SpecialChar nobreakdash\n";
4333 os << "\\SpecialChar endofsentence\n";
4337 else if (t.cs() == "textquotedbl") {
4338 context.check_layout(os);
4343 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
4344 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
4345 || t.cs() == "%" || t.cs() == "-") {
4346 context.check_layout(os);
4348 os << "\\SpecialChar softhyphen\n";
4353 else if (t.cs() == "char") {
4354 context.check_layout(os);
4355 if (p.next_token().character() == '`') {
4357 if (p.next_token().cs() == "\"") {
4362 output_ert_inset(os, "\\char`", context);
4365 output_ert_inset(os, "\\char", context);
4369 else if (t.cs() == "verb") {
4370 context.check_layout(os);
4371 // set catcodes to verbatim early, just in case.
4372 p.setCatcodes(VERBATIM_CATCODES);
4373 string delim = p.get_token().asInput();
4374 Parser::Arg arg = p.verbatimStuff(delim);
4376 output_ert_inset(os, "\\verb" + delim
4377 + arg.second + delim, context);
4379 cerr << "invalid \\verb command. Skipping" << endl;
4382 // Problem: \= creates a tabstop inside the tabbing environment
4383 // and else an accent. In the latter case we really would want
4384 // \={o} instead of \= o.
4385 else if (t.cs() == "=" && (flags & FLAG_TABBING))
4386 output_ert_inset(os, t.asInput(), context);
4388 else if (t.cs() == "\\") {
4389 context.check_layout(os);
4391 output_ert_inset(os, "\\\\" + p.getOpt(), context);
4392 else if (p.next_token().asInput() == "*") {
4394 // getOpt() eats the following space if there
4395 // is no optional argument, but that is OK
4396 // here since it has no effect in the output.
4397 output_ert_inset(os, "\\\\*" + p.getOpt(), context);
4400 begin_inset(os, "Newline newline");
4405 else if (t.cs() == "newline" ||
4406 (t.cs() == "linebreak" && !p.hasOpt())) {
4407 context.check_layout(os);
4408 begin_inset(os, "Newline ");
4411 skip_spaces_braces(p);
4414 else if (t.cs() == "input" || t.cs() == "include"
4415 || t.cs() == "verbatiminput") {
4416 string name = t.cs();
4417 if (t.cs() == "verbatiminput"
4418 && p.next_token().asInput() == "*")
4419 name += p.get_token().asInput();
4420 context.check_layout(os);
4421 string filename(normalize_filename(p.getArg('{', '}')));
4422 string const path = getMasterFilePath(true);
4423 // We want to preserve relative / absolute filenames,
4424 // therefore path is only used for testing
4425 if ((t.cs() == "include" || t.cs() == "input") &&
4426 !makeAbsPath(filename, path).exists()) {
4427 // The file extension is probably missing.
4428 // Now try to find it out.
4429 string const tex_name =
4430 find_file(filename, path,
4431 known_tex_extensions);
4432 if (!tex_name.empty())
4433 filename = tex_name;
4435 bool external = false;
4437 if (makeAbsPath(filename, path).exists()) {
4438 string const abstexname =
4439 makeAbsPath(filename, path).absFileName();
4440 string const absfigname =
4441 changeExtension(abstexname, ".fig");
4442 fix_child_filename(filename);
4443 string const lyxname = changeExtension(filename,
4444 roundtripMode() ? ".lyx.lyx" : ".lyx");
4445 string const abslyxname = makeAbsPath(
4446 lyxname, getParentFilePath(false)).absFileName();
4448 if (!skipChildren())
4449 external = FileName(absfigname).exists();
4450 if (t.cs() == "input" && !skipChildren()) {
4451 string const ext = getExtension(abstexname);
4453 // Combined PS/LaTeX:
4454 // x.eps, x.pstex_t (old xfig)
4455 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
4456 FileName const absepsname(
4457 changeExtension(abstexname, ".eps"));
4458 FileName const abspstexname(
4459 changeExtension(abstexname, ".pstex"));
4460 bool const xfigeps =
4461 (absepsname.exists() ||
4462 abspstexname.exists()) &&
4465 // Combined PDF/LaTeX:
4466 // x.pdf, x.pdftex_t (old xfig)
4467 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
4468 FileName const abspdfname(
4469 changeExtension(abstexname, ".pdf"));
4470 bool const xfigpdf =
4471 abspdfname.exists() &&
4472 (ext == "pdftex_t" || ext == "pdf_t");
4476 // Combined PS/PDF/LaTeX:
4477 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
4478 string const absbase2(
4479 removeExtension(abstexname) + "_pspdftex");
4480 FileName const abseps2name(
4481 addExtension(absbase2, ".eps"));
4482 FileName const abspdf2name(
4483 addExtension(absbase2, ".pdf"));
4484 bool const xfigboth =
4485 abspdf2name.exists() &&
4486 abseps2name.exists() && ext == "pspdftex";
4488 xfig = xfigpdf || xfigeps || xfigboth;
4489 external = external && xfig;
4492 outname = changeExtension(filename, ".fig");
4493 FileName abssrc(changeExtension(abstexname, ".fig"));
4494 copy_file(abssrc, outname);
4496 // Don't try to convert, the result
4497 // would be full of ERT.
4499 FileName abssrc(abstexname);
4500 copy_file(abssrc, outname);
4501 } else if (t.cs() != "verbatiminput" &&
4503 tex2lyx(abstexname, FileName(abslyxname),
4506 // no need to call copy_file
4507 // tex2lyx creates the file
4510 FileName abssrc(abstexname);
4511 copy_file(abssrc, outname);
4514 cerr << "Warning: Could not find included file '"
4515 << filename << "'." << endl;
4519 begin_inset(os, "External\n");
4520 os << "\ttemplate XFig\n"
4521 << "\tfilename " << outname << '\n';
4522 registerExternalTemplatePackages("XFig");
4524 begin_command_inset(os, "include", name);
4525 outname = subst(outname, "\"", "\\\"");
4526 os << "preview false\n"
4527 "filename \"" << outname << "\"\n";
4528 if (t.cs() == "verbatiminput")
4529 preamble.registerAutomaticallyLoadedPackage("verbatim");
4534 else if (t.cs() == "bibliographystyle") {
4535 // store new bibliographystyle
4536 bibliographystyle = p.verbatim_item();
4537 // If any other command than \bibliography, \addcontentsline
4538 // and \nocite{*} follows, we need to output the style
4539 // (because it might be used by that command).
4540 // Otherwise, it will automatically be output by LyX.
4543 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
4544 if (t2.cat() == catBegin)
4546 if (t2.cat() != catEscape)
4548 if (t2.cs() == "nocite") {
4549 if (p.getArg('{', '}') == "*")
4551 } else if (t2.cs() == "bibliography")
4553 else if (t2.cs() == "phantomsection") {
4557 else if (t2.cs() == "addcontentsline") {
4558 // get the 3 arguments of \addcontentsline
4561 contentslineContent = p.getArg('{', '}');
4562 // if the last argument is not \refname we must output
4563 if (contentslineContent == "\\refname")
4570 output_ert_inset(os,
4571 "\\bibliographystyle{" + bibliographystyle + '}',
4576 else if (t.cs() == "phantomsection") {
4577 // we only support this if it occurs between
4578 // \bibliographystyle and \bibliography
4579 if (bibliographystyle.empty())
4580 output_ert_inset(os, "\\phantomsection", context);
4583 else if (t.cs() == "addcontentsline") {
4584 context.check_layout(os);
4585 // get the 3 arguments of \addcontentsline
4586 string const one = p.getArg('{', '}');
4587 string const two = p.getArg('{', '}');
4588 string const three = p.getArg('{', '}');
4589 // only if it is a \refname, we support if for the bibtex inset
4590 if (contentslineContent != "\\refname") {
4591 output_ert_inset(os,
4592 "\\addcontentsline{" + one + "}{" + two + "}{"+ three + '}',
4597 else if (t.cs() == "bibliography") {
4598 context.check_layout(os);
4600 begin_command_inset(os, "bibtex", "bibtex");
4601 if (!btprint.empty()) {
4602 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4603 // clear the string because the next BibTeX inset can be without the
4604 // \nocite{*} option
4607 os << "bibfiles " << '"' << normalize_filename(p.verbatim_item()) << '"' << "\n";
4608 // Do we have addcontentsline?
4609 if (contentslineContent == "\\refname") {
4610 BibOpts = "bibtotoc";
4611 // clear string because next BibTeX inset can be without addcontentsline
4612 contentslineContent.clear();
4614 // Do we have a bibliographystyle set?
4615 if (!bibliographystyle.empty()) {
4616 if (BibOpts.empty())
4617 BibOpts = normalize_filename(bibliographystyle);
4619 BibOpts = BibOpts + ',' + normalize_filename(bibliographystyle);
4620 // clear it because each bibtex entry has its style
4621 // and we need an empty string to handle \phantomsection
4622 bibliographystyle.clear();
4624 os << "options " << '"' << BibOpts << '"' << "\n";
4628 else if (t.cs() == "printbibliography") {
4629 context.check_layout(os);
4631 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4632 vector<string> opts = getVectorFromString(bbloptions);
4633 vector<string>::iterator it =
4634 find(opts.begin(), opts.end(), "heading=bibintoc");
4635 if (it != opts.end()) {
4637 BibOpts = "bibtotoc";
4639 bbloptions = getStringFromVector(opts);
4640 begin_command_inset(os, "bibtex", "bibtex");
4641 if (!btprint.empty()) {
4642 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
4643 // clear the string because the next BibTeX inset can be without the
4644 // \nocite{*} option
4648 for (auto const & bf : preamble.biblatex_bibliographies) {
4649 if (!bibfiles.empty())
4651 bibfiles += normalize_filename(bf);
4653 if (!bibfiles.empty())
4654 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4655 // Do we have addcontentsline?
4656 if (contentslineContent == "\\refname") {
4657 BibOpts = "bibtotoc";
4658 // clear string because next BibTeX inset can be without addcontentsline
4659 contentslineContent.clear();
4661 os << "options " << '"' << BibOpts << '"' << "\n";
4662 if (!bbloptions.empty())
4663 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4665 need_commentbib = false;
4668 else if (t.cs() == "bibbysection") {
4669 context.check_layout(os);
4671 string bbloptions = p.hasOpt() ? p.getArg('[', ']') : string();
4672 vector<string> opts = getVectorFromString(bbloptions);
4673 vector<string>::iterator it =
4674 find(opts.begin(), opts.end(), "heading=bibintoc");
4675 if (it != opts.end()) {
4677 BibOpts = "bibtotoc";
4679 bbloptions = getStringFromVector(opts);
4680 begin_command_inset(os, "bibtex", "bibtex");
4681 os << "btprint " << '"' << "bibbysection" << '"' << "\n";
4683 for (auto const & bf : preamble.biblatex_bibliographies) {
4684 if (!bibfiles.empty())
4686 bibfiles += normalize_filename(bf);
4688 if (!bibfiles.empty())
4689 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
4690 os << "options " << '"' << BibOpts << '"' << "\n";
4691 if (!bbloptions.empty())
4692 os << "biblatexopts " << '"' << bbloptions << '"' << "\n";
4694 need_commentbib = false;
4697 else if (t.cs() == "parbox") {
4698 // Test whether this is an outer box of a shaded box
4700 // swallow arguments
4701 while (p.hasOpt()) {
4703 p.skip_spaces(true);
4706 p.skip_spaces(true);
4708 if (p.next_token().cat() == catBegin)
4710 p.skip_spaces(true);
4711 Token to = p.get_token();
4712 bool shaded = false;
4713 if (to.asInput() == "\\begin") {
4714 p.skip_spaces(true);
4715 if (p.getArg('{', '}') == "shaded")
4720 parse_outer_box(p, os, FLAG_ITEM, outer,
4721 context, "parbox", "shaded");
4723 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4724 "", "", t.cs(), "", "");
4727 else if (t.cs() == "fbox" || t.cs() == "mbox" ||
4728 t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
4729 t.cs() == "shadowbox" || t.cs() == "doublebox")
4730 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
4732 else if (t.cs() == "fcolorbox" || t.cs() == "colorbox") {
4733 string backgroundcolor;
4734 preamble.registerAutomaticallyLoadedPackage("xcolor");
4735 if (t.cs() == "fcolorbox") {
4736 string const framecolor = p.getArg('{', '}');
4737 backgroundcolor = p.getArg('{', '}');
4738 parse_box(p, os, 0, 0, outer, context, "", "", "", framecolor, backgroundcolor);
4740 backgroundcolor = p.getArg('{', '}');
4741 parse_box(p, os, 0, 0, outer, context, "", "", "", "", backgroundcolor);
4745 // FIXME: due to the compiler limit of "if" nestings
4746 // the code for the alignment was put here
4747 // put them in their own if if this is fixed
4748 else if (t.cs() == "fboxrule" || t.cs() == "fboxsep"
4749 || t.cs() == "shadowsize"
4750 || t.cs() == "raggedleft" || t.cs() == "centering"
4751 || t.cs() == "raggedright") {
4752 if (t.cs() == "fboxrule")
4754 if (t.cs() == "fboxsep")
4756 if (t.cs() == "shadowsize")
4758 if (t.cs() != "raggedleft" && t.cs() != "centering"
4759 && t.cs() != "raggedright") {
4760 p.skip_spaces(true);
4761 while (p.good() && p.next_token().cat() != catSpace
4762 && p.next_token().cat() != catNewline
4763 && p.next_token().cat() != catEscape) {
4764 if (t.cs() == "fboxrule")
4765 fboxrule = fboxrule + p.get_token().asInput();
4766 if (t.cs() == "fboxsep")
4767 fboxsep = fboxsep + p.get_token().asInput();
4768 if (t.cs() == "shadowsize")
4769 shadow_size = shadow_size + p.get_token().asInput();
4772 output_ert_inset(os, t.asInput(), context);
4776 //\framebox() is part of the picture environment and different from \framebox{}
4777 //\framebox{} will be parsed by parse_outer_box
4778 else if (t.cs() == "framebox") {
4779 if (p.next_token().character() == '(') {
4780 //the syntax is: \framebox(x,y)[position]{content}
4781 string arg = t.asInput();
4782 arg += p.getFullParentheseArg();
4783 arg += p.getFullOpt();
4784 eat_whitespace(p, os, context, false);
4785 output_ert_inset(os, arg + '{', context);
4786 parse_text(p, os, FLAG_ITEM, outer, context);
4787 output_ert_inset(os, "}", context);
4789 //the syntax is: \framebox[width][position]{content}
4790 string special = p.getFullOpt();
4791 special += p.getOpt();
4792 parse_outer_box(p, os, FLAG_ITEM, outer,
4793 context, t.cs(), special);
4797 //\makebox() is part of the picture environment and different from \makebox{}
4798 //\makebox{} will be parsed by parse_box
4799 else if (t.cs() == "makebox") {
4800 if (p.next_token().character() == '(') {
4801 //the syntax is: \makebox(x,y)[position]{content}
4802 string arg = t.asInput();
4803 arg += p.getFullParentheseArg();
4804 arg += p.getFullOpt();
4805 eat_whitespace(p, os, context, false);
4806 output_ert_inset(os, arg + '{', context);
4807 parse_text(p, os, FLAG_ITEM, outer, context);
4808 output_ert_inset(os, "}", context);
4810 //the syntax is: \makebox[width][position]{content}
4811 parse_box(p, os, 0, FLAG_ITEM, outer, context,
4812 "", "", t.cs(), "", "");
4815 else if (t.cs() == "smallskip" ||
4816 t.cs() == "medskip" ||
4817 t.cs() == "bigskip" ||
4818 t.cs() == "vfill") {
4819 context.check_layout(os);
4820 begin_inset(os, "VSpace ");
4823 skip_spaces_braces(p);
4826 else if ((where = is_known(t.cs(), known_spaces))) {
4827 context.check_layout(os);
4828 begin_inset(os, "space ");
4829 os << '\\' << known_coded_spaces[where - known_spaces]
4832 // LaTeX swallows whitespace after all spaces except
4833 // "\\,". We have to do that here, too, because LyX
4834 // adds "{}" which would make the spaces significant.
4836 eat_whitespace(p, os, context, false);
4837 // LyX adds "{}" after all spaces except "\\ " and
4838 // "\\,", so we have to remove "{}".
4839 // "\\,{}" is equivalent to "\\," in LaTeX, so we
4840 // remove the braces after "\\,", too.
4845 else if (t.cs() == "newpage" ||
4846 (t.cs() == "pagebreak" && !p.hasOpt()) ||
4847 t.cs() == "clearpage" ||
4848 t.cs() == "cleardoublepage") {
4849 context.check_layout(os);
4850 begin_inset(os, "Newpage ");
4853 skip_spaces_braces(p);
4856 else if (t.cs() == "DeclareRobustCommand" ||
4857 t.cs() == "DeclareRobustCommandx" ||
4858 t.cs() == "newcommand" ||
4859 t.cs() == "newcommandx" ||
4860 t.cs() == "providecommand" ||
4861 t.cs() == "providecommandx" ||
4862 t.cs() == "renewcommand" ||
4863 t.cs() == "renewcommandx") {
4864 // DeclareRobustCommand, DeclareRobustCommandx,
4865 // providecommand and providecommandx could be handled
4866 // by parse_command(), but we need to call
4867 // add_known_command() here.
4868 string name = t.asInput();
4869 if (p.next_token().asInput() == "*") {
4870 // Starred form. Eat '*'
4874 string const command = p.verbatim_item();
4875 string const opt1 = p.getFullOpt();
4876 string const opt2 = p.getFullOpt();
4877 add_known_command(command, opt1, !opt2.empty());
4878 string const ert = name + '{' + command + '}' +
4880 '{' + p.verbatim_item() + '}';
4882 if (t.cs() == "DeclareRobustCommand" ||
4883 t.cs() == "DeclareRobustCommandx" ||
4884 t.cs() == "providecommand" ||
4885 t.cs() == "providecommandx" ||
4886 name[name.length()-1] == '*')
4887 output_ert_inset(os, ert, context);
4889 context.check_layout(os);
4890 begin_inset(os, "FormulaMacro");
4896 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
4897 // let could be handled by parse_command(),
4898 // but we need to call add_known_command() here.
4899 string ert = t.asInput();
4902 if (p.next_token().cat() == catBegin) {
4903 name = p.verbatim_item();
4904 ert += '{' + name + '}';
4906 name = p.verbatim_item();
4911 if (p.next_token().cat() == catBegin) {
4912 command = p.verbatim_item();
4913 ert += '{' + command + '}';
4915 command = p.verbatim_item();
4918 // If command is known, make name known too, to parse
4919 // its arguments correctly. For this reason we also
4920 // have commands in syntax.default that are hardcoded.
4921 CommandMap::iterator it = known_commands.find(command);
4922 if (it != known_commands.end())
4923 known_commands[t.asInput()] = it->second;
4924 output_ert_inset(os, ert, context);
4927 else if (t.cs() == "hspace" || t.cs() == "vspace") {
4930 string name = t.asInput();
4931 string const length = p.verbatim_item();
4934 bool valid = splitLatexLength(length, valstring, unit);
4935 bool known_hspace = false;
4936 bool known_vspace = false;
4937 bool known_unit = false;
4940 istringstream iss(valstring);
4943 if (t.cs()[0] == 'h') {
4944 if (unit == "\\fill") {
4949 known_hspace = true;
4952 if (unit == "\\smallskipamount") {
4954 known_vspace = true;
4955 } else if (unit == "\\medskipamount") {
4957 known_vspace = true;
4958 } else if (unit == "\\bigskipamount") {
4960 known_vspace = true;
4961 } else if (unit == "\\fill") {
4963 known_vspace = true;
4967 if (!known_hspace && !known_vspace) {
4968 switch (unitFromString(unit)) {
4984 //unitFromString(unit) fails for relative units like Length::PCW
4985 // therefore handle them separately
4986 if (unit == "\\paperwidth" || unit == "\\columnwidth"
4987 || unit == "\\textwidth" || unit == "\\linewidth"
4988 || unit == "\\textheight" || unit == "\\paperheight"
4989 || unit == "\\baselineskip")
4997 // check for glue lengths
4998 bool is_gluelength = false;
4999 string gluelength = length;
5000 string::size_type i = length.find(" minus");
5001 if (i == string::npos) {
5002 i = length.find(" plus");
5003 if (i != string::npos)
5004 is_gluelength = true;
5006 is_gluelength = true;
5007 // if yes transform "9xx minus 8yy plus 7zz"
5009 if (is_gluelength) {
5010 i = gluelength.find(" minus");
5011 if (i != string::npos)
5012 gluelength.replace(i, 7, "-");
5013 i = gluelength.find(" plus");
5014 if (i != string::npos)
5015 gluelength.replace(i, 6, "+");
5018 if (t.cs()[0] == 'h' && (known_unit || known_hspace || is_gluelength)) {
5019 // Literal horizontal length or known variable
5020 context.check_layout(os);
5021 begin_inset(os, "space ");
5029 if (known_unit && !known_hspace)
5030 os << "\n\\length " << translate_len(length);
5032 os << "\n\\length " << gluelength;
5034 } else if (known_unit || known_vspace || is_gluelength) {
5035 // Literal vertical length or known variable
5036 context.check_layout(os);
5037 begin_inset(os, "VSpace ");
5040 if (known_unit && !known_vspace)
5041 os << translate_len(length);
5048 // LyX can't handle other length variables in Inset VSpace/space
5053 output_ert_inset(os, name + '{' + unit + '}', context);
5054 else if (value == -1.0)
5055 output_ert_inset(os, name + "{-" + unit + '}', context);
5057 output_ert_inset(os, name + '{' + valstring + unit + '}', context);
5059 output_ert_inset(os, name + '{' + length + '}', context);
5063 // The single '=' is meant here.
5064 else if ((newinsetlayout = findInsetLayout(context.textclass, starredname, true))) {
5068 context.check_layout(os);
5069 docstring const name = newinsetlayout->name();
5070 bool const caption = name.find(from_ascii("Caption:")) == 0;
5072 // Already done for floating minted listings.
5073 if (minted_float.empty()) {
5074 begin_inset(os, "Caption ");
5075 os << to_utf8(name.substr(8)) << '\n';
5078 begin_inset(os, "Flex ");
5079 os << to_utf8(name) << '\n'
5080 << "status collapsed\n";
5082 if (!minted_float.empty()) {
5083 parse_text_snippet(p, os, FLAG_ITEM, false, context);
5084 } else if (newinsetlayout->isPassThru()) {
5085 // set catcodes to verbatim early, just in case.
5086 p.setCatcodes(VERBATIM_CATCODES);
5087 string delim = p.get_token().asInput();
5089 cerr << "Warning: bad delimiter for command " << t.asInput() << endl;
5090 //FIXME: handle error condition
5091 string const arg = p.verbatimStuff("}").second;
5092 Context newcontext(true, context.textclass);
5093 if (newinsetlayout->forcePlainLayout())
5094 newcontext.layout = &context.textclass.plainLayout();
5095 output_ert(os, arg, newcontext);
5097 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
5100 // Minted caption insets are not closed here because
5101 // we collect everything into the caption.
5102 if (minted_float.empty())
5106 else if (t.cs() == "includepdf") {
5108 string const arg = p.getArg('[', ']');
5109 map<string, string> opts;
5110 vector<string> keys;
5111 split_map(arg, opts, keys);
5112 string name = normalize_filename(p.verbatim_item());
5113 string const path = getMasterFilePath(true);
5114 // We want to preserve relative / absolute filenames,
5115 // therefore path is only used for testing
5116 if (!makeAbsPath(name, path).exists()) {
5117 // The file extension is probably missing.
5118 // Now try to find it out.
5119 char const * const pdfpages_format[] = {"pdf", 0};
5120 string const pdftex_name =
5121 find_file(name, path, pdfpages_format);
5122 if (!pdftex_name.empty()) {
5127 FileName const absname = makeAbsPath(name, path);
5128 if (absname.exists())
5130 fix_child_filename(name);
5131 copy_file(absname, name);
5133 cerr << "Warning: Could not find file '"
5134 << name << "'." << endl;
5136 context.check_layout(os);
5137 begin_inset(os, "External\n\ttemplate ");
5138 os << "PDFPages\n\tfilename "
5140 // parse the options
5141 if (opts.find("pages") != opts.end())
5142 os << "\textra LaTeX \"pages="
5143 << opts["pages"] << "\"\n";
5144 if (opts.find("angle") != opts.end())
5145 os << "\trotateAngle "
5146 << opts["angle"] << '\n';
5147 if (opts.find("origin") != opts.end()) {
5149 string const opt = opts["origin"];
5150 if (opt == "tl") ss << "topleft";
5151 if (opt == "bl") ss << "bottomleft";
5152 if (opt == "Bl") ss << "baselineleft";
5153 if (opt == "c") ss << "center";
5154 if (opt == "tc") ss << "topcenter";
5155 if (opt == "bc") ss << "bottomcenter";
5156 if (opt == "Bc") ss << "baselinecenter";
5157 if (opt == "tr") ss << "topright";
5158 if (opt == "br") ss << "bottomright";
5159 if (opt == "Br") ss << "baselineright";
5160 if (!ss.str().empty())
5161 os << "\trotateOrigin " << ss.str() << '\n';
5163 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
5165 if (opts.find("width") != opts.end())
5167 << translate_len(opts["width"]) << '\n';
5168 if (opts.find("height") != opts.end())
5170 << translate_len(opts["height"]) << '\n';
5171 if (opts.find("keepaspectratio") != opts.end())
5172 os << "\tkeepAspectRatio\n";
5174 context.check_layout(os);
5175 registerExternalTemplatePackages("PDFPages");
5178 else if (t.cs() == "loadgame") {
5180 string name = normalize_filename(p.verbatim_item());
5181 string const path = getMasterFilePath(true);
5182 // We want to preserve relative / absolute filenames,
5183 // therefore path is only used for testing
5184 if (!makeAbsPath(name, path).exists()) {
5185 // The file extension is probably missing.
5186 // Now try to find it out.
5187 char const * const lyxskak_format[] = {"fen", 0};
5188 string const lyxskak_name =
5189 find_file(name, path, lyxskak_format);
5190 if (!lyxskak_name.empty())
5191 name = lyxskak_name;
5193 FileName const absname = makeAbsPath(name, path);
5194 if (absname.exists())
5196 fix_child_filename(name);
5197 copy_file(absname, name);
5199 cerr << "Warning: Could not find file '"
5200 << name << "'." << endl;
5201 context.check_layout(os);
5202 begin_inset(os, "External\n\ttemplate ");
5203 os << "ChessDiagram\n\tfilename "
5206 context.check_layout(os);
5207 // after a \loadgame follows a \showboard
5208 if (p.get_token().asInput() == "showboard")
5210 registerExternalTemplatePackages("ChessDiagram");
5214 // try to see whether the string is in unicodesymbols
5215 // Only use text mode commands, since we are in text mode here,
5216 // and math commands may be invalid (bug 6797)
5217 string name = t.asInput();
5218 // handle the dingbats, cyrillic and greek
5219 if (name == "\\ding" || name == "\\textcyr" ||
5220 (name == "\\textgreek" && !preamble.usePolyglossia()))
5221 name = name + '{' + p.getArg('{', '}') + '}';
5222 // handle the ifsym characters
5223 else if (name == "\\textifsymbol") {
5224 string const optif = p.getFullOpt();
5225 string const argif = p.getArg('{', '}');
5226 name = name + optif + '{' + argif + '}';
5228 // handle the \ascii characters
5229 // the case of \ascii within braces, as LyX outputs it, is already
5230 // handled for t.cat() == catBegin
5231 else if (name == "\\ascii") {
5232 // the code is "\asci\xxx"
5233 name = "{" + name + p.get_token().asInput() + "}";
5236 // handle some TIPA special characters
5237 else if (preamble.isPackageUsed("tipa")) {
5238 if (name == "\\s") {
5239 // fromLaTeXCommand() does not yet
5240 // recognize tipa short cuts
5241 name = "\\textsyllabic";
5242 } else if (name == "\\=" &&
5243 p.next_token().asInput() == "*") {
5244 // fromLaTeXCommand() does not yet
5245 // recognize tipa short cuts
5247 name = "\\textsubbar";
5248 } else if (name == "\\textdoublevertline") {
5249 // FIXME: This is not correct,
5250 // \textvertline is higher than \textbardbl
5251 name = "\\textbardbl";
5253 } else if (name == "\\!" ) {
5254 if (p.next_token().asInput() == "b") {
5255 p.get_token(); // eat 'b'
5258 } else if (p.next_token().asInput() == "d") {
5262 } else if (p.next_token().asInput() == "g") {
5266 } else if (p.next_token().asInput() == "G") {
5268 name = "\\texthtscg";
5270 } else if (p.next_token().asInput() == "j") {
5272 name = "\\texthtbardotlessj";
5274 } else if (p.next_token().asInput() == "o") {
5276 name = "\\textbullseye";
5279 } else if (name == "\\*" ) {
5280 if (p.next_token().asInput() == "k") {
5282 name = "\\textturnk";
5284 } else if (p.next_token().asInput() == "r") {
5285 p.get_token(); // eat 'b'
5286 name = "\\textturnr";
5288 } else if (p.next_token().asInput() == "t") {
5290 name = "\\textturnt";
5292 } else if (p.next_token().asInput() == "w") {
5294 name = "\\textturnw";
5299 if ((name.size() == 2 &&
5300 contains("\"'.=^`bcdHkrtuv~", name[1]) &&
5301 p.next_token().asInput() != "*") ||
5302 is_known(name.substr(1), known_tipa_marks)) {
5303 // name is a command that corresponds to a
5304 // combining character in unicodesymbols.
5305 // Append the argument, fromLaTeXCommand()
5306 // will either convert it to a single
5307 // character or a combining sequence.
5308 name += '{' + p.verbatim_item() + '}';
5310 // now get the character from unicodesymbols
5314 docstring s = normalize_c(encodings.fromLaTeXCommand(from_utf8(name),
5315 Encodings::TEXT_CMD, termination, rem, &req));
5317 context.check_layout(os);
5320 output_ert_inset(os, to_utf8(rem), context);
5322 skip_spaces_braces(p);
5323 for (set<string>::const_iterator it = req.begin(); it != req.end(); ++it)
5324 preamble.registerAutomaticallyLoadedPackage(*it);
5326 //cerr << "#: " << t << " mode: " << mode << endl;
5327 // heuristic: read up to next non-nested space
5329 string s = t.asInput();
5330 string z = p.verbatim_item();
5331 while (p.good() && z != " " && !z.empty()) {
5332 //cerr << "read: " << z << endl;
5334 z = p.verbatim_item();
5336 cerr << "found ERT: " << s << endl;
5337 output_ert_inset(os, s + ' ', context);
5340 if (t.asInput() == name &&
5341 p.next_token().asInput() == "*") {
5342 // Starred commands like \vspace*{}
5343 p.get_token(); // Eat '*'
5346 if (!parse_command(name, p, os, outer, context))
5347 output_ert_inset(os, name, context);
5351 if (flags & FLAG_LEAVE) {
5352 flags &= ~FLAG_LEAVE;
5359 string guessLanguage(Parser & p, string const & lang)
5361 typedef std::map<std::string, size_t> LangMap;
5362 // map from language names to number of characters
5365 for (char const * const * i = supported_CJK_languages; *i; i++)
5366 used[string(*i)] = 0;
5369 Token const t = p.get_token();
5370 // comments are not counted for any language
5371 if (t.cat() == catComment)
5373 // commands are not counted as well, but we need to detect
5374 // \begin{CJK} and switch encoding if needed
5375 if (t.cat() == catEscape) {
5376 if (t.cs() == "inputencoding") {
5377 string const enc = subst(p.verbatim_item(), "\n", " ");
5378 p.setEncoding(enc, Encoding::inputenc);
5381 if (t.cs() != "begin")
5384 // Non-CJK content is counted for lang.
5385 // We do not care about the real language here:
5386 // If we have more non-CJK contents than CJK contents,
5387 // we simply use the language that was specified as
5388 // babel main language.
5389 used[lang] += t.asInput().length();
5392 // Now we are starting an environment
5394 string const name = p.getArg('{', '}');
5395 if (name != "CJK") {
5399 // It is a CJK environment
5401 /* name = */ p.getArg('{', '}');
5402 string const encoding = p.getArg('{', '}');
5403 /* mapping = */ p.getArg('{', '}');
5404 string const encoding_old = p.getEncoding();
5405 char const * const * const where =
5406 is_known(encoding, supported_CJK_encodings);
5408 p.setEncoding(encoding, Encoding::CJK);
5410 p.setEncoding("UTF-8");
5411 string const text = p.ertEnvironment("CJK");
5412 p.setEncoding(encoding_old);
5415 // ignore contents in unknown CJK encoding
5418 // the language of the text
5420 supported_CJK_languages[where - supported_CJK_encodings];
5421 used[cjk] += text.length();
5423 LangMap::const_iterator use = used.begin();
5424 for (LangMap::const_iterator it = used.begin(); it != used.end(); ++it) {
5425 if (it->second > use->second)
5432 void check_comment_bib(ostream & os, Context & context)
5434 if (!need_commentbib)
5436 // We have a bibliography database, but no bibliography with biblatex
5437 // which is completely valid. Insert a bibtex inset in a note.
5438 context.check_layout(os);
5439 begin_inset(os, "Note Note\n");
5440 os << "status open\n";
5441 os << "\\begin_layout Plain Layout\n";
5442 begin_command_inset(os, "bibtex", "bibtex");
5444 for (auto const & bf : preamble.biblatex_bibliographies) {
5445 if (!bibfiles.empty())
5447 bibfiles += normalize_filename(bf);
5449 if (!bibfiles.empty())
5450 os << "bibfiles " << '"' << bibfiles << '"' << "\n";
5451 end_inset(os);// Bibtex
5452 os << "\\end_layout\n";
5453 end_inset(os);// Note