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/os.h"
33 #include "support/Package.h"
34 #include "support/Systemcall.h"
45 using namespace lyx::support;
46 using namespace lyx::support::os;
50 string const trimSpaceAndEol(string const & a)
52 return trim(a, " \t\n\r");
56 void split(string const & s, vector<string> & result, char delim)
58 //cerr << "split 1: '" << s << "'\n";
61 while (getline(is, t, delim))
63 //cerr << "split 2\n";
67 string join(vector<string> const & input, char const * delim)
70 for (size_t i = 0; i != input.size(); ++i) {
79 char const * const * is_known(string const & str, char const * const * what)
81 for ( ; *what; ++what)
89 // current stack of nested environments
90 vector<string> active_environments;
93 string active_environment()
95 return active_environments.empty() ? string() : active_environments.back();
99 TeX2LyXDocClass textclass;
100 CommandMap known_commands;
101 CommandMap known_environments;
102 CommandMap known_math_environments;
103 FullCommandMap possible_textclass_commands;
104 FullEnvironmentMap possible_textclass_environments;
105 FullCommandMap possible_textclass_theorems;
106 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
109 LayoutModuleList used_modules;
110 vector<string> preloaded_modules;
113 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
115 // We have to handle the following cases:
116 // definition o1 o2 invocation result
117 // \newcommand{\foo}{bar} "" false \foo bar
118 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
119 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
120 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
121 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
122 unsigned int nargs = 0;
123 string const opt1 = rtrim(ltrim(o1, "["), "]");
124 if (isStrUnsignedInt(opt1)) {
125 // The command has arguments
126 nargs = convert<unsigned int>(opt1);
127 if (nargs > 0 && o2) {
128 // The first argument is optional
129 arguments.push_back(optional);
133 for (unsigned int i = 0; i < nargs; ++i)
134 arguments.push_back(required);
138 void add_known_command(string const & command, string const & o1,
139 bool o2, docstring const & definition)
141 vector<ArgumentType> arguments;
142 convertArgs(o1, o2, arguments);
143 known_commands[command] = arguments;
144 if (!definition.empty())
145 possible_textclass_commands[command] =
146 FullCommand(arguments, definition);
150 void add_known_environment(string const & environment, string const & o1,
151 bool o2, docstring const & beg, docstring const &end)
153 vector<ArgumentType> arguments;
154 convertArgs(o1, o2, arguments);
155 known_environments[environment] = arguments;
156 if (!beg.empty() || ! end.empty())
157 possible_textclass_environments[environment] =
158 FullEnvironment(arguments, beg, end);
162 void add_known_theorem(string const & theorem, string const & o1,
163 bool o2, docstring const & definition)
165 vector<ArgumentType> arguments;
166 convertArgs(o1, o2, arguments);
167 if (!definition.empty())
168 possible_textclass_theorems[theorem] =
169 FullCommand(arguments, definition);
173 Layout const * findLayoutWithoutModule(TextClass const & textclass,
174 string const & name, bool command)
176 DocumentClass::const_iterator it = textclass.begin();
177 DocumentClass::const_iterator en = textclass.end();
178 for (; it != en; ++it) {
179 if (it->latexname() == name &&
180 ((command && it->isCommand()) || (!command && it->isEnvironment())))
187 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
188 string const & name, bool command)
190 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
191 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
192 for (; it != en; ++it) {
193 if (it->second.latexname() == name &&
194 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
195 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
196 return &(it->second);
204 typedef map<string, DocumentClassPtr> ModuleMap;
208 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
210 // avoid endless loop for circular dependency
211 vector<string>::const_iterator const vb = visited.begin();
212 vector<string>::const_iterator const ve = visited.end();
213 if (find(vb, ve, module) != ve) {
214 cerr << "Circular dependency detected for module " << module << '\n';
217 LyXModule const * const lm = theModuleList[module];
219 cerr << "Could not find module " << module << " in module list.\n";
222 bool foundone = false;
223 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
224 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
225 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
226 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
227 vector<string> const reqs = lm->getRequiredModules();
231 LayoutModuleList::const_iterator mit = m.begin();
232 LayoutModuleList::const_iterator men = m.end();
233 vector<string>::const_iterator rit = reqs.begin();
234 vector<string>::const_iterator ren = reqs.end();
235 for (; rit != ren; ++rit) {
236 if (find(mit, men, *rit) != men) {
240 if (find(provmodstart, provmodend, *rit) != provmodend) {
246 visited.push_back(module);
247 for (rit = reqs.begin(); rit != ren; ++rit) {
248 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
249 if (addModule(*rit, baseClass, m, visited)) {
259 cerr << "Could not add required modules for " << module << ".\n";
262 if (!m.moduleCanBeAdded(module, &baseClass))
271 // Create list of dummy document classes if not already done.
272 // This is needed since a module cannot be read on its own, only as
273 // part of a document class.
274 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
275 static bool init = true;
278 LyXModuleList::const_iterator const end = theModuleList.end();
279 LyXModuleList::const_iterator it = theModuleList.begin();
280 for (; it != end; ++it) {
281 string const module = it->getID();
284 if (!addModule(module, baseClass, m, v))
286 modules[module] = getDocumentClass(baseClass, m);
293 bool addModule(string const & module)
296 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
297 if (!used_modules.moduleCanBeAdded(module, &baseClass))
299 FileName layout_file = libFileSearch("layouts", module, "module");
300 if (textclass.read(layout_file, TextClass::MODULE)) {
301 used_modules.push_back(module);
302 // speed up further searches:
303 // the module does not need to be checked anymore.
304 ModuleMap::iterator const it = modules.find(module);
305 if (it != modules.end())
315 bool checkModule(string const & name, bool command)
317 // Cache to avoid slowdown by repated searches
318 static set<string> failed[2];
320 // Only add the module if the command was actually defined in the LyX preamble
321 bool theorem = false;
323 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
326 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
327 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
333 if (failed[command].find(name) != failed[command].end())
337 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
339 // Try to find a module that defines the command.
340 // Only add it if the definition can be found in the preamble of the
341 // style that corresponds to the command. This is a heuristic and
342 // different from the way how we parse the builtin commands of the
343 // text class (in that case we only compare the name), but it is
344 // needed since it is not unlikely that two different modules define a
345 // command with the same name.
346 ModuleMap::iterator const end = modules.end();
347 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
348 string const module = it->first;
349 if (used_modules.moduleConflicts(module, &baseClass))
351 if (findLayoutWithoutModule(textclass, name, command))
353 if (findInsetLayoutWithoutModule(textclass, name, command))
355 DocumentClassConstPtr c = it->second;
356 Layout const * layout = findLayoutWithoutModule(*c, name, command);
357 InsetLayout const * insetlayout = layout ? 0 :
358 findInsetLayoutWithoutModule(*c, name, command);
361 preamble = layout->preamble();
362 else if (insetlayout)
363 preamble = insetlayout->preamble();
364 if (preamble.empty())
368 FullCommand const & cmd =
369 possible_textclass_commands['\\' + name];
370 if (preamble.find(cmd.def) != docstring::npos)
372 } else if (theorem) {
373 FullCommand const & thm =
374 possible_textclass_theorems[name];
375 if (preamble.find(thm.def) != docstring::npos)
378 FullEnvironment const & env =
379 possible_textclass_environments[name];
380 if (preamble.find(env.beg) != docstring::npos &&
381 preamble.find(env.end) != docstring::npos)
385 FileName layout_file = libFileSearch("layouts", module, "module");
386 if (textclass.read(layout_file, TextClass::MODULE)) {
387 used_modules.push_back(module);
388 // speed up further searches:
389 // the module does not need to be checked anymore.
395 failed[command].insert(name);
400 bool isProvided(string const & name)
402 // This works only for features that are named like the LaTeX packages
403 return textclass.provides(name) || preamble.isPackageUsed(name);
407 bool noweb_mode = false;
408 bool pdflatex = false;
410 bool is_nonCJKJapanese = false;
411 bool roundtrip = false;
418 * Read one command definition from the syntax file
420 void read_command(Parser & p, string command, CommandMap & commands)
422 if (p.next_token().asInput() == "*") {
426 vector<ArgumentType> arguments;
427 while (p.next_token().cat() == catBegin ||
428 p.next_token().asInput() == "[") {
429 if (p.next_token().cat() == catBegin) {
430 string const arg = p.getArg('{', '}');
431 if (arg == "translate")
432 arguments.push_back(required);
433 else if (arg == "group")
434 arguments.push_back(req_group);
435 else if (arg == "item")
436 arguments.push_back(item);
437 else if (arg == "displaymath")
438 arguments.push_back(displaymath);
440 arguments.push_back(verbatim);
442 string const arg = p.getArg('[', ']');
444 arguments.push_back(opt_group);
446 arguments.push_back(optional);
449 commands[command] = arguments;
454 * Read a class of environments from the syntax file
456 void read_environment(Parser & p, string const & begin,
457 CommandMap & environments)
461 Token const & t = p.get_token();
462 if (t.cat() == catLetter)
463 environment += t.asInput();
464 else if (!environment.empty()) {
466 read_command(p, environment, environments);
469 if (t.cat() == catEscape && t.asInput() == "\\end") {
470 string const end = p.getArg('{', '}');
479 * Read a list of TeX commands from a reLyX compatible syntax file.
480 * Since this list is used after all commands that have a LyX counterpart
481 * are handled, it does not matter that the "syntax.default" file
482 * has almost all of them listed. For the same reason the reLyX-specific
483 * reLyXre environment is ignored.
485 bool read_syntaxfile(FileName const & file_name)
487 ifdocstream is(file_name.toFilesystemEncoding().c_str());
489 cerr << "Could not open syntax file \"" << file_name
490 << "\" for reading." << endl;
493 // We can use our TeX parser, since the syntax of the layout file is
494 // modeled after TeX.
495 // Unknown tokens are just silently ignored, this helps us to skip some
496 // reLyX specific things.
497 Parser p(is, string());
499 Token const & t = p.get_token();
500 if (t.cat() == catEscape) {
501 string const command = t.asInput();
502 if (command == "\\begin") {
503 string const name = p.getArg('{', '}');
504 if (name == "environments" || name == "reLyXre")
505 // We understand "reLyXre", but it is
506 // not as powerful as "environments".
507 read_environment(p, name,
509 else if (name == "mathenvironments")
510 read_environment(p, name,
511 known_math_environments);
513 read_command(p, command, known_commands);
521 string documentclass;
522 string default_encoding;
523 bool fixed_encoding = false;
525 bool copy_files = false;
526 bool overwrite_files = false;
527 bool skip_children = false;
530 /// return the number of arguments consumed
531 typedef int (*cmd_helper)(string const &, string const &);
534 int parse_help(string const &, string const &)
536 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
538 "\t-c textclass Declare the textclass.\n"
539 "\t-m mod1[,mod2...] Load the given modules.\n"
540 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
541 "\t-e encoding Set the default encoding (latex name).\n"
542 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
543 "\t-f Force overwrite of .lyx files.\n"
544 "\t-help Print this message and quit.\n"
545 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
546 "\t-skipchildren Do not translate included child documents.\n"
547 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
548 "\t-s syntaxfile read additional syntax file.\n"
549 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
550 "\t Default: " << package().system_support() << "\n"
551 "\t-userdir USERDIR Set user directory to USERDIR.\n"
552 "\t Default: " << package().user_support() << "\n"
553 "\t-version Summarize version and build info.\n"
555 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
556 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
557 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
558 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
559 "Check the tex2lyx man page for more details."
565 int parse_version(string const &, string const &)
567 cout << "tex2lyx " << lyx_version
568 << " (" << lyx_release_date << ")" << endl;
569 cout << "Built on " << lyx_build_date << ", " << lyx_build_time
572 cout << lyx_version_info << endl;
577 void error_message(string const & message)
579 cerr << "tex2lyx: " << message << "\n\n";
581 parse_help(string(), string());
585 int parse_class(string const & arg, string const &)
588 error_message("Missing textclass string after -c switch");
594 int parse_module(string const & arg, string const &)
597 error_message("Missing modules string after -m switch");
598 split(arg, preloaded_modules, ',');
603 int parse_encoding(string const & arg, string const &)
606 error_message("Missing encoding string after -e switch");
607 default_encoding = arg;
612 int parse_fixed_encoding(string const & arg, string const &)
615 error_message("Missing encoding string after -fixedenc switch");
616 default_encoding = arg;
617 fixed_encoding = true;
622 int parse_syntaxfile(string const & arg, string const &)
625 error_message("Missing syntaxfile string after -s switch");
626 syntaxfile = internal_path(arg);
631 // Filled with the command line arguments "foo" of "-sysdir foo" or
633 string cl_system_support;
634 string cl_user_support;
637 int parse_sysdir(string const & arg, string const &)
640 error_message("Missing directory for -sysdir switch");
641 cl_system_support = internal_path(arg);
646 int parse_userdir(string const & arg, string const &)
649 error_message("Missing directory for -userdir switch");
650 cl_user_support = internal_path(arg);
655 int parse_force(string const &, string const &)
657 overwrite_files = true;
662 int parse_noweb(string const &, string const &)
669 int parse_skipchildren(string const &, string const &)
671 skip_children = true;
676 int parse_roundtrip(string const &, string const &)
683 int parse_copyfiles(string const &, string const &)
690 void easyParse(int & argc, char * argv[])
692 map<string, cmd_helper> cmdmap;
694 cmdmap["-h"] = parse_help;
695 cmdmap["-help"] = parse_help;
696 cmdmap["--help"] = parse_help;
697 cmdmap["-v"] = parse_version;
698 cmdmap["-version"] = parse_version;
699 cmdmap["--version"] = parse_version;
700 cmdmap["-c"] = parse_class;
701 cmdmap["-m"] = parse_module;
702 cmdmap["-e"] = parse_encoding;
703 cmdmap["-fixedenc"] = parse_fixed_encoding;
704 cmdmap["-f"] = parse_force;
705 cmdmap["-s"] = parse_syntaxfile;
706 cmdmap["-n"] = parse_noweb;
707 cmdmap["-skipchildren"] = parse_skipchildren;
708 cmdmap["-sysdir"] = parse_sysdir;
709 cmdmap["-userdir"] = parse_userdir;
710 cmdmap["-roundtrip"] = parse_roundtrip;
711 cmdmap["-copyfiles"] = parse_copyfiles;
713 for (int i = 1; i < argc; ++i) {
714 map<string, cmd_helper>::const_iterator it
715 = cmdmap.find(argv[i]);
717 // don't complain if not found - may be parsed later
718 if (it == cmdmap.end()) {
719 if (argv[i][0] == '-')
720 error_message(string("Unknown option `") + argv[i] + "'.");
725 string arg = (i + 1 < argc) ? os::utf8_argv(i + 1) : string();
726 string arg2 = (i + 2 < argc) ? os::utf8_argv(i + 2) : string();
728 int const remove = 1 + it->second(arg, arg2);
730 // Now, remove used arguments by shifting
731 // the following ones remove places down.
732 os::remove_internal_args(i, remove);
734 for (int j = i; j < argc; ++j)
735 argv[j] = argv[j + remove];
741 // path of the first parsed file
742 string masterFilePathLyX;
743 string masterFilePathTeX;
744 // path of the currently parsed file
745 string parentFilePathTeX;
747 } // anonymous namespace
750 string getMasterFilePath(bool input)
752 return input ? masterFilePathTeX : masterFilePathLyX;
755 string getParentFilePath(bool input)
758 return parentFilePathTeX;
759 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
760 from_utf8(parentFilePathTeX)));
761 if (rel.substr(0, 3) == "../") {
762 // The parent is not below the master - keep the path
763 return parentFilePathTeX;
765 return makeAbsPath(rel, masterFilePathLyX).absFileName();
775 bool overwriteFiles()
777 return overwrite_files;
783 return skip_children;
796 * Reads tex input from \a is and writes lyx output to \a os.
797 * Uses some common settings for the preamble, so this should only
798 * be used more than once for included documents.
799 * Caution: Overwrites the existing preamble settings if the new document
800 * contains a preamble.
801 * You must ensure that \p parentFilePathTeX is properly set before calling
804 bool tex2lyx(idocstream & is, ostream & os, string encoding)
806 // Set a sensible default encoding.
807 // This is used until an encoding command is found.
808 // For child documents use the encoding of the master, else ISO8859-1,
809 // (formerly known by its latex name latin1), since ISO8859-1 does not
810 // cause an iconv error if the actual encoding is different (bug 7509).
811 if (encoding.empty()) {
812 if (preamble.inputencoding() == "auto")
813 encoding = "ISO8859-1";
815 Encoding const * const enc = encodings.fromLyXName(
816 preamble.inputencoding(), true);
817 encoding = enc->iconvName();
821 Parser p(is, fixed_encoding ? default_encoding : string());
822 p.setEncoding(encoding);
825 preamble.parse(p, documentclass, textclass);
826 list<string> removed_modules;
827 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
828 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
829 cerr << "Could not load default modules for text class." << endl;
833 // Load preloaded modules.
834 // This needs to be done after the preamble is parsed, since the text
835 // class may not be known before. It neds to be done before parsing
836 // body, since otherwise the commands/environments provided by the
837 // modules would be parsed as ERT.
838 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
839 if (!addModule(preloaded_modules[i])) {
840 cerr << "Error: Could not load module \""
841 << preloaded_modules[i] << "\"." << endl;
845 // Ensure that the modules are not loaded again for included files
846 preloaded_modules.clear();
848 active_environments.push_back("document");
849 Context context(true, textclass);
851 // store the document language in the context to be able to handle the
852 // commands like \foreignlanguage and \textenglish etc.
853 context.font.language = preamble.defaultLanguage();
854 // parse the main text
855 parse_text(p, ss, FLAG_END, true, context);
857 // Empty document body. LyX needs at least one paragraph.
858 context.check_layout(ss);
859 context.check_end_layout(ss);
860 ss << "\n\\end_body\n\\end_document\n";
861 active_environments.pop_back();
863 // We know the used modules only after parsing the full text
864 if (!used_modules.empty()) {
865 LayoutModuleList::const_iterator const end = used_modules.end();
866 LayoutModuleList::const_iterator it = used_modules.begin();
867 for (; it != end; ++it)
868 preamble.addModule(*it);
870 if (!preamble.writeLyXHeader(os, !active_environments.empty())) {
871 cerr << "Could not write LyX file header." << endl;
879 ofdocstream parsertest("parsertest.tex");
881 parsertest << p.get_token().asInput();
882 // <origfile> and parsertest.tex should now have identical content
888 /// convert TeX from \p infilename to LyX and write it to \p os
889 bool tex2lyx(FileName const & infilename, ostream & os, string const & encoding)
892 // forbid buffering on this stream
893 is.rdbuf()->pubsetbuf(0,0);
894 is.open(infilename.toFilesystemEncoding().c_str());
896 cerr << "Could not open input file \"" << infilename
897 << "\" for reading." << endl;
900 string const oldParentFilePath = parentFilePathTeX;
901 parentFilePathTeX = onlyPath(infilename.absFileName());
902 bool retval = tex2lyx(is, os, encoding);
903 parentFilePathTeX = oldParentFilePath;
907 } // anonymous namespace
910 bool tex2lyx(string const & infilename, FileName const & outfilename,
911 string const & encoding)
913 if (outfilename.isReadableFile()) {
914 if (overwrite_files) {
915 cerr << "Overwriting existing file "
916 << outfilename << endl;
918 cerr << "Not overwriting existing file "
919 << outfilename << endl;
923 cerr << "Creating file " << outfilename << endl;
925 ofstream os(outfilename.toFilesystemEncoding().c_str());
927 cerr << "Could not open output file \"" << outfilename
928 << "\" for writing." << endl;
932 cerr << "Input file: " << infilename << "\n";
933 cerr << "Output file: " << outfilename << "\n";
935 return tex2lyx(FileName(infilename), os, encoding);
939 bool tex2tex(string const & infilename, FileName const & outfilename,
940 string const & encoding)
942 if (!tex2lyx(infilename, outfilename, encoding))
944 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
946 command += " -f main";
948 command += " -f none";
950 command += " -e pdflatex ";
952 command += " -e xetex ";
954 command += " -e latex ";
955 command += quoteName(outfilename.toFilesystemEncoding());
957 if (one.startscript(Systemcall::Wait, command) == 0)
959 cerr << "Error: Running '" << command << "' failed." << endl;
966 int main(int argc, char * argv[])
970 //setlocale(LC_CTYPE, "");
972 lyxerr.setStream(cerr);
974 os::init(argc, argv);
977 init_package(internal_path(os::utf8_argv(0)), string(), string());
978 } catch (ExceptionMessage const & message) {
979 cerr << to_utf8(message.title_) << ":\n"
980 << to_utf8(message.details_) << endl;
981 if (message.type_ == ErrorException)
985 easyParse(argc, argv);
988 error_message("Not enough arguments.");
991 init_package(internal_path(os::utf8_argv(0)),
992 cl_system_support, cl_user_support);
993 } catch (ExceptionMessage const & message) {
994 cerr << to_utf8(message.title_) << ":\n"
995 << to_utf8(message.details_) << endl;
996 if (message.type_ == ErrorException)
1000 // Check that user LyX directory is ok.
1001 FileName const sup = package().user_support();
1002 if (sup.exists() && sup.isDirectory()) {
1003 string const lock_file = package().getConfigureLockName();
1004 int fd = fileLock(lock_file.c_str());
1005 if (configFileNeedsUpdate("lyxrc.defaults") ||
1006 configFileNeedsUpdate("lyxmodules.lst") ||
1007 configFileNeedsUpdate("textclass.lst") ||
1008 configFileNeedsUpdate("packages.lst"))
1009 package().reconfigureUserLyXDir("");
1010 fileUnlock(fd, lock_file.c_str());
1012 error_message("User directory does not exist.");
1014 // Now every known option is parsed. Look for input and output
1015 // file name (the latter is optional).
1016 string infilename = internal_path(os::utf8_argv(1));
1017 infilename = makeAbsPath(infilename).absFileName();
1021 outfilename = internal_path(os::utf8_argv(2));
1022 if (outfilename != "-")
1023 outfilename = makeAbsPath(outfilename).absFileName();
1025 if (outfilename == "-") {
1026 cerr << "Error: Writing to standard output is "
1027 "not supported in roundtrip mode."
1029 return EXIT_FAILURE;
1031 string texfilename = changeExtension(outfilename, ".tex");
1032 if (equivalent(FileName(infilename), FileName(texfilename))) {
1033 cerr << "Error: The input file `" << infilename
1034 << "´ would be overwritten by the TeX file exported from `"
1035 << outfilename << "´ in roundtrip mode." << endl;
1036 return EXIT_FAILURE;
1039 } else if (roundtrip) {
1040 // avoid overwriting the input file
1041 outfilename = changeExtension(infilename, ".lyx.lyx");
1043 outfilename = changeExtension(infilename, ".lyx");
1045 // Read the syntax tables
1046 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1047 if (system_syntaxfile.empty()) {
1048 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1049 return EXIT_FAILURE;
1051 if (!read_syntaxfile(system_syntaxfile))
1053 if (!syntaxfile.empty())
1054 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1057 // Read the encodings table.
1058 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1059 if (symbols_path.empty()) {
1060 cerr << "Error: Could not find file \"unicodesymbols\"."
1062 return EXIT_FAILURE;
1064 FileName const enc_path = libFileSearch(string(), "encodings");
1065 if (enc_path.empty()) {
1066 cerr << "Error: Could not find file \"encodings\"."
1068 return EXIT_FAILURE;
1070 encodings.read(enc_path, symbols_path);
1071 if (!default_encoding.empty()) {
1072 Encoding const * const enc = encodings.fromLaTeXName(
1073 default_encoding, Encoding::any, true);
1075 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1076 default_encoding = enc->iconvName();
1078 preamble.setInputencoding(enc->name());
1082 LayoutFileList::get().read();
1083 //...and the modules
1084 theModuleList.read();
1086 // The real work now.
1087 masterFilePathTeX = onlyPath(infilename);
1088 parentFilePathTeX = masterFilePathTeX;
1089 if (outfilename == "-") {
1090 // assume same directory as input file
1091 masterFilePathLyX = masterFilePathTeX;
1092 if (tex2lyx(FileName(infilename), cout, default_encoding))
1093 return EXIT_SUCCESS;
1095 masterFilePathLyX = onlyPath(outfilename);
1097 FileName const path(masterFilePathLyX);
1098 if (!path.isDirectory()) {
1099 if (!path.createPath()) {
1100 cerr << "Warning: Could not create directory for file `"
1101 << masterFilePathLyX << "´." << endl;
1102 return EXIT_FAILURE;
1107 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1108 return EXIT_SUCCESS;
1110 if (tex2lyx(infilename, FileName(outfilename), default_encoding))
1111 return EXIT_SUCCESS;
1114 return EXIT_FAILURE;