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,
177 string const & latexparam)
179 for (auto const & lay : tc) {
180 if (lay.latexname() == name &&
181 (latexparam.empty() ||
182 (!lay.latexparam().empty() && suffixIs(latexparam, lay.latexparam()))) &&
183 ((command && lay.isCommand()) || (!command && lay.isEnvironment())))
190 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & tc,
191 string const & name, bool command,
192 string const & latexparam)
194 for (auto const & ilay : tc.insetLayouts()) {
195 if (ilay.second.latexname() == name &&
196 (latexparam.empty() ||
197 (!ilay.second.latexparam().empty() && suffixIs(latexparam, ilay.second.latexparam()))) &&
198 ((command && ilay.second.latextype() == InsetLayout::COMMAND) ||
199 (!command && ilay.second.latextype() == InsetLayout::ENVIRONMENT)))
200 return &(ilay.second);
208 typedef map<string, DocumentClassPtr> ModuleMap;
212 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
214 // avoid endless loop for circular dependency
215 vector<string>::const_iterator const vb = visited.begin();
216 vector<string>::const_iterator const ve = visited.end();
217 if (find(vb, ve, module) != ve) {
218 cerr << "Circular dependency detected for module " << module << '\n';
221 LyXModule const * const lm = theModuleList[module];
223 cerr << "Could not find module " << module << " in module list.\n";
226 bool foundone = false;
227 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
228 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
229 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
230 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
231 vector<string> const reqs = lm->getRequiredModules();
235 LayoutModuleList::const_iterator mit = m.begin();
236 LayoutModuleList::const_iterator men = m.end();
237 vector<string>::const_iterator rit = reqs.begin();
238 vector<string>::const_iterator ren = reqs.end();
239 for (; rit != ren; ++rit) {
240 if (find(mit, men, *rit) != men) {
244 if (find(provmodstart, provmodend, *rit) != provmodend) {
250 visited.push_back(module);
251 for (rit = reqs.begin(); rit != ren; ++rit) {
252 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
253 if (addModule(*rit, baseClass, m, visited)) {
263 cerr << "Could not add required modules for " << module << ".\n";
266 if (!m.moduleCanBeAdded(module, &baseClass))
275 // Create list of dummy document classes if not already done.
276 // This is needed since a module cannot be read on its own, only as
277 // part of a document class.
278 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
279 static bool init = true;
282 LyXModuleList::const_iterator const end = theModuleList.end();
283 LyXModuleList::const_iterator it = theModuleList.begin();
284 for (; it != end; ++it) {
285 string const module = it->getID();
288 if (!addModule(module, baseClass, m, v))
290 modules[module] = getDocumentClass(baseClass, m);
297 bool addModule(string const & module)
300 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
301 if (!used_modules.moduleCanBeAdded(module, &baseClass))
303 FileName layout_file = libFileSearch("layouts", module, "module");
304 if (textclass.read(layout_file, TextClass::MODULE)) {
305 used_modules.push_back(module);
306 // speed up further searches:
307 // the module does not need to be checked anymore.
308 ModuleMap::iterator const it = modules.find(module);
309 if (it != modules.end())
319 bool checkModule(string const & name, bool command)
321 // Cache to avoid slowdown by repated searches
322 static set<string> failed[2];
324 // Only add the module if the command was actually defined in the LyX preamble
325 bool theorem = false;
327 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
330 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
331 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
337 if (failed[command].find(name) != failed[command].end())
341 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
343 // Try to find a module that defines the command.
344 // Only add it if the definition can be found in the preamble of the
345 // style that corresponds to the command. This is a heuristic and
346 // different from the way how we parse the builtin commands of the
347 // text class (in that case we only compare the name), but it is
348 // needed since it is not unlikely that two different modules define a
349 // command with the same name.
350 ModuleMap::iterator const end = modules.end();
351 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
352 string const module = it->first;
353 if (used_modules.moduleConflicts(module, &baseClass))
355 if (findLayoutWithoutModule(textclass, name, command))
357 if (findInsetLayoutWithoutModule(textclass, name, command))
359 DocumentClassConstPtr c = it->second;
360 Layout const * layout = findLayoutWithoutModule(*c, name, command);
361 InsetLayout const * insetlayout = layout ? 0 :
362 findInsetLayoutWithoutModule(*c, name, command);
365 dpre = layout->preamble();
366 else if (insetlayout)
367 dpre = insetlayout->preamble();
372 FullCommand const & cmd =
373 possible_textclass_commands['\\' + name];
374 if (dpre.find(cmd.def) != docstring::npos)
376 } else if (theorem) {
377 FullCommand const & thm =
378 possible_textclass_theorems[name];
379 if (dpre.find(thm.def) != docstring::npos)
382 FullEnvironment const & env =
383 possible_textclass_environments[name];
384 if (dpre.find(env.beg) != docstring::npos &&
385 dpre.find(env.end) != docstring::npos)
389 FileName layout_file = libFileSearch("layouts", module, "module");
390 if (textclass.read(layout_file, TextClass::MODULE)) {
391 used_modules.push_back(module);
392 // speed up further searches:
393 // the module does not need to be checked anymore.
399 failed[command].insert(name);
404 bool isProvided(string const & name)
406 // This works only for features that are named like the LaTeX packages
407 return textclass.provides(name) || preamble.isPackageUsed(name);
411 bool noweb_mode = false;
412 bool pdflatex = false;
414 bool is_nonCJKJapanese = false;
415 bool roundtrip = false;
422 * Read one command definition from the syntax file
424 void read_command(Parser & p, string command, CommandMap & commands)
426 if (p.next_token().asInput() == "*") {
430 vector<ArgumentType> arguments;
431 while (p.next_token().cat() == catBegin ||
432 p.next_token().asInput() == "[") {
433 if (p.next_token().cat() == catBegin) {
434 string const arg = p.getArg('{', '}');
435 if (arg == "translate")
436 arguments.push_back(required);
437 else if (arg == "group")
438 arguments.push_back(req_group);
439 else if (arg == "item")
440 arguments.push_back(item);
441 else if (arg == "displaymath")
442 arguments.push_back(displaymath);
444 arguments.push_back(verbatim);
446 string const arg = p.getArg('[', ']');
448 arguments.push_back(opt_group);
450 arguments.push_back(optional);
453 commands[command] = arguments;
458 * Read a class of environments from the syntax file
460 void read_environment(Parser & p, string const & begin,
461 CommandMap & environments)
465 Token const & t = p.get_token();
466 if (t.cat() == catLetter)
467 environment += t.asInput();
468 else if (!environment.empty()) {
470 read_command(p, environment, environments);
473 if (t.cat() == catEscape && t.asInput() == "\\end") {
474 string const end = p.getArg('{', '}');
483 * Read a list of TeX commands from a reLyX compatible syntax file.
484 * Since this list is used after all commands that have a LyX counterpart
485 * are handled, it does not matter that the "syntax.default" file
486 * has almost all of them listed. For the same reason the reLyX-specific
487 * reLyXre environment is ignored.
489 bool read_syntaxfile(FileName const & file_name)
491 ifdocstream is(file_name.toFilesystemEncoding().c_str());
493 cerr << "Could not open syntax file \"" << file_name
494 << "\" for reading." << endl;
497 // We can use our TeX parser, since the syntax of the layout file is
498 // modeled after TeX.
499 // Unknown tokens are just silently ignored, this helps us to skip some
500 // reLyX specific things.
501 Parser p(is, string());
503 Token const & t = p.get_token();
504 if (t.cat() == catEscape) {
505 string const command = t.asInput();
506 if (command == "\\begin") {
507 string const name = p.getArg('{', '}');
508 if (name == "environments" || name == "reLyXre")
509 // We understand "reLyXre", but it is
510 // not as powerful as "environments".
511 read_environment(p, name,
513 else if (name == "mathenvironments")
514 read_environment(p, name,
515 known_math_environments);
517 read_command(p, command, known_commands);
525 string documentclass;
526 string default_encoding;
527 bool fixed_encoding = false;
529 bool copy_files = false;
530 bool overwrite_files = false;
531 bool skip_children = false;
534 /// return the number of arguments consumed
535 typedef int (*cmd_helper)(string const &, string const &);
538 class StopException : public exception
541 StopException(int status) : status_(status) {}
542 int status() const { return status_; }
548 /// The main application class
549 class TeX2LyXApp : public ConsoleApplication
552 TeX2LyXApp(int & argc, char * argv[])
553 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
554 argc_(argc), argv_(argv)
560 int const exit_status = run();
563 catch (StopException & e) {
576 int parse_help(string const &, string const &)
578 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
580 "\t-c textclass Declare the textclass.\n"
581 "\t-m mod1[,mod2...] Load the given modules.\n"
582 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
583 "\t-e encoding Set the default encoding (latex name).\n"
584 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
585 "\t-f Force overwrite of .lyx files.\n"
586 "\t-help Print this message and quit.\n"
587 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
588 "\t-skipchildren Do not translate included child documents.\n"
589 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
590 "\t-s syntaxfile read additional syntax file.\n"
591 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
592 "\t Default: " << package().system_support() << "\n"
593 "\t-userdir USERDIR Set user directory to USERDIR.\n"
594 "\t Default: " << package().user_support() << "\n"
595 "\t-version Summarize version and build info.\n"
597 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
598 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
599 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
600 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
601 "Check the tex2lyx man page for more details."
603 throw StopException(error_code);
607 int parse_version(string const &, string const &)
609 cout << "tex2lyx " << lyx_version
610 << " (" << lyx_release_date << ")" << endl;
612 cout << lyx_version_info << endl;
613 throw StopException(error_code);
617 void error_message(string const & message)
619 cerr << "tex2lyx: " << message << "\n\n";
620 error_code = EXIT_FAILURE;
621 parse_help(string(), string());
625 int parse_class(string const & arg, string const &)
628 error_message("Missing textclass string after -c switch");
634 int parse_module(string const & arg, string const &)
637 error_message("Missing modules string after -m switch");
638 split(arg, preloaded_modules, ',');
643 int parse_encoding(string const & arg, string const &)
646 error_message("Missing encoding string after -e switch");
647 default_encoding = arg;
652 int parse_fixed_encoding(string const & arg, string const &)
655 error_message("Missing encoding string after -fixedenc switch");
656 default_encoding = arg;
657 fixed_encoding = true;
662 int parse_syntaxfile(string const & arg, string const &)
665 error_message("Missing syntaxfile string after -s switch");
666 syntaxfile = internal_path(arg);
671 // Filled with the command line arguments "foo" of "-sysdir foo" or
673 string cl_system_support;
674 string cl_user_support;
677 int parse_sysdir(string const & arg, string const &)
680 error_message("Missing directory for -sysdir switch");
681 cl_system_support = internal_path(arg);
686 int parse_userdir(string const & arg, string const &)
689 error_message("Missing directory for -userdir switch");
690 cl_user_support = internal_path(arg);
695 int parse_force(string const &, string const &)
697 overwrite_files = true;
702 int parse_noweb(string const &, string const &)
709 int parse_skipchildren(string const &, string const &)
711 skip_children = true;
716 int parse_roundtrip(string const &, string const &)
723 int parse_copyfiles(string const &, string const &)
730 void TeX2LyXApp::easyParse()
732 map<string, cmd_helper> cmdmap;
734 cmdmap["-h"] = parse_help;
735 cmdmap["-help"] = parse_help;
736 cmdmap["--help"] = parse_help;
737 cmdmap["-v"] = parse_version;
738 cmdmap["-version"] = parse_version;
739 cmdmap["--version"] = parse_version;
740 cmdmap["-c"] = parse_class;
741 cmdmap["-m"] = parse_module;
742 cmdmap["-e"] = parse_encoding;
743 cmdmap["-fixedenc"] = parse_fixed_encoding;
744 cmdmap["-f"] = parse_force;
745 cmdmap["-s"] = parse_syntaxfile;
746 cmdmap["-n"] = parse_noweb;
747 cmdmap["-skipchildren"] = parse_skipchildren;
748 cmdmap["-sysdir"] = parse_sysdir;
749 cmdmap["-userdir"] = parse_userdir;
750 cmdmap["-roundtrip"] = parse_roundtrip;
751 cmdmap["-copyfiles"] = parse_copyfiles;
753 for (int i = 1; i < argc_; ++i) {
754 map<string, cmd_helper>::const_iterator it
755 = cmdmap.find(argv_[i]);
757 // don't complain if not found - may be parsed later
758 if (it == cmdmap.end()) {
759 if (argv_[i][0] == '-')
760 error_message(string("Unknown option `") + argv_[i] + "'.");
765 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
766 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
768 int const remove = 1 + it->second(arg, arg2);
770 // Now, remove used arguments by shifting
771 // the following ones remove places down.
772 os::remove_internal_args(i, remove);
774 for (int j = i; j < argc_; ++j)
775 argv_[j] = argv_[j + remove];
781 // path of the first parsed file
782 string masterFilePathLyX;
783 string masterFilePathTeX;
784 // path of the currently parsed file
785 string parentFilePathTeX;
787 } // anonymous namespace
790 string getMasterFilePath(bool input)
792 return input ? masterFilePathTeX : masterFilePathLyX;
795 string getParentFilePath(bool input)
798 return parentFilePathTeX;
799 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
800 from_utf8(parentFilePathTeX)));
801 if (rel.substr(0, 3) == "../") {
802 // The parent is not below the master - keep the path
803 return parentFilePathTeX;
805 return makeAbsPath(rel, masterFilePathLyX).absFileName();
815 bool overwriteFiles()
817 return overwrite_files;
823 return skip_children;
836 * Reads tex input from \a is and writes lyx output to \a os.
837 * Uses some common settings for the preamble, so this should only
838 * be used more than once for included documents.
839 * Caution: Overwrites the existing preamble settings if the new document
840 * contains a preamble.
841 * You must ensure that \p parentFilePathTeX is properly set before calling
844 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
845 string const & outfiledir)
847 Parser p(is, fixed_encoding ? default_encoding : string());
848 p.setEncoding(encoding);
851 preamble.parse(p, documentclass, textclass);
852 list<string> removed_modules;
853 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
854 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
855 cerr << "Could not load default modules for text class." << endl;
859 // Load preloaded modules.
860 // This needs to be done after the preamble is parsed, since the text
861 // class may not be known before. It neds to be done before parsing
862 // body, since otherwise the commands/environments provided by the
863 // modules would be parsed as ERT.
864 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
865 if (!addModule(preloaded_modules[i])) {
866 cerr << "Error: Could not load module \""
867 << preloaded_modules[i] << "\"." << endl;
871 // Ensure that the modules are not loaded again for included files
872 preloaded_modules.clear();
874 active_environments.push_back("document");
875 Context context(true, textclass);
877 // store the document language in the context to be able to handle the
878 // commands like \foreignlanguage and \textenglish etc.
879 context.font.language = preamble.defaultLanguage();
880 // parse the main text
881 parse_text(p, ss, FLAG_END, true, context);
882 // check if we need a commented bibtex inset (biblatex)
883 check_comment_bib(ss, context);
885 // Empty document body. LyX needs at least one paragraph.
886 context.check_layout(ss);
887 context.check_end_layout(ss);
888 ss << "\n\\end_body\n\\end_document\n";
889 active_environments.pop_back();
891 // We know the used modules only after parsing the full text
892 if (!used_modules.empty()) {
893 LayoutModuleList::const_iterator const end = used_modules.end();
894 LayoutModuleList::const_iterator it = used_modules.begin();
895 for (; it != end; ++it)
896 preamble.addModule(*it);
898 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
899 cerr << "Could not write LyX file header." << endl;
907 ofdocstream parsertest("parsertest.tex");
909 parsertest << p.get_token().asInput();
910 // <origfile> and parsertest.tex should now have identical content
916 /// convert TeX from \p infilename to LyX and write it to \p os
917 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
918 string const & outfiledir)
920 // Set a sensible default encoding.
921 // This is used until an encoding command is found.
922 // For child documents use the encoding of the master, else try to
923 // detect it from the preamble, since setting an encoding of an open
924 // fstream does currently not work on OS X.
925 // Always start with ISO-8859-1, (formerly known by its latex name
926 // latin1), since ISO-8859-1 does not cause an iconv error if the
927 // actual encoding is different (bug 7509).
928 if (encoding.empty()) {
929 Encoding const * enc = 0;
930 if (preamble.inputencoding() == "auto") {
931 ifdocstream is(setEncoding("ISO-8859-1"));
932 // forbid buffering on this stream
933 is.rdbuf()->pubsetbuf(0, 0);
934 is.open(infilename.toFilesystemEncoding().c_str());
936 Parser ep(is, string());
937 ep.setEncoding("ISO-8859-1");
938 Preamble encodingpreamble;
939 string const e = encodingpreamble
940 .parseEncoding(ep, documentclass);
942 enc = encodings.fromLyXName(e, true);
945 enc = encodings.fromLyXName(
946 preamble.inputencoding(), true);
948 encoding = enc->iconvName();
950 encoding = "ISO-8859-1";
953 ifdocstream is(setEncoding(encoding));
954 // forbid buffering on this stream
955 is.rdbuf()->pubsetbuf(0, 0);
956 is.open(infilename.toFilesystemEncoding().c_str());
958 cerr << "Could not open input file \"" << infilename
959 << "\" for reading." << endl;
962 string const oldParentFilePath = parentFilePathTeX;
963 parentFilePathTeX = onlyPath(infilename.absFileName());
964 bool retval = tex2lyx(is, os, encoding, outfiledir);
965 parentFilePathTeX = oldParentFilePath;
969 } // anonymous namespace
972 bool tex2lyx(string const & infilename, FileName const & outfilename,
973 string const & encoding)
975 if (outfilename.isReadableFile()) {
976 if (overwrite_files) {
977 cerr << "Overwriting existing file "
978 << outfilename << endl;
980 cerr << "Not overwriting existing file "
981 << outfilename << endl;
985 cerr << "Creating file " << outfilename << endl;
987 ofstream os(outfilename.toFilesystemEncoding().c_str());
989 cerr << "Could not open output file \"" << outfilename
990 << "\" for writing." << endl;
994 cerr << "Input file: " << infilename << "\n";
995 cerr << "Output file: " << outfilename << "\n";
997 return tex2lyx(FileName(infilename), os, encoding,
998 outfilename.onlyPath().absFileName() + '/');
1002 bool tex2tex(string const & infilename, FileName const & outfilename,
1003 string const & encoding)
1005 if (!tex2lyx(infilename, outfilename, encoding))
1007 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1008 if (overwrite_files)
1009 command += " -f main";
1011 command += " -f none";
1013 command += " -e pdflatex ";
1015 command += " -e xetex ";
1017 command += " -e latex ";
1018 command += quoteName(outfilename.toFilesystemEncoding());
1020 if (one.startscript(Systemcall::Wait, command) == 0)
1022 cerr << "Error: Running '" << command << "' failed." << endl;
1029 int TeX2LyXApp::run()
1031 // qt changes this, and our numeric conversions require the C locale
1032 setlocale(LC_NUMERIC, "C");
1035 init_package(internal_path(os::utf8_argv(0)), string(), string());
1036 } catch (ExceptionMessage const & message) {
1037 cerr << to_utf8(message.title_) << ":\n"
1038 << to_utf8(message.details_) << endl;
1039 if (message.type_ == ErrorException)
1040 return EXIT_FAILURE;
1046 error_message("Not enough arguments.");
1049 init_package(internal_path(os::utf8_argv(0)),
1050 cl_system_support, cl_user_support);
1051 } catch (ExceptionMessage const & message) {
1052 cerr << to_utf8(message.title_) << ":\n"
1053 << to_utf8(message.details_) << endl;
1054 if (message.type_ == ErrorException)
1055 return EXIT_FAILURE;
1058 // Check that user LyX directory is ok.
1059 FileName const sup = package().user_support();
1060 if (sup.exists() && sup.isDirectory()) {
1061 string const lock_file = package().getConfigureLockName();
1062 int fd = fileLock(lock_file.c_str());
1063 if (configFileNeedsUpdate("lyxrc.defaults") ||
1064 configFileNeedsUpdate("lyxmodules.lst") ||
1065 configFileNeedsUpdate("textclass.lst") ||
1066 configFileNeedsUpdate("packages.lst") ||
1067 configFileNeedsUpdate("lyxciteengines.lst") ||
1068 configFileNeedsUpdate("xtemplates.lst"))
1069 package().reconfigureUserLyXDir("");
1070 fileUnlock(fd, lock_file.c_str());
1072 error_message("User directory does not exist.");
1074 // Now every known option is parsed. Look for input and output
1075 // file name (the latter is optional).
1076 string infilename = internal_path(os::utf8_argv(1));
1077 infilename = makeAbsPath(infilename).absFileName();
1081 outfilename = internal_path(os::utf8_argv(2));
1082 if (outfilename != "-")
1083 outfilename = makeAbsPath(outfilename).absFileName();
1085 if (outfilename == "-") {
1086 cerr << "Error: Writing to standard output is "
1087 "not supported in roundtrip mode."
1089 return EXIT_FAILURE;
1091 string texfilename = changeExtension(outfilename, ".tex");
1092 if (equivalent(FileName(infilename), FileName(texfilename))) {
1093 cerr << "Error: The input file `" << infilename
1094 << "´ would be overwritten by the TeX file exported from `"
1095 << outfilename << "´ in roundtrip mode." << endl;
1096 return EXIT_FAILURE;
1099 } else if (roundtrip) {
1100 // avoid overwriting the input file
1101 outfilename = changeExtension(infilename, ".lyx.lyx");
1103 outfilename = changeExtension(infilename, ".lyx");
1105 // Read the syntax tables
1106 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1107 if (system_syntaxfile.empty()) {
1108 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1109 return EXIT_FAILURE;
1111 if (!read_syntaxfile(system_syntaxfile))
1113 if (!syntaxfile.empty())
1114 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1117 // Read the encodings table.
1118 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1119 if (symbols_path.empty()) {
1120 cerr << "Error: Could not find file \"unicodesymbols\"."
1122 return EXIT_FAILURE;
1124 FileName const enc_path = libFileSearch(string(), "encodings");
1125 if (enc_path.empty()) {
1126 cerr << "Error: Could not find file \"encodings\"."
1128 return EXIT_FAILURE;
1130 encodings.read(enc_path, symbols_path);
1131 if (!default_encoding.empty()) {
1132 Encoding const * const enc = encodings.fromLaTeXName(
1133 default_encoding, Encoding::any, true);
1135 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1136 default_encoding = enc->iconvName();
1138 preamble.setInputencoding(enc->name());
1142 LayoutFileList::get().read();
1143 //...and the modules
1144 theModuleList.read();
1146 // The real work now.
1147 masterFilePathTeX = onlyPath(infilename);
1148 parentFilePathTeX = masterFilePathTeX;
1149 if (outfilename == "-") {
1150 // assume same directory as input file
1151 masterFilePathLyX = masterFilePathTeX;
1152 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1153 return EXIT_SUCCESS;
1155 masterFilePathLyX = onlyPath(outfilename);
1157 FileName const path(masterFilePathLyX);
1158 if (!path.isDirectory()) {
1159 if (!path.createPath()) {
1160 cerr << "Warning: Could not create directory for file `"
1161 << masterFilePathLyX << "´." << endl;
1162 return EXIT_FAILURE;
1167 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1168 return EXIT_SUCCESS;
1170 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1171 return EXIT_SUCCESS;
1174 return EXIT_FAILURE;
1177 } // anonymous namespace
1181 int main(int argc, char * argv[])
1183 //setlocale(LC_CTYPE, "");
1185 lyx::lyxerr.setStream(cerr);
1187 os::init(argc, &argv);
1189 lyx::TeX2LyXApp app(argc, argv);