3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
32 using lyx::support::ChangeExtension;
33 using lyx::support::MakeAbsPath;
34 using lyx::support::MakeRelPath;
35 using lyx::support::rtrim;
36 using lyx::support::suffixIs;
37 using lyx::support::contains;
38 using lyx::support::subst;
45 using std::ostringstream;
46 using std::istringstream;
50 namespace fs = boost::filesystem;
53 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
54 Context const & context)
56 Context newcontext(true, context.textclass);
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 /// parses a paragraph snippet, useful for example for \\emph{...}
66 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
69 Context newcontext(context);
70 // Don't inherit the extra stuff
71 newcontext.extra_stuff.clear();
72 parse_text(p, os, flags, outer, newcontext);
73 // Make sure that we don't create invalid .lyx files
74 context.need_layout = newcontext.need_layout;
75 context.need_end_layout = newcontext.need_end_layout;
80 * Thin wrapper around parse_text_snippet() using a string.
82 * We completely ignore \c context.need_layout and \c context.need_end_layout,
83 * because our return value is not used directly (otherwise the stream version
84 * of parse_text_snippet() could be used). That means that the caller needs
85 * to do layout management manually.
86 * This is intended to parse text that does not create any layout changes.
88 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
91 Context newcontext(context);
92 newcontext.need_layout = false;
93 newcontext.need_end_layout = false;
94 newcontext.new_layout_allowed = false;
95 // Avoid warning by Context::~Context()
96 newcontext.extra_stuff.clear();
98 parse_text_snippet(p, os, flags, outer, newcontext);
103 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
104 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
108 * We can't put these into known_latex_commands because the argument order
109 * is reversed in lyx if there are 2 arguments.
110 * The starred forms are also known.
112 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
118 * We can't put these into known_latex_commands because the argument order
119 * is reversed in lyx if there are 2 arguments.
120 * No starred form other than "cite*" known.
122 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
123 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
124 // jurabib commands not (yet) supported by LyX:
125 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
126 // "footciteauthor", "footciteyear", "footciteyearpar",
127 "citefield", "citetitle", "cite*", 0 };
129 /// LaTeX names for quotes
130 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
131 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
133 /// the same as known_quotes with .lyx names
134 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
135 "grd", "gls", "fls", "frd", 0};
137 /// LaTeX names for font sizes
138 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
139 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
141 /// the same as known_sizes with .lyx names
142 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
145 /// LaTeX 2.09 names for font families
146 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
148 /// LaTeX names for font families
149 char const * const known_font_families[] = { "rmfamily", "sffamily",
152 /// the same as known_old_font_families and known_font_families with .lyx names
153 char const * const known_coded_font_families[] = { "roman", "sans",
156 /// LaTeX 2.09 names for font series
157 char const * const known_old_font_series[] = { "bf", 0};
159 /// LaTeX names for font series
160 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
162 /// the same as known_old_font_series and known_font_series with .lyx names
163 char const * const known_coded_font_series[] = { "bold", "medium", 0};
165 /// LaTeX 2.09 names for font shapes
166 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
168 /// LaTeX names for font shapes
169 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
172 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
173 char const * const known_coded_font_shapes[] = { "italic", "slanted",
174 "smallcaps", "up", 0};
177 * Graphics file extensions known by the dvips driver of the graphics package.
178 * These extensions are used to complete the filename of an included
179 * graphics file if it does not contain an extension.
180 * The order must be the same that latex uses to find a file, because we
181 * will use the first extension that matches.
182 * This is only an approximation for the common cases. If we would want to
183 * do it right in all cases, we would need to know which graphics driver is
184 * used and know the extensions of every driver of the graphics package.
186 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
187 "ps.gz", "eps.Z", "ps.Z", 0};
190 * Graphics file extensions known by the pdftex driver of the graphics package.
191 * \sa known_dvips_graphics_formats
193 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
197 * Known file extensions for TeX files as used by \\include.
199 char const * const known_tex_extensions[] = {"tex", 0};
202 /// splits "x=z, y=b" into a map
203 map<string, string> split_map(string const & s)
205 map<string, string> res;
208 for (size_t i = 0; i < v.size(); ++i) {
209 size_t const pos = v[i].find('=');
210 string const index = v[i].substr(0, pos);
211 string const value = v[i].substr(pos + 1, string::npos);
212 res[trim(index)] = trim(value);
219 * Split a LaTeX length into value and unit.
220 * The latter can be a real unit like "pt", or a latex length variable
221 * like "\textwidth". The unit may contain additional stuff like glue
222 * lengths, but we don't care, because such lengths are ERT anyway.
223 * \returns true if \p value and \p unit are valid.
225 bool splitLatexLength(string const & len, string & value, string & unit)
229 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
230 //'4,5' is a valid LaTeX length number. Change it to '4.5'
231 string const length = subst(len, ',', '.');
232 if (i == string::npos)
235 if (len[0] == '\\') {
236 // We had something like \textwidth without a factor
242 value = trim(string(length, 0, i));
246 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
247 if (contains(len, '\\'))
248 unit = trim(string(len, i));
250 unit = lyx::support::lowercase(trim(string(len, i)));
255 /// A simple function to translate a latex length to something lyx can
256 /// understand. Not perfect, but rather best-effort.
257 bool translate_len(string const & length, string & valstring, string & unit)
259 if (!splitLatexLength(length, valstring, unit))
261 // LyX uses percent values
263 istringstream iss(valstring);
268 string const percentval = oss.str();
270 if (unit.empty() || unit[0] != '\\')
272 string::size_type const i = unit.find(' ');
273 string const endlen = (i == string::npos) ? string() : string(unit, i);
274 if (unit == "\\textwidth") {
275 valstring = percentval;
276 unit = "text%" + endlen;
277 } else if (unit == "\\columnwidth") {
278 valstring = percentval;
279 unit = "col%" + endlen;
280 } else if (unit == "\\paperwidth") {
281 valstring = percentval;
282 unit = "page%" + endlen;
283 } else if (unit == "\\linewidth") {
284 valstring = percentval;
285 unit = "line%" + endlen;
286 } else if (unit == "\\paperheight") {
287 valstring = percentval;
288 unit = "pheight%" + endlen;
289 } else if (unit == "\\textheight") {
290 valstring = percentval;
291 unit = "theight%" + endlen;
297 string translate_len(string const & length)
301 if (translate_len(length, value, unit))
303 // If the input is invalid, return what we have.
309 * Translates a LaTeX length into \p value, \p unit and
310 * \p special parts suitable for a box inset.
311 * The difference from translate_len() is that a box inset knows about
312 * some special "units" that are stored in \p special.
314 void translate_box_len(string const & length, string & value, string & unit, string & special)
316 if (translate_len(length, value, unit)) {
317 if (unit == "\\height" || unit == "\\depth" ||
318 unit == "\\totalheight" || unit == "\\width") {
319 special = unit.substr(1);
320 // The unit is not used, but LyX requires a dummy setting
333 * Find a file with basename \p name in path \p path and an extension
336 string find_file(string const & name, string const & path,
337 char const * const * extensions)
339 for (char const * const * what = extensions; *what; ++what) {
340 // We don't use ChangeExtension() because it does the wrong
341 // thing if name contains a dot.
342 string const trial = name + '.' + (*what);
343 if (fs::exists(MakeAbsPath(trial, path)))
350 void begin_inset(ostream & os, string const & name)
352 os << "\n\\begin_inset " << name;
356 void end_inset(ostream & os)
358 os << "\n\\end_inset\n\n";
362 void skip_braces(Parser & p)
364 if (p.next_token().cat() != catBegin)
367 if (p.next_token().cat() == catEnd) {
375 void handle_ert(ostream & os, string const & s, Context & context)
377 // We must have a valid layout before outputting the ERT inset.
378 context.check_layout(os);
379 Context newcontext(true, context.textclass);
380 begin_inset(os, "ERT");
381 os << "\nstatus collapsed\n";
382 newcontext.check_layout(os);
383 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
385 os << "\n\\backslash\n";
386 else if (*it == '\n') {
387 newcontext.new_paragraph(os);
388 newcontext.check_layout(os);
392 newcontext.check_end_layout(os);
397 void handle_comment(ostream & os, string const & s, Context & context)
399 // TODO: Handle this better
400 Context newcontext(true, context.textclass);
401 begin_inset(os, "ERT");
402 os << "\nstatus collapsed\n";
403 newcontext.check_layout(os);
404 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
406 os << "\n\\backslash\n";
410 // make sure that our comment is the last thing on the line
411 newcontext.new_paragraph(os);
412 newcontext.check_layout(os);
413 newcontext.check_end_layout(os);
418 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
420 isLayout(string const name) : name_(name) {}
421 bool operator()(LyXLayout_ptr const & ptr) const {
422 return ptr->latexname() == name_;
429 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
432 LyXTextClass::const_iterator beg = textclass.begin();
433 LyXTextClass::const_iterator end = textclass.end();
435 LyXTextClass::const_iterator
436 it = std::find_if(beg, end, isLayout(name));
438 return (it == end) ? LyXLayout_ptr() : *it;
442 void eat_whitespace(Parser &, ostream &, Context &, bool);
445 void output_command_layout(ostream & os, Parser & p, bool outer,
446 Context & parent_context,
447 LyXLayout_ptr newlayout)
449 parent_context.check_end_layout(os);
450 Context context(true, parent_context.textclass, newlayout,
451 parent_context.layout, parent_context.font);
452 if (parent_context.deeper_paragraph) {
453 // We are beginning a nested environment after a
454 // deeper paragraph inside the outer list environment.
455 // Therefore we don't need to output a "begin deeper".
456 context.need_end_deeper = true;
458 context.check_deeper(os);
459 context.check_layout(os);
460 if (context.layout->optionalargs > 0) {
461 eat_whitespace(p, os, context, false);
462 if (p.next_token().character() == '[') {
463 p.get_token(); // eat '['
464 begin_inset(os, "OptArg\n");
465 os << "status collapsed\n\n";
466 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
468 eat_whitespace(p, os, context, false);
471 parse_text(p, os, FLAG_ITEM, outer, context);
472 context.check_end_layout(os);
473 if (parent_context.deeper_paragraph) {
474 // We must suppress the "end deeper" because we
475 // suppressed the "begin deeper" above.
476 context.need_end_deeper = false;
478 context.check_end_deeper(os);
479 // We don't need really a new paragraph, but
480 // we must make sure that the next item gets a \begin_layout.
481 parent_context.new_paragraph(os);
486 * Output a space if necessary.
487 * This function gets called for every whitespace token.
489 * We have three cases here:
490 * 1. A space must be suppressed. Example: The lyxcode case below
491 * 2. A space may be suppressed. Example: Spaces before "\par"
492 * 3. A space must not be suppressed. Example: A space between two words
494 * We currently handle only 1. and 3 and from 2. only the case of
495 * spaces before newlines as a side effect.
497 * 2. could be used to suppress as many spaces as possible. This has two effects:
498 * - Reimporting LyX generated LaTeX files changes almost no whitespace
499 * - Superflous whitespace from non LyX generated LaTeX files is removed.
500 * The drawback is that the logic inside the function becomes
501 * complicated, and that is the reason why it is not implemented.
503 void check_space(Parser const & p, ostream & os, Context & context)
505 Token const next = p.next_token();
506 Token const curr = p.curr_token();
507 // A space before a single newline and vice versa must be ignored
508 // LyX emits a newline before \end{lyxcode}.
509 // This newline must be ignored,
510 // otherwise LyX will add an additional protected space.
511 if (next.cat() == catSpace ||
512 next.cat() == catNewline ||
513 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
516 context.check_layout(os);
522 * Parse all arguments of \p command
524 void parse_arguments(string const & command,
525 vector<ArgumentType> const & template_arguments,
526 Parser & p, ostream & os, bool outer, Context & context)
528 string ert = command;
529 size_t no_arguments = template_arguments.size();
530 for (size_t i = 0; i < no_arguments; ++i) {
531 switch (template_arguments[i]) {
533 // This argument contains regular LaTeX
534 handle_ert(os, ert + '{', context);
535 parse_text(p, os, FLAG_ITEM, outer, context);
539 // This argument may contain special characters
540 ert += '{' + p.verbatim_item() + '}';
547 handle_ert(os, ert, context);
552 * Check whether \p command is a known command. If yes,
553 * handle the command with all arguments.
554 * \return true if the command was parsed, false otherwise.
556 bool parse_command(string const & command, Parser & p, ostream & os,
557 bool outer, Context & context)
559 if (known_commands.find(command) != known_commands.end()) {
560 parse_arguments(command, known_commands[command], p, os,
568 /// Parses a minipage or parbox
569 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
570 Context & parent_context, bool use_parbox)
574 string height_value = "0";
575 string height_unit = "pt";
576 string height_special = "none";
578 if (p.next_token().asInput() == "[") {
579 position = p.getArg('[', ']');
580 if (position != "t" && position != "c" && position != "b") {
582 cerr << "invalid position for minipage/parbox" << endl;
584 if (p.next_token().asInput() == "[") {
585 latex_height = p.getArg('[', ']');
586 translate_box_len(latex_height, height_value, height_unit, height_special);
588 if (p.next_token().asInput() == "[") {
589 inner_pos = p.getArg('[', ']');
590 if (inner_pos != "c" && inner_pos != "t" &&
591 inner_pos != "b" && inner_pos != "s") {
592 inner_pos = position;
593 cerr << "invalid inner_pos for minipage/parbox"
601 string const latex_width = p.verbatim_item();
602 translate_len(latex_width, width_value, width_unit);
603 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
604 // LyX can't handle length variables
609 ss << "\\begin{minipage}";
610 if (!position.empty())
611 ss << '[' << position << ']';
612 if (!latex_height.empty())
613 ss << '[' << latex_height << ']';
614 if (!inner_pos.empty())
615 ss << '[' << inner_pos << ']';
616 ss << "{" << latex_width << "}";
619 handle_ert(os, ss.str(), parent_context);
620 parent_context.new_paragraph(os);
621 parse_text_in_inset(p, os, flags, outer, parent_context);
623 handle_ert(os, "}", parent_context);
625 handle_ert(os, "\\end{minipage}", parent_context);
627 // LyX does not like empty positions, so we have
628 // to set them to the LaTeX default values here.
629 if (position.empty())
631 if (inner_pos.empty())
632 inner_pos = position;
633 parent_context.check_layout(os);
634 begin_inset(os, "Box Frameless\n");
635 os << "position \"" << position << "\"\n";
636 os << "hor_pos \"c\"\n";
637 os << "has_inner_box 1\n";
638 os << "inner_pos \"" << inner_pos << "\"\n";
639 os << "use_parbox " << use_parbox << "\n";
640 os << "width \"" << width_value << width_unit << "\"\n";
641 os << "special \"none\"\n";
642 os << "height \"" << height_value << height_unit << "\"\n";
643 os << "height_special \"" << height_special << "\"\n";
644 os << "status open\n\n";
645 parse_text_in_inset(p, os, flags, outer, parent_context);
647 #ifdef PRESERVE_LAYOUT
648 // lyx puts a % after the end of the minipage
649 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
651 //handle_comment(os, "%dummy", parent_context);
654 parent_context.new_paragraph(os);
656 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
657 //handle_comment(os, "%dummy", parent_context);
660 // We add a protected space if something real follows
661 if (p.good() && p.next_token().cat() != catComment) {
662 os << "\\InsetSpace ~\n";
670 /// parse an unknown environment
671 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
672 unsigned flags, bool outer,
673 Context & parent_context)
675 if (name == "tabbing")
676 // We need to remember that we have to handle '\=' specially
677 flags |= FLAG_TABBING;
679 // We need to translate font changes and paragraphs inside the
680 // environment to ERT if we have a non standard font.
681 // Otherwise things like
682 // \large\begin{foo}\huge bar\end{foo}
684 bool const specialfont =
685 (parent_context.font != parent_context.normalfont);
686 bool const new_layout_allowed = parent_context.new_layout_allowed;
688 parent_context.new_layout_allowed = false;
689 handle_ert(os, "\\begin{" + name + "}", parent_context);
690 parse_text_snippet(p, os, flags, outer, parent_context);
691 handle_ert(os, "\\end{" + name + "}", parent_context);
693 parent_context.new_layout_allowed = new_layout_allowed;
697 void parse_environment(Parser & p, ostream & os, bool outer,
698 Context & parent_context)
700 LyXLayout_ptr newlayout;
701 string const name = p.getArg('{', '}');
702 const bool is_starred = suffixIs(name, '*');
703 string const unstarred_name = rtrim(name, "*");
704 active_environments.push_back(name);
706 if (is_math_env(name)) {
707 parent_context.check_layout(os);
708 begin_inset(os, "Formula ");
709 os << "\\begin{" << name << "}";
710 parse_math(p, os, FLAG_END, MATH_MODE);
711 os << "\\end{" << name << "}";
715 else if (name == "tabular" || name == "longtable") {
716 eat_whitespace(p, os, parent_context, false);
717 parent_context.check_layout(os);
718 begin_inset(os, "Tabular ");
719 handle_tabular(p, os, name == "longtable", parent_context);
724 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
725 eat_whitespace(p, os, parent_context, false);
726 parent_context.check_layout(os);
727 begin_inset(os, "Float " + unstarred_name + "\n");
728 if (p.next_token().asInput() == "[") {
729 os << "placement " << p.getArg('[', ']') << '\n';
731 os << "wide " << convert<string>(is_starred)
732 << "\nsideways false"
733 << "\nstatus open\n\n";
734 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
736 // We don't need really a new paragraph, but
737 // we must make sure that the next item gets a \begin_layout.
738 parent_context.new_paragraph(os);
742 else if (name == "minipage") {
743 eat_whitespace(p, os, parent_context, false);
744 parse_box(p, os, FLAG_END, outer, parent_context, false);
748 else if (name == "comment") {
749 eat_whitespace(p, os, parent_context, false);
750 parent_context.check_layout(os);
751 begin_inset(os, "Note Comment\n");
752 os << "status open\n";
753 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
758 else if (name == "lyxgreyedout") {
759 eat_whitespace(p, os, parent_context, false);
760 parent_context.check_layout(os);
761 begin_inset(os, "Note Greyedout\n");
762 os << "status open\n";
763 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
768 else if (!parent_context.new_layout_allowed)
769 parse_unknown_environment(p, name, os, FLAG_END, outer,
772 // Alignment settings
773 else if (name == "center" || name == "flushleft" || name == "flushright" ||
774 name == "centering" || name == "raggedright" || name == "raggedleft") {
775 eat_whitespace(p, os, parent_context, false);
776 // We must begin a new paragraph if not already done
777 if (! parent_context.atParagraphStart()) {
778 parent_context.check_end_layout(os);
779 parent_context.new_paragraph(os);
781 if (name == "flushleft" || name == "raggedright")
782 parent_context.add_extra_stuff("\\align left\n");
783 else if (name == "flushright" || name == "raggedleft")
784 parent_context.add_extra_stuff("\\align right\n");
786 parent_context.add_extra_stuff("\\align center\n");
787 parse_text(p, os, FLAG_END, outer, parent_context);
788 // Just in case the environment is empty ..
789 parent_context.extra_stuff.erase();
790 // We must begin a new paragraph to reset the alignment
791 parent_context.new_paragraph(os);
795 // The single '=' is meant here.
796 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
797 newlayout->isEnvironment()) {
798 eat_whitespace(p, os, parent_context, false);
799 Context context(true, parent_context.textclass, newlayout,
800 parent_context.layout, parent_context.font);
801 if (parent_context.deeper_paragraph) {
802 // We are beginning a nested environment after a
803 // deeper paragraph inside the outer list environment.
804 // Therefore we don't need to output a "begin deeper".
805 context.need_end_deeper = true;
807 parent_context.check_end_layout(os);
808 switch (context.layout->latextype) {
809 case LATEX_LIST_ENVIRONMENT:
810 context.extra_stuff = "\\labelwidthstring "
811 + p.verbatim_item() + '\n';
814 case LATEX_BIB_ENVIRONMENT:
815 p.verbatim_item(); // swallow next arg
821 context.check_deeper(os);
822 parse_text(p, os, FLAG_END, outer, context);
823 context.check_end_layout(os);
824 if (parent_context.deeper_paragraph) {
825 // We must suppress the "end deeper" because we
826 // suppressed the "begin deeper" above.
827 context.need_end_deeper = false;
829 context.check_end_deeper(os);
830 parent_context.new_paragraph(os);
834 else if (name == "appendix") {
835 // This is no good latex style, but it works and is used in some documents...
836 eat_whitespace(p, os, parent_context, false);
837 parent_context.check_end_layout(os);
838 Context context(true, parent_context.textclass, parent_context.layout,
839 parent_context.layout, parent_context.font);
840 context.check_layout(os);
841 os << "\\start_of_appendix\n";
842 parse_text(p, os, FLAG_END, outer, context);
843 context.check_end_layout(os);
847 else if (known_environments.find(name) != known_environments.end()) {
848 vector<ArgumentType> arguments = known_environments[name];
849 // The last "argument" denotes wether we may translate the
850 // environment contents to LyX
851 // The default required if no argument is given makes us
852 // compatible with the reLyXre environment.
853 ArgumentType contents = arguments.empty() ?
856 if (!arguments.empty())
857 arguments.pop_back();
858 // See comment in parse_unknown_environment()
859 bool const specialfont =
860 (parent_context.font != parent_context.normalfont);
861 bool const new_layout_allowed =
862 parent_context.new_layout_allowed;
864 parent_context.new_layout_allowed = false;
865 parse_arguments("\\begin{" + name + "}", arguments, p, os,
866 outer, parent_context);
867 if (contents == verbatim)
868 handle_ert(os, p.verbatimEnvironment(name),
871 parse_text_snippet(p, os, FLAG_END, outer,
873 handle_ert(os, "\\end{" + name + "}", parent_context);
875 parent_context.new_layout_allowed = new_layout_allowed;
879 parse_unknown_environment(p, name, os, FLAG_END, outer,
882 active_environments.pop_back();
886 /// parses a comment and outputs it to \p os.
887 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
889 BOOST_ASSERT(t.cat() == catComment);
890 if (!t.cs().empty()) {
891 context.check_layout(os);
892 handle_comment(os, '%' + t.cs(), context);
893 if (p.next_token().cat() == catNewline) {
894 // A newline after a comment line starts a new
896 if (context.new_layout_allowed) {
897 if(!context.atParagraphStart())
898 // Only start a new paragraph if not already
899 // done (we might get called recursively)
900 context.new_paragraph(os);
902 handle_ert(os, "\n", context);
903 eat_whitespace(p, os, context, true);
913 * Reads spaces and comments until the first non-space, non-comment token.
914 * New paragraphs (double newlines or \\par) are handled like simple spaces
915 * if \p eatParagraph is true.
916 * Spaces are skipped, but comments are written to \p os.
918 void eat_whitespace(Parser & p, ostream & os, Context & context,
922 Token const & t = p.get_token();
923 if (t.cat() == catComment)
924 parse_comment(p, os, t, context);
925 else if ((! eatParagraph && p.isParagraph()) ||
926 (t.cat() != catSpace && t.cat() != catNewline)) {
935 * Set a font attribute, parse text and reset the font attribute.
936 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
937 * \param currentvalue Current value of the attribute. Is set to the new
938 * value during parsing.
939 * \param newvalue New value of the attribute
941 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
942 Context & context, string const & attribute,
943 string & currentvalue, string const & newvalue)
945 context.check_layout(os);
946 string const oldvalue = currentvalue;
947 currentvalue = newvalue;
948 os << '\n' << attribute << ' ' << newvalue << "\n";
949 parse_text_snippet(p, os, flags, outer, context);
950 context.check_layout(os);
951 os << '\n' << attribute << ' ' << oldvalue << "\n";
952 currentvalue = oldvalue;
956 /// get the arguments of a natbib or jurabib citation command
957 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
959 // We need to distinguish "" and "[]", so we can't use p.getOpt().
961 // text before the citation
963 // text after the citation
964 string after = p.getFullOpt();
966 if (!after.empty()) {
967 before = p.getFullOpt();
968 if (natbibOrder && !before.empty())
969 std::swap(before, after);
971 return std::make_pair(before, after);
975 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
976 string const normalize_filename(string const & name)
978 Parser p(trim(name, "\""));
981 Token const & t = p.get_token();
982 if (t.cat() != catEscape)
984 else if (t.cs() == "lyxdot") {
985 // This is used by LyX for simple dots in relative
989 } else if (t.cs() == "space") {
999 /// Convert \p name from TeX convention (relative to master file) to LyX
1000 /// convention (relative to .lyx file) if it is relative
1001 void fix_relative_filename(string & name)
1003 if (lyx::support::AbsolutePath(name))
1005 name = MakeRelPath(MakeAbsPath(name, getMasterFilePath()),
1006 getParentFilePath());
1009 } // anonymous namespace
1012 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1015 LyXLayout_ptr newlayout;
1016 // Store the latest bibliographystyle (needed for bibtex inset)
1017 string bibliographystyle;
1018 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1019 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1021 Token const & t = p.get_token();
1024 cerr << "t: " << t << " flags: " << flags << "\n";
1027 if (flags & FLAG_ITEM) {
1028 if (t.cat() == catSpace)
1031 flags &= ~FLAG_ITEM;
1032 if (t.cat() == catBegin) {
1033 // skip the brace and collect everything to the next matching
1035 flags |= FLAG_BRACE_LAST;
1039 // handle only this single token, leave the loop if done
1040 flags |= FLAG_LEAVE;
1043 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1049 if (t.cat() == catMath) {
1050 // we are inside some text mode thingy, so opening new math is allowed
1051 context.check_layout(os);
1052 begin_inset(os, "Formula ");
1053 Token const & n = p.get_token();
1054 if (n.cat() == catMath && outer) {
1055 // TeX's $$...$$ syntax for displayed math
1057 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1059 p.get_token(); // skip the second '$' token
1061 // simple $...$ stuff
1064 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1070 else if (t.cat() == catSuper || t.cat() == catSub)
1071 cerr << "catcode " << t << " illegal in text mode\n";
1073 // Basic support for english quotes. This should be
1074 // extended to other quotes, but is not so easy (a
1075 // left english quote is the same as a right german
1077 else if (t.asInput() == "`"
1078 && p.next_token().asInput() == "`") {
1079 context.check_layout(os);
1080 begin_inset(os, "Quotes ");
1086 else if (t.asInput() == "'"
1087 && p.next_token().asInput() == "'") {
1088 context.check_layout(os);
1089 begin_inset(os, "Quotes ");
1096 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1097 check_space(p, os, context);
1099 else if (t.cat() == catLetter ||
1100 t.cat() == catOther ||
1101 t.cat() == catAlign ||
1102 t.cat() == catParameter) {
1103 // This translates "&" to "\\&" which may be wrong...
1104 context.check_layout(os);
1105 os << t.character();
1108 else if (p.isParagraph()) {
1109 if (context.new_layout_allowed)
1110 context.new_paragraph(os);
1112 handle_ert(os, "\\par ", context);
1113 eat_whitespace(p, os, context, true);
1116 else if (t.cat() == catActive) {
1117 context.check_layout(os);
1118 if (t.character() == '~') {
1119 if (context.layout->free_spacing)
1122 os << "\\InsetSpace ~\n";
1124 os << t.character();
1127 else if (t.cat() == catBegin &&
1128 p.next_token().cat() == catEnd) {
1130 Token const prev = p.prev_token();
1132 if (p.next_token().character() == '`' ||
1133 (prev.character() == '-' &&
1134 p.next_token().character() == '-'))
1135 ; // ignore it in {}`` or -{}-
1137 handle_ert(os, "{}", context);
1141 else if (t.cat() == catBegin) {
1142 context.check_layout(os);
1143 // special handling of font attribute changes
1144 Token const prev = p.prev_token();
1145 Token const next = p.next_token();
1146 Font const oldFont = context.font;
1147 if (next.character() == '[' ||
1148 next.character() == ']' ||
1149 next.character() == '*') {
1151 if (p.next_token().cat() == catEnd) {
1152 os << next.character();
1156 handle_ert(os, "{", context);
1157 parse_text_snippet(p, os,
1160 handle_ert(os, "}", context);
1162 } else if (! context.new_layout_allowed) {
1163 handle_ert(os, "{", context);
1164 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1166 handle_ert(os, "}", context);
1167 } else if (is_known(next.cs(), known_sizes)) {
1168 // next will change the size, so we must
1170 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1172 if (!context.atParagraphStart())
1174 << context.font.size << "\n";
1175 } else if (is_known(next.cs(), known_font_families)) {
1176 // next will change the font family, so we
1177 // must reset it here
1178 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1180 if (!context.atParagraphStart())
1182 << context.font.family << "\n";
1183 } else if (is_known(next.cs(), known_font_series)) {
1184 // next will change the font series, so we
1185 // must reset it here
1186 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1188 if (!context.atParagraphStart())
1190 << context.font.series << "\n";
1191 } else if (is_known(next.cs(), known_font_shapes)) {
1192 // next will change the font shape, so we
1193 // must reset it here
1194 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1196 if (!context.atParagraphStart())
1198 << context.font.shape << "\n";
1199 } else if (is_known(next.cs(), known_old_font_families) ||
1200 is_known(next.cs(), known_old_font_series) ||
1201 is_known(next.cs(), known_old_font_shapes)) {
1202 // next will change the font family, series
1203 // and shape, so we must reset it here
1204 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1206 if (!context.atParagraphStart())
1208 << context.font.family
1210 << context.font.series
1212 << context.font.shape << "\n";
1214 handle_ert(os, "{", context);
1215 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1217 handle_ert(os, "}", context);
1221 else if (t.cat() == catEnd) {
1222 if (flags & FLAG_BRACE_LAST) {
1225 cerr << "stray '}' in text\n";
1226 handle_ert(os, "}", context);
1229 else if (t.cat() == catComment)
1230 parse_comment(p, os, t, context);
1233 // control sequences
1236 else if (t.cs() == "(") {
1237 context.check_layout(os);
1238 begin_inset(os, "Formula");
1240 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1245 else if (t.cs() == "[") {
1246 context.check_layout(os);
1247 begin_inset(os, "Formula");
1249 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1254 else if (t.cs() == "begin")
1255 parse_environment(p, os, outer, context);
1257 else if (t.cs() == "end") {
1258 if (flags & FLAG_END) {
1259 // eat environment name
1260 string const name = p.getArg('{', '}');
1261 if (name != active_environment())
1262 cerr << "\\end{" + name + "} does not match \\begin{"
1263 + active_environment() + "}\n";
1266 p.error("found 'end' unexpectedly");
1269 else if (t.cs() == "item") {
1272 bool optarg = false;
1273 if (p.next_token().character() == '[') {
1274 p.get_token(); // eat '['
1275 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1280 context.check_layout(os);
1281 if (context.has_item) {
1282 // An item in an unknown list-like environment
1283 // FIXME: Do this in check_layout()!
1284 context.has_item = false;
1286 handle_ert(os, "\\item", context);
1288 handle_ert(os, "\\item ", context);
1291 if (context.layout->labeltype != LABEL_MANUAL) {
1292 // lyx does not support \item[\mybullet]
1293 // in itemize environments
1294 handle_ert(os, "[", context);
1296 handle_ert(os, "]", context);
1297 } else if (!s.empty()) {
1298 // The space is needed to separate the
1299 // item from the rest of the sentence.
1301 eat_whitespace(p, os, context, false);
1306 else if (t.cs() == "bibitem") {
1308 context.check_layout(os);
1311 os << '{' << p.verbatim_item() << '}' << "\n";
1314 else if (t.cs() == "def") {
1315 context.check_layout(os);
1316 eat_whitespace(p, os, context, false);
1317 string name = p.get_token().cs();
1318 while (p.next_token().cat() != catBegin)
1319 name += p.get_token().asString();
1320 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1323 else if (t.cs() == "noindent") {
1325 context.add_extra_stuff("\\noindent\n");
1328 else if (t.cs() == "appendix") {
1329 context.add_extra_stuff("\\start_of_appendix\n");
1330 // We need to start a new paragraph. Otherwise the
1331 // appendix in 'bla\appendix\chapter{' would start
1333 context.new_paragraph(os);
1334 // We need to make sure that the paragraph is
1335 // generated even if it is empty. Otherwise the
1336 // appendix in '\par\appendix\par\chapter{' would
1338 context.check_layout(os);
1339 // FIXME: This is a hack to prevent paragraph
1340 // deletion if it is empty. Handle this better!
1342 "%dummy comment inserted by tex2lyx to "
1343 "ensure that this paragraph is not empty",
1345 // Both measures above may generate an additional
1346 // empty paragraph, but that does not hurt, because
1347 // whitespace does not matter here.
1348 eat_whitespace(p, os, context, true);
1351 // Must attempt to parse "Section*" before "Section".
1352 else if ((p.next_token().asInput() == "*") &&
1353 context.new_layout_allowed &&
1354 // The single '=' is meant here.
1355 (newlayout = findLayout(context.textclass,
1356 t.cs() + '*')).get() &&
1357 newlayout->isCommand()) {
1359 output_command_layout(os, p, outer, context, newlayout);
1363 // The single '=' is meant here.
1364 else if (context.new_layout_allowed &&
1365 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1366 newlayout->isCommand()) {
1367 output_command_layout(os, p, outer, context, newlayout);
1371 else if (t.cs() == "includegraphics") {
1372 bool const clip = p.next_token().asInput() == "*";
1375 map<string, string> opts = split_map(p.getArg('[', ']'));
1377 opts["clip"] = string();
1378 string name = normalize_filename(p.verbatim_item());
1380 string const path = getMasterFilePath();
1381 // We want to preserve relative / absolute filenames,
1382 // therefore path is only used for testing
1383 if (!fs::exists(MakeAbsPath(name, path))) {
1384 // The file extension is probably missing.
1385 // Now try to find it out.
1386 string const dvips_name =
1387 find_file(name, path,
1388 known_dvips_graphics_formats);
1389 string const pdftex_name =
1390 find_file(name, path,
1391 known_pdftex_graphics_formats);
1392 if (!dvips_name.empty()) {
1393 if (!pdftex_name.empty()) {
1394 cerr << "This file contains the "
1396 "\"\\includegraphics{"
1398 "However, files\n\""
1399 << dvips_name << "\" and\n\""
1400 << pdftex_name << "\"\n"
1401 "both exist, so I had to make a "
1402 "choice and took the first one.\n"
1403 "Please move the unwanted one "
1404 "someplace else and try again\n"
1405 "if my choice was wrong."
1409 } else if (!pdftex_name.empty())
1413 if (fs::exists(MakeAbsPath(name, path)))
1414 fix_relative_filename(name);
1416 cerr << "Warning: Could not find graphics file '"
1417 << name << "'." << endl;
1419 context.check_layout(os);
1420 begin_inset(os, "Graphics ");
1421 os << "\n\tfilename " << name << '\n';
1422 if (opts.find("width") != opts.end())
1424 << translate_len(opts["width"]) << '\n';
1425 if (opts.find("height") != opts.end())
1427 << translate_len(opts["height"]) << '\n';
1428 if (opts.find("scale") != opts.end()) {
1429 istringstream iss(opts["scale"]);
1433 os << "\tscale " << val << '\n';
1435 if (opts.find("angle") != opts.end())
1436 os << "\trotateAngle "
1437 << opts["angle"] << '\n';
1438 if (opts.find("origin") != opts.end()) {
1440 string const opt = opts["origin"];
1441 if (opt.find('l') != string::npos) ss << "left";
1442 if (opt.find('r') != string::npos) ss << "right";
1443 if (opt.find('c') != string::npos) ss << "center";
1444 if (opt.find('t') != string::npos) ss << "Top";
1445 if (opt.find('b') != string::npos) ss << "Bottom";
1446 if (opt.find('B') != string::npos) ss << "Baseline";
1447 if (!ss.str().empty())
1448 os << "\trotateOrigin " << ss.str() << '\n';
1450 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1452 if (opts.find("keepaspectratio") != opts.end())
1453 os << "\tkeepAspectRatio\n";
1454 if (opts.find("clip") != opts.end())
1456 if (opts.find("draft") != opts.end())
1458 if (opts.find("bb") != opts.end())
1459 os << "\tBoundingBox "
1460 << opts["bb"] << '\n';
1461 int numberOfbbOptions = 0;
1462 if (opts.find("bbllx") != opts.end())
1463 numberOfbbOptions++;
1464 if (opts.find("bblly") != opts.end())
1465 numberOfbbOptions++;
1466 if (opts.find("bburx") != opts.end())
1467 numberOfbbOptions++;
1468 if (opts.find("bbury") != opts.end())
1469 numberOfbbOptions++;
1470 if (numberOfbbOptions == 4)
1471 os << "\tBoundingBox "
1472 << opts["bbllx"] << opts["bblly"]
1473 << opts["bburx"] << opts["bbury"] << '\n';
1474 else if (numberOfbbOptions > 0)
1475 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1476 numberOfbbOptions = 0;
1477 if (opts.find("natwidth") != opts.end())
1478 numberOfbbOptions++;
1479 if (opts.find("natheight") != opts.end())
1480 numberOfbbOptions++;
1481 if (numberOfbbOptions == 2)
1482 os << "\tBoundingBox 0bp 0bp "
1483 << opts["natwidth"] << opts["natheight"] << '\n';
1484 else if (numberOfbbOptions > 0)
1485 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1486 ostringstream special;
1487 if (opts.find("hiresbb") != opts.end())
1488 special << "hiresbb,";
1489 if (opts.find("trim") != opts.end())
1491 if (opts.find("viewport") != opts.end())
1492 special << "viewport=" << opts["viewport"] << ',';
1493 if (opts.find("totalheight") != opts.end())
1494 special << "totalheight=" << opts["totalheight"] << ',';
1495 if (opts.find("type") != opts.end())
1496 special << "type=" << opts["type"] << ',';
1497 if (opts.find("ext") != opts.end())
1498 special << "ext=" << opts["ext"] << ',';
1499 if (opts.find("read") != opts.end())
1500 special << "read=" << opts["read"] << ',';
1501 if (opts.find("command") != opts.end())
1502 special << "command=" << opts["command"] << ',';
1503 string s_special = special.str();
1504 if (!s_special.empty()) {
1505 // We had special arguments. Remove the trailing ','.
1506 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1508 // TODO: Handle the unknown settings better.
1509 // Warn about invalid options.
1510 // Check whether some option was given twice.
1514 else if (t.cs() == "footnote" ||
1515 (t.cs() == "thanks" && context.layout->intitle)) {
1517 context.check_layout(os);
1518 begin_inset(os, "Foot\n");
1519 os << "status collapsed\n\n";
1520 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1524 else if (t.cs() == "marginpar") {
1526 context.check_layout(os);
1527 begin_inset(os, "Marginal\n");
1528 os << "status collapsed\n\n";
1529 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1533 else if (t.cs() == "ensuremath") {
1535 context.check_layout(os);
1536 string const s = p.verbatim_item();
1537 if (s == "±" || s == "³" || s == "²" || s == "µ")
1540 handle_ert(os, "\\ensuremath{" + s + "}",
1544 else if (t.cs() == "hfill") {
1545 context.check_layout(os);
1546 os << "\n\\hfill\n";
1551 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1552 // FIXME: Somehow prevent title layouts if
1553 // "maketitle" was not found
1555 skip_braces(p); // swallow this
1558 else if (t.cs() == "tableofcontents") {
1560 context.check_layout(os);
1561 begin_inset(os, "LatexCommand \\tableofcontents\n");
1563 skip_braces(p); // swallow this
1566 else if (t.cs() == "listoffigures") {
1568 context.check_layout(os);
1569 begin_inset(os, "FloatList figure\n");
1571 skip_braces(p); // swallow this
1574 else if (t.cs() == "listoftables") {
1576 context.check_layout(os);
1577 begin_inset(os, "FloatList table\n");
1579 skip_braces(p); // swallow this
1582 else if (t.cs() == "listof") {
1583 p.skip_spaces(true);
1584 string const name = p.get_token().asString();
1585 if (context.textclass.floats().typeExist(name)) {
1586 context.check_layout(os);
1587 begin_inset(os, "FloatList ");
1590 p.get_token(); // swallow second arg
1592 handle_ert(os, "\\listof{" + name + "}", context);
1595 else if (t.cs() == "textrm")
1596 parse_text_attributes(p, os, FLAG_ITEM, outer,
1597 context, "\\family",
1598 context.font.family, "roman");
1600 else if (t.cs() == "textsf")
1601 parse_text_attributes(p, os, FLAG_ITEM, outer,
1602 context, "\\family",
1603 context.font.family, "sans");
1605 else if (t.cs() == "texttt")
1606 parse_text_attributes(p, os, FLAG_ITEM, outer,
1607 context, "\\family",
1608 context.font.family, "typewriter");
1610 else if (t.cs() == "textmd")
1611 parse_text_attributes(p, os, FLAG_ITEM, outer,
1612 context, "\\series",
1613 context.font.series, "medium");
1615 else if (t.cs() == "textbf")
1616 parse_text_attributes(p, os, FLAG_ITEM, outer,
1617 context, "\\series",
1618 context.font.series, "bold");
1620 else if (t.cs() == "textup")
1621 parse_text_attributes(p, os, FLAG_ITEM, outer,
1623 context.font.shape, "up");
1625 else if (t.cs() == "textit")
1626 parse_text_attributes(p, os, FLAG_ITEM, outer,
1628 context.font.shape, "italic");
1630 else if (t.cs() == "textsl")
1631 parse_text_attributes(p, os, FLAG_ITEM, outer,
1633 context.font.shape, "slanted");
1635 else if (t.cs() == "textsc")
1636 parse_text_attributes(p, os, FLAG_ITEM, outer,
1638 context.font.shape, "smallcaps");
1640 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1641 context.check_layout(os);
1642 Font oldFont = context.font;
1643 context.font.init();
1644 context.font.size = oldFont.size;
1645 os << "\n\\family " << context.font.family << "\n";
1646 os << "\n\\series " << context.font.series << "\n";
1647 os << "\n\\shape " << context.font.shape << "\n";
1648 if (t.cs() == "textnormal") {
1649 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1650 output_font_change(os, context.font, oldFont);
1651 context.font = oldFont;
1653 eat_whitespace(p, os, context, false);
1656 else if (t.cs() == "underbar") {
1657 // Do NOT handle \underline.
1658 // \underbar cuts through y, g, q, p etc.,
1659 // \underline does not.
1660 context.check_layout(os);
1661 os << "\n\\bar under\n";
1662 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1663 context.check_layout(os);
1664 os << "\n\\bar default\n";
1667 else if (t.cs() == "emph" || t.cs() == "noun") {
1668 context.check_layout(os);
1669 os << "\n\\" << t.cs() << " on\n";
1670 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1671 context.check_layout(os);
1672 os << "\n\\" << t.cs() << " default\n";
1675 else if (use_natbib &&
1676 is_known(t.cs(), known_natbib_commands) &&
1677 ((t.cs() != "citefullauthor" &&
1678 t.cs() != "citeyear" &&
1679 t.cs() != "citeyearpar") ||
1680 p.next_token().asInput() != "*")) {
1681 context.check_layout(os);
1683 // \citet[before][after]{a} \citet[after][before]{a}
1684 // \citet[before][]{a} \citet[][before]{a}
1685 // \citet[after]{a} \citet[after]{a}
1686 // \citet{a} \citet{a}
1687 string command = '\\' + t.cs();
1688 if (p.next_token().asInput() == "*") {
1692 if (command == "\\citefullauthor")
1693 // alternative name for "\\citeauthor*"
1694 command = "\\citeauthor*";
1696 // text before the citation
1698 // text after the citation
1701 boost::tie(before, after) = getCiteArguments(p, true);
1702 if (command == "\\cite") {
1703 // \cite without optional argument means
1704 // \citet, \cite with at least one optional
1705 // argument means \citep.
1706 if (before.empty() && after.empty())
1707 command = "\\citet";
1709 command = "\\citep";
1711 if (before.empty() && after == "[]")
1712 // avoid \citet[]{a}
1714 else if (before == "[]" && after == "[]") {
1715 // avoid \citet[][]{a}
1719 begin_inset(os, "LatexCommand ");
1720 os << command << after << before
1721 << '{' << p.verbatim_item() << "}\n";
1725 else if (use_jurabib &&
1726 is_known(t.cs(), known_jurabib_commands)) {
1727 context.check_layout(os);
1728 string const command = '\\' + t.cs();
1729 char argumentOrder = '\0';
1730 vector<string> const & options = used_packages["jurabib"];
1731 if (std::find(options.begin(), options.end(),
1732 "natbiborder") != options.end())
1733 argumentOrder = 'n';
1734 else if (std::find(options.begin(), options.end(),
1735 "jurabiborder") != options.end())
1736 argumentOrder = 'j';
1738 // text before the citation
1740 // text after the citation
1743 boost::tie(before, after) =
1744 getCiteArguments(p, argumentOrder != 'j');
1745 string const citation = p.verbatim_item();
1746 if (!before.empty() && argumentOrder == '\0') {
1747 cerr << "Warning: Assuming argument order "
1748 "of jurabib version 0.6 for\n'"
1749 << command << before << after << '{'
1750 << citation << "}'.\n"
1751 "Add 'jurabiborder' to the jurabib "
1752 "package options if you used an\n"
1753 "earlier jurabib version." << endl;
1755 begin_inset(os, "LatexCommand ");
1756 os << command << after << before
1757 << '{' << citation << "}\n";
1761 else if (is_known(t.cs(), known_latex_commands)) {
1762 // This needs to be after the check for natbib and
1763 // jurabib commands, because "cite" has different
1764 // arguments with natbib and jurabib.
1765 context.check_layout(os);
1766 begin_inset(os, "LatexCommand ");
1767 os << '\\' << t.cs();
1768 // lyx cannot handle newlines in a latex command
1769 // FIXME: Move the substitution into parser::getOpt()?
1770 os << subst(p.getOpt(), "\n", " ");
1771 os << subst(p.getOpt(), "\n", " ");
1772 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1776 else if (is_known(t.cs(), known_quotes)) {
1777 char const * const * where = is_known(t.cs(), known_quotes);
1778 context.check_layout(os);
1779 begin_inset(os, "Quotes ");
1780 os << known_coded_quotes[where - known_quotes];
1782 // LyX adds {} after the quote, so we have to eat
1783 // spaces here if there are any before a possible
1785 eat_whitespace(p, os, context, false);
1789 else if (is_known(t.cs(), known_sizes) &&
1790 context.new_layout_allowed) {
1791 char const * const * where = is_known(t.cs(), known_sizes);
1792 context.check_layout(os);
1793 Font const oldFont = context.font;
1794 context.font.size = known_coded_sizes[where - known_sizes];
1795 output_font_change(os, oldFont, context.font);
1796 eat_whitespace(p, os, context, false);
1799 else if (is_known(t.cs(), known_font_families) &&
1800 context.new_layout_allowed) {
1801 char const * const * where =
1802 is_known(t.cs(), known_font_families);
1803 context.check_layout(os);
1804 Font const oldFont = context.font;
1805 context.font.family =
1806 known_coded_font_families[where - known_font_families];
1807 output_font_change(os, oldFont, context.font);
1808 eat_whitespace(p, os, context, false);
1811 else if (is_known(t.cs(), known_font_series) &&
1812 context.new_layout_allowed) {
1813 char const * const * where =
1814 is_known(t.cs(), known_font_series);
1815 context.check_layout(os);
1816 Font const oldFont = context.font;
1817 context.font.series =
1818 known_coded_font_series[where - known_font_series];
1819 output_font_change(os, oldFont, context.font);
1820 eat_whitespace(p, os, context, false);
1823 else if (is_known(t.cs(), known_font_shapes) &&
1824 context.new_layout_allowed) {
1825 char const * const * where =
1826 is_known(t.cs(), known_font_shapes);
1827 context.check_layout(os);
1828 Font const oldFont = context.font;
1829 context.font.shape =
1830 known_coded_font_shapes[where - known_font_shapes];
1831 output_font_change(os, oldFont, context.font);
1832 eat_whitespace(p, os, context, false);
1834 else if (is_known(t.cs(), known_old_font_families) &&
1835 context.new_layout_allowed) {
1836 char const * const * where =
1837 is_known(t.cs(), known_old_font_families);
1838 context.check_layout(os);
1839 Font const oldFont = context.font;
1840 context.font.init();
1841 context.font.size = oldFont.size;
1842 context.font.family =
1843 known_coded_font_families[where - known_old_font_families];
1844 output_font_change(os, oldFont, context.font);
1845 eat_whitespace(p, os, context, false);
1848 else if (is_known(t.cs(), known_old_font_series) &&
1849 context.new_layout_allowed) {
1850 char const * const * where =
1851 is_known(t.cs(), known_old_font_series);
1852 context.check_layout(os);
1853 Font const oldFont = context.font;
1854 context.font.init();
1855 context.font.size = oldFont.size;
1856 context.font.series =
1857 known_coded_font_series[where - known_old_font_series];
1858 output_font_change(os, oldFont, context.font);
1859 eat_whitespace(p, os, context, false);
1862 else if (is_known(t.cs(), known_old_font_shapes) &&
1863 context.new_layout_allowed) {
1864 char const * const * where =
1865 is_known(t.cs(), known_old_font_shapes);
1866 context.check_layout(os);
1867 Font const oldFont = context.font;
1868 context.font.init();
1869 context.font.size = oldFont.size;
1870 context.font.shape =
1871 known_coded_font_shapes[where - known_old_font_shapes];
1872 output_font_change(os, oldFont, context.font);
1873 eat_whitespace(p, os, context, false);
1876 else if (t.cs() == "LyX" || t.cs() == "TeX"
1877 || t.cs() == "LaTeX") {
1878 context.check_layout(os);
1880 skip_braces(p); // eat {}
1883 else if (t.cs() == "LaTeXe") {
1884 context.check_layout(os);
1886 skip_braces(p); // eat {}
1889 else if (t.cs() == "ldots") {
1890 context.check_layout(os);
1892 os << "\\SpecialChar \\ldots{}\n";
1895 else if (t.cs() == "lyxarrow") {
1896 context.check_layout(os);
1897 os << "\\SpecialChar \\menuseparator\n";
1901 else if (t.cs() == "textcompwordmark") {
1902 context.check_layout(os);
1903 os << "\\SpecialChar \\textcompwordmark{}\n";
1907 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1908 context.check_layout(os);
1909 os << "\\SpecialChar \\@.\n";
1913 else if (t.cs() == "-") {
1914 context.check_layout(os);
1915 os << "\\SpecialChar \\-\n";
1918 else if (t.cs() == "textasciitilde") {
1919 context.check_layout(os);
1924 else if (t.cs() == "textasciicircum") {
1925 context.check_layout(os);
1930 else if (t.cs() == "textbackslash") {
1931 context.check_layout(os);
1932 os << "\n\\backslash\n";
1936 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1937 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1939 context.check_layout(os);
1943 else if (t.cs() == "char") {
1944 context.check_layout(os);
1945 if (p.next_token().character() == '`') {
1947 if (p.next_token().cs() == "\"") {
1952 handle_ert(os, "\\char`", context);
1955 handle_ert(os, "\\char", context);
1959 else if (t.cs() == "verb") {
1960 context.check_layout(os);
1961 char const delimiter = p.next_token().character();
1962 string const arg = p.getArg(delimiter, delimiter);
1964 oss << "\\verb" << delimiter << arg << delimiter;
1965 handle_ert(os, oss.str(), context);
1968 else if (t.cs() == "\"") {
1969 context.check_layout(os);
1970 string const name = p.verbatim_item();
1971 if (name == "a") os << 'ä';
1972 else if (name == "o") os << 'ö';
1973 else if (name == "u") os << 'ü';
1974 else if (name == "A") os << 'Ä';
1975 else if (name == "O") os << 'Ö';
1976 else if (name == "U") os << 'Ü';
1977 else handle_ert(os, "\"{" + name + "}", context);
1980 // Problem: \= creates a tabstop inside the tabbing environment
1981 // and else an accent. In the latter case we really would want
1982 // \={o} instead of \= o.
1983 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1984 handle_ert(os, t.asInput(), context);
1986 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
1987 || t.cs() == "'" || t.cs() == "`"
1988 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1989 // we need the trim as the LyX parser chokes on such spaces
1990 context.check_layout(os);
1991 os << "\n\\i \\" << t.cs() << "{"
1992 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
1996 else if (t.cs() == "ss") {
1997 context.check_layout(os);
1999 skip_braces(p); // eat {}
2002 else if (t.cs() == "i" || t.cs() == "j") {
2003 context.check_layout(os);
2004 os << "\\" << t.cs() << ' ';
2005 skip_braces(p); // eat {}
2008 else if (t.cs() == "\\") {
2009 context.check_layout(os);
2010 string const next = p.next_token().asInput();
2012 handle_ert(os, "\\\\" + p.getOpt(), context);
2013 else if (next == "*") {
2015 handle_ert(os, "\\\\*" + p.getOpt(), context);
2018 os << "\n\\newline\n";
2022 else if (t.cs() == "input" || t.cs() == "include"
2023 || t.cs() == "verbatiminput") {
2024 string name = '\\' + t.cs();
2025 if (t.cs() == "verbatiminput"
2026 && p.next_token().asInput() == "*")
2027 name += p.get_token().asInput();
2028 context.check_layout(os);
2029 begin_inset(os, "Include ");
2030 string filename(normalize_filename(p.getArg('{', '}')));
2031 string const path = getMasterFilePath();
2032 // We want to preserve relative / absolute filenames,
2033 // therefore path is only used for testing
2034 if (t.cs() == "include" &&
2035 !fs::exists(MakeAbsPath(filename, path))) {
2036 // The file extension is probably missing.
2037 // Now try to find it out.
2038 string const tex_name =
2039 find_file(filename, path,
2040 known_tex_extensions);
2041 if (!tex_name.empty())
2042 filename = tex_name;
2044 if (fs::exists(MakeAbsPath(filename, path))) {
2045 string const abstexname =
2046 MakeAbsPath(filename, path);
2047 string const abslyxname =
2048 ChangeExtension(abstexname, ".lyx");
2049 fix_relative_filename(filename);
2050 string const lyxname =
2051 ChangeExtension(filename, ".lyx");
2052 if (t.cs() != "verbatiminput" &&
2053 tex2lyx(abstexname, abslyxname)) {
2054 os << name << '{' << lyxname << "}\n";
2056 os << name << '{' << filename << "}\n";
2059 cerr << "Warning: Could not find included file '"
2060 << filename << "'." << endl;
2061 os << name << '{' << filename << "}\n";
2063 os << "preview false\n";
2067 else if (t.cs() == "bibliographystyle") {
2068 // store new bibliographystyle
2069 bibliographystyle = p.verbatim_item();
2070 // output new bibliographystyle.
2071 // This is only necessary if used in some other macro than \bibliography.
2072 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2075 else if (t.cs() == "bibliography") {
2076 context.check_layout(os);
2077 begin_inset(os, "LatexCommand ");
2079 // Do we have a bibliographystyle set?
2080 if (!bibliographystyle.empty()) {
2081 os << '[' << bibliographystyle << ']';
2083 os << '{' << p.verbatim_item() << "}\n";
2087 else if (t.cs() == "parbox")
2088 parse_box(p, os, FLAG_ITEM, outer, context, true);
2090 else if (t.cs() == "smallskip" ||
2091 t.cs() == "medskip" ||
2092 t.cs() == "bigskip" ||
2093 t.cs() == "vfill") {
2094 context.check_layout(os);
2095 begin_inset(os, "VSpace ");
2101 else if (t.cs() == "newpage") {
2102 context.check_layout(os);
2103 // FIXME: what about \\clearpage and \\pagebreak?
2104 os << "\n\\newpage\n";
2105 skip_braces(p); // eat {}
2108 else if (t.cs() == "newcommand" ||
2109 t.cs() == "providecommand" ||
2110 t.cs() == "renewcommand") {
2111 // these could be handled by parse_command(), but
2112 // we need to call add_known_command() here.
2113 string name = t.asInput();
2114 if (p.next_token().asInput() == "*") {
2115 // Starred form. Eat '*'
2119 string const command = p.verbatim_item();
2120 string const opt1 = p.getOpt();
2121 string const opt2 = p.getFullOpt();
2122 add_known_command(command, opt1, !opt2.empty());
2123 string const ert = name + '{' + command + '}' +
2125 '{' + p.verbatim_item() + '}';
2126 handle_ert(os, ert, context);
2129 else if (t.cs() == "vspace") {
2130 bool starred = false;
2131 if (p.next_token().asInput() == "*") {
2135 string const length = p.verbatim_item();
2138 bool valid = splitLatexLength(length, valstring, unit);
2139 bool known_vspace = false;
2140 bool known_unit = false;
2143 istringstream iss(valstring);
2146 if (unit == "\\smallskipamount") {
2148 known_vspace = true;
2149 } else if (unit == "\\medskipamount") {
2151 known_vspace = true;
2152 } else if (unit == "\\bigskipamount") {
2154 known_vspace = true;
2155 } else if (unit == "\\fill") {
2157 known_vspace = true;
2160 if (!known_vspace) {
2161 switch (unitFromString(unit)) {
2182 if (known_unit || known_vspace) {
2183 // Literal length or known variable
2184 context.check_layout(os);
2185 begin_inset(os, "VSpace ");
2193 // LyX can't handle other length variables in Inset VSpace
2194 string name = t.asInput();
2199 handle_ert(os, name + '{' + unit + '}', context);
2200 else if (value == -1.0)
2201 handle_ert(os, name + "{-" + unit + '}', context);
2203 handle_ert(os, name + '{' + valstring + unit + '}', context);
2205 handle_ert(os, name + '{' + length + '}', context);
2210 //cerr << "#: " << t << " mode: " << mode << endl;
2211 // heuristic: read up to next non-nested space
2213 string s = t.asInput();
2214 string z = p.verbatim_item();
2215 while (p.good() && z != " " && z.size()) {
2216 //cerr << "read: " << z << endl;
2218 z = p.verbatim_item();
2220 cerr << "found ERT: " << s << endl;
2221 handle_ert(os, s + ' ', context);
2223 string name = t.asInput();
2224 if (p.next_token().asInput() == "*") {
2225 // Starred commands like \vspace*{}
2226 p.get_token(); // Eat '*'
2229 if (! parse_command(name, p, os, outer, context))
2230 handle_ert(os, name, context);
2233 if (flags & FLAG_LEAVE) {
2234 flags &= ~FLAG_LEAVE;