3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
20 #include "LayoutFile.h"
21 #include "LayoutModuleList.h"
22 #include "ModuleList.h"
23 #include "TextClass.h"
25 #include "support/convert.h"
26 #include "support/debug.h"
27 #include "support/ExceptionMessage.h"
28 #include "support/filetools.h"
29 #include "support/lassert.h"
30 #include "support/lstrings.h"
31 #include "support/Messages.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Systemcall.h"
44 using namespace lyx::support;
45 using namespace lyx::support::os;
51 void warning(docstring const & title, docstring const & message,
61 // Dummy texrow support
62 void TexRow::newline()
66 void TexRow::newlines(int)
70 // Dummy LyXRC support
76 // Dummy translation support
78 Messages const & getMessages(std::string const &)
84 Messages const & getGuiMessages()
90 // Keep the linker happy on Windows
95 string const trim(string const & a, char const * p)
102 size_t r = a.find_last_not_of(p);
103 size_t l = a.find_first_not_of(p);
105 // Is this the minimal test? (lgb)
106 if (r == string::npos && l == string::npos)
109 return a.substr(l, r - l + 1);
113 void split(string const & s, vector<string> & result, char delim)
115 //cerr << "split 1: '" << s << "'\n";
118 while (getline(is, t, delim))
120 //cerr << "split 2\n";
124 string join(vector<string> const & input, char const * delim)
127 for (size_t i = 0; i != input.size(); ++i) {
136 char const * const * is_known(string const & str, char const * const * what)
138 for ( ; *what; ++what)
146 // current stack of nested environments
147 vector<string> active_environments;
150 string active_environment()
152 return active_environments.empty() ? string() : active_environments.back();
156 TeX2LyXDocClass textclass;
157 CommandMap known_commands;
158 CommandMap known_environments;
159 CommandMap known_math_environments;
160 FullCommandMap possible_textclass_commands;
161 FullEnvironmentMap possible_textclass_environments;
164 LayoutModuleList used_modules;
167 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
169 // We have to handle the following cases:
170 // definition o1 o2 invocation result
171 // \newcommand{\foo}{bar} "" false \foo bar
172 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
173 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
174 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
175 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
176 unsigned int nargs = 0;
177 string const opt1 = rtrim(ltrim(o1, "["), "]");
178 if (isStrUnsignedInt(opt1)) {
179 // The command has arguments
180 nargs = convert<unsigned int>(opt1);
181 if (nargs > 0 && o2) {
182 // The first argument is optional
183 arguments.push_back(optional);
187 for (unsigned int i = 0; i < nargs; ++i)
188 arguments.push_back(required);
192 void add_known_command(string const & command, string const & o1,
193 bool o2, docstring const & definition)
195 vector<ArgumentType> arguments;
196 convertArgs(o1, o2, arguments);
197 known_commands[command] = arguments;
198 if (!definition.empty())
199 possible_textclass_commands[command] =
200 FullCommand(arguments, definition);
204 void add_known_environment(string const & environment, string const & o1,
205 bool o2, docstring const & beg, docstring const &end)
207 vector<ArgumentType> arguments;
208 convertArgs(o1, o2, arguments);
209 known_environments[environment] = arguments;
210 if (!beg.empty() || ! end.empty())
211 possible_textclass_environments[environment] =
212 FullEnvironment(arguments, beg, end);
216 Layout const * findLayoutWithoutModule(TextClass const & textclass,
217 string const & name, bool command)
219 DocumentClass::const_iterator it = textclass.begin();
220 DocumentClass::const_iterator en = textclass.end();
221 for (; it != en; ++it) {
222 if (it->latexname() == name &&
223 ((command && it->isCommand()) || (!command && it->isEnvironment())))
230 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
231 string const & name, bool command)
233 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
234 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
235 for (; it != en; ++it) {
236 if (it->second.latexname() == name &&
237 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
238 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
239 return &(it->second);
245 bool checkModule(string const & name, bool command)
247 // Cache to avoid slowdown by repated searches
248 static set<string> failed[2];
250 // Only add the module if the command was actually defined in the LyX preamble
252 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
255 if (possible_textclass_environments.find(name) == possible_textclass_environments.end())
258 if (failed[command].find(name) != failed[command].end())
261 // Create list of dummy document classes if not already done.
262 // This is needed since a module cannot be read on its own, only as
263 // part of a document class.
264 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
265 typedef map<string, DocumentClass *> ModuleMap;
266 static ModuleMap modules;
267 static bool init = true;
270 DocumentClassBundle & bundle = DocumentClassBundle::get();
271 LyXModuleList::const_iterator const end = theModuleList.end();
272 LyXModuleList::const_iterator it = theModuleList.begin();
273 for (; it != end; it++) {
274 string const module = it->getID();
276 // FIXME this excludes all modules that depend on another one
277 if (!m.moduleCanBeAdded(module, &baseClass))
280 modules[module] = &bundle.makeDocumentClass(baseClass, m);
285 // Try to find a module that defines the command.
286 // Only add it if the definition can be found in the preamble of the
287 // style that corresponds to the command. This is a heuristic and
288 // different from the way how we parse the builtin commands of the
289 // text class (in that case we only compare the name), but it is
290 // needed since it is not unlikely that two different modules define a
291 // command with the same name.
292 ModuleMap::iterator const end = modules.end();
293 for (ModuleMap::iterator it = modules.begin(); it != end; it++) {
294 string const module = it->first;
295 if (!used_modules.moduleCanBeAdded(module, &baseClass))
297 if (findLayoutWithoutModule(textclass, name, command))
299 if (findInsetLayoutWithoutModule(textclass, name, command))
301 DocumentClass const * c = it->second;
302 Layout const * layout = findLayoutWithoutModule(*c, name, command);
303 InsetLayout const * insetlayout = layout ? 0 :
304 findInsetLayoutWithoutModule(*c, name, command);
307 preamble = layout->preamble();
308 else if (insetlayout)
309 preamble = insetlayout->preamble();
310 if (preamble.empty())
314 FullCommand const & cmd =
315 possible_textclass_commands['\\' + name];
316 if (preamble.find(cmd.def) != docstring::npos)
319 FullEnvironment const & env =
320 possible_textclass_environments[name];
321 if (preamble.find(env.beg) != docstring::npos &&
322 preamble.find(env.end) != docstring::npos)
326 FileName layout_file = libFileSearch("layouts", module, "module");
327 if (textclass.read(layout_file, TextClass::MODULE)) {
328 used_modules.push_back(module);
329 // speed up further searches:
330 // the module does not need to be checked anymore.
336 failed[command].insert(name);
341 bool noweb_mode = false;
342 bool pdflatex = false;
343 bool roundtrip = false;
350 * Read one command definition from the syntax file
352 void read_command(Parser & p, string command, CommandMap & commands)
354 if (p.next_token().asInput() == "*") {
358 vector<ArgumentType> arguments;
359 while (p.next_token().cat() == catBegin ||
360 p.next_token().asInput() == "[") {
361 if (p.next_token().cat() == catBegin) {
362 string const arg = p.getArg('{', '}');
363 if (arg == "translate")
364 arguments.push_back(required);
365 else if (arg == "item")
366 arguments.push_back(item);
368 arguments.push_back(verbatim);
371 arguments.push_back(optional);
374 commands[command] = arguments;
379 * Read a class of environments from the syntax file
381 void read_environment(Parser & p, string const & begin,
382 CommandMap & environments)
386 Token const & t = p.get_token();
387 if (t.cat() == catLetter)
388 environment += t.asInput();
389 else if (!environment.empty()) {
391 read_command(p, environment, environments);
394 if (t.cat() == catEscape && t.asInput() == "\\end") {
395 string const end = p.getArg('{', '}');
404 * Read a list of TeX commands from a reLyX compatible syntax file.
405 * Since this list is used after all commands that have a LyX counterpart
406 * are handled, it does not matter that the "syntax.default" file
407 * has almost all of them listed. For the same reason the reLyX-specific
408 * reLyXre environment is ignored.
410 void read_syntaxfile(FileName const & file_name)
412 ifdocstream is(file_name.toFilesystemEncoding().c_str());
414 cerr << "Could not open syntax file \"" << file_name
415 << "\" for reading." << endl;
418 // We can use our TeX parser, since the syntax of the layout file is
419 // modeled after TeX.
420 // Unknown tokens are just silently ignored, this helps us to skip some
421 // reLyX specific things.
424 Token const & t = p.get_token();
425 if (t.cat() == catEscape) {
426 string const command = t.asInput();
427 if (command == "\\begin") {
428 string const name = p.getArg('{', '}');
429 if (name == "environments" || name == "reLyXre")
430 // We understand "reLyXre", but it is
431 // not as powerful as "environments".
432 read_environment(p, name,
434 else if (name == "mathenvironments")
435 read_environment(p, name,
436 known_math_environments);
438 read_command(p, command, known_commands);
445 string documentclass;
446 string default_encoding;
448 bool overwrite_files = false;
451 /// return the number of arguments consumed
452 typedef int (*cmd_helper)(string const &, string const &);
455 int parse_help(string const &, string const &)
457 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
459 "\t-c textclass Declare the textclass.\n"
460 "\t-e encoding Set the default encoding (latex name).\n"
461 "\t-f Force overwrite of .lyx files.\n"
462 "\t-help Print this message and quit.\n"
463 "\t-n translate a noweb (aka literate programming) file.\n"
464 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
465 "\t-s syntaxfile read additional syntax file.\n"
466 "\t-sysdir dir Set system directory to DIR.\n"
467 "\t-userdir DIR Set user directory to DIR."
473 void error_message(string const & message)
475 cerr << "tex2lyx: " << message << "\n\n";
477 parse_help(string(), string());
481 int parse_class(string const & arg, string const &)
484 error_message("Missing textclass string after -c switch");
490 int parse_encoding(string const & arg, string const &)
493 error_message("Missing encoding string after -e switch");
494 default_encoding = arg;
499 int parse_syntaxfile(string const & arg, string const &)
502 error_message("Missing syntaxfile string after -s switch");
503 syntaxfile = internal_path(arg);
508 // Filled with the command line arguments "foo" of "-sysdir foo" or
510 string cl_system_support;
511 string cl_user_support;
514 int parse_sysdir(string const & arg, string const &)
517 error_message("Missing directory for -sysdir switch");
518 cl_system_support = internal_path(arg);
523 int parse_userdir(string const & arg, string const &)
526 error_message("Missing directory for -userdir switch");
527 cl_user_support = internal_path(arg);
532 int parse_force(string const &, string const &)
534 overwrite_files = true;
539 int parse_noweb(string const &, string const &)
546 int parse_roundtrip(string const &, string const &)
553 void easyParse(int & argc, char * argv[])
555 map<string, cmd_helper> cmdmap;
557 cmdmap["-c"] = parse_class;
558 cmdmap["-e"] = parse_encoding;
559 cmdmap["-f"] = parse_force;
560 cmdmap["-s"] = parse_syntaxfile;
561 cmdmap["-help"] = parse_help;
562 cmdmap["--help"] = parse_help;
563 cmdmap["-n"] = parse_noweb;
564 cmdmap["-sysdir"] = parse_sysdir;
565 cmdmap["-userdir"] = parse_userdir;
566 cmdmap["-roundtrip"] = parse_roundtrip;
568 for (int i = 1; i < argc; ++i) {
569 map<string, cmd_helper>::const_iterator it
570 = cmdmap.find(argv[i]);
572 // don't complain if not found - may be parsed later
573 if (it == cmdmap.end()) {
574 if (argv[i][0] == '-')
575 error_message(string("Unknown option `") + argv[i] + "'.");
580 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
581 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
583 int const remove = 1 + it->second(arg, arg2);
585 // Now, remove used arguments by shifting
586 // the following ones remove places down.
587 os::remove_internal_args(i, remove);
589 for (int j = i; j < argc; ++j)
590 argv[j] = argv[j + remove];
596 // path of the first parsed file
597 string masterFilePath;
598 // path of the currently parsed file
599 string parentFilePath;
601 } // anonymous namespace
604 string getMasterFilePath()
606 return masterFilePath;
609 string getParentFilePath()
611 return parentFilePath;
618 * Reads tex input from \a is and writes lyx output to \a os.
619 * Uses some common settings for the preamble, so this should only
620 * be used more than once for included documents.
621 * Caution: Overwrites the existing preamble settings if the new document
622 * contains a preamble.
623 * You must ensure that \p parentFilePath is properly set before calling
626 void tex2lyx(idocstream & is, ostream & os, string const & encoding)
629 if (!encoding.empty())
630 p.setEncoding(encoding);
634 parse_preamble(p, ps, documentclass, textclass);
636 active_environments.push_back("document");
637 Context context(true, textclass);
639 parse_text(p, ss, FLAG_END, true, context);
641 // Empty document body. LyX needs at least one paragraph.
642 context.check_layout(ss);
643 context.check_end_layout(ss);
644 ss << "\n\\end_body\n\\end_document\n";
645 active_environments.pop_back();
647 // We know the used modules only after parsing the full text
649 if (!used_modules.empty()) {
650 ms << "\\begin_modules\n";
651 LayoutModuleList::const_iterator const end = used_modules.end();
652 LayoutModuleList::const_iterator it = used_modules.begin();
653 for (; it != end; it++)
655 ms << "\\end_modules\n";
657 os << subst(ps.str(), modules_placeholder, ms.str());
663 ofdocstream parsertest("parsertest.tex");
665 parsertest << p.get_token().asInput();
666 // <origfile> and parsertest.tex should now have identical content
671 /// convert TeX from \p infilename to LyX and write it to \p os
672 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
675 // forbid buffering on this stream
676 is.rdbuf()->pubsetbuf(0,0);
677 is.open(infilename.toFilesystemEncoding().c_str());
679 cerr << "Could not open input file \"" << infilename
680 << "\" for reading." << endl;
683 string const oldParentFilePath = parentFilePath;
684 parentFilePath = onlyPath(infilename.absFileName());
685 tex2lyx(is, os, encoding);
686 parentFilePath = oldParentFilePath;
690 } // anonymous namespace
693 bool tex2lyx(string const & infilename, FileName const & outfilename,
694 string const & encoding)
696 if (outfilename.isReadableFile()) {
697 if (overwrite_files) {
698 cerr << "Overwriting existing file "
699 << outfilename << endl;
701 cerr << "Not overwriting existing file "
702 << outfilename << endl;
706 cerr << "Creating file " << outfilename << endl;
708 ofstream os(outfilename.toFilesystemEncoding().c_str());
710 cerr << "Could not open output file \"" << outfilename
711 << "\" for writing." << endl;
715 cerr << "Input file: " << infilename << "\n";
716 cerr << "Output file: " << outfilename << "\n";
718 return tex2lyx(FileName(infilename), os, encoding);
722 bool tex2tex(string const & infilename, FileName const & outfilename,
723 string const & encoding)
725 if (!tex2lyx(infilename, outfilename, encoding))
727 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
729 command += " -f main";
731 command += " -f none";
733 command += " -e pdflatex ";
735 command += " -e latex ";
736 command += quoteName(outfilename.toFilesystemEncoding());
738 if (one.startscript(Systemcall::Wait, command) == 0)
740 cerr << "Error: Running '" << command << "' failed." << endl;
747 int main(int argc, char * argv[])
751 //setlocale(LC_CTYPE, "");
753 lyxerr.setStream(cerr);
755 os::init(argc, argv);
757 easyParse(argc, argv);
760 error_message("Not enough arguments.");
763 init_package(internal_path(os::utf8_argv(0)),
764 cl_system_support, cl_user_support,
765 top_build_dir_is_two_levels_up);
766 } catch (ExceptionMessage const & message) {
767 cerr << to_utf8(message.title_) << ":\n"
768 << to_utf8(message.details_) << endl;
769 if (message.type_ == ErrorException)
773 // Now every known option is parsed. Look for input and output
774 // file name (the latter is optional).
775 string infilename = internal_path(os::utf8_argv(1));
776 infilename = makeAbsPath(infilename).absFileName();
781 // Do not allow a user supplied output filename
782 // (otherwise it could easily happen that LyX would
783 // overwrite the original .tex file)
784 cerr << "Error: output filename must not be given in roundtrip mode."
788 outfilename = changeExtension(infilename, ".lyx.lyx");
789 } else if (argc > 2) {
790 outfilename = internal_path(os::utf8_argv(2));
791 if (outfilename != "-")
792 outfilename = makeAbsPath(outfilename).absFileName();
794 outfilename = changeExtension(infilename, ".lyx");
796 // Read the syntax tables
797 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
798 if (system_syntaxfile.empty()) {
799 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
802 read_syntaxfile(system_syntaxfile);
803 if (!syntaxfile.empty())
804 read_syntaxfile(makeAbsPath(syntaxfile));
806 // Read the encodings table.
807 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
808 if (symbols_path.empty()) {
809 cerr << "Error: Could not find file \"unicodesymbols\"."
813 FileName const enc_path = libFileSearch(string(), "encodings");
814 if (enc_path.empty()) {
815 cerr << "Error: Could not find file \"encodings\"."
819 encodings.read(enc_path, symbols_path);
820 if (!default_encoding.empty() && !encodings.fromLaTeXName(default_encoding))
821 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
824 LayoutFileList::get().read();
826 theModuleList.read();
828 // The real work now.
829 masterFilePath = onlyPath(infilename);
830 parentFilePath = masterFilePath;
831 if (outfilename == "-") {
832 if (tex2lyx(FileName(infilename), cout, default_encoding))
834 } else if (roundtrip) {
835 if (tex2tex(infilename, FileName(outfilename), default_encoding))
838 if (tex2lyx(infilename, FileName(outfilename), default_encoding))