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.
22 #include "LayoutFile.h"
23 #include "LayoutModuleList.h"
24 #include "ModuleList.h"
26 #include "TextClass.h"
28 #include "support/convert.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/filetools.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/Messages.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/Systemcall.h"
47 using namespace lyx::support;
48 using namespace lyx::support::os;
54 void warning(docstring const & title, docstring const & message,
57 cerr << to_utf8(title) << "\n" << to_utf8(message) << endl;
63 // Dummy texrow support
64 void TexRow::newline()
68 void TexRow::newlines(int)
72 // Dummy LyXRC support
79 // Dummy translation support
81 Messages const & getMessages(string const &)
87 Messages const & getGuiMessages()
93 // tex2lyx does not read lyxrc and therefore can't really check for
94 // zipped formats (Used by lexer)
98 bool Formats::isZippedFile(FileName const&) const
104 // Keep the linker happy on Windows
109 string const trimSpaceAndEol(string const & a)
111 return trim(a, " \t\n\r");
115 void split(string const & s, vector<string> & result, char delim)
117 //cerr << "split 1: '" << s << "'\n";
120 while (getline(is, t, delim))
122 //cerr << "split 2\n";
126 string join(vector<string> const & input, char const * delim)
129 for (size_t i = 0; i != input.size(); ++i) {
138 char const * const * is_known(string const & str, char const * const * what)
140 for ( ; *what; ++what)
148 // current stack of nested environments
149 vector<string> active_environments;
152 string active_environment()
154 return active_environments.empty() ? string() : active_environments.back();
158 TeX2LyXDocClass textclass;
159 CommandMap known_commands;
160 CommandMap known_environments;
161 CommandMap known_math_environments;
162 FullCommandMap possible_textclass_commands;
163 FullEnvironmentMap possible_textclass_environments;
164 FullCommandMap possible_textclass_theorems;
165 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
168 LayoutModuleList used_modules;
169 vector<string> preloaded_modules;
172 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
174 // We have to handle the following cases:
175 // definition o1 o2 invocation result
176 // \newcommand{\foo}{bar} "" false \foo bar
177 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
178 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
179 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
180 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
181 unsigned int nargs = 0;
182 string const opt1 = rtrim(ltrim(o1, "["), "]");
183 if (isStrUnsignedInt(opt1)) {
184 // The command has arguments
185 nargs = convert<unsigned int>(opt1);
186 if (nargs > 0 && o2) {
187 // The first argument is optional
188 arguments.push_back(optional);
192 for (unsigned int i = 0; i < nargs; ++i)
193 arguments.push_back(required);
197 void add_known_command(string const & command, string const & o1,
198 bool o2, docstring const & definition)
200 vector<ArgumentType> arguments;
201 convertArgs(o1, o2, arguments);
202 known_commands[command] = arguments;
203 if (!definition.empty())
204 possible_textclass_commands[command] =
205 FullCommand(arguments, definition);
209 void add_known_environment(string const & environment, string const & o1,
210 bool o2, docstring const & beg, docstring const &end)
212 vector<ArgumentType> arguments;
213 convertArgs(o1, o2, arguments);
214 known_environments[environment] = arguments;
215 if (!beg.empty() || ! end.empty())
216 possible_textclass_environments[environment] =
217 FullEnvironment(arguments, beg, end);
221 void add_known_theorem(string const & theorem, string const & o1,
222 bool o2, docstring const & definition)
224 vector<ArgumentType> arguments;
225 convertArgs(o1, o2, arguments);
226 if (!definition.empty())
227 possible_textclass_theorems[theorem] =
228 FullCommand(arguments, definition);
232 Layout const * findLayoutWithoutModule(TextClass const & textclass,
233 string const & name, bool command)
235 DocumentClass::const_iterator it = textclass.begin();
236 DocumentClass::const_iterator en = textclass.end();
237 for (; it != en; ++it) {
238 if (it->latexname() == name &&
239 ((command && it->isCommand()) || (!command && it->isEnvironment())))
246 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
247 string const & name, bool command)
249 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
250 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
251 for (; it != en; ++it) {
252 if (it->second.latexname() == name &&
253 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
254 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
255 return &(it->second);
263 typedef map<string, DocumentClassPtr> ModuleMap;
267 bool addModule(string const module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
269 // avoid endless loop for circular dependency
270 vector<string>::const_iterator const vb = visited.begin();
271 vector<string>::const_iterator const ve = visited.end();
272 if (find(vb, ve, module) != ve) {
273 cerr << "Circular dependency detected for module " << module << '\n';
276 LyXModule const * const lm = theModuleList[module];
278 cerr << "Could not find module " << module << " in module list.\n";
281 bool foundone = false;
282 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
283 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
284 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
285 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
286 vector<string> const reqs = lm->getRequiredModules();
290 LayoutModuleList::const_iterator mit = m.begin();
291 LayoutModuleList::const_iterator men = m.end();
292 vector<string>::const_iterator rit = reqs.begin();
293 vector<string>::const_iterator ren = reqs.end();
294 for (; rit != ren; ++rit) {
295 if (find(mit, men, *rit) != men) {
299 if (find(provmodstart, provmodend, *rit) != provmodend) {
305 visited.push_back(module);
306 for (rit = reqs.begin(); rit != ren; ++rit) {
307 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
308 if (addModule(*rit, baseClass, m, visited)) {
318 cerr << "Could not add required modules for " << module << ".\n";
321 if (!m.moduleCanBeAdded(module, &baseClass))
330 // Create list of dummy document classes if not already done.
331 // This is needed since a module cannot be read on its own, only as
332 // part of a document class.
333 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
334 static bool init = true;
337 LyXModuleList::const_iterator const end = theModuleList.end();
338 LyXModuleList::const_iterator it = theModuleList.begin();
339 for (; it != end; ++it) {
340 string const module = it->getID();
343 if (!addModule(module, baseClass, m, v))
345 modules[module] = getDocumentClass(baseClass, m);
352 bool addModule(string const & module)
355 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
356 if (!used_modules.moduleCanBeAdded(module, &baseClass))
358 FileName layout_file = libFileSearch("layouts", module, "module");
359 if (textclass.read(layout_file, TextClass::MODULE)) {
360 used_modules.push_back(module);
361 // speed up further searches:
362 // the module does not need to be checked anymore.
363 ModuleMap::iterator const it = modules.find(module);
364 if (it != modules.end())
374 bool checkModule(string const & name, bool command)
376 // Cache to avoid slowdown by repated searches
377 static set<string> failed[2];
379 // Only add the module if the command was actually defined in the LyX preamble
380 bool theorem = false;
382 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
385 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
386 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
392 if (failed[command].find(name) != failed[command].end())
396 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
398 // Try to find a module that defines the command.
399 // Only add it if the definition can be found in the preamble of the
400 // style that corresponds to the command. This is a heuristic and
401 // different from the way how we parse the builtin commands of the
402 // text class (in that case we only compare the name), but it is
403 // needed since it is not unlikely that two different modules define a
404 // command with the same name.
405 ModuleMap::iterator const end = modules.end();
406 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
407 string const module = it->first;
408 if (used_modules.moduleConflicts(module, &baseClass))
410 if (findLayoutWithoutModule(textclass, name, command))
412 if (findInsetLayoutWithoutModule(textclass, name, command))
414 DocumentClassConstPtr c = it->second;
415 Layout const * layout = findLayoutWithoutModule(*c, name, command);
416 InsetLayout const * insetlayout = layout ? 0 :
417 findInsetLayoutWithoutModule(*c, name, command);
420 preamble = layout->preamble();
421 else if (insetlayout)
422 preamble = insetlayout->preamble();
423 if (preamble.empty())
427 FullCommand const & cmd =
428 possible_textclass_commands['\\' + name];
429 if (preamble.find(cmd.def) != docstring::npos)
431 } else if (theorem) {
432 FullCommand const & thm =
433 possible_textclass_theorems[name];
434 if (preamble.find(thm.def) != docstring::npos)
437 FullEnvironment const & env =
438 possible_textclass_environments[name];
439 if (preamble.find(env.beg) != docstring::npos &&
440 preamble.find(env.end) != docstring::npos)
444 FileName layout_file = libFileSearch("layouts", module, "module");
445 if (textclass.read(layout_file, TextClass::MODULE)) {
446 used_modules.push_back(module);
447 // speed up further searches:
448 // the module does not need to be checked anymore.
454 failed[command].insert(name);
459 bool isProvided(string const & name)
461 // This works only for features that are named like the LaTeX packages
462 return textclass.provides(name) || preamble.isPackageUsed(name);
466 bool noweb_mode = false;
467 bool pdflatex = false;
469 bool is_nonCJKJapanese = false;
470 bool roundtrip = false;
477 * Read one command definition from the syntax file
479 void read_command(Parser & p, string command, CommandMap & commands)
481 if (p.next_token().asInput() == "*") {
485 vector<ArgumentType> arguments;
486 while (p.next_token().cat() == catBegin ||
487 p.next_token().asInput() == "[") {
488 if (p.next_token().cat() == catBegin) {
489 string const arg = p.getArg('{', '}');
490 if (arg == "translate")
491 arguments.push_back(required);
492 else if (arg == "group")
493 arguments.push_back(req_group);
494 else if (arg == "item")
495 arguments.push_back(item);
496 else if (arg == "displaymath")
497 arguments.push_back(displaymath);
499 arguments.push_back(verbatim);
501 string const arg = p.getArg('[', ']');
503 arguments.push_back(opt_group);
505 arguments.push_back(optional);
508 commands[command] = arguments;
513 * Read a class of environments from the syntax file
515 void read_environment(Parser & p, string const & begin,
516 CommandMap & environments)
520 Token const & t = p.get_token();
521 if (t.cat() == catLetter)
522 environment += t.asInput();
523 else if (!environment.empty()) {
525 read_command(p, environment, environments);
528 if (t.cat() == catEscape && t.asInput() == "\\end") {
529 string const end = p.getArg('{', '}');
538 * Read a list of TeX commands from a reLyX compatible syntax file.
539 * Since this list is used after all commands that have a LyX counterpart
540 * are handled, it does not matter that the "syntax.default" file
541 * has almost all of them listed. For the same reason the reLyX-specific
542 * reLyXre environment is ignored.
544 void read_syntaxfile(FileName const & file_name)
546 ifdocstream is(file_name.toFilesystemEncoding().c_str());
548 cerr << "Could not open syntax file \"" << file_name
549 << "\" for reading." << endl;
552 // We can use our TeX parser, since the syntax of the layout file is
553 // modeled after TeX.
554 // Unknown tokens are just silently ignored, this helps us to skip some
555 // reLyX specific things.
558 Token const & t = p.get_token();
559 if (t.cat() == catEscape) {
560 string const command = t.asInput();
561 if (command == "\\begin") {
562 string const name = p.getArg('{', '}');
563 if (name == "environments" || name == "reLyXre")
564 // We understand "reLyXre", but it is
565 // not as powerful as "environments".
566 read_environment(p, name,
568 else if (name == "mathenvironments")
569 read_environment(p, name,
570 known_math_environments);
572 read_command(p, command, known_commands);
579 string documentclass;
580 string default_encoding;
582 bool copy_files = false;
583 bool overwrite_files = false;
584 bool skip_children = false;
587 /// return the number of arguments consumed
588 typedef int (*cmd_helper)(string const &, string const &);
591 int parse_help(string const &, string const &)
593 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
595 "\t-c textclass Declare the textclass.\n"
596 "\t-m mod1[,mod2...] Load the given modules.\n"
597 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
598 "\t-e encoding Set the default encoding (latex name).\n"
599 "\t-f Force overwrite of .lyx files.\n"
600 "\t-help Print this message and quit.\n"
601 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
602 "\t-skipchildren Do not translate included child documents.\n"
603 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
604 "\t-s syntaxfile read additional syntax file.\n"
605 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
606 "\t Default: " << package().system_support() << "\n"
607 "\t-userdir USERDIR Set user directory to USERDIR.\n"
608 "\t Default: " << package().user_support() << "\n"
609 "\t-version Summarize version and build info.\n"
611 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
612 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
613 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
614 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
615 "Check the tex2lyx man page for more details."
621 int parse_version(string const &, string const &)
623 lyxerr << "tex2lyx " << lyx_version
624 << " (" << lyx_release_date << ")" << endl;
625 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
627 lyxerr << lyx_version_info << endl;
632 void error_message(string const & message)
634 cerr << "tex2lyx: " << message << "\n\n";
636 parse_help(string(), string());
640 int parse_class(string const & arg, string const &)
643 error_message("Missing textclass string after -c switch");
649 int parse_module(string const & arg, string const &)
652 error_message("Missing modules string after -m switch");
653 split(arg, preloaded_modules, ',');
658 int parse_encoding(string const & arg, string const &)
661 error_message("Missing encoding string after -e switch");
662 default_encoding = arg;
667 int parse_syntaxfile(string const & arg, string const &)
670 error_message("Missing syntaxfile string after -s switch");
671 syntaxfile = internal_path(arg);
676 // Filled with the command line arguments "foo" of "-sysdir foo" or
678 string cl_system_support;
679 string cl_user_support;
682 int parse_sysdir(string const & arg, string const &)
685 error_message("Missing directory for -sysdir switch");
686 cl_system_support = internal_path(arg);
691 int parse_userdir(string const & arg, string const &)
694 error_message("Missing directory for -userdir switch");
695 cl_user_support = internal_path(arg);
700 int parse_force(string const &, string const &)
702 overwrite_files = true;
707 int parse_noweb(string const &, string const &)
714 int parse_skipchildren(string const &, string const &)
716 skip_children = true;
721 int parse_roundtrip(string const &, string const &)
728 int parse_copyfiles(string const &, string const &)
735 void easyParse(int & argc, char * argv[])
737 map<string, cmd_helper> cmdmap;
739 cmdmap["-h"] = parse_help;
740 cmdmap["-help"] = parse_help;
741 cmdmap["--help"] = parse_help;
742 cmdmap["-v"] = parse_version;
743 cmdmap["-version"] = parse_version;
744 cmdmap["--version"] = parse_version;
745 cmdmap["-c"] = parse_class;
746 cmdmap["-m"] = parse_module;
747 cmdmap["-e"] = parse_encoding;
748 cmdmap["-f"] = parse_force;
749 cmdmap["-s"] = parse_syntaxfile;
750 cmdmap["-n"] = parse_noweb;
751 cmdmap["-skipchildren"] = parse_skipchildren;
752 cmdmap["-sysdir"] = parse_sysdir;
753 cmdmap["-userdir"] = parse_userdir;
754 cmdmap["-roundtrip"] = parse_roundtrip;
755 cmdmap["-copyfiles"] = parse_copyfiles;
757 for (int i = 1; i < argc; ++i) {
758 map<string, cmd_helper>::const_iterator it
759 = cmdmap.find(argv[i]);
761 // don't complain if not found - may be parsed later
762 if (it == cmdmap.end()) {
763 if (argv[i][0] == '-')
764 error_message(string("Unknown option `") + argv[i] + "'.");
769 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
770 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
772 int const remove = 1 + it->second(arg, arg2);
774 // Now, remove used arguments by shifting
775 // the following ones remove places down.
776 os::remove_internal_args(i, remove);
778 for (int j = i; j < argc; ++j)
779 argv[j] = argv[j + remove];
785 // path of the first parsed file
786 string masterFilePathLyX;
787 string masterFilePathTeX;
788 // path of the currently parsed file
789 string parentFilePathTeX;
791 } // anonymous namespace
794 string getMasterFilePath(bool input)
796 return input ? masterFilePathTeX : masterFilePathLyX;
799 string getParentFilePath(bool input)
802 return parentFilePathTeX;
803 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
804 from_utf8(parentFilePathTeX)));
805 if (rel.substr(0, 3) == "../") {
806 // The parent is not below the master - keep the path
807 return parentFilePathTeX;
809 return makeAbsPath(rel, masterFilePathLyX).absFileName();
819 bool overwriteFiles()
821 return overwrite_files;
827 return skip_children;
840 * Reads tex input from \a is and writes lyx output to \a os.
841 * Uses some common settings for the preamble, so this should only
842 * be used more than once for included documents.
843 * Caution: Overwrites the existing preamble settings if the new document
844 * contains a preamble.
845 * You must ensure that \p parentFilePathTeX is properly set before calling
848 bool tex2lyx(idocstream & is, ostream & os, string encoding)
850 // Set a sensible default encoding.
851 // This is used until an encoding command is found.
852 // For child documents use the encoding of the master, else ISO8859-1,
853 // (formerly known by its latex name latin1), since ISO8859-1 does not
854 // cause an iconv error if the actual encoding is different (bug 7509).
855 if (encoding.empty()) {
856 if (preamble.inputencoding() == "auto")
857 encoding = "ISO8859-1";
859 Encoding const * const enc = encodings.fromLyXName(
860 preamble.inputencoding(), true);
861 encoding = enc->iconvName();
866 p.setEncoding(encoding);
869 preamble.parse(p, documentclass, textclass);
870 list<string> removed_modules;
871 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
872 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
873 cerr << "Could not load default modules for text class." << endl;
877 // Load preloaded modules.
878 // This needs to be done after the preamble is parsed, since the text
879 // class may not be known before. It neds to be done before parsing
880 // body, since otherwise the commands/environments provided by the
881 // modules would be parsed as ERT.
882 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
883 if (!addModule(preloaded_modules[i])) {
884 cerr << "Error: Could not load module \""
885 << preloaded_modules[i] << "\"." << endl;
889 // Ensure that the modules are not loaded again for included files
890 preloaded_modules.clear();
892 active_environments.push_back("document");
893 Context context(true, textclass);
895 // store the document language in the context to be able to handle the
896 // commands like \foreignlanguage and \textenglish etc.
897 context.font.language = preamble.defaultLanguage();
898 // parse the main text
899 parse_text(p, ss, FLAG_END, true, context);
901 // Empty document body. LyX needs at least one paragraph.
902 context.check_layout(ss);
903 context.check_end_layout(ss);
904 ss << "\n\\end_body\n\\end_document\n";
905 active_environments.pop_back();
907 // We know the used modules only after parsing the full text
908 if (!used_modules.empty()) {
909 LayoutModuleList::const_iterator const end = used_modules.end();
910 LayoutModuleList::const_iterator it = used_modules.begin();
911 for (; it != end; ++it)
912 preamble.addModule(*it);
914 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
915 cerr << "Could not write LyX file header." << endl;
923 ofdocstream parsertest("parsertest.tex");
925 parsertest << p.get_token().asInput();
926 // <origfile> and parsertest.tex should now have identical content
932 /// convert TeX from \p infilename to LyX and write it to \p os
933 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
936 // forbid buffering on this stream
937 is.rdbuf()->pubsetbuf(0,0);
938 is.open(infilename.toFilesystemEncoding().c_str());
940 cerr << "Could not open input file \"" << infilename
941 << "\" for reading." << endl;
944 string const oldParentFilePath = parentFilePathTeX;
945 parentFilePathTeX = onlyPath(infilename.absFileName());
946 bool retval = tex2lyx(is, os, encoding);
947 parentFilePathTeX = oldParentFilePath;
951 } // anonymous namespace
954 bool tex2lyx(string const & infilename, FileName const & outfilename,
955 string const & encoding)
957 if (outfilename.isReadableFile()) {
958 if (overwrite_files) {
959 cerr << "Overwriting existing file "
960 << outfilename << endl;
962 cerr << "Not overwriting existing file "
963 << outfilename << endl;
967 cerr << "Creating file " << outfilename << endl;
969 ofstream os(outfilename.toFilesystemEncoding().c_str());
971 cerr << "Could not open output file \"" << outfilename
972 << "\" for writing." << endl;
976 cerr << "Input file: " << infilename << "\n";
977 cerr << "Output file: " << outfilename << "\n";
979 return tex2lyx(FileName(infilename), os, encoding);
983 bool tex2tex(string const & infilename, FileName const & outfilename,
984 string const & encoding)
986 if (!tex2lyx(infilename, outfilename, encoding))
988 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
990 command += " -f main";
992 command += " -f none";
994 command += " -e pdflatex ";
996 command += " -e xetex ";
998 command += " -e latex ";
999 command += quoteName(outfilename.toFilesystemEncoding());
1001 if (one.startscript(Systemcall::Wait, command) == 0)
1003 cerr << "Error: Running '" << command << "' failed." << endl;
1010 int main(int argc, char * argv[])
1012 using namespace lyx;
1014 //setlocale(LC_CTYPE, "");
1016 lyxerr.setStream(cerr);
1018 os::init(argc, argv);
1021 init_package(internal_path(os::utf8_argv(0)), string(), string());
1022 } catch (ExceptionMessage const & message) {
1023 cerr << to_utf8(message.title_) << ":\n"
1024 << to_utf8(message.details_) << endl;
1025 if (message.type_ == ErrorException)
1026 return EXIT_FAILURE;
1029 easyParse(argc, argv);
1032 error_message("Not enough arguments.");
1035 init_package(internal_path(os::utf8_argv(0)),
1036 cl_system_support, cl_user_support);
1037 } catch (ExceptionMessage const & message) {
1038 cerr << to_utf8(message.title_) << ":\n"
1039 << to_utf8(message.details_) << endl;
1040 if (message.type_ == ErrorException)
1041 return EXIT_FAILURE;
1044 // Now every known option is parsed. Look for input and output
1045 // file name (the latter is optional).
1046 string infilename = internal_path(os::utf8_argv(1));
1047 infilename = makeAbsPath(infilename).absFileName();
1051 outfilename = internal_path(os::utf8_argv(2));
1052 if (outfilename != "-")
1053 outfilename = makeAbsPath(outfilename).absFileName();
1055 if (outfilename == "-") {
1056 cerr << "Error: Writing to standard output is "
1057 "not supported in roundtrip mode."
1059 return EXIT_FAILURE;
1061 string texfilename = changeExtension(outfilename, ".tex");
1062 if (equivalent(FileName(infilename), FileName(texfilename))) {
1063 cerr << "Error: The input file `" << infilename
1064 << "´ would be overwritten by the TeX file exported from `"
1065 << outfilename << "´ in roundtrip mode." << endl;
1066 return EXIT_FAILURE;
1069 } else if (roundtrip) {
1070 // avoid overwriting the input file
1071 outfilename = changeExtension(infilename, ".lyx.lyx");
1073 outfilename = changeExtension(infilename, ".lyx");
1075 // Read the syntax tables
1076 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1077 if (system_syntaxfile.empty()) {
1078 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1079 return EXIT_FAILURE;
1081 read_syntaxfile(system_syntaxfile);
1082 if (!syntaxfile.empty())
1083 read_syntaxfile(makeAbsPath(syntaxfile));
1085 // Read the encodings table.
1086 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1087 if (symbols_path.empty()) {
1088 cerr << "Error: Could not find file \"unicodesymbols\"."
1090 return EXIT_FAILURE;
1092 FileName const enc_path = libFileSearch(string(), "encodings");
1093 if (enc_path.empty()) {
1094 cerr << "Error: Could not find file \"encodings\"."
1096 return EXIT_FAILURE;
1098 encodings.read(enc_path, symbols_path);
1099 if (!default_encoding.empty()) {
1100 Encoding const * const enc = encodings.fromLaTeXName(
1101 default_encoding, Encoding::any, true);
1103 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1104 default_encoding = enc->iconvName();
1108 LayoutFileList::get().read();
1109 //...and the modules
1110 theModuleList.read();
1112 // The real work now.
1113 masterFilePathTeX = onlyPath(infilename);
1114 parentFilePathTeX = masterFilePathTeX;
1115 if (outfilename == "-") {
1116 // assume same directory as input file
1117 masterFilePathLyX = masterFilePathTeX;
1118 if (tex2lyx(FileName(infilename), cout, default_encoding))
1119 return EXIT_SUCCESS;
1121 masterFilePathLyX = onlyPath(outfilename);
1123 FileName const path(masterFilePathLyX);
1124 if (!path.isDirectory()) {
1125 if (!path.createPath()) {
1126 cerr << "Warning: Could not create directory for file `"
1127 << masterFilePathLyX << "´." << endl;
1128 return EXIT_FAILURE;
1133 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1134 return EXIT_SUCCESS;
1136 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
1137 return EXIT_SUCCESS;
1140 return EXIT_FAILURE;