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",
124 // jurabib commands not (yet) supported by LyX:
126 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
127 // "footciteauthor", "footciteyear", "footciteyearpar",
128 "citefield", "citetitle", "cite*", 0 };
130 /// LaTeX names for quotes
131 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
132 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
134 /// the same as known_quotes with .lyx names
135 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
136 "grd", "gls", "fls", "frd", 0};
138 /// LaTeX names for font sizes
139 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
140 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
142 /// the same as known_sizes with .lyx names
143 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
144 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
146 /// LaTeX 2.09 names for font families
147 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
149 /// LaTeX names for font families
150 char const * const known_font_families[] = { "rmfamily", "sffamily",
153 /// the same as known_old_font_families and known_font_families with .lyx names
154 char const * const known_coded_font_families[] = { "roman", "sans",
157 /// LaTeX 2.09 names for font series
158 char const * const known_old_font_series[] = { "bf", 0};
160 /// LaTeX names for font series
161 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
163 /// the same as known_old_font_series and known_font_series with .lyx names
164 char const * const known_coded_font_series[] = { "bold", "medium", 0};
166 /// LaTeX 2.09 names for font shapes
167 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
169 /// LaTeX names for font shapes
170 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
173 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
174 char const * const known_coded_font_shapes[] = { "italic", "slanted",
175 "smallcaps", "up", 0};
178 * Graphics file extensions known by the dvips driver of the graphics package.
179 * These extensions are used to complete the filename of an included
180 * graphics file if it does not contain an extension.
181 * The order must be the same that latex uses to find a file, because we
182 * will use the first extension that matches.
183 * This is only an approximation for the common cases. If we would want to
184 * do it right in all cases, we would need to know which graphics driver is
185 * used and know the extensions of every driver of the graphics package.
187 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
188 "ps.gz", "eps.Z", "ps.Z", 0};
191 * Graphics file extensions known by the pdftex driver of the graphics package.
192 * \sa known_dvips_graphics_formats
194 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
198 * Known file extensions for TeX files as used by \\include.
200 char const * const known_tex_extensions[] = {"tex", 0};
202 /// spaces known by InsetSpace
203 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
204 "qquad", "enspace", "enskip", "negthinspace", 0};
206 /// the same as known_spaces with .lyx names
207 char const * const known_coded_spaces[] = { "space{}", "space{}",
208 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
209 "negthinspace{}", 0};
212 /// splits "x=z, y=b" into a map
213 map<string, string> split_map(string const & s)
215 map<string, string> res;
218 for (size_t i = 0; i < v.size(); ++i) {
219 size_t const pos = v[i].find('=');
220 string const index = v[i].substr(0, pos);
221 string const value = v[i].substr(pos + 1, string::npos);
222 res[trim(index)] = trim(value);
229 * Split a LaTeX length into value and unit.
230 * The latter can be a real unit like "pt", or a latex length variable
231 * like "\textwidth". The unit may contain additional stuff like glue
232 * lengths, but we don't care, because such lengths are ERT anyway.
233 * \returns true if \p value and \p unit are valid.
235 bool splitLatexLength(string const & len, string & value, string & unit)
239 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
240 //'4,5' is a valid LaTeX length number. Change it to '4.5'
241 string const length = subst(len, ',', '.');
242 if (i == string::npos)
245 if (len[0] == '\\') {
246 // We had something like \textwidth without a factor
252 value = trim(string(length, 0, i));
256 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
257 if (contains(len, '\\'))
258 unit = trim(string(len, i));
260 unit = lyx::support::lowercase(trim(string(len, i)));
265 /// A simple function to translate a latex length to something lyx can
266 /// understand. Not perfect, but rather best-effort.
267 bool translate_len(string const & length, string & valstring, string & unit)
269 if (!splitLatexLength(length, valstring, unit))
271 // LyX uses percent values
273 istringstream iss(valstring);
278 string const percentval = oss.str();
280 if (unit.empty() || unit[0] != '\\')
282 string::size_type const i = unit.find(' ');
283 string const endlen = (i == string::npos) ? string() : string(unit, i);
284 if (unit == "\\textwidth") {
285 valstring = percentval;
286 unit = "text%" + endlen;
287 } else if (unit == "\\columnwidth") {
288 valstring = percentval;
289 unit = "col%" + endlen;
290 } else if (unit == "\\paperwidth") {
291 valstring = percentval;
292 unit = "page%" + endlen;
293 } else if (unit == "\\linewidth") {
294 valstring = percentval;
295 unit = "line%" + endlen;
296 } else if (unit == "\\paperheight") {
297 valstring = percentval;
298 unit = "pheight%" + endlen;
299 } else if (unit == "\\textheight") {
300 valstring = percentval;
301 unit = "theight%" + endlen;
309 string translate_len(string const & length)
313 if (translate_len(length, value, unit))
315 // If the input is invalid, return what we have.
323 * Translates a LaTeX length into \p value, \p unit and
324 * \p special parts suitable for a box inset.
325 * The difference from translate_len() is that a box inset knows about
326 * some special "units" that are stored in \p special.
328 void translate_box_len(string const & length, string & value, string & unit, string & special)
330 if (translate_len(length, value, unit)) {
331 if (unit == "\\height" || unit == "\\depth" ||
332 unit == "\\totalheight" || unit == "\\width") {
333 special = unit.substr(1);
334 // The unit is not used, but LyX requires a dummy setting
347 * Find a file with basename \p name in path \p path and an extension
350 string find_file(string const & name, string const & path,
351 char const * const * extensions)
353 for (char const * const * what = extensions; *what; ++what) {
354 // We don't use ChangeExtension() because it does the wrong
355 // thing if name contains a dot.
356 string const trial = name + '.' + (*what);
357 if (fs::exists(makeAbsPath(trial, path)))
364 void begin_inset(ostream & os, string const & name)
366 os << "\n\\begin_inset " << name;
370 void end_inset(ostream & os)
372 os << "\n\\end_inset\n\n";
376 void skip_braces(Parser & p)
378 if (p.next_token().cat() != catBegin)
381 if (p.next_token().cat() == catEnd) {
389 void handle_ert(ostream & os, string const & s, Context & context)
391 // We must have a valid layout before outputting the ERT inset.
392 context.check_layout(os);
393 Context newcontext(true, context.textclass);
394 begin_inset(os, "ERT");
395 os << "\nstatus collapsed\n";
396 newcontext.check_layout(os);
397 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
399 os << "\n\\backslash\n";
400 else if (*it == '\n') {
401 newcontext.new_paragraph(os);
402 newcontext.check_layout(os);
406 newcontext.check_end_layout(os);
411 void handle_comment(ostream & os, string const & s, Context & context)
413 // TODO: Handle this better
414 Context newcontext(true, context.textclass);
415 begin_inset(os, "ERT");
416 os << "\nstatus collapsed\n";
417 newcontext.check_layout(os);
418 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
420 os << "\n\\backslash\n";
424 // make sure that our comment is the last thing on the line
425 newcontext.new_paragraph(os);
426 newcontext.check_layout(os);
427 newcontext.check_end_layout(os);
432 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
434 isLayout(string const name) : name_(name) {}
435 bool operator()(LyXLayout_ptr const & ptr) const {
436 return ptr->latexname() == name_;
443 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
446 LyXTextClass::const_iterator beg = textclass.begin();
447 LyXTextClass::const_iterator end = textclass.end();
449 LyXTextClass::const_iterator
450 it = std::find_if(beg, end, isLayout(name));
452 return (it == end) ? LyXLayout_ptr() : *it;
456 void eat_whitespace(Parser &, ostream &, Context &, bool);
459 void output_command_layout(ostream & os, Parser & p, bool outer,
460 Context & parent_context,
461 LyXLayout_ptr newlayout)
463 parent_context.check_end_layout(os);
464 Context context(true, parent_context.textclass, newlayout,
465 parent_context.layout, parent_context.font);
466 if (parent_context.deeper_paragraph) {
467 // We are beginning a nested environment after a
468 // deeper paragraph inside the outer list environment.
469 // Therefore we don't need to output a "begin deeper".
470 context.need_end_deeper = true;
472 context.check_deeper(os);
473 context.check_layout(os);
474 if (context.layout->optionalargs > 0) {
475 eat_whitespace(p, os, context, false);
476 if (p.next_token().character() == '[') {
477 p.get_token(); // eat '['
478 begin_inset(os, "OptArg\n");
479 os << "status collapsed\n\n";
480 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
482 eat_whitespace(p, os, context, false);
485 parse_text(p, os, FLAG_ITEM, outer, context);
486 context.check_end_layout(os);
487 if (parent_context.deeper_paragraph) {
488 // We must suppress the "end deeper" because we
489 // suppressed the "begin deeper" above.
490 context.need_end_deeper = false;
492 context.check_end_deeper(os);
493 // We don't need really a new paragraph, but
494 // we must make sure that the next item gets a \begin_layout.
495 parent_context.new_paragraph(os);
500 * Output a space if necessary.
501 * This function gets called for every whitespace token.
503 * We have three cases here:
504 * 1. A space must be suppressed. Example: The lyxcode case below
505 * 2. A space may be suppressed. Example: Spaces before "\par"
506 * 3. A space must not be suppressed. Example: A space between two words
508 * We currently handle only 1. and 3 and from 2. only the case of
509 * spaces before newlines as a side effect.
511 * 2. could be used to suppress as many spaces as possible. This has two effects:
512 * - Reimporting LyX generated LaTeX files changes almost no whitespace
513 * - Superflous whitespace from non LyX generated LaTeX files is removed.
514 * The drawback is that the logic inside the function becomes
515 * complicated, and that is the reason why it is not implemented.
517 void check_space(Parser const & p, ostream & os, Context & context)
519 Token const next = p.next_token();
520 Token const curr = p.curr_token();
521 // A space before a single newline and vice versa must be ignored
522 // LyX emits a newline before \end{lyxcode}.
523 // This newline must be ignored,
524 // otherwise LyX will add an additional protected space.
525 if (next.cat() == catSpace ||
526 next.cat() == catNewline ||
527 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
530 context.check_layout(os);
536 * Parse all arguments of \p command
538 void parse_arguments(string const & command,
539 vector<ArgumentType> const & template_arguments,
540 Parser & p, ostream & os, bool outer, Context & context)
542 string ert = command;
543 size_t no_arguments = template_arguments.size();
544 for (size_t i = 0; i < no_arguments; ++i) {
545 switch (template_arguments[i]) {
547 // This argument contains regular LaTeX
548 handle_ert(os, ert + '{', context);
549 eat_whitespace(p, os, context, false);
550 parse_text(p, os, FLAG_ITEM, outer, context);
554 // This argument may contain special characters
555 ert += '{' + p.verbatim_item() + '}';
562 handle_ert(os, ert, context);
567 * Check whether \p command is a known command. If yes,
568 * handle the command with all arguments.
569 * \return true if the command was parsed, false otherwise.
571 bool parse_command(string const & command, Parser & p, ostream & os,
572 bool outer, Context & context)
574 if (known_commands.find(command) != known_commands.end()) {
575 parse_arguments(command, known_commands[command], p, os,
583 /// Parses a minipage or parbox
584 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
585 Context & parent_context, bool use_parbox)
589 string height_value = "0";
590 string height_unit = "pt";
591 string height_special = "none";
593 if (p.next_token().asInput() == "[") {
594 position = p.getArg('[', ']');
595 if (position != "t" && position != "c" && position != "b") {
597 cerr << "invalid position for minipage/parbox" << endl;
599 if (p.next_token().asInput() == "[") {
600 latex_height = p.getArg('[', ']');
601 translate_box_len(latex_height, height_value, height_unit, height_special);
603 if (p.next_token().asInput() == "[") {
604 inner_pos = p.getArg('[', ']');
605 if (inner_pos != "c" && inner_pos != "t" &&
606 inner_pos != "b" && inner_pos != "s") {
607 inner_pos = position;
608 cerr << "invalid inner_pos for minipage/parbox"
616 string const latex_width = p.verbatim_item();
617 translate_len(latex_width, width_value, width_unit);
618 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
619 // LyX can't handle length variables
624 ss << "\\begin{minipage}";
625 if (!position.empty())
626 ss << '[' << position << ']';
627 if (!latex_height.empty())
628 ss << '[' << latex_height << ']';
629 if (!inner_pos.empty())
630 ss << '[' << inner_pos << ']';
631 ss << "{" << latex_width << "}";
634 handle_ert(os, ss.str(), parent_context);
635 parent_context.new_paragraph(os);
636 parse_text_in_inset(p, os, flags, outer, parent_context);
638 handle_ert(os, "}", parent_context);
640 handle_ert(os, "\\end{minipage}", parent_context);
642 // LyX does not like empty positions, so we have
643 // to set them to the LaTeX default values here.
644 if (position.empty())
646 if (inner_pos.empty())
647 inner_pos = position;
648 parent_context.check_layout(os);
649 begin_inset(os, "Box Frameless\n");
650 os << "position \"" << position << "\"\n";
651 os << "hor_pos \"c\"\n";
652 os << "has_inner_box 1\n";
653 os << "inner_pos \"" << inner_pos << "\"\n";
654 os << "use_parbox " << use_parbox << "\n";
655 os << "width \"" << width_value << width_unit << "\"\n";
656 os << "special \"none\"\n";
657 os << "height \"" << height_value << height_unit << "\"\n";
658 os << "height_special \"" << height_special << "\"\n";
659 os << "status open\n\n";
660 parse_text_in_inset(p, os, flags, outer, parent_context);
662 #ifdef PRESERVE_LAYOUT
663 // lyx puts a % after the end of the minipage
664 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
666 //handle_comment(os, "%dummy", parent_context);
669 parent_context.new_paragraph(os);
671 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
672 //handle_comment(os, "%dummy", parent_context);
675 // We add a protected space if something real follows
676 if (p.good() && p.next_token().cat() != catComment) {
677 os << "\\InsetSpace ~\n";
685 /// parse an unknown environment
686 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
687 unsigned flags, bool outer,
688 Context & parent_context)
690 if (name == "tabbing")
691 // We need to remember that we have to handle '\=' specially
692 flags |= FLAG_TABBING;
694 // We need to translate font changes and paragraphs inside the
695 // environment to ERT if we have a non standard font.
696 // Otherwise things like
697 // \large\begin{foo}\huge bar\end{foo}
699 bool const specialfont =
700 (parent_context.font != parent_context.normalfont);
701 bool const new_layout_allowed = parent_context.new_layout_allowed;
703 parent_context.new_layout_allowed = false;
704 handle_ert(os, "\\begin{" + name + "}", parent_context);
705 parse_text_snippet(p, os, flags, outer, parent_context);
706 handle_ert(os, "\\end{" + name + "}", parent_context);
708 parent_context.new_layout_allowed = new_layout_allowed;
712 void parse_environment(Parser & p, ostream & os, bool outer,
713 Context & parent_context)
715 LyXLayout_ptr newlayout;
716 string const name = p.getArg('{', '}');
717 const bool is_starred = suffixIs(name, '*');
718 string const unstarred_name = rtrim(name, "*");
719 active_environments.push_back(name);
721 if (is_math_env(name)) {
722 parent_context.check_layout(os);
723 begin_inset(os, "Formula ");
724 os << "\\begin{" << name << "}";
725 parse_math(p, os, FLAG_END, MATH_MODE);
726 os << "\\end{" << name << "}";
730 else if (name == "tabular" || name == "longtable") {
731 eat_whitespace(p, os, parent_context, false);
732 parent_context.check_layout(os);
733 begin_inset(os, "Tabular ");
734 handle_tabular(p, os, name == "longtable", parent_context);
739 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
740 eat_whitespace(p, os, parent_context, false);
741 parent_context.check_layout(os);
742 begin_inset(os, "Float " + unstarred_name + "\n");
743 if (p.next_token().asInput() == "[") {
744 os << "placement " << p.getArg('[', ']') << '\n';
746 os << "wide " << convert<string>(is_starred)
747 << "\nsideways false"
748 << "\nstatus open\n\n";
749 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
751 // We don't need really a new paragraph, but
752 // we must make sure that the next item gets a \begin_layout.
753 parent_context.new_paragraph(os);
757 else if (name == "minipage") {
758 eat_whitespace(p, os, parent_context, false);
759 parse_box(p, os, FLAG_END, outer, parent_context, false);
763 else if (name == "comment") {
764 eat_whitespace(p, os, parent_context, false);
765 parent_context.check_layout(os);
766 begin_inset(os, "Note Comment\n");
767 os << "status open\n";
768 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
773 else if (name == "lyxgreyedout") {
774 eat_whitespace(p, os, parent_context, false);
775 parent_context.check_layout(os);
776 begin_inset(os, "Note Greyedout\n");
777 os << "status open\n";
778 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
783 else if (!parent_context.new_layout_allowed)
784 parse_unknown_environment(p, name, os, FLAG_END, outer,
787 // Alignment settings
788 else if (name == "center" || name == "flushleft" || name == "flushright" ||
789 name == "centering" || name == "raggedright" || name == "raggedleft") {
790 eat_whitespace(p, os, parent_context, false);
791 // We must begin a new paragraph if not already done
792 if (! parent_context.atParagraphStart()) {
793 parent_context.check_end_layout(os);
794 parent_context.new_paragraph(os);
796 if (name == "flushleft" || name == "raggedright")
797 parent_context.add_extra_stuff("\\align left\n");
798 else if (name == "flushright" || name == "raggedleft")
799 parent_context.add_extra_stuff("\\align right\n");
801 parent_context.add_extra_stuff("\\align center\n");
802 parse_text(p, os, FLAG_END, outer, parent_context);
803 // Just in case the environment is empty ..
804 parent_context.extra_stuff.erase();
805 // We must begin a new paragraph to reset the alignment
806 parent_context.new_paragraph(os);
810 // The single '=' is meant here.
811 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
812 newlayout->isEnvironment()) {
813 eat_whitespace(p, os, parent_context, false);
814 Context context(true, parent_context.textclass, newlayout,
815 parent_context.layout, parent_context.font);
816 if (parent_context.deeper_paragraph) {
817 // We are beginning a nested environment after a
818 // deeper paragraph inside the outer list environment.
819 // Therefore we don't need to output a "begin deeper".
820 context.need_end_deeper = true;
822 parent_context.check_end_layout(os);
823 switch (context.layout->latextype) {
824 case LATEX_LIST_ENVIRONMENT:
825 context.extra_stuff = "\\labelwidthstring "
826 + p.verbatim_item() + '\n';
829 case LATEX_BIB_ENVIRONMENT:
830 p.verbatim_item(); // swallow next arg
836 context.check_deeper(os);
837 parse_text(p, os, FLAG_END, outer, context);
838 context.check_end_layout(os);
839 if (parent_context.deeper_paragraph) {
840 // We must suppress the "end deeper" because we
841 // suppressed the "begin deeper" above.
842 context.need_end_deeper = false;
844 context.check_end_deeper(os);
845 parent_context.new_paragraph(os);
849 else if (name == "appendix") {
850 // This is no good latex style, but it works and is used in some documents...
851 eat_whitespace(p, os, parent_context, false);
852 parent_context.check_end_layout(os);
853 Context context(true, parent_context.textclass, parent_context.layout,
854 parent_context.layout, parent_context.font);
855 context.check_layout(os);
856 os << "\\start_of_appendix\n";
857 parse_text(p, os, FLAG_END, outer, context);
858 context.check_end_layout(os);
862 else if (known_environments.find(name) != known_environments.end()) {
863 vector<ArgumentType> arguments = known_environments[name];
864 // The last "argument" denotes wether we may translate the
865 // environment contents to LyX
866 // The default required if no argument is given makes us
867 // compatible with the reLyXre environment.
868 ArgumentType contents = arguments.empty() ?
871 if (!arguments.empty())
872 arguments.pop_back();
873 // See comment in parse_unknown_environment()
874 bool const specialfont =
875 (parent_context.font != parent_context.normalfont);
876 bool const new_layout_allowed =
877 parent_context.new_layout_allowed;
879 parent_context.new_layout_allowed = false;
880 parse_arguments("\\begin{" + name + "}", arguments, p, os,
881 outer, parent_context);
882 if (contents == verbatim)
883 handle_ert(os, p.verbatimEnvironment(name),
886 parse_text_snippet(p, os, FLAG_END, outer,
888 handle_ert(os, "\\end{" + name + "}", parent_context);
890 parent_context.new_layout_allowed = new_layout_allowed;
894 parse_unknown_environment(p, name, os, FLAG_END, outer,
897 active_environments.pop_back();
901 /// parses a comment and outputs it to \p os.
902 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
904 BOOST_ASSERT(t.cat() == catComment);
905 if (!t.cs().empty()) {
906 context.check_layout(os);
907 handle_comment(os, '%' + t.cs(), context);
908 if (p.next_token().cat() == catNewline) {
909 // A newline after a comment line starts a new
911 if (context.new_layout_allowed) {
912 if(!context.atParagraphStart())
913 // Only start a new paragraph if not already
914 // done (we might get called recursively)
915 context.new_paragraph(os);
917 handle_ert(os, "\n", context);
918 eat_whitespace(p, os, context, true);
928 * Reads spaces and comments until the first non-space, non-comment token.
929 * New paragraphs (double newlines or \\par) are handled like simple spaces
930 * if \p eatParagraph is true.
931 * Spaces are skipped, but comments are written to \p os.
933 void eat_whitespace(Parser & p, ostream & os, Context & context,
937 Token const & t = p.get_token();
938 if (t.cat() == catComment)
939 parse_comment(p, os, t, context);
940 else if ((! eatParagraph && p.isParagraph()) ||
941 (t.cat() != catSpace && t.cat() != catNewline)) {
950 * Set a font attribute, parse text and reset the font attribute.
951 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
952 * \param currentvalue Current value of the attribute. Is set to the new
953 * value during parsing.
954 * \param newvalue New value of the attribute
956 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
957 Context & context, string const & attribute,
958 string & currentvalue, string const & newvalue)
960 context.check_layout(os);
961 string const oldvalue = currentvalue;
962 currentvalue = newvalue;
963 os << '\n' << attribute << ' ' << newvalue << "\n";
964 parse_text_snippet(p, os, flags, outer, context);
965 context.check_layout(os);
966 os << '\n' << attribute << ' ' << oldvalue << "\n";
967 currentvalue = oldvalue;
971 /// get the arguments of a natbib or jurabib citation command
972 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
974 // We need to distinguish "" and "[]", so we can't use p.getOpt().
976 // text before the citation
978 // text after the citation
979 string after = p.getFullOpt();
981 if (!after.empty()) {
982 before = p.getFullOpt();
983 if (natbibOrder && !before.empty())
984 std::swap(before, after);
986 return std::make_pair(before, after);
990 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
991 string const normalize_filename(string const & name)
993 Parser p(trim(name, "\""));
996 Token const & t = p.get_token();
997 if (t.cat() != catEscape)
999 else if (t.cs() == "lyxdot") {
1000 // This is used by LyX for simple dots in relative
1004 } else if (t.cs() == "space") {
1014 /// Convert \p name from TeX convention (relative to master file) to LyX
1015 /// convention (relative to .lyx file) if it is relative
1016 void fix_relative_filename(string & name)
1018 if (lyx::support::absolutePath(name))
1020 name = makeRelPath(makeAbsPath(name, getMasterFilePath()),
1021 getParentFilePath());
1025 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1026 void parse_noweb(Parser & p, ostream & os, Context & context)
1028 // assemble the rest of the keyword
1032 Token const & t = p.get_token();
1033 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1036 scrap = (p.good() && p.next_token().asInput() == "=");
1038 name += p.get_token().asInput();
1041 name += t.asInput();
1044 if (!scrap || !context.new_layout_allowed ||
1045 !context.textclass.hasLayout("Scrap")) {
1046 cerr << "Warning: Could not interpret '" << name
1047 << "'. Ignoring it." << endl;
1051 context.check_end_layout(os);
1052 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1053 newcontext.check_layout(os);
1056 Token const & t = p.get_token();
1057 // We abuse the parser a bit, because this is no TeX syntax
1059 if (t.cat() == catEscape)
1060 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1062 os << subst(t.asInput(), "\n", "\n\\newline\n");
1063 // The scrap chunk is ended by an @ at the beginning of a line.
1064 // After the @ the line may contain a comment and/or
1065 // whitespace, but nothing else.
1066 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1067 (p.next_token().cat() == catSpace ||
1068 p.next_token().cat() == catNewline ||
1069 p.next_token().cat() == catComment)) {
1070 while (p.good() && p.next_token().cat() == catSpace)
1071 os << p.get_token().asInput();
1072 if (p.next_token().cat() == catComment)
1073 // The comment includes a final '\n'
1074 os << p.get_token().asInput();
1076 if (p.next_token().cat() == catNewline)
1083 newcontext.check_end_layout(os);
1086 } // anonymous namespace
1089 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1092 LyXLayout_ptr newlayout;
1093 // Store the latest bibliographystyle (needed for bibtex inset)
1094 string bibliographystyle;
1095 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1096 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1098 Token const & t = p.get_token();
1101 cerr << "t: " << t << " flags: " << flags << "\n";
1104 if (flags & FLAG_ITEM) {
1105 if (t.cat() == catSpace)
1108 flags &= ~FLAG_ITEM;
1109 if (t.cat() == catBegin) {
1110 // skip the brace and collect everything to the next matching
1112 flags |= FLAG_BRACE_LAST;
1116 // handle only this single token, leave the loop if done
1117 flags |= FLAG_LEAVE;
1120 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1126 if (t.cat() == catMath) {
1127 // we are inside some text mode thingy, so opening new math is allowed
1128 context.check_layout(os);
1129 begin_inset(os, "Formula ");
1130 Token const & n = p.get_token();
1131 if (n.cat() == catMath && outer) {
1132 // TeX's $$...$$ syntax for displayed math
1134 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1136 p.get_token(); // skip the second '$' token
1138 // simple $...$ stuff
1141 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1147 else if (t.cat() == catSuper || t.cat() == catSub)
1148 cerr << "catcode " << t << " illegal in text mode\n";
1150 // Basic support for english quotes. This should be
1151 // extended to other quotes, but is not so easy (a
1152 // left english quote is the same as a right german
1154 else if (t.asInput() == "`"
1155 && p.next_token().asInput() == "`") {
1156 context.check_layout(os);
1157 begin_inset(os, "Quotes ");
1163 else if (t.asInput() == "'"
1164 && p.next_token().asInput() == "'") {
1165 context.check_layout(os);
1166 begin_inset(os, "Quotes ");
1173 else if (t.asInput() == "<"
1174 && p.next_token().asInput() == "<" && noweb_mode) {
1176 parse_noweb(p, os, context);
1179 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1180 check_space(p, os, context);
1182 else if (t.character() == '[' && noweb_mode &&
1183 p.next_token().character() == '[') {
1184 // These can contain underscores
1186 string const s = p.getFullOpt() + ']';
1187 if (p.next_token().character() == ']')
1190 cerr << "Warning: Inserting missing ']' in '"
1191 << s << "'." << endl;
1192 handle_ert(os, s, context);
1195 else if (t.cat() == catLetter ||
1196 t.cat() == catOther ||
1197 t.cat() == catAlign ||
1198 t.cat() == catParameter) {
1199 // This translates "&" to "\\&" which may be wrong...
1200 context.check_layout(os);
1201 os << t.character();
1204 else if (p.isParagraph()) {
1205 if (context.new_layout_allowed)
1206 context.new_paragraph(os);
1208 handle_ert(os, "\\par ", context);
1209 eat_whitespace(p, os, context, true);
1212 else if (t.cat() == catActive) {
1213 context.check_layout(os);
1214 if (t.character() == '~') {
1215 if (context.layout->free_spacing)
1218 os << "\\InsetSpace ~\n";
1220 os << t.character();
1223 else if (t.cat() == catBegin &&
1224 p.next_token().cat() == catEnd) {
1226 Token const prev = p.prev_token();
1228 if (p.next_token().character() == '`' ||
1229 (prev.character() == '-' &&
1230 p.next_token().character() == '-'))
1231 ; // ignore it in {}`` or -{}-
1233 handle_ert(os, "{}", context);
1237 else if (t.cat() == catBegin) {
1238 context.check_layout(os);
1239 // special handling of font attribute changes
1240 Token const prev = p.prev_token();
1241 Token const next = p.next_token();
1242 Font const oldFont = context.font;
1243 if (next.character() == '[' ||
1244 next.character() == ']' ||
1245 next.character() == '*') {
1247 if (p.next_token().cat() == catEnd) {
1248 os << next.character();
1252 handle_ert(os, "{", context);
1253 parse_text_snippet(p, os,
1256 handle_ert(os, "}", context);
1258 } else if (! context.new_layout_allowed) {
1259 handle_ert(os, "{", context);
1260 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1262 handle_ert(os, "}", context);
1263 } else if (is_known(next.cs(), known_sizes)) {
1264 // next will change the size, so we must
1266 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1268 if (!context.atParagraphStart())
1270 << context.font.size << "\n";
1271 } else if (is_known(next.cs(), known_font_families)) {
1272 // next will change the font family, so we
1273 // must reset it here
1274 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1276 if (!context.atParagraphStart())
1278 << context.font.family << "\n";
1279 } else if (is_known(next.cs(), known_font_series)) {
1280 // next will change the font series, so we
1281 // must reset it here
1282 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1284 if (!context.atParagraphStart())
1286 << context.font.series << "\n";
1287 } else if (is_known(next.cs(), known_font_shapes)) {
1288 // next will change the font shape, so we
1289 // must reset it here
1290 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1292 if (!context.atParagraphStart())
1294 << context.font.shape << "\n";
1295 } else if (is_known(next.cs(), known_old_font_families) ||
1296 is_known(next.cs(), known_old_font_series) ||
1297 is_known(next.cs(), known_old_font_shapes)) {
1298 // next will change the font family, series
1299 // and shape, so we must reset it here
1300 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1302 if (!context.atParagraphStart())
1304 << context.font.family
1306 << context.font.series
1308 << context.font.shape << "\n";
1310 handle_ert(os, "{", context);
1311 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1313 handle_ert(os, "}", context);
1317 else if (t.cat() == catEnd) {
1318 if (flags & FLAG_BRACE_LAST) {
1321 cerr << "stray '}' in text\n";
1322 handle_ert(os, "}", context);
1325 else if (t.cat() == catComment)
1326 parse_comment(p, os, t, context);
1329 // control sequences
1332 else if (t.cs() == "(") {
1333 context.check_layout(os);
1334 begin_inset(os, "Formula");
1336 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1341 else if (t.cs() == "[") {
1342 context.check_layout(os);
1343 begin_inset(os, "Formula");
1345 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1350 else if (t.cs() == "begin")
1351 parse_environment(p, os, outer, context);
1353 else if (t.cs() == "end") {
1354 if (flags & FLAG_END) {
1355 // eat environment name
1356 string const name = p.getArg('{', '}');
1357 if (name != active_environment())
1358 cerr << "\\end{" + name + "} does not match \\begin{"
1359 + active_environment() + "}\n";
1362 p.error("found 'end' unexpectedly");
1365 else if (t.cs() == "item") {
1368 bool optarg = false;
1369 if (p.next_token().character() == '[') {
1370 p.get_token(); // eat '['
1371 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1376 context.check_layout(os);
1377 if (context.has_item) {
1378 // An item in an unknown list-like environment
1379 // FIXME: Do this in check_layout()!
1380 context.has_item = false;
1382 handle_ert(os, "\\item", context);
1384 handle_ert(os, "\\item ", context);
1387 if (context.layout->labeltype != LABEL_MANUAL) {
1388 // lyx does not support \item[\mybullet]
1389 // in itemize environments
1390 handle_ert(os, "[", context);
1392 handle_ert(os, "]", context);
1393 } else if (!s.empty()) {
1394 // The space is needed to separate the
1395 // item from the rest of the sentence.
1397 eat_whitespace(p, os, context, false);
1402 else if (t.cs() == "bibitem") {
1404 context.check_layout(os);
1407 os << '{' << p.verbatim_item() << '}' << "\n";
1410 else if (t.cs() == "def") {
1411 context.check_layout(os);
1412 eat_whitespace(p, os, context, false);
1413 string name = p.get_token().cs();
1414 while (p.next_token().cat() != catBegin)
1415 name += p.get_token().asString();
1416 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1419 else if (t.cs() == "noindent") {
1421 context.add_extra_stuff("\\noindent\n");
1424 else if (t.cs() == "appendix") {
1425 context.add_extra_stuff("\\start_of_appendix\n");
1426 // We need to start a new paragraph. Otherwise the
1427 // appendix in 'bla\appendix\chapter{' would start
1429 context.new_paragraph(os);
1430 // We need to make sure that the paragraph is
1431 // generated even if it is empty. Otherwise the
1432 // appendix in '\par\appendix\par\chapter{' would
1434 context.check_layout(os);
1435 // FIXME: This is a hack to prevent paragraph
1436 // deletion if it is empty. Handle this better!
1438 "%dummy comment inserted by tex2lyx to "
1439 "ensure that this paragraph is not empty",
1441 // Both measures above may generate an additional
1442 // empty paragraph, but that does not hurt, because
1443 // whitespace does not matter here.
1444 eat_whitespace(p, os, context, true);
1447 // Must attempt to parse "Section*" before "Section".
1448 else if ((p.next_token().asInput() == "*") &&
1449 context.new_layout_allowed &&
1450 // The single '=' is meant here.
1451 (newlayout = findLayout(context.textclass,
1452 t.cs() + '*')).get() &&
1453 newlayout->isCommand()) {
1455 output_command_layout(os, p, outer, context, newlayout);
1459 // The single '=' is meant here.
1460 else if (context.new_layout_allowed &&
1461 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1462 newlayout->isCommand()) {
1463 output_command_layout(os, p, outer, context, newlayout);
1467 else if (t.cs() == "includegraphics") {
1468 bool const clip = p.next_token().asInput() == "*";
1471 map<string, string> opts = split_map(p.getArg('[', ']'));
1473 opts["clip"] = string();
1474 string name = normalize_filename(p.verbatim_item());
1476 string const path = getMasterFilePath();
1477 // We want to preserve relative / absolute filenames,
1478 // therefore path is only used for testing
1479 if (!fs::exists(makeAbsPath(name, path))) {
1480 // The file extension is probably missing.
1481 // Now try to find it out.
1482 string const dvips_name =
1483 find_file(name, path,
1484 known_dvips_graphics_formats);
1485 string const pdftex_name =
1486 find_file(name, path,
1487 known_pdftex_graphics_formats);
1488 if (!dvips_name.empty()) {
1489 if (!pdftex_name.empty()) {
1490 cerr << "This file contains the "
1492 "\"\\includegraphics{"
1494 "However, files\n\""
1495 << dvips_name << "\" and\n\""
1496 << pdftex_name << "\"\n"
1497 "both exist, so I had to make a "
1498 "choice and took the first one.\n"
1499 "Please move the unwanted one "
1500 "someplace else and try again\n"
1501 "if my choice was wrong."
1505 } else if (!pdftex_name.empty())
1509 if (fs::exists(makeAbsPath(name, path)))
1510 fix_relative_filename(name);
1512 cerr << "Warning: Could not find graphics file '"
1513 << name << "'." << endl;
1515 context.check_layout(os);
1516 begin_inset(os, "Graphics ");
1517 os << "\n\tfilename " << name << '\n';
1518 if (opts.find("width") != opts.end())
1520 << translate_len(opts["width"]) << '\n';
1521 if (opts.find("height") != opts.end())
1523 << translate_len(opts["height"]) << '\n';
1524 if (opts.find("scale") != opts.end()) {
1525 istringstream iss(opts["scale"]);
1529 os << "\tscale " << val << '\n';
1531 if (opts.find("angle") != opts.end())
1532 os << "\trotateAngle "
1533 << opts["angle"] << '\n';
1534 if (opts.find("origin") != opts.end()) {
1536 string const opt = opts["origin"];
1537 if (opt.find('l') != string::npos) ss << "left";
1538 if (opt.find('r') != string::npos) ss << "right";
1539 if (opt.find('c') != string::npos) ss << "center";
1540 if (opt.find('t') != string::npos) ss << "Top";
1541 if (opt.find('b') != string::npos) ss << "Bottom";
1542 if (opt.find('B') != string::npos) ss << "Baseline";
1543 if (!ss.str().empty())
1544 os << "\trotateOrigin " << ss.str() << '\n';
1546 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1548 if (opts.find("keepaspectratio") != opts.end())
1549 os << "\tkeepAspectRatio\n";
1550 if (opts.find("clip") != opts.end())
1552 if (opts.find("draft") != opts.end())
1554 if (opts.find("bb") != opts.end())
1555 os << "\tBoundingBox "
1556 << opts["bb"] << '\n';
1557 int numberOfbbOptions = 0;
1558 if (opts.find("bbllx") != opts.end())
1559 numberOfbbOptions++;
1560 if (opts.find("bblly") != opts.end())
1561 numberOfbbOptions++;
1562 if (opts.find("bburx") != opts.end())
1563 numberOfbbOptions++;
1564 if (opts.find("bbury") != opts.end())
1565 numberOfbbOptions++;
1566 if (numberOfbbOptions == 4)
1567 os << "\tBoundingBox "
1568 << opts["bbllx"] << opts["bblly"]
1569 << opts["bburx"] << opts["bbury"] << '\n';
1570 else if (numberOfbbOptions > 0)
1571 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1572 numberOfbbOptions = 0;
1573 if (opts.find("natwidth") != opts.end())
1574 numberOfbbOptions++;
1575 if (opts.find("natheight") != opts.end())
1576 numberOfbbOptions++;
1577 if (numberOfbbOptions == 2)
1578 os << "\tBoundingBox 0bp 0bp "
1579 << opts["natwidth"] << opts["natheight"] << '\n';
1580 else if (numberOfbbOptions > 0)
1581 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1582 ostringstream special;
1583 if (opts.find("hiresbb") != opts.end())
1584 special << "hiresbb,";
1585 if (opts.find("trim") != opts.end())
1587 if (opts.find("viewport") != opts.end())
1588 special << "viewport=" << opts["viewport"] << ',';
1589 if (opts.find("totalheight") != opts.end())
1590 special << "totalheight=" << opts["totalheight"] << ',';
1591 if (opts.find("type") != opts.end())
1592 special << "type=" << opts["type"] << ',';
1593 if (opts.find("ext") != opts.end())
1594 special << "ext=" << opts["ext"] << ',';
1595 if (opts.find("read") != opts.end())
1596 special << "read=" << opts["read"] << ',';
1597 if (opts.find("command") != opts.end())
1598 special << "command=" << opts["command"] << ',';
1599 string s_special = special.str();
1600 if (!s_special.empty()) {
1601 // We had special arguments. Remove the trailing ','.
1602 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1604 // TODO: Handle the unknown settings better.
1605 // Warn about invalid options.
1606 // Check whether some option was given twice.
1610 else if (t.cs() == "footnote" ||
1611 (t.cs() == "thanks" && context.layout->intitle)) {
1613 context.check_layout(os);
1614 begin_inset(os, "Foot\n");
1615 os << "status collapsed\n\n";
1616 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1620 else if (t.cs() == "marginpar") {
1622 context.check_layout(os);
1623 begin_inset(os, "Marginal\n");
1624 os << "status collapsed\n\n";
1625 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1629 else if (t.cs() == "ensuremath") {
1631 context.check_layout(os);
1632 string const s = p.verbatim_item();
1633 if (s == "±" || s == "³" || s == "²" || s == "µ")
1636 handle_ert(os, "\\ensuremath{" + s + "}",
1640 else if (t.cs() == "hfill") {
1641 context.check_layout(os);
1642 os << "\n\\hfill\n";
1647 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1648 // FIXME: Somehow prevent title layouts if
1649 // "maketitle" was not found
1651 skip_braces(p); // swallow this
1654 else if (t.cs() == "tableofcontents") {
1656 context.check_layout(os);
1657 begin_inset(os, "LatexCommand \\tableofcontents\n");
1659 skip_braces(p); // swallow this
1662 else if (t.cs() == "listoffigures") {
1664 context.check_layout(os);
1665 begin_inset(os, "FloatList figure\n");
1667 skip_braces(p); // swallow this
1670 else if (t.cs() == "listoftables") {
1672 context.check_layout(os);
1673 begin_inset(os, "FloatList table\n");
1675 skip_braces(p); // swallow this
1678 else if (t.cs() == "listof") {
1679 p.skip_spaces(true);
1680 string const name = p.get_token().asString();
1681 if (context.textclass.floats().typeExist(name)) {
1682 context.check_layout(os);
1683 begin_inset(os, "FloatList ");
1686 p.get_token(); // swallow second arg
1688 handle_ert(os, "\\listof{" + name + "}", context);
1691 else if (t.cs() == "textrm")
1692 parse_text_attributes(p, os, FLAG_ITEM, outer,
1693 context, "\\family",
1694 context.font.family, "roman");
1696 else if (t.cs() == "textsf")
1697 parse_text_attributes(p, os, FLAG_ITEM, outer,
1698 context, "\\family",
1699 context.font.family, "sans");
1701 else if (t.cs() == "texttt")
1702 parse_text_attributes(p, os, FLAG_ITEM, outer,
1703 context, "\\family",
1704 context.font.family, "typewriter");
1706 else if (t.cs() == "textmd")
1707 parse_text_attributes(p, os, FLAG_ITEM, outer,
1708 context, "\\series",
1709 context.font.series, "medium");
1711 else if (t.cs() == "textbf")
1712 parse_text_attributes(p, os, FLAG_ITEM, outer,
1713 context, "\\series",
1714 context.font.series, "bold");
1716 else if (t.cs() == "textup")
1717 parse_text_attributes(p, os, FLAG_ITEM, outer,
1719 context.font.shape, "up");
1721 else if (t.cs() == "textit")
1722 parse_text_attributes(p, os, FLAG_ITEM, outer,
1724 context.font.shape, "italic");
1726 else if (t.cs() == "textsl")
1727 parse_text_attributes(p, os, FLAG_ITEM, outer,
1729 context.font.shape, "slanted");
1731 else if (t.cs() == "textsc")
1732 parse_text_attributes(p, os, FLAG_ITEM, outer,
1734 context.font.shape, "smallcaps");
1736 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1737 context.check_layout(os);
1738 Font oldFont = context.font;
1739 context.font.init();
1740 context.font.size = oldFont.size;
1741 os << "\n\\family " << context.font.family << "\n";
1742 os << "\n\\series " << context.font.series << "\n";
1743 os << "\n\\shape " << context.font.shape << "\n";
1744 if (t.cs() == "textnormal") {
1745 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1746 output_font_change(os, context.font, oldFont);
1747 context.font = oldFont;
1749 eat_whitespace(p, os, context, false);
1752 else if (t.cs() == "underbar") {
1753 // Do NOT handle \underline.
1754 // \underbar cuts through y, g, q, p etc.,
1755 // \underline does not.
1756 context.check_layout(os);
1757 os << "\n\\bar under\n";
1758 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1759 context.check_layout(os);
1760 os << "\n\\bar default\n";
1763 else if (t.cs() == "emph" || t.cs() == "noun") {
1764 context.check_layout(os);
1765 os << "\n\\" << t.cs() << " on\n";
1766 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1767 context.check_layout(os);
1768 os << "\n\\" << t.cs() << " default\n";
1771 else if (use_natbib &&
1772 is_known(t.cs(), known_natbib_commands) &&
1773 ((t.cs() != "citefullauthor" &&
1774 t.cs() != "citeyear" &&
1775 t.cs() != "citeyearpar") ||
1776 p.next_token().asInput() != "*")) {
1777 context.check_layout(os);
1779 // \citet[before][after]{a} \citet[after][before]{a}
1780 // \citet[before][]{a} \citet[][before]{a}
1781 // \citet[after]{a} \citet[after]{a}
1782 // \citet{a} \citet{a}
1783 string command = '\\' + t.cs();
1784 if (p.next_token().asInput() == "*") {
1788 if (command == "\\citefullauthor")
1789 // alternative name for "\\citeauthor*"
1790 command = "\\citeauthor*";
1792 // text before the citation
1794 // text after the citation
1797 boost::tie(before, after) = getCiteArguments(p, true);
1798 if (command == "\\cite") {
1799 // \cite without optional argument means
1800 // \citet, \cite with at least one optional
1801 // argument means \citep.
1802 if (before.empty() && after.empty())
1803 command = "\\citet";
1805 command = "\\citep";
1807 if (before.empty() && after == "[]")
1808 // avoid \citet[]{a}
1810 else if (before == "[]" && after == "[]") {
1811 // avoid \citet[][]{a}
1815 begin_inset(os, "LatexCommand ");
1816 os << command << after << before
1817 << '{' << p.verbatim_item() << "}\n";
1821 else if (use_jurabib &&
1822 is_known(t.cs(), known_jurabib_commands)) {
1823 context.check_layout(os);
1824 string const command = '\\' + t.cs();
1825 char argumentOrder = '\0';
1826 vector<string> const & options = used_packages["jurabib"];
1827 if (std::find(options.begin(), options.end(),
1828 "natbiborder") != options.end())
1829 argumentOrder = 'n';
1830 else if (std::find(options.begin(), options.end(),
1831 "jurabiborder") != options.end())
1832 argumentOrder = 'j';
1834 // text before the citation
1836 // text after the citation
1839 boost::tie(before, after) =
1840 getCiteArguments(p, argumentOrder != 'j');
1841 string const citation = p.verbatim_item();
1842 if (!before.empty() && argumentOrder == '\0') {
1843 cerr << "Warning: Assuming argument order "
1844 "of jurabib version 0.6 for\n'"
1845 << command << before << after << '{'
1846 << citation << "}'.\n"
1847 "Add 'jurabiborder' to the jurabib "
1848 "package options if you used an\n"
1849 "earlier jurabib version." << endl;
1851 begin_inset(os, "LatexCommand ");
1852 os << command << after << before
1853 << '{' << citation << "}\n";
1857 else if (is_known(t.cs(), known_latex_commands)) {
1858 // This needs to be after the check for natbib and
1859 // jurabib commands, because "cite" has different
1860 // arguments with natbib and jurabib.
1861 context.check_layout(os);
1862 begin_inset(os, "LatexCommand ");
1863 os << '\\' << t.cs();
1864 // lyx cannot handle newlines in a latex command
1865 // FIXME: Move the substitution into parser::getOpt()?
1866 os << subst(p.getOpt(), "\n", " ");
1867 os << subst(p.getOpt(), "\n", " ");
1868 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1872 else if (is_known(t.cs(), known_quotes)) {
1873 char const * const * where = is_known(t.cs(), known_quotes);
1874 context.check_layout(os);
1875 begin_inset(os, "Quotes ");
1876 os << known_coded_quotes[where - known_quotes];
1878 // LyX adds {} after the quote, so we have to eat
1879 // spaces here if there are any before a possible
1881 eat_whitespace(p, os, context, false);
1885 else if (is_known(t.cs(), known_sizes) &&
1886 context.new_layout_allowed) {
1887 char const * const * where = is_known(t.cs(), known_sizes);
1888 context.check_layout(os);
1889 Font const oldFont = context.font;
1890 context.font.size = known_coded_sizes[where - known_sizes];
1891 output_font_change(os, oldFont, context.font);
1892 eat_whitespace(p, os, context, false);
1895 else if (is_known(t.cs(), known_font_families) &&
1896 context.new_layout_allowed) {
1897 char const * const * where =
1898 is_known(t.cs(), known_font_families);
1899 context.check_layout(os);
1900 Font const oldFont = context.font;
1901 context.font.family =
1902 known_coded_font_families[where - known_font_families];
1903 output_font_change(os, oldFont, context.font);
1904 eat_whitespace(p, os, context, false);
1907 else if (is_known(t.cs(), known_font_series) &&
1908 context.new_layout_allowed) {
1909 char const * const * where =
1910 is_known(t.cs(), known_font_series);
1911 context.check_layout(os);
1912 Font const oldFont = context.font;
1913 context.font.series =
1914 known_coded_font_series[where - known_font_series];
1915 output_font_change(os, oldFont, context.font);
1916 eat_whitespace(p, os, context, false);
1919 else if (is_known(t.cs(), known_font_shapes) &&
1920 context.new_layout_allowed) {
1921 char const * const * where =
1922 is_known(t.cs(), known_font_shapes);
1923 context.check_layout(os);
1924 Font const oldFont = context.font;
1925 context.font.shape =
1926 known_coded_font_shapes[where - known_font_shapes];
1927 output_font_change(os, oldFont, context.font);
1928 eat_whitespace(p, os, context, false);
1930 else if (is_known(t.cs(), known_old_font_families) &&
1931 context.new_layout_allowed) {
1932 char const * const * where =
1933 is_known(t.cs(), known_old_font_families);
1934 context.check_layout(os);
1935 Font const oldFont = context.font;
1936 context.font.init();
1937 context.font.size = oldFont.size;
1938 context.font.family =
1939 known_coded_font_families[where - known_old_font_families];
1940 output_font_change(os, oldFont, context.font);
1941 eat_whitespace(p, os, context, false);
1944 else if (is_known(t.cs(), known_old_font_series) &&
1945 context.new_layout_allowed) {
1946 char const * const * where =
1947 is_known(t.cs(), known_old_font_series);
1948 context.check_layout(os);
1949 Font const oldFont = context.font;
1950 context.font.init();
1951 context.font.size = oldFont.size;
1952 context.font.series =
1953 known_coded_font_series[where - known_old_font_series];
1954 output_font_change(os, oldFont, context.font);
1955 eat_whitespace(p, os, context, false);
1958 else if (is_known(t.cs(), known_old_font_shapes) &&
1959 context.new_layout_allowed) {
1960 char const * const * where =
1961 is_known(t.cs(), known_old_font_shapes);
1962 context.check_layout(os);
1963 Font const oldFont = context.font;
1964 context.font.init();
1965 context.font.size = oldFont.size;
1966 context.font.shape =
1967 known_coded_font_shapes[where - known_old_font_shapes];
1968 output_font_change(os, oldFont, context.font);
1969 eat_whitespace(p, os, context, false);
1972 else if (t.cs() == "LyX" || t.cs() == "TeX"
1973 || t.cs() == "LaTeX") {
1974 context.check_layout(os);
1976 skip_braces(p); // eat {}
1979 else if (t.cs() == "LaTeXe") {
1980 context.check_layout(os);
1982 skip_braces(p); // eat {}
1985 else if (t.cs() == "ldots") {
1986 context.check_layout(os);
1988 os << "\\SpecialChar \\ldots{}\n";
1991 else if (t.cs() == "lyxarrow") {
1992 context.check_layout(os);
1993 os << "\\SpecialChar \\menuseparator\n";
1997 else if (t.cs() == "textcompwordmark") {
1998 context.check_layout(os);
1999 os << "\\SpecialChar \\textcompwordmark{}\n";
2003 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2004 context.check_layout(os);
2005 os << "\\SpecialChar \\@.\n";
2009 else if (t.cs() == "-") {
2010 context.check_layout(os);
2011 os << "\\SpecialChar \\-\n";
2014 else if (t.cs() == "textasciitilde") {
2015 context.check_layout(os);
2020 else if (t.cs() == "textasciicircum") {
2021 context.check_layout(os);
2026 else if (t.cs() == "textbackslash") {
2027 context.check_layout(os);
2028 os << "\n\\backslash\n";
2032 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2033 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2035 context.check_layout(os);
2039 else if (t.cs() == "char") {
2040 context.check_layout(os);
2041 if (p.next_token().character() == '`') {
2043 if (p.next_token().cs() == "\"") {
2048 handle_ert(os, "\\char`", context);
2051 handle_ert(os, "\\char", context);
2055 else if (t.cs() == "verb") {
2056 context.check_layout(os);
2057 char const delimiter = p.next_token().character();
2058 string const arg = p.getArg(delimiter, delimiter);
2060 oss << "\\verb" << delimiter << arg << delimiter;
2061 handle_ert(os, oss.str(), context);
2064 else if (t.cs() == "\"") {
2065 context.check_layout(os);
2066 string const name = p.verbatim_item();
2067 if (name == "a") os << 'ä';
2068 else if (name == "o") os << 'ö';
2069 else if (name == "u") os << 'ü';
2070 else if (name == "A") os << 'Ä';
2071 else if (name == "O") os << 'Ö';
2072 else if (name == "U") os << 'Ü';
2073 else handle_ert(os, "\"{" + name + "}", context);
2076 // Problem: \= creates a tabstop inside the tabbing environment
2077 // and else an accent. In the latter case we really would want
2078 // \={o} instead of \= o.
2079 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2080 handle_ert(os, t.asInput(), context);
2082 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2083 || t.cs() == "'" || t.cs() == "`"
2084 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2085 // we need the trim as the LyX parser chokes on such spaces
2086 context.check_layout(os);
2087 os << "\n\\i \\" << t.cs() << "{"
2088 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2092 else if (t.cs() == "ss") {
2093 context.check_layout(os);
2095 skip_braces(p); // eat {}
2098 else if (t.cs() == "i" || t.cs() == "j") {
2099 context.check_layout(os);
2100 os << "\\" << t.cs() << ' ';
2101 skip_braces(p); // eat {}
2104 else if (t.cs() == "\\") {
2105 context.check_layout(os);
2106 string const next = p.next_token().asInput();
2108 handle_ert(os, "\\\\" + p.getOpt(), context);
2109 else if (next == "*") {
2111 handle_ert(os, "\\\\*" + p.getOpt(), context);
2114 os << "\n\\newline\n";
2118 else if (t.cs() == "input" || t.cs() == "include"
2119 || t.cs() == "verbatiminput") {
2120 string name = '\\' + t.cs();
2121 if (t.cs() == "verbatiminput"
2122 && p.next_token().asInput() == "*")
2123 name += p.get_token().asInput();
2124 context.check_layout(os);
2125 begin_inset(os, "Include ");
2126 string filename(normalize_filename(p.getArg('{', '}')));
2127 string const path = getMasterFilePath();
2128 // We want to preserve relative / absolute filenames,
2129 // therefore path is only used for testing
2130 if (t.cs() == "include" &&
2131 !fs::exists(makeAbsPath(filename, path))) {
2132 // The file extension is probably missing.
2133 // Now try to find it out.
2134 string const tex_name =
2135 find_file(filename, path,
2136 known_tex_extensions);
2137 if (!tex_name.empty())
2138 filename = tex_name;
2140 if (fs::exists(makeAbsPath(filename, path))) {
2141 string const abstexname =
2142 makeAbsPath(filename, path);
2143 string const abslyxname =
2144 changeExtension(abstexname, ".lyx");
2145 fix_relative_filename(filename);
2146 string const lyxname =
2147 changeExtension(filename, ".lyx");
2148 if (t.cs() != "verbatiminput" &&
2149 tex2lyx(abstexname, abslyxname)) {
2150 os << name << '{' << lyxname << "}\n";
2152 os << name << '{' << filename << "}\n";
2155 cerr << "Warning: Could not find included file '"
2156 << filename << "'." << endl;
2157 os << name << '{' << filename << "}\n";
2159 os << "preview false\n";
2163 else if (t.cs() == "bibliographystyle") {
2164 // store new bibliographystyle
2165 bibliographystyle = p.verbatim_item();
2166 // output new bibliographystyle.
2167 // This is only necessary if used in some other macro than \bibliography.
2168 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2171 else if (t.cs() == "bibliography") {
2172 context.check_layout(os);
2173 begin_inset(os, "LatexCommand ");
2175 // Do we have a bibliographystyle set?
2176 if (!bibliographystyle.empty()) {
2177 os << '[' << bibliographystyle << ']';
2179 os << '{' << p.verbatim_item() << "}\n";
2183 else if (t.cs() == "parbox")
2184 parse_box(p, os, FLAG_ITEM, outer, context, true);
2186 else if (t.cs() == "smallskip" ||
2187 t.cs() == "medskip" ||
2188 t.cs() == "bigskip" ||
2189 t.cs() == "vfill") {
2190 context.check_layout(os);
2191 begin_inset(os, "VSpace ");
2197 else if (is_known(t.cs(), known_spaces)) {
2198 char const * const * where = is_known(t.cs(), known_spaces);
2199 context.check_layout(os);
2200 begin_inset(os, "InsetSpace ");
2201 os << '\\' << known_coded_spaces[where - known_spaces]
2203 // LaTeX swallows whitespace after all spaces except
2204 // "\\,". We have to do that here, too, because LyX
2205 // adds "{}" which would make the spaces significant.
2207 eat_whitespace(p, os, context, false);
2208 // LyX adds "{}" after all spaces except "\\ " and
2209 // "\\,", so we have to remove "{}".
2210 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2211 // remove the braces after "\\,", too.
2216 else if (t.cs() == "newpage") {
2217 context.check_layout(os);
2218 // FIXME: what about \\clearpage and \\pagebreak?
2219 os << "\n\\newpage\n";
2220 skip_braces(p); // eat {}
2223 else if (t.cs() == "newcommand" ||
2224 t.cs() == "providecommand" ||
2225 t.cs() == "renewcommand") {
2226 // these could be handled by parse_command(), but
2227 // we need to call add_known_command() here.
2228 string name = t.asInput();
2229 if (p.next_token().asInput() == "*") {
2230 // Starred form. Eat '*'
2234 string const command = p.verbatim_item();
2235 string const opt1 = p.getOpt();
2236 string const opt2 = p.getFullOpt();
2237 add_known_command(command, opt1, !opt2.empty());
2238 string const ert = name + '{' + command + '}' +
2240 '{' + p.verbatim_item() + '}';
2241 handle_ert(os, ert, context);
2244 else if (t.cs() == "vspace") {
2245 bool starred = false;
2246 if (p.next_token().asInput() == "*") {
2250 string const length = p.verbatim_item();
2253 bool valid = splitLatexLength(length, valstring, unit);
2254 bool known_vspace = false;
2255 bool known_unit = false;
2258 istringstream iss(valstring);
2261 if (unit == "\\smallskipamount") {
2263 known_vspace = true;
2264 } else if (unit == "\\medskipamount") {
2266 known_vspace = true;
2267 } else if (unit == "\\bigskipamount") {
2269 known_vspace = true;
2270 } else if (unit == "\\fill") {
2272 known_vspace = true;
2275 if (!known_vspace) {
2276 switch (unitFromString(unit)) {
2297 if (known_unit || known_vspace) {
2298 // Literal length or known variable
2299 context.check_layout(os);
2300 begin_inset(os, "VSpace ");
2308 // LyX can't handle other length variables in Inset VSpace
2309 string name = t.asInput();
2314 handle_ert(os, name + '{' + unit + '}', context);
2315 else if (value == -1.0)
2316 handle_ert(os, name + "{-" + unit + '}', context);
2318 handle_ert(os, name + '{' + valstring + unit + '}', context);
2320 handle_ert(os, name + '{' + length + '}', context);
2325 //cerr << "#: " << t << " mode: " << mode << endl;
2326 // heuristic: read up to next non-nested space
2328 string s = t.asInput();
2329 string z = p.verbatim_item();
2330 while (p.good() && z != " " && z.size()) {
2331 //cerr << "read: " << z << endl;
2333 z = p.verbatim_item();
2335 cerr << "found ERT: " << s << endl;
2336 handle_ert(os, s + ' ', context);
2338 string name = t.asInput();
2339 if (p.next_token().asInput() == "*") {
2340 // Starred commands like \vspace*{}
2341 p.get_token(); // Eat '*'
2344 if (! parse_command(name, p, os, outer, context))
2345 handle_ert(os, name, context);
2348 if (flags & FLAG_LEAVE) {
2349 flags &= ~FLAG_LEAVE;