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 & tc,
176 string const & name, bool command)
178 for (auto const & lay : tc) {
179 if (lay.latexname() == name &&
180 ((command && lay.isCommand()) || (!command && lay.isEnvironment())))
187 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & tc,
188 string const & name, bool command)
190 for (auto const & ilay : tc.insetLayouts()) {
191 if (ilay.second.latexname() == name &&
192 ((command && ilay.second.latextype() == InsetLayout::COMMAND) ||
193 (!command && ilay.second.latextype() == InsetLayout::ENVIRONMENT)))
194 return &(ilay.second);
202 typedef map<string, DocumentClassPtr> ModuleMap;
206 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
208 // avoid endless loop for circular dependency
209 vector<string>::const_iterator const vb = visited.begin();
210 vector<string>::const_iterator const ve = visited.end();
211 if (find(vb, ve, module) != ve) {
212 cerr << "Circular dependency detected for module " << module << '\n';
215 LyXModule const * const lm = theModuleList[module];
217 cerr << "Could not find module " << module << " in module list.\n";
220 bool foundone = false;
221 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
222 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
223 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
224 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
225 vector<string> const reqs = lm->getRequiredModules();
229 LayoutModuleList::const_iterator mit = m.begin();
230 LayoutModuleList::const_iterator men = m.end();
231 vector<string>::const_iterator rit = reqs.begin();
232 vector<string>::const_iterator ren = reqs.end();
233 for (; rit != ren; ++rit) {
234 if (find(mit, men, *rit) != men) {
238 if (find(provmodstart, provmodend, *rit) != provmodend) {
244 visited.push_back(module);
245 for (rit = reqs.begin(); rit != ren; ++rit) {
246 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
247 if (addModule(*rit, baseClass, m, visited)) {
257 cerr << "Could not add required modules for " << module << ".\n";
260 if (!m.moduleCanBeAdded(module, &baseClass))
269 // Create list of dummy document classes if not already done.
270 // This is needed since a module cannot be read on its own, only as
271 // part of a document class.
272 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
273 static bool init = true;
276 LyXModuleList::const_iterator const end = theModuleList.end();
277 LyXModuleList::const_iterator it = theModuleList.begin();
278 for (; it != end; ++it) {
279 string const module = it->getID();
283 if (!addModule(module, baseClass, m, v))
285 modules[module] = getDocumentClass(baseClass, m, c);
292 bool addModule(string const & module)
295 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
296 if (!used_modules.moduleCanBeAdded(module, &baseClass))
298 FileName layout_file = libFileSearch("layouts", module, "module");
299 if (textclass.read(layout_file, TextClass::MODULE)) {
300 used_modules.push_back(module);
301 // speed up further searches:
302 // the module does not need to be checked anymore.
303 ModuleMap::iterator const it = modules.find(module);
304 if (it != modules.end())
314 bool checkModule(string const & name, bool command)
316 // Cache to avoid slowdown by repated searches
317 static set<string> failed[2];
319 // Only add the module if the command was actually defined in the LyX preamble
320 bool theorem = false;
322 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
325 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
326 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
332 if (failed[command].find(name) != failed[command].end())
336 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
338 // Try to find a module that defines the command.
339 // Only add it if the definition can be found in the preamble of the
340 // style that corresponds to the command. This is a heuristic and
341 // different from the way how we parse the builtin commands of the
342 // text class (in that case we only compare the name), but it is
343 // needed since it is not unlikely that two different modules define a
344 // command with the same name.
345 ModuleMap::iterator const end = modules.end();
346 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
347 string const module = it->first;
348 if (used_modules.moduleConflicts(module, &baseClass))
350 if (findLayoutWithoutModule(textclass, name, command))
352 if (findInsetLayoutWithoutModule(textclass, name, command))
354 DocumentClassConstPtr c = it->second;
355 Layout const * layout = findLayoutWithoutModule(*c, name, command);
356 InsetLayout const * insetlayout = layout ? 0 :
357 findInsetLayoutWithoutModule(*c, name, command);
360 dpre = layout->preamble();
361 else if (insetlayout)
362 dpre = insetlayout->preamble();
367 FullCommand const & cmd =
368 possible_textclass_commands['\\' + name];
369 if (dpre.find(cmd.def) != docstring::npos)
371 } else if (theorem) {
372 FullCommand const & thm =
373 possible_textclass_theorems[name];
374 if (dpre.find(thm.def) != docstring::npos)
377 FullEnvironment const & env =
378 possible_textclass_environments[name];
379 if (dpre.find(env.beg) != docstring::npos &&
380 dpre.find(env.end) != docstring::npos)
384 FileName layout_file = libFileSearch("layouts", module, "module");
385 if (textclass.read(layout_file, TextClass::MODULE)) {
386 used_modules.push_back(module);
387 // speed up further searches:
388 // the module does not need to be checked anymore.
394 failed[command].insert(name);
399 bool isProvided(string const & name)
401 // This works only for features that are named like the LaTeX packages
402 return textclass.provides(name) || preamble.isPackageUsed(name);
406 bool noweb_mode = false;
407 bool pdflatex = false;
409 bool is_nonCJKJapanese = false;
410 bool roundtrip = false;
417 * Read one command definition from the syntax file
419 void read_command(Parser & p, string command, CommandMap & commands)
421 if (p.next_token().asInput() == "*") {
425 vector<ArgumentType> arguments;
426 while (p.next_token().cat() == catBegin ||
427 p.next_token().asInput() == "[") {
428 if (p.next_token().cat() == catBegin) {
429 string const arg = p.getArg('{', '}');
430 if (arg == "translate")
431 arguments.push_back(required);
432 else if (arg == "group")
433 arguments.push_back(req_group);
434 else if (arg == "item")
435 arguments.push_back(item);
436 else if (arg == "displaymath")
437 arguments.push_back(displaymath);
439 arguments.push_back(verbatim);
441 string const arg = p.getArg('[', ']');
443 arguments.push_back(opt_group);
445 arguments.push_back(optional);
448 commands[command] = arguments;
453 * Read a class of environments from the syntax file
455 void read_environment(Parser & p, string const & begin,
456 CommandMap & environments)
460 Token const & t = p.get_token();
461 if (t.cat() == catLetter)
462 environment += t.asInput();
463 else if (!environment.empty()) {
465 read_command(p, environment, environments);
468 if (t.cat() == catEscape && t.asInput() == "\\end") {
469 string const end = p.getArg('{', '}');
478 * Read a list of TeX commands from a reLyX compatible syntax file.
479 * Since this list is used after all commands that have a LyX counterpart
480 * are handled, it does not matter that the "syntax.default" file
481 * has almost all of them listed. For the same reason the reLyX-specific
482 * reLyXre environment is ignored.
484 bool read_syntaxfile(FileName const & file_name)
486 ifdocstream is(file_name.toFilesystemEncoding().c_str());
488 cerr << "Could not open syntax file \"" << file_name
489 << "\" for reading." << endl;
492 // We can use our TeX parser, since the syntax of the layout file is
493 // modeled after TeX.
494 // Unknown tokens are just silently ignored, this helps us to skip some
495 // reLyX specific things.
496 Parser p(is, string());
498 Token const & t = p.get_token();
499 if (t.cat() == catEscape) {
500 string const command = t.asInput();
501 if (command == "\\begin") {
502 string const name = p.getArg('{', '}');
503 if (name == "environments" || name == "reLyXre")
504 // We understand "reLyXre", but it is
505 // not as powerful as "environments".
506 read_environment(p, name,
508 else if (name == "mathenvironments")
509 read_environment(p, name,
510 known_math_environments);
512 read_command(p, command, known_commands);
520 string documentclass;
521 string default_encoding;
522 bool fixed_encoding = false;
524 bool copy_files = false;
525 bool overwrite_files = false;
526 bool skip_children = false;
529 /// return the number of arguments consumed
530 typedef int (*cmd_helper)(string const &, string const &);
533 class StopException : public exception
536 StopException(int status) : status_(status) {}
537 int status() const { return status_; }
543 /// The main application class
544 class TeX2LyXApp : public ConsoleApplication
547 TeX2LyXApp(int & argc, char * argv[])
548 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
549 argc_(argc), argv_(argv)
555 int const exit_status = run();
558 catch (StopException & e) {
571 int parse_help(string const &, string const &)
573 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
575 "\t-c textclass Declare the textclass.\n"
576 "\t-m mod1[,mod2...] Load the given modules.\n"
577 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
578 "\t-e encoding Set the default encoding (latex name).\n"
579 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
580 "\t-f Force overwrite of .lyx files.\n"
581 "\t-help Print this message and quit.\n"
582 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
583 "\t-skipchildren Do not translate included child documents.\n"
584 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
585 "\t-s syntaxfile read additional syntax file.\n"
586 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
587 "\t Default: " << package().system_support() << "\n"
588 "\t-userdir USERDIR Set user directory to USERDIR.\n"
589 "\t Default: " << package().user_support() << "\n"
590 "\t-version Summarize version and build info.\n"
592 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
593 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
594 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
595 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
596 "Check the tex2lyx man page for more details."
598 throw StopException(error_code);
602 int parse_version(string const &, string const &)
604 cout << "tex2lyx " << lyx_version
605 << " (" << lyx_release_date << ")" << endl;
607 cout << lyx_version_info << endl;
608 throw StopException(error_code);
612 void error_message(string const & message)
614 cerr << "tex2lyx: " << message << "\n\n";
615 error_code = EXIT_FAILURE;
616 parse_help(string(), string());
620 int parse_class(string const & arg, string const &)
623 error_message("Missing textclass string after -c switch");
629 int parse_module(string const & arg, string const &)
632 error_message("Missing modules string after -m switch");
633 split(arg, preloaded_modules, ',');
638 int parse_encoding(string const & arg, string const &)
641 error_message("Missing encoding string after -e switch");
642 default_encoding = arg;
647 int parse_fixed_encoding(string const & arg, string const &)
650 error_message("Missing encoding string after -fixedenc switch");
651 default_encoding = arg;
652 fixed_encoding = true;
657 int parse_syntaxfile(string const & arg, string const &)
660 error_message("Missing syntaxfile string after -s switch");
661 syntaxfile = internal_path(arg);
666 // Filled with the command line arguments "foo" of "-sysdir foo" or
668 string cl_system_support;
669 string cl_user_support;
672 int parse_sysdir(string const & arg, string const &)
675 error_message("Missing directory for -sysdir switch");
676 cl_system_support = internal_path(arg);
681 int parse_userdir(string const & arg, string const &)
684 error_message("Missing directory for -userdir switch");
685 cl_user_support = internal_path(arg);
690 int parse_force(string const &, string const &)
692 overwrite_files = true;
697 int parse_noweb(string const &, string const &)
704 int parse_skipchildren(string const &, string const &)
706 skip_children = true;
711 int parse_roundtrip(string const &, string const &)
718 int parse_copyfiles(string const &, string const &)
725 void TeX2LyXApp::easyParse()
727 map<string, cmd_helper> cmdmap;
729 cmdmap["-h"] = parse_help;
730 cmdmap["-help"] = parse_help;
731 cmdmap["--help"] = parse_help;
732 cmdmap["-v"] = parse_version;
733 cmdmap["-version"] = parse_version;
734 cmdmap["--version"] = parse_version;
735 cmdmap["-c"] = parse_class;
736 cmdmap["-m"] = parse_module;
737 cmdmap["-e"] = parse_encoding;
738 cmdmap["-fixedenc"] = parse_fixed_encoding;
739 cmdmap["-f"] = parse_force;
740 cmdmap["-s"] = parse_syntaxfile;
741 cmdmap["-n"] = parse_noweb;
742 cmdmap["-skipchildren"] = parse_skipchildren;
743 cmdmap["-sysdir"] = parse_sysdir;
744 cmdmap["-userdir"] = parse_userdir;
745 cmdmap["-roundtrip"] = parse_roundtrip;
746 cmdmap["-copyfiles"] = parse_copyfiles;
748 for (int i = 1; i < argc_; ++i) {
749 map<string, cmd_helper>::const_iterator it
750 = cmdmap.find(argv_[i]);
752 // don't complain if not found - may be parsed later
753 if (it == cmdmap.end()) {
754 if (argv_[i][0] == '-')
755 error_message(string("Unknown option `") + argv_[i] + "'.");
760 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
761 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
763 int const remove = 1 + it->second(arg, arg2);
765 // Now, remove used arguments by shifting
766 // the following ones remove places down.
767 os::remove_internal_args(i, remove);
769 for (int j = i; j < argc_; ++j)
770 argv_[j] = argv_[j + remove];
776 // path of the first parsed file
777 string masterFilePathLyX;
778 string masterFilePathTeX;
779 // path of the currently parsed file
780 string parentFilePathTeX;
782 } // anonymous namespace
785 string getMasterFilePath(bool input)
787 return input ? masterFilePathTeX : masterFilePathLyX;
790 string getParentFilePath(bool input)
793 return parentFilePathTeX;
794 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
795 from_utf8(parentFilePathTeX)));
796 if (rel.substr(0, 3) == "../") {
797 // The parent is not below the master - keep the path
798 return parentFilePathTeX;
800 return makeAbsPath(rel, masterFilePathLyX).absFileName();
810 bool overwriteFiles()
812 return overwrite_files;
818 return skip_children;
831 * Reads tex input from \a is and writes lyx output to \a os.
832 * Uses some common settings for the preamble, so this should only
833 * be used more than once for included documents.
834 * Caution: Overwrites the existing preamble settings if the new document
835 * contains a preamble.
836 * You must ensure that \p parentFilePathTeX is properly set before calling
839 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
840 string const & outfiledir)
842 Parser p(is, fixed_encoding ? default_encoding : string());
843 p.setEncoding(encoding);
846 preamble.parse(p, documentclass, textclass);
847 list<string> removed_modules;
848 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
849 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
850 cerr << "Could not load default modules for text class." << endl;
854 // Load preloaded modules.
855 // This needs to be done after the preamble is parsed, since the text
856 // class may not be known before. It neds to be done before parsing
857 // body, since otherwise the commands/environments provided by the
858 // modules would be parsed as ERT.
859 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
860 if (!addModule(preloaded_modules[i])) {
861 cerr << "Error: Could not load module \""
862 << preloaded_modules[i] << "\"." << endl;
866 // Ensure that the modules are not loaded again for included files
867 preloaded_modules.clear();
869 active_environments.push_back("document");
870 Context context(true, textclass);
872 // store the document language in the context to be able to handle the
873 // commands like \foreignlanguage and \textenglish etc.
874 context.font.language = preamble.defaultLanguage();
875 // parse the main text
876 parse_text(p, ss, FLAG_END, true, context);
878 // Empty document body. LyX needs at least one paragraph.
879 context.check_layout(ss);
880 context.check_end_layout(ss);
881 ss << "\n\\end_body\n\\end_document\n";
882 active_environments.pop_back();
884 // We know the used modules only after parsing the full text
885 if (!used_modules.empty()) {
886 LayoutModuleList::const_iterator const end = used_modules.end();
887 LayoutModuleList::const_iterator it = used_modules.begin();
888 for (; it != end; ++it)
889 preamble.addModule(*it);
891 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
892 cerr << "Could not write LyX file header." << endl;
900 ofdocstream parsertest("parsertest.tex");
902 parsertest << p.get_token().asInput();
903 // <origfile> and parsertest.tex should now have identical content
909 /// convert TeX from \p infilename to LyX and write it to \p os
910 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
911 string const & outfiledir)
913 // Set a sensible default encoding.
914 // This is used until an encoding command is found.
915 // For child documents use the encoding of the master, else try to
916 // detect it from the preamble, since setting an encoding of an open
917 // fstream does currently not work on OS X.
918 // Always start with ISO-8859-1, (formerly known by its latex name
919 // latin1), since ISO-8859-1 does not cause an iconv error if the
920 // actual encoding is different (bug 7509).
921 if (encoding.empty()) {
922 Encoding const * enc = 0;
923 if (preamble.inputencoding() == "auto") {
924 ifdocstream is(setEncoding("ISO-8859-1"));
925 // forbid buffering on this stream
926 is.rdbuf()->pubsetbuf(0, 0);
927 is.open(infilename.toFilesystemEncoding().c_str());
929 Parser ep(is, string());
930 ep.setEncoding("ISO-8859-1");
931 Preamble encodingpreamble;
932 string const e = encodingpreamble
933 .parseEncoding(ep, documentclass);
935 enc = encodings.fromLyXName(e, true);
938 enc = encodings.fromLyXName(
939 preamble.inputencoding(), true);
941 encoding = enc->iconvName();
943 encoding = "ISO-8859-1";
946 ifdocstream is(setEncoding(encoding));
947 // forbid buffering on this stream
948 is.rdbuf()->pubsetbuf(0, 0);
949 is.open(infilename.toFilesystemEncoding().c_str());
951 cerr << "Could not open input file \"" << infilename
952 << "\" for reading." << endl;
955 string const oldParentFilePath = parentFilePathTeX;
956 parentFilePathTeX = onlyPath(infilename.absFileName());
957 bool retval = tex2lyx(is, os, encoding, outfiledir);
958 parentFilePathTeX = oldParentFilePath;
962 } // anonymous namespace
965 bool tex2lyx(string const & infilename, FileName const & outfilename,
966 string const & encoding)
968 if (outfilename.isReadableFile()) {
969 if (overwrite_files) {
970 cerr << "Overwriting existing file "
971 << outfilename << endl;
973 cerr << "Not overwriting existing file "
974 << outfilename << endl;
978 cerr << "Creating file " << outfilename << endl;
980 ofstream os(outfilename.toFilesystemEncoding().c_str());
982 cerr << "Could not open output file \"" << outfilename
983 << "\" for writing." << endl;
987 cerr << "Input file: " << infilename << "\n";
988 cerr << "Output file: " << outfilename << "\n";
990 return tex2lyx(FileName(infilename), os, encoding,
991 outfilename.onlyPath().absFileName() + '/');
995 bool tex2tex(string const & infilename, FileName const & outfilename,
996 string const & encoding)
998 if (!tex2lyx(infilename, outfilename, encoding))
1000 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1001 if (overwrite_files)
1002 command += " -f main";
1004 command += " -f none";
1006 command += " -e pdflatex ";
1008 command += " -e xetex ";
1010 command += " -e latex ";
1011 command += quoteName(outfilename.toFilesystemEncoding());
1013 if (one.startscript(Systemcall::Wait, command) == 0)
1015 cerr << "Error: Running '" << command << "' failed." << endl;
1022 int TeX2LyXApp::run()
1024 // qt changes this, and our numeric conversions require the C locale
1025 setlocale(LC_NUMERIC, "C");
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;
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 // Check that user LyX directory is ok.
1052 FileName const sup = package().user_support();
1053 if (sup.exists() && sup.isDirectory()) {
1054 string const lock_file = package().getConfigureLockName();
1055 int fd = fileLock(lock_file.c_str());
1056 if (configFileNeedsUpdate("lyxrc.defaults") ||
1057 configFileNeedsUpdate("lyxmodules.lst") ||
1058 configFileNeedsUpdate("textclass.lst") ||
1059 configFileNeedsUpdate("packages.lst") ||
1060 configFileNeedsUpdate("lyxciteengines.lst") ||
1061 configFileNeedsUpdate("xtemplates.lst"))
1062 package().reconfigureUserLyXDir("");
1063 fileUnlock(fd, lock_file.c_str());
1065 error_message("User directory does not exist.");
1067 // Now every known option is parsed. Look for input and output
1068 // file name (the latter is optional).
1069 string infilename = internal_path(os::utf8_argv(1));
1070 infilename = makeAbsPath(infilename).absFileName();
1074 outfilename = internal_path(os::utf8_argv(2));
1075 if (outfilename != "-")
1076 outfilename = makeAbsPath(outfilename).absFileName();
1078 if (outfilename == "-") {
1079 cerr << "Error: Writing to standard output is "
1080 "not supported in roundtrip mode."
1082 return EXIT_FAILURE;
1084 string texfilename = changeExtension(outfilename, ".tex");
1085 if (equivalent(FileName(infilename), FileName(texfilename))) {
1086 cerr << "Error: The input file `" << infilename
1087 << "´ would be overwritten by the TeX file exported from `"
1088 << outfilename << "´ in roundtrip mode." << endl;
1089 return EXIT_FAILURE;
1092 } else if (roundtrip) {
1093 // avoid overwriting the input file
1094 outfilename = changeExtension(infilename, ".lyx.lyx");
1096 outfilename = changeExtension(infilename, ".lyx");
1098 // Read the syntax tables
1099 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1100 if (system_syntaxfile.empty()) {
1101 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1102 return EXIT_FAILURE;
1104 if (!read_syntaxfile(system_syntaxfile))
1106 if (!syntaxfile.empty())
1107 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1110 // Read the encodings table.
1111 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1112 if (symbols_path.empty()) {
1113 cerr << "Error: Could not find file \"unicodesymbols\"."
1115 return EXIT_FAILURE;
1117 FileName const enc_path = libFileSearch(string(), "encodings");
1118 if (enc_path.empty()) {
1119 cerr << "Error: Could not find file \"encodings\"."
1121 return EXIT_FAILURE;
1123 encodings.read(enc_path, symbols_path);
1124 if (!default_encoding.empty()) {
1125 Encoding const * const enc = encodings.fromLaTeXName(
1126 default_encoding, Encoding::any, true);
1128 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1129 default_encoding = enc->iconvName();
1131 preamble.setInputencoding(enc->name());
1135 LayoutFileList::get().read();
1136 //...and the modules
1137 theModuleList.read();
1139 // The real work now.
1140 masterFilePathTeX = onlyPath(infilename);
1141 parentFilePathTeX = masterFilePathTeX;
1142 if (outfilename == "-") {
1143 // assume same directory as input file
1144 masterFilePathLyX = masterFilePathTeX;
1145 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1146 return EXIT_SUCCESS;
1148 masterFilePathLyX = onlyPath(outfilename);
1150 FileName const path(masterFilePathLyX);
1151 if (!path.isDirectory()) {
1152 if (!path.createPath()) {
1153 cerr << "Warning: Could not create directory for file `"
1154 << masterFilePathLyX << "´." << endl;
1155 return EXIT_FAILURE;
1160 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1161 return EXIT_SUCCESS;
1163 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1164 return EXIT_SUCCESS;
1167 return EXIT_FAILURE;
1170 } // anonymous namespace
1174 int main(int argc, char * argv[])
1176 //setlocale(LC_CTYPE, "");
1178 lyx::lyxerr.setStream(cerr);
1180 os::init(argc, &argv);
1182 lyx::TeX2LyXApp app(argc, argv);