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 "LayoutFile.h"
22 #include "LayoutModuleList.h"
23 #include "ModuleList.h"
25 #include "TextClass.h"
27 #include "support/convert.h"
28 #include "support/ExceptionMessage.h"
29 #include "support/filetools.h"
30 #include "support/lassert.h"
31 #include "support/lstrings.h"
32 #include "support/Messages.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Systemcall.h"
46 using namespace lyx::support;
47 using namespace lyx::support::os;
53 void warning(docstring const & title, docstring const & message,
56 cerr << to_utf8(title) << "\n" << to_utf8(message) << endl;
62 // Dummy texrow support
63 void TexRow::newline()
67 void TexRow::newlines(int)
71 // Dummy LyXRC support
78 // Dummy translation support
80 Messages const & getMessages(std::string const &)
86 Messages const & getGuiMessages()
92 // Keep the linker happy on Windows
97 string const trimSpaceAndEol(string const & a)
99 return trim(a, " \t\n\r");
103 void split(string const & s, vector<string> & result, char delim)
105 //cerr << "split 1: '" << s << "'\n";
108 while (getline(is, t, delim))
110 //cerr << "split 2\n";
114 string join(vector<string> const & input, char const * delim)
117 for (size_t i = 0; i != input.size(); ++i) {
126 char const * const * is_known(string const & str, char const * const * what)
128 for ( ; *what; ++what)
136 // current stack of nested environments
137 vector<string> active_environments;
140 string active_environment()
142 return active_environments.empty() ? string() : active_environments.back();
146 TeX2LyXDocClass textclass;
147 CommandMap known_commands;
148 CommandMap known_environments;
149 CommandMap known_math_environments;
150 FullCommandMap possible_textclass_commands;
151 FullEnvironmentMap possible_textclass_environments;
152 FullCommandMap possible_textclass_theorems;
153 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
156 LayoutModuleList used_modules;
157 vector<string> preloaded_modules;
160 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
162 // We have to handle the following cases:
163 // definition o1 o2 invocation result
164 // \newcommand{\foo}{bar} "" false \foo bar
165 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
166 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
167 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
168 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
169 unsigned int nargs = 0;
170 string const opt1 = rtrim(ltrim(o1, "["), "]");
171 if (isStrUnsignedInt(opt1)) {
172 // The command has arguments
173 nargs = convert<unsigned int>(opt1);
174 if (nargs > 0 && o2) {
175 // The first argument is optional
176 arguments.push_back(optional);
180 for (unsigned int i = 0; i < nargs; ++i)
181 arguments.push_back(required);
185 void add_known_command(string const & command, string const & o1,
186 bool o2, docstring const & definition)
188 vector<ArgumentType> arguments;
189 convertArgs(o1, o2, arguments);
190 known_commands[command] = arguments;
191 if (!definition.empty())
192 possible_textclass_commands[command] =
193 FullCommand(arguments, definition);
197 void add_known_environment(string const & environment, string const & o1,
198 bool o2, docstring const & beg, docstring const &end)
200 vector<ArgumentType> arguments;
201 convertArgs(o1, o2, arguments);
202 known_environments[environment] = arguments;
203 if (!beg.empty() || ! end.empty())
204 possible_textclass_environments[environment] =
205 FullEnvironment(arguments, beg, end);
209 void add_known_theorem(string const & theorem, string const & o1,
210 bool o2, docstring const & definition)
212 vector<ArgumentType> arguments;
213 convertArgs(o1, o2, arguments);
214 if (!definition.empty())
215 possible_textclass_theorems[theorem] =
216 FullCommand(arguments, definition);
220 Layout const * findLayoutWithoutModule(TextClass const & textclass,
221 string const & name, bool command)
223 DocumentClass::const_iterator it = textclass.begin();
224 DocumentClass::const_iterator en = textclass.end();
225 for (; it != en; ++it) {
226 if (it->latexname() == name &&
227 ((command && it->isCommand()) || (!command && it->isEnvironment())))
234 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
235 string const & name, bool command)
237 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
238 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
239 for (; it != en; ++it) {
240 if (it->second.latexname() == name &&
241 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
242 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
243 return &(it->second);
251 typedef map<string, DocumentClassPtr> ModuleMap;
255 bool addModule(string const module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
257 // avoid endless loop for circular dependency
258 vector<string>::const_iterator const vb = visited.begin();
259 vector<string>::const_iterator const ve = visited.end();
260 if (find(vb, ve, module) != ve) {
261 cerr << "Circular dependency detected for module " << module << '\n';
264 LyXModule const * const lm = theModuleList[module];
266 cerr << "Could not find module " << module << " in module list.\n";
269 bool foundone = false;
270 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
271 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
272 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
273 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
274 vector<string> const reqs = lm->getRequiredModules();
278 LayoutModuleList::const_iterator mit = m.begin();
279 LayoutModuleList::const_iterator men = m.end();
280 vector<string>::const_iterator rit = reqs.begin();
281 vector<string>::const_iterator ren = reqs.end();
282 for (; rit != ren; ++rit) {
283 if (find(mit, men, *rit) != men) {
287 if (find(provmodstart, provmodend, *rit) != provmodend) {
293 visited.push_back(module);
294 for (rit = reqs.begin(); rit != ren; ++rit) {
295 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
296 if (addModule(*rit, baseClass, m, visited)) {
306 cerr << "Could not add required modules for " << module << ".\n";
309 if (!m.moduleCanBeAdded(module, &baseClass))
318 // Create list of dummy document classes if not already done.
319 // This is needed since a module cannot be read on its own, only as
320 // part of a document class.
321 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
322 static bool init = true;
325 LyXModuleList::const_iterator const end = theModuleList.end();
326 LyXModuleList::const_iterator it = theModuleList.begin();
327 for (; it != end; ++it) {
328 string const module = it->getID();
331 if (!addModule(module, baseClass, m, v))
333 modules[module] = getDocumentClass(baseClass, m);
340 bool addModule(string const & module)
343 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
344 if (!used_modules.moduleCanBeAdded(module, &baseClass))
346 FileName layout_file = libFileSearch("layouts", module, "module");
347 if (textclass.read(layout_file, TextClass::MODULE)) {
348 used_modules.push_back(module);
349 // speed up further searches:
350 // the module does not need to be checked anymore.
351 ModuleMap::iterator const it = modules.find(module);
352 if (it != modules.end())
362 bool checkModule(string const & name, bool command)
364 // Cache to avoid slowdown by repated searches
365 static set<string> failed[2];
367 // Only add the module if the command was actually defined in the LyX preamble
368 bool theorem = false;
370 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
373 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
374 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
380 if (failed[command].find(name) != failed[command].end())
384 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
386 // Try to find a module that defines the command.
387 // Only add it if the definition can be found in the preamble of the
388 // style that corresponds to the command. This is a heuristic and
389 // different from the way how we parse the builtin commands of the
390 // text class (in that case we only compare the name), but it is
391 // needed since it is not unlikely that two different modules define a
392 // command with the same name.
393 ModuleMap::iterator const end = modules.end();
394 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
395 string const module = it->first;
396 if (used_modules.moduleConflicts(module, &baseClass))
398 if (findLayoutWithoutModule(textclass, name, command))
400 if (findInsetLayoutWithoutModule(textclass, name, command))
402 DocumentClassConstPtr c = it->second;
403 Layout const * layout = findLayoutWithoutModule(*c, name, command);
404 InsetLayout const * insetlayout = layout ? 0 :
405 findInsetLayoutWithoutModule(*c, name, command);
408 preamble = layout->preamble();
409 else if (insetlayout)
410 preamble = insetlayout->preamble();
411 if (preamble.empty())
415 FullCommand const & cmd =
416 possible_textclass_commands['\\' + name];
417 if (preamble.find(cmd.def) != docstring::npos)
419 } else if (theorem) {
420 FullCommand const & thm =
421 possible_textclass_theorems[name];
422 if (preamble.find(thm.def) != docstring::npos)
425 FullEnvironment const & env =
426 possible_textclass_environments[name];
427 if (preamble.find(env.beg) != docstring::npos &&
428 preamble.find(env.end) != docstring::npos)
432 FileName layout_file = libFileSearch("layouts", module, "module");
433 if (textclass.read(layout_file, TextClass::MODULE)) {
434 used_modules.push_back(module);
435 // speed up further searches:
436 // the module does not need to be checked anymore.
442 failed[command].insert(name);
447 bool isProvided(string const & name)
449 // This works only for features that are named like the LaTeX packages
450 return textclass.provides(name) || preamble.isPackageUsed(name);
454 bool noweb_mode = false;
455 bool pdflatex = false;
457 bool is_nonCJKJapanese = false;
458 bool roundtrip = false;
465 * Read one command definition from the syntax file
467 void read_command(Parser & p, string command, CommandMap & commands)
469 if (p.next_token().asInput() == "*") {
473 vector<ArgumentType> arguments;
474 while (p.next_token().cat() == catBegin ||
475 p.next_token().asInput() == "[") {
476 if (p.next_token().cat() == catBegin) {
477 string const arg = p.getArg('{', '}');
478 if (arg == "translate")
479 arguments.push_back(required);
480 else if (arg == "group")
481 arguments.push_back(req_group);
482 else if (arg == "item")
483 arguments.push_back(item);
484 else if (arg == "displaymath")
485 arguments.push_back(displaymath);
487 arguments.push_back(verbatim);
489 string const arg = p.getArg('[', ']');
491 arguments.push_back(opt_group);
493 arguments.push_back(optional);
496 commands[command] = arguments;
501 * Read a class of environments from the syntax file
503 void read_environment(Parser & p, string const & begin,
504 CommandMap & environments)
508 Token const & t = p.get_token();
509 if (t.cat() == catLetter)
510 environment += t.asInput();
511 else if (!environment.empty()) {
513 read_command(p, environment, environments);
516 if (t.cat() == catEscape && t.asInput() == "\\end") {
517 string const end = p.getArg('{', '}');
526 * Read a list of TeX commands from a reLyX compatible syntax file.
527 * Since this list is used after all commands that have a LyX counterpart
528 * are handled, it does not matter that the "syntax.default" file
529 * has almost all of them listed. For the same reason the reLyX-specific
530 * reLyXre environment is ignored.
532 void read_syntaxfile(FileName const & file_name)
534 ifdocstream is(file_name.toFilesystemEncoding().c_str());
536 cerr << "Could not open syntax file \"" << file_name
537 << "\" for reading." << endl;
540 // We can use our TeX parser, since the syntax of the layout file is
541 // modeled after TeX.
542 // Unknown tokens are just silently ignored, this helps us to skip some
543 // reLyX specific things.
546 Token const & t = p.get_token();
547 if (t.cat() == catEscape) {
548 string const command = t.asInput();
549 if (command == "\\begin") {
550 string const name = p.getArg('{', '}');
551 if (name == "environments" || name == "reLyXre")
552 // We understand "reLyXre", but it is
553 // not as powerful as "environments".
554 read_environment(p, name,
556 else if (name == "mathenvironments")
557 read_environment(p, name,
558 known_math_environments);
560 read_command(p, command, known_commands);
567 string documentclass;
568 string default_encoding;
570 bool copy_files = false;
571 bool overwrite_files = false;
572 bool skip_children = false;
575 /// return the number of arguments consumed
576 typedef int (*cmd_helper)(string const &, string const &);
579 int parse_help(string const &, string const &)
581 cerr << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
583 "\t-c textclass Declare the textclass.\n"
584 "\t-m mod1[,mod2...] Load the given modules.\n"
585 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
586 "\t-e encoding Set the default encoding (latex name).\n"
587 "\t-f Force overwrite of .lyx files.\n"
588 "\t-help Print this message and quit.\n"
589 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
590 "\t-skipchildren Do not translate included child documents.\n"
591 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
592 "\t-s syntaxfile read additional syntax file.\n"
593 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
594 "\t Default: " << package().system_support() << "\n"
595 "\t-userdir USERDIR Set user directory to USERDIR.\n"
596 "\t Default: " << package().user_support() << "\n"
597 "\t-version Summarize version and build info.\n"
599 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
600 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
601 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
602 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
603 "Check the tex2lyx man page for more details."
609 int parse_version(string const &, string const &)
611 lyxerr << "tex2lyx " << lyx_version
612 << " (" << lyx_release_date << ")" << endl;
613 lyxerr << "Built on " << __DATE__ << ", " << __TIME__ << endl;
615 lyxerr << lyx_version_info << endl;
620 void error_message(string const & message)
622 cerr << "tex2lyx: " << message << "\n\n";
624 parse_help(string(), string());
628 int parse_class(string const & arg, string const &)
631 error_message("Missing textclass string after -c switch");
637 int parse_module(string const & arg, string const &)
640 error_message("Missing modules string after -m switch");
641 split(arg, preloaded_modules, ',');
646 int parse_encoding(string const & arg, string const &)
649 error_message("Missing encoding string after -e switch");
650 default_encoding = arg;
655 int parse_syntaxfile(string const & arg, string const &)
658 error_message("Missing syntaxfile string after -s switch");
659 syntaxfile = internal_path(arg);
664 // Filled with the command line arguments "foo" of "-sysdir foo" or
666 string cl_system_support;
667 string cl_user_support;
670 int parse_sysdir(string const & arg, string const &)
673 error_message("Missing directory for -sysdir switch");
674 cl_system_support = internal_path(arg);
679 int parse_userdir(string const & arg, string const &)
682 error_message("Missing directory for -userdir switch");
683 cl_user_support = internal_path(arg);
688 int parse_force(string const &, string const &)
690 overwrite_files = true;
695 int parse_noweb(string const &, string const &)
702 int parse_skipchildren(string const &, string const &)
704 skip_children = true;
709 int parse_roundtrip(string const &, string const &)
716 int parse_copyfiles(string const &, string const &)
723 void easyParse(int & argc, char * argv[])
725 map<string, cmd_helper> cmdmap;
727 cmdmap["-h"] = parse_help;
728 cmdmap["-help"] = parse_help;
729 cmdmap["--help"] = parse_help;
730 cmdmap["-v"] = parse_version;
731 cmdmap["-version"] = parse_version;
732 cmdmap["--version"] = parse_version;
733 cmdmap["-c"] = parse_class;
734 cmdmap["-m"] = parse_module;
735 cmdmap["-e"] = parse_encoding;
736 cmdmap["-f"] = parse_force;
737 cmdmap["-s"] = parse_syntaxfile;
738 cmdmap["-n"] = parse_noweb;
739 cmdmap["-skipchildren"] = parse_skipchildren;
740 cmdmap["-sysdir"] = parse_sysdir;
741 cmdmap["-userdir"] = parse_userdir;
742 cmdmap["-roundtrip"] = parse_roundtrip;
743 cmdmap["-copyfiles"] = parse_copyfiles;
745 for (int i = 1; i < argc; ++i) {
746 map<string, cmd_helper>::const_iterator it
747 = cmdmap.find(argv[i]);
749 // don't complain if not found - may be parsed later
750 if (it == cmdmap.end()) {
751 if (argv[i][0] == '-')
752 error_message(string("Unknown option `") + argv[i] + "'.");
757 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
758 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
760 int const remove = 1 + it->second(arg, arg2);
762 // Now, remove used arguments by shifting
763 // the following ones remove places down.
764 os::remove_internal_args(i, remove);
766 for (int j = i; j < argc; ++j)
767 argv[j] = argv[j + remove];
773 // path of the first parsed file
774 string masterFilePathLyX;
775 string masterFilePathTeX;
776 // path of the currently parsed file
777 string parentFilePathTeX;
779 } // anonymous namespace
782 string getMasterFilePath(bool input)
784 return input ? masterFilePathTeX : masterFilePathLyX;
787 string getParentFilePath(bool input)
790 return parentFilePathTeX;
791 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
792 from_utf8(parentFilePathTeX)));
793 if (rel.substr(0, 3) == "../") {
794 // The parent is not below the master - keep the path
795 return parentFilePathTeX;
797 return makeAbsPath(rel, masterFilePathLyX).absFileName();
807 bool overwriteFiles()
809 return overwrite_files;
815 return skip_children;
828 * Reads tex input from \a is and writes lyx output to \a os.
829 * Uses some common settings for the preamble, so this should only
830 * be used more than once for included documents.
831 * Caution: Overwrites the existing preamble settings if the new document
832 * contains a preamble.
833 * You must ensure that \p parentFilePathTeX is properly set before calling
836 bool tex2lyx(idocstream & is, ostream & os, string encoding)
838 // Set a sensible default encoding.
839 // This is used until an encoding command is found.
840 // For child documents use the encoding of the master, else ISO8859-1,
841 // (formerly known by its latex name latin1), since ISO8859-1 does not
842 // cause an iconv error if the actual encoding is different (bug 7509).
843 if (encoding.empty()) {
844 if (preamble.inputencoding() == "auto")
845 encoding = "ISO8859-1";
847 Encoding const * const enc = encodings.fromLyXName(
848 preamble.inputencoding(), true);
849 encoding = enc->iconvName();
854 p.setEncoding(encoding);
857 preamble.parse(p, documentclass, textclass);
858 list<string> removed_modules;
859 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
860 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
861 cerr << "Could not load default modules for text class." << endl;
865 // Load preloaded modules.
866 // This needs to be done after the preamble is parsed, since the text
867 // class may not be known before. It neds to be done before parsing
868 // body, since otherwise the commands/environments provided by the
869 // modules would be parsed as ERT.
870 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
871 if (!addModule(preloaded_modules[i])) {
872 cerr << "Error: Could not load module \""
873 << preloaded_modules[i] << "\"." << endl;
877 // Ensure that the modules are not loaded again for included files
878 preloaded_modules.clear();
880 active_environments.push_back("document");
881 Context context(true, textclass);
883 // store the document language in the context to be able to handle the
884 // commands like \foreignlanguage and \textenglish etc.
885 context.font.language = preamble.defaultLanguage();
886 // parse the main text
887 parse_text(p, ss, FLAG_END, true, context);
889 // Empty document body. LyX needs at least one paragraph.
890 context.check_layout(ss);
891 context.check_end_layout(ss);
892 ss << "\n\\end_body\n\\end_document\n";
893 active_environments.pop_back();
895 // We know the used modules only after parsing the full text
896 if (!used_modules.empty()) {
897 LayoutModuleList::const_iterator const end = used_modules.end();
898 LayoutModuleList::const_iterator it = used_modules.begin();
899 for (; it != end; ++it)
900 preamble.addModule(*it);
902 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
903 cerr << "Could not write LyX file header." << endl;
911 ofdocstream parsertest("parsertest.tex");
913 parsertest << p.get_token().asInput();
914 // <origfile> and parsertest.tex should now have identical content
920 /// convert TeX from \p infilename to LyX and write it to \p os
921 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
924 // forbid buffering on this stream
925 is.rdbuf()->pubsetbuf(0,0);
926 is.open(infilename.toFilesystemEncoding().c_str());
928 cerr << "Could not open input file \"" << infilename
929 << "\" for reading." << endl;
932 string const oldParentFilePath = parentFilePathTeX;
933 parentFilePathTeX = onlyPath(infilename.absFileName());
934 bool retval = tex2lyx(is, os, encoding);
935 parentFilePathTeX = oldParentFilePath;
939 } // anonymous namespace
942 bool tex2lyx(string const & infilename, FileName const & outfilename,
943 string const & encoding)
945 if (outfilename.isReadableFile()) {
946 if (overwrite_files) {
947 cerr << "Overwriting existing file "
948 << outfilename << endl;
950 cerr << "Not overwriting existing file "
951 << outfilename << endl;
955 cerr << "Creating file " << outfilename << endl;
957 ofstream os(outfilename.toFilesystemEncoding().c_str());
959 cerr << "Could not open output file \"" << outfilename
960 << "\" for writing." << endl;
964 cerr << "Input file: " << infilename << "\n";
965 cerr << "Output file: " << outfilename << "\n";
967 return tex2lyx(FileName(infilename), os, encoding);
971 bool tex2tex(string const & infilename, FileName const & outfilename,
972 string const & encoding)
974 if (!tex2lyx(infilename, outfilename, encoding))
976 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
978 command += " -f main";
980 command += " -f none";
982 command += " -e pdflatex ";
984 command += " -e xetex ";
986 command += " -e latex ";
987 command += quoteName(outfilename.toFilesystemEncoding());
989 if (one.startscript(Systemcall::Wait, command) == 0)
991 cerr << "Error: Running '" << command << "' failed." << endl;
998 int main(int argc, char * argv[])
1000 using namespace lyx;
1002 //setlocale(LC_CTYPE, "");
1004 lyxerr.setStream(cerr);
1006 os::init(argc, argv);
1009 init_package(internal_path(os::utf8_argv(0)), string(), string());
1010 } catch (ExceptionMessage const & message) {
1011 cerr << to_utf8(message.title_) << ":\n"
1012 << to_utf8(message.details_) << endl;
1013 if (message.type_ == ErrorException)
1014 return EXIT_FAILURE;
1017 easyParse(argc, argv);
1020 error_message("Not enough arguments.");
1023 init_package(internal_path(os::utf8_argv(0)),
1024 cl_system_support, cl_user_support);
1025 } catch (ExceptionMessage const & message) {
1026 cerr << to_utf8(message.title_) << ":\n"
1027 << to_utf8(message.details_) << endl;
1028 if (message.type_ == ErrorException)
1029 return EXIT_FAILURE;
1032 // Now every known option is parsed. Look for input and output
1033 // file name (the latter is optional).
1034 string infilename = internal_path(os::utf8_argv(1));
1035 infilename = makeAbsPath(infilename).absFileName();
1039 outfilename = internal_path(os::utf8_argv(2));
1040 if (outfilename != "-")
1041 outfilename = makeAbsPath(outfilename).absFileName();
1043 if (outfilename == "-") {
1044 cerr << "Error: Writing to standard output is "
1045 "not supported in roundtrip mode."
1047 return EXIT_FAILURE;
1049 string texfilename = changeExtension(outfilename, ".tex");
1050 if (equivalent(FileName(infilename), FileName(texfilename))) {
1051 cerr << "Error: The input file `" << infilename
1052 << "´ would be overwritten by the TeX file exported from `"
1053 << outfilename << "´ in roundtrip mode." << endl;
1054 return EXIT_FAILURE;
1057 } else if (roundtrip) {
1058 // avoid overwriting the input file
1059 outfilename = changeExtension(infilename, ".lyx.lyx");
1061 outfilename = changeExtension(infilename, ".lyx");
1063 // Read the syntax tables
1064 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1065 if (system_syntaxfile.empty()) {
1066 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1067 return EXIT_FAILURE;
1069 read_syntaxfile(system_syntaxfile);
1070 if (!syntaxfile.empty())
1071 read_syntaxfile(makeAbsPath(syntaxfile));
1073 // Read the encodings table.
1074 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1075 if (symbols_path.empty()) {
1076 cerr << "Error: Could not find file \"unicodesymbols\"."
1078 return EXIT_FAILURE;
1080 FileName const enc_path = libFileSearch(string(), "encodings");
1081 if (enc_path.empty()) {
1082 cerr << "Error: Could not find file \"encodings\"."
1084 return EXIT_FAILURE;
1086 encodings.read(enc_path, symbols_path);
1087 if (!default_encoding.empty()) {
1088 Encoding const * const enc = encodings.fromLaTeXName(
1089 default_encoding, Encoding::any, true);
1091 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1092 default_encoding = enc->iconvName();
1096 LayoutFileList::get().read();
1097 //...and the modules
1098 theModuleList.read();
1100 // The real work now.
1101 masterFilePathTeX = onlyPath(infilename);
1102 parentFilePathTeX = masterFilePathTeX;
1103 if (outfilename == "-") {
1104 // assume same directory as input file
1105 masterFilePathLyX = masterFilePathTeX;
1106 if (tex2lyx(FileName(infilename), cout, default_encoding))
1107 return EXIT_SUCCESS;
1109 masterFilePathLyX = onlyPath(outfilename);
1111 FileName const path(masterFilePathLyX);
1112 if (!path.isDirectory()) {
1113 if (!path.createPath()) {
1114 cerr << "Warning: Could not create directory for file `"
1115 << masterFilePathLyX << "´." << endl;
1116 return EXIT_FAILURE;
1121 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1122 return EXIT_SUCCESS;
1124 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
1125 return EXIT_SUCCESS;
1128 return EXIT_FAILURE;