3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
21 #include "LayoutFile.h"
22 #include "LayoutModuleList.h"
23 #include "ModuleList.h"
25 #include "TextClass.h"
27 #include "support/ConsoleApplication.h"
28 #include "support/convert.h"
29 #include "support/ExceptionMessage.h"
30 #include "support/filetools.h"
31 #include "support/lassert.h"
32 #include "support/lstrings.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Systemcall.h"
47 using namespace lyx::support;
48 using namespace lyx::support::os;
52 string const trimSpaceAndEol(string const & a)
54 return trim(a, " \t\n\r");
58 void split(string const & s, vector<string> & result, char delim)
60 //cerr << "split 1: '" << s << "'\n";
63 while (getline(is, t, delim))
65 //cerr << "split 2\n";
69 string join(vector<string> const & input, char const * delim)
72 for (size_t i = 0; i != input.size(); ++i) {
81 char const * const * is_known(string const & str, char const * const * what)
83 for ( ; *what; ++what)
91 // current stack of nested environments
92 vector<string> active_environments;
95 string active_environment()
97 return active_environments.empty() ? string() : active_environments.back();
101 TeX2LyXDocClass textclass;
102 CommandMap known_commands;
103 CommandMap known_environments;
104 CommandMap known_math_environments;
105 FullCommandMap possible_textclass_commands;
106 FullEnvironmentMap possible_textclass_environments;
107 FullCommandMap possible_textclass_theorems;
108 int const LYX_FORMAT = LYX_FORMAT_TEX2LYX;
111 LayoutModuleList used_modules;
112 vector<string> preloaded_modules;
115 void convertArgs(string const & o1, bool o2, vector<ArgumentType> & arguments)
117 // We have to handle the following cases:
118 // definition o1 o2 invocation result
119 // \newcommand{\foo}{bar} "" false \foo bar
120 // \newcommand{\foo}[1]{bar #1} "[1]" false \foo{x} bar x
121 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo bar
122 // \newcommand{\foo}[1][]{bar #1} "[1]" true \foo[x] bar x
123 // \newcommand{\foo}[1][x]{bar #1} "[1]" true \foo[x] bar x
124 unsigned int nargs = 0;
125 string const opt1 = rtrim(ltrim(o1, "["), "]");
126 if (isStrUnsignedInt(opt1)) {
127 // The command has arguments
128 nargs = convert<unsigned int>(opt1);
129 if (nargs > 0 && o2) {
130 // The first argument is optional
131 arguments.push_back(optional);
135 for (unsigned int i = 0; i < nargs; ++i)
136 arguments.push_back(required);
140 void add_known_command(string const & command, string const & o1,
141 bool o2, docstring const & definition)
143 vector<ArgumentType> arguments;
144 convertArgs(o1, o2, arguments);
145 known_commands[command] = arguments;
146 if (!definition.empty())
147 possible_textclass_commands[command] =
148 FullCommand(arguments, definition);
152 void add_known_environment(string const & environment, string const & o1,
153 bool o2, docstring const & beg, docstring const &end)
155 vector<ArgumentType> arguments;
156 convertArgs(o1, o2, arguments);
157 known_environments[environment] = arguments;
158 if (!beg.empty() || ! end.empty())
159 possible_textclass_environments[environment] =
160 FullEnvironment(arguments, beg, end);
164 void add_known_theorem(string const & theorem, string const & o1,
165 bool o2, docstring const & definition)
167 vector<ArgumentType> arguments;
168 convertArgs(o1, o2, arguments);
169 if (!definition.empty())
170 possible_textclass_theorems[theorem] =
171 FullCommand(arguments, definition);
175 Layout const * findLayoutWithoutModule(TextClass const & textclass,
176 string const & name, bool command)
178 DocumentClass::const_iterator it = textclass.begin();
179 DocumentClass::const_iterator en = textclass.end();
180 for (; it != en; ++it) {
181 if (it->latexname() == name &&
182 ((command && it->isCommand()) || (!command && it->isEnvironment())))
189 InsetLayout const * findInsetLayoutWithoutModule(TextClass const & textclass,
190 string const & name, bool command)
192 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
193 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
194 for (; it != en; ++it) {
195 if (it->second.latexname() == name &&
196 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
197 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
198 return &(it->second);
206 typedef map<string, DocumentClassPtr> ModuleMap;
210 bool addModule(string const & module, LayoutFile const & baseClass, LayoutModuleList & m, vector<string> & visited)
212 // avoid endless loop for circular dependency
213 vector<string>::const_iterator const vb = visited.begin();
214 vector<string>::const_iterator const ve = visited.end();
215 if (find(vb, ve, module) != ve) {
216 cerr << "Circular dependency detected for module " << module << '\n';
219 LyXModule const * const lm = theModuleList[module];
221 cerr << "Could not find module " << module << " in module list.\n";
224 bool foundone = false;
225 LayoutModuleList::const_iterator const exclmodstart = baseClass.excludedModules().begin();
226 LayoutModuleList::const_iterator const exclmodend = baseClass.excludedModules().end();
227 LayoutModuleList::const_iterator const provmodstart = baseClass.providedModules().begin();
228 LayoutModuleList::const_iterator const provmodend = baseClass.providedModules().end();
229 vector<string> const reqs = lm->getRequiredModules();
233 LayoutModuleList::const_iterator mit = m.begin();
234 LayoutModuleList::const_iterator men = m.end();
235 vector<string>::const_iterator rit = reqs.begin();
236 vector<string>::const_iterator ren = reqs.end();
237 for (; rit != ren; ++rit) {
238 if (find(mit, men, *rit) != men) {
242 if (find(provmodstart, provmodend, *rit) != provmodend) {
248 visited.push_back(module);
249 for (rit = reqs.begin(); rit != ren; ++rit) {
250 if (find(exclmodstart, exclmodend, *rit) == exclmodend) {
251 if (addModule(*rit, baseClass, m, visited)) {
261 cerr << "Could not add required modules for " << module << ".\n";
264 if (!m.moduleCanBeAdded(module, &baseClass))
273 // Create list of dummy document classes if not already done.
274 // This is needed since a module cannot be read on its own, only as
275 // part of a document class.
276 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
277 static bool init = true;
280 LyXModuleList::const_iterator const end = theModuleList.end();
281 LyXModuleList::const_iterator it = theModuleList.begin();
282 for (; it != end; ++it) {
283 string const module = it->getID();
287 if (!addModule(module, baseClass, m, v))
289 modules[module] = getDocumentClass(baseClass, m, c);
296 bool addModule(string const & module)
299 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
300 if (!used_modules.moduleCanBeAdded(module, &baseClass))
302 FileName layout_file = libFileSearch("layouts", module, "module");
303 if (textclass.read(layout_file, TextClass::MODULE)) {
304 used_modules.push_back(module);
305 // speed up further searches:
306 // the module does not need to be checked anymore.
307 ModuleMap::iterator const it = modules.find(module);
308 if (it != modules.end())
318 bool checkModule(string const & name, bool command)
320 // Cache to avoid slowdown by repated searches
321 static set<string> failed[2];
323 // Only add the module if the command was actually defined in the LyX preamble
324 bool theorem = false;
326 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
329 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
330 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
336 if (failed[command].find(name) != failed[command].end())
340 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
342 // Try to find a module that defines the command.
343 // Only add it if the definition can be found in the preamble of the
344 // style that corresponds to the command. This is a heuristic and
345 // different from the way how we parse the builtin commands of the
346 // text class (in that case we only compare the name), but it is
347 // needed since it is not unlikely that two different modules define a
348 // command with the same name.
349 ModuleMap::iterator const end = modules.end();
350 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
351 string const module = it->first;
352 if (used_modules.moduleConflicts(module, &baseClass))
354 if (findLayoutWithoutModule(textclass, name, command))
356 if (findInsetLayoutWithoutModule(textclass, name, command))
358 DocumentClassConstPtr c = it->second;
359 Layout const * layout = findLayoutWithoutModule(*c, name, command);
360 InsetLayout const * insetlayout = layout ? 0 :
361 findInsetLayoutWithoutModule(*c, name, command);
364 preamble = layout->preamble();
365 else if (insetlayout)
366 preamble = insetlayout->preamble();
367 if (preamble.empty())
371 FullCommand const & cmd =
372 possible_textclass_commands['\\' + name];
373 if (preamble.find(cmd.def) != docstring::npos)
375 } else if (theorem) {
376 FullCommand const & thm =
377 possible_textclass_theorems[name];
378 if (preamble.find(thm.def) != docstring::npos)
381 FullEnvironment const & env =
382 possible_textclass_environments[name];
383 if (preamble.find(env.beg) != docstring::npos &&
384 preamble.find(env.end) != docstring::npos)
388 FileName layout_file = libFileSearch("layouts", module, "module");
389 if (textclass.read(layout_file, TextClass::MODULE)) {
390 used_modules.push_back(module);
391 // speed up further searches:
392 // the module does not need to be checked anymore.
398 failed[command].insert(name);
403 bool isProvided(string const & name)
405 // This works only for features that are named like the LaTeX packages
406 return textclass.provides(name) || preamble.isPackageUsed(name);
410 bool noweb_mode = false;
411 bool pdflatex = false;
413 bool is_nonCJKJapanese = false;
414 bool roundtrip = false;
421 * Read one command definition from the syntax file
423 void read_command(Parser & p, string command, CommandMap & commands)
425 if (p.next_token().asInput() == "*") {
429 vector<ArgumentType> arguments;
430 while (p.next_token().cat() == catBegin ||
431 p.next_token().asInput() == "[") {
432 if (p.next_token().cat() == catBegin) {
433 string const arg = p.getArg('{', '}');
434 if (arg == "translate")
435 arguments.push_back(required);
436 else if (arg == "group")
437 arguments.push_back(req_group);
438 else if (arg == "item")
439 arguments.push_back(item);
440 else if (arg == "displaymath")
441 arguments.push_back(displaymath);
443 arguments.push_back(verbatim);
445 string const arg = p.getArg('[', ']');
447 arguments.push_back(opt_group);
449 arguments.push_back(optional);
452 commands[command] = arguments;
457 * Read a class of environments from the syntax file
459 void read_environment(Parser & p, string const & begin,
460 CommandMap & environments)
464 Token const & t = p.get_token();
465 if (t.cat() == catLetter)
466 environment += t.asInput();
467 else if (!environment.empty()) {
469 read_command(p, environment, environments);
472 if (t.cat() == catEscape && t.asInput() == "\\end") {
473 string const end = p.getArg('{', '}');
482 * Read a list of TeX commands from a reLyX compatible syntax file.
483 * Since this list is used after all commands that have a LyX counterpart
484 * are handled, it does not matter that the "syntax.default" file
485 * has almost all of them listed. For the same reason the reLyX-specific
486 * reLyXre environment is ignored.
488 bool read_syntaxfile(FileName const & file_name)
490 ifdocstream is(file_name.toFilesystemEncoding().c_str());
492 cerr << "Could not open syntax file \"" << file_name
493 << "\" for reading." << endl;
496 // We can use our TeX parser, since the syntax of the layout file is
497 // modeled after TeX.
498 // Unknown tokens are just silently ignored, this helps us to skip some
499 // reLyX specific things.
500 Parser p(is, string());
502 Token const & t = p.get_token();
503 if (t.cat() == catEscape) {
504 string const command = t.asInput();
505 if (command == "\\begin") {
506 string const name = p.getArg('{', '}');
507 if (name == "environments" || name == "reLyXre")
508 // We understand "reLyXre", but it is
509 // not as powerful as "environments".
510 read_environment(p, name,
512 else if (name == "mathenvironments")
513 read_environment(p, name,
514 known_math_environments);
516 read_command(p, command, known_commands);
524 string documentclass;
525 string default_encoding;
526 bool fixed_encoding = false;
528 bool copy_files = false;
529 bool overwrite_files = false;
530 bool skip_children = false;
533 /// return the number of arguments consumed
534 typedef int (*cmd_helper)(string const &, string const &);
537 class StopException : public exception
540 StopException(int status) : status_(status) {}
541 int status() const { return status_; }
547 /// The main application class
548 class TeX2LyXApp : public ConsoleApplication
551 TeX2LyXApp(int & argc, char * argv[])
552 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
553 argc_(argc), argv_(argv)
559 int const exit_status = run();
562 catch (StopException & e) {
575 int parse_help(string const &, string const &)
577 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
579 "\t-c textclass Declare the textclass.\n"
580 "\t-m mod1[,mod2...] Load the given modules.\n"
581 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
582 "\t-e encoding Set the default encoding (latex name).\n"
583 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
584 "\t-f Force overwrite of .lyx files.\n"
585 "\t-help Print this message and quit.\n"
586 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
587 "\t-skipchildren Do not translate included child documents.\n"
588 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
589 "\t-s syntaxfile read additional syntax file.\n"
590 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
591 "\t Default: " << package().system_support() << "\n"
592 "\t-userdir USERDIR Set user directory to USERDIR.\n"
593 "\t Default: " << package().user_support() << "\n"
594 "\t-version Summarize version and build info.\n"
596 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
597 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
598 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
599 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
600 "Check the tex2lyx man page for more details."
602 throw StopException(error_code);
606 int parse_version(string const &, string const &)
608 cout << "tex2lyx " << lyx_version
609 << " (" << lyx_release_date << ")" << endl;
611 cout << lyx_version_info << endl;
612 throw StopException(error_code);
616 void error_message(string const & message)
618 cerr << "tex2lyx: " << message << "\n\n";
619 error_code = EXIT_FAILURE;
620 parse_help(string(), string());
624 int parse_class(string const & arg, string const &)
627 error_message("Missing textclass string after -c switch");
633 int parse_module(string const & arg, string const &)
636 error_message("Missing modules string after -m switch");
637 split(arg, preloaded_modules, ',');
642 int parse_encoding(string const & arg, string const &)
645 error_message("Missing encoding string after -e switch");
646 default_encoding = arg;
651 int parse_fixed_encoding(string const & arg, string const &)
654 error_message("Missing encoding string after -fixedenc switch");
655 default_encoding = arg;
656 fixed_encoding = true;
661 int parse_syntaxfile(string const & arg, string const &)
664 error_message("Missing syntaxfile string after -s switch");
665 syntaxfile = internal_path(arg);
670 // Filled with the command line arguments "foo" of "-sysdir foo" or
672 string cl_system_support;
673 string cl_user_support;
676 int parse_sysdir(string const & arg, string const &)
679 error_message("Missing directory for -sysdir switch");
680 cl_system_support = internal_path(arg);
685 int parse_userdir(string const & arg, string const &)
688 error_message("Missing directory for -userdir switch");
689 cl_user_support = internal_path(arg);
694 int parse_force(string const &, string const &)
696 overwrite_files = true;
701 int parse_noweb(string const &, string const &)
708 int parse_skipchildren(string const &, string const &)
710 skip_children = true;
715 int parse_roundtrip(string const &, string const &)
722 int parse_copyfiles(string const &, string const &)
729 void TeX2LyXApp::easyParse()
731 map<string, cmd_helper> cmdmap;
733 cmdmap["-h"] = parse_help;
734 cmdmap["-help"] = parse_help;
735 cmdmap["--help"] = parse_help;
736 cmdmap["-v"] = parse_version;
737 cmdmap["-version"] = parse_version;
738 cmdmap["--version"] = parse_version;
739 cmdmap["-c"] = parse_class;
740 cmdmap["-m"] = parse_module;
741 cmdmap["-e"] = parse_encoding;
742 cmdmap["-fixedenc"] = parse_fixed_encoding;
743 cmdmap["-f"] = parse_force;
744 cmdmap["-s"] = parse_syntaxfile;
745 cmdmap["-n"] = parse_noweb;
746 cmdmap["-skipchildren"] = parse_skipchildren;
747 cmdmap["-sysdir"] = parse_sysdir;
748 cmdmap["-userdir"] = parse_userdir;
749 cmdmap["-roundtrip"] = parse_roundtrip;
750 cmdmap["-copyfiles"] = parse_copyfiles;
752 for (int i = 1; i < argc_; ++i) {
753 map<string, cmd_helper>::const_iterator it
754 = cmdmap.find(argv_[i]);
756 // don't complain if not found - may be parsed later
757 if (it == cmdmap.end()) {
758 if (argv_[i][0] == '-')
759 error_message(string("Unknown option `") + argv_[i] + "'.");
764 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
765 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
767 int const remove = 1 + it->second(arg, arg2);
769 // Now, remove used arguments by shifting
770 // the following ones remove places down.
771 os::remove_internal_args(i, remove);
773 for (int j = i; j < argc_; ++j)
774 argv_[j] = argv_[j + remove];
780 // path of the first parsed file
781 string masterFilePathLyX;
782 string masterFilePathTeX;
783 // path of the currently parsed file
784 string parentFilePathTeX;
786 } // anonymous namespace
789 string getMasterFilePath(bool input)
791 return input ? masterFilePathTeX : masterFilePathLyX;
794 string getParentFilePath(bool input)
797 return parentFilePathTeX;
798 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
799 from_utf8(parentFilePathTeX)));
800 if (rel.substr(0, 3) == "../") {
801 // The parent is not below the master - keep the path
802 return parentFilePathTeX;
804 return makeAbsPath(rel, masterFilePathLyX).absFileName();
814 bool overwriteFiles()
816 return overwrite_files;
822 return skip_children;
835 * Reads tex input from \a is and writes lyx output to \a os.
836 * Uses some common settings for the preamble, so this should only
837 * be used more than once for included documents.
838 * Caution: Overwrites the existing preamble settings if the new document
839 * contains a preamble.
840 * You must ensure that \p parentFilePathTeX is properly set before calling
843 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
844 string const & outfiledir)
846 Parser p(is, fixed_encoding ? default_encoding : string());
847 p.setEncoding(encoding);
850 preamble.parse(p, documentclass, textclass);
851 list<string> removed_modules;
852 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
853 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
854 cerr << "Could not load default modules for text class." << endl;
858 // Load preloaded modules.
859 // This needs to be done after the preamble is parsed, since the text
860 // class may not be known before. It neds to be done before parsing
861 // body, since otherwise the commands/environments provided by the
862 // modules would be parsed as ERT.
863 for (size_t i = 0; i < preloaded_modules.size(); ++i) {
864 if (!addModule(preloaded_modules[i])) {
865 cerr << "Error: Could not load module \""
866 << preloaded_modules[i] << "\"." << endl;
870 // Ensure that the modules are not loaded again for included files
871 preloaded_modules.clear();
873 active_environments.push_back("document");
874 Context context(true, textclass);
876 // store the document language in the context to be able to handle the
877 // commands like \foreignlanguage and \textenglish etc.
878 context.font.language = preamble.defaultLanguage();
879 // parse the main text
880 parse_text(p, ss, FLAG_END, true, context);
882 // Empty document body. LyX needs at least one paragraph.
883 context.check_layout(ss);
884 context.check_end_layout(ss);
885 ss << "\n\\end_body\n\\end_document\n";
886 active_environments.pop_back();
888 // We know the used modules only after parsing the full text
889 if (!used_modules.empty()) {
890 LayoutModuleList::const_iterator const end = used_modules.end();
891 LayoutModuleList::const_iterator it = used_modules.begin();
892 for (; it != end; ++it)
893 preamble.addModule(*it);
895 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
896 cerr << "Could not write LyX file header." << endl;
904 ofdocstream parsertest("parsertest.tex");
906 parsertest << p.get_token().asInput();
907 // <origfile> and parsertest.tex should now have identical content
913 /// convert TeX from \p infilename to LyX and write it to \p os
914 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
915 string const & outfiledir)
917 // Set a sensible default encoding.
918 // This is used until an encoding command is found.
919 // For child documents use the encoding of the master, else try to
920 // detect it from the preamble, since setting an encoding of an open
921 // fstream does currently not work on OS X.
922 // Always start with ISO-8859-1, (formerly known by its latex name
923 // latin1), since ISO-8859-1 does not cause an iconv error if the
924 // actual encoding is different (bug 7509).
925 if (encoding.empty()) {
926 Encoding const * enc = 0;
927 if (preamble.inputencoding() == "auto") {
928 ifdocstream is(setEncoding("ISO-8859-1"));
929 // forbid buffering on this stream
930 is.rdbuf()->pubsetbuf(0, 0);
931 is.open(infilename.toFilesystemEncoding().c_str());
933 Parser ep(is, string());
934 ep.setEncoding("ISO-8859-1");
935 Preamble encodingpreamble;
936 string const e = encodingpreamble
937 .parseEncoding(ep, documentclass);
939 enc = encodings.fromLyXName(e, true);
942 enc = encodings.fromLyXName(
943 preamble.inputencoding(), true);
945 encoding = enc->iconvName();
947 encoding = "ISO-8859-1";
950 ifdocstream is(setEncoding(encoding));
951 // forbid buffering on this stream
952 is.rdbuf()->pubsetbuf(0, 0);
953 is.open(infilename.toFilesystemEncoding().c_str());
955 cerr << "Could not open input file \"" << infilename
956 << "\" for reading." << endl;
959 string const oldParentFilePath = parentFilePathTeX;
960 parentFilePathTeX = onlyPath(infilename.absFileName());
961 bool retval = tex2lyx(is, os, encoding, outfiledir);
962 parentFilePathTeX = oldParentFilePath;
966 } // anonymous namespace
969 bool tex2lyx(string const & infilename, FileName const & outfilename,
970 string const & encoding)
972 if (outfilename.isReadableFile()) {
973 if (overwrite_files) {
974 cerr << "Overwriting existing file "
975 << outfilename << endl;
977 cerr << "Not overwriting existing file "
978 << outfilename << endl;
982 cerr << "Creating file " << outfilename << endl;
984 ofstream os(outfilename.toFilesystemEncoding().c_str());
986 cerr << "Could not open output file \"" << outfilename
987 << "\" for writing." << endl;
991 cerr << "Input file: " << infilename << "\n";
992 cerr << "Output file: " << outfilename << "\n";
994 return tex2lyx(FileName(infilename), os, encoding,
995 outfilename.onlyPath().absFileName() + '/');
999 bool tex2tex(string const & infilename, FileName const & outfilename,
1000 string const & encoding)
1002 if (!tex2lyx(infilename, outfilename, encoding))
1004 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1005 if (overwrite_files)
1006 command += " -f main";
1008 command += " -f none";
1010 command += " -e pdflatex ";
1012 command += " -e xetex ";
1014 command += " -e latex ";
1015 command += quoteName(outfilename.toFilesystemEncoding());
1017 if (one.startscript(Systemcall::Wait, command) == 0)
1019 cerr << "Error: Running '" << command << "' failed." << endl;
1026 int TeX2LyXApp::run()
1028 // qt changes this, and our numeric conversions require the C locale
1029 setlocale(LC_NUMERIC, "C");
1032 init_package(internal_path(os::utf8_argv(0)), string(), string());
1033 } catch (ExceptionMessage const & message) {
1034 cerr << to_utf8(message.title_) << ":\n"
1035 << to_utf8(message.details_) << endl;
1036 if (message.type_ == ErrorException)
1037 return EXIT_FAILURE;
1043 error_message("Not enough arguments.");
1046 init_package(internal_path(os::utf8_argv(0)),
1047 cl_system_support, cl_user_support);
1048 } catch (ExceptionMessage const & message) {
1049 cerr << to_utf8(message.title_) << ":\n"
1050 << to_utf8(message.details_) << endl;
1051 if (message.type_ == ErrorException)
1052 return EXIT_FAILURE;
1055 // Check that user LyX directory is ok.
1056 FileName const sup = package().user_support();
1057 if (sup.exists() && sup.isDirectory()) {
1058 string const lock_file = package().getConfigureLockName();
1059 int fd = fileLock(lock_file.c_str());
1060 if (configFileNeedsUpdate("lyxrc.defaults") ||
1061 configFileNeedsUpdate("lyxmodules.lst") ||
1062 configFileNeedsUpdate("textclass.lst") ||
1063 configFileNeedsUpdate("packages.lst") ||
1064 configFileNeedsUpdate("lyxciteengines.lst") ||
1065 configFileNeedsUpdate("xtemplates.lst"))
1066 package().reconfigureUserLyXDir("");
1067 fileUnlock(fd, lock_file.c_str());
1069 error_message("User directory does not exist.");
1071 // Now every known option is parsed. Look for input and output
1072 // file name (the latter is optional).
1073 string infilename = internal_path(os::utf8_argv(1));
1074 infilename = makeAbsPath(infilename).absFileName();
1078 outfilename = internal_path(os::utf8_argv(2));
1079 if (outfilename != "-")
1080 outfilename = makeAbsPath(outfilename).absFileName();
1082 if (outfilename == "-") {
1083 cerr << "Error: Writing to standard output is "
1084 "not supported in roundtrip mode."
1086 return EXIT_FAILURE;
1088 string texfilename = changeExtension(outfilename, ".tex");
1089 if (equivalent(FileName(infilename), FileName(texfilename))) {
1090 cerr << "Error: The input file `" << infilename
1091 << "´ would be overwritten by the TeX file exported from `"
1092 << outfilename << "´ in roundtrip mode." << endl;
1093 return EXIT_FAILURE;
1096 } else if (roundtrip) {
1097 // avoid overwriting the input file
1098 outfilename = changeExtension(infilename, ".lyx.lyx");
1100 outfilename = changeExtension(infilename, ".lyx");
1102 // Read the syntax tables
1103 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1104 if (system_syntaxfile.empty()) {
1105 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1106 return EXIT_FAILURE;
1108 if (!read_syntaxfile(system_syntaxfile))
1110 if (!syntaxfile.empty())
1111 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1114 // Read the encodings table.
1115 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1116 if (symbols_path.empty()) {
1117 cerr << "Error: Could not find file \"unicodesymbols\"."
1119 return EXIT_FAILURE;
1121 FileName const enc_path = libFileSearch(string(), "encodings");
1122 if (enc_path.empty()) {
1123 cerr << "Error: Could not find file \"encodings\"."
1125 return EXIT_FAILURE;
1127 encodings.read(enc_path, symbols_path);
1128 if (!default_encoding.empty()) {
1129 Encoding const * const enc = encodings.fromLaTeXName(
1130 default_encoding, Encoding::any, true);
1132 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1133 default_encoding = enc->iconvName();
1135 preamble.setInputencoding(enc->name());
1139 LayoutFileList::get().read();
1140 //...and the modules
1141 theModuleList.read();
1143 // The real work now.
1144 masterFilePathTeX = onlyPath(infilename);
1145 parentFilePathTeX = masterFilePathTeX;
1146 if (outfilename == "-") {
1147 // assume same directory as input file
1148 masterFilePathLyX = masterFilePathTeX;
1149 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1150 return EXIT_SUCCESS;
1152 masterFilePathLyX = onlyPath(outfilename);
1154 FileName const path(masterFilePathLyX);
1155 if (!path.isDirectory()) {
1156 if (!path.createPath()) {
1157 cerr << "Warning: Could not create directory for file `"
1158 << masterFilePathLyX << "´." << endl;
1159 return EXIT_FAILURE;
1164 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1165 return EXIT_SUCCESS;
1167 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1168 return EXIT_SUCCESS;
1171 return EXIT_FAILURE;
1174 } // anonymous namespace
1178 int main(int argc, char * argv[])
1180 //setlocale(LC_CTYPE, "");
1182 lyx::lyxerr.setStream(cerr);
1184 os::init(argc, &argv);
1186 lyx::TeX2LyXApp app(argc, argv);