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/ConsoleApplication.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/os.h"
34 #include "support/Package.h"
35 #include "support/Systemcall.h"
47 using namespace lyx::support;
48 using namespace lyx::support::os;
52 string const trimSpaceAndEol(string const & a)
54 return trim(a, " \t\n\r");
58 void split(string const & s, vector<string> & result, char delim)
60 //cerr << "split 1: '" << s << "'\n";
63 while (getline(is, t, delim))
65 //cerr << "split 2\n";
69 string join(vector<string> const & input, char const * delim)
72 for (size_t i = 0; i != input.size(); ++i) {
81 char const * const * is_known(string const & str, char const * const * what)
83 for ( ; *what; ++what)
91 // current stack of nested environments
92 vector<string> active_environments;
95 string active_environment()
97 return active_environments.empty() ? string() : active_environments.back();
101 TeX2LyXDocClass textclass;
102 CommandMap known_commands;
103 CommandMap known_environments;
104 CommandMap known_math_environments;
105 FullCommandMap possible_textclass_commands;
106 FullEnvironmentMap possible_textclass_environments;
107 FullCommandMap possible_textclass_theorems;
108 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
111 LayoutModuleList used_modules;
112 vector<string> preloaded_modules;
115 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
117 // We have to handle the following cases:
118 // definition o1 o2 invocation result
119 // \newcommand{\foo}{bar} "" false \foo bar
120 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
121 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
122 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
123 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
124 unsigned int nargs = 0;
125 string const opt1 = rtrim(ltrim(o1, "["), "]");
126 if (isStrUnsignedInt(opt1)) {
127 // The command has arguments
128 nargs = convert<unsigned int>(opt1);
129 if (nargs > 0 && o2) {
130 // The first argument is optional
131 arguments.push_back(optional);
135 for (unsigned int i = 0; i < nargs; ++i)
136 arguments.push_back(required);
140 void add_known_command(string const & command, string const & o1,
141 bool o2, docstring const & definition)
143 vector<ArgumentType> arguments;
144 convertArgs(o1, o2, arguments);
145 known_commands[command] = arguments;
146 if (!definition.empty())
147 possible_textclass_commands[command] =
148 FullCommand(arguments, definition);
152 void add_known_environment(string const & environment, string const & o1,
153 bool o2, docstring const & beg, docstring const &end)
155 vector<ArgumentType> arguments;
156 convertArgs(o1, o2, arguments);
157 known_environments[environment] = arguments;
158 if (!beg.empty() || ! end.empty())
159 possible_textclass_environments[environment] =
160 FullEnvironment(arguments, beg, end);
164 void add_known_theorem(string const & theorem, string const & o1,
165 bool o2, docstring const & definition)
167 vector<ArgumentType> arguments;
168 convertArgs(o1, o2, arguments);
169 if (!definition.empty())
170 possible_textclass_theorems[theorem] =
171 FullCommand(arguments, definition);
175 Layout const * findLayoutWithoutModule(TextClass const & textclass,
176 string const & name, bool command)
178 DocumentClass::const_iterator it = textclass.begin();
179 DocumentClass::const_iterator en = textclass.end();
180 for (; it != en; ++it) {
181 if (it->latexname() == name &&
182 ((command && it->isCommand()) || (!command && it->isEnvironment())))
189 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
190 string const & name, bool command)
192 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
193 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
194 for (; it != en; ++it) {
195 if (it->second.latexname() == name &&
196 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
197 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
198 return &(it->second);
206 typedef map<string, DocumentClassPtr> ModuleMap;
210 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
212 // avoid endless loop for circular dependency
213 vector<string>::const_iterator const vb = visited.begin();
214 vector<string>::const_iterator const ve = visited.end();
215 if (find(vb, ve, module) != ve) {
216 cerr << "Circular dependency detected for module " << module << '\n';
219 LyXModule const * const lm = theModuleList[module];
221 cerr << "Could not find module " << module << " in module list.\n";
224 bool foundone = false;
225 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
226 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
227 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
228 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
229 vector<string> const reqs = lm->getRequiredModules();
233 LayoutModuleList::const_iterator mit = m.begin();
234 LayoutModuleList::const_iterator men = m.end();
235 vector<string>::const_iterator rit = reqs.begin();
236 vector<string>::const_iterator ren = reqs.end();
237 for (; rit != ren; ++rit) {
238 if (find(mit, men, *rit) != men) {
242 if (find(provmodstart, provmodend, *rit) != provmodend) {
248 visited.push_back(module);
249 for (rit = reqs.begin(); rit != ren; ++rit) {
250 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
251 if (addModule(*rit, baseClass, m, visited)) {
261 cerr << "Could not add required modules for " << module << ".\n";
264 if (!m.moduleCanBeAdded(module, &baseClass))
273 // Create list of dummy document classes if not already done.
274 // This is needed since a module cannot be read on its own, only as
275 // part of a document class.
276 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
277 static bool init = true;
280 LyXModuleList::const_iterator const end = theModuleList.end();
281 LyXModuleList::const_iterator it = theModuleList.begin();
282 for (; it != end; ++it) {
283 string const module = it->getID();
286 if (!addModule(module, baseClass, m, v))
288 modules[module] = getDocumentClass(baseClass, m);
295 bool addModule(string const & module)
298 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
299 if (!used_modules.moduleCanBeAdded(module, &baseClass))
301 FileName layout_file = libFileSearch("layouts", module, "module");
302 if (textclass.read(layout_file, TextClass::MODULE)) {
303 used_modules.push_back(module);
304 // speed up further searches:
305 // the module does not need to be checked anymore.
306 ModuleMap::iterator const it = modules.find(module);
307 if (it != modules.end())
317 bool checkModule(string const & name, bool command)
319 // Cache to avoid slowdown by repated searches
320 static set<string> failed[2];
322 // Only add the module if the command was actually defined in the LyX preamble
323 bool theorem = false;
325 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
328 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
329 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
335 if (failed[command].find(name) != failed[command].end())
339 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
341 // Try to find a module that defines the command.
342 // Only add it if the definition can be found in the preamble of the
343 // style that corresponds to the command. This is a heuristic and
344 // different from the way how we parse the builtin commands of the
345 // text class (in that case we only compare the name), but it is
346 // needed since it is not unlikely that two different modules define a
347 // command with the same name.
348 ModuleMap::iterator const end = modules.end();
349 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
350 string const module = it->first;
351 if (used_modules.moduleConflicts(module, &baseClass))
353 if (findLayoutWithoutModule(textclass, name, command))
355 if (findInsetLayoutWithoutModule(textclass, name, command))
357 DocumentClassConstPtr c = it->second;
358 Layout const * layout = findLayoutWithoutModule(*c, name, command);
359 InsetLayout const * insetlayout = layout ? 0 :
360 findInsetLayoutWithoutModule(*c, name, command);
363 preamble = layout->preamble();
364 else if (insetlayout)
365 preamble = insetlayout->preamble();
366 if (preamble.empty())
370 FullCommand const & cmd =
371 possible_textclass_commands['\\' + name];
372 if (preamble.find(cmd.def) != docstring::npos)
374 } else if (theorem) {
375 FullCommand const & thm =
376 possible_textclass_theorems[name];
377 if (preamble.find(thm.def) != docstring::npos)
380 FullEnvironment const & env =
381 possible_textclass_environments[name];
382 if (preamble.find(env.beg) != docstring::npos &&
383 preamble.find(env.end) != docstring::npos)
387 FileName layout_file = libFileSearch("layouts", module, "module");
388 if (textclass.read(layout_file, TextClass::MODULE)) {
389 used_modules.push_back(module);
390 // speed up further searches:
391 // the module does not need to be checked anymore.
397 failed[command].insert(name);
402 bool isProvided(string const & name)
404 // This works only for features that are named like the LaTeX packages
405 return textclass.provides(name) || preamble.isPackageUsed(name);
409 bool noweb_mode = false;
410 bool pdflatex = false;
412 bool is_nonCJKJapanese = false;
413 bool roundtrip = false;
420 * Read one command definition from the syntax file
422 void read_command(Parser & p, string command, CommandMap & commands)
424 if (p.next_token().asInput() == "*") {
428 vector<ArgumentType> arguments;
429 while (p.next_token().cat() == catBegin ||
430 p.next_token().asInput() == "[") {
431 if (p.next_token().cat() == catBegin) {
432 string const arg = p.getArg('{', '}');
433 if (arg == "translate")
434 arguments.push_back(required);
435 else if (arg == "group")
436 arguments.push_back(req_group);
437 else if (arg == "item")
438 arguments.push_back(item);
439 else if (arg == "displaymath")
440 arguments.push_back(displaymath);
442 arguments.push_back(verbatim);
444 string const arg = p.getArg('[', ']');
446 arguments.push_back(opt_group);
448 arguments.push_back(optional);
451 commands[command] = arguments;
456 * Read a class of environments from the syntax file
458 void read_environment(Parser & p, string const & begin,
459 CommandMap & environments)
463 Token const & t = p.get_token();
464 if (t.cat() == catLetter)
465 environment += t.asInput();
466 else if (!environment.empty()) {
468 read_command(p, environment, environments);
471 if (t.cat() == catEscape && t.asInput() == "\\end") {
472 string const end = p.getArg('{', '}');
481 * Read a list of TeX commands from a reLyX compatible syntax file.
482 * Since this list is used after all commands that have a LyX counterpart
483 * are handled, it does not matter that the "syntax.default" file
484 * has almost all of them listed. For the same reason the reLyX-specific
485 * reLyXre environment is ignored.
487 bool read_syntaxfile(FileName const & file_name)
489 ifdocstream is(file_name.toFilesystemEncoding().c_str());
491 cerr << "Could not open syntax file \"" << file_name
492 << "\" for reading." << endl;
495 // We can use our TeX parser, since the syntax of the layout file is
496 // modeled after TeX.
497 // Unknown tokens are just silently ignored, this helps us to skip some
498 // reLyX specific things.
499 Parser p(is, string());
501 Token const & t = p.get_token();
502 if (t.cat() == catEscape) {
503 string const command = t.asInput();
504 if (command == "\\begin") {
505 string const name = p.getArg('{', '}');
506 if (name == "environments" || name == "reLyXre")
507 // We understand "reLyXre", but it is
508 // not as powerful as "environments".
509 read_environment(p, name,
511 else if (name == "mathenvironments")
512 read_environment(p, name,
513 known_math_environments);
515 read_command(p, command, known_commands);
523 string documentclass;
524 string default_encoding;
525 bool fixed_encoding = false;
527 bool copy_files = false;
528 bool overwrite_files = false;
529 bool skip_children = false;
532 /// return the number of arguments consumed
533 typedef int (*cmd_helper)(string const &, string const &);
536 class StopException : public exception
539 StopException(int status) : status_(status) {}
540 int status() const { return status_; }
546 /// The main application class
547 class TeX2LyXApp : public ConsoleApplication
550 TeX2LyXApp(int & argc, char * argv[])
551 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
552 argc_(argc), argv_(argv)
558 int const exit_status = run();
561 catch (StopException & e) {
574 int parse_help(string const &, string const &)
576 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
578 "\t-c textclass Declare the textclass.\n"
579 "\t-m mod1[,mod2...] Load the given modules.\n"
580 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
581 "\t-e encoding Set the default encoding (latex name).\n"
582 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
583 "\t-f Force overwrite of .lyx files.\n"
584 "\t-help Print this message and quit.\n"
585 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
586 "\t-skipchildren Do not translate included child documents.\n"
587 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
588 "\t-s syntaxfile read additional syntax file.\n"
589 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
590 "\t Default: " << package().system_support() << "\n"
591 "\t-userdir USERDIR Set user directory to USERDIR.\n"
592 "\t Default: " << package().user_support() << "\n"
593 "\t-version Summarize version and build info.\n"
595 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
596 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
597 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
598 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
599 "Check the tex2lyx man page for more details."
601 throw StopException(error_code);
605 int parse_version(string const &, string const &)
607 cout << "tex2lyx " << lyx_version
608 << " (" << lyx_release_date << ")" << endl;
610 cout << lyx_version_info << endl;
611 throw StopException(error_code);
615 void error_message(string const & message)
617 cerr << "tex2lyx: " << message << "\n\n";
618 error_code = EXIT_FAILURE;
619 parse_help(string(), string());
623 int parse_class(string const & arg, string const &)
626 error_message("Missing textclass string after -c switch");
632 int parse_module(string const & arg, string const &)
635 error_message("Missing modules string after -m switch");
636 split(arg, preloaded_modules, ',');
641 int parse_encoding(string const & arg, string const &)
644 error_message("Missing encoding string after -e switch");
645 default_encoding = arg;
650 int parse_fixed_encoding(string const & arg, string const &)
653 error_message("Missing encoding string after -fixedenc switch");
654 default_encoding = arg;
655 fixed_encoding = true;
660 int parse_syntaxfile(string const & arg, string const &)
663 error_message("Missing syntaxfile string after -s switch");
664 syntaxfile = internal_path(arg);
669 // Filled with the command line arguments "foo" of "-sysdir foo" or
671 string cl_system_support;
672 string cl_user_support;
675 int parse_sysdir(string const & arg, string const &)
678 error_message("Missing directory for -sysdir switch");
679 cl_system_support = internal_path(arg);
684 int parse_userdir(string const & arg, string const &)
687 error_message("Missing directory for -userdir switch");
688 cl_user_support = internal_path(arg);
693 int parse_force(string const &, string const &)
695 overwrite_files = true;
700 int parse_noweb(string const &, string const &)
707 int parse_skipchildren(string const &, string const &)
709 skip_children = true;
714 int parse_roundtrip(string const &, string const &)
721 int parse_copyfiles(string const &, string const &)
728 void TeX2LyXApp::easyParse()
730 map<string, cmd_helper> cmdmap;
732 cmdmap["-h"] = parse_help;
733 cmdmap["-help"] = parse_help;
734 cmdmap["--help"] = parse_help;
735 cmdmap["-v"] = parse_version;
736 cmdmap["-version"] = parse_version;
737 cmdmap["--version"] = parse_version;
738 cmdmap["-c"] = parse_class;
739 cmdmap["-m"] = parse_module;
740 cmdmap["-e"] = parse_encoding;
741 cmdmap["-fixedenc"] = parse_fixed_encoding;
742 cmdmap["-f"] = parse_force;
743 cmdmap["-s"] = parse_syntaxfile;
744 cmdmap["-n"] = parse_noweb;
745 cmdmap["-skipchildren"] = parse_skipchildren;
746 cmdmap["-sysdir"] = parse_sysdir;
747 cmdmap["-userdir"] = parse_userdir;
748 cmdmap["-roundtrip"] = parse_roundtrip;
749 cmdmap["-copyfiles"] = parse_copyfiles;
751 for (int i = 1; i < argc_; ++i) {
752 map<string, cmd_helper>::const_iterator it
753 = cmdmap.find(argv_[i]);
755 // don't complain if not found - may be parsed later
756 if (it == cmdmap.end()) {
757 if (argv_[i][0] == '-')
758 error_message(string("Unknown option `") + argv_[i] + "'.");
763 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
764 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
766 int const remove = 1 + it->second(arg, arg2);
768 // Now, remove used arguments by shifting
769 // the following ones remove places down.
770 os::remove_internal_args(i, remove);
772 for (int j = i; j < argc_; ++j)
773 argv_[j] = argv_[j + remove];
779 // path of the first parsed file
780 string masterFilePathLyX;
781 string masterFilePathTeX;
782 // path of the currently parsed file
783 string parentFilePathTeX;
785 } // anonymous namespace
788 string getMasterFilePath(bool input)
790 return input ? masterFilePathTeX : masterFilePathLyX;
793 string getParentFilePath(bool input)
796 return parentFilePathTeX;
797 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
798 from_utf8(parentFilePathTeX)));
799 if (rel.substr(0, 3) == "../") {
800 // The parent is not below the master - keep the path
801 return parentFilePathTeX;
803 return makeAbsPath(rel, masterFilePathLyX).absFileName();
813 bool overwriteFiles()
815 return overwrite_files;
821 return skip_children;
834 * Reads tex input from \a is and writes lyx output to \a os.
835 * Uses some common settings for the preamble, so this should only
836 * be used more than once for included documents.
837 * Caution: Overwrites the existing preamble settings if the new document
838 * contains a preamble.
839 * You must ensure that \p parentFilePathTeX is properly set before calling
842 bool tex2lyx(idocstream & is, ostream & os, string encoding,
843 string const & outfiledir)
845 // Set a sensible default encoding.
846 // This is used until an encoding command is found.
847 // For child documents use the encoding of the master, else ISO-8859-1,
848 // (formerly known by its latex name latin1), since ISO-8859-1 does not
849 // cause an iconv error if the actual encoding is different (bug 7509).
850 if (encoding.empty()) {
851 if (preamble.inputencoding() == "auto")
852 encoding = "ISO-8859-1";
854 Encoding const * const enc = encodings.fromLyXName(
855 preamble.inputencoding(), true);
856 encoding = enc->iconvName();
860 Parser p(is, fixed_encoding ? default_encoding : string());
861 p.setEncoding(encoding);
864 preamble.parse(p, documentclass, textclass);
865 list<string> removed_modules;
866 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
867 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
868 cerr << "Could not load default modules for text class." << endl;
872 // Load preloaded modules.
873 // This needs to be done after the preamble is parsed, since the text
874 // class may not be known before. It neds to be done before parsing
875 // body, since otherwise the commands/environments provided by the
876 // modules would be parsed as ERT.
877 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
878 if (!addModule(preloaded_modules[i])) {
879 cerr << "Error: Could not load module \""
880 << preloaded_modules[i] << "\"." << endl;
884 // Ensure that the modules are not loaded again for included files
885 preloaded_modules.clear();
887 active_environments.push_back("document");
888 Context context(true, textclass);
890 // store the document language in the context to be able to handle the
891 // commands like \foreignlanguage and \textenglish etc.
892 context.font.language = preamble.defaultLanguage();
893 // parse the main text
894 parse_text(p, ss, FLAG_END, true, context);
896 // Empty document body. LyX needs at least one paragraph.
897 context.check_layout(ss);
898 context.check_end_layout(ss);
899 ss << "\n\\end_body\n\\end_document\n";
900 active_environments.pop_back();
902 // We know the used modules only after parsing the full text
903 if (!used_modules.empty()) {
904 LayoutModuleList::const_iterator const end = used_modules.end();
905 LayoutModuleList::const_iterator it = used_modules.begin();
906 for (; it != end; ++it)
907 preamble.addModule(*it);
909 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
910 cerr << "Could not write LyX file header." << endl;
918 ofdocstream parsertest("parsertest.tex");
920 parsertest << p.get_token().asInput();
921 // <origfile> and parsertest.tex should now have identical content
927 /// convert TeX from \p infilename to LyX and write it to \p os
928 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding,
929 string const & outfiledir)
932 // forbid buffering on this stream
933 is.rdbuf()->pubsetbuf(0,0);
934 is.open(infilename.toFilesystemEncoding().c_str());
936 cerr << "Could not open input file \"" << infilename
937 << "\" for reading." << endl;
940 string const oldParentFilePath = parentFilePathTeX;
941 parentFilePathTeX = onlyPath(infilename.absFileName());
942 bool retval = tex2lyx(is, os, encoding, outfiledir);
943 parentFilePathTeX = oldParentFilePath;
947 } // anonymous namespace
950 bool tex2lyx(string const & infilename, FileName const & outfilename,
951 string const & encoding)
953 if (outfilename.isReadableFile()) {
954 if (overwrite_files) {
955 cerr << "Overwriting existing file "
956 << outfilename << endl;
958 cerr << "Not overwriting existing file "
959 << outfilename << endl;
963 cerr << "Creating file " << outfilename << endl;
965 ofstream os(outfilename.toFilesystemEncoding().c_str());
967 cerr << "Could not open output file \"" << outfilename
968 << "\" for writing." << endl;
972 cerr << "Input file: " << infilename << "\n";
973 cerr << "Output file: " << outfilename << "\n";
975 return tex2lyx(FileName(infilename), os, encoding,
976 outfilename.onlyPath().absFileName() + '/');
980 bool tex2tex(string const & infilename, FileName const & outfilename,
981 string const & encoding)
983 if (!tex2lyx(infilename, outfilename, encoding))
985 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
987 command += " -f main";
989 command += " -f none";
991 command += " -e pdflatex ";
993 command += " -e xetex ";
995 command += " -e latex ";
996 command += quoteName(outfilename.toFilesystemEncoding());
998 if (one.startscript(Systemcall::Wait, command) == 0)
1000 cerr << "Error: Running '" << command << "' failed." << endl;
1007 int TeX2LyXApp::run()
1009 // qt changes this, and our numeric conversions require the C locale
1010 setlocale(LC_NUMERIC, "C");
1013 init_package(internal_path(os::utf8_argv(0)), string(), string());
1014 } catch (ExceptionMessage const & message) {
1015 cerr << to_utf8(message.title_) << ":\n"
1016 << to_utf8(message.details_) << endl;
1017 if (message.type_ == ErrorException)
1018 return EXIT_FAILURE;
1024 error_message("Not enough arguments.");
1027 init_package(internal_path(os::utf8_argv(0)),
1028 cl_system_support, cl_user_support);
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 // Check that user LyX directory is ok.
1037 FileName const sup = package().user_support();
1038 if (sup.exists() && sup.isDirectory()) {
1039 string const lock_file = package().getConfigureLockName();
1040 int fd = fileLock(lock_file.c_str());
1041 if (configFileNeedsUpdate("lyxrc.defaults") ||
1042 configFileNeedsUpdate("lyxmodules.lst") ||
1043 configFileNeedsUpdate("textclass.lst") ||
1044 configFileNeedsUpdate("packages.lst"))
1045 package().reconfigureUserLyXDir("");
1046 fileUnlock(fd, lock_file.c_str());
1048 error_message("User directory does not exist.");
1050 // Now every known option is parsed. Look for input and output
1051 // file name (the latter is optional).
1052 string infilename = internal_path(os::utf8_argv(1));
1053 infilename = makeAbsPath(infilename).absFileName();
1057 outfilename = internal_path(os::utf8_argv(2));
1058 if (outfilename != "-")
1059 outfilename = makeAbsPath(outfilename).absFileName();
1061 if (outfilename == "-") {
1062 cerr << "Error: Writing to standard output is "
1063 "not supported in roundtrip mode."
1065 return EXIT_FAILURE;
1067 string texfilename = changeExtension(outfilename, ".tex");
1068 if (equivalent(FileName(infilename), FileName(texfilename))) {
1069 cerr << "Error: The input file `" << infilename
1070 << "´ would be overwritten by the TeX file exported from `"
1071 << outfilename << "´ in roundtrip mode." << endl;
1072 return EXIT_FAILURE;
1075 } else if (roundtrip) {
1076 // avoid overwriting the input file
1077 outfilename = changeExtension(infilename, ".lyx.lyx");
1079 outfilename = changeExtension(infilename, ".lyx");
1081 // Read the syntax tables
1082 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1083 if (system_syntaxfile.empty()) {
1084 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1085 return EXIT_FAILURE;
1087 if (!read_syntaxfile(system_syntaxfile))
1089 if (!syntaxfile.empty())
1090 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1093 // Read the encodings table.
1094 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1095 if (symbols_path.empty()) {
1096 cerr << "Error: Could not find file \"unicodesymbols\"."
1098 return EXIT_FAILURE;
1100 FileName const enc_path = libFileSearch(string(), "encodings");
1101 if (enc_path.empty()) {
1102 cerr << "Error: Could not find file \"encodings\"."
1104 return EXIT_FAILURE;
1106 encodings.read(enc_path, symbols_path);
1107 if (!default_encoding.empty()) {
1108 Encoding const * const enc = encodings.fromLaTeXName(
1109 default_encoding, Encoding::any, true);
1111 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1112 default_encoding = enc->iconvName();
1114 preamble.setInputencoding(enc->name());
1118 LayoutFileList::get().read();
1119 //...and the modules
1120 theModuleList.read();
1122 // The real work now.
1123 masterFilePathTeX = onlyPath(infilename);
1124 parentFilePathTeX = masterFilePathTeX;
1125 if (outfilename == "-") {
1126 // assume same directory as input file
1127 masterFilePathLyX = masterFilePathTeX;
1128 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1129 return EXIT_SUCCESS;
1131 masterFilePathLyX = onlyPath(outfilename);
1133 FileName const path(masterFilePathLyX);
1134 if (!path.isDirectory()) {
1135 if (!path.createPath()) {
1136 cerr << "Warning: Could not create directory for file `"
1137 << masterFilePathLyX << "´." << endl;
1138 return EXIT_FAILURE;
1143 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1144 return EXIT_SUCCESS;
1146 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1147 return EXIT_SUCCESS;
1150 return EXIT_FAILURE;
1153 } // anonymous namespace
1157 int main(int argc, char * argv[])
1159 //setlocale(LC_CTYPE, "");
1161 lyx::lyxerr.setStream(cerr);
1163 os::init(argc, argv);
1165 lyx::TeX2LyXApp app(argc, argv);