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"
26 #include "support/ConsoleApplication.h"
27 #include "support/convert.h"
28 #include "support/debug.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() == InsetLaTeXType::COMMAND) ||
199 (!command && ilay.second.latextype() == InsetLaTeXType::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 // Record whether the command was actually defined in the LyX preamble
325 bool theorem = false;
326 bool preamble_def = true;
328 if (possible_textclass_commands.find('\\' + name) == possible_textclass_commands.end())
329 preamble_def = false;
331 if (possible_textclass_environments.find(name) == possible_textclass_environments.end()) {
332 if (possible_textclass_theorems.find(name) != possible_textclass_theorems.end())
335 preamble_def = false;
338 if (failed[command].find(name) != failed[command].end())
342 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
344 // Try to find a module that defines the command.
345 // For commands with preamble definitions we prefer modules where the definition
346 // can be found in the preamble of the style that corresponds to the command.
347 // For others we check whether the command or module requires a package that is loaded
348 // in the tex file and use a style with the respective command.
349 // This is a heuristic and different from the way how we parse the builtin
350 // commands of the text class (in that case we only compare the name),
351 // but it is needed since it is not unlikely that two different modules define a
352 // command with the same name.
354 vector<string> potential_modules;
355 ModuleMap::iterator const end = modules.end();
356 for (ModuleMap::iterator it = modules.begin(); it != end; ++it) {
357 string const module = it->first;
358 if (used_modules.moduleConflicts(module, &baseClass))
360 if (findLayoutWithoutModule(textclass, name, command))
362 if (findInsetLayoutWithoutModule(textclass, name, command))
364 DocumentClassConstPtr c = it->second;
365 Layout const * layout = findLayoutWithoutModule(*c, name, command);
366 InsetLayout const * insetlayout = layout ? nullptr :
367 findInsetLayoutWithoutModule(*c, name, command);
369 std::set<std::string> cmd_reqs;
370 bool found_style = false;
373 dpre = layout->preamble();
374 std::set<std::string> const & lreqs = layout->required();
376 cmd_reqs.insert(lreqs.begin(), lreqs.end());
377 } else if (insetlayout) {
379 dpre = insetlayout->preamble();
380 std::set<std::string> lreqs = insetlayout->required();
382 cmd_reqs.insert(lreqs.begin(), lreqs.end());
384 if (dpre.empty() && preamble_def)
386 bool const package_cmd = dpre.empty();
387 bool match_req = false;
389 std::set<std::string> mreqs = it->second->required();
391 cmd_reqs.insert(mreqs.begin(), mreqs.end());
392 for (auto const & pack : cmd_reqs) {
393 // If a requirement of the module matches a used package
394 // we load the module except if we have an auto-loaded package
395 // which is only required generally by the module, and the module
396 // does not provide the [inset]layout we are looking for.
397 // This heuristics should
398 // * load modules if the provide a style we don't have in the class
399 // * load modules that provide a package support generally (such as fixltx2e)
400 // * not unnecessarily load modules just because they require a package which we
402 if (preamble.isPackageUsed(pack)
403 && (found_style || !preamble.isPackageAutoLoaded(pack))) {
407 potential_modules.push_back(module);
412 bool add = match_req;
415 FullCommand const & cmd =
416 possible_textclass_commands['\\' + name];
417 if (dpre.find(cmd.def) != docstring::npos)
419 } else if (theorem) {
420 FullCommand const & thm =
421 possible_textclass_theorems[name];
422 if (dpre.find(thm.def) != docstring::npos)
425 FullEnvironment const & env =
426 possible_textclass_environments[name];
427 if (dpre.find(env.beg) != docstring::npos &&
428 dpre.find(env.end) != docstring::npos)
433 found_module = module;
437 if (found_module.empty()) {
438 // take one of the second row
439 if (!potential_modules.empty())
440 found_module = potential_modules.front();
443 if (!found_module.empty()) {
445 LayoutModuleList mods;
446 // addModule is necessary in order to catch required modules
447 // as well (see #11156)
448 if (!addModule(found_module, baseClass, mods, v))
450 for (auto const & mod : mods) {
451 if (!used_modules.moduleCanBeAdded(mod, &baseClass))
453 FileName layout_file = libFileSearch("layouts", mod, "module");
454 if (textclass.read(layout_file, TextClass::MODULE)) {
455 used_modules.push_back(mod);
456 // speed up further searches:
457 // the module does not need to be checked anymore.
458 ModuleMap::iterator const it = modules.find(mod);
459 if (it != modules.end())
465 failed[command].insert(name);
470 bool isProvided(string const & name)
472 // This works only for features that are named like the LaTeX packages
473 return textclass.provides(name) || preamble.isPackageUsed(name);
477 bool noweb_mode = false;
478 bool pdflatex = false;
480 bool is_nonCJKJapanese = false;
481 bool roundtrip = false;
488 * Read one command definition from the syntax file
490 void read_command(Parser & p, string command, CommandMap & commands)
492 if (p.next_token().asInput() == "*") {
496 vector<ArgumentType> arguments;
497 while (p.next_token().cat() == catBegin ||
498 p.next_token().asInput() == "[") {
499 if (p.next_token().cat() == catBegin) {
500 string const arg = p.getArg('{', '}');
501 if (arg == "translate")
502 arguments.push_back(required);
503 else if (arg == "group")
504 arguments.push_back(req_group);
505 else if (arg == "item")
506 arguments.push_back(item);
507 else if (arg == "displaymath")
508 arguments.push_back(displaymath);
510 arguments.push_back(verbatim);
512 string const arg = p.getArg('[', ']');
514 arguments.push_back(opt_group);
516 arguments.push_back(optional);
519 commands[command] = arguments;
524 * Read a class of environments from the syntax file
526 void read_environment(Parser & p, string const & begin,
527 CommandMap & environments)
531 Token const & t = p.get_token();
532 if (t.cat() == catLetter)
533 environment += t.asInput();
534 else if (!environment.empty()) {
536 read_command(p, environment, environments);
539 if (t.cat() == catEscape && t.asInput() == "\\end") {
540 string const end = p.getArg('{', '}');
549 * Read a list of TeX commands from a reLyX compatible syntax file.
550 * Since this list is used after all commands that have a LyX counterpart
551 * are handled, it does not matter that the "syntax.default" file
552 * has almost all of them listed. For the same reason the reLyX-specific
553 * reLyXre environment is ignored.
555 bool read_syntaxfile(FileName const & file_name)
557 ifdocstream is(file_name.toFilesystemEncoding().c_str());
559 cerr << "Could not open syntax file \"" << file_name
560 << "\" for reading." << endl;
563 // We can use our TeX parser, since the syntax of the layout file is
564 // modeled after TeX.
565 // Unknown tokens are just silently ignored, this helps us to skip some
566 // reLyX specific things.
567 Parser p(is, string());
569 Token const & t = p.get_token();
570 if (t.cat() == catEscape) {
571 string const command = t.asInput();
572 if (command == "\\begin") {
573 string const name = p.getArg('{', '}');
574 if (name == "environments" || name == "reLyXre")
575 // We understand "reLyXre", but it is
576 // not as powerful as "environments".
577 read_environment(p, name,
579 else if (name == "mathenvironments")
580 read_environment(p, name,
581 known_math_environments);
583 read_command(p, command, known_commands);
591 string documentclass;
592 string default_encoding;
593 bool fixed_encoding = false;
595 bool copy_files = false;
596 bool overwrite_files = false;
597 bool skip_children = false;
600 /// return the number of arguments consumed
601 typedef int (*cmd_helper)(string const &, string const &);
604 class StopException : public exception
607 StopException(int status) : status_(status) {}
608 int status() const { return status_; }
614 /// The main application class
615 class TeX2LyXApp : public ConsoleApplication
618 TeX2LyXApp(int & argc, char * argv[])
619 : ConsoleApplication("tex2lyx" PROGRAM_SUFFIX, argc, argv),
620 argc_(argc), argv_(argv)
623 void doExec() override
626 int const exit_status = run();
629 catch (StopException & e) {
642 int parse_help(string const &, string const &)
644 cout << "Usage: tex2lyx [options] infile.tex [outfile.lyx]\n"
646 "\t-c textclass Declare the textclass.\n"
647 "\t-m mod1[,mod2...] Load the given modules.\n"
648 "\t-copyfiles Copy all included files to the directory of outfile.lyx.\n"
649 "\t-e encoding Set the default encoding (latex name).\n"
650 "\t-fixedenc encoding Like -e, but ignore encoding changing commands while parsing.\n"
651 "\t-f Force overwrite of .lyx files.\n"
652 "\t-help Print this message and quit.\n"
653 "\t-n translate literate programming (noweb, sweave,... ) file.\n"
654 "\t-skipchildren Do not translate included child documents.\n"
655 "\t-roundtrip re-export created .lyx file infile.lyx.lyx to infile.lyx.tex.\n"
656 "\t-s syntaxfile read additional syntax file.\n"
657 "\t-sysdir SYSDIR Set system directory to SYSDIR.\n"
658 "\t Default: " << package().system_support() << "\n"
659 "\t-userdir USERDIR Set user directory to USERDIR.\n"
660 "\t Default: " << package().user_support() << "\n"
661 "\t-version Summarize version and build info.\n"
663 "\tThe program searches for the files \"encodings\", \"lyxmodules.lst\",\n"
664 "\t\"textclass.lst\", \"syntax.default\", and \"unicodesymbols\", first in\n"
665 "\t\"USERDIR\", then in \"SYSDIR\". The subdirectories \"USERDIR/layouts\"\n"
666 "\tand \"SYSDIR/layouts\" are searched for layout and module files.\n"
667 "Check the tex2lyx man page for more details."
669 throw StopException(error_code);
673 int parse_version(string const &, string const &)
675 cout << "tex2lyx " << lyx_version
676 << " (" << lyx_release_date << ")" << endl;
678 cout << lyx_version_info << endl;
679 throw StopException(error_code);
683 void error_message(string const & message)
685 cerr << "tex2lyx: " << message << "\n\n";
686 error_code = EXIT_FAILURE;
687 parse_help(string(), string());
691 int parse_class(string const & arg, string const &)
694 error_message("Missing textclass string after -c switch");
700 int parse_module(string const & arg, string const &)
702 split(arg, preloaded_modules, ',');
707 int parse_encoding(string const & arg, string const &)
710 error_message("Missing encoding string after -e switch");
711 default_encoding = arg;
716 int parse_fixed_encoding(string const & arg, string const &)
719 error_message("Missing encoding string after -fixedenc switch");
720 default_encoding = arg;
721 fixed_encoding = true;
726 int parse_syntaxfile(string const & arg, string const &)
729 error_message("Missing syntaxfile string after -s switch");
730 syntaxfile = internal_path(arg);
735 // Filled with the command line arguments "foo" of "-sysdir foo" or
737 string cl_system_support;
738 string cl_user_support;
741 int parse_sysdir(string const & arg, string const &)
744 error_message("Missing directory for -sysdir switch");
745 cl_system_support = internal_path(arg);
750 int parse_userdir(string const & arg, string const &)
753 error_message("Missing directory for -userdir switch");
754 cl_user_support = internal_path(arg);
759 int parse_force(string const &, string const &)
761 overwrite_files = true;
766 int parse_noweb(string const &, string const &)
773 int parse_skipchildren(string const &, string const &)
775 skip_children = true;
780 int parse_roundtrip(string const &, string const &)
787 int parse_copyfiles(string const &, string const &)
794 void TeX2LyXApp::easyParse()
796 map<string, cmd_helper> cmdmap;
798 cmdmap["-h"] = parse_help;
799 cmdmap["-help"] = parse_help;
800 cmdmap["--help"] = parse_help;
801 cmdmap["-v"] = parse_version;
802 cmdmap["-version"] = parse_version;
803 cmdmap["--version"] = parse_version;
804 cmdmap["-c"] = parse_class;
805 cmdmap["-m"] = parse_module;
806 cmdmap["-e"] = parse_encoding;
807 cmdmap["-fixedenc"] = parse_fixed_encoding;
808 cmdmap["-f"] = parse_force;
809 cmdmap["-s"] = parse_syntaxfile;
810 cmdmap["-n"] = parse_noweb;
811 cmdmap["-skipchildren"] = parse_skipchildren;
812 cmdmap["-sysdir"] = parse_sysdir;
813 cmdmap["-userdir"] = parse_userdir;
814 cmdmap["-roundtrip"] = parse_roundtrip;
815 cmdmap["-copyfiles"] = parse_copyfiles;
817 for (int i = 1; i < argc_; ++i) {
818 map<string, cmd_helper>::const_iterator it
819 = cmdmap.find(argv_[i]);
821 // don't complain if not found - may be parsed later
822 if (it == cmdmap.end()) {
823 if (argv_[i][0] == '-')
824 error_message(string("Unknown option `") + argv_[i] + "'.");
829 string arg = (i + 1 < argc_) ? os::utf8_argv(i + 1) : string();
830 string arg2 = (i + 2 < argc_) ? os::utf8_argv(i + 2) : string();
832 int const remove = 1 + it->second(arg, arg2);
834 // Now, remove used arguments by shifting
835 // the following ones remove places down.
836 os::remove_internal_args(i, remove);
838 for (int j = i; j < argc_; ++j)
839 argv_[j] = argv_[j + remove];
845 // path of the first parsed file
846 string masterFilePathLyX;
847 string masterFilePathTeX;
848 // path of the currently parsed file
849 string parentFilePathTeX;
851 } // anonymous namespace
854 string getMasterFilePath(bool input)
856 return input ? masterFilePathTeX : masterFilePathLyX;
859 string getParentFilePath(bool input)
862 return parentFilePathTeX;
863 string const rel = to_utf8(makeRelPath(from_utf8(masterFilePathTeX),
864 from_utf8(parentFilePathTeX)));
865 if (rel.substr(0, 3) == "../") {
866 // The parent is not below the master - keep the path
867 return parentFilePathTeX;
869 return makeAbsPath(rel, masterFilePathLyX).absFileName();
879 bool overwriteFiles()
881 return overwrite_files;
887 return skip_children;
900 * Reads tex input from \a is and writes lyx output to \a os.
901 * Uses some common settings for the preamble, so this should only
902 * be used more than once for included documents.
903 * Caution: Overwrites the existing preamble settings if the new document
904 * contains a preamble.
905 * You must ensure that \p parentFilePathTeX is properly set before calling
908 bool tex2lyx(idocstream & is, ostream & os, string const & encoding,
909 string const & outfiledir)
911 Parser p(is, fixed_encoding ? default_encoding : string());
912 p.setEncoding(encoding);
915 preamble.parse(p, documentclass, textclass);
916 list<string> removed_modules;
917 LayoutFile const & baseClass = LayoutFileList::get()[textclass.name()];
918 if (!used_modules.adaptToBaseClass(&baseClass, removed_modules)) {
919 cerr << "Could not load default modules for text class." << endl;
923 // Load preloaded modules.
924 // This needs to be done after the preamble is parsed, since the text
925 // class may not be known before. It needs to be done before parsing
926 // body, since otherwise the commands/environments provided by the
927 // modules would be parsed as ERT.
928 // Empty module names are silently skipped.
929 for (auto const & module : preloaded_modules) {
930 if (!module.empty() && !addModule(module)) {
931 cerr << "Error: Could not load module \""
932 << module << "\"." << endl;
936 // Ensure that the modules are not loaded again for included files
937 preloaded_modules.clear();
939 active_environments.push_back("document");
940 Context context(true, textclass);
942 // store the document language in the context to be able to handle the
943 // commands like \foreignlanguage and \textenglish etc.
944 context.font.language = preamble.defaultLanguage();
945 // parse the main text
946 parse_text(p, ss, FLAG_END, true, context);
947 // check if we need a commented bibtex inset (biblatex)
948 check_comment_bib(ss, context);
950 // Empty document body. LyX needs at least one paragraph.
951 context.check_layout(ss);
952 context.check_end_layout(ss);
953 ss << "\n\\end_body\n\\end_document\n";
954 active_environments.pop_back();
956 // We know the used modules only after parsing the full text
957 if (!used_modules.empty()) {
958 LayoutModuleList::const_iterator const end = used_modules.end();
959 LayoutModuleList::const_iterator it = used_modules.begin();
960 for (; it != end; ++it)
961 preamble.addModule(*it);
963 if (!preamble.writeLyXHeader(os, !active_environments.empty(), outfiledir)) {
964 cerr << "Could not write LyX file header." << endl;
972 ofdocstream parsertest("parsertest.tex");
974 parsertest << p.get_token().asInput();
975 // <origfile> and parsertest.tex should now have identical content
981 /// convert TeX from \p infilename to LyX and write it to \p os
982 bool tex2lyx(FileName const & infilename, ostream & os, string encoding,
983 string const & outfiledir)
985 // Set a sensible default encoding.
986 // This is used until an encoding command is found.
987 // For child documents use the encoding of the master, else try to
988 // detect it from the preamble, since setting an encoding of an open
989 // fstream does currently not work on OS X.
990 // Always start with ISO-8859-1, (formerly known by its latex name
991 // latin1), since ISO-8859-1 does not cause an iconv error if the
992 // actual encoding is different (bug 7509).
993 if (encoding.empty()) {
994 Encoding const * enc = 0;
995 if (preamble.inputencoding() == "auto-legacy") {
996 ifdocstream is(setEncoding("ISO-8859-1"));
997 // forbid buffering on this stream
998 is.rdbuf()->pubsetbuf(0, 0);
999 is.open(infilename.toFilesystemEncoding().c_str());
1001 Parser ep(is, string());
1002 ep.setEncoding("ISO-8859-1");
1003 Preamble encodingpreamble;
1004 string const e = encodingpreamble
1005 .parseEncoding(ep, documentclass);
1007 enc = encodings.fromLyXName(e, true);
1010 enc = encodings.fromLyXName(
1011 preamble.inputencoding(), true);
1013 encoding = enc->iconvName();
1015 encoding = "ISO-8859-1";
1017 preamble.docencoding = encoding;
1020 ifdocstream is(setEncoding(encoding));
1021 // forbid buffering on this stream
1022 is.rdbuf()->pubsetbuf(0, 0);
1023 is.open(infilename.toFilesystemEncoding().c_str());
1025 cerr << "Could not open input file \"" << infilename
1026 << "\" for reading." << endl;
1029 string const oldParentFilePath = parentFilePathTeX;
1030 parentFilePathTeX = onlyPath(infilename.absFileName());
1031 bool retval = tex2lyx(is, os, encoding, outfiledir);
1032 parentFilePathTeX = oldParentFilePath;
1036 } // anonymous namespace
1039 bool tex2lyx(string const & infilename, FileName const & outfilename,
1040 string const & encoding)
1042 if (outfilename.isReadableFile()) {
1043 if (overwrite_files) {
1044 cerr << "Overwriting existing file "
1045 << outfilename << endl;
1047 cerr << "Not overwriting existing file "
1048 << outfilename << endl;
1052 cerr << "Creating file " << outfilename << endl;
1054 ofstream os(outfilename.toFilesystemEncoding().c_str());
1056 cerr << "Could not open output file \"" << outfilename
1057 << "\" for writing." << endl;
1061 cerr << "Input file: " << infilename << "\n";
1062 cerr << "Output file: " << outfilename << "\n";
1064 return tex2lyx(FileName(infilename), os, encoding,
1065 outfilename.onlyPath().absFileName() + '/');
1069 bool tex2tex(string const & infilename, FileName const & outfilename,
1070 string const & encoding)
1072 if (!tex2lyx(infilename, outfilename, encoding))
1074 string command = quoteName(package().lyx_binary().toFilesystemEncoding());
1075 if (overwrite_files)
1076 command += " -f main";
1078 command += " -f none";
1080 command += " -e pdflatex ";
1082 command += " -e xetex ";
1084 command += " -e latex ";
1085 command += quoteName(outfilename.toFilesystemEncoding());
1087 if (one.startscript(Systemcall::Wait, command) == 0)
1089 cerr << "Error: Running '" << command << "' failed." << endl;
1096 int TeX2LyXApp::run()
1098 // qt changes this, and our numeric conversions require the C locale
1099 setlocale(LC_NUMERIC, "C");
1102 init_package(internal_path(os::utf8_argv(0)), string(), string());
1103 } catch (ExceptionMessage const & message) {
1104 cerr << to_utf8(message.title_) << ":\n"
1105 << to_utf8(message.details_) << endl;
1106 if (message.type_ == ErrorException)
1107 return EXIT_FAILURE;
1113 error_message("Not enough arguments.");
1116 init_package(internal_path(os::utf8_argv(0)),
1117 cl_system_support, cl_user_support);
1118 } catch (ExceptionMessage const & message) {
1119 cerr << to_utf8(message.title_) << ":\n"
1120 << to_utf8(message.details_) << endl;
1121 if (message.type_ == ErrorException)
1122 return EXIT_FAILURE;
1125 // Check that user LyX directory is ok.
1126 FileName const sup = package().user_support();
1127 if (sup.exists() && sup.isDirectory()) {
1128 string const lock_file = package().getConfigureLockName();
1129 int fd = fileLock(lock_file.c_str());
1130 if (configFileNeedsUpdate("lyxrc.defaults") ||
1131 configFileNeedsUpdate("lyxmodules.lst") ||
1132 configFileNeedsUpdate("textclass.lst") ||
1133 configFileNeedsUpdate("packages.lst") ||
1134 configFileNeedsUpdate("lyxciteengines.lst") ||
1135 configFileNeedsUpdate("xtemplates.lst"))
1136 package().reconfigureUserLyXDir("");
1137 fileUnlock(fd, lock_file.c_str());
1139 error_message("User directory does not exist.");
1141 // Now every known option is parsed. Look for input and output
1142 // file name (the latter is optional).
1143 string infilename = internal_path(os::utf8_argv(1));
1144 infilename = makeAbsPath(infilename).absFileName();
1148 outfilename = internal_path(os::utf8_argv(2));
1149 if (outfilename != "-")
1150 outfilename = makeAbsPath(outfilename).absFileName();
1152 if (outfilename == "-") {
1153 cerr << "Error: Writing to standard output is "
1154 "not supported in roundtrip mode."
1156 return EXIT_FAILURE;
1158 string texfilename = changeExtension(outfilename, ".tex");
1159 if (equivalent(FileName(infilename), FileName(texfilename))) {
1160 cerr << "Error: The input file `" << infilename
1161 << "´ would be overwritten by the TeX file exported from `"
1162 << outfilename << "´ in roundtrip mode." << endl;
1163 return EXIT_FAILURE;
1166 } else if (roundtrip) {
1167 // avoid overwriting the input file
1168 outfilename = changeExtension(infilename, ".lyx.lyx");
1170 outfilename = changeExtension(infilename, ".lyx");
1172 // Read the syntax tables
1173 FileName const system_syntaxfile = libFileSearch("", "syntax.default");
1174 if (system_syntaxfile.empty()) {
1175 cerr << "Error: Could not find syntax file \"syntax.default\"." << endl;
1176 return EXIT_FAILURE;
1178 if (!read_syntaxfile(system_syntaxfile))
1180 if (!syntaxfile.empty())
1181 if (!read_syntaxfile(makeAbsPath(syntaxfile)))
1184 // Read the encodings table.
1185 FileName const symbols_path = libFileSearch(string(), "unicodesymbols");
1186 if (symbols_path.empty()) {
1187 cerr << "Error: Could not find file \"unicodesymbols\"."
1189 return EXIT_FAILURE;
1191 FileName const enc_path = libFileSearch(string(), "encodings");
1192 if (enc_path.empty()) {
1193 cerr << "Error: Could not find file \"encodings\"."
1195 return EXIT_FAILURE;
1197 encodings.read(enc_path, symbols_path);
1198 if (!default_encoding.empty()) {
1199 Encoding const * const enc = encodings.fromLaTeXName(
1200 default_encoding, Encoding::any, true);
1202 error_message("Unknown LaTeX encoding `" + default_encoding + "'");
1203 default_encoding = enc->iconvName();
1205 preamble.setInputencoding(enc->name());
1209 LayoutFileList::get().read();
1210 //...and the modules
1211 theModuleList.read();
1213 // The real work now.
1214 masterFilePathTeX = onlyPath(infilename);
1215 parentFilePathTeX = masterFilePathTeX;
1216 if (outfilename == "-") {
1217 // assume same directory as input file
1218 masterFilePathLyX = masterFilePathTeX;
1219 if (tex2lyx(FileName(infilename), cout, default_encoding, masterFilePathLyX))
1220 return EXIT_SUCCESS;
1222 masterFilePathLyX = onlyPath(outfilename);
1224 FileName const path(masterFilePathLyX);
1225 if (!path.isDirectory()) {
1226 if (!path.createPath()) {
1227 cerr << "Warning: Could not create directory for file `"
1228 << masterFilePathLyX << "´." << endl;
1229 return EXIT_FAILURE;
1234 if (tex2tex(infilename, FileName(outfilename), default_encoding))
1235 return EXIT_SUCCESS;
1237 if (lyx::tex2lyx(infilename, FileName(outfilename), default_encoding))
1238 return EXIT_SUCCESS;
1241 return EXIT_FAILURE;
1244 } // anonymous namespace
1248 int main(int argc, char * argv[])
1250 //setlocale(LC_CTYPE, "");
1252 lyx::lyxerr.setStream(cerr);
1254 os::init(argc, &argv);
1256 lyx::TeX2LyXApp app(argc, argv);