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
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
32 using lyx::support::changeExtension;
33 using lyx::support::makeAbsPath;
34 using lyx::support::makeRelPath;
35 using lyx::support::rtrim;
36 using lyx::support::suffixIs;
37 using lyx::support::contains;
38 using lyx::support::subst;
45 using std::ostringstream;
46 using std::istringstream;
50 namespace fs = boost::filesystem;
53 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
54 Context const & context)
56 Context newcontext(true, context.textclass);
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 /// parses a paragraph snippet, useful for example for \\emph{...}
66 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
69 Context newcontext(context);
70 // Don't inherit the extra stuff
71 newcontext.extra_stuff.clear();
72 parse_text(p, os, flags, outer, newcontext);
73 // Make sure that we don't create invalid .lyx files
74 context.need_layout = newcontext.need_layout;
75 context.need_end_layout = newcontext.need_end_layout;
80 * Thin wrapper around parse_text_snippet() using a string.
82 * We completely ignore \c context.need_layout and \c context.need_end_layout,
83 * because our return value is not used directly (otherwise the stream version
84 * of parse_text_snippet() could be used). That means that the caller needs
85 * to do layout management manually.
86 * This is intended to parse text that does not create any layout changes.
88 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
91 Context newcontext(context);
92 newcontext.need_layout = false;
93 newcontext.need_end_layout = false;
94 newcontext.new_layout_allowed = false;
95 // Avoid warning by Context::~Context()
96 newcontext.extra_stuff.clear();
98 parse_text_snippet(p, os, flags, outer, newcontext);
103 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
104 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
108 * We can't put these into known_latex_commands because the argument order
109 * is reversed in lyx if there are 2 arguments.
110 * The starred forms are also known.
112 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
118 * We can't put these into known_latex_commands because the argument order
119 * is reversed in lyx if there are 2 arguments.
120 * No starred form other than "cite*" known.
122 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
123 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
124 // jurabib commands not (yet) supported by LyX:
125 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
126 // "footciteauthor", "footciteyear", "footciteyearpar",
127 "citefield", "citetitle", "cite*", 0 };
129 /// LaTeX names for quotes
130 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
131 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
133 /// the same as known_quotes with .lyx names
134 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
135 "grd", "gls", "fls", "frd", 0};
137 /// LaTeX names for font sizes
138 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
139 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
141 /// the same as known_sizes with .lyx names
142 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
145 /// LaTeX 2.09 names for font families
146 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
148 /// LaTeX names for font families
149 char const * const known_font_families[] = { "rmfamily", "sffamily",
152 /// the same as known_old_font_families and known_font_families with .lyx names
153 char const * const known_coded_font_families[] = { "roman", "sans",
156 /// LaTeX 2.09 names for font series
157 char const * const known_old_font_series[] = { "bf", 0};
159 /// LaTeX names for font series
160 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
162 /// the same as known_old_font_series and known_font_series with .lyx names
163 char const * const known_coded_font_series[] = { "bold", "medium", 0};
165 /// LaTeX 2.09 names for font shapes
166 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
168 /// LaTeX names for font shapes
169 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
172 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
173 char const * const known_coded_font_shapes[] = { "italic", "slanted",
174 "smallcaps", "up", 0};
177 * Graphics file extensions known by the dvips driver of the graphics package.
178 * These extensions are used to complete the filename of an included
179 * graphics file if it does not contain an extension.
180 * The order must be the same that latex uses to find a file, because we
181 * will use the first extension that matches.
182 * This is only an approximation for the common cases. If we would want to
183 * do it right in all cases, we would need to know which graphics driver is
184 * used and know the extensions of every driver of the graphics package.
186 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
187 "ps.gz", "eps.Z", "ps.Z", 0};
190 * Graphics file extensions known by the pdftex driver of the graphics package.
191 * \sa known_dvips_graphics_formats
193 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
197 * Known file extensions for TeX files as used by \\include.
199 char const * const known_tex_extensions[] = {"tex", 0};
202 /// splits "x=z, y=b" into a map
203 map<string, string> split_map(string const & s)
205 map<string, string> res;
208 for (size_t i = 0; i < v.size(); ++i) {
209 size_t const pos = v[i].find('=');
210 string const index = v[i].substr(0, pos);
211 string const value = v[i].substr(pos + 1, string::npos);
212 res[trim(index)] = trim(value);
219 * Split a LaTeX length into value and unit.
220 * The latter can be a real unit like "pt", or a latex length variable
221 * like "\textwidth". The unit may contain additional stuff like glue
222 * lengths, but we don't care, because such lengths are ERT anyway.
223 * \returns true if \p value and \p unit are valid.
225 bool splitLatexLength(string const & len, string & value, string & unit)
229 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
230 //'4,5' is a valid LaTeX length number. Change it to '4.5'
231 string const length = subst(len, ',', '.');
232 if (i == string::npos)
235 if (len[0] == '\\') {
236 // We had something like \textwidth without a factor
242 value = trim(string(length, 0, i));
246 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
247 if (contains(len, '\\'))
248 unit = trim(string(len, i));
250 unit = lyx::support::lowercase(trim(string(len, i)));
255 /// A simple function to translate a latex length to something lyx can
256 /// understand. Not perfect, but rather best-effort.
257 bool translate_len(string const & length, string & valstring, string & unit)
259 if (!splitLatexLength(length, valstring, unit))
261 // LyX uses percent values
263 istringstream iss(valstring);
268 string const percentval = oss.str();
270 if (unit.empty() || unit[0] != '\\')
272 string::size_type const i = unit.find(' ');
273 string const endlen = (i == string::npos) ? string() : string(unit, i);
274 if (unit == "\\textwidth") {
275 valstring = percentval;
276 unit = "text%" + endlen;
277 } else if (unit == "\\columnwidth") {
278 valstring = percentval;
279 unit = "col%" + endlen;
280 } else if (unit == "\\paperwidth") {
281 valstring = percentval;
282 unit = "page%" + endlen;
283 } else if (unit == "\\linewidth") {
284 valstring = percentval;
285 unit = "line%" + endlen;
286 } else if (unit == "\\paperheight") {
287 valstring = percentval;
288 unit = "pheight%" + endlen;
289 } else if (unit == "\\textheight") {
290 valstring = percentval;
291 unit = "theight%" + endlen;
299 string translate_len(string const & length)
303 if (translate_len(length, value, unit))
305 // If the input is invalid, return what we have.
313 * Translates a LaTeX length into \p value, \p unit and
314 * \p special parts suitable for a box inset.
315 * The difference from translate_len() is that a box inset knows about
316 * some special "units" that are stored in \p special.
318 void translate_box_len(string const & length, string & value, string & unit, string & special)
320 if (translate_len(length, value, unit)) {
321 if (unit == "\\height" || unit == "\\depth" ||
322 unit == "\\totalheight" || unit == "\\width") {
323 special = unit.substr(1);
324 // The unit is not used, but LyX requires a dummy setting
337 * Find a file with basename \p name in path \p path and an extension
340 string find_file(string const & name, string const & path,
341 char const * const * extensions)
343 for (char const * const * what = extensions; *what; ++what) {
344 // We don't use ChangeExtension() because it does the wrong
345 // thing if name contains a dot.
346 string const trial = name + '.' + (*what);
347 if (fs::exists(makeAbsPath(trial, path)))
354 void begin_inset(ostream & os, string const & name)
356 os << "\n\\begin_inset " << name;
360 void end_inset(ostream & os)
362 os << "\n\\end_inset\n\n";
366 void skip_braces(Parser & p)
368 if (p.next_token().cat() != catBegin)
371 if (p.next_token().cat() == catEnd) {
379 void handle_ert(ostream & os, string const & s, Context & context)
381 // We must have a valid layout before outputting the ERT inset.
382 context.check_layout(os);
383 Context newcontext(true, context.textclass);
384 begin_inset(os, "ERT");
385 os << "\nstatus collapsed\n";
386 newcontext.check_layout(os);
387 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
389 os << "\n\\backslash\n";
390 else if (*it == '\n') {
391 newcontext.new_paragraph(os);
392 newcontext.check_layout(os);
396 newcontext.check_end_layout(os);
401 void handle_comment(ostream & os, string const & s, Context & context)
403 // TODO: Handle this better
404 Context newcontext(true, context.textclass);
405 begin_inset(os, "ERT");
406 os << "\nstatus collapsed\n";
407 newcontext.check_layout(os);
408 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
410 os << "\n\\backslash\n";
414 // make sure that our comment is the last thing on the line
415 newcontext.new_paragraph(os);
416 newcontext.check_layout(os);
417 newcontext.check_end_layout(os);
422 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
424 isLayout(string const name) : name_(name) {}
425 bool operator()(LyXLayout_ptr const & ptr) const {
426 return ptr->latexname() == name_;
433 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
436 LyXTextClass::const_iterator beg = textclass.begin();
437 LyXTextClass::const_iterator end = textclass.end();
439 LyXTextClass::const_iterator
440 it = std::find_if(beg, end, isLayout(name));
442 return (it == end) ? LyXLayout_ptr() : *it;
446 void eat_whitespace(Parser &, ostream &, Context &, bool);
449 void output_command_layout(ostream & os, Parser & p, bool outer,
450 Context & parent_context,
451 LyXLayout_ptr newlayout)
453 parent_context.check_end_layout(os);
454 Context context(true, parent_context.textclass, newlayout,
455 parent_context.layout, parent_context.font);
456 if (parent_context.deeper_paragraph) {
457 // We are beginning a nested environment after a
458 // deeper paragraph inside the outer list environment.
459 // Therefore we don't need to output a "begin deeper".
460 context.need_end_deeper = true;
462 context.check_deeper(os);
463 context.check_layout(os);
464 if (context.layout->optionalargs > 0) {
465 eat_whitespace(p, os, context, false);
466 if (p.next_token().character() == '[') {
467 p.get_token(); // eat '['
468 begin_inset(os, "OptArg\n");
469 os << "status collapsed\n\n";
470 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
472 eat_whitespace(p, os, context, false);
475 parse_text(p, os, FLAG_ITEM, outer, context);
476 context.check_end_layout(os);
477 if (parent_context.deeper_paragraph) {
478 // We must suppress the "end deeper" because we
479 // suppressed the "begin deeper" above.
480 context.need_end_deeper = false;
482 context.check_end_deeper(os);
483 // We don't need really a new paragraph, but
484 // we must make sure that the next item gets a \begin_layout.
485 parent_context.new_paragraph(os);
490 * Output a space if necessary.
491 * This function gets called for every whitespace token.
493 * We have three cases here:
494 * 1. A space must be suppressed. Example: The lyxcode case below
495 * 2. A space may be suppressed. Example: Spaces before "\par"
496 * 3. A space must not be suppressed. Example: A space between two words
498 * We currently handle only 1. and 3 and from 2. only the case of
499 * spaces before newlines as a side effect.
501 * 2. could be used to suppress as many spaces as possible. This has two effects:
502 * - Reimporting LyX generated LaTeX files changes almost no whitespace
503 * - Superflous whitespace from non LyX generated LaTeX files is removed.
504 * The drawback is that the logic inside the function becomes
505 * complicated, and that is the reason why it is not implemented.
507 void check_space(Parser const & p, ostream & os, Context & context)
509 Token const next = p.next_token();
510 Token const curr = p.curr_token();
511 // A space before a single newline and vice versa must be ignored
512 // LyX emits a newline before \end{lyxcode}.
513 // This newline must be ignored,
514 // otherwise LyX will add an additional protected space.
515 if (next.cat() == catSpace ||
516 next.cat() == catNewline ||
517 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
520 context.check_layout(os);
526 * Parse all arguments of \p command
528 void parse_arguments(string const & command,
529 vector<ArgumentType> const & template_arguments,
530 Parser & p, ostream & os, bool outer, Context & context)
532 string ert = command;
533 size_t no_arguments = template_arguments.size();
534 for (size_t i = 0; i < no_arguments; ++i) {
535 switch (template_arguments[i]) {
537 // This argument contains regular LaTeX
538 handle_ert(os, ert + '{', context);
539 eat_whitespace(p, os, context, false);
540 parse_text(p, os, FLAG_ITEM, outer, context);
544 // This argument may contain special characters
545 ert += '{' + p.verbatim_item() + '}';
552 handle_ert(os, ert, context);
557 * Check whether \p command is a known command. If yes,
558 * handle the command with all arguments.
559 * \return true if the command was parsed, false otherwise.
561 bool parse_command(string const & command, Parser & p, ostream & os,
562 bool outer, Context & context)
564 if (known_commands.find(command) != known_commands.end()) {
565 parse_arguments(command, known_commands[command], p, os,
573 /// Parses a minipage or parbox
574 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
575 Context & parent_context, bool use_parbox)
579 string height_value = "0";
580 string height_unit = "pt";
581 string height_special = "none";
583 if (p.next_token().asInput() == "[") {
584 position = p.getArg('[', ']');
585 if (position != "t" && position != "c" && position != "b") {
587 cerr << "invalid position for minipage/parbox" << endl;
589 if (p.next_token().asInput() == "[") {
590 latex_height = p.getArg('[', ']');
591 translate_box_len(latex_height, height_value, height_unit, height_special);
593 if (p.next_token().asInput() == "[") {
594 inner_pos = p.getArg('[', ']');
595 if (inner_pos != "c" && inner_pos != "t" &&
596 inner_pos != "b" && inner_pos != "s") {
597 inner_pos = position;
598 cerr << "invalid inner_pos for minipage/parbox"
606 string const latex_width = p.verbatim_item();
607 translate_len(latex_width, width_value, width_unit);
608 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
609 // LyX can't handle length variables
614 ss << "\\begin{minipage}";
615 if (!position.empty())
616 ss << '[' << position << ']';
617 if (!latex_height.empty())
618 ss << '[' << latex_height << ']';
619 if (!inner_pos.empty())
620 ss << '[' << inner_pos << ']';
621 ss << "{" << latex_width << "}";
624 handle_ert(os, ss.str(), parent_context);
625 parent_context.new_paragraph(os);
626 parse_text_in_inset(p, os, flags, outer, parent_context);
628 handle_ert(os, "}", parent_context);
630 handle_ert(os, "\\end{minipage}", parent_context);
632 // LyX does not like empty positions, so we have
633 // to set them to the LaTeX default values here.
634 if (position.empty())
636 if (inner_pos.empty())
637 inner_pos = position;
638 parent_context.check_layout(os);
639 begin_inset(os, "Box Frameless\n");
640 os << "position \"" << position << "\"\n";
641 os << "hor_pos \"c\"\n";
642 os << "has_inner_box 1\n";
643 os << "inner_pos \"" << inner_pos << "\"\n";
644 os << "use_parbox " << use_parbox << "\n";
645 os << "width \"" << width_value << width_unit << "\"\n";
646 os << "special \"none\"\n";
647 os << "height \"" << height_value << height_unit << "\"\n";
648 os << "height_special \"" << height_special << "\"\n";
649 os << "status open\n\n";
650 parse_text_in_inset(p, os, flags, outer, parent_context);
652 #ifdef PRESERVE_LAYOUT
653 // lyx puts a % after the end of the minipage
654 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
656 //handle_comment(os, "%dummy", parent_context);
659 parent_context.new_paragraph(os);
661 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
662 //handle_comment(os, "%dummy", parent_context);
665 // We add a protected space if something real follows
666 if (p.good() && p.next_token().cat() != catComment) {
667 os << "\\InsetSpace ~\n";
675 /// parse an unknown environment
676 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
677 unsigned flags, bool outer,
678 Context & parent_context)
680 if (name == "tabbing")
681 // We need to remember that we have to handle '\=' specially
682 flags |= FLAG_TABBING;
684 // We need to translate font changes and paragraphs inside the
685 // environment to ERT if we have a non standard font.
686 // Otherwise things like
687 // \large\begin{foo}\huge bar\end{foo}
689 bool const specialfont =
690 (parent_context.font != parent_context.normalfont);
691 bool const new_layout_allowed = parent_context.new_layout_allowed;
693 parent_context.new_layout_allowed = false;
694 handle_ert(os, "\\begin{" + name + "}", parent_context);
695 parse_text_snippet(p, os, flags, outer, parent_context);
696 handle_ert(os, "\\end{" + name + "}", parent_context);
698 parent_context.new_layout_allowed = new_layout_allowed;
702 void parse_environment(Parser & p, ostream & os, bool outer,
703 Context & parent_context)
705 LyXLayout_ptr newlayout;
706 string const name = p.getArg('{', '}');
707 const bool is_starred = suffixIs(name, '*');
708 string const unstarred_name = rtrim(name, "*");
709 active_environments.push_back(name);
711 if (is_math_env(name)) {
712 parent_context.check_layout(os);
713 begin_inset(os, "Formula ");
714 os << "\\begin{" << name << "}";
715 parse_math(p, os, FLAG_END, MATH_MODE);
716 os << "\\end{" << name << "}";
720 else if (name == "tabular" || name == "longtable") {
721 eat_whitespace(p, os, parent_context, false);
722 parent_context.check_layout(os);
723 begin_inset(os, "Tabular ");
724 handle_tabular(p, os, name == "longtable", parent_context);
729 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
730 eat_whitespace(p, os, parent_context, false);
731 parent_context.check_layout(os);
732 begin_inset(os, "Float " + unstarred_name + "\n");
733 if (p.next_token().asInput() == "[") {
734 os << "placement " << p.getArg('[', ']') << '\n';
736 os << "wide " << convert<string>(is_starred)
737 << "\nsideways false"
738 << "\nstatus open\n\n";
739 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
741 // We don't need really a new paragraph, but
742 // we must make sure that the next item gets a \begin_layout.
743 parent_context.new_paragraph(os);
747 else if (name == "minipage") {
748 eat_whitespace(p, os, parent_context, false);
749 parse_box(p, os, FLAG_END, outer, parent_context, false);
753 else if (name == "comment") {
754 eat_whitespace(p, os, parent_context, false);
755 parent_context.check_layout(os);
756 begin_inset(os, "Note Comment\n");
757 os << "status open\n";
758 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
763 else if (name == "lyxgreyedout") {
764 eat_whitespace(p, os, parent_context, false);
765 parent_context.check_layout(os);
766 begin_inset(os, "Note Greyedout\n");
767 os << "status open\n";
768 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
773 else if (!parent_context.new_layout_allowed)
774 parse_unknown_environment(p, name, os, FLAG_END, outer,
777 // Alignment settings
778 else if (name == "center" || name == "flushleft" || name == "flushright" ||
779 name == "centering" || name == "raggedright" || name == "raggedleft") {
780 eat_whitespace(p, os, parent_context, false);
781 // We must begin a new paragraph if not already done
782 if (! parent_context.atParagraphStart()) {
783 parent_context.check_end_layout(os);
784 parent_context.new_paragraph(os);
786 if (name == "flushleft" || name == "raggedright")
787 parent_context.add_extra_stuff("\\align left\n");
788 else if (name == "flushright" || name == "raggedleft")
789 parent_context.add_extra_stuff("\\align right\n");
791 parent_context.add_extra_stuff("\\align center\n");
792 parse_text(p, os, FLAG_END, outer, parent_context);
793 // Just in case the environment is empty ..
794 parent_context.extra_stuff.erase();
795 // We must begin a new paragraph to reset the alignment
796 parent_context.new_paragraph(os);
800 // The single '=' is meant here.
801 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
802 newlayout->isEnvironment()) {
803 eat_whitespace(p, os, parent_context, false);
804 Context context(true, parent_context.textclass, newlayout,
805 parent_context.layout, parent_context.font);
806 if (parent_context.deeper_paragraph) {
807 // We are beginning a nested environment after a
808 // deeper paragraph inside the outer list environment.
809 // Therefore we don't need to output a "begin deeper".
810 context.need_end_deeper = true;
812 parent_context.check_end_layout(os);
813 switch (context.layout->latextype) {
814 case LATEX_LIST_ENVIRONMENT:
815 context.extra_stuff = "\\labelwidthstring "
816 + p.verbatim_item() + '\n';
819 case LATEX_BIB_ENVIRONMENT:
820 p.verbatim_item(); // swallow next arg
826 context.check_deeper(os);
827 parse_text(p, os, FLAG_END, outer, context);
828 context.check_end_layout(os);
829 if (parent_context.deeper_paragraph) {
830 // We must suppress the "end deeper" because we
831 // suppressed the "begin deeper" above.
832 context.need_end_deeper = false;
834 context.check_end_deeper(os);
835 parent_context.new_paragraph(os);
839 else if (name == "appendix") {
840 // This is no good latex style, but it works and is used in some documents...
841 eat_whitespace(p, os, parent_context, false);
842 parent_context.check_end_layout(os);
843 Context context(true, parent_context.textclass, parent_context.layout,
844 parent_context.layout, parent_context.font);
845 context.check_layout(os);
846 os << "\\start_of_appendix\n";
847 parse_text(p, os, FLAG_END, outer, context);
848 context.check_end_layout(os);
852 else if (known_environments.find(name) != known_environments.end()) {
853 vector<ArgumentType> arguments = known_environments[name];
854 // The last "argument" denotes wether we may translate the
855 // environment contents to LyX
856 // The default required if no argument is given makes us
857 // compatible with the reLyXre environment.
858 ArgumentType contents = arguments.empty() ?
861 if (!arguments.empty())
862 arguments.pop_back();
863 // See comment in parse_unknown_environment()
864 bool const specialfont =
865 (parent_context.font != parent_context.normalfont);
866 bool const new_layout_allowed =
867 parent_context.new_layout_allowed;
869 parent_context.new_layout_allowed = false;
870 parse_arguments("\\begin{" + name + "}", arguments, p, os,
871 outer, parent_context);
872 if (contents == verbatim)
873 handle_ert(os, p.verbatimEnvironment(name),
876 parse_text_snippet(p, os, FLAG_END, outer,
878 handle_ert(os, "\\end{" + name + "}", parent_context);
880 parent_context.new_layout_allowed = new_layout_allowed;
884 parse_unknown_environment(p, name, os, FLAG_END, outer,
887 active_environments.pop_back();
891 /// parses a comment and outputs it to \p os.
892 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
894 BOOST_ASSERT(t.cat() == catComment);
895 if (!t.cs().empty()) {
896 context.check_layout(os);
897 handle_comment(os, '%' + t.cs(), context);
898 if (p.next_token().cat() == catNewline) {
899 // A newline after a comment line starts a new
901 if (context.new_layout_allowed) {
902 if(!context.atParagraphStart())
903 // Only start a new paragraph if not already
904 // done (we might get called recursively)
905 context.new_paragraph(os);
907 handle_ert(os, "\n", context);
908 eat_whitespace(p, os, context, true);
918 * Reads spaces and comments until the first non-space, non-comment token.
919 * New paragraphs (double newlines or \\par) are handled like simple spaces
920 * if \p eatParagraph is true.
921 * Spaces are skipped, but comments are written to \p os.
923 void eat_whitespace(Parser & p, ostream & os, Context & context,
927 Token const & t = p.get_token();
928 if (t.cat() == catComment)
929 parse_comment(p, os, t, context);
930 else if ((! eatParagraph && p.isParagraph()) ||
931 (t.cat() != catSpace && t.cat() != catNewline)) {
940 * Set a font attribute, parse text and reset the font attribute.
941 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
942 * \param currentvalue Current value of the attribute. Is set to the new
943 * value during parsing.
944 * \param newvalue New value of the attribute
946 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
947 Context & context, string const & attribute,
948 string & currentvalue, string const & newvalue)
950 context.check_layout(os);
951 string const oldvalue = currentvalue;
952 currentvalue = newvalue;
953 os << '\n' << attribute << ' ' << newvalue << "\n";
954 parse_text_snippet(p, os, flags, outer, context);
955 context.check_layout(os);
956 os << '\n' << attribute << ' ' << oldvalue << "\n";
957 currentvalue = oldvalue;
961 /// get the arguments of a natbib or jurabib citation command
962 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
964 // We need to distinguish "" and "[]", so we can't use p.getOpt().
966 // text before the citation
968 // text after the citation
969 string after = p.getFullOpt();
971 if (!after.empty()) {
972 before = p.getFullOpt();
973 if (natbibOrder && !before.empty())
974 std::swap(before, after);
976 return std::make_pair(before, after);
980 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
981 string const normalize_filename(string const & name)
983 Parser p(trim(name, "\""));
986 Token const & t = p.get_token();
987 if (t.cat() != catEscape)
989 else if (t.cs() == "lyxdot") {
990 // This is used by LyX for simple dots in relative
994 } else if (t.cs() == "space") {
1004 /// Convert \p name from TeX convention (relative to master file) to LyX
1005 /// convention (relative to .lyx file) if it is relative
1006 void fix_relative_filename(string & name)
1008 if (lyx::support::absolutePath(name))
1010 name = makeRelPath(makeAbsPath(name, getMasterFilePath()),
1011 getParentFilePath());
1015 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1016 void parse_noweb(Parser & p, ostream & os, Context & context)
1018 // assemble the rest of the keyword
1022 Token const & t = p.get_token();
1023 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1026 scrap = (p.good() && p.next_token().asInput() == "=");
1028 name += p.get_token().asInput();
1031 name += t.asInput();
1034 if (!scrap || !context.new_layout_allowed ||
1035 !context.textclass.hasLayout("Scrap")) {
1036 cerr << "Warning: Could not interpret '" << name
1037 << "'. Ignoring it." << endl;
1041 context.check_end_layout(os);
1042 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1043 newcontext.check_layout(os);
1046 Token const & t = p.get_token();
1047 // We abuse the parser a bit, because this is no TeX syntax
1049 if (t.cat() == catEscape)
1050 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1052 os << subst(t.asInput(), "\n", "\n\\newline\n");
1053 // The scrap chunk is ended by an @ at the beginning of a line.
1054 // After the @ the line may contain a comment and/or
1055 // whitespace, but nothing else.
1056 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1057 (p.next_token().cat() == catSpace ||
1058 p.next_token().cat() == catNewline ||
1059 p.next_token().cat() == catComment)) {
1060 while (p.good() && p.next_token().cat() == catSpace)
1061 os << p.get_token().asInput();
1062 if (p.next_token().cat() == catComment)
1063 // The comment includes a final '\n'
1064 os << p.get_token().asInput();
1066 if (p.next_token().cat() == catNewline)
1073 newcontext.check_end_layout(os);
1076 } // anonymous namespace
1079 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1082 LyXLayout_ptr newlayout;
1083 // Store the latest bibliographystyle (needed for bibtex inset)
1084 string bibliographystyle;
1085 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1086 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1088 Token const & t = p.get_token();
1091 cerr << "t: " << t << " flags: " << flags << "\n";
1094 if (flags & FLAG_ITEM) {
1095 if (t.cat() == catSpace)
1098 flags &= ~FLAG_ITEM;
1099 if (t.cat() == catBegin) {
1100 // skip the brace and collect everything to the next matching
1102 flags |= FLAG_BRACE_LAST;
1106 // handle only this single token, leave the loop if done
1107 flags |= FLAG_LEAVE;
1110 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1116 if (t.cat() == catMath) {
1117 // we are inside some text mode thingy, so opening new math is allowed
1118 context.check_layout(os);
1119 begin_inset(os, "Formula ");
1120 Token const & n = p.get_token();
1121 if (n.cat() == catMath && outer) {
1122 // TeX's $$...$$ syntax for displayed math
1124 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1126 p.get_token(); // skip the second '$' token
1128 // simple $...$ stuff
1131 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1137 else if (t.cat() == catSuper || t.cat() == catSub)
1138 cerr << "catcode " << t << " illegal in text mode\n";
1140 // Basic support for english quotes. This should be
1141 // extended to other quotes, but is not so easy (a
1142 // left english quote is the same as a right german
1144 else if (t.asInput() == "`"
1145 && p.next_token().asInput() == "`") {
1146 context.check_layout(os);
1147 begin_inset(os, "Quotes ");
1153 else if (t.asInput() == "'"
1154 && p.next_token().asInput() == "'") {
1155 context.check_layout(os);
1156 begin_inset(os, "Quotes ");
1163 else if (t.asInput() == "<"
1164 && p.next_token().asInput() == "<" && noweb_mode) {
1166 parse_noweb(p, os, context);
1169 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1170 check_space(p, os, context);
1172 else if (t.character() == '[' && noweb_mode &&
1173 p.next_token().character() == '[') {
1174 // These can contain underscores
1176 string const s = p.getFullOpt() + ']';
1177 if (p.next_token().character() == ']')
1180 cerr << "Warning: Inserting missing ']' in '"
1181 << s << "'." << endl;
1182 handle_ert(os, s, context);
1185 else if (t.cat() == catLetter ||
1186 t.cat() == catOther ||
1187 t.cat() == catAlign ||
1188 t.cat() == catParameter) {
1189 // This translates "&" to "\\&" which may be wrong...
1190 context.check_layout(os);
1191 os << t.character();
1194 else if (p.isParagraph()) {
1195 if (context.new_layout_allowed)
1196 context.new_paragraph(os);
1198 handle_ert(os, "\\par ", context);
1199 eat_whitespace(p, os, context, true);
1202 else if (t.cat() == catActive) {
1203 context.check_layout(os);
1204 if (t.character() == '~') {
1205 if (context.layout->free_spacing)
1208 os << "\\InsetSpace ~\n";
1210 os << t.character();
1213 else if (t.cat() == catBegin &&
1214 p.next_token().cat() == catEnd) {
1216 Token const prev = p.prev_token();
1218 if (p.next_token().character() == '`' ||
1219 (prev.character() == '-' &&
1220 p.next_token().character() == '-'))
1221 ; // ignore it in {}`` or -{}-
1223 handle_ert(os, "{}", context);
1227 else if (t.cat() == catBegin) {
1228 context.check_layout(os);
1229 // special handling of font attribute changes
1230 Token const prev = p.prev_token();
1231 Token const next = p.next_token();
1232 Font const oldFont = context.font;
1233 if (next.character() == '[' ||
1234 next.character() == ']' ||
1235 next.character() == '*') {
1237 if (p.next_token().cat() == catEnd) {
1238 os << next.character();
1242 handle_ert(os, "{", context);
1243 parse_text_snippet(p, os,
1246 handle_ert(os, "}", context);
1248 } else if (! context.new_layout_allowed) {
1249 handle_ert(os, "{", context);
1250 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1252 handle_ert(os, "}", context);
1253 } else if (is_known(next.cs(), known_sizes)) {
1254 // next will change the size, so we must
1256 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1258 if (!context.atParagraphStart())
1260 << context.font.size << "\n";
1261 } else if (is_known(next.cs(), known_font_families)) {
1262 // next will change the font family, so we
1263 // must reset it here
1264 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1266 if (!context.atParagraphStart())
1268 << context.font.family << "\n";
1269 } else if (is_known(next.cs(), known_font_series)) {
1270 // next will change the font series, so we
1271 // must reset it here
1272 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1274 if (!context.atParagraphStart())
1276 << context.font.series << "\n";
1277 } else if (is_known(next.cs(), known_font_shapes)) {
1278 // next will change the font shape, so we
1279 // must reset it here
1280 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1282 if (!context.atParagraphStart())
1284 << context.font.shape << "\n";
1285 } else if (is_known(next.cs(), known_old_font_families) ||
1286 is_known(next.cs(), known_old_font_series) ||
1287 is_known(next.cs(), known_old_font_shapes)) {
1288 // next will change the font family, series
1289 // and shape, so we must reset it here
1290 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1292 if (!context.atParagraphStart())
1294 << context.font.family
1296 << context.font.series
1298 << context.font.shape << "\n";
1300 handle_ert(os, "{", context);
1301 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1303 handle_ert(os, "}", context);
1307 else if (t.cat() == catEnd) {
1308 if (flags & FLAG_BRACE_LAST) {
1311 cerr << "stray '}' in text\n";
1312 handle_ert(os, "}", context);
1315 else if (t.cat() == catComment)
1316 parse_comment(p, os, t, context);
1319 // control sequences
1322 else if (t.cs() == "(") {
1323 context.check_layout(os);
1324 begin_inset(os, "Formula");
1326 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1331 else if (t.cs() == "[") {
1332 context.check_layout(os);
1333 begin_inset(os, "Formula");
1335 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1340 else if (t.cs() == "begin")
1341 parse_environment(p, os, outer, context);
1343 else if (t.cs() == "end") {
1344 if (flags & FLAG_END) {
1345 // eat environment name
1346 string const name = p.getArg('{', '}');
1347 if (name != active_environment())
1348 cerr << "\\end{" + name + "} does not match \\begin{"
1349 + active_environment() + "}\n";
1352 p.error("found 'end' unexpectedly");
1355 else if (t.cs() == "item") {
1358 bool optarg = false;
1359 if (p.next_token().character() == '[') {
1360 p.get_token(); // eat '['
1361 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1366 context.check_layout(os);
1367 if (context.has_item) {
1368 // An item in an unknown list-like environment
1369 // FIXME: Do this in check_layout()!
1370 context.has_item = false;
1372 handle_ert(os, "\\item", context);
1374 handle_ert(os, "\\item ", context);
1377 if (context.layout->labeltype != LABEL_MANUAL) {
1378 // lyx does not support \item[\mybullet]
1379 // in itemize environments
1380 handle_ert(os, "[", context);
1382 handle_ert(os, "]", context);
1383 } else if (!s.empty()) {
1384 // The space is needed to separate the
1385 // item from the rest of the sentence.
1387 eat_whitespace(p, os, context, false);
1392 else if (t.cs() == "bibitem") {
1394 context.check_layout(os);
1397 os << '{' << p.verbatim_item() << '}' << "\n";
1400 else if (t.cs() == "def") {
1401 context.check_layout(os);
1402 eat_whitespace(p, os, context, false);
1403 string name = p.get_token().cs();
1404 while (p.next_token().cat() != catBegin)
1405 name += p.get_token().asString();
1406 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1409 else if (t.cs() == "noindent") {
1411 context.add_extra_stuff("\\noindent\n");
1414 else if (t.cs() == "appendix") {
1415 context.add_extra_stuff("\\start_of_appendix\n");
1416 // We need to start a new paragraph. Otherwise the
1417 // appendix in 'bla\appendix\chapter{' would start
1419 context.new_paragraph(os);
1420 // We need to make sure that the paragraph is
1421 // generated even if it is empty. Otherwise the
1422 // appendix in '\par\appendix\par\chapter{' would
1424 context.check_layout(os);
1425 // FIXME: This is a hack to prevent paragraph
1426 // deletion if it is empty. Handle this better!
1428 "%dummy comment inserted by tex2lyx to "
1429 "ensure that this paragraph is not empty",
1431 // Both measures above may generate an additional
1432 // empty paragraph, but that does not hurt, because
1433 // whitespace does not matter here.
1434 eat_whitespace(p, os, context, true);
1437 // Must attempt to parse "Section*" before "Section".
1438 else if ((p.next_token().asInput() == "*") &&
1439 context.new_layout_allowed &&
1440 // The single '=' is meant here.
1441 (newlayout = findLayout(context.textclass,
1442 t.cs() + '*')).get() &&
1443 newlayout->isCommand()) {
1445 output_command_layout(os, p, outer, context, newlayout);
1449 // The single '=' is meant here.
1450 else if (context.new_layout_allowed &&
1451 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1452 newlayout->isCommand()) {
1453 output_command_layout(os, p, outer, context, newlayout);
1457 else if (t.cs() == "includegraphics") {
1458 bool const clip = p.next_token().asInput() == "*";
1461 map<string, string> opts = split_map(p.getArg('[', ']'));
1463 opts["clip"] = string();
1464 string name = normalize_filename(p.verbatim_item());
1466 string const path = getMasterFilePath();
1467 // We want to preserve relative / absolute filenames,
1468 // therefore path is only used for testing
1469 if (!fs::exists(makeAbsPath(name, path))) {
1470 // The file extension is probably missing.
1471 // Now try to find it out.
1472 string const dvips_name =
1473 find_file(name, path,
1474 known_dvips_graphics_formats);
1475 string const pdftex_name =
1476 find_file(name, path,
1477 known_pdftex_graphics_formats);
1478 if (!dvips_name.empty()) {
1479 if (!pdftex_name.empty()) {
1480 cerr << "This file contains the "
1482 "\"\\includegraphics{"
1484 "However, files\n\""
1485 << dvips_name << "\" and\n\""
1486 << pdftex_name << "\"\n"
1487 "both exist, so I had to make a "
1488 "choice and took the first one.\n"
1489 "Please move the unwanted one "
1490 "someplace else and try again\n"
1491 "if my choice was wrong."
1495 } else if (!pdftex_name.empty())
1499 if (fs::exists(makeAbsPath(name, path)))
1500 fix_relative_filename(name);
1502 cerr << "Warning: Could not find graphics file '"
1503 << name << "'." << endl;
1505 context.check_layout(os);
1506 begin_inset(os, "Graphics ");
1507 os << "\n\tfilename " << name << '\n';
1508 if (opts.find("width") != opts.end())
1510 << translate_len(opts["width"]) << '\n';
1511 if (opts.find("height") != opts.end())
1513 << translate_len(opts["height"]) << '\n';
1514 if (opts.find("scale") != opts.end()) {
1515 istringstream iss(opts["scale"]);
1519 os << "\tscale " << val << '\n';
1521 if (opts.find("angle") != opts.end())
1522 os << "\trotateAngle "
1523 << opts["angle"] << '\n';
1524 if (opts.find("origin") != opts.end()) {
1526 string const opt = opts["origin"];
1527 if (opt.find('l') != string::npos) ss << "left";
1528 if (opt.find('r') != string::npos) ss << "right";
1529 if (opt.find('c') != string::npos) ss << "center";
1530 if (opt.find('t') != string::npos) ss << "Top";
1531 if (opt.find('b') != string::npos) ss << "Bottom";
1532 if (opt.find('B') != string::npos) ss << "Baseline";
1533 if (!ss.str().empty())
1534 os << "\trotateOrigin " << ss.str() << '\n';
1536 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1538 if (opts.find("keepaspectratio") != opts.end())
1539 os << "\tkeepAspectRatio\n";
1540 if (opts.find("clip") != opts.end())
1542 if (opts.find("draft") != opts.end())
1544 if (opts.find("bb") != opts.end())
1545 os << "\tBoundingBox "
1546 << opts["bb"] << '\n';
1547 int numberOfbbOptions = 0;
1548 if (opts.find("bbllx") != opts.end())
1549 numberOfbbOptions++;
1550 if (opts.find("bblly") != opts.end())
1551 numberOfbbOptions++;
1552 if (opts.find("bburx") != opts.end())
1553 numberOfbbOptions++;
1554 if (opts.find("bbury") != opts.end())
1555 numberOfbbOptions++;
1556 if (numberOfbbOptions == 4)
1557 os << "\tBoundingBox "
1558 << opts["bbllx"] << opts["bblly"]
1559 << opts["bburx"] << opts["bbury"] << '\n';
1560 else if (numberOfbbOptions > 0)
1561 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1562 numberOfbbOptions = 0;
1563 if (opts.find("natwidth") != opts.end())
1564 numberOfbbOptions++;
1565 if (opts.find("natheight") != opts.end())
1566 numberOfbbOptions++;
1567 if (numberOfbbOptions == 2)
1568 os << "\tBoundingBox 0bp 0bp "
1569 << opts["natwidth"] << opts["natheight"] << '\n';
1570 else if (numberOfbbOptions > 0)
1571 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1572 ostringstream special;
1573 if (opts.find("hiresbb") != opts.end())
1574 special << "hiresbb,";
1575 if (opts.find("trim") != opts.end())
1577 if (opts.find("viewport") != opts.end())
1578 special << "viewport=" << opts["viewport"] << ',';
1579 if (opts.find("totalheight") != opts.end())
1580 special << "totalheight=" << opts["totalheight"] << ',';
1581 if (opts.find("type") != opts.end())
1582 special << "type=" << opts["type"] << ',';
1583 if (opts.find("ext") != opts.end())
1584 special << "ext=" << opts["ext"] << ',';
1585 if (opts.find("read") != opts.end())
1586 special << "read=" << opts["read"] << ',';
1587 if (opts.find("command") != opts.end())
1588 special << "command=" << opts["command"] << ',';
1589 string s_special = special.str();
1590 if (!s_special.empty()) {
1591 // We had special arguments. Remove the trailing ','.
1592 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1594 // TODO: Handle the unknown settings better.
1595 // Warn about invalid options.
1596 // Check whether some option was given twice.
1600 else if (t.cs() == "footnote" ||
1601 (t.cs() == "thanks" && context.layout->intitle)) {
1603 context.check_layout(os);
1604 begin_inset(os, "Foot\n");
1605 os << "status collapsed\n\n";
1606 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1610 else if (t.cs() == "marginpar") {
1612 context.check_layout(os);
1613 begin_inset(os, "Marginal\n");
1614 os << "status collapsed\n\n";
1615 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1619 else if (t.cs() == "ensuremath") {
1621 context.check_layout(os);
1622 string const s = p.verbatim_item();
1623 if (s == "±" || s == "³" || s == "²" || s == "µ")
1626 handle_ert(os, "\\ensuremath{" + s + "}",
1630 else if (t.cs() == "hfill") {
1631 context.check_layout(os);
1632 os << "\n\\hfill\n";
1637 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1638 // FIXME: Somehow prevent title layouts if
1639 // "maketitle" was not found
1641 skip_braces(p); // swallow this
1644 else if (t.cs() == "tableofcontents") {
1646 context.check_layout(os);
1647 begin_inset(os, "LatexCommand \\tableofcontents\n");
1649 skip_braces(p); // swallow this
1652 else if (t.cs() == "listoffigures") {
1654 context.check_layout(os);
1655 begin_inset(os, "FloatList figure\n");
1657 skip_braces(p); // swallow this
1660 else if (t.cs() == "listoftables") {
1662 context.check_layout(os);
1663 begin_inset(os, "FloatList table\n");
1665 skip_braces(p); // swallow this
1668 else if (t.cs() == "listof") {
1669 p.skip_spaces(true);
1670 string const name = p.get_token().asString();
1671 if (context.textclass.floats().typeExist(name)) {
1672 context.check_layout(os);
1673 begin_inset(os, "FloatList ");
1676 p.get_token(); // swallow second arg
1678 handle_ert(os, "\\listof{" + name + "}", context);
1681 else if (t.cs() == "textrm")
1682 parse_text_attributes(p, os, FLAG_ITEM, outer,
1683 context, "\\family",
1684 context.font.family, "roman");
1686 else if (t.cs() == "textsf")
1687 parse_text_attributes(p, os, FLAG_ITEM, outer,
1688 context, "\\family",
1689 context.font.family, "sans");
1691 else if (t.cs() == "texttt")
1692 parse_text_attributes(p, os, FLAG_ITEM, outer,
1693 context, "\\family",
1694 context.font.family, "typewriter");
1696 else if (t.cs() == "textmd")
1697 parse_text_attributes(p, os, FLAG_ITEM, outer,
1698 context, "\\series",
1699 context.font.series, "medium");
1701 else if (t.cs() == "textbf")
1702 parse_text_attributes(p, os, FLAG_ITEM, outer,
1703 context, "\\series",
1704 context.font.series, "bold");
1706 else if (t.cs() == "textup")
1707 parse_text_attributes(p, os, FLAG_ITEM, outer,
1709 context.font.shape, "up");
1711 else if (t.cs() == "textit")
1712 parse_text_attributes(p, os, FLAG_ITEM, outer,
1714 context.font.shape, "italic");
1716 else if (t.cs() == "textsl")
1717 parse_text_attributes(p, os, FLAG_ITEM, outer,
1719 context.font.shape, "slanted");
1721 else if (t.cs() == "textsc")
1722 parse_text_attributes(p, os, FLAG_ITEM, outer,
1724 context.font.shape, "smallcaps");
1726 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1727 context.check_layout(os);
1728 Font oldFont = context.font;
1729 context.font.init();
1730 context.font.size = oldFont.size;
1731 os << "\n\\family " << context.font.family << "\n";
1732 os << "\n\\series " << context.font.series << "\n";
1733 os << "\n\\shape " << context.font.shape << "\n";
1734 if (t.cs() == "textnormal") {
1735 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1736 output_font_change(os, context.font, oldFont);
1737 context.font = oldFont;
1739 eat_whitespace(p, os, context, false);
1742 else if (t.cs() == "underbar") {
1743 // Do NOT handle \underline.
1744 // \underbar cuts through y, g, q, p etc.,
1745 // \underline does not.
1746 context.check_layout(os);
1747 os << "\n\\bar under\n";
1748 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1749 context.check_layout(os);
1750 os << "\n\\bar default\n";
1753 else if (t.cs() == "emph" || t.cs() == "noun") {
1754 context.check_layout(os);
1755 os << "\n\\" << t.cs() << " on\n";
1756 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1757 context.check_layout(os);
1758 os << "\n\\" << t.cs() << " default\n";
1761 else if (use_natbib &&
1762 is_known(t.cs(), known_natbib_commands) &&
1763 ((t.cs() != "citefullauthor" &&
1764 t.cs() != "citeyear" &&
1765 t.cs() != "citeyearpar") ||
1766 p.next_token().asInput() != "*")) {
1767 context.check_layout(os);
1769 // \citet[before][after]{a} \citet[after][before]{a}
1770 // \citet[before][]{a} \citet[][before]{a}
1771 // \citet[after]{a} \citet[after]{a}
1772 // \citet{a} \citet{a}
1773 string command = '\\' + t.cs();
1774 if (p.next_token().asInput() == "*") {
1778 if (command == "\\citefullauthor")
1779 // alternative name for "\\citeauthor*"
1780 command = "\\citeauthor*";
1782 // text before the citation
1784 // text after the citation
1787 boost::tie(before, after) = getCiteArguments(p, true);
1788 if (command == "\\cite") {
1789 // \cite without optional argument means
1790 // \citet, \cite with at least one optional
1791 // argument means \citep.
1792 if (before.empty() && after.empty())
1793 command = "\\citet";
1795 command = "\\citep";
1797 if (before.empty() && after == "[]")
1798 // avoid \citet[]{a}
1800 else if (before == "[]" && after == "[]") {
1801 // avoid \citet[][]{a}
1805 begin_inset(os, "LatexCommand ");
1806 os << command << after << before
1807 << '{' << p.verbatim_item() << "}\n";
1811 else if (use_jurabib &&
1812 is_known(t.cs(), known_jurabib_commands)) {
1813 context.check_layout(os);
1814 string const command = '\\' + t.cs();
1815 char argumentOrder = '\0';
1816 vector<string> const & options = used_packages["jurabib"];
1817 if (std::find(options.begin(), options.end(),
1818 "natbiborder") != options.end())
1819 argumentOrder = 'n';
1820 else if (std::find(options.begin(), options.end(),
1821 "jurabiborder") != options.end())
1822 argumentOrder = 'j';
1824 // text before the citation
1826 // text after the citation
1829 boost::tie(before, after) =
1830 getCiteArguments(p, argumentOrder != 'j');
1831 string const citation = p.verbatim_item();
1832 if (!before.empty() && argumentOrder == '\0') {
1833 cerr << "Warning: Assuming argument order "
1834 "of jurabib version 0.6 for\n'"
1835 << command << before << after << '{'
1836 << citation << "}'.\n"
1837 "Add 'jurabiborder' to the jurabib "
1838 "package options if you used an\n"
1839 "earlier jurabib version." << endl;
1841 begin_inset(os, "LatexCommand ");
1842 os << command << after << before
1843 << '{' << citation << "}\n";
1847 else if (is_known(t.cs(), known_latex_commands)) {
1848 // This needs to be after the check for natbib and
1849 // jurabib commands, because "cite" has different
1850 // arguments with natbib and jurabib.
1851 context.check_layout(os);
1852 begin_inset(os, "LatexCommand ");
1853 os << '\\' << t.cs();
1854 // lyx cannot handle newlines in a latex command
1855 // FIXME: Move the substitution into parser::getOpt()?
1856 os << subst(p.getOpt(), "\n", " ");
1857 os << subst(p.getOpt(), "\n", " ");
1858 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1862 else if (is_known(t.cs(), known_quotes)) {
1863 char const * const * where = is_known(t.cs(), known_quotes);
1864 context.check_layout(os);
1865 begin_inset(os, "Quotes ");
1866 os << known_coded_quotes[where - known_quotes];
1868 // LyX adds {} after the quote, so we have to eat
1869 // spaces here if there are any before a possible
1871 eat_whitespace(p, os, context, false);
1875 else if (is_known(t.cs(), known_sizes) &&
1876 context.new_layout_allowed) {
1877 char const * const * where = is_known(t.cs(), known_sizes);
1878 context.check_layout(os);
1879 Font const oldFont = context.font;
1880 context.font.size = known_coded_sizes[where - known_sizes];
1881 output_font_change(os, oldFont, context.font);
1882 eat_whitespace(p, os, context, false);
1885 else if (is_known(t.cs(), known_font_families) &&
1886 context.new_layout_allowed) {
1887 char const * const * where =
1888 is_known(t.cs(), known_font_families);
1889 context.check_layout(os);
1890 Font const oldFont = context.font;
1891 context.font.family =
1892 known_coded_font_families[where - known_font_families];
1893 output_font_change(os, oldFont, context.font);
1894 eat_whitespace(p, os, context, false);
1897 else if (is_known(t.cs(), known_font_series) &&
1898 context.new_layout_allowed) {
1899 char const * const * where =
1900 is_known(t.cs(), known_font_series);
1901 context.check_layout(os);
1902 Font const oldFont = context.font;
1903 context.font.series =
1904 known_coded_font_series[where - known_font_series];
1905 output_font_change(os, oldFont, context.font);
1906 eat_whitespace(p, os, context, false);
1909 else if (is_known(t.cs(), known_font_shapes) &&
1910 context.new_layout_allowed) {
1911 char const * const * where =
1912 is_known(t.cs(), known_font_shapes);
1913 context.check_layout(os);
1914 Font const oldFont = context.font;
1915 context.font.shape =
1916 known_coded_font_shapes[where - known_font_shapes];
1917 output_font_change(os, oldFont, context.font);
1918 eat_whitespace(p, os, context, false);
1920 else if (is_known(t.cs(), known_old_font_families) &&
1921 context.new_layout_allowed) {
1922 char const * const * where =
1923 is_known(t.cs(), known_old_font_families);
1924 context.check_layout(os);
1925 Font const oldFont = context.font;
1926 context.font.init();
1927 context.font.size = oldFont.size;
1928 context.font.family =
1929 known_coded_font_families[where - known_old_font_families];
1930 output_font_change(os, oldFont, context.font);
1931 eat_whitespace(p, os, context, false);
1934 else if (is_known(t.cs(), known_old_font_series) &&
1935 context.new_layout_allowed) {
1936 char const * const * where =
1937 is_known(t.cs(), known_old_font_series);
1938 context.check_layout(os);
1939 Font const oldFont = context.font;
1940 context.font.init();
1941 context.font.size = oldFont.size;
1942 context.font.series =
1943 known_coded_font_series[where - known_old_font_series];
1944 output_font_change(os, oldFont, context.font);
1945 eat_whitespace(p, os, context, false);
1948 else if (is_known(t.cs(), known_old_font_shapes) &&
1949 context.new_layout_allowed) {
1950 char const * const * where =
1951 is_known(t.cs(), known_old_font_shapes);
1952 context.check_layout(os);
1953 Font const oldFont = context.font;
1954 context.font.init();
1955 context.font.size = oldFont.size;
1956 context.font.shape =
1957 known_coded_font_shapes[where - known_old_font_shapes];
1958 output_font_change(os, oldFont, context.font);
1959 eat_whitespace(p, os, context, false);
1962 else if (t.cs() == "LyX" || t.cs() == "TeX"
1963 || t.cs() == "LaTeX") {
1964 context.check_layout(os);
1966 skip_braces(p); // eat {}
1969 else if (t.cs() == "LaTeXe") {
1970 context.check_layout(os);
1972 skip_braces(p); // eat {}
1975 else if (t.cs() == "ldots") {
1976 context.check_layout(os);
1978 os << "\\SpecialChar \\ldots{}\n";
1981 else if (t.cs() == "lyxarrow") {
1982 context.check_layout(os);
1983 os << "\\SpecialChar \\menuseparator\n";
1987 else if (t.cs() == "textcompwordmark") {
1988 context.check_layout(os);
1989 os << "\\SpecialChar \\textcompwordmark{}\n";
1993 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1994 context.check_layout(os);
1995 os << "\\SpecialChar \\@.\n";
1999 else if (t.cs() == "-") {
2000 context.check_layout(os);
2001 os << "\\SpecialChar \\-\n";
2004 else if (t.cs() == "textasciitilde") {
2005 context.check_layout(os);
2010 else if (t.cs() == "textasciicircum") {
2011 context.check_layout(os);
2016 else if (t.cs() == "textbackslash") {
2017 context.check_layout(os);
2018 os << "\n\\backslash\n";
2022 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2023 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2025 context.check_layout(os);
2029 else if (t.cs() == "char") {
2030 context.check_layout(os);
2031 if (p.next_token().character() == '`') {
2033 if (p.next_token().cs() == "\"") {
2038 handle_ert(os, "\\char`", context);
2041 handle_ert(os, "\\char", context);
2045 else if (t.cs() == "verb") {
2046 context.check_layout(os);
2047 char const delimiter = p.next_token().character();
2048 string const arg = p.getArg(delimiter, delimiter);
2050 oss << "\\verb" << delimiter << arg << delimiter;
2051 handle_ert(os, oss.str(), context);
2054 else if (t.cs() == "\"") {
2055 context.check_layout(os);
2056 string const name = p.verbatim_item();
2057 if (name == "a") os << 'ä';
2058 else if (name == "o") os << 'ö';
2059 else if (name == "u") os << 'ü';
2060 else if (name == "A") os << 'Ä';
2061 else if (name == "O") os << 'Ö';
2062 else if (name == "U") os << 'Ü';
2063 else handle_ert(os, "\"{" + name + "}", context);
2066 // Problem: \= creates a tabstop inside the tabbing environment
2067 // and else an accent. In the latter case we really would want
2068 // \={o} instead of \= o.
2069 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2070 handle_ert(os, t.asInput(), context);
2072 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2073 || t.cs() == "'" || t.cs() == "`"
2074 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2075 // we need the trim as the LyX parser chokes on such spaces
2076 context.check_layout(os);
2077 os << "\n\\i \\" << t.cs() << "{"
2078 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2082 else if (t.cs() == "ss") {
2083 context.check_layout(os);
2085 skip_braces(p); // eat {}
2088 else if (t.cs() == "i" || t.cs() == "j") {
2089 context.check_layout(os);
2090 os << "\\" << t.cs() << ' ';
2091 skip_braces(p); // eat {}
2094 else if (t.cs() == "\\") {
2095 context.check_layout(os);
2096 string const next = p.next_token().asInput();
2098 handle_ert(os, "\\\\" + p.getOpt(), context);
2099 else if (next == "*") {
2101 handle_ert(os, "\\\\*" + p.getOpt(), context);
2104 os << "\n\\newline\n";
2108 else if (t.cs() == "input" || t.cs() == "include"
2109 || t.cs() == "verbatiminput") {
2110 string name = '\\' + t.cs();
2111 if (t.cs() == "verbatiminput"
2112 && p.next_token().asInput() == "*")
2113 name += p.get_token().asInput();
2114 context.check_layout(os);
2115 begin_inset(os, "Include ");
2116 string filename(normalize_filename(p.getArg('{', '}')));
2117 string const path = getMasterFilePath();
2118 // We want to preserve relative / absolute filenames,
2119 // therefore path is only used for testing
2120 if (t.cs() == "include" &&
2121 !fs::exists(makeAbsPath(filename, path))) {
2122 // The file extension is probably missing.
2123 // Now try to find it out.
2124 string const tex_name =
2125 find_file(filename, path,
2126 known_tex_extensions);
2127 if (!tex_name.empty())
2128 filename = tex_name;
2130 if (fs::exists(makeAbsPath(filename, path))) {
2131 string const abstexname =
2132 makeAbsPath(filename, path);
2133 string const abslyxname =
2134 changeExtension(abstexname, ".lyx");
2135 fix_relative_filename(filename);
2136 string const lyxname =
2137 changeExtension(filename, ".lyx");
2138 if (t.cs() != "verbatiminput" &&
2139 tex2lyx(abstexname, abslyxname)) {
2140 os << name << '{' << lyxname << "}\n";
2142 os << name << '{' << filename << "}\n";
2145 cerr << "Warning: Could not find included file '"
2146 << filename << "'." << endl;
2147 os << name << '{' << filename << "}\n";
2149 os << "preview false\n";
2153 else if (t.cs() == "bibliographystyle") {
2154 // store new bibliographystyle
2155 bibliographystyle = p.verbatim_item();
2156 // output new bibliographystyle.
2157 // This is only necessary if used in some other macro than \bibliography.
2158 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2161 else if (t.cs() == "bibliography") {
2162 context.check_layout(os);
2163 begin_inset(os, "LatexCommand ");
2165 // Do we have a bibliographystyle set?
2166 if (!bibliographystyle.empty()) {
2167 os << '[' << bibliographystyle << ']';
2169 os << '{' << p.verbatim_item() << "}\n";
2173 else if (t.cs() == "parbox")
2174 parse_box(p, os, FLAG_ITEM, outer, context, true);
2176 else if (t.cs() == "smallskip" ||
2177 t.cs() == "medskip" ||
2178 t.cs() == "bigskip" ||
2179 t.cs() == "vfill") {
2180 context.check_layout(os);
2181 begin_inset(os, "VSpace ");
2187 else if (t.cs() == "newpage") {
2188 context.check_layout(os);
2189 // FIXME: what about \\clearpage and \\pagebreak?
2190 os << "\n\\newpage\n";
2191 skip_braces(p); // eat {}
2194 else if (t.cs() == "newcommand" ||
2195 t.cs() == "providecommand" ||
2196 t.cs() == "renewcommand") {
2197 // these could be handled by parse_command(), but
2198 // we need to call add_known_command() here.
2199 string name = t.asInput();
2200 if (p.next_token().asInput() == "*") {
2201 // Starred form. Eat '*'
2205 string const command = p.verbatim_item();
2206 string const opt1 = p.getOpt();
2207 string const opt2 = p.getFullOpt();
2208 add_known_command(command, opt1, !opt2.empty());
2209 string const ert = name + '{' + command + '}' +
2211 '{' + p.verbatim_item() + '}';
2212 handle_ert(os, ert, context);
2215 else if (t.cs() == "vspace") {
2216 bool starred = false;
2217 if (p.next_token().asInput() == "*") {
2221 string const length = p.verbatim_item();
2224 bool valid = splitLatexLength(length, valstring, unit);
2225 bool known_vspace = false;
2226 bool known_unit = false;
2229 istringstream iss(valstring);
2232 if (unit == "\\smallskipamount") {
2234 known_vspace = true;
2235 } else if (unit == "\\medskipamount") {
2237 known_vspace = true;
2238 } else if (unit == "\\bigskipamount") {
2240 known_vspace = true;
2241 } else if (unit == "\\fill") {
2243 known_vspace = true;
2246 if (!known_vspace) {
2247 switch (unitFromString(unit)) {
2268 if (known_unit || known_vspace) {
2269 // Literal length or known variable
2270 context.check_layout(os);
2271 begin_inset(os, "VSpace ");
2279 // LyX can't handle other length variables in Inset VSpace
2280 string name = t.asInput();
2285 handle_ert(os, name + '{' + unit + '}', context);
2286 else if (value == -1.0)
2287 handle_ert(os, name + "{-" + unit + '}', context);
2289 handle_ert(os, name + '{' + valstring + unit + '}', context);
2291 handle_ert(os, name + '{' + length + '}', context);
2296 //cerr << "#: " << t << " mode: " << mode << endl;
2297 // heuristic: read up to next non-nested space
2299 string s = t.asInput();
2300 string z = p.verbatim_item();
2301 while (p.good() && z != " " && z.size()) {
2302 //cerr << "read: " << z << endl;
2304 z = p.verbatim_item();
2306 cerr << "found ERT: " << s << endl;
2307 handle_ert(os, s + ' ', context);
2309 string name = t.asInput();
2310 if (p.next_token().asInput() == "*") {
2311 // Starred commands like \vspace*{}
2312 p.get_token(); // Eat '*'
2315 if (! parse_command(name, p, os, outer, context))
2316 handle_ert(os, name, context);
2319 if (flags & FLAG_LEAVE) {
2320 flags &= ~FLAG_LEAVE;