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>
35 using lyx::support::changeExtension;
36 using lyx::support::makeAbsPath;
37 using lyx::support::makeRelPath;
38 using lyx::support::rtrim;
39 using lyx::support::suffixIs;
40 using lyx::support::contains;
41 using lyx::support::subst;
48 using std::ostringstream;
49 using std::istringstream;
53 namespace fs = boost::filesystem;
56 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
57 Context const & context)
59 Context newcontext(true, context.textclass);
60 newcontext.font = context.font;
61 parse_text(p, os, flags, outer, newcontext);
62 newcontext.check_end_layout(os);
68 /// parses a paragraph snippet, useful for example for \\emph{...}
69 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
72 Context newcontext(context);
73 // Don't inherit the extra stuff
74 newcontext.extra_stuff.clear();
75 parse_text(p, os, flags, outer, newcontext);
76 // Make sure that we don't create invalid .lyx files
77 context.need_layout = newcontext.need_layout;
78 context.need_end_layout = newcontext.need_end_layout;
83 * Thin wrapper around parse_text_snippet() using a string.
85 * We completely ignore \c context.need_layout and \c context.need_end_layout,
86 * because our return value is not used directly (otherwise the stream version
87 * of parse_text_snippet() could be used). That means that the caller needs
88 * to do layout management manually.
89 * This is intended to parse text that does not create any layout changes.
91 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
94 Context newcontext(context);
95 newcontext.need_layout = false;
96 newcontext.need_end_layout = false;
97 newcontext.new_layout_allowed = false;
98 // Avoid warning by Context::~Context()
99 newcontext.extra_stuff.clear();
101 parse_text_snippet(p, os, flags, outer, newcontext);
106 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
107 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
111 * We can't put these into known_latex_commands because the argument order
112 * is reversed in lyx if there are 2 arguments.
113 * The starred forms are also known.
115 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
116 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
117 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
121 * We can't put these into known_latex_commands because the argument order
122 * is reversed in lyx if there are 2 arguments.
123 * No starred form other than "cite*" known.
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", "cite*", 0 };
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
135 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
137 /// the same as known_quotes with .lyx names
138 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
139 "grd", "gls", "fls", "frd", 0};
141 /// LaTeX names for font sizes
142 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
145 /// the same as known_sizes with .lyx names
146 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
149 /// LaTeX 2.09 names for font families
150 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
152 /// LaTeX names for font families
153 char const * const known_font_families[] = { "rmfamily", "sffamily",
156 /// the same as known_old_font_families and known_font_families with .lyx names
157 char const * const known_coded_font_families[] = { "roman", "sans",
160 /// LaTeX 2.09 names for font series
161 char const * const known_old_font_series[] = { "bf", 0};
163 /// LaTeX names for font series
164 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
166 /// the same as known_old_font_series and known_font_series with .lyx names
167 char const * const known_coded_font_series[] = { "bold", "medium", 0};
169 /// LaTeX 2.09 names for font shapes
170 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
172 /// LaTeX names for font shapes
173 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
176 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
177 char const * const known_coded_font_shapes[] = { "italic", "slanted",
178 "smallcaps", "up", 0};
181 * Graphics file extensions known by the dvips driver of the graphics package.
182 * These extensions are used to complete the filename of an included
183 * graphics file if it does not contain an extension.
184 * The order must be the same that latex uses to find a file, because we
185 * will use the first extension that matches.
186 * This is only an approximation for the common cases. If we would want to
187 * do it right in all cases, we would need to know which graphics driver is
188 * used and know the extensions of every driver of the graphics package.
190 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
191 "ps.gz", "eps.Z", "ps.Z", 0};
194 * Graphics file extensions known by the pdftex driver of the graphics package.
195 * \sa known_dvips_graphics_formats
197 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
201 * Known file extensions for TeX files as used by \\include.
203 char const * const known_tex_extensions[] = {"tex", 0};
205 /// spaces known by InsetSpace
206 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
207 "qquad", "enspace", "enskip", "negthinspace", 0};
209 /// the same as known_spaces with .lyx names
210 char const * const known_coded_spaces[] = { "space{}", "space{}",
211 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
212 "negthinspace{}", 0};
215 /// splits "x=z, y=b" into a map
216 map<string, string> split_map(string const & s)
218 map<string, string> res;
221 for (size_t i = 0; i < v.size(); ++i) {
222 size_t const pos = v[i].find('=');
223 string const index = v[i].substr(0, pos);
224 string const value = v[i].substr(pos + 1, string::npos);
225 res[trim(index)] = trim(value);
232 * Split a LaTeX length into value and unit.
233 * The latter can be a real unit like "pt", or a latex length variable
234 * like "\textwidth". The unit may contain additional stuff like glue
235 * lengths, but we don't care, because such lengths are ERT anyway.
236 * \returns true if \p value and \p unit are valid.
238 bool splitLatexLength(string const & len, string & value, string & unit)
242 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
243 //'4,5' is a valid LaTeX length number. Change it to '4.5'
244 string const length = subst(len, ',', '.');
245 if (i == string::npos)
248 if (len[0] == '\\') {
249 // We had something like \textwidth without a factor
255 value = trim(string(length, 0, i));
259 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
260 if (contains(len, '\\'))
261 unit = trim(string(len, i));
263 unit = lyx::support::lowercase(trim(string(len, i)));
268 /// A simple function to translate a latex length to something lyx can
269 /// understand. Not perfect, but rather best-effort.
270 bool translate_len(string const & length, string & valstring, string & unit)
272 if (!splitLatexLength(length, valstring, unit))
274 // LyX uses percent values
276 istringstream iss(valstring);
281 string const percentval = oss.str();
283 if (unit.empty() || unit[0] != '\\')
285 string::size_type const i = unit.find(' ');
286 string const endlen = (i == string::npos) ? string() : string(unit, i);
287 if (unit == "\\textwidth") {
288 valstring = percentval;
289 unit = "text%" + endlen;
290 } else if (unit == "\\columnwidth") {
291 valstring = percentval;
292 unit = "col%" + endlen;
293 } else if (unit == "\\paperwidth") {
294 valstring = percentval;
295 unit = "page%" + endlen;
296 } else if (unit == "\\linewidth") {
297 valstring = percentval;
298 unit = "line%" + endlen;
299 } else if (unit == "\\paperheight") {
300 valstring = percentval;
301 unit = "pheight%" + endlen;
302 } else if (unit == "\\textheight") {
303 valstring = percentval;
304 unit = "theight%" + endlen;
312 string translate_len(string const & length)
316 if (translate_len(length, value, unit))
318 // If the input is invalid, return what we have.
326 * Translates a LaTeX length into \p value, \p unit and
327 * \p special parts suitable for a box inset.
328 * The difference from translate_len() is that a box inset knows about
329 * some special "units" that are stored in \p special.
331 void translate_box_len(string const & length, string & value, string & unit, string & special)
333 if (translate_len(length, value, unit)) {
334 if (unit == "\\height" || unit == "\\depth" ||
335 unit == "\\totalheight" || unit == "\\width") {
336 special = unit.substr(1);
337 // The unit is not used, but LyX requires a dummy setting
350 * Find a file with basename \p name in path \p path and an extension
353 string find_file(string const & name, string const & path,
354 char const * const * extensions)
356 for (char const * const * what = extensions; *what; ++what) {
357 // We don't use ChangeExtension() because it does the wrong
358 // thing if name contains a dot.
359 string const trial = name + '.' + (*what);
360 if (fs::exists(makeAbsPath(trial, path)))
367 void begin_inset(ostream & os, string const & name)
369 os << "\n\\begin_inset " << name;
373 void end_inset(ostream & os)
375 os << "\n\\end_inset\n\n";
379 void skip_braces(Parser & p)
381 if (p.next_token().cat() != catBegin)
384 if (p.next_token().cat() == catEnd) {
392 void handle_ert(ostream & os, string const & s, Context & context)
394 // We must have a valid layout before outputting the ERT inset.
395 context.check_layout(os);
396 Context newcontext(true, context.textclass);
397 begin_inset(os, "ERT");
398 os << "\nstatus collapsed\n";
399 newcontext.check_layout(os);
400 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
402 os << "\n\\backslash\n";
403 else if (*it == '\n') {
404 newcontext.new_paragraph(os);
405 newcontext.check_layout(os);
409 newcontext.check_end_layout(os);
414 void handle_comment(ostream & os, string const & s, Context & context)
416 // TODO: Handle this better
417 Context newcontext(true, context.textclass);
418 begin_inset(os, "ERT");
419 os << "\nstatus collapsed\n";
420 newcontext.check_layout(os);
421 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
423 os << "\n\\backslash\n";
427 // make sure that our comment is the last thing on the line
428 newcontext.new_paragraph(os);
429 newcontext.check_layout(os);
430 newcontext.check_end_layout(os);
435 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
437 isLayout(string const name) : name_(name) {}
438 bool operator()(LyXLayout_ptr const & ptr) const {
439 return ptr->latexname() == name_;
446 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
449 LyXTextClass::const_iterator beg = textclass.begin();
450 LyXTextClass::const_iterator end = textclass.end();
452 LyXTextClass::const_iterator
453 it = std::find_if(beg, end, isLayout(name));
455 return (it == end) ? LyXLayout_ptr() : *it;
459 void eat_whitespace(Parser &, ostream &, Context &, bool);
462 void output_command_layout(ostream & os, Parser & p, bool outer,
463 Context & parent_context,
464 LyXLayout_ptr newlayout)
466 parent_context.check_end_layout(os);
467 Context context(true, parent_context.textclass, newlayout,
468 parent_context.layout, parent_context.font);
469 if (parent_context.deeper_paragraph) {
470 // We are beginning a nested environment after a
471 // deeper paragraph inside the outer list environment.
472 // Therefore we don't need to output a "begin deeper".
473 context.need_end_deeper = true;
475 context.check_deeper(os);
476 context.check_layout(os);
477 if (context.layout->optionalargs > 0) {
478 eat_whitespace(p, os, context, false);
479 if (p.next_token().character() == '[') {
480 p.get_token(); // eat '['
481 begin_inset(os, "OptArg\n");
482 os << "status collapsed\n\n";
483 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
485 eat_whitespace(p, os, context, false);
488 parse_text(p, os, FLAG_ITEM, outer, context);
489 context.check_end_layout(os);
490 if (parent_context.deeper_paragraph) {
491 // We must suppress the "end deeper" because we
492 // suppressed the "begin deeper" above.
493 context.need_end_deeper = false;
495 context.check_end_deeper(os);
496 // We don't need really a new paragraph, but
497 // we must make sure that the next item gets a \begin_layout.
498 parent_context.new_paragraph(os);
503 * Output a space if necessary.
504 * This function gets called for every whitespace token.
506 * We have three cases here:
507 * 1. A space must be suppressed. Example: The lyxcode case below
508 * 2. A space may be suppressed. Example: Spaces before "\par"
509 * 3. A space must not be suppressed. Example: A space between two words
511 * We currently handle only 1. and 3 and from 2. only the case of
512 * spaces before newlines as a side effect.
514 * 2. could be used to suppress as many spaces as possible. This has two effects:
515 * - Reimporting LyX generated LaTeX files changes almost no whitespace
516 * - Superflous whitespace from non LyX generated LaTeX files is removed.
517 * The drawback is that the logic inside the function becomes
518 * complicated, and that is the reason why it is not implemented.
520 void check_space(Parser const & p, ostream & os, Context & context)
522 Token const next = p.next_token();
523 Token const curr = p.curr_token();
524 // A space before a single newline and vice versa must be ignored
525 // LyX emits a newline before \end{lyxcode}.
526 // This newline must be ignored,
527 // otherwise LyX will add an additional protected space.
528 if (next.cat() == catSpace ||
529 next.cat() == catNewline ||
530 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
533 context.check_layout(os);
539 * Parse all arguments of \p command
541 void parse_arguments(string const & command,
542 vector<ArgumentType> const & template_arguments,
543 Parser & p, ostream & os, bool outer, Context & context)
545 string ert = command;
546 size_t no_arguments = template_arguments.size();
547 for (size_t i = 0; i < no_arguments; ++i) {
548 switch (template_arguments[i]) {
550 // This argument contains regular LaTeX
551 handle_ert(os, ert + '{', context);
552 eat_whitespace(p, os, context, false);
553 parse_text(p, os, FLAG_ITEM, outer, context);
557 // This argument may contain special characters
558 ert += '{' + p.verbatim_item() + '}';
565 handle_ert(os, ert, context);
570 * Check whether \p command is a known command. If yes,
571 * handle the command with all arguments.
572 * \return true if the command was parsed, false otherwise.
574 bool parse_command(string const & command, Parser & p, ostream & os,
575 bool outer, Context & context)
577 if (known_commands.find(command) != known_commands.end()) {
578 parse_arguments(command, known_commands[command], p, os,
586 /// Parses a minipage or parbox
587 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
588 Context & parent_context, bool use_parbox)
592 string height_value = "0";
593 string height_unit = "pt";
594 string height_special = "none";
596 if (p.next_token().asInput() == "[") {
597 position = p.getArg('[', ']');
598 if (position != "t" && position != "c" && position != "b") {
600 cerr << "invalid position for minipage/parbox" << endl;
602 if (p.next_token().asInput() == "[") {
603 latex_height = p.getArg('[', ']');
604 translate_box_len(latex_height, height_value, height_unit, height_special);
606 if (p.next_token().asInput() == "[") {
607 inner_pos = p.getArg('[', ']');
608 if (inner_pos != "c" && inner_pos != "t" &&
609 inner_pos != "b" && inner_pos != "s") {
610 inner_pos = position;
611 cerr << "invalid inner_pos for minipage/parbox"
619 string const latex_width = p.verbatim_item();
620 translate_len(latex_width, width_value, width_unit);
621 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
622 // LyX can't handle length variables
627 ss << "\\begin{minipage}";
628 if (!position.empty())
629 ss << '[' << position << ']';
630 if (!latex_height.empty())
631 ss << '[' << latex_height << ']';
632 if (!inner_pos.empty())
633 ss << '[' << inner_pos << ']';
634 ss << "{" << latex_width << "}";
637 handle_ert(os, ss.str(), parent_context);
638 parent_context.new_paragraph(os);
639 parse_text_in_inset(p, os, flags, outer, parent_context);
641 handle_ert(os, "}", parent_context);
643 handle_ert(os, "\\end{minipage}", parent_context);
645 // LyX does not like empty positions, so we have
646 // to set them to the LaTeX default values here.
647 if (position.empty())
649 if (inner_pos.empty())
650 inner_pos = position;
651 parent_context.check_layout(os);
652 begin_inset(os, "Box Frameless\n");
653 os << "position \"" << position << "\"\n";
654 os << "hor_pos \"c\"\n";
655 os << "has_inner_box 1\n";
656 os << "inner_pos \"" << inner_pos << "\"\n";
657 os << "use_parbox " << use_parbox << "\n";
658 os << "width \"" << width_value << width_unit << "\"\n";
659 os << "special \"none\"\n";
660 os << "height \"" << height_value << height_unit << "\"\n";
661 os << "height_special \"" << height_special << "\"\n";
662 os << "status open\n\n";
663 parse_text_in_inset(p, os, flags, outer, parent_context);
665 #ifdef PRESERVE_LAYOUT
666 // lyx puts a % after the end of the minipage
667 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
669 //handle_comment(os, "%dummy", parent_context);
672 parent_context.new_paragraph(os);
674 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
675 //handle_comment(os, "%dummy", parent_context);
678 // We add a protected space if something real follows
679 if (p.good() && p.next_token().cat() != catComment) {
680 os << "\\InsetSpace ~\n";
688 /// parse an unknown environment
689 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
690 unsigned flags, bool outer,
691 Context & parent_context)
693 if (name == "tabbing")
694 // We need to remember that we have to handle '\=' specially
695 flags |= FLAG_TABBING;
697 // We need to translate font changes and paragraphs inside the
698 // environment to ERT if we have a non standard font.
699 // Otherwise things like
700 // \large\begin{foo}\huge bar\end{foo}
702 bool const specialfont =
703 (parent_context.font != parent_context.normalfont);
704 bool const new_layout_allowed = parent_context.new_layout_allowed;
706 parent_context.new_layout_allowed = false;
707 handle_ert(os, "\\begin{" + name + "}", parent_context);
708 parse_text_snippet(p, os, flags, outer, parent_context);
709 handle_ert(os, "\\end{" + name + "}", parent_context);
711 parent_context.new_layout_allowed = new_layout_allowed;
715 void parse_environment(Parser & p, ostream & os, bool outer,
716 Context & parent_context)
718 LyXLayout_ptr newlayout;
719 string const name = p.getArg('{', '}');
720 const bool is_starred = suffixIs(name, '*');
721 string const unstarred_name = rtrim(name, "*");
722 active_environments.push_back(name);
724 if (is_math_env(name)) {
725 parent_context.check_layout(os);
726 begin_inset(os, "Formula ");
727 os << "\\begin{" << name << "}";
728 parse_math(p, os, FLAG_END, MATH_MODE);
729 os << "\\end{" << name << "}";
733 else if (name == "tabular" || name == "longtable") {
734 eat_whitespace(p, os, parent_context, false);
735 parent_context.check_layout(os);
736 begin_inset(os, "Tabular ");
737 handle_tabular(p, os, name == "longtable", parent_context);
742 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
743 eat_whitespace(p, os, parent_context, false);
744 parent_context.check_layout(os);
745 begin_inset(os, "Float " + unstarred_name + "\n");
746 if (p.next_token().asInput() == "[") {
747 os << "placement " << p.getArg('[', ']') << '\n';
749 os << "wide " << convert<string>(is_starred)
750 << "\nsideways false"
751 << "\nstatus open\n\n";
752 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
754 // We don't need really a new paragraph, but
755 // we must make sure that the next item gets a \begin_layout.
756 parent_context.new_paragraph(os);
760 else if (name == "minipage") {
761 eat_whitespace(p, os, parent_context, false);
762 parse_box(p, os, FLAG_END, outer, parent_context, false);
766 else if (name == "comment") {
767 eat_whitespace(p, os, parent_context, false);
768 parent_context.check_layout(os);
769 begin_inset(os, "Note Comment\n");
770 os << "status open\n";
771 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
776 else if (name == "lyxgreyedout") {
777 eat_whitespace(p, os, parent_context, false);
778 parent_context.check_layout(os);
779 begin_inset(os, "Note Greyedout\n");
780 os << "status open\n";
781 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
786 else if (!parent_context.new_layout_allowed)
787 parse_unknown_environment(p, name, os, FLAG_END, outer,
790 // Alignment settings
791 else if (name == "center" || name == "flushleft" || name == "flushright" ||
792 name == "centering" || name == "raggedright" || name == "raggedleft") {
793 eat_whitespace(p, os, parent_context, false);
794 // We must begin a new paragraph if not already done
795 if (! parent_context.atParagraphStart()) {
796 parent_context.check_end_layout(os);
797 parent_context.new_paragraph(os);
799 if (name == "flushleft" || name == "raggedright")
800 parent_context.add_extra_stuff("\\align left\n");
801 else if (name == "flushright" || name == "raggedleft")
802 parent_context.add_extra_stuff("\\align right\n");
804 parent_context.add_extra_stuff("\\align center\n");
805 parse_text(p, os, FLAG_END, outer, parent_context);
806 // Just in case the environment is empty ..
807 parent_context.extra_stuff.erase();
808 // We must begin a new paragraph to reset the alignment
809 parent_context.new_paragraph(os);
813 // The single '=' is meant here.
814 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
815 newlayout->isEnvironment()) {
816 eat_whitespace(p, os, parent_context, false);
817 Context context(true, parent_context.textclass, newlayout,
818 parent_context.layout, parent_context.font);
819 if (parent_context.deeper_paragraph) {
820 // We are beginning a nested environment after a
821 // deeper paragraph inside the outer list environment.
822 // Therefore we don't need to output a "begin deeper".
823 context.need_end_deeper = true;
825 parent_context.check_end_layout(os);
826 switch (context.layout->latextype) {
827 case LATEX_LIST_ENVIRONMENT:
828 context.extra_stuff = "\\labelwidthstring "
829 + p.verbatim_item() + '\n';
832 case LATEX_BIB_ENVIRONMENT:
833 p.verbatim_item(); // swallow next arg
839 context.check_deeper(os);
840 parse_text(p, os, FLAG_END, outer, context);
841 context.check_end_layout(os);
842 if (parent_context.deeper_paragraph) {
843 // We must suppress the "end deeper" because we
844 // suppressed the "begin deeper" above.
845 context.need_end_deeper = false;
847 context.check_end_deeper(os);
848 parent_context.new_paragraph(os);
852 else if (name == "appendix") {
853 // This is no good latex style, but it works and is used in some documents...
854 eat_whitespace(p, os, parent_context, false);
855 parent_context.check_end_layout(os);
856 Context context(true, parent_context.textclass, parent_context.layout,
857 parent_context.layout, parent_context.font);
858 context.check_layout(os);
859 os << "\\start_of_appendix\n";
860 parse_text(p, os, FLAG_END, outer, context);
861 context.check_end_layout(os);
865 else if (known_environments.find(name) != known_environments.end()) {
866 vector<ArgumentType> arguments = known_environments[name];
867 // The last "argument" denotes wether we may translate the
868 // environment contents to LyX
869 // The default required if no argument is given makes us
870 // compatible with the reLyXre environment.
871 ArgumentType contents = arguments.empty() ?
874 if (!arguments.empty())
875 arguments.pop_back();
876 // See comment in parse_unknown_environment()
877 bool const specialfont =
878 (parent_context.font != parent_context.normalfont);
879 bool const new_layout_allowed =
880 parent_context.new_layout_allowed;
882 parent_context.new_layout_allowed = false;
883 parse_arguments("\\begin{" + name + "}", arguments, p, os,
884 outer, parent_context);
885 if (contents == verbatim)
886 handle_ert(os, p.verbatimEnvironment(name),
889 parse_text_snippet(p, os, FLAG_END, outer,
891 handle_ert(os, "\\end{" + name + "}", parent_context);
893 parent_context.new_layout_allowed = new_layout_allowed;
897 parse_unknown_environment(p, name, os, FLAG_END, outer,
900 active_environments.pop_back();
904 /// parses a comment and outputs it to \p os.
905 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
907 BOOST_ASSERT(t.cat() == catComment);
908 if (!t.cs().empty()) {
909 context.check_layout(os);
910 handle_comment(os, '%' + t.cs(), context);
911 if (p.next_token().cat() == catNewline) {
912 // A newline after a comment line starts a new
914 if (context.new_layout_allowed) {
915 if(!context.atParagraphStart())
916 // Only start a new paragraph if not already
917 // done (we might get called recursively)
918 context.new_paragraph(os);
920 handle_ert(os, "\n", context);
921 eat_whitespace(p, os, context, true);
931 * Reads spaces and comments until the first non-space, non-comment token.
932 * New paragraphs (double newlines or \\par) are handled like simple spaces
933 * if \p eatParagraph is true.
934 * Spaces are skipped, but comments are written to \p os.
936 void eat_whitespace(Parser & p, ostream & os, Context & context,
940 Token const & t = p.get_token();
941 if (t.cat() == catComment)
942 parse_comment(p, os, t, context);
943 else if ((! eatParagraph && p.isParagraph()) ||
944 (t.cat() != catSpace && t.cat() != catNewline)) {
953 * Set a font attribute, parse text and reset the font attribute.
954 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
955 * \param currentvalue Current value of the attribute. Is set to the new
956 * value during parsing.
957 * \param newvalue New value of the attribute
959 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
960 Context & context, string const & attribute,
961 string & currentvalue, string const & newvalue)
963 context.check_layout(os);
964 string const oldvalue = currentvalue;
965 currentvalue = newvalue;
966 os << '\n' << attribute << ' ' << newvalue << "\n";
967 parse_text_snippet(p, os, flags, outer, context);
968 context.check_layout(os);
969 os << '\n' << attribute << ' ' << oldvalue << "\n";
970 currentvalue = oldvalue;
974 /// get the arguments of a natbib or jurabib citation command
975 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
977 // We need to distinguish "" and "[]", so we can't use p.getOpt().
979 // text before the citation
981 // text after the citation
982 string after = p.getFullOpt();
984 if (!after.empty()) {
985 before = p.getFullOpt();
986 if (natbibOrder && !before.empty())
987 std::swap(before, after);
989 return std::make_pair(before, after);
993 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
994 string const normalize_filename(string const & name)
996 Parser p(trim(name, "\""));
999 Token const & t = p.get_token();
1000 if (t.cat() != catEscape)
1002 else if (t.cs() == "lyxdot") {
1003 // This is used by LyX for simple dots in relative
1007 } else if (t.cs() == "space") {
1017 /// Convert \p name from TeX convention (relative to master file) to LyX
1018 /// convention (relative to .lyx file) if it is relative
1019 void fix_relative_filename(string & name)
1021 if (lyx::support::absolutePath(name))
1023 name = makeRelPath(makeAbsPath(name, getMasterFilePath()),
1024 getParentFilePath());
1028 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1029 void parse_noweb(Parser & p, ostream & os, Context & context)
1031 // assemble the rest of the keyword
1035 Token const & t = p.get_token();
1036 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1039 scrap = (p.good() && p.next_token().asInput() == "=");
1041 name += p.get_token().asInput();
1044 name += t.asInput();
1047 if (!scrap || !context.new_layout_allowed ||
1048 !context.textclass.hasLayout("Scrap")) {
1049 cerr << "Warning: Could not interpret '" << name
1050 << "'. Ignoring it." << endl;
1054 context.check_end_layout(os);
1055 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1056 newcontext.check_layout(os);
1059 Token const & t = p.get_token();
1060 // We abuse the parser a bit, because this is no TeX syntax
1062 if (t.cat() == catEscape)
1063 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1065 os << subst(t.asInput(), "\n", "\n\\newline\n");
1066 // The scrap chunk is ended by an @ at the beginning of a line.
1067 // After the @ the line may contain a comment and/or
1068 // whitespace, but nothing else.
1069 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1070 (p.next_token().cat() == catSpace ||
1071 p.next_token().cat() == catNewline ||
1072 p.next_token().cat() == catComment)) {
1073 while (p.good() && p.next_token().cat() == catSpace)
1074 os << p.get_token().asInput();
1075 if (p.next_token().cat() == catComment)
1076 // The comment includes a final '\n'
1077 os << p.get_token().asInput();
1079 if (p.next_token().cat() == catNewline)
1086 newcontext.check_end_layout(os);
1089 } // anonymous namespace
1092 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1095 LyXLayout_ptr newlayout;
1096 // Store the latest bibliographystyle (needed for bibtex inset)
1097 string bibliographystyle;
1098 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1099 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1101 Token const & t = p.get_token();
1104 cerr << "t: " << t << " flags: " << flags << "\n";
1107 if (flags & FLAG_ITEM) {
1108 if (t.cat() == catSpace)
1111 flags &= ~FLAG_ITEM;
1112 if (t.cat() == catBegin) {
1113 // skip the brace and collect everything to the next matching
1115 flags |= FLAG_BRACE_LAST;
1119 // handle only this single token, leave the loop if done
1120 flags |= FLAG_LEAVE;
1123 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1129 if (t.cat() == catMath) {
1130 // we are inside some text mode thingy, so opening new math is allowed
1131 context.check_layout(os);
1132 begin_inset(os, "Formula ");
1133 Token const & n = p.get_token();
1134 if (n.cat() == catMath && outer) {
1135 // TeX's $$...$$ syntax for displayed math
1137 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1139 p.get_token(); // skip the second '$' token
1141 // simple $...$ stuff
1144 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1150 else if (t.cat() == catSuper || t.cat() == catSub)
1151 cerr << "catcode " << t << " illegal in text mode\n";
1153 // Basic support for english quotes. This should be
1154 // extended to other quotes, but is not so easy (a
1155 // left english quote is the same as a right german
1157 else if (t.asInput() == "`"
1158 && p.next_token().asInput() == "`") {
1159 context.check_layout(os);
1160 begin_inset(os, "Quotes ");
1166 else if (t.asInput() == "'"
1167 && p.next_token().asInput() == "'") {
1168 context.check_layout(os);
1169 begin_inset(os, "Quotes ");
1176 else if (t.asInput() == "<"
1177 && p.next_token().asInput() == "<" && noweb_mode) {
1179 parse_noweb(p, os, context);
1182 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1183 check_space(p, os, context);
1185 else if (t.character() == '[' && noweb_mode &&
1186 p.next_token().character() == '[') {
1187 // These can contain underscores
1189 string const s = p.getFullOpt() + ']';
1190 if (p.next_token().character() == ']')
1193 cerr << "Warning: Inserting missing ']' in '"
1194 << s << "'." << endl;
1195 handle_ert(os, s, context);
1198 else if (t.cat() == catLetter ||
1199 t.cat() == catOther ||
1200 t.cat() == catAlign ||
1201 t.cat() == catParameter) {
1202 // This translates "&" to "\\&" which may be wrong...
1203 context.check_layout(os);
1204 os << t.character();
1207 else if (p.isParagraph()) {
1208 if (context.new_layout_allowed)
1209 context.new_paragraph(os);
1211 handle_ert(os, "\\par ", context);
1212 eat_whitespace(p, os, context, true);
1215 else if (t.cat() == catActive) {
1216 context.check_layout(os);
1217 if (t.character() == '~') {
1218 if (context.layout->free_spacing)
1221 os << "\\InsetSpace ~\n";
1223 os << t.character();
1226 else if (t.cat() == catBegin &&
1227 p.next_token().cat() == catEnd) {
1229 Token const prev = p.prev_token();
1231 if (p.next_token().character() == '`' ||
1232 (prev.character() == '-' &&
1233 p.next_token().character() == '-'))
1234 ; // ignore it in {}`` or -{}-
1236 handle_ert(os, "{}", context);
1240 else if (t.cat() == catBegin) {
1241 context.check_layout(os);
1242 // special handling of font attribute changes
1243 Token const prev = p.prev_token();
1244 Token const next = p.next_token();
1245 Font const oldFont = context.font;
1246 if (next.character() == '[' ||
1247 next.character() == ']' ||
1248 next.character() == '*') {
1250 if (p.next_token().cat() == catEnd) {
1251 os << next.character();
1255 handle_ert(os, "{", context);
1256 parse_text_snippet(p, os,
1259 handle_ert(os, "}", context);
1261 } else if (! context.new_layout_allowed) {
1262 handle_ert(os, "{", context);
1263 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1265 handle_ert(os, "}", context);
1266 } else if (is_known(next.cs(), known_sizes)) {
1267 // next will change the size, so we must
1269 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1271 if (!context.atParagraphStart())
1273 << context.font.size << "\n";
1274 } else if (is_known(next.cs(), known_font_families)) {
1275 // next will change the font family, so we
1276 // must reset it here
1277 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1279 if (!context.atParagraphStart())
1281 << context.font.family << "\n";
1282 } else if (is_known(next.cs(), known_font_series)) {
1283 // next will change the font series, so we
1284 // must reset it here
1285 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1287 if (!context.atParagraphStart())
1289 << context.font.series << "\n";
1290 } else if (is_known(next.cs(), known_font_shapes)) {
1291 // next will change the font shape, so we
1292 // must reset it here
1293 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1295 if (!context.atParagraphStart())
1297 << context.font.shape << "\n";
1298 } else if (is_known(next.cs(), known_old_font_families) ||
1299 is_known(next.cs(), known_old_font_series) ||
1300 is_known(next.cs(), known_old_font_shapes)) {
1301 // next will change the font family, series
1302 // and shape, so we must reset it here
1303 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1305 if (!context.atParagraphStart())
1307 << context.font.family
1309 << context.font.series
1311 << context.font.shape << "\n";
1313 handle_ert(os, "{", context);
1314 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1316 handle_ert(os, "}", context);
1320 else if (t.cat() == catEnd) {
1321 if (flags & FLAG_BRACE_LAST) {
1324 cerr << "stray '}' in text\n";
1325 handle_ert(os, "}", context);
1328 else if (t.cat() == catComment)
1329 parse_comment(p, os, t, context);
1332 // control sequences
1335 else if (t.cs() == "(") {
1336 context.check_layout(os);
1337 begin_inset(os, "Formula");
1339 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1344 else if (t.cs() == "[") {
1345 context.check_layout(os);
1346 begin_inset(os, "Formula");
1348 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1353 else if (t.cs() == "begin")
1354 parse_environment(p, os, outer, context);
1356 else if (t.cs() == "end") {
1357 if (flags & FLAG_END) {
1358 // eat environment name
1359 string const name = p.getArg('{', '}');
1360 if (name != active_environment())
1361 cerr << "\\end{" + name + "} does not match \\begin{"
1362 + active_environment() + "}\n";
1365 p.error("found 'end' unexpectedly");
1368 else if (t.cs() == "item") {
1371 bool optarg = false;
1372 if (p.next_token().character() == '[') {
1373 p.get_token(); // eat '['
1374 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1379 context.check_layout(os);
1380 if (context.has_item) {
1381 // An item in an unknown list-like environment
1382 // FIXME: Do this in check_layout()!
1383 context.has_item = false;
1385 handle_ert(os, "\\item", context);
1387 handle_ert(os, "\\item ", context);
1390 if (context.layout->labeltype != LABEL_MANUAL) {
1391 // lyx does not support \item[\mybullet]
1392 // in itemize environments
1393 handle_ert(os, "[", context);
1395 handle_ert(os, "]", context);
1396 } else if (!s.empty()) {
1397 // The space is needed to separate the
1398 // item from the rest of the sentence.
1400 eat_whitespace(p, os, context, false);
1405 else if (t.cs() == "bibitem") {
1407 context.check_layout(os);
1410 os << '{' << p.verbatim_item() << '}' << "\n";
1413 else if (t.cs() == "def") {
1414 context.check_layout(os);
1415 eat_whitespace(p, os, context, false);
1416 string name = p.get_token().cs();
1417 while (p.next_token().cat() != catBegin)
1418 name += p.get_token().asString();
1419 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1422 else if (t.cs() == "noindent") {
1424 context.add_extra_stuff("\\noindent\n");
1427 else if (t.cs() == "appendix") {
1428 context.add_extra_stuff("\\start_of_appendix\n");
1429 // We need to start a new paragraph. Otherwise the
1430 // appendix in 'bla\appendix\chapter{' would start
1432 context.new_paragraph(os);
1433 // We need to make sure that the paragraph is
1434 // generated even if it is empty. Otherwise the
1435 // appendix in '\par\appendix\par\chapter{' would
1437 context.check_layout(os);
1438 // FIXME: This is a hack to prevent paragraph
1439 // deletion if it is empty. Handle this better!
1441 "%dummy comment inserted by tex2lyx to "
1442 "ensure that this paragraph is not empty",
1444 // Both measures above may generate an additional
1445 // empty paragraph, but that does not hurt, because
1446 // whitespace does not matter here.
1447 eat_whitespace(p, os, context, true);
1450 // Must attempt to parse "Section*" before "Section".
1451 else if ((p.next_token().asInput() == "*") &&
1452 context.new_layout_allowed &&
1453 // The single '=' is meant here.
1454 (newlayout = findLayout(context.textclass,
1455 t.cs() + '*')).get() &&
1456 newlayout->isCommand()) {
1458 output_command_layout(os, p, outer, context, newlayout);
1462 // The single '=' is meant here.
1463 else if (context.new_layout_allowed &&
1464 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1465 newlayout->isCommand()) {
1466 output_command_layout(os, p, outer, context, newlayout);
1470 else if (t.cs() == "includegraphics") {
1471 bool const clip = p.next_token().asInput() == "*";
1474 map<string, string> opts = split_map(p.getArg('[', ']'));
1476 opts["clip"] = string();
1477 string name = normalize_filename(p.verbatim_item());
1479 string const path = getMasterFilePath();
1480 // We want to preserve relative / absolute filenames,
1481 // therefore path is only used for testing
1482 if (!fs::exists(makeAbsPath(name, path))) {
1483 // The file extension is probably missing.
1484 // Now try to find it out.
1485 string const dvips_name =
1486 find_file(name, path,
1487 known_dvips_graphics_formats);
1488 string const pdftex_name =
1489 find_file(name, path,
1490 known_pdftex_graphics_formats);
1491 if (!dvips_name.empty()) {
1492 if (!pdftex_name.empty()) {
1493 cerr << "This file contains the "
1495 "\"\\includegraphics{"
1497 "However, files\n\""
1498 << dvips_name << "\" and\n\""
1499 << pdftex_name << "\"\n"
1500 "both exist, so I had to make a "
1501 "choice and took the first one.\n"
1502 "Please move the unwanted one "
1503 "someplace else and try again\n"
1504 "if my choice was wrong."
1508 } else if (!pdftex_name.empty())
1512 if (fs::exists(makeAbsPath(name, path)))
1513 fix_relative_filename(name);
1515 cerr << "Warning: Could not find graphics file '"
1516 << name << "'." << endl;
1518 context.check_layout(os);
1519 begin_inset(os, "Graphics ");
1520 os << "\n\tfilename " << name << '\n';
1521 if (opts.find("width") != opts.end())
1523 << translate_len(opts["width"]) << '\n';
1524 if (opts.find("height") != opts.end())
1526 << translate_len(opts["height"]) << '\n';
1527 if (opts.find("scale") != opts.end()) {
1528 istringstream iss(opts["scale"]);
1532 os << "\tscale " << val << '\n';
1534 if (opts.find("angle") != opts.end())
1535 os << "\trotateAngle "
1536 << opts["angle"] << '\n';
1537 if (opts.find("origin") != opts.end()) {
1539 string const opt = opts["origin"];
1540 if (opt.find('l') != string::npos) ss << "left";
1541 if (opt.find('r') != string::npos) ss << "right";
1542 if (opt.find('c') != string::npos) ss << "center";
1543 if (opt.find('t') != string::npos) ss << "Top";
1544 if (opt.find('b') != string::npos) ss << "Bottom";
1545 if (opt.find('B') != string::npos) ss << "Baseline";
1546 if (!ss.str().empty())
1547 os << "\trotateOrigin " << ss.str() << '\n';
1549 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1551 if (opts.find("keepaspectratio") != opts.end())
1552 os << "\tkeepAspectRatio\n";
1553 if (opts.find("clip") != opts.end())
1555 if (opts.find("draft") != opts.end())
1557 if (opts.find("bb") != opts.end())
1558 os << "\tBoundingBox "
1559 << opts["bb"] << '\n';
1560 int numberOfbbOptions = 0;
1561 if (opts.find("bbllx") != opts.end())
1562 numberOfbbOptions++;
1563 if (opts.find("bblly") != opts.end())
1564 numberOfbbOptions++;
1565 if (opts.find("bburx") != opts.end())
1566 numberOfbbOptions++;
1567 if (opts.find("bbury") != opts.end())
1568 numberOfbbOptions++;
1569 if (numberOfbbOptions == 4)
1570 os << "\tBoundingBox "
1571 << opts["bbllx"] << opts["bblly"]
1572 << opts["bburx"] << opts["bbury"] << '\n';
1573 else if (numberOfbbOptions > 0)
1574 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1575 numberOfbbOptions = 0;
1576 if (opts.find("natwidth") != opts.end())
1577 numberOfbbOptions++;
1578 if (opts.find("natheight") != opts.end())
1579 numberOfbbOptions++;
1580 if (numberOfbbOptions == 2)
1581 os << "\tBoundingBox 0bp 0bp "
1582 << opts["natwidth"] << opts["natheight"] << '\n';
1583 else if (numberOfbbOptions > 0)
1584 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1585 ostringstream special;
1586 if (opts.find("hiresbb") != opts.end())
1587 special << "hiresbb,";
1588 if (opts.find("trim") != opts.end())
1590 if (opts.find("viewport") != opts.end())
1591 special << "viewport=" << opts["viewport"] << ',';
1592 if (opts.find("totalheight") != opts.end())
1593 special << "totalheight=" << opts["totalheight"] << ',';
1594 if (opts.find("type") != opts.end())
1595 special << "type=" << opts["type"] << ',';
1596 if (opts.find("ext") != opts.end())
1597 special << "ext=" << opts["ext"] << ',';
1598 if (opts.find("read") != opts.end())
1599 special << "read=" << opts["read"] << ',';
1600 if (opts.find("command") != opts.end())
1601 special << "command=" << opts["command"] << ',';
1602 string s_special = special.str();
1603 if (!s_special.empty()) {
1604 // We had special arguments. Remove the trailing ','.
1605 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1607 // TODO: Handle the unknown settings better.
1608 // Warn about invalid options.
1609 // Check whether some option was given twice.
1613 else if (t.cs() == "footnote" ||
1614 (t.cs() == "thanks" && context.layout->intitle)) {
1616 context.check_layout(os);
1617 begin_inset(os, "Foot\n");
1618 os << "status collapsed\n\n";
1619 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1623 else if (t.cs() == "marginpar") {
1625 context.check_layout(os);
1626 begin_inset(os, "Marginal\n");
1627 os << "status collapsed\n\n";
1628 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1632 else if (t.cs() == "ensuremath") {
1634 context.check_layout(os);
1635 string const s = p.verbatim_item();
1636 if (s == "±" || s == "³" || s == "²" || s == "µ")
1639 handle_ert(os, "\\ensuremath{" + s + "}",
1643 else if (t.cs() == "hfill") {
1644 context.check_layout(os);
1645 os << "\n\\hfill\n";
1650 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1651 // FIXME: Somehow prevent title layouts if
1652 // "maketitle" was not found
1654 skip_braces(p); // swallow this
1657 else if (t.cs() == "tableofcontents") {
1659 context.check_layout(os);
1660 begin_inset(os, "LatexCommand \\tableofcontents\n");
1662 skip_braces(p); // swallow this
1665 else if (t.cs() == "listoffigures") {
1667 context.check_layout(os);
1668 begin_inset(os, "FloatList figure\n");
1670 skip_braces(p); // swallow this
1673 else if (t.cs() == "listoftables") {
1675 context.check_layout(os);
1676 begin_inset(os, "FloatList table\n");
1678 skip_braces(p); // swallow this
1681 else if (t.cs() == "listof") {
1682 p.skip_spaces(true);
1683 string const name = p.get_token().asString();
1684 if (context.textclass.floats().typeExist(name)) {
1685 context.check_layout(os);
1686 begin_inset(os, "FloatList ");
1689 p.get_token(); // swallow second arg
1691 handle_ert(os, "\\listof{" + name + "}", context);
1694 else if (t.cs() == "textrm")
1695 parse_text_attributes(p, os, FLAG_ITEM, outer,
1696 context, "\\family",
1697 context.font.family, "roman");
1699 else if (t.cs() == "textsf")
1700 parse_text_attributes(p, os, FLAG_ITEM, outer,
1701 context, "\\family",
1702 context.font.family, "sans");
1704 else if (t.cs() == "texttt")
1705 parse_text_attributes(p, os, FLAG_ITEM, outer,
1706 context, "\\family",
1707 context.font.family, "typewriter");
1709 else if (t.cs() == "textmd")
1710 parse_text_attributes(p, os, FLAG_ITEM, outer,
1711 context, "\\series",
1712 context.font.series, "medium");
1714 else if (t.cs() == "textbf")
1715 parse_text_attributes(p, os, FLAG_ITEM, outer,
1716 context, "\\series",
1717 context.font.series, "bold");
1719 else if (t.cs() == "textup")
1720 parse_text_attributes(p, os, FLAG_ITEM, outer,
1722 context.font.shape, "up");
1724 else if (t.cs() == "textit")
1725 parse_text_attributes(p, os, FLAG_ITEM, outer,
1727 context.font.shape, "italic");
1729 else if (t.cs() == "textsl")
1730 parse_text_attributes(p, os, FLAG_ITEM, outer,
1732 context.font.shape, "slanted");
1734 else if (t.cs() == "textsc")
1735 parse_text_attributes(p, os, FLAG_ITEM, outer,
1737 context.font.shape, "smallcaps");
1739 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1740 context.check_layout(os);
1741 Font oldFont = context.font;
1742 context.font.init();
1743 context.font.size = oldFont.size;
1744 os << "\n\\family " << context.font.family << "\n";
1745 os << "\n\\series " << context.font.series << "\n";
1746 os << "\n\\shape " << context.font.shape << "\n";
1747 if (t.cs() == "textnormal") {
1748 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1749 output_font_change(os, context.font, oldFont);
1750 context.font = oldFont;
1752 eat_whitespace(p, os, context, false);
1755 else if (t.cs() == "underbar") {
1756 // Do NOT handle \underline.
1757 // \underbar cuts through y, g, q, p etc.,
1758 // \underline does not.
1759 context.check_layout(os);
1760 os << "\n\\bar under\n";
1761 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1762 context.check_layout(os);
1763 os << "\n\\bar default\n";
1766 else if (t.cs() == "emph" || t.cs() == "noun") {
1767 context.check_layout(os);
1768 os << "\n\\" << t.cs() << " on\n";
1769 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1770 context.check_layout(os);
1771 os << "\n\\" << t.cs() << " default\n";
1774 else if (use_natbib &&
1775 is_known(t.cs(), known_natbib_commands) &&
1776 ((t.cs() != "citefullauthor" &&
1777 t.cs() != "citeyear" &&
1778 t.cs() != "citeyearpar") ||
1779 p.next_token().asInput() != "*")) {
1780 context.check_layout(os);
1782 // \citet[before][after]{a} \citet[after][before]{a}
1783 // \citet[before][]{a} \citet[][before]{a}
1784 // \citet[after]{a} \citet[after]{a}
1785 // \citet{a} \citet{a}
1786 string command = '\\' + t.cs();
1787 if (p.next_token().asInput() == "*") {
1791 if (command == "\\citefullauthor")
1792 // alternative name for "\\citeauthor*"
1793 command = "\\citeauthor*";
1795 // text before the citation
1797 // text after the citation
1800 boost::tie(before, after) = getCiteArguments(p, true);
1801 if (command == "\\cite") {
1802 // \cite without optional argument means
1803 // \citet, \cite with at least one optional
1804 // argument means \citep.
1805 if (before.empty() && after.empty())
1806 command = "\\citet";
1808 command = "\\citep";
1810 if (before.empty() && after == "[]")
1811 // avoid \citet[]{a}
1813 else if (before == "[]" && after == "[]") {
1814 // avoid \citet[][]{a}
1818 begin_inset(os, "LatexCommand ");
1819 os << command << after << before
1820 << '{' << p.verbatim_item() << "}\n";
1824 else if (use_jurabib &&
1825 is_known(t.cs(), known_jurabib_commands)) {
1826 context.check_layout(os);
1827 string const command = '\\' + t.cs();
1828 char argumentOrder = '\0';
1829 vector<string> const & options = used_packages["jurabib"];
1830 if (std::find(options.begin(), options.end(),
1831 "natbiborder") != options.end())
1832 argumentOrder = 'n';
1833 else if (std::find(options.begin(), options.end(),
1834 "jurabiborder") != options.end())
1835 argumentOrder = 'j';
1837 // text before the citation
1839 // text after the citation
1842 boost::tie(before, after) =
1843 getCiteArguments(p, argumentOrder != 'j');
1844 string const citation = p.verbatim_item();
1845 if (!before.empty() && argumentOrder == '\0') {
1846 cerr << "Warning: Assuming argument order "
1847 "of jurabib version 0.6 for\n'"
1848 << command << before << after << '{'
1849 << citation << "}'.\n"
1850 "Add 'jurabiborder' to the jurabib "
1851 "package options if you used an\n"
1852 "earlier jurabib version." << endl;
1854 begin_inset(os, "LatexCommand ");
1855 os << command << after << before
1856 << '{' << citation << "}\n";
1860 else if (is_known(t.cs(), known_latex_commands)) {
1861 // This needs to be after the check for natbib and
1862 // jurabib commands, because "cite" has different
1863 // arguments with natbib and jurabib.
1864 context.check_layout(os);
1865 begin_inset(os, "LatexCommand ");
1866 os << '\\' << t.cs();
1867 // lyx cannot handle newlines in a latex command
1868 // FIXME: Move the substitution into parser::getOpt()?
1869 os << subst(p.getOpt(), "\n", " ");
1870 os << subst(p.getOpt(), "\n", " ");
1871 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1875 else if (is_known(t.cs(), known_quotes)) {
1876 char const * const * where = is_known(t.cs(), known_quotes);
1877 context.check_layout(os);
1878 begin_inset(os, "Quotes ");
1879 os << known_coded_quotes[where - known_quotes];
1881 // LyX adds {} after the quote, so we have to eat
1882 // spaces here if there are any before a possible
1884 eat_whitespace(p, os, context, false);
1888 else if (is_known(t.cs(), known_sizes) &&
1889 context.new_layout_allowed) {
1890 char const * const * where = is_known(t.cs(), known_sizes);
1891 context.check_layout(os);
1892 Font const oldFont = context.font;
1893 context.font.size = known_coded_sizes[where - known_sizes];
1894 output_font_change(os, oldFont, context.font);
1895 eat_whitespace(p, os, context, false);
1898 else if (is_known(t.cs(), known_font_families) &&
1899 context.new_layout_allowed) {
1900 char const * const * where =
1901 is_known(t.cs(), known_font_families);
1902 context.check_layout(os);
1903 Font const oldFont = context.font;
1904 context.font.family =
1905 known_coded_font_families[where - known_font_families];
1906 output_font_change(os, oldFont, context.font);
1907 eat_whitespace(p, os, context, false);
1910 else if (is_known(t.cs(), known_font_series) &&
1911 context.new_layout_allowed) {
1912 char const * const * where =
1913 is_known(t.cs(), known_font_series);
1914 context.check_layout(os);
1915 Font const oldFont = context.font;
1916 context.font.series =
1917 known_coded_font_series[where - known_font_series];
1918 output_font_change(os, oldFont, context.font);
1919 eat_whitespace(p, os, context, false);
1922 else if (is_known(t.cs(), known_font_shapes) &&
1923 context.new_layout_allowed) {
1924 char const * const * where =
1925 is_known(t.cs(), known_font_shapes);
1926 context.check_layout(os);
1927 Font const oldFont = context.font;
1928 context.font.shape =
1929 known_coded_font_shapes[where - known_font_shapes];
1930 output_font_change(os, oldFont, context.font);
1931 eat_whitespace(p, os, context, false);
1933 else if (is_known(t.cs(), known_old_font_families) &&
1934 context.new_layout_allowed) {
1935 char const * const * where =
1936 is_known(t.cs(), known_old_font_families);
1937 context.check_layout(os);
1938 Font const oldFont = context.font;
1939 context.font.init();
1940 context.font.size = oldFont.size;
1941 context.font.family =
1942 known_coded_font_families[where - known_old_font_families];
1943 output_font_change(os, oldFont, context.font);
1944 eat_whitespace(p, os, context, false);
1947 else if (is_known(t.cs(), known_old_font_series) &&
1948 context.new_layout_allowed) {
1949 char const * const * where =
1950 is_known(t.cs(), known_old_font_series);
1951 context.check_layout(os);
1952 Font const oldFont = context.font;
1953 context.font.init();
1954 context.font.size = oldFont.size;
1955 context.font.series =
1956 known_coded_font_series[where - known_old_font_series];
1957 output_font_change(os, oldFont, context.font);
1958 eat_whitespace(p, os, context, false);
1961 else if (is_known(t.cs(), known_old_font_shapes) &&
1962 context.new_layout_allowed) {
1963 char const * const * where =
1964 is_known(t.cs(), known_old_font_shapes);
1965 context.check_layout(os);
1966 Font const oldFont = context.font;
1967 context.font.init();
1968 context.font.size = oldFont.size;
1969 context.font.shape =
1970 known_coded_font_shapes[where - known_old_font_shapes];
1971 output_font_change(os, oldFont, context.font);
1972 eat_whitespace(p, os, context, false);
1975 else if (t.cs() == "LyX" || t.cs() == "TeX"
1976 || t.cs() == "LaTeX") {
1977 context.check_layout(os);
1979 skip_braces(p); // eat {}
1982 else if (t.cs() == "LaTeXe") {
1983 context.check_layout(os);
1985 skip_braces(p); // eat {}
1988 else if (t.cs() == "ldots") {
1989 context.check_layout(os);
1991 os << "\\SpecialChar \\ldots{}\n";
1994 else if (t.cs() == "lyxarrow") {
1995 context.check_layout(os);
1996 os << "\\SpecialChar \\menuseparator\n";
2000 else if (t.cs() == "textcompwordmark") {
2001 context.check_layout(os);
2002 os << "\\SpecialChar \\textcompwordmark{}\n";
2006 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2007 context.check_layout(os);
2008 os << "\\SpecialChar \\@.\n";
2012 else if (t.cs() == "-") {
2013 context.check_layout(os);
2014 os << "\\SpecialChar \\-\n";
2017 else if (t.cs() == "textasciitilde") {
2018 context.check_layout(os);
2023 else if (t.cs() == "textasciicircum") {
2024 context.check_layout(os);
2029 else if (t.cs() == "textbackslash") {
2030 context.check_layout(os);
2031 os << "\n\\backslash\n";
2035 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2036 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2038 context.check_layout(os);
2042 else if (t.cs() == "char") {
2043 context.check_layout(os);
2044 if (p.next_token().character() == '`') {
2046 if (p.next_token().cs() == "\"") {
2051 handle_ert(os, "\\char`", context);
2054 handle_ert(os, "\\char", context);
2058 else if (t.cs() == "verb") {
2059 context.check_layout(os);
2060 char const delimiter = p.next_token().character();
2061 string const arg = p.getArg(delimiter, delimiter);
2063 oss << "\\verb" << delimiter << arg << delimiter;
2064 handle_ert(os, oss.str(), context);
2067 else if (t.cs() == "\"") {
2068 context.check_layout(os);
2069 string const name = p.verbatim_item();
2070 if (name == "a") os << 'ä';
2071 else if (name == "o") os << 'ö';
2072 else if (name == "u") os << 'ü';
2073 else if (name == "A") os << 'Ä';
2074 else if (name == "O") os << 'Ö';
2075 else if (name == "U") os << 'Ü';
2076 else handle_ert(os, "\"{" + name + "}", context);
2079 // Problem: \= creates a tabstop inside the tabbing environment
2080 // and else an accent. In the latter case we really would want
2081 // \={o} instead of \= o.
2082 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2083 handle_ert(os, t.asInput(), context);
2085 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2086 || t.cs() == "'" || t.cs() == "`"
2087 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2088 // we need the trim as the LyX parser chokes on such spaces
2089 context.check_layout(os);
2090 os << "\n\\i \\" << t.cs() << "{"
2091 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2095 else if (t.cs() == "ss") {
2096 context.check_layout(os);
2098 skip_braces(p); // eat {}
2101 else if (t.cs() == "i" || t.cs() == "j") {
2102 context.check_layout(os);
2103 os << "\\" << t.cs() << ' ';
2104 skip_braces(p); // eat {}
2107 else if (t.cs() == "\\") {
2108 context.check_layout(os);
2109 string const next = p.next_token().asInput();
2111 handle_ert(os, "\\\\" + p.getOpt(), context);
2112 else if (next == "*") {
2114 handle_ert(os, "\\\\*" + p.getOpt(), context);
2117 os << "\n\\newline\n";
2121 else if (t.cs() == "input" || t.cs() == "include"
2122 || t.cs() == "verbatiminput") {
2123 string name = '\\' + t.cs();
2124 if (t.cs() == "verbatiminput"
2125 && p.next_token().asInput() == "*")
2126 name += p.get_token().asInput();
2127 context.check_layout(os);
2128 begin_inset(os, "Include ");
2129 string filename(normalize_filename(p.getArg('{', '}')));
2130 string const path = getMasterFilePath();
2131 // We want to preserve relative / absolute filenames,
2132 // therefore path is only used for testing
2133 if (t.cs() == "include" &&
2134 !fs::exists(makeAbsPath(filename, path))) {
2135 // The file extension is probably missing.
2136 // Now try to find it out.
2137 string const tex_name =
2138 find_file(filename, path,
2139 known_tex_extensions);
2140 if (!tex_name.empty())
2141 filename = tex_name;
2143 if (fs::exists(makeAbsPath(filename, path))) {
2144 string const abstexname =
2145 makeAbsPath(filename, path);
2146 string const abslyxname =
2147 changeExtension(abstexname, ".lyx");
2148 fix_relative_filename(filename);
2149 string const lyxname =
2150 changeExtension(filename, ".lyx");
2151 if (t.cs() != "verbatiminput" &&
2152 tex2lyx(abstexname, abslyxname)) {
2153 os << name << '{' << lyxname << "}\n";
2155 os << name << '{' << filename << "}\n";
2158 cerr << "Warning: Could not find included file '"
2159 << filename << "'." << endl;
2160 os << name << '{' << filename << "}\n";
2162 os << "preview false\n";
2166 else if (t.cs() == "bibliographystyle") {
2167 // store new bibliographystyle
2168 bibliographystyle = p.verbatim_item();
2169 // output new bibliographystyle.
2170 // This is only necessary if used in some other macro than \bibliography.
2171 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2174 else if (t.cs() == "bibliography") {
2175 context.check_layout(os);
2176 begin_inset(os, "LatexCommand ");
2178 // Do we have a bibliographystyle set?
2179 if (!bibliographystyle.empty()) {
2180 os << '[' << bibliographystyle << ']';
2182 os << '{' << p.verbatim_item() << "}\n";
2186 else if (t.cs() == "parbox")
2187 parse_box(p, os, FLAG_ITEM, outer, context, true);
2189 else if (t.cs() == "smallskip" ||
2190 t.cs() == "medskip" ||
2191 t.cs() == "bigskip" ||
2192 t.cs() == "vfill") {
2193 context.check_layout(os);
2194 begin_inset(os, "VSpace ");
2200 else if (is_known(t.cs(), known_spaces)) {
2201 char const * const * where = is_known(t.cs(), known_spaces);
2202 context.check_layout(os);
2203 begin_inset(os, "InsetSpace ");
2204 os << '\\' << known_coded_spaces[where - known_spaces]
2206 // LaTeX swallows whitespace after all spaces except
2207 // "\\,". We have to do that here, too, because LyX
2208 // adds "{}" which would make the spaces significant.
2210 eat_whitespace(p, os, context, false);
2211 // LyX adds "{}" after all spaces except "\\ " and
2212 // "\\,", so we have to remove "{}".
2213 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2214 // remove the braces after "\\,", too.
2219 else if (t.cs() == "newpage") {
2220 context.check_layout(os);
2221 // FIXME: what about \\clearpage and \\pagebreak?
2222 os << "\n\\newpage\n";
2223 skip_braces(p); // eat {}
2226 else if (t.cs() == "newcommand" ||
2227 t.cs() == "providecommand" ||
2228 t.cs() == "renewcommand") {
2229 // these could be handled by parse_command(), but
2230 // we need to call add_known_command() here.
2231 string name = t.asInput();
2232 if (p.next_token().asInput() == "*") {
2233 // Starred form. Eat '*'
2237 string const command = p.verbatim_item();
2238 string const opt1 = p.getOpt();
2239 string const opt2 = p.getFullOpt();
2240 add_known_command(command, opt1, !opt2.empty());
2241 string const ert = name + '{' + command + '}' +
2243 '{' + p.verbatim_item() + '}';
2244 handle_ert(os, ert, context);
2247 else if (t.cs() == "vspace") {
2248 bool starred = false;
2249 if (p.next_token().asInput() == "*") {
2253 string const length = p.verbatim_item();
2256 bool valid = splitLatexLength(length, valstring, unit);
2257 bool known_vspace = false;
2258 bool known_unit = false;
2261 istringstream iss(valstring);
2264 if (unit == "\\smallskipamount") {
2266 known_vspace = true;
2267 } else if (unit == "\\medskipamount") {
2269 known_vspace = true;
2270 } else if (unit == "\\bigskipamount") {
2272 known_vspace = true;
2273 } else if (unit == "\\fill") {
2275 known_vspace = true;
2278 if (!known_vspace) {
2279 switch (unitFromString(unit)) {
2300 if (known_unit || known_vspace) {
2301 // Literal length or known variable
2302 context.check_layout(os);
2303 begin_inset(os, "VSpace ");
2311 // LyX can't handle other length variables in Inset VSpace
2312 string name = t.asInput();
2317 handle_ert(os, name + '{' + unit + '}', context);
2318 else if (value == -1.0)
2319 handle_ert(os, name + "{-" + unit + '}', context);
2321 handle_ert(os, name + '{' + valstring + unit + '}', context);
2323 handle_ert(os, name + '{' + length + '}', context);
2328 //cerr << "#: " << t << " mode: " << mode << endl;
2329 // heuristic: read up to next non-nested space
2331 string s = t.asInput();
2332 string z = p.verbatim_item();
2333 while (p.good() && z != " " && z.size()) {
2334 //cerr << "read: " << z << endl;
2336 z = p.verbatim_item();
2338 cerr << "found ERT: " << s << endl;
2339 handle_ert(os, s + ' ', context);
2341 string name = t.asInput();
2342 if (p.next_token().asInput() == "*") {
2343 // Starred commands like \vspace*{}
2344 p.get_token(); // Eat '*'
2347 if (! parse_command(name, p, os, outer, context))
2348 handle_ert(os, name, context);
2351 if (flags & FLAG_LEAVE) {
2352 flags &= ~FLAG_LEAVE;