3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
32 using lyx::support::changeExtension;
33 using lyx::support::makeAbsPath;
34 using lyx::support::makeRelPath;
35 using lyx::support::rtrim;
36 using lyx::support::suffixIs;
37 using lyx::support::contains;
38 using lyx::support::subst;
45 using std::ostringstream;
46 using std::istringstream;
50 namespace fs = boost::filesystem;
53 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
54 Context const & context)
56 Context newcontext(true, context.textclass);
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 /// parses a paragraph snippet, useful for example for \\emph{...}
66 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
69 Context newcontext(context);
70 // Don't inherit the extra stuff
71 newcontext.extra_stuff.clear();
72 parse_text(p, os, flags, outer, newcontext);
73 // Make sure that we don't create invalid .lyx files
74 context.need_layout = newcontext.need_layout;
75 context.need_end_layout = newcontext.need_end_layout;
80 * Thin wrapper around parse_text_snippet() using a string.
82 * We completely ignore \c context.need_layout and \c context.need_end_layout,
83 * because our return value is not used directly (otherwise the stream version
84 * of parse_text_snippet() could be used). That means that the caller needs
85 * to do layout management manually.
86 * This is intended to parse text that does not create any layout changes.
88 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
91 Context newcontext(context);
92 newcontext.need_layout = false;
93 newcontext.need_end_layout = false;
94 newcontext.new_layout_allowed = false;
95 // Avoid warning by Context::~Context()
96 newcontext.extra_stuff.clear();
98 parse_text_snippet(p, os, flags, outer, newcontext);
103 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
104 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
108 * We can't put these into known_latex_commands because the argument order
109 * is reversed in lyx if there are 2 arguments.
110 * The starred forms are also known.
112 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
118 * We can't put these into known_latex_commands because the argument order
119 * is reversed in lyx if there are 2 arguments.
120 * No starred form other than "cite*" known.
122 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
123 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
124 // jurabib commands not (yet) supported by LyX:
125 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
126 // "footciteauthor", "footciteyear", "footciteyearpar",
127 "citefield", "citetitle", "cite*", 0 };
129 /// LaTeX names for quotes
130 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
131 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
133 /// the same as known_quotes with .lyx names
134 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
135 "grd", "gls", "fls", "frd", 0};
137 /// LaTeX names for font sizes
138 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
139 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
141 /// the same as known_sizes with .lyx names
142 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
145 /// LaTeX 2.09 names for font families
146 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
148 /// LaTeX names for font families
149 char const * const known_font_families[] = { "rmfamily", "sffamily",
152 /// the same as known_old_font_families and known_font_families with .lyx names
153 char const * const known_coded_font_families[] = { "roman", "sans",
156 /// LaTeX 2.09 names for font series
157 char const * const known_old_font_series[] = { "bf", 0};
159 /// LaTeX names for font series
160 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
162 /// the same as known_old_font_series and known_font_series with .lyx names
163 char const * const known_coded_font_series[] = { "bold", "medium", 0};
165 /// LaTeX 2.09 names for font shapes
166 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
168 /// LaTeX names for font shapes
169 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
172 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
173 char const * const known_coded_font_shapes[] = { "italic", "slanted",
174 "smallcaps", "up", 0};
177 * Graphics file extensions known by the dvips driver of the graphics package.
178 * These extensions are used to complete the filename of an included
179 * graphics file if it does not contain an extension.
180 * The order must be the same that latex uses to find a file, because we
181 * will use the first extension that matches.
182 * This is only an approximation for the common cases. If we would want to
183 * do it right in all cases, we would need to know which graphics driver is
184 * used and know the extensions of every driver of the graphics package.
186 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
187 "ps.gz", "eps.Z", "ps.Z", 0};
190 * Graphics file extensions known by the pdftex driver of the graphics package.
191 * \sa known_dvips_graphics_formats
193 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
197 * Known file extensions for TeX files as used by \\include.
199 char const * const known_tex_extensions[] = {"tex", 0};
201 /// spaces known by InsetSpace
202 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
203 "qquad", "enspace", "enskip", "negthinspace", 0};
205 /// the same as known_spaces with .lyx names
206 char const * const known_coded_spaces[] = { "space{}", "space{}",
207 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
208 "negthinspace{}", 0};
211 /// splits "x=z, y=b" into a map
212 map<string, string> split_map(string const & s)
214 map<string, string> res;
217 for (size_t i = 0; i < v.size(); ++i) {
218 size_t const pos = v[i].find('=');
219 string const index = v[i].substr(0, pos);
220 string const value = v[i].substr(pos + 1, string::npos);
221 res[trim(index)] = trim(value);
228 * Split a LaTeX length into value and unit.
229 * The latter can be a real unit like "pt", or a latex length variable
230 * like "\textwidth". The unit may contain additional stuff like glue
231 * lengths, but we don't care, because such lengths are ERT anyway.
232 * \returns true if \p value and \p unit are valid.
234 bool splitLatexLength(string const & len, string & value, string & unit)
238 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
239 //'4,5' is a valid LaTeX length number. Change it to '4.5'
240 string const length = subst(len, ',', '.');
241 if (i == string::npos)
244 if (len[0] == '\\') {
245 // We had something like \textwidth without a factor
251 value = trim(string(length, 0, i));
255 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
256 if (contains(len, '\\'))
257 unit = trim(string(len, i));
259 unit = lyx::support::lowercase(trim(string(len, i)));
264 /// A simple function to translate a latex length to something lyx can
265 /// understand. Not perfect, but rather best-effort.
266 bool translate_len(string const & length, string & valstring, string & unit)
268 if (!splitLatexLength(length, valstring, unit))
270 // LyX uses percent values
272 istringstream iss(valstring);
277 string const percentval = oss.str();
279 if (unit.empty() || unit[0] != '\\')
281 string::size_type const i = unit.find(' ');
282 string const endlen = (i == string::npos) ? string() : string(unit, i);
283 if (unit == "\\textwidth") {
284 valstring = percentval;
285 unit = "text%" + endlen;
286 } else if (unit == "\\columnwidth") {
287 valstring = percentval;
288 unit = "col%" + endlen;
289 } else if (unit == "\\paperwidth") {
290 valstring = percentval;
291 unit = "page%" + endlen;
292 } else if (unit == "\\linewidth") {
293 valstring = percentval;
294 unit = "line%" + endlen;
295 } else if (unit == "\\paperheight") {
296 valstring = percentval;
297 unit = "pheight%" + endlen;
298 } else if (unit == "\\textheight") {
299 valstring = percentval;
300 unit = "theight%" + endlen;
308 string translate_len(string const & length)
312 if (translate_len(length, value, unit))
314 // If the input is invalid, return what we have.
322 * Translates a LaTeX length into \p value, \p unit and
323 * \p special parts suitable for a box inset.
324 * The difference from translate_len() is that a box inset knows about
325 * some special "units" that are stored in \p special.
327 void translate_box_len(string const & length, string & value, string & unit, string & special)
329 if (translate_len(length, value, unit)) {
330 if (unit == "\\height" || unit == "\\depth" ||
331 unit == "\\totalheight" || unit == "\\width") {
332 special = unit.substr(1);
333 // The unit is not used, but LyX requires a dummy setting
346 * Find a file with basename \p name in path \p path and an extension
349 string find_file(string const & name, string const & path,
350 char const * const * extensions)
352 for (char const * const * what = extensions; *what; ++what) {
353 // We don't use ChangeExtension() because it does the wrong
354 // thing if name contains a dot.
355 string const trial = name + '.' + (*what);
356 if (fs::exists(makeAbsPath(trial, path)))
363 void begin_inset(ostream & os, string const & name)
365 os << "\n\\begin_inset " << name;
369 void end_inset(ostream & os)
371 os << "\n\\end_inset\n\n";
375 void skip_braces(Parser & p)
377 if (p.next_token().cat() != catBegin)
380 if (p.next_token().cat() == catEnd) {
388 void handle_ert(ostream & os, string const & s, Context & context)
390 // We must have a valid layout before outputting the ERT inset.
391 context.check_layout(os);
392 Context newcontext(true, context.textclass);
393 begin_inset(os, "ERT");
394 os << "\nstatus collapsed\n";
395 newcontext.check_layout(os);
396 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
398 os << "\n\\backslash\n";
399 else if (*it == '\n') {
400 newcontext.new_paragraph(os);
401 newcontext.check_layout(os);
405 newcontext.check_end_layout(os);
410 void handle_comment(ostream & os, string const & s, Context & context)
412 // TODO: Handle this better
413 Context newcontext(true, context.textclass);
414 begin_inset(os, "ERT");
415 os << "\nstatus collapsed\n";
416 newcontext.check_layout(os);
417 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
419 os << "\n\\backslash\n";
423 // make sure that our comment is the last thing on the line
424 newcontext.new_paragraph(os);
425 newcontext.check_layout(os);
426 newcontext.check_end_layout(os);
431 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
433 isLayout(string const name) : name_(name) {}
434 bool operator()(LyXLayout_ptr const & ptr) const {
435 return ptr->latexname() == name_;
442 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
445 LyXTextClass::const_iterator beg = textclass.begin();
446 LyXTextClass::const_iterator end = textclass.end();
448 LyXTextClass::const_iterator
449 it = std::find_if(beg, end, isLayout(name));
451 return (it == end) ? LyXLayout_ptr() : *it;
455 void eat_whitespace(Parser &, ostream &, Context &, bool);
458 void output_command_layout(ostream & os, Parser & p, bool outer,
459 Context & parent_context,
460 LyXLayout_ptr newlayout)
462 parent_context.check_end_layout(os);
463 Context context(true, parent_context.textclass, newlayout,
464 parent_context.layout, parent_context.font);
465 if (parent_context.deeper_paragraph) {
466 // We are beginning a nested environment after a
467 // deeper paragraph inside the outer list environment.
468 // Therefore we don't need to output a "begin deeper".
469 context.need_end_deeper = true;
471 context.check_deeper(os);
472 context.check_layout(os);
473 if (context.layout->optionalargs > 0) {
474 eat_whitespace(p, os, context, false);
475 if (p.next_token().character() == '[') {
476 p.get_token(); // eat '['
477 begin_inset(os, "OptArg\n");
478 os << "status collapsed\n\n";
479 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
481 eat_whitespace(p, os, context, false);
484 parse_text(p, os, FLAG_ITEM, outer, context);
485 context.check_end_layout(os);
486 if (parent_context.deeper_paragraph) {
487 // We must suppress the "end deeper" because we
488 // suppressed the "begin deeper" above.
489 context.need_end_deeper = false;
491 context.check_end_deeper(os);
492 // We don't need really a new paragraph, but
493 // we must make sure that the next item gets a \begin_layout.
494 parent_context.new_paragraph(os);
499 * Output a space if necessary.
500 * This function gets called for every whitespace token.
502 * We have three cases here:
503 * 1. A space must be suppressed. Example: The lyxcode case below
504 * 2. A space may be suppressed. Example: Spaces before "\par"
505 * 3. A space must not be suppressed. Example: A space between two words
507 * We currently handle only 1. and 3 and from 2. only the case of
508 * spaces before newlines as a side effect.
510 * 2. could be used to suppress as many spaces as possible. This has two effects:
511 * - Reimporting LyX generated LaTeX files changes almost no whitespace
512 * - Superflous whitespace from non LyX generated LaTeX files is removed.
513 * The drawback is that the logic inside the function becomes
514 * complicated, and that is the reason why it is not implemented.
516 void check_space(Parser const & p, ostream & os, Context & context)
518 Token const next = p.next_token();
519 Token const curr = p.curr_token();
520 // A space before a single newline and vice versa must be ignored
521 // LyX emits a newline before \end{lyxcode}.
522 // This newline must be ignored,
523 // otherwise LyX will add an additional protected space.
524 if (next.cat() == catSpace ||
525 next.cat() == catNewline ||
526 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
529 context.check_layout(os);
535 * Parse all arguments of \p command
537 void parse_arguments(string const & command,
538 vector<ArgumentType> const & template_arguments,
539 Parser & p, ostream & os, bool outer, Context & context)
541 string ert = command;
542 size_t no_arguments = template_arguments.size();
543 for (size_t i = 0; i < no_arguments; ++i) {
544 switch (template_arguments[i]) {
546 // This argument contains regular LaTeX
547 handle_ert(os, ert + '{', context);
548 eat_whitespace(p, os, context, false);
549 parse_text(p, os, FLAG_ITEM, outer, context);
553 // This argument may contain special characters
554 ert += '{' + p.verbatim_item() + '}';
561 handle_ert(os, ert, context);
566 * Check whether \p command is a known command. If yes,
567 * handle the command with all arguments.
568 * \return true if the command was parsed, false otherwise.
570 bool parse_command(string const & command, Parser & p, ostream & os,
571 bool outer, Context & context)
573 if (known_commands.find(command) != known_commands.end()) {
574 parse_arguments(command, known_commands[command], p, os,
582 /// Parses a minipage or parbox
583 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
584 Context & parent_context, bool use_parbox)
588 string height_value = "0";
589 string height_unit = "pt";
590 string height_special = "none";
592 if (p.next_token().asInput() == "[") {
593 position = p.getArg('[', ']');
594 if (position != "t" && position != "c" && position != "b") {
596 cerr << "invalid position for minipage/parbox" << endl;
598 if (p.next_token().asInput() == "[") {
599 latex_height = p.getArg('[', ']');
600 translate_box_len(latex_height, height_value, height_unit, height_special);
602 if (p.next_token().asInput() == "[") {
603 inner_pos = p.getArg('[', ']');
604 if (inner_pos != "c" && inner_pos != "t" &&
605 inner_pos != "b" && inner_pos != "s") {
606 inner_pos = position;
607 cerr << "invalid inner_pos for minipage/parbox"
615 string const latex_width = p.verbatim_item();
616 translate_len(latex_width, width_value, width_unit);
617 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
618 // LyX can't handle length variables
623 ss << "\\begin{minipage}";
624 if (!position.empty())
625 ss << '[' << position << ']';
626 if (!latex_height.empty())
627 ss << '[' << latex_height << ']';
628 if (!inner_pos.empty())
629 ss << '[' << inner_pos << ']';
630 ss << "{" << latex_width << "}";
633 handle_ert(os, ss.str(), parent_context);
634 parent_context.new_paragraph(os);
635 parse_text_in_inset(p, os, flags, outer, parent_context);
637 handle_ert(os, "}", parent_context);
639 handle_ert(os, "\\end{minipage}", parent_context);
641 // LyX does not like empty positions, so we have
642 // to set them to the LaTeX default values here.
643 if (position.empty())
645 if (inner_pos.empty())
646 inner_pos = position;
647 parent_context.check_layout(os);
648 begin_inset(os, "Box Frameless\n");
649 os << "position \"" << position << "\"\n";
650 os << "hor_pos \"c\"\n";
651 os << "has_inner_box 1\n";
652 os << "inner_pos \"" << inner_pos << "\"\n";
653 os << "use_parbox " << use_parbox << "\n";
654 os << "width \"" << width_value << width_unit << "\"\n";
655 os << "special \"none\"\n";
656 os << "height \"" << height_value << height_unit << "\"\n";
657 os << "height_special \"" << height_special << "\"\n";
658 os << "status open\n\n";
659 parse_text_in_inset(p, os, flags, outer, parent_context);
661 #ifdef PRESERVE_LAYOUT
662 // lyx puts a % after the end of the minipage
663 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
665 //handle_comment(os, "%dummy", parent_context);
668 parent_context.new_paragraph(os);
670 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
671 //handle_comment(os, "%dummy", parent_context);
674 // We add a protected space if something real follows
675 if (p.good() && p.next_token().cat() != catComment) {
676 os << "\\InsetSpace ~\n";
684 /// parse an unknown environment
685 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
686 unsigned flags, bool outer,
687 Context & parent_context)
689 if (name == "tabbing")
690 // We need to remember that we have to handle '\=' specially
691 flags |= FLAG_TABBING;
693 // We need to translate font changes and paragraphs inside the
694 // environment to ERT if we have a non standard font.
695 // Otherwise things like
696 // \large\begin{foo}\huge bar\end{foo}
698 bool const specialfont =
699 (parent_context.font != parent_context.normalfont);
700 bool const new_layout_allowed = parent_context.new_layout_allowed;
702 parent_context.new_layout_allowed = false;
703 handle_ert(os, "\\begin{" + name + "}", parent_context);
704 parse_text_snippet(p, os, flags, outer, parent_context);
705 handle_ert(os, "\\end{" + name + "}", parent_context);
707 parent_context.new_layout_allowed = new_layout_allowed;
711 void parse_environment(Parser & p, ostream & os, bool outer,
712 Context & parent_context)
714 LyXLayout_ptr newlayout;
715 string const name = p.getArg('{', '}');
716 const bool is_starred = suffixIs(name, '*');
717 string const unstarred_name = rtrim(name, "*");
718 active_environments.push_back(name);
720 if (is_math_env(name)) {
721 parent_context.check_layout(os);
722 begin_inset(os, "Formula ");
723 os << "\\begin{" << name << "}";
724 parse_math(p, os, FLAG_END, MATH_MODE);
725 os << "\\end{" << name << "}";
729 else if (name == "tabular" || name == "longtable") {
730 eat_whitespace(p, os, parent_context, false);
731 parent_context.check_layout(os);
732 begin_inset(os, "Tabular ");
733 handle_tabular(p, os, name == "longtable", parent_context);
738 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
739 eat_whitespace(p, os, parent_context, false);
740 parent_context.check_layout(os);
741 begin_inset(os, "Float " + unstarred_name + "\n");
742 if (p.next_token().asInput() == "[") {
743 os << "placement " << p.getArg('[', ']') << '\n';
745 os << "wide " << convert<string>(is_starred)
746 << "\nsideways false"
747 << "\nstatus open\n\n";
748 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
750 // We don't need really a new paragraph, but
751 // we must make sure that the next item gets a \begin_layout.
752 parent_context.new_paragraph(os);
756 else if (name == "minipage") {
757 eat_whitespace(p, os, parent_context, false);
758 parse_box(p, os, FLAG_END, outer, parent_context, false);
762 else if (name == "comment") {
763 eat_whitespace(p, os, parent_context, false);
764 parent_context.check_layout(os);
765 begin_inset(os, "Note Comment\n");
766 os << "status open\n";
767 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
772 else if (name == "lyxgreyedout") {
773 eat_whitespace(p, os, parent_context, false);
774 parent_context.check_layout(os);
775 begin_inset(os, "Note Greyedout\n");
776 os << "status open\n";
777 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
782 else if (!parent_context.new_layout_allowed)
783 parse_unknown_environment(p, name, os, FLAG_END, outer,
786 // Alignment settings
787 else if (name == "center" || name == "flushleft" || name == "flushright" ||
788 name == "centering" || name == "raggedright" || name == "raggedleft") {
789 eat_whitespace(p, os, parent_context, false);
790 // We must begin a new paragraph if not already done
791 if (! parent_context.atParagraphStart()) {
792 parent_context.check_end_layout(os);
793 parent_context.new_paragraph(os);
795 if (name == "flushleft" || name == "raggedright")
796 parent_context.add_extra_stuff("\\align left\n");
797 else if (name == "flushright" || name == "raggedleft")
798 parent_context.add_extra_stuff("\\align right\n");
800 parent_context.add_extra_stuff("\\align center\n");
801 parse_text(p, os, FLAG_END, outer, parent_context);
802 // Just in case the environment is empty ..
803 parent_context.extra_stuff.erase();
804 // We must begin a new paragraph to reset the alignment
805 parent_context.new_paragraph(os);
809 // The single '=' is meant here.
810 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
811 newlayout->isEnvironment()) {
812 eat_whitespace(p, os, parent_context, false);
813 Context context(true, parent_context.textclass, newlayout,
814 parent_context.layout, parent_context.font);
815 if (parent_context.deeper_paragraph) {
816 // We are beginning a nested environment after a
817 // deeper paragraph inside the outer list environment.
818 // Therefore we don't need to output a "begin deeper".
819 context.need_end_deeper = true;
821 parent_context.check_end_layout(os);
822 switch (context.layout->latextype) {
823 case LATEX_LIST_ENVIRONMENT:
824 context.extra_stuff = "\\labelwidthstring "
825 + p.verbatim_item() + '\n';
828 case LATEX_BIB_ENVIRONMENT:
829 p.verbatim_item(); // swallow next arg
835 context.check_deeper(os);
836 parse_text(p, os, FLAG_END, outer, context);
837 context.check_end_layout(os);
838 if (parent_context.deeper_paragraph) {
839 // We must suppress the "end deeper" because we
840 // suppressed the "begin deeper" above.
841 context.need_end_deeper = false;
843 context.check_end_deeper(os);
844 parent_context.new_paragraph(os);
848 else if (name == "appendix") {
849 // This is no good latex style, but it works and is used in some documents...
850 eat_whitespace(p, os, parent_context, false);
851 parent_context.check_end_layout(os);
852 Context context(true, parent_context.textclass, parent_context.layout,
853 parent_context.layout, parent_context.font);
854 context.check_layout(os);
855 os << "\\start_of_appendix\n";
856 parse_text(p, os, FLAG_END, outer, context);
857 context.check_end_layout(os);
861 else if (known_environments.find(name) != known_environments.end()) {
862 vector<ArgumentType> arguments = known_environments[name];
863 // The last "argument" denotes wether we may translate the
864 // environment contents to LyX
865 // The default required if no argument is given makes us
866 // compatible with the reLyXre environment.
867 ArgumentType contents = arguments.empty() ?
870 if (!arguments.empty())
871 arguments.pop_back();
872 // See comment in parse_unknown_environment()
873 bool const specialfont =
874 (parent_context.font != parent_context.normalfont);
875 bool const new_layout_allowed =
876 parent_context.new_layout_allowed;
878 parent_context.new_layout_allowed = false;
879 parse_arguments("\\begin{" + name + "}", arguments, p, os,
880 outer, parent_context);
881 if (contents == verbatim)
882 handle_ert(os, p.verbatimEnvironment(name),
885 parse_text_snippet(p, os, FLAG_END, outer,
887 handle_ert(os, "\\end{" + name + "}", parent_context);
889 parent_context.new_layout_allowed = new_layout_allowed;
893 parse_unknown_environment(p, name, os, FLAG_END, outer,
896 active_environments.pop_back();
900 /// parses a comment and outputs it to \p os.
901 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
903 BOOST_ASSERT(t.cat() == catComment);
904 if (!t.cs().empty()) {
905 context.check_layout(os);
906 handle_comment(os, '%' + t.cs(), context);
907 if (p.next_token().cat() == catNewline) {
908 // A newline after a comment line starts a new
910 if (context.new_layout_allowed) {
911 if(!context.atParagraphStart())
912 // Only start a new paragraph if not already
913 // done (we might get called recursively)
914 context.new_paragraph(os);
916 handle_ert(os, "\n", context);
917 eat_whitespace(p, os, context, true);
927 * Reads spaces and comments until the first non-space, non-comment token.
928 * New paragraphs (double newlines or \\par) are handled like simple spaces
929 * if \p eatParagraph is true.
930 * Spaces are skipped, but comments are written to \p os.
932 void eat_whitespace(Parser & p, ostream & os, Context & context,
936 Token const & t = p.get_token();
937 if (t.cat() == catComment)
938 parse_comment(p, os, t, context);
939 else if ((! eatParagraph && p.isParagraph()) ||
940 (t.cat() != catSpace && t.cat() != catNewline)) {
949 * Set a font attribute, parse text and reset the font attribute.
950 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
951 * \param currentvalue Current value of the attribute. Is set to the new
952 * value during parsing.
953 * \param newvalue New value of the attribute
955 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
956 Context & context, string const & attribute,
957 string & currentvalue, string const & newvalue)
959 context.check_layout(os);
960 string const oldvalue = currentvalue;
961 currentvalue = newvalue;
962 os << '\n' << attribute << ' ' << newvalue << "\n";
963 parse_text_snippet(p, os, flags, outer, context);
964 context.check_layout(os);
965 os << '\n' << attribute << ' ' << oldvalue << "\n";
966 currentvalue = oldvalue;
970 /// get the arguments of a natbib or jurabib citation command
971 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
973 // We need to distinguish "" and "[]", so we can't use p.getOpt().
975 // text before the citation
977 // text after the citation
978 string after = p.getFullOpt();
980 if (!after.empty()) {
981 before = p.getFullOpt();
982 if (natbibOrder && !before.empty())
983 std::swap(before, after);
985 return std::make_pair(before, after);
989 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
990 string const normalize_filename(string const & name)
992 Parser p(trim(name, "\""));
995 Token const & t = p.get_token();
996 if (t.cat() != catEscape)
998 else if (t.cs() == "lyxdot") {
999 // This is used by LyX for simple dots in relative
1003 } else if (t.cs() == "space") {
1013 /// Convert \p name from TeX convention (relative to master file) to LyX
1014 /// convention (relative to .lyx file) if it is relative
1015 void fix_relative_filename(string & name)
1017 if (lyx::support::absolutePath(name))
1019 name = makeRelPath(makeAbsPath(name, getMasterFilePath()),
1020 getParentFilePath());
1024 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1025 void parse_noweb(Parser & p, ostream & os, Context & context)
1027 // assemble the rest of the keyword
1031 Token const & t = p.get_token();
1032 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1035 scrap = (p.good() && p.next_token().asInput() == "=");
1037 name += p.get_token().asInput();
1040 name += t.asInput();
1043 if (!scrap || !context.new_layout_allowed ||
1044 !context.textclass.hasLayout("Scrap")) {
1045 cerr << "Warning: Could not interpret '" << name
1046 << "'. Ignoring it." << endl;
1050 context.check_end_layout(os);
1051 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1052 newcontext.check_layout(os);
1055 Token const & t = p.get_token();
1056 // We abuse the parser a bit, because this is no TeX syntax
1058 if (t.cat() == catEscape)
1059 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1061 os << subst(t.asInput(), "\n", "\n\\newline\n");
1062 // The scrap chunk is ended by an @ at the beginning of a line.
1063 // After the @ the line may contain a comment and/or
1064 // whitespace, but nothing else.
1065 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1066 (p.next_token().cat() == catSpace ||
1067 p.next_token().cat() == catNewline ||
1068 p.next_token().cat() == catComment)) {
1069 while (p.good() && p.next_token().cat() == catSpace)
1070 os << p.get_token().asInput();
1071 if (p.next_token().cat() == catComment)
1072 // The comment includes a final '\n'
1073 os << p.get_token().asInput();
1075 if (p.next_token().cat() == catNewline)
1082 newcontext.check_end_layout(os);
1085 } // anonymous namespace
1088 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1091 LyXLayout_ptr newlayout;
1092 // Store the latest bibliographystyle (needed for bibtex inset)
1093 string bibliographystyle;
1094 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1095 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1097 Token const & t = p.get_token();
1100 cerr << "t: " << t << " flags: " << flags << "\n";
1103 if (flags & FLAG_ITEM) {
1104 if (t.cat() == catSpace)
1107 flags &= ~FLAG_ITEM;
1108 if (t.cat() == catBegin) {
1109 // skip the brace and collect everything to the next matching
1111 flags |= FLAG_BRACE_LAST;
1115 // handle only this single token, leave the loop if done
1116 flags |= FLAG_LEAVE;
1119 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1125 if (t.cat() == catMath) {
1126 // we are inside some text mode thingy, so opening new math is allowed
1127 context.check_layout(os);
1128 begin_inset(os, "Formula ");
1129 Token const & n = p.get_token();
1130 if (n.cat() == catMath && outer) {
1131 // TeX's $$...$$ syntax for displayed math
1133 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1135 p.get_token(); // skip the second '$' token
1137 // simple $...$ stuff
1140 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1146 else if (t.cat() == catSuper || t.cat() == catSub)
1147 cerr << "catcode " << t << " illegal in text mode\n";
1149 // Basic support for english quotes. This should be
1150 // extended to other quotes, but is not so easy (a
1151 // left english quote is the same as a right german
1153 else if (t.asInput() == "`"
1154 && p.next_token().asInput() == "`") {
1155 context.check_layout(os);
1156 begin_inset(os, "Quotes ");
1162 else if (t.asInput() == "'"
1163 && p.next_token().asInput() == "'") {
1164 context.check_layout(os);
1165 begin_inset(os, "Quotes ");
1172 else if (t.asInput() == "<"
1173 && p.next_token().asInput() == "<" && noweb_mode) {
1175 parse_noweb(p, os, context);
1178 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1179 check_space(p, os, context);
1181 else if (t.character() == '[' && noweb_mode &&
1182 p.next_token().character() == '[') {
1183 // These can contain underscores
1185 string const s = p.getFullOpt() + ']';
1186 if (p.next_token().character() == ']')
1189 cerr << "Warning: Inserting missing ']' in '"
1190 << s << "'." << endl;
1191 handle_ert(os, s, context);
1194 else if (t.cat() == catLetter ||
1195 t.cat() == catOther ||
1196 t.cat() == catAlign ||
1197 t.cat() == catParameter) {
1198 // This translates "&" to "\\&" which may be wrong...
1199 context.check_layout(os);
1200 os << t.character();
1203 else if (p.isParagraph()) {
1204 if (context.new_layout_allowed)
1205 context.new_paragraph(os);
1207 handle_ert(os, "\\par ", context);
1208 eat_whitespace(p, os, context, true);
1211 else if (t.cat() == catActive) {
1212 context.check_layout(os);
1213 if (t.character() == '~') {
1214 if (context.layout->free_spacing)
1217 os << "\\InsetSpace ~\n";
1219 os << t.character();
1222 else if (t.cat() == catBegin &&
1223 p.next_token().cat() == catEnd) {
1225 Token const prev = p.prev_token();
1227 if (p.next_token().character() == '`' ||
1228 (prev.character() == '-' &&
1229 p.next_token().character() == '-'))
1230 ; // ignore it in {}`` or -{}-
1232 handle_ert(os, "{}", context);
1236 else if (t.cat() == catBegin) {
1237 context.check_layout(os);
1238 // special handling of font attribute changes
1239 Token const prev = p.prev_token();
1240 Token const next = p.next_token();
1241 Font const oldFont = context.font;
1242 if (next.character() == '[' ||
1243 next.character() == ']' ||
1244 next.character() == '*') {
1246 if (p.next_token().cat() == catEnd) {
1247 os << next.character();
1251 handle_ert(os, "{", context);
1252 parse_text_snippet(p, os,
1255 handle_ert(os, "}", context);
1257 } else if (! context.new_layout_allowed) {
1258 handle_ert(os, "{", context);
1259 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1261 handle_ert(os, "}", context);
1262 } else if (is_known(next.cs(), known_sizes)) {
1263 // next will change the size, so we must
1265 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1267 if (!context.atParagraphStart())
1269 << context.font.size << "\n";
1270 } else if (is_known(next.cs(), known_font_families)) {
1271 // next will change the font family, so we
1272 // must reset it here
1273 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1275 if (!context.atParagraphStart())
1277 << context.font.family << "\n";
1278 } else if (is_known(next.cs(), known_font_series)) {
1279 // next will change the font series, so we
1280 // must reset it here
1281 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1283 if (!context.atParagraphStart())
1285 << context.font.series << "\n";
1286 } else if (is_known(next.cs(), known_font_shapes)) {
1287 // next will change the font shape, so we
1288 // must reset it here
1289 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1291 if (!context.atParagraphStart())
1293 << context.font.shape << "\n";
1294 } else if (is_known(next.cs(), known_old_font_families) ||
1295 is_known(next.cs(), known_old_font_series) ||
1296 is_known(next.cs(), known_old_font_shapes)) {
1297 // next will change the font family, series
1298 // and shape, so we must reset it here
1299 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1301 if (!context.atParagraphStart())
1303 << context.font.family
1305 << context.font.series
1307 << context.font.shape << "\n";
1309 handle_ert(os, "{", context);
1310 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1312 handle_ert(os, "}", context);
1316 else if (t.cat() == catEnd) {
1317 if (flags & FLAG_BRACE_LAST) {
1320 cerr << "stray '}' in text\n";
1321 handle_ert(os, "}", context);
1324 else if (t.cat() == catComment)
1325 parse_comment(p, os, t, context);
1328 // control sequences
1331 else if (t.cs() == "(") {
1332 context.check_layout(os);
1333 begin_inset(os, "Formula");
1335 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1340 else if (t.cs() == "[") {
1341 context.check_layout(os);
1342 begin_inset(os, "Formula");
1344 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1349 else if (t.cs() == "begin")
1350 parse_environment(p, os, outer, context);
1352 else if (t.cs() == "end") {
1353 if (flags & FLAG_END) {
1354 // eat environment name
1355 string const name = p.getArg('{', '}');
1356 if (name != active_environment())
1357 cerr << "\\end{" + name + "} does not match \\begin{"
1358 + active_environment() + "}\n";
1361 p.error("found 'end' unexpectedly");
1364 else if (t.cs() == "item") {
1367 bool optarg = false;
1368 if (p.next_token().character() == '[') {
1369 p.get_token(); // eat '['
1370 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1375 context.check_layout(os);
1376 if (context.has_item) {
1377 // An item in an unknown list-like environment
1378 // FIXME: Do this in check_layout()!
1379 context.has_item = false;
1381 handle_ert(os, "\\item", context);
1383 handle_ert(os, "\\item ", context);
1386 if (context.layout->labeltype != LABEL_MANUAL) {
1387 // lyx does not support \item[\mybullet]
1388 // in itemize environments
1389 handle_ert(os, "[", context);
1391 handle_ert(os, "]", context);
1392 } else if (!s.empty()) {
1393 // The space is needed to separate the
1394 // item from the rest of the sentence.
1396 eat_whitespace(p, os, context, false);
1401 else if (t.cs() == "bibitem") {
1403 context.check_layout(os);
1406 os << '{' << p.verbatim_item() << '}' << "\n";
1409 else if (t.cs() == "def") {
1410 context.check_layout(os);
1411 eat_whitespace(p, os, context, false);
1412 string name = p.get_token().cs();
1413 while (p.next_token().cat() != catBegin)
1414 name += p.get_token().asString();
1415 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1418 else if (t.cs() == "noindent") {
1420 context.add_extra_stuff("\\noindent\n");
1423 else if (t.cs() == "appendix") {
1424 context.add_extra_stuff("\\start_of_appendix\n");
1425 // We need to start a new paragraph. Otherwise the
1426 // appendix in 'bla\appendix\chapter{' would start
1428 context.new_paragraph(os);
1429 // We need to make sure that the paragraph is
1430 // generated even if it is empty. Otherwise the
1431 // appendix in '\par\appendix\par\chapter{' would
1433 context.check_layout(os);
1434 // FIXME: This is a hack to prevent paragraph
1435 // deletion if it is empty. Handle this better!
1437 "%dummy comment inserted by tex2lyx to "
1438 "ensure that this paragraph is not empty",
1440 // Both measures above may generate an additional
1441 // empty paragraph, but that does not hurt, because
1442 // whitespace does not matter here.
1443 eat_whitespace(p, os, context, true);
1446 // Must attempt to parse "Section*" before "Section".
1447 else if ((p.next_token().asInput() == "*") &&
1448 context.new_layout_allowed &&
1449 // The single '=' is meant here.
1450 (newlayout = findLayout(context.textclass,
1451 t.cs() + '*')).get() &&
1452 newlayout->isCommand()) {
1454 output_command_layout(os, p, outer, context, newlayout);
1458 // The single '=' is meant here.
1459 else if (context.new_layout_allowed &&
1460 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1461 newlayout->isCommand()) {
1462 output_command_layout(os, p, outer, context, newlayout);
1466 else if (t.cs() == "includegraphics") {
1467 bool const clip = p.next_token().asInput() == "*";
1470 map<string, string> opts = split_map(p.getArg('[', ']'));
1472 opts["clip"] = string();
1473 string name = normalize_filename(p.verbatim_item());
1475 string const path = getMasterFilePath();
1476 // We want to preserve relative / absolute filenames,
1477 // therefore path is only used for testing
1478 if (!fs::exists(makeAbsPath(name, path))) {
1479 // The file extension is probably missing.
1480 // Now try to find it out.
1481 string const dvips_name =
1482 find_file(name, path,
1483 known_dvips_graphics_formats);
1484 string const pdftex_name =
1485 find_file(name, path,
1486 known_pdftex_graphics_formats);
1487 if (!dvips_name.empty()) {
1488 if (!pdftex_name.empty()) {
1489 cerr << "This file contains the "
1491 "\"\\includegraphics{"
1493 "However, files\n\""
1494 << dvips_name << "\" and\n\""
1495 << pdftex_name << "\"\n"
1496 "both exist, so I had to make a "
1497 "choice and took the first one.\n"
1498 "Please move the unwanted one "
1499 "someplace else and try again\n"
1500 "if my choice was wrong."
1504 } else if (!pdftex_name.empty())
1508 if (fs::exists(makeAbsPath(name, path)))
1509 fix_relative_filename(name);
1511 cerr << "Warning: Could not find graphics file '"
1512 << name << "'." << endl;
1514 context.check_layout(os);
1515 begin_inset(os, "Graphics ");
1516 os << "\n\tfilename " << name << '\n';
1517 if (opts.find("width") != opts.end())
1519 << translate_len(opts["width"]) << '\n';
1520 if (opts.find("height") != opts.end())
1522 << translate_len(opts["height"]) << '\n';
1523 if (opts.find("scale") != opts.end()) {
1524 istringstream iss(opts["scale"]);
1528 os << "\tscale " << val << '\n';
1530 if (opts.find("angle") != opts.end())
1531 os << "\trotateAngle "
1532 << opts["angle"] << '\n';
1533 if (opts.find("origin") != opts.end()) {
1535 string const opt = opts["origin"];
1536 if (opt.find('l') != string::npos) ss << "left";
1537 if (opt.find('r') != string::npos) ss << "right";
1538 if (opt.find('c') != string::npos) ss << "center";
1539 if (opt.find('t') != string::npos) ss << "Top";
1540 if (opt.find('b') != string::npos) ss << "Bottom";
1541 if (opt.find('B') != string::npos) ss << "Baseline";
1542 if (!ss.str().empty())
1543 os << "\trotateOrigin " << ss.str() << '\n';
1545 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1547 if (opts.find("keepaspectratio") != opts.end())
1548 os << "\tkeepAspectRatio\n";
1549 if (opts.find("clip") != opts.end())
1551 if (opts.find("draft") != opts.end())
1553 if (opts.find("bb") != opts.end())
1554 os << "\tBoundingBox "
1555 << opts["bb"] << '\n';
1556 int numberOfbbOptions = 0;
1557 if (opts.find("bbllx") != opts.end())
1558 numberOfbbOptions++;
1559 if (opts.find("bblly") != opts.end())
1560 numberOfbbOptions++;
1561 if (opts.find("bburx") != opts.end())
1562 numberOfbbOptions++;
1563 if (opts.find("bbury") != opts.end())
1564 numberOfbbOptions++;
1565 if (numberOfbbOptions == 4)
1566 os << "\tBoundingBox "
1567 << opts["bbllx"] << opts["bblly"]
1568 << opts["bburx"] << opts["bbury"] << '\n';
1569 else if (numberOfbbOptions > 0)
1570 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1571 numberOfbbOptions = 0;
1572 if (opts.find("natwidth") != opts.end())
1573 numberOfbbOptions++;
1574 if (opts.find("natheight") != opts.end())
1575 numberOfbbOptions++;
1576 if (numberOfbbOptions == 2)
1577 os << "\tBoundingBox 0bp 0bp "
1578 << opts["natwidth"] << opts["natheight"] << '\n';
1579 else if (numberOfbbOptions > 0)
1580 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1581 ostringstream special;
1582 if (opts.find("hiresbb") != opts.end())
1583 special << "hiresbb,";
1584 if (opts.find("trim") != opts.end())
1586 if (opts.find("viewport") != opts.end())
1587 special << "viewport=" << opts["viewport"] << ',';
1588 if (opts.find("totalheight") != opts.end())
1589 special << "totalheight=" << opts["totalheight"] << ',';
1590 if (opts.find("type") != opts.end())
1591 special << "type=" << opts["type"] << ',';
1592 if (opts.find("ext") != opts.end())
1593 special << "ext=" << opts["ext"] << ',';
1594 if (opts.find("read") != opts.end())
1595 special << "read=" << opts["read"] << ',';
1596 if (opts.find("command") != opts.end())
1597 special << "command=" << opts["command"] << ',';
1598 string s_special = special.str();
1599 if (!s_special.empty()) {
1600 // We had special arguments. Remove the trailing ','.
1601 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1603 // TODO: Handle the unknown settings better.
1604 // Warn about invalid options.
1605 // Check whether some option was given twice.
1609 else if (t.cs() == "footnote" ||
1610 (t.cs() == "thanks" && context.layout->intitle)) {
1612 context.check_layout(os);
1613 begin_inset(os, "Foot\n");
1614 os << "status collapsed\n\n";
1615 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1619 else if (t.cs() == "marginpar") {
1621 context.check_layout(os);
1622 begin_inset(os, "Marginal\n");
1623 os << "status collapsed\n\n";
1624 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1628 else if (t.cs() == "ensuremath") {
1630 context.check_layout(os);
1631 string const s = p.verbatim_item();
1632 if (s == "±" || s == "³" || s == "²" || s == "µ")
1635 handle_ert(os, "\\ensuremath{" + s + "}",
1639 else if (t.cs() == "hfill") {
1640 context.check_layout(os);
1641 os << "\n\\hfill\n";
1646 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1647 // FIXME: Somehow prevent title layouts if
1648 // "maketitle" was not found
1650 skip_braces(p); // swallow this
1653 else if (t.cs() == "tableofcontents") {
1655 context.check_layout(os);
1656 begin_inset(os, "LatexCommand \\tableofcontents\n");
1658 skip_braces(p); // swallow this
1661 else if (t.cs() == "listoffigures") {
1663 context.check_layout(os);
1664 begin_inset(os, "FloatList figure\n");
1666 skip_braces(p); // swallow this
1669 else if (t.cs() == "listoftables") {
1671 context.check_layout(os);
1672 begin_inset(os, "FloatList table\n");
1674 skip_braces(p); // swallow this
1677 else if (t.cs() == "listof") {
1678 p.skip_spaces(true);
1679 string const name = p.get_token().asString();
1680 if (context.textclass.floats().typeExist(name)) {
1681 context.check_layout(os);
1682 begin_inset(os, "FloatList ");
1685 p.get_token(); // swallow second arg
1687 handle_ert(os, "\\listof{" + name + "}", context);
1690 else if (t.cs() == "textrm")
1691 parse_text_attributes(p, os, FLAG_ITEM, outer,
1692 context, "\\family",
1693 context.font.family, "roman");
1695 else if (t.cs() == "textsf")
1696 parse_text_attributes(p, os, FLAG_ITEM, outer,
1697 context, "\\family",
1698 context.font.family, "sans");
1700 else if (t.cs() == "texttt")
1701 parse_text_attributes(p, os, FLAG_ITEM, outer,
1702 context, "\\family",
1703 context.font.family, "typewriter");
1705 else if (t.cs() == "textmd")
1706 parse_text_attributes(p, os, FLAG_ITEM, outer,
1707 context, "\\series",
1708 context.font.series, "medium");
1710 else if (t.cs() == "textbf")
1711 parse_text_attributes(p, os, FLAG_ITEM, outer,
1712 context, "\\series",
1713 context.font.series, "bold");
1715 else if (t.cs() == "textup")
1716 parse_text_attributes(p, os, FLAG_ITEM, outer,
1718 context.font.shape, "up");
1720 else if (t.cs() == "textit")
1721 parse_text_attributes(p, os, FLAG_ITEM, outer,
1723 context.font.shape, "italic");
1725 else if (t.cs() == "textsl")
1726 parse_text_attributes(p, os, FLAG_ITEM, outer,
1728 context.font.shape, "slanted");
1730 else if (t.cs() == "textsc")
1731 parse_text_attributes(p, os, FLAG_ITEM, outer,
1733 context.font.shape, "smallcaps");
1735 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1736 context.check_layout(os);
1737 Font oldFont = context.font;
1738 context.font.init();
1739 context.font.size = oldFont.size;
1740 os << "\n\\family " << context.font.family << "\n";
1741 os << "\n\\series " << context.font.series << "\n";
1742 os << "\n\\shape " << context.font.shape << "\n";
1743 if (t.cs() == "textnormal") {
1744 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1745 output_font_change(os, context.font, oldFont);
1746 context.font = oldFont;
1748 eat_whitespace(p, os, context, false);
1751 else if (t.cs() == "underbar") {
1752 // Do NOT handle \underline.
1753 // \underbar cuts through y, g, q, p etc.,
1754 // \underline does not.
1755 context.check_layout(os);
1756 os << "\n\\bar under\n";
1757 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1758 context.check_layout(os);
1759 os << "\n\\bar default\n";
1762 else if (t.cs() == "emph" || t.cs() == "noun") {
1763 context.check_layout(os);
1764 os << "\n\\" << t.cs() << " on\n";
1765 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1766 context.check_layout(os);
1767 os << "\n\\" << t.cs() << " default\n";
1770 else if (use_natbib &&
1771 is_known(t.cs(), known_natbib_commands) &&
1772 ((t.cs() != "citefullauthor" &&
1773 t.cs() != "citeyear" &&
1774 t.cs() != "citeyearpar") ||
1775 p.next_token().asInput() != "*")) {
1776 context.check_layout(os);
1778 // \citet[before][after]{a} \citet[after][before]{a}
1779 // \citet[before][]{a} \citet[][before]{a}
1780 // \citet[after]{a} \citet[after]{a}
1781 // \citet{a} \citet{a}
1782 string command = '\\' + t.cs();
1783 if (p.next_token().asInput() == "*") {
1787 if (command == "\\citefullauthor")
1788 // alternative name for "\\citeauthor*"
1789 command = "\\citeauthor*";
1791 // text before the citation
1793 // text after the citation
1796 boost::tie(before, after) = getCiteArguments(p, true);
1797 if (command == "\\cite") {
1798 // \cite without optional argument means
1799 // \citet, \cite with at least one optional
1800 // argument means \citep.
1801 if (before.empty() && after.empty())
1802 command = "\\citet";
1804 command = "\\citep";
1806 if (before.empty() && after == "[]")
1807 // avoid \citet[]{a}
1809 else if (before == "[]" && after == "[]") {
1810 // avoid \citet[][]{a}
1814 begin_inset(os, "LatexCommand ");
1815 os << command << after << before
1816 << '{' << p.verbatim_item() << "}\n";
1820 else if (use_jurabib &&
1821 is_known(t.cs(), known_jurabib_commands)) {
1822 context.check_layout(os);
1823 string const command = '\\' + t.cs();
1824 char argumentOrder = '\0';
1825 vector<string> const & options = used_packages["jurabib"];
1826 if (std::find(options.begin(), options.end(),
1827 "natbiborder") != options.end())
1828 argumentOrder = 'n';
1829 else if (std::find(options.begin(), options.end(),
1830 "jurabiborder") != options.end())
1831 argumentOrder = 'j';
1833 // text before the citation
1835 // text after the citation
1838 boost::tie(before, after) =
1839 getCiteArguments(p, argumentOrder != 'j');
1840 string const citation = p.verbatim_item();
1841 if (!before.empty() && argumentOrder == '\0') {
1842 cerr << "Warning: Assuming argument order "
1843 "of jurabib version 0.6 for\n'"
1844 << command << before << after << '{'
1845 << citation << "}'.\n"
1846 "Add 'jurabiborder' to the jurabib "
1847 "package options if you used an\n"
1848 "earlier jurabib version." << endl;
1850 begin_inset(os, "LatexCommand ");
1851 os << command << after << before
1852 << '{' << citation << "}\n";
1856 else if (is_known(t.cs(), known_latex_commands)) {
1857 // This needs to be after the check for natbib and
1858 // jurabib commands, because "cite" has different
1859 // arguments with natbib and jurabib.
1860 context.check_layout(os);
1861 begin_inset(os, "LatexCommand ");
1862 os << '\\' << t.cs();
1863 // lyx cannot handle newlines in a latex command
1864 // FIXME: Move the substitution into parser::getOpt()?
1865 os << subst(p.getOpt(), "\n", " ");
1866 os << subst(p.getOpt(), "\n", " ");
1867 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1871 else if (is_known(t.cs(), known_quotes)) {
1872 char const * const * where = is_known(t.cs(), known_quotes);
1873 context.check_layout(os);
1874 begin_inset(os, "Quotes ");
1875 os << known_coded_quotes[where - known_quotes];
1877 // LyX adds {} after the quote, so we have to eat
1878 // spaces here if there are any before a possible
1880 eat_whitespace(p, os, context, false);
1884 else if (is_known(t.cs(), known_sizes) &&
1885 context.new_layout_allowed) {
1886 char const * const * where = is_known(t.cs(), known_sizes);
1887 context.check_layout(os);
1888 Font const oldFont = context.font;
1889 context.font.size = known_coded_sizes[where - known_sizes];
1890 output_font_change(os, oldFont, context.font);
1891 eat_whitespace(p, os, context, false);
1894 else if (is_known(t.cs(), known_font_families) &&
1895 context.new_layout_allowed) {
1896 char const * const * where =
1897 is_known(t.cs(), known_font_families);
1898 context.check_layout(os);
1899 Font const oldFont = context.font;
1900 context.font.family =
1901 known_coded_font_families[where - known_font_families];
1902 output_font_change(os, oldFont, context.font);
1903 eat_whitespace(p, os, context, false);
1906 else if (is_known(t.cs(), known_font_series) &&
1907 context.new_layout_allowed) {
1908 char const * const * where =
1909 is_known(t.cs(), known_font_series);
1910 context.check_layout(os);
1911 Font const oldFont = context.font;
1912 context.font.series =
1913 known_coded_font_series[where - known_font_series];
1914 output_font_change(os, oldFont, context.font);
1915 eat_whitespace(p, os, context, false);
1918 else if (is_known(t.cs(), known_font_shapes) &&
1919 context.new_layout_allowed) {
1920 char const * const * where =
1921 is_known(t.cs(), known_font_shapes);
1922 context.check_layout(os);
1923 Font const oldFont = context.font;
1924 context.font.shape =
1925 known_coded_font_shapes[where - known_font_shapes];
1926 output_font_change(os, oldFont, context.font);
1927 eat_whitespace(p, os, context, false);
1929 else if (is_known(t.cs(), known_old_font_families) &&
1930 context.new_layout_allowed) {
1931 char const * const * where =
1932 is_known(t.cs(), known_old_font_families);
1933 context.check_layout(os);
1934 Font const oldFont = context.font;
1935 context.font.init();
1936 context.font.size = oldFont.size;
1937 context.font.family =
1938 known_coded_font_families[where - known_old_font_families];
1939 output_font_change(os, oldFont, context.font);
1940 eat_whitespace(p, os, context, false);
1943 else if (is_known(t.cs(), known_old_font_series) &&
1944 context.new_layout_allowed) {
1945 char const * const * where =
1946 is_known(t.cs(), known_old_font_series);
1947 context.check_layout(os);
1948 Font const oldFont = context.font;
1949 context.font.init();
1950 context.font.size = oldFont.size;
1951 context.font.series =
1952 known_coded_font_series[where - known_old_font_series];
1953 output_font_change(os, oldFont, context.font);
1954 eat_whitespace(p, os, context, false);
1957 else if (is_known(t.cs(), known_old_font_shapes) &&
1958 context.new_layout_allowed) {
1959 char const * const * where =
1960 is_known(t.cs(), known_old_font_shapes);
1961 context.check_layout(os);
1962 Font const oldFont = context.font;
1963 context.font.init();
1964 context.font.size = oldFont.size;
1965 context.font.shape =
1966 known_coded_font_shapes[where - known_old_font_shapes];
1967 output_font_change(os, oldFont, context.font);
1968 eat_whitespace(p, os, context, false);
1971 else if (t.cs() == "LyX" || t.cs() == "TeX"
1972 || t.cs() == "LaTeX") {
1973 context.check_layout(os);
1975 skip_braces(p); // eat {}
1978 else if (t.cs() == "LaTeXe") {
1979 context.check_layout(os);
1981 skip_braces(p); // eat {}
1984 else if (t.cs() == "ldots") {
1985 context.check_layout(os);
1987 os << "\\SpecialChar \\ldots{}\n";
1990 else if (t.cs() == "lyxarrow") {
1991 context.check_layout(os);
1992 os << "\\SpecialChar \\menuseparator\n";
1996 else if (t.cs() == "textcompwordmark") {
1997 context.check_layout(os);
1998 os << "\\SpecialChar \\textcompwordmark{}\n";
2002 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2003 context.check_layout(os);
2004 os << "\\SpecialChar \\@.\n";
2008 else if (t.cs() == "-") {
2009 context.check_layout(os);
2010 os << "\\SpecialChar \\-\n";
2013 else if (t.cs() == "textasciitilde") {
2014 context.check_layout(os);
2019 else if (t.cs() == "textasciicircum") {
2020 context.check_layout(os);
2025 else if (t.cs() == "textbackslash") {
2026 context.check_layout(os);
2027 os << "\n\\backslash\n";
2031 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2032 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2034 context.check_layout(os);
2038 else if (t.cs() == "char") {
2039 context.check_layout(os);
2040 if (p.next_token().character() == '`') {
2042 if (p.next_token().cs() == "\"") {
2047 handle_ert(os, "\\char`", context);
2050 handle_ert(os, "\\char", context);
2054 else if (t.cs() == "verb") {
2055 context.check_layout(os);
2056 char const delimiter = p.next_token().character();
2057 string const arg = p.getArg(delimiter, delimiter);
2059 oss << "\\verb" << delimiter << arg << delimiter;
2060 handle_ert(os, oss.str(), context);
2063 else if (t.cs() == "\"") {
2064 context.check_layout(os);
2065 string const name = p.verbatim_item();
2066 if (name == "a") os << 'ä';
2067 else if (name == "o") os << 'ö';
2068 else if (name == "u") os << 'ü';
2069 else if (name == "A") os << 'Ä';
2070 else if (name == "O") os << 'Ö';
2071 else if (name == "U") os << 'Ü';
2072 else handle_ert(os, "\"{" + name + "}", context);
2075 // Problem: \= creates a tabstop inside the tabbing environment
2076 // and else an accent. In the latter case we really would want
2077 // \={o} instead of \= o.
2078 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2079 handle_ert(os, t.asInput(), context);
2081 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2082 || t.cs() == "'" || t.cs() == "`"
2083 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2084 // we need the trim as the LyX parser chokes on such spaces
2085 context.check_layout(os);
2086 os << "\n\\i \\" << t.cs() << "{"
2087 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2091 else if (t.cs() == "ss") {
2092 context.check_layout(os);
2094 skip_braces(p); // eat {}
2097 else if (t.cs() == "i" || t.cs() == "j") {
2098 context.check_layout(os);
2099 os << "\\" << t.cs() << ' ';
2100 skip_braces(p); // eat {}
2103 else if (t.cs() == "\\") {
2104 context.check_layout(os);
2105 string const next = p.next_token().asInput();
2107 handle_ert(os, "\\\\" + p.getOpt(), context);
2108 else if (next == "*") {
2110 handle_ert(os, "\\\\*" + p.getOpt(), context);
2113 os << "\n\\newline\n";
2117 else if (t.cs() == "input" || t.cs() == "include"
2118 || t.cs() == "verbatiminput") {
2119 string name = '\\' + t.cs();
2120 if (t.cs() == "verbatiminput"
2121 && p.next_token().asInput() == "*")
2122 name += p.get_token().asInput();
2123 context.check_layout(os);
2124 begin_inset(os, "Include ");
2125 string filename(normalize_filename(p.getArg('{', '}')));
2126 string const path = getMasterFilePath();
2127 // We want to preserve relative / absolute filenames,
2128 // therefore path is only used for testing
2129 if (t.cs() == "include" &&
2130 !fs::exists(makeAbsPath(filename, path))) {
2131 // The file extension is probably missing.
2132 // Now try to find it out.
2133 string const tex_name =
2134 find_file(filename, path,
2135 known_tex_extensions);
2136 if (!tex_name.empty())
2137 filename = tex_name;
2139 if (fs::exists(makeAbsPath(filename, path))) {
2140 string const abstexname =
2141 makeAbsPath(filename, path);
2142 string const abslyxname =
2143 changeExtension(abstexname, ".lyx");
2144 fix_relative_filename(filename);
2145 string const lyxname =
2146 changeExtension(filename, ".lyx");
2147 if (t.cs() != "verbatiminput" &&
2148 tex2lyx(abstexname, abslyxname)) {
2149 os << name << '{' << lyxname << "}\n";
2151 os << name << '{' << filename << "}\n";
2154 cerr << "Warning: Could not find included file '"
2155 << filename << "'." << endl;
2156 os << name << '{' << filename << "}\n";
2158 os << "preview false\n";
2162 else if (t.cs() == "bibliographystyle") {
2163 // store new bibliographystyle
2164 bibliographystyle = p.verbatim_item();
2165 // output new bibliographystyle.
2166 // This is only necessary if used in some other macro than \bibliography.
2167 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2170 else if (t.cs() == "bibliography") {
2171 context.check_layout(os);
2172 begin_inset(os, "LatexCommand ");
2174 // Do we have a bibliographystyle set?
2175 if (!bibliographystyle.empty()) {
2176 os << '[' << bibliographystyle << ']';
2178 os << '{' << p.verbatim_item() << "}\n";
2182 else if (t.cs() == "parbox")
2183 parse_box(p, os, FLAG_ITEM, outer, context, true);
2185 else if (t.cs() == "smallskip" ||
2186 t.cs() == "medskip" ||
2187 t.cs() == "bigskip" ||
2188 t.cs() == "vfill") {
2189 context.check_layout(os);
2190 begin_inset(os, "VSpace ");
2196 else if (is_known(t.cs(), known_spaces)) {
2197 char const * const * where = is_known(t.cs(), known_spaces);
2198 context.check_layout(os);
2199 begin_inset(os, "InsetSpace ");
2200 os << '\\' << known_coded_spaces[where - known_spaces]
2202 // LaTeX swallows whitespace after all spaces except
2203 // "\\,". We have to do that here, too, because LyX
2204 // adds "{}" which would make the spaces significant.
2206 eat_whitespace(p, os, context, false);
2207 // LyX adds "{}" after all spaces except "\\ " and
2208 // "\\,", so we have to remove "{}".
2209 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2210 // remove the braces after "\\,", too.
2215 else if (t.cs() == "newpage") {
2216 context.check_layout(os);
2217 // FIXME: what about \\clearpage and \\pagebreak?
2218 os << "\n\\newpage\n";
2219 skip_braces(p); // eat {}
2222 else if (t.cs() == "newcommand" ||
2223 t.cs() == "providecommand" ||
2224 t.cs() == "renewcommand") {
2225 // these could be handled by parse_command(), but
2226 // we need to call add_known_command() here.
2227 string name = t.asInput();
2228 if (p.next_token().asInput() == "*") {
2229 // Starred form. Eat '*'
2233 string const command = p.verbatim_item();
2234 string const opt1 = p.getOpt();
2235 string const opt2 = p.getFullOpt();
2236 add_known_command(command, opt1, !opt2.empty());
2237 string const ert = name + '{' + command + '}' +
2239 '{' + p.verbatim_item() + '}';
2240 handle_ert(os, ert, context);
2243 else if (t.cs() == "vspace") {
2244 bool starred = false;
2245 if (p.next_token().asInput() == "*") {
2249 string const length = p.verbatim_item();
2252 bool valid = splitLatexLength(length, valstring, unit);
2253 bool known_vspace = false;
2254 bool known_unit = false;
2257 istringstream iss(valstring);
2260 if (unit == "\\smallskipamount") {
2262 known_vspace = true;
2263 } else if (unit == "\\medskipamount") {
2265 known_vspace = true;
2266 } else if (unit == "\\bigskipamount") {
2268 known_vspace = true;
2269 } else if (unit == "\\fill") {
2271 known_vspace = true;
2274 if (!known_vspace) {
2275 switch (unitFromString(unit)) {
2296 if (known_unit || known_vspace) {
2297 // Literal length or known variable
2298 context.check_layout(os);
2299 begin_inset(os, "VSpace ");
2307 // LyX can't handle other length variables in Inset VSpace
2308 string name = t.asInput();
2313 handle_ert(os, name + '{' + unit + '}', context);
2314 else if (value == -1.0)
2315 handle_ert(os, name + "{-" + unit + '}', context);
2317 handle_ert(os, name + '{' + valstring + unit + '}', context);
2319 handle_ert(os, name + '{' + length + '}', context);
2324 //cerr << "#: " << t << " mode: " << mode << endl;
2325 // heuristic: read up to next non-nested space
2327 string s = t.asInput();
2328 string z = p.verbatim_item();
2329 while (p.good() && z != " " && z.size()) {
2330 //cerr << "read: " << z << endl;
2332 z = p.verbatim_item();
2334 cerr << "found ERT: " << s << endl;
2335 handle_ert(os, s + ' ', context);
2337 string name = t.asInput();
2338 if (p.next_token().asInput() == "*") {
2339 // Starred commands like \vspace*{}
2340 p.get_token(); // Eat '*'
2343 if (! parse_command(name, p, os, outer, context))
2344 handle_ert(os, name, context);
2347 if (flags & FLAG_LEAVE) {
2348 flags &= ~FLAG_LEAVE;