2 * \file tex2lyx/text.cpp
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.
19 #include "FloatList.h"
20 #include "lengthcommon.h"
21 #include "support/lstrings.h"
22 #include "support/convert.h"
23 #include "support/filetools.h"
25 #include <boost/filesystem/operations.hpp>
26 #include <boost/tuple/tuple.hpp>
38 using std::ostringstream;
39 using std::istringstream;
45 using support::addExtension;
46 using support::changeExtension;
47 using support::FileName;
48 using support::makeAbsPath;
49 using support::makeRelPath;
51 using support::suffixIs;
52 using support::contains;
55 namespace fs = boost::filesystem;
58 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context const & context)
61 Context newcontext(true, context.textclass);
62 newcontext.font = context.font;
63 parse_text(p, os, flags, outer, newcontext);
64 newcontext.check_end_layout(os);
70 /// parses a paragraph snippet, useful for example for \\emph{...}
71 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
74 Context newcontext(context);
75 // Don't inherit the extra stuff
76 newcontext.extra_stuff.clear();
77 parse_text(p, os, flags, outer, newcontext);
78 // Make sure that we don't create invalid .lyx files
79 context.need_layout = newcontext.need_layout;
80 context.need_end_layout = newcontext.need_end_layout;
85 * Thin wrapper around parse_text_snippet() using a string.
87 * We completely ignore \c context.need_layout and \c context.need_end_layout,
88 * because our return value is not used directly (otherwise the stream version
89 * of parse_text_snippet() could be used). That means that the caller needs
90 * to do layout management manually.
91 * This is intended to parse text that does not create any layout changes.
93 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
96 Context newcontext(context);
97 newcontext.need_layout = false;
98 newcontext.need_end_layout = false;
99 newcontext.new_layout_allowed = false;
100 // Avoid warning by Context::~Context()
101 newcontext.extra_stuff.clear();
103 parse_text_snippet(p, os, flags, outer, newcontext);
108 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
109 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
113 * We can't put these into known_latex_commands because the argument order
114 * is reversed in lyx if there are 2 arguments.
115 * The starred forms are also known.
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * We can't put these into known_latex_commands because the argument order
124 * is reversed in lyx if there are 2 arguments.
125 * No starred form other than "cite*" known.
127 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
128 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
129 // jurabib commands not (yet) supported by LyX:
131 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
132 // "footciteauthor", "footciteyear", "footciteyearpar",
133 "citefield", "citetitle", "cite*", 0 };
135 /// LaTeX names for quotes
136 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
137 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
141 "grd", "gls", "fls", "frs", 0};
143 /// LaTeX names for font sizes
144 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
145 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
147 /// the same as known_sizes with .lyx names
148 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
149 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
151 /// LaTeX 2.09 names for font families
152 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
154 /// LaTeX names for font families
155 char const * const known_font_families[] = { "rmfamily", "sffamily",
158 /// the same as known_old_font_families and known_font_families with .lyx names
159 char const * const known_coded_font_families[] = { "roman", "sans",
162 /// LaTeX 2.09 names for font series
163 char const * const known_old_font_series[] = { "bf", 0};
165 /// LaTeX names for font series
166 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
168 /// the same as known_old_font_series and known_font_series with .lyx names
169 char const * const known_coded_font_series[] = { "bold", "medium", 0};
171 /// LaTeX 2.09 names for font shapes
172 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
174 /// LaTeX names for font shapes
175 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
178 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
179 char const * const known_coded_font_shapes[] = { "italic", "slanted",
180 "smallcaps", "up", 0};
183 * Graphics file extensions known by the dvips driver of the graphics package.
184 * These extensions are used to complete the filename of an included
185 * graphics file if it does not contain an extension.
186 * The order must be the same that latex uses to find a file, because we
187 * will use the first extension that matches.
188 * This is only an approximation for the common cases. If we would want to
189 * do it right in all cases, we would need to know which graphics driver is
190 * used and know the extensions of every driver of the graphics package.
192 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
193 "ps.gz", "eps.Z", "ps.Z", 0};
196 * Graphics file extensions known by the pdftex driver of the graphics package.
197 * \sa known_dvips_graphics_formats
199 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
203 * Known file extensions for TeX files as used by \\include.
205 char const * const known_tex_extensions[] = {"tex", 0};
207 /// spaces known by InsetSpace
208 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
209 "qquad", "enspace", "enskip", "negthinspace", 0};
211 /// the same as known_spaces with .lyx names
212 char const * const known_coded_spaces[] = { "space{}", "space{}",
213 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
214 "negthinspace{}", 0};
217 /// splits "x=z, y=b" into a map
218 map<string, string> split_map(string const & s)
220 map<string, string> res;
223 for (size_t i = 0; i < v.size(); ++i) {
224 size_t const pos = v[i].find('=');
225 string const index = v[i].substr(0, pos);
226 string const value = v[i].substr(pos + 1, string::npos);
227 res[trim(index)] = trim(value);
234 * Split a LaTeX length into value and unit.
235 * The latter can be a real unit like "pt", or a latex length variable
236 * like "\textwidth". The unit may contain additional stuff like glue
237 * lengths, but we don't care, because such lengths are ERT anyway.
238 * \returns true if \p value and \p unit are valid.
240 bool splitLatexLength(string const & len, string & value, string & unit)
244 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
245 //'4,5' is a valid LaTeX length number. Change it to '4.5'
246 string const length = subst(len, ',', '.');
247 if (i == string::npos)
250 if (len[0] == '\\') {
251 // We had something like \textwidth without a factor
257 value = trim(string(length, 0, i));
261 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
262 if (contains(len, '\\'))
263 unit = trim(string(len, i));
265 unit = support::ascii_lowercase(trim(string(len, i)));
270 /// A simple function to translate a latex length to something lyx can
271 /// understand. Not perfect, but rather best-effort.
272 bool translate_len(string const & length, string & valstring, string & unit)
274 if (!splitLatexLength(length, valstring, unit))
276 // LyX uses percent values
278 istringstream iss(valstring);
283 string const percentval = oss.str();
285 if (unit.empty() || unit[0] != '\\')
287 string::size_type const i = unit.find(' ');
288 string const endlen = (i == string::npos) ? string() : string(unit, i);
289 if (unit == "\\textwidth") {
290 valstring = percentval;
291 unit = "text%" + endlen;
292 } else if (unit == "\\columnwidth") {
293 valstring = percentval;
294 unit = "col%" + endlen;
295 } else if (unit == "\\paperwidth") {
296 valstring = percentval;
297 unit = "page%" + endlen;
298 } else if (unit == "\\linewidth") {
299 valstring = percentval;
300 unit = "line%" + endlen;
301 } else if (unit == "\\paperheight") {
302 valstring = percentval;
303 unit = "pheight%" + endlen;
304 } else if (unit == "\\textheight") {
305 valstring = percentval;
306 unit = "theight%" + endlen;
314 string translate_len(string const & length)
318 if (translate_len(length, value, unit))
320 // If the input is invalid, return what we have.
328 * Translates a LaTeX length into \p value, \p unit and
329 * \p special parts suitable for a box inset.
330 * The difference from translate_len() is that a box inset knows about
331 * some special "units" that are stored in \p special.
333 void translate_box_len(string const & length, string & value, string & unit, string & special)
335 if (translate_len(length, value, unit)) {
336 if (unit == "\\height" || unit == "\\depth" ||
337 unit == "\\totalheight" || unit == "\\width") {
338 special = unit.substr(1);
339 // The unit is not used, but LyX requires a dummy setting
352 * Find a file with basename \p name in path \p path and an extension
355 string find_file(string const & name, string const & path,
356 char const * const * extensions)
358 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
360 for (char const * const * what = extensions; *what; ++what) {
361 string const trial = addExtension(name, *what);
362 if (fs::exists(makeAbsPath(trial, path).toFilesystemEncoding()))
369 void begin_inset(ostream & os, string const & name)
371 os << "\n\\begin_inset " << name;
375 void end_inset(ostream & os)
377 os << "\n\\end_inset\n\n";
381 void skip_braces(Parser & p)
383 if (p.next_token().cat() != catBegin)
386 if (p.next_token().cat() == catEnd) {
394 void handle_ert(ostream & os, string const & s, Context & context)
396 // We must have a valid layout before outputting the ERT inset.
397 context.check_layout(os);
398 Context newcontext(true, context.textclass);
399 begin_inset(os, "ERT");
400 os << "\nstatus collapsed\n";
401 newcontext.check_layout(os);
402 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
404 os << "\n\\backslash\n";
405 else if (*it == '\n') {
406 newcontext.new_paragraph(os);
407 newcontext.check_layout(os);
411 newcontext.check_end_layout(os);
416 void handle_comment(ostream & os, string const & s, Context & context)
418 // TODO: Handle this better
419 Context newcontext(true, context.textclass);
420 begin_inset(os, "ERT");
421 os << "\nstatus collapsed\n";
422 newcontext.check_layout(os);
423 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
425 os << "\n\\backslash\n";
429 // make sure that our comment is the last thing on the line
430 newcontext.new_paragraph(os);
431 newcontext.check_layout(os);
432 newcontext.check_end_layout(os);
437 class isLayout : public std::unary_function<LayoutPtr, bool> {
439 isLayout(string const name) : name_(name) {}
440 bool operator()(LayoutPtr const & ptr) const {
441 return ptr->latexname() == name_;
448 LayoutPtr findLayout(TextClass const & textclass,
451 TextClass::const_iterator beg = textclass.begin();
452 TextClass::const_iterator end = textclass.end();
454 TextClass::const_iterator
455 it = std::find_if(beg, end, isLayout(name));
457 return (it == end) ? LayoutPtr() : *it;
461 void eat_whitespace(Parser &, ostream &, Context &, bool);
464 void output_command_layout(ostream & os, Parser & p, bool outer,
465 Context & parent_context,
468 parent_context.check_end_layout(os);
469 Context context(true, parent_context.textclass, newlayout,
470 parent_context.layout, parent_context.font);
471 if (parent_context.deeper_paragraph) {
472 // We are beginning a nested environment after a
473 // deeper paragraph inside the outer list environment.
474 // Therefore we don't need to output a "begin deeper".
475 context.need_end_deeper = true;
477 context.check_deeper(os);
478 context.check_layout(os);
479 if (context.layout->optionalargs > 0) {
480 eat_whitespace(p, os, context, false);
481 if (p.next_token().character() == '[') {
482 p.get_token(); // eat '['
483 begin_inset(os, "OptArg\n");
484 os << "status collapsed\n\n";
485 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
487 eat_whitespace(p, os, context, false);
490 parse_text(p, os, FLAG_ITEM, outer, context);
491 context.check_end_layout(os);
492 if (parent_context.deeper_paragraph) {
493 // We must suppress the "end deeper" because we
494 // suppressed the "begin deeper" above.
495 context.need_end_deeper = false;
497 context.check_end_deeper(os);
498 // We don't need really a new paragraph, but
499 // we must make sure that the next item gets a \begin_layout.
500 parent_context.new_paragraph(os);
505 * Output a space if necessary.
506 * This function gets called for every whitespace token.
508 * We have three cases here:
509 * 1. A space must be suppressed. Example: The lyxcode case below
510 * 2. A space may be suppressed. Example: Spaces before "\par"
511 * 3. A space must not be suppressed. Example: A space between two words
513 * We currently handle only 1. and 3 and from 2. only the case of
514 * spaces before newlines as a side effect.
516 * 2. could be used to suppress as many spaces as possible. This has two effects:
517 * - Reimporting LyX generated LaTeX files changes almost no whitespace
518 * - Superflous whitespace from non LyX generated LaTeX files is removed.
519 * The drawback is that the logic inside the function becomes
520 * complicated, and that is the reason why it is not implemented.
522 void check_space(Parser const & p, ostream & os, Context & context)
524 Token const next = p.next_token();
525 Token const curr = p.curr_token();
526 // A space before a single newline and vice versa must be ignored
527 // LyX emits a newline before \end{lyxcode}.
528 // This newline must be ignored,
529 // otherwise LyX will add an additional protected space.
530 if (next.cat() == catSpace ||
531 next.cat() == catNewline ||
532 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
535 context.check_layout(os);
541 * Parse all arguments of \p command
543 void parse_arguments(string const & command,
544 vector<ArgumentType> const & template_arguments,
545 Parser & p, ostream & os, bool outer, Context & context)
547 string ert = command;
548 size_t no_arguments = template_arguments.size();
549 for (size_t i = 0; i < no_arguments; ++i) {
550 switch (template_arguments[i]) {
552 // This argument contains regular LaTeX
553 handle_ert(os, ert + '{', context);
554 eat_whitespace(p, os, context, false);
555 parse_text(p, os, FLAG_ITEM, outer, context);
559 // This argument may contain special characters
560 ert += '{' + p.verbatim_item() + '}';
567 handle_ert(os, ert, context);
572 * Check whether \p command is a known command. If yes,
573 * handle the command with all arguments.
574 * \return true if the command was parsed, false otherwise.
576 bool parse_command(string const & command, Parser & p, ostream & os,
577 bool outer, Context & context)
579 if (known_commands.find(command) != known_commands.end()) {
580 parse_arguments(command, known_commands[command], p, os,
588 /// Parses a minipage or parbox
589 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
590 Context & parent_context, bool use_parbox)
594 // We need to set the height to the LaTeX default of 1\\totalheight
595 // for the case when no height argument is given
596 string height_value = "1";
597 string height_unit = "in";
598 string height_special = "totalheight";
600 if (p.next_token().asInput() == "[") {
601 position = p.getArg('[', ']');
602 if (position != "t" && position != "c" && position != "b") {
604 cerr << "invalid position for minipage/parbox" << endl;
606 if (p.next_token().asInput() == "[") {
607 latex_height = p.getArg('[', ']');
608 translate_box_len(latex_height, height_value, height_unit, height_special);
610 if (p.next_token().asInput() == "[") {
611 inner_pos = p.getArg('[', ']');
612 if (inner_pos != "c" && inner_pos != "t" &&
613 inner_pos != "b" && inner_pos != "s") {
614 inner_pos = position;
615 cerr << "invalid inner_pos for minipage/parbox"
623 string const latex_width = p.verbatim_item();
624 translate_len(latex_width, width_value, width_unit);
625 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
626 // LyX can't handle length variables
631 ss << "\\begin{minipage}";
632 if (!position.empty())
633 ss << '[' << position << ']';
634 if (!latex_height.empty())
635 ss << '[' << latex_height << ']';
636 if (!inner_pos.empty())
637 ss << '[' << inner_pos << ']';
638 ss << "{" << latex_width << "}";
641 handle_ert(os, ss.str(), parent_context);
642 parent_context.new_paragraph(os);
643 parse_text_in_inset(p, os, flags, outer, parent_context);
645 handle_ert(os, "}", parent_context);
647 handle_ert(os, "\\end{minipage}", parent_context);
649 // LyX does not like empty positions, so we have
650 // to set them to the LaTeX default values here.
651 if (position.empty())
653 if (inner_pos.empty())
654 inner_pos = position;
655 parent_context.check_layout(os);
656 begin_inset(os, "Box Frameless\n");
657 os << "position \"" << position << "\"\n";
658 os << "hor_pos \"c\"\n";
659 os << "has_inner_box 1\n";
660 os << "inner_pos \"" << inner_pos << "\"\n";
661 os << "use_parbox " << use_parbox << "\n";
662 os << "width \"" << width_value << width_unit << "\"\n";
663 os << "special \"none\"\n";
664 os << "height \"" << height_value << height_unit << "\"\n";
665 os << "height_special \"" << height_special << "\"\n";
666 os << "status open\n\n";
667 parse_text_in_inset(p, os, flags, outer, parent_context);
669 #ifdef PRESERVE_LAYOUT
670 // lyx puts a % after the end of the minipage
671 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
673 //handle_comment(os, "%dummy", parent_context);
676 parent_context.new_paragraph(os);
678 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
679 //handle_comment(os, "%dummy", parent_context);
682 // We add a protected space if something real follows
683 if (p.good() && p.next_token().cat() != catComment) {
684 os << "\\InsetSpace ~\n";
692 /// parse an unknown environment
693 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
694 unsigned flags, bool outer,
695 Context & parent_context)
697 if (name == "tabbing")
698 // We need to remember that we have to handle '\=' specially
699 flags |= FLAG_TABBING;
701 // We need to translate font changes and paragraphs inside the
702 // environment to ERT if we have a non standard font.
703 // Otherwise things like
704 // \large\begin{foo}\huge bar\end{foo}
706 bool const specialfont =
707 (parent_context.font != parent_context.normalfont);
708 bool const new_layout_allowed = parent_context.new_layout_allowed;
710 parent_context.new_layout_allowed = false;
711 handle_ert(os, "\\begin{" + name + "}", parent_context);
712 parse_text_snippet(p, os, flags, outer, parent_context);
713 handle_ert(os, "\\end{" + name + "}", parent_context);
715 parent_context.new_layout_allowed = new_layout_allowed;
719 void parse_environment(Parser & p, ostream & os, bool outer,
720 Context & parent_context)
723 string const name = p.getArg('{', '}');
724 const bool is_starred = suffixIs(name, '*');
725 string const unstarred_name = rtrim(name, "*");
726 active_environments.push_back(name);
728 if (is_math_env(name)) {
729 parent_context.check_layout(os);
730 begin_inset(os, "Formula ");
731 os << "\\begin{" << name << "}";
732 parse_math(p, os, FLAG_END, MATH_MODE);
733 os << "\\end{" << name << "}";
737 else if (name == "tabular" || name == "longtable") {
738 eat_whitespace(p, os, parent_context, false);
739 parent_context.check_layout(os);
740 begin_inset(os, "Tabular ");
741 handle_tabular(p, os, name == "longtable", parent_context);
746 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
747 eat_whitespace(p, os, parent_context, false);
748 parent_context.check_layout(os);
749 begin_inset(os, "Float " + unstarred_name + "\n");
750 if (p.next_token().asInput() == "[") {
751 os << "placement " << p.getArg('[', ']') << '\n';
753 os << "wide " << convert<string>(is_starred)
754 << "\nsideways false"
755 << "\nstatus open\n\n";
756 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
758 // We don't need really a new paragraph, but
759 // we must make sure that the next item gets a \begin_layout.
760 parent_context.new_paragraph(os);
764 else if (name == "minipage") {
765 eat_whitespace(p, os, parent_context, false);
766 parse_box(p, os, FLAG_END, outer, parent_context, false);
770 else if (name == "comment") {
771 eat_whitespace(p, os, parent_context, false);
772 parent_context.check_layout(os);
773 begin_inset(os, "Note Comment\n");
774 os << "status open\n";
775 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
780 else if (name == "lyxgreyedout") {
781 eat_whitespace(p, os, parent_context, false);
782 parent_context.check_layout(os);
783 begin_inset(os, "Note Greyedout\n");
784 os << "status open\n";
785 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
790 else if (!parent_context.new_layout_allowed)
791 parse_unknown_environment(p, name, os, FLAG_END, outer,
794 // Alignment settings
795 else if (name == "center" || name == "flushleft" || name == "flushright" ||
796 name == "centering" || name == "raggedright" || name == "raggedleft") {
797 eat_whitespace(p, os, parent_context, false);
798 // We must begin a new paragraph if not already done
799 if (! parent_context.atParagraphStart()) {
800 parent_context.check_end_layout(os);
801 parent_context.new_paragraph(os);
803 if (name == "flushleft" || name == "raggedright")
804 parent_context.add_extra_stuff("\\align left\n");
805 else if (name == "flushright" || name == "raggedleft")
806 parent_context.add_extra_stuff("\\align right\n");
808 parent_context.add_extra_stuff("\\align center\n");
809 parse_text(p, os, FLAG_END, outer, parent_context);
810 // Just in case the environment is empty ..
811 parent_context.extra_stuff.erase();
812 // We must begin a new paragraph to reset the alignment
813 parent_context.new_paragraph(os);
817 // The single '=' is meant here.
818 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
819 newlayout->isEnvironment()) {
820 eat_whitespace(p, os, parent_context, false);
821 Context context(true, parent_context.textclass, newlayout,
822 parent_context.layout, parent_context.font);
823 if (parent_context.deeper_paragraph) {
824 // We are beginning a nested environment after a
825 // deeper paragraph inside the outer list environment.
826 // Therefore we don't need to output a "begin deeper".
827 context.need_end_deeper = true;
829 parent_context.check_end_layout(os);
830 switch (context.layout->latextype) {
831 case LATEX_LIST_ENVIRONMENT:
832 context.extra_stuff = "\\labelwidthstring "
833 + p.verbatim_item() + '\n';
836 case LATEX_BIB_ENVIRONMENT:
837 p.verbatim_item(); // swallow next arg
843 context.check_deeper(os);
844 parse_text(p, os, FLAG_END, outer, context);
845 context.check_end_layout(os);
846 if (parent_context.deeper_paragraph) {
847 // We must suppress the "end deeper" because we
848 // suppressed the "begin deeper" above.
849 context.need_end_deeper = false;
851 context.check_end_deeper(os);
852 parent_context.new_paragraph(os);
856 else if (name == "appendix") {
857 // This is no good latex style, but it works and is used in some documents...
858 eat_whitespace(p, os, parent_context, false);
859 parent_context.check_end_layout(os);
860 Context context(true, parent_context.textclass, parent_context.layout,
861 parent_context.layout, parent_context.font);
862 context.check_layout(os);
863 os << "\\start_of_appendix\n";
864 parse_text(p, os, FLAG_END, outer, context);
865 context.check_end_layout(os);
869 else if (known_environments.find(name) != known_environments.end()) {
870 vector<ArgumentType> arguments = known_environments[name];
871 // The last "argument" denotes wether we may translate the
872 // environment contents to LyX
873 // The default required if no argument is given makes us
874 // compatible with the reLyXre environment.
875 ArgumentType contents = arguments.empty() ?
878 if (!arguments.empty())
879 arguments.pop_back();
880 // See comment in parse_unknown_environment()
881 bool const specialfont =
882 (parent_context.font != parent_context.normalfont);
883 bool const new_layout_allowed =
884 parent_context.new_layout_allowed;
886 parent_context.new_layout_allowed = false;
887 parse_arguments("\\begin{" + name + "}", arguments, p, os,
888 outer, parent_context);
889 if (contents == verbatim)
890 handle_ert(os, p.verbatimEnvironment(name),
893 parse_text_snippet(p, os, FLAG_END, outer,
895 handle_ert(os, "\\end{" + name + "}", parent_context);
897 parent_context.new_layout_allowed = new_layout_allowed;
901 parse_unknown_environment(p, name, os, FLAG_END, outer,
904 active_environments.pop_back();
908 /// parses a comment and outputs it to \p os.
909 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
911 BOOST_ASSERT(t.cat() == catComment);
912 if (!t.cs().empty()) {
913 context.check_layout(os);
914 handle_comment(os, '%' + t.cs(), context);
915 if (p.next_token().cat() == catNewline) {
916 // A newline after a comment line starts a new
918 if (context.new_layout_allowed) {
919 if(!context.atParagraphStart())
920 // Only start a new paragraph if not already
921 // done (we might get called recursively)
922 context.new_paragraph(os);
924 handle_ert(os, "\n", context);
925 eat_whitespace(p, os, context, true);
935 * Reads spaces and comments until the first non-space, non-comment token.
936 * New paragraphs (double newlines or \\par) are handled like simple spaces
937 * if \p eatParagraph is true.
938 * Spaces are skipped, but comments are written to \p os.
940 void eat_whitespace(Parser & p, ostream & os, Context & context,
944 Token const & t = p.get_token();
945 if (t.cat() == catComment)
946 parse_comment(p, os, t, context);
947 else if ((! eatParagraph && p.isParagraph()) ||
948 (t.cat() != catSpace && t.cat() != catNewline)) {
957 * Set a font attribute, parse text and reset the font attribute.
958 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
959 * \param currentvalue Current value of the attribute. Is set to the new
960 * value during parsing.
961 * \param newvalue New value of the attribute
963 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
964 Context & context, string const & attribute,
965 string & currentvalue, string const & newvalue)
967 context.check_layout(os);
968 string const oldvalue = currentvalue;
969 currentvalue = newvalue;
970 os << '\n' << attribute << ' ' << newvalue << "\n";
971 parse_text_snippet(p, os, flags, outer, context);
972 context.check_layout(os);
973 os << '\n' << attribute << ' ' << oldvalue << "\n";
974 currentvalue = oldvalue;
978 /// get the arguments of a natbib or jurabib citation command
979 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
981 // We need to distinguish "" and "[]", so we can't use p.getOpt().
983 // text before the citation
985 // text after the citation
986 string after = p.getFullOpt();
988 if (!after.empty()) {
989 before = p.getFullOpt();
990 if (natbibOrder && !before.empty())
991 std::swap(before, after);
993 return std::make_pair(before, after);
997 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
998 string const normalize_filename(string const & name)
1000 Parser p(trim(name, "\""));
1003 Token const & t = p.get_token();
1004 if (t.cat() != catEscape)
1006 else if (t.cs() == "lyxdot") {
1007 // This is used by LyX for simple dots in relative
1011 } else if (t.cs() == "space") {
1021 /// Convert \p name from TeX convention (relative to master file) to LyX
1022 /// convention (relative to .lyx file) if it is relative
1023 void fix_relative_filename(string & name)
1025 if (lyx::support::absolutePath(name))
1027 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1029 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFilename()),
1030 from_utf8(getParentFilePath())));
1034 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1035 void parse_noweb(Parser & p, ostream & os, Context & context)
1037 // assemble the rest of the keyword
1041 Token const & t = p.get_token();
1042 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1045 scrap = (p.good() && p.next_token().asInput() == "=");
1047 name += p.get_token().asInput();
1050 name += t.asInput();
1053 if (!scrap || !context.new_layout_allowed ||
1054 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1055 cerr << "Warning: Could not interpret '" << name
1056 << "'. Ignoring it." << endl;
1060 // We use new_paragraph instead of check_end_layout because the stuff
1061 // following the noweb chunk needs to start with a \begin_layout.
1062 // This may create a new paragraph even if there was none in the
1063 // noweb file, but the alternative is an invalid LyX file. Since
1064 // noweb code chunks are implemented with a layout style in LyX they
1065 // always must be in an own paragraph.
1066 context.new_paragraph(os);
1067 Context newcontext(true, context.textclass,
1068 context.textclass[from_ascii("Scrap")]);
1069 newcontext.check_layout(os);
1072 Token const & t = p.get_token();
1073 // We abuse the parser a bit, because this is no TeX syntax
1075 if (t.cat() == catEscape)
1076 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1078 os << subst(t.asInput(), "\n", "\n\\newline\n");
1079 // The scrap chunk is ended by an @ at the beginning of a line.
1080 // After the @ the line may contain a comment and/or
1081 // whitespace, but nothing else.
1082 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1083 (p.next_token().cat() == catSpace ||
1084 p.next_token().cat() == catNewline ||
1085 p.next_token().cat() == catComment)) {
1086 while (p.good() && p.next_token().cat() == catSpace)
1087 os << p.get_token().asInput();
1088 if (p.next_token().cat() == catComment)
1089 // The comment includes a final '\n'
1090 os << p.get_token().asInput();
1092 if (p.next_token().cat() == catNewline)
1099 newcontext.check_end_layout(os);
1102 } // anonymous namespace
1105 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1108 LayoutPtr newlayout;
1109 // Store the latest bibliographystyle (needed for bibtex inset)
1110 string bibliographystyle;
1111 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1112 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1114 Token const & t = p.get_token();
1117 cerr << "t: " << t << " flags: " << flags << "\n";
1120 if (flags & FLAG_ITEM) {
1121 if (t.cat() == catSpace)
1124 flags &= ~FLAG_ITEM;
1125 if (t.cat() == catBegin) {
1126 // skip the brace and collect everything to the next matching
1128 flags |= FLAG_BRACE_LAST;
1132 // handle only this single token, leave the loop if done
1133 flags |= FLAG_LEAVE;
1136 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1142 if (t.cat() == catMath) {
1143 // we are inside some text mode thingy, so opening new math is allowed
1144 context.check_layout(os);
1145 begin_inset(os, "Formula ");
1146 Token const & n = p.get_token();
1147 if (n.cat() == catMath && outer) {
1148 // TeX's $$...$$ syntax for displayed math
1150 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1152 p.get_token(); // skip the second '$' token
1154 // simple $...$ stuff
1157 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1163 else if (t.cat() == catSuper || t.cat() == catSub)
1164 cerr << "catcode " << t << " illegal in text mode\n";
1166 // Basic support for english quotes. This should be
1167 // extended to other quotes, but is not so easy (a
1168 // left english quote is the same as a right german
1170 else if (t.asInput() == "`"
1171 && p.next_token().asInput() == "`") {
1172 context.check_layout(os);
1173 begin_inset(os, "Quotes ");
1179 else if (t.asInput() == "'"
1180 && p.next_token().asInput() == "'") {
1181 context.check_layout(os);
1182 begin_inset(os, "Quotes ");
1189 else if (t.asInput() == "<"
1190 && p.next_token().asInput() == "<" && noweb_mode) {
1192 parse_noweb(p, os, context);
1195 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1196 check_space(p, os, context);
1198 else if (t.character() == '[' && noweb_mode &&
1199 p.next_token().character() == '[') {
1200 // These can contain underscores
1202 string const s = p.getFullOpt() + ']';
1203 if (p.next_token().character() == ']')
1206 cerr << "Warning: Inserting missing ']' in '"
1207 << s << "'." << endl;
1208 handle_ert(os, s, context);
1211 else if (t.cat() == catLetter ||
1212 t.cat() == catOther ||
1213 t.cat() == catAlign ||
1214 t.cat() == catParameter) {
1215 // This translates "&" to "\\&" which may be wrong...
1216 context.check_layout(os);
1217 os << t.character();
1220 else if (p.isParagraph()) {
1221 if (context.new_layout_allowed)
1222 context.new_paragraph(os);
1224 handle_ert(os, "\\par ", context);
1225 eat_whitespace(p, os, context, true);
1228 else if (t.cat() == catActive) {
1229 context.check_layout(os);
1230 if (t.character() == '~') {
1231 if (context.layout->free_spacing)
1234 os << "\\InsetSpace ~\n";
1236 os << t.character();
1239 else if (t.cat() == catBegin &&
1240 p.next_token().cat() == catEnd) {
1242 Token const prev = p.prev_token();
1244 if (p.next_token().character() == '`' ||
1245 (prev.character() == '-' &&
1246 p.next_token().character() == '-'))
1247 ; // ignore it in {}`` or -{}-
1249 handle_ert(os, "{}", context);
1253 else if (t.cat() == catBegin) {
1254 context.check_layout(os);
1255 // special handling of font attribute changes
1256 Token const prev = p.prev_token();
1257 Token const next = p.next_token();
1258 TeXFont const oldFont = context.font;
1259 if (next.character() == '[' ||
1260 next.character() == ']' ||
1261 next.character() == '*') {
1263 if (p.next_token().cat() == catEnd) {
1264 os << next.character();
1268 handle_ert(os, "{", context);
1269 parse_text_snippet(p, os,
1272 handle_ert(os, "}", context);
1274 } else if (! context.new_layout_allowed) {
1275 handle_ert(os, "{", context);
1276 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1278 handle_ert(os, "}", context);
1279 } else if (is_known(next.cs(), known_sizes)) {
1280 // next will change the size, so we must
1282 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1284 if (!context.atParagraphStart())
1286 << context.font.size << "\n";
1287 } else if (is_known(next.cs(), known_font_families)) {
1288 // next will change the font family, so we
1289 // must reset it here
1290 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1292 if (!context.atParagraphStart())
1294 << context.font.family << "\n";
1295 } else if (is_known(next.cs(), known_font_series)) {
1296 // next will change the font series, so we
1297 // must reset it here
1298 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1300 if (!context.atParagraphStart())
1302 << context.font.series << "\n";
1303 } else if (is_known(next.cs(), known_font_shapes)) {
1304 // next will change the font shape, so we
1305 // must reset it here
1306 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1308 if (!context.atParagraphStart())
1310 << context.font.shape << "\n";
1311 } else if (is_known(next.cs(), known_old_font_families) ||
1312 is_known(next.cs(), known_old_font_series) ||
1313 is_known(next.cs(), known_old_font_shapes)) {
1314 // next will change the font family, series
1315 // and shape, so we must reset it here
1316 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1318 if (!context.atParagraphStart())
1320 << context.font.family
1322 << context.font.series
1324 << context.font.shape << "\n";
1326 handle_ert(os, "{", context);
1327 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1329 handle_ert(os, "}", context);
1333 else if (t.cat() == catEnd) {
1334 if (flags & FLAG_BRACE_LAST) {
1337 cerr << "stray '}' in text\n";
1338 handle_ert(os, "}", context);
1341 else if (t.cat() == catComment)
1342 parse_comment(p, os, t, context);
1345 // control sequences
1348 else if (t.cs() == "(") {
1349 context.check_layout(os);
1350 begin_inset(os, "Formula");
1352 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1357 else if (t.cs() == "[") {
1358 context.check_layout(os);
1359 begin_inset(os, "Formula");
1361 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1366 else if (t.cs() == "begin")
1367 parse_environment(p, os, outer, context);
1369 else if (t.cs() == "end") {
1370 if (flags & FLAG_END) {
1371 // eat environment name
1372 string const name = p.getArg('{', '}');
1373 if (name != active_environment())
1374 cerr << "\\end{" + name + "} does not match \\begin{"
1375 + active_environment() + "}\n";
1378 p.error("found 'end' unexpectedly");
1381 else if (t.cs() == "item") {
1384 bool optarg = false;
1385 if (p.next_token().character() == '[') {
1386 p.get_token(); // eat '['
1387 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1392 context.check_layout(os);
1393 if (context.has_item) {
1394 // An item in an unknown list-like environment
1395 // FIXME: Do this in check_layout()!
1396 context.has_item = false;
1398 handle_ert(os, "\\item", context);
1400 handle_ert(os, "\\item ", context);
1403 if (context.layout->labeltype != LABEL_MANUAL) {
1404 // lyx does not support \item[\mybullet]
1405 // in itemize environments
1406 handle_ert(os, "[", context);
1408 handle_ert(os, "]", context);
1409 } else if (!s.empty()) {
1410 // The space is needed to separate the
1411 // item from the rest of the sentence.
1413 eat_whitespace(p, os, context, false);
1418 else if (t.cs() == "bibitem") {
1420 context.check_layout(os);
1423 os << '{' << p.verbatim_item() << '}' << "\n";
1426 else if (t.cs() == "def") {
1427 context.check_layout(os);
1428 eat_whitespace(p, os, context, false);
1429 string name = p.get_token().cs();
1430 eat_whitespace(p, os, context, false);
1436 while (p.next_token().cat() != catBegin) {
1437 if (p.next_token().cat() == catParameter) {
1442 // followed by number?
1443 if (p.next_token().cat() == catOther) {
1444 char c = p.getChar();
1446 // number = current arity + 1?
1447 if (c == arity + '0' + 1)
1452 paramtext += p.get_token().asString();
1454 paramtext += p.get_token().asString();
1459 // only output simple (i.e. compatible) macro as FormulaMacros
1460 string ert = "\\def\\" + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1462 context.check_layout(os);
1463 begin_inset(os, "FormulaMacro");
1467 handle_ert(os, ert, context);
1470 else if (t.cs() == "noindent") {
1472 context.add_extra_stuff("\\noindent\n");
1475 else if (t.cs() == "appendix") {
1476 context.add_extra_stuff("\\start_of_appendix\n");
1477 // We need to start a new paragraph. Otherwise the
1478 // appendix in 'bla\appendix\chapter{' would start
1480 context.new_paragraph(os);
1481 // We need to make sure that the paragraph is
1482 // generated even if it is empty. Otherwise the
1483 // appendix in '\par\appendix\par\chapter{' would
1485 context.check_layout(os);
1486 // FIXME: This is a hack to prevent paragraph
1487 // deletion if it is empty. Handle this better!
1489 "%dummy comment inserted by tex2lyx to "
1490 "ensure that this paragraph is not empty",
1492 // Both measures above may generate an additional
1493 // empty paragraph, but that does not hurt, because
1494 // whitespace does not matter here.
1495 eat_whitespace(p, os, context, true);
1498 // Must attempt to parse "Section*" before "Section".
1499 else if ((p.next_token().asInput() == "*") &&
1500 context.new_layout_allowed &&
1501 // The single '=' is meant here.
1502 (newlayout = findLayout(context.textclass,
1503 t.cs() + '*')).get() &&
1504 newlayout->isCommand()) {
1506 output_command_layout(os, p, outer, context, newlayout);
1510 // The single '=' is meant here.
1511 else if (context.new_layout_allowed &&
1512 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1513 newlayout->isCommand()) {
1514 output_command_layout(os, p, outer, context, newlayout);
1518 // Special handling for \caption
1519 // FIXME: remove this when InsetCaption is supported.
1520 else if (context.new_layout_allowed &&
1521 t.cs() == captionlayout->latexname()) {
1522 output_command_layout(os, p, outer, context,
1527 else if (t.cs() == "includegraphics") {
1528 bool const clip = p.next_token().asInput() == "*";
1531 map<string, string> opts = split_map(p.getArg('[', ']'));
1533 opts["clip"] = string();
1534 string name = normalize_filename(p.verbatim_item());
1536 string const path = getMasterFilePath();
1537 // We want to preserve relative / absolute filenames,
1538 // therefore path is only used for testing
1539 // FIXME UNICODE encoding of name and path may be
1540 // wrong (makeAbsPath expects utf8)
1541 if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1542 // The file extension is probably missing.
1543 // Now try to find it out.
1544 string const dvips_name =
1545 find_file(name, path,
1546 known_dvips_graphics_formats);
1547 string const pdftex_name =
1548 find_file(name, path,
1549 known_pdftex_graphics_formats);
1550 if (!dvips_name.empty()) {
1551 if (!pdftex_name.empty()) {
1552 cerr << "This file contains the "
1554 "\"\\includegraphics{"
1556 "However, files\n\""
1557 << dvips_name << "\" and\n\""
1558 << pdftex_name << "\"\n"
1559 "both exist, so I had to make a "
1560 "choice and took the first one.\n"
1561 "Please move the unwanted one "
1562 "someplace else and try again\n"
1563 "if my choice was wrong."
1567 } else if (!pdftex_name.empty())
1571 // FIXME UNICODE encoding of name and path may be
1572 // wrong (makeAbsPath expects utf8)
1573 if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1574 fix_relative_filename(name);
1576 cerr << "Warning: Could not find graphics file '"
1577 << name << "'." << endl;
1579 context.check_layout(os);
1580 begin_inset(os, "Graphics ");
1581 os << "\n\tfilename " << name << '\n';
1582 if (opts.find("width") != opts.end())
1584 << translate_len(opts["width"]) << '\n';
1585 if (opts.find("height") != opts.end())
1587 << translate_len(opts["height"]) << '\n';
1588 if (opts.find("scale") != opts.end()) {
1589 istringstream iss(opts["scale"]);
1593 os << "\tscale " << val << '\n';
1595 if (opts.find("angle") != opts.end())
1596 os << "\trotateAngle "
1597 << opts["angle"] << '\n';
1598 if (opts.find("origin") != opts.end()) {
1600 string const opt = opts["origin"];
1601 if (opt.find('l') != string::npos) ss << "left";
1602 if (opt.find('r') != string::npos) ss << "right";
1603 if (opt.find('c') != string::npos) ss << "center";
1604 if (opt.find('t') != string::npos) ss << "Top";
1605 if (opt.find('b') != string::npos) ss << "Bottom";
1606 if (opt.find('B') != string::npos) ss << "Baseline";
1607 if (!ss.str().empty())
1608 os << "\trotateOrigin " << ss.str() << '\n';
1610 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1612 if (opts.find("keepaspectratio") != opts.end())
1613 os << "\tkeepAspectRatio\n";
1614 if (opts.find("clip") != opts.end())
1616 if (opts.find("draft") != opts.end())
1618 if (opts.find("bb") != opts.end())
1619 os << "\tBoundingBox "
1620 << opts["bb"] << '\n';
1621 int numberOfbbOptions = 0;
1622 if (opts.find("bbllx") != opts.end())
1623 numberOfbbOptions++;
1624 if (opts.find("bblly") != opts.end())
1625 numberOfbbOptions++;
1626 if (opts.find("bburx") != opts.end())
1627 numberOfbbOptions++;
1628 if (opts.find("bbury") != opts.end())
1629 numberOfbbOptions++;
1630 if (numberOfbbOptions == 4)
1631 os << "\tBoundingBox "
1632 << opts["bbllx"] << opts["bblly"]
1633 << opts["bburx"] << opts["bbury"] << '\n';
1634 else if (numberOfbbOptions > 0)
1635 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1636 numberOfbbOptions = 0;
1637 if (opts.find("natwidth") != opts.end())
1638 numberOfbbOptions++;
1639 if (opts.find("natheight") != opts.end())
1640 numberOfbbOptions++;
1641 if (numberOfbbOptions == 2)
1642 os << "\tBoundingBox 0bp 0bp "
1643 << opts["natwidth"] << opts["natheight"] << '\n';
1644 else if (numberOfbbOptions > 0)
1645 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1646 ostringstream special;
1647 if (opts.find("hiresbb") != opts.end())
1648 special << "hiresbb,";
1649 if (opts.find("trim") != opts.end())
1651 if (opts.find("viewport") != opts.end())
1652 special << "viewport=" << opts["viewport"] << ',';
1653 if (opts.find("totalheight") != opts.end())
1654 special << "totalheight=" << opts["totalheight"] << ',';
1655 if (opts.find("type") != opts.end())
1656 special << "type=" << opts["type"] << ',';
1657 if (opts.find("ext") != opts.end())
1658 special << "ext=" << opts["ext"] << ',';
1659 if (opts.find("read") != opts.end())
1660 special << "read=" << opts["read"] << ',';
1661 if (opts.find("command") != opts.end())
1662 special << "command=" << opts["command"] << ',';
1663 string s_special = special.str();
1664 if (!s_special.empty()) {
1665 // We had special arguments. Remove the trailing ','.
1666 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1668 // TODO: Handle the unknown settings better.
1669 // Warn about invalid options.
1670 // Check whether some option was given twice.
1674 else if (t.cs() == "footnote" ||
1675 (t.cs() == "thanks" && context.layout->intitle)) {
1677 context.check_layout(os);
1678 begin_inset(os, "Foot\n");
1679 os << "status collapsed\n\n";
1680 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1684 else if (t.cs() == "marginpar") {
1686 context.check_layout(os);
1687 begin_inset(os, "Marginal\n");
1688 os << "status collapsed\n\n";
1689 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1693 else if (t.cs() == "ensuremath") {
1695 context.check_layout(os);
1696 string const s = p.verbatim_item();
1697 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1700 handle_ert(os, "\\ensuremath{" + s + "}",
1704 else if (t.cs() == "hfill") {
1705 context.check_layout(os);
1706 os << "\n\\hfill\n";
1711 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1712 // FIXME: Somehow prevent title layouts if
1713 // "maketitle" was not found
1715 skip_braces(p); // swallow this
1718 else if (t.cs() == "tableofcontents") {
1720 context.check_layout(os);
1721 begin_inset(os, "LatexCommand \\tableofcontents\n");
1723 skip_braces(p); // swallow this
1726 else if (t.cs() == "listoffigures") {
1728 context.check_layout(os);
1729 begin_inset(os, "FloatList figure\n");
1731 skip_braces(p); // swallow this
1734 else if (t.cs() == "listoftables") {
1736 context.check_layout(os);
1737 begin_inset(os, "FloatList table\n");
1739 skip_braces(p); // swallow this
1742 else if (t.cs() == "listof") {
1743 p.skip_spaces(true);
1744 string const name = p.get_token().asString();
1745 if (context.textclass.floats().typeExist(name)) {
1746 context.check_layout(os);
1747 begin_inset(os, "FloatList ");
1750 p.get_token(); // swallow second arg
1752 handle_ert(os, "\\listof{" + name + "}", context);
1755 else if (t.cs() == "textrm")
1756 parse_text_attributes(p, os, FLAG_ITEM, outer,
1757 context, "\\family",
1758 context.font.family, "roman");
1760 else if (t.cs() == "textsf")
1761 parse_text_attributes(p, os, FLAG_ITEM, outer,
1762 context, "\\family",
1763 context.font.family, "sans");
1765 else if (t.cs() == "texttt")
1766 parse_text_attributes(p, os, FLAG_ITEM, outer,
1767 context, "\\family",
1768 context.font.family, "typewriter");
1770 else if (t.cs() == "textmd")
1771 parse_text_attributes(p, os, FLAG_ITEM, outer,
1772 context, "\\series",
1773 context.font.series, "medium");
1775 else if (t.cs() == "textbf")
1776 parse_text_attributes(p, os, FLAG_ITEM, outer,
1777 context, "\\series",
1778 context.font.series, "bold");
1780 else if (t.cs() == "textup")
1781 parse_text_attributes(p, os, FLAG_ITEM, outer,
1783 context.font.shape, "up");
1785 else if (t.cs() == "textit")
1786 parse_text_attributes(p, os, FLAG_ITEM, outer,
1788 context.font.shape, "italic");
1790 else if (t.cs() == "textsl")
1791 parse_text_attributes(p, os, FLAG_ITEM, outer,
1793 context.font.shape, "slanted");
1795 else if (t.cs() == "textsc")
1796 parse_text_attributes(p, os, FLAG_ITEM, outer,
1798 context.font.shape, "smallcaps");
1800 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1801 context.check_layout(os);
1802 TeXFont oldFont = context.font;
1803 context.font.init();
1804 context.font.size = oldFont.size;
1805 os << "\n\\family " << context.font.family << "\n";
1806 os << "\n\\series " << context.font.series << "\n";
1807 os << "\n\\shape " << context.font.shape << "\n";
1808 if (t.cs() == "textnormal") {
1809 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1810 output_font_change(os, context.font, oldFont);
1811 context.font = oldFont;
1813 eat_whitespace(p, os, context, false);
1816 else if (t.cs() == "underbar") {
1817 // Do NOT handle \underline.
1818 // \underbar cuts through y, g, q, p etc.,
1819 // \underline does not.
1820 context.check_layout(os);
1821 os << "\n\\bar under\n";
1822 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1823 context.check_layout(os);
1824 os << "\n\\bar default\n";
1827 else if (t.cs() == "emph" || t.cs() == "noun") {
1828 context.check_layout(os);
1829 os << "\n\\" << t.cs() << " on\n";
1830 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1831 context.check_layout(os);
1832 os << "\n\\" << t.cs() << " default\n";
1835 else if (use_natbib &&
1836 is_known(t.cs(), known_natbib_commands) &&
1837 ((t.cs() != "citefullauthor" &&
1838 t.cs() != "citeyear" &&
1839 t.cs() != "citeyearpar") ||
1840 p.next_token().asInput() != "*")) {
1841 context.check_layout(os);
1843 // \citet[before][after]{a} \citet[after][before]{a}
1844 // \citet[before][]{a} \citet[][before]{a}
1845 // \citet[after]{a} \citet[after]{a}
1846 // \citet{a} \citet{a}
1847 string command = '\\' + t.cs();
1848 if (p.next_token().asInput() == "*") {
1852 if (command == "\\citefullauthor")
1853 // alternative name for "\\citeauthor*"
1854 command = "\\citeauthor*";
1856 // text before the citation
1858 // text after the citation
1861 boost::tie(before, after) = getCiteArguments(p, true);
1862 if (command == "\\cite") {
1863 // \cite without optional argument means
1864 // \citet, \cite with at least one optional
1865 // argument means \citep.
1866 if (before.empty() && after.empty())
1867 command = "\\citet";
1869 command = "\\citep";
1871 if (before.empty() && after == "[]")
1872 // avoid \citet[]{a}
1874 else if (before == "[]" && after == "[]") {
1875 // avoid \citet[][]{a}
1879 begin_inset(os, "LatexCommand ");
1880 os << command << after << before
1881 << '{' << p.verbatim_item() << "}\n";
1885 else if (use_jurabib &&
1886 is_known(t.cs(), known_jurabib_commands)) {
1887 context.check_layout(os);
1888 string const command = '\\' + t.cs();
1889 char argumentOrder = '\0';
1890 vector<string> const & options = used_packages["jurabib"];
1891 if (std::find(options.begin(), options.end(),
1892 "natbiborder") != options.end())
1893 argumentOrder = 'n';
1894 else if (std::find(options.begin(), options.end(),
1895 "jurabiborder") != options.end())
1896 argumentOrder = 'j';
1898 // text before the citation
1900 // text after the citation
1903 boost::tie(before, after) =
1904 getCiteArguments(p, argumentOrder != 'j');
1905 string const citation = p.verbatim_item();
1906 if (!before.empty() && argumentOrder == '\0') {
1907 cerr << "Warning: Assuming argument order "
1908 "of jurabib version 0.6 for\n'"
1909 << command << before << after << '{'
1910 << citation << "}'.\n"
1911 "Add 'jurabiborder' to the jurabib "
1912 "package options if you used an\n"
1913 "earlier jurabib version." << endl;
1915 begin_inset(os, "LatexCommand ");
1916 os << command << after << before
1917 << '{' << citation << "}\n";
1921 else if (is_known(t.cs(), known_latex_commands)) {
1922 // This needs to be after the check for natbib and
1923 // jurabib commands, because "cite" has different
1924 // arguments with natbib and jurabib.
1925 context.check_layout(os);
1926 begin_inset(os, "LatexCommand ");
1927 os << '\\' << t.cs();
1928 // lyx cannot handle newlines in a latex command
1929 // FIXME: Move the substitution into parser::getOpt()?
1930 os << subst(p.getOpt(), "\n", " ");
1931 os << subst(p.getOpt(), "\n", " ");
1932 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1936 else if (is_known(t.cs(), known_quotes)) {
1937 char const * const * where = is_known(t.cs(), known_quotes);
1938 context.check_layout(os);
1939 begin_inset(os, "Quotes ");
1940 os << known_coded_quotes[where - known_quotes];
1942 // LyX adds {} after the quote, so we have to eat
1943 // spaces here if there are any before a possible
1945 eat_whitespace(p, os, context, false);
1949 else if (is_known(t.cs(), known_sizes) &&
1950 context.new_layout_allowed) {
1951 char const * const * where = is_known(t.cs(), known_sizes);
1952 context.check_layout(os);
1953 TeXFont const oldFont = context.font;
1954 context.font.size = known_coded_sizes[where - known_sizes];
1955 output_font_change(os, oldFont, context.font);
1956 eat_whitespace(p, os, context, false);
1959 else if (is_known(t.cs(), known_font_families) &&
1960 context.new_layout_allowed) {
1961 char const * const * where =
1962 is_known(t.cs(), known_font_families);
1963 context.check_layout(os);
1964 TeXFont const oldFont = context.font;
1965 context.font.family =
1966 known_coded_font_families[where - known_font_families];
1967 output_font_change(os, oldFont, context.font);
1968 eat_whitespace(p, os, context, false);
1971 else if (is_known(t.cs(), known_font_series) &&
1972 context.new_layout_allowed) {
1973 char const * const * where =
1974 is_known(t.cs(), known_font_series);
1975 context.check_layout(os);
1976 TeXFont const oldFont = context.font;
1977 context.font.series =
1978 known_coded_font_series[where - known_font_series];
1979 output_font_change(os, oldFont, context.font);
1980 eat_whitespace(p, os, context, false);
1983 else if (is_known(t.cs(), known_font_shapes) &&
1984 context.new_layout_allowed) {
1985 char const * const * where =
1986 is_known(t.cs(), known_font_shapes);
1987 context.check_layout(os);
1988 TeXFont const oldFont = context.font;
1989 context.font.shape =
1990 known_coded_font_shapes[where - known_font_shapes];
1991 output_font_change(os, oldFont, context.font);
1992 eat_whitespace(p, os, context, false);
1994 else if (is_known(t.cs(), known_old_font_families) &&
1995 context.new_layout_allowed) {
1996 char const * const * where =
1997 is_known(t.cs(), known_old_font_families);
1998 context.check_layout(os);
1999 TeXFont const oldFont = context.font;
2000 context.font.init();
2001 context.font.size = oldFont.size;
2002 context.font.family =
2003 known_coded_font_families[where - known_old_font_families];
2004 output_font_change(os, oldFont, context.font);
2005 eat_whitespace(p, os, context, false);
2008 else if (is_known(t.cs(), known_old_font_series) &&
2009 context.new_layout_allowed) {
2010 char const * const * where =
2011 is_known(t.cs(), known_old_font_series);
2012 context.check_layout(os);
2013 TeXFont const oldFont = context.font;
2014 context.font.init();
2015 context.font.size = oldFont.size;
2016 context.font.series =
2017 known_coded_font_series[where - known_old_font_series];
2018 output_font_change(os, oldFont, context.font);
2019 eat_whitespace(p, os, context, false);
2022 else if (is_known(t.cs(), known_old_font_shapes) &&
2023 context.new_layout_allowed) {
2024 char const * const * where =
2025 is_known(t.cs(), known_old_font_shapes);
2026 context.check_layout(os);
2027 TeXFont const oldFont = context.font;
2028 context.font.init();
2029 context.font.size = oldFont.size;
2030 context.font.shape =
2031 known_coded_font_shapes[where - known_old_font_shapes];
2032 output_font_change(os, oldFont, context.font);
2033 eat_whitespace(p, os, context, false);
2036 else if (t.cs() == "LyX" || t.cs() == "TeX"
2037 || t.cs() == "LaTeX") {
2038 context.check_layout(os);
2040 skip_braces(p); // eat {}
2043 else if (t.cs() == "LaTeXe") {
2044 context.check_layout(os);
2046 skip_braces(p); // eat {}
2049 else if (t.cs() == "ldots") {
2050 context.check_layout(os);
2052 os << "\\SpecialChar \\ldots{}\n";
2055 else if (t.cs() == "lyxarrow") {
2056 context.check_layout(os);
2057 os << "\\SpecialChar \\menuseparator\n";
2061 else if (t.cs() == "textcompwordmark") {
2062 context.check_layout(os);
2063 os << "\\SpecialChar \\textcompwordmark{}\n";
2067 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2068 context.check_layout(os);
2069 os << "\\SpecialChar \\@.\n";
2073 else if (t.cs() == "-") {
2074 context.check_layout(os);
2075 os << "\\SpecialChar \\-\n";
2078 else if (t.cs() == "textasciitilde") {
2079 context.check_layout(os);
2084 else if (t.cs() == "textasciicircum") {
2085 context.check_layout(os);
2090 else if (t.cs() == "textbackslash") {
2091 context.check_layout(os);
2092 os << "\n\\backslash\n";
2096 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2097 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2099 context.check_layout(os);
2103 else if (t.cs() == "char") {
2104 context.check_layout(os);
2105 if (p.next_token().character() == '`') {
2107 if (p.next_token().cs() == "\"") {
2112 handle_ert(os, "\\char`", context);
2115 handle_ert(os, "\\char", context);
2119 else if (t.cs() == "verb") {
2120 context.check_layout(os);
2121 char const delimiter = p.next_token().character();
2122 string const arg = p.getArg(delimiter, delimiter);
2124 oss << "\\verb" << delimiter << arg << delimiter;
2125 handle_ert(os, oss.str(), context);
2128 else if (t.cs() == "\"") {
2129 context.check_layout(os);
2130 string const name = p.verbatim_item();
2131 if (name == "a") os << '\xe4';
2132 else if (name == "o") os << '\xf6';
2133 else if (name == "u") os << '\xfc';
2134 else if (name == "A") os << '\xc4';
2135 else if (name == "O") os << '\xd6';
2136 else if (name == "U") os << '\xdc';
2137 else handle_ert(os, "\"{" + name + "}", context);
2140 // Problem: \= creates a tabstop inside the tabbing environment
2141 // and else an accent. In the latter case we really would want
2142 // \={o} instead of \= o.
2143 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2144 handle_ert(os, t.asInput(), context);
2146 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2147 || t.cs() == "'" || t.cs() == "`"
2148 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2149 // we need the trim as the LyX parser chokes on such spaces
2150 // The argument of InsetLatexAccent is parsed as a
2151 // subset of LaTeX, so don't parse anything here,
2152 // but use the raw argument.
2153 // Otherwise we would convert \~{\i} wrongly.
2154 // This will of course not translate \~{\ss} to \~{ß},
2155 // but that does at least compile and does only look
2156 // strange on screen.
2157 context.check_layout(os);
2158 os << "\\i \\" << t.cs() << "{"
2159 << trim(p.verbatim_item(), " ")
2163 else if (t.cs() == "ss") {
2164 context.check_layout(os);
2166 skip_braces(p); // eat {}
2169 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2171 context.check_layout(os);
2172 os << "\\i \\" << t.cs() << "{}\n";
2173 skip_braces(p); // eat {}
2176 else if (t.cs() == "\\") {
2177 context.check_layout(os);
2178 string const next = p.next_token().asInput();
2180 handle_ert(os, "\\\\" + p.getOpt(), context);
2181 else if (next == "*") {
2183 handle_ert(os, "\\\\*" + p.getOpt(), context);
2186 os << "\n\\newline\n";
2190 else if (t.cs() == "input" || t.cs() == "include"
2191 || t.cs() == "verbatiminput") {
2192 string name = '\\' + t.cs();
2193 if (t.cs() == "verbatiminput"
2194 && p.next_token().asInput() == "*")
2195 name += p.get_token().asInput();
2196 context.check_layout(os);
2197 begin_inset(os, "Include ");
2198 string filename(normalize_filename(p.getArg('{', '}')));
2199 string const path = getMasterFilePath();
2200 // We want to preserve relative / absolute filenames,
2201 // therefore path is only used for testing
2202 // FIXME UNICODE encoding of filename and path may be
2203 // wrong (makeAbsPath expects utf8)
2204 if ((t.cs() == "include" || t.cs() == "input") &&
2205 !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2206 // The file extension is probably missing.
2207 // Now try to find it out.
2208 string const tex_name =
2209 find_file(filename, path,
2210 known_tex_extensions);
2211 if (!tex_name.empty())
2212 filename = tex_name;
2214 // FIXME UNICODE encoding of filename and path may be
2215 // wrong (makeAbsPath expects utf8)
2216 if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2217 string const abstexname =
2218 makeAbsPath(filename, path).absFilename();
2219 string const abslyxname =
2220 changeExtension(abstexname, ".lyx");
2221 fix_relative_filename(filename);
2222 string const lyxname =
2223 changeExtension(filename, ".lyx");
2224 if (t.cs() != "verbatiminput" &&
2225 tex2lyx(abstexname, FileName(abslyxname))) {
2226 os << name << '{' << lyxname << "}\n";
2228 os << name << '{' << filename << "}\n";
2231 cerr << "Warning: Could not find included file '"
2232 << filename << "'." << endl;
2233 os << name << '{' << filename << "}\n";
2235 os << "preview false\n";
2239 else if (t.cs() == "bibliographystyle") {
2240 // store new bibliographystyle
2241 bibliographystyle = p.verbatim_item();
2242 // output new bibliographystyle.
2243 // This is only necessary if used in some other macro than \bibliography.
2244 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2247 else if (t.cs() == "bibliography") {
2248 context.check_layout(os);
2249 begin_inset(os, "LatexCommand ");
2251 // Do we have a bibliographystyle set?
2252 if (!bibliographystyle.empty()) {
2253 os << '[' << bibliographystyle << ']';
2255 os << '{' << p.verbatim_item() << "}\n";
2259 else if (t.cs() == "parbox")
2260 parse_box(p, os, FLAG_ITEM, outer, context, true);
2262 else if (t.cs() == "smallskip" ||
2263 t.cs() == "medskip" ||
2264 t.cs() == "bigskip" ||
2265 t.cs() == "vfill") {
2266 context.check_layout(os);
2267 begin_inset(os, "VSpace ");
2273 else if (is_known(t.cs(), known_spaces)) {
2274 char const * const * where = is_known(t.cs(), known_spaces);
2275 context.check_layout(os);
2276 begin_inset(os, "InsetSpace ");
2277 os << '\\' << known_coded_spaces[where - known_spaces]
2279 // LaTeX swallows whitespace after all spaces except
2280 // "\\,". We have to do that here, too, because LyX
2281 // adds "{}" which would make the spaces significant.
2283 eat_whitespace(p, os, context, false);
2284 // LyX adds "{}" after all spaces except "\\ " and
2285 // "\\,", so we have to remove "{}".
2286 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2287 // remove the braces after "\\,", too.
2292 else if (t.cs() == "newpage" ||
2293 t.cs() == "clearpage" ||
2294 t.cs() == "cleardoublepage") {
2295 context.check_layout(os);
2296 // FIXME: what about \\pagebreak?
2297 os << "\n\\" << t.cs() << "\n";
2298 skip_braces(p); // eat {}
2301 else if (t.cs() == "newcommand" ||
2302 t.cs() == "providecommand" ||
2303 t.cs() == "renewcommand") {
2304 // these could be handled by parse_command(), but
2305 // we need to call add_known_command() here.
2306 string name = t.asInput();
2307 if (p.next_token().asInput() == "*") {
2308 // Starred form. Eat '*'
2312 string const command = p.verbatim_item();
2313 string const opt1 = p.getOpt();
2314 string const opt2 = p.getFullOpt();
2315 add_known_command(command, opt1, !opt2.empty());
2316 string const ert = name + '{' + command + '}' +
2318 '{' + p.verbatim_item() + '}';
2321 context.check_layout(os);
2322 begin_inset(os, "FormulaMacro");
2326 // we cannot handle optional argument, so only output ERT
2327 handle_ert(os, ert, context);
2330 else if (t.cs() == "vspace") {
2331 bool starred = false;
2332 if (p.next_token().asInput() == "*") {
2336 string const length = p.verbatim_item();
2339 bool valid = splitLatexLength(length, valstring, unit);
2340 bool known_vspace = false;
2341 bool known_unit = false;
2344 istringstream iss(valstring);
2347 if (unit == "\\smallskipamount") {
2349 known_vspace = true;
2350 } else if (unit == "\\medskipamount") {
2352 known_vspace = true;
2353 } else if (unit == "\\bigskipamount") {
2355 known_vspace = true;
2356 } else if (unit == "\\fill") {
2358 known_vspace = true;
2361 if (!known_vspace) {
2362 switch (unitFromString(unit)) {
2383 if (known_unit || known_vspace) {
2384 // Literal length or known variable
2385 context.check_layout(os);
2386 begin_inset(os, "VSpace ");
2394 // LyX can't handle other length variables in Inset VSpace
2395 string name = t.asInput();
2400 handle_ert(os, name + '{' + unit + '}', context);
2401 else if (value == -1.0)
2402 handle_ert(os, name + "{-" + unit + '}', context);
2404 handle_ert(os, name + '{' + valstring + unit + '}', context);
2406 handle_ert(os, name + '{' + length + '}', context);
2411 //cerr << "#: " << t << " mode: " << mode << endl;
2412 // heuristic: read up to next non-nested space
2414 string s = t.asInput();
2415 string z = p.verbatim_item();
2416 while (p.good() && z != " " && z.size()) {
2417 //cerr << "read: " << z << endl;
2419 z = p.verbatim_item();
2421 cerr << "found ERT: " << s << endl;
2422 handle_ert(os, s + ' ', context);
2424 string name = t.asInput();
2425 if (p.next_token().asInput() == "*") {
2426 // Starred commands like \vspace*{}
2427 p.get_token(); // Eat '*'
2430 if (! parse_command(name, p, os, outer, context))
2431 handle_ert(os, name, context);
2434 if (flags & FLAG_LEAVE) {
2435 flags &= ~FLAG_LEAVE;