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.
21 #include "LaTeXFeatures.h"
23 #include "LayoutFile.h"
24 #include "LayoutModuleList.h"
25 #include "ModuleList.h"
27 #include "TextClass.h"
29 #include "support/convert.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/filetools.h"
32 #include "support/lassert.h"
33 #include "support/lstrings.h"
34 #include "support/Messages.h"
35 #include "support/os.h"
36 #include "support/Package.h"
37 #include "support/Systemcall.h"
48 using namespace lyx::support;
49 using namespace lyx::support::os;
55 void warning(docstring const & title, docstring const & message,
58 cerr << to_utf8(title) << "\n" << to_utf8(message) << endl;
64 // Dummy texrow support
65 void TexRow::newline()
69 void TexRow::newlines(int)
73 // Dummy LyXRC support
80 // Dummy translation support
82 Messages const & getMessages(string const &)
88 Messages const & getGuiMessages()
94 // tex2lyx does not read lyxrc and therefore can't really check for
95 // zipped formats (Used by lexer)
99 bool Formats::isZippedFile(FileName const&) const
105 bool LaTeXFeatures::isAvailable(string const &)
111 // Keep the linker happy on Windows
116 string const trimSpaceAndEol(string const & a)
118 return trim(a, " \t\n\r");
122 void split(string const & s, vector<string> & result, char delim)
124 //cerr << "split 1: '" << s << "'\n";
127 while (getline(is, t, delim))
129 //cerr << "split 2\n";
133 string join(vector<string> const & input, char const * delim)
136 for (size_t i = 0; i != input.size(); ++i) {
145 char const * const * is_known(string const & str, char const * const * what)
147 for ( ; *what; ++what)
155 // current stack of nested environments
156 vector<string> active_environments;
159 string active_environment()
161 return active_environments.empty() ? string() : active_environments.back();
165 TeX2LyXDocClass textclass;
166 CommandMap known_commands;
167 CommandMap known_environments;
168 CommandMap known_math_environments;
169 FullCommandMap possible_textclass_commands;
170 FullEnvironmentMap possible_textclass_environments;
171 FullCommandMap possible_textclass_theorems;
172 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
175 LayoutModuleList used_modules;
176 vector<string> preloaded_modules;
179 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
181 // We have to handle the following cases:
182 // definition o1 o2 invocation result
183 // \newcommand{\foo}{bar} "" false \foo bar
184 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
185 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
186 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
187 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
188 unsigned int nargs = 0;
189 string const opt1 = rtrim(ltrim(o1, "["), "]");
190 if (isStrUnsignedInt(opt1)) {
191 // The command has arguments
192 nargs = convert<unsigned int>(opt1);
193 if (nargs > 0 && o2) {
194 // The first argument is optional
195 arguments.push_back(optional);
199 for (unsigned int i = 0; i < nargs; ++i)
200 arguments.push_back(required);
204 void add_known_command(string const & command, string const & o1,
205 bool o2, docstring const & definition)
207 vector<ArgumentType> arguments;
208 convertArgs(o1, o2, arguments);
209 known_commands[command] = arguments;
210 if (!definition.empty())
211 possible_textclass_commands[command] =
212 FullCommand(arguments, definition);
216 void add_known_environment(string const & environment, string const & o1,
217 bool o2, docstring const & beg, docstring const &end)
219 vector<ArgumentType> arguments;
220 convertArgs(o1, o2, arguments);
221 known_environments[environment] = arguments;
222 if (!beg.empty() || ! end.empty())
223 possible_textclass_environments[environment] =
224 FullEnvironment(arguments, beg, end);
228 void add_known_theorem(string const & theorem, string const & o1,
229 bool o2, docstring const & definition)
231 vector<ArgumentType> arguments;
232 convertArgs(o1, o2, arguments);
233 if (!definition.empty())
234 possible_textclass_theorems[theorem] =
235 FullCommand(arguments, definition);
239 Layout const * findLayoutWithoutModule(TextClass const & textclass,
240 string const & name, bool command)
242 DocumentClass::const_iterator it = textclass.begin();
243 DocumentClass::const_iterator en = textclass.end();
244 for (; it != en; ++it) {
245 if (it->latexname() == name &&
246 ((command && it->isCommand()) || (!command && it->isEnvironment())))
253 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
254 string const & name, bool command)
256 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
257 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
258 for (; it != en; ++it) {
259 if (it->second.latexname() == name &&
260 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
261 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
262 return &(it->second);
270 typedef map<string, DocumentClassPtr> ModuleMap;
274 bool addModule(string const module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
276 // avoid endless loop for circular dependency
277 vector<string>::const_iterator const vb = visited.begin();
278 vector<string>::const_iterator const ve = visited.end();
279 if (find(vb, ve, module) != ve) {
280 cerr << "Circular dependency detected for module " << module << '\n';
283 LyXModule const * const lm = theModuleList[module];
285 cerr << "Could not find module " << module << " in module list.\n";
288 bool foundone = false;
289 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
290 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
291 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
292 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
293 vector<string> const reqs = lm->getRequiredModules();
297 LayoutModuleList::const_iterator mit = m.begin();
298 LayoutModuleList::const_iterator men = m.end();
299 vector<string>::const_iterator rit = reqs.begin();
300 vector<string>::const_iterator ren = reqs.end();
301 for (; rit != ren; ++rit) {
302 if (find(mit, men, *rit) != men) {
306 if (find(provmodstart, provmodend, *rit) != provmodend) {
312 visited.push_back(module);
313 for (rit = reqs.begin(); rit != ren; ++rit) {
314 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
315 if (addModule(*rit, baseClass, m, visited)) {
325 cerr << "Could not add required modules for " << module << ".\n";
328 if (!m.moduleCanBeAdded(module, &baseClass))
337 // Create list of dummy document classes if not already done.
338 // This is needed since a module cannot be read on its own, only as
339 // part of a document class.
340 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
341 static bool init = true;
344 LyXModuleList::const_iterator const end = theModuleList.end();
345 LyXModuleList::const_iterator it = theModuleList.begin();
346 for (; it != end; ++it) {
347 string const module = it->getID();
350 if (!addModule(module, baseClass, m, v))
352 modules[module] = getDocumentClass(baseClass, m);
359 bool addModule(string const & module)
362 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
363 if (!used_modules.moduleCanBeAdded(module, &baseClass))
365 FileName layout_file = libFileSearch("layouts", module, "module");
366 if (textclass.read(layout_file, TextClass::MODULE)) {
367 used_modules.push_back(module);
368 // speed up further searches:
369 // the module does not need to be checked anymore.
370 ModuleMap::iterator const it = modules.find(module);
371 if (it != modules.end())
381 bool checkModule(string const & name, bool command)
383 // Cache to avoid slowdown by repated searches
384 static set<string> failed[2];
386 // Only add the module if the command was actually defined in the LyX preamble
387 bool theorem = false;
389 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
392 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
393 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
399 if (failed[command].find(name) != failed[command].end())
403 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
405 // Try to find a module that defines the command.
406 // Only add it if the definition can be found in the preamble of the
407 // style that corresponds to the command. This is a heuristic and
408 // different from the way how we parse the builtin commands of the
409 // text class (in that case we only compare the name), but it is
410 // needed since it is not unlikely that two different modules define a
411 // command with the same name.
412 ModuleMap::iterator const end = modules.end();
413 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
414 string const module = it->first;
415 if (used_modules.moduleConflicts(module, &baseClass))
417 if (findLayoutWithoutModule(textclass, name, command))
419 if (findInsetLayoutWithoutModule(textclass, name, command))
421 DocumentClassConstPtr c = it->second;
422 Layout const * layout = findLayoutWithoutModule(*c, name, command);
423 InsetLayout const * insetlayout = layout ? 0 :
424 findInsetLayoutWithoutModule(*c, name, command);
427 preamble = layout->preamble();
428 else if (insetlayout)
429 preamble = insetlayout->preamble();
430 if (preamble.empty())
434 FullCommand const & cmd =
435 possible_textclass_commands['\\' + name];
436 if (preamble.find(cmd.def) != docstring::npos)
438 } else if (theorem) {
439 FullCommand const & thm =
440 possible_textclass_theorems[name];
441 if (preamble.find(thm.def) != docstring::npos)
444 FullEnvironment const & env =
445 possible_textclass_environments[name];
446 if (preamble.find(env.beg) != docstring::npos &&
447 preamble.find(env.end) != docstring::npos)
451 FileName layout_file = libFileSearch("layouts", module, "module");
452 if (textclass.read(layout_file, TextClass::MODULE)) {
453 used_modules.push_back(module);
454 // speed up further searches:
455 // the module does not need to be checked anymore.
461 failed[command].insert(name);
466 bool isProvided(string const & name)
468 // This works only for features that are named like the LaTeX packages
469 return textclass.provides(name) || preamble.isPackageUsed(name);
473 bool noweb_mode = false;
474 bool pdflatex = false;
476 bool is_nonCJKJapanese = false;
477 bool roundtrip = false;
484 * Read one command definition from the syntax file
486 void read_command(Parser & p, string command, CommandMap & commands)
488 if (p.next_token().asInput() == "*") {
492 vector<ArgumentType> arguments;
493 while (p.next_token().cat() == catBegin ||
494 p.next_token().asInput() == "[") {
495 if (p.next_token().cat() == catBegin) {
496 string const arg = p.getArg('{', '}');
497 if (arg == "translate")
498 arguments.push_back(required);
499 else if (arg == "group")
500 arguments.push_back(req_group);
501 else if (arg == "item")
502 arguments.push_back(item);
503 else if (arg == "displaymath")
504 arguments.push_back(displaymath);
506 arguments.push_back(verbatim);
508 string const arg = p.getArg('[', ']');
510 arguments.push_back(opt_group);
512 arguments.push_back(optional);
515 commands[command] = arguments;
520 * Read a class of environments from the syntax file
522 void read_environment(Parser & p, string const & begin,
523 CommandMap & environments)
527 Token const & t = p.get_token();
528 if (t.cat() == catLetter)
529 environment += t.asInput();
530 else if (!environment.empty()) {
532 read_command(p, environment, environments);
535 if (t.cat() == catEscape && t.asInput() == "\\end") {
536 string const end = p.getArg('{', '}');
545 * Read a list of TeX commands from a reLyX compatible syntax file.
546 * Since this list is used after all commands that have a LyX counterpart
547 * are handled, it does not matter that the "syntax.default" file
548 * has almost all of them listed. For the same reason the reLyX-specific
549 * reLyXre environment is ignored.
551 void read_syntaxfile(FileName const & file_name)
553 ifdocstream is(file_name.toFilesystemEncoding().c_str());
555 cerr << "Could not open syntax file \"" << file_name
556 << "\" for reading." << endl;
559 // We can use our TeX parser, since the syntax of the layout file is
560 // modeled after TeX.
561 // Unknown tokens are just silently ignored, this helps us to skip some
562 // reLyX specific things.
565 Token const & t = p.get_token();
566 if (t.cat() == catEscape) {
567 string const command = t.asInput();
568 if (command == "\\begin") {
569 string const name = p.getArg('{', '}');
570 if (name == "environments" || name == "reLyXre")
571 // We understand "reLyXre", but it is
572 // not as powerful as "environments".
573 read_environment(p, name,
575 else if (name == "mathenvironments")
576 read_environment(p, name,
577 known_math_environments);
579 read_command(p, command, known_commands);
586 string documentclass;
587 string default_encoding;
589 bool copy_files = false;
590 bool overwrite_files = false;
591 bool skip_children = false;
594 /// return the number of arguments consumed
595 typedef int (*cmd_helper)(string const &, string const &);
598 int parse_help(string const &, string const &)
600 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
602 "\t-c textclass Declare the textclass.\n"
603 "\t-m mod1[,mod2...] Load the given modules.\n"
604 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
605 "\t-e encoding Set the default encoding (latex name).\n"
606 "\t-f Force overwrite of .lyx files.\n"
607 "\t-help Print this message and quit.\n"
608 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
609 "\t-skipchildren Do not translate included child documents.\n"
610 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
611 "\t-s syntaxfile read additional syntax file.\n"
612 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
613 "\t Default: " << package().system_support() << "\n"
614 "\t-userdir USERDIR Set user directory to USERDIR.\n"
615 "\t Default: " << package().user_support() << "\n"
616 "\t-version Summarize version and build info.\n"
618 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
619 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
620 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
621 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
622 "Check the tex2lyx man page for more details."
628 int parse_version(string const &, string const &)
630 lyxerr << "tex2lyx " << lyx_version
631 << " (" << lyx_release_date << ")" << endl;
632 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
634 lyxerr << lyx_version_info << endl;
639 void error_message(string const & message)
641 cerr << "tex2lyx: " << message << "\n\n";
643 parse_help(string(), string());
647 int parse_class(string const & arg, string const &)
650 error_message("Missing textclass string after -c switch");
656 int parse_module(string const & arg, string const &)
659 error_message("Missing modules string after -m switch");
660 split(arg, preloaded_modules, ',');
665 int parse_encoding(string const & arg, string const &)
668 error_message("Missing encoding string after -e switch");
669 default_encoding = arg;
674 int parse_syntaxfile(string const & arg, string const &)
677 error_message("Missing syntaxfile string after -s switch");
678 syntaxfile = internal_path(arg);
683 // Filled with the command line arguments "foo" of "-sysdir foo" or
685 string cl_system_support;
686 string cl_user_support;
689 int parse_sysdir(string const & arg, string const &)
692 error_message("Missing directory for -sysdir switch");
693 cl_system_support = internal_path(arg);
698 int parse_userdir(string const & arg, string const &)
701 error_message("Missing directory for -userdir switch");
702 cl_user_support = internal_path(arg);
707 int parse_force(string const &, string const &)
709 overwrite_files = true;
714 int parse_noweb(string const &, string const &)
721 int parse_skipchildren(string const &, string const &)
723 skip_children = true;
728 int parse_roundtrip(string const &, string const &)
735 int parse_copyfiles(string const &, string const &)
742 void easyParse(int & argc, char * argv[])
744 map<string, cmd_helper> cmdmap;
746 cmdmap["-h"] = parse_help;
747 cmdmap["-help"] = parse_help;
748 cmdmap["--help"] = parse_help;
749 cmdmap["-v"] = parse_version;
750 cmdmap["-version"] = parse_version;
751 cmdmap["--version"] = parse_version;
752 cmdmap["-c"] = parse_class;
753 cmdmap["-m"] = parse_module;
754 cmdmap["-e"] = parse_encoding;
755 cmdmap["-f"] = parse_force;
756 cmdmap["-s"] = parse_syntaxfile;
757 cmdmap["-n"] = parse_noweb;
758 cmdmap["-skipchildren"] = parse_skipchildren;
759 cmdmap["-sysdir"] = parse_sysdir;
760 cmdmap["-userdir"] = parse_userdir;
761 cmdmap["-roundtrip"] = parse_roundtrip;
762 cmdmap["-copyfiles"] = parse_copyfiles;
764 for (int i = 1; i < argc; ++i) {
765 map<string, cmd_helper>::const_iterator it
766 = cmdmap.find(argv[i]);
768 // don't complain if not found - may be parsed later
769 if (it == cmdmap.end()) {
770 if (argv[i][0] == '-')
771 error_message(string("Unknown option `") + argv[i] + "'.");
776 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
777 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
779 int const remove = 1 + it->second(arg, arg2);
781 // Now, remove used arguments by shifting
782 // the following ones remove places down.
783 os::remove_internal_args(i, remove);
785 for (int j = i; j < argc; ++j)
786 argv[j] = argv[j + remove];
792 // path of the first parsed file
793 string masterFilePathLyX;
794 string masterFilePathTeX;
795 // path of the currently parsed file
796 string parentFilePathTeX;
798 } // anonymous namespace
801 string getMasterFilePath(bool input)
803 return input ? masterFilePathTeX : masterFilePathLyX;
806 string getParentFilePath(bool input)
809 return parentFilePathTeX;
810 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
811 from_utf8(parentFilePathTeX)));
812 if (rel.substr(0, 3) == "../") {
813 // The parent is not below the master - keep the path
814 return parentFilePathTeX;
816 return makeAbsPath(rel, masterFilePathLyX).absFileName();
826 bool overwriteFiles()
828 return overwrite_files;
834 return skip_children;
847 * Reads tex input from \a is and writes lyx output to \a os.
848 * Uses some common settings for the preamble, so this should only
849 * be used more than once for included documents.
850 * Caution: Overwrites the existing preamble settings if the new document
851 * contains a preamble.
852 * You must ensure that \p parentFilePathTeX is properly set before calling
855 bool tex2lyx(idocstream & is, ostream & os, string encoding)
857 // Set a sensible default encoding.
858 // This is used until an encoding command is found.
859 // For child documents use the encoding of the master, else ISO8859-1,
860 // (formerly known by its latex name latin1), since ISO8859-1 does not
861 // cause an iconv error if the actual encoding is different (bug 7509).
862 if (encoding.empty()) {
863 if (preamble.inputencoding() == "auto")
864 encoding = "ISO8859-1";
866 Encoding const * const enc = encodings.fromLyXName(
867 preamble.inputencoding(), true);
868 encoding = enc->iconvName();
873 p.setEncoding(encoding);
876 preamble.parse(p, documentclass, textclass);
877 list<string> removed_modules;
878 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
879 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
880 cerr << "Could not load default modules for text class." << endl;
884 // Load preloaded modules.
885 // This needs to be done after the preamble is parsed, since the text
886 // class may not be known before. It neds to be done before parsing
887 // body, since otherwise the commands/environments provided by the
888 // modules would be parsed as ERT.
889 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
890 if (!addModule(preloaded_modules[i])) {
891 cerr << "Error: Could not load module \""
892 << preloaded_modules[i] << "\"." << endl;
896 // Ensure that the modules are not loaded again for included files
897 preloaded_modules.clear();
899 active_environments.push_back("document");
900 Context context(true, textclass);
902 // store the document language in the context to be able to handle the
903 // commands like \foreignlanguage and \textenglish etc.
904 context.font.language = preamble.defaultLanguage();
905 // parse the main text
906 parse_text(p, ss, FLAG_END, true, context);
908 // Empty document body. LyX needs at least one paragraph.
909 context.check_layout(ss);
910 context.check_end_layout(ss);
911 ss << "\n\\end_body\n\\end_document\n";
912 active_environments.pop_back();
914 // We know the used modules only after parsing the full text
915 if (!used_modules.empty()) {
916 LayoutModuleList::const_iterator const end = used_modules.end();
917 LayoutModuleList::const_iterator it = used_modules.begin();
918 for (; it != end; ++it)
919 preamble.addModule(*it);
921 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
922 cerr << "Could not write LyX file header." << endl;
930 ofdocstream parsertest("parsertest.tex");
932 parsertest << p.get_token().asInput();
933 // <origfile> and parsertest.tex should now have identical content
939 /// convert TeX from \p infilename to LyX and write it to \p os
940 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
943 // forbid buffering on this stream
944 is.rdbuf()->pubsetbuf(0,0);
945 is.open(infilename.toFilesystemEncoding().c_str());
947 cerr << "Could not open input file \"" << infilename
948 << "\" for reading." << endl;
951 string const oldParentFilePath = parentFilePathTeX;
952 parentFilePathTeX = onlyPath(infilename.absFileName());
953 bool retval = tex2lyx(is, os, encoding);
954 parentFilePathTeX = oldParentFilePath;
958 } // anonymous namespace
961 bool tex2lyx(string const & infilename, FileName const & outfilename,
962 string const & encoding)
964 if (outfilename.isReadableFile()) {
965 if (overwrite_files) {
966 cerr << "Overwriting existing file "
967 << outfilename << endl;
969 cerr << "Not overwriting existing file "
970 << outfilename << endl;
974 cerr << "Creating file " << outfilename << endl;
976 ofstream os(outfilename.toFilesystemEncoding().c_str());
978 cerr << "Could not open output file \"" << outfilename
979 << "\" for writing." << endl;
983 cerr << "Input file: " << infilename << "\n";
984 cerr << "Output file: " << outfilename << "\n";
986 return tex2lyx(FileName(infilename), os, encoding);
990 bool tex2tex(string const & infilename, FileName const & outfilename,
991 string const & encoding)
993 if (!tex2lyx(infilename, outfilename, encoding))
995 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
997 command += " -f main";
999 command += " -f none";
1001 command += " -e pdflatex ";
1003 command += " -e xetex ";
1005 command += " -e latex ";
1006 command += quoteName(outfilename.toFilesystemEncoding());
1008 if (one.startscript(Systemcall::Wait, command) == 0)
1010 cerr << "Error: Running '" << command << "' failed." << endl;
1017 int main(int argc, char * argv[])
1019 using namespace lyx;
1021 //setlocale(LC_CTYPE, "");
1023 lyxerr.setStream(cerr);
1025 os::init(argc, argv);
1028 init_package(internal_path(os::utf8_argv(0)), string(), string());
1029 } catch (ExceptionMessage const & message) {
1030 cerr << to_utf8(message.title_) << ":\n"
1031 << to_utf8(message.details_) << endl;
1032 if (message.type_ == ErrorException)
1033 return EXIT_FAILURE;
1036 easyParse(argc, argv);
1039 error_message("Not enough arguments.");
1042 init_package(internal_path(os::utf8_argv(0)),
1043 cl_system_support, cl_user_support);
1044 } catch (ExceptionMessage const & message) {
1045 cerr << to_utf8(message.title_) << ":\n"
1046 << to_utf8(message.details_) << endl;
1047 if (message.type_ == ErrorException)
1048 return EXIT_FAILURE;
1051 // Now every known option is parsed. Look for input and output
1052 // file name (the latter is optional).
1053 string infilename = internal_path(os::utf8_argv(1));
1054 infilename = makeAbsPath(infilename).absFileName();
1058 outfilename = internal_path(os::utf8_argv(2));
1059 if (outfilename != "-")
1060 outfilename = makeAbsPath(outfilename).absFileName();
1062 if (outfilename == "-") {
1063 cerr << "Error: Writing to standard output is "
1064 "not supported in roundtrip mode."
1066 return EXIT_FAILURE;
1068 string texfilename = changeExtension(outfilename, ".tex");
1069 if (equivalent(FileName(infilename), FileName(texfilename))) {
1070 cerr << "Error: The input file `" << infilename
1071 << "´ would be overwritten by the TeX file exported from `"
1072 << outfilename << "´ in roundtrip mode." << endl;
1073 return EXIT_FAILURE;
1076 } else if (roundtrip) {
1077 // avoid overwriting the input file
1078 outfilename = changeExtension(infilename, ".lyx.lyx");
1080 outfilename = changeExtension(infilename, ".lyx");
1082 // Read the syntax tables
1083 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1084 if (system_syntaxfile.empty()) {
1085 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1086 return EXIT_FAILURE;
1088 read_syntaxfile(system_syntaxfile);
1089 if (!syntaxfile.empty())
1090 read_syntaxfile(makeAbsPath(syntaxfile));
1092 // Read the encodings table.
1093 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1094 if (symbols_path.empty()) {
1095 cerr << "Error: Could not find file \"unicodesymbols\"."
1097 return EXIT_FAILURE;
1099 FileName const enc_path = libFileSearch(string(), "encodings");
1100 if (enc_path.empty()) {
1101 cerr << "Error: Could not find file \"encodings\"."
1103 return EXIT_FAILURE;
1105 encodings.read(enc_path, symbols_path);
1106 if (!default_encoding.empty()) {
1107 Encoding const * const enc = encodings.fromLaTeXName(
1108 default_encoding, Encoding::any, true);
1110 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1111 default_encoding = enc->iconvName();
1115 LayoutFileList::get().read();
1116 //...and the modules
1117 theModuleList.read();
1119 // The real work now.
1120 masterFilePathTeX = onlyPath(infilename);
1121 parentFilePathTeX = masterFilePathTeX;
1122 if (outfilename == "-") {
1123 // assume same directory as input file
1124 masterFilePathLyX = masterFilePathTeX;
1125 if (tex2lyx(FileName(infilename), cout, default_encoding))
1126 return EXIT_SUCCESS;
1128 masterFilePathLyX = onlyPath(outfilename);
1130 FileName const path(masterFilePathLyX);
1131 if (!path.isDirectory()) {
1132 if (!path.createPath()) {
1133 cerr << "Warning: Could not create directory for file `"
1134 << masterFilePathLyX << "´." << endl;
1135 return EXIT_FAILURE;
1140 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1141 return EXIT_SUCCESS;
1143 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
1144 return EXIT_SUCCESS;
1147 return EXIT_FAILURE;