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;
58 App * theApp() { return &app; }
61 string const trimSpaceAndEol(string const & a)
63 return trim(a, " \t\n\r");
67 void split(string const & s, vector<string> & result, char delim)
69 //cerr << "split 1: '" << s << "'\n";
72 while (getline(is, t, delim))
74 //cerr << "split 2\n";
78 string join(vector<string> const & input, char const * delim)
81 for (size_t i = 0; i != input.size(); ++i) {
90 char const * const * is_known(string const & str, char const * const * what)
92 for ( ; *what; ++what)
100 // current stack of nested environments
101 vector<string> active_environments;
104 string active_environment()
106 return active_environments.empty() ? string() : active_environments.back();
110 TeX2LyXDocClass textclass;
111 CommandMap known_commands;
112 CommandMap known_environments;
113 CommandMap known_math_environments;
114 FullCommandMap possible_textclass_commands;
115 FullEnvironmentMap possible_textclass_environments;
116 FullCommandMap possible_textclass_theorems;
117 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
120 LayoutModuleList used_modules;
121 vector<string> preloaded_modules;
124 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
126 // We have to handle the following cases:
127 // definition o1 o2 invocation result
128 // \newcommand{\foo}{bar} "" false \foo bar
129 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
130 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
131 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
132 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
133 unsigned int nargs = 0;
134 string const opt1 = rtrim(ltrim(o1, "["), "]");
135 if (isStrUnsignedInt(opt1)) {
136 // The command has arguments
137 nargs = convert<unsigned int>(opt1);
138 if (nargs > 0 && o2) {
139 // The first argument is optional
140 arguments.push_back(optional);
144 for (unsigned int i = 0; i < nargs; ++i)
145 arguments.push_back(required);
149 void add_known_command(string const & command, string const & o1,
150 bool o2, docstring const & definition)
152 vector<ArgumentType> arguments;
153 convertArgs(o1, o2, arguments);
154 known_commands[command] = arguments;
155 if (!definition.empty())
156 possible_textclass_commands[command] =
157 FullCommand(arguments, definition);
161 void add_known_environment(string const & environment, string const & o1,
162 bool o2, docstring const & beg, docstring const &end)
164 vector<ArgumentType> arguments;
165 convertArgs(o1, o2, arguments);
166 known_environments[environment] = arguments;
167 if (!beg.empty() || ! end.empty())
168 possible_textclass_environments[environment] =
169 FullEnvironment(arguments, beg, end);
173 void add_known_theorem(string const & theorem, string const & o1,
174 bool o2, docstring const & definition)
176 vector<ArgumentType> arguments;
177 convertArgs(o1, o2, arguments);
178 if (!definition.empty())
179 possible_textclass_theorems[theorem] =
180 FullCommand(arguments, definition);
184 Layout const * findLayoutWithoutModule(TextClass const & textclass,
185 string const & name, bool command)
187 DocumentClass::const_iterator it = textclass.begin();
188 DocumentClass::const_iterator en = textclass.end();
189 for (; it != en; ++it) {
190 if (it->latexname() == name &&
191 ((command && it->isCommand()) || (!command && it->isEnvironment())))
198 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
199 string const & name, bool command)
201 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
202 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
203 for (; it != en; ++it) {
204 if (it->second.latexname() == name &&
205 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
206 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
207 return &(it->second);
215 typedef map<string, DocumentClassPtr> ModuleMap;
219 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
221 // avoid endless loop for circular dependency
222 vector<string>::const_iterator const vb = visited.begin();
223 vector<string>::const_iterator const ve = visited.end();
224 if (find(vb, ve, module) != ve) {
225 cerr << "Circular dependency detected for module " << module << '\n';
228 LyXModule const * const lm = theModuleList[module];
230 cerr << "Could not find module " << module << " in module list.\n";
233 bool foundone = false;
234 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
235 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
236 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
237 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
238 vector<string> const reqs = lm->getRequiredModules();
242 LayoutModuleList::const_iterator mit = m.begin();
243 LayoutModuleList::const_iterator men = m.end();
244 vector<string>::const_iterator rit = reqs.begin();
245 vector<string>::const_iterator ren = reqs.end();
246 for (; rit != ren; ++rit) {
247 if (find(mit, men, *rit) != men) {
251 if (find(provmodstart, provmodend, *rit) != provmodend) {
257 visited.push_back(module);
258 for (rit = reqs.begin(); rit != ren; ++rit) {
259 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
260 if (addModule(*rit, baseClass, m, visited)) {
270 cerr << "Could not add required modules for " << module << ".\n";
273 if (!m.moduleCanBeAdded(module, &baseClass))
282 // Create list of dummy document classes if not already done.
283 // This is needed since a module cannot be read on its own, only as
284 // part of a document class.
285 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
286 static bool init = true;
289 LyXModuleList::const_iterator const end = theModuleList.end();
290 LyXModuleList::const_iterator it = theModuleList.begin();
291 for (; it != end; ++it) {
292 string const module = it->getID();
296 if (!addModule(module, baseClass, m, v))
298 modules[module] = getDocumentClass(baseClass, m, c);
305 bool addModule(string const & module)
308 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
309 if (!used_modules.moduleCanBeAdded(module, &baseClass))
311 FileName layout_file = libFileSearch("layouts", module, "module");
312 if (textclass.read(layout_file, TextClass::MODULE)) {
313 used_modules.push_back(module);
314 // speed up further searches:
315 // the module does not need to be checked anymore.
316 ModuleMap::iterator const it = modules.find(module);
317 if (it != modules.end())
327 bool checkModule(string const & name, bool command)
329 // Cache to avoid slowdown by repated searches
330 static set<string> failed[2];
332 // Only add the module if the command was actually defined in the LyX preamble
333 bool theorem = false;
335 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
338 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
339 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
345 if (failed[command].find(name) != failed[command].end())
349 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
351 // Try to find a module that defines the command.
352 // Only add it if the definition can be found in the preamble of the
353 // style that corresponds to the command. This is a heuristic and
354 // different from the way how we parse the builtin commands of the
355 // text class (in that case we only compare the name), but it is
356 // needed since it is not unlikely that two different modules define a
357 // command with the same name.
358 ModuleMap::iterator const end = modules.end();
359 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
360 string const module = it->first;
361 if (used_modules.moduleConflicts(module, &baseClass))
363 if (findLayoutWithoutModule(textclass, name, command))
365 if (findInsetLayoutWithoutModule(textclass, name, command))
367 DocumentClassConstPtr c = it->second;
368 Layout const * layout = findLayoutWithoutModule(*c, name, command);
369 InsetLayout const * insetlayout = layout ? 0 :
370 findInsetLayoutWithoutModule(*c, name, command);
373 preamble = layout->preamble();
374 else if (insetlayout)
375 preamble = insetlayout->preamble();
376 if (preamble.empty())
380 FullCommand const & cmd =
381 possible_textclass_commands['\\' + name];
382 if (preamble.find(cmd.def) != docstring::npos)
384 } else if (theorem) {
385 FullCommand const & thm =
386 possible_textclass_theorems[name];
387 if (preamble.find(thm.def) != docstring::npos)
390 FullEnvironment const & env =
391 possible_textclass_environments[name];
392 if (preamble.find(env.beg) != docstring::npos &&
393 preamble.find(env.end) != docstring::npos)
397 FileName layout_file = libFileSearch("layouts", module, "module");
398 if (textclass.read(layout_file, TextClass::MODULE)) {
399 used_modules.push_back(module);
400 // speed up further searches:
401 // the module does not need to be checked anymore.
407 failed[command].insert(name);
412 bool isProvided(string const & name)
414 // This works only for features that are named like the LaTeX packages
415 return textclass.provides(name) || preamble.isPackageUsed(name);
419 bool noweb_mode = false;
420 bool pdflatex = false;
422 bool is_nonCJKJapanese = false;
423 bool roundtrip = false;
430 * Read one command definition from the syntax file
432 void read_command(Parser & p, string command, CommandMap & commands)
434 if (p.next_token().asInput() == "*") {
438 vector<ArgumentType> arguments;
439 while (p.next_token().cat() == catBegin ||
440 p.next_token().asInput() == "[") {
441 if (p.next_token().cat() == catBegin) {
442 string const arg = p.getArg('{', '}');
443 if (arg == "translate")
444 arguments.push_back(required);
445 else if (arg == "group")
446 arguments.push_back(req_group);
447 else if (arg == "item")
448 arguments.push_back(item);
449 else if (arg == "displaymath")
450 arguments.push_back(displaymath);
452 arguments.push_back(verbatim);
454 string const arg = p.getArg('[', ']');
456 arguments.push_back(opt_group);
458 arguments.push_back(optional);
461 commands[command] = arguments;
466 * Read a class of environments from the syntax file
468 void read_environment(Parser & p, string const & begin,
469 CommandMap & environments)
473 Token const & t = p.get_token();
474 if (t.cat() == catLetter)
475 environment += t.asInput();
476 else if (!environment.empty()) {
478 read_command(p, environment, environments);
481 if (t.cat() == catEscape && t.asInput() == "\\end") {
482 string const end = p.getArg('{', '}');
491 * Read a list of TeX commands from a reLyX compatible syntax file.
492 * Since this list is used after all commands that have a LyX counterpart
493 * are handled, it does not matter that the "syntax.default" file
494 * has almost all of them listed. For the same reason the reLyX-specific
495 * reLyXre environment is ignored.
497 bool read_syntaxfile(FileName const & file_name)
499 ifdocstream is(file_name.toFilesystemEncoding().c_str());
501 cerr << "Could not open syntax file \"" << file_name
502 << "\" for reading." << endl;
505 // We can use our TeX parser, since the syntax of the layout file is
506 // modeled after TeX.
507 // Unknown tokens are just silently ignored, this helps us to skip some
508 // reLyX specific things.
509 Parser p(is, string());
511 Token const & t = p.get_token();
512 if (t.cat() == catEscape) {
513 string const command = t.asInput();
514 if (command == "\\begin") {
515 string const name = p.getArg('{', '}');
516 if (name == "environments" || name == "reLyXre")
517 // We understand "reLyXre", but it is
518 // not as powerful as "environments".
519 read_environment(p, name,
521 else if (name == "mathenvironments")
522 read_environment(p, name,
523 known_math_environments);
525 read_command(p, command, known_commands);
533 string documentclass;
534 string default_encoding;
535 bool fixed_encoding = false;
537 bool copy_files = false;
538 bool overwrite_files = false;
539 bool skip_children = false;
542 /// return the number of arguments consumed
543 typedef int (*cmd_helper)(string const &, string const &);
546 class StopException : public exception
549 StopException(int status) : status_(status) {}
550 int status() const { return status_; }
556 /// The main application class
557 class TeX2LyXApp : public ConsoleApplication
560 TeX2LyXApp(int & argc, char * argv[])
561 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
562 argc_(argc), argv_(argv)
568 int const exit_status = run();
571 catch (StopException & e) {
584 int parse_help(string const &, string const &)
586 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
588 "\t-c textclass Declare the textclass.\n"
589 "\t-m mod1[,mod2...] Load the given modules.\n"
590 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
591 "\t-e encoding Set the default encoding (latex name).\n"
592 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
593 "\t-f Force overwrite of .lyx files.\n"
594 "\t-help Print this message and quit.\n"
595 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
596 "\t-skipchildren Do not translate included child documents.\n"
597 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
598 "\t-s syntaxfile read additional syntax file.\n"
599 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
600 "\t Default: " << package().system_support() << "\n"
601 "\t-userdir USERDIR Set user directory to USERDIR.\n"
602 "\t Default: " << package().user_support() << "\n"
603 "\t-version Summarize version and build info.\n"
605 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
606 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
607 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
608 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
609 "Check the tex2lyx man page for more details."
611 throw StopException(error_code);
615 int parse_version(string const &, string const &)
617 cout << "tex2lyx " << lyx_version
618 << " (" << lyx_release_date << ")" << endl;
620 cout << lyx_version_info << endl;
621 throw StopException(error_code);
625 void error_message(string const & message)
627 cerr << "tex2lyx: " << message << "\n\n";
628 error_code = EXIT_FAILURE;
629 parse_help(string(), string());
633 int parse_class(string const & arg, string const &)
636 error_message("Missing textclass string after -c switch");
642 int parse_module(string const & arg, string const &)
645 error_message("Missing modules string after -m switch");
646 split(arg, preloaded_modules, ',');
651 int parse_encoding(string const & arg, string const &)
654 error_message("Missing encoding string after -e switch");
655 default_encoding = arg;
660 int parse_fixed_encoding(string const & arg, string const &)
663 error_message("Missing encoding string after -fixedenc switch");
664 default_encoding = arg;
665 fixed_encoding = true;
670 int parse_syntaxfile(string const & arg, string const &)
673 error_message("Missing syntaxfile string after -s switch");
674 syntaxfile = internal_path(arg);
679 // Filled with the command line arguments "foo" of "-sysdir foo" or
681 string cl_system_support;
682 string cl_user_support;
685 int parse_sysdir(string const & arg, string const &)
688 error_message("Missing directory for -sysdir switch");
689 cl_system_support = internal_path(arg);
694 int parse_userdir(string const & arg, string const &)
697 error_message("Missing directory for -userdir switch");
698 cl_user_support = internal_path(arg);
703 int parse_force(string const &, string const &)
705 overwrite_files = true;
710 int parse_noweb(string const &, string const &)
717 int parse_skipchildren(string const &, string const &)
719 skip_children = true;
724 int parse_roundtrip(string const &, string const &)
731 int parse_copyfiles(string const &, string const &)
738 void TeX2LyXApp::easyParse()
740 map<string, cmd_helper> cmdmap;
742 cmdmap["-h"] = parse_help;
743 cmdmap["-help"] = parse_help;
744 cmdmap["--help"] = parse_help;
745 cmdmap["-v"] = parse_version;
746 cmdmap["-version"] = parse_version;
747 cmdmap["--version"] = parse_version;
748 cmdmap["-c"] = parse_class;
749 cmdmap["-m"] = parse_module;
750 cmdmap["-e"] = parse_encoding;
751 cmdmap["-fixedenc"] = parse_fixed_encoding;
752 cmdmap["-f"] = parse_force;
753 cmdmap["-s"] = parse_syntaxfile;
754 cmdmap["-n"] = parse_noweb;
755 cmdmap["-skipchildren"] = parse_skipchildren;
756 cmdmap["-sysdir"] = parse_sysdir;
757 cmdmap["-userdir"] = parse_userdir;
758 cmdmap["-roundtrip"] = parse_roundtrip;
759 cmdmap["-copyfiles"] = parse_copyfiles;
761 for (int i = 1; i < argc_; ++i) {
762 map<string, cmd_helper>::const_iterator it
763 = cmdmap.find(argv_[i]);
765 // don't complain if not found - may be parsed later
766 if (it == cmdmap.end()) {
767 if (argv_[i][0] == '-')
768 error_message(string("Unknown option `") + argv_[i] + "'.");
773 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
774 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
776 int const remove = 1 + it->second(arg, arg2);
778 // Now, remove used arguments by shifting
779 // the following ones remove places down.
780 os::remove_internal_args(i, remove);
782 for (int j = i; j < argc_; ++j)
783 argv_[j] = argv_[j + remove];
789 // path of the first parsed file
790 string masterFilePathLyX;
791 string masterFilePathTeX;
792 // path of the currently parsed file
793 string parentFilePathTeX;
795 } // anonymous namespace
798 string getMasterFilePath(bool input)
800 return input ? masterFilePathTeX : masterFilePathLyX;
803 string getParentFilePath(bool input)
806 return parentFilePathTeX;
807 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
808 from_utf8(parentFilePathTeX)));
809 if (rel.substr(0, 3) == "../") {
810 // The parent is not below the master - keep the path
811 return parentFilePathTeX;
813 return makeAbsPath(rel, masterFilePathLyX).absFileName();
823 bool overwriteFiles()
825 return overwrite_files;
831 return skip_children;
844 * Reads tex input from \a is and writes lyx output to \a os.
845 * Uses some common settings for the preamble, so this should only
846 * be used more than once for included documents.
847 * Caution: Overwrites the existing preamble settings if the new document
848 * contains a preamble.
849 * You must ensure that \p parentFilePathTeX is properly set before calling
852 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
853 string const & outfiledir)
855 Parser p(is, fixed_encoding ? default_encoding : string());
856 p.setEncoding(encoding);
859 preamble.parse(p, documentclass, textclass);
860 list<string> removed_modules;
861 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
862 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
863 cerr << "Could not load default modules for text class." << endl;
867 // Load preloaded modules.
868 // This needs to be done after the preamble is parsed, since the text
869 // class may not be known before. It neds to be done before parsing
870 // body, since otherwise the commands/environments provided by the
871 // modules would be parsed as ERT.
872 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
873 if (!addModule(preloaded_modules[i])) {
874 cerr << "Error: Could not load module \""
875 << preloaded_modules[i] << "\"." << endl;
879 // Ensure that the modules are not loaded again for included files
880 preloaded_modules.clear();
882 active_environments.push_back("document");
883 Context context(true, textclass);
885 // store the document language in the context to be able to handle the
886 // commands like \foreignlanguage and \textenglish etc.
887 context.font.language = preamble.defaultLanguage();
888 // parse the main text
889 parse_text(p, ss, FLAG_END, true, context);
891 // Empty document body. LyX needs at least one paragraph.
892 context.check_layout(ss);
893 context.check_end_layout(ss);
894 ss << "\n\\end_body\n\\end_document\n";
895 active_environments.pop_back();
897 // We know the used modules only after parsing the full text
898 if (!used_modules.empty()) {
899 LayoutModuleList::const_iterator const end = used_modules.end();
900 LayoutModuleList::const_iterator it = used_modules.begin();
901 for (; it != end; ++it)
902 preamble.addModule(*it);
904 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
905 cerr << "Could not write LyX file header." << endl;
913 ofdocstream parsertest("parsertest.tex");
915 parsertest << p.get_token().asInput();
916 // <origfile> and parsertest.tex should now have identical content
922 /// convert TeX from \p infilename to LyX and write it to \p os
923 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
924 string const & outfiledir)
926 // Set a sensible default encoding.
927 // This is used until an encoding command is found.
928 // For child documents use the encoding of the master, else try to
929 // detect it from the preamble, since setting an encoding of an open
930 // fstream does currently not work on OS X.
931 // Always start with ISO-8859-1, (formerly known by its latex name
932 // latin1), since ISO-8859-1 does not cause an iconv error if the
933 // actual encoding is different (bug 7509).
934 if (encoding.empty()) {
935 Encoding const * enc = 0;
936 if (preamble.inputencoding() == "auto") {
937 ifdocstream is(setEncoding("ISO-8859-1"));
938 // forbid buffering on this stream
939 is.rdbuf()->pubsetbuf(0, 0);
940 is.open(infilename.toFilesystemEncoding().c_str());
942 Parser ep(is, string());
943 ep.setEncoding("ISO-8859-1");
944 Preamble encodingpreamble;
945 string const e = encodingpreamble
946 .parseEncoding(ep, documentclass);
948 enc = encodings.fromLyXName(e, true);
951 enc = encodings.fromLyXName(
952 preamble.inputencoding(), true);
954 encoding = enc->iconvName();
956 encoding = "ISO-8859-1";
959 ifdocstream is(setEncoding(encoding));
960 // forbid buffering on this stream
961 is.rdbuf()->pubsetbuf(0, 0);
962 is.open(infilename.toFilesystemEncoding().c_str());
964 cerr << "Could not open input file \"" << infilename
965 << "\" for reading." << endl;
968 string const oldParentFilePath = parentFilePathTeX;
969 parentFilePathTeX = onlyPath(infilename.absFileName());
970 bool retval = tex2lyx(is, os, encoding, outfiledir);
971 parentFilePathTeX = oldParentFilePath;
975 } // anonymous namespace
978 bool tex2lyx(string const & infilename, FileName const & outfilename,
979 string const & encoding)
981 if (outfilename.isReadableFile()) {
982 if (overwrite_files) {
983 cerr << "Overwriting existing file "
984 << outfilename << endl;
986 cerr << "Not overwriting existing file "
987 << outfilename << endl;
991 cerr << "Creating file " << outfilename << endl;
993 ofstream os(outfilename.toFilesystemEncoding().c_str());
995 cerr << "Could not open output file \"" << outfilename
996 << "\" for writing." << endl;
1000 cerr << "Input file: " << infilename << "\n";
1001 cerr << "Output file: " << outfilename << "\n";
1003 return tex2lyx(FileName(infilename), os, encoding,
1004 outfilename.onlyPath().absFileName() + '/');
1008 bool tex2tex(string const & infilename, FileName const & outfilename,
1009 string const & encoding)
1011 if (!tex2lyx(infilename, outfilename, encoding))
1013 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1014 if (overwrite_files)
1015 command += " -f main";
1017 command += " -f none";
1019 command += " -e pdflatex ";
1021 command += " -e xetex ";
1023 command += " -e latex ";
1024 command += quoteName(outfilename.toFilesystemEncoding());
1026 if (one.startscript(Systemcall::Wait, command) == 0)
1028 cerr << "Error: Running '" << command << "' failed." << endl;
1035 int TeX2LyXApp::run()
1037 // qt changes this, and our numeric conversions require the C locale
1038 setlocale(LC_NUMERIC, "C");
1041 init_package(internal_path(os::utf8_argv(0)), string(), string());
1042 } catch (ExceptionMessage const & message) {
1043 cerr << to_utf8(message.title_) << ":\n"
1044 << to_utf8(message.details_) << endl;
1045 if (message.type_ == ErrorException)
1046 return EXIT_FAILURE;
1052 error_message("Not enough arguments.");
1055 init_package(internal_path(os::utf8_argv(0)),
1056 cl_system_support, cl_user_support);
1057 } catch (ExceptionMessage const & message) {
1058 cerr << to_utf8(message.title_) << ":\n"
1059 << to_utf8(message.details_) << endl;
1060 if (message.type_ == ErrorException)
1061 return EXIT_FAILURE;
1064 // Check that user LyX directory is ok.
1065 FileName const sup = package().user_support();
1066 if (sup.exists() && sup.isDirectory()) {
1067 string const lock_file = package().getConfigureLockName();
1068 int fd = fileLock(lock_file.c_str());
1069 if (configFileNeedsUpdate("lyxrc.defaults") ||
1070 configFileNeedsUpdate("lyxmodules.lst") ||
1071 configFileNeedsUpdate("textclass.lst") ||
1072 configFileNeedsUpdate("packages.lst") ||
1073 configFileNeedsUpdate("lyxciteengines.lst") ||
1074 configFileNeedsUpdate("xtemplates.lst"))
1075 package().reconfigureUserLyXDir("");
1076 fileUnlock(fd, lock_file.c_str());
1078 error_message("User directory does not exist.");
1080 // Now every known option is parsed. Look for input and output
1081 // file name (the latter is optional).
1082 string infilename = internal_path(os::utf8_argv(1));
1083 infilename = makeAbsPath(infilename).absFileName();
1087 outfilename = internal_path(os::utf8_argv(2));
1088 if (outfilename != "-")
1089 outfilename = makeAbsPath(outfilename).absFileName();
1091 if (outfilename == "-") {
1092 cerr << "Error: Writing to standard output is "
1093 "not supported in roundtrip mode."
1095 return EXIT_FAILURE;
1097 string texfilename = changeExtension(outfilename, ".tex");
1098 if (equivalent(FileName(infilename), FileName(texfilename))) {
1099 cerr << "Error: The input file `" << infilename
1100 << "´ would be overwritten by the TeX file exported from `"
1101 << outfilename << "´ in roundtrip mode." << endl;
1102 return EXIT_FAILURE;
1105 } else if (roundtrip) {
1106 // avoid overwriting the input file
1107 outfilename = changeExtension(infilename, ".lyx.lyx");
1109 outfilename = changeExtension(infilename, ".lyx");
1111 // Read the syntax tables
1112 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1113 if (system_syntaxfile.empty()) {
1114 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1115 return EXIT_FAILURE;
1117 if (!read_syntaxfile(system_syntaxfile))
1119 if (!syntaxfile.empty())
1120 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1123 // Read the encodings table.
1124 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1125 if (symbols_path.empty()) {
1126 cerr << "Error: Could not find file \"unicodesymbols\"."
1128 return EXIT_FAILURE;
1130 FileName const enc_path = libFileSearch(string(), "encodings");
1131 if (enc_path.empty()) {
1132 cerr << "Error: Could not find file \"encodings\"."
1134 return EXIT_FAILURE;
1136 encodings.read(enc_path, symbols_path);
1137 if (!default_encoding.empty()) {
1138 Encoding const * const enc = encodings.fromLaTeXName(
1139 default_encoding, Encoding::any, true);
1141 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1142 default_encoding = enc->iconvName();
1144 preamble.setInputencoding(enc->name());
1148 LayoutFileList::get().read();
1149 //...and the modules
1150 theModuleList.read();
1152 // The real work now.
1153 masterFilePathTeX = onlyPath(infilename);
1154 parentFilePathTeX = masterFilePathTeX;
1155 if (outfilename == "-") {
1156 // assume same directory as input file
1157 masterFilePathLyX = masterFilePathTeX;
1158 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1159 return EXIT_SUCCESS;
1161 masterFilePathLyX = onlyPath(outfilename);
1163 FileName const path(masterFilePathLyX);
1164 if (!path.isDirectory()) {
1165 if (!path.createPath()) {
1166 cerr << "Warning: Could not create directory for file `"
1167 << masterFilePathLyX << "´." << endl;
1168 return EXIT_FAILURE;
1173 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1174 return EXIT_SUCCESS;
1176 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1177 return EXIT_SUCCESS;
1180 return EXIT_FAILURE;
1183 } // anonymous namespace
1187 int main(int argc, char * argv[])
1189 //setlocale(LC_CTYPE, "");
1191 lyx::lyxerr.setStream(cerr);
1193 os::init(argc, &argv);
1195 lyx::TeX2LyXApp app(argc, argv);