3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
35 using support::addExtension;
36 using support::changeExtension;
37 using support::FileName;
38 using support::makeAbsPath;
39 using support::makeRelPath;
41 using support::suffixIs;
42 using support::contains;
50 using std::ostringstream;
51 using std::istringstream;
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 = lyx::support::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<LyXLayout_ptr, bool> {
439 isLayout(string const name) : name_(name) {}
440 bool operator()(LyXLayout_ptr const & ptr) const {
441 return ptr->latexname() == name_;
448 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
451 LyXTextClass::const_iterator beg = textclass.begin();
452 LyXTextClass::const_iterator end = textclass.end();
454 LyXTextClass::const_iterator
455 it = std::find_if(beg, end, isLayout(name));
457 return (it == end) ? LyXLayout_ptr() : *it;
461 void eat_whitespace(Parser &, ostream &, Context &, bool);
464 void output_command_layout(ostream & os, Parser & p, bool outer,
465 Context & parent_context,
466 LyXLayout_ptr newlayout)
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 string height_value = "0";
595 string height_unit = "pt";
596 string height_special = "none";
598 if (p.next_token().asInput() == "[") {
599 position = p.getArg('[', ']');
600 if (position != "t" && position != "c" && position != "b") {
602 cerr << "invalid position for minipage/parbox" << endl;
604 if (p.next_token().asInput() == "[") {
605 latex_height = p.getArg('[', ']');
606 translate_box_len(latex_height, height_value, height_unit, height_special);
608 if (p.next_token().asInput() == "[") {
609 inner_pos = p.getArg('[', ']');
610 if (inner_pos != "c" && inner_pos != "t" &&
611 inner_pos != "b" && inner_pos != "s") {
612 inner_pos = position;
613 cerr << "invalid inner_pos for minipage/parbox"
621 string const latex_width = p.verbatim_item();
622 translate_len(latex_width, width_value, width_unit);
623 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
624 // LyX can't handle length variables
629 ss << "\\begin{minipage}";
630 if (!position.empty())
631 ss << '[' << position << ']';
632 if (!latex_height.empty())
633 ss << '[' << latex_height << ']';
634 if (!inner_pos.empty())
635 ss << '[' << inner_pos << ']';
636 ss << "{" << latex_width << "}";
639 handle_ert(os, ss.str(), parent_context);
640 parent_context.new_paragraph(os);
641 parse_text_in_inset(p, os, flags, outer, parent_context);
643 handle_ert(os, "}", parent_context);
645 handle_ert(os, "\\end{minipage}", parent_context);
647 // LyX does not like empty positions, so we have
648 // to set them to the LaTeX default values here.
649 if (position.empty())
651 if (inner_pos.empty())
652 inner_pos = position;
653 parent_context.check_layout(os);
654 begin_inset(os, "Box Frameless\n");
655 os << "position \"" << position << "\"\n";
656 os << "hor_pos \"c\"\n";
657 os << "has_inner_box 1\n";
658 os << "inner_pos \"" << inner_pos << "\"\n";
659 os << "use_parbox " << use_parbox << "\n";
660 os << "width \"" << width_value << width_unit << "\"\n";
661 os << "special \"none\"\n";
662 os << "height \"" << height_value << height_unit << "\"\n";
663 os << "height_special \"" << height_special << "\"\n";
664 os << "status open\n\n";
665 parse_text_in_inset(p, os, flags, outer, parent_context);
667 #ifdef PRESERVE_LAYOUT
668 // lyx puts a % after the end of the minipage
669 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
671 //handle_comment(os, "%dummy", parent_context);
674 parent_context.new_paragraph(os);
676 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
677 //handle_comment(os, "%dummy", parent_context);
680 // We add a protected space if something real follows
681 if (p.good() && p.next_token().cat() != catComment) {
682 os << "\\InsetSpace ~\n";
690 /// parse an unknown environment
691 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
692 unsigned flags, bool outer,
693 Context & parent_context)
695 if (name == "tabbing")
696 // We need to remember that we have to handle '\=' specially
697 flags |= FLAG_TABBING;
699 // We need to translate font changes and paragraphs inside the
700 // environment to ERT if we have a non standard font.
701 // Otherwise things like
702 // \large\begin{foo}\huge bar\end{foo}
704 bool const specialfont =
705 (parent_context.font != parent_context.normalfont);
706 bool const new_layout_allowed = parent_context.new_layout_allowed;
708 parent_context.new_layout_allowed = false;
709 handle_ert(os, "\\begin{" + name + "}", parent_context);
710 parse_text_snippet(p, os, flags, outer, parent_context);
711 handle_ert(os, "\\end{" + name + "}", parent_context);
713 parent_context.new_layout_allowed = new_layout_allowed;
717 void parse_environment(Parser & p, ostream & os, bool outer,
718 Context & parent_context)
720 LyXLayout_ptr newlayout;
721 string const name = p.getArg('{', '}');
722 const bool is_starred = suffixIs(name, '*');
723 string const unstarred_name = rtrim(name, "*");
724 active_environments.push_back(name);
726 if (is_math_env(name)) {
727 parent_context.check_layout(os);
728 begin_inset(os, "Formula ");
729 os << "\\begin{" << name << "}";
730 parse_math(p, os, FLAG_END, MATH_MODE);
731 os << "\\end{" << name << "}";
735 else if (name == "tabular" || name == "longtable") {
736 eat_whitespace(p, os, parent_context, false);
737 parent_context.check_layout(os);
738 begin_inset(os, "Tabular ");
739 handle_tabular(p, os, name == "longtable", parent_context);
744 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
745 eat_whitespace(p, os, parent_context, false);
746 parent_context.check_layout(os);
747 begin_inset(os, "Float " + unstarred_name + "\n");
748 if (p.next_token().asInput() == "[") {
749 os << "placement " << p.getArg('[', ']') << '\n';
751 os << "wide " << convert<string>(is_starred)
752 << "\nsideways false"
753 << "\nstatus open\n\n";
754 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
756 // We don't need really a new paragraph, but
757 // we must make sure that the next item gets a \begin_layout.
758 parent_context.new_paragraph(os);
762 else if (name == "minipage") {
763 eat_whitespace(p, os, parent_context, false);
764 parse_box(p, os, FLAG_END, outer, parent_context, false);
768 else if (name == "comment") {
769 eat_whitespace(p, os, parent_context, false);
770 parent_context.check_layout(os);
771 begin_inset(os, "Note Comment\n");
772 os << "status open\n";
773 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
778 else if (name == "lyxgreyedout") {
779 eat_whitespace(p, os, parent_context, false);
780 parent_context.check_layout(os);
781 begin_inset(os, "Note Greyedout\n");
782 os << "status open\n";
783 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
788 else if (!parent_context.new_layout_allowed)
789 parse_unknown_environment(p, name, os, FLAG_END, outer,
792 // Alignment settings
793 else if (name == "center" || name == "flushleft" || name == "flushright" ||
794 name == "centering" || name == "raggedright" || name == "raggedleft") {
795 eat_whitespace(p, os, parent_context, false);
796 // We must begin a new paragraph if not already done
797 if (! parent_context.atParagraphStart()) {
798 parent_context.check_end_layout(os);
799 parent_context.new_paragraph(os);
801 if (name == "flushleft" || name == "raggedright")
802 parent_context.add_extra_stuff("\\align left\n");
803 else if (name == "flushright" || name == "raggedleft")
804 parent_context.add_extra_stuff("\\align right\n");
806 parent_context.add_extra_stuff("\\align center\n");
807 parse_text(p, os, FLAG_END, outer, parent_context);
808 // Just in case the environment is empty ..
809 parent_context.extra_stuff.erase();
810 // We must begin a new paragraph to reset the alignment
811 parent_context.new_paragraph(os);
815 // The single '=' is meant here.
816 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
817 newlayout->isEnvironment()) {
818 eat_whitespace(p, os, parent_context, false);
819 Context context(true, parent_context.textclass, newlayout,
820 parent_context.layout, parent_context.font);
821 if (parent_context.deeper_paragraph) {
822 // We are beginning a nested environment after a
823 // deeper paragraph inside the outer list environment.
824 // Therefore we don't need to output a "begin deeper".
825 context.need_end_deeper = true;
827 parent_context.check_end_layout(os);
828 switch (context.layout->latextype) {
829 case LATEX_LIST_ENVIRONMENT:
830 context.extra_stuff = "\\labelwidthstring "
831 + p.verbatim_item() + '\n';
834 case LATEX_BIB_ENVIRONMENT:
835 p.verbatim_item(); // swallow next arg
841 context.check_deeper(os);
842 parse_text(p, os, FLAG_END, outer, context);
843 context.check_end_layout(os);
844 if (parent_context.deeper_paragraph) {
845 // We must suppress the "end deeper" because we
846 // suppressed the "begin deeper" above.
847 context.need_end_deeper = false;
849 context.check_end_deeper(os);
850 parent_context.new_paragraph(os);
854 else if (name == "appendix") {
855 // This is no good latex style, but it works and is used in some documents...
856 eat_whitespace(p, os, parent_context, false);
857 parent_context.check_end_layout(os);
858 Context context(true, parent_context.textclass, parent_context.layout,
859 parent_context.layout, parent_context.font);
860 context.check_layout(os);
861 os << "\\start_of_appendix\n";
862 parse_text(p, os, FLAG_END, outer, context);
863 context.check_end_layout(os);
867 else if (known_environments.find(name) != known_environments.end()) {
868 vector<ArgumentType> arguments = known_environments[name];
869 // The last "argument" denotes wether we may translate the
870 // environment contents to LyX
871 // The default required if no argument is given makes us
872 // compatible with the reLyXre environment.
873 ArgumentType contents = arguments.empty() ?
876 if (!arguments.empty())
877 arguments.pop_back();
878 // See comment in parse_unknown_environment()
879 bool const specialfont =
880 (parent_context.font != parent_context.normalfont);
881 bool const new_layout_allowed =
882 parent_context.new_layout_allowed;
884 parent_context.new_layout_allowed = false;
885 parse_arguments("\\begin{" + name + "}", arguments, p, os,
886 outer, parent_context);
887 if (contents == verbatim)
888 handle_ert(os, p.verbatimEnvironment(name),
891 parse_text_snippet(p, os, FLAG_END, outer,
893 handle_ert(os, "\\end{" + name + "}", parent_context);
895 parent_context.new_layout_allowed = new_layout_allowed;
899 parse_unknown_environment(p, name, os, FLAG_END, outer,
902 active_environments.pop_back();
906 /// parses a comment and outputs it to \p os.
907 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
909 BOOST_ASSERT(t.cat() == catComment);
910 if (!t.cs().empty()) {
911 context.check_layout(os);
912 handle_comment(os, '%' + t.cs(), context);
913 if (p.next_token().cat() == catNewline) {
914 // A newline after a comment line starts a new
916 if (context.new_layout_allowed) {
917 if(!context.atParagraphStart())
918 // Only start a new paragraph if not already
919 // done (we might get called recursively)
920 context.new_paragraph(os);
922 handle_ert(os, "\n", context);
923 eat_whitespace(p, os, context, true);
933 * Reads spaces and comments until the first non-space, non-comment token.
934 * New paragraphs (double newlines or \\par) are handled like simple spaces
935 * if \p eatParagraph is true.
936 * Spaces are skipped, but comments are written to \p os.
938 void eat_whitespace(Parser & p, ostream & os, Context & context,
942 Token const & t = p.get_token();
943 if (t.cat() == catComment)
944 parse_comment(p, os, t, context);
945 else if ((! eatParagraph && p.isParagraph()) ||
946 (t.cat() != catSpace && t.cat() != catNewline)) {
955 * Set a font attribute, parse text and reset the font attribute.
956 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
957 * \param currentvalue Current value of the attribute. Is set to the new
958 * value during parsing.
959 * \param newvalue New value of the attribute
961 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
962 Context & context, string const & attribute,
963 string & currentvalue, string const & newvalue)
965 context.check_layout(os);
966 string const oldvalue = currentvalue;
967 currentvalue = newvalue;
968 os << '\n' << attribute << ' ' << newvalue << "\n";
969 parse_text_snippet(p, os, flags, outer, context);
970 context.check_layout(os);
971 os << '\n' << attribute << ' ' << oldvalue << "\n";
972 currentvalue = oldvalue;
976 /// get the arguments of a natbib or jurabib citation command
977 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
979 // We need to distinguish "" and "[]", so we can't use p.getOpt().
981 // text before the citation
983 // text after the citation
984 string after = p.getFullOpt();
986 if (!after.empty()) {
987 before = p.getFullOpt();
988 if (natbibOrder && !before.empty())
989 std::swap(before, after);
991 return std::make_pair(before, after);
995 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
996 string const normalize_filename(string const & name)
998 Parser p(trim(name, "\""));
1001 Token const & t = p.get_token();
1002 if (t.cat() != catEscape)
1004 else if (t.cs() == "lyxdot") {
1005 // This is used by LyX for simple dots in relative
1009 } else if (t.cs() == "space") {
1019 /// Convert \p name from TeX convention (relative to master file) to LyX
1020 /// convention (relative to .lyx file) if it is relative
1021 void fix_relative_filename(string & name)
1023 if (lyx::support::absolutePath(name))
1025 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1027 name = makeRelPath(makeAbsPath(name, getMasterFilePath()).absFilename(),
1028 getParentFilePath());
1032 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1033 void parse_noweb(Parser & p, ostream & os, Context & context)
1035 // assemble the rest of the keyword
1039 Token const & t = p.get_token();
1040 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1043 scrap = (p.good() && p.next_token().asInput() == "=");
1045 name += p.get_token().asInput();
1048 name += t.asInput();
1051 if (!scrap || !context.new_layout_allowed ||
1052 !context.textclass.hasLayout("Scrap")) {
1053 cerr << "Warning: Could not interpret '" << name
1054 << "'. Ignoring it." << endl;
1058 // We use new_paragraph instead of check_end_layout because the stuff
1059 // following the noweb chunk needs to start with a \begin_layout.
1060 // This may create a new paragraph even if there was none in the
1061 // noweb file, but the alternative is an invalid LyX file. Since
1062 // noweb code chunks are implemented with a layout style in LyX they
1063 // always must be in an own paragraph.
1064 context.new_paragraph(os);
1065 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1066 newcontext.check_layout(os);
1069 Token const & t = p.get_token();
1070 // We abuse the parser a bit, because this is no TeX syntax
1072 if (t.cat() == catEscape)
1073 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1075 os << subst(t.asInput(), "\n", "\n\\newline\n");
1076 // The scrap chunk is ended by an @ at the beginning of a line.
1077 // After the @ the line may contain a comment and/or
1078 // whitespace, but nothing else.
1079 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1080 (p.next_token().cat() == catSpace ||
1081 p.next_token().cat() == catNewline ||
1082 p.next_token().cat() == catComment)) {
1083 while (p.good() && p.next_token().cat() == catSpace)
1084 os << p.get_token().asInput();
1085 if (p.next_token().cat() == catComment)
1086 // The comment includes a final '\n'
1087 os << p.get_token().asInput();
1089 if (p.next_token().cat() == catNewline)
1096 newcontext.check_end_layout(os);
1099 } // anonymous namespace
1102 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1105 LyXLayout_ptr newlayout;
1106 // Store the latest bibliographystyle (needed for bibtex inset)
1107 string bibliographystyle;
1108 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1109 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1111 Token const & t = p.get_token();
1114 cerr << "t: " << t << " flags: " << flags << "\n";
1117 if (flags & FLAG_ITEM) {
1118 if (t.cat() == catSpace)
1121 flags &= ~FLAG_ITEM;
1122 if (t.cat() == catBegin) {
1123 // skip the brace and collect everything to the next matching
1125 flags |= FLAG_BRACE_LAST;
1129 // handle only this single token, leave the loop if done
1130 flags |= FLAG_LEAVE;
1133 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1139 if (t.cat() == catMath) {
1140 // we are inside some text mode thingy, so opening new math is allowed
1141 context.check_layout(os);
1142 begin_inset(os, "Formula ");
1143 Token const & n = p.get_token();
1144 if (n.cat() == catMath && outer) {
1145 // TeX's $$...$$ syntax for displayed math
1147 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1149 p.get_token(); // skip the second '$' token
1151 // simple $...$ stuff
1154 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1160 else if (t.cat() == catSuper || t.cat() == catSub)
1161 cerr << "catcode " << t << " illegal in text mode\n";
1163 // Basic support for english quotes. This should be
1164 // extended to other quotes, but is not so easy (a
1165 // left english quote is the same as a right german
1167 else if (t.asInput() == "`"
1168 && p.next_token().asInput() == "`") {
1169 context.check_layout(os);
1170 begin_inset(os, "Quotes ");
1176 else if (t.asInput() == "'"
1177 && p.next_token().asInput() == "'") {
1178 context.check_layout(os);
1179 begin_inset(os, "Quotes ");
1186 else if (t.asInput() == "<"
1187 && p.next_token().asInput() == "<" && noweb_mode) {
1189 parse_noweb(p, os, context);
1192 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1193 check_space(p, os, context);
1195 else if (t.character() == '[' && noweb_mode &&
1196 p.next_token().character() == '[') {
1197 // These can contain underscores
1199 string const s = p.getFullOpt() + ']';
1200 if (p.next_token().character() == ']')
1203 cerr << "Warning: Inserting missing ']' in '"
1204 << s << "'." << endl;
1205 handle_ert(os, s, context);
1208 else if (t.cat() == catLetter ||
1209 t.cat() == catOther ||
1210 t.cat() == catAlign ||
1211 t.cat() == catParameter) {
1212 // This translates "&" to "\\&" which may be wrong...
1213 context.check_layout(os);
1214 os << t.character();
1217 else if (p.isParagraph()) {
1218 if (context.new_layout_allowed)
1219 context.new_paragraph(os);
1221 handle_ert(os, "\\par ", context);
1222 eat_whitespace(p, os, context, true);
1225 else if (t.cat() == catActive) {
1226 context.check_layout(os);
1227 if (t.character() == '~') {
1228 if (context.layout->free_spacing)
1231 os << "\\InsetSpace ~\n";
1233 os << t.character();
1236 else if (t.cat() == catBegin &&
1237 p.next_token().cat() == catEnd) {
1239 Token const prev = p.prev_token();
1241 if (p.next_token().character() == '`' ||
1242 (prev.character() == '-' &&
1243 p.next_token().character() == '-'))
1244 ; // ignore it in {}`` or -{}-
1246 handle_ert(os, "{}", context);
1250 else if (t.cat() == catBegin) {
1251 context.check_layout(os);
1252 // special handling of font attribute changes
1253 Token const prev = p.prev_token();
1254 Token const next = p.next_token();
1255 Font const oldFont = context.font;
1256 if (next.character() == '[' ||
1257 next.character() == ']' ||
1258 next.character() == '*') {
1260 if (p.next_token().cat() == catEnd) {
1261 os << next.character();
1265 handle_ert(os, "{", context);
1266 parse_text_snippet(p, os,
1269 handle_ert(os, "}", context);
1271 } else if (! context.new_layout_allowed) {
1272 handle_ert(os, "{", context);
1273 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1275 handle_ert(os, "}", context);
1276 } else if (is_known(next.cs(), known_sizes)) {
1277 // next will change the size, so we must
1279 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1281 if (!context.atParagraphStart())
1283 << context.font.size << "\n";
1284 } else if (is_known(next.cs(), known_font_families)) {
1285 // next will change the font family, so we
1286 // must reset it here
1287 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1289 if (!context.atParagraphStart())
1291 << context.font.family << "\n";
1292 } else if (is_known(next.cs(), known_font_series)) {
1293 // next will change the font series, so we
1294 // must reset it here
1295 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1297 if (!context.atParagraphStart())
1299 << context.font.series << "\n";
1300 } else if (is_known(next.cs(), known_font_shapes)) {
1301 // next will change the font shape, so we
1302 // must reset it here
1303 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1305 if (!context.atParagraphStart())
1307 << context.font.shape << "\n";
1308 } else if (is_known(next.cs(), known_old_font_families) ||
1309 is_known(next.cs(), known_old_font_series) ||
1310 is_known(next.cs(), known_old_font_shapes)) {
1311 // next will change the font family, series
1312 // and shape, so we must reset it here
1313 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1315 if (!context.atParagraphStart())
1317 << context.font.family
1319 << context.font.series
1321 << context.font.shape << "\n";
1323 handle_ert(os, "{", context);
1324 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1326 handle_ert(os, "}", context);
1330 else if (t.cat() == catEnd) {
1331 if (flags & FLAG_BRACE_LAST) {
1334 cerr << "stray '}' in text\n";
1335 handle_ert(os, "}", context);
1338 else if (t.cat() == catComment)
1339 parse_comment(p, os, t, context);
1342 // control sequences
1345 else if (t.cs() == "(") {
1346 context.check_layout(os);
1347 begin_inset(os, "Formula");
1349 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1354 else if (t.cs() == "[") {
1355 context.check_layout(os);
1356 begin_inset(os, "Formula");
1358 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1363 else if (t.cs() == "begin")
1364 parse_environment(p, os, outer, context);
1366 else if (t.cs() == "end") {
1367 if (flags & FLAG_END) {
1368 // eat environment name
1369 string const name = p.getArg('{', '}');
1370 if (name != active_environment())
1371 cerr << "\\end{" + name + "} does not match \\begin{"
1372 + active_environment() + "}\n";
1375 p.error("found 'end' unexpectedly");
1378 else if (t.cs() == "item") {
1381 bool optarg = false;
1382 if (p.next_token().character() == '[') {
1383 p.get_token(); // eat '['
1384 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1389 context.check_layout(os);
1390 if (context.has_item) {
1391 // An item in an unknown list-like environment
1392 // FIXME: Do this in check_layout()!
1393 context.has_item = false;
1395 handle_ert(os, "\\item", context);
1397 handle_ert(os, "\\item ", context);
1400 if (context.layout->labeltype != LABEL_MANUAL) {
1401 // lyx does not support \item[\mybullet]
1402 // in itemize environments
1403 handle_ert(os, "[", context);
1405 handle_ert(os, "]", context);
1406 } else if (!s.empty()) {
1407 // The space is needed to separate the
1408 // item from the rest of the sentence.
1410 eat_whitespace(p, os, context, false);
1415 else if (t.cs() == "bibitem") {
1417 context.check_layout(os);
1420 os << '{' << p.verbatim_item() << '}' << "\n";
1423 else if (t.cs() == "def") {
1424 context.check_layout(os);
1425 eat_whitespace(p, os, context, false);
1426 string name = p.get_token().cs();
1427 while (p.next_token().cat() != catBegin)
1428 name += p.get_token().asString();
1429 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1432 else if (t.cs() == "noindent") {
1434 context.add_extra_stuff("\\noindent\n");
1437 else if (t.cs() == "appendix") {
1438 context.add_extra_stuff("\\start_of_appendix\n");
1439 // We need to start a new paragraph. Otherwise the
1440 // appendix in 'bla\appendix\chapter{' would start
1442 context.new_paragraph(os);
1443 // We need to make sure that the paragraph is
1444 // generated even if it is empty. Otherwise the
1445 // appendix in '\par\appendix\par\chapter{' would
1447 context.check_layout(os);
1448 // FIXME: This is a hack to prevent paragraph
1449 // deletion if it is empty. Handle this better!
1451 "%dummy comment inserted by tex2lyx to "
1452 "ensure that this paragraph is not empty",
1454 // Both measures above may generate an additional
1455 // empty paragraph, but that does not hurt, because
1456 // whitespace does not matter here.
1457 eat_whitespace(p, os, context, true);
1460 // Must attempt to parse "Section*" before "Section".
1461 else if ((p.next_token().asInput() == "*") &&
1462 context.new_layout_allowed &&
1463 // The single '=' is meant here.
1464 (newlayout = findLayout(context.textclass,
1465 t.cs() + '*')).get() &&
1466 newlayout->isCommand()) {
1468 output_command_layout(os, p, outer, context, newlayout);
1472 // The single '=' is meant here.
1473 else if (context.new_layout_allowed &&
1474 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1475 newlayout->isCommand()) {
1476 output_command_layout(os, p, outer, context, newlayout);
1480 else if (t.cs() == "includegraphics") {
1481 bool const clip = p.next_token().asInput() == "*";
1484 map<string, string> opts = split_map(p.getArg('[', ']'));
1486 opts["clip"] = string();
1487 string name = normalize_filename(p.verbatim_item());
1489 string const path = getMasterFilePath();
1490 // We want to preserve relative / absolute filenames,
1491 // therefore path is only used for testing
1492 // FIXME UNICODE encoding of name and path may be
1493 // wrong (makeAbsPath expects utf8)
1494 if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1495 // The file extension is probably missing.
1496 // Now try to find it out.
1497 string const dvips_name =
1498 find_file(name, path,
1499 known_dvips_graphics_formats);
1500 string const pdftex_name =
1501 find_file(name, path,
1502 known_pdftex_graphics_formats);
1503 if (!dvips_name.empty()) {
1504 if (!pdftex_name.empty()) {
1505 cerr << "This file contains the "
1507 "\"\\includegraphics{"
1509 "However, files\n\""
1510 << dvips_name << "\" and\n\""
1511 << pdftex_name << "\"\n"
1512 "both exist, so I had to make a "
1513 "choice and took the first one.\n"
1514 "Please move the unwanted one "
1515 "someplace else and try again\n"
1516 "if my choice was wrong."
1520 } else if (!pdftex_name.empty())
1524 // FIXME UNICODE encoding of name and path may be
1525 // wrong (makeAbsPath expects utf8)
1526 if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1527 fix_relative_filename(name);
1529 cerr << "Warning: Could not find graphics file '"
1530 << name << "'." << endl;
1532 context.check_layout(os);
1533 begin_inset(os, "Graphics ");
1534 os << "\n\tfilename " << name << '\n';
1535 if (opts.find("width") != opts.end())
1537 << translate_len(opts["width"]) << '\n';
1538 if (opts.find("height") != opts.end())
1540 << translate_len(opts["height"]) << '\n';
1541 if (opts.find("scale") != opts.end()) {
1542 istringstream iss(opts["scale"]);
1546 os << "\tscale " << val << '\n';
1548 if (opts.find("angle") != opts.end())
1549 os << "\trotateAngle "
1550 << opts["angle"] << '\n';
1551 if (opts.find("origin") != opts.end()) {
1553 string const opt = opts["origin"];
1554 if (opt.find('l') != string::npos) ss << "left";
1555 if (opt.find('r') != string::npos) ss << "right";
1556 if (opt.find('c') != string::npos) ss << "center";
1557 if (opt.find('t') != string::npos) ss << "Top";
1558 if (opt.find('b') != string::npos) ss << "Bottom";
1559 if (opt.find('B') != string::npos) ss << "Baseline";
1560 if (!ss.str().empty())
1561 os << "\trotateOrigin " << ss.str() << '\n';
1563 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1565 if (opts.find("keepaspectratio") != opts.end())
1566 os << "\tkeepAspectRatio\n";
1567 if (opts.find("clip") != opts.end())
1569 if (opts.find("draft") != opts.end())
1571 if (opts.find("bb") != opts.end())
1572 os << "\tBoundingBox "
1573 << opts["bb"] << '\n';
1574 int numberOfbbOptions = 0;
1575 if (opts.find("bbllx") != opts.end())
1576 numberOfbbOptions++;
1577 if (opts.find("bblly") != opts.end())
1578 numberOfbbOptions++;
1579 if (opts.find("bburx") != opts.end())
1580 numberOfbbOptions++;
1581 if (opts.find("bbury") != opts.end())
1582 numberOfbbOptions++;
1583 if (numberOfbbOptions == 4)
1584 os << "\tBoundingBox "
1585 << opts["bbllx"] << opts["bblly"]
1586 << opts["bburx"] << opts["bbury"] << '\n';
1587 else if (numberOfbbOptions > 0)
1588 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1589 numberOfbbOptions = 0;
1590 if (opts.find("natwidth") != opts.end())
1591 numberOfbbOptions++;
1592 if (opts.find("natheight") != opts.end())
1593 numberOfbbOptions++;
1594 if (numberOfbbOptions == 2)
1595 os << "\tBoundingBox 0bp 0bp "
1596 << opts["natwidth"] << opts["natheight"] << '\n';
1597 else if (numberOfbbOptions > 0)
1598 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1599 ostringstream special;
1600 if (opts.find("hiresbb") != opts.end())
1601 special << "hiresbb,";
1602 if (opts.find("trim") != opts.end())
1604 if (opts.find("viewport") != opts.end())
1605 special << "viewport=" << opts["viewport"] << ',';
1606 if (opts.find("totalheight") != opts.end())
1607 special << "totalheight=" << opts["totalheight"] << ',';
1608 if (opts.find("type") != opts.end())
1609 special << "type=" << opts["type"] << ',';
1610 if (opts.find("ext") != opts.end())
1611 special << "ext=" << opts["ext"] << ',';
1612 if (opts.find("read") != opts.end())
1613 special << "read=" << opts["read"] << ',';
1614 if (opts.find("command") != opts.end())
1615 special << "command=" << opts["command"] << ',';
1616 string s_special = special.str();
1617 if (!s_special.empty()) {
1618 // We had special arguments. Remove the trailing ','.
1619 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1621 // TODO: Handle the unknown settings better.
1622 // Warn about invalid options.
1623 // Check whether some option was given twice.
1627 else if (t.cs() == "footnote" ||
1628 (t.cs() == "thanks" && context.layout->intitle)) {
1630 context.check_layout(os);
1631 begin_inset(os, "Foot\n");
1632 os << "status collapsed\n\n";
1633 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1637 else if (t.cs() == "marginpar") {
1639 context.check_layout(os);
1640 begin_inset(os, "Marginal\n");
1641 os << "status collapsed\n\n";
1642 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1646 else if (t.cs() == "ensuremath") {
1648 context.check_layout(os);
1649 string const s = p.verbatim_item();
1650 if (s == "±" || s == "³" || s == "²" || s == "µ")
1653 handle_ert(os, "\\ensuremath{" + s + "}",
1657 else if (t.cs() == "hfill") {
1658 context.check_layout(os);
1659 os << "\n\\hfill\n";
1664 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1665 // FIXME: Somehow prevent title layouts if
1666 // "maketitle" was not found
1668 skip_braces(p); // swallow this
1671 else if (t.cs() == "tableofcontents") {
1673 context.check_layout(os);
1674 begin_inset(os, "LatexCommand \\tableofcontents\n");
1676 skip_braces(p); // swallow this
1679 else if (t.cs() == "listoffigures") {
1681 context.check_layout(os);
1682 begin_inset(os, "FloatList figure\n");
1684 skip_braces(p); // swallow this
1687 else if (t.cs() == "listoftables") {
1689 context.check_layout(os);
1690 begin_inset(os, "FloatList table\n");
1692 skip_braces(p); // swallow this
1695 else if (t.cs() == "listof") {
1696 p.skip_spaces(true);
1697 string const name = p.get_token().asString();
1698 if (context.textclass.floats().typeExist(name)) {
1699 context.check_layout(os);
1700 begin_inset(os, "FloatList ");
1703 p.get_token(); // swallow second arg
1705 handle_ert(os, "\\listof{" + name + "}", context);
1708 else if (t.cs() == "textrm")
1709 parse_text_attributes(p, os, FLAG_ITEM, outer,
1710 context, "\\family",
1711 context.font.family, "roman");
1713 else if (t.cs() == "textsf")
1714 parse_text_attributes(p, os, FLAG_ITEM, outer,
1715 context, "\\family",
1716 context.font.family, "sans");
1718 else if (t.cs() == "texttt")
1719 parse_text_attributes(p, os, FLAG_ITEM, outer,
1720 context, "\\family",
1721 context.font.family, "typewriter");
1723 else if (t.cs() == "textmd")
1724 parse_text_attributes(p, os, FLAG_ITEM, outer,
1725 context, "\\series",
1726 context.font.series, "medium");
1728 else if (t.cs() == "textbf")
1729 parse_text_attributes(p, os, FLAG_ITEM, outer,
1730 context, "\\series",
1731 context.font.series, "bold");
1733 else if (t.cs() == "textup")
1734 parse_text_attributes(p, os, FLAG_ITEM, outer,
1736 context.font.shape, "up");
1738 else if (t.cs() == "textit")
1739 parse_text_attributes(p, os, FLAG_ITEM, outer,
1741 context.font.shape, "italic");
1743 else if (t.cs() == "textsl")
1744 parse_text_attributes(p, os, FLAG_ITEM, outer,
1746 context.font.shape, "slanted");
1748 else if (t.cs() == "textsc")
1749 parse_text_attributes(p, os, FLAG_ITEM, outer,
1751 context.font.shape, "smallcaps");
1753 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1754 context.check_layout(os);
1755 Font oldFont = context.font;
1756 context.font.init();
1757 context.font.size = oldFont.size;
1758 os << "\n\\family " << context.font.family << "\n";
1759 os << "\n\\series " << context.font.series << "\n";
1760 os << "\n\\shape " << context.font.shape << "\n";
1761 if (t.cs() == "textnormal") {
1762 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1763 output_font_change(os, context.font, oldFont);
1764 context.font = oldFont;
1766 eat_whitespace(p, os, context, false);
1769 else if (t.cs() == "underbar") {
1770 // Do NOT handle \underline.
1771 // \underbar cuts through y, g, q, p etc.,
1772 // \underline does not.
1773 context.check_layout(os);
1774 os << "\n\\bar under\n";
1775 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1776 context.check_layout(os);
1777 os << "\n\\bar default\n";
1780 else if (t.cs() == "emph" || t.cs() == "noun") {
1781 context.check_layout(os);
1782 os << "\n\\" << t.cs() << " on\n";
1783 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1784 context.check_layout(os);
1785 os << "\n\\" << t.cs() << " default\n";
1788 else if (use_natbib &&
1789 is_known(t.cs(), known_natbib_commands) &&
1790 ((t.cs() != "citefullauthor" &&
1791 t.cs() != "citeyear" &&
1792 t.cs() != "citeyearpar") ||
1793 p.next_token().asInput() != "*")) {
1794 context.check_layout(os);
1796 // \citet[before][after]{a} \citet[after][before]{a}
1797 // \citet[before][]{a} \citet[][before]{a}
1798 // \citet[after]{a} \citet[after]{a}
1799 // \citet{a} \citet{a}
1800 string command = '\\' + t.cs();
1801 if (p.next_token().asInput() == "*") {
1805 if (command == "\\citefullauthor")
1806 // alternative name for "\\citeauthor*"
1807 command = "\\citeauthor*";
1809 // text before the citation
1811 // text after the citation
1814 boost::tie(before, after) = getCiteArguments(p, true);
1815 if (command == "\\cite") {
1816 // \cite without optional argument means
1817 // \citet, \cite with at least one optional
1818 // argument means \citep.
1819 if (before.empty() && after.empty())
1820 command = "\\citet";
1822 command = "\\citep";
1824 if (before.empty() && after == "[]")
1825 // avoid \citet[]{a}
1827 else if (before == "[]" && after == "[]") {
1828 // avoid \citet[][]{a}
1832 begin_inset(os, "LatexCommand ");
1833 os << command << after << before
1834 << '{' << p.verbatim_item() << "}\n";
1838 else if (use_jurabib &&
1839 is_known(t.cs(), known_jurabib_commands)) {
1840 context.check_layout(os);
1841 string const command = '\\' + t.cs();
1842 char argumentOrder = '\0';
1843 vector<string> const & options = used_packages["jurabib"];
1844 if (std::find(options.begin(), options.end(),
1845 "natbiborder") != options.end())
1846 argumentOrder = 'n';
1847 else if (std::find(options.begin(), options.end(),
1848 "jurabiborder") != options.end())
1849 argumentOrder = 'j';
1851 // text before the citation
1853 // text after the citation
1856 boost::tie(before, after) =
1857 getCiteArguments(p, argumentOrder != 'j');
1858 string const citation = p.verbatim_item();
1859 if (!before.empty() && argumentOrder == '\0') {
1860 cerr << "Warning: Assuming argument order "
1861 "of jurabib version 0.6 for\n'"
1862 << command << before << after << '{'
1863 << citation << "}'.\n"
1864 "Add 'jurabiborder' to the jurabib "
1865 "package options if you used an\n"
1866 "earlier jurabib version." << endl;
1868 begin_inset(os, "LatexCommand ");
1869 os << command << after << before
1870 << '{' << citation << "}\n";
1874 else if (is_known(t.cs(), known_latex_commands)) {
1875 // This needs to be after the check for natbib and
1876 // jurabib commands, because "cite" has different
1877 // arguments with natbib and jurabib.
1878 context.check_layout(os);
1879 begin_inset(os, "LatexCommand ");
1880 os << '\\' << t.cs();
1881 // lyx cannot handle newlines in a latex command
1882 // FIXME: Move the substitution into parser::getOpt()?
1883 os << subst(p.getOpt(), "\n", " ");
1884 os << subst(p.getOpt(), "\n", " ");
1885 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1889 else if (is_known(t.cs(), known_quotes)) {
1890 char const * const * where = is_known(t.cs(), known_quotes);
1891 context.check_layout(os);
1892 begin_inset(os, "Quotes ");
1893 os << known_coded_quotes[where - known_quotes];
1895 // LyX adds {} after the quote, so we have to eat
1896 // spaces here if there are any before a possible
1898 eat_whitespace(p, os, context, false);
1902 else if (is_known(t.cs(), known_sizes) &&
1903 context.new_layout_allowed) {
1904 char const * const * where = is_known(t.cs(), known_sizes);
1905 context.check_layout(os);
1906 Font const oldFont = context.font;
1907 context.font.size = known_coded_sizes[where - known_sizes];
1908 output_font_change(os, oldFont, context.font);
1909 eat_whitespace(p, os, context, false);
1912 else if (is_known(t.cs(), known_font_families) &&
1913 context.new_layout_allowed) {
1914 char const * const * where =
1915 is_known(t.cs(), known_font_families);
1916 context.check_layout(os);
1917 Font const oldFont = context.font;
1918 context.font.family =
1919 known_coded_font_families[where - known_font_families];
1920 output_font_change(os, oldFont, context.font);
1921 eat_whitespace(p, os, context, false);
1924 else if (is_known(t.cs(), known_font_series) &&
1925 context.new_layout_allowed) {
1926 char const * const * where =
1927 is_known(t.cs(), known_font_series);
1928 context.check_layout(os);
1929 Font const oldFont = context.font;
1930 context.font.series =
1931 known_coded_font_series[where - known_font_series];
1932 output_font_change(os, oldFont, context.font);
1933 eat_whitespace(p, os, context, false);
1936 else if (is_known(t.cs(), known_font_shapes) &&
1937 context.new_layout_allowed) {
1938 char const * const * where =
1939 is_known(t.cs(), known_font_shapes);
1940 context.check_layout(os);
1941 Font const oldFont = context.font;
1942 context.font.shape =
1943 known_coded_font_shapes[where - known_font_shapes];
1944 output_font_change(os, oldFont, context.font);
1945 eat_whitespace(p, os, context, false);
1947 else if (is_known(t.cs(), known_old_font_families) &&
1948 context.new_layout_allowed) {
1949 char const * const * where =
1950 is_known(t.cs(), known_old_font_families);
1951 context.check_layout(os);
1952 Font const oldFont = context.font;
1953 context.font.init();
1954 context.font.size = oldFont.size;
1955 context.font.family =
1956 known_coded_font_families[where - known_old_font_families];
1957 output_font_change(os, oldFont, context.font);
1958 eat_whitespace(p, os, context, false);
1961 else if (is_known(t.cs(), known_old_font_series) &&
1962 context.new_layout_allowed) {
1963 char const * const * where =
1964 is_known(t.cs(), known_old_font_series);
1965 context.check_layout(os);
1966 Font const oldFont = context.font;
1967 context.font.init();
1968 context.font.size = oldFont.size;
1969 context.font.series =
1970 known_coded_font_series[where - known_old_font_series];
1971 output_font_change(os, oldFont, context.font);
1972 eat_whitespace(p, os, context, false);
1975 else if (is_known(t.cs(), known_old_font_shapes) &&
1976 context.new_layout_allowed) {
1977 char const * const * where =
1978 is_known(t.cs(), known_old_font_shapes);
1979 context.check_layout(os);
1980 Font const oldFont = context.font;
1981 context.font.init();
1982 context.font.size = oldFont.size;
1983 context.font.shape =
1984 known_coded_font_shapes[where - known_old_font_shapes];
1985 output_font_change(os, oldFont, context.font);
1986 eat_whitespace(p, os, context, false);
1989 else if (t.cs() == "LyX" || t.cs() == "TeX"
1990 || t.cs() == "LaTeX") {
1991 context.check_layout(os);
1993 skip_braces(p); // eat {}
1996 else if (t.cs() == "LaTeXe") {
1997 context.check_layout(os);
1999 skip_braces(p); // eat {}
2002 else if (t.cs() == "ldots") {
2003 context.check_layout(os);
2005 os << "\\SpecialChar \\ldots{}\n";
2008 else if (t.cs() == "lyxarrow") {
2009 context.check_layout(os);
2010 os << "\\SpecialChar \\menuseparator\n";
2014 else if (t.cs() == "textcompwordmark") {
2015 context.check_layout(os);
2016 os << "\\SpecialChar \\textcompwordmark{}\n";
2020 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2021 context.check_layout(os);
2022 os << "\\SpecialChar \\@.\n";
2026 else if (t.cs() == "-") {
2027 context.check_layout(os);
2028 os << "\\SpecialChar \\-\n";
2031 else if (t.cs() == "textasciitilde") {
2032 context.check_layout(os);
2037 else if (t.cs() == "textasciicircum") {
2038 context.check_layout(os);
2043 else if (t.cs() == "textbackslash") {
2044 context.check_layout(os);
2045 os << "\n\\backslash\n";
2049 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2050 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2052 context.check_layout(os);
2056 else if (t.cs() == "char") {
2057 context.check_layout(os);
2058 if (p.next_token().character() == '`') {
2060 if (p.next_token().cs() == "\"") {
2065 handle_ert(os, "\\char`", context);
2068 handle_ert(os, "\\char", context);
2072 else if (t.cs() == "verb") {
2073 context.check_layout(os);
2074 char const delimiter = p.next_token().character();
2075 string const arg = p.getArg(delimiter, delimiter);
2077 oss << "\\verb" << delimiter << arg << delimiter;
2078 handle_ert(os, oss.str(), context);
2081 else if (t.cs() == "\"") {
2082 context.check_layout(os);
2083 string const name = p.verbatim_item();
2084 if (name == "a") os << 'ä';
2085 else if (name == "o") os << 'ö';
2086 else if (name == "u") os << 'ü';
2087 else if (name == "A") os << 'Ä';
2088 else if (name == "O") os << 'Ö';
2089 else if (name == "U") os << 'Ü';
2090 else handle_ert(os, "\"{" + name + "}", context);
2093 // Problem: \= creates a tabstop inside the tabbing environment
2094 // and else an accent. In the latter case we really would want
2095 // \={o} instead of \= o.
2096 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2097 handle_ert(os, t.asInput(), context);
2099 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2100 || t.cs() == "'" || t.cs() == "`"
2101 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2102 // we need the trim as the LyX parser chokes on such spaces
2103 // The argument of InsetLatexAccent is parsed as a
2104 // subset of LaTeX, so don't parse anything here,
2105 // but use the raw argument.
2106 // Otherwise we would convert \~{\i} wrongly.
2107 // This will of course not translate \~{\ss} to \~{ß},
2108 // but that does at least compile and does only look
2109 // strange on screen.
2110 context.check_layout(os);
2111 os << "\\i \\" << t.cs() << "{"
2112 << trim(p.verbatim_item(), " ")
2116 else if (t.cs() == "ss") {
2117 context.check_layout(os);
2119 skip_braces(p); // eat {}
2122 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2124 context.check_layout(os);
2125 os << "\\i \\" << t.cs() << "{}\n";
2126 skip_braces(p); // eat {}
2129 else if (t.cs() == "\\") {
2130 context.check_layout(os);
2131 string const next = p.next_token().asInput();
2133 handle_ert(os, "\\\\" + p.getOpt(), context);
2134 else if (next == "*") {
2136 handle_ert(os, "\\\\*" + p.getOpt(), context);
2139 os << "\n\\newline\n";
2143 else if (t.cs() == "input" || t.cs() == "include"
2144 || t.cs() == "verbatiminput") {
2145 string name = '\\' + t.cs();
2146 if (t.cs() == "verbatiminput"
2147 && p.next_token().asInput() == "*")
2148 name += p.get_token().asInput();
2149 context.check_layout(os);
2150 begin_inset(os, "Include ");
2151 string filename(normalize_filename(p.getArg('{', '}')));
2152 string const path = getMasterFilePath();
2153 // We want to preserve relative / absolute filenames,
2154 // therefore path is only used for testing
2155 // FIXME UNICODE encoding of filename and path may be
2156 // wrong (makeAbsPath expects utf8)
2157 if (t.cs() == "include" &&
2158 !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2159 // The file extension is probably missing.
2160 // Now try to find it out.
2161 string const tex_name =
2162 find_file(filename, path,
2163 known_tex_extensions);
2164 if (!tex_name.empty())
2165 filename = tex_name;
2167 // FIXME UNICODE encoding of filename and path may be
2168 // wrong (makeAbsPath expects utf8)
2169 if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2170 string const abstexname =
2171 makeAbsPath(filename, path).absFilename();
2172 string const abslyxname =
2173 changeExtension(abstexname, ".lyx");
2174 fix_relative_filename(filename);
2175 string const lyxname =
2176 changeExtension(filename, ".lyx");
2177 if (t.cs() != "verbatiminput" &&
2178 tex2lyx(abstexname, FileName(abslyxname))) {
2179 os << name << '{' << lyxname << "}\n";
2181 os << name << '{' << filename << "}\n";
2184 cerr << "Warning: Could not find included file '"
2185 << filename << "'." << endl;
2186 os << name << '{' << filename << "}\n";
2188 os << "preview false\n";
2192 else if (t.cs() == "bibliographystyle") {
2193 // store new bibliographystyle
2194 bibliographystyle = p.verbatim_item();
2195 // output new bibliographystyle.
2196 // This is only necessary if used in some other macro than \bibliography.
2197 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2200 else if (t.cs() == "bibliography") {
2201 context.check_layout(os);
2202 begin_inset(os, "LatexCommand ");
2204 // Do we have a bibliographystyle set?
2205 if (!bibliographystyle.empty()) {
2206 os << '[' << bibliographystyle << ']';
2208 os << '{' << p.verbatim_item() << "}\n";
2212 else if (t.cs() == "parbox")
2213 parse_box(p, os, FLAG_ITEM, outer, context, true);
2215 else if (t.cs() == "smallskip" ||
2216 t.cs() == "medskip" ||
2217 t.cs() == "bigskip" ||
2218 t.cs() == "vfill") {
2219 context.check_layout(os);
2220 begin_inset(os, "VSpace ");
2226 else if (is_known(t.cs(), known_spaces)) {
2227 char const * const * where = is_known(t.cs(), known_spaces);
2228 context.check_layout(os);
2229 begin_inset(os, "InsetSpace ");
2230 os << '\\' << known_coded_spaces[where - known_spaces]
2232 // LaTeX swallows whitespace after all spaces except
2233 // "\\,". We have to do that here, too, because LyX
2234 // adds "{}" which would make the spaces significant.
2236 eat_whitespace(p, os, context, false);
2237 // LyX adds "{}" after all spaces except "\\ " and
2238 // "\\,", so we have to remove "{}".
2239 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2240 // remove the braces after "\\,", too.
2245 else if (t.cs() == "newpage" ||
2246 t.cs() == "clearpage" ||
2247 t.cs() == "cleardoublepage") {
2248 context.check_layout(os);
2249 // FIXME: what about \\pagebreak?
2250 os << "\n\\" << t.cs() << "\n";
2251 skip_braces(p); // eat {}
2254 else if (t.cs() == "newcommand" ||
2255 t.cs() == "providecommand" ||
2256 t.cs() == "renewcommand") {
2257 // these could be handled by parse_command(), but
2258 // we need to call add_known_command() here.
2259 string name = t.asInput();
2260 if (p.next_token().asInput() == "*") {
2261 // Starred form. Eat '*'
2265 string const command = p.verbatim_item();
2266 string const opt1 = p.getOpt();
2267 string const opt2 = p.getFullOpt();
2268 add_known_command(command, opt1, !opt2.empty());
2269 string const ert = name + '{' + command + '}' +
2271 '{' + p.verbatim_item() + '}';
2272 handle_ert(os, ert, context);
2275 else if (t.cs() == "vspace") {
2276 bool starred = false;
2277 if (p.next_token().asInput() == "*") {
2281 string const length = p.verbatim_item();
2284 bool valid = splitLatexLength(length, valstring, unit);
2285 bool known_vspace = false;
2286 bool known_unit = false;
2289 istringstream iss(valstring);
2292 if (unit == "\\smallskipamount") {
2294 known_vspace = true;
2295 } else if (unit == "\\medskipamount") {
2297 known_vspace = true;
2298 } else if (unit == "\\bigskipamount") {
2300 known_vspace = true;
2301 } else if (unit == "\\fill") {
2303 known_vspace = true;
2306 if (!known_vspace) {
2307 switch (unitFromString(unit)) {
2328 if (known_unit || known_vspace) {
2329 // Literal length or known variable
2330 context.check_layout(os);
2331 begin_inset(os, "VSpace ");
2339 // LyX can't handle other length variables in Inset VSpace
2340 string name = t.asInput();
2345 handle_ert(os, name + '{' + unit + '}', context);
2346 else if (value == -1.0)
2347 handle_ert(os, name + "{-" + unit + '}', context);
2349 handle_ert(os, name + '{' + valstring + unit + '}', context);
2351 handle_ert(os, name + '{' + length + '}', context);
2356 //cerr << "#: " << t << " mode: " << mode << endl;
2357 // heuristic: read up to next non-nested space
2359 string s = t.asInput();
2360 string z = p.verbatim_item();
2361 while (p.good() && z != " " && z.size()) {
2362 //cerr << "read: " << z << endl;
2364 z = p.verbatim_item();
2366 cerr << "found ERT: " << s << endl;
2367 handle_ert(os, s + ' ', context);
2369 string name = t.asInput();
2370 if (p.next_token().asInput() == "*") {
2371 // Starred commands like \vspace*{}
2372 p.get_token(); // Eat '*'
2375 if (! parse_command(name, p, os, outer, context))
2376 handle_ert(os, name, context);
2379 if (flags & FLAG_LEAVE) {
2380 flags &= ~FLAG_LEAVE;